text
stringlengths 54
60.6k
|
---|
<commit_before>#include <iostream>
#include "TChain.h"
#include "TH1F.h"
#include "TList.h"
#include "TGeoGlobalMagField.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliAODEvent.h"
#include "AliHeader.h"
#include "AliMCEvent.h"
#include "AliGenEventHeader.h"
#include "AliESDtrackCuts.h"
#include "AlidNdPtTools.h"
#include "AliAnalysisTaskMKBase.h"
#include "AliAnalysisTaskDCArStudy.h"
class AliAnalysisTaskDCArStudy;
using namespace std;
ClassImp(AliAnalysisTaskDCArStudy)
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy::AliAnalysisTaskDCArStudy()
: AliAnalysisTaskMKBase()
, fHistDCA(0)
, fHistDCATPC(0)
{
// default contructor
}
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy::AliAnalysisTaskDCArStudy(const char* name)
: AliAnalysisTaskMKBase(name)
, fHistDCA(0)
, fHistDCATPC(0)
{
// constructor
}
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy::~AliAnalysisTaskDCArStudy()
{
// destructor
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AddOutput()
{
//dcar:pt:mult:cent:mcinfo
AddAxis("DCAxy",5000,-1,1);
AddAxis("pt");
AddAxis("nTracks","mult6kcoarse");
AddAxis("cent");
AddAxis("MCinfo",4,-1.5,2.5); // 0=prim, 1=decay 2=material -1=data
fHistDCA = CreateHist("fHistDCA");
fOutputList->Add(fHistDCA);
//dcar:pt:mult:cent:mcinfo
AddAxis("DCAxy",5000,-20,20);
AddAxis("TPCpt","pt");
AddAxis("nTracks","mult6kcoarse");
AddAxis("cent");
AddAxis("MCinfo",4,-1.5,2.5); // 0=prim, 1=decay 2=material -1=data
fHistDCATPC = CreateHist("fHistDCATPC");
fOutputList->Add(fHistDCATPC);
//dcar:pt:mult:mcinfo
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskDCArStudy::IsEventSelected()
{
return fIsAcceptedAliEventCuts;
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AnaEvent()
{
LoopOverAllTracks();
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AnaTrackMC(Int_t flag)
{
if (fAcceptTrack[0]) { FillHist(fHistDCATPC, fDCArTPC, fPtInnerTPC, fNTracksAcc, fMultPercentileV0M, fMCPrimSec); }
if (fAcceptTrack[1]) { FillHist(fHistDCA, fDCAr, fPt, fNTracksAcc, fMultPercentileV0M, fMCPrimSec); }
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AnaTrackDATA(Int_t flag)
{
if (fAcceptTrack[0]) { FillHist(fHistDCATPC, fDCArTPC, fPtInnerTPC, fNTracksAcc, fMultPercentileV0M, -1); }
if (fAcceptTrack[1]) { FillHist(fHistDCA, fDCAr, fPt, fNTracksAcc, fMultPercentileV0M, -1); }
}
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy* AliAnalysisTaskDCArStudy::AddTaskDCArStudy(const char* name, const char* outfile)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskDCArStudy", "No analysis manager to connect to.");
return 0;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskDCArStudy", "This task requires an input event handler");
return NULL;
}
// Setup output file
//===========================================================================
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":";
fileName += name; // create a subfolder in the file
if (outfile) { // if a finename is given, use that one
fileName = TString(outfile);
}
// create the task
//===========================================================================
AliAnalysisTaskDCArStudy *task = new AliAnalysisTaskDCArStudy(name);
if (!task) { return 0; }
// configure the task
//===========================================================================
task->SelectCollisionCandidates(AliVEvent::kAnyINT);
task->SetESDtrackCutsM(AlidNdPtTools::CreateESDtrackCuts("defaultEta08"));
task->SetESDtrackCuts(0,AlidNdPtTools::CreateESDtrackCuts("TPCgeoNoDCArEta08"));
task->SetESDtrackCuts(1,AlidNdPtTools::CreateESDtrackCuts("TPCITSforDCArStudyEta08"));
task->SetNeedEventMult(kTRUE);
task->SetNeedEventVertex(kTRUE);
task->SetNeedTrackTPC(kTRUE);
// attach the task to the manager and configure in and ouput
//===========================================================================
mgr->AddTask(task);
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(task,1,mgr->CreateContainer(name, TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
return task;
}
<commit_msg>Updated dca study for dNdPt framework: changed mult. binning<commit_after>#include <iostream>
#include "TChain.h"
#include "TH1F.h"
#include "TList.h"
#include "TGeoGlobalMagField.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliAODEvent.h"
#include "AliHeader.h"
#include "AliMCEvent.h"
#include "AliGenEventHeader.h"
#include "AliESDtrackCuts.h"
#include "AlidNdPtTools.h"
#include "AliAnalysisTaskMKBase.h"
#include "AliAnalysisTaskDCArStudy.h"
class AliAnalysisTaskDCArStudy;
using namespace std;
ClassImp(AliAnalysisTaskDCArStudy)
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy::AliAnalysisTaskDCArStudy()
: AliAnalysisTaskMKBase()
, fHistDCA(0)
, fHistDCATPC(0)
{
// default contructor
}
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy::AliAnalysisTaskDCArStudy(const char* name)
: AliAnalysisTaskMKBase(name)
, fHistDCA(0)
, fHistDCATPC(0)
{
// constructor
}
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy::~AliAnalysisTaskDCArStudy()
{
// destructor
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AddOutput()
{
//dcar:pt:mult:mcinfo
AddAxis("DCAxy",5000,-1,1);
AddAxis("pt");
AddAxis("nTracks",4000, -0.5, 3999.5);
AddAxis("MCinfo",4,-1.5,2.5); // 0=prim, 1=decay 2=material -1=data
fHistDCA = CreateHist("fHistDCA");
fOutputList->Add(fHistDCA);
//dcar:pt:mult:mcinfo
AddAxis("DCAxy",5000,-20,20);
AddAxis("TPCpt","pt");
AddAxis("nTracks",4000, -0.5, 3999.5);
AddAxis("MCinfo",4,-1.5,2.5); // 0=prim, 1=decay 2=material -1=data
fHistDCATPC = CreateHist("fHistDCATPC");
fOutputList->Add(fHistDCATPC);
//dcar:pt:mult:mcinfo
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskDCArStudy::IsEventSelected()
{
return fIsAcceptedAliEventCuts;
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AnaEvent()
{
LoopOverAllTracks();
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AnaTrackMC(Int_t flag)
{
if (fAcceptTrack[0]) { FillHist(fHistDCATPC, fDCArTPC, fPtInnerTPC, fNTracksAcc, fMCPrimSec); }
if (fAcceptTrack[1]) { FillHist(fHistDCA, fDCAr, fPt, fNTracksAcc, fMCPrimSec); }
}
//_____________________________________________________________________________
void AliAnalysisTaskDCArStudy::AnaTrackDATA(Int_t flag)
{
if (fAcceptTrack[0]) { FillHist(fHistDCATPC, fDCArTPC, fPtInnerTPC, fNTracksAcc, -1); }
if (fAcceptTrack[1]) { FillHist(fHistDCA, fDCAr, fPt, fNTracksAcc, -1); }
}
//_____________________________________________________________________________
AliAnalysisTaskDCArStudy* AliAnalysisTaskDCArStudy::AddTaskDCArStudy(const char* name, const char* outfile)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskDCArStudy", "No analysis manager to connect to.");
return 0;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskDCArStudy", "This task requires an input event handler");
return NULL;
}
// Setup output file
//===========================================================================
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":";
fileName += name; // create a subfolder in the file
if (outfile) { // if a finename is given, use that one
fileName = TString(outfile);
}
// create the task
//===========================================================================
AliAnalysisTaskDCArStudy *task = new AliAnalysisTaskDCArStudy(name);
if (!task) { return 0; }
// configure the task
//===========================================================================
task->SelectCollisionCandidates(AliVEvent::kAnyINT);
task->SetESDtrackCutsM(AlidNdPtTools::CreateESDtrackCuts("defaultEta08"));
task->SetESDtrackCuts(0,AlidNdPtTools::CreateESDtrackCuts("TPCgeoNoDCArEta08"));
task->SetESDtrackCuts(1,AlidNdPtTools::CreateESDtrackCuts("TPCITSforDCArStudyEta08"));
task->SetNeedEventMult(kTRUE);
task->SetNeedEventVertex(kTRUE);
task->SetNeedTrackTPC(kTRUE);
// attach the task to the manager and configure in and ouput
//===========================================================================
mgr->AddTask(task);
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(task,1,mgr->CreateContainer(name, TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
return task;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <fstream>
#define CAMERA 0
#define VWIDTH 640
#define VHEIGHT 480
#define HORIZ 1
#define RADIUS 10
using namespace cv;
using namespace std;
Scalar linecolor = Scalar(0,255,0);
Scalar rectcolor = Scalar(0,200,0);
//Function to find the centroid of a binary image
void getCentroid(Mat &thresholded_image, Point &Centroid, int &Area)
{
///The object that holds all the centroids.
///Pass in the image. The boolean true tells the function that
///the image is binary
Moments m = moments(thresholded_image, true);
///Moment along x axis
double M10 = m.m10;
///Moment along y-axis;
double M01 = m.m01;
///Area
double M00 = m.m00;
Centroid.x = int(M10/M00);
Centroid.y = int(M01/M00);
Area = int(M00);
}
int main(int argc, char** argv)
{
Mat frame, head, tail;
char keypress;
int rlower_h = 0; int glower_h = 0; int blower_h = 0;
int rupper_h = 255; int gupper_h = 255; int bupper_h = 255;
int rlower_t = 0; int glower_t = 0; int blower_t = 0;
int rupper_t = 255; int gupper_t = 255; int bupper_t = 255;
int max_thresh = 255;
Scalar head_lower, head_upper,
tail_lower, tail_upper;
Point head_centroid, tail_centroid, direction;
Point head_prev(0,0); Point motion(0,0);
int head_area, tail_area;
namedWindow("head");
namedWindow("tail");
createTrackbar("R Upper", "head", &rupper_h, max_thresh, NULL);
createTrackbar("R Lower", "head", &rlower_h, max_thresh, NULL);
createTrackbar("G Upper", "head", &gupper_h, max_thresh, NULL);
createTrackbar("G Lower", "head", &glower_h, max_thresh, NULL);
createTrackbar("B Upper", "head", &bupper_h, max_thresh, NULL);
createTrackbar("B Lower", "head", &blower_h, max_thresh, NULL);
createTrackbar("R Upper", "tail", &rupper_t, max_thresh, NULL);
createTrackbar("R Lower", "tail", &rlower_t, max_thresh, NULL);
createTrackbar("G Upper", "tail", &gupper_t, max_thresh, NULL);
createTrackbar("G Lower", "tail", &glower_t, max_thresh, NULL);
createTrackbar("B Upper", "tail", &bupper_t, max_thresh, NULL);
createTrackbar("B Lower", "tail", &blower_t, max_thresh, NULL);
VideoCapture camera;
camera.open(CAMERA);
//Setting the camera resolution
camera.set(CV_CAP_PROP_FRAME_WIDTH, VWIDTH);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, VHEIGHT);
while(1)
{
//Get frame from camera
camera >> frame;
flip(frame, frame, HORIZ);
//Threshold out the green marker(tail)
//Threshold out the red marker(head)
inRange(frame, Scalar(rlower_h, glower_h, blower_h),
Scalar(rupper_h, gupper_h, bupper_h), head);
inRange(frame, Scalar(rlower_t, glower_t, blower_t),
Scalar(rupper_t, gupper_t, bupper_t), tail);
medianBlur(head, head, 7);
//Get coordinates of the tail marker
getCentroid(tail, tail_centroid, tail_area);
//Get coordinates of the head marker
getCentroid(head, head_centroid, head_area);
//Subtract the coordinates to get a direction vector
direction = head_centroid - tail_centroid;
//Draw the appropriate stuff on the image
motion = head_centroid - head_prev;
line(frame, tail_centroid, head_centroid, linecolor);
circle(frame, head_centroid, RADIUS, linecolor);
//cout<<"Direction: "<<direction<<endl;
//Use the direction vector to decide which way the arm must move
//Display the motion as output on the terminal
imshow("head", head);
imshow("tail", tail);
imshow("frame", frame);
head_prev = head_centroid;
keypress = waitKey(10);
if(keypress == 27) break;
if(keypress == 's')
{
//save thresholds
//Show directions
cout<<"Direction is: "<<direction<<endl;
break;
}
//Use the sliders to adjust the thresholds
//Save the thresholds in variables
//break out of loop
}
return 0;
}
<commit_msg>Sending commands to right is working.<commit_after>#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <fstream>
#include "include/netTransmit.h"
#include <math.h>
#define CAMERA 0
#define VWIDTH 640
#define VHEIGHT 480
#define HORIZ 1
#define RADIUS 10
using namespace cv;
using namespace std;
Scalar linecolor = Scalar(0,255,0);
Scalar rectcolor = Scalar(0,200,0);
//Function to convert from number to string
template <typename T>
string NumberToString (T Number)
{
ostringstream ss;
ss << Number;
return ss.str();
}
//Function to find the centroid of a binary image
void getCentroid(Mat &thresholded_image, Point &Centroid, int &Area)
{
///The object that holds all the centroids.
///Pass in the image. The boolean true tells the function that
///the image is binary
Moments m = moments(thresholded_image, true);
///Moment along x axis
double M10 = m.m10;
///Moment along y-axis;
double M01 = m.m01;
///Area
double M00 = m.m00;
Centroid.x = int(M10/M00);
Centroid.y = int(M01/M00);
Area = int(M00);
}
//Simplified puttext
void ptext(Mat& img, const string& text, Point org)
{
static double FSIZE = 0.5;
static int THICKNESS = 1;
putText(img, text, org, FONT_HERSHEY_SIMPLEX, FSIZE,
Scalar(0,255,0), THICKNESS, CV_AA);
}
int main(int argc, char** argv)
{
Mat frame, head, tail;
char keypress;
int rlower_h = 0; int glower_h = 0; int blower_h = 0;
int rupper_h = 255; int gupper_h = 255; int bupper_h = 255;
//int rlower_t = 0; int glower_t = 0; int blower_t = 0;
//int rupper_t = 255; int gupper_t = 255; int bupper_t = 255;
int max_thresh = 255;
Scalar head_lower, head_upper;
//tail_lower, tail_upper;
Point head_centroid, direction;
double angle;
Point tail_centroid = Point(VWIDTH/2, VHEIGHT/2);
Point head_prev(0,0); Point motion(0,0);
int head_area, tail_area;
char *msg = "Hello World!";
char *up = "U";
char *down = "D";
char *left = "L";
char *right = "R";
char *stop = "S";
string disp;
//class to transmit the arm motion.
netTransmit dataFire("127.0.0.1", 31415);
namedWindow("head");
//namedWindow("tail");
createTrackbar("R Upper", "head", &rupper_h, max_thresh, NULL);
createTrackbar("R Lower", "head", &rlower_h, max_thresh, NULL);
createTrackbar("G Upper", "head", &gupper_h, max_thresh, NULL);
createTrackbar("G Lower", "head", &glower_h, max_thresh, NULL);
createTrackbar("B Upper", "head", &bupper_h, max_thresh, NULL);
createTrackbar("B Lower", "head", &blower_h, max_thresh, NULL);
//createTrackbar("R Upper", "tail", &rupper_t, max_thresh, NULL);
//createTrackbar("R Lower", "tail", &rlower_t, max_thresh, NULL);
//createTrackbar("G Upper", "tail", &gupper_t, max_thresh, NULL);
//createTrackbar("G Lower", "tail", &glower_t, max_thresh, NULL);
//createTrackbar("B Upper", "tail", &bupper_t, max_thresh, NULL);
//createTrackbar("B Lower", "tail", &blower_t, max_thresh, NULL);
VideoCapture camera;
camera.open(CAMERA);
//Setting the camera resolution
camera.set(CV_CAP_PROP_FRAME_WIDTH, VWIDTH);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, VHEIGHT);
while(1)
{
//Get frame from camera
camera >> frame;
flip(frame, frame, HORIZ);
//Threshold out the green marker(tail)
//Threshold out the red marker(head)
inRange(frame, Scalar(rlower_h, glower_h, blower_h),
Scalar(rupper_h, gupper_h, bupper_h), head);
//inRange(frame, Scalar(rlower_t, glower_t, blower_t),
// Scalar(rupper_t, gupper_t, bupper_t), tail);
medianBlur(head, head, 7);
//Get coordinates of the tail marker
//getCentroid(tail, tail_centroid, tail_area);
//Get coordinates of the head marker
getCentroid(head, head_centroid, head_area);
//Subtract the coordinates to get a direction vector
direction = head_centroid - tail_centroid;
angle = (180.0/3.14159)*atan2(-1*direction.y, direction.x);
//Draw the appropriate stuff on the image
motion = head_centroid - head_prev;
line(frame, tail_centroid, head_centroid, linecolor);
circle(frame, head_centroid, RADIUS, linecolor);
ptext(frame, NumberToString(angle), head_centroid+Point(20, 0));
if((angle>0)&&(angle<45)) ptext(frame, string(right), Point(VWIDTH/2, 40));
//cout<<"Direction: "<<direction<<endl;
//Use the direction vector to decide which way the arm must move
//Display the motion as output on the terminal
imshow("head", head);
imshow("frame", frame);
head_prev = head_centroid;
//dataFire.transmit(msg);
keypress = waitKey(10);
if(keypress == 27) break;
if(keypress == 's')
{
//save thresholds
//Show directions
cout<<"Direction is: "<<direction<<endl;
break;
}
//Use the sliders to adjust the thresholds
//Save the thresholds in variables
//break out of loop
}
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/learning_based/model_inference/trajectory_imitation_inference.h"
#include <string>
#include <utility>
#include <vector>
#include "cyber/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/vec2d.h"
#include "modules/planning/learning_based/img_feature_renderer/birdview_img_feature_renderer.h"
#include "opencv2/opencv.hpp"
namespace apollo {
namespace planning {
TrajectoryConvRnnInference::TrajectoryConvRnnInference(
const LearningModelInferenceTaskConfig& config)
: ModelInference(config), device_(torch::kCPU) {
LoadModel(config);
}
// TODO(Jinyun): evaluate whether use fake input in load model speed up the
// loading process
bool TrajectoryConvRnnInference::LoadModel(
const LearningModelInferenceTaskConfig& config) {
if (config.use_cuda() && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
model_ = torch::jit::load(config.model_file(), device_);
torch::set_num_threads(1);
return true;
}
bool TrajectoryConvRnnInference::Inference(
LearningDataFrame* learning_data_frame) {
const int past_points_size = learning_data_frame->adc_trajectory_point_size();
if (past_points_size == 0) {
AERROR << "No current trajectory point status";
return false;
}
cv::Mat input_feature;
if (!BirdviewImgFeatureRenderer::Instance()->RenderMultiChannelEnv(
*learning_data_frame, &input_feature)) {
AERROR << "Render multi-channel input image failed";
return false;
}
cv::Mat input_feature_float;
input_feature.convertTo(input_feature_float, CV_32F, 1.0 / 255);
torch::Tensor input_feature_tensor =
torch::from_blob(input_feature_float.data,
{1, input_feature_float.rows, input_feature_float.cols,
input_feature_float.channels()});
input_feature_tensor = input_feature_tensor.permute({0, 3, 1, 2});
for (int i = 0; i < input_feature_float.channels(); ++i) {
input_feature_tensor[0][i] = input_feature_tensor[0][i].sub(0.5).div(0.5);
}
cv::Mat initial_point;
if (!BirdviewImgFeatureRenderer::Instance()->RenderCurrentEgoPoint(
*learning_data_frame, &initial_point)) {
AERROR << "Render initial states image failed";
return false;
}
cv::Mat initial_point_float;
initial_point.convertTo(initial_point_float, CV_32F, 1.0 / 255);
torch::Tensor initial_point_tensor =
torch::from_blob(initial_point_float.data,
{1, initial_point_float.rows, initial_point_float.cols,
initial_point_float.channels()});
initial_point_tensor = initial_point_tensor.permute({0, 3, 1, 2});
cv::Mat initial_box;
if (!BirdviewImgFeatureRenderer::Instance()->RenderCurrentEgoBox(
*learning_data_frame, &initial_box)) {
AERROR << "Render initial states image failed";
return false;
}
cv::Mat initial_box_float;
initial_box.convertTo(initial_box_float, CV_32F, 1.0 / 255);
torch::Tensor initial_box_tensor =
torch::from_blob(initial_box_float.data,
{1, initial_box_float.rows, initial_box_float.cols,
initial_box_float.channels()});
initial_box_tensor = initial_box_tensor.permute({0, 3, 1, 2});
std::vector<torch::jit::IValue> torch_inputs;
torch_inputs.push_back(c10::ivalue::Tuple::create(
{std::move(input_feature_tensor.to(device_)),
std::move(initial_point_tensor.to(device_)),
std::move(initial_box_tensor.to(device_))},
c10::TupleType::create(
std::vector<c10::TypePtr>(3, c10::TensorType::create()))));
auto start_time = std::chrono::system_clock::now();
at::Tensor torch_output_tensor = model_.forward(torch_inputs)
.toTuple()
->elements()[2]
.toTensor()
.to(torch::kCPU);
auto end_time = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end_time - start_time;
ADEBUG << "trajectory imitation model inference used time: "
<< diff.count() * 1000 << " ms.";
const auto& cur_traj_point =
learning_data_frame->adc_trajectory_point(past_points_size - 1);
const double cur_time_sec = cur_traj_point.timestamp_sec();
const auto& cur_path_point = cur_traj_point.trajectory_point().path_point();
const double cur_x = cur_path_point.x();
const double cur_y = cur_path_point.y();
const double cur_heading = cur_path_point.theta();
learning_data_frame->mutable_output()->clear_adc_future_trajectory_point();
// TODO(Jinyun): move delta_t to conf or deduce it somehow
const double delta_t = 0.2;
auto torch_output = torch_output_tensor.accessor<float, 3>();
for (int i = 0; i < torch_output_tensor.size(1); ++i) {
const double dx = static_cast<double>(torch_output[0][i][0]);
const double dy = static_cast<double>(torch_output[0][i][1]);
const double dtheta = static_cast<double>(torch_output[0][i][2]);
const double v = static_cast<double>(torch_output[0][i][3]);
const double time_sec = cur_time_sec + delta_t * (i + 1);
apollo::common::math::Vec2d offset(dx, dy);
apollo::common::math::Vec2d rotated_offset = offset.rotate(cur_heading);
const double x = cur_x + rotated_offset.x();
const double y = cur_y + rotated_offset.y();
const double heading =
apollo::common::math::NormalizeAngle(dtheta + cur_heading);
auto* traj_point = learning_data_frame->mutable_output()
->add_adc_future_trajectory_point();
traj_point->set_timestamp_sec(time_sec);
traj_point->mutable_trajectory_point()->mutable_path_point()->set_x(x);
traj_point->mutable_trajectory_point()->mutable_path_point()->set_y(y);
traj_point->mutable_trajectory_point()->mutable_path_point()->set_theta(
heading);
traj_point->mutable_trajectory_point()->set_v(v);
traj_point->mutable_trajectory_point()->set_relative_time(delta_t *
(i + 1));
}
return true;
}
} // namespace planning
} // namespace apollo
<commit_msg>Planning: log time statisics in model inference<commit_after>/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/learning_based/model_inference/trajectory_imitation_inference.h"
#include <string>
#include <utility>
#include <vector>
#include "cyber/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/vec2d.h"
#include "modules/planning/learning_based/img_feature_renderer/birdview_img_feature_renderer.h"
#include "opencv2/opencv.hpp"
namespace apollo {
namespace planning {
TrajectoryConvRnnInference::TrajectoryConvRnnInference(
const LearningModelInferenceTaskConfig& config)
: ModelInference(config), device_(torch::kCPU) {
LoadModel(config);
}
// TODO(Jinyun): evaluate whether use fake input in load model speed up the
// loading process
bool TrajectoryConvRnnInference::LoadModel(
const LearningModelInferenceTaskConfig& config) {
if (config.use_cuda() && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
model_ = torch::jit::load(config.model_file(), device_);
torch::set_num_threads(1);
return true;
}
bool TrajectoryConvRnnInference::Inference(
LearningDataFrame* learning_data_frame) {
const int past_points_size = learning_data_frame->adc_trajectory_point_size();
if (past_points_size == 0) {
AERROR << "No current trajectory point status";
return false;
}
auto input_renderering_start_time = std::chrono::system_clock::now();
cv::Mat input_feature;
if (!BirdviewImgFeatureRenderer::Instance()->RenderMultiChannelEnv(
*learning_data_frame, &input_feature)) {
AERROR << "Render multi-channel input image failed";
return false;
}
cv::Mat initial_point;
if (!BirdviewImgFeatureRenderer::Instance()->RenderCurrentEgoPoint(
*learning_data_frame, &initial_point)) {
AERROR << "Render initial states image failed";
return false;
}
cv::Mat initial_box;
if (!BirdviewImgFeatureRenderer::Instance()->RenderCurrentEgoBox(
*learning_data_frame, &initial_box)) {
AERROR << "Render initial states image failed";
return false;
}
auto input_renderering_end_time = std::chrono::system_clock::now();
std::chrono::duration<double> rendering_diff =
input_renderering_end_time - input_renderering_start_time;
ADEBUG << "trajectory imitation model input renderer used time: "
<< rendering_diff.count() * 1000 << " ms.";
auto input_prepration_start_time = std::chrono::system_clock::now();
cv::Mat input_feature_float;
input_feature.convertTo(input_feature_float, CV_32F, 1.0 / 255);
torch::Tensor input_feature_tensor =
torch::from_blob(input_feature_float.data,
{1, input_feature_float.rows, input_feature_float.cols,
input_feature_float.channels()});
input_feature_tensor = input_feature_tensor.permute({0, 3, 1, 2});
for (int i = 0; i < input_feature_float.channels(); ++i) {
input_feature_tensor[0][i] = input_feature_tensor[0][i].sub(0.5).div(0.5);
}
cv::Mat initial_point_float;
initial_point.convertTo(initial_point_float, CV_32F, 1.0 / 255);
torch::Tensor initial_point_tensor =
torch::from_blob(initial_point_float.data,
{1, initial_point_float.rows, initial_point_float.cols,
initial_point_float.channels()});
initial_point_tensor = initial_point_tensor.permute({0, 3, 1, 2});
cv::Mat initial_box_float;
initial_box.convertTo(initial_box_float, CV_32F, 1.0 / 255);
torch::Tensor initial_box_tensor =
torch::from_blob(initial_box_float.data,
{1, initial_box_float.rows, initial_box_float.cols,
initial_box_float.channels()});
initial_box_tensor = initial_box_tensor.permute({0, 3, 1, 2});
std::vector<torch::jit::IValue> torch_inputs;
torch_inputs.push_back(c10::ivalue::Tuple::create(
{std::move(input_feature_tensor.to(device_)),
std::move(initial_point_tensor.to(device_)),
std::move(initial_box_tensor.to(device_))},
c10::TupleType::create(
std::vector<c10::TypePtr>(3, c10::TensorType::create()))));
auto input_prepration_end_time = std::chrono::system_clock::now();
std::chrono::duration<double> prepration_diff =
input_prepration_end_time - input_prepration_start_time;
ADEBUG << "trajectory imitation model input prepration used time: "
<< prepration_diff.count() * 1000 << " ms.";
auto inference_start_time = std::chrono::system_clock::now();
at::Tensor torch_output_tensor = model_.forward(torch_inputs)
.toTuple()
->elements()[2]
.toTensor()
.to(torch::kCPU);
auto inference_end_time = std::chrono::system_clock::now();
std::chrono::duration<double> inference_diff =
inference_end_time - inference_start_time;
ADEBUG << "trajectory imitation model inference used time: "
<< inference_diff.count() * 1000 << " ms.";
const auto& cur_traj_point =
learning_data_frame->adc_trajectory_point(past_points_size - 1);
const double cur_time_sec = cur_traj_point.timestamp_sec();
const auto& cur_path_point = cur_traj_point.trajectory_point().path_point();
const double cur_x = cur_path_point.x();
const double cur_y = cur_path_point.y();
const double cur_heading = cur_path_point.theta();
learning_data_frame->mutable_output()->clear_adc_future_trajectory_point();
// TODO(Jinyun): move delta_t to conf or deduce it somehow
const double delta_t = 0.2;
auto torch_output = torch_output_tensor.accessor<float, 3>();
for (int i = 0; i < torch_output_tensor.size(1); ++i) {
const double dx = static_cast<double>(torch_output[0][i][0]);
const double dy = static_cast<double>(torch_output[0][i][1]);
const double dtheta = static_cast<double>(torch_output[0][i][2]);
const double v = static_cast<double>(torch_output[0][i][3]);
const double time_sec = cur_time_sec + delta_t * (i + 1);
apollo::common::math::Vec2d offset(dx, dy);
apollo::common::math::Vec2d rotated_offset = offset.rotate(cur_heading);
const double x = cur_x + rotated_offset.x();
const double y = cur_y + rotated_offset.y();
const double heading =
apollo::common::math::NormalizeAngle(dtheta + cur_heading);
auto* traj_point = learning_data_frame->mutable_output()
->add_adc_future_trajectory_point();
traj_point->set_timestamp_sec(time_sec);
traj_point->mutable_trajectory_point()->mutable_path_point()->set_x(x);
traj_point->mutable_trajectory_point()->mutable_path_point()->set_y(y);
traj_point->mutable_trajectory_point()->mutable_path_point()->set_theta(
heading);
traj_point->mutable_trajectory_point()->set_v(v);
traj_point->mutable_trajectory_point()->set_relative_time(delta_t *
(i + 1));
}
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/program_options.hpp>
#include "float-semiring.h"
#include "free-semiring.h"
#include "semilinSetExp.h"
#include "matrix.h"
#include "polynomial.h"
#include "newton.h"
#include "commutativeRExp.h"
#include "parser.h"
// group the equations to SCCs
template <typename SR>
std::vector<std::vector<std::pair<VarPtr, Polynomial<SR>>>> group_by_scc(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool graphviz_output)
{
struct VertexProp {
std::string name; // used for graphviz output
VarPtr var; // var and rex combines the equations in the vertex
Polynomial<SR> rex;
};
// create map of variables to [0..n]. this is used to enumerate important variables in a clean way from 0 to n during graph construction
std::map<VarPtr, int> var_key;
// build the graph
boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProp> graph(equations.size());
for(auto e_it = equations.begin(); e_it != equations.end(); ++e_it)
{
// if the variable is not yet in the map insert it together with the size of
// the map. this way we get a unique identifier for the variable counting from 0 to n
if(var_key.find(e_it->first) == var_key.end())
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(e_it->first,var_key.size()));
int a = var_key.find(e_it->first)->second; // variable key
graph[a].var = e_it->first; // store VarPtr to the vertex
graph[a].name = e_it->first->string(); // store the name to the vertex
graph[a].rex = e_it->second; // store the regular expression to the vertex
auto v = e_it->second.get_variables(); // all variables of this rule;
for(auto v_it = v.begin(); v_it != v.end(); ++v_it)
{
if(var_key.find(*v_it) == var_key.end()) // variable is not yet in the map
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(*v_it,var_key.size()));
int b = var_key.find(*v_it)->second; // variable key
boost::add_edge(a, b, graph);
}
} // graph is complete
if(graphviz_output)
{
// output the created graph to graph.dot
boost::dynamic_properties dp;
dp.property("label", boost::get(&VertexProp::name, graph)); // vertex name is the name of the equation
dp.property("node_id", get(boost::vertex_index, graph)); // this is needed
std::ofstream outf("graph.dot");
boost::write_graphviz_dp(outf, graph, dp);
}
// calculate strong connected components and store them in 'component'
std::vector<int> component(boost::num_vertices(graph));
boost::strong_components(graph,&component[0]);
// group neccessary equations together
int num_comp = *std::max_element(component.begin(), component.end()) + 1; // find the number of components
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> grouped_equations;
grouped_equations.resize(num_comp);
// iterate over all vertices (0 to n)
// collect the necessary variables + equations for every component
for (unsigned int j = 0; j != component.size(); ++j)
{
//std::cout << j << ", " << graph[j].var << " is in component " << component[j] << std::endl;
grouped_equations[component[j]].push_back(std::pair<VarPtr,Polynomial<SR>>(graph[j].var, graph[j].rex));
}
return grouped_equations;
}
// apply the newton method to the given input
template <typename SR>
std::map<VarPtr, SR> apply_newton(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool scc, bool iteration_flag, int iterations, bool graphviz_output)
{
// TODO: sanity checks on the input!
// generate an instance of the newton solver
Newton<SR> newton;
// if we use the scc method, group the equations
// the outer vector contains SCCs starting with a bottom SCC at 0
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> equations2;
if(scc)
{
auto tmp = group_by_scc(equations, graphviz_output);
equations2.insert(equations2.begin(), tmp.begin(), tmp.end());
}
else if (!scc)
{
equations2.push_back(equations);
}
// this holds the solution
std::map<VarPtr, SR> solution;
// the same loop is used for both the scc and the non-scc variant
// in the non-scc variant, we just run once through the loop
//for(auto it1 = equations2.begin(); it != equations2.end(); ++it)
for(unsigned int j = 0; j != equations2.size(); ++j)
{
// use the solutions to get rid of variables in the remaining equations
// does nothing in the first round
std::vector<std::pair<VarPtr, Polynomial<SR>>> tmp1;
for(auto it = equations2[j].begin(); it != equations2[j].end(); ++it)
{ // it = (VarPtr, Polynomial[SR])
auto tmp2 = it->second.partial_eval(solution);
tmp1.push_back(std::pair<VarPtr, Polynomial<SR>>(it->first, tmp2));
}
// replace old equations with simplified ones
equations2[j] = tmp1;
// dynamic iterations
if(!iteration_flag)
iterations = equations2[j].size();
// do some real work here
std::map<VarPtr, SR> result = newton.solve_fixpoint(equations2[j], iterations);
// copy the results into the solution map
solution.insert(result.begin(), result.end());
}
return solution;
}
template <typename SR>
std::string result_string(std::map<VarPtr,SR> result)
{
std::stringstream ss;
for(auto r_it = result.begin(); r_it != result.end(); ++r_it)
ss << r_it->first << " == " << r_it->second << std::endl;
return ss.str();
}
int main(int argc, char* argv[])
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
( "scc", "apply newton method iteratively to strongly connected components of the equation graph" )
( "help,h", "print this help message" )
( "iterations,i", po::value<int>(), "specify the number of newton iterations. default is optimal number" )
//( "verbose", "enable verbose output" )
//( "debug", "enable debug output" )
( "file,f", po::value<std::string>(), "input file" )
( "float", "float semiring" )
( "rexp", "commutative regular expression semiring" )
( "graphviz", "create the file graph.dot with the equation graph" )
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << std::endl;
return 0;
}
int iterations=0;
if(vm.count("iterations"))
iterations = vm["iterations"].as<int>();
// check if we can do something useful
if(!vm.count("float") && !vm.count("rexp")) // check for all compatible parameters
return 0;
std::vector<std::string> input;
std::string line;
if(vm.count("file"))
{
// we are reading the input from the given file
std::ifstream file;
file.open(vm["file"].as<std::string>(), std::ifstream::in);
while(std::getline(file, line))
input.push_back(line);
}
else
{
// we are reading from stdin
while(std::getline(std::cin, line))
input.push_back(line);
}
// join the input into one string
std::string input_all = std::accumulate(input.begin(), input.end(), std::string(""));
Parser p;
if(vm.count("rexp"))
{
// parse the input into a list of (Var → Polynomial[SR])
std::vector<std::pair<VarPtr, Polynomial<CommutativeRExp>>> equations(p.rexp_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
// apply the newton method to the equations
auto result = apply_newton<CommutativeRExp>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
else if(vm.count("float"))
{
std::vector<std::pair<VarPtr, Polynomial<FloatSemiring>>> equations(p.float_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
auto result = apply_newton<FloatSemiring>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
return 0;
}
<commit_msg>now clang++ is able to compile the project (but output is different. seems to be different multiset order)<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/program_options.hpp>
#include "float-semiring.h"
#include "free-semiring.h"
#include "semilinSetExp.h"
#include "matrix.h"
#include "polynomial.h"
#include "newton.h"
#include "commutativeRExp.h"
#include "parser.h"
template <typename SR>
struct VertexProp {
std::string name; // used for graphviz output
VarPtr var; // var and rex combines the equations in the vertex
Polynomial<SR> rex;
};
// group the equations to SCCs
template <typename SR>
std::vector<std::vector<std::pair<VarPtr, Polynomial<SR>>>> group_by_scc(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool graphviz_output)
{
// create map of variables to [0..n]. this is used to enumerate important variables in a clean way from 0 to n during graph construction
std::map<VarPtr, int> var_key;
// build the graph
boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProp<SR>> graph(equations.size());
for(auto e_it = equations.begin(); e_it != equations.end(); ++e_it)
{
// if the variable is not yet in the map insert it together with the size of
// the map. this way we get a unique identifier for the variable counting from 0 to n
if(var_key.find(e_it->first) == var_key.end())
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(e_it->first,var_key.size()));
int a = var_key.find(e_it->first)->second; // variable key
graph[a].var = e_it->first; // store VarPtr to the vertex
graph[a].name = e_it->first->string(); // store the name to the vertex
graph[a].rex = e_it->second; // store the regular expression to the vertex
auto v = e_it->second.get_variables(); // all variables of this rule;
for(auto v_it = v.begin(); v_it != v.end(); ++v_it)
{
if(var_key.find(*v_it) == var_key.end()) // variable is not yet in the map
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(*v_it,var_key.size()));
int b = var_key.find(*v_it)->second; // variable key
boost::add_edge(a, b, graph);
}
} // graph is complete
if(graphviz_output)
{
// output the created graph to graph.dot
boost::dynamic_properties dp;
dp.property("label", boost::get(&VertexProp<SR>::name, graph)); // vertex name is the name of the equation
dp.property("node_id", get(boost::vertex_index, graph)); // this is needed
std::ofstream outf("graph.dot");
boost::write_graphviz_dp(outf, graph, dp);
}
// calculate strong connected components and store them in 'component'
std::vector<int> component(boost::num_vertices(graph));
boost::strong_components(graph,&component[0]);
// group neccessary equations together
int num_comp = *std::max_element(component.begin(), component.end()) + 1; // find the number of components
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> grouped_equations;
grouped_equations.resize(num_comp);
// iterate over all vertices (0 to n)
// collect the necessary variables + equations for every component
for (unsigned int j = 0; j != component.size(); ++j)
{
//std::cout << j << ", " << graph[j].var << " is in component " << component[j] << std::endl;
grouped_equations[component[j]].push_back(std::pair<VarPtr,Polynomial<SR>>(graph[j].var, graph[j].rex));
}
return grouped_equations;
}
// apply the newton method to the given input
template <typename SR>
std::map<VarPtr, SR> apply_newton(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool scc, bool iteration_flag, int iterations, bool graphviz_output)
{
// TODO: sanity checks on the input!
// generate an instance of the newton solver
Newton<SR> newton;
// if we use the scc method, group the equations
// the outer vector contains SCCs starting with a bottom SCC at 0
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> equations2;
if(scc)
{
auto tmp = group_by_scc(equations, graphviz_output);
equations2.insert(equations2.begin(), tmp.begin(), tmp.end());
}
else if (!scc)
{
equations2.push_back(equations);
}
// this holds the solution
std::map<VarPtr, SR> solution;
// the same loop is used for both the scc and the non-scc variant
// in the non-scc variant, we just run once through the loop
//for(auto it1 = equations2.begin(); it != equations2.end(); ++it)
for(unsigned int j = 0; j != equations2.size(); ++j)
{
// use the solutions to get rid of variables in the remaining equations
// does nothing in the first round
std::vector<std::pair<VarPtr, Polynomial<SR>>> tmp1;
for(auto it = equations2[j].begin(); it != equations2[j].end(); ++it)
{ // it = (VarPtr, Polynomial[SR])
auto tmp2 = it->second.partial_eval(solution);
tmp1.push_back(std::pair<VarPtr, Polynomial<SR>>(it->first, tmp2));
}
// replace old equations with simplified ones
equations2[j] = tmp1;
// dynamic iterations
if(!iteration_flag)
iterations = equations2[j].size();
// do some real work here
std::map<VarPtr, SR> result = newton.solve_fixpoint(equations2[j], iterations);
// copy the results into the solution map
solution.insert(result.begin(), result.end());
}
return solution;
}
template <typename SR>
std::string result_string(std::map<VarPtr,SR> result)
{
std::stringstream ss;
for(auto r_it = result.begin(); r_it != result.end(); ++r_it)
ss << r_it->first << " == " << r_it->second << std::endl;
return ss.str();
}
int main(int argc, char* argv[])
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
( "scc", "apply newton method iteratively to strongly connected components of the equation graph" )
( "help,h", "print this help message" )
( "iterations,i", po::value<int>(), "specify the number of newton iterations. default is optimal number" )
//( "verbose", "enable verbose output" )
//( "debug", "enable debug output" )
( "file,f", po::value<std::string>(), "input file" )
( "float", "float semiring" )
( "rexp", "commutative regular expression semiring" )
( "graphviz", "create the file graph.dot with the equation graph" )
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << std::endl;
return 0;
}
int iterations=0;
if(vm.count("iterations"))
iterations = vm["iterations"].as<int>();
// check if we can do something useful
if(!vm.count("float") && !vm.count("rexp")) // check for all compatible parameters
return 0;
std::vector<std::string> input;
std::string line;
if(vm.count("file"))
{
// we are reading the input from the given file
std::ifstream file;
file.open(vm["file"].as<std::string>(), std::ifstream::in);
while(std::getline(file, line))
input.push_back(line);
}
else
{
// we are reading from stdin
while(std::getline(std::cin, line))
input.push_back(line);
}
// join the input into one string
std::string input_all = std::accumulate(input.begin(), input.end(), std::string(""));
Parser p;
if(vm.count("rexp"))
{
// parse the input into a list of (Var → Polynomial[SR])
std::vector<std::pair<VarPtr, Polynomial<CommutativeRExp>>> equations(p.rexp_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
// apply the newton method to the equations
auto result = apply_newton<CommutativeRExp>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
else if(vm.count("float"))
{
std::vector<std::pair<VarPtr, Polynomial<FloatSemiring>>> equations(p.float_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
auto result = apply_newton<FloatSemiring>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "float-semiring.h"
#include "free-semiring.h"
#include "semilinSetExp.h"
#include "matrix.h"
#include "polynomial.h"
#include "newton.h"
#include "commutativeRExp.h"
void test_addition()
{
FloatSemiring first(0.5);
FloatSemiring second(0.3);
FloatSemiring result = first + second;
std::cout << "- float semiring addition: " << std::endl;
std::cout << first << " + " << second << " = " << result << std::endl;
}
void test_multiplication()
{
FloatSemiring first(0.5);
FloatSemiring second(0.3);
FloatSemiring result = first * second;
std::cout << "- float semiring multiplication: " << std::endl;
std::cout << first << " * " << second << " = " << result << std::endl;
}
void test_variables()
{
Var var1;
Var var2;
std::cout << "- variables:" << std::endl;
std::cout << var1 << "," << var2 << std::endl;
}
void test_monomials()
{
std::cout << "- monomials:" << std::endl;
Monomial<FloatSemiring> mon1(FloatSemiring(5),{Var("x"),Var("x"),Var("y")});
Monomial<FloatSemiring> mon2(FloatSemiring(2),{Var("y"), Var("x")});
Monomial<FloatSemiring> res1 = mon1 + mon1;
Monomial<FloatSemiring> res2 = mon1 * mon2;
std::cout << mon1 << " + " << mon1 << " = " << res1 << std::endl;
std::cout << mon1 << " * " << mon2 << " = " << res2 << std::endl;
std::cout << "derivative of " << mon1 << " = " << mon1.derivative(Var("x")) << std::endl;
}
Polynomial<FloatSemiring> get_first_polynomial()
{
// define new polynomial 2xx+7y
return Polynomial<FloatSemiring>(
{ Monomial<FloatSemiring>(FloatSemiring(2),{Var("x"),Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(7),{Var("z")}) });
}
Polynomial<FloatSemiring> get_second_polynomial()
{
// define new polynomial 5xx+3xy+6yy
return Polynomial<FloatSemiring>(
{ Monomial<FloatSemiring>(FloatSemiring(5),{Var("x"),Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(3),{Var("x"),Var("y")}),
Monomial<FloatSemiring>(FloatSemiring(6),{Var("y"),Var("y")})});
}
void test_polynomial_addition()
{
Polynomial<FloatSemiring> first = get_first_polynomial();
Polynomial<FloatSemiring> second = get_second_polynomial();
Polynomial<FloatSemiring> result = first + second;
std::cout << "- polynomial addition:" << std::endl;
std::cout << first << " + " << second << " = " << result << std::endl;
}
void test_polynomial_multiplication()
{
Polynomial<FloatSemiring> first = get_first_polynomial();
Polynomial<FloatSemiring> second = get_second_polynomial();
Polynomial<FloatSemiring> result = first * second;
std::cout << "- polynomial multiplication:" << std::endl;
std::cout << first << " * " << second << " = " << result << std::endl;
}
std::map<Var,FloatSemiring> get_variable_values()
{
std::map<Var,FloatSemiring> values;
values.insert(values.begin(), std::pair<Var,FloatSemiring>(Var("x"),FloatSemiring(5)));
values.insert(values.begin(), std::pair<Var,FloatSemiring>(Var("y"),FloatSemiring(4)));
values.insert(values.begin(), std::pair<Var,FloatSemiring>(Var("z"),FloatSemiring(0)));
return values;
}
void test_polynomial_evaluation()
{
Polynomial<FloatSemiring> polynomial = get_second_polynomial();
std::map<Var,FloatSemiring> values = get_variable_values();
FloatSemiring result = polynomial.eval(values);
std::cout << "- polynomial evaluation:" << std::endl;
std::cout << polynomial << " at {x=5, y=4, z=0} = " << result << std::endl;
}
Matrix<FloatSemiring> get_first_matrix()
{
FloatSemiring elems[] = {
FloatSemiring(0.5), FloatSemiring(0.9),
FloatSemiring(0.2), FloatSemiring(0.1)};
return Matrix<FloatSemiring>(2,2,std::vector<FloatSemiring>(elems, elems+4));
}
Matrix<FloatSemiring> get_second_matrix()
{
FloatSemiring elems[] = {
FloatSemiring(0.3), FloatSemiring(0.1),
FloatSemiring(0.7), FloatSemiring(0.2)};
return Matrix<FloatSemiring>(2,2,std::vector<FloatSemiring>(elems, elems+4));
}
Matrix<FreeSemiring> get_star_test_matrix()
{
/* FloatSemiring elems[] = {
FloatSemiring(0.6), FloatSemiring(0.1), FloatSemiring(0.1),
FloatSemiring(0.1), FloatSemiring(0.4), FloatSemiring(0.1),
FloatSemiring(0.1), FloatSemiring(0.1), FloatSemiring(0.3)};
return Matrix<FloatSemiring>(3,3,std::vector<FloatSemiring>(elems, elems+9));
*/
FreeSemiring elems[] = {
FreeSemiring(Var("a")),
FreeSemiring(Var("b")),
FreeSemiring(Var("c")),
FreeSemiring(Var("d")) };
return Matrix<FreeSemiring>(2,2,std::vector<FreeSemiring>(elems, elems+4));
}
void test_matrix_addition()
{
Matrix<FloatSemiring> first = get_first_matrix();
Matrix<FloatSemiring> second = get_second_matrix();
Matrix<FloatSemiring> result = first + second;
std::cout << "- matrix addition:" << std::endl;
std::cout << first << " + " << std::endl << second << " = " << std::endl << result;
}
void test_matrix_multiplication()
{
Matrix<FloatSemiring> first = get_first_matrix();
Matrix<FloatSemiring> second = get_second_matrix();
Matrix<FloatSemiring> result = first * second;
std::cout << "- matrix multiplication:" << std::endl;
std::cout << first << " * " << std::endl << second << " = " << std::endl << result;
}
void test_matrix_transpose()
{
Matrix<FloatSemiring> matrix = get_first_matrix();
Matrix<FloatSemiring> result = matrix.transpose();
std::cout << "- matrix transpose:" << std::endl;
std::cout << matrix << " transposed " << std::endl << result;
}
void test_matrix_star()
{
auto matrix = get_star_test_matrix();
auto result = matrix.star();
std::cout << "- matrix star:" << std::endl;
std::cout << matrix << " the matrix star of this is: " << std::endl << result;
}
void test_jacobian()
{
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::vector<Polynomial<FloatSemiring> > polynomials;
polynomials.push_back(get_first_polynomial());
polynomials.push_back(get_second_polynomial());
Matrix<Polynomial<FloatSemiring> > jacobian = Polynomial<FloatSemiring>::jacobian(polynomials, variables);
std::cout << "- jacobian (x,y,z) of " << std::endl;
std::cout << polynomials.at(0) << std::endl << polynomials.at(1) << std::endl << " = " << std::endl << jacobian << std::endl;
}
void test_polynomial_matrix_evaluation()
{
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::vector<Polynomial<FloatSemiring> > polynomials;
polynomials.push_back(get_first_polynomial());
polynomials.push_back(get_second_polynomial());
Matrix<Polynomial<FloatSemiring> > polynomial_matrix = Polynomial<FloatSemiring>::jacobian(polynomials, variables);
std::map<Var,FloatSemiring> values = get_variable_values();
Matrix<FloatSemiring> result = Polynomial<FloatSemiring>::eval(polynomial_matrix, values);
std::cout << "- polynomial matrix evaluation" << std::endl;
std::cout << polynomial_matrix << " at {x=5, y=4, z=0} = " << std::endl << result;
}
void test_freesemiring()
{
std::cout << "- free semiring" << std::endl;
FreeSemiring term1 = FreeSemiring(Var("a"));
FreeSemiring term2 = FreeSemiring(Var("b"));
std::cout << "some terms: " << term1 << " and " << term2 << std::endl;
FreeSemiring termAdd = term1 + term2;
FreeSemiring termMul = term1 * term2;
std::cout << "addition&multiplication&star: " << (termAdd*termMul.star()) << std::endl;
}
void test_polynomial_to_freesemiring()
{
std::cout << "- polynomial to free semiring conversion" <<std::endl;
Polynomial<FloatSemiring> poly = get_first_polynomial();
auto valuation = new std::unordered_map<FloatSemiring, FreeSemiring, FloatSemiring>();
FreeSemiring elem = poly.make_free(valuation);
for(auto v_it = valuation->begin(); v_it != valuation->end(); ++v_it)
{
std::cout << "valuation: " << v_it->first << " → " << v_it->second << std::endl;
}
std::cout << "polynomial: " << poly << std::endl;
std::cout << "free semiring: " << elem << std::endl;
}
std::vector<Polynomial<FloatSemiring> > get_newton_test_polynomials()
{
std::vector<Polynomial<FloatSemiring> > polynomials;
// define new polynomial 0.4xy+0.6
Polynomial<FloatSemiring> f1 = Polynomial<FloatSemiring>({
Monomial<FloatSemiring>(FloatSemiring(0.4), {Var("x"),Var("y")}),
Monomial<FloatSemiring>(FloatSemiring(0.6), {}) });
// define new polynomial 0.3yz+0.4yx+0.3
Polynomial<FloatSemiring> f2 = Polynomial<FloatSemiring>({
Monomial<FloatSemiring>(FloatSemiring(0.3), {Var("y"),Var("z")}),
Monomial<FloatSemiring>(FloatSemiring(0.4), {Var("y"),Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(0.3), {}) });
// define new polynomial 0.3x+0.7
Polynomial<FloatSemiring> f3 = Polynomial<FloatSemiring>({
Monomial<FloatSemiring>(FloatSemiring(0.3), {Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(0.7), {}) });
polynomials.push_back(f1);
polynomials.push_back(f2);
polynomials.push_back(f3);
return polynomials;
}
void test_newton()
{
/*
Newton<FloatSemiring> newton;
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::cout << "- newton (float):" << std::endl;
std::vector<Polynomial<FloatSemiring> > polynomials = get_newton_test_polynomials();
Matrix<FloatSemiring> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
*/
/*
Newton<FreeSemiring> newton;
std::vector<Var> variables;
variables.push_back(Var("x"));
std::cout << "- newton (free-SR):" << std::endl;
std::vector<Polynomial<FreeSemiring> > polynomials;
Polynomial<FreeSemiring> f1 = Polynomial<FreeSemiring>({
Monomial<FreeSemiring>(FreeSemiring(Var("a")), {Var("x"),Var("x")}),
Monomial<FreeSemiring>(FreeSemiring(Var("c")), {}) });
polynomials.push_back(f1);
Matrix<FreeSemiring> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
*/
Newton<SemilinSetExp> newton;
std::vector<Var> variables;
variables.push_back(Var("x"));
std::cout << "- newton (counting-SR):" << std::endl;
std::vector<Polynomial<SemilinSetExp> > polynomials;
Polynomial<SemilinSetExp> f1 = Polynomial<SemilinSetExp>({
Monomial<SemilinSetExp>(SemilinSetExp(Var("a")), {Var("x"),Var("x")}),
Monomial<SemilinSetExp>(SemilinSetExp(Var("c")), {}) });
polynomials.push_back(f1);
Matrix<SemilinSetExp> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
}
int main(int argc, char* argv[])
{
std::cout << "testing..." << std::endl;
//test_addition();
//test_multiplication();
//test_variables();
//test_monomials();
//test_polynomial_addition();
//test_polynomial_multiplication();
//test_polynomial_evaluation();
//test_matrix_addition();
//test_matrix_multiplication();
//test_matrix_transpose();
//test_matrix_star();
//test_jacobian();
//test_polynomial_matrix_evaluation();
//test_freesemiring();
//test_polynomial_to_freesemiring();
//test_newton();
return 0;
}
<commit_msg>new testcase (in main)<commit_after>#include <iostream>
#include "float-semiring.h"
#include "free-semiring.h"
//#include "semilinSetExp.h"
#include "matrix.h"
#include "polynomial.h"
#include "newton.h"
#include "commutativeRExp.h"
void test_addition()
{
FloatSemiring first(0.5);
FloatSemiring second(0.3);
FloatSemiring result = first + second;
std::cout << "- float semiring addition: " << std::endl;
std::cout << first << " + " << second << " = " << result << std::endl;
}
void test_multiplication()
{
FloatSemiring first(0.5);
FloatSemiring second(0.3);
FloatSemiring result = first * second;
std::cout << "- float semiring multiplication: " << std::endl;
std::cout << first << " * " << second << " = " << result << std::endl;
}
void test_variables()
{
Var var1;
Var var2;
std::cout << "- variables:" << std::endl;
std::cout << var1 << "," << var2 << std::endl;
}
void test_monomials()
{
std::cout << "- monomials:" << std::endl;
Monomial<FloatSemiring> mon1(FloatSemiring(5),{Var("x"),Var("x"),Var("y")});
Monomial<FloatSemiring> mon2(FloatSemiring(2),{Var("y"), Var("x")});
Monomial<FloatSemiring> res1 = mon1 + mon1;
Monomial<FloatSemiring> res2 = mon1 * mon2;
std::cout << mon1 << " + " << mon1 << " = " << res1 << std::endl;
std::cout << mon1 << " * " << mon2 << " = " << res2 << std::endl;
std::cout << "derivative of " << mon1 << " = " << mon1.derivative(Var("x")) << std::endl;
}
Polynomial<FloatSemiring> get_first_polynomial()
{
// define new polynomial 2xx+7y
return Polynomial<FloatSemiring>(
{ Monomial<FloatSemiring>(FloatSemiring(2),{Var("x"),Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(7),{Var("z")}) });
}
Polynomial<FloatSemiring> get_second_polynomial()
{
// define new polynomial 5xx+3xy+6yy
return Polynomial<FloatSemiring>(
{ Monomial<FloatSemiring>(FloatSemiring(5),{Var("x"),Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(3),{Var("x"),Var("y")}),
Monomial<FloatSemiring>(FloatSemiring(6),{Var("y"),Var("y")})});
}
void test_polynomial_addition()
{
Polynomial<FloatSemiring> first = get_first_polynomial();
Polynomial<FloatSemiring> second = get_second_polynomial();
Polynomial<FloatSemiring> result = first + second;
std::cout << "- polynomial addition:" << std::endl;
std::cout << first << " + " << second << " = " << result << std::endl;
}
void test_polynomial_multiplication()
{
Polynomial<FloatSemiring> first = get_first_polynomial();
Polynomial<FloatSemiring> second = get_second_polynomial();
Polynomial<FloatSemiring> result = first * second;
std::cout << "- polynomial multiplication:" << std::endl;
std::cout << first << " * " << second << " = " << result << std::endl;
}
std::map<Var,FloatSemiring> get_variable_values()
{
std::map<Var,FloatSemiring> values;
values.insert(values.begin(), std::pair<Var,FloatSemiring>(Var("x"),FloatSemiring(5)));
values.insert(values.begin(), std::pair<Var,FloatSemiring>(Var("y"),FloatSemiring(4)));
values.insert(values.begin(), std::pair<Var,FloatSemiring>(Var("z"),FloatSemiring(0)));
return values;
}
void test_polynomial_evaluation()
{
Polynomial<FloatSemiring> polynomial = get_second_polynomial();
std::map<Var,FloatSemiring> values = get_variable_values();
FloatSemiring result = polynomial.eval(values);
std::cout << "- polynomial evaluation:" << std::endl;
std::cout << polynomial << " at {x=5, y=4, z=0} = " << result << std::endl;
}
Matrix<FloatSemiring> get_first_matrix()
{
FloatSemiring elems[] = {
FloatSemiring(0.5), FloatSemiring(0.9),
FloatSemiring(0.2), FloatSemiring(0.1)};
return Matrix<FloatSemiring>(2,2,std::vector<FloatSemiring>(elems, elems+4));
}
Matrix<FloatSemiring> get_second_matrix()
{
FloatSemiring elems[] = {
FloatSemiring(0.3), FloatSemiring(0.1),
FloatSemiring(0.7), FloatSemiring(0.2)};
return Matrix<FloatSemiring>(2,2,std::vector<FloatSemiring>(elems, elems+4));
}
Matrix<FreeSemiring> get_star_test_matrix()
{
/* FloatSemiring elems[] = {
FloatSemiring(0.6), FloatSemiring(0.1), FloatSemiring(0.1),
FloatSemiring(0.1), FloatSemiring(0.4), FloatSemiring(0.1),
FloatSemiring(0.1), FloatSemiring(0.1), FloatSemiring(0.3)};
return Matrix<FloatSemiring>(3,3,std::vector<FloatSemiring>(elems, elems+9));
*/
FreeSemiring elems[] = {
FreeSemiring(Var("a")),
FreeSemiring(Var("b")),
FreeSemiring(Var("c")),
FreeSemiring(Var("d")) };
return Matrix<FreeSemiring>(2,2,std::vector<FreeSemiring>(elems, elems+4));
}
void test_matrix_addition()
{
Matrix<FloatSemiring> first = get_first_matrix();
Matrix<FloatSemiring> second = get_second_matrix();
Matrix<FloatSemiring> result = first + second;
std::cout << "- matrix addition:" << std::endl;
std::cout << first << " + " << std::endl << second << " = " << std::endl << result;
}
void test_matrix_multiplication()
{
Matrix<FloatSemiring> first = get_first_matrix();
Matrix<FloatSemiring> second = get_second_matrix();
Matrix<FloatSemiring> result = first * second;
std::cout << "- matrix multiplication:" << std::endl;
std::cout << first << " * " << std::endl << second << " = " << std::endl << result;
}
void test_matrix_transpose()
{
Matrix<FloatSemiring> matrix = get_first_matrix();
Matrix<FloatSemiring> result = matrix.transpose();
std::cout << "- matrix transpose:" << std::endl;
std::cout << matrix << " transposed " << std::endl << result;
}
void test_matrix_star()
{
auto matrix = get_star_test_matrix();
auto result = matrix.star();
std::cout << "- matrix star:" << std::endl;
std::cout << matrix << " the matrix star of this is: " << std::endl << result;
}
void test_jacobian()
{
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::vector<Polynomial<FloatSemiring> > polynomials;
polynomials.push_back(get_first_polynomial());
polynomials.push_back(get_second_polynomial());
Matrix<Polynomial<FloatSemiring> > jacobian = Polynomial<FloatSemiring>::jacobian(polynomials, variables);
std::cout << "- jacobian (x,y,z) of " << std::endl;
std::cout << polynomials.at(0) << std::endl << polynomials.at(1) << std::endl << " = " << std::endl << jacobian << std::endl;
}
void test_polynomial_matrix_evaluation()
{
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::vector<Polynomial<FloatSemiring> > polynomials;
polynomials.push_back(get_first_polynomial());
polynomials.push_back(get_second_polynomial());
Matrix<Polynomial<FloatSemiring> > polynomial_matrix = Polynomial<FloatSemiring>::jacobian(polynomials, variables);
std::map<Var,FloatSemiring> values = get_variable_values();
Matrix<FloatSemiring> result = Polynomial<FloatSemiring>::eval(polynomial_matrix, values);
std::cout << "- polynomial matrix evaluation" << std::endl;
std::cout << polynomial_matrix << " at {x=5, y=4, z=0} = " << std::endl << result;
}
void test_freesemiring()
{
std::cout << "- free semiring" << std::endl;
FreeSemiring term1 = FreeSemiring(Var("a"));
FreeSemiring term2 = FreeSemiring(Var("b"));
std::cout << "some terms: " << term1 << " and " << term2 << std::endl;
FreeSemiring termAdd = term1 + term2;
FreeSemiring termMul = term1 * term2;
std::cout << "addition&multiplication&star: " << (termAdd*termMul.star()) << std::endl;
}
void test_polynomial_to_freesemiring()
{
std::cout << "- polynomial to free semiring conversion" <<std::endl;
Polynomial<FloatSemiring> poly = get_first_polynomial();
auto valuation = new std::unordered_map<FloatSemiring, FreeSemiring, FloatSemiring>();
FreeSemiring elem = poly.make_free(valuation);
for(auto v_it = valuation->begin(); v_it != valuation->end(); ++v_it)
{
std::cout << "valuation: " << v_it->first << " → " << v_it->second << std::endl;
}
std::cout << "polynomial: " << poly << std::endl;
std::cout << "free semiring: " << elem << std::endl;
}
std::vector<Polynomial<FloatSemiring> > get_newton_test_polynomials()
{
std::vector<Polynomial<FloatSemiring> > polynomials;
// define new polynomial 0.4xy+0.6
Polynomial<FloatSemiring> f1 = Polynomial<FloatSemiring>({
Monomial<FloatSemiring>(FloatSemiring(0.4), {Var("x"),Var("y")}),
Monomial<FloatSemiring>(FloatSemiring(0.6), {}) });
// define new polynomial 0.3yz+0.4yx+0.3
Polynomial<FloatSemiring> f2 = Polynomial<FloatSemiring>({
Monomial<FloatSemiring>(FloatSemiring(0.3), {Var("y"),Var("z")}),
Monomial<FloatSemiring>(FloatSemiring(0.4), {Var("y"),Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(0.3), {}) });
// define new polynomial 0.3x+0.7
Polynomial<FloatSemiring> f3 = Polynomial<FloatSemiring>({
Monomial<FloatSemiring>(FloatSemiring(0.3), {Var("x")}),
Monomial<FloatSemiring>(FloatSemiring(0.7), {}) });
polynomials.push_back(f1);
polynomials.push_back(f2);
polynomials.push_back(f3);
return polynomials;
}
void test_newton()
{
/*
Newton<FloatSemiring> newton;
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::cout << "- newton (float):" << std::endl;
std::vector<Polynomial<FloatSemiring> > polynomials = get_newton_test_polynomials();
Matrix<FloatSemiring> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
*/
/*
Newton<FreeSemiring> newton;
std::vector<Var> variables;
variables.push_back(Var("x"));
std::cout << "- newton (free-SR):" << std::endl;
std::vector<Polynomial<FreeSemiring> > polynomials;
Polynomial<FreeSemiring> f1 = Polynomial<FreeSemiring>({
Monomial<FreeSemiring>(FreeSemiring(Var("a")), {Var("x"),Var("x")}),
Monomial<FreeSemiring>(FreeSemiring(Var("c")), {}) });
polynomials.push_back(f1);
Matrix<FreeSemiring> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
*/
Newton<CommutativeRExp> newton;
std::vector<Var> variables;
variables.push_back(Var("x"));
variables.push_back(Var("y"));
variables.push_back(Var("z"));
std::cout << "- newton (counting-SR):" << std::endl;
std::vector<Polynomial<CommutativeRExp> > polynomials;
// define new polynomial axy+b
Polynomial<CommutativeRExp> f1 = Polynomial<CommutativeRExp>({
Monomial<CommutativeRExp>(CommutativeRExp(Var("a")), {Var("x"),Var("y")}),
Monomial<CommutativeRExp>(CommutativeRExp(Var("b")), {}) });
// define new polynomial cyz+dyx+e
Polynomial<CommutativeRExp> f2 = Polynomial<CommutativeRExp>({
Monomial<CommutativeRExp>(CommutativeRExp(Var("c")), {Var("y"),Var("z")}),
Monomial<CommutativeRExp>(CommutativeRExp(Var("d")), {Var("y"),Var("x")}),
Monomial<CommutativeRExp>(CommutativeRExp(Var("e")), {}) });
// define new polynomial fx+g
Polynomial<CommutativeRExp> f3 = Polynomial<CommutativeRExp>({
Monomial<CommutativeRExp>(CommutativeRExp(Var("f")), {Var("x")}),
Monomial<CommutativeRExp>(CommutativeRExp(Var("g")), {}) });
polynomials.push_back(f1);
polynomials.push_back(f2);
polynomials.push_back(f3);
Matrix<CommutativeRExp> result = newton.solve_fixpoint(polynomials, variables, 3);
std::cout << result << std::endl;
}
int main(int argc, char* argv[])
{
std::cout << "testing..." << std::endl;
//test_addition();
//test_multiplication();
//test_variables();
//test_monomials();
//test_polynomial_addition();
//test_polynomial_multiplication();
//test_polynomial_evaluation();
//test_matrix_addition();
//test_matrix_multiplication();
//test_matrix_transpose();
//test_matrix_star();
//test_jacobian();
//test_polynomial_matrix_evaluation();
//test_freesemiring();
//test_polynomial_to_freesemiring();
test_newton();
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <re2/re2.h>
#include "cre2.h"
#define TO_OPT(opt) (reinterpret_cast<RE2::Options *>(opt))
cre2_options *cre2_opt_new(void) {
return reinterpret_cast<void*>(new RE2::Options());
}
void cre2_opt_delete(cre2_options *opt) {
delete TO_OPT(opt);
}
#define OPT_bool(name) \
void cre2_opt_##name(cre2_options *opt, int flag) { \
TO_OPT(opt)->set_##name(bool(flag)); \
}
OPT_bool(posix_syntax)
OPT_bool(longest_match)
OPT_bool(log_errors)
OPT_bool(literal)
OPT_bool(never_nl)
OPT_bool(case_sensitive)
OPT_bool(perl_classes)
OPT_bool(word_boundary)
OPT_bool(one_line)
#undef OPT_BOOL
void cre2_opt_encoding(cre2_options *opt, encoding_t enc) {
switch (enc) {
case CRE2_UTF8:
TO_OPT(opt)->set_encoding(RE2::Options::EncodingUTF8);
break;
case CRE2_Latin1:
TO_OPT(opt)->set_encoding(RE2::Options::EncodingLatin1);
break;
}
}
void cre2_opt_max_mem(cre2_options *opt, int m) {
TO_OPT(opt)->set_max_mem(m);
}
#define TO_RE2(re) (reinterpret_cast<RE2 *>(re))
#define TO_CONST_RE2(re) (reinterpret_cast<const RE2 *>(re))
cre2 *cre2_new(const char *pattern, const cre2_options *opt) {
return reinterpret_cast<void*>(
new RE2(pattern, *reinterpret_cast<const RE2::Options *>(opt)));
}
void cre2_delete(cre2 *re) {
delete TO_RE2(re);
}
int cre2_error_code(const cre2 *re) {
return int(TO_CONST_RE2(re)->error_code());
}
char *cre2_error_string(const cre2 *re) {
return strdup(TO_CONST_RE2(re)->error().c_str());
}
char *cre2_error_arg(const cre2 *re) {
return strdup(TO_CONST_RE2(re)->error_arg().c_str());
}
int cre2_num_capturing_groups(const cre2 *re) {
return TO_CONST_RE2(re)->NumberOfCapturingGroups();
}
int cre2_program_size(const cre2 *re) {
return TO_CONST_RE2(re)->ProgramSize();
}
int cre2_match(
const cre2 *re
, const char *text
, int startpos
, int endpos
, anchor_t anchor
, struct string_piece *match
, int nmatch) {
// FIXME: exceptions?
re2::StringPiece *match_re2 = new re2::StringPiece[nmatch];
RE2::Anchor anchor_re2;
switch (anchor) {
case CRE2_UNANCHORED:
anchor_re2 = RE2::UNANCHORED; break;
case CRE2_ANCHOR_START:
anchor_re2 = RE2::ANCHOR_START; break;
case CRE2_ANCHOR_BOTH:
anchor_re2 = RE2::ANCHOR_BOTH; break;
}
bool ret = TO_CONST_RE2(re)
->Match(text, startpos, endpos, anchor_re2, match_re2, nmatch);
if (ret) {
for (int i=0; i<nmatch; i++) {
match[i].data = match_re2[i].data();
match[i].length = match_re2[i].length();
}
}
delete [] match_re2;
return int(ret);
}
<commit_msg>initialize anchor_re2<commit_after>#include <string>
#include <re2/re2.h>
#include "cre2.h"
#define TO_OPT(opt) (reinterpret_cast<RE2::Options *>(opt))
cre2_options *cre2_opt_new(void) {
return reinterpret_cast<void*>(new RE2::Options());
}
void cre2_opt_delete(cre2_options *opt) {
delete TO_OPT(opt);
}
#define OPT_bool(name) \
void cre2_opt_##name(cre2_options *opt, int flag) { \
TO_OPT(opt)->set_##name(bool(flag)); \
}
OPT_bool(posix_syntax)
OPT_bool(longest_match)
OPT_bool(log_errors)
OPT_bool(literal)
OPT_bool(never_nl)
OPT_bool(case_sensitive)
OPT_bool(perl_classes)
OPT_bool(word_boundary)
OPT_bool(one_line)
#undef OPT_BOOL
void cre2_opt_encoding(cre2_options *opt, encoding_t enc) {
switch (enc) {
case CRE2_UTF8:
TO_OPT(opt)->set_encoding(RE2::Options::EncodingUTF8);
break;
case CRE2_Latin1:
TO_OPT(opt)->set_encoding(RE2::Options::EncodingLatin1);
break;
}
}
void cre2_opt_max_mem(cre2_options *opt, int m) {
TO_OPT(opt)->set_max_mem(m);
}
#define TO_RE2(re) (reinterpret_cast<RE2 *>(re))
#define TO_CONST_RE2(re) (reinterpret_cast<const RE2 *>(re))
cre2 *cre2_new(const char *pattern, const cre2_options *opt) {
return reinterpret_cast<void*>(
new RE2(pattern, *reinterpret_cast<const RE2::Options *>(opt)));
}
void cre2_delete(cre2 *re) {
delete TO_RE2(re);
}
int cre2_error_code(const cre2 *re) {
return int(TO_CONST_RE2(re)->error_code());
}
char *cre2_error_string(const cre2 *re) {
return strdup(TO_CONST_RE2(re)->error().c_str());
}
char *cre2_error_arg(const cre2 *re) {
return strdup(TO_CONST_RE2(re)->error_arg().c_str());
}
int cre2_num_capturing_groups(const cre2 *re) {
return TO_CONST_RE2(re)->NumberOfCapturingGroups();
}
int cre2_program_size(const cre2 *re) {
return TO_CONST_RE2(re)->ProgramSize();
}
int cre2_match(
const cre2 *re
, const char *text
, int startpos
, int endpos
, anchor_t anchor
, struct string_piece *match
, int nmatch) {
// FIXME: exceptions?
re2::StringPiece *match_re2 = new re2::StringPiece[nmatch];
RE2::Anchor anchor_re2 = RE2::UNANCHORED;
switch (anchor) {
case CRE2_ANCHOR_START:
anchor_re2 = RE2::ANCHOR_START; break;
case CRE2_ANCHOR_BOTH:
anchor_re2 = RE2::ANCHOR_BOTH; break;
}
bool ret = TO_CONST_RE2(re)
->Match(text, startpos, endpos, anchor_re2, match_re2, nmatch);
if (ret) {
for (int i=0; i<nmatch; i++) {
match[i].data = match_re2[i].data();
match[i].length = match_re2[i].length();
}
}
delete [] match_re2;
return int(ret);
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2015 Cornell University
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <assert.h>
#include "SonicUserRequest.h"
#include "SonicUserIndication.h"
#define NUMBER_OF_TESTS 1
static SonicUserRequestProxy *device = 0;
//static sem_t wait_log;
class SonicUser : public SonicUserIndicationWrapper
{
public:
virtual void dtp_read_version_resp(uint32_t a) {
fprintf(stderr, "read version %d\n", a);
}
virtual void dtp_read_delay_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read delay(%d) %d\n", p, a);
}
virtual void dtp_read_state_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read state(%d) %d\n", p, a);
}
virtual void dtp_read_error_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read error(%d) %ld\n", p, a);
}
virtual void dtp_read_cnt_resp(uint64_t a) {
fprintf(stderr, "readCycleCount(%lx)\n", a);
}
virtual void dtp_logger_read_cnt_resp(uint8_t a, uint64_t b, uint64_t c, uint64_t d) {
fprintf(stderr, "read from port(%d) local_cnt(%lx) msg1(%lx) msg2(%lx)\n", a, b, c, d);
}
virtual void dtp_read_local_cnt_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%lx)\n", p, a);
}
virtual void dtp_read_global_cnt_resp(uint64_t a) {
fprintf(stderr, "read global_cnt(%lx)\n", a);
}
virtual void dtp_read_beacon_interval_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%x)\n", p, a);
}
virtual void dtp_debug_rcvd_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq1(%x) enq2(%x) deq(%x)\n", p, a, b, c);
}
virtual void dtp_debug_sent_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq(%x) deq1(%x) deq2(%x)\n", p, a, b, c);
}
virtual void dtp_debug_rcvd_err_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) err(%x)\n", p, a);
}
virtual void dtp_get_mode_resp(uint8_t a) {
fprintf(stderr, "read from mode(%x)\n", a);
}
SonicUser(unsigned int id) : SonicUserIndicationWrapper(id) {}
};
int main(int argc, const char **argv)
{
uint32_t count = 100;
SonicUser indication(IfcNames_SonicUserIndicationH2S);
device = new SonicUserRequestProxy(IfcNames_SonicUserRequestS2H);
device->pint.busyType = BUSY_SPIN; /* spin until request portal 'notFull' */
device->dtp_reset(32);
device->dtp_get_mode();
device->dtp_read_version();
fprintf(stderr, "Main::about to go to sleep\n");
while(true){
for (int i=0; i<1; i++) {
device->dtp_read_delay(i);
device->dtp_read_state(i);
device->dtp_read_error(i);
device->dtp_read_cnt(i);
}
sleep(1);
for (int i=0; i<4; i++) {
device->dtp_logger_write_cnt(i, count);
}
for (int i=0; i<4; i++) {
device->dtp_logger_read_cnt(i);
}
count ++;
sleep(1);
}
}
<commit_msg>fixed test-dtp<commit_after>/* Copyright (c) 2015 Cornell University
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <assert.h>
#include "DtpUserRequest.h"
#include "DtpUserIndication.h"
#define NUMBER_OF_TESTS 1
static DtpUserRequestProxy *device = 0;
//static sem_t wait_log;
class DtpUser : public DtpUserIndicationWrapper
{
public:
virtual void dtp_read_version_resp(uint32_t a) {
fprintf(stderr, "read version %d\n", a);
}
virtual void dtp_read_delay_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read delay(%d) %d\n", p, a);
}
virtual void dtp_read_state_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read state(%d) %d\n", p, a);
}
virtual void dtp_read_error_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read error(%d) %ld\n", p, a);
}
virtual void dtp_read_cnt_resp(uint64_t a) {
fprintf(stderr, "readCycleCount(%lx)\n", a);
}
virtual void dtp_logger_read_cnt_resp(uint8_t a, uint64_t b, uint64_t c, uint64_t d) {
fprintf(stderr, "read from port(%d) local_cnt(%lx) msg1(%lx) msg2(%lx)\n", a, b, c, d);
}
virtual void dtp_read_local_cnt_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%lx)\n", p, a);
}
virtual void dtp_read_global_cnt_resp(uint64_t a) {
fprintf(stderr, "read global_cnt(%lx)\n", a);
}
virtual void dtp_read_beacon_interval_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%x)\n", p, a);
}
virtual void dtp_debug_rcvd_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq1(%x) enq2(%x) deq(%x)\n", p, a, b, c);
}
virtual void dtp_debug_sent_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq(%x) deq1(%x) deq2(%x)\n", p, a, b, c);
}
virtual void dtp_debug_rcvd_err_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) err(%x)\n", p, a);
}
virtual void dtp_get_mode_resp(uint8_t a) {
fprintf(stderr, "read from mode(%x)\n", a);
}
DtpUser(unsigned int id) : DtpUserIndicationWrapper(id) {}
};
int main(int argc, const char **argv)
{
uint32_t count = 100;
DtpUser indication(IfcNames_DtpUserIndicationH2S);
device = new DtpUserRequestProxy(IfcNames_DtpUserRequestS2H);
device->pint.busyType = BUSY_SPIN; /* spin until request portal 'notFull' */
device->dtp_reset(32);
device->dtp_get_mode();
device->dtp_read_version();
fprintf(stderr, "Main::about to go to sleep\n");
while(true){
for (int i=0; i<1; i++) {
device->dtp_read_delay(i);
device->dtp_read_state(i);
device->dtp_read_error(i);
device->dtp_read_cnt(i);
}
sleep(1);
for (int i=0; i<4; i++) {
device->dtp_logger_write_cnt(i, count);
}
for (int i=0; i<4; i++) {
device->dtp_logger_read_cnt(i);
}
count ++;
sleep(1);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/test/thread_test_helper.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/in_process_webkit/indexed_db_context.h"
#include "content/browser/in_process_webkit/webkit_context.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/common/content_switches.h"
#include "webkit/database/database_util.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include "webkit/quota/quota_manager.h"
#include "webkit/quota/special_storage_policy.h"
using content::BrowserThread;
using quota::QuotaManager;
using webkit_database::DatabaseUtil;
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url, bool incognito = false) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
Browser* the_browser = incognito ? CreateIncognitoBrowser() : browser();
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
the_browser, test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = the_browser->GetSelectedWebContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
the_browser->GetSelectedWebContents()->GetRenderViewHost(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))),
true /* incognito */);
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorPrefetch) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_prefetch.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
#if defined(OS_WIN)
// http://crbug.com/104306
#define KeyTypesTest FLAKY_KeyTypesTest
#endif
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_types_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedWebContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_84933.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug106883Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_106883.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug109187Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_109187.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath protected_path;
FilePath unprotected_path;
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
// Test our assumptions about what is protected and what is not.
const GURL kProtectedOrigin("chrome-extension://foo/");
const GURL kUnprotectedOrigin("http://foo/");
quota::SpecialStoragePolicy* policy = profile.GetSpecialStoragePolicy();
ASSERT_TRUE(policy->IsStorageProtected(kProtectedOrigin));
ASSERT_FALSE(policy->IsStorageProtected(kUnprotectedOrigin));
// Create some indexedDB paths.
// With the levelDB backend, these are directories.
WebKitContext *webkit_context = profile.GetWebKitContext();
IndexedDBContext* idb_context = webkit_context->indexed_db_context();
idb_context->set_data_path_for_testing(temp_dir.path());
protected_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kProtectedOrigin));
unprotected_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kUnprotectedOrigin));
ASSERT_TRUE(file_util::CreateDirectory(protected_path));
ASSERT_TRUE(file_util::CreateDirectory(unprotected_path));
// Setup to clear all unprotected origins on exit.
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::WEBKIT_DEPRECATED)));
ASSERT_TRUE(helper->Run());
ASSERT_TRUE(file_util::DirectoryExists(protected_path));
ASSERT_FALSE(file_util::DirectoryExists(unprotected_path));
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearSessionOnlyDatabases) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath normal_path;
FilePath session_only_path;
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
const GURL kNormalOrigin("http://normal/");
const GURL kSessionOnlyOrigin("http://session-only/");
scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =
new quota::MockSpecialStoragePolicy;
special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);
// Create some indexedDB paths.
// With the levelDB backend, these are directories.
WebKitContext *webkit_context = profile.GetWebKitContext();
IndexedDBContext* idb_context = webkit_context->indexed_db_context();
// Override the storage policy with our own.
idb_context->special_storage_policy_ = special_storage_policy;
idb_context->set_data_path_for_testing(temp_dir.path());
normal_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kNormalOrigin));
session_only_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));
ASSERT_TRUE(file_util::CreateDirectory(normal_path));
ASSERT_TRUE(file_util::CreateDirectory(session_only_path));
}
// Make sure we wait until the destructor has run.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::WEBKIT_DEPRECATED)));
ASSERT_TRUE(helper->Run());
EXPECT_TRUE(file_util::DirectoryExists(normal_path));
EXPECT_FALSE(file_util::DirectoryExists(session_only_path));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, SaveSessionState) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath normal_path;
FilePath session_only_path;
// Create the scope which will ensure we run the destructor of the webkit
// context.
{
TestingProfile profile;
const GURL kNormalOrigin("http://normal/");
const GURL kSessionOnlyOrigin("http://session-only/");
scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =
new quota::MockSpecialStoragePolicy;
special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);
// Create some indexedDB paths.
// With the levelDB backend, these are directories.
WebKitContext *webkit_context = profile.GetWebKitContext();
IndexedDBContext* idb_context = webkit_context->indexed_db_context();
// Override the storage policy with our own.
idb_context->special_storage_policy_ = special_storage_policy;
idb_context->set_clear_local_state_on_exit(true);
idb_context->set_data_path_for_testing(temp_dir.path());
// Save session state. This should bypass the destruction-time deletion.
idb_context->SaveSessionState();
normal_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kNormalOrigin));
session_only_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));
ASSERT_TRUE(file_util::CreateDirectory(normal_path));
ASSERT_TRUE(file_util::CreateDirectory(session_only_path));
}
// Make sure we wait until the destructor has run.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::WEBKIT_DEPRECATED)));
ASSERT_TRUE(helper->Run());
// No data was cleared because of SaveSessionState.
EXPECT_TRUE(file_util::DirectoryExists(normal_path));
EXPECT_TRUE(file_util::DirectoryExists(session_only_path));
}
class IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest {
public:
virtual void SetUpOnMainThread() {
const int kInitialQuotaKilobytes = 5000;
const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes
* 1024 * QuotaManager::kPerHostTemporaryPortion;
SetTempQuota(
kTemporaryStorageQuotaMaxSize, browser()->profile()->GetQuotaManager());
}
static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes,
qm));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback());
// Don't return until the quota has been set.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)));
ASSERT_TRUE(helper->Run());
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, FAILS_QuotaTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("quota_test.html"))));
}
class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed,
DatabaseCallbacksTest) {
SimpleTest(
testUrl(FilePath(FILE_PATH_LITERAL("database_callbacks_first.html"))));
}
<commit_msg>Mark IndexeDBBrowserTestWithLowQuota.QuotaTest test as DISABLED.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/test/thread_test_helper.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/in_process_webkit/indexed_db_context.h"
#include "content/browser/in_process_webkit/webkit_context.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/common/content_switches.h"
#include "webkit/database/database_util.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include "webkit/quota/quota_manager.h"
#include "webkit/quota/special_storage_policy.h"
using content::BrowserThread;
using quota::QuotaManager;
using webkit_database::DatabaseUtil;
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url, bool incognito = false) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
Browser* the_browser = incognito ? CreateIncognitoBrowser() : browser();
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
the_browser, test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = the_browser->GetSelectedWebContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
the_browser->GetSelectedWebContents()->GetRenderViewHost(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))),
true /* incognito */);
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorPrefetch) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_prefetch.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
#if defined(OS_WIN)
// http://crbug.com/104306
#define KeyTypesTest FLAKY_KeyTypesTest
#endif
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_types_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedWebContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_84933.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug106883Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_106883.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug109187Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_109187.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath protected_path;
FilePath unprotected_path;
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
// Test our assumptions about what is protected and what is not.
const GURL kProtectedOrigin("chrome-extension://foo/");
const GURL kUnprotectedOrigin("http://foo/");
quota::SpecialStoragePolicy* policy = profile.GetSpecialStoragePolicy();
ASSERT_TRUE(policy->IsStorageProtected(kProtectedOrigin));
ASSERT_FALSE(policy->IsStorageProtected(kUnprotectedOrigin));
// Create some indexedDB paths.
// With the levelDB backend, these are directories.
WebKitContext *webkit_context = profile.GetWebKitContext();
IndexedDBContext* idb_context = webkit_context->indexed_db_context();
idb_context->set_data_path_for_testing(temp_dir.path());
protected_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kProtectedOrigin));
unprotected_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kUnprotectedOrigin));
ASSERT_TRUE(file_util::CreateDirectory(protected_path));
ASSERT_TRUE(file_util::CreateDirectory(unprotected_path));
// Setup to clear all unprotected origins on exit.
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::WEBKIT_DEPRECATED)));
ASSERT_TRUE(helper->Run());
ASSERT_TRUE(file_util::DirectoryExists(protected_path));
ASSERT_FALSE(file_util::DirectoryExists(unprotected_path));
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearSessionOnlyDatabases) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath normal_path;
FilePath session_only_path;
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
const GURL kNormalOrigin("http://normal/");
const GURL kSessionOnlyOrigin("http://session-only/");
scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =
new quota::MockSpecialStoragePolicy;
special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);
// Create some indexedDB paths.
// With the levelDB backend, these are directories.
WebKitContext *webkit_context = profile.GetWebKitContext();
IndexedDBContext* idb_context = webkit_context->indexed_db_context();
// Override the storage policy with our own.
idb_context->special_storage_policy_ = special_storage_policy;
idb_context->set_data_path_for_testing(temp_dir.path());
normal_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kNormalOrigin));
session_only_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));
ASSERT_TRUE(file_util::CreateDirectory(normal_path));
ASSERT_TRUE(file_util::CreateDirectory(session_only_path));
}
// Make sure we wait until the destructor has run.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::WEBKIT_DEPRECATED)));
ASSERT_TRUE(helper->Run());
EXPECT_TRUE(file_util::DirectoryExists(normal_path));
EXPECT_FALSE(file_util::DirectoryExists(session_only_path));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, SaveSessionState) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath normal_path;
FilePath session_only_path;
// Create the scope which will ensure we run the destructor of the webkit
// context.
{
TestingProfile profile;
const GURL kNormalOrigin("http://normal/");
const GURL kSessionOnlyOrigin("http://session-only/");
scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =
new quota::MockSpecialStoragePolicy;
special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);
// Create some indexedDB paths.
// With the levelDB backend, these are directories.
WebKitContext *webkit_context = profile.GetWebKitContext();
IndexedDBContext* idb_context = webkit_context->indexed_db_context();
// Override the storage policy with our own.
idb_context->special_storage_policy_ = special_storage_policy;
idb_context->set_clear_local_state_on_exit(true);
idb_context->set_data_path_for_testing(temp_dir.path());
// Save session state. This should bypass the destruction-time deletion.
idb_context->SaveSessionState();
normal_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kNormalOrigin));
session_only_path = idb_context->GetIndexedDBFilePath(
DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));
ASSERT_TRUE(file_util::CreateDirectory(normal_path));
ASSERT_TRUE(file_util::CreateDirectory(session_only_path));
}
// Make sure we wait until the destructor has run.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::WEBKIT_DEPRECATED)));
ASSERT_TRUE(helper->Run());
// No data was cleared because of SaveSessionState.
EXPECT_TRUE(file_util::DirectoryExists(normal_path));
EXPECT_TRUE(file_util::DirectoryExists(session_only_path));
}
class IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest {
public:
virtual void SetUpOnMainThread() {
const int kInitialQuotaKilobytes = 5000;
const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes
* 1024 * QuotaManager::kPerHostTemporaryPortion;
SetTempQuota(
kTemporaryStorageQuotaMaxSize, browser()->profile()->GetQuotaManager());
}
static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes,
qm));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback());
// Don't return until the quota has been set.
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)));
ASSERT_TRUE(helper->Run());
}
};
// No longer testable with file: URL: http://crbug.com/104748
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, DISABLED_QuotaTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("quota_test.html"))));
}
class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed,
DatabaseCallbacksTest) {
SimpleTest(
testUrl(FilePath(FILE_PATH_LITERAL("database_callbacks_first.html"))));
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "executors.h"
#include "engine_wrapper.h"
#include "utilities.h"
#include <daemon/mcbp.h>
#include <memcached/protocol_binary.h>
void dcp_buffer_acknowledgement_executor(Cookie& cookie) {
auto ret = cookie.swapAiostat(ENGINE_SUCCESS);
auto& connection = cookie.getConnection();
if (ret == ENGINE_SUCCESS) {
ret = mcbp::haveDcpPrivilege(cookie);
if (ret == ENGINE_SUCCESS) {
const auto& header = cookie.getRequest();
const auto* req = reinterpret_cast<
const protocol_binary_request_dcp_buffer_acknowledgement*>(
&header);
uint32_t bbytes;
memcpy(&bbytes, &req->message.body.buffer_bytes, 4);
ret = dcpBufferAcknowledgement(cookie,
header.getOpaque(),
header.getVBucket(),
ntohl(bbytes));
}
}
ret = connection.remapErrorCode(ret);
switch (ret) {
case ENGINE_SUCCESS:
connection.setState(StateMachine::State::new_cmd);
break;
case ENGINE_DISCONNECT:
connection.setState(StateMachine::State::closing);
break;
case ENGINE_EWOULDBLOCK:
cookie.setEwouldblock(true);
break;
default:
cookie.sendResponse(cb::engine_errc(ret));
}
}
<commit_msg>Refactor: Prepare dcp_buffer_acknowledgement_executor for Frame Extras<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "executors.h"
#include "engine_wrapper.h"
#include "utilities.h"
#include <daemon/mcbp.h>
#include <memcached/protocol_binary.h>
void dcp_buffer_acknowledgement_executor(Cookie& cookie) {
auto ret = cookie.swapAiostat(ENGINE_SUCCESS);
auto& connection = cookie.getConnection();
if (ret == ENGINE_SUCCESS) {
ret = mcbp::haveDcpPrivilege(cookie);
if (ret == ENGINE_SUCCESS) {
auto& req = cookie.getRequest(Cookie::PacketContent::Full);
auto extras = req.getExtdata();
uint32_t bytes =
ntohl(*reinterpret_cast<const uint32_t*>(extras.data()));
ret = dcpBufferAcknowledgement(
cookie, req.getOpaque(), req.getVBucket(), bytes);
}
}
ret = connection.remapErrorCode(ret);
switch (ret) {
case ENGINE_SUCCESS:
connection.setState(StateMachine::State::new_cmd);
break;
case ENGINE_DISCONNECT:
connection.setState(StateMachine::State::closing);
break;
case ENGINE_EWOULDBLOCK:
cookie.setEwouldblock(true);
break;
default:
cookie.sendResponse(cb::engine_errc(ret));
}
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
// \author John W. Peterson
// \date 2011
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "libmesh/elem.h"
#include "libmesh/face_tri3.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_tetgen_interface.h"
#include "libmesh/mesh_triangle_holes.h"
#include "libmesh/mesh_triangle_interface.h"
#include "libmesh/node.h"
#include "libmesh/replicated_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain(const Parallel::Communicator & comm);
void tetrahedralize_domain(const Parallel::Communicator & comm);
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase & mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char ** argv)
{
// Initialize libMesh and any dependent libraries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
libMesh::out << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain(init.comm());
libmesh_example_requires(3 <= LIBMESH_DIM, "3D support");
libMesh::out << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain(init.comm());
return 0;
}
void triangulate_domain(const Parallel::Communicator & comm)
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(comm, 2);
// The points which make up the L-shape:
mesh.add_point(Point(0., 0.));
mesh.add_point(Point(0., -1.));
mesh.add_point(Point(-1., -1.));
mesh.add_point(Point(-1., 1.));
mesh.add_point(Point(1., 1.));
mesh.add_point(Point(1., 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole *> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#else
// Avoid compiler warnings
libmesh_ignore(comm);
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain(const Parallel::Communicator & comm)
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
ReplicatedMesh mesh(comm, 3);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh,
Point(0., 0., 0.),
Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point(0.5*(hole_lower_limit + hole_upper_limit));
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
// In debug mode, set the tetgen switches
// -V (verbose) and
// -CC (check consistency and constrained Delaunay)
// In optimized mode, only switch Q (quiet) is set.
// For more options, see tetgen website:
// (http://wias-berlin.de/software/tetgen/1.5/doc/manual/manual005.html#cmd-m)
#ifdef DEBUG
t.set_switches("VCC");
#endif
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#else
// Avoid compiler warnings
libmesh_ignore(comm);
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase & mesh,
Point lower_limit,
Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
ReplicatedMesh cube_mesh(mesh.comm(), 3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem, n_elem, n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned, unsigned> node_id_map;
typedef std::map<unsigned, unsigned>::iterator iterator;
for (auto & elem : cube_mesh.element_ptr_range())
for (auto s : elem->side_index_range())
if (elem->neighbor(s) == nullptr)
{
// Add the node IDs of this side to the set
std::unique_ptr<Elem> side = elem->side(s);
for (auto n : side->node_index_range())
node_id_map.insert(std::make_pair(side->node_id(n), /*dummy_value=*/0));
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node & old_node = cube_mesh.node_ref(id);
// Add geometric point to input mesh
Node * new_node = mesh.add_point (old_node);
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
for (auto & old_elem : cube_mesh.element_ptr_range())
if (old_elem->type() == TRI3)
{
Elem * new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (auto i : old_elem->node_index_range())
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node_id(i));
// Check for not found
if (it == node_id_map.end())
libmesh_error_msg("Node id " << old_elem->node_id(i) << " not found in map!");
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
#else
// Avoid compiler warnings
libmesh_ignore(mesh, lower_limit, upper_limit);
#endif // LIBMESH_HAVE_TETGEN
}
<commit_msg>Remove deprecated Elem API calls.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
// \author John W. Peterson
// \date 2011
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "libmesh/elem.h"
#include "libmesh/face_tri3.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_tetgen_interface.h"
#include "libmesh/mesh_triangle_holes.h"
#include "libmesh/mesh_triangle_interface.h"
#include "libmesh/node.h"
#include "libmesh/replicated_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain(const Parallel::Communicator & comm);
void tetrahedralize_domain(const Parallel::Communicator & comm);
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase & mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char ** argv)
{
// Initialize libMesh and any dependent libraries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
libMesh::out << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain(init.comm());
libmesh_example_requires(3 <= LIBMESH_DIM, "3D support");
libMesh::out << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain(init.comm());
return 0;
}
void triangulate_domain(const Parallel::Communicator & comm)
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(comm, 2);
// The points which make up the L-shape:
mesh.add_point(Point(0., 0.));
mesh.add_point(Point(0., -1.));
mesh.add_point(Point(-1., -1.));
mesh.add_point(Point(-1., 1.));
mesh.add_point(Point(1., 1.));
mesh.add_point(Point(1., 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole *> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#else
// Avoid compiler warnings
libmesh_ignore(comm);
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain(const Parallel::Communicator & comm)
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
ReplicatedMesh mesh(comm, 3);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh,
Point(0., 0., 0.),
Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point(0.5*(hole_lower_limit + hole_upper_limit));
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
// In debug mode, set the tetgen switches
// -V (verbose) and
// -CC (check consistency and constrained Delaunay)
// In optimized mode, only switch Q (quiet) is set.
// For more options, see tetgen website:
// (http://wias-berlin.de/software/tetgen/1.5/doc/manual/manual005.html#cmd-m)
#ifdef DEBUG
t.set_switches("VCC");
#endif
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#else
// Avoid compiler warnings
libmesh_ignore(comm);
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase & mesh,
Point lower_limit,
Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
ReplicatedMesh cube_mesh(mesh.comm(), 3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem, n_elem, n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned, unsigned> node_id_map;
typedef std::map<unsigned, unsigned>::iterator iterator;
for (auto & elem : cube_mesh.element_ptr_range())
for (auto s : elem->side_index_range())
if (elem->neighbor_ptr(s) == nullptr)
{
// Add the node IDs of this side to the set
std::unique_ptr<Elem> side = elem->side_ptr(s);
for (auto n : side->node_index_range())
node_id_map.insert(std::make_pair(side->node_id(n), /*dummy_value=*/0));
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node & old_node = cube_mesh.node_ref(id);
// Add geometric point to input mesh
Node * new_node = mesh.add_point (old_node);
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
for (auto & old_elem : cube_mesh.element_ptr_range())
if (old_elem->type() == TRI3)
{
Elem * new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (auto i : old_elem->node_index_range())
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node_id(i));
// Check for not found
if (it == node_id_map.end())
libmesh_error_msg("Node id " << old_elem->node_id(i) << " not found in map!");
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
#else
// Avoid compiler warnings
libmesh_ignore(mesh, lower_limit, upper_limit);
#endif // LIBMESH_HAVE_TETGEN
}
<|endoftext|> |
<commit_before>//===- tools/llvm-cov/llvm-cov.cpp - LLVM coverage tool -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// llvm-cov is a command line tools to analyze and report coverage information.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/GCOV.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
using namespace llvm;
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("source filename"), cl::init(""));
static cl::opt<bool>
DumpGCOV("dump", cl::init(false), cl::desc("dump gcov file"));
static cl::opt<std::string>
InputGCNO("gcno", cl::desc("<input gcno file>"), cl::init(""));
static cl::opt<std::string>
InputGCDA("gcda", cl::desc("<input gcda file>"), cl::init(""));
//===----------------------------------------------------------------------===//
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm cov\n");
if (InputFilename.empty()) {
// FIXME: Error out here.
}
sys::Path SrcFile(InputFilename);
sys::Path GCNOFile(SrcFile);
GCNOFile.eraseSuffix();
GCNOFile.appendSuffix(".gcno");
sys::Path GCDAFile(SrcFile);
GCDAFile.eraseSuffix();
GCDAFile.appendSuffix(".gcda");
sys::Path OutputFile(SrcFile);
OutputFile.appendSuffix(".gcov");
GCOVFile GF;
if (InputGCNO.empty())
errs() << " " << argv[0] << ": No gcov input file!\n";
OwningPtr<MemoryBuffer> GCNO_Buff;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCNO, GCNO_Buff)) {
errs() << InputGCNO << ": " << ec.message() << "\n";
return 1;
}
GCOVBuffer GCNO_GB(GCNO_Buff.take());
if (!GF.read(GCNO_GB)) {
errs() << "Invalid .gcno File!\n";
return 1;
}
if (!InputGCDA.empty()) {
OwningPtr<MemoryBuffer> GCDA_Buff;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCDA, GCDA_Buff)) {
errs() << InputGCDA << ": " << ec.message() << "\n";
return 1;
}
GCOVBuffer GCDA_GB(GCDA_Buff.take());
if (!GF.read(GCDA_GB)) {
errs() << "Invalid .gcda File!\n";
return 1;
}
}
if (DumpGCOV)
GF.dump();
FileInfo FI;
GF.collectLineCounts(FI);
return 0;
}
<commit_msg>Remove accidental commit.<commit_after>//===- tools/llvm-cov/llvm-cov.cpp - LLVM coverage tool -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// llvm-cov is a command line tools to analyze and report coverage information.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/GCOV.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
using namespace llvm;
static cl::opt<bool>
DumpGCOV("dump", cl::init(false), cl::desc("dump gcov file"));
static cl::opt<std::string>
InputGCNO("gcno", cl::desc("<input gcno file>"), cl::init(""));
static cl::opt<std::string>
InputGCDA("gcda", cl::desc("<input gcda file>"), cl::init(""));
//===----------------------------------------------------------------------===//
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm cov\n");
GCOVFile GF;
if (InputGCNO.empty())
errs() << " " << argv[0] << ": No gcov input file!\n";
OwningPtr<MemoryBuffer> GCNO_Buff;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCNO, GCNO_Buff)) {
errs() << InputGCNO << ": " << ec.message() << "\n";
return 1;
}
GCOVBuffer GCNO_GB(GCNO_Buff.take());
if (!GF.read(GCNO_GB)) {
errs() << "Invalid .gcno File!\n";
return 1;
}
if (!InputGCDA.empty()) {
OwningPtr<MemoryBuffer> GCDA_Buff;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCDA, GCDA_Buff)) {
errs() << InputGCDA << ": " << ec.message() << "\n";
return 1;
}
GCOVBuffer GCDA_GB(GCDA_Buff.take());
if (!GF.read(GCDA_GB)) {
errs() << "Invalid .gcda File!\n";
return 1;
}
}
if (DumpGCOV)
GF.dump();
FileInfo FI;
GF.collectLineCounts(FI);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef OPENGLPOINTERS_HPP
#define OPENGLPOINTERS_HPP
class QOpenGLContext;
class QOpenGLFunctions_3_0;
class QOpenGLFunctions_3_1;
class QOpenGLFunctions_3_2_Core;
class QOpenGLFunctions_3_3_Core;
class QOpenGLFunctions_4_0_Core;
class QOpenGLFunctions_4_1_Core;
class QOpenGLFunctions_4_2_Core;
class QOpenGLFunctions_4_3_Core;
namespace balls {
/**
* @brief Contains pointers to all QOpenGLFunctions that refer to OpenGL
* functionality supported by the hardware. Assumes that if version X is
* supported, then all features for versions < X are too.
* @todo Support OpenGL 4.4 and 4.5 (when I can upgrade to Qt 5.5 or 5.6)
*/
struct OpenGLPointers {
OpenGLPointers(QOpenGLContext*);
OpenGLPointers();
QOpenGLFunctions_3_0* gl30;
QOpenGLFunctions_3_1* gl31;
QOpenGLFunctions_3_2_Core* gl32;
QOpenGLFunctions_3_3_Core* gl33;
QOpenGLFunctions_4_0_Core* gl40;
QOpenGLFunctions_4_1_Core* gl41;
QOpenGLFunctions_4_2_Core* gl42;
QOpenGLFunctions_4_3_Core* gl43;
};
}
#endif // OPENGLPOINTERS_HPP
<commit_msg>Make OpenGLPointers a Q_GADGET<commit_after>#ifndef OPENGLPOINTERS_HPP
#define OPENGLPOINTERS_HPP
#include <QObject>
class QOpenGLContext;
class QOpenGLFunctions_3_0;
class QOpenGLFunctions_3_1;
class QOpenGLFunctions_3_2_Core;
class QOpenGLFunctions_3_3_Core;
class QOpenGLFunctions_4_0_Core;
class QOpenGLFunctions_4_1_Core;
class QOpenGLFunctions_4_2_Core;
class QOpenGLFunctions_4_3_Core;
namespace balls {
/**
* @brief Contains pointers to all QOpenGLFunctions that refer to OpenGL
* functionality supported by the hardware. Assumes that if version X is
* supported, then all features for versions < X are too.
* @todo Support OpenGL 4.4 and 4.5 (when I can upgrade to Qt 5.5 or 5.6)
*/
struct OpenGLPointers {
Q_GADGET
OpenGLPointers(QOpenGLContext*);
OpenGLPointers();
QOpenGLFunctions_3_0* gl30;
QOpenGLFunctions_3_1* gl31;
QOpenGLFunctions_3_2_Core* gl32;
QOpenGLFunctions_3_3_Core* gl33;
QOpenGLFunctions_4_0_Core* gl40;
QOpenGLFunctions_4_1_Core* gl41;
QOpenGLFunctions_4_2_Core* gl42;
QOpenGLFunctions_4_3_Core* gl43;
};
}
Q_DECLARE_METATYPE(balls::OpenGLPointers*)
#endif // OPENGLPOINTERS_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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 "formats.h"
#include "tcamgststrings.h"
#include <iostream>
#include <iomanip>
void list_formats (const std::vector<VideoFormatDescription>& available_formats)
{
std::cout << "Available format settings:" << std::endl;
for (const VideoFormatDescription& f : available_formats)
{
auto desc = f.get_struct();
std::cout << "Format: " << desc.description << " - Fourcc(" << desc.fourcc << ")" << std::endl;
for (const auto& s : f.get_resolutions())
{
if (s.type == TCAM_RESOLUTION_TYPE_RANGE)
{
std::cout << "\tResolutionrange: "
<< s.min_size.width << "x" << s.min_size.height << " - "
<< s.max_size.width << "x" << s.max_size.height << std::endl;
}
else
{
std::cout << "\tResolution: " << s.min_size.width << "x" << s.min_size.height << std::endl;
}
for (const auto& fps : f.get_frame_rates(s))
{
std::cout << "\t\t" << std::setw(8) << std::fixed << std::setprecision(4)<< fps << " fps" << std::endl;
}
}
std::cout << std::endl;
}
}
void list_gstreamer_1_0_formats (const std::vector<VideoFormatDescription>& available_formats)
{
std::cout << "Available gstreamer-1.0 caps:" << std::endl;
for (const auto& f : available_formats)
{
const char* tmp = tcam_fourcc_to_gst_1_0_caps_string(f.get_fourcc());
if (tmp == nullptr)
{
continue;
}
std::string format = tmp;
for (const auto& res : f.get_resolutions())
{
if (res.type == TCAM_RESOLUTION_TYPE_FIXED)
{
std::string fps_string = ", fps={";
auto rates = f.get_framerates(res.min_size);
for (unsigned int i = 0; i < rates.size(); ++i)
{
fps_string += std::to_string(rates.at(i));
if (i < rates.size()-1)
{
fps_string += ", ";
}
}
fps_string += "}";
std::string output = format
+ ", width=" + std::to_string(res.min_size.width)
+ ", height=" + std::to_string(res.min_size.height)
+ fps_string;
std::cout << output << std::endl;
}
else
{
auto resolutions = tcam::get_standard_resolutions(res.min_size, res.max_size);
for (const auto& r: resolutions)
{
std::string fps_string = ", fps={";
auto rates = f.get_framerates(res.min_size);
for (unsigned int i = 0; i < rates.size(); ++i)
{
fps_string += std::to_string(rates.at(i));
if (i < rates.size()-1)
{
fps_string += ", ";
}
}
fps_string += "}";
std::string output = format
+ ", width=" + std::to_string(r.width)
+ ", height=" + std::to_string(r.height)
+ fps_string;
std::cout << output << std::endl;
}
}
}
}
}
void print_active_format (const VideoFormat& format)
{
std::cout << "Active format:\n"
<< "Format: \t" << fourcc_to_description(format.get_fourcc())
<< "\nResolution: \t" << format.get_size().width << "x" << format.get_size().height
<< "\nFramerate: \t" << format.get_framerate() << "\n" << std::endl;
}
bool set_active_format (std::shared_ptr<CaptureDevice> dev, const std::string& new_format)
{
VideoFormat v;
bool ret = v.from_string(new_format);
if (ret)
{
return dev->set_video_format(v);
}
else
{
std::cout << "Invalid string description!" << std::endl;
}
return false;
}
<commit_msg>Fix framerate output for tcam-ctrl -c<commit_after>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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 "formats.h"
#include "tcamgststrings.h"
#include <iostream>
#include <iomanip>
void list_formats (const std::vector<VideoFormatDescription>& available_formats)
{
std::cout << "Available format settings:" << std::endl;
for (const VideoFormatDescription& f : available_formats)
{
auto desc = f.get_struct();
std::cout << "Format: " << desc.description << " - Fourcc(" << desc.fourcc << ")" << std::endl;
for (const auto& s : f.get_resolutions())
{
if (s.type == TCAM_RESOLUTION_TYPE_RANGE)
{
std::cout << "\tResolutionrange: "
<< s.min_size.width << "x" << s.min_size.height << " - "
<< s.max_size.width << "x" << s.max_size.height << std::endl;
}
else
{
std::cout << "\tResolution: " << s.min_size.width << "x" << s.min_size.height << std::endl;
}
for (const auto& fps : f.get_frame_rates(s))
{
std::cout << "\t\t" << std::setw(8) << std::fixed << std::setprecision(4)<< fps << " fps" << std::endl;
}
}
std::cout << std::endl;
}
}
void list_gstreamer_1_0_formats (const std::vector<VideoFormatDescription>& available_formats)
{
std::cout << "Available gstreamer-1.0 caps:" << std::endl;
for (const auto& f : available_formats)
{
const char* tmp = tcam_fourcc_to_gst_1_0_caps_string(f.get_fourcc());
if (tmp == nullptr)
{
continue;
}
std::string format = tmp;
for (const auto& res : f.get_resolutions())
{
if (res.type == TCAM_RESOLUTION_TYPE_FIXED)
{
std::string fps_string = ", fps={";
auto rates = f.get_framerates(res.min_size);
for (unsigned int i = 0; i < rates.size(); ++i)
{
fps_string += std::to_string(rates.at(i));
if (i < rates.size()-1)
{
fps_string += ", ";
}
}
fps_string += "}";
std::string output = format
+ ", width=" + std::to_string(res.min_size.width)
+ ", height=" + std::to_string(res.min_size.height)
+ fps_string;
std::cout << output << std::endl;
}
else
{
auto resolutions = tcam::get_standard_resolutions(res.min_size, res.max_size);
for (const auto& r: resolutions)
{
std::string fps_string = ", fps={";
auto rates = f.get_framerates(r);
for (unsigned int i = 0; i < rates.size(); ++i)
{
fps_string += std::to_string(rates.at(i));
if (i < rates.size()-1)
{
fps_string += ", ";
}
}
fps_string += "}";
std::string output = format
+ ", width=" + std::to_string(r.width)
+ ", height=" + std::to_string(r.height)
+ fps_string;
std::cout << output << std::endl;
}
}
}
}
}
void print_active_format (const VideoFormat& format)
{
std::cout << "Active format:\n"
<< "Format: \t" << fourcc_to_description(format.get_fourcc())
<< "\nResolution: \t" << format.get_size().width << "x" << format.get_size().height
<< "\nFramerate: \t" << format.get_framerate() << "\n" << std::endl;
}
bool set_active_format (std::shared_ptr<CaptureDevice> dev, const std::string& new_format)
{
VideoFormat v;
bool ret = v.from_string(new_format);
if (ret)
{
return dev->set_video_format(v);
}
else
{
std::cout << "Invalid string description!" << std::endl;
}
return false;
}
<|endoftext|> |
<commit_before>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens
* See accompanying Bayes++.htm for terms and conditions of use.
*
* $Header$
* $NoKeywords: $
*/
/*
* Matrix types for filter classes
* Provides the predefined type 'Vec' and a variety of 'Matrix' types
* Replace this header to substitute alternative matrix support
*
* Everything in namespace Bayes_filter_matrix is intended to support the matrix storage
* and algebra requirements of the library. Therefore the interfaces and implementation is
* not intended to be stable.
*/
/*
* Use the Boost uBLAS Basic Linear Algebra library
* That is boost::numeric::ublas
* Thanks to Joerg Walter and Mathias Koch for an excellent library!
*
*
* Sparse support: The macros BAYES_FILTER_(SPARSE/COMPRESSED/COORDINATE) control experimental sparse matrix support
* These simply replace the default storage types with their sparse equivilents
*/
#include <boost/version.hpp>
#if !(BOOST_VERSION >= 103000)
#error Requires Boost 1.30.0 or later
#endif
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/banded.hpp>
#if defined(BAYES_FILTER_SPARSE) || defined(BAYES_FILTER_COMPRESSED) || defined(BAYES_FILTER_COORDINATE)
#include <map>
#include <boost/numeric/ublas/vector_sparse.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#define BAYES_FILTER_GAPPY
#endif
/* Filter Matrix Namespace */
namespace Bayesian_filter_matrix
{
// Allow use of a local ublas namespace
namespace ublas = boost::numeric::ublas;
/*
* Declare the value used for ALL linear algebra operations
* Also required as the matrix/vector container value_type
*/
typedef double Float;
/*
* uBlas base types - these will be wrapper to provide the actual vector and matrix types
* Symmetric types don't appear. They are defined later by adapting these base types
*/
namespace detail {
// Dense types
typedef ublas::vector<Float> BaseDenseVector;
typedef ublas::matrix<Float, ublas::row_major> BaseDenseRowMatrix;
typedef ublas::matrix<Float, ublas::column_major> BaseDenseColMatrix;
typedef ublas::triangular_matrix<Float, ublas::upper, ublas::row_major> BaseDenseUpperTriMatrix;
typedef ublas::triangular_matrix<Float, ublas::lower, ublas::row_major> BaseDenseLowerTriMatrix;
typedef ublas::banded_matrix<Float> BaseDenseDiagMatrix;
// Sparse types
#if defined(BAYES_FILTER_SPARSE)
typedef ublas::sparse_vector<Float, std::map<size_t,Float> > BaseSparseVector;
typedef ublas::sparse_matrix<Float, ublas::row_major, std::map<size_t,Float> > BaseSparseRowMatrix;
typedef ublas::sparse_matrix<Float, ublas::column_major, std::map<size_t,Float> > BaseSparseColMatrix;
// OR Compressed types
#elif defined(BAYES_FILTER_COMPRESSED)
typedef ublas::compressed_vector<Float> BaseSparseVector;
typedef ublas::compressed_matrix<Float, ublas::row_major> BaseSparseRowMatrix;
typedef ublas::compressed_matrix<Float, ublas::column_major> BaseSparseColMatrix;
// OR Coordinate types
#elif defined(BAYES_FILTER_COORDINATE)
typedef ublas::coordinate_vector<Float> BaseSparseVector;
typedef ublas::coordinate_matrix<Float, ublas::row_major> BaseSparseRowMatrix;
typedef ublas::coordinate_matrix<Float, ublas::column_major> BaseSparseColMatrix;
#endif
// Default types Dense or Gappy
#ifndef BAYES_FILTER_GAPPY
typedef BaseDenseVector BaseVector;
typedef BaseDenseRowMatrix BaseRowMatrix;
typedef BaseDenseColMatrix BaseColMatrix;
typedef BaseDenseUpperTriMatrix BaseUpperTriMatrix;
typedef BaseDenseLowerTriMatrix BaseLowerTriMatrix;
typedef BaseDenseDiagMatrix BaseDiagMatrix;
#else
typedef BaseSparseVector BaseVector;
typedef BaseSparseRowMatrix BaseRowMatrix;
typedef BaseSparseColMatrix BaseColMatrix;
typedef BaseDenseUpperTriMatrix BaseUpperTriMatrix; // No sparse triangular or banded
typedef BaseDenseLowerTriMatrix BaseLowerTriMatrix;
typedef BaseDenseDiagMatrix BaseDiagMatrix;
#endif
}
}//namespace
/*
* Common type independant uBlas interface
*/
#include "uBLASmatrix.hpp"
<commit_msg>comments about proxies<commit_after>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens
* See accompanying Bayes++.htm for terms and conditions of use.
*
* $Header$
* $NoKeywords: $
*/
/*
* Matrix types for filter classes
* Provides the predefined type 'Vec' and a variety of 'Matrix' types
* Replace this header to substitute alternative matrix support
*
* Everything in namespace Bayes_filter_matrix is intended to support the matrix storage
* and algebra requirements of the library. Therefore the interfaces and implementation is
* not intended to be stable.
*/
/*
* Use the Boost uBLAS Basic Linear Algebra library
* That is boost::numeric::ublas
* Thanks to Joerg Walter and Mathias Koch for an excellent library!
*
* Gappy matrix support: The macros BAYES_FILTER_(SPARSE/COMPRESSED/COORDINATE) control experimental gappy matrix support
* When enabled the default storage types are replaced with their sparse equivilents
*
* ISSUE: Element proxies.
* Element proxies have a colourful history!
* As of Boost 1.30.0 they do not allow assignment of elements between mixed types.
* They do not work with gcc-3.3. The order of expression temporary distruction overrights previous changes. They must be disabled.
* The sparse support in Bayes++ does not require element proxies.
* Define BOOST_UBLAS_NO_ELEMENT_PROXIES to disable them.
*/
#include <boost/version.hpp>
#if !(BOOST_VERSION >= 103000)
#error Requires Boost 1.30.0 or later
#endif
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/banded.hpp>
#if defined(BAYES_FILTER_SPARSE) || defined(BAYES_FILTER_COMPRESSED) || defined(BAYES_FILTER_COORDINATE)
#include <map>
#include <boost/numeric/ublas/vector_sparse.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#define BAYES_FILTER_GAPPY
#endif
/* Filter Matrix Namespace */
namespace Bayesian_filter_matrix
{
// Allow use of a local ublas namespace
namespace ublas = boost::numeric::ublas;
/*
* Declare the value used for ALL linear algebra operations
* Also required as the matrix/vector container value_type
*/
typedef double Float;
/*
* uBlas base types - these will be wrapper to provide the actual vector and matrix types
* Symmetric types don't appear. They are defined later by adapting these base types
*/
namespace detail {
// Dense types
typedef ublas::vector<Float> BaseDenseVector;
typedef ublas::matrix<Float, ublas::row_major> BaseDenseRowMatrix;
typedef ublas::matrix<Float, ublas::column_major> BaseDenseColMatrix;
typedef ublas::triangular_matrix<Float, ublas::upper, ublas::row_major> BaseDenseUpperTriMatrix;
typedef ublas::triangular_matrix<Float, ublas::lower, ublas::row_major> BaseDenseLowerTriMatrix;
typedef ublas::banded_matrix<Float> BaseDenseDiagMatrix;
// Sparse types
#if defined(BAYES_FILTER_SPARSE)
typedef ublas::sparse_vector<Float, std::map<size_t,Float> > BaseSparseVector;
typedef ublas::sparse_matrix<Float, ublas::row_major, std::map<size_t,Float> > BaseSparseRowMatrix;
typedef ublas::sparse_matrix<Float, ublas::column_major, std::map<size_t,Float> > BaseSparseColMatrix;
// OR Compressed types
#elif defined(BAYES_FILTER_COMPRESSED)
typedef ublas::compressed_vector<Float> BaseSparseVector;
typedef ublas::compressed_matrix<Float, ublas::row_major> BaseSparseRowMatrix;
typedef ublas::compressed_matrix<Float, ublas::column_major> BaseSparseColMatrix;
// OR Coordinate types
#elif defined(BAYES_FILTER_COORDINATE)
typedef ublas::coordinate_vector<Float> BaseSparseVector;
typedef ublas::coordinate_matrix<Float, ublas::row_major> BaseSparseRowMatrix;
typedef ublas::coordinate_matrix<Float, ublas::column_major> BaseSparseColMatrix;
#endif
// Default types Dense or Gappy
#ifndef BAYES_FILTER_GAPPY
typedef BaseDenseVector BaseVector;
typedef BaseDenseRowMatrix BaseRowMatrix;
typedef BaseDenseColMatrix BaseColMatrix;
typedef BaseDenseUpperTriMatrix BaseUpperTriMatrix;
typedef BaseDenseLowerTriMatrix BaseLowerTriMatrix;
typedef BaseDenseDiagMatrix BaseDiagMatrix;
#else
typedef BaseSparseVector BaseVector;
typedef BaseSparseRowMatrix BaseRowMatrix;
typedef BaseSparseColMatrix BaseColMatrix;
typedef BaseDenseUpperTriMatrix BaseUpperTriMatrix; // No sparse triangular or banded
typedef BaseDenseLowerTriMatrix BaseLowerTriMatrix;
typedef BaseDenseDiagMatrix BaseDiagMatrix;
#endif
}
}//namespace
/*
* Common type independant uBlas interface
*/
#include "uBLASmatrix.hpp"
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it **
under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/gui/qt/QMenuFilesRecentlyOpened.h>
#include <sofa/helper/system/FileRepository.h>
#include <fstream>
#include <algorithm>
namespace sofa
{
namespace gui
{
namespace qt
{
void QMenuFilesRecentlyOpened::updateWidget()
{
//Clear the current widget
while (menuRecentlyOpenedFiles->count()) menuRecentlyOpenedFiles->removeItemAt(0);
//Add the content of files
for (unsigned int i=0; i<files.size(); ++i) menuRecentlyOpenedFiles->insertItem(QString(files[i].c_str()),i);
}
QMenu *QMenuFilesRecentlyOpened::createWidget(QWidget *parent, const std::string &name)
{
menuRecentlyOpenedFiles = new QMenu(QString(name.c_str()), parent);
#ifdef SOFA_QT4
menuRecentlyOpenedFiles->setTearOffEnabled(true);
#endif
updateWidget();
return menuRecentlyOpenedFiles;
}
void QMenuFilesRecentlyOpened::openFile(const std::string &file)
{
FilesRecentlyOpenedManager::openFile(file);
updateWidget();
writeFiles();
}
}
}
}
<commit_msg>r7446/sofa-dev : FIX: compilation qt3<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it **
under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/gui/qt/QMenuFilesRecentlyOpened.h>
#include <sofa/helper/system/FileRepository.h>
#include <fstream>
#include <algorithm>
namespace sofa
{
namespace gui
{
namespace qt
{
void QMenuFilesRecentlyOpened::updateWidget()
{
//Clear the current widget
while (menuRecentlyOpenedFiles->count()) menuRecentlyOpenedFiles->removeItemAt(0);
//Add the content of files
for (unsigned int i=0; i<files.size(); ++i) menuRecentlyOpenedFiles->insertItem(QString(files[i].c_str()),i);
}
QMenu *QMenuFilesRecentlyOpened::createWidget(QWidget *parent, const std::string &name)
{
#ifdef SOFA_QT4
menuRecentlyOpenedFiles = new QMenu(QString(name.c_str()), parent);
menuRecentlyOpenedFiles->setTearOffEnabled(true);
#else
menuRecentlyOpenedFiles = new QMenu(parent,QString(name.c_str()));
#endif
updateWidget();
return menuRecentlyOpenedFiles;
}
void QMenuFilesRecentlyOpened::openFile(const std::string &file)
{
FilesRecentlyOpenedManager::openFile(file);
updateWidget();
writeFiles();
}
}
}
}
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
#include <iostream>
#include "librealsense2/rs.hpp"
#include "tclap/CmdLine.h"
#include "converters/converter-csv.hpp"
#include "converters/converter-png.hpp"
#include "converters/converter-raw.hpp"
#include "converters/converter-ply.hpp"
#include "converters/converter-bin.hpp"
#include <mutex>
using namespace std;
using namespace TCLAP;
int main(int argc, char** argv) try
{
rs2::log_to_file(RS2_LOG_SEVERITY_WARN);
// Parse command line arguments
CmdLine cmd("librealsense rs-convert tool", ' ');
ValueArg<string> inputFilename("i", "input", "ROS-bag filename", true, "", "ros-bag-file");
ValueArg<string> outputFilenamePng("p", "output-png", "output PNG file(s) path", false, "", "png-path");
ValueArg<string> outputFilenameCsv("v", "output-csv", "output CSV (depth matrix) file(s) path", false, "", "csv-path");
ValueArg<string> outputFilenameRaw("r", "output-raw", "output RAW file(s) path", false, "", "raw-path");
ValueArg<string> outputFilenamePly("l", "output-ply", "output PLY file(s) path", false, "", "ply-path");
ValueArg<string> outputFilenameBin("b", "output-bin", "output BIN (depth matrix) file(s) path", false, "", "bin-path");
SwitchArg switchDepth("d", "depth", "convert depth frames (default - all supported)", false);
SwitchArg switchColor("c", "color", "convert color frames (default - all supported)", false);
cmd.add(inputFilename);
cmd.add(outputFilenamePng);
cmd.add(outputFilenameCsv);
cmd.add(outputFilenameRaw);
cmd.add(outputFilenamePly);
cmd.add(outputFilenameBin);
cmd.add(switchDepth);
cmd.add(switchColor);
cmd.parse(argc, argv);
vector<shared_ptr<rs2::tools::converter::converter_base>> converters;
shared_ptr<rs2::tools::converter::converter_ply> plyconverter;
rs2_stream streamType = switchDepth.isSet() ? rs2_stream::RS2_STREAM_DEPTH
: switchColor.isSet() ? rs2_stream::RS2_STREAM_COLOR
: rs2_stream::RS2_STREAM_ANY;
if (outputFilenameCsv.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_csv>(
outputFilenameCsv.getValue()
, streamType));
}
if (outputFilenamePng.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_png>(
outputFilenamePng.getValue()
, streamType));
}
if (outputFilenameRaw.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_raw>(
outputFilenameRaw.getValue()
, streamType));
}
if (outputFilenameBin.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_bin>(
outputFilenameBin.getValue()));
}
if (converters.empty() && !outputFilenamePly.isSet()) {
throw runtime_error("output not defined");
}
//in order to convert frames into ply we need synced depth and color frames,
//therefore we use pipeline
if (outputFilenamePly.isSet()) {
// Since we are running in blocking "non-real-time" mode,
// we don't want to prevent process termination if some of the frames
// did not find a match and hence were not serviced
auto pipe = std::shared_ptr<rs2::pipeline>(
new rs2::pipeline(), [](rs2::pipeline*) {});
plyconverter = make_shared<rs2::tools::converter::converter_ply>(
outputFilenamePly.getValue());
rs2::config cfg;
cfg.enable_device_from_file(inputFilename.getValue());
pipe->start(cfg);
auto device = pipe->get_active_profile().get_device();
rs2::playback playback = device.as<rs2::playback>();
playback.set_real_time(false);
auto duration = playback.get_duration();
int progress = 0;
auto frameNumber = 0ULL;
rs2::frameset frameset;
uint64_t posLast = playback.get_position();
while (pipe->try_wait_for_frames(&frameset, 1000))
{
int posP = static_cast<int>(posLast * 100. / duration.count());
if (posP > progress) {
progress = posP;
cout << posP << "%" << "\r" << flush;
}
frameNumber = frameset[0].get_frame_number();
plyconverter->convert(frameset);
plyconverter->wait();
const uint64_t posCurr = playback.get_position();
if (static_cast<int64_t>(posCurr - posLast) < 0) {
break;
}
posLast = posCurr;
}
}
// for every converter other than ply,
// we get the frames from playback sensors
// and convert them one by one
if (!converters.empty()) {
rs2::context ctx;
auto playback = ctx.load_device(inputFilename.getValue());
playback.set_real_time(false);
std::vector<rs2::sensor> sensors = playback.query_sensors();
std::mutex mutex;
auto duration = playback.get_duration();
int progress = 0;
uint64_t posLast = playback.get_position();
for (auto sensor : sensors) {
if (!sensor.get_stream_profiles().size())
{
continue;
}
sensor.open(sensor.get_stream_profiles());
sensor.start([&](rs2::frame frame)
{
std::lock_guard<std::mutex> lock(mutex);
for_each(converters.begin(), converters.end(),
[&frame](shared_ptr<rs2::tools::converter::converter_base>& converter) {
converter->convert(frame);
});
for_each(converters.begin(), converters.end(),
[](shared_ptr<rs2::tools::converter::converter_base>& converter) {
converter->wait();
});
});
}
//we need to clear the output of ply progress (100%) before writing
//the progress of the other converters in the same line
cout << "\r \r";
while (true)
{
int posP = static_cast<int>(posLast * 100. / duration.count());
if (posP > progress) {
progress = posP;
cout << posP << "%" << "\r" << flush;
}
const uint64_t posCurr = playback.get_position();
if (static_cast<int64_t>(posCurr - posLast) < 0) {
break;
}
posLast = posCurr;
}
for (auto sensor : sensors) {
if (!sensor.get_stream_profiles().size())
{
continue;
}
sensor.stop();
sensor.close();
}
}
cout << endl;
//print statistics for ply converter.
if (outputFilenamePly.isSet()) {
cout << plyconverter->get_statistics() << endl;
}
for_each(converters.begin(), converters.end(),
[](shared_ptr<rs2::tools::converter::converter_base>& converter) {
cout << converter->get_statistics() << endl;
});
return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
cerr << "RealSense error calling " << e.get_failed_function()
<< "(" << e.get_failed_args() << "):\n " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const exception & e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
catch (...)
{
cerr << "some error" << endl;
return EXIT_FAILURE;
}
<commit_msg>metadata changes<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
#include <iostream>
#include "librealsense2/rs.hpp"
#include "tclap/CmdLine.h"
#include "converters/converter-csv.hpp"
#include "converters/converter-png.hpp"
#include "converters/converter-raw.hpp"
#include "converters/converter-ply.hpp"
#include "converters/converter-bin.hpp"
#include <mutex>
using namespace std;
using namespace TCLAP;
int main(int argc, char** argv) try
{
rs2::log_to_file(RS2_LOG_SEVERITY_WARN);
// Parse command line arguments
CmdLine cmd("librealsense rs-convert tool", ' ');
ValueArg<string> inputFilename("i", "input", "ROS-bag filename", true, "", "ros-bag-file");
ValueArg<string> outputFilenamePng("p", "output-png", "output PNG file(s) path", false, "", "png-path");
ValueArg<string> outputFilenameCsv("v", "output-csv", "output CSV (depth matrix) file(s) path", false, "", "csv-path");
ValueArg<string> outputFilenameRaw("r", "output-raw", "output RAW file(s) path", false, "", "raw-path");
ValueArg<string> outputFilenamePly("l", "output-ply", "output PLY file(s) path", false, "", "ply-path");
ValueArg<string> outputFilenameBin("b", "output-bin", "output BIN (depth matrix) file(s) path", false, "", "bin-path");
SwitchArg switchDepth("d", "depth", "convert depth frames (default - all supported)", false);
SwitchArg switchColor("c", "color", "convert color frames (default - all supported)", false);
cmd.add(inputFilename);
cmd.add(outputFilenamePng);
cmd.add(outputFilenameCsv);
cmd.add(outputFilenameRaw);
cmd.add(outputFilenamePly);
cmd.add(outputFilenameBin);
cmd.add(switchDepth);
cmd.add(switchColor);
cmd.parse(argc, argv);
vector<shared_ptr<rs2::tools::converter::converter_base>> converters;
shared_ptr<rs2::tools::converter::converter_ply> plyconverter;
rs2_stream streamType = switchDepth.isSet() ? rs2_stream::RS2_STREAM_DEPTH
: switchColor.isSet() ? rs2_stream::RS2_STREAM_COLOR
: rs2_stream::RS2_STREAM_ANY;
if (outputFilenameCsv.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_csv>(
outputFilenameCsv.getValue()
, streamType));
}
if (outputFilenamePng.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_png>(
outputFilenamePng.getValue()
, streamType));
}
if (outputFilenameRaw.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_raw>(
outputFilenameRaw.getValue()
, streamType));
}
if (outputFilenameBin.isSet()) {
converters.push_back(
make_shared<rs2::tools::converter::converter_bin>(
outputFilenameBin.getValue()));
}
if (converters.empty() && !outputFilenamePly.isSet()) {
throw runtime_error("output not defined");
}
//in order to convert frames into ply we need synced depth and color frames,
//therefore we use pipeline
if (outputFilenamePly.isSet()) {
// Since we are running in blocking "non-real-time" mode,
// we don't want to prevent process termination if some of the frames
// did not find a match and hence were not serviced
auto pipe = std::shared_ptr<rs2::pipeline>(
new rs2::pipeline(), [](rs2::pipeline*) {});
plyconverter = make_shared<rs2::tools::converter::converter_ply>(
outputFilenamePly.getValue());
rs2::config cfg;
cfg.enable_device_from_file(inputFilename.getValue());
pipe->start(cfg);
auto device = pipe->get_active_profile().get_device();
rs2::playback playback = device.as<rs2::playback>();
playback.set_real_time(false);
auto duration = playback.get_duration();
int progress = 0;
auto frameNumber = 0ULL;
rs2::frameset frameset;
uint64_t posLast = playback.get_position();
while (pipe->try_wait_for_frames(&frameset, 1000))
{
int posP = static_cast<int>(posLast * 100. / duration.count());
if (posP > progress) {
progress = posP;
cout << posP << "%" << "\r" << flush;
}
frameNumber = frameset[0].get_frame_number();
plyconverter->convert(frameset);
plyconverter->wait();
const uint64_t posCurr = playback.get_position();
if (static_cast<int64_t>(posCurr - posLast) < 0) {
break;
}
posLast = posCurr;
}
}
// for every converter other than ply,
// we get the frames from playback sensors
// and convert them one by one
if (!converters.empty()) {
rs2::context ctx;
auto playback = ctx.load_device(inputFilename.getValue());
playback.set_real_time(false);
std::vector<rs2::sensor> sensors = playback.query_sensors();
std::mutex mutex;
auto duration = playback.get_duration();
int progress = 0;
uint64_t posLast = playback.get_position();
for (auto sensor : sensors) {
if (!sensor.get_stream_profiles().size())
{
continue;
}
sensor.open(sensor.get_stream_profiles());
sensor.start([&](rs2::frame frame)
{
std::lock_guard<std::mutex> lock(mutex);
for_each(converters.begin(), converters.end(),
[&frame](shared_ptr<rs2::tools::converter::converter_base>& converter) {
converter->convert(frame);
});
for_each(converters.begin(), converters.end(),
[](shared_ptr<rs2::tools::converter::converter_base>& converter) {
converter->wait();
});
});
}
//we need to clear the output of ply progress ("100%") before writing
//the progress of the other converters in the same line
cout << "\r \r";
while (true)
{
int posP = static_cast<int>(posLast * 100. / duration.count());
if (posP > progress) {
progress = posP;
cout << posP << "%" << "\r" << flush;
}
const uint64_t posCurr = playback.get_position();
if (static_cast<int64_t>(posCurr - posLast) < 0) {
break;
}
posLast = posCurr;
}
for (auto sensor : sensors) {
if (!sensor.get_stream_profiles().size())
{
continue;
}
sensor.stop();
sensor.close();
}
}
cout << endl;
//print statistics for ply converter.
if (outputFilenamePly.isSet()) {
cout << plyconverter->get_statistics() << endl;
}
for_each(converters.begin(), converters.end(),
[](shared_ptr<rs2::tools::converter::converter_base>& converter) {
cout << converter->get_statistics() << endl;
});
return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
cerr << "RealSense error calling " << e.get_failed_function()
<< "(" << e.get_failed_args() << "):\n " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const exception & e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
catch (...)
{
cerr << "some error" << endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>//===- CIndexHigh.cpp - Higher level API functions ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IndexingContext.h"
#include "clang/AST/DeclVisitor.h"
using namespace clang;
using namespace cxindex;
namespace {
class IndexingDeclVisitor : public DeclVisitor<IndexingDeclVisitor, bool> {
IndexingContext &IndexCtx;
public:
explicit IndexingDeclVisitor(IndexingContext &indexCtx)
: IndexCtx(indexCtx) { }
void handleDeclarator(DeclaratorDecl *D, const NamedDecl *Parent = 0) {
if (!Parent) Parent = D;
if (!IndexCtx.shouldIndexFunctionLocalSymbols()) {
IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), Parent);
IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent);
} else {
if (ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(D)) {
IndexCtx.handleVar(Parm);
} else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
for (FunctionDecl::param_iterator
PI = FD->param_begin(), PE = FD->param_end(); PI != PE; ++PI) {
IndexCtx.handleVar(*PI);
}
}
}
}
void handleObjCMethod(ObjCMethodDecl *D) {
IndexCtx.handleObjCMethod(D);
if (D->isImplicit())
return;
IndexCtx.indexTypeSourceInfo(D->getResultTypeSourceInfo(), D);
for (ObjCMethodDecl::param_iterator
I = D->param_begin(), E = D->param_end(); I != E; ++I)
handleDeclarator(*I, D);
if (D->isThisDeclarationADefinition()) {
const Stmt *Body = D->getBody();
if (Body) {
IndexCtx.indexBody(Body, D, D);
}
}
}
bool VisitFunctionDecl(FunctionDecl *D) {
IndexCtx.handleFunction(D);
handleDeclarator(D);
if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
// Constructor initializers.
for (CXXConstructorDecl::init_iterator I = Ctor->init_begin(),
E = Ctor->init_end();
I != E; ++I) {
CXXCtorInitializer *Init = *I;
if (Init->isWritten()) {
IndexCtx.indexTypeSourceInfo(Init->getTypeSourceInfo(), D);
if (const FieldDecl *Member = Init->getAnyMember())
IndexCtx.handleReference(Member, Init->getMemberLocation(), D, D);
IndexCtx.indexBody(Init->getInit(), D, D);
}
}
}
if (D->isThisDeclarationADefinition()) {
const Stmt *Body = D->getBody();
if (Body) {
IndexCtx.indexBody(Body, D, D);
}
}
return true;
}
bool VisitVarDecl(VarDecl *D) {
IndexCtx.handleVar(D);
handleDeclarator(D);
IndexCtx.indexBody(D->getInit(), D);
return true;
}
bool VisitFieldDecl(FieldDecl *D) {
IndexCtx.handleField(D);
handleDeclarator(D);
if (D->isBitField())
IndexCtx.indexBody(D->getBitWidth(), D);
else if (D->hasInClassInitializer())
IndexCtx.indexBody(D->getInClassInitializer(), D);
return true;
}
bool VisitEnumConstantDecl(EnumConstantDecl *D) {
IndexCtx.handleEnumerator(D);
IndexCtx.indexBody(D->getInitExpr(), D);
return true;
}
bool VisitTypedefNameDecl(TypedefNameDecl *D) {
IndexCtx.handleTypedefName(D);
IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), D);
return true;
}
bool VisitTagDecl(TagDecl *D) {
// Non-free standing tags are handled in indexTypeSourceInfo.
if (D->isFreeStanding())
IndexCtx.indexTagDecl(D);
return true;
}
bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
IndexCtx.handleObjCInterface(D);
if (D->isThisDeclarationADefinition()) {
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
}
return true;
}
bool VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
IndexCtx.handleObjCProtocol(D);
if (D->isThisDeclarationADefinition()) {
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
}
return true;
}
bool VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
const ObjCInterfaceDecl *Class = D->getClassInterface();
if (!Class)
return true;
if (Class->isImplicitInterfaceDecl())
IndexCtx.handleObjCInterface(Class);
IndexCtx.handleObjCImplementation(D);
IndexCtx.indexTUDeclsInObjCContainer();
// Index the ivars first to make sure the synthesized ivars are indexed
// before indexing the methods that can reference them.
for (ObjCImplementationDecl::ivar_iterator
IvarI = D->ivar_begin(),
IvarE = D->ivar_end(); IvarI != IvarE; ++IvarI) {
IndexCtx.indexDecl(*IvarI);
}
for (DeclContext::decl_iterator
I = D->decls_begin(), E = D->decls_end(); I != E; ++I) {
if (!isa<ObjCIvarDecl>(*I))
IndexCtx.indexDecl(*I);
}
return true;
}
bool VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
IndexCtx.handleObjCCategory(D);
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
return true;
}
bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
const ObjCCategoryDecl *Cat = D->getCategoryDecl();
if (!Cat)
return true;
IndexCtx.handleObjCCategoryImpl(D);
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
return true;
}
bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
// Methods associated with a property, even user-declared ones, are
// handled when we handle the property.
if (D->isPropertyAccessor())
return true;
handleObjCMethod(D);
return true;
}
bool VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
if (ObjCMethodDecl *MD = D->getGetterMethodDecl())
if (MD->getLexicalDeclContext() == D->getLexicalDeclContext())
handleObjCMethod(MD);
if (ObjCMethodDecl *MD = D->getSetterMethodDecl())
if (MD->getLexicalDeclContext() == D->getLexicalDeclContext())
handleObjCMethod(MD);
IndexCtx.handleObjCProperty(D);
IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), D);
return true;
}
bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
ObjCPropertyDecl *PD = D->getPropertyDecl();
IndexCtx.handleSynthesizedObjCProperty(D);
if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
return true;
assert(D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize);
if (ObjCIvarDecl *IvarD = D->getPropertyIvarDecl()) {
if (!IvarD->getSynthesize())
IndexCtx.handleReference(IvarD, D->getPropertyIvarDeclLoc(), 0,
D->getDeclContext());
}
if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) {
if (MD->isPropertyAccessor())
IndexCtx.handleSynthesizedObjCMethod(MD, D->getLocation(),
D->getLexicalDeclContext());
}
if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) {
if (MD->isPropertyAccessor())
IndexCtx.handleSynthesizedObjCMethod(MD, D->getLocation(),
D->getLexicalDeclContext());
}
return true;
}
bool VisitNamespaceDecl(NamespaceDecl *D) {
IndexCtx.handleNamespace(D);
IndexCtx.indexDeclContext(D);
return true;
}
bool VisitUsingDecl(UsingDecl *D) {
// FIXME: Parent for the following is CXIdxEntity_Unexposed with no USR,
// we should do better.
IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D);
for (UsingDecl::shadow_iterator
I = D->shadow_begin(), E = D->shadow_end(); I != E; ++I) {
IndexCtx.handleReference((*I)->getUnderlyingDecl(), D->getLocation(),
D, D->getLexicalDeclContext());
}
return true;
}
bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
// FIXME: Parent for the following is CXIdxEntity_Unexposed with no USR,
// we should do better.
IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D);
IndexCtx.handleReference(D->getNominatedNamespaceAsWritten(),
D->getLocation(), D, D->getLexicalDeclContext());
return true;
}
bool VisitClassTemplateDecl(ClassTemplateDecl *D) {
IndexCtx.handleClassTemplate(D);
if (D->isThisDeclarationADefinition())
IndexCtx.indexDeclContext(D->getTemplatedDecl());
return true;
}
bool VisitClassTemplateSpecializationDecl(
ClassTemplateSpecializationDecl *D) {
// FIXME: Notify subsequent callbacks if info comes from implicit
// instantiation.
if (D->isThisDeclarationADefinition() &&
(IndexCtx.shouldIndexImplicitTemplateInsts() ||
!IndexCtx.isTemplateImplicitInstantiation(D)))
IndexCtx.indexTagDecl(D);
return true;
}
bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
IndexCtx.handleFunctionTemplate(D);
FunctionDecl *FD = D->getTemplatedDecl();
handleDeclarator(FD, D);
if (FD->isThisDeclarationADefinition()) {
const Stmt *Body = FD->getBody();
if (Body) {
IndexCtx.indexBody(Body, D, FD);
}
}
return true;
}
bool VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
IndexCtx.handleTypeAliasTemplate(D);
IndexCtx.indexTypeSourceInfo(D->getTemplatedDecl()->getTypeSourceInfo(), D);
return true;
}
bool VisitImportDecl(ImportDecl *D) {
IndexCtx.importedModule(D);
return true;
}
};
} // anonymous namespace
void IndexingContext::indexDecl(const Decl *D) {
if (D->isImplicit() && shouldIgnoreIfImplicit(D))
return;
bool Handled = IndexingDeclVisitor(*this).Visit(const_cast<Decl*>(D));
if (!Handled && isa<DeclContext>(D))
indexDeclContext(cast<DeclContext>(D));
}
void IndexingContext::indexDeclContext(const DeclContext *DC) {
for (DeclContext::decl_iterator
I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
indexDecl(*I);
}
}
void IndexingContext::indexTopLevelDecl(const Decl *D) {
if (isNotFromSourceFile(D->getLocation()))
return;
if (isa<ObjCMethodDecl>(D))
return; // Wait for the objc container.
indexDecl(D);
}
void IndexingContext::indexDeclGroupRef(DeclGroupRef DG) {
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
indexTopLevelDecl(*I);
}
void IndexingContext::indexTUDeclsInObjCContainer() {
while (!TUDeclsInObjCContainer.empty()) {
DeclGroupRef DG = TUDeclsInObjCContainer.front();
TUDeclsInObjCContainer.pop_front();
indexDeclGroupRef(DG);
}
}
<commit_msg>libclang: migrate IndexingDeclVisitor to ConstDeclVisitor<commit_after>//===- CIndexHigh.cpp - Higher level API functions ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IndexingContext.h"
#include "clang/AST/DeclVisitor.h"
using namespace clang;
using namespace cxindex;
namespace {
class IndexingDeclVisitor : public ConstDeclVisitor<IndexingDeclVisitor, bool> {
IndexingContext &IndexCtx;
public:
explicit IndexingDeclVisitor(IndexingContext &indexCtx)
: IndexCtx(indexCtx) { }
void handleDeclarator(const DeclaratorDecl *D, const NamedDecl *Parent = 0) {
if (!Parent) Parent = D;
if (!IndexCtx.shouldIndexFunctionLocalSymbols()) {
IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), Parent);
IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent);
} else {
if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(D)) {
IndexCtx.handleVar(Parm);
} else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
for (FunctionDecl::param_const_iterator PI = FD->param_begin(),
PE = FD->param_end();
PI != PE; ++PI) {
IndexCtx.handleVar(*PI);
}
}
}
}
void handleObjCMethod(const ObjCMethodDecl *D) {
IndexCtx.handleObjCMethod(D);
if (D->isImplicit())
return;
IndexCtx.indexTypeSourceInfo(D->getResultTypeSourceInfo(), D);
for (ObjCMethodDecl::param_const_iterator I = D->param_begin(),
E = D->param_end();
I != E; ++I)
handleDeclarator(*I, D);
if (D->isThisDeclarationADefinition()) {
const Stmt *Body = D->getBody();
if (Body) {
IndexCtx.indexBody(Body, D, D);
}
}
}
bool VisitFunctionDecl(const FunctionDecl *D) {
IndexCtx.handleFunction(D);
handleDeclarator(D);
if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
// Constructor initializers.
for (CXXConstructorDecl::init_const_iterator I = Ctor->init_begin(),
E = Ctor->init_end();
I != E; ++I) {
CXXCtorInitializer *Init = *I;
if (Init->isWritten()) {
IndexCtx.indexTypeSourceInfo(Init->getTypeSourceInfo(), D);
if (const FieldDecl *Member = Init->getAnyMember())
IndexCtx.handleReference(Member, Init->getMemberLocation(), D, D);
IndexCtx.indexBody(Init->getInit(), D, D);
}
}
}
if (D->isThisDeclarationADefinition()) {
const Stmt *Body = D->getBody();
if (Body) {
IndexCtx.indexBody(Body, D, D);
}
}
return true;
}
bool VisitVarDecl(const VarDecl *D) {
IndexCtx.handleVar(D);
handleDeclarator(D);
IndexCtx.indexBody(D->getInit(), D);
return true;
}
bool VisitFieldDecl(const FieldDecl *D) {
IndexCtx.handleField(D);
handleDeclarator(D);
if (D->isBitField())
IndexCtx.indexBody(D->getBitWidth(), D);
else if (D->hasInClassInitializer())
IndexCtx.indexBody(D->getInClassInitializer(), D);
return true;
}
bool VisitEnumConstantDecl(const EnumConstantDecl *D) {
IndexCtx.handleEnumerator(D);
IndexCtx.indexBody(D->getInitExpr(), D);
return true;
}
bool VisitTypedefNameDecl(const TypedefNameDecl *D) {
IndexCtx.handleTypedefName(D);
IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), D);
return true;
}
bool VisitTagDecl(const TagDecl *D) {
// Non-free standing tags are handled in indexTypeSourceInfo.
if (D->isFreeStanding())
IndexCtx.indexTagDecl(D);
return true;
}
bool VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
IndexCtx.handleObjCInterface(D);
if (D->isThisDeclarationADefinition()) {
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
}
return true;
}
bool VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
IndexCtx.handleObjCProtocol(D);
if (D->isThisDeclarationADefinition()) {
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
}
return true;
}
bool VisitObjCImplementationDecl(const ObjCImplementationDecl *D) {
const ObjCInterfaceDecl *Class = D->getClassInterface();
if (!Class)
return true;
if (Class->isImplicitInterfaceDecl())
IndexCtx.handleObjCInterface(Class);
IndexCtx.handleObjCImplementation(D);
IndexCtx.indexTUDeclsInObjCContainer();
// Index the ivars first to make sure the synthesized ivars are indexed
// before indexing the methods that can reference them.
for (ObjCImplementationDecl::ivar_iterator
IvarI = D->ivar_begin(),
IvarE = D->ivar_end(); IvarI != IvarE; ++IvarI) {
IndexCtx.indexDecl(*IvarI);
}
for (DeclContext::decl_iterator
I = D->decls_begin(), E = D->decls_end(); I != E; ++I) {
if (!isa<ObjCIvarDecl>(*I))
IndexCtx.indexDecl(*I);
}
return true;
}
bool VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
IndexCtx.handleObjCCategory(D);
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
return true;
}
bool VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
const ObjCCategoryDecl *Cat = D->getCategoryDecl();
if (!Cat)
return true;
IndexCtx.handleObjCCategoryImpl(D);
IndexCtx.indexTUDeclsInObjCContainer();
IndexCtx.indexDeclContext(D);
return true;
}
bool VisitObjCMethodDecl(const ObjCMethodDecl *D) {
// Methods associated with a property, even user-declared ones, are
// handled when we handle the property.
if (D->isPropertyAccessor())
return true;
handleObjCMethod(D);
return true;
}
bool VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
if (ObjCMethodDecl *MD = D->getGetterMethodDecl())
if (MD->getLexicalDeclContext() == D->getLexicalDeclContext())
handleObjCMethod(MD);
if (ObjCMethodDecl *MD = D->getSetterMethodDecl())
if (MD->getLexicalDeclContext() == D->getLexicalDeclContext())
handleObjCMethod(MD);
IndexCtx.handleObjCProperty(D);
IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), D);
return true;
}
bool VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
ObjCPropertyDecl *PD = D->getPropertyDecl();
IndexCtx.handleSynthesizedObjCProperty(D);
if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
return true;
assert(D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize);
if (ObjCIvarDecl *IvarD = D->getPropertyIvarDecl()) {
if (!IvarD->getSynthesize())
IndexCtx.handleReference(IvarD, D->getPropertyIvarDeclLoc(), 0,
D->getDeclContext());
}
if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) {
if (MD->isPropertyAccessor())
IndexCtx.handleSynthesizedObjCMethod(MD, D->getLocation(),
D->getLexicalDeclContext());
}
if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) {
if (MD->isPropertyAccessor())
IndexCtx.handleSynthesizedObjCMethod(MD, D->getLocation(),
D->getLexicalDeclContext());
}
return true;
}
bool VisitNamespaceDecl(const NamespaceDecl *D) {
IndexCtx.handleNamespace(D);
IndexCtx.indexDeclContext(D);
return true;
}
bool VisitUsingDecl(const UsingDecl *D) {
// FIXME: Parent for the following is CXIdxEntity_Unexposed with no USR,
// we should do better.
IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D);
for (UsingDecl::shadow_iterator
I = D->shadow_begin(), E = D->shadow_end(); I != E; ++I) {
IndexCtx.handleReference((*I)->getUnderlyingDecl(), D->getLocation(),
D, D->getLexicalDeclContext());
}
return true;
}
bool VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
// FIXME: Parent for the following is CXIdxEntity_Unexposed with no USR,
// we should do better.
IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D);
IndexCtx.handleReference(D->getNominatedNamespaceAsWritten(),
D->getLocation(), D, D->getLexicalDeclContext());
return true;
}
bool VisitClassTemplateDecl(const ClassTemplateDecl *D) {
IndexCtx.handleClassTemplate(D);
if (D->isThisDeclarationADefinition())
IndexCtx.indexDeclContext(D->getTemplatedDecl());
return true;
}
bool VisitClassTemplateSpecializationDecl(const
ClassTemplateSpecializationDecl *D) {
// FIXME: Notify subsequent callbacks if info comes from implicit
// instantiation.
if (D->isThisDeclarationADefinition() &&
(IndexCtx.shouldIndexImplicitTemplateInsts() ||
!IndexCtx.isTemplateImplicitInstantiation(D)))
IndexCtx.indexTagDecl(D);
return true;
}
bool VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
IndexCtx.handleFunctionTemplate(D);
FunctionDecl *FD = D->getTemplatedDecl();
handleDeclarator(FD, D);
if (FD->isThisDeclarationADefinition()) {
const Stmt *Body = FD->getBody();
if (Body) {
IndexCtx.indexBody(Body, D, FD);
}
}
return true;
}
bool VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) {
IndexCtx.handleTypeAliasTemplate(D);
IndexCtx.indexTypeSourceInfo(D->getTemplatedDecl()->getTypeSourceInfo(), D);
return true;
}
bool VisitImportDecl(const ImportDecl *D) {
IndexCtx.importedModule(D);
return true;
}
};
} // anonymous namespace
void IndexingContext::indexDecl(const Decl *D) {
if (D->isImplicit() && shouldIgnoreIfImplicit(D))
return;
bool Handled = IndexingDeclVisitor(*this).Visit(D);
if (!Handled && isa<DeclContext>(D))
indexDeclContext(cast<DeclContext>(D));
}
void IndexingContext::indexDeclContext(const DeclContext *DC) {
for (DeclContext::decl_iterator
I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
indexDecl(*I);
}
}
void IndexingContext::indexTopLevelDecl(const Decl *D) {
if (isNotFromSourceFile(D->getLocation()))
return;
if (isa<ObjCMethodDecl>(D))
return; // Wait for the objc container.
indexDecl(D);
}
void IndexingContext::indexDeclGroupRef(DeclGroupRef DG) {
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
indexTopLevelDecl(*I);
}
void IndexingContext::indexTUDeclsInObjCContainer() {
while (!TUDeclsInObjCContainer.empty()) {
DeclGroupRef DG = TUDeclsInObjCContainer.front();
TUDeclsInObjCContainer.pop_front();
indexDeclGroupRef(DG);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012-2015 Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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.
*/
#ifndef FILE_DESCRIPTOR_HXX
#define FILE_DESCRIPTOR_HXX
#include <inline/compiler.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#ifdef __linux__
#define HAVE_POSIX
#define HAVE_EVENTFD
#define HAVE_SIGNALFD
#define HAVE_INOTIFY
#include <signal.h>
#endif
/**
* An OO wrapper for a UNIX file descriptor.
*
* This class is unmanaged and trivial; for a managed version, see
* #UniqueFileDescriptor.
*/
class FileDescriptor {
protected:
int fd;
public:
FileDescriptor() = default;
explicit constexpr FileDescriptor(int _fd):fd(_fd) {}
constexpr bool operator==(FileDescriptor other) const {
return fd == other.fd;
}
constexpr bool IsDefined() const {
return fd >= 0;
}
/**
* Returns the file descriptor. This may only be called if
* IsDefined() returns true.
*/
constexpr int Get() const {
return fd;
}
void Set(int _fd) {
fd = _fd;
}
int Steal() {
assert(IsDefined());
int _fd = fd;
fd = -1;
return _fd;
}
void SetUndefined() {
fd = -1;
}
static constexpr FileDescriptor Undefined() {
return FileDescriptor(-1);
}
bool Open(const char *pathname, int flags, mode_t mode=0666);
bool OpenReadOnly(const char *pathname);
#ifdef HAVE_POSIX
bool OpenNonBlocking(const char *pathname);
static bool CreatePipe(FileDescriptor &r, FileDescriptor &w);
/**
* Enable non-blocking mode on this file descriptor.
*/
void SetNonBlocking();
/**
* Enable blocking mode on this file descriptor.
*/
void SetBlocking();
/**
* Duplicate the file descriptor onto the given file descriptor.
*/
bool Duplicate(int new_fd) const {
return ::dup2(Get(), new_fd) == 0;
}
#endif
#ifdef HAVE_EVENTFD
bool CreateEventFD(unsigned initval=0);
#endif
#ifdef HAVE_SIGNALFD
bool CreateSignalFD(const sigset_t *mask);
#endif
#ifdef HAVE_INOTIFY
bool CreateInotify();
#endif
/**
* Close the file descriptor. It is legal to call it on an
* "undefined" object. After this call, IsDefined() is guaranteed
* to return false, and this object may be reused.
*/
bool Close() {
return ::close(Steal()) == 0;
}
/**
* Rewind the pointer to the beginning of the file.
*/
bool Rewind();
off_t Seek(off_t offset) {
return lseek(Get(), offset, SEEK_SET);
}
off_t Skip(off_t offset) {
return lseek(Get(), offset, SEEK_CUR);
}
gcc_pure
off_t Tell() const {
return lseek(Get(), 0, SEEK_CUR);
}
/**
* Returns the size of the file in bytes, or -1 on error.
*/
gcc_pure
off_t GetSize() const;
ssize_t Read(void *buffer, size_t length) {
return ::read(fd, buffer, length);
}
ssize_t Write(const void *buffer, size_t length) {
return ::write(fd, buffer, length);
}
#ifdef HAVE_POSIX
int Poll(short events, int timeout) const;
int WaitReadable(int timeout) const;
int WaitWritable(int timeout) const;
#endif
};
#endif
<commit_msg>system/FileDescriptor: Close() should not be called on undefined object<commit_after>/*
* Copyright (C) 2012-2015 Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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.
*/
#ifndef FILE_DESCRIPTOR_HXX
#define FILE_DESCRIPTOR_HXX
#include <inline/compiler.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#ifdef __linux__
#define HAVE_POSIX
#define HAVE_EVENTFD
#define HAVE_SIGNALFD
#define HAVE_INOTIFY
#include <signal.h>
#endif
/**
* An OO wrapper for a UNIX file descriptor.
*
* This class is unmanaged and trivial; for a managed version, see
* #UniqueFileDescriptor.
*/
class FileDescriptor {
protected:
int fd;
public:
FileDescriptor() = default;
explicit constexpr FileDescriptor(int _fd):fd(_fd) {}
constexpr bool operator==(FileDescriptor other) const {
return fd == other.fd;
}
constexpr bool IsDefined() const {
return fd >= 0;
}
/**
* Returns the file descriptor. This may only be called if
* IsDefined() returns true.
*/
constexpr int Get() const {
return fd;
}
void Set(int _fd) {
fd = _fd;
}
int Steal() {
assert(IsDefined());
int _fd = fd;
fd = -1;
return _fd;
}
void SetUndefined() {
fd = -1;
}
static constexpr FileDescriptor Undefined() {
return FileDescriptor(-1);
}
bool Open(const char *pathname, int flags, mode_t mode=0666);
bool OpenReadOnly(const char *pathname);
#ifdef HAVE_POSIX
bool OpenNonBlocking(const char *pathname);
static bool CreatePipe(FileDescriptor &r, FileDescriptor &w);
/**
* Enable non-blocking mode on this file descriptor.
*/
void SetNonBlocking();
/**
* Enable blocking mode on this file descriptor.
*/
void SetBlocking();
/**
* Duplicate the file descriptor onto the given file descriptor.
*/
bool Duplicate(int new_fd) const {
return ::dup2(Get(), new_fd) == 0;
}
#endif
#ifdef HAVE_EVENTFD
bool CreateEventFD(unsigned initval=0);
#endif
#ifdef HAVE_SIGNALFD
bool CreateSignalFD(const sigset_t *mask);
#endif
#ifdef HAVE_INOTIFY
bool CreateInotify();
#endif
/**
* Close the file descriptor. It should not be called on an
* "undefined" object. After this call, IsDefined() is guaranteed
* to return false, and this object may be reused.
*/
bool Close() {
return ::close(Steal()) == 0;
}
/**
* Rewind the pointer to the beginning of the file.
*/
bool Rewind();
off_t Seek(off_t offset) {
return lseek(Get(), offset, SEEK_SET);
}
off_t Skip(off_t offset) {
return lseek(Get(), offset, SEEK_CUR);
}
gcc_pure
off_t Tell() const {
return lseek(Get(), 0, SEEK_CUR);
}
/**
* Returns the size of the file in bytes, or -1 on error.
*/
gcc_pure
off_t GetSize() const;
ssize_t Read(void *buffer, size_t length) {
return ::read(fd, buffer, length);
}
ssize_t Write(const void *buffer, size_t length) {
return ::write(fd, buffer, length);
}
#ifdef HAVE_POSIX
int Poll(short events, int timeout) const;
int WaitReadable(int timeout) const;
int WaitWritable(int timeout) const;
#endif
};
#endif
<|endoftext|> |
<commit_before>/*
@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CLBL_TRTS_HAS_VARARGS_HPP
#define BOOST_CLBL_TRTS_HAS_VARARGS_HPP
#include <boost/callable_traits/detail/core.hpp>
namespace boost { namespace callable_traits {
//[ has_varargs_hpp
/*`[section:ref_has_varargs has_varargs]
[heading Header]
``#include <boost/callable_traits/has_varargs.hpp>``
[heading Definition]
*/
// inherits from either std::true_type or std::false_type
template<typename T>
struct has_varargs;
//<-
template<typename T>
struct has_varargs : detail::traits<
detail::shallow_decay<T>>::has_varargs {
using type = typename detail::traits<
detail::shallow_decay<T>>::has_varargs;
};
#ifdef BOOST_CLBL_TRTS_DISABLE_VARIABLE_TEMPLATES
template<typename T>
struct has_varargs_v {
static_assert(std::is_same<T, detail::dummy>::value,
"Variable templates not supported on this compiler.");
};
#else
//->
// only available when variable templates are supported
template<typename T>
//<-
BOOST_CLBL_TRAITS_INLINE_VAR
//->
constexpr bool has_varargs_v = //see below
//<-
detail::traits<detail::shallow_decay<T>>::has_varargs::value;
#endif
}} // namespace boost::callable_traits
//->
/*`
[heading Constraints]
* none
[heading Behavior]
* `std::false_type` is inherited by `has_varargs<T>` and is aliased by `typename has_varargs<T>::type`, except when one of the following criteria is met, in which case `std::true_type` would be similarly inherited and aliased:
* `T` is a function, function pointer, or function reference where the function's parameter list includes C-style variadics.
* `T` is a pointer to a member function with C-style variadics in the parameter list.
* `T` is a function object with a non-overloaded `operator()`, which has C-style variadics in the parameter list of its `operator()`.
* On compilers that support variable templates, `has_varargs_v<T>` is equivalent to `has_varargs<T>::value`.
[heading Input/Output Examples]
[table
[[`T`] [`has_varargs_v<T>`]]
[[`void(...)`] [`true`]]
[[`void(int, ...) const`] [`true`]]
[[`void(* volatile)(...)`] [`true`]]
[[`void(&)(...)`] [`true`]]
[[`void(foo::*)(...) const`] [`true`]]
[[`void(*)()`] [`false`]]
[[`void(*&)()`] [`false`]]
[[`int`] [`false`]]
[[`const int`] [`false`]]
[[`int foo::*`] [`false`]]
]
[heading Example Program]
[import ../example/has_varargs.cpp]
[has_varargs]
[endsect]
*/
//]
#endif
<commit_msg>Delete has_varargs.hpp<commit_after><|endoftext|> |
<commit_before>AliAnalysisTask *AddTask_miweber_LMEE_PbPb_woCutLib(Int_t cutDefinition = 0, TString outputFileName = "AnalysisResult.root", TString directoryBaseName = "miweber_LMEE_PbPb", Bool_t isNano = kFALSE, Bool_t bCutQA = kTRUE){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_miweber_LMEE_PbPb_woCutLib", "No analysis manager found.");
return 0;
}
Bool_t bESDANA=kFALSE; //Autodetect via InputHandler
TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configFile("Config_miweber_LMEE_PbPb_woCutLib.C");
TString configFilePath(configBasePath+configFile);
//load dielectron configuration files
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
gROOT->LoadMacro(configFilePath.Data());
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//AOD Usage currently tested with Input handler
if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib", "no dedicated AOD configuration");
}
else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib","switching on ESD specific code");
bESDANA=kTRUE;
}
//create task and add it to the manager
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData_miweber_PbPb_woCutLib");
// for MC no need for physics selection and for Nano AODs this has been done already
if (!hasMC && !isNano) task->UsePhysicsSelection();
//Add event filter
Int_t triggerNames = AliVEvent::kINT7;//PbPb Min Bias, can be set also from outside
// for Nano AODs this has been done already
if(!isNano){
task->SelectCollisionCandidates(triggerNames);
task->SetTriggerMask(triggerNames);
// task->SetRejectPileup(); // to be done differently (too strong cuts at the moment in dielectron framework)
}
// Note: event cuts are identical for all analysis 'cutDefinition's that run together!
//Add event filter
task->SetEventFilter( GetEventCuts() );
// Add the task to the manager
mgr->AddTask(task);
//add dielectron analysis with selected cut to the task
AliDielectron *diel_low = Config_miweber_LMEE_PbPb_woCutLib(cutDefinition,bESDANA,bCutQA);
if(diel_low){
task->AddDielectron(diel_low);
printf("successfully added AliDielectron: %s\n",diel_low->GetName());
}
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("%s_tree",directoryBaseName.Data()),
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer(Form("%s_out",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer(Form("%s_CF",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
// "miweber_LMEE_PbPb_CF.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer(Form("%s_EventStat",directoryBaseName.Data()),
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<commit_msg>Added event plane cut in event cuts<commit_after>AliAnalysisTask *AddTask_miweber_LMEE_PbPb_woCutLib(Int_t cutDefinition = 0, TString outputFileName = "AnalysisResult.root", TString directoryBaseName = "miweber_LMEE_PbPb", Bool_t isNano = kFALSE, Bool_t bCutQA = kTRUE){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_miweber_LMEE_PbPb_woCutLib", "No analysis manager found.");
return 0;
}
Bool_t bESDANA=kFALSE; //Autodetect via InputHandler
TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configFile("Config_miweber_LMEE_PbPb_woCutLib.C");
TString configFilePath(configBasePath+configFile);
//load dielectron configuration files
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
gROOT->LoadMacro(configFilePath.Data());
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//AOD Usage currently tested with Input handler
if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib", "no dedicated AOD configuration");
}
else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib","switching on ESD specific code");
bESDANA=kTRUE;
}
//create task and add it to the manager
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData_miweber_PbPb_woCutLib");
// for MC no need for physics selection and for Nano AODs this has been done already
if (!hasMC && !isNano) task->UsePhysicsSelection();
//Add event filter
Int_t triggerNames = AliVEvent::kINT7;//PbPb Min Bias, can be set also from outside
// for Nano AODs this has been done already
if(!isNano){
task->SelectCollisionCandidates(triggerNames);
task->SetTriggerMask(triggerNames);
// task->SetRejectPileup(); // to be done differently (too strong cuts at the moment in dielectron framework)
}
// Note: event cuts are identical for all analysis 'cutDefinition's that run together!
//Add event filter
task->SetEventFilter( GetEventCuts() );
// Add the task to the manager
mgr->AddTask(task);
//add dielectron analysis with selected cut to the task
AliDielectron *diel_low = Config_miweber_LMEE_PbPb_woCutLib(cutDefinition,bESDANA,bCutQA);
if(diel_low){
AliDielectronVarCuts *eventplaneCuts = new AliDielectronVarCuts("eventplaneCuts","eventplaneCuts");
eventplaneCuts->AddCut(AliDielectronVarManager::kQnTPCrpH2,-999.,kTRUE); // makes sure that the event has an eventplane
eventplaneCuts->Print();
diel_low->GetEventFilter().AddCuts(eventplaneCuts);
task->AddDielectron(diel_low);
printf("successfully added AliDielectron: %s\n",diel_low->GetName());
}
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("%s_tree",directoryBaseName.Data()),
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer(Form("%s_out",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer(Form("%s_CF",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
// "miweber_LMEE_PbPb_CF.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer(Form("%s_EventStat",directoryBaseName.Data()),
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkAutocropAction.h"
#include "mitkAutoCropImageFilter.h"
#include "mitkImageCast.h"
#include "mitkImageWriteAccessor.h"
#include "mitkRenderingManager.h"
#include "mitkProgressBar.h"
#include <itkConstantPadImageFilter.h>
//needed for qApp
#include <qcoreapplication.h>
QmitkAutocropAction::QmitkAutocropAction()
{
}
QmitkAutocropAction::~QmitkAutocropAction()
{
}
void QmitkAutocropAction::Run( const QList<mitk::DataNode::Pointer> &selectedNodes )
{
foreach ( mitk::DataNode::Pointer node, selectedNodes )
{
if (node)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() );
if (image.IsNull()) return;
mitk::ProgressBar::GetInstance()->AddStepsToDo(10);
mitk::ProgressBar::GetInstance()->Progress(2);
qApp->processEvents();
mitk::AutoCropImageFilter::Pointer cropFilter = mitk::AutoCropImageFilter::New();
cropFilter->SetInput( image );
cropFilter->SetBackgroundValue( 0 );
try
{
cropFilter->Update();
image = cropFilter->GetOutput();
if (image.IsNotNull())
{
if (image->GetDimension() == 4)
{
MITK_INFO << "4D AUTOCROP DOES NOT WORK AT THE MOMENT";
throw "4D AUTOCROP DOES NOT WORK AT THE MOMENT";
unsigned int timesteps = image->GetDimension(3);
for (unsigned int i = 0; i < timesteps; i++)
{
mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New();
imageTimeSelector->SetInput(image);
imageTimeSelector->SetTimeNr(i);
imageTimeSelector->UpdateLargestPossibleRegion();
// We split a long nested code line into separate calls for debugging:
mitk::ImageSource::OutputImageType *_3dSlice = imageTimeSelector->GetOutput();
mitk::Image::Pointer _cropped3dSlice = this->IncreaseCroppedImageSize(_3dSlice);
// +++ BUG +++ BUG +++ BUG +++ BUG +++ BUG +++ BUG +++ BUG +++
mitk::ImageWriteAccessor imAccess(_cropped3dSlice);
void *_data = imAccess.GetData();
// <ToBeRemoved>
// We write some stripes into the image
if ((i & 1) == 0)
{
int depth = _cropped3dSlice->GetDimension(2);
int height = _cropped3dSlice->GetDimension(1);
int width = _cropped3dSlice->GetDimension(0);
for (int z = 0; z < depth; ++z)
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
reinterpret_cast<unsigned char *>(_data)[(width * height * z) + (width * y) + x] = x & 1;
// </ToBeRemoved>
}
image->SetVolume(_data, i);
}
node->SetData( image ); // bug fix 3145
}
else
{
node->SetData( this->IncreaseCroppedImageSize(image) ); // bug fix 3145
}
// Reinit node
mitk::RenderingManager::GetInstance()->InitializeViews(
node->GetData()->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
catch(...)
{
MITK_ERROR << "Cropping image failed...";
}
mitk::ProgressBar::GetInstance()->Progress(8);
}
else
{
MITK_INFO << " a nullptr node selected";
}
}
}
mitk::Image::Pointer QmitkAutocropAction::IncreaseCroppedImageSize( mitk::Image::Pointer image )
{
typedef itk::Image< short, 3 > ImageType;
typedef itk::Image< unsigned char, 3 > PADOutputImageType;
ImageType::Pointer itkTransformImage = ImageType::New();
mitk::CastToItkImage( image, itkTransformImage );
typedef itk::ConstantPadImageFilter< ImageType, PADOutputImageType > PadFilterType;
PadFilterType::Pointer padFilter = PadFilterType::New();
itk::SizeValueType upperPad[3];
itk::SizeValueType lowerPad[3];
int borderLiner = 3;
mitk::Point3D mitkOriginPoint;
double origin[3];
origin[0]=0;
origin[1]=0;
origin[2]=0;
itkTransformImage->SetOrigin(origin);
lowerPad[0]=borderLiner;
lowerPad[1]=borderLiner;
lowerPad[2]=borderLiner;
upperPad[0]=borderLiner;
upperPad[1]=borderLiner;
upperPad[2]=borderLiner;
padFilter->SetInput(itkTransformImage);
padFilter->SetConstant(0);
padFilter->SetPadUpperBound(upperPad);
padFilter->SetPadLowerBound(lowerPad);
padFilter->UpdateLargestPossibleRegion();
mitk::Image::Pointer paddedImage = mitk::Image::New();
paddedImage->InitializeByItk(padFilter->GetOutput());
mitk::CastToMitkImage(padFilter->GetOutput(), paddedImage);
//calculate translation according to padding to get the new origin
mitk::Point3D paddedOrigin = image->GetGeometry()->GetOrigin();
mitk::Vector3D spacing = image->GetGeometry()->GetSpacing();
paddedOrigin[0] -= (borderLiner)*spacing[0];
paddedOrigin[1] -= (borderLiner)*spacing[1];
paddedOrigin[2] -= (borderLiner)*spacing[2];
paddedImage->GetGeometry()->SetOrigin( paddedOrigin );
return paddedImage;
}
void QmitkAutocropAction::SetSmoothed(bool /*smoothed*/)
{
//not needed
}
void QmitkAutocropAction::SetDecimated(bool /*decimated*/)
{
//not needed
}
void QmitkAutocropAction::SetDataStorage(mitk::DataStorage* /*dataStorage*/)
{
//not needed
}
void QmitkAutocropAction::SetFunctionality(berry::QtViewPart* /*view*/)
{
//not needed
}
<commit_msg>Do not request a rendering update twice<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkAutocropAction.h"
#include "mitkAutoCropImageFilter.h"
#include "mitkImageCast.h"
#include "mitkImageWriteAccessor.h"
#include "mitkRenderingManager.h"
#include "mitkProgressBar.h"
#include <itkConstantPadImageFilter.h>
//needed for qApp
#include <qcoreapplication.h>
QmitkAutocropAction::QmitkAutocropAction()
{
}
QmitkAutocropAction::~QmitkAutocropAction()
{
}
void QmitkAutocropAction::Run( const QList<mitk::DataNode::Pointer> &selectedNodes )
{
foreach ( mitk::DataNode::Pointer node, selectedNodes )
{
if (node)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() );
if (image.IsNull()) return;
mitk::ProgressBar::GetInstance()->AddStepsToDo(10);
mitk::ProgressBar::GetInstance()->Progress(2);
qApp->processEvents();
mitk::AutoCropImageFilter::Pointer cropFilter = mitk::AutoCropImageFilter::New();
cropFilter->SetInput( image );
cropFilter->SetBackgroundValue( 0 );
try
{
cropFilter->Update();
image = cropFilter->GetOutput();
if (image.IsNotNull())
{
if (image->GetDimension() == 4)
{
MITK_INFO << "4D AUTOCROP DOES NOT WORK AT THE MOMENT";
throw "4D AUTOCROP DOES NOT WORK AT THE MOMENT";
unsigned int timesteps = image->GetDimension(3);
for (unsigned int i = 0; i < timesteps; i++)
{
mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New();
imageTimeSelector->SetInput(image);
imageTimeSelector->SetTimeNr(i);
imageTimeSelector->UpdateLargestPossibleRegion();
// We split a long nested code line into separate calls for debugging:
mitk::ImageSource::OutputImageType *_3dSlice = imageTimeSelector->GetOutput();
mitk::Image::Pointer _cropped3dSlice = this->IncreaseCroppedImageSize(_3dSlice);
// +++ BUG +++ BUG +++ BUG +++ BUG +++ BUG +++ BUG +++ BUG +++
mitk::ImageWriteAccessor imAccess(_cropped3dSlice);
void *_data = imAccess.GetData();
// <ToBeRemoved>
// We write some stripes into the image
if ((i & 1) == 0)
{
int depth = _cropped3dSlice->GetDimension(2);
int height = _cropped3dSlice->GetDimension(1);
int width = _cropped3dSlice->GetDimension(0);
for (int z = 0; z < depth; ++z)
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
reinterpret_cast<unsigned char *>(_data)[(width * height * z) + (width * y) + x] = x & 1;
// </ToBeRemoved>
}
image->SetVolume(_data, i);
}
node->SetData( image ); // bug fix 3145
}
else
{
node->SetData( this->IncreaseCroppedImageSize(image) ); // bug fix 3145
}
// Reinit node
mitk::RenderingManager::GetInstance()->InitializeViews(
node->GetData()->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true);
}
}
catch(...)
{
MITK_ERROR << "Cropping image failed...";
}
mitk::ProgressBar::GetInstance()->Progress(8);
}
else
{
MITK_INFO << " a nullptr node selected";
}
}
}
mitk::Image::Pointer QmitkAutocropAction::IncreaseCroppedImageSize( mitk::Image::Pointer image )
{
typedef itk::Image< short, 3 > ImageType;
typedef itk::Image< unsigned char, 3 > PADOutputImageType;
ImageType::Pointer itkTransformImage = ImageType::New();
mitk::CastToItkImage( image, itkTransformImage );
typedef itk::ConstantPadImageFilter< ImageType, PADOutputImageType > PadFilterType;
PadFilterType::Pointer padFilter = PadFilterType::New();
itk::SizeValueType upperPad[3];
itk::SizeValueType lowerPad[3];
int borderLiner = 3;
mitk::Point3D mitkOriginPoint;
double origin[3];
origin[0]=0;
origin[1]=0;
origin[2]=0;
itkTransformImage->SetOrigin(origin);
lowerPad[0]=borderLiner;
lowerPad[1]=borderLiner;
lowerPad[2]=borderLiner;
upperPad[0]=borderLiner;
upperPad[1]=borderLiner;
upperPad[2]=borderLiner;
padFilter->SetInput(itkTransformImage);
padFilter->SetConstant(0);
padFilter->SetPadUpperBound(upperPad);
padFilter->SetPadLowerBound(lowerPad);
padFilter->UpdateLargestPossibleRegion();
mitk::Image::Pointer paddedImage = mitk::Image::New();
paddedImage->InitializeByItk(padFilter->GetOutput());
mitk::CastToMitkImage(padFilter->GetOutput(), paddedImage);
//calculate translation according to padding to get the new origin
mitk::Point3D paddedOrigin = image->GetGeometry()->GetOrigin();
mitk::Vector3D spacing = image->GetGeometry()->GetSpacing();
paddedOrigin[0] -= (borderLiner)*spacing[0];
paddedOrigin[1] -= (borderLiner)*spacing[1];
paddedOrigin[2] -= (borderLiner)*spacing[2];
paddedImage->GetGeometry()->SetOrigin( paddedOrigin );
return paddedImage;
}
void QmitkAutocropAction::SetSmoothed(bool /*smoothed*/)
{
//not needed
}
void QmitkAutocropAction::SetDecimated(bool /*decimated*/)
{
//not needed
}
void QmitkAutocropAction::SetDataStorage(mitk::DataStorage* /*dataStorage*/)
{
//not needed
}
void QmitkAutocropAction::SetFunctionality(berry::QtViewPart* /*view*/)
{
//not needed
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/api/file_system/file_system_api.h"
#include "chrome/browser/extensions/platform_app_browsertest_util.h"
using extensions::FileSystemChooseEntryFunction;
class FileSystemApiTest : public extensions::PlatformAppBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
test_root_folder_ = test_data_dir_.AppendASCII("api_test")
.AppendASCII("file_system");
}
virtual void TearDown() OVERRIDE {
FileSystemChooseEntryFunction::StopSkippingPickerForTest();
extensions::PlatformAppBrowserTest::TearDown();
};
protected:
base::FilePath TempFilePath(const std::string& destination_name,
bool copy_gold) {
if (!temp_dir_.CreateUniqueTempDir()) {
ADD_FAILURE() << "CreateUniqueTempDir failed";
return base::FilePath();
}
base::FilePath destination = temp_dir_.path().AppendASCII(destination_name);
if (copy_gold) {
base::FilePath source = test_root_folder_.AppendASCII("gold.txt");
EXPECT_TRUE(file_util::CopyFile(source, destination));
}
return destination;
}
base::FilePath test_root_folder_;
base::ScopedTempDir temp_dir_;
};
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPath) {
base::FilePath test_file = test_root_folder_.AppendASCII("gold.txt");
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/get_display_path"))
<< message_;
}
#if defined(OS_WIN) || defined(OS_POSIX)
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPathPrettify) {
#if defined(OS_WIN)
int override = base::DIR_PROFILE;
#elif defined(OS_POSIX)
int override = base::DIR_HOME;
#endif
ASSERT_TRUE(PathService::OverrideAndCreateIfNeeded(override,
test_root_folder_, false));
base::FilePath test_file = test_root_folder_.AppendASCII("gold.txt");
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_display_path_prettify")) << message_;
}
#endif
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiGetDisplayPathPrettifyMac) {
// On Mac, "test.localized" will be localized into just "test".
base::FilePath test_path = TempFilePath("test.localized", false);
ASSERT_TRUE(file_util::CreateDirectory(test_path));
base::FilePath test_file = test_path.AppendASCII("gold.txt");
base::FilePath source = test_root_folder_.AppendASCII("gold.txt");
EXPECT_TRUE(file_util::CopyFile(source, test_file));
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_display_path_prettify_mac")) << message_;
}
#endif
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/open_existing"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiInvalidChooseEntryTypeTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/invalid_choose_file_type")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiOpenExistingFileWithWriteTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/open_existing_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiOpenWritableExistingFileTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/open_writable_existing")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiOpenWritableExistingFileWithWriteTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/open_writable_existing_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenCancelTest) {
FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/open_cancel"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenBackgroundTest) {
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/open_background"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveNewFileTest) {
base::FilePath test_file = TempFilePath("save_new.txt", false);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_new"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveExistingFileTest) {
base::FilePath test_file = TempFilePath("save_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_existing"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiSaveNewFileWithWriteTest) {
base::FilePath test_file = TempFilePath("save_new.txt", false);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_new_with_write"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiSaveExistingFileWithWriteTest) {
base::FilePath test_file = TempFilePath("save_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/save_existing_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveCancelTest) {
FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_cancel"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveBackgroundTest) {
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_background"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableTest) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_writable_file_entry")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiGetWritableWithWriteTest) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_writable_file_entry_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiIsWritableTest) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/is_writable_file_entry")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetEntryId) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_entry_id")) << message_;
}
<commit_msg>Disable two FileSystemApiTests on Linux: FileSystemApiOpenBackgroundTest FileSystemApiSaveBackgroundTest<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/file_system/file_system_api.h"
#include "chrome/browser/extensions/platform_app_browsertest_util.h"
using extensions::FileSystemChooseEntryFunction;
class FileSystemApiTest : public extensions::PlatformAppBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
test_root_folder_ = test_data_dir_.AppendASCII("api_test")
.AppendASCII("file_system");
}
virtual void TearDown() OVERRIDE {
FileSystemChooseEntryFunction::StopSkippingPickerForTest();
extensions::PlatformAppBrowserTest::TearDown();
};
protected:
base::FilePath TempFilePath(const std::string& destination_name,
bool copy_gold) {
if (!temp_dir_.CreateUniqueTempDir()) {
ADD_FAILURE() << "CreateUniqueTempDir failed";
return base::FilePath();
}
base::FilePath destination = temp_dir_.path().AppendASCII(destination_name);
if (copy_gold) {
base::FilePath source = test_root_folder_.AppendASCII("gold.txt");
EXPECT_TRUE(file_util::CopyFile(source, destination));
}
return destination;
}
base::FilePath test_root_folder_;
base::ScopedTempDir temp_dir_;
};
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPath) {
base::FilePath test_file = test_root_folder_.AppendASCII("gold.txt");
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/get_display_path"))
<< message_;
}
#if defined(OS_WIN) || defined(OS_POSIX)
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPathPrettify) {
#if defined(OS_WIN)
int override = base::DIR_PROFILE;
#elif defined(OS_POSIX)
int override = base::DIR_HOME;
#endif
ASSERT_TRUE(PathService::OverrideAndCreateIfNeeded(override,
test_root_folder_, false));
base::FilePath test_file = test_root_folder_.AppendASCII("gold.txt");
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_display_path_prettify")) << message_;
}
#endif
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiGetDisplayPathPrettifyMac) {
// On Mac, "test.localized" will be localized into just "test".
base::FilePath test_path = TempFilePath("test.localized", false);
ASSERT_TRUE(file_util::CreateDirectory(test_path));
base::FilePath test_file = test_path.AppendASCII("gold.txt");
base::FilePath source = test_root_folder_.AppendASCII("gold.txt");
EXPECT_TRUE(file_util::CopyFile(source, test_file));
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_display_path_prettify_mac")) << message_;
}
#endif
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/open_existing"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiInvalidChooseEntryTypeTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/invalid_choose_file_type")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiOpenExistingFileWithWriteTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/open_existing_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiOpenWritableExistingFileTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/open_writable_existing")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiOpenWritableExistingFileWithWriteTest) {
base::FilePath test_file = TempFilePath("open_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/open_writable_existing_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenCancelTest) {
FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/open_cancel"))
<< message_;
}
#if defined(OS_LINUX)
// Disabled on linux due to crbug.com/178679.
#define MAYBE_FileSystemApiSaveBackgroundTest \
DISABLED_FileSystemApiOpenBackgroundTest
#else
#define MAYBE_FileSystemApiOpenBackgroundTest FileSystemApiOpenBackgroundTest
#endif
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
MAYBE_FileSystemApiOpenBackgroundTest) {
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/open_background"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveNewFileTest) {
base::FilePath test_file = TempFilePath("save_new.txt", false);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_new"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveExistingFileTest) {
base::FilePath test_file = TempFilePath("save_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_existing"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiSaveNewFileWithWriteTest) {
base::FilePath test_file = TempFilePath("save_new.txt", false);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_new_with_write"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiSaveExistingFileWithWriteTest) {
base::FilePath test_file = TempFilePath("save_existing.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/save_existing_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveCancelTest) {
FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_cancel"))
<< message_;
}
#if defined(OS_LINUX)
// Disabled on linux due to crbug.com/178679.
#define MAYBE_FileSystemApiSaveBackgroundTest \
DISABLED_FileSystemApiSaveBackgroundTest
#else
#define MAYBE_FileSystemApiSaveBackgroundTest FileSystemApiSaveBackgroundTest
#endif
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
MAYBE_FileSystemApiSaveBackgroundTest) {
ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/save_background"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableTest) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_writable_file_entry")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest,
FileSystemApiGetWritableWithWriteTest) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_writable_file_entry_with_write")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiIsWritableTest) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/is_writable_file_entry")) << message_;
}
IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetEntryId) {
base::FilePath test_file = TempFilePath("writable.txt", true);
ASSERT_FALSE(test_file.empty());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&test_file);
ASSERT_TRUE(RunPlatformAppTest(
"api_test/file_system/get_entry_id")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/extensions/extension_action_view_controller.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "chrome/browser/extensions/extension_action.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extension_view_host.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/sidebar/sidebar_container.h"
#include "chrome/browser/sidebar/sidebar_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/accelerator_priority.h"
#include "chrome/browser/ui/extensions/extension_action_platform_delegate.h"
#include "chrome/browser/ui/toolbar/toolbar_action_view_delegate.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
using extensions::ActionInfo;
using extensions::CommandService;
ExtensionActionViewController::ExtensionActionViewController(
const extensions::Extension* extension,
Browser* browser,
ExtensionAction* extension_action)
: extension_(extension),
browser_(browser),
extension_action_(extension_action),
popup_host_(nullptr),
view_delegate_(nullptr),
platform_delegate_(ExtensionActionPlatformDelegate::Create(this)),
icon_factory_(browser->profile(), extension, extension_action, this),
icon_observer_(nullptr),
extension_registry_(
extensions::ExtensionRegistry::Get(browser_->profile())),
popup_host_observer_(this) {
DCHECK(extension_action);
DCHECK(extension_action->action_type() == ActionInfo::TYPE_PAGE ||
extension_action->action_type() == ActionInfo::TYPE_BROWSER);
DCHECK(extension);
}
ExtensionActionViewController::~ExtensionActionViewController() {
DCHECK(!is_showing_popup());
SidebarManager::GetInstance()->RemoveObserver(this);
}
const std::string& ExtensionActionViewController::GetId() const {
return extension_->id();
}
void ExtensionActionViewController::SetDelegate(
ToolbarActionViewDelegate* delegate) {
DCHECK((delegate == nullptr) ^ (view_delegate_ == nullptr));
if (delegate) {
view_delegate_ = delegate;
platform_delegate_->OnDelegateSet();
} else {
if (is_showing_popup())
HidePopup();
platform_delegate_.reset();
view_delegate_ = nullptr;
}
}
gfx::Image ExtensionActionViewController::GetIcon(
content::WebContents* web_contents) {
if (!ExtensionIsValid())
return gfx::Image();
return icon_factory_.GetIcon(SessionTabHelper::IdForTab(web_contents));
}
gfx::ImageSkia ExtensionActionViewController::GetIconWithBadge() {
if (!ExtensionIsValid())
return gfx::ImageSkia();
content::WebContents* web_contents = view_delegate_->GetCurrentWebContents();
gfx::Size spacing(0, 3);
gfx::ImageSkia icon = *GetIcon(web_contents).ToImageSkia();
if (!IsEnabled(web_contents))
icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
return extension_action_->GetIconWithBadge(
icon, SessionTabHelper::IdForTab(web_contents), spacing);
}
base::string16 ExtensionActionViewController::GetActionName() const {
if (!ExtensionIsValid())
return base::string16();
return base::UTF8ToUTF16(extension_->name());
}
base::string16 ExtensionActionViewController::GetAccessibleName(
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return base::string16();
std::string title =
extension_action()->GetTitle(SessionTabHelper::IdForTab(web_contents));
return base::UTF8ToUTF16(title.empty() ? extension()->name() : title);
}
base::string16 ExtensionActionViewController::GetTooltip(
content::WebContents* web_contents) const {
return GetAccessibleName(web_contents);
}
bool ExtensionActionViewController::IsEnabled(
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return false;
return extension_action_->GetIsVisible(
SessionTabHelper::IdForTab(web_contents)) ||
extensions::ExtensionActionAPI::Get(browser_->profile())->
ExtensionWantsToRun(extension(), web_contents);
}
bool ExtensionActionViewController::WantsToRun(
content::WebContents* web_contents) const {
return extensions::ExtensionActionAPI::Get(browser_->profile())->
ExtensionWantsToRun(extension(), web_contents);
}
bool ExtensionActionViewController::HasPopup(
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return false;
int tab_id = SessionTabHelper::IdForTab(web_contents);
return (tab_id < 0) ? false : extension_action_->HasPopup(tab_id);
}
void ExtensionActionViewController::HidePopup() {
if (is_showing_popup()) {
popup_host_->Close();
// We need to do these actions synchronously (instead of closing and then
// performing the rest of the cleanup in OnExtensionHostDestroyed()) because
// the extension host can close asynchronously, and we need to keep the view
// delegate up-to-date.
OnPopupClosed();
}
}
gfx::NativeView ExtensionActionViewController::GetPopupNativeView() {
return popup_host_ ? popup_host_->view()->GetNativeView() : nullptr;
}
ui::MenuModel* ExtensionActionViewController::GetContextMenu() {
if (!ExtensionIsValid() || !extension()->ShowConfigureContextMenus())
return nullptr;
// Reconstruct the menu every time because the menu's contents are dynamic.
context_menu_model_ = make_scoped_refptr(new ExtensionContextMenuModel(
extension(), browser_, this));
return context_menu_model_.get();
}
bool ExtensionActionViewController::IsMenuRunning() const {
return platform_delegate_->IsMenuRunning();
}
bool ExtensionActionViewController::CanDrag() const {
return true;
}
bool ExtensionActionViewController::ExecuteAction(bool by_user) {
return ExecuteAction(SHOW_POPUP, by_user);
}
void ExtensionActionViewController::UpdateState() {
if (!ExtensionIsValid())
return;
view_delegate_->UpdateState();
}
bool ExtensionActionViewController::ExecuteAction(PopupShowAction show_action,
bool grant_tab_permissions) {
if (!ExtensionIsValid())
return false;
if (extensions::ExtensionActionAPI::Get(browser_->profile())
->ExecuteExtensionAction(
extension_, browser_, grant_tab_permissions) ==
ExtensionAction::ACTION_SHOW_POPUP) {
GURL popup_url = extension_action_->GetPopupUrl(
SessionTabHelper::IdForTab(view_delegate_->GetCurrentWebContents()));
return static_cast<ExtensionActionViewController*>(
view_delegate_->GetPreferredPopupViewController())
->ShowPopupWithUrl(show_action, popup_url, grant_tab_permissions);
}
return false;
}
void ExtensionActionViewController::PaintExtra(
gfx::Canvas* canvas,
const gfx::Rect& bounds,
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return;
int tab_id = SessionTabHelper::IdForTab(web_contents);
if (tab_id >= 0)
extension_action_->PaintBadge(canvas, bounds, tab_id);
}
void ExtensionActionViewController::RegisterCommand() {
if (!ExtensionIsValid())
return;
platform_delegate_->RegisterCommand();
}
void ExtensionActionViewController::InspectPopup() {
ExecuteAction(SHOW_POPUP_AND_INSPECT, true);
}
void ExtensionActionViewController::OnIconUpdated() {
if (icon_observer_)
icon_observer_->OnIconUpdated();
if (view_delegate_)
view_delegate_->UpdateState();
}
void ExtensionActionViewController::OnExtensionHostDestroyed(
const extensions::ExtensionHost* host) {
OnPopupClosed();
}
bool ExtensionActionViewController::ExtensionIsValid() const {
return extension_registry_->enabled_extensions().Contains(extension_->id());
}
bool ExtensionActionViewController::GetExtensionCommand(
extensions::Command* command) {
DCHECK(command);
if (!ExtensionIsValid())
return false;
CommandService* command_service = CommandService::Get(browser_->profile());
if (extension_action_->action_type() == ActionInfo::TYPE_PAGE) {
return command_service->GetPageActionCommand(
extension_->id(), CommandService::ACTIVE, command, NULL);
}
return command_service->GetBrowserActionCommand(
extension_->id(), CommandService::ACTIVE, command, NULL);
}
bool ExtensionActionViewController::ShowPopupWithUrl(
PopupShowAction show_action,
const GURL& popup_url,
bool grant_tab_permissions) {
if (!ExtensionIsValid())
return false;
bool already_showing = is_showing_popup();
// Always hide the current popup, even if it's not owned by this extension.
// Only one popup should be visible at a time.
platform_delegate_->CloseActivePopup();
// If we were showing a popup already, then we treat the action to open the
// same one as a desire to close it (like clicking a menu button that was
// already open).
if (already_showing)
return false;
bool use_sidebar =
browser()->profile()->GetPrefs()->GetBoolean(prefs::kShowPopupInSidebar);
if (use_sidebar) {
SidebarManager* sidebar_manager = SidebarManager::GetInstance();
content::WebContents* web_contents = view_delegate_->GetCurrentWebContents();
if (active_in_webcontents_.find(web_contents) != active_in_webcontents_.end()) {
sidebar_manager->HideSidebar(
web_contents, GetId());
return false;
}
active_in_webcontents_.insert(web_contents);
sidebar_manager->AddObserver(this);
sidebar_manager->ShowSidebar(
web_contents, GetId());
sidebar_manager->NavigateSidebar(
web_contents, GetId(), popup_url);
return true;
}
popup_host_ = platform_delegate_->ShowPopupWithUrl(
show_action, popup_url, grant_tab_permissions);
if (popup_host_) {
popup_host_observer_.Add(popup_host_);
view_delegate_->OnPopupShown(grant_tab_permissions);
}
return is_showing_popup();
}
void ExtensionActionViewController::OnPopupClosed() {
popup_host_observer_.Remove(popup_host_);
popup_host_ = nullptr;
view_delegate_->OnPopupClosed();
}
void ExtensionActionViewController::OnSidebarShown(content::WebContents* tab,
const std::string& content_id) {
if (view_delegate_->GetCurrentWebContents() == tab &&
content_id == GetId())
// Without the popup corner arrow indicator, marking the browserAction icon
// is necessary for extension attribution
view_delegate_->OnPopupShown(true);
}
void ExtensionActionViewController::OnSidebarHidden(content::WebContents* tab,
const std::string& content_id) {
if (view_delegate_->GetCurrentWebContents() == tab &&
content_id == GetId()) {
view_delegate_->OnPopupClosed();
active_in_webcontents_.erase(active_in_webcontents_.find(
view_delegate_->GetCurrentWebContents()));
if (active_in_webcontents_.size() == 0)
SidebarManager::GetInstance()->RemoveObserver(this);
}
}
void ExtensionActionViewController::OnSidebarSwitched(content::WebContents* old_tab,
const std::string& old_content_id,
content::WebContents* new_tab,
const std::string& new_content_id) {
if (view_delegate_->GetCurrentWebContents() == new_tab &&
new_content_id == GetId())
// Without the popup corner arrow indicator, marking the browserAction icon
// is necessary for extension attribution
view_delegate_->OnPopupShown(true);
else
view_delegate_->OnPopupClosed();
}
<commit_msg>Handle depressed button for multiple windows / multiple tabs<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/extensions/extension_action_view_controller.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "chrome/browser/extensions/extension_action.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extension_view_host.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/sidebar/sidebar_container.h"
#include "chrome/browser/sidebar/sidebar_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/accelerator_priority.h"
#include "chrome/browser/ui/extensions/extension_action_platform_delegate.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/browser/ui/toolbar/toolbar_action_view_delegate.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
using extensions::ActionInfo;
using extensions::CommandService;
ExtensionActionViewController::ExtensionActionViewController(
const extensions::Extension* extension,
Browser* browser,
ExtensionAction* extension_action)
: extension_(extension),
browser_(browser),
extension_action_(extension_action),
popup_host_(nullptr),
view_delegate_(nullptr),
platform_delegate_(ExtensionActionPlatformDelegate::Create(this)),
icon_factory_(browser->profile(), extension, extension_action, this),
icon_observer_(nullptr),
extension_registry_(
extensions::ExtensionRegistry::Get(browser_->profile())),
popup_host_observer_(this) {
DCHECK(extension_action);
DCHECK(extension_action->action_type() == ActionInfo::TYPE_PAGE ||
extension_action->action_type() == ActionInfo::TYPE_BROWSER);
DCHECK(extension);
}
ExtensionActionViewController::~ExtensionActionViewController() {
DCHECK(!is_showing_popup());
SidebarManager::GetInstance()->RemoveObserver(this);
}
const std::string& ExtensionActionViewController::GetId() const {
return extension_->id();
}
void ExtensionActionViewController::SetDelegate(
ToolbarActionViewDelegate* delegate) {
DCHECK((delegate == nullptr) ^ (view_delegate_ == nullptr));
if (delegate) {
view_delegate_ = delegate;
platform_delegate_->OnDelegateSet();
} else {
if (is_showing_popup())
HidePopup();
platform_delegate_.reset();
view_delegate_ = nullptr;
}
}
gfx::Image ExtensionActionViewController::GetIcon(
content::WebContents* web_contents) {
if (!ExtensionIsValid())
return gfx::Image();
return icon_factory_.GetIcon(SessionTabHelper::IdForTab(web_contents));
}
gfx::ImageSkia ExtensionActionViewController::GetIconWithBadge() {
if (!ExtensionIsValid())
return gfx::ImageSkia();
content::WebContents* web_contents = view_delegate_->GetCurrentWebContents();
gfx::Size spacing(0, 3);
gfx::ImageSkia icon = *GetIcon(web_contents).ToImageSkia();
if (!IsEnabled(web_contents))
icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
return extension_action_->GetIconWithBadge(
icon, SessionTabHelper::IdForTab(web_contents), spacing);
}
base::string16 ExtensionActionViewController::GetActionName() const {
if (!ExtensionIsValid())
return base::string16();
return base::UTF8ToUTF16(extension_->name());
}
base::string16 ExtensionActionViewController::GetAccessibleName(
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return base::string16();
std::string title =
extension_action()->GetTitle(SessionTabHelper::IdForTab(web_contents));
return base::UTF8ToUTF16(title.empty() ? extension()->name() : title);
}
base::string16 ExtensionActionViewController::GetTooltip(
content::WebContents* web_contents) const {
return GetAccessibleName(web_contents);
}
bool ExtensionActionViewController::IsEnabled(
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return false;
return extension_action_->GetIsVisible(
SessionTabHelper::IdForTab(web_contents)) ||
extensions::ExtensionActionAPI::Get(browser_->profile())->
ExtensionWantsToRun(extension(), web_contents);
}
bool ExtensionActionViewController::WantsToRun(
content::WebContents* web_contents) const {
return extensions::ExtensionActionAPI::Get(browser_->profile())->
ExtensionWantsToRun(extension(), web_contents);
}
bool ExtensionActionViewController::HasPopup(
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return false;
int tab_id = SessionTabHelper::IdForTab(web_contents);
return (tab_id < 0) ? false : extension_action_->HasPopup(tab_id);
}
void ExtensionActionViewController::HidePopup() {
if (is_showing_popup()) {
popup_host_->Close();
// We need to do these actions synchronously (instead of closing and then
// performing the rest of the cleanup in OnExtensionHostDestroyed()) because
// the extension host can close asynchronously, and we need to keep the view
// delegate up-to-date.
OnPopupClosed();
}
}
gfx::NativeView ExtensionActionViewController::GetPopupNativeView() {
return popup_host_ ? popup_host_->view()->GetNativeView() : nullptr;
}
ui::MenuModel* ExtensionActionViewController::GetContextMenu() {
if (!ExtensionIsValid() || !extension()->ShowConfigureContextMenus())
return nullptr;
// Reconstruct the menu every time because the menu's contents are dynamic.
context_menu_model_ = make_scoped_refptr(new ExtensionContextMenuModel(
extension(), browser_, this));
return context_menu_model_.get();
}
bool ExtensionActionViewController::IsMenuRunning() const {
return platform_delegate_->IsMenuRunning();
}
bool ExtensionActionViewController::CanDrag() const {
return true;
}
bool ExtensionActionViewController::ExecuteAction(bool by_user) {
return ExecuteAction(SHOW_POPUP, by_user);
}
void ExtensionActionViewController::UpdateState() {
if (!ExtensionIsValid())
return;
view_delegate_->UpdateState();
}
bool ExtensionActionViewController::ExecuteAction(PopupShowAction show_action,
bool grant_tab_permissions) {
if (!ExtensionIsValid())
return false;
if (extensions::ExtensionActionAPI::Get(browser_->profile())
->ExecuteExtensionAction(
extension_, browser_, grant_tab_permissions) ==
ExtensionAction::ACTION_SHOW_POPUP) {
GURL popup_url = extension_action_->GetPopupUrl(
SessionTabHelper::IdForTab(view_delegate_->GetCurrentWebContents()));
return static_cast<ExtensionActionViewController*>(
view_delegate_->GetPreferredPopupViewController())
->ShowPopupWithUrl(show_action, popup_url, grant_tab_permissions);
}
return false;
}
void ExtensionActionViewController::PaintExtra(
gfx::Canvas* canvas,
const gfx::Rect& bounds,
content::WebContents* web_contents) const {
if (!ExtensionIsValid())
return;
int tab_id = SessionTabHelper::IdForTab(web_contents);
if (tab_id >= 0)
extension_action_->PaintBadge(canvas, bounds, tab_id);
}
void ExtensionActionViewController::RegisterCommand() {
if (!ExtensionIsValid())
return;
platform_delegate_->RegisterCommand();
}
void ExtensionActionViewController::InspectPopup() {
ExecuteAction(SHOW_POPUP_AND_INSPECT, true);
}
void ExtensionActionViewController::OnIconUpdated() {
if (icon_observer_)
icon_observer_->OnIconUpdated();
if (view_delegate_)
view_delegate_->UpdateState();
}
void ExtensionActionViewController::OnExtensionHostDestroyed(
const extensions::ExtensionHost* host) {
OnPopupClosed();
}
bool ExtensionActionViewController::ExtensionIsValid() const {
return extension_registry_->enabled_extensions().Contains(extension_->id());
}
bool ExtensionActionViewController::GetExtensionCommand(
extensions::Command* command) {
DCHECK(command);
if (!ExtensionIsValid())
return false;
CommandService* command_service = CommandService::Get(browser_->profile());
if (extension_action_->action_type() == ActionInfo::TYPE_PAGE) {
return command_service->GetPageActionCommand(
extension_->id(), CommandService::ACTIVE, command, NULL);
}
return command_service->GetBrowserActionCommand(
extension_->id(), CommandService::ACTIVE, command, NULL);
}
bool ExtensionActionViewController::ShowPopupWithUrl(
PopupShowAction show_action,
const GURL& popup_url,
bool grant_tab_permissions) {
if (!ExtensionIsValid())
return false;
bool already_showing = is_showing_popup();
// Always hide the current popup, even if it's not owned by this extension.
// Only one popup should be visible at a time.
platform_delegate_->CloseActivePopup();
// If we were showing a popup already, then we treat the action to open the
// same one as a desire to close it (like clicking a menu button that was
// already open).
if (already_showing)
return false;
bool use_sidebar =
browser()->profile()->GetPrefs()->GetBoolean(prefs::kShowPopupInSidebar);
if (use_sidebar) {
SidebarManager* sidebar_manager = SidebarManager::GetInstance();
content::WebContents* web_contents = view_delegate_->GetCurrentWebContents();
if (active_in_webcontents_.find(web_contents) != active_in_webcontents_.end()) {
sidebar_manager->HideSidebar(
web_contents, GetId());
return false;
}
active_in_webcontents_.insert(web_contents);
sidebar_manager->AddObserver(this);
sidebar_manager->ShowSidebar(
web_contents, GetId());
sidebar_manager->NavigateSidebar(
web_contents, GetId(), popup_url);
return true;
}
popup_host_ = platform_delegate_->ShowPopupWithUrl(
show_action, popup_url, grant_tab_permissions);
if (popup_host_) {
popup_host_observer_.Add(popup_host_);
view_delegate_->OnPopupShown(grant_tab_permissions);
}
return is_showing_popup();
}
void ExtensionActionViewController::OnPopupClosed() {
popup_host_observer_.Remove(popup_host_);
popup_host_ = nullptr;
view_delegate_->OnPopupClosed();
}
void ExtensionActionViewController::OnSidebarShown(content::WebContents* tab,
const std::string& content_id) {
if (view_delegate_->GetCurrentWebContents() == tab &&
content_id == GetId())
// Without the popup corner arrow indicator, marking the browserAction icon
// is necessary for extension attribution
view_delegate_->OnPopupShown(true);
}
void ExtensionActionViewController::OnSidebarHidden(content::WebContents* tab,
const std::string& content_id) {
if (view_delegate_->GetCurrentWebContents() == tab &&
content_id == GetId()) {
view_delegate_->OnPopupClosed();
active_in_webcontents_.erase(active_in_webcontents_.find(
view_delegate_->GetCurrentWebContents()));
if (active_in_webcontents_.size() == 0)
SidebarManager::GetInstance()->RemoveObserver(this);
}
}
void ExtensionActionViewController::OnSidebarSwitched(content::WebContents* old_tab,
const std::string& old_content_id,
content::WebContents* new_tab,
const std::string& new_content_id) {
if (browser_->tab_strip_model()->GetIndexOfWebContents(new_tab ? new_tab : old_tab) == TabStripModel::kNoTab)
return;
if (view_delegate_->GetCurrentWebContents() == new_tab &&
new_content_id == GetId())
// Without the popup corner arrow indicator, marking the browserAction icon
// is necessary for extension attribution
view_delegate_->OnPopupShown(true);
else
view_delegate_->OnPopupClosed();
}
<|endoftext|> |
<commit_before>/*
* GLMeshBuffer.cpp
* moFlo
*
* Created by Scott Downie on 01/10/2010.
* Copyright 2010 Tag Games. All rights reserved.
*
*/
#include <ChilliSource/Backend/Rendering/OpenGL/Base/MeshBuffer.h>
#include <ChilliSource/Backend/Rendering/OpenGL/Base/RenderSystem.h>
namespace ChilliSource
{
namespace OpenGL
{
CMeshBuffer* CMeshBuffer::pCurrentlyBoundBuffer = nullptr;
//-----------------------------------------------------
/// Constructor
///
/// Create a vertex buffer and index buffer from
/// the given buffer description
/// @param Buffer desciption
//-----------------------------------------------------
CMeshBuffer::CMeshBuffer(ChilliSource::Rendering::BufferDescription &inBuffDesc)
: ChilliSource::Rendering::MeshBuffer(inBuffDesc), mVertexBuffer(0), mIndexBuffer(0), mBufferUsage(0), mBufferAccess(0),
mpVertexData(nullptr), mpIndexData(nullptr), mpVertexDataBackup(nullptr), mpIndexDataBackup(nullptr), mbMapBufferAvailable(false), mbCacheValid(false)
{
glGenBuffers(1, &mVertexBuffer);
if(mBufferDesc.IndexDataCapacity > 0)
glGenBuffers(1, &mIndexBuffer);
switch(mBufferDesc.eUsageFlag)
{
case Rendering::BufferUsage::k_dynamic:
mBufferUsage = GL_DYNAMIC_DRAW;
break;
case Rendering::BufferUsage::k_static:
mBufferUsage = GL_STATIC_DRAW;
break;
};
switch(mBufferDesc.eAccessFlag)
{
case Rendering::BufferAccess::k_write:
#ifdef MOFLOW_OPENGL
mBufferAccess = GL_WRITE_ONLY;
#elif defined MOFLOW_OPENGLES2
mBufferAccess = GL_WRITE_ONLY_OES;
#endif
break;
case Rendering::BufferAccess::k_read:
#ifdef MOFLOW_OPENGL
mBufferAccess = GL_WRITE_ONLY;
#elif defined MOFLOW_OPENGLES2
mBufferAccess = GL_WRITE_ONLY_OES;
#endif
break;
case Rendering::BufferAccess::k_readWrite:
default:
#ifdef MOFLOW_OPENGL
mBufferAccess = GL_WRITE_ONLY;
#elif defined MOFLOW_OPENGLES2
mBufferAccess = GL_WRITE_ONLY_OES;
#endif
break;
};
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, nullptr, mBufferUsage);
if(mIndexBuffer != 0)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mBufferDesc.IndexDataCapacity, nullptr, mBufferUsage);
}
CMeshBuffer::pCurrentlyBoundBuffer = this;
}
//-----------------------------------------------------
/// Bind
///
/// Set the active buffer by binding to the context
//-----------------------------------------------------
void CMeshBuffer::Bind()
{
if(CMeshBuffer::pCurrentlyBoundBuffer != this)
{
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
CMeshBuffer::pCurrentlyBoundBuffer = this;
}
}
//-----------------------------------------------------
/// Lock Vertex
///
/// Obtain a handle to the buffer memory in order
/// to map data
/// @param Outputs the pointer to the buffer
/// @param The offset to the subset of the buffer
/// @param The vertex layout stride
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::LockVertex(f32** outppBuffer, u32 inDataOffset, u32 inDataStride)
{
if(mbMapBufferAvailable)
{
if (mBufferDesc.eUsageFlag == Rendering::BufferUsage::k_dynamic)
{
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, nullptr, mBufferUsage);
}
#ifdef MOFLOW_OPENGL
(*outppBuffer) = static_cast<f32*>(glMapBuffer(GL_ARRAY_BUFFER, mBufferAccess));
#elif defined MOFLOW_OPENGLES2
(*outppBuffer) = static_cast<f32*>(glMapBufferOES(GL_ARRAY_BUFFER, mBufferAccess));
#endif
mpVertexData = (*outppBuffer);
}
else
{
if(!mpVertexData)
{
mpVertexData = (f32*)new u8[mBufferDesc.VertexDataCapacity];
}
(*outppBuffer) = mpVertexData;
}
mbCacheValid = false;
return ((*outppBuffer));
}
//-----------------------------------------------------
/// Lock Index
///
/// Obtain a handle to the buffer memory in order
/// to map data
/// @param Outputs the pointer to the buffer
/// @param The offset to the subset of the buffer
/// @param The vertex layout stride
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::LockIndex(u16** outppBuffer, u32 inDataOffset, u32 inDataStride)
{
if(!mIndexBuffer)
{
(*outppBuffer) = nullptr;
return false;
}
if(mbMapBufferAvailable)
{
#ifdef MOFLOW_OPENGL
(*outppBuffer) = static_cast<u16*>(glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferAccess));
#elif defined MOFLOW_OPENGLES2
(*outppBuffer) = static_cast<u16*>(glMapBufferOES(GL_ELEMENT_ARRAY_BUFFER, mBufferAccess));
#endif
mpIndexData = (*outppBuffer);
}
else
{
if(!mpIndexData)
{
mpIndexData = (u16*)new u8[mBufferDesc.IndexDataCapacity];
}
(*outppBuffer) = mpIndexData;
}
mbCacheValid = false;
return ((*outppBuffer));
}
//-----------------------------------------------------
/// Unlock Vertex
///
/// Releases the buffer from mapping
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::UnlockVertex()
{
if(mbMapBufferAvailable)
{
mpVertexData = nullptr;
#ifdef MOFLOW_OPENGL
return glUnmapBuffer(GL_ARRAY_BUFFER);
#elif defined MOFLOW_OPENGLES2
return glUnmapBufferOES(GL_ARRAY_BUFFER);
#endif
}
else
{
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, mpVertexData, mBufferUsage);
return true;
}
}
//-----------------------------------------------------
/// Unlock Index
///
/// Releases the buffer from mapping
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::UnlockIndex()
{
if(!mIndexBuffer)
return false;
if(mbMapBufferAvailable)
{
mpIndexData = nullptr;
#ifdef MOFLOW_OPENGL
return glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
#elif defined MOFLOW_OPENGLES2
return glUnmapBufferOES(GL_ELEMENT_ARRAY_BUFFER);
#endif
}
else
{
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mBufferDesc.IndexDataCapacity, mpIndexData, mBufferUsage);
return true;
}
}
//-----------------------------------------------------
/// Set Map Buffer Available
///
/// @param Whether the GL implementation supports
/// the map buffer extension
//-----------------------------------------------------
void CMeshBuffer::SetMapBufferAvailable(bool inbEnabled)
{
mbMapBufferAvailable = inbEnabled;
}
//-----------------------------------------------------
/// Backup
///
/// Backs up the data in the mesh buffer to make
/// sure it is not lost on context loss
//-----------------------------------------------------
void CMeshBuffer::Backup()
{
if(!mpIndexDataBackup)
{
mpIndexDataBackup = (u16*)new u8[mBufferDesc.IndexDataCapacity];
}
//Fill the backup
Bind();
if(!mpVertexDataBackup)
{
mpVertexDataBackup = (f32*)new u8[mBufferDesc.VertexDataCapacity];
}
f32* pVBuffer = nullptr;
LockVertex(&pVBuffer, 0, 0);
memcpy(mpVertexDataBackup, pVBuffer, GetVertexCapacity());
UnlockVertex();
if(mIndexBuffer != 0)
{
if(!mpIndexDataBackup)
{
mpIndexDataBackup = (u16*)new u8[mBufferDesc.IndexDataCapacity];
}
u16* pIBuffer = nullptr;
LockIndex(&pIBuffer, 0, 0);
memcpy(mpIndexDataBackup, pIBuffer, GetIndexCapacity());
UnlockIndex();
}
mVertexBuffer = 0;
mIndexBuffer = 0;
}
//-----------------------------------------------------
/// Restore
///
/// Restore the mesh buffer data from the last
/// backup after the context has been re-created
//-----------------------------------------------------
void CMeshBuffer::Restore()
{
//Force bind as we may have been bound from before context destruction
CMeshBuffer::pCurrentlyBoundBuffer = nullptr;
if(mpVertexDataBackup == nullptr)
{
return;
}
//Check for backups
if(mpVertexDataBackup)
{
glGenBuffers(1, &mVertexBuffer);
}
if(mpIndexDataBackup)
{
glGenBuffers(1, &mIndexBuffer);
}
Bind();
f32* pVBuffer = nullptr;
LockVertex(&pVBuffer, 0, 0);
memcpy(pVBuffer, mpVertexDataBackup, GetVertexCapacity());
UnlockVertex();
if(mIndexBuffer != 0)
{
u16* pIBuffer = nullptr;
LockIndex(&pIBuffer, 0, 0);
memcpy(pIBuffer, mpIndexDataBackup, GetIndexCapacity());
UnlockIndex();
}
CS_SAFE_DELETE_ARRAY(mpVertexDataBackup);
CS_SAFE_DELETE_ARRAY(mpIndexDataBackup);
}
//-----------------------------------------------------
/// Set Owning Render System
///
/// The owning render system so we may inform it
/// when this mesh buffer is destroyed
///
/// @param Pointer to render system
//-----------------------------------------------------
void CMeshBuffer::SetOwningRenderSystem(CRenderSystem* inpSystem)
{
mpRenderSystem = inpSystem;
}
//-----------------------------------------------------
/// Is Cache Valid
///
/// The owning render system needs to know if the
/// buffer has changed and needs to apply vertex pointers
///
/// @return Has mesh buffer been modifier
//-----------------------------------------------------
bool CMeshBuffer::IsCacheValid() const
{
return mbCacheValid;
}
//-----------------------------------------------------
/// Set Cache Valid
///
/// The owning render system has seen that the
/// buffer has changed and applied vertex pointers
//-----------------------------------------------------
void CMeshBuffer::SetCacheValid()
{
mbCacheValid = true;
}
//-----------------------------------------------------
/// Destructor
///
//-----------------------------------------------------
CMeshBuffer::~CMeshBuffer()
{
if(mpRenderSystem)
{
mpRenderSystem->RemoveBuffer(this);
}
if(CMeshBuffer::pCurrentlyBoundBuffer == this)
{
CMeshBuffer::pCurrentlyBoundBuffer = nullptr;
}
glDeleteBuffers(1, &mVertexBuffer);
if(mIndexBuffer != 0)
{
glDeleteBuffers(1, &mIndexBuffer);
}
mVertexBuffer = 0;
mIndexBuffer = 0;
CS_SAFE_DELETE_ARRAY(mpVertexData);
CS_SAFE_DELETE_ARRAY(mpIndexData);
CS_SAFE_DELETE_ARRAY(mpVertexDataBackup);
CS_SAFE_DELETE_ARRAY(mpIndexDataBackup);
}
}
}
<commit_msg>Added fix for Android mesh buffer restore issue found in moFlow.<commit_after>/*
* GLMeshBuffer.cpp
* moFlo
*
* Created by Scott Downie on 01/10/2010.
* Copyright 2010 Tag Games. All rights reserved.
*
*/
#include <ChilliSource/Backend/Rendering/OpenGL/Base/MeshBuffer.h>
#include <ChilliSource/Backend/Rendering/OpenGL/Base/RenderSystem.h>
namespace ChilliSource
{
namespace OpenGL
{
CMeshBuffer* CMeshBuffer::pCurrentlyBoundBuffer = nullptr;
//-----------------------------------------------------
/// Constructor
///
/// Create a vertex buffer and index buffer from
/// the given buffer description
/// @param Buffer desciption
//-----------------------------------------------------
CMeshBuffer::CMeshBuffer(ChilliSource::Rendering::BufferDescription &inBuffDesc)
: ChilliSource::Rendering::MeshBuffer(inBuffDesc), mVertexBuffer(0), mIndexBuffer(0), mBufferUsage(0), mBufferAccess(0),
mpVertexData(nullptr), mpIndexData(nullptr), mpVertexDataBackup(nullptr), mpIndexDataBackup(nullptr), mbMapBufferAvailable(false), mbCacheValid(false)
{
glGenBuffers(1, &mVertexBuffer);
if(mBufferDesc.IndexDataCapacity > 0)
glGenBuffers(1, &mIndexBuffer);
switch(mBufferDesc.eUsageFlag)
{
case Rendering::BufferUsage::k_dynamic:
mBufferUsage = GL_DYNAMIC_DRAW;
break;
case Rendering::BufferUsage::k_static:
mBufferUsage = GL_STATIC_DRAW;
break;
};
switch(mBufferDesc.eAccessFlag)
{
case Rendering::BufferAccess::k_write:
#ifdef MOFLOW_OPENGL
mBufferAccess = GL_WRITE_ONLY;
#elif defined MOFLOW_OPENGLES2
mBufferAccess = GL_WRITE_ONLY_OES;
#endif
break;
case Rendering::BufferAccess::k_read:
#ifdef MOFLOW_OPENGL
mBufferAccess = GL_WRITE_ONLY;
#elif defined MOFLOW_OPENGLES2
mBufferAccess = GL_WRITE_ONLY_OES;
#endif
break;
case Rendering::BufferAccess::k_readWrite:
default:
#ifdef MOFLOW_OPENGL
mBufferAccess = GL_WRITE_ONLY;
#elif defined MOFLOW_OPENGLES2
mBufferAccess = GL_WRITE_ONLY_OES;
#endif
break;
};
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, nullptr, mBufferUsage);
if(mIndexBuffer != 0)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mBufferDesc.IndexDataCapacity, nullptr, mBufferUsage);
}
CMeshBuffer::pCurrentlyBoundBuffer = this;
}
//-----------------------------------------------------
/// Bind
///
/// Set the active buffer by binding to the context
//-----------------------------------------------------
void CMeshBuffer::Bind()
{
if(CMeshBuffer::pCurrentlyBoundBuffer != this)
{
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
CMeshBuffer::pCurrentlyBoundBuffer = this;
}
}
//-----------------------------------------------------
/// Lock Vertex
///
/// Obtain a handle to the buffer memory in order
/// to map data
/// @param Outputs the pointer to the buffer
/// @param The offset to the subset of the buffer
/// @param The vertex layout stride
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::LockVertex(f32** outppBuffer, u32 inDataOffset, u32 inDataStride)
{
if(mbMapBufferAvailable)
{
if (mBufferDesc.eUsageFlag == Rendering::BufferUsage::k_dynamic)
{
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, nullptr, mBufferUsage);
}
#ifdef MOFLOW_OPENGL
(*outppBuffer) = static_cast<f32*>(glMapBuffer(GL_ARRAY_BUFFER, mBufferAccess));
#elif defined MOFLOW_OPENGLES2
(*outppBuffer) = static_cast<f32*>(glMapBufferOES(GL_ARRAY_BUFFER, mBufferAccess));
#endif
mpVertexData = (*outppBuffer);
}
else
{
if(!mpVertexData)
{
mpVertexData = (f32*)new u8[mBufferDesc.VertexDataCapacity];
}
(*outppBuffer) = mpVertexData;
}
mbCacheValid = false;
return ((*outppBuffer));
}
//-----------------------------------------------------
/// Lock Index
///
/// Obtain a handle to the buffer memory in order
/// to map data
/// @param Outputs the pointer to the buffer
/// @param The offset to the subset of the buffer
/// @param The vertex layout stride
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::LockIndex(u16** outppBuffer, u32 inDataOffset, u32 inDataStride)
{
if(!mIndexBuffer)
{
(*outppBuffer) = nullptr;
return false;
}
if(mbMapBufferAvailable)
{
#ifdef MOFLOW_OPENGL
(*outppBuffer) = static_cast<u16*>(glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferAccess));
#elif defined MOFLOW_OPENGLES2
(*outppBuffer) = static_cast<u16*>(glMapBufferOES(GL_ELEMENT_ARRAY_BUFFER, mBufferAccess));
#endif
mpIndexData = (*outppBuffer);
}
else
{
if(!mpIndexData)
{
mpIndexData = (u16*)new u8[mBufferDesc.IndexDataCapacity];
}
(*outppBuffer) = mpIndexData;
}
mbCacheValid = false;
return ((*outppBuffer));
}
//-----------------------------------------------------
/// Unlock Vertex
///
/// Releases the buffer from mapping
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::UnlockVertex()
{
if(mbMapBufferAvailable)
{
mpVertexData = nullptr;
#ifdef MOFLOW_OPENGL
return glUnmapBuffer(GL_ARRAY_BUFFER);
#elif defined MOFLOW_OPENGLES2
return glUnmapBufferOES(GL_ARRAY_BUFFER);
#endif
}
else
{
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, mpVertexData, mBufferUsage);
return true;
}
}
//-----------------------------------------------------
/// Unlock Index
///
/// Releases the buffer from mapping
/// @return If successful
//-----------------------------------------------------
bool CMeshBuffer::UnlockIndex()
{
if(!mIndexBuffer)
return false;
if(mbMapBufferAvailable)
{
mpIndexData = nullptr;
#ifdef MOFLOW_OPENGL
return glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
#elif defined MOFLOW_OPENGLES2
return glUnmapBufferOES(GL_ELEMENT_ARRAY_BUFFER);
#endif
}
else
{
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mBufferDesc.IndexDataCapacity, mpIndexData, mBufferUsage);
return true;
}
}
//-----------------------------------------------------
/// Set Map Buffer Available
///
/// @param Whether the GL implementation supports
/// the map buffer extension
//-----------------------------------------------------
void CMeshBuffer::SetMapBufferAvailable(bool inbEnabled)
{
mbMapBufferAvailable = inbEnabled;
}
//-----------------------------------------------------
/// Backup
///
/// Backs up the data in the mesh buffer to make
/// sure it is not lost on context loss
//-----------------------------------------------------
void CMeshBuffer::Backup()
{
if(!mpIndexDataBackup)
{
mpIndexDataBackup = (u16*)new u8[mBufferDesc.IndexDataCapacity];
}
//Fill the backup
Bind();
if(!mpVertexDataBackup)
{
mpVertexDataBackup = (f32*)new u8[mBufferDesc.VertexDataCapacity];
}
f32* pVBuffer = nullptr;
LockVertex(&pVBuffer, 0, 0);
memcpy(mpVertexDataBackup, pVBuffer, GetVertexCapacity());
UnlockVertex();
if(mIndexBuffer != 0)
{
if(!mpIndexDataBackup)
{
mpIndexDataBackup = (u16*)new u8[mBufferDesc.IndexDataCapacity];
}
u16* pIBuffer = nullptr;
LockIndex(&pIBuffer, 0, 0);
memcpy(mpIndexDataBackup, pIBuffer, GetIndexCapacity());
UnlockIndex();
}
mVertexBuffer = 0;
mIndexBuffer = 0;
}
//-----------------------------------------------------
/// Restore
///
/// Restore the mesh buffer data from the last
/// backup after the context has been re-created
//-----------------------------------------------------
void CMeshBuffer::Restore()
{
//Force bind as we may have been bound from before context destruction
CMeshBuffer::pCurrentlyBoundBuffer = nullptr;
if(mpVertexDataBackup == nullptr)
{
return;
}
//Check for backups
if(mpVertexDataBackup)
{
glGenBuffers(1, &mVertexBuffer);
}
if(mpIndexDataBackup)
{
glGenBuffers(1, &mIndexBuffer);
}
Bind();
glBufferData(GL_ARRAY_BUFFER, mBufferDesc.VertexDataCapacity, nullptr, mBufferUsage);
f32* pVBuffer = nullptr;
LockVertex(&pVBuffer, 0, 0);
memcpy(pVBuffer, mpVertexDataBackup, GetVertexCapacity());
UnlockVertex();
if(mIndexBuffer != 0)
{
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mBufferDesc.IndexDataCapacity, nullptr, mBufferUsage);
u16* pIBuffer = nullptr;
LockIndex(&pIBuffer, 0, 0);
memcpy(pIBuffer, mpIndexDataBackup, GetIndexCapacity());
UnlockIndex();
}
CS_SAFE_DELETE_ARRAY(mpVertexDataBackup);
CS_SAFE_DELETE_ARRAY(mpIndexDataBackup);
}
//-----------------------------------------------------
/// Set Owning Render System
///
/// The owning render system so we may inform it
/// when this mesh buffer is destroyed
///
/// @param Pointer to render system
//-----------------------------------------------------
void CMeshBuffer::SetOwningRenderSystem(CRenderSystem* inpSystem)
{
mpRenderSystem = inpSystem;
}
//-----------------------------------------------------
/// Is Cache Valid
///
/// The owning render system needs to know if the
/// buffer has changed and needs to apply vertex pointers
///
/// @return Has mesh buffer been modifier
//-----------------------------------------------------
bool CMeshBuffer::IsCacheValid() const
{
return mbCacheValid;
}
//-----------------------------------------------------
/// Set Cache Valid
///
/// The owning render system has seen that the
/// buffer has changed and applied vertex pointers
//-----------------------------------------------------
void CMeshBuffer::SetCacheValid()
{
mbCacheValid = true;
}
//-----------------------------------------------------
/// Destructor
///
//-----------------------------------------------------
CMeshBuffer::~CMeshBuffer()
{
if(mpRenderSystem)
{
mpRenderSystem->RemoveBuffer(this);
}
if(CMeshBuffer::pCurrentlyBoundBuffer == this)
{
CMeshBuffer::pCurrentlyBoundBuffer = nullptr;
}
glDeleteBuffers(1, &mVertexBuffer);
if(mIndexBuffer != 0)
{
glDeleteBuffers(1, &mIndexBuffer);
}
mVertexBuffer = 0;
mIndexBuffer = 0;
CS_SAFE_DELETE_ARRAY(mpVertexData);
CS_SAFE_DELETE_ARRAY(mpIndexData);
CS_SAFE_DELETE_ARRAY(mpVertexDataBackup);
CS_SAFE_DELETE_ARRAY(mpIndexDataBackup);
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fcntl.h>
#include <fstream>
#include <algorithm>
#include <vector>
#include "util/file-system.h"
namespace Util{
static int upperCase(int c){
return toupper(c);
}
std::string upperCaseAll(std::string str){
std::transform(str.begin(), str.end(), str.begin(), upperCase);
return str;
}
Filesystem::AbsolutePath getDataPath2(){
return Filesystem::AbsolutePath(".");
}
}
void testGetFiles(){
std::vector<Filesystem::AbsolutePath> paths = Storage::instance().getFiles(Filesystem::AbsolutePath("data"), Filesystem::RelativePath("m*/*.txt"), false);
for (std::vector<Filesystem::AbsolutePath>::iterator it = paths.begin(); it != paths.end(); it++){
std::cout << it->path() << std::endl;
}
}
void testZip(){
try{
open("/", O_RDONLY, 0);
Storage::instance().addOverlay(Filesystem::AbsolutePath("src/test/util/test.zip"), Filesystem::AbsolutePath("test"));
Util::ReferenceCount<Storage::File> file = Storage::instance().open(Filesystem::AbsolutePath("test/SConstruct"));
char line[1024];
int read = file->readLine(line, sizeof(line) - 1);
line[read] = '\0';
std::cout << "Read '" << std::string(line) << "'" << std::endl;
} catch (const Storage::Exception & fail){
Global::debug(0) << "Zip file error: " << fail.getTrace() << std::endl;
exit(1);
}
}
static void testLastComponent(){
Filesystem::AbsolutePath foo("a/b/c/");
Global::debug(0) << "Last component of " << foo.path() << " is " << foo.getLastComponent() << std::endl;
if (foo.getLastComponent() != "c"){
Global::debug(0) << "Last component failed" << std::endl;
exit(1);
}
}
int main(){
testGetFiles();
testZip();
testLastComponent();
}
<commit_msg>add directory test<commit_after>#include <iostream>
#include <string>
#include <fcntl.h>
#include <fstream>
#include <algorithm>
#include <vector>
#include "util/file-system.h"
namespace Util{
static int upperCase(int c){
return toupper(c);
}
std::string upperCaseAll(std::string str){
std::transform(str.begin(), str.end(), str.begin(), upperCase);
return str;
}
Filesystem::AbsolutePath getDataPath2(){
return Filesystem::AbsolutePath(".");
}
}
void testGetFiles(){
std::vector<Filesystem::AbsolutePath> paths = Storage::instance().getFiles(Filesystem::AbsolutePath("data"), Filesystem::RelativePath("m*/*.txt"), false);
for (std::vector<Filesystem::AbsolutePath>::iterator it = paths.begin(); it != paths.end(); it++){
std::cout << it->path() << std::endl;
}
}
void testZip(){
try{
open("/", O_RDONLY, 0);
Storage::instance().addOverlay(Filesystem::AbsolutePath("src/test/util/test.zip"), Filesystem::AbsolutePath("test"));
Util::ReferenceCount<Storage::File> file = Storage::instance().open(Filesystem::AbsolutePath("test/SConstruct"));
char line[1024];
int read = file->readLine(line, sizeof(line) - 1);
line[read] = '\0';
std::cout << "Read '" << std::string(line) << "'" << std::endl;
} catch (const Storage::Exception & fail){
Global::debug(0) << "Zip file error: " << fail.getTrace() << std::endl;
exit(1);
}
}
static void testLastComponent(){
Filesystem::AbsolutePath foo("a/b/c/");
Global::debug(0) << "Last component of " << foo.path() << " is " << foo.getLastComponent() << std::endl;
if (foo.getLastComponent() != "c"){
Global::debug(0) << "Last component failed" << std::endl;
exit(1);
}
}
static void testDirectory(){
Storage::Directory directory;
class EmptyDescriptor: public Storage::Descriptor {
public:
virtual Util::ReferenceCount<Storage::File> open(Storage::File::Access mode){
return Util::ReferenceCount<Storage::File>(NULL);
}
};
Util::ReferenceCount<Storage::Descriptor> test1(new EmptyDescriptor());
Util::ReferenceCount<Storage::Descriptor> test2(new EmptyDescriptor());
directory.addFile(Filesystem::AbsolutePath("a/b"), test1);
directory.addFile(Filesystem::AbsolutePath("b/a"), test2);
if (directory.lookup(Filesystem::AbsolutePath("a/b")) != test1){
Global::debug(0) << "[1] Directory test failed" << std::endl;
exit(1);
}
if (directory.lookup(Filesystem::AbsolutePath("a/../a/./b")) != test1){
Global::debug(0) << "[2] Directory test failed" << std::endl;
exit(1);
}
if (directory.lookup(Filesystem::AbsolutePath("b/a")) != test2){
Global::debug(0) << "[3] Directory test failed" << std::endl;
exit(1);
}
}
int main(){
testGetFiles();
testZip();
testLastComponent();
testDirectory();
}
<|endoftext|> |
<commit_before>unsigned int rnd() {
unsigned int y = rand();
y <<= 16;
y |= rand();
return y;
}
struct treap{
struct item{
int x, l, r, y;
item(int x): x(x), l(0), r(0), y(rnd()) {}
};
vector<item> t;
inline item& operator[](int i) {
return t[i];
}
inline void apply(int v/*, int add*/) {
//t[v].add += add;
}
inline void push(int v) {
if (v) {
if (t[v].l) apply(t[v].l/*, t[v].add*/);
if (t[v].r) apply(t[v].r/*, t[v].add*/);
//t[v].add = 0;
}
}
int add(item i) {
t.push_back(i);
return t.size() - 1;
}
int add(int key) {
return add(item(key));
}
void merge(int &v, int l, int r) {
push(l);
push(r);
if (!l || !r) {
v = l | r;
} else if (t[l].y > t[r].y) {
v = l;
merge(t[l].r, t[l].r, r);
} else {
v = r;
merge(t[r].l, l, t[r].l);
}
}
void split(int v, int &l, int &r, int key) {
if (v) {
push(v);
if (t[v].x < key) {
l = v;
split(t[l].r, t[l].r, r, key);
} else {
r = v;
split(t[r].l, l, t[r].l, key);
}
} else {
l = r = 0;
}
}
void insert2(int &v, int x) {
if (v) {
push(v);
if (t[x].y > t[v].y) {
split(v, t[x].l, t[x].r, t[x].x);
v = x;
} else {
insert(t[x].x < t[v].x ? t[v].l : t[v].r, x);
}
} else {
v = x;
}
}
inline void insert(int &v, int x) {
if (v) {
int t1;
split(v, v, t1, t[x].x);
merge(v, v, x);
merge(v, v, t1);
} else {
v = x;
}
}
void transfer(int from, int &to) {
if (!from) return;
queue<int> q;
q.push(from);
while (!q.empty()) {
int v = q.front();
q.pop();
push(v);
if (t[v].l) q.push(t[v].l);
if (t[v].r) q.push(t[v].r);
t[v].l = t[v].r = 0;
insert(to, v);
}
}
void unite(int &v, int l, int r) {
if (!l || !r) {
v = l | r;
} else {
push(l);
push(r);
if (t[l].y < t[r].y) swap(l, r);
int lx, rx;
split(r, lx, rx, t[l].x);
unite(t[l].l, t[l].l, lx);
unite(t[l].r, t[l].r, rx);
v = l;
}
}
template<typename F>
void walk(int v, F &lambda) {
if (v) {
push(v);
walk(t[v].l, lambda);
lambda(t[v]);
walk(t[v].r, lambda);
}
}
treap() {
t.push_back(item(0));
}
};
<commit_msg>fixed insert2<commit_after>unsigned int rnd() {
unsigned int y = rand();
y <<= 16;
y |= rand();
return y;
}
struct treap{
struct item{
int x, l, r, y;
item(int x): x(x), l(0), r(0), y(rnd()) {}
};
vector<item> t;
inline item& operator[](int i) {
return t[i];
}
inline void apply(int v/*, int add*/) {
//t[v].add += add;
}
inline void push(int v) {
if (v) {
if (t[v].l) apply(t[v].l/*, t[v].add*/);
if (t[v].r) apply(t[v].r/*, t[v].add*/);
//t[v].add = 0;
}
}
int add(item i) {
t.push_back(i);
return t.size() - 1;
}
int add(int key) {
return add(item(key));
}
void merge(int &v, int l, int r) {
push(l);
push(r);
if (!l || !r) {
v = l | r;
} else if (t[l].y > t[r].y) {
v = l;
merge(t[l].r, t[l].r, r);
} else {
v = r;
merge(t[r].l, l, t[r].l);
}
}
void split(int v, int &l, int &r, int key) {
if (v) {
push(v);
if (t[v].x < key) {
l = v;
split(t[l].r, t[l].r, r, key);
} else {
r = v;
split(t[r].l, l, t[r].l, key);
}
} else {
l = r = 0;
}
}
void insert2(int &v, int x) {
if (v) {
push(v);
if (t[x].y > t[v].y) {
split(v, t[x].l, t[x].r, t[x].x);
v = x;
} else {
insert2(t[x].x < t[v].x ? t[v].l : t[v].r, x);
}
} else {
v = x;
}
}
inline void insert(int &v, int x) {
if (v) {
int t1;
split(v, v, t1, t[x].x);
merge(v, v, x);
merge(v, v, t1);
} else {
v = x;
}
}
void transfer(int from, int &to) {
if (!from) return;
queue<int> q;
q.push(from);
while (!q.empty()) {
int v = q.front();
q.pop();
push(v);
if (t[v].l) q.push(t[v].l);
if (t[v].r) q.push(t[v].r);
t[v].l = t[v].r = 0;
insert(to, v);
}
}
void unite(int &v, int l, int r) {
if (!l || !r) {
v = l | r;
} else {
push(l);
push(r);
if (t[l].y < t[r].y) swap(l, r);
int lx, rx;
split(r, lx, rx, t[l].x);
unite(t[l].l, t[l].l, lx);
unite(t[l].r, t[l].r, rx);
v = l;
}
}
template<typename F>
void walk(int v, F &lambda) {
if (v) {
push(v);
walk(t[v].l, lambda);
lambda(t[v]);
walk(t[v].r, lambda);
}
}
treap() {
t.push_back(item(0));
}
};
<|endoftext|> |
<commit_before>
#include <iostream>
#include <string.h>
#include <SDL.h>
#include <SDL_audio.h>
#include <akPGTA.h>
#include <queue>
#include "FileUtils.h"
#include "utils.h"
#include "AudioBuffer.h"
int pgtaMain(SDL_AudioDeviceID audioDevice, AudioBuffer* audioOut)
{
PGTA::PGTADevice pgtaDevice;
if (!pgtaDevice.Initialize())
{
return -1;
}
// load track data to memory
// "tracks/demo.track"
std::string trackSource;
if (!ReadBinaryFileToString("tracks/rain_thunder.track", trackSource))
{
return -1;
}
HPGTATrack demoTrack = nullptr;
const char* source = trackSource.data();
const size_t length = trackSource.length();
if (pgtaDevice.CreateTracks(1, &source, &length, &demoTrack) <= 0 || !demoTrack)
{
return -1;
}
PGTAConfig config;
config.audioDesc.samplesPerSecond = 44100;
config.audioDesc.bytesPerSample = 2;
config.audioDesc.channels = 1;
config.numBuffers = 4;
config.bufferSizeInSamples = 8192;
PGTA::PGTAContext pgtaContext(pgtaDevice.CreateContext(config));
//pgtaContext.BindTrack(demoTrack);
utils::RunLoop(10.0f, [&](double absoluteTime, float delta)
{
int32_t numBuffers = 0;
const PGTABuffer* buffers = pgtaContext.Update(delta, &numBuffers);
for (int32_t i = 0; i < numBuffers; ++i)
{
const PGTABuffer& buf = buffers[i];
const int16_t* samples = reinterpret_cast<const int16_t*>(buf.samples);
SDL_LockAudioDevice(audioDevice);
if (audioOut->PushSamples(samples, buf.numSamples) < 0)
{
printf("PushSamples failed!\n");
}
SDL_UnlockAudioDevice(audioDevice);
}
return (buffers != nullptr);
});
return 0;
}
int main(int argc, char *argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);
AudioBuffer audioBuffer;
SDL_AudioSpec audioSpec;
SDL_zero(audioSpec);
audioSpec.freq = 44100;
audioSpec.format = AUDIO_S16;
audioSpec.channels = 1;
audioSpec.samples = 4096;
audioSpec.callback = [](void *userdata, Uint8* stream, int len)
{
AudioBuffer* buffer = reinterpret_cast<AudioBuffer*>(userdata);
int16_t* samples = reinterpret_cast<int16_t*>(stream);
const int samplesToWrite = len / sizeof(int16_t);
const int samplesWritten = buffer->PopSamples(samples, samplesToWrite);
// write silence for unfilled samples
if (samplesWritten < 0)
{
printf("PopSamples failed!\n");
memset(stream, 0, len);
}
else if (samplesWritten < samplesToWrite)
{
const int bytesWritten = samplesWritten * 2;
memset(stream + bytesWritten, 0, len - bytesWritten);
}
};
audioSpec.userdata = &audioBuffer;
SDL_AudioDeviceID audioDevice = SDL_OpenAudioDevice(nullptr, false, &audioSpec, nullptr, 0);
int ret = 0;
if (audioDevice > 0)
{
SDL_PauseAudioDevice(audioDevice, 0);
ret = pgtaMain(audioDevice, &audioBuffer);
SDL_CloseAudioDevice(audioDevice);
}
SDL_Quit();
return ret;
}
<commit_msg>Made use of SDL_QueueAudio instead of callbacks<commit_after>
#include <iostream>
#include <string.h>
#include <SDL.h>
#include <SDL_audio.h>
#include <akPGTA.h>
#include <queue>
#include "FileUtils.h"
#include "utils.h"
int pgtaMain(SDL_AudioDeviceID audioDevice)
{
PGTA::PGTADevice pgtaDevice;
if (!pgtaDevice.Initialize())
{
return -1;
}
// load track data to memory
// "tracks/demo.track"
std::string trackSource;
if (!ReadBinaryFileToString("tracks/rain_thunder.track", trackSource))
{
return -1;
}
HPGTATrack demoTrack = nullptr;
const char* source = trackSource.data();
const size_t length = trackSource.length();
if (pgtaDevice.CreateTracks(1, &source, &length, &demoTrack) <= 0 || !demoTrack)
{
return -1;
}
PGTAConfig config;
config.audioDesc.samplesPerSecond = 44100;
config.audioDesc.bytesPerSample = 2;
config.audioDesc.channels = 1;
config.numBuffers = 4;
config.bufferSizeInSamples = 8192;
PGTA::PGTAContext pgtaContext(pgtaDevice.CreateContext(config));
//pgtaContext.BindTrack(demoTrack);
utils::RunLoop(10.0f, [&](double absoluteTime, float delta)
{
int32_t numBuffers = 0;
const PGTABuffer* buffers = pgtaContext.Update(delta, &numBuffers);
for (int32_t i = 0; i < numBuffers; ++i)
{
const PGTABuffer& buf = buffers[i];
const int16_t* samples = reinterpret_cast<const int16_t*>(buf.samples);
SDL_QueueAudio(audioDevice, samples, buf.numSamples*2);
}
return (buffers != nullptr);
});
return 0;
}
int main(int argc, char *argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_AudioSpec audioSpec;
SDL_zero(audioSpec);
audioSpec.freq = 44100;
audioSpec.format = AUDIO_S16;
audioSpec.channels = 1;
audioSpec.samples = 4096;
SDL_AudioDeviceID audioDevice = SDL_OpenAudioDevice(nullptr, false, &audioSpec, nullptr, 0);
int ret = 0;
if (audioDevice > 0)
{
SDL_PauseAudioDevice(audioDevice, 0);
ret = pgtaMain(audioDevice);
SDL_CloseAudioDevice(audioDevice);
}
SDL_Quit();
return ret;
}
<|endoftext|> |
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH
#define DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH
#ifdef HAVE_EIGEN
// eigen
#include <Eigen/Core>
#include <Eigen/Sparse>
// dune-common
#include <dune/common/shared_ptr.hh>
namespace Dune {
namespace DetailedDiscretizations {
namespace LA {
namespace Backend {
namespace Container {
namespace Eigen {
template <class EntryImp>
class SparseMatrix
{
public:
typedef EntryImp EntryType;
typedef SparseMatrix<EntryType> ThisType;
typedef ::Eigen::SparseMatrix<EntryType> StorageType;
SparseMatrix(unsigned int rows, unsigned int cols)
: rows_(rows)
, cols_(cols)
, storage_(new StorageType(rows_, cols_))
{
}
SparseMatrix(Dune::shared_ptr<StorageType> storage)
: rows_(storage->rows())
, cols_(storage->cols())
, storage_(storage)
{
}
SparseMatrix(const ThisType& other)
: rows_(other.rows())
, cols_(other.cols())
, storage_(other.storage())
{
}
ThisType& operator=(const ThisType& other)
{
rows_ = other.rows();
cols_ = other.cols();
storage_ = other.storage();
return *this;
}
unsigned int rows() const
{
return rows_;
}
unsigned int cols() const
{
return cols_;
}
Dune::shared_ptr<StorageType> storage()
{
return storage_;
}
const Dune::shared_ptr<StorageType> storage() const
{
return storage_;
}
void reserve(unsigned int nnz)
{
storage_->reserve(nnz);
}
void add(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->coeffRef(i, j) += val;
}
void set(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->coeffRef(i, j) = val;
}
const EntryType get(unsigned int i, unsigned int j) const
{
return storage_->coeff(i, j);
}
private:
unsigned int rows_;
unsigned int cols_;
Dune::shared_ptr<StorageType> storage_;
}; // class SparseMatrix
template <class EntryImp>
class DenseMatrix;
template <>
class DenseMatrix<double>
{
public:
typedef double EntryType;
typedef DenseMatrix<EntryType> ThisType;
typedef ::Eigen::MatrixXd StorageType;
DenseMatrix(unsigned int rows, unsigned int cols)
: rows_(rows)
, cols_(cols)
, storage_(new StorageType(rows_, cols_))
{
}
DenseMatrix(Dune::shared_ptr<StorageType> storage)
: rows_(storage->rows())
, cols_(storage->cols())
, storage_(storage)
{
}
DenseMatrix(const ThisType& other)
: rows_(other.rows())
, cols_(other.cols())
, storage_(other.storage())
{
}
ThisType& operator=(const ThisType& other)
{
rows_ = other.rows();
cols_ = other.cols();
storage_ = other.storage();
return *this;
}
unsigned int rows() const
{
return rows_;
}
unsigned int cols() const
{
return cols_;
}
Dune::shared_ptr<StorageType> storage()
{
return storage_;
}
const Dune::shared_ptr<StorageType> storage() const
{
return storage_;
}
void reserve()
{
storage_->operator=(StorageType::Zero(rows(), cols()));
}
void add(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->operator()(i, j) += val;
}
void set(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->operator()(i, j) = val;
}
const EntryType get(unsigned int i, unsigned int j) const
{
return storage_->operator()(i, j);
}
private:
unsigned int rows_;
unsigned int cols_;
Dune::shared_ptr<StorageType> storage_;
}; // class DenseMatrix
template <class EntryImp>
class DenseVector;
template <>
class DenseVector<double>
{
public:
typedef double EntryType;
typedef DenseVector<EntryType> ThisType;
typedef ::Eigen::VectorXd StorageType;
DenseVector(unsigned int size)
: size_(size)
, storage_(new StorageType(size_))
{
}
DenseVector(Dune::shared_ptr<StorageType> storage)
: size_(storage->rows())
, storage_(storage)
{
}
DenseVector(const ThisType& other)
: size_(other.size())
, storage_(other.storage())
{
}
ThisType& operator=(const ThisType& other)
{
size_ = other.size();
storage_ = other.storage();
return *this;
}
unsigned int size() const
{
return size_;
}
Dune::shared_ptr<StorageType> storage()
{
return storage_;
}
const Dune::shared_ptr<StorageType> storage() const
{
return storage_;
}
void reserve()
{
storage_->operator=(StorageType::Zero(size()));
}
void add(unsigned int i, const EntryType& val)
{
storage_->operator()(i) += val;
}
void set(unsigned int i, const EntryType& val)
{
storage_->operator()(i) = val;
}
const EntryType get(unsigned int i) const
{
return storage_->operator()(i);
}
private:
unsigned int size_;
Dune::shared_ptr<StorageType> storage_;
}; // class DenseVector
} // namespace Container
} // namespace Eigen
} // namespace Backend
} // namespace LA
} // namespace DetailedDiscretizations
} // namespace Dune
#endif // HAVE_EIGEN
#endif // DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH
<commit_msg>[la.backend.container.eigen] added operator[] to DenseVector<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH
#define DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH
#ifdef HAVE_EIGEN
// eigen
#include <Eigen/Core>
#include <Eigen/Sparse>
// dune-common
#include <dune/common/shared_ptr.hh>
namespace Dune {
namespace DetailedDiscretizations {
namespace LA {
namespace Backend {
namespace Container {
namespace Eigen {
template <class EntryImp>
class SparseMatrix
{
public:
typedef EntryImp EntryType;
typedef SparseMatrix<EntryType> ThisType;
typedef ::Eigen::SparseMatrix<EntryType> StorageType;
SparseMatrix(unsigned int rows, unsigned int cols)
: rows_(rows)
, cols_(cols)
, storage_(new StorageType(rows_, cols_))
{
}
SparseMatrix(Dune::shared_ptr<StorageType> storage)
: rows_(storage->rows())
, cols_(storage->cols())
, storage_(storage)
{
}
SparseMatrix(const ThisType& other)
: rows_(other.rows())
, cols_(other.cols())
, storage_(other.storage())
{
}
ThisType& operator=(const ThisType& other)
{
rows_ = other.rows();
cols_ = other.cols();
storage_ = other.storage();
return *this;
}
unsigned int rows() const
{
return rows_;
}
unsigned int cols() const
{
return cols_;
}
Dune::shared_ptr<StorageType> storage()
{
return storage_;
}
const Dune::shared_ptr<StorageType> storage() const
{
return storage_;
}
void reserve(unsigned int nnz)
{
storage_->reserve(nnz);
}
void add(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->coeffRef(i, j) += val;
}
void set(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->coeffRef(i, j) = val;
}
const EntryType get(unsigned int i, unsigned int j) const
{
return storage_->coeff(i, j);
}
private:
unsigned int rows_;
unsigned int cols_;
Dune::shared_ptr<StorageType> storage_;
}; // class SparseMatrix
template <class EntryImp>
class DenseMatrix;
template <>
class DenseMatrix<double>
{
public:
typedef double EntryType;
typedef DenseMatrix<EntryType> ThisType;
typedef ::Eigen::MatrixXd StorageType;
DenseMatrix(unsigned int rows, unsigned int cols)
: rows_(rows)
, cols_(cols)
, storage_(new StorageType(rows_, cols_))
{
}
DenseMatrix(Dune::shared_ptr<StorageType> storage)
: rows_(storage->rows())
, cols_(storage->cols())
, storage_(storage)
{
}
DenseMatrix(const ThisType& other)
: rows_(other.rows())
, cols_(other.cols())
, storage_(other.storage())
{
}
ThisType& operator=(const ThisType& other)
{
rows_ = other.rows();
cols_ = other.cols();
storage_ = other.storage();
return *this;
}
unsigned int rows() const
{
return rows_;
}
unsigned int cols() const
{
return cols_;
}
Dune::shared_ptr<StorageType> storage()
{
return storage_;
}
const Dune::shared_ptr<StorageType> storage() const
{
return storage_;
}
void reserve()
{
storage_->operator=(StorageType::Zero(rows(), cols()));
}
void add(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->operator()(i, j) += val;
}
void set(unsigned int i, unsigned int j, const EntryType& val)
{
storage_->operator()(i, j) = val;
}
const EntryType get(unsigned int i, unsigned int j) const
{
return storage_->operator()(i, j);
}
private:
unsigned int rows_;
unsigned int cols_;
Dune::shared_ptr<StorageType> storage_;
}; // class DenseMatrix
template <class EntryImp>
class DenseVector;
template <>
class DenseVector<double>
{
public:
typedef double EntryType;
typedef DenseVector<EntryType> ThisType;
typedef ::Eigen::VectorXd StorageType;
DenseVector(unsigned int size)
: size_(size)
, storage_(new StorageType(size_))
{
}
DenseVector(Dune::shared_ptr<StorageType> storage)
: size_(storage->rows())
, storage_(storage)
{
}
DenseVector(const ThisType& other)
: size_(other.size())
, storage_(other.storage())
{
}
ThisType& operator=(const ThisType& other)
{
size_ = other.size();
storage_ = other.storage();
return *this;
}
unsigned int size() const
{
return size_;
}
Dune::shared_ptr<StorageType> storage()
{
return storage_;
}
const Dune::shared_ptr<StorageType> storage() const
{
return storage_;
}
void reserve()
{
storage_->operator=(StorageType::Zero(size()));
}
void add(unsigned int i, const EntryType& val)
{
storage_->operator()(i) += val;
}
void set(unsigned int i, const EntryType& val)
{
storage_->operator()(i) = val;
}
const EntryType get(unsigned int i) const
{
return storage_->operator()(i);
}
const EntryType& operator[](unsigned int i) const
{
return storage_->coeff(i);
}
EntryType& operator[](unsigned int i)
{
return storage_->coeffRef(i);
}
private:
unsigned int size_;
Dune::shared_ptr<StorageType> storage_;
}; // class DenseVector
} // namespace Container
} // namespace Eigen
} // namespace Backend
} // namespace LA
} // namespace DetailedDiscretizations
} // namespace Dune
#endif // HAVE_EIGEN
#endif // DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2010 VMware, Inc.
* All Rights Reserved.
*
* 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.
*
**************************************************************************/
#ifdef _WIN32
#include <windows.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <string>
#include "os.hpp"
#include "os_string.hpp"
namespace os {
String
getProcessName(void)
{
String path;
DWORD size = MAX_PATH;
char *buf = path.buf(size);
DWORD nWritten = GetModuleFileNameA(NULL, buf, size);
(void)nWritten;
path.truncate();
return path;
}
String
getCurrentDir(void)
{
String path;
DWORD size = MAX_PATH;
char *buf = path.buf(size);
DWORD ret = GetCurrentDirectoryA(size, buf);
(void)ret;
buf[size - 1] = 0;
path.truncate();
return path;
}
bool
createDirectory(const String &path)
{
return CreateDirectoryA(path, NULL);
}
bool
String::exists(void) const
{
DWORD attrs = GetFileAttributesA(str());
return attrs != INVALID_FILE_ATTRIBUTES;
}
bool
copyFile(const String &srcFileName, const String &dstFileName, bool override)
{
return CopyFileA(srcFileName, dstFileName, !override);
}
bool
removeFile(const String &srcFilename)
{
return DeleteFileA(srcFilename);
}
/**
* Determine whether an argument should be quoted.
*/
static bool
needsQuote(const char *arg)
{
char c;
while (true) {
c = *arg++;
if (c == '\0') {
break;
}
if (c == ' ' || c == '\t' || c == '\"') {
return true;
}
if (c == '\\') {
c = *arg++;
if (c == '\0') {
break;
}
if (c == '"') {
return true;
}
}
}
return false;
}
static void
quoteArg(std::string &s, const char *arg)
{
char c;
unsigned backslashes = 0;
s.push_back('"');
while (true) {
c = *arg++;
if (c == '\0') {
break;
} else if (c == '"') {
while (backslashes) {
s.push_back('\\');
--backslashes;
}
s.push_back('\\');
} else {
if (c == '\\') {
++backslashes;
} else {
backslashes = 0;
}
}
s.push_back(c);
}
s.push_back('"');
}
int execute(char * const * args)
{
std::string commandLine;
const char *arg0 = *args;
const char *arg;
char sep = 0;
while ((arg = *args++) != NULL) {
if (sep) {
commandLine.push_back(sep);
}
if (needsQuote(arg)) {
quoteArg(commandLine, arg);
} else {
commandLine.append(arg);
}
sep = ' ';
}
STARTUPINFOA startupInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
if (!CreateProcessA(NULL,
const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
0, // process attributes
0, // thread attributes
FALSE, // inherit handles
0, // creation flags,
NULL, // environment
NULL, // current directory
&startupInfo,
&processInformation
)) {
log("error: failed to execute %s\n", arg0);
return -1;
}
WaitForSingleObject(processInformation.hProcess, INFINITE);
DWORD exitCode = ~0UL;
GetExitCodeProcess(processInformation.hProcess, &exitCode);
CloseHandle(processInformation.hProcess);
CloseHandle(processInformation.hThread);
return (int)exitCode;
}
#ifndef HAVE_EXTERNAL_OS_LOG
void
log(const char *format, ...)
{
char buf[4096];
va_list ap;
va_start(ap, format);
fflush(stdout);
vsnprintf(buf, sizeof buf, format, ap);
va_end(ap);
OutputDebugStringA(buf);
/*
* Also write the message to stderr, when a debugger is not present (to
* avoid duplicate messages in command line debuggers).
*/
#if _WIN32_WINNT > 0x0400
if (!IsDebuggerPresent()) {
fflush(stdout);
fputs(buf, stderr);
fflush(stderr);
}
#endif
}
#endif /* !HAVE_EXTERNAL_OS_LOG */
long long timeFrequency = 0LL;
void
abort(void)
{
TerminateProcess(GetCurrentProcess(), 1);
}
#ifndef DBG_PRINTEXCEPTION_C
#define DBG_PRINTEXCEPTION_C 0x40010006
#endif
static PVOID prevExceptionFilter = NULL;
static void (*gCallback)(void) = NULL;
static LONG CALLBACK
unhandledExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
PEXCEPTION_RECORD pExceptionRecord = pExceptionInfo->ExceptionRecord;
/*
* Ignore OutputDebugStringA exception.
*/
if (pExceptionRecord->ExceptionCode == DBG_PRINTEXCEPTION_C) {
return EXCEPTION_CONTINUE_SEARCH;
}
/*
* Ignore C++ exceptions
*
* http://support.microsoft.com/kb/185294
* http://blogs.msdn.com/b/oldnewthing/archive/2010/07/30/10044061.aspx
*/
if (pExceptionRecord->ExceptionCode == 0xe06d7363) {
return EXCEPTION_CONTINUE_SEARCH;
}
/*
* Ignore thread naming exception.
*
* http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
*/
if (pExceptionRecord->ExceptionCode == 0x406d1388) {
return EXCEPTION_CONTINUE_SEARCH;
}
/*
* Ignore .NET exception.
*
* http://ig2600.blogspot.co.uk/2011/01/why-do-i-keep-getting-exception-code.html
*/
if (pExceptionRecord->ExceptionCode == 0xe0434352) {
return EXCEPTION_CONTINUE_SEARCH;
}
// Clear direction flag
#ifdef _MSC_VER
#ifndef _WIN64
__asm {
cld
};
#endif
#else
asm("cld");
#endif
log("apitrace: warning: caught exception 0x%08lx\n", pExceptionRecord->ExceptionCode);
static int recursion_count = 0;
if (recursion_count) {
fputs("apitrace: warning: recursion handling exception\n", stderr);
} else {
if (gCallback) {
++recursion_count;
gCallback();
--recursion_count;
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
void
setExceptionCallback(void (*callback)(void))
{
assert(!gCallback);
if (!gCallback) {
gCallback = callback;
assert(!prevExceptionFilter);
prevExceptionFilter = AddVectoredExceptionHandler(0, unhandledExceptionHandler);
}
}
void
resetExceptionCallback(void)
{
if (gCallback) {
RemoveVectoredExceptionHandler(prevExceptionFilter);
gCallback = NULL;
}
}
} /* namespace os */
#endif // defined(_WIN32)
<commit_msg>os: Silence ‘noreturn’ function does return warning.<commit_after>/**************************************************************************
*
* Copyright 2010 VMware, Inc.
* All Rights Reserved.
*
* 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.
*
**************************************************************************/
#ifdef _WIN32
#include <windows.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <string>
#include "os.hpp"
#include "os_string.hpp"
namespace os {
String
getProcessName(void)
{
String path;
DWORD size = MAX_PATH;
char *buf = path.buf(size);
DWORD nWritten = GetModuleFileNameA(NULL, buf, size);
(void)nWritten;
path.truncate();
return path;
}
String
getCurrentDir(void)
{
String path;
DWORD size = MAX_PATH;
char *buf = path.buf(size);
DWORD ret = GetCurrentDirectoryA(size, buf);
(void)ret;
buf[size - 1] = 0;
path.truncate();
return path;
}
bool
createDirectory(const String &path)
{
return CreateDirectoryA(path, NULL);
}
bool
String::exists(void) const
{
DWORD attrs = GetFileAttributesA(str());
return attrs != INVALID_FILE_ATTRIBUTES;
}
bool
copyFile(const String &srcFileName, const String &dstFileName, bool override)
{
return CopyFileA(srcFileName, dstFileName, !override);
}
bool
removeFile(const String &srcFilename)
{
return DeleteFileA(srcFilename);
}
/**
* Determine whether an argument should be quoted.
*/
static bool
needsQuote(const char *arg)
{
char c;
while (true) {
c = *arg++;
if (c == '\0') {
break;
}
if (c == ' ' || c == '\t' || c == '\"') {
return true;
}
if (c == '\\') {
c = *arg++;
if (c == '\0') {
break;
}
if (c == '"') {
return true;
}
}
}
return false;
}
static void
quoteArg(std::string &s, const char *arg)
{
char c;
unsigned backslashes = 0;
s.push_back('"');
while (true) {
c = *arg++;
if (c == '\0') {
break;
} else if (c == '"') {
while (backslashes) {
s.push_back('\\');
--backslashes;
}
s.push_back('\\');
} else {
if (c == '\\') {
++backslashes;
} else {
backslashes = 0;
}
}
s.push_back(c);
}
s.push_back('"');
}
int execute(char * const * args)
{
std::string commandLine;
const char *arg0 = *args;
const char *arg;
char sep = 0;
while ((arg = *args++) != NULL) {
if (sep) {
commandLine.push_back(sep);
}
if (needsQuote(arg)) {
quoteArg(commandLine, arg);
} else {
commandLine.append(arg);
}
sep = ' ';
}
STARTUPINFOA startupInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
if (!CreateProcessA(NULL,
const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
0, // process attributes
0, // thread attributes
FALSE, // inherit handles
0, // creation flags,
NULL, // environment
NULL, // current directory
&startupInfo,
&processInformation
)) {
log("error: failed to execute %s\n", arg0);
return -1;
}
WaitForSingleObject(processInformation.hProcess, INFINITE);
DWORD exitCode = ~0UL;
GetExitCodeProcess(processInformation.hProcess, &exitCode);
CloseHandle(processInformation.hProcess);
CloseHandle(processInformation.hThread);
return (int)exitCode;
}
#ifndef HAVE_EXTERNAL_OS_LOG
void
log(const char *format, ...)
{
char buf[4096];
va_list ap;
va_start(ap, format);
fflush(stdout);
vsnprintf(buf, sizeof buf, format, ap);
va_end(ap);
OutputDebugStringA(buf);
/*
* Also write the message to stderr, when a debugger is not present (to
* avoid duplicate messages in command line debuggers).
*/
#if _WIN32_WINNT > 0x0400
if (!IsDebuggerPresent()) {
fflush(stdout);
fputs(buf, stderr);
fflush(stderr);
}
#endif
}
#endif /* !HAVE_EXTERNAL_OS_LOG */
long long timeFrequency = 0LL;
void
abort(void)
{
TerminateProcess(GetCurrentProcess(), 1);
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
__builtin_unreachable();
#endif
}
#ifndef DBG_PRINTEXCEPTION_C
#define DBG_PRINTEXCEPTION_C 0x40010006
#endif
static PVOID prevExceptionFilter = NULL;
static void (*gCallback)(void) = NULL;
static LONG CALLBACK
unhandledExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
PEXCEPTION_RECORD pExceptionRecord = pExceptionInfo->ExceptionRecord;
/*
* Ignore OutputDebugStringA exception.
*/
if (pExceptionRecord->ExceptionCode == DBG_PRINTEXCEPTION_C) {
return EXCEPTION_CONTINUE_SEARCH;
}
/*
* Ignore C++ exceptions
*
* http://support.microsoft.com/kb/185294
* http://blogs.msdn.com/b/oldnewthing/archive/2010/07/30/10044061.aspx
*/
if (pExceptionRecord->ExceptionCode == 0xe06d7363) {
return EXCEPTION_CONTINUE_SEARCH;
}
/*
* Ignore thread naming exception.
*
* http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
*/
if (pExceptionRecord->ExceptionCode == 0x406d1388) {
return EXCEPTION_CONTINUE_SEARCH;
}
/*
* Ignore .NET exception.
*
* http://ig2600.blogspot.co.uk/2011/01/why-do-i-keep-getting-exception-code.html
*/
if (pExceptionRecord->ExceptionCode == 0xe0434352) {
return EXCEPTION_CONTINUE_SEARCH;
}
// Clear direction flag
#ifdef _MSC_VER
#ifndef _WIN64
__asm {
cld
};
#endif
#else
asm("cld");
#endif
log("apitrace: warning: caught exception 0x%08lx\n", pExceptionRecord->ExceptionCode);
static int recursion_count = 0;
if (recursion_count) {
fputs("apitrace: warning: recursion handling exception\n", stderr);
} else {
if (gCallback) {
++recursion_count;
gCallback();
--recursion_count;
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
void
setExceptionCallback(void (*callback)(void))
{
assert(!gCallback);
if (!gCallback) {
gCallback = callback;
assert(!prevExceptionFilter);
prevExceptionFilter = AddVectoredExceptionHandler(0, unhandledExceptionHandler);
}
}
void
resetExceptionCallback(void)
{
if (gCallback) {
RemoveVectoredExceptionHandler(prevExceptionFilter);
gCallback = NULL;
}
}
} /* namespace os */
#endif // defined(_WIN32)
<|endoftext|> |
<commit_before>/*!
*
* Copyright (C) 2012 Jolla Ltd.
*
* Contact: Mohammed Hassan <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "griloregistry.h"
#include <QDebug>
GriloRegistry::GriloRegistry(QObject *parent) :
QObject(parent),
m_registry(0) {
grl_init(0, 0);
}
GriloRegistry::~GriloRegistry() {
foreach (const QString &source, m_sources) {
GrlSource *src = lookupSource(source);
if (src) {
g_signal_handlers_disconnect_by_data(src, this);
}
}
g_signal_handlers_disconnect_by_data(m_registry, this);
m_registry = 0;
}
void GriloRegistry::classBegin() {
}
void GriloRegistry::componentComplete() {
m_registry = grl_registry_get_default();
g_signal_connect(m_registry, "source-added", G_CALLBACK(grilo_source_added), this);
g_signal_connect(m_registry, "source-removed", G_CALLBACK(grilo_source_removed), this);
GList *sources = grl_registry_get_sources(m_registry, FALSE);
g_list_foreach(sources, connect_source, this);
g_list_free(sources);
loadConfigurationFile();
}
QStringList GriloRegistry::availableSources() {
return m_sources;
}
bool GriloRegistry::loadAll() {
// TODO: error reporting
return grl_registry_load_all_plugins(m_registry, NULL) == TRUE;
}
QString GriloRegistry::configurationFile() const {
return m_configurationFile;
}
void GriloRegistry::setConfigurationFile(const QString& file) {
if (m_configurationFile != file) {
m_configurationFile = file;
emit configurationFileChanged();
if (m_registry) {
loadConfigurationFile();
}
}
}
void GriloRegistry::loadConfigurationFile() {
if (!m_configurationFile.isEmpty() && m_registry) {
grl_registry_add_config_from_file(m_registry, m_configurationFile.toLocal8Bit().constData(),
NULL);
}
}
void GriloRegistry::connect_source(gpointer data, gpointer user_data)
{
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
grilo_source_added(reg->m_registry, static_cast<GrlSource *>(data), user_data);
}
void GriloRegistry::grilo_source_added(GrlRegistry *registry, GrlSource *src,
gpointer user_data) {
Q_UNUSED(registry);
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
const char *id = grl_source_get_id(src);
if (reg->m_sources.indexOf(id) == -1) {
reg->m_sources << id;
g_signal_connect(src, "content-changed", G_CALLBACK(grilo_content_changed_cb), reg);
grl_source_notify_change_start(src, 0);
emit reg->availableSourcesChanged();
}
}
void GriloRegistry::grilo_source_removed(GrlRegistry *registry, GrlSource *src,
gpointer user_data) {
Q_UNUSED(registry);
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
const char *id = grl_source_get_id(src);
if (int index = reg->m_sources.indexOf(id) != -1) {
reg->m_sources.removeAt(index);
g_signal_handlers_disconnect_by_data(src, reg);
emit reg->availableSourcesChanged();
}
}
void GriloRegistry::grilo_content_changed_cb(GrlSource *source, GPtrArray *changed_media,
GrlSourceChangeType change_type, gboolean location_unknown,
gpointer user_data) {
Q_UNUSED(location_unknown);
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
const char *id = grl_source_get_id(source);
emit reg->contentChanged(id, change_type, changed_media);
}
GrlSource *GriloRegistry::lookupSource(const QString& id) {
if (m_registry) {
return grl_registry_lookup_source(m_registry, id.toUtf8().constData());
}
return 0;
}
<commit_msg>[registry] Added more debugging output<commit_after>/*!
*
* Copyright (C) 2012 Jolla Ltd.
*
* Contact: Mohammed Hassan <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "griloregistry.h"
#include <QDebug>
GriloRegistry::GriloRegistry(QObject *parent) :
QObject(parent),
m_registry(0) {
grl_init(0, 0);
}
GriloRegistry::~GriloRegistry() {
foreach (const QString &source, m_sources) {
GrlSource *src = lookupSource(source);
if (src) {
g_signal_handlers_disconnect_by_data(src, this);
}
}
g_signal_handlers_disconnect_by_data(m_registry, this);
m_registry = 0;
}
void GriloRegistry::classBegin() {
}
void GriloRegistry::componentComplete() {
m_registry = grl_registry_get_default();
g_signal_connect(m_registry, "source-added", G_CALLBACK(grilo_source_added), this);
g_signal_connect(m_registry, "source-removed", G_CALLBACK(grilo_source_removed), this);
GList *sources = grl_registry_get_sources(m_registry, FALSE);
g_list_foreach(sources, connect_source, this);
g_list_free(sources);
loadConfigurationFile();
}
QStringList GriloRegistry::availableSources() {
return m_sources;
}
bool GriloRegistry::loadAll() {
// TODO: error reporting
return grl_registry_load_all_plugins(m_registry, NULL) == TRUE;
}
QString GriloRegistry::configurationFile() const {
return m_configurationFile;
}
void GriloRegistry::setConfigurationFile(const QString& file) {
if (m_configurationFile != file) {
m_configurationFile = file;
emit configurationFileChanged();
if (m_registry) {
loadConfigurationFile();
}
}
}
void GriloRegistry::loadConfigurationFile() {
if (!m_configurationFile.isEmpty() && m_registry) {
grl_registry_add_config_from_file(m_registry, m_configurationFile.toLocal8Bit().constData(),
NULL);
}
}
void GriloRegistry::connect_source(gpointer data, gpointer user_data)
{
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
grilo_source_added(reg->m_registry, static_cast<GrlSource *>(data), user_data);
}
void GriloRegistry::grilo_source_added(GrlRegistry *registry, GrlSource *src,
gpointer user_data) {
Q_UNUSED(registry);
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
const char *id = grl_source_get_id(src);
if (reg->m_sources.indexOf(id) == -1) {
reg->m_sources << id;
g_signal_connect(src, "content-changed", G_CALLBACK(grilo_content_changed_cb), reg);
grl_source_notify_change_start(src, 0);
emit reg->availableSourcesChanged();
}
}
void GriloRegistry::grilo_source_removed(GrlRegistry *registry, GrlSource *src,
gpointer user_data) {
Q_UNUSED(registry);
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
const char *id = grl_source_get_id(src);
if (int index = reg->m_sources.indexOf(id) != -1) {
reg->m_sources.removeAt(index);
g_signal_handlers_disconnect_by_data(src, reg);
emit reg->availableSourcesChanged();
}
}
void GriloRegistry::grilo_content_changed_cb(GrlSource *source, GPtrArray *changed_media,
GrlSourceChangeType change_type, gboolean location_unknown,
gpointer user_data) {
Q_UNUSED(location_unknown);
GriloRegistry *reg = static_cast<GriloRegistry *>(user_data);
const char *id = grl_source_get_id(source);
emit reg->contentChanged(id, change_type, changed_media);
}
GrlSource *GriloRegistry::lookupSource(const QString& id) {
if (!m_registry) {
qCritical() << "No registry object!!!";
return 0;
}
return grl_registry_lookup_source(m_registry, id.toUtf8().constData());
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file tgStructure.cpp
* @brief Implementation of class tgStructure
* @author Ryan Adams
* @date March 2014
* $Id$
*/
// This module
#include "tgStructure.h"
// This library
#include "tgNode.h"
#include "tgPair.h"
// The Bullet Physics library
#include <LinearMath/btQuaternion.h>
#include <LinearMath/btVector3.h>
tgStructure::tgStructure() : tgTaggable()
{
}
/**
* Copy constructor
*/
tgStructure::tgStructure(const tgStructure& orig) : tgTaggable(orig.getTags()),
m_children(orig.m_children.size()), m_nodes(orig.m_nodes), m_pairs(orig.m_pairs)
{
// Copy children
for (std::size_t i = 0; i < orig.m_children.size(); ++i) {
m_children[i] = new tgStructure(*orig.m_children[i]);
}
}
tgStructure::tgStructure(const tgTags& tags) : tgTaggable(tags)
{
}
tgStructure::tgStructure(const std::string& space_separated_tags) : tgTaggable(space_separated_tags)
{
}
tgStructure::~tgStructure()
{
for (std::size_t i = 0; i < m_children.size(); ++i)
{
delete m_children[i];
}
}
void tgStructure::addNode(double x, double y, double z, std::string tags)
{
m_nodes.addNode(x, y, z, tags);
}
void tgStructure::addNode(tgNode& newNode)
{
m_nodes.addNode(newNode);
}
void tgStructure::addPair(int fromNodeIdx, int toNodeIdx, std::string tags)
{
addPair(m_nodes[fromNodeIdx], m_nodes[toNodeIdx], tags);
}
void tgStructure::addPair(const btVector3& from, const btVector3& to, std::string tags)
{
// @todo: do we need to pass in tags here? might be able to save some proc time if not...
tgPair p = tgPair(from, to);
if (!m_pairs.contains(p))
{
m_pairs.addPair(tgPair(from, to, tags));
}
else
{
std::ostringstream os;
os << "A pair matching " << p << " already exists in this structure.";
throw tgException(os.str());
}
}
void tgStructure::move(const btVector3& offset)
{
m_nodes.move(offset);
m_pairs.move(offset);
for (size_t i = 0; i < m_children.size(); ++i)
{
tgStructure * const pStructure = m_children[i];
assert(pStructure != NULL);
pStructure->move(offset);
}
}
void tgStructure::addRotation(const btVector3& fixedPoint,
const btVector3& axis,
double angle)
{
const btQuaternion rotation(axis, angle);
addRotation(fixedPoint, rotation);
}
void tgStructure::addRotation(const btVector3& fixedPoint,
const btVector3& fromOrientation,
const btVector3& toOrientation)
{
addRotation(fixedPoint,
tgUtil::getQuaternionBetween(fromOrientation,
toOrientation));
}
void tgStructure::addRotation(const btVector3& fixedPoint,
const btQuaternion& rotation)
{
m_nodes.addRotation(fixedPoint, rotation);
m_pairs.addRotation(fixedPoint, rotation);
for (std::size_t i = 0; i < m_children.size(); ++i)
{
tgStructure * const pStructure = m_children[i];
assert(pStructure != NULL);
pStructure->addRotation(fixedPoint, rotation);
}
}
void tgStructure::addChild(tgStructure* pChild)
{
/// @todo: check to make sure we don't already have one of these structures
/// (what does that mean?)
/// @note: We only want to check that pairs are the same at build time, since one
/// structure may build the pairs, while another may not depending on its tags.
if (pChild != NULL)
{
m_children.push_back(pChild);
}
}
void tgStructure::addChild(const tgStructure& child)
{
m_children.push_back(new tgStructure(child));
}
/* Standalone functions */
std::string asYamlElement(const tgStructure& structure, int indentLevel)
{
std::stringstream os;
std::string indent = std::string(2 * (indentLevel), ' ');
os << indent << "structure:" << std::endl;
os << indent << " tags: " << asYamlList(structure.getTags()) << std::endl;
os << asYamlItems(structure.getNodes(), indentLevel + 1);
os << asYamlItems(structure.getPairs(), indentLevel + 1);
os << asYamlItems(structure.getChildren(), indentLevel + 1);
return os.str();
}
std::string asYamlItem(const tgStructure& structure, int indentLevel)
{
std::stringstream os;
std::string indent = std::string(2 * (indentLevel), ' ');
os << indent << "- tags: " << asYamlList(structure.getTags()) << std::endl;
os << asYamlItems(structure.getNodes(), indentLevel + 1);
os << asYamlItems(structure.getPairs(), indentLevel + 1);
os << asYamlItems(structure.getChildren(), indentLevel + 1);
return os.str();
}
std::string asYamlItems(const std::vector<tgStructure*> structures, int indentLevel)
{
std::stringstream os;
std::string indent = std::string(2 * (indentLevel), ' ');
if (structures.size() == 0) {
os << indent << "structures: []" << std::endl;
return os.str();
}
os << indent << "structures:" << std::endl;
for(size_t i = 0; i < structures.size(); i++)
{
os << asYamlItem(*structures[i], indentLevel+1);
}
return os.str();
}
<commit_msg>Fixed #188 by adding tags to the copy constructor initializer list<commit_after>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file tgStructure.cpp
* @brief Implementation of class tgStructure
* @author Ryan Adams
* @date March 2014
* $Id$
*/
// This module
#include "tgStructure.h"
// This library
#include "tgNode.h"
#include "tgPair.h"
// The Bullet Physics library
#include <LinearMath/btQuaternion.h>
#include <LinearMath/btVector3.h>
tgStructure::tgStructure() : tgTaggable()
{
}
/**
* Copy constructor
*/
tgStructure::tgStructure(const tgStructure& orig) : tgTaggable(orig.getTags()),
m_children(orig.m_children.size()), m_nodes(orig.m_nodes), m_pairs(orig.m_pairs)
{
// Copy children
for (std::size_t i = 0; i < orig.m_children.size(); ++i) {
m_children[i] = new tgStructure(*orig.m_children[i]);
}
}
tgStructure::tgStructure(const tgTags& tags) : tgTaggable(tags)
{
}
tgStructure::tgStructure(const std::string& space_separated_tags) : tgTaggable(space_separated_tags)
{
}
tgStructure::~tgStructure()
{
for (std::size_t i = 0; i < m_children.size(); ++i)
{
delete m_children[i];
}
}
void tgStructure::addNode(double x, double y, double z, std::string tags)
{
m_nodes.addNode(x, y, z, tags);
}
void tgStructure::addNode(tgNode& newNode)
{
m_nodes.addNode(newNode);
}
void tgStructure::addPair(int fromNodeIdx, int toNodeIdx, std::string tags)
{
addPair(m_nodes[fromNodeIdx], m_nodes[toNodeIdx], tags);
}
void tgStructure::addPair(const btVector3& from, const btVector3& to, std::string tags)
{
// @todo: do we need to pass in tags here? might be able to save some proc time if not...
tgPair p = tgPair(from, to);
if (!m_pairs.contains(p))
{
m_pairs.addPair(tgPair(from, to, tags));
}
else
{
std::ostringstream os;
os << "A pair matching " << p << " already exists in this structure.";
throw tgException(os.str());
}
}
void tgStructure::move(const btVector3& offset)
{
m_nodes.move(offset);
m_pairs.move(offset);
for (size_t i = 0; i < m_children.size(); ++i)
{
tgStructure * const pStructure = m_children[i];
assert(pStructure != NULL);
pStructure->move(offset);
}
}
void tgStructure::addRotation(const btVector3& fixedPoint,
const btVector3& axis,
double angle)
{
const btQuaternion rotation(axis, angle);
addRotation(fixedPoint, rotation);
}
void tgStructure::addRotation(const btVector3& fixedPoint,
const btVector3& fromOrientation,
const btVector3& toOrientation)
{
addRotation(fixedPoint,
tgUtil::getQuaternionBetween(fromOrientation,
toOrientation));
}
void tgStructure::addRotation(const btVector3& fixedPoint,
const btQuaternion& rotation)
{
m_nodes.addRotation(fixedPoint, rotation);
m_pairs.addRotation(fixedPoint, rotation);
for (std::size_t i = 0; i < m_children.size(); ++i)
{
tgStructure * const pStructure = m_children[i];
assert(pStructure != NULL);
pStructure->addRotation(fixedPoint, rotation);
}
}
void tgStructure::addChild(tgStructure* pChild)
{
/// @todo: check to make sure we don't already have one of these structures
/// (what does that mean?)
/// @note: We only want to check that pairs are the same at build time, since one
/// structure may build the pairs, while another may not depending on its tags.
if (pChild != NULL)
{
m_children.push_back(pChild);
}
}
void tgStructure::addChild(const tgStructure& child)
{
m_children.push_back(new tgStructure(child));
}
/* Standalone functions */
std::string asYamlElement(const tgStructure& structure, int indentLevel)
{
std::stringstream os;
std::string indent = std::string(2 * (indentLevel), ' ');
os << indent << "structure:" << std::endl;
os << indent << " tags: " << asYamlList(structure.getTags()) << std::endl;
os << asYamlItems(structure.getNodes(), indentLevel + 1);
os << asYamlItems(structure.getPairs(), indentLevel + 1);
os << asYamlItems(structure.getChildren(), indentLevel + 1);
return os.str();
}
std::string asYamlItem(const tgStructure& structure, int indentLevel)
{
std::stringstream os;
std::string indent = std::string(2 * (indentLevel), ' ');
os << indent << "- tags: " << asYamlList(structure.getTags()) << std::endl;
os << asYamlItems(structure.getNodes(), indentLevel + 1);
os << asYamlItems(structure.getPairs(), indentLevel + 1);
os << asYamlItems(structure.getChildren(), indentLevel + 1);
return os.str();
}
std::string asYamlItems(const std::vector<tgStructure*> structures, int indentLevel)
{
std::stringstream os;
std::string indent = std::string(2 * (indentLevel), ' ');
if (structures.size() == 0) {
os << indent << "structures: []" << std::endl;
return os.str();
}
os << indent << "structures:" << std::endl;
for(size_t i = 0; i < structures.size(); i++)
{
os << asYamlItem(*structures[i], indentLevel+1);
}
return os.str();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Dean ChaoJun Pan. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <rocksdb/slice_transform.h>
#include "compactionfilterPrivate.h"
#include "compactionfilter.h"
extern "C" {
#include "_cgo_export.h"
}
DEFINE_C_WRAP_CONSTRUCTOR(CompactionFilterContext)
DEFINE_C_WRAP_DESTRUCTOR(CompactionFilterContext)
DEFINE_C_WRAP_CONSTRUCTOR(CompactionFilter)
DEFINE_C_WRAP_DESTRUCTOR(CompactionFilter)
DEFINE_C_WRAP_CONSTRUCTOR(CompactionFilter_Context)
DEFINE_C_WRAP_DESTRUCTOR(CompactionFilter_Context)
DEFINE_C_WRAP_CONSTRUCTOR(PCompactionFilterFactory)
DEFINE_C_WRAP_CONSTRUCTOR_DEFAULT(PCompactionFilterFactory)
DEFINE_C_WRAP_DESTRUCTOR(PCompactionFilterFactory)
// C++ wrap class for go ICompactionFilter
// CompactionFilter allows an application to modify/delete a key-value at
// the time of compaction.
class CompactionFilterGo : public CompactionFilter {
public:
CompactionFilterGo(void* go_cpf)
: m_go_cpf(go_cpf)
, m_name(nullptr)
{
if (go_cpf)
{
m_name = ICompactionFilterName(go_cpf);
}
}
// Destructor
~CompactionFilterGo()
{
if (m_go_cpf)
{
InterfacesRemoveReference(m_go_cpf);
}
if (m_name)
{
free(m_name);
}
}
// The compaction process invokes this
// method for kv that is being compacted. A return value
// of false indicates that the kv should be preserved in the
// output of this compaction run and a return value of true
// indicates that this key-value should be removed from the
// output of the compaction. The application can inspect
// the existing value of the key and make decision based on it.
//
// When the value is to be preserved, the application has the option
// to modify the existing_value and pass it back through new_value.
// value_changed needs to be set to true in this case.
//
// If multithreaded compaction is being used *and* a single CompactionFilter
// instance was supplied via Options::compaction_filter, this method may be
// called from different threads concurrently. The application must ensure
// that the call is thread-safe.
//
// If the CompactionFilter was created by a factory, then it will only ever
// be used by a single thread that is doing the compaction run, and this
// call does not need to be thread-safe. However, multiple filters may be
// in existence and operating concurrently.
virtual bool Filter(int level,
const Slice& key,
const Slice& existing_value,
std::string* new_value,
bool* value_changed) const override
{
bool ret = false;
if (m_go_cpf)
{
Slice_t slc_key{const_cast<Slice *>(&key)};
Slice_t slc_exval{const_cast<Slice *>(&existing_value)};
String_t str{new_value};
ret = ICompactionFilterFilter(m_go_cpf, level, &slc_key, &slc_exval, &str, value_changed);
}
return ret;
}
// Returns a name that identifies this compaction filter.
// The name will be printed to LOG file on start up for diagnosis.
virtual const char* Name() const override
{
return m_name;
}
private:
// Wrapped go ICompactionFilter
void* m_go_cpf;
// The name of the compaction filter
char* m_name;
};
// Return a CompactionFilter from a go ICompactionFilter
CompactionFilter_t NewCompactionFilter(void* go_cpf)
{
CompactionFilter_t wrap_t;
wrap_t.rep = (go_cpf ? new CompactionFilterGo(go_cpf) : NULL);
return wrap_t;
}
// Each compaction will create a new CompactionFilter allowing the
// application to know about different compactions
class CompactionFilterFactoryGo : public CompactionFilterFactory {
public:
CompactionFilterFactoryGo(void* go_cpfac)
: m_go_cpfac(go_cpfac)
, m_name(nullptr)
{
if (go_cpfac)
{
m_name = ICompactionFilterFactoryName(go_cpfac);
}
}
// Destructor
~CompactionFilterFactoryGo()
{
if (m_go_cpfac)
{
InterfacesRemoveReference(m_go_cpfac);
}
if (m_name)
{
free(m_name);
}
}
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context)
{
std::unique_ptr<CompactionFilter> ret;
if (m_go_cpfac)
{
CompactionFilter_Context_t cxt{const_cast<CompactionFilter::Context *>(&context)};
ret.reset(new CompactionFilterGo(ICompactionFilterFactoryCreateCompactionFilter(m_go_cpfac, &cxt)));
}
return ret;
}
// Returns a name that identifies this compaction filter factory.
virtual const char* Name() const
{
return m_name;
}
private:
// Wrapped go ICompactionFilterFactory
void* m_go_cpfac;
// The name of the CompactionFilterFactory
char* m_name;
};
// Return a CompactionFilterFactory from a go ICompactionFilterFactory
PCompactionFilterFactory_t NewPCompactionFilterFactory(void* go_cpflt)
{
PCompactionFilterFactory_t wrap_t;
wrap_t.rep = new PCompactionFilterFactory(go_cpflt ? new CompactionFilterFactoryGo(go_cpflt) : NULL);
return wrap_t;
}
<commit_msg>Fix wrong file names<commit_after>// Copyright (c) 2015, Dean ChaoJun Pan. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <rocksdb/slice_transform.h>
#include "compactionFilterPrivate.h"
#include "compactionFilter.h"
extern "C" {
#include "_cgo_export.h"
}
DEFINE_C_WRAP_CONSTRUCTOR(CompactionFilterContext)
DEFINE_C_WRAP_DESTRUCTOR(CompactionFilterContext)
DEFINE_C_WRAP_CONSTRUCTOR(CompactionFilter)
DEFINE_C_WRAP_DESTRUCTOR(CompactionFilter)
DEFINE_C_WRAP_CONSTRUCTOR(CompactionFilter_Context)
DEFINE_C_WRAP_DESTRUCTOR(CompactionFilter_Context)
DEFINE_C_WRAP_CONSTRUCTOR(PCompactionFilterFactory)
DEFINE_C_WRAP_CONSTRUCTOR_DEFAULT(PCompactionFilterFactory)
DEFINE_C_WRAP_DESTRUCTOR(PCompactionFilterFactory)
// C++ wrap class for go ICompactionFilter
// CompactionFilter allows an application to modify/delete a key-value at
// the time of compaction.
class CompactionFilterGo : public CompactionFilter {
public:
CompactionFilterGo(void* go_cpf)
: m_go_cpf(go_cpf)
, m_name(nullptr)
{
if (go_cpf)
{
m_name = ICompactionFilterName(go_cpf);
}
}
// Destructor
~CompactionFilterGo()
{
if (m_go_cpf)
{
InterfacesRemoveReference(m_go_cpf);
}
if (m_name)
{
free(m_name);
}
}
// The compaction process invokes this
// method for kv that is being compacted. A return value
// of false indicates that the kv should be preserved in the
// output of this compaction run and a return value of true
// indicates that this key-value should be removed from the
// output of the compaction. The application can inspect
// the existing value of the key and make decision based on it.
//
// When the value is to be preserved, the application has the option
// to modify the existing_value and pass it back through new_value.
// value_changed needs to be set to true in this case.
//
// If multithreaded compaction is being used *and* a single CompactionFilter
// instance was supplied via Options::compaction_filter, this method may be
// called from different threads concurrently. The application must ensure
// that the call is thread-safe.
//
// If the CompactionFilter was created by a factory, then it will only ever
// be used by a single thread that is doing the compaction run, and this
// call does not need to be thread-safe. However, multiple filters may be
// in existence and operating concurrently.
virtual bool Filter(int level,
const Slice& key,
const Slice& existing_value,
std::string* new_value,
bool* value_changed) const override
{
bool ret = false;
if (m_go_cpf)
{
Slice_t slc_key{const_cast<Slice *>(&key)};
Slice_t slc_exval{const_cast<Slice *>(&existing_value)};
String_t str{new_value};
ret = ICompactionFilterFilter(m_go_cpf, level, &slc_key, &slc_exval, &str, value_changed);
}
return ret;
}
// Returns a name that identifies this compaction filter.
// The name will be printed to LOG file on start up for diagnosis.
virtual const char* Name() const override
{
return m_name;
}
private:
// Wrapped go ICompactionFilter
void* m_go_cpf;
// The name of the compaction filter
char* m_name;
};
// Return a CompactionFilter from a go ICompactionFilter
CompactionFilter_t NewCompactionFilter(void* go_cpf)
{
CompactionFilter_t wrap_t;
wrap_t.rep = (go_cpf ? new CompactionFilterGo(go_cpf) : NULL);
return wrap_t;
}
// Each compaction will create a new CompactionFilter allowing the
// application to know about different compactions
class CompactionFilterFactoryGo : public CompactionFilterFactory {
public:
CompactionFilterFactoryGo(void* go_cpfac)
: m_go_cpfac(go_cpfac)
, m_name(nullptr)
{
if (go_cpfac)
{
m_name = ICompactionFilterFactoryName(go_cpfac);
}
}
// Destructor
~CompactionFilterFactoryGo()
{
if (m_go_cpfac)
{
InterfacesRemoveReference(m_go_cpfac);
}
if (m_name)
{
free(m_name);
}
}
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context)
{
std::unique_ptr<CompactionFilter> ret;
if (m_go_cpfac)
{
CompactionFilter_Context_t cxt{const_cast<CompactionFilter::Context *>(&context)};
ret.reset(new CompactionFilterGo(ICompactionFilterFactoryCreateCompactionFilter(m_go_cpfac, &cxt)));
}
return ret;
}
// Returns a name that identifies this compaction filter factory.
virtual const char* Name() const
{
return m_name;
}
private:
// Wrapped go ICompactionFilterFactory
void* m_go_cpfac;
// The name of the CompactionFilterFactory
char* m_name;
};
// Return a CompactionFilterFactory from a go ICompactionFilterFactory
PCompactionFilterFactory_t NewPCompactionFilterFactory(void* go_cpflt)
{
PCompactionFilterFactory_t wrap_t;
wrap_t.rep = new PCompactionFilterFactory(go_cpflt ? new CompactionFilterFactoryGo(go_cpflt) : NULL);
return wrap_t;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include <pandora.hpp>
using namespace pandora;
class TestDataSet:public CPPUNIT_NS::TestFixture {
public:
void setUp() {
unsigned int &openMode = open_mode();
h5file = H5::H5File("test_dataset.h5", openMode);
if (openMode == H5F_ACC_TRUNC) {
h5group = h5file.createGroup("charon");
} else {
h5group = h5file.openGroup("charon");
}
openMode = H5F_ACC_RDWR;
}
void testChunkGuessing() {
PSize dims(2);
dims[0] = 1024;
dims[1] = 1024;
PSize chunks = DataSet::guessChunking(dims, DataType::Double);
CPPUNIT_ASSERT_EQUAL(chunks[0], 64ULL);
CPPUNIT_ASSERT_EQUAL(chunks[1], 64ULL);
}
void testBasic() {
PSize dims(2);
dims[0] = 4;
dims[1] = 6;
PSize chunks = DataSet::guessChunking(dims, DataType::Double);
PSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDouble", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[4][6]);
int values = 0;
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
A[i][j] = values++;
ds.write(A);
array_type B(boost::extents[1][1]);
ds.read(B, true);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
array_type C(boost::extents[8][12]);
values = 0;
for(index i = 0; i != 8; ++i)
for(index j = 0; j != 12; ++j)
C[i][j] = values++;
dims[0] = 8;
dims[1] = 12;
ds.extend(dims);
ds.write(C);
}
void testSelection() {
PSize dims(2);
dims[0] = 15;
dims[1] = 15;
PSize chunks = DataSet::guessChunking(dims, DataType::Double);
PSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDoubleSelection", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[5][5]);
int values = 1;
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
A[i][j] = values++;
Selection memSelection(ds.createSelection(A));
Selection fileSelection(ds.createSelection());
PSize fileCount(dims.size());
PSize fileStart(dims.size());
fileCount.fill(5ULL);
fileStart.fill(5ULL);
fileSelection.select(fileCount, fileStart);
PSize boundsStart(dims.size());
PSize boundsEnd(dims.size());
fileSelection.bounds(boundsStart, boundsEnd);
PSize boundsSize = fileSelection.size();
for (size_t idx = 0; idx < dims.size(); idx++) {
std::cout << boundsStart[idx] << " : " << boundsEnd[idx] << "|" << boundsSize[idx] << std::endl;
}
ds.write(A, fileSelection, memSelection);
array_type B(boost::extents[5][5]);
ds.read(B, fileSelection); //NB: no mem-selection
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
PSSize offset(dims.size(), 5);
fileSelection.offset(offset);
ds.write(A, fileSelection);
array_type C(boost::extents[5][5]);
ds.read(C, fileSelection, true);
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], C[i][j]);
}
void tearDown() {
h5group.close();
h5file.close();
}
private:
static unsigned int &open_mode();
H5::H5File h5file;
H5::Group h5group;
CPPUNIT_TEST_SUITE(TestDataSet);
CPPUNIT_TEST(testChunkGuessing);
CPPUNIT_TEST(testBasic);
CPPUNIT_TEST(testSelection);
CPPUNIT_TEST_SUITE_END ();
};
unsigned int & TestDataSet::open_mode()
{
static unsigned int openMode = H5F_ACC_TRUNC;
return openMode;
}
<commit_msg>TestDataSet: remove debug prints<commit_after>#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include <pandora.hpp>
using namespace pandora;
class TestDataSet:public CPPUNIT_NS::TestFixture {
public:
void setUp() {
unsigned int &openMode = open_mode();
h5file = H5::H5File("test_dataset.h5", openMode);
if (openMode == H5F_ACC_TRUNC) {
h5group = h5file.createGroup("charon");
} else {
h5group = h5file.openGroup("charon");
}
openMode = H5F_ACC_RDWR;
}
void testChunkGuessing() {
PSize dims(2);
dims[0] = 1024;
dims[1] = 1024;
PSize chunks = DataSet::guessChunking(dims, DataType::Double);
CPPUNIT_ASSERT_EQUAL(chunks[0], 64ULL);
CPPUNIT_ASSERT_EQUAL(chunks[1], 64ULL);
}
void testBasic() {
PSize dims(2);
dims[0] = 4;
dims[1] = 6;
PSize chunks = DataSet::guessChunking(dims, DataType::Double);
PSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDouble", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[4][6]);
int values = 0;
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
A[i][j] = values++;
ds.write(A);
array_type B(boost::extents[1][1]);
ds.read(B, true);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
array_type C(boost::extents[8][12]);
values = 0;
for(index i = 0; i != 8; ++i)
for(index j = 0; j != 12; ++j)
C[i][j] = values++;
dims[0] = 8;
dims[1] = 12;
ds.extend(dims);
ds.write(C);
}
void testSelection() {
PSize dims(2);
dims[0] = 15;
dims[1] = 15;
PSize chunks = DataSet::guessChunking(dims, DataType::Double);
PSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDoubleSelection", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[5][5]);
int values = 1;
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
A[i][j] = values++;
Selection memSelection(ds.createSelection(A));
Selection fileSelection(ds.createSelection());
PSize fileCount(dims.size());
PSize fileStart(dims.size());
fileCount.fill(5ULL);
fileStart.fill(5ULL);
fileSelection.select(fileCount, fileStart);
PSize boundsStart(dims.size());
PSize boundsEnd(dims.size());
fileSelection.bounds(boundsStart, boundsEnd);
PSize boundsSize = fileSelection.size();
ds.write(A, fileSelection, memSelection);
array_type B(boost::extents[5][5]);
ds.read(B, fileSelection); //NB: no mem-selection
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
PSSize offset(dims.size(), 5);
fileSelection.offset(offset);
ds.write(A, fileSelection);
array_type C(boost::extents[5][5]);
ds.read(C, fileSelection, true);
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], C[i][j]);
}
void tearDown() {
h5group.close();
h5file.close();
}
private:
static unsigned int &open_mode();
H5::H5File h5file;
H5::Group h5group;
CPPUNIT_TEST_SUITE(TestDataSet);
CPPUNIT_TEST(testChunkGuessing);
CPPUNIT_TEST(testBasic);
CPPUNIT_TEST(testSelection);
CPPUNIT_TEST_SUITE_END ();
};
unsigned int & TestDataSet::open_mode()
{
static unsigned int openMode = H5F_ACC_TRUNC;
return openMode;
}
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/tools/graph_transforms/fold_constants_lib.h"
#include "tensorflow/core/common_runtime/constant_folding.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
Status ReplaceSendRecvs(const GraphDef& original_graph_def,
const GraphDef& rewritten_graph_def,
const std::vector<string>& inputs,
const std::vector<string>& outputs,
GraphDef* output_graph_def) {
std::map<string, const NodeDef*> original_map;
MapNamesToNodes(original_graph_def, &original_map);
std::map<string, string> new_node_names;
for (const NodeDef& node : rewritten_graph_def.node()) {
// If the op isn't a Recv, or it was in the original, nothing to do.
if ((node.op() != "_Recv") || (original_map.count(node.name()) == 1)) {
continue;
}
// See if it matches an input from the original.
for (const string& input : inputs) {
// Here we rely on the naming convention for the Recv nodes that
// RewriteGraphForExecution adds in the place of the feed inputs.
string input_prefix = "_recv_" + input + "_";
if (StringPiece(node.name()).starts_with(input_prefix)) {
// If it does, prepare to rename any inputs that refer to it.
new_node_names[node.name()] = input;
}
}
}
std::vector<NodeDef> nodes_to_add;
for (const NodeDef& node : rewritten_graph_def.node()) {
if ((node.op() == "_Send") || (node.op() == "_Recv")) {
// If the op is a Send or Recv that wasn't in the original, skip it.
if (original_map.count(node.name()) == 0) {
continue;
}
}
NodeDef new_node;
new_node.CopyFrom(node);
new_node.mutable_input()->Clear();
for (const string& old_input : node.input()) {
string input_prefix;
string input_node_name;
string input_suffix;
NodeNamePartsFromInput(old_input, &input_prefix, &input_node_name,
&input_suffix);
string new_input;
if (new_node_names.count(input_node_name) > 0) {
new_input =
input_prefix + new_node_names[input_node_name] + input_suffix;
} else {
new_input = old_input;
}
*(new_node.mutable_input()->Add()) = new_input;
}
nodes_to_add.push_back(new_node);
}
for (std::pair<string, string> entry : new_node_names) {
string removed_node_name = entry.second;
const NodeDef* removed_node = original_map[removed_node_name];
NodeDef new_node;
new_node.CopyFrom(*removed_node);
nodes_to_add.push_back(new_node);
}
for (const NodeDef& node : nodes_to_add) {
output_graph_def->mutable_node()->Add()->CopyFrom(node);
}
return Status::OK();
}
Status RemoveUnusedNodes(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
std::map<string, const NodeDef*> node_map;
MapNamesToNodes(input_graph_def, &node_map);
std::map<string, bool> used_nodes;
for (const string& input : context.input_names) {
used_nodes[input] = true;
}
std::vector<string> current_nodes = context.output_names;
while (!current_nodes.empty()) {
std::vector<string> next_nodes;
for (const string& node_name : current_nodes) {
used_nodes[node_name] = true;
if (node_map.count(node_name) == 0) {
LOG(ERROR) << "Bad graph structure, no node named '" << node_name
<< "' found for input lookup";
return errors::InvalidArgument("Bad graph structure, no node named '",
node_name, "' found for input lookup");
}
const NodeDef& node = *(node_map[node_name]);
for (const string& input_name : node.input()) {
const string& input_node_name = NodeNameFromInput(input_name);
if (used_nodes.count(input_node_name) == 0) {
next_nodes.push_back(input_node_name);
}
}
}
current_nodes = next_nodes;
}
FilterGraphDef(
input_graph_def,
[&](const NodeDef& node) { return used_nodes.count(node.name()) > 0; },
output_graph_def);
return Status::OK();
}
// Converts any sub-graphs that can be resolved into constant expressions into
// single Const ops.
Status FoldConstants(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
// Some older GraphDefs have saved _output_shapes attributes which are out of
// date and cause import errors, so clean them up first.
GraphDef cleaned_graph_def;
RemoveAttributes(input_graph_def, {"_output_shapes"}, &cleaned_graph_def);
Graph input_graph(OpRegistry::Global());
ImportGraphDefOptions import_opts;
TF_RETURN_IF_ERROR(
ImportGraphDef(import_opts, cleaned_graph_def, &input_graph, nullptr));
DeviceAttributes device_attributes;
TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(
&input_graph, context.input_names, context.output_names, {},
device_attributes));
bool was_mutated;
TF_RETURN_IF_ERROR(DoConstantFoldingWithStatus(
ConstantFoldingOptions(), nullptr, Env::Default(), nullptr, &input_graph,
&was_mutated));
GraphDef folded_graph_def;
input_graph.ToGraphDef(&folded_graph_def);
GraphDef send_recvs_replaced;
TF_RETURN_IF_ERROR(ReplaceSendRecvs(input_graph_def, folded_graph_def,
context.input_names, context.output_names,
&send_recvs_replaced));
TF_RETURN_IF_ERROR(
RemoveUnusedNodes(send_recvs_replaced, context, output_graph_def));
return Status::OK();
}
REGISTER_GRAPH_TRANSFORM("fold_constants", FoldConstants);
} // namespace graph_transforms
} // namespace tensorflow
<commit_msg>Fix complexity problem in transform node iteration Before this change, graphs with a large number of output ports per node (for example quantized graphs) would hang during processing. Change: 143216742<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/tools/graph_transforms/fold_constants_lib.h"
#include "tensorflow/core/common_runtime/constant_folding.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
Status ReplaceSendRecvs(const GraphDef& original_graph_def,
const GraphDef& rewritten_graph_def,
const std::vector<string>& inputs,
const std::vector<string>& outputs,
GraphDef* output_graph_def) {
std::map<string, const NodeDef*> original_map;
MapNamesToNodes(original_graph_def, &original_map);
std::map<string, string> new_node_names;
for (const NodeDef& node : rewritten_graph_def.node()) {
// If the op isn't a Recv, or it was in the original, nothing to do.
if ((node.op() != "_Recv") || (original_map.count(node.name()) == 1)) {
continue;
}
// See if it matches an input from the original.
for (const string& input : inputs) {
// Here we rely on the naming convention for the Recv nodes that
// RewriteGraphForExecution adds in the place of the feed inputs.
string input_prefix = "_recv_" + input + "_";
if (StringPiece(node.name()).starts_with(input_prefix)) {
// If it does, prepare to rename any inputs that refer to it.
new_node_names[node.name()] = input;
}
}
}
std::vector<NodeDef> nodes_to_add;
for (const NodeDef& node : rewritten_graph_def.node()) {
if ((node.op() == "_Send") || (node.op() == "_Recv")) {
// If the op is a Send or Recv that wasn't in the original, skip it.
if (original_map.count(node.name()) == 0) {
continue;
}
}
NodeDef new_node;
new_node.CopyFrom(node);
new_node.mutable_input()->Clear();
for (const string& old_input : node.input()) {
string input_prefix;
string input_node_name;
string input_suffix;
NodeNamePartsFromInput(old_input, &input_prefix, &input_node_name,
&input_suffix);
string new_input;
if (new_node_names.count(input_node_name) > 0) {
new_input =
input_prefix + new_node_names[input_node_name] + input_suffix;
} else {
new_input = old_input;
}
*(new_node.mutable_input()->Add()) = new_input;
}
nodes_to_add.push_back(new_node);
}
for (std::pair<string, string> entry : new_node_names) {
string removed_node_name = entry.second;
const NodeDef* removed_node = original_map[removed_node_name];
NodeDef new_node;
new_node.CopyFrom(*removed_node);
nodes_to_add.push_back(new_node);
}
for (const NodeDef& node : nodes_to_add) {
output_graph_def->mutable_node()->Add()->CopyFrom(node);
}
return Status::OK();
}
Status RemoveUnusedNodes(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
std::map<string, const NodeDef*> node_map;
MapNamesToNodes(input_graph_def, &node_map);
std::set<string> used_nodes;
for (const string& input : context.input_names) {
used_nodes.insert(input);
}
std::vector<string> current_nodes = context.output_names;
while (!current_nodes.empty()) {
std::set<string> next_nodes;
for (const string& node_name : current_nodes) {
used_nodes.insert(node_name);
if (node_map.count(node_name) == 0) {
LOG(ERROR) << "Bad graph structure, no node named '" << node_name
<< "' found for input lookup";
return errors::InvalidArgument("Bad graph structure, no node named '",
node_name, "' found for input lookup");
}
const NodeDef& node = *(node_map[node_name]);
for (const string& input_name : node.input()) {
const string& input_node_name = NodeNameFromInput(input_name);
if (used_nodes.count(input_node_name) == 0) {
next_nodes.insert(input_node_name);
}
}
}
current_nodes = std::vector<string>(next_nodes.begin(), next_nodes.end());
}
FilterGraphDef(
input_graph_def,
[&](const NodeDef& node) { return used_nodes.count(node.name()) > 0; },
output_graph_def);
return Status::OK();
}
// Converts any sub-graphs that can be resolved into constant expressions into
// single Const ops.
Status FoldConstants(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
// Some older GraphDefs have saved _output_shapes attributes which are out of
// date and cause import errors, so clean them up first.
GraphDef cleaned_graph_def;
RemoveAttributes(input_graph_def, {"_output_shapes"}, &cleaned_graph_def);
Graph input_graph(OpRegistry::Global());
ImportGraphDefOptions import_opts;
TF_RETURN_IF_ERROR(
ImportGraphDef(import_opts, cleaned_graph_def, &input_graph, nullptr));
DeviceAttributes device_attributes;
TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(
&input_graph, context.input_names, context.output_names, {},
device_attributes));
bool was_mutated;
TF_RETURN_IF_ERROR(DoConstantFoldingWithStatus(
ConstantFoldingOptions(), nullptr, Env::Default(), nullptr, &input_graph,
&was_mutated));
GraphDef folded_graph_def;
input_graph.ToGraphDef(&folded_graph_def);
GraphDef send_recvs_replaced;
TF_RETURN_IF_ERROR(ReplaceSendRecvs(input_graph_def, folded_graph_def,
context.input_names, context.output_names,
&send_recvs_replaced));
TF_RETURN_IF_ERROR(
RemoveUnusedNodes(send_recvs_replaced, context, output_graph_def));
return Status::OK();
}
REGISTER_GRAPH_TRANSFORM("fold_constants", FoldConstants);
} // namespace graph_transforms
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright (c) 2017 Alexander Gallego. All rights reserved.
//
#include <chrono>
#include <iostream>
#include <seastar/core/app-template.hh>
#include <seastar/core/distributed.hh>
#include <seastar/core/reactor.hh>
#include <seastar/net/api.hh>
#include "smf/histogram_seastar_utils.h"
#include "smf/log.h"
#include "smf/rpc_filter.h"
#include "smf/rpc_server.h"
#include "smf/unique_histogram_adder.h"
#include "smf/zstd_filter.h"
#include "demo_service.smf.fb.h"
class storage_service final : public smf_gen::demo::SmfStorage {
virtual seastar::future<smf::rpc_typed_envelope<smf_gen::demo::Response>>
Get(smf::rpc_recv_typed_context<smf_gen::demo::Request> &&rec) final {
smf::rpc_typed_envelope<smf_gen::demo::Response> data;
// return the same payload
if (rec) { data.data->name = rec->name()->c_str(); }
data.envelope.set_status(200);
return seastar::make_ready_future<
smf::rpc_typed_envelope<smf_gen::demo::Response>>(std::move(data));
}
};
void
cli_opts(boost::program_options::options_description_easy_init o) {
namespace po = boost::program_options;
o("ip", po::value<std::string>()->default_value("127.0.0.1"),
"ip to connect to");
o("port", po::value<uint16_t>()->default_value(20776), "port for service");
o("httpport", po::value<uint16_t>()->default_value(20777),
"port for http stats service");
o("key",
po::value<std::string>()->default_value(""),
"key for TLS seccured connection");
o("cert", po::value<std::string>()->default_value(""),
"cert for TLS seccured connection");
}
int
main(int args, char **argv, char **env) {
std::setvbuf(stdout, nullptr, _IOLBF, 1024);
seastar::distributed<smf::rpc_server> rpc;
seastar::app_template app;
cli_opts(app.add_options());
return app.run_deprecated(args, argv, [&] {
seastar::engine().at_exit([&] {
return rpc
.map_reduce(smf::unique_histogram_adder(),
&smf::rpc_server::copy_histogram)
.then([](auto h) {
LOG_INFO("Writing server histograms");
return smf::histogram_seastar_utils::write("server_latency.hgrm",
std::move(h));
})
.then([&rpc] { return rpc.stop(); });
});
auto &cfg = app.configuration();
smf::rpc_server_args args;
args.ip = cfg["ip"].as<std::string>().c_str();
args.rpc_port = cfg["port"].as<uint16_t>();
args.http_port = cfg["httpport"].as<uint16_t>();
auto key = cfg["key"].as<std::string>();
auto cert = cfg["cert"].as<std::string>();
if (key != "" && cert != "") {
auto builder = seastar::tls::credentials_builder();
builder.set_dh_level(seastar::tls::dh_params::level::MEDIUM);
builder
.set_x509_key_file(cert, key, seastar::tls::x509_crt_format::PEM)
.get();
args.credentials
= builder.build_reloadable_server_credentials().get0();
}
args.memory_avail_per_core =
static_cast<uint64_t>(0.9 * seastar::memory::stats().total_memory());
return rpc.start(args)
.then([&rpc] {
LOG_INFO("Registering smf_gen::demo::storage_service");
return rpc.invoke_on_all(
&smf::rpc_server::register_service<storage_service>);
})
.then([&rpc] {
return rpc.invoke_on_all(&smf::rpc_server::register_incoming_filter<
smf::zstd_decompression_filter>);
})
.then([&rpc] {
LOG_INFO("Invoking rpc start on all cores");
return rpc.invoke_on_all(&smf::rpc_server::start);
});
});
}
<commit_msg>tls: fix promises<commit_after>// Copyright (c) 2017 Alexander Gallego. All rights reserved.
//
#include <chrono>
#include <iostream>
#include <seastar/core/app-template.hh>
#include <seastar/core/distributed.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/thread.hh>
#include <seastar/net/api.hh>
#include "smf/histogram_seastar_utils.h"
#include "smf/log.h"
#include "smf/rpc_filter.h"
#include "smf/rpc_server.h"
#include "smf/unique_histogram_adder.h"
#include "smf/zstd_filter.h"
#include "demo_service.smf.fb.h"
class storage_service final : public smf_gen::demo::SmfStorage {
virtual seastar::future<smf::rpc_typed_envelope<smf_gen::demo::Response>>
Get(smf::rpc_recv_typed_context<smf_gen::demo::Request> &&rec) final {
smf::rpc_typed_envelope<smf_gen::demo::Response> data;
// return the same payload
if (rec) { data.data->name = rec->name()->c_str(); }
data.envelope.set_status(200);
return seastar::make_ready_future<
smf::rpc_typed_envelope<smf_gen::demo::Response>>(std::move(data));
}
};
void
cli_opts(boost::program_options::options_description_easy_init o) {
namespace po = boost::program_options;
o("ip", po::value<std::string>()->default_value("127.0.0.1"),
"ip to connect to");
o("port", po::value<uint16_t>()->default_value(20776), "port for service");
o("httpport", po::value<uint16_t>()->default_value(20777),
"port for http stats service");
o("key", po::value<std::string>()->default_value(""),
"key for TLS seccured connection");
o("cert", po::value<std::string>()->default_value(""),
"cert for TLS seccured connection");
}
int
main(int args, char **argv, char **env) {
std::setvbuf(stdout, nullptr, _IOLBF, 1024);
seastar::distributed<smf::rpc_server> rpc;
seastar::app_template app;
cli_opts(app.add_options());
return app.run_deprecated(args, argv, [&] {
seastar::engine().at_exit([&] {
return rpc
.map_reduce(smf::unique_histogram_adder(),
&smf::rpc_server::copy_histogram)
.then([](auto h) {
LOG_INFO("Writing server histograms");
return smf::histogram_seastar_utils::write("server_latency.hgrm",
std::move(h));
})
.then([&rpc] { return rpc.stop(); });
});
auto &cfg = app.configuration();
return seastar::async([&] {
smf::rpc_server_args args;
args.ip = cfg["ip"].as<std::string>().c_str();
args.rpc_port = cfg["port"].as<uint16_t>();
args.http_port = cfg["httpport"].as<uint16_t>();
args.memory_avail_per_core =
static_cast<uint64_t>(0.9 * seastar::memory::stats().total_memory());
auto key = cfg["key"].as<std::string>();
auto cert = cfg["cert"].as<std::string>();
if (key != "" && cert != "") {
LOG_INFO("Setting tls credentials");
auto builder = seastar::tls::credentials_builder();
builder.set_dh_level(seastar::tls::dh_params::level::MEDIUM);
builder.set_x509_key_file(cert, key, seastar::tls::x509_crt_format::PEM)
.get();
args.credentials = builder.build_reloadable_server_credentials().get0();
}
rpc.start(args).get();
LOG_INFO("Registering smf_gen::demo::storage_service");
rpc.invoke_on_all(&smf::rpc_server::register_service<storage_service>)
.get();
rpc
.invoke_on_all(&smf::rpc_server::register_incoming_filter<
smf::zstd_decompression_filter>)
.get();
LOG_INFO("Invoking rpc start on all cores");
rpc.invoke_on_all(&smf::rpc_server::start).get();
});
});
}
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_mc
/// Macro to compare masses in ROOT data base to the values from pdg
/// (http://pdg.lbl.gov/2009/mcdata/mass_width_2008.mc)[pdg]
///
/// The ROOT values are read in by TDatabasePDG from `$ROOTSYS/etc/pdg_table.txt`
///
/// \macro_output
/// \macro_code
///
/// \author Christian.Klein-Boesing
#include "TDatabasePDG.h"
#include "TParticlePDG.h"
void CompareMasses()
{
TString massWidthFile = gSystem->UnixPathName(__FILE__);
massWidthFile.ReplaceAll("CompareMasses.C","mass_width_2008.mc.txt");
FILE* file = fopen(massWidthFile.Data(),"r");
if (!file){
Printf("Could not open PDG particle file %s", massWidthFile.Data());
return;
}
char c[200];
char cempty;
Int_t pdg[4];
Float_t mass, err1, err2, err;
Int_t ndiff = 0;
while (fgets(c, 200, file)) {
if (c[0] != '*' && c[0] !='W') {
//printf("%s",c);
sscanf(&c[1], "%8d", &pdg[0]);
// check emptiness
pdg[1] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[9+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[9],"%8d",&pdg[1]);
}
pdg[2] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[17+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[17],"%8d",&pdg[2]);
}
pdg[3] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[25+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[25],"%8d",&pdg[3]);
}
sscanf(&c[35],"%14f",&mass);
sscanf(&c[50],"%8f",&err1);
sscanf(&c[50],"%8f",&err2);
err = TMath::Max((Double_t)err1,(Double_t)-1.*err2);
for(int ipdg = 0;ipdg < 4;ipdg++){
if(pdg[ipdg]==0)continue;
TParticlePDG *partRoot = TDatabasePDG::Instance()->GetParticle(pdg[ipdg]);
if(partRoot){
Float_t massRoot = partRoot->Mass();
Float_t deltaM = TMath::Abs(massRoot - mass);
// if(deltaM > err){
if (mass != 0.0 && deltaM/mass>1E-05){
ndiff++;
Printf("%10s %8d pdg mass %E pdg err %E root Mass %E >> deltaM %E = %3.3f%%",partRoot->GetName(),pdg[ipdg],mass,err,massRoot,deltaM,100.*deltaM/mass);
}
}
}
}
}// while
fclose(file);
if (ndiff == 0) Printf("Crongratulations !! All particles in ROOT and PDG have identical masses");
}
<commit_msg>Fix markdown<commit_after>/// \file
/// \ingroup tutorial_mc
/// Macro to compare masses in ROOT data base to the values from pdg
/// [pdg](http://pdg.lbl.gov/2009/mcdata/mass_width_2008.mc).
///
/// The ROOT values are read in by TDatabasePDG from `$ROOTSYS/etc/pdg_table.txt`
///
/// \macro_output
/// \macro_code
///
/// \author Christian.Klein-Boesing
#include "TDatabasePDG.h"
#include "TParticlePDG.h"
void CompareMasses()
{
TString massWidthFile = gSystem->UnixPathName(__FILE__);
massWidthFile.ReplaceAll("CompareMasses.C","mass_width_2008.mc.txt");
FILE* file = fopen(massWidthFile.Data(),"r");
if (!file){
Printf("Could not open PDG particle file %s", massWidthFile.Data());
return;
}
char c[200];
char cempty;
Int_t pdg[4];
Float_t mass, err1, err2, err;
Int_t ndiff = 0;
while (fgets(c, 200, file)) {
if (c[0] != '*' && c[0] !='W') {
//printf("%s",c);
sscanf(&c[1], "%8d", &pdg[0]);
// check emptiness
pdg[1] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[9+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[9],"%8d",&pdg[1]);
}
pdg[2] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[17+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[17],"%8d",&pdg[2]);
}
pdg[3] = 0;
for(int i = 0;i<8;i++){
sscanf(&c[25+i],"%c",&cempty);
if(cempty != ' ')sscanf(&c[25],"%8d",&pdg[3]);
}
sscanf(&c[35],"%14f",&mass);
sscanf(&c[50],"%8f",&err1);
sscanf(&c[50],"%8f",&err2);
err = TMath::Max((Double_t)err1,(Double_t)-1.*err2);
for(int ipdg = 0;ipdg < 4;ipdg++){
if(pdg[ipdg]==0)continue;
TParticlePDG *partRoot = TDatabasePDG::Instance()->GetParticle(pdg[ipdg]);
if(partRoot){
Float_t massRoot = partRoot->Mass();
Float_t deltaM = TMath::Abs(massRoot - mass);
// if(deltaM > err){
if (mass != 0.0 && deltaM/mass>1E-05){
ndiff++;
Printf("%10s %8d pdg mass %E pdg err %E root Mass %E >> deltaM %E = %3.3f%%",partRoot->GetName(),pdg[ipdg],mass,err,massRoot,deltaM,100.*deltaM/mass);
}
}
}
}
}// while
fclose(file);
if (ndiff == 0) Printf("Crongratulations !! All particles in ROOT and PDG have identical masses");
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/datasets.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("unit/conv/sgd/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::updater<dll::updater_type::MOMENTUM>, dll::batch_size<10>>::dbn_t dbn_t;
// Load the dataset
auto dataset = dll::make_mnist_dataset_sub(500, 0, dll::batch_size<10>{});
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK_DATASET(25, 5e-2);
TEST_CHECK_DATASET(0.25);
}
TEST_CASE("unit/conv/sgd/2", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::TANH>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.4);
}
TEST_CASE("unit/conv/sgd/3", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 4, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<4 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::updater<dll::updater_type::SGD>, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(800);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(75, 6e-2);
TEST_CHECK(0.25);
}
TEST_CASE("unit/conv/sgd/4", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::conv_desc<6, 24, 24, 4, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<4 * 20 * 20, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<20>, dll::scale_pre<255>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(800);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.1;
FT_CHECK(35, 0.2);
TEST_CHECK(0.25);
}
TEST_CASE("unit/conv/sgd/5", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::conv_desc<6, 24, 24, 4, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<4 * 20 * 20, 200, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<200, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(25, 6e-2);
TEST_CHECK(0.2);
}
// Test custom training
TEST_CASE("unit/conv/sgd/partial/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
REQUIRE(!dataset.training_images.empty());
using generator_t = dll::inmemory_data_generator_desc<dll::batch_size<10>, dll::categorical>;
auto generator = dll::make_generator(dataset.training_images, dataset.training_labels, 10, generator_t{});
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
auto trainer = dbn->get_trainer();
trainer.start_training(*dbn, 30);
// Train for 25 epochs
for(size_t epoch = 0; epoch < 30; ++epoch){
trainer.start_epoch(*dbn, epoch);
generator->reset();
double error;
double loss;
// Train for one epoch
std::tie(loss, error) = trainer.train_epoch(*dbn, *generator, epoch);
if(trainer.stop_epoch(*dbn, epoch, error, loss)){
break;
}
}
auto ft_error = trainer.stop_training(*dbn);
REQUIRE(ft_error < 5e-2);
TEST_CHECK(0.25);
}
<commit_msg>Test He initialization<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/datasets.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("unit/conv/sgd/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::updater<dll::updater_type::MOMENTUM>, dll::batch_size<10>>::dbn_t dbn_t;
// Load the dataset
auto dataset = dll::make_mnist_dataset_sub(500, 0, dll::batch_size<10>{});
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK_DATASET(25, 5e-2);
TEST_CHECK_DATASET(0.25);
}
TEST_CASE("unit/conv/sgd/2", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::TANH>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.4);
}
TEST_CASE("unit/conv/sgd/3", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 4, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<4 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::updater<dll::updater_type::SGD>, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(800);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(75, 6e-2);
TEST_CHECK(0.25);
}
TEST_CASE("unit/conv/sgd/4", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::conv_desc<6, 24, 24, 4, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<4 * 20 * 20, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<20>, dll::scale_pre<255>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(800);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.1;
FT_CHECK(35, 0.2);
TEST_CHECK(0.25);
}
TEST_CASE("unit/conv/sgd/5", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::RELU>, dll::initializer<dll::initializer_type::HE>>::layer_t,
dll::conv_desc<6, 24, 24, 4, 5, 5, dll::activation<dll::function::RELU>, dll::initializer<dll::initializer_type::HE>>::layer_t,
dll::dense_desc<4 * 20 * 20, 200, dll::activation<dll::function::RELU>, dll::initializer<dll::initializer_type::HE>>::layer_t,
dll::dense_desc<200, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(1000);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(25, 6e-2);
TEST_CHECK(0.2);
}
// Test custom training
TEST_CASE("unit/conv/sgd/partial/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
REQUIRE(!dataset.training_images.empty());
using generator_t = dll::inmemory_data_generator_desc<dll::batch_size<10>, dll::categorical>;
auto generator = dll::make_generator(dataset.training_images, dataset.training_labels, 10, generator_t{});
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
auto trainer = dbn->get_trainer();
trainer.start_training(*dbn, 30);
// Train for 25 epochs
for(size_t epoch = 0; epoch < 30; ++epoch){
trainer.start_epoch(*dbn, epoch);
generator->reset();
double error;
double loss;
// Train for one epoch
std::tie(loss, error) = trainer.train_epoch(*dbn, *generator, epoch);
if(trainer.stop_epoch(*dbn, epoch, error, loss)){
break;
}
}
auto ft_error = trainer.stop_training(*dbn);
REQUIRE(ft_error < 5e-2);
TEST_CHECK(0.25);
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "packetqueue.h"
#include "packet.h"
#include <vespa/fastos/time.h>
#include <cassert>
#include <chrono>
void
FNET_PacketQueue_NoLock::ExpandBuf(uint32_t needentries)
{
uint32_t oldsize = _bufsize;
if (_bufsize < 8)
_bufsize = 8;
while (_bufsize < _bufused + needentries)
_bufsize *= 2;
_QElem *newbuf = static_cast<_QElem *>(malloc(sizeof(_QElem) * _bufsize));
assert(newbuf != nullptr);
if (_bufused == 0) { // EMPTY
// BUFFER: |....................|
// USED: |....................|
} else if (_in_pos > _out_pos) { // NON-WRAPPED
// BUFFER: |....................|
// USED: |....############....|
// rOfs rLen
uint32_t rOfs = _out_pos;
uint32_t rLen = (_in_pos - _out_pos);
//TODO Rewrite to pure C++
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wclass-memaccess"
memcpy(newbuf + rOfs, _buf + rOfs, rLen * sizeof(_QElem));
#pragma GCC diagnostic pop
} else { // WRAPPED
// BUFFER: |....................|
// USED: |######........######|
// r1Len r2Len
uint32_t r1Len = _in_pos;
uint32_t r2Len = (oldsize - _out_pos);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wclass-memaccess"
memcpy(newbuf, _buf, r1Len * sizeof(_QElem));
memcpy(newbuf + _bufsize - r2Len, _buf + oldsize - r2Len, r2Len * sizeof(_QElem));
#pragma GCC diagnostic pop
_out_pos += _bufsize - oldsize;
}
free(_buf);
_buf = newbuf;
}
FNET_PacketQueue_NoLock::FNET_PacketQueue_NoLock(uint32_t len,
HP_RetCode hpRetCode)
: _buf(nullptr),
_bufsize(len),
_bufused(0),
_in_pos(0),
_out_pos(0),
_hpRetCode(hpRetCode)
{
_buf = static_cast<_QElem *>(malloc(sizeof(_QElem) * len));
assert(_buf != nullptr);
}
FNET_PacketQueue_NoLock::~FNET_PacketQueue_NoLock()
{
DiscardPackets_NoLock();
free(_buf);
}
FNET_IPacketHandler::HP_RetCode
FNET_PacketQueue_NoLock::HandlePacket(FNET_Packet *packet,
FNET_Context context)
{
QueuePacket_NoLock(packet, context);
return _hpRetCode;
}
void
FNET_PacketQueue_NoLock::QueuePacket_NoLock(FNET_Packet *packet,
FNET_Context context)
{
if (packet == nullptr)
return;
EnsureFree();
_buf[_in_pos]._packet = packet;
_buf[_in_pos]._context = context;
if (++_in_pos == _bufsize)
_in_pos = 0; // wrap around.
_bufused++;
}
FNET_Packet*
FNET_PacketQueue_NoLock::DequeuePacket_NoLock(FNET_Context *context)
{
assert(context != nullptr);
FNET_Packet *packet = nullptr;
if (_bufused > 0) {
packet = _buf[_out_pos]._packet;
__builtin_prefetch(packet, 0);
*context = _buf[_out_pos]._context;
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
_bufused--;
}
return packet;
}
uint32_t
FNET_PacketQueue_NoLock::FlushPackets_NoLock(FNET_PacketQueue_NoLock *target)
{
uint32_t cnt = _bufused;
target->EnsureFree(cnt);
for (; _bufused > 0; _bufused--, target->_bufused++) {
target->_buf[target->_in_pos]._packet = _buf[_out_pos]._packet;
target->_buf[target->_in_pos]._context = _buf[_out_pos]._context;
if (++target->_in_pos == target->_bufsize)
target->_in_pos = 0; // wrap around.
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around.
}
assert(_out_pos == _in_pos);
return cnt;
}
void
FNET_PacketQueue_NoLock::DiscardPackets_NoLock()
{
for (; _bufused > 0; _bufused--) {
_buf[_out_pos]._packet->Free(); // discard packet
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
}
assert(_out_pos == _in_pos);
}
void
FNET_PacketQueue_NoLock::Print(uint32_t indent)
{
uint32_t i = _out_pos;
uint32_t cnt = _bufused;
printf("%*sFNET_PacketQueue_NoLock {\n", indent, "");
printf("%*s bufsize : %d\n", indent, "", _bufsize);
printf("%*s bufused : %d\n", indent, "", _bufused);
printf("%*s in_pos : %d\n", indent, "", _in_pos);
printf("%*s out_pos : %d\n", indent, "", _out_pos);
for (; cnt > 0; i++, cnt--) {
if (i == _bufsize)
i = 0; // wrap around
_buf[i]._packet->Print(indent + 2);
_buf[i]._context.Print(indent + 2);
}
printf("%*s}\n", indent, "");
}
//------------------------------------------------------------------
FNET_PacketQueue::FNET_PacketQueue(uint32_t len,
HP_RetCode hpRetCode)
: FNET_PacketQueue_NoLock(len, hpRetCode),
_lock(),
_cond(),
_waitCnt(0)
{
}
FNET_PacketQueue::~FNET_PacketQueue()
{
}
FNET_IPacketHandler::HP_RetCode
FNET_PacketQueue::HandlePacket(FNET_Packet *packet,
FNET_Context context)
{
QueuePacket(packet, context);
return _hpRetCode;
}
void
FNET_PacketQueue::QueuePacket(FNET_Packet *packet, FNET_Context context)
{
assert(packet != nullptr);
std::lock_guard<std::mutex> guard(_lock);
EnsureFree();
_buf[_in_pos]._packet = packet; // insert packet ref.
_buf[_in_pos]._context = context;
if (++_in_pos == _bufsize)
_in_pos = 0; // wrap around.
_bufused++;
if (_waitCnt >= _bufused) { // signal waiting thread(s)
_cond.notify_one();
}
}
FNET_Packet*
FNET_PacketQueue::DequeuePacket(FNET_Context *context)
{
FNET_Packet *packet = nullptr;
std::unique_lock<std::mutex> guard(_lock);
_waitCnt++;
while (_bufused == 0) {
_cond.wait(guard);
}
_waitCnt--;
packet = _buf[_out_pos]._packet;
*context = _buf[_out_pos]._context;
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
_bufused--;
return packet;
}
FNET_Packet*
FNET_PacketQueue::DequeuePacket(uint32_t maxwait, FNET_Context *context)
{
FNET_Packet *packet = nullptr;
FastOS_Time startTime;
int waitTime;
if (maxwait > 0)
startTime.SetNow();
std::unique_lock<std::mutex> guard(_lock);
if (maxwait > 0) {
bool timeout = false;
_waitCnt++;
while ((_bufused == 0) && !timeout && (waitTime = (int)(maxwait - startTime.MilliSecsToNow())) > 0) {
timeout = _cond.wait_for(guard, std::chrono::milliseconds(waitTime)) == std::cv_status::timeout;
}
_waitCnt--;
}
if (_bufused > 0) {
packet = _buf[_out_pos]._packet;
*context = _buf[_out_pos]._context;
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
_bufused--;
}
return packet;
}
void
FNET_PacketQueue::Print(uint32_t indent)
{
std::lock_guard<std::mutex> guard(_lock);
uint32_t i = _out_pos;
uint32_t cnt = _bufused;
printf("%*sFNET_PacketQueue {\n", indent, "");
printf("%*s bufsize : %d\n", indent, "", _bufsize);
printf("%*s bufused : %d\n", indent, "", _bufused);
printf("%*s in_pos : %d\n", indent, "", _in_pos);
printf("%*s out_pos : %d\n", indent, "", _out_pos);
printf("%*s waitCnt : %d\n", indent, "", _waitCnt);
for (; cnt > 0; i++, cnt--) {
if (i == _bufsize)
i = 0; // wrap around
_buf[i]._packet->Print(indent + 2);
_buf[i]._context.Print(indent + 2);
}
printf("%*s}\n", indent, "");
}
<commit_msg>Only ignore warning on gcc 8<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "packetqueue.h"
#include "packet.h"
#include <vespa/fastos/time.h>
#include <cassert>
#include <chrono>
void
FNET_PacketQueue_NoLock::ExpandBuf(uint32_t needentries)
{
uint32_t oldsize = _bufsize;
if (_bufsize < 8)
_bufsize = 8;
while (_bufsize < _bufused + needentries)
_bufsize *= 2;
_QElem *newbuf = static_cast<_QElem *>(malloc(sizeof(_QElem) * _bufsize));
assert(newbuf != nullptr);
if (_bufused == 0) { // EMPTY
// BUFFER: |....................|
// USED: |....................|
} else if (_in_pos > _out_pos) { // NON-WRAPPED
// BUFFER: |....................|
// USED: |....############....|
// rOfs rLen
uint32_t rOfs = _out_pos;
uint32_t rLen = (_in_pos - _out_pos);
//TODO Rewrite to pure C++
#pragma GCC diagnostic push
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
memcpy(newbuf + rOfs, _buf + rOfs, rLen * sizeof(_QElem));
#pragma GCC diagnostic pop
} else { // WRAPPED
// BUFFER: |....................|
// USED: |######........######|
// r1Len r2Len
uint32_t r1Len = _in_pos;
uint32_t r2Len = (oldsize - _out_pos);
#pragma GCC diagnostic push
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
memcpy(newbuf, _buf, r1Len * sizeof(_QElem));
memcpy(newbuf + _bufsize - r2Len, _buf + oldsize - r2Len, r2Len * sizeof(_QElem));
#pragma GCC diagnostic pop
_out_pos += _bufsize - oldsize;
}
free(_buf);
_buf = newbuf;
}
FNET_PacketQueue_NoLock::FNET_PacketQueue_NoLock(uint32_t len,
HP_RetCode hpRetCode)
: _buf(nullptr),
_bufsize(len),
_bufused(0),
_in_pos(0),
_out_pos(0),
_hpRetCode(hpRetCode)
{
_buf = static_cast<_QElem *>(malloc(sizeof(_QElem) * len));
assert(_buf != nullptr);
}
FNET_PacketQueue_NoLock::~FNET_PacketQueue_NoLock()
{
DiscardPackets_NoLock();
free(_buf);
}
FNET_IPacketHandler::HP_RetCode
FNET_PacketQueue_NoLock::HandlePacket(FNET_Packet *packet,
FNET_Context context)
{
QueuePacket_NoLock(packet, context);
return _hpRetCode;
}
void
FNET_PacketQueue_NoLock::QueuePacket_NoLock(FNET_Packet *packet,
FNET_Context context)
{
if (packet == nullptr)
return;
EnsureFree();
_buf[_in_pos]._packet = packet;
_buf[_in_pos]._context = context;
if (++_in_pos == _bufsize)
_in_pos = 0; // wrap around.
_bufused++;
}
FNET_Packet*
FNET_PacketQueue_NoLock::DequeuePacket_NoLock(FNET_Context *context)
{
assert(context != nullptr);
FNET_Packet *packet = nullptr;
if (_bufused > 0) {
packet = _buf[_out_pos]._packet;
__builtin_prefetch(packet, 0);
*context = _buf[_out_pos]._context;
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
_bufused--;
}
return packet;
}
uint32_t
FNET_PacketQueue_NoLock::FlushPackets_NoLock(FNET_PacketQueue_NoLock *target)
{
uint32_t cnt = _bufused;
target->EnsureFree(cnt);
for (; _bufused > 0; _bufused--, target->_bufused++) {
target->_buf[target->_in_pos]._packet = _buf[_out_pos]._packet;
target->_buf[target->_in_pos]._context = _buf[_out_pos]._context;
if (++target->_in_pos == target->_bufsize)
target->_in_pos = 0; // wrap around.
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around.
}
assert(_out_pos == _in_pos);
return cnt;
}
void
FNET_PacketQueue_NoLock::DiscardPackets_NoLock()
{
for (; _bufused > 0; _bufused--) {
_buf[_out_pos]._packet->Free(); // discard packet
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
}
assert(_out_pos == _in_pos);
}
void
FNET_PacketQueue_NoLock::Print(uint32_t indent)
{
uint32_t i = _out_pos;
uint32_t cnt = _bufused;
printf("%*sFNET_PacketQueue_NoLock {\n", indent, "");
printf("%*s bufsize : %d\n", indent, "", _bufsize);
printf("%*s bufused : %d\n", indent, "", _bufused);
printf("%*s in_pos : %d\n", indent, "", _in_pos);
printf("%*s out_pos : %d\n", indent, "", _out_pos);
for (; cnt > 0; i++, cnt--) {
if (i == _bufsize)
i = 0; // wrap around
_buf[i]._packet->Print(indent + 2);
_buf[i]._context.Print(indent + 2);
}
printf("%*s}\n", indent, "");
}
//------------------------------------------------------------------
FNET_PacketQueue::FNET_PacketQueue(uint32_t len,
HP_RetCode hpRetCode)
: FNET_PacketQueue_NoLock(len, hpRetCode),
_lock(),
_cond(),
_waitCnt(0)
{
}
FNET_PacketQueue::~FNET_PacketQueue()
{
}
FNET_IPacketHandler::HP_RetCode
FNET_PacketQueue::HandlePacket(FNET_Packet *packet,
FNET_Context context)
{
QueuePacket(packet, context);
return _hpRetCode;
}
void
FNET_PacketQueue::QueuePacket(FNET_Packet *packet, FNET_Context context)
{
assert(packet != nullptr);
std::lock_guard<std::mutex> guard(_lock);
EnsureFree();
_buf[_in_pos]._packet = packet; // insert packet ref.
_buf[_in_pos]._context = context;
if (++_in_pos == _bufsize)
_in_pos = 0; // wrap around.
_bufused++;
if (_waitCnt >= _bufused) { // signal waiting thread(s)
_cond.notify_one();
}
}
FNET_Packet*
FNET_PacketQueue::DequeuePacket(FNET_Context *context)
{
FNET_Packet *packet = nullptr;
std::unique_lock<std::mutex> guard(_lock);
_waitCnt++;
while (_bufused == 0) {
_cond.wait(guard);
}
_waitCnt--;
packet = _buf[_out_pos]._packet;
*context = _buf[_out_pos]._context;
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
_bufused--;
return packet;
}
FNET_Packet*
FNET_PacketQueue::DequeuePacket(uint32_t maxwait, FNET_Context *context)
{
FNET_Packet *packet = nullptr;
FastOS_Time startTime;
int waitTime;
if (maxwait > 0)
startTime.SetNow();
std::unique_lock<std::mutex> guard(_lock);
if (maxwait > 0) {
bool timeout = false;
_waitCnt++;
while ((_bufused == 0) && !timeout && (waitTime = (int)(maxwait - startTime.MilliSecsToNow())) > 0) {
timeout = _cond.wait_for(guard, std::chrono::milliseconds(waitTime)) == std::cv_status::timeout;
}
_waitCnt--;
}
if (_bufused > 0) {
packet = _buf[_out_pos]._packet;
*context = _buf[_out_pos]._context;
if (++_out_pos == _bufsize)
_out_pos = 0; // wrap around
_bufused--;
}
return packet;
}
void
FNET_PacketQueue::Print(uint32_t indent)
{
std::lock_guard<std::mutex> guard(_lock);
uint32_t i = _out_pos;
uint32_t cnt = _bufused;
printf("%*sFNET_PacketQueue {\n", indent, "");
printf("%*s bufsize : %d\n", indent, "", _bufsize);
printf("%*s bufused : %d\n", indent, "", _bufused);
printf("%*s in_pos : %d\n", indent, "", _in_pos);
printf("%*s out_pos : %d\n", indent, "", _out_pos);
printf("%*s waitCnt : %d\n", indent, "", _waitCnt);
for (; cnt > 0; i++, cnt--) {
if (i == _bufsize)
i = 0; // wrap around
_buf[i]._packet->Print(indent + 2);
_buf[i]._context.Print(indent + 2);
}
printf("%*s}\n", indent, "");
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "stmt.h"
#include "view.h"
BasicBlock::BasicBlock(int init_id) : id(init_id) {}
#define BB_START() \
basicBlock = new BasicBlock(id++)
#define BB_ADD(expr) \
basicBlock->exprs.add(expr)
#define BB_ADD_LS(exprls) \
for_alist(expr, exprls) { \
BB_ADD(expr); \
}
#define BB_STOP() \
fn->basicBlocks->add(basicBlock); \
basicBlock = NULL
#define BB_RESTART() \
BB_STOP(); \
BB_START()
#define BBB(stmt) \
if (stmt) { \
buildBasicBlocks(fn, stmt); \
}
#define BB_THREAD(in, out) \
out->ins.add(in); \
in->outs.add(out)
void buildBasicBlocks(FnSymbol* fn, Expr* stmt) {
static BasicBlock* basicBlock;
static Map<LabelSymbol*,Vec<BasicBlock*>*> gotoMaps;
static Map<LabelSymbol*,BasicBlock*> labelMaps;
static int id;
if (!stmt) {
if (fn->basicBlocks) {
forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
delete bb;
}
delete fn->basicBlocks;
}
fn->basicBlocks = new Vec<BasicBlock*>();
gotoMaps.clear();
labelMaps.clear();
id = 0;
BB_START();
BBB(fn->body);
BB_STOP();
} else {
if (BlockStmt* s = toBlockStmt(stmt)) {
if (s->loopInfo) {
BasicBlock* top = basicBlock;
BB_RESTART();
BB_ADD(s->loopInfo);
BasicBlock* loopTop = basicBlock;
for_alist(stmt, s->body) {
BBB(stmt);
}
BasicBlock* loopBottom = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
BB_THREAD(top, loopTop);
BB_THREAD(loopBottom, bottom);
BB_THREAD(loopBottom, loopTop);
BB_THREAD(top, bottom);
} else {
for_alist(stmt, s->body) {
BBB(stmt);
}
}
} else if (CondStmt* s = toCondStmt(stmt)) {
BB_ADD(s->condExpr);
BasicBlock* top = basicBlock;
BB_RESTART();
BasicBlock* thenTop = basicBlock;
BBB(s->thenStmt);
BasicBlock* thenBottom = basicBlock;
BB_RESTART();
BasicBlock* elseTop = basicBlock;
BBB(s->elseStmt);
BasicBlock* elseBottom = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
BB_THREAD(top, thenTop);
BB_THREAD(top, elseTop);
BB_THREAD(thenBottom, bottom);
BB_THREAD(elseBottom, bottom);
} else if (GotoStmt* s = toGotoStmt(stmt)) {
LabelSymbol* label = toLabelSymbol(s->label);
if (BasicBlock* bb = labelMaps.get(label)) {
BB_THREAD(basicBlock, bb);
} else {
Vec<BasicBlock*>* vbb = gotoMaps.get(label);
if (!vbb)
vbb = new Vec<BasicBlock*>();
vbb->add(basicBlock);
gotoMaps.put(label, vbb);
}
BB_RESTART();
} else {
DefExpr* def = toDefExpr(stmt);
if (def && toLabelSymbol(def->sym)) {
BasicBlock* top = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
BB_THREAD(top, bottom);
LabelSymbol* label = toLabelSymbol(def->sym);
if (Vec<BasicBlock*>* vbb = gotoMaps.get(label)) {
forv_Vec(BasicBlock, basicBlock, *vbb) {
BB_THREAD(basicBlock, bottom);
}
}
labelMaps.put(label, bottom);
} else
BB_ADD(stmt);
}
}
}
void buildLocalsVectorMap(FnSymbol* fn,
Vec<Symbol*>& locals,
Map<Symbol*,int>& localMap) {
int i = 0;
forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
forv_Vec(Expr, expr, bb->exprs) {
if (DefExpr* def = toDefExpr(expr)) {
if (toVarSymbol(def->sym)) {
locals.add(def->sym);
localMap.put(def->sym, i++);
}
}
}
}
}
void buildDefsVectorMap(FnSymbol* fn,
Vec<Symbol*>& locals,
Vec<SymExpr*>& defs,
Map<SymExpr*,int>& defMap) {
int i = 0;
forv_Vec(Symbol, local, locals) {
forv_Vec(SymExpr, se, local->defs) {
defs.add(se);
defMap.put(se, i++);
}
}
}
void buildDefUseSets(FnSymbol* fn,
Vec<Symbol*>& locals,
Vec<SymExpr*>& useSet,
Vec<SymExpr*>& defSet) {
compute_sym_uses(fn);
forv_Vec(Symbol, local, locals) {
forv_Vec(SymExpr, se, local->defs) {
defSet.set_add(se);
}
forv_Vec(SymExpr, se, local->uses) {
useSet.set_add(se);
}
}
}
//#define DEBUG_FLOW
void backwardFlowAnalysis(FnSymbol* fn,
Vec<Vec<bool>*>& GEN,
Vec<Vec<bool>*>& KILL,
Vec<Vec<bool>*>& IN,
Vec<Vec<bool>*>& OUT) {
bool iterate = true;
while (iterate) {
iterate = false;
int i = 0;
forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
for (int j = 0; j < IN.v[i]->n; j++) {
bool new_in = (OUT.v[i]->v[j] & !KILL.v[i]->v[j]) | GEN.v[i]->v[j];
if (new_in != IN.v[i]->v[j]) {
IN.v[i]->v[j] = new_in;
iterate = true;
}
bool new_out = false;
forv_Vec(BasicBlock, bbout, bb->outs) {
new_out = new_out | IN.v[bbout->id]->v[j];
}
if (new_out != OUT.v[i]->v[j]) {
OUT.v[i]->v[j] = new_out;
iterate = true;
}
}
i++;
}
#ifdef DEBUG_FLOW
printf("IN\n"); printBitVectorSets(IN);
printf("OUT\n"); printBitVectorSets(OUT);
#endif
}
}
void forwardFlowAnalysis(FnSymbol* fn,
Vec<Vec<bool>*>& GEN,
Vec<Vec<bool>*>& KILL,
Vec<Vec<bool>*>& IN,
Vec<Vec<bool>*>& OUT,
bool intersect) {
int nbbq = fn->basicBlocks->n; // size of bb queue
int* bbq = (int*)malloc(nbbq*sizeof(int)); // bb queue
bool* bbs = (bool*)malloc(nbbq*sizeof(bool)); // bb set (bbs[i]: is ith bb in bbq?)
int iq = -1, nq = nbbq-1; // index to first and last bb in bbq
for (int i = 0; i < fn->basicBlocks->n; i++) {
bbq[i] = i;
bbs[i] = true;
}
while (iq != nq) {
iq = (iq + 1) % nbbq;
int i = bbq[iq];
bbs[i] = false;
#ifdef DEBUG_FLOW
if (iq == 0) {
printf("IN\n"); debug_flow_print_set(IN);
printf("OUT\n"); debug_flow_print_set(OUT);
}
#endif
BasicBlock* bb = fn->basicBlocks->v[i];
bool change = false;
for (int j = 0; j < IN.v[i]->n; j++) {
if (bb->ins.n > 0) {
bool new_in = intersect;
forv_Vec(BasicBlock, bbin, bb->ins) {
if (intersect)
new_in = new_in & OUT.v[bbin->id]->v[j];
else
new_in = new_in | OUT.v[bbin->id]->v[j];
}
if (new_in != IN.v[i]->v[j]) {
IN.v[i]->v[j] = new_in;
change = true;
}
}
bool new_out = (IN.v[i]->v[j] & !KILL.v[i]->v[j]) | GEN.v[i]->v[j];
if (new_out != OUT.v[i]->v[j]) {
OUT.v[i]->v[j] = new_out;
change = true;
}
}
if (change) {
forv_Vec(BasicBlock, bbout, bb->outs) {
if (!bbs[bbout->id]) {
nq = (nq + 1) % nbbq;
bbs[bbout->id] = true;
bbq[nq] = bbout->id;
}
}
}
}
free(bbq);
free(bbs);
}
void printBasicBlocks(FnSymbol* fn) {
forv_Vec(BasicBlock, b, *fn->basicBlocks) {
printf("%2d: ", b->id);
forv_Vec(BasicBlock, bb, b->ins) {
printf("%d ", bb->id);
}
printf(" > ");
forv_Vec(BasicBlock, bb, b->outs) {
printf("%d ", bb->id);
}
printf("\n");
forv_Vec(Expr, expr, b->exprs) {
list_view_noline(expr);
}
printf("\n");
}
}
void printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {
printf("Local Variables\n");
forv_Vec(Symbol, local, locals) {
printf("%2d: %s[%d]\n", localMap.get(local), local->name, local->id);
}
printf("\n");
}
void printDefsVector(Vec<SymExpr*> defs, Map<SymExpr*,int>& defMap) {
printf("Variable Definitions\n");
forv_Vec(SymExpr, def, defs) {
printf("%2d: %s[%d] in %d\n", defMap.get(def), def->var->name,
def->var->id, def->getStmtExpr()->id);
}
printf("\n");
}
void printLocalsVectorSets(Vec<Vec<bool>*>& sets, Vec<Symbol*> locals) {
int i = 0;
forv_Vec(Vec<bool>, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->n; j++) {
if (set->v[j])
printf("%s[%d] ", locals.v[j]->name, locals.v[j]->id);
}
printf("\n");
i++;
}
printf("\n");
}
void printBitVectorSets(Vec<Vec<bool>*>& sets) {
int i = 0;
forv_Vec(Vec<bool>, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->n; j++) {
printf("%d", (set->v[j]) ? 1 : 0);
if ((j+1) % 10 == 0) printf(" ");
}
printf("\n");
i++;
}
printf("\n");
}
<commit_msg><commit_after>#include <stdlib.h>
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "stmt.h"
#include "view.h"
BasicBlock::BasicBlock(int init_id) : id(init_id) {}
#define BB_START() \
basicBlock = new BasicBlock(id++)
#define BB_ADD(expr) \
basicBlock->exprs.add(expr)
#define BB_ADD_LS(exprls) \
for_alist(expr, exprls) { \
BB_ADD(expr); \
}
#define BB_STOP() \
fn->basicBlocks->add(basicBlock); \
basicBlock = NULL
#define BB_RESTART() \
BB_STOP(); \
BB_START()
#define BBB(stmt) \
if (stmt) { \
buildBasicBlocks(fn, stmt); \
}
#define BB_THREAD(in, out) \
out->ins.add(in); \
in->outs.add(out)
void buildBasicBlocks(FnSymbol* fn, Expr* stmt) {
static BasicBlock* basicBlock;
static Map<LabelSymbol*,Vec<BasicBlock*>*> gotoMaps;
static Map<LabelSymbol*,BasicBlock*> labelMaps;
static int id;
if (!stmt) {
if (fn->basicBlocks) {
forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
delete bb;
}
delete fn->basicBlocks;
}
fn->basicBlocks = new Vec<BasicBlock*>();
gotoMaps.clear();
labelMaps.clear();
id = 0;
BB_START();
BBB(fn->body);
BB_STOP();
} else {
if (BlockStmt* s = toBlockStmt(stmt)) {
if (s->loopInfo) {
BasicBlock* top = basicBlock;
BB_RESTART();
BB_ADD(s->loopInfo);
BasicBlock* loopTop = basicBlock;
for_alist(stmt, s->body) {
BBB(stmt);
}
BasicBlock* loopBottom = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
BB_THREAD(top, loopTop);
BB_THREAD(loopBottom, bottom);
BB_THREAD(loopBottom, loopTop);
BB_THREAD(top, bottom);
} else {
for_alist(stmt, s->body) {
BBB(stmt);
}
}
} else if (CondStmt* s = toCondStmt(stmt)) {
BB_ADD(s->condExpr);
BasicBlock* top = basicBlock;
BB_RESTART();
BasicBlock* thenTop = basicBlock;
BBB(s->thenStmt);
BasicBlock* thenBottom = basicBlock;
BB_RESTART();
BasicBlock* elseTop = basicBlock;
BBB(s->elseStmt);
BasicBlock* elseBottom = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
BB_THREAD(top, thenTop);
BB_THREAD(top, elseTop);
BB_THREAD(thenBottom, bottom);
BB_THREAD(elseBottom, bottom);
} else if (GotoStmt* s = toGotoStmt(stmt)) {
LabelSymbol* label = toLabelSymbol(s->label);
if (BasicBlock* bb = labelMaps.get(label)) {
BB_THREAD(basicBlock, bb);
} else {
Vec<BasicBlock*>* vbb = gotoMaps.get(label);
if (!vbb)
vbb = new Vec<BasicBlock*>();
vbb->add(basicBlock);
gotoMaps.put(label, vbb);
}
BB_RESTART();
} else {
DefExpr* def = toDefExpr(stmt);
if (def && toLabelSymbol(def->sym)) {
BasicBlock* top = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
BB_THREAD(top, bottom);
LabelSymbol* label = toLabelSymbol(def->sym);
if (Vec<BasicBlock*>* vbb = gotoMaps.get(label)) {
forv_Vec(BasicBlock, basicBlock, *vbb) {
BB_THREAD(basicBlock, bottom);
}
}
labelMaps.put(label, bottom);
} else
BB_ADD(stmt);
}
}
}
void buildLocalsVectorMap(FnSymbol* fn,
Vec<Symbol*>& locals,
Map<Symbol*,int>& localMap) {
int i = 0;
forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
forv_Vec(Expr, expr, bb->exprs) {
if (DefExpr* def = toDefExpr(expr)) {
if (toVarSymbol(def->sym)) {
locals.add(def->sym);
localMap.put(def->sym, i++);
}
}
}
}
}
void buildDefsVectorMap(FnSymbol* fn,
Vec<Symbol*>& locals,
Vec<SymExpr*>& defs,
Map<SymExpr*,int>& defMap) {
int i = 0;
forv_Vec(Symbol, local, locals) {
forv_Vec(SymExpr, se, local->defs) {
defs.add(se);
defMap.put(se, i++);
}
}
}
void buildDefUseSets(FnSymbol* fn,
Vec<Symbol*>& locals,
Vec<SymExpr*>& useSet,
Vec<SymExpr*>& defSet) {
compute_sym_uses(fn);
forv_Vec(Symbol, local, locals) {
forv_Vec(SymExpr, se, local->defs) {
defSet.set_add(se);
}
forv_Vec(SymExpr, se, local->uses) {
useSet.set_add(se);
}
}
}
//#define DEBUG_FLOW
void backwardFlowAnalysis(FnSymbol* fn,
Vec<Vec<bool>*>& GEN,
Vec<Vec<bool>*>& KILL,
Vec<Vec<bool>*>& IN,
Vec<Vec<bool>*>& OUT) {
bool iterate = true;
while (iterate) {
iterate = false;
int i = 0;
forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
for (int j = 0; j < IN.v[i]->n; j++) {
bool new_in = (OUT.v[i]->v[j] & !KILL.v[i]->v[j]) | GEN.v[i]->v[j];
if (new_in != IN.v[i]->v[j]) {
IN.v[i]->v[j] = new_in;
iterate = true;
}
bool new_out = false;
forv_Vec(BasicBlock, bbout, bb->outs) {
new_out = new_out | IN.v[bbout->id]->v[j];
}
if (new_out != OUT.v[i]->v[j]) {
OUT.v[i]->v[j] = new_out;
iterate = true;
}
}
i++;
}
#ifdef DEBUG_FLOW
printf("IN\n"); printBitVectorSets(IN);
printf("OUT\n"); printBitVectorSets(OUT);
#endif
}
}
void forwardFlowAnalysis(FnSymbol* fn,
Vec<Vec<bool>*>& GEN,
Vec<Vec<bool>*>& KILL,
Vec<Vec<bool>*>& IN,
Vec<Vec<bool>*>& OUT,
bool intersect) {
int nbbq = fn->basicBlocks->n; // size of bb queue
Vec<int> bbq;
Vec<bool> bbs;
int iq = -1, nq = nbbq-1; // index to first and last bb in bbq
for (int i = 0; i < fn->basicBlocks->n; i++) {
bbq.add(i);
bbs.add(true);
}
while (iq != nq) {
iq = (iq + 1) % nbbq;
int i = bbq.v[iq];
bbs.v[i] = false;
#ifdef DEBUG_FLOW
if (iq == 0) {
printf("IN\n"); debug_flow_print_set(IN);
printf("OUT\n"); debug_flow_print_set(OUT);
}
#endif
BasicBlock* bb = fn->basicBlocks->v[i];
bool change = false;
for (int j = 0; j < IN.v[i]->n; j++) {
if (bb->ins.n > 0) {
bool new_in = intersect;
forv_Vec(BasicBlock, bbin, bb->ins) {
if (intersect)
new_in = new_in & OUT.v[bbin->id]->v[j];
else
new_in = new_in | OUT.v[bbin->id]->v[j];
}
if (new_in != IN.v[i]->v[j]) {
IN.v[i]->v[j] = new_in;
change = true;
}
}
bool new_out = (IN.v[i]->v[j] & !KILL.v[i]->v[j]) | GEN.v[i]->v[j];
if (new_out != OUT.v[i]->v[j]) {
OUT.v[i]->v[j] = new_out;
change = true;
}
}
if (change) {
forv_Vec(BasicBlock, bbout, bb->outs) {
if (!bbs.v[bbout->id]) {
nq = (nq + 1) % nbbq;
bbs.v[bbout->id] = true;
bbq.v[nq] = bbout->id;
}
}
}
}
}
void printBasicBlocks(FnSymbol* fn) {
forv_Vec(BasicBlock, b, *fn->basicBlocks) {
printf("%2d: ", b->id);
forv_Vec(BasicBlock, bb, b->ins) {
printf("%d ", bb->id);
}
printf(" > ");
forv_Vec(BasicBlock, bb, b->outs) {
printf("%d ", bb->id);
}
printf("\n");
forv_Vec(Expr, expr, b->exprs) {
list_view_noline(expr);
}
printf("\n");
}
}
void printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {
printf("Local Variables\n");
forv_Vec(Symbol, local, locals) {
printf("%2d: %s[%d]\n", localMap.get(local), local->name, local->id);
}
printf("\n");
}
void printDefsVector(Vec<SymExpr*> defs, Map<SymExpr*,int>& defMap) {
printf("Variable Definitions\n");
forv_Vec(SymExpr, def, defs) {
printf("%2d: %s[%d] in %d\n", defMap.get(def), def->var->name,
def->var->id, def->getStmtExpr()->id);
}
printf("\n");
}
void printLocalsVectorSets(Vec<Vec<bool>*>& sets, Vec<Symbol*> locals) {
int i = 0;
forv_Vec(Vec<bool>, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->n; j++) {
if (set->v[j])
printf("%s[%d] ", locals.v[j]->name, locals.v[j]->id);
}
printf("\n");
i++;
}
printf("\n");
}
void printBitVectorSets(Vec<Vec<bool>*>& sets) {
int i = 0;
forv_Vec(Vec<bool>, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->n; j++) {
printf("%d", (set->v[j]) ? 1 : 0);
if ((j+1) % 10 == 0) printf(" ");
}
printf("\n");
i++;
}
printf("\n");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019-2020 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "mfx_common.h"
#if defined(MFX_ENABLE_H265_VIDEO_ENCODE) && (MFX_VERSION >= 1031)
#include "hevcehw_g12_rext.h"
#include "hevcehw_g9_legacy.h"
using namespace HEVCEHW;
using namespace HEVCEHW::Gen12;
const GUID RExt::DXVA2_Intel_Encode_HEVC_Main12 =
{ 0xd6d6bc4f, 0xd51a, 0x4712,{ 0x97, 0xe8, 0x75, 0x9, 0x17, 0xc8, 0x60, 0xfd } };
const GUID RExt::DXVA2_Intel_Encode_HEVC_Main422_12 =
{ 0x7fef652d, 0x3233, 0x44df,{ 0xac, 0xf7, 0xec, 0xfb, 0x58, 0x4d, 0xab, 0x35 } };
const GUID RExt::DXVA2_Intel_Encode_HEVC_Main444_12 =
{ 0xf8fa34b7, 0x93f5, 0x45a4,{ 0xbf, 0xc0, 0x38, 0x17, 0xce, 0xe6, 0xbb, 0x93 } };
void RExt::InitInternal(const FeatureBlocks& /*blocks*/, TPushII Push)
{
Push(BLK_SetRecInfo
, [](StorageRW& strg, StorageRW& local) -> mfxStatus
{
MFX_CHECK(!local.Contains(Gen9::Tmp::RecInfo::Key), MFX_ERR_NONE);
auto& par = Gen9::Glob::VideoParam::Get(strg);
mfxExtCodingOption3& CO3 = ExtBuffer::Get(par);
bool bG12SpecificRec =
CO3.TargetBitDepthLuma == 12
|| (CO3.TargetBitDepthLuma == 10
&& (CO3.TargetChromaFormatPlus1 == (1 + MFX_CHROMAFORMAT_YUV420)
|| CO3.TargetChromaFormatPlus1 == (1 + MFX_CHROMAFORMAT_YUV422)));
MFX_CHECK(bG12SpecificRec, MFX_ERR_NONE);
const std::map<mfxU16, std::function<void(mfxFrameInfo&, mfxU16&)>> mUpdateRecInfo =
{
{
mfxU16(1 + MFX_CHROMAFORMAT_YUV444)
, [](mfxFrameInfo& rec, mfxU16& type)
{
rec.FourCC = MFX_FOURCC_Y416;
rec.Width = mfx::align2_value<mfxU16>(rec.Width, 256 / 4);
rec.Height = mfx::align2_value<mfxU16>(rec.Height * 3 / 2, 8);
type = (
MFX_MEMTYPE_FROM_ENCODE
| MFX_MEMTYPE_DXVA2_DECODER_TARGET
| MFX_MEMTYPE_INTERNAL_FRAME);
}
}
, {
mfxU16(1 + MFX_CHROMAFORMAT_YUV422)
, [](mfxFrameInfo& rec, mfxU16& type)
{
rec.FourCC = MFX_FOURCC_Y216;
rec.Width /= 2;
rec.Height *= 2;
type = (
MFX_MEMTYPE_FROM_ENCODE
| MFX_MEMTYPE_DXVA2_DECODER_TARGET
| MFX_MEMTYPE_INTERNAL_FRAME);
}
}
, {
mfxU16(1 + MFX_CHROMAFORMAT_YUV420)
, [](mfxFrameInfo& rec, mfxU16&)
{
rec.FourCC = MFX_FOURCC_NV12;
rec.Width = mfx::align2_value(rec.Width, 32) * 2;
}
}
};
MFX_CHECK(mUpdateRecInfo.count(CO3.TargetChromaFormatPlus1), MFX_ERR_NONE);
auto pRI = make_storable<mfxFrameAllocRequest>(mfxFrameAllocRequest{});
auto& rec = pRI->Info;
rec = par.mfx.FrameInfo;
mUpdateRecInfo.at(CO3.TargetChromaFormatPlus1)(rec, pRI->Type);
rec.ChromaFormat = CO3.TargetChromaFormatPlus1 - 1;
rec.BitDepthLuma = CO3.TargetBitDepthLuma;
rec.BitDepthChroma = CO3.TargetBitDepthChroma;
local.Insert(Gen9::Tmp::RecInfo::Key, std::move(pRI));
return MFX_ERR_NONE;
});
}
mfxStatus RExt::SetGuid(mfxVideoParam& par, StorageRW& strg)
{
auto& fi = par.mfx.FrameInfo;
const GUID* pGUID = nullptr;
const mfxExtCodingOption3* pCO3 = ExtBuffer::Get(par);
MFX_CHECK(fi.BitDepthLuma <= 12, MFX_ERR_NONE);
MFX_CHECK(fi.BitDepthChroma <= 12, MFX_ERR_NONE);
MFX_CHECK(!pCO3 || pCO3->TargetBitDepthLuma <= 12, MFX_ERR_NONE);
MFX_CHECK(!pCO3 || pCO3->TargetBitDepthChroma <= 12, MFX_ERR_NONE);
MFX_CHECK(!IsOn(par.mfx.LowPower), MFX_ERR_NONE);
SetIf(pGUID, fi.FourCC == MFX_FOURCC_P016, &DXVA2_Intel_Encode_HEVC_Main12);
SetIf(pGUID, fi.FourCC == MFX_FOURCC_Y216, &DXVA2_Intel_Encode_HEVC_Main422_12);
SetIf(pGUID, fi.FourCC == MFX_FOURCC_Y416, &DXVA2_Intel_Encode_HEVC_Main444_12);
MFX_CHECK(pGUID, MFX_ERR_NONE);
Gen9::Glob::GUID::GetOrConstruct(strg) = *pGUID;
return MFX_ERR_NONE;
}
void RExt::Query1NoCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push)
{
Push(BLK_SetDefaultsCallChain
, [this](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus
{
auto& defaults = Glob::Defaults::GetOrConstruct(strg);
auto& bSet = defaults.SetForFeature[GetID()];
MFX_CHECK(!bSet, MFX_ERR_NONE);
defaults.CheckFourCC.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
return MFX_ERR_NONE;
});
defaults.CheckInputFormatByFourCC.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
auto& fi = par.mfx.FrameInfo;
mfxU32 invalid = 0;
invalid += CheckOrZero<mfxU16, 12, 0>(fi.BitDepthLuma);
invalid += CheckOrZero<mfxU16, 12, 0>(fi.BitDepthChroma);
invalid += (fi.FourCC == MFX_FOURCC_P016) && CheckOrZero<mfxU16, MFX_CHROMAFORMAT_YUV420>(fi.ChromaFormat);
invalid += (fi.FourCC == MFX_FOURCC_Y216) && CheckOrZero<mfxU16, MFX_CHROMAFORMAT_YUV422>(fi.ChromaFormat);
invalid += (fi.FourCC == MFX_FOURCC_Y416) && CheckOrZero<mfxU16, MFX_CHROMAFORMAT_YUV444>(fi.ChromaFormat);
MFX_CHECK(!invalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.CheckTargetBitDepth.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
mfxExtCodingOption3* pCO3 = ExtBuffer::Get(par);
MFX_CHECK(pCO3 && IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
mfxU32 invalid = 0;
invalid += CheckOrZero<mfxU16, 12, 0>(pCO3->TargetBitDepthLuma);
invalid += CheckOrZero<mfxU16, 12, 0>(pCO3->TargetBitDepthChroma);
MFX_CHECK(!invalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.CheckFourCCByTargetFormat.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
auto tcf = dpar.base.GetTargetChromaFormat(dpar);
auto& fi = par.mfx.FrameInfo;
mfxU32 invalid = 0;
invalid +=
(tcf == MFX_CHROMAFORMAT_YUV444 + 1)
&& Check<mfxU32, MFX_FOURCC_Y416>(fi.FourCC);
invalid +=
(tcf == MFX_CHROMAFORMAT_YUV422 + 1)
&& Check<mfxU32, MFX_FOURCC_Y216, MFX_FOURCC_Y416>(fi.FourCC);
MFX_CHECK(!invalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.CheckProfile.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
bool bInvalid = CheckOrZero<mfxU16, 0, MFX_PROFILE_HEVC_REXT>(par.mfx.CodecProfile);
MFX_CHECK(!bInvalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.GetMaxChromaByFourCC.Push(
[](Gen9::Defaults::TChain<mfxU16>::TExt prev
, const Gen9::Defaults::Param& dpar)
{
MFX_CHECK(IsRextFourCC(dpar.mvp.mfx.FrameInfo.FourCC), prev(dpar));
auto fcc = dpar.mvp.mfx.FrameInfo.FourCC;
return mfxU16(
(fcc == MFX_FOURCC_P016) * MFX_CHROMAFORMAT_YUV420
+ (fcc == MFX_FOURCC_Y216) * MFX_CHROMAFORMAT_YUV422
+ (fcc == MFX_FOURCC_Y416) * MFX_CHROMAFORMAT_YUV444);
});
defaults.GetMaxBitDepthByFourCC.Push(
[](Gen9::Defaults::TChain<mfxU16>::TExt prev
, const Gen9::Defaults::Param& dpar)
{
MFX_CHECK(IsRextFourCC(dpar.mvp.mfx.FrameInfo.FourCC), prev(dpar));
return mfxU16(12);
});
defaults.RunFastCopyWrapper.Push(
[](Gen9::Defaults::TRunFastCopyWrapper::TExt prev
, mfxFrameSurface1 &surfDst
, mfxU16 dstMemType
, mfxFrameSurface1 &surfSrc
, mfxU16 srcMemType)
{
// convert to native shift in core.CopyFrame() if required
surfDst.Info.Shift |=
surfDst.Info.FourCC == MFX_FOURCC_P016
|| surfDst.Info.FourCC == MFX_FOURCC_Y216;
return prev(
surfDst
, dstMemType
, surfSrc
, srcMemType);
});
bSet = true;
return MFX_ERR_NONE;
});
Push(BLK_SetGUID
, [this](const mfxVideoParam&, mfxVideoParam& par, StorageRW& strg) -> mfxStatus
{
//don't change GUID in Reset
MFX_CHECK(!strg.Contains(Glob::RealState::Key), MFX_ERR_NONE);
return SetGuid(par, strg);
});
}
void RExt::Query1WithCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push)
{
Push(BLK_CheckShift
, [](const mfxVideoParam&, mfxVideoParam& out, StorageW&) -> mfxStatus
{
auto& fi = out.mfx.FrameInfo;
bool bVideoMem = Gen9::Legacy::IsInVideoMem(out, ExtBuffer::Get(out));
bool bNeedShift =
(bVideoMem && !fi.Shift)
&& ( fi.FourCC == MFX_FOURCC_P016
|| fi.FourCC == MFX_FOURCC_Y216
|| fi.FourCC == MFX_FOURCC_Y416);
SetIf(fi.Shift, bNeedShift, 1);
MFX_CHECK(!bNeedShift, MFX_WRN_INCOMPATIBLE_VIDEO_PARAM);
return MFX_ERR_NONE;
});
Push(BLK_HardcodeCaps
, [](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus
{
Gen9::Glob::EncodeCaps::Get(strg).MaxEncodedBitDepth = 2;
return MFX_ERR_NONE;
});
}
#endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE)
<commit_msg>[HEVCe] Fixed recon surface creation for P010<commit_after>// Copyright (c) 2019-2020 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "mfx_common.h"
#if defined(MFX_ENABLE_H265_VIDEO_ENCODE) && (MFX_VERSION >= 1031)
#include "hevcehw_g12_rext.h"
#include "hevcehw_g9_legacy.h"
using namespace HEVCEHW;
using namespace HEVCEHW::Gen12;
const GUID RExt::DXVA2_Intel_Encode_HEVC_Main12 =
{ 0xd6d6bc4f, 0xd51a, 0x4712,{ 0x97, 0xe8, 0x75, 0x9, 0x17, 0xc8, 0x60, 0xfd } };
const GUID RExt::DXVA2_Intel_Encode_HEVC_Main422_12 =
{ 0x7fef652d, 0x3233, 0x44df,{ 0xac, 0xf7, 0xec, 0xfb, 0x58, 0x4d, 0xab, 0x35 } };
const GUID RExt::DXVA2_Intel_Encode_HEVC_Main444_12 =
{ 0xf8fa34b7, 0x93f5, 0x45a4,{ 0xbf, 0xc0, 0x38, 0x17, 0xce, 0xe6, 0xbb, 0x93 } };
void RExt::InitInternal(const FeatureBlocks& /*blocks*/, TPushII Push)
{
Push(BLK_SetRecInfo
, [](StorageRW& strg, StorageRW& local) -> mfxStatus
{
auto& par = Gen9::Glob::VideoParam::Get(strg);
mfxExtCodingOption3& CO3 = ExtBuffer::Get(par);
bool bG12SpecificRec =
CO3.TargetBitDepthLuma == 12
|| (CO3.TargetBitDepthLuma == 10
&& (CO3.TargetChromaFormatPlus1 == (1 + MFX_CHROMAFORMAT_YUV420)
|| CO3.TargetChromaFormatPlus1 == (1 + MFX_CHROMAFORMAT_YUV422)));
MFX_CHECK(bG12SpecificRec, MFX_ERR_NONE);
local.Erase(Gen9::Tmp::RecInfo::Key);
const std::map<mfxU16, std::function<void(mfxFrameInfo&, mfxU16&)>> mUpdateRecInfo =
{
{
mfxU16(1 + MFX_CHROMAFORMAT_YUV444)
, [](mfxFrameInfo& rec, mfxU16& type)
{
rec.FourCC = MFX_FOURCC_Y416;
rec.Width = mfx::align2_value<mfxU16>(rec.Width, 256 / 4);
rec.Height = mfx::align2_value<mfxU16>(rec.Height * 3 / 2, 8);
type = (
MFX_MEMTYPE_FROM_ENCODE
| MFX_MEMTYPE_DXVA2_DECODER_TARGET
| MFX_MEMTYPE_INTERNAL_FRAME);
}
}
, {
mfxU16(1 + MFX_CHROMAFORMAT_YUV422)
, [](mfxFrameInfo& rec, mfxU16& type)
{
rec.FourCC = MFX_FOURCC_Y216;
rec.Width /= 2;
rec.Height *= 2;
type = (
MFX_MEMTYPE_FROM_ENCODE
| MFX_MEMTYPE_DXVA2_DECODER_TARGET
| MFX_MEMTYPE_INTERNAL_FRAME);
}
}
, {
mfxU16(1 + MFX_CHROMAFORMAT_YUV420)
, [](mfxFrameInfo& rec, mfxU16&)
{
rec.FourCC = MFX_FOURCC_NV12;
rec.Width = mfx::align2_value(rec.Width, 32) * 2;
}
}
};
MFX_CHECK(mUpdateRecInfo.count(CO3.TargetChromaFormatPlus1), MFX_ERR_NONE);
auto pRI = make_storable<mfxFrameAllocRequest>(mfxFrameAllocRequest{});
auto& rec = pRI->Info;
rec = par.mfx.FrameInfo;
mUpdateRecInfo.at(CO3.TargetChromaFormatPlus1)(rec, pRI->Type);
rec.ChromaFormat = CO3.TargetChromaFormatPlus1 - 1;
rec.BitDepthLuma = CO3.TargetBitDepthLuma;
rec.BitDepthChroma = CO3.TargetBitDepthChroma;
local.Insert(Gen9::Tmp::RecInfo::Key, std::move(pRI));
return MFX_ERR_NONE;
});
}
mfxStatus RExt::SetGuid(mfxVideoParam& par, StorageRW& strg)
{
auto& fi = par.mfx.FrameInfo;
const GUID* pGUID = nullptr;
const mfxExtCodingOption3* pCO3 = ExtBuffer::Get(par);
MFX_CHECK(fi.BitDepthLuma <= 12, MFX_ERR_NONE);
MFX_CHECK(fi.BitDepthChroma <= 12, MFX_ERR_NONE);
MFX_CHECK(!pCO3 || pCO3->TargetBitDepthLuma <= 12, MFX_ERR_NONE);
MFX_CHECK(!pCO3 || pCO3->TargetBitDepthChroma <= 12, MFX_ERR_NONE);
MFX_CHECK(!IsOn(par.mfx.LowPower), MFX_ERR_NONE);
SetIf(pGUID, fi.FourCC == MFX_FOURCC_P016, &DXVA2_Intel_Encode_HEVC_Main12);
SetIf(pGUID, fi.FourCC == MFX_FOURCC_Y216, &DXVA2_Intel_Encode_HEVC_Main422_12);
SetIf(pGUID, fi.FourCC == MFX_FOURCC_Y416, &DXVA2_Intel_Encode_HEVC_Main444_12);
MFX_CHECK(pGUID, MFX_ERR_NONE);
Gen9::Glob::GUID::GetOrConstruct(strg) = *pGUID;
return MFX_ERR_NONE;
}
void RExt::Query1NoCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push)
{
Push(BLK_SetDefaultsCallChain
, [this](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus
{
auto& defaults = Glob::Defaults::GetOrConstruct(strg);
auto& bSet = defaults.SetForFeature[GetID()];
MFX_CHECK(!bSet, MFX_ERR_NONE);
defaults.CheckFourCC.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
return MFX_ERR_NONE;
});
defaults.CheckInputFormatByFourCC.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
auto& fi = par.mfx.FrameInfo;
mfxU32 invalid = 0;
invalid += CheckOrZero<mfxU16, 12, 0>(fi.BitDepthLuma);
invalid += CheckOrZero<mfxU16, 12, 0>(fi.BitDepthChroma);
invalid += (fi.FourCC == MFX_FOURCC_P016) && CheckOrZero<mfxU16, MFX_CHROMAFORMAT_YUV420>(fi.ChromaFormat);
invalid += (fi.FourCC == MFX_FOURCC_Y216) && CheckOrZero<mfxU16, MFX_CHROMAFORMAT_YUV422>(fi.ChromaFormat);
invalid += (fi.FourCC == MFX_FOURCC_Y416) && CheckOrZero<mfxU16, MFX_CHROMAFORMAT_YUV444>(fi.ChromaFormat);
MFX_CHECK(!invalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.CheckTargetBitDepth.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
mfxExtCodingOption3* pCO3 = ExtBuffer::Get(par);
MFX_CHECK(pCO3 && IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
mfxU32 invalid = 0;
invalid += CheckOrZero<mfxU16, 12, 0>(pCO3->TargetBitDepthLuma);
invalid += CheckOrZero<mfxU16, 12, 0>(pCO3->TargetBitDepthChroma);
MFX_CHECK(!invalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.CheckFourCCByTargetFormat.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
auto tcf = dpar.base.GetTargetChromaFormat(dpar);
auto& fi = par.mfx.FrameInfo;
mfxU32 invalid = 0;
invalid +=
(tcf == MFX_CHROMAFORMAT_YUV444 + 1)
&& Check<mfxU32, MFX_FOURCC_Y416>(fi.FourCC);
invalid +=
(tcf == MFX_CHROMAFORMAT_YUV422 + 1)
&& Check<mfxU32, MFX_FOURCC_Y216, MFX_FOURCC_Y416>(fi.FourCC);
MFX_CHECK(!invalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.CheckProfile.Push(
[](Gen9::Defaults::TCheckAndFix::TExt prev
, const Gen9::Defaults::Param& dpar
, mfxVideoParam& par)
{
MFX_CHECK(IsRextFourCC(par.mfx.FrameInfo.FourCC), prev(dpar, par));
bool bInvalid = CheckOrZero<mfxU16, 0, MFX_PROFILE_HEVC_REXT>(par.mfx.CodecProfile);
MFX_CHECK(!bInvalid, MFX_ERR_UNSUPPORTED);
return MFX_ERR_NONE;
});
defaults.GetMaxChromaByFourCC.Push(
[](Gen9::Defaults::TChain<mfxU16>::TExt prev
, const Gen9::Defaults::Param& dpar)
{
MFX_CHECK(IsRextFourCC(dpar.mvp.mfx.FrameInfo.FourCC), prev(dpar));
auto fcc = dpar.mvp.mfx.FrameInfo.FourCC;
return mfxU16(
(fcc == MFX_FOURCC_P016) * MFX_CHROMAFORMAT_YUV420
+ (fcc == MFX_FOURCC_Y216) * MFX_CHROMAFORMAT_YUV422
+ (fcc == MFX_FOURCC_Y416) * MFX_CHROMAFORMAT_YUV444);
});
defaults.GetMaxBitDepthByFourCC.Push(
[](Gen9::Defaults::TChain<mfxU16>::TExt prev
, const Gen9::Defaults::Param& dpar)
{
MFX_CHECK(IsRextFourCC(dpar.mvp.mfx.FrameInfo.FourCC), prev(dpar));
return mfxU16(12);
});
defaults.RunFastCopyWrapper.Push(
[](Gen9::Defaults::TRunFastCopyWrapper::TExt prev
, mfxFrameSurface1 &surfDst
, mfxU16 dstMemType
, mfxFrameSurface1 &surfSrc
, mfxU16 srcMemType)
{
// convert to native shift in core.CopyFrame() if required
surfDst.Info.Shift |=
surfDst.Info.FourCC == MFX_FOURCC_P016
|| surfDst.Info.FourCC == MFX_FOURCC_Y216;
return prev(
surfDst
, dstMemType
, surfSrc
, srcMemType);
});
bSet = true;
return MFX_ERR_NONE;
});
Push(BLK_SetGUID
, [this](const mfxVideoParam&, mfxVideoParam& par, StorageRW& strg) -> mfxStatus
{
//don't change GUID in Reset
MFX_CHECK(!strg.Contains(Glob::RealState::Key), MFX_ERR_NONE);
return SetGuid(par, strg);
});
}
void RExt::Query1WithCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push)
{
Push(BLK_CheckShift
, [](const mfxVideoParam&, mfxVideoParam& out, StorageW&) -> mfxStatus
{
auto& fi = out.mfx.FrameInfo;
bool bVideoMem = Gen9::Legacy::IsInVideoMem(out, ExtBuffer::Get(out));
bool bNeedShift =
(bVideoMem && !fi.Shift)
&& ( fi.FourCC == MFX_FOURCC_P016
|| fi.FourCC == MFX_FOURCC_Y216
|| fi.FourCC == MFX_FOURCC_Y416);
SetIf(fi.Shift, bNeedShift, 1);
MFX_CHECK(!bNeedShift, MFX_WRN_INCOMPATIBLE_VIDEO_PARAM);
return MFX_ERR_NONE;
});
Push(BLK_HardcodeCaps
, [](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus
{
Gen9::Glob::EncodeCaps::Get(strg).MaxEncodedBitDepth = 2;
return MFX_ERR_NONE;
});
}
#endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE)
<|endoftext|> |
<commit_before>#include "demo-common.h"
#include <glibmm/fileutils.h>
#include <glibmm/miscutils.h> //For Glib::build_filename().
#include <iostream>
#ifdef GLIBMM_WIN32
#undef DEMOCODEDIR
// TODO: Apply scorched earth tactics on code below.
static char *
get_democodedir(void)
{
static char *result = NULL;
if (result == NULL)
{
result = g_win32_get_package_installation_directory_of_module(0);
if (result == NULL)
result = "unknown-location";
result = g_strconcat (result, "\\share\\gtkmm-2.4\\demo", NULL);
}
return result;
}
#define DEMOCODEDIR get_democodedir()
#endif // GLIBMM_WIN32
/**
* demo_find_file:
* @base: base filename
*
* Looks for @base first in the current directory, then in the
* location where gtkmm will be installed on make install,
* returns the first file found.
*
* Return value: the filename, if found, else throws a Glib::FileError.
**/
std::string demo_find_file(const std::string& base)
{
if(Glib::file_test("gtk-logo-rgb.gif", Glib::FILE_TEST_EXISTS) &&
Glib::file_test (base, Glib::FILE_TEST_EXISTS))
{
return base;
}
else
{
std::string filename = Glib::build_filename(DEMOCODEDIR, base);
if(!Glib::file_test(filename, Glib::FILE_TEST_EXISTS))
{
Glib::ustring msg = "Cannot find demo data file " + base;
throw Glib::FileError(Glib::FileError::NO_SUCH_ENTITY, msg);
return Glib::ustring();
}
return filename;
}
}
<commit_msg>Demos: Fix Demo Data Path on Windows<commit_after>#include "demo-common.h"
#include <glibmm/fileutils.h>
#include <glibmm/miscutils.h> //For Glib::build_filename().
#include <iostream>
#ifdef GLIBMM_WIN32
#undef DEMOCODEDIR
// TODO: Apply scorched earth tactics on code below.
static char *
get_democodedir(void)
{
static char *result = NULL;
if (result == NULL)
{
result = g_win32_get_package_installation_directory_of_module(0);
if (result == NULL)
result = "unknown-location";
result = g_strconcat (result, "\\share\\gtkmm-3.0\\demo", NULL);
}
return result;
}
#define DEMOCODEDIR get_democodedir()
#endif // GLIBMM_WIN32
/**
* demo_find_file:
* @base: base filename
*
* Looks for @base first in the current directory, then in the
* location where gtkmm will be installed on make install,
* returns the first file found.
*
* Return value: the filename, if found, else throws a Glib::FileError.
**/
std::string demo_find_file(const std::string& base)
{
if(Glib::file_test("gtk-logo-rgb.gif", Glib::FILE_TEST_EXISTS) &&
Glib::file_test (base, Glib::FILE_TEST_EXISTS))
{
return base;
}
else
{
std::string filename = Glib::build_filename(DEMOCODEDIR, base);
if(!Glib::file_test(filename, Glib::FILE_TEST_EXISTS))
{
Glib::ustring msg = "Cannot find demo data file " + base;
throw Glib::FileError(Glib::FileError::NO_SUCH_ENTITY, msg);
return Glib::ustring();
}
return filename;
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <algorithm>
#include <mutex>
#include <sstream>
#include <dirent.h>
#include "text_helper.hpp"
namespace
{
/* The purpose of the DaaBufferHolder is to -DELAY-
* the loading of data until the first time the data
* is requested.
*/
class DataBufferLoader:public fastuidraw::reference_counted<DataBufferLoader>::default_base
{
public:
explicit
DataBufferLoader(const std::string &pfilename):
m_filename(pfilename)
{}
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase>
buffer(void)
{
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase> R;
m_mutex.lock();
if (!m_buffer)
{
m_buffer = FASTUIDRAWnew fastuidraw::DataBuffer(m_filename.c_str());
}
R = m_buffer;
m_mutex.unlock();
return R;
}
private:
std::string m_filename;
std::mutex m_mutex;
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase> m_buffer;
};
class FreeTypeFontGenerator:public fastuidraw::GlyphSelector::FontGeneratorBase
{
public:
FreeTypeFontGenerator(fastuidraw::reference_counted_ptr<DataBufferLoader> buffer,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> lib,
fastuidraw::FontFreeType::RenderParams render_params,
int face_index,
const fastuidraw::FontProperties &props):
m_buffer(buffer),
m_lib(lib),
m_render_params(render_params),
m_face_index(face_index),
m_props(props)
{}
virtual
fastuidraw::reference_counted_ptr<const fastuidraw::FontBase>
generate_font(void) const
{
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeFace::GeneratorBase> h;
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase> buffer;
fastuidraw::reference_counted_ptr<const fastuidraw::FontBase> font;
buffer = m_buffer->buffer();
h = FASTUIDRAWnew fastuidraw::FreeTypeFace::GeneratorMemory(buffer, m_face_index);
font = FASTUIDRAWnew fastuidraw::FontFreeType(h, m_props, m_render_params, m_lib);
return font;
}
virtual
const fastuidraw::FontProperties&
font_properties(void) const
{
return m_props;
}
private:
fastuidraw::reference_counted_ptr<DataBufferLoader> m_buffer;
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> m_lib;
fastuidraw::FontFreeType::RenderParams m_render_params;
int m_face_index;
fastuidraw::FontProperties m_props;
};
void
preprocess_text(std::string &text)
{
/* we want to change '\t' into 4 spaces
*/
std::string v;
v.reserve(text.size() + 4 * std::count(text.begin(), text.end(), '\t'));
for(std::string::const_iterator iter = text.begin(); iter != text.end(); ++iter)
{
if (*iter != '\t')
{
v.push_back(*iter);
}
else
{
v.push_back(' ');
}
}
text.swap(v);
}
void
add_fonts_from_file(const std::string &filename,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> lib,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector> glyph_selector,
fastuidraw::FontFreeType::RenderParams render_params)
{
FT_Error error_code;
FT_Face face(nullptr);
lib->lock();
error_code = FT_New_Face(lib->lib(), filename.c_str(), 0, &face);
lib->unlock();
if (error_code == 0 && face != nullptr && (face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
{
fastuidraw::reference_counted_ptr<DataBufferLoader> buffer_loader;
buffer_loader = FASTUIDRAWnew DataBufferLoader(filename);
for(unsigned int i = 0, endi = face->num_faces; i < endi; ++i)
{
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector::FontGeneratorBase> h;
std::ostringstream source_label;
fastuidraw::FontProperties props;
if (i != 0)
{
lib->lock();
FT_Done_Face(face);
FT_New_Face(lib->lib(), filename.c_str(), i, &face);
lib->unlock();
}
fastuidraw::FontFreeType::compute_font_properties_from_face(face, props);
source_label << filename << ":" << i;
props.source_label(source_label.str().c_str());
h = FASTUIDRAWnew FreeTypeFontGenerator(buffer_loader, lib, render_params, i, props);
glyph_selector->add_font_generator(h);
//std::cout << "add font: " << props << "\n";
}
}
lib->lock();
if (face != nullptr)
{
FT_Done_Face(face);
}
lib->unlock();
}
}
/////////////////////////////
// GlyphSetGenerator methods
GlyphSetGenerator::
GlyphSetGenerator(fastuidraw::GlyphRender r,
fastuidraw::reference_counted_ptr<const fastuidraw::FontFreeType> f,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeFace> face,
std::vector<fastuidraw::Glyph> &dst):
m_render(r),
m_font(f)
{
dst.resize(face->face()->num_glyphs);
m_dst = fastuidraw::c_array<fastuidraw::Glyph>(&dst[0], dst.size());
SDL_AtomicSet(&m_counter, 0);
}
int
GlyphSetGenerator::
execute(void *ptr)
{
unsigned int idx, K;
GlyphSetGenerator *p(static_cast<GlyphSetGenerator*>(ptr));
for(idx = SDL_AtomicAdd(&p->m_counter, 1), K = 0;
idx < p->m_dst.size();
idx = SDL_AtomicAdd(&p->m_counter, 1), ++K)
{
p->m_dst[idx] = fastuidraw::Glyph::create_glyph(p->m_render, p->m_font, idx);
}
return K;
}
void
GlyphSetGenerator::
generate(unsigned int num_threads,
fastuidraw::GlyphRender r,
fastuidraw::reference_counted_ptr<const fastuidraw::FontFreeType> f,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeFace> face,
std::vector<fastuidraw::Glyph> &dst,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphCache> glyph_cache,
std::vector<int> &cnts)
{
GlyphSetGenerator generator(r, f, face, dst);
std::vector<SDL_Thread*> threads;
cnts.clear();
cnts.resize(fastuidraw::t_max(1u, num_threads), 0);
if (num_threads < 2)
{
cnts[0] = execute(&generator);
}
else
{
for(int i = 0; i < num_threads; ++i)
{
threads.push_back(SDL_CreateThread(execute, "", &generator));
}
for(int i = 0; i < num_threads; ++i)
{
SDL_WaitThread(threads[i], &cnts[i]);
}
}
if (glyph_cache)
{
for(fastuidraw::Glyph glyph : dst)
{
glyph_cache->add_glyph(glyph);
}
}
}
//////////////////////////////
// global methods
void
create_formatted_text(std::istream &istr, fastuidraw::GlyphRender renderer,
float pixel_size,
fastuidraw::reference_counted_ptr<const fastuidraw::FontBase> font,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector> glyph_selector,
std::vector<fastuidraw::Glyph> &glyphs,
std::vector<fastuidraw::vec2> &positions,
std::vector<uint32_t> &character_codes,
std::vector<LineData> *line_data,
std::vector<fastuidraw::range_type<float> > *glyph_extents,
enum fastuidraw::PainterEnums::glyph_orientation orientation)
{
std::streampos current_position, end_position;
unsigned int loc(0);
fastuidraw::vec2 pen(0.0f, 0.0f);
std::string line, original_line;
float last_negative_tallest(0.0f);
current_position = istr.tellg();
istr.seekg(0, std::ios::end);
end_position = istr.tellg();
istr.seekg(current_position, std::ios::beg);
glyphs.resize(end_position - current_position);
positions.resize(end_position - current_position);
character_codes.resize(end_position - current_position);
if (glyph_extents)
{
glyph_extents->resize(end_position - current_position);
}
if (line_data)
{
line_data->clear();
}
fastuidraw::c_array<fastuidraw::Glyph> glyphs_ptr(cast_c_array(glyphs));
fastuidraw::c_array<fastuidraw::vec2> pos_ptr(cast_c_array(positions));
fastuidraw::c_array<uint32_t> char_codes_ptr(cast_c_array(character_codes));
fastuidraw::c_array<fastuidraw::range_type<float> > extents_ptr;
if (glyph_extents)
{
extents_ptr = cast_c_array(*glyph_extents);
}
while(getline(istr, line))
{
fastuidraw::c_array<fastuidraw::Glyph> sub_g;
fastuidraw::c_array<fastuidraw::vec2> sub_p;
fastuidraw::c_array<uint32_t> sub_ch;
fastuidraw::c_array<fastuidraw::range_type<float> > sub_extents;
float tallest, negative_tallest, offset;
bool empty_line;
LineData L;
float pen_y_advance;
empty_line = true;
tallest = 0.0f;
negative_tallest = 0.0f;
original_line = line;
preprocess_text(line);
sub_g = glyphs_ptr.sub_array(loc, line.length());
sub_p = pos_ptr.sub_array(loc, line.length());
sub_ch = char_codes_ptr.sub_array(loc, line.length());
if (glyph_extents)
{
sub_extents = extents_ptr.sub_array(loc, line.length());
}
glyph_selector->create_glyph_sequence(renderer, font, line.begin(), line.end(), sub_g.begin());
for(unsigned int i = 0, endi = sub_g.size(); i < endi; ++i)
{
fastuidraw::Glyph g;
g = sub_g[i];
sub_p[i] = pen;
sub_ch[i] = static_cast<uint32_t>(line[i]);
if (g.valid())
{
float ratio;
ratio = pixel_size / g.layout().m_units_per_EM;
if (glyph_extents)
{
sub_extents[i].m_begin = pen.x() + ratio * g.layout().m_horizontal_layout_offset.x();
sub_extents[i].m_end = sub_extents[i].m_begin + ratio * g.layout().m_size.x();
}
empty_line = false;
pen.x() += ratio * g.layout().m_advance.x();
tallest = std::max(tallest, ratio * (g.layout().m_horizontal_layout_offset.y() + g.layout().m_size.y()));
negative_tallest = std::min(negative_tallest, ratio * g.layout().m_horizontal_layout_offset.y());
}
}
if (empty_line)
{
offset = pixel_size + 1.0f;
pen_y_advance = offset;
}
else
{
if (orientation == fastuidraw::PainterEnums::y_increases_downwards)
{
offset = (tallest - last_negative_tallest);
pen_y_advance = offset;
}
else
{
offset = -negative_tallest;
pen_y_advance = tallest - negative_tallest;
}
}
for(unsigned int i = 0; i < sub_p.size(); ++i)
{
sub_p[i].y() += offset;
}
L.m_range.m_begin = loc;
L.m_range.m_end = loc + line.length();
L.m_horizontal_spread.m_begin = 0.0f;
L.m_horizontal_spread.m_end = pen.x();
L.m_vertical_spread.m_begin = pen.y() + offset - tallest;
L.m_vertical_spread.m_end = pen.y() + offset - negative_tallest;
pen.x() = 0.0f;
pen.y() += pen_y_advance + 1.0f;
loc += line.length();
last_negative_tallest = negative_tallest;
if (line_data && !empty_line)
{
L.m_horizontal_spread.sanitize();
L.m_vertical_spread.sanitize();
line_data->push_back(L);
}
}
glyphs.resize(loc);
positions.resize(loc);
character_codes.resize(loc);
if (glyph_extents)
{
glyph_extents->resize(loc);
}
}
void
add_fonts_from_path(const std::string &filename,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> lib,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector> glyph_selector,
fastuidraw::FontFreeType::RenderParams render_params)
{
DIR *dir;
struct dirent *entry;
dir = opendir(filename.c_str());
if (!dir)
{
add_fonts_from_file(filename, lib, glyph_selector, render_params);
return;
}
for(entry = readdir(dir); entry != nullptr; entry = readdir(dir))
{
std::string file;
file = entry->d_name;
if (file != ".." && file != ".")
{
add_fonts_from_path(filename + "/" + file, lib, glyph_selector, render_params);
}
}
closedir(dir);
}
fastuidraw::c_string
default_font(void)
{
#ifdef __WIN32
{
return "C:/Windows/Fonts/arial.ttf";
}
#else
{
return "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf";
}
#endif
}
fastuidraw::c_string
default_font_path(void)
{
#ifdef __WIN32
{
return "C:/Windows/Fonts";
}
#else
{
return "/usr/share/fonts/";
}
#endif
}
<commit_msg>demos: Correct compliation guard for WIN32<commit_after>#include <string>
#include <algorithm>
#include <mutex>
#include <sstream>
#include <dirent.h>
#include "text_helper.hpp"
namespace
{
/* The purpose of the DaaBufferHolder is to -DELAY-
* the loading of data until the first time the data
* is requested.
*/
class DataBufferLoader:public fastuidraw::reference_counted<DataBufferLoader>::default_base
{
public:
explicit
DataBufferLoader(const std::string &pfilename):
m_filename(pfilename)
{}
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase>
buffer(void)
{
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase> R;
m_mutex.lock();
if (!m_buffer)
{
m_buffer = FASTUIDRAWnew fastuidraw::DataBuffer(m_filename.c_str());
}
R = m_buffer;
m_mutex.unlock();
return R;
}
private:
std::string m_filename;
std::mutex m_mutex;
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase> m_buffer;
};
class FreeTypeFontGenerator:public fastuidraw::GlyphSelector::FontGeneratorBase
{
public:
FreeTypeFontGenerator(fastuidraw::reference_counted_ptr<DataBufferLoader> buffer,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> lib,
fastuidraw::FontFreeType::RenderParams render_params,
int face_index,
const fastuidraw::FontProperties &props):
m_buffer(buffer),
m_lib(lib),
m_render_params(render_params),
m_face_index(face_index),
m_props(props)
{}
virtual
fastuidraw::reference_counted_ptr<const fastuidraw::FontBase>
generate_font(void) const
{
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeFace::GeneratorBase> h;
fastuidraw::reference_counted_ptr<fastuidraw::DataBufferBase> buffer;
fastuidraw::reference_counted_ptr<const fastuidraw::FontBase> font;
buffer = m_buffer->buffer();
h = FASTUIDRAWnew fastuidraw::FreeTypeFace::GeneratorMemory(buffer, m_face_index);
font = FASTUIDRAWnew fastuidraw::FontFreeType(h, m_props, m_render_params, m_lib);
return font;
}
virtual
const fastuidraw::FontProperties&
font_properties(void) const
{
return m_props;
}
private:
fastuidraw::reference_counted_ptr<DataBufferLoader> m_buffer;
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> m_lib;
fastuidraw::FontFreeType::RenderParams m_render_params;
int m_face_index;
fastuidraw::FontProperties m_props;
};
void
preprocess_text(std::string &text)
{
/* we want to change '\t' into 4 spaces
*/
std::string v;
v.reserve(text.size() + 4 * std::count(text.begin(), text.end(), '\t'));
for(std::string::const_iterator iter = text.begin(); iter != text.end(); ++iter)
{
if (*iter != '\t')
{
v.push_back(*iter);
}
else
{
v.push_back(' ');
}
}
text.swap(v);
}
void
add_fonts_from_file(const std::string &filename,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> lib,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector> glyph_selector,
fastuidraw::FontFreeType::RenderParams render_params)
{
FT_Error error_code;
FT_Face face(nullptr);
lib->lock();
error_code = FT_New_Face(lib->lib(), filename.c_str(), 0, &face);
lib->unlock();
if (error_code == 0 && face != nullptr && (face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
{
fastuidraw::reference_counted_ptr<DataBufferLoader> buffer_loader;
buffer_loader = FASTUIDRAWnew DataBufferLoader(filename);
for(unsigned int i = 0, endi = face->num_faces; i < endi; ++i)
{
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector::FontGeneratorBase> h;
std::ostringstream source_label;
fastuidraw::FontProperties props;
if (i != 0)
{
lib->lock();
FT_Done_Face(face);
FT_New_Face(lib->lib(), filename.c_str(), i, &face);
lib->unlock();
}
fastuidraw::FontFreeType::compute_font_properties_from_face(face, props);
source_label << filename << ":" << i;
props.source_label(source_label.str().c_str());
h = FASTUIDRAWnew FreeTypeFontGenerator(buffer_loader, lib, render_params, i, props);
glyph_selector->add_font_generator(h);
//std::cout << "add font: " << props << "\n";
}
}
lib->lock();
if (face != nullptr)
{
FT_Done_Face(face);
}
lib->unlock();
}
}
/////////////////////////////
// GlyphSetGenerator methods
GlyphSetGenerator::
GlyphSetGenerator(fastuidraw::GlyphRender r,
fastuidraw::reference_counted_ptr<const fastuidraw::FontFreeType> f,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeFace> face,
std::vector<fastuidraw::Glyph> &dst):
m_render(r),
m_font(f)
{
dst.resize(face->face()->num_glyphs);
m_dst = fastuidraw::c_array<fastuidraw::Glyph>(&dst[0], dst.size());
SDL_AtomicSet(&m_counter, 0);
}
int
GlyphSetGenerator::
execute(void *ptr)
{
unsigned int idx, K;
GlyphSetGenerator *p(static_cast<GlyphSetGenerator*>(ptr));
for(idx = SDL_AtomicAdd(&p->m_counter, 1), K = 0;
idx < p->m_dst.size();
idx = SDL_AtomicAdd(&p->m_counter, 1), ++K)
{
p->m_dst[idx] = fastuidraw::Glyph::create_glyph(p->m_render, p->m_font, idx);
}
return K;
}
void
GlyphSetGenerator::
generate(unsigned int num_threads,
fastuidraw::GlyphRender r,
fastuidraw::reference_counted_ptr<const fastuidraw::FontFreeType> f,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeFace> face,
std::vector<fastuidraw::Glyph> &dst,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphCache> glyph_cache,
std::vector<int> &cnts)
{
GlyphSetGenerator generator(r, f, face, dst);
std::vector<SDL_Thread*> threads;
cnts.clear();
cnts.resize(fastuidraw::t_max(1u, num_threads), 0);
if (num_threads < 2)
{
cnts[0] = execute(&generator);
}
else
{
for(int i = 0; i < num_threads; ++i)
{
threads.push_back(SDL_CreateThread(execute, "", &generator));
}
for(int i = 0; i < num_threads; ++i)
{
SDL_WaitThread(threads[i], &cnts[i]);
}
}
if (glyph_cache)
{
for(fastuidraw::Glyph glyph : dst)
{
glyph_cache->add_glyph(glyph);
}
}
}
//////////////////////////////
// global methods
void
create_formatted_text(std::istream &istr, fastuidraw::GlyphRender renderer,
float pixel_size,
fastuidraw::reference_counted_ptr<const fastuidraw::FontBase> font,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector> glyph_selector,
std::vector<fastuidraw::Glyph> &glyphs,
std::vector<fastuidraw::vec2> &positions,
std::vector<uint32_t> &character_codes,
std::vector<LineData> *line_data,
std::vector<fastuidraw::range_type<float> > *glyph_extents,
enum fastuidraw::PainterEnums::glyph_orientation orientation)
{
std::streampos current_position, end_position;
unsigned int loc(0);
fastuidraw::vec2 pen(0.0f, 0.0f);
std::string line, original_line;
float last_negative_tallest(0.0f);
current_position = istr.tellg();
istr.seekg(0, std::ios::end);
end_position = istr.tellg();
istr.seekg(current_position, std::ios::beg);
glyphs.resize(end_position - current_position);
positions.resize(end_position - current_position);
character_codes.resize(end_position - current_position);
if (glyph_extents)
{
glyph_extents->resize(end_position - current_position);
}
if (line_data)
{
line_data->clear();
}
fastuidraw::c_array<fastuidraw::Glyph> glyphs_ptr(cast_c_array(glyphs));
fastuidraw::c_array<fastuidraw::vec2> pos_ptr(cast_c_array(positions));
fastuidraw::c_array<uint32_t> char_codes_ptr(cast_c_array(character_codes));
fastuidraw::c_array<fastuidraw::range_type<float> > extents_ptr;
if (glyph_extents)
{
extents_ptr = cast_c_array(*glyph_extents);
}
while(getline(istr, line))
{
fastuidraw::c_array<fastuidraw::Glyph> sub_g;
fastuidraw::c_array<fastuidraw::vec2> sub_p;
fastuidraw::c_array<uint32_t> sub_ch;
fastuidraw::c_array<fastuidraw::range_type<float> > sub_extents;
float tallest, negative_tallest, offset;
bool empty_line;
LineData L;
float pen_y_advance;
empty_line = true;
tallest = 0.0f;
negative_tallest = 0.0f;
original_line = line;
preprocess_text(line);
sub_g = glyphs_ptr.sub_array(loc, line.length());
sub_p = pos_ptr.sub_array(loc, line.length());
sub_ch = char_codes_ptr.sub_array(loc, line.length());
if (glyph_extents)
{
sub_extents = extents_ptr.sub_array(loc, line.length());
}
glyph_selector->create_glyph_sequence(renderer, font, line.begin(), line.end(), sub_g.begin());
for(unsigned int i = 0, endi = sub_g.size(); i < endi; ++i)
{
fastuidraw::Glyph g;
g = sub_g[i];
sub_p[i] = pen;
sub_ch[i] = static_cast<uint32_t>(line[i]);
if (g.valid())
{
float ratio;
ratio = pixel_size / g.layout().m_units_per_EM;
if (glyph_extents)
{
sub_extents[i].m_begin = pen.x() + ratio * g.layout().m_horizontal_layout_offset.x();
sub_extents[i].m_end = sub_extents[i].m_begin + ratio * g.layout().m_size.x();
}
empty_line = false;
pen.x() += ratio * g.layout().m_advance.x();
tallest = std::max(tallest, ratio * (g.layout().m_horizontal_layout_offset.y() + g.layout().m_size.y()));
negative_tallest = std::min(negative_tallest, ratio * g.layout().m_horizontal_layout_offset.y());
}
}
if (empty_line)
{
offset = pixel_size + 1.0f;
pen_y_advance = offset;
}
else
{
if (orientation == fastuidraw::PainterEnums::y_increases_downwards)
{
offset = (tallest - last_negative_tallest);
pen_y_advance = offset;
}
else
{
offset = -negative_tallest;
pen_y_advance = tallest - negative_tallest;
}
}
for(unsigned int i = 0; i < sub_p.size(); ++i)
{
sub_p[i].y() += offset;
}
L.m_range.m_begin = loc;
L.m_range.m_end = loc + line.length();
L.m_horizontal_spread.m_begin = 0.0f;
L.m_horizontal_spread.m_end = pen.x();
L.m_vertical_spread.m_begin = pen.y() + offset - tallest;
L.m_vertical_spread.m_end = pen.y() + offset - negative_tallest;
pen.x() = 0.0f;
pen.y() += pen_y_advance + 1.0f;
loc += line.length();
last_negative_tallest = negative_tallest;
if (line_data && !empty_line)
{
L.m_horizontal_spread.sanitize();
L.m_vertical_spread.sanitize();
line_data->push_back(L);
}
}
glyphs.resize(loc);
positions.resize(loc);
character_codes.resize(loc);
if (glyph_extents)
{
glyph_extents->resize(loc);
}
}
void
add_fonts_from_path(const std::string &filename,
fastuidraw::reference_counted_ptr<fastuidraw::FreeTypeLib> lib,
fastuidraw::reference_counted_ptr<fastuidraw::GlyphSelector> glyph_selector,
fastuidraw::FontFreeType::RenderParams render_params)
{
DIR *dir;
struct dirent *entry;
dir = opendir(filename.c_str());
if (!dir)
{
add_fonts_from_file(filename, lib, glyph_selector, render_params);
return;
}
for(entry = readdir(dir); entry != nullptr; entry = readdir(dir))
{
std::string file;
file = entry->d_name;
if (file != ".." && file != ".")
{
add_fonts_from_path(filename + "/" + file, lib, glyph_selector, render_params);
}
}
closedir(dir);
}
fastuidraw::c_string
default_font(void)
{
#ifdef _WIN32
{
return "C:/Windows/Fonts/arial.ttf";
}
#else
{
return "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf";
}
#endif
}
fastuidraw::c_string
default_font_path(void)
{
#ifdef _WIN32
{
return "C:/Windows/Fonts";
}
#else
{
return "/usr/share/fonts/";
}
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "bb.h"
#include "astutil.h"
#include "bitVec.h"
#include "expr.h"
#include "stlUtil.h"
#include "stmt.h"
#include "view.h"
#include <cstdlib>
BasicBlock::BasicBlock()
: id(nextid++) {}
#define BB_START() \
basicBlock = new BasicBlock()
// The assert tests that the expression we are adding to this basic block
// has not already been deleted.
#define BB_ADD(expr) \
do { \
INT_ASSERT(expr); \
basicBlock->exprs.push_back(expr); \
} while (0)
#define BB_STOP() \
fn->basicBlocks->push_back(Steal())
#define BB_RESTART() \
do { \
BB_STOP(); \
BB_START(); \
} while (0)
#define BBB(stmt) \
buildBasicBlocks(fn, stmt)
#define BB_THREAD(src, dst) \
do { \
(dst)->ins.push_back(src); \
(src)->outs.push_back(dst); \
} while (0)
//# Statics
BasicBlock* BasicBlock::basicBlock;
Map<LabelSymbol*,std::vector<BasicBlock*>*> BasicBlock::gotoMaps;
Map<LabelSymbol*,BasicBlock*> BasicBlock::labelMaps;
int BasicBlock::nextid;
// Returns true if the class invariants have been preserved.
bool BasicBlock::isOK()
{
// Expressions must be live (non-NULL);
for_vector(Expr, expr, exprs)
if (expr == 0) return false;
// Every in edge must have a corresponding out edge in the source block.
for_vector(BasicBlock, source, ins) {
bool found = false;
for_vector(BasicBlock, bb, source->outs)
if (bb == this) { found = true; break; }
if (!found) return false;
}
// Every out edge must have a corresponding in edge in the target block.
for_vector(BasicBlock, target, outs) {
bool found = false;
for_vector(BasicBlock, bb, target->ins)
if (bb == this) { found = true; break; }
if (!found) return false;
}
return true;
}
void BasicBlock::clear(FnSymbol* fn)
{
if (!fn->basicBlocks)
return;
for_vector(BasicBlock, bb, *fn->basicBlocks)
delete bb, bb = 0;
delete fn->basicBlocks; fn->basicBlocks = 0;
}
// Reset the shared statics.
void BasicBlock::reset(FnSymbol* fn)
{
clear(fn);
gotoMaps.clear();
labelMaps.clear();
fn->basicBlocks = new std::vector<BasicBlock*>();
nextid = 0;
}
BasicBlock* BasicBlock::Steal()
{
BasicBlock* temp = basicBlock;
basicBlock = 0;
return temp;
}
// This is the top-level (public) builder function.
void buildBasicBlocks(FnSymbol* fn)
{
BasicBlock::reset(fn);
BasicBlock::basicBlock = new BasicBlock(); // BB_START();
BasicBlock::buildBasicBlocks(fn, fn->body); // BBB(fn->body);
fn->basicBlocks->push_back(BasicBlock::Steal()); // BB_STOP();
INT_ASSERT(verifyBasicBlocks(fn));
}
void BasicBlock::buildBasicBlocks(FnSymbol* fn, Expr* stmt)
{
if (!stmt) return;
if (BlockStmt* s = toBlockStmt(stmt))
{
CallExpr* loop = toCallExpr(s->blockInfoGet());
if (loop)
{
bool cForLoop = loop->isPrimitive(PRIM_BLOCK_C_FOR_LOOP);
// for c for loops, add the init expr before the loop body
if (cForLoop) {
for_alist(stmt, toBlockStmt(loop->get(1))->body) { BBB(stmt); }
}
// mark the top of the loop
BasicBlock* top = basicBlock;
BB_RESTART();
// for c for loops, add the test expr at the loop top
if (cForLoop) {
for_alist(stmt, toBlockStmt(loop->get(2))->body) { BBB(stmt); }
}
// add the CallExpr that is the loop itself and then add the loops body
BB_ADD(loop);
BasicBlock* loopTop = basicBlock;
for_alist(stmt, s->body) {
BBB(stmt);
}
// for c for loops, add the incr expr after the loop body
if (cForLoop) {
for_alist(stmt, toBlockStmt(loop->get(3))->body) { BBB(stmt); }
}
BasicBlock* loopBottom = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
// thread the basic blocks of the pre-loop, loop, and post-loop together
BB_THREAD(top, loopTop);
BB_THREAD(loopBottom, bottom);
BB_THREAD(loopBottom, loopTop);
BB_THREAD(top, bottom);
}
else
{
for_alist(stmt, s->body)
BBB(stmt);
}
}
else if (CondStmt* s = toCondStmt(stmt))
{
INT_ASSERT(s->condExpr);
BB_ADD(s->condExpr);
BasicBlock* top = basicBlock;
BB_RESTART();
BB_THREAD(top, basicBlock);
BBB(s->thenStmt);
BasicBlock* thenBottom = basicBlock;
BB_RESTART();
if (s->elseStmt)
{
BB_THREAD(top, basicBlock);
BBB(s->elseStmt);
BasicBlock* elseBottom = basicBlock;
BB_RESTART();
BB_THREAD(elseBottom, basicBlock);
}
else
{
BB_THREAD(top, basicBlock);
}
BB_THREAD(thenBottom, basicBlock);
} else if (GotoStmt* s = toGotoStmt(stmt)) {
LabelSymbol* label = toLabelSymbol(toSymExpr(s->label)->var);
if (BasicBlock* bb = labelMaps.get(label)) {
BB_THREAD(basicBlock, bb);
} else {
std::vector<BasicBlock*>* vbb = gotoMaps.get(label);
if (!vbb)
vbb = new std::vector<BasicBlock*>();
vbb->push_back(basicBlock);
gotoMaps.put(label, vbb);
}
BB_ADD(s); // Put the goto at the end of its block.
BB_RESTART();
} else {
DefExpr* def = toDefExpr(stmt);
if (def && toLabelSymbol(def->sym)) {
// If a label appears in the middle of a block,
// we start a new block.
if (basicBlock->exprs.size() > 0)
{
BasicBlock* top = basicBlock;
BB_RESTART();
BB_THREAD(top, basicBlock);
}
BB_ADD(def); // Put the label def at the start of its block.
// OK, this statement is a label def, so get the label.
LabelSymbol* label = toLabelSymbol(def->sym);
// See if we have any unresolved references to this label,
// and resolve them.
if (std::vector<BasicBlock*>* vbb = gotoMaps.get(label)) {
for_vector(BasicBlock, bb, *vbb) {
BB_THREAD(bb, basicBlock);
}
}
labelMaps.put(label, basicBlock);
} else {
BB_ADD(stmt);
}
}
}
// Returns true if the basic block structure is OK, false otherwise.
bool verifyBasicBlocks(FnSymbol* fn)
{
for_vector(BasicBlock, bb, *fn->basicBlocks)
{
if (! bb->isOK())
return false;
}
return true;
}
void buildLocalsVectorMap(FnSymbol* fn,
Vec<Symbol*>& locals,
Map<Symbol*,int>& localMap) {
int i = 0;
for_vector(BasicBlock, bb, *fn->basicBlocks) {
for_vector(Expr, expr, bb->exprs) {
if (DefExpr* def = toDefExpr(expr)) {
if (toVarSymbol(def->sym)) {
locals.add(def->sym);
localMap.put(def->sym, i++);
}
}
}
}
}
//#define DEBUG_FLOW
void backwardFlowAnalysis(FnSymbol* fn,
std::vector<BitVec*>& GEN,
std::vector<BitVec*>& KILL,
std::vector<BitVec*>& IN,
std::vector<BitVec*>& OUT) {
bool iterate = true;
while (iterate) {
iterate = false;
int i = 0;
for_vector(BasicBlock, bb, *fn->basicBlocks) {
for (int j = 0; j < IN[i]->ndata; j++) {
unsigned new_in = (OUT[i]->data[j] & ~KILL[i]->data[j]) | GEN[i]->data[j];
if (new_in != IN[i]->data[j]) {
IN[i]->data[j] = new_in;
iterate = true;
}
unsigned new_out = 0;
for_vector(BasicBlock, bbout, bb->outs) {
new_out = new_out | IN[bbout->id]->data[j];
}
if (new_out != OUT[i]->data[j]) {
OUT[i]->data[j] = new_out;
iterate = true;
}
}
i++;
}
#ifdef DEBUG_FLOW
printf("IN\n"); printBitVectorSets(IN);
printf("OUT\n"); printBitVectorSets(OUT);
#endif
}
}
void forwardFlowAnalysis(FnSymbol* fn,
std::vector<BitVec*>& GEN,
std::vector<BitVec*>& KILL,
std::vector<BitVec*>& IN,
std::vector<BitVec*>& OUT,
bool intersect) {
size_t nbbq = fn->basicBlocks->size(); // size of bb queue
std::vector<int> bbq;
BitVec bbs(nbbq);
int iq = -1, nq = nbbq-1; // index to first and last bb in bbq
for (size_t i = 0; i < nbbq; i++) {
bbq.push_back(i);
bbs.set(i);
}
while (iq != nq) {
iq = (iq + 1) % nbbq;
int i = bbq[iq];
bbs.unset(i);
#ifdef DEBUG_FLOW
if (iq == 0) {
printf("IN\n"); printBitVectorSets(IN);
printf("OUT\n"); printBitVectorSets(OUT);
}
#endif
BasicBlock* bb = (*fn->basicBlocks)[i];
bool change = false;
for (int j = 0; j < IN[i]->ndata; j++) {
if (bb->ins.size() > 0) {
unsigned new_in = (intersect) ? (unsigned)(-1) : 0;
for_vector(BasicBlock, bbin, bb->ins) {
if (intersect)
new_in &= OUT[bbin->id]->data[j];
else
new_in |= OUT[bbin->id]->data[j];
}
if (new_in != IN[i]->data[j]) {
IN[i]->data[j] = new_in;
change = true;
}
}
unsigned new_out = (IN[i]->data[j] & ~KILL[i]->data[j]) | GEN[i]->data[j];
if (new_out != OUT[i]->data[j]) {
OUT[i]->data[j] = new_out;
change = true;
}
}
if (change) {
for_vector(BasicBlock, bbout, bb->outs) {
if (!bbs.get(bbout->id)) {
nq = (nq + 1) % nbbq;
bbs.set(bbout->id);
bbq[nq] = bbout->id;
}
}
}
}
}
void printBasicBlocks(FnSymbol* fn) {
for_vector(BasicBlock, b, *fn->basicBlocks) {
printf("%2d: ", b->id);
for_vector(BasicBlock, bb, b->ins) {
printf("%d ", bb->id);
}
printf(" > ");
for_vector(BasicBlock, bc, b->outs) {
printf("%d ", bc->id);
}
printf("\n");
for_vector(Expr, expr, b->exprs) {
if (expr)
list_view_noline(expr);
else
printf("0 (null)\n");
}
printf("\n");
}
}
void printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {
printf("Local Variables\n");
forv_Vec(Symbol, local, locals) {
printf("%2d: %s[%d]\n", localMap.get(local), local->name, local->id);
}
printf("\n");
}
void printDefsVector(std::vector<SymExpr*> defs, Map<SymExpr*,int>& defMap) {
printf("Variable Definitions\n");
for_vector(SymExpr, def, defs) {
printf("%2d: %s[%d] in %d\n", defMap.get(def), def->var->name,
def->var->id, def->getStmtExpr()->id);
}
printf("\n");
}
void printLocalsVectorSets(std::vector<BitVec*>& sets, Vec<Symbol*> locals) {
int i = 0;
for_vector(BitVec, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->size(); j++) {
if (set->get(j))
printf("%s[%d] ", locals.v[j]->name, locals.v[j]->id);
}
printf("\n");
i++;
}
printf("\n");
}
void printBitVectorSets(std::vector<BitVec*>& sets) {
int i = 0;
for_vector(BitVec, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->size(); j++) {
printf("%d", (set->get(j)) ? 1 : 0);
if ((j+1) % 10 == 0) printf(" ");
}
printf("\n");
i++;
}
printf("\n");
}
<commit_msg>When building basic blocks for loop, only put the test expression at the top of the loop body; not the entire blockInfo callExpr for C-For loops<commit_after>/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "bb.h"
#include "astutil.h"
#include "bitVec.h"
#include "expr.h"
#include "stlUtil.h"
#include "stmt.h"
#include "view.h"
#include <cstdlib>
BasicBlock::BasicBlock()
: id(nextid++) {}
#define BB_START() \
basicBlock = new BasicBlock()
// The assert tests that the expression we are adding to this basic block
// has not already been deleted.
#define BB_ADD(expr) \
do { \
INT_ASSERT(expr); \
basicBlock->exprs.push_back(expr); \
} while (0)
#define BB_STOP() \
fn->basicBlocks->push_back(Steal())
#define BB_RESTART() \
do { \
BB_STOP(); \
BB_START(); \
} while (0)
#define BBB(stmt) \
buildBasicBlocks(fn, stmt)
#define BB_THREAD(src, dst) \
do { \
(dst)->ins.push_back(src); \
(src)->outs.push_back(dst); \
} while (0)
//# Statics
BasicBlock* BasicBlock::basicBlock;
Map<LabelSymbol*,std::vector<BasicBlock*>*> BasicBlock::gotoMaps;
Map<LabelSymbol*,BasicBlock*> BasicBlock::labelMaps;
int BasicBlock::nextid;
// Returns true if the class invariants have been preserved.
bool BasicBlock::isOK()
{
// Expressions must be live (non-NULL);
for_vector(Expr, expr, exprs)
if (expr == 0) return false;
// Every in edge must have a corresponding out edge in the source block.
for_vector(BasicBlock, source, ins) {
bool found = false;
for_vector(BasicBlock, bb, source->outs)
if (bb == this) { found = true; break; }
if (!found) return false;
}
// Every out edge must have a corresponding in edge in the target block.
for_vector(BasicBlock, target, outs) {
bool found = false;
for_vector(BasicBlock, bb, target->ins)
if (bb == this) { found = true; break; }
if (!found) return false;
}
return true;
}
void BasicBlock::clear(FnSymbol* fn)
{
if (!fn->basicBlocks)
return;
for_vector(BasicBlock, bb, *fn->basicBlocks)
delete bb, bb = 0;
delete fn->basicBlocks; fn->basicBlocks = 0;
}
// Reset the shared statics.
void BasicBlock::reset(FnSymbol* fn)
{
clear(fn);
gotoMaps.clear();
labelMaps.clear();
fn->basicBlocks = new std::vector<BasicBlock*>();
nextid = 0;
}
BasicBlock* BasicBlock::Steal()
{
BasicBlock* temp = basicBlock;
basicBlock = 0;
return temp;
}
// This is the top-level (public) builder function.
void buildBasicBlocks(FnSymbol* fn)
{
BasicBlock::reset(fn);
BasicBlock::basicBlock = new BasicBlock(); // BB_START();
BasicBlock::buildBasicBlocks(fn, fn->body); // BBB(fn->body);
fn->basicBlocks->push_back(BasicBlock::Steal()); // BB_STOP();
INT_ASSERT(verifyBasicBlocks(fn));
}
void BasicBlock::buildBasicBlocks(FnSymbol* fn, Expr* stmt)
{
if (stmt == 0)
{
}
else if (BlockStmt* s = toBlockStmt(stmt))
{
CallExpr* loop = toCallExpr(s->blockInfoGet());
if (loop)
{
bool cForLoop = loop->isPrimitive(PRIM_BLOCK_C_FOR_LOOP);
// for c for loops, add the init expr before the loop body
if (cForLoop) {
for_alist(stmt, toBlockStmt(loop->get(1))->body) { BBB(stmt); }
}
// mark the top of the loop
BasicBlock* top = basicBlock;
BB_RESTART();
// add the test expr at the loop top
if (cForLoop) {
for_alist(stmt, toBlockStmt(loop->get(2))->body) { BBB(stmt); }
} else {
BB_ADD(loop);
}
BasicBlock* loopTop = basicBlock;
for_alist(stmt, s->body) {
BBB(stmt);
}
// for c for loops, add the incr expr after the loop body
if (cForLoop) {
for_alist(stmt, toBlockStmt(loop->get(3))->body) { BBB(stmt); }
}
BasicBlock* loopBottom = basicBlock;
BB_RESTART();
BasicBlock* bottom = basicBlock;
// thread the basic blocks of the pre-loop, loop, and post-loop together
BB_THREAD(top, loopTop);
BB_THREAD(loopBottom, bottom);
BB_THREAD(loopBottom, loopTop);
BB_THREAD(top, bottom);
}
else
{
for_alist(stmt, s->body)
BBB(stmt);
}
}
else if (CondStmt* s = toCondStmt(stmt))
{
INT_ASSERT(s->condExpr);
BB_ADD(s->condExpr);
BasicBlock* top = basicBlock;
BB_RESTART();
BB_THREAD(top, basicBlock);
BBB(s->thenStmt);
BasicBlock* thenBottom = basicBlock;
BB_RESTART();
if (s->elseStmt)
{
BB_THREAD(top, basicBlock);
BBB(s->elseStmt);
BasicBlock* elseBottom = basicBlock;
BB_RESTART();
BB_THREAD(elseBottom, basicBlock);
}
else
{
BB_THREAD(top, basicBlock);
}
BB_THREAD(thenBottom, basicBlock);
} else if (GotoStmt* s = toGotoStmt(stmt)) {
LabelSymbol* label = toLabelSymbol(toSymExpr(s->label)->var);
if (BasicBlock* bb = labelMaps.get(label)) {
BB_THREAD(basicBlock, bb);
} else {
std::vector<BasicBlock*>* vbb = gotoMaps.get(label);
if (!vbb)
vbb = new std::vector<BasicBlock*>();
vbb->push_back(basicBlock);
gotoMaps.put(label, vbb);
}
BB_ADD(s); // Put the goto at the end of its block.
BB_RESTART();
} else {
DefExpr* def = toDefExpr(stmt);
if (def && toLabelSymbol(def->sym)) {
// If a label appears in the middle of a block,
// we start a new block.
if (basicBlock->exprs.size() > 0)
{
BasicBlock* top = basicBlock;
BB_RESTART();
BB_THREAD(top, basicBlock);
}
BB_ADD(def); // Put the label def at the start of its block.
// OK, this statement is a label def, so get the label.
LabelSymbol* label = toLabelSymbol(def->sym);
// See if we have any unresolved references to this label,
// and resolve them.
if (std::vector<BasicBlock*>* vbb = gotoMaps.get(label)) {
for_vector(BasicBlock, bb, *vbb) {
BB_THREAD(bb, basicBlock);
}
}
labelMaps.put(label, basicBlock);
} else {
BB_ADD(stmt);
}
}
}
// Returns true if the basic block structure is OK, false otherwise.
bool verifyBasicBlocks(FnSymbol* fn)
{
for_vector(BasicBlock, bb, *fn->basicBlocks)
{
if (! bb->isOK())
return false;
}
return true;
}
void buildLocalsVectorMap(FnSymbol* fn,
Vec<Symbol*>& locals,
Map<Symbol*,int>& localMap) {
int i = 0;
for_vector(BasicBlock, bb, *fn->basicBlocks) {
for_vector(Expr, expr, bb->exprs) {
if (DefExpr* def = toDefExpr(expr)) {
if (toVarSymbol(def->sym)) {
locals.add(def->sym);
localMap.put(def->sym, i++);
}
}
}
}
}
//#define DEBUG_FLOW
void backwardFlowAnalysis(FnSymbol* fn,
std::vector<BitVec*>& GEN,
std::vector<BitVec*>& KILL,
std::vector<BitVec*>& IN,
std::vector<BitVec*>& OUT) {
bool iterate = true;
while (iterate) {
iterate = false;
int i = 0;
for_vector(BasicBlock, bb, *fn->basicBlocks) {
for (int j = 0; j < IN[i]->ndata; j++) {
unsigned new_in = (OUT[i]->data[j] & ~KILL[i]->data[j]) | GEN[i]->data[j];
if (new_in != IN[i]->data[j]) {
IN[i]->data[j] = new_in;
iterate = true;
}
unsigned new_out = 0;
for_vector(BasicBlock, bbout, bb->outs) {
new_out = new_out | IN[bbout->id]->data[j];
}
if (new_out != OUT[i]->data[j]) {
OUT[i]->data[j] = new_out;
iterate = true;
}
}
i++;
}
#ifdef DEBUG_FLOW
printf("IN\n"); printBitVectorSets(IN);
printf("OUT\n"); printBitVectorSets(OUT);
#endif
}
}
void forwardFlowAnalysis(FnSymbol* fn,
std::vector<BitVec*>& GEN,
std::vector<BitVec*>& KILL,
std::vector<BitVec*>& IN,
std::vector<BitVec*>& OUT,
bool intersect) {
size_t nbbq = fn->basicBlocks->size(); // size of bb queue
std::vector<int> bbq;
BitVec bbs(nbbq);
int iq = -1, nq = nbbq-1; // index to first and last bb in bbq
for (size_t i = 0; i < nbbq; i++) {
bbq.push_back(i);
bbs.set(i);
}
while (iq != nq) {
iq = (iq + 1) % nbbq;
int i = bbq[iq];
bbs.unset(i);
#ifdef DEBUG_FLOW
if (iq == 0) {
printf("IN\n"); printBitVectorSets(IN);
printf("OUT\n"); printBitVectorSets(OUT);
}
#endif
BasicBlock* bb = (*fn->basicBlocks)[i];
bool change = false;
for (int j = 0; j < IN[i]->ndata; j++) {
if (bb->ins.size() > 0) {
unsigned new_in = (intersect) ? (unsigned)(-1) : 0;
for_vector(BasicBlock, bbin, bb->ins) {
if (intersect)
new_in &= OUT[bbin->id]->data[j];
else
new_in |= OUT[bbin->id]->data[j];
}
if (new_in != IN[i]->data[j]) {
IN[i]->data[j] = new_in;
change = true;
}
}
unsigned new_out = (IN[i]->data[j] & ~KILL[i]->data[j]) | GEN[i]->data[j];
if (new_out != OUT[i]->data[j]) {
OUT[i]->data[j] = new_out;
change = true;
}
}
if (change) {
for_vector(BasicBlock, bbout, bb->outs) {
if (!bbs.get(bbout->id)) {
nq = (nq + 1) % nbbq;
bbs.set(bbout->id);
bbq[nq] = bbout->id;
}
}
}
}
}
void printBasicBlocks(FnSymbol* fn) {
for_vector(BasicBlock, b, *fn->basicBlocks) {
printf("%2d: ", b->id);
for_vector(BasicBlock, bb, b->ins) {
printf("%d ", bb->id);
}
printf(" > ");
for_vector(BasicBlock, bc, b->outs) {
printf("%d ", bc->id);
}
printf("\n");
for_vector(Expr, expr, b->exprs) {
if (expr)
list_view_noline(expr);
else
printf("0 (null)\n");
}
printf("\n");
}
}
void printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {
printf("Local Variables\n");
forv_Vec(Symbol, local, locals) {
printf("%2d: %s[%d]\n", localMap.get(local), local->name, local->id);
}
printf("\n");
}
void printDefsVector(std::vector<SymExpr*> defs, Map<SymExpr*,int>& defMap) {
printf("Variable Definitions\n");
for_vector(SymExpr, def, defs) {
printf("%2d: %s[%d] in %d\n", defMap.get(def), def->var->name,
def->var->id, def->getStmtExpr()->id);
}
printf("\n");
}
void printLocalsVectorSets(std::vector<BitVec*>& sets, Vec<Symbol*> locals) {
int i = 0;
for_vector(BitVec, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->size(); j++) {
if (set->get(j))
printf("%s[%d] ", locals.v[j]->name, locals.v[j]->id);
}
printf("\n");
i++;
}
printf("\n");
}
void printBitVectorSets(std::vector<BitVec*>& sets) {
int i = 0;
for_vector(BitVec, set, sets) {
printf("%2d: ", i);
for (int j = 0; j < set->size(); j++) {
printf("%d", (set->get(j)) ? 1 : 0);
if ((j+1) % 10 == 0) printf(" ");
}
printf("\n");
i++;
}
printf("\n");
}
<|endoftext|> |
<commit_before>#ifndef __MAPNIK_VECTOR_PROCESSOR_H__
#define __MAPNIK_VECTOR_PROCESSOR_H__
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/request.hpp>
#include <mapnik/view_transform.hpp>
#include <mapnik/image_scaling.hpp>
#include <mapnik/image_compositing.hpp>
#include <mapnik/geometry.hpp>
#include "clipper.hpp"
#include "vector_tile_config.hpp"
namespace mapnik { namespace vector_tile_impl {
enum polygon_fill_type : std::uint8_t {
even_odd_fill = 0,
non_zero_fill,
positive_fill,
negative_fill
};
/*
This processor combines concepts from mapnik's
feature_style_processor and agg_renderer. It
differs in that here we only process layers in
isolation of their styles, and because of this we need
options for clipping and simplification, for example,
that would normally come from a style's symbolizers
*/
template <typename T>
class processor : private mapnik::util::noncopyable
{
public:
typedef T backend_type;
private:
backend_type & backend_;
mapnik::Map const& m_;
mapnik::request const& m_req_;
double scale_factor_;
mapnik::view_transform t_;
double area_threshold_;
bool strictly_simple_;
std::string image_format_;
scaling_method_e scaling_method_;
bool painted_;
double simplify_distance_;
bool multi_polygon_union_;
ClipperLib::PolyFillType fill_type_;
bool process_all_mp_rings_;
public:
MAPNIK_VECTOR_INLINE processor(T & backend,
mapnik::Map const& map,
mapnik::request const& m_req,
double scale_factor=1.0,
unsigned offset_x=0,
unsigned offset_y=0,
double area_threshold=0.1,
bool strictly_simple=false,
std::string const& image_format="jpeg",
scaling_method_e scaling_method=SCALING_NEAR
);
inline void set_simplify_distance(double dist)
{
simplify_distance_ = dist;
}
inline void set_process_all_mp_rings(bool value)
{
process_all_mp_rings_ = value;
}
inline void set_multi_polygon_union(bool value)
{
multi_polygon_union_ = value;
}
inline double get_simplify_distance() const
{
return simplify_distance_;
}
inline mapnik::view_transform const& get_transform()
{
return t_;
}
MAPNIK_VECTOR_INLINE void set_fill_type(polygon_fill_type type);
MAPNIK_VECTOR_INLINE void apply(double scale_denom=0.0);
MAPNIK_VECTOR_INLINE bool painted() const;
MAPNIK_VECTOR_INLINE void apply_to_layer(mapnik::layer const& lay,
mapnik::projection const& proj0,
double scale,
double scale_denom,
unsigned width,
unsigned height,
box2d<double> const& extent,
int buffer_size);
template <typename T2>
MAPNIK_VECTOR_INLINE bool handle_geometry(T2 const& vs,
mapnik::feature_impl const& feature,
mapnik::geometry::geometry<double> const& geom,
mapnik::box2d<int> const& tile_clipping_extent,
mapnik::box2d<double> const& target_clipping_extent);
};
}} // end ns
#if !defined(MAPNIK_VECTOR_TILE_LIBRARY)
#include "vector_tile_processor.ipp"
#endif
#endif // __MAPNIK_VECTOR_TILE_PROCESSOR_H__
<commit_msg>Maximum fill type value added to enum<commit_after>#ifndef __MAPNIK_VECTOR_PROCESSOR_H__
#define __MAPNIK_VECTOR_PROCESSOR_H__
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/request.hpp>
#include <mapnik/view_transform.hpp>
#include <mapnik/image_scaling.hpp>
#include <mapnik/image_compositing.hpp>
#include <mapnik/geometry.hpp>
#include "clipper.hpp"
#include "vector_tile_config.hpp"
namespace mapnik { namespace vector_tile_impl {
enum polygon_fill_type : std::uint8_t {
even_odd_fill = 0,
non_zero_fill,
positive_fill,
negative_fill,
polygon_fill_type_max
};
/*
This processor combines concepts from mapnik's
feature_style_processor and agg_renderer. It
differs in that here we only process layers in
isolation of their styles, and because of this we need
options for clipping and simplification, for example,
that would normally come from a style's symbolizers
*/
template <typename T>
class processor : private mapnik::util::noncopyable
{
public:
typedef T backend_type;
private:
backend_type & backend_;
mapnik::Map const& m_;
mapnik::request const& m_req_;
double scale_factor_;
mapnik::view_transform t_;
double area_threshold_;
bool strictly_simple_;
std::string image_format_;
scaling_method_e scaling_method_;
bool painted_;
double simplify_distance_;
bool multi_polygon_union_;
ClipperLib::PolyFillType fill_type_;
bool process_all_mp_rings_;
public:
MAPNIK_VECTOR_INLINE processor(T & backend,
mapnik::Map const& map,
mapnik::request const& m_req,
double scale_factor=1.0,
unsigned offset_x=0,
unsigned offset_y=0,
double area_threshold=0.1,
bool strictly_simple=false,
std::string const& image_format="jpeg",
scaling_method_e scaling_method=SCALING_NEAR
);
inline void set_simplify_distance(double dist)
{
simplify_distance_ = dist;
}
inline void set_process_all_mp_rings(bool value)
{
process_all_mp_rings_ = value;
}
inline void set_multi_polygon_union(bool value)
{
multi_polygon_union_ = value;
}
inline double get_simplify_distance() const
{
return simplify_distance_;
}
inline mapnik::view_transform const& get_transform()
{
return t_;
}
MAPNIK_VECTOR_INLINE void set_fill_type(polygon_fill_type type);
MAPNIK_VECTOR_INLINE void apply(double scale_denom=0.0);
MAPNIK_VECTOR_INLINE bool painted() const;
MAPNIK_VECTOR_INLINE void apply_to_layer(mapnik::layer const& lay,
mapnik::projection const& proj0,
double scale,
double scale_denom,
unsigned width,
unsigned height,
box2d<double> const& extent,
int buffer_size);
template <typename T2>
MAPNIK_VECTOR_INLINE bool handle_geometry(T2 const& vs,
mapnik::feature_impl const& feature,
mapnik::geometry::geometry<double> const& geom,
mapnik::box2d<int> const& tile_clipping_extent,
mapnik::box2d<double> const& target_clipping_extent);
};
}} // end ns
#if !defined(MAPNIK_VECTOR_TILE_LIBRARY)
#include "vector_tile_processor.ipp"
#endif
#endif // __MAPNIK_VECTOR_TILE_PROCESSOR_H__
<|endoftext|> |
<commit_before><commit_msg>TBR: phajdan.jr<commit_after><|endoftext|> |
<commit_before>/* string_test.cc
Copyright (c) 2012 Datacratic. All rights reserved.
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "soa/types/string.h"
#include <boost/test/unit_test.hpp>
#include <boost/regex/icu.hpp>
#include <boost/regex.hpp>
#include "soa/jsoncpp/json.h"
#include "jml/arch/format.h"
using namespace std;
using namespace ML;
using namespace Datacratic;
BOOST_AUTO_TEST_CASE( test_print_format )
{
std::string raw = "saint-jérôme";
// Test 1 - Iterate through the raw string with normal iterators we should not find 'é'
unsigned numAccentedChars = 0;
for(string::const_iterator it = raw.begin() ; it != raw.end(); ++it)
{
if (*it == L'é' || *it == L'ô')
numAccentedChars++;
}
BOOST_CHECK_EQUAL(numAccentedChars, 0);
Utf8String utf8(raw);
// Now iterate through the utf8 string
for (Utf8String::const_iterator it = utf8.begin(); it != utf8.end(); ++it)
{
if (*it == L'é' || *it == L'ô')
numAccentedChars++;
}
BOOST_CHECK_EQUAL(numAccentedChars, 2);
// Now add another string to it
std::string raw2 = "saint-jérôme2";
utf8+=raw2;
numAccentedChars=0;
// Now iterate through the utf8 string
for (Utf8String::const_iterator it = utf8.begin(); it != utf8.end(); ++it)
{
if (*it == L'é' || *it == L'ô')
numAccentedChars++;
}
BOOST_CHECK_EQUAL(numAccentedChars, 4);
string theString(utf8.rawData(), utf8.rawLength());
size_t found = raw.find(L'é') ;
BOOST_CHECK_EQUAL(found, string::npos);
// We do a normal regex first
boost::regex reg("é");
std::string raw4 = "saint-jérôme";
BOOST_CHECK_EQUAL( boost::regex_search(raw4, reg), true);
// Please see Saint-j\xC3A9r\xC3B4me for UTF-8 character table
boost::u32regex withHex = boost::make_u32regex("saint-j\xc3\xa9r\xc3\xb4me");
boost::u32regex withoutHex = boost::make_u32regex(L"[a-z]*-jérôme");
boost::match_results<std::string::const_iterator> matches;
BOOST_CHECK_EQUAL(boost::u32regex_search(raw, matches, withoutHex), true);
if (boost::u32regex_search(raw, matches, withoutHex))
{
for (boost::match_results< std::string::const_iterator >::const_iterator i = matches.begin(); i != matches.end(); ++i)
{
if (i->matched) std::cout << "matches : [" << i->str() << "]\n";
else std::cout << "doesn't match : [" << i->str() << "]\n";
}
}
else
{
cerr << "did not get a match without hex" << endl;
}
BOOST_CHECK_EQUAL(boost::u32regex_search(raw, matches, withHex), true);
}
template<typename Str>
static size_t count_chars(const Str &str, std::initializer_list<wchar_t> chars) {
size_t count = std::count_if(begin(str), end(str),
[&](typename std::iterator_traits<typename Str::iterator>::value_type c) {
return std::find(begin(chars), end(chars), c) != end(chars);
});
return count;
}
BOOST_AUTO_TEST_CASE( test_u32_string )
{
const std::string str1 { "daß auf dïch" };
auto nonAscii = count_chars(str1, { L'ß', L'ï' });
BOOST_CHECK_EQUAL(nonAscii, 0);
const Utf32String u32str1 { str1 };
nonAscii = count_chars(u32str1, { L'ß', L'ï' });
BOOST_CHECK_EQUAL(nonAscii, 2);
Utf32String u32str2 { "daß" };
Utf32String u32str3 { "für" };
auto u32str4 = u32str2 + u32str3;
nonAscii = count_chars(u32str4, { L'ß', L'ü' });
BOOST_CHECK_EQUAL(nonAscii, 2);
u32str4 += "Ô Mélodie!";
nonAscii = count_chars(u32str4, { L'ß', L'ü', L'Ô', L'é' });
BOOST_CHECK_EQUAL(nonAscii, 4);
std::string ascii = u32str1.extractAscii();
BOOST_CHECK_EQUAL(ascii, "da? auf d?ch");
Utf32String plainAscii { "Plain Ascii" };
BOOST_CHECK_EQUAL(plainAscii.extractAscii(), "Plain Ascii");
}
<commit_msg>Add basic test for dtoa<commit_after>/* string_test.cc
Copyright (c) 2012 Datacratic. All rights reserved.
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "soa/types/string.h"
#include <boost/test/unit_test.hpp>
#include <boost/regex/icu.hpp>
#include <boost/regex.hpp>
#include "soa/jsoncpp/json.h"
#include "soa/types/dtoa.h"
#include "jml/arch/format.h"
using namespace std;
using namespace ML;
using namespace Datacratic;
BOOST_AUTO_TEST_CASE( test_print_format )
{
std::string raw = "saint-jérôme";
// Test 1 - Iterate through the raw string with normal iterators we should not find 'é'
unsigned numAccentedChars = 0;
for(string::const_iterator it = raw.begin() ; it != raw.end(); ++it)
{
if (*it == L'é' || *it == L'ô')
numAccentedChars++;
}
BOOST_CHECK_EQUAL(numAccentedChars, 0);
Utf8String utf8(raw);
// Now iterate through the utf8 string
for (Utf8String::const_iterator it = utf8.begin(); it != utf8.end(); ++it)
{
if (*it == L'é' || *it == L'ô')
numAccentedChars++;
}
BOOST_CHECK_EQUAL(numAccentedChars, 2);
// Now add another string to it
std::string raw2 = "saint-jérôme2";
utf8+=raw2;
numAccentedChars=0;
// Now iterate through the utf8 string
for (Utf8String::const_iterator it = utf8.begin(); it != utf8.end(); ++it)
{
if (*it == L'é' || *it == L'ô')
numAccentedChars++;
}
BOOST_CHECK_EQUAL(numAccentedChars, 4);
string theString(utf8.rawData(), utf8.rawLength());
size_t found = raw.find(L'é') ;
BOOST_CHECK_EQUAL(found, string::npos);
// We do a normal regex first
boost::regex reg("é");
std::string raw4 = "saint-jérôme";
BOOST_CHECK_EQUAL( boost::regex_search(raw4, reg), true);
// Please see Saint-j\xC3A9r\xC3B4me for UTF-8 character table
boost::u32regex withHex = boost::make_u32regex("saint-j\xc3\xa9r\xc3\xb4me");
boost::u32regex withoutHex = boost::make_u32regex(L"[a-z]*-jérôme");
boost::match_results<std::string::const_iterator> matches;
BOOST_CHECK_EQUAL(boost::u32regex_search(raw, matches, withoutHex), true);
if (boost::u32regex_search(raw, matches, withoutHex))
{
for (boost::match_results< std::string::const_iterator >::const_iterator i = matches.begin(); i != matches.end(); ++i)
{
if (i->matched) std::cout << "matches : [" << i->str() << "]\n";
else std::cout << "doesn't match : [" << i->str() << "]\n";
}
}
else
{
cerr << "did not get a match without hex" << endl;
}
BOOST_CHECK_EQUAL(boost::u32regex_search(raw, matches, withHex), true);
}
template<typename Str>
static size_t count_chars(const Str &str, std::initializer_list<wchar_t> chars) {
size_t count = std::count_if(begin(str), end(str),
[&](typename std::iterator_traits<typename Str::iterator>::value_type c) {
return std::find(begin(chars), end(chars), c) != end(chars);
});
return count;
}
BOOST_AUTO_TEST_CASE( test_u32_string )
{
const std::string str1 { "daß auf dïch" };
auto nonAscii = count_chars(str1, { L'ß', L'ï' });
BOOST_CHECK_EQUAL(nonAscii, 0);
const Utf32String u32str1 { str1 };
nonAscii = count_chars(u32str1, { L'ß', L'ï' });
BOOST_CHECK_EQUAL(nonAscii, 2);
Utf32String u32str2 { "daß" };
Utf32String u32str3 { "für" };
auto u32str4 = u32str2 + u32str3;
nonAscii = count_chars(u32str4, { L'ß', L'ü' });
BOOST_CHECK_EQUAL(nonAscii, 2);
u32str4 += "Ô Mélodie!";
nonAscii = count_chars(u32str4, { L'ß', L'ü', L'Ô', L'é' });
BOOST_CHECK_EQUAL(nonAscii, 4);
std::string ascii = u32str1.extractAscii();
BOOST_CHECK_EQUAL(ascii, "da? auf d?ch");
Utf32String plainAscii { "Plain Ascii" };
BOOST_CHECK_EQUAL(plainAscii.extractAscii(), "Plain Ascii");
}
BOOST_AUTO_TEST_CASE( test_basic_dtoa )
{
double value = 365.0;
BOOST_CHECK_EQUAL(dtoa(value) , "365");
value = 0.0;
BOOST_CHECK_EQUAL(dtoa(value) , "0");
value = 10.1;
BOOST_CHECK_EQUAL(dtoa(value) , "10.1");
value = -10.1;
BOOST_CHECK_EQUAL(dtoa(value) , "-10.1");
value = -1089000000000;
BOOST_CHECK_EQUAL(dtoa(value) , "-1.089e12");
}
<|endoftext|> |
<commit_before>/**
* @author Parikshit Ram ([email protected])
* @file nbc_main.cc
*
* This program test drives the Simple Naive Bayes Classifier
*
* This classifier does parametric naive bayes classification
* assuming that the features are sampled from a Gaussian
* distribution.
*
* PARAMETERS TO BE INPUT:
*
* --train
* This is the file that contains the training data
*
* --nbc/classes
* This is the number of classes present in the training data
*
* --test
* This file contains the data points which the trained
* classifier would classify
*
* --output
* This file will contain the classes to which the corresponding
* data points in the testing data
*
*/
#include "simple_nbc.h"
#include <fastlib/fx/io.h>
#include <armadillo>
#include <fastlib/data/dataset.h>
#include <fastlib/base/arma_compat.h>
/*const fx_entry_doc parm_nbc_main_entries[] = {
{"train", FX_REQUIRED, FX_STR, NULL,
" A file containing the training set\n"},
{"test", FX_REQUIRED, FX_STR, NULL,
" A file containing the test set\n"},
{"output", FX_PARAM, FX_STR, NULL,
" The file in which the output of the test would be "
"written (defaults to 'output.csv')\n"},
FX_ENTRY_DOC_DONE
};*/
PARAM_STRING_REQ("train", "A file containing the training set", "nbc");
PARAM_STRING_REQ("test", "A file containing the test set", "nbc");
PARAM_STRING("output", "The file in which the output of the test would\
be written, defaults to 'output.csv')", "nbc", "output.csv");
/*const fx_submodule_doc parm_nbc_main_submodules[] = {
{"nbc", &parm_nbc_doc,
" Trains on a given set and number of classes and "
"tests them on a given set\n"},
FX_SUBMODULE_DOC_DONE
};*/
PARAM_MODULE("nbc", "Trains on a given set and number\
of classes and tests them on a given set");
/*const fx_module_doc parm_nbc_main_doc = {
parm_nbc_main_entries, parm_nbc_main_submodules,
"This program test drives the Parametric Naive Bayes \n"
"Classifier assuming that the features are sampled \n"
"from a Gaussian distribution.\n"
};*/
PROGRAM_INFO("Parametric Naive Bayes", "This program test drives the\
Parametric Naive Bayes Classifier assuming that the features are\
sampled from a Gaussian distribution.", "nbc");
using namespace mlpack;
int main(int argc, char* argv[]) {
IO::ParseCommandLine(argc, argv);
////// READING PARAMETERS AND LOADING DATA //////
const char *training_data_filename = IO::GetParam<std::string>("nbc/train").c_str();
arma::mat training_data;
data::Load(training_data_filename, training_data);
const char *testing_data_filename = IO::GetParam<std::string>("nbc/test").c_str();
arma::mat testing_data;
data::Load(testing_data_filename, testing_data);
////// SIMPLE NAIVE BAYES CLASSIFICATION ASSUMING THE DATA TO BE UNIFORMLY DISTRIBUTED //////
////// Timing the training of the Naive Bayes Classifier //////
IO::StartTimer("nbc/training");
////// Create and train the classifier
SimpleNaiveBayesClassifier nbc = SimpleNaiveBayesClassifier(training_data);
////// Stop training timer //////
IO::StopTimer("nbc/training");
////// Timing the testing of the Naive Bayes Classifier //////
////// The variable that contains the result of the classification
arma::vec results;
IO::StartTimer("nbc/testing");
////// Calling the function that classifies the test data
nbc.Classify(testing_data, results);
////// Stop testing timer //////
IO::StopTimer("nbc/testing");
////// OUTPUT RESULTS //////
std::string output_filename = IO::GetParam<std::string>("nbc/output");
data::Save(output_filename.c_str(), results);
return 1;
}
<commit_msg>Stop using arma_compat.<commit_after>/**
* @author Parikshit Ram ([email protected])
* @file nbc_main.cc
*
* This program test drives the Simple Naive Bayes Classifier
*
* This classifier does parametric naive bayes classification
* assuming that the features are sampled from a Gaussian
* distribution.
*
* PARAMETERS TO BE INPUT:
*
* --train
* This is the file that contains the training data
*
* --nbc/classes
* This is the number of classes present in the training data
*
* --test
* This file contains the data points which the trained
* classifier would classify
*
* --output
* This file will contain the classes to which the corresponding
* data points in the testing data
*
*/
#include "simple_nbc.h"
#include <fastlib/fx/io.h>
#include <armadillo>
#include <fastlib/data/dataset.h>
/*const fx_entry_doc parm_nbc_main_entries[] = {
{"train", FX_REQUIRED, FX_STR, NULL,
" A file containing the training set\n"},
{"test", FX_REQUIRED, FX_STR, NULL,
" A file containing the test set\n"},
{"output", FX_PARAM, FX_STR, NULL,
" The file in which the output of the test would be "
"written (defaults to 'output.csv')\n"},
FX_ENTRY_DOC_DONE
};*/
PARAM_STRING_REQ("train", "A file containing the training set", "nbc");
PARAM_STRING_REQ("test", "A file containing the test set", "nbc");
PARAM_STRING("output", "The file in which the output of the test would\
be written, defaults to 'output.csv')", "nbc", "output.csv");
/*const fx_submodule_doc parm_nbc_main_submodules[] = {
{"nbc", &parm_nbc_doc,
" Trains on a given set and number of classes and "
"tests them on a given set\n"},
FX_SUBMODULE_DOC_DONE
};*/
PARAM_MODULE("nbc", "Trains on a given set and number\
of classes and tests them on a given set");
/*const fx_module_doc parm_nbc_main_doc = {
parm_nbc_main_entries, parm_nbc_main_submodules,
"This program test drives the Parametric Naive Bayes \n"
"Classifier assuming that the features are sampled \n"
"from a Gaussian distribution.\n"
};*/
PROGRAM_INFO("Parametric Naive Bayes", "This program test drives the\
Parametric Naive Bayes Classifier assuming that the features are\
sampled from a Gaussian distribution.", "nbc");
using namespace mlpack;
int main(int argc, char* argv[]) {
IO::ParseCommandLine(argc, argv);
////// READING PARAMETERS AND LOADING DATA //////
const char *training_data_filename = IO::GetParam<std::string>("nbc/train").c_str();
arma::mat training_data;
data::Load(training_data_filename, training_data);
const char *testing_data_filename = IO::GetParam<std::string>("nbc/test").c_str();
arma::mat testing_data;
data::Load(testing_data_filename, testing_data);
////// SIMPLE NAIVE BAYES CLASSIFICATION ASSUMING THE DATA TO BE UNIFORMLY DISTRIBUTED //////
////// Timing the training of the Naive Bayes Classifier //////
IO::StartTimer("nbc/training");
////// Create and train the classifier
SimpleNaiveBayesClassifier nbc = SimpleNaiveBayesClassifier(training_data);
////// Stop training timer //////
IO::StopTimer("nbc/training");
////// Timing the testing of the Naive Bayes Classifier //////
////// The variable that contains the result of the classification
arma::vec results;
IO::StartTimer("nbc/testing");
////// Calling the function that classifies the test data
nbc.Classify(testing_data, results);
////// Stop testing timer //////
IO::StopTimer("nbc/testing");
////// OUTPUT RESULTS //////
std::string output_filename = IO::GetParam<std::string>("nbc/output");
data::Save(output_filename.c_str(), results);
return 1;
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// MOOSE includes
#include "Resurrector.h"
#include "FEProblem.h"
#include "MooseUtils.h"
#include "MooseApp.h"
#include "NonlinearSystem.h"
#include <stdio.h>
#include <sys/stat.h>
const std::string Resurrector::MAT_PROP_EXT(".msmp");
const std::string Resurrector::RESTARTABLE_DATA_EXT(".rd");
Resurrector::Resurrector(FEProblemBase & fe_problem)
: PerfGraphInterface(fe_problem.getMooseApp().perfGraph(), "Resurrector"),
_fe_problem(fe_problem),
_restart_file_suffix("xdr"),
_restartable(_fe_problem),
_restart_from_file_timer(registerTimedSection("restartFromFile", 3)),
_restart_restartable_data_timer(registerTimedSection("restartRestartableData", 3))
{
}
void
Resurrector::setRestartFile(const std::string & file_base)
{
_restart_file_base = file_base;
}
void
Resurrector::setRestartSuffix(const std::string & file_ext)
{
_restart_file_suffix = file_ext;
}
void
Resurrector::restartFromFile()
{
TIME_SECTION(_restart_from_file_timer);
std::string file_name(_restart_file_base + '.' + _restart_file_suffix);
MooseUtils::checkFileReadable(file_name);
_restartable.readRestartableDataHeader(_restart_file_base + RESTARTABLE_DATA_EXT);
unsigned int read_flags = EquationSystems::READ_DATA;
if (!_fe_problem.skipAdditionalRestartData())
read_flags |= EquationSystems::READ_ADDITIONAL_DATA;
// Set libHilbert renumbering flag to false. We don't support
// N-to-M restarts regardless, and if we're *never* going to do
// N-to-M restarts then libHilbert is just unnecessary computation
// and communication.
const bool renumber = false;
// DECODE or READ based on suffix.
// MOOSE doesn't currently use partition-agnostic renumbering, since
// it can break restarts when multiple nodes are at the same point
_fe_problem.es().read(file_name, read_flags, renumber);
_fe_problem.getNonlinearSystemBase().update();
Moose::perf_log.pop("restartFromFile()", "Setup");
}
void
Resurrector::restartRestartableData()
{
TIME_SECTION(_restart_restartable_data_timer);
_restartable.readRestartableData(_fe_problem.getMooseApp().getRestartableData(),
_fe_problem.getMooseApp().getRecoverableData());
}
<commit_msg>Fix restart failure refs #11551<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// MOOSE includes
#include "Resurrector.h"
#include "FEProblem.h"
#include "MooseUtils.h"
#include "MooseApp.h"
#include "NonlinearSystem.h"
#include <stdio.h>
#include <sys/stat.h>
const std::string Resurrector::MAT_PROP_EXT(".msmp");
const std::string Resurrector::RESTARTABLE_DATA_EXT(".rd");
Resurrector::Resurrector(FEProblemBase & fe_problem)
: PerfGraphInterface(fe_problem.getMooseApp().perfGraph(), "Resurrector"),
_fe_problem(fe_problem),
_restart_file_suffix("xdr"),
_restartable(_fe_problem),
_restart_from_file_timer(registerTimedSection("restartFromFile", 3)),
_restart_restartable_data_timer(registerTimedSection("restartRestartableData", 3))
{
}
void
Resurrector::setRestartFile(const std::string & file_base)
{
_restart_file_base = file_base;
}
void
Resurrector::setRestartSuffix(const std::string & file_ext)
{
_restart_file_suffix = file_ext;
}
void
Resurrector::restartFromFile()
{
TIME_SECTION(_restart_from_file_timer);
std::string file_name(_restart_file_base + '.' + _restart_file_suffix);
MooseUtils::checkFileReadable(file_name);
_restartable.readRestartableDataHeader(_restart_file_base + RESTARTABLE_DATA_EXT);
unsigned int read_flags = EquationSystems::READ_DATA;
if (!_fe_problem.skipAdditionalRestartData())
read_flags |= EquationSystems::READ_ADDITIONAL_DATA;
// Set libHilbert renumbering flag to false. We don't support
// N-to-M restarts regardless, and if we're *never* going to do
// N-to-M restarts then libHilbert is just unnecessary computation
// and communication.
const bool renumber = false;
// DECODE or READ based on suffix.
// MOOSE doesn't currently use partition-agnostic renumbering, since
// it can break restarts when multiple nodes are at the same point
_fe_problem.es().read(file_name, read_flags, renumber);
_fe_problem.getNonlinearSystemBase().update();
}
void
Resurrector::restartRestartableData()
{
TIME_SECTION(_restart_restartable_data_timer);
_restartable.readRestartableData(_fe_problem.getMooseApp().getRestartableData(),
_fe_problem.getMooseApp().getRecoverableData());
}
<|endoftext|> |
<commit_before>#if !FEATURE_LWIP
#error [NOT_SUPPORTED] LWIP not supported for this target
#endif
#if DEVICE_EMAC
#error [NOT_SUPPORTED] Not supported for WiFi targets
#endif
#include "mbed.h"
#include "EthernetInterface.h"
#include "UDPSocket.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#ifndef MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE
#define MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE 256
#endif
#ifndef MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT
#define MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT 500
#endif
namespace {
char tx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0};
char rx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0};
const char ASCII_MAX = '~' - ' ';
const int ECHO_LOOPS = 16;
}
void prep_buffer(char *tx_buffer, size_t tx_size) {
for (size_t i=0; i<tx_size; ++i) {
tx_buffer[i] = (rand() % 10) + '0';
}
}
int main() {
GREENTEA_SETUP(60, "udp_echo");
EthernetInterface eth;
eth.connect();
printf("UDP client IP Address is %s\n", eth.get_ip_address());
greentea_send_kv("target_ip", eth.get_ip_address());
char recv_key[] = "host_port";
char ipbuf[60] = {0};
char portbuf[16] = {0};
unsigned int port = 0;
UDPSocket sock;
sock.open(ð);
sock.set_timeout(MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT);
greentea_send_kv("host_ip", " ");
greentea_parse_kv(recv_key, ipbuf, sizeof(recv_key), sizeof(ipbuf));
greentea_send_kv("host_port", " ");
greentea_parse_kv(recv_key, portbuf, sizeof(recv_key), sizeof(ipbuf));
sscanf(portbuf, "%u", &port);
printf("MBED: UDP Server IP address received: %s:%d \n", ipbuf, port);
SocketAddress udp_addr(ipbuf, port);
int success = 0;
for (int i=0; i < ECHO_LOOPS; ++i) {
prep_buffer(tx_buffer, sizeof(tx_buffer));
const int ret = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
printf("[%02d] sent...%d Bytes \n", i, ret);
SocketAddress temp_addr;
const int n = sock.recvfrom(&temp_addr, rx_buffer, sizeof(rx_buffer));
printf("[%02d] recv...%d Bytes \n", i, n);
if ((temp_addr == udp_addr &&
n == sizeof(tx_buffer) &&
memcmp(rx_buffer, tx_buffer, sizeof(rx_buffer)) == 0)) {
success += 1;
}
}
bool result = (success > 3*ECHO_LOOPS/4);
sock.close();
eth.disconnect();
GREENTEA_TESTSUITE_RESULT(result);
}
<commit_msg>Making UDP test less strict on dropped/mismatched packets.<commit_after>#if !FEATURE_LWIP
#error [NOT_SUPPORTED] LWIP not supported for this target
#endif
#if DEVICE_EMAC
#error [NOT_SUPPORTED] Not supported for WiFi targets
#endif
#include "mbed.h"
#include "EthernetInterface.h"
#include "UDPSocket.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#ifndef MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE
#define MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE 64
#endif
#ifndef MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT
#define MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT 500
#endif
namespace {
char tx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0};
char rx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0};
const char ASCII_MAX = '~' - ' ';
const int ECHO_LOOPS = 16;
}
void prep_buffer(char *uuid_buffer, size_t uuid_len, char *tx_buffer, size_t tx_size) {
size_t i = 0;
for (; i<uuid_len; ++i) {
tx_buffer[i] = uuid_buffer[i];
}
tx_buffer[i++] = ' ';
for (; i<tx_size; ++i) {
tx_buffer[i] = (rand() % 10) + '0';
}
}
int main() {
char uuid[48] = {0};
GREENTEA_SETUP_UUID(60, "udp_echo", uuid, 48);
printf("Got a uuid of %s\r\n", uuid);
size_t uuid_len = strlen(uuid);
EthernetInterface eth;
eth.connect();
printf("UDP client IP Address is %s\n", eth.get_ip_address());
greentea_send_kv("target_ip", eth.get_ip_address());
char recv_key[] = "host_port";
char ipbuf[60] = {0};
char portbuf[16] = {0};
unsigned int port = 0;
UDPSocket sock;
sock.open(ð);
sock.set_timeout(MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT);
greentea_send_kv("host_ip", " ");
greentea_parse_kv(recv_key, ipbuf, sizeof(recv_key), sizeof(ipbuf));
greentea_send_kv("host_port", " ");
greentea_parse_kv(recv_key, portbuf, sizeof(recv_key), sizeof(ipbuf));
sscanf(portbuf, "%u", &port);
printf("MBED: UDP Server IP address received: %s:%d \n", ipbuf, port);
SocketAddress udp_addr(ipbuf, port);
int success = 0;
int i = 0;
while (success < ECHO_LOOPS) {
prep_buffer(uuid, uuid_len, tx_buffer, sizeof(tx_buffer));
const int ret = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
printf("[%02d] sent %d Bytes - %.*s \n", i, ret, MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE, tx_buffer);
SocketAddress temp_addr;
const int n = sock.recvfrom(&temp_addr, rx_buffer, sizeof(rx_buffer));
printf("[%02d] recv %d Bytes - %.*s \n", i, ret, MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE, rx_buffer);
if ((temp_addr == udp_addr &&
n == sizeof(tx_buffer) &&
memcmp(rx_buffer, tx_buffer, sizeof(rx_buffer)) == 0)) {
success += 1;
printf("[%02d] success #%d\n", i, success);
}
i++;
}
bool result = success == ECHO_LOOPS;
sock.close();
eth.disconnect();
GREENTEA_TESTSUITE_RESULT(result);
}
<|endoftext|> |
<commit_before>#include "common/buffer/buffer_impl.h"
#include "common/common/logger.h"
#include "common/http/http2/metadata_decoder.h"
#include "common/http/http2/metadata_encoder.h"
#include "common/runtime/runtime_impl.h"
#include "test/test_common/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "nghttp2/nghttp2.h"
// A global variable in nghttp2 to disable preface and initial settings for tests.
// TODO(soya3129): Remove after issue https://github.com/nghttp2/nghttp2/issues/1246 is fixed.
extern "C" {
extern int nghttp2_enable_strict_preface;
}
namespace Envoy {
namespace Http {
namespace Http2 {
namespace {
static const uint64_t STREAM_ID = 1;
// The buffer stores data sent by encoder and received by decoder.
struct TestBuffer {
uint8_t buf[1024 * 1024] = {0};
size_t length = 0;
};
// The application data structure passes to nghttp2 session.
struct UserData {
MetadataEncoder* encoder;
MetadataDecoder* decoder;
// Stores data sent by encoder and received by the decoder.
TestBuffer* output_buffer;
};
// Nghttp2 callback function for sending extension frame.
static ssize_t pack_extension_callback(nghttp2_session* session, uint8_t* buf, size_t len,
const nghttp2_frame*, void* user_data) {
EXPECT_NE(nullptr, session);
MetadataEncoder* encoder = reinterpret_cast<UserData*>(user_data)->encoder;
const uint64_t size_copied = encoder->packNextFramePayload(buf, len);
return static_cast<ssize_t>(size_copied);
}
// Nghttp2 callback function for receiving extension frame.
static int on_extension_chunk_recv_callback(nghttp2_session* session, const nghttp2_frame_hd* hd,
const uint8_t* data, size_t len, void* user_data) {
EXPECT_NE(nullptr, session);
EXPECT_GE(hd->length, len);
MetadataDecoder* decoder = reinterpret_cast<UserData*>(user_data)->decoder;
bool success = decoder->receiveMetadata(data, len);
return success ? 0 : NGHTTP2_ERR_CALLBACK_FAILURE;
}
// Nghttp2 callback function for unpack extension frames.
static int unpack_extension_callback(nghttp2_session* session, void** payload,
const nghttp2_frame_hd* hd, void* user_data) {
EXPECT_NE(nullptr, session);
EXPECT_NE(nullptr, hd);
EXPECT_NE(nullptr, payload);
MetadataDecoder* decoder = reinterpret_cast<UserData*>(user_data)->decoder;
bool result = decoder->onMetadataFrameComplete((hd->flags == END_METADATA_FLAG) ? true : false);
return result ? 0 : NGHTTP2_ERR_CALLBACK_FAILURE;
}
// Nghttp2 callback function for sending data to peer.
static ssize_t send_callback(nghttp2_session* session, const uint8_t* buf, size_t len, int flags,
void* user_data) {
EXPECT_NE(nullptr, session);
EXPECT_LE(0, flags);
TestBuffer* buffer = (reinterpret_cast<UserData*>(user_data))->output_buffer;
memcpy(buffer->buf + buffer->length, buf, len);
buffer->length += len;
return len;
}
} // namespace
class MetadataEncoderDecoderTest : public testing::Test {
public:
void initialize(MetadataCallback cb) {
decoder_ = std::make_unique<MetadataDecoder>(cb);
// Enables extension frame.
nghttp2_option_new(&option_);
nghttp2_option_set_user_recv_extension_type(option_, METADATA_FRAME_TYPE);
// Sets callback functions.
nghttp2_session_callbacks_new(&callbacks_);
nghttp2_session_callbacks_set_pack_extension_callback(callbacks_, pack_extension_callback);
nghttp2_session_callbacks_set_send_callback(callbacks_, send_callback);
nghttp2_session_callbacks_set_on_extension_chunk_recv_callback(
callbacks_, on_extension_chunk_recv_callback);
nghttp2_session_callbacks_set_unpack_extension_callback(callbacks_, unpack_extension_callback);
// Sets application data to pass to nghttp2 session.
user_data_.encoder = &encoder_;
user_data_.decoder = decoder_.get();
user_data_.output_buffer = &output_buffer_;
// Creates new nghttp2 session.
nghttp2_enable_strict_preface = 0;
nghttp2_session_client_new2(&session_, callbacks_, &user_data_, option_);
nghttp2_enable_strict_preface = 1;
}
void cleanUp() {
nghttp2_session_del(session_);
nghttp2_session_callbacks_del(callbacks_);
nghttp2_option_del(option_);
}
void verifyMetadataMapVector(MetadataMapVector& expect, MetadataMapPtr&& metadata_map_ptr) {
for (const auto& metadata : *metadata_map_ptr) {
EXPECT_EQ(expect.front()->find(metadata.first)->second, metadata.second);
}
expect.erase(expect.begin());
}
void submitMetadata(const MetadataMapVector& metadata_map_vector) {
// Creates metadata payload.
encoder_.createPayload(metadata_map_vector);
for (uint8_t flags : encoder_.payloadFrameFlagBytes()) {
int result =
nghttp2_submit_extension(session_, METADATA_FRAME_TYPE, flags, STREAM_ID, nullptr);
EXPECT_EQ(0, result);
}
// Triggers nghttp2 to populate the payloads of the METADATA frames.
int result = nghttp2_session_send(session_);
EXPECT_EQ(0, result);
}
nghttp2_session* session_ = nullptr;
nghttp2_session_callbacks* callbacks_;
MetadataEncoder encoder_;
std::unique_ptr<MetadataDecoder> decoder_;
nghttp2_option* option_;
int count_ = 0;
// Stores data received by peer.
TestBuffer output_buffer_;
// Application data passed to nghttp2.
UserData user_data_;
Runtime::RandomGeneratorImpl random_generator_;
};
TEST_F(MetadataEncoderDecoderTest, TestMetadataSizeLimit) {
MetadataMap metadata_map = {
{"header_key1", std::string(1024 * 1024 + 1, 'a')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
// metadata_map exceeds size limit.
EXPECT_LOG_CONTAINS("error", "exceeds the max bound.",
EXPECT_FALSE(encoder_.createPayload(metadata_map_vector)));
std::string payload = std::string(1024 * 1024 + 1, 'a');
EXPECT_FALSE(
decoder_->receiveMetadata(reinterpret_cast<const uint8_t*>(payload.data()), payload.size()));
cleanUp();
}
TEST_F(MetadataEncoderDecoderTest, TestDecodeBadData) {
MetadataMap metadata_map = {
{"header_key1", "header_value1"},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Messes up with the encoded payload, and passes it to the decoder.
output_buffer_.buf[10] |= 0xff;
decoder_->receiveMetadata(output_buffer_.buf, output_buffer_.length);
EXPECT_FALSE(decoder_->onMetadataFrameComplete(true));
cleanUp();
}
// Checks if accumulated metadata size reaches size limit, returns failure.
TEST_F(MetadataEncoderDecoderTest, VerifyEncoderDecoderMultipleMetadataReachSizeLimit) {
MetadataMap metadata_map_empty = {};
MetadataCallback cb = [](std::unique_ptr<MetadataMap>) -> void {};
initialize(cb);
ssize_t result = 0;
for (int i = 0; i < 100; i++) {
// Cleans up the output buffer.
memset(output_buffer_.buf, 0, output_buffer_.length);
output_buffer_.length = 0;
MetadataMap metadata_map = {
{"header_key1", std::string(10000, 'a')},
{"header_key2", std::string(10000, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
// Encode and decode the second MetadataMap.
decoder_->callback_ = [this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
};
submitMetadata(metadata_map_vector);
result = nghttp2_session_mem_recv(session_, output_buffer_.buf, output_buffer_.length);
if (result < 0) {
break;
}
}
// Verifies max metadata limit reached.
EXPECT_LT(result, 0);
EXPECT_LE(decoder_->max_payload_size_bound_, decoder_->total_payload_size_);
cleanUp();
}
// Tests encoding/decoding small metadata map vectors.
TEST_F(MetadataEncoderDecoderTest, EncodeMetadataMapVectorSmall) {
MetadataMap metadata_map = {
{"header_key1", std::string(5, 'a')},
{"header_key2", std::string(5, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMap metadata_map_2 = {
{"header_key3", std::string(5, 'a')},
{"header_key4", std::string(5, 'b')},
};
MetadataMapPtr metadata_map_ptr_2 = std::make_unique<MetadataMap>(metadata_map);
MetadataMap metadata_map_3 = {
{"header_key1", std::string(1, 'a')},
{"header_key2", std::string(1, 'b')},
};
MetadataMapPtr metadata_map_ptr_3 = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
metadata_map_vector.push_back(std::move(metadata_map_ptr_2));
metadata_map_vector.push_back(std::move(metadata_map_ptr_3));
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Verifies flag and payload are encoded correctly.
const uint64_t consume_size = random_generator_.random() % output_buffer_.length;
nghttp2_session_mem_recv(session_, output_buffer_.buf, consume_size);
nghttp2_session_mem_recv(session_, output_buffer_.buf + consume_size,
output_buffer_.length - consume_size);
cleanUp();
}
// Tests encoding/decoding large metadata map vectors.
TEST_F(MetadataEncoderDecoderTest, EncodeMetadataMapVectorLarge) {
MetadataMapVector metadata_map_vector;
for (int i = 0; i < 10; i++) {
MetadataMap metadata_map = {
{"header_key1", std::string(50000, 'a')},
{"header_key2", std::string(50000, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
metadata_map_vector.push_back(std::move(metadata_map_ptr));
}
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Verifies flag and payload are encoded correctly.
const uint64_t consume_size = random_generator_.random() % output_buffer_.length;
nghttp2_session_mem_recv(session_, output_buffer_.buf, consume_size);
nghttp2_session_mem_recv(session_, output_buffer_.buf + consume_size,
output_buffer_.length - consume_size);
cleanUp();
}
// Tests encoding/decoding with fuzzed metadata size.
TEST_F(MetadataEncoderDecoderTest, EncodeFuzzedMetadata) {
MetadataMapVector metadata_map_vector;
for (int i = 0; i < 10; i++) {
Runtime::RandomGeneratorImpl random;
int value_size_1 = random.random() % (2 * Http::METADATA_MAX_PAYLOAD_SIZE) + 1;
int value_size_2 = random.random() % (2 * Http::METADATA_MAX_PAYLOAD_SIZE) + 1;
MetadataMap metadata_map = {
{"header_key1", std::string(value_size_1, 'a')},
{"header_key2", std::string(value_size_2, 'a')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
metadata_map_vector.push_back(std::move(metadata_map_ptr));
}
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Verifies flag and payload are encoded correctly.
nghttp2_session_mem_recv(session_, output_buffer_.buf, output_buffer_.length);
cleanUp();
}
using MetadataEncoderDecoderDeathTest = MetadataEncoderDecoderTest;
// Crash if a caller tries to pack more frames than the encoder has data for.
TEST_F(MetadataEncoderDecoderDeathTest, PackTooManyFrames) {
MetadataMap metadata_map = {
{"header_key1", std::string(5, 'a')},
{"header_key2", std::string(5, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Try to send an extra METADATA frame. Submitting the frame to nghttp2 should succeed, but
// pack_extension_callback should fail, and that failure will propagate through
// nghttp2_session_send. How to handle the failure is up to the HTTP/2 codec (in practice, it will
// throw a CodecProtocolException).
int result = nghttp2_submit_extension(session_, METADATA_FRAME_TYPE, 0, STREAM_ID, nullptr);
EXPECT_EQ(0, result);
EXPECT_DEATH(nghttp2_session_send(session_),
"No payload remaining to pack into a METADATA frame.");
cleanUp();
}
} // namespace Http2
} // namespace Http
} // namespace Envoy
<commit_msg>Fix MetadataEncoderDecoderDeathTest.PackTooManyFrames in coverage build. (#10279)<commit_after>#include "common/buffer/buffer_impl.h"
#include "common/common/logger.h"
#include "common/http/http2/metadata_decoder.h"
#include "common/http/http2/metadata_encoder.h"
#include "common/runtime/runtime_impl.h"
#include "test/test_common/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "nghttp2/nghttp2.h"
// A global variable in nghttp2 to disable preface and initial settings for tests.
// TODO(soya3129): Remove after issue https://github.com/nghttp2/nghttp2/issues/1246 is fixed.
extern "C" {
extern int nghttp2_enable_strict_preface;
}
namespace Envoy {
namespace Http {
namespace Http2 {
namespace {
static const uint64_t STREAM_ID = 1;
// The buffer stores data sent by encoder and received by decoder.
struct TestBuffer {
uint8_t buf[1024 * 1024] = {0};
size_t length = 0;
};
// The application data structure passes to nghttp2 session.
struct UserData {
MetadataEncoder* encoder;
MetadataDecoder* decoder;
// Stores data sent by encoder and received by the decoder.
TestBuffer* output_buffer;
};
// Nghttp2 callback function for sending extension frame.
static ssize_t pack_extension_callback(nghttp2_session* session, uint8_t* buf, size_t len,
const nghttp2_frame*, void* user_data) {
EXPECT_NE(nullptr, session);
MetadataEncoder* encoder = reinterpret_cast<UserData*>(user_data)->encoder;
const uint64_t size_copied = encoder->packNextFramePayload(buf, len);
return static_cast<ssize_t>(size_copied);
}
// Nghttp2 callback function for receiving extension frame.
static int on_extension_chunk_recv_callback(nghttp2_session* session, const nghttp2_frame_hd* hd,
const uint8_t* data, size_t len, void* user_data) {
EXPECT_NE(nullptr, session);
EXPECT_GE(hd->length, len);
MetadataDecoder* decoder = reinterpret_cast<UserData*>(user_data)->decoder;
bool success = decoder->receiveMetadata(data, len);
return success ? 0 : NGHTTP2_ERR_CALLBACK_FAILURE;
}
// Nghttp2 callback function for unpack extension frames.
static int unpack_extension_callback(nghttp2_session* session, void** payload,
const nghttp2_frame_hd* hd, void* user_data) {
EXPECT_NE(nullptr, session);
EXPECT_NE(nullptr, hd);
EXPECT_NE(nullptr, payload);
MetadataDecoder* decoder = reinterpret_cast<UserData*>(user_data)->decoder;
bool result = decoder->onMetadataFrameComplete((hd->flags == END_METADATA_FLAG) ? true : false);
return result ? 0 : NGHTTP2_ERR_CALLBACK_FAILURE;
}
// Nghttp2 callback function for sending data to peer.
static ssize_t send_callback(nghttp2_session* session, const uint8_t* buf, size_t len, int flags,
void* user_data) {
EXPECT_NE(nullptr, session);
EXPECT_LE(0, flags);
TestBuffer* buffer = (reinterpret_cast<UserData*>(user_data))->output_buffer;
memcpy(buffer->buf + buffer->length, buf, len);
buffer->length += len;
return len;
}
} // namespace
class MetadataEncoderDecoderTest : public testing::Test {
public:
void initialize(MetadataCallback cb) {
decoder_ = std::make_unique<MetadataDecoder>(cb);
// Enables extension frame.
nghttp2_option_new(&option_);
nghttp2_option_set_user_recv_extension_type(option_, METADATA_FRAME_TYPE);
// Sets callback functions.
nghttp2_session_callbacks_new(&callbacks_);
nghttp2_session_callbacks_set_pack_extension_callback(callbacks_, pack_extension_callback);
nghttp2_session_callbacks_set_send_callback(callbacks_, send_callback);
nghttp2_session_callbacks_set_on_extension_chunk_recv_callback(
callbacks_, on_extension_chunk_recv_callback);
nghttp2_session_callbacks_set_unpack_extension_callback(callbacks_, unpack_extension_callback);
// Sets application data to pass to nghttp2 session.
user_data_.encoder = &encoder_;
user_data_.decoder = decoder_.get();
user_data_.output_buffer = &output_buffer_;
// Creates new nghttp2 session.
nghttp2_enable_strict_preface = 0;
nghttp2_session_client_new2(&session_, callbacks_, &user_data_, option_);
nghttp2_enable_strict_preface = 1;
}
void cleanUp() {
nghttp2_session_del(session_);
nghttp2_session_callbacks_del(callbacks_);
nghttp2_option_del(option_);
}
void verifyMetadataMapVector(MetadataMapVector& expect, MetadataMapPtr&& metadata_map_ptr) {
for (const auto& metadata : *metadata_map_ptr) {
EXPECT_EQ(expect.front()->find(metadata.first)->second, metadata.second);
}
expect.erase(expect.begin());
}
void submitMetadata(const MetadataMapVector& metadata_map_vector) {
// Creates metadata payload.
encoder_.createPayload(metadata_map_vector);
for (uint8_t flags : encoder_.payloadFrameFlagBytes()) {
int result =
nghttp2_submit_extension(session_, METADATA_FRAME_TYPE, flags, STREAM_ID, nullptr);
EXPECT_EQ(0, result);
}
// Triggers nghttp2 to populate the payloads of the METADATA frames.
int result = nghttp2_session_send(session_);
EXPECT_EQ(0, result);
}
nghttp2_session* session_ = nullptr;
nghttp2_session_callbacks* callbacks_;
MetadataEncoder encoder_;
std::unique_ptr<MetadataDecoder> decoder_;
nghttp2_option* option_;
int count_ = 0;
// Stores data received by peer.
TestBuffer output_buffer_;
// Application data passed to nghttp2.
UserData user_data_;
Runtime::RandomGeneratorImpl random_generator_;
};
TEST_F(MetadataEncoderDecoderTest, TestMetadataSizeLimit) {
MetadataMap metadata_map = {
{"header_key1", std::string(1024 * 1024 + 1, 'a')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
// metadata_map exceeds size limit.
EXPECT_LOG_CONTAINS("error", "exceeds the max bound.",
EXPECT_FALSE(encoder_.createPayload(metadata_map_vector)));
std::string payload = std::string(1024 * 1024 + 1, 'a');
EXPECT_FALSE(
decoder_->receiveMetadata(reinterpret_cast<const uint8_t*>(payload.data()), payload.size()));
cleanUp();
}
TEST_F(MetadataEncoderDecoderTest, TestDecodeBadData) {
MetadataMap metadata_map = {
{"header_key1", "header_value1"},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Messes up with the encoded payload, and passes it to the decoder.
output_buffer_.buf[10] |= 0xff;
decoder_->receiveMetadata(output_buffer_.buf, output_buffer_.length);
EXPECT_FALSE(decoder_->onMetadataFrameComplete(true));
cleanUp();
}
// Checks if accumulated metadata size reaches size limit, returns failure.
TEST_F(MetadataEncoderDecoderTest, VerifyEncoderDecoderMultipleMetadataReachSizeLimit) {
MetadataMap metadata_map_empty = {};
MetadataCallback cb = [](std::unique_ptr<MetadataMap>) -> void {};
initialize(cb);
ssize_t result = 0;
for (int i = 0; i < 100; i++) {
// Cleans up the output buffer.
memset(output_buffer_.buf, 0, output_buffer_.length);
output_buffer_.length = 0;
MetadataMap metadata_map = {
{"header_key1", std::string(10000, 'a')},
{"header_key2", std::string(10000, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
// Encode and decode the second MetadataMap.
decoder_->callback_ = [this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
};
submitMetadata(metadata_map_vector);
result = nghttp2_session_mem_recv(session_, output_buffer_.buf, output_buffer_.length);
if (result < 0) {
break;
}
}
// Verifies max metadata limit reached.
EXPECT_LT(result, 0);
EXPECT_LE(decoder_->max_payload_size_bound_, decoder_->total_payload_size_);
cleanUp();
}
// Tests encoding/decoding small metadata map vectors.
TEST_F(MetadataEncoderDecoderTest, EncodeMetadataMapVectorSmall) {
MetadataMap metadata_map = {
{"header_key1", std::string(5, 'a')},
{"header_key2", std::string(5, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMap metadata_map_2 = {
{"header_key3", std::string(5, 'a')},
{"header_key4", std::string(5, 'b')},
};
MetadataMapPtr metadata_map_ptr_2 = std::make_unique<MetadataMap>(metadata_map);
MetadataMap metadata_map_3 = {
{"header_key1", std::string(1, 'a')},
{"header_key2", std::string(1, 'b')},
};
MetadataMapPtr metadata_map_ptr_3 = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
metadata_map_vector.push_back(std::move(metadata_map_ptr_2));
metadata_map_vector.push_back(std::move(metadata_map_ptr_3));
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Verifies flag and payload are encoded correctly.
const uint64_t consume_size = random_generator_.random() % output_buffer_.length;
nghttp2_session_mem_recv(session_, output_buffer_.buf, consume_size);
nghttp2_session_mem_recv(session_, output_buffer_.buf + consume_size,
output_buffer_.length - consume_size);
cleanUp();
}
// Tests encoding/decoding large metadata map vectors.
TEST_F(MetadataEncoderDecoderTest, EncodeMetadataMapVectorLarge) {
MetadataMapVector metadata_map_vector;
for (int i = 0; i < 10; i++) {
MetadataMap metadata_map = {
{"header_key1", std::string(50000, 'a')},
{"header_key2", std::string(50000, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
metadata_map_vector.push_back(std::move(metadata_map_ptr));
}
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Verifies flag and payload are encoded correctly.
const uint64_t consume_size = random_generator_.random() % output_buffer_.length;
nghttp2_session_mem_recv(session_, output_buffer_.buf, consume_size);
nghttp2_session_mem_recv(session_, output_buffer_.buf + consume_size,
output_buffer_.length - consume_size);
cleanUp();
}
// Tests encoding/decoding with fuzzed metadata size.
TEST_F(MetadataEncoderDecoderTest, EncodeFuzzedMetadata) {
MetadataMapVector metadata_map_vector;
for (int i = 0; i < 10; i++) {
Runtime::RandomGeneratorImpl random;
int value_size_1 = random.random() % (2 * Http::METADATA_MAX_PAYLOAD_SIZE) + 1;
int value_size_2 = random.random() % (2 * Http::METADATA_MAX_PAYLOAD_SIZE) + 1;
MetadataMap metadata_map = {
{"header_key1", std::string(value_size_1, 'a')},
{"header_key2", std::string(value_size_2, 'a')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
metadata_map_vector.push_back(std::move(metadata_map_ptr));
}
// Verifies the encoding/decoding result in decoder's callback functions.
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Verifies flag and payload are encoded correctly.
nghttp2_session_mem_recv(session_, output_buffer_.buf, output_buffer_.length);
cleanUp();
}
using MetadataEncoderDecoderDeathTest = MetadataEncoderDecoderTest;
// Crash if a caller tries to pack more frames than the encoder has data for.
TEST_F(MetadataEncoderDecoderDeathTest, PackTooManyFrames) {
Logger::StderrSinkDelegate stderr_sink(Logger::Registry::getSink()); // For coverage build.
MetadataMap metadata_map = {
{"header_key1", std::string(5, 'a')},
{"header_key2", std::string(5, 'b')},
};
MetadataMapPtr metadata_map_ptr = std::make_unique<MetadataMap>(metadata_map);
MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
initialize([this, &metadata_map_vector](MetadataMapPtr&& metadata_map_ptr) -> void {
this->verifyMetadataMapVector(metadata_map_vector, std::move(metadata_map_ptr));
});
submitMetadata(metadata_map_vector);
// Try to send an extra METADATA frame. Submitting the frame to nghttp2 should succeed, but
// pack_extension_callback should fail, and that failure will propagate through
// nghttp2_session_send. How to handle the failure is up to the HTTP/2 codec (in practice, it will
// throw a CodecProtocolException).
int result = nghttp2_submit_extension(session_, METADATA_FRAME_TYPE, 0, STREAM_ID, nullptr);
EXPECT_EQ(0, result);
EXPECT_DEATH(nghttp2_session_send(session_),
"No payload remaining to pack into a METADATA frame.");
cleanUp();
}
} // namespace Http2
} // namespace Http
} // namespace Envoy
<|endoftext|> |
<commit_before>#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <Eigen/Dense>
#include "firmware_generator.h"
#include "firmware_template.h"
#include "control_design_functions.h"
void firmware_generator(const std::vector<model_data> & md, std::string filename_base)
{
const int observer_state_size = 1; // observer state is w
const int observer_input_size = 4; // observer inputs are: steer, roll rate, steer rate, steer torque
const int observer_output_size = 1; // estimate of roll angle
const int plant_model_state_size = 4; // roll, steer, roll rate, steer rate
const int plant_model_input_size = 1; // torque
std::string header_body{};
header_body += "const uint32_t num_gains = "
+ std::to_string(md.size()) + ";\n";
header_body += "const uint32_t observer_state_size = "
+ std::to_string(observer_state_size) + ";\n";
header_body += "const uint32_t observer_input_size = "
+ std::to_string(observer_input_size) + ";\n";
header_body += "const uint32_t observer_output_size = "
+ std::to_string(observer_output_size) + ";\n";
header_body += "const uint32_t plant_model_state_size = "
+ std::to_string(plant_model_state_size) + ";\n";
header_body += "const uint32_t plant_model_input_size = "
+ std::to_string(plant_model_input_size) + ";\n";
std::ofstream header_file(filename_base + ".h");
header_file << firmware_template::preamble
<< header_body << firmware_template::postamble;
header_file.close();
std::ofstream source_file(filename_base + ".cpp");
source_file << generate_source(md, filename_base);
source_file.close();
}
std::string generate_source(const std::vector<model_data> & md, std::string filename_base)
{
//std::string source_body{};
Eigen::IOFormat printfmt(Eigen::FullPrecision, 0, ", ", ", ", "", "", "{{", "}}");
std::ostringstream out;
out << "#include \"" << filename_base << ".h\"\n\n";
out << "namespace control {\n\n";
out << "const std::array<rt_controller_t, " << md.size();
out << "> GainSchedule::schedule_ {{\n";
for(auto it = md.begin(); it != md.end(); ++it) {
out << "\t{\n";
out << "\t\t" << it->theta_R_dot <<"f, // theta_R_dot\n";
out << "\t\t{\n"; // start writing out controllers
out << "\t\t\t{ // StateEstimator\n";
out << "\t\t\t\t" << it->A_obs.format(printfmt) << ",\n";
out << "\t\t\t\t" << it->B_obs.format(printfmt) << ",\n";
out << "\t\t\t\t" << it->C_obs.format(printfmt) << ",\n";
out << "\t\t\t\t" << it->D_obs.format(printfmt) << "\n";
out << "\t\t\t},\n"; // StateEstimator End
out << "\t\t\t{ // LQRController\n"; // LQRController Start
out << "\t\t\t\t" << it->K_lqr.format(printfmt) << "\n";
out << "\t\t\t},\n"; // LQRController End
out << "\t\t\t{ // PIController\n"; // PIController Start
out << "\t\t\t\t0, 0\n";
out << "\t\t\t}\n"; // PIController End
out << "\t\t}\n"; // controllers end
if (it + 1 == md.end()) {
out << "\t}\n";
} else {
out << "\t},\n";
}
}
out << "}};\n\n} // namespace control";
return out.str();
}
<commit_msg>Fix typo in model_data data member.<commit_after>#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <Eigen/Dense>
#include "firmware_generator.h"
#include "firmware_template.h"
#include "control_design_functions.h"
void firmware_generator(const std::vector<model_data> & md, std::string filename_base)
{
const int observer_state_size = 1; // observer state is w
const int observer_input_size = 4; // observer inputs are: steer, roll rate, steer rate, steer torque
const int observer_output_size = 1; // estimate of roll angle
const int plant_model_state_size = 4; // roll, steer, roll rate, steer rate
const int plant_model_input_size = 1; // torque
std::string header_body{};
header_body += "const uint32_t num_gains = "
+ std::to_string(md.size()) + ";\n";
header_body += "const uint32_t observer_state_size = "
+ std::to_string(observer_state_size) + ";\n";
header_body += "const uint32_t observer_input_size = "
+ std::to_string(observer_input_size) + ";\n";
header_body += "const uint32_t observer_output_size = "
+ std::to_string(observer_output_size) + ";\n";
header_body += "const uint32_t plant_model_state_size = "
+ std::to_string(plant_model_state_size) + ";\n";
header_body += "const uint32_t plant_model_input_size = "
+ std::to_string(plant_model_input_size) + ";\n";
std::ofstream header_file(filename_base + ".h");
header_file << firmware_template::preamble
<< header_body << firmware_template::postamble;
header_file.close();
std::ofstream source_file(filename_base + ".cpp");
source_file << generate_source(md, filename_base);
source_file.close();
}
std::string generate_source(const std::vector<model_data> & md, std::string filename_base)
{
//std::string source_body{};
Eigen::IOFormat printfmt(Eigen::FullPrecision, 0, ", ", ", ", "", "", "{{", "}}");
std::ostringstream out;
out << "#include \"" << filename_base << ".h\"\n\n";
out << "namespace control {\n\n";
out << "const std::array<rt_controller_t, " << md.size();
out << "> GainSchedule::schedule_ {{\n";
for(auto it = md.begin(); it != md.end(); ++it) {
out << "\t{\n";
out << "\t\t" << it->theta_R_dot <<"f, // theta_R_dot\n";
out << "\t\t{\n"; // start writing out controllers
out << "\t\t\t{ // StateEstimator\n";
out << "\t\t\t\t" << it->A_obs_d.format(printfmt) << ",\n";
out << "\t\t\t\t" << it->B_obs_d.format(printfmt) << ",\n";
out << "\t\t\t\t" << it->C_obs.format(printfmt) << ",\n";
out << "\t\t\t\t" << it->D_obs.format(printfmt) << "\n";
out << "\t\t\t},\n"; // StateEstimator End
out << "\t\t\t{ // LQRController\n"; // LQRController Start
out << "\t\t\t\t" << it->K_lqr.format(printfmt) << "\n";
out << "\t\t\t},\n"; // LQRController End
out << "\t\t\t{ // PIController\n"; // PIController Start
out << "\t\t\t\t0, 0\n";
out << "\t\t\t}\n"; // PIController End
out << "\t\t}\n"; // controllers end
if (it + 1 == md.end()) {
out << "\t}\n";
} else {
out << "\t},\n";
}
}
out << "}};\n\n} // namespace control";
return out.str();
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <nlohmann/json.hpp>
#include <vector>
#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
namespace dai {
/// FeatureTracker configuration data structure
struct FeatureTrackerConfigData {
struct CornerDetector {
static constexpr const int AUTO = 0;
enum class AlgorithmType : std::int32_t {
/**
* Harris corner detector.
*/
HARRIS,
/**
* Shi-Thomasi corner detector.
*/
SHI_THOMASI
};
/**
* Corner detector algorithm type.
*/
AlgorithmType algorithmType = AlgorithmType::HARRIS;
/**
* Ensures distributed feature detection across the image.
* Image is divided into horizontal and vertical cells,
* each cell has a target feature count = targetNumFeatures / cellGridDimension.
* Each cell has it's own feature threshold.
* A value of 4 means that the image is divided into 4x4 cells of equal width/height.
* Maximum 4, minimum 1.
*/
std::int32_t cellGridDimension = 4;
/**
* Target number of features to detect.
* Maximum number of features is determined at runtime based on algorithm type.
*/
std::int32_t targetNumFeatures = 320;
/**
* Hard limit for the maximum number of features that can be detected.
* 0 means auto, will be set to the maximum value based on memory constraints.
*/
std::int32_t maxNumFeatures = AUTO;
/**
* Enable 3x3 sobel operator to smoothen the image whose gradient is be computed.
* If disabled a simple 1D row/column differentiator is used for gradient.
*/
bool enableSobel = true;
/**
* Enable sorting detected features based on their score or not.
*/
bool enableSorting = true;
/**
* Threshold settings structure for corner detector.
*/
struct Thresholds {
static constexpr const float AUTO = 0;
/**
* Minimum strength of a feature which will be detected.
* 0 means automatic threshold update. Recommended so the tracker can adapt to different scenes/textures.
* Each chell has its own threshold.
* Empirical value.
*/
float initialValue = AUTO;
/**
* Minimum limit for threshold.
* Applicable when automatic threshold update is enabled.
* 0 means auto, 6000000 for HARRIS, 1200 for SHI_THOMASI
* Empirical value.
*/
float min = AUTO;
/**
* Maximum limit for threshold.
* Applicable when automatic threshold update is enabled.
* 0 means auto.
* Empirical value.
*/
float max = AUTO;
/**
* When detected number of features exceeds the maximum in a cell threshold is lowered
* by multiplying its value with this factor.
*/
float decreaseFactor = 0.9;
/**
* When detected number of features doesn't exceed the maximum in a cell threshold is increased
* by multiplying its value with this factor.
*/
float increaseFactor = 1.1;
};
/**
* Threshold settings.
* These are advanced settings, suitable for debugging/special cases.
*/
Thresholds thresholds;
};
/**
* Used for feature reidentification between current and previous features.
*/
struct MotionEstimator {
bool enable = true;
enum class AlgorithmType : std::int32_t {
/**
* Using the pyramidal Lucas-Kanade optical flow method.
*/
LUCAS_KANADE_OPTICAL_FLOW
};
/**
* Motion estimator algorithm type.
*/
AlgorithmType algorithmType = AlgorithmType::LUCAS_KANADE_OPTICAL_FLOW;
/**
* Optical flow configuration structure.
*/
struct OpticalFlow {
static constexpr const std::int32_t AUTO = 0;
/**
* Number of pyramid levels, only for optical flow.
* AUTO means it's decided based on input resolution: 3 if image width <= 640, else 4.
* Valid values are either 3/4 for VGA, 4 for 720p and above.
*/
std::int32_t pyramidLevels = AUTO;
/**
* Image patch width used to track features.
* Must be an odd number, maximum 9.
* N means the algorithm will be able to track motion at most (N-1)/2 pixels in a direction per pyramid level.
* Increasing this number increases runtime
*/
std::int32_t searchWindowWidth = 5;
/**
* Image patch height used to track features.
* Must be an odd number, maximum 9.
* N means the algorithm will be able to track motion at most (N-1)/2 pixels in a direction per pyramid level.
* Increasing this number increases runtime
*/
std::int32_t searchWindowHeight = 5;
/**
* Feature tracking termination criteria.
* Optical flow will refine the feature position on each pyramid level until
* the displacement between two refinements is smaller than this value.
* Decreasing this number increases runtime.
*/
float epsilon = 0.01;
/**
* Feature tracking termination criteria. Optical flow will refine the feature position maximum this many times
* on each pyramid level. If the Epsilon criteria described in the previous chapter is not met after this number
* of iterations, the algorithm will continue with the current calculated value.
* Increasing this number increases runtime.
*/
std::int32_t maxIterations = 9;
};
/**
* Optical flow configuration.
* Takes effect only if MotionEstimator algorithm type set to LUCAS_KANADE_OPTICAL_FLOW.
*/
OpticalFlow opticalFlow;
};
/**
* Used for feature filtering.
*/
struct FeatureMaintainer {
bool enable = true;
/**
* Used to filter out detected feature points that are too close.
* Unit of measurement is squared euclidian distance in pixels.
*/
float minimumDistanceBetweenFeatures = 50;
/**
* Optical flow measures the tracking error for every feature.
* If the point can’t be tracked or it’s out of the image it will set this error to a maximum value.
* This threshold defines the level where the tracking accuracy is considered too bad to keep the point.
*/
float lostFeatureErrorThreshold = 50000;
/**
* Once a feature was detected and we started tracking it, we need to update its Harris score on each image.
* This is needed because a feature point can disappear, or it can become too weak to be tracked. This
* threshold defines the point where such a feature must be dropped.
* As the goal of the algorithm is to provide longer tracks, we try to add strong points and track them until
* they are absolutely untrackable. This is why, this value is usually smaller than the detection threshold.
*/
float trackedFeatureThreshold = 200000;
};
/**
* Corner detector configuration.
* Used for feature detection.
*/
CornerDetector cornerDetector;
/**
* Motion estimator configuration.
* Used for feature reidentification between current and previos features.
*/
MotionEstimator motionEstimator;
/**
* FeatureMaintainer configuration.
* Used for feature maintaining.
*/
FeatureMaintainer featureMaintainer;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerConfigData::CornerDetector::Thresholds, initialValue, min, max, decreaseFactor, increaseFactor);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
FeatureTrackerConfigData::CornerDetector, algorithmType, cellGridDimension, targetNumFeatures, maxNumFeatures, thresholds, enableSobel, enableSorting);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
FeatureTrackerConfigData::MotionEstimator::OpticalFlow, pyramidLevels, searchWindowWidth, searchWindowHeight, epsilon, maxIterations);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerConfigData::MotionEstimator, enable, algorithmType, opticalFlow);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
FeatureTrackerConfigData::FeatureMaintainer, enable, minimumDistanceBetweenFeatures, lostFeatureErrorThreshold, trackedFeatureThreshold);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerConfigData, cornerDetector, motionEstimator, featureMaintainer);
/// RawFeatureTrackerConfig configuration structure
struct RawFeatureTrackerConfig : public RawBuffer {
FeatureTrackerConfigData config;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::FeatureTrackerConfig;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawFeatureTrackerConfig, config);
};
} // namespace dai
<commit_msg>Add HW motion estimator algorith type to motion estimator config<commit_after>#pragma once
#include <cstdint>
#include <nlohmann/json.hpp>
#include <vector>
#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
namespace dai {
/// FeatureTracker configuration data structure
struct FeatureTrackerConfigData {
struct CornerDetector {
static constexpr const int AUTO = 0;
enum class AlgorithmType : std::int32_t {
/**
* Harris corner detector.
*/
HARRIS,
/**
* Shi-Thomasi corner detector.
*/
SHI_THOMASI
};
/**
* Corner detector algorithm type.
*/
AlgorithmType algorithmType = AlgorithmType::HARRIS;
/**
* Ensures distributed feature detection across the image.
* Image is divided into horizontal and vertical cells,
* each cell has a target feature count = targetNumFeatures / cellGridDimension.
* Each cell has it's own feature threshold.
* A value of 4 means that the image is divided into 4x4 cells of equal width/height.
* Maximum 4, minimum 1.
*/
std::int32_t cellGridDimension = 4;
/**
* Target number of features to detect.
* Maximum number of features is determined at runtime based on algorithm type.
*/
std::int32_t targetNumFeatures = 320;
/**
* Hard limit for the maximum number of features that can be detected.
* 0 means auto, will be set to the maximum value based on memory constraints.
*/
std::int32_t maxNumFeatures = AUTO;
/**
* Enable 3x3 sobel operator to smoothen the image whose gradient is be computed.
* If disabled a simple 1D row/column differentiator is used for gradient.
*/
bool enableSobel = true;
/**
* Enable sorting detected features based on their score or not.
*/
bool enableSorting = true;
/**
* Threshold settings structure for corner detector.
*/
struct Thresholds {
static constexpr const float AUTO = 0;
/**
* Minimum strength of a feature which will be detected.
* 0 means automatic threshold update. Recommended so the tracker can adapt to different scenes/textures.
* Each chell has its own threshold.
* Empirical value.
*/
float initialValue = AUTO;
/**
* Minimum limit for threshold.
* Applicable when automatic threshold update is enabled.
* 0 means auto, 6000000 for HARRIS, 1200 for SHI_THOMASI
* Empirical value.
*/
float min = AUTO;
/**
* Maximum limit for threshold.
* Applicable when automatic threshold update is enabled.
* 0 means auto.
* Empirical value.
*/
float max = AUTO;
/**
* When detected number of features exceeds the maximum in a cell threshold is lowered
* by multiplying its value with this factor.
*/
float decreaseFactor = 0.9;
/**
* When detected number of features doesn't exceed the maximum in a cell threshold is increased
* by multiplying its value with this factor.
*/
float increaseFactor = 1.1;
};
/**
* Threshold settings.
* These are advanced settings, suitable for debugging/special cases.
*/
Thresholds thresholds;
};
/**
* Used for feature reidentification between current and previous features.
*/
struct MotionEstimator {
bool enable = true;
enum class AlgorithmType : std::int32_t {
/**
* Using the pyramidal Lucas-Kanade optical flow method.
*/
LUCAS_KANADE_OPTICAL_FLOW,
/**
* Using a dense motion estimation hardware block (Block matcher).
*/
HW_MOTION_ESTIMATION
};
/**
* Motion estimator algorithm type.
*/
AlgorithmType algorithmType = AlgorithmType::LUCAS_KANADE_OPTICAL_FLOW;
/**
* Optical flow configuration structure.
*/
struct OpticalFlow {
static constexpr const std::int32_t AUTO = 0;
/**
* Number of pyramid levels, only for optical flow.
* AUTO means it's decided based on input resolution: 3 if image width <= 640, else 4.
* Valid values are either 3/4 for VGA, 4 for 720p and above.
*/
std::int32_t pyramidLevels = AUTO;
/**
* Image patch width used to track features.
* Must be an odd number, maximum 9.
* N means the algorithm will be able to track motion at most (N-1)/2 pixels in a direction per pyramid level.
* Increasing this number increases runtime
*/
std::int32_t searchWindowWidth = 5;
/**
* Image patch height used to track features.
* Must be an odd number, maximum 9.
* N means the algorithm will be able to track motion at most (N-1)/2 pixels in a direction per pyramid level.
* Increasing this number increases runtime
*/
std::int32_t searchWindowHeight = 5;
/**
* Feature tracking termination criteria.
* Optical flow will refine the feature position on each pyramid level until
* the displacement between two refinements is smaller than this value.
* Decreasing this number increases runtime.
*/
float epsilon = 0.01;
/**
* Feature tracking termination criteria. Optical flow will refine the feature position maximum this many times
* on each pyramid level. If the Epsilon criteria described in the previous chapter is not met after this number
* of iterations, the algorithm will continue with the current calculated value.
* Increasing this number increases runtime.
*/
std::int32_t maxIterations = 9;
};
/**
* Optical flow configuration.
* Takes effect only if MotionEstimator algorithm type set to LUCAS_KANADE_OPTICAL_FLOW.
*/
OpticalFlow opticalFlow;
};
/**
* Used for feature filtering.
*/
struct FeatureMaintainer {
bool enable = true;
/**
* Used to filter out detected feature points that are too close.
* Unit of measurement is squared euclidian distance in pixels.
*/
float minimumDistanceBetweenFeatures = 50;
/**
* Optical flow measures the tracking error for every feature.
* If the point can’t be tracked or it’s out of the image it will set this error to a maximum value.
* This threshold defines the level where the tracking accuracy is considered too bad to keep the point.
*/
float lostFeatureErrorThreshold = 50000;
/**
* Once a feature was detected and we started tracking it, we need to update its Harris score on each image.
* This is needed because a feature point can disappear, or it can become too weak to be tracked. This
* threshold defines the point where such a feature must be dropped.
* As the goal of the algorithm is to provide longer tracks, we try to add strong points and track them until
* they are absolutely untrackable. This is why, this value is usually smaller than the detection threshold.
*/
float trackedFeatureThreshold = 200000;
};
/**
* Corner detector configuration.
* Used for feature detection.
*/
CornerDetector cornerDetector;
/**
* Motion estimator configuration.
* Used for feature reidentification between current and previos features.
*/
MotionEstimator motionEstimator;
/**
* FeatureMaintainer configuration.
* Used for feature maintaining.
*/
FeatureMaintainer featureMaintainer;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerConfigData::CornerDetector::Thresholds, initialValue, min, max, decreaseFactor, increaseFactor);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
FeatureTrackerConfigData::CornerDetector, algorithmType, cellGridDimension, targetNumFeatures, maxNumFeatures, thresholds, enableSobel, enableSorting);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
FeatureTrackerConfigData::MotionEstimator::OpticalFlow, pyramidLevels, searchWindowWidth, searchWindowHeight, epsilon, maxIterations);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerConfigData::MotionEstimator, enable, algorithmType, opticalFlow);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
FeatureTrackerConfigData::FeatureMaintainer, enable, minimumDistanceBetweenFeatures, lostFeatureErrorThreshold, trackedFeatureThreshold);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerConfigData, cornerDetector, motionEstimator, featureMaintainer);
/// RawFeatureTrackerConfig configuration structure
struct RawFeatureTrackerConfig : public RawBuffer {
FeatureTrackerConfigData config;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::FeatureTrackerConfig;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawFeatureTrackerConfig, config);
};
} // namespace dai
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2012 by the fifechan team *
* http://fifechan.github.com/fifechan *
* This file is part of fifechan. *
* *
* fifechan is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
/*
* For comments regarding functions please see the header file.
*/
#include "fifechan/widgets/flowcontainer.hpp"
#include "fifechan/exception.hpp"
namespace fcn {
FlowContainer::FlowContainer():
mAlignment(Center) {
//setBorderSize(1);
//setPadding(2);
setOpaque(true);
}
FlowContainer::~FlowContainer() {
}
void FlowContainer::setAlignment(FlowContainer::Alignment alignment) {
mAlignment = alignment;
}
FlowContainer::Alignment FlowContainer::getAlignment() const {
return mAlignment;
}
void FlowContainer::adjustContent() {
// diff means border, padding, ...
int diffW = getDimension().width - getChildrenArea().width;
int diffH = getDimension().height - getChildrenArea().height;
// max size that can be used for layouting
// if no size is set the parent or max size is used
int containerW = getWidth();
int containerH = getHeight();
if (getParent()) {
// width
if (containerW - diffW < 1) {
containerW = getParent()->getChildrenArea().width;
} else {
containerW = std::min(containerW, getParent()->getChildrenArea().width);
}
containerW = std::max(containerW, getMinSize().getWidth());
containerW = std::min(containerW, getMaxSize().getWidth()) - diffW;;
// height
if (containerH - diffH < 1) {
containerH = getParent()->getChildrenArea().height;
} else {
containerH = std::min(containerH, getParent()->getChildrenArea().height);
}
containerH = std::max(containerH, getMinSize().getHeight());
containerH = std::min(containerH, getMaxSize().getHeight()) - diffH;
} else {
containerW -= diffW;
containerH -= diffH;
if (containerW < 1) {
containerW = getMaxSize().getWidth() - diffW;
}
if (containerH < 1) {
containerH = getMaxSize().getHeight() - diffH;
}
}
// calculates max layout size per column or row
std::vector<int> layoutMax;
int tmpSize = 0;
int x = 0;
int y = 0;
int visibleChilds = 0;
std::list<Widget*>::const_iterator currChild(mChildren.begin());
std::list<Widget*>::const_iterator endChildren(mChildren.end());
for(; currChild != endChildren; ++currChild) {
Widget* child = *currChild;
if (!child->isVisible()) {
continue;
}
++visibleChilds;
const Rectangle& rec = child->getDimension();
if (mLayout == Vertical) {
// new column
// negative bottom margin have no effect here
if (y + child->getMarginTop() + rec.height + (child->getMarginBottom() > 0 ? child->getMarginBottom() : 0) > containerH) {
y = 0;
layoutMax.push_back(tmpSize);
tmpSize = 0;
continue;
}
y += rec.height + child->getMarginTop() + child->getMarginBottom() + getVerticalSpacing();
tmpSize = std::max(tmpSize, rec.width + child->getMarginLeft() + (child->getMarginRight() > 0 ? child->getMarginRight() : 0));
} else {
// new row
// negative right margin have no effect here
if (x + rec.width + child->getMarginLeft() + (child->getMarginRight() > 0 ? child->getMarginRight() : 0) > containerW) {
x = 0;
layoutMax.push_back(tmpSize);
tmpSize = 0;
continue;
}
x += rec.width + child->getMarginLeft() + child->getMarginRight() + getHorizontalSpacing();
tmpSize = std::max(tmpSize, rec.height + child->getMarginTop() + (child->getMarginBottom() > 0 ? child->getMarginBottom() : 0));
}
}
if (tmpSize != 0) {
layoutMax.push_back(tmpSize);
}
// places all widgets
x = 0;
y = 0;
int totalW = 0;
int totalH = 0;
unsigned int layout = 0;
if (mLayout == Vertical && visibleChilds > 0) {
currChild = mChildren.begin();
endChildren = mChildren.end();
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
int columnW = layoutMax[layout];
int layoutW = (*currChild)->getWidth() + (*currChild)->getMarginLeft() + ((*currChild)->getMarginRight() > 0 ? (*currChild)->getMarginRight() : 0);
Rectangle dim((*currChild)->getMarginLeft(), (*currChild)->getMarginTop(), layoutW, (*currChild)->getHeight());
// new column
// negative bottom margin have no effect here
if (y + (*currChild)->getMarginTop() + dim.height + ((*currChild)->getMarginBottom() > 0 ? (*currChild)->getMarginBottom() : 0) > containerH) {
x += columnW + getHorizontalSpacing();
y = 0;
++layout;
columnW = layoutMax[layout];
}
dim.y += y;
switch (getAlignment()) {
case Left:
dim.x += x;
break;
case Center:
dim.x += x + (columnW - layoutW) / 2;
break;
case Right:
dim.x += x + (columnW - layoutW);
break;
default:
throw FCN_EXCEPTION("Unknown alignment.");
}
(*currChild)->setDimension(dim);
y += (*currChild)->getHeight() + (*currChild)->getMarginTop() + (*currChild)->getMarginBottom() + getVerticalSpacing();
totalW = std::max(totalW, dim.x + dim.width);
totalH = std::max(totalH, y);
}
// remove last spacing
totalH -= getVerticalSpacing();
} else if (mLayout == Horizontal && visibleChilds > 0) {
currChild = mChildren.begin();
endChildren = mChildren.end();
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
int rowH = layoutMax[layout];
int layoutH = (*currChild)->getHeight() + (*currChild)->getMarginTop() + ((*currChild)->getMarginBottom() > 0 ? (*currChild)->getMarginBottom() : 0);
Rectangle dim((*currChild)->getMarginLeft(), (*currChild)->getMarginTop(), (*currChild)->getWidth(), layoutH);
// new row
// negative right margin have no effect here
if (x + (*currChild)->getMarginLeft() + dim.width + ((*currChild)->getMarginRight() > 0 ? (*currChild)->getMarginRight() : 0) > containerW) {
x = 0;
y += rowH + getVerticalSpacing();
++layout;
rowH = layoutMax[layout];
}
dim.x += x;
switch (getAlignment()) {
case Top:
dim.y += y;
break;
case Center:
dim.y += y + (rowH - layoutH) / 2;
break;
case Bottom:
dim.y += y + (rowH - layoutH);
break;
default:
throw FCN_EXCEPTION("Unknown alignment.");
}
(*currChild)->setDimension(dim);
x += (*currChild)->getWidth() + (*currChild)->getMarginLeft() + (*currChild)->getMarginRight() + getHorizontalSpacing();
totalW = std::max(totalW, x);
totalH = std::max(totalH, dim.y + dim.width);
}
// remove last spacing
totalW -= getHorizontalSpacing();
}
// resize container
totalW += diffW;
totalH += diffH;
setSize(totalW, totalH);
}
void FlowContainer::setLayout(Container::LayoutPolicy policy) {
if (policy == Circular) {
throw FCN_EXCEPTION("Circular layout is not implemented for the FlowContainer.");
} else {
Container::setLayout(policy);
}
}
void FlowContainer::resizeToContent(bool recursiv) {
if (recursiv) {
std::list<Widget*>::const_iterator currChild(mChildren.begin());
std::list<Widget*>::const_iterator endChildren(mChildren.end());
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
(*currChild)->resizeToContent(recursiv);
}
}
if (mLayout != Absolute) {
adjustContent();
}
}
void FlowContainer::expandContent(bool recursiv) {
if (mLayout != Absolute) {
adjustContent();
}
// not really needed
if (recursiv) {
std::list<Widget*>::const_iterator currChild(mChildren.begin());
std::list<Widget*>::const_iterator endChildren(mChildren.end());
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
(*currChild)->expandContent(recursiv);
}
}
}
}
<commit_msg> * Fixed layouting problems with FlowContainer. The resizeToContent() call sets the size to min size if the widget have a parent.<commit_after>/***************************************************************************
* Copyright (C) 2012 by the fifechan team *
* http://fifechan.github.com/fifechan *
* This file is part of fifechan. *
* *
* fifechan is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
/*
* For comments regarding functions please see the header file.
*/
#include "fifechan/widgets/flowcontainer.hpp"
#include "fifechan/exception.hpp"
namespace fcn {
FlowContainer::FlowContainer():
mAlignment(Center) {
setOpaque(true);
}
FlowContainer::~FlowContainer() {
}
void FlowContainer::setAlignment(FlowContainer::Alignment alignment) {
mAlignment = alignment;
}
FlowContainer::Alignment FlowContainer::getAlignment() const {
return mAlignment;
}
void FlowContainer::adjustContent() {
// diff means border, padding, ...
int diffW = ABS(getDimension().width - getChildrenArea().width);
int diffH = ABS(getDimension().height - getChildrenArea().height);
int containerW = getChildrenArea().width;
int containerH = getChildrenArea().height;
// calculates max layout size per column or row
std::vector<int> layoutMax;
int tmpSize = 0;
int x = 0;
int y = 0;
int visibleChilds = 0;
std::list<Widget*>::const_iterator currChild(mChildren.begin());
std::list<Widget*>::const_iterator endChildren(mChildren.end());
for(; currChild != endChildren; ++currChild) {
Widget* child = *currChild;
if (!child->isVisible()) {
continue;
}
++visibleChilds;
const Rectangle& rec = child->getDimension();
if (mLayout == Vertical) {
// new column
// negative bottom margin have no effect here
if (y + child->getMarginTop() + rec.height + (child->getMarginBottom() > 0 ? child->getMarginBottom() : 0) > containerH) {
y = 0;
layoutMax.push_back(tmpSize);
tmpSize = 0;
}
y += rec.height + child->getMarginTop() + child->getMarginBottom() + getVerticalSpacing();
tmpSize = std::max(tmpSize, rec.width + child->getMarginLeft() + (child->getMarginRight() > 0 ? child->getMarginRight() : 0));
} else {
// new row
// negative right margin have no effect here
if (x + rec.width + child->getMarginLeft() + (child->getMarginRight() > 0 ? child->getMarginRight() : 0) > containerW) {
x = 0;
layoutMax.push_back(tmpSize);
tmpSize = 0;
}
x += rec.width + child->getMarginLeft() + child->getMarginRight() + getHorizontalSpacing();
tmpSize = std::max(tmpSize, rec.height + child->getMarginTop() + (child->getMarginBottom() > 0 ? child->getMarginBottom() : 0));
}
}
if (tmpSize != 0) {
layoutMax.push_back(tmpSize);
}
// places all widgets
x = 0;
y = 0;
int totalW = 0;
int totalH = 0;
unsigned int layout = 0;
if (mLayout == Vertical && visibleChilds > 0) {
currChild = mChildren.begin();
endChildren = mChildren.end();
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
int columnW = layoutMax[layout];
int layoutW = (*currChild)->getWidth() + (*currChild)->getMarginLeft() + ((*currChild)->getMarginRight() > 0 ? (*currChild)->getMarginRight() : 0);
Rectangle dim((*currChild)->getMarginLeft(), (*currChild)->getMarginTop(), layoutW, (*currChild)->getHeight());
// new column
// negative bottom margin have no effect here
if (y + (*currChild)->getMarginTop() + dim.height + ((*currChild)->getMarginBottom() > 0 ? (*currChild)->getMarginBottom() : 0) > containerH) {
x += columnW + getHorizontalSpacing();
y = 0;
++layout;
columnW = layoutMax[layout];
}
dim.y += y;
switch (getAlignment()) {
case Left:
dim.x += x;
break;
case Center:
dim.x += x + (columnW - layoutW) / 2;
break;
case Right:
dim.x += x + (columnW - layoutW);
break;
default:
throw FCN_EXCEPTION("Unknown alignment.");
}
(*currChild)->setDimension(dim);
y += (*currChild)->getHeight() + (*currChild)->getMarginTop() + (*currChild)->getMarginBottom() + getVerticalSpacing();
totalW = std::max(totalW, dim.x + dim.width);
totalH = std::max(totalH, y);
}
// remove last spacing
totalH -= getVerticalSpacing();
// always expand height but width only if horizontal expand is enabled
totalH = std::max(totalH, containerH);
if (isHorizontalExpand()) {
totalW = std::max(totalW, containerW);
}
} else if (mLayout == Horizontal && visibleChilds > 0) {
currChild = mChildren.begin();
endChildren = mChildren.end();
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
int rowH = layoutMax[layout];
int layoutH = (*currChild)->getHeight() + (*currChild)->getMarginTop() + ((*currChild)->getMarginBottom() > 0 ? (*currChild)->getMarginBottom() : 0);
Rectangle dim((*currChild)->getMarginLeft(), (*currChild)->getMarginTop(), (*currChild)->getWidth(), layoutH);
// new row
// negative right margin have no effect here
if (x + (*currChild)->getMarginLeft() + dim.width + ((*currChild)->getMarginRight() > 0 ? (*currChild)->getMarginRight() : 0) > containerW) {
x = 0;
y += rowH + getVerticalSpacing();
++layout;
rowH = layoutMax[layout];
}
dim.x += x;
switch (getAlignment()) {
case Top:
dim.y += y;
break;
case Center:
dim.y += y + (rowH - layoutH) / 2;
break;
case Bottom:
dim.y += y + (rowH - layoutH);
break;
default:
throw FCN_EXCEPTION("Unknown alignment.");
}
(*currChild)->setDimension(dim);
x += (*currChild)->getWidth() + (*currChild)->getMarginLeft() + (*currChild)->getMarginRight() + getHorizontalSpacing();
totalW = std::max(totalW, x);
totalH = std::max(totalH, dim.y + dim.height);
}
// remove last spacing
totalW -= getHorizontalSpacing();
// always expand width but height only if vertical expand is enabled
totalW = std::max(totalW, containerW);
if (isVerticalExpand()) {
totalH = std::max(totalH, containerH);
}
}
// resize container
totalW += diffW;
totalH += diffH;
setSize(totalW, totalH);
}
void FlowContainer::setLayout(Container::LayoutPolicy policy) {
if (policy == Circular) {
throw FCN_EXCEPTION("Circular layout is not implemented for the FlowContainer.");
} else {
Container::setLayout(policy);
}
}
void FlowContainer::resizeToContent(bool recursiv) {
if (recursiv) {
std::list<Widget*>::const_iterator currChild(mChildren.begin());
std::list<Widget*>::const_iterator endChildren(mChildren.end());
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
(*currChild)->resizeToContent(recursiv);
}
}
if (mLayout != Absolute) {
if (getParent()) {
setSize(getMinSize().getWidth(), getMinSize().getHeight());
}
}
}
void FlowContainer::expandContent(bool recursiv) {
if (mLayout != Absolute) {
adjustContent();
}
// not really needed
if (recursiv) {
std::list<Widget*>::const_iterator currChild(mChildren.begin());
std::list<Widget*>::const_iterator endChildren(mChildren.end());
for(; currChild != endChildren; ++currChild) {
if (!(*currChild)->isVisible()) {
continue;
}
(*currChild)->expandContent(recursiv);
}
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include "cvrp.h"
namespace VrpSolver {
void Cvrp::read_vrp(const std::string &infile) {
VrpSolver::read_vrp(problem_, infile);
// 車体数の設定(TSPLIB formatでは明示的に示されていないので
// ファイル名から読み取る
size_t i = infile.rfind('k');
size_t j = infile.rfind('.');
std::istringstream iss(infile.substr(i+1, j));
iss >> num_vehicles_;
if (!iss)
throw std::runtime_error("error: can not read number of vehicles");
}
std::string Cvrp::name() const {
return problem_->name_;
}
unsigned int Cvrp::dimension() const {
return problem_->dimension_;
}
unsigned int Cvrp::capacity() const {
return problem_->capacity_;
}
unsigned int Cvrp::demand(unsigned int node_id) const {
if ((1 > node_id) || (node_id > problem_->dimension_))
throw std::out_of_range("error: in Cvrp::demand");
return problem_->customers_[node_id].demand();
}
unsigned int Cvrp::num_vehicles() const {
return num_vehicles_;
}
unsigned int Cvrp::distance(unsigned int from, unsigned int to) const {
if ((1 > from) || (from > problem_->dimension_) ||
(1 > to) || (to > problem_->dimension_))
throw std::out_of_range("error: in Cvrp::distance");
const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
((from-2)*(from-1)/2+(to-1));
return problem_->distances_[index];
}
const DistanceList &Cvrp::distance_list() const {
return problem_->distances_;
}
const CustomerList &Cvrp::customer_list() const {
return problem_->customers_;
}
unsigned int distance(const DistanceList& dlist,
const Customer& c1, const Customer& c2) {
const int from = c1.id();
const int to = c2.id();
const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
((from-2)*(from-1)/2+(to-1));
return dlist[index];
}
// 文字列strからtrim_char文字列に含まれている文字を削除
void trim(std::string& str, const std::string& trim_char) {
size_t pos;
while ((pos = str.find_first_of(trim_char)) != std::string::npos)
str.erase(pos, 1);
}
// セミコロン以後の文字列(空白の直前まで)を読み取る
std::string get_parameter(std::ifstream& ifs) {
std::string param;
ifs >> param;
while (param == ":") ifs >> param; // ":"は読み飛ばす
return param;
}
typedef std::string keyword;
enum TsplibKeyword {
// The specification part
NAME, TYPE, COMMENT, DIMENSION, CAPACITY,
EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,
NODE_COORD_TYPE, DISPLAY_DATA_TYPE, END_OF_FILE,
// The data part
NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,
EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,
};
std::map<keyword, TsplibKeyword> keyword_map = {
// The specification part
{ "NAME", NAME },
{ "TYPE", TYPE },
{ "COMMENT", COMMENT },
{ "DIMENSION", DIMENSION },
{ "CAPACITY", CAPACITY },
{ "EDGE_WEIGHT_TYPE", EDGE_WEIGHT_TYPE },
{ "EDGE_WEIGHT_FORMAT", EDGE_WEIGHT_FORMAT },
{ "EDGE_DATA_FORMAT", EDGE_DATA_FORMAT },
{ "NODE_COORD_TYPE", NODE_COORD_TYPE },
{ "DISPLAY_DATA_TYPE", DISPLAY_DATA_TYPE },
{ "EOF", END_OF_FILE },
// The data part
{ "NODE_COORD_SECTION", NODE_COORD_SECTION },
{ "DEPOT_SECTION", DEPOT_SECTION },
{ "DEMAND_SECTION", DEMAND_SECTION },
{ "EDGE_DATA_SECTION", EDGE_DATA_SECTION },
{ "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION }
};
enum EdgeWeightType {
EXPLICIT, EUC_2D
};
std::map<keyword, EdgeWeightType> ew_type_map = {
{ "EXPLICIT", EXPLICIT },
{ "EUC_2D", EUC_2D }
};
enum EdgeWeightFormat {
LOWER_ROW
};
std::map<keyword, EdgeWeightFormat> ew_format_map = {
{ "LOWER_ROW", LOWER_ROW }
};
// infileから情報を読み取りCvrpクラスをセットアップする
void read_vrp(Problem *problem, const std::string &infile) {
std::ifstream ifs(infile.c_str());
if (!ifs)
throw std::runtime_error("error: can't open file " + infile);
EdgeWeightType edge_weight_type;
EdgeWeightFormat edge_weight_format;
while (ifs) {
keyword tsp_keyword;
ifs >> tsp_keyword;
if (ifs.eof()) break;
trim(tsp_keyword, " :");
switch (keyword_map[tsp_keyword]) {
// The specification part
case NAME :
problem->name_ = get_parameter(ifs);
break;
case TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case COMMENT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DIMENSION :
problem->dimension_ = stoi(get_parameter(ifs));
break;
case CAPACITY :
problem->capacity_ = stoi(get_parameter(ifs));
break;
case EDGE_WEIGHT_TYPE :
edge_weight_type = ew_type_map[get_parameter(ifs)];
break;
case EDGE_WEIGHT_FORMAT :
edge_weight_format = ew_format_map[get_parameter(ifs)];
break;
case EDGE_DATA_FORMAT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case NODE_COORD_TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DISPLAY_DATA_TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case END_OF_FILE :
// do nothing
break;
// The data part
case NODE_COORD_SECTION :
{
int n=0, m, x, y; // m do not use
for (int i=0; i != problem->dimension_; i++) {
ifs >> m >> x >> y;
std::pair<int,int> c(x,y);
problem->coords_.push_back(c);
}
}
break;
case DEPOT_SECTION :
{
problem->depot_ = stoi(get_parameter(ifs));
if (stoi(get_parameter(ifs)) != -1)
throw std::runtime_error("error:"
"can't handle multiple depots");
}
break;
case DEMAND_SECTION :
{
problem->customers_.push_back(Customer(0,0)); // 0番目は使用しない
for (int i=1; i <= problem->dimension_; i++) {
unsigned int node_id, demand;
ifs >> node_id >> demand;
if (node_id != i)
throw std::runtime_error("error:"
"DEMAND_SECTION format may be different");
problem->customers_.push_back(Customer(node_id, demand));
}
}
break;
case EDGE_DATA_SECTION :
throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'");
break;
case EDGE_WEIGHT_SECTION :
{
if (edge_weight_format != LOWER_ROW)
throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW");
for (int i=0; i < problem->dimension_; i++) {
for (int j=0; j < i; j++) {
int distance;
ifs >> distance;
problem->distances_.push_back(distance);
}
}
}
break;
default :
throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'");
break;
}
}
// distancesの設定
if (edge_weight_type != EXPLICIT) {
auto& distances = problem->distances_;
auto& coords = problem->coords_;
for (int i=0; i < problem->dimension_; i++) {
for (int j=0; j < i; j++) {
int dx = coords[j].first - coords[i].first;
int dy = coords[j].second - coords[i].second;
distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));
}
}
}
}
} // namespace VrpSolver
<commit_msg>read_vrpをヘッダーから消したためにプロトタイプ宣言が必要になった<commit_after>#include <iostream>
#include <cmath>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include "cvrp.h"
namespace VrpSolver {
void read_vrp(Problem *, const std::string &infile);
void Cvrp::read_vrp(const std::string &infile) {
VrpSolver::read_vrp(problem_, infile);
// 車体数の設定(TSPLIB formatでは明示的に示されていないので
// ファイル名から読み取る
size_t i = infile.rfind('k');
size_t j = infile.rfind('.');
std::istringstream iss(infile.substr(i+1, j));
iss >> num_vehicles_;
if (!iss)
throw std::runtime_error("error: can not read number of vehicles");
}
std::string Cvrp::name() const {
return problem_->name_;
}
unsigned int Cvrp::dimension() const {
return problem_->dimension_;
}
unsigned int Cvrp::capacity() const {
return problem_->capacity_;
}
unsigned int Cvrp::demand(unsigned int node_id) const {
if ((1 > node_id) || (node_id > problem_->dimension_))
throw std::out_of_range("error: in Cvrp::demand");
return problem_->customers_[node_id].demand();
}
unsigned int Cvrp::num_vehicles() const {
return num_vehicles_;
}
unsigned int Cvrp::distance(unsigned int from, unsigned int to) const {
if ((1 > from) || (from > problem_->dimension_) ||
(1 > to) || (to > problem_->dimension_))
throw std::out_of_range("error: in Cvrp::distance");
const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
((from-2)*(from-1)/2+(to-1));
return problem_->distances_[index];
}
const DistanceList &Cvrp::distance_list() const {
return problem_->distances_;
}
const CustomerList &Cvrp::customer_list() const {
return problem_->customers_;
}
unsigned int distance(const DistanceList& dlist,
const Customer& c1, const Customer& c2) {
const int from = c1.id();
const int to = c2.id();
const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
((from-2)*(from-1)/2+(to-1));
return dlist[index];
}
// 文字列strからtrim_char文字列に含まれている文字を削除
void trim(std::string& str, const std::string& trim_char) {
size_t pos;
while ((pos = str.find_first_of(trim_char)) != std::string::npos)
str.erase(pos, 1);
}
// セミコロン以後の文字列(空白の直前まで)を読み取る
std::string get_parameter(std::ifstream& ifs) {
std::string param;
ifs >> param;
while (param == ":") ifs >> param; // ":"は読み飛ばす
return param;
}
typedef std::string keyword;
enum TsplibKeyword {
// The specification part
NAME, TYPE, COMMENT, DIMENSION, CAPACITY,
EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,
NODE_COORD_TYPE, DISPLAY_DATA_TYPE, END_OF_FILE,
// The data part
NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,
EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,
};
std::map<keyword, TsplibKeyword> keyword_map = {
// The specification part
{ "NAME", NAME },
{ "TYPE", TYPE },
{ "COMMENT", COMMENT },
{ "DIMENSION", DIMENSION },
{ "CAPACITY", CAPACITY },
{ "EDGE_WEIGHT_TYPE", EDGE_WEIGHT_TYPE },
{ "EDGE_WEIGHT_FORMAT", EDGE_WEIGHT_FORMAT },
{ "EDGE_DATA_FORMAT", EDGE_DATA_FORMAT },
{ "NODE_COORD_TYPE", NODE_COORD_TYPE },
{ "DISPLAY_DATA_TYPE", DISPLAY_DATA_TYPE },
{ "EOF", END_OF_FILE },
// The data part
{ "NODE_COORD_SECTION", NODE_COORD_SECTION },
{ "DEPOT_SECTION", DEPOT_SECTION },
{ "DEMAND_SECTION", DEMAND_SECTION },
{ "EDGE_DATA_SECTION", EDGE_DATA_SECTION },
{ "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION }
};
enum EdgeWeightType {
EXPLICIT, EUC_2D
};
std::map<keyword, EdgeWeightType> ew_type_map = {
{ "EXPLICIT", EXPLICIT },
{ "EUC_2D", EUC_2D }
};
enum EdgeWeightFormat {
LOWER_ROW
};
std::map<keyword, EdgeWeightFormat> ew_format_map = {
{ "LOWER_ROW", LOWER_ROW }
};
// infileから情報を読み取りCvrpクラスをセットアップする
void read_vrp(Problem *problem, const std::string &infile) {
std::ifstream ifs(infile.c_str());
if (!ifs)
throw std::runtime_error("error: can't open file " + infile);
EdgeWeightType edge_weight_type;
EdgeWeightFormat edge_weight_format;
while (ifs) {
keyword tsp_keyword;
ifs >> tsp_keyword;
if (ifs.eof()) break;
trim(tsp_keyword, " :");
switch (keyword_map[tsp_keyword]) {
// The specification part
case NAME :
problem->name_ = get_parameter(ifs);
break;
case TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case COMMENT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DIMENSION :
problem->dimension_ = stoi(get_parameter(ifs));
break;
case CAPACITY :
problem->capacity_ = stoi(get_parameter(ifs));
break;
case EDGE_WEIGHT_TYPE :
edge_weight_type = ew_type_map[get_parameter(ifs)];
break;
case EDGE_WEIGHT_FORMAT :
edge_weight_format = ew_format_map[get_parameter(ifs)];
break;
case EDGE_DATA_FORMAT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case NODE_COORD_TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DISPLAY_DATA_TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case END_OF_FILE :
// do nothing
break;
// The data part
case NODE_COORD_SECTION :
{
int n=0, m, x, y; // m do not use
for (int i=0; i != problem->dimension_; i++) {
ifs >> m >> x >> y;
std::pair<int,int> c(x,y);
problem->coords_.push_back(c);
}
}
break;
case DEPOT_SECTION :
{
problem->depot_ = stoi(get_parameter(ifs));
if (stoi(get_parameter(ifs)) != -1)
throw std::runtime_error("error:"
"can't handle multiple depots");
}
break;
case DEMAND_SECTION :
{
problem->customers_.push_back(Customer(0,0)); // 0番目は使用しない
for (int i=1; i <= problem->dimension_; i++) {
unsigned int node_id, demand;
ifs >> node_id >> demand;
if (node_id != i)
throw std::runtime_error("error:"
"DEMAND_SECTION format may be different");
problem->customers_.push_back(Customer(node_id, demand));
}
}
break;
case EDGE_DATA_SECTION :
throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'");
break;
case EDGE_WEIGHT_SECTION :
{
if (edge_weight_format != LOWER_ROW)
throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW");
for (int i=0; i < problem->dimension_; i++) {
for (int j=0; j < i; j++) {
int distance;
ifs >> distance;
problem->distances_.push_back(distance);
}
}
}
break;
default :
throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'");
break;
}
}
// distancesの設定
if (edge_weight_type != EXPLICIT) {
auto& distances = problem->distances_;
auto& coords = problem->coords_;
for (int i=0; i < problem->dimension_; i++) {
for (int j=0; j < i; j++) {
int dx = coords[j].first - coords[i].first;
int dy = coords[j].second - coords[i].second;
distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));
}
}
}
}
} // namespace VrpSolver
<|endoftext|> |
<commit_before>#include <accumulate.hpp>
#include "helpers.hpp"
#include <vector>
#include <iterator>
#include <string>
#include "catch.hpp"
using iter::accumulate;
using itertest::BasicIterable;
using Vec = const std::vector<int>;
TEST_CASE("Simple sum", "[accumulate]") {
Vec ns{1,2,3,4,5};
auto a = accumulate(ns);
Vec v(std::begin(a), std::end(a));
Vec vc{1,3,6,10,15};
REQUIRE( v == vc );
}
TEST_CASE("accumulate: With subtraction lambda", "[accumulate]") {
Vec ns{5,4,3,2,1};
auto a = accumulate(ns, [](int a, int b){return a - b; });
Vec v(std::begin(a), std::end(a));
Vec vc{5, 1, -2, -4, -5};
REQUIRE( v == vc );
}
TEST_CASE("accumulate: with initializer_list works", "[accumulate]") {
auto a = accumulate({1, 2, 3});
Vec v(std::begin(a), std::end(a));
Vec vc{1, 3, 6};
REQUIRE( v == vc );
}
TEST_CASE("accumulate: binds reference when it should", "[accumulate]") {
BasicIterable<int> bi{1, 2};
accumulate(bi);
REQUIRE_FALSE( bi.was_moved_from() );
}
TEST_CASE("accumulate: moves rvalues when it should", "[accumulate]") {
BasicIterable<int> bi{1, 2};
accumulate(std::move(bi));
REQUIRE( bi.was_moved_from() );
}
TEST_CASE("accumulate: operator==", "[accumulate]") {
Vec v;
auto a = accumulate(v);
REQUIRE( std::begin(a) == std::end(a) );
}
TEST_CASE("accumulate: postfix ++", "[accumulate]") {
Vec ns{2,3};
auto a = accumulate(ns);
auto it = std::begin(a);
it++;
REQUIRE( *it == 5 );
}
TEST_CASE("accumulate: operator->", "[accumulate]") {
Vec ns{7, 3};
auto a = accumulate(ns);
auto it = std::begin(a);
const int *p = it.operator->();
REQUIRE( *p == 7 );
}
TEST_CASE("accumulate: iterator meets requirements", "[accumulate]") {
Vec ns{};
auto a = accumulate(ns);
REQUIRE( itertest::IsIterator<decltype(std::begin(a))>::value );
}
<commit_msg>tests accumulate with lambda iters are assignable<commit_after>#include <accumulate.hpp>
#include "helpers.hpp"
#include <vector>
#include <iterator>
#include <string>
#include "catch.hpp"
using iter::accumulate;
using itertest::BasicIterable;
using Vec = const std::vector<int>;
TEST_CASE("Simple sum", "[accumulate]") {
Vec ns{1,2,3,4,5};
auto a = accumulate(ns);
Vec v(std::begin(a), std::end(a));
Vec vc{1,3,6,10,15};
REQUIRE( v == vc );
}
TEST_CASE("accumulate: With subtraction lambda", "[accumulate]") {
Vec ns{5,4,3,2,1};
auto a = accumulate(ns, [](int a, int b){return a - b; });
Vec v(std::begin(a), std::end(a));
Vec vc{5, 1, -2, -4, -5};
REQUIRE( v == vc );
}
TEST_CASE("accumulate: with initializer_list works", "[accumulate]") {
auto a = accumulate({1, 2, 3});
Vec v(std::begin(a), std::end(a));
Vec vc{1, 3, 6};
REQUIRE( v == vc );
}
struct Integer {
const int value;
constexpr Integer(int i) : value{i} { }
constexpr Integer operator+(Integer other) const noexcept {
return {this->value + other.value};
}
};
TEST_CASE("accumulate: intermidate type need not be default constructible",
"[accumulate]") {
std::vector<Integer> v = {{2}, {3}, {10}};
auto a = accumulate(v, std::plus<Integer>{});
auto it = std::begin(a);
}
TEST_CASE("accumulate: binds reference when it should", "[accumulate]") {
BasicIterable<int> bi{1, 2};
accumulate(bi);
REQUIRE_FALSE( bi.was_moved_from() );
}
TEST_CASE("accumulate: moves rvalues when it should", "[accumulate]") {
BasicIterable<int> bi{1, 2};
accumulate(std::move(bi));
REQUIRE( bi.was_moved_from() );
}
TEST_CASE("accumulate: operator==", "[accumulate]") {
Vec v;
auto a = accumulate(v);
REQUIRE( std::begin(a) == std::end(a) );
}
TEST_CASE("accumulate: postfix ++", "[accumulate]") {
Vec ns{2,3};
auto a = accumulate(ns);
auto it = std::begin(a);
it++;
REQUIRE( *it == 5 );
}
TEST_CASE("accumulate: operator->", "[accumulate]") {
Vec ns{7, 3};
auto a = accumulate(ns);
auto it = std::begin(a);
const int *p = it.operator->();
REQUIRE( *p == 7 );
}
TEST_CASE("accumulate: iterator meets requirements", "[accumulate]") {
Vec ns{};
auto a = accumulate(ns, [](int a, int b) { return a + b; });
auto it = std::begin(a);
it = std::begin(a);
REQUIRE( itertest::IsIterator<decltype(std::begin(a))>::value );
}
<|endoftext|> |
<commit_before>#include "joblistwidget.h"
WARNINGS_DISABLE
#include <QAbstractItemView>
#include <QKeyEvent>
#include <QList>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QRegExp>
#include <Qt>
WARNINGS_ENABLE
#include "messages/archiverestoreoptions.h"
#include "debug.h"
#include "joblistwidgetitem.h"
#include "persistentmodel/job.h"
#include "restoredialog.h"
JobListWidget::JobListWidget(QWidget *parent)
: QListWidget(parent), _filter(new QRegExp)
{
_filter->setCaseSensitivity(Qt::CaseInsensitive);
_filter->setPatternSyntax(QRegExp::Wildcard);
connect(this, &QListWidget::itemActivated, [this](QListWidgetItem *item) {
emit displayJobDetails(static_cast<JobListWidgetItem *>(item)->job());
});
}
JobListWidget::~JobListWidget()
{
clear();
delete _filter;
}
void JobListWidget::backupSelectedItems()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
QMessageBox::StandardButton confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Initiate backup for the %1 selected job(s)?")
.arg(selectedItems().count()));
if(confirm != QMessageBox::Yes)
return;
for(QListWidgetItem *item : selectedItems())
{
if(item->isSelected())
{
JobPtr job = static_cast<JobListWidgetItem *>(item)->job();
emit backupJob(job);
}
}
}
void JobListWidget::selectJob(JobPtr job)
{
// Bail (if applicable).
if(!job)
{
DEBUG << "Null JobPtr passed.";
return;
}
for(int i = 0; i < count(); ++i)
{
JobListWidgetItem *jobItem = static_cast<JobListWidgetItem *>(item(i));
if(jobItem && (jobItem->job()->objectKey() == job->objectKey()))
{
clearSelection();
setCurrentItem(jobItem);
scrollToItem(currentItem(), QAbstractItemView::EnsureVisible);
break;
}
}
}
void JobListWidget::inspectJobByRef(const QString &jobRef)
{
// Bail (if applicable).
if(jobRef.isEmpty())
return;
for(int i = 0; i < count(); ++i)
{
JobListWidgetItem *jobItem = static_cast<JobListWidgetItem *>(item(i));
if(jobItem && (jobItem->job()->objectKey() == jobRef))
emit displayJobDetails(jobItem->job());
}
}
void JobListWidget::backupAllJobs()
{
for(int i = 0; i < count(); ++i)
{
JobPtr job = static_cast<JobListWidgetItem *>(item(i))->job();
emit backupJob(job);
}
}
void JobListWidget::backupItem()
{
// Bail (if applicable).
if(!sender())
return;
JobPtr job = qobject_cast<JobListWidgetItem *>(sender())->job();
if(job)
emit backupJob(job);
}
void JobListWidget::inspectItem()
{
// Bail (if applicable).
if(!sender())
return;
emit displayJobDetails(qobject_cast<JobListWidgetItem *>(sender())->job());
}
void JobListWidget::restoreItem()
{
// Bail (if applicable).
if(!sender())
return;
JobPtr job = qobject_cast<JobListWidgetItem *>(sender())->job();
// Bail (if applicable).
if(job->archives().isEmpty())
return;
ArchivePtr archive = job->archives().first();
RestoreDialog *restoreDialog = new RestoreDialog(this, archive);
connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] {
emit restoreArchive(restoreDialog->archive(),
restoreDialog->getOptions());
});
restoreDialog->show();
}
void JobListWidget::deleteItem()
{
execDeleteJob(qobject_cast<JobListWidgetItem *>(sender()));
}
void JobListWidget::execDeleteJob(JobListWidgetItem *jobItem)
{
// Bail (if applicable).
if(!jobItem)
{
DEBUG << "Null JobListWidgetItem passed.";
return;
}
JobPtr job = jobItem->job();
QMessageBox::StandardButton confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Are you sure you want to delete job \"%1\" "
"(this cannot be undone)?")
.arg(job->name()));
if(confirm != QMessageBox::Yes)
return;
bool purgeArchives = false;
if(!job->archives().isEmpty())
{
QMessageBox::StandardButton delArchives =
QMessageBox::question(this, tr("Confirm action"),
tr("Also delete %1 archives "
"belonging to this job "
"(this cannot be undone)?")
.arg(job->archives().count()));
if(delArchives == QMessageBox::Yes)
purgeArchives = true;
}
emit deleteJob(job, purgeArchives);
delete jobItem;
emit countChanged(count(), visibleItemsCount());
}
int JobListWidget::visibleItemsCount()
{
int count = 0;
for(QListWidgetItem *item : findItems("*", Qt::MatchWildcard))
{
if(item && !item->isHidden())
count++;
}
return count;
}
void JobListWidget::setJobs(const QMap<QString, JobPtr> &jobs)
{
setUpdatesEnabled(false);
clear();
for(const JobPtr &job : jobs)
{
addJob(job);
}
setUpdatesEnabled(true);
}
void JobListWidget::addJob(JobPtr job)
{
// Bail (if applicable).
if(!job)
{
DEBUG << "Null JobPtr passed.";
return;
}
JobListWidgetItem *item = new JobListWidgetItem(job);
connect(item, &JobListWidgetItem::requestBackup, this,
&JobListWidget::backupItem);
connect(item, &JobListWidgetItem::requestInspect, this,
&JobListWidget::inspectItem);
connect(item, &JobListWidgetItem::requestRestore, this,
&JobListWidget::restoreItem);
connect(item, &JobListWidgetItem::requestDelete, this,
&JobListWidget::deleteItem);
insertItem(count(), item);
setItemWidget(item, item->widget());
item->setHidden(!job->name().contains(*_filter));
emit countChanged(count(), visibleItemsCount());
}
void JobListWidget::inspectSelectedItem()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
emit displayJobDetails(
static_cast<JobListWidgetItem *>(selectedItems().first())->job());
}
void JobListWidget::restoreSelectedItem()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
JobPtr job =
static_cast<JobListWidgetItem *>(selectedItems().first())->job();
// Bail (if applicable).
if(job->archives().isEmpty())
return;
ArchivePtr archive = job->archives().first();
RestoreDialog *restoreDialog = new RestoreDialog(this, archive);
connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] {
emit restoreArchive(restoreDialog->archive(),
restoreDialog->getOptions());
});
restoreDialog->show();
}
void JobListWidget::deleteSelectedItem()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
execDeleteJob(static_cast<JobListWidgetItem *>(selectedItems().first()));
}
void JobListWidget::setFilter(const QString ®ex)
{
setUpdatesEnabled(false);
clearSelection();
_filter->setPattern(regex);
for(int i = 0; i < count(); ++i)
{
JobListWidgetItem *jobItem = static_cast<JobListWidgetItem *>(item(i));
if(jobItem)
{
if(jobItem->job()->name().contains(*_filter))
jobItem->setHidden(false);
else
jobItem->setHidden(true);
}
}
setUpdatesEnabled(true);
emit countChanged(count(), visibleItemsCount());
}
void JobListWidget::keyPressEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Delete:
deleteSelectedItem();
break;
case Qt::Key_Escape:
if(!selectedItems().isEmpty())
clearSelection();
else
QListWidget::keyPressEvent(event);
break;
default:
QListWidget::keyPressEvent(event);
}
}
<commit_msg>JobListWidget: comments<commit_after>#include "joblistwidget.h"
WARNINGS_DISABLE
#include <QAbstractItemView>
#include <QKeyEvent>
#include <QList>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QRegExp>
#include <Qt>
WARNINGS_ENABLE
#include "messages/archiverestoreoptions.h"
#include "debug.h"
#include "joblistwidgetitem.h"
#include "persistentmodel/job.h"
#include "restoredialog.h"
JobListWidget::JobListWidget(QWidget *parent)
: QListWidget(parent), _filter(new QRegExp)
{
// Set up filtering job names.
_filter->setCaseSensitivity(Qt::CaseInsensitive);
_filter->setPatternSyntax(QRegExp::Wildcard);
// Connection for showing info about a Job.
connect(this, &QListWidget::itemActivated, [this](QListWidgetItem *item) {
emit displayJobDetails(static_cast<JobListWidgetItem *>(item)->job());
});
}
JobListWidget::~JobListWidget()
{
clear();
delete _filter;
}
void JobListWidget::backupSelectedItems()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
// Confirm that the user wants to create new archive(s).
QMessageBox::StandardButton confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Initiate backup for the %1 selected job(s)?")
.arg(selectedItems().count()));
if(confirm != QMessageBox::Yes)
return;
// Create a new archive for each selected Job.
for(QListWidgetItem *item : selectedItems())
{
if(item->isSelected())
{
JobPtr job = static_cast<JobListWidgetItem *>(item)->job();
emit backupJob(job);
}
}
}
void JobListWidget::selectJob(JobPtr job)
{
// Bail (if applicable).
if(!job)
{
DEBUG << "Null JobPtr passed.";
return;
}
// Find the item representing the Job, and select it.
for(int i = 0; i < count(); ++i)
{
JobListWidgetItem *jobItem = static_cast<JobListWidgetItem *>(item(i));
if(jobItem && (jobItem->job()->objectKey() == job->objectKey()))
{
clearSelection();
setCurrentItem(jobItem);
scrollToItem(currentItem(), QAbstractItemView::EnsureVisible);
break;
}
}
}
void JobListWidget::inspectJobByRef(const QString &jobRef)
{
// Bail (if applicable).
if(jobRef.isEmpty())
return;
// Find the item representing the Job, and display its details.
for(int i = 0; i < count(); ++i)
{
JobListWidgetItem *jobItem = static_cast<JobListWidgetItem *>(item(i));
if(jobItem && (jobItem->job()->objectKey() == jobRef))
emit displayJobDetails(jobItem->job());
}
}
void JobListWidget::backupAllJobs()
{
// Start a new archive for all jobs.
for(int i = 0; i < count(); ++i)
{
JobPtr job = static_cast<JobListWidgetItem *>(item(i))->job();
emit backupJob(job);
}
}
void JobListWidget::backupItem()
{
// Bail (if applicable).
if(!sender())
return;
// Start a new archive for this job.
JobPtr job = qobject_cast<JobListWidgetItem *>(sender())->job();
if(job)
emit backupJob(job);
}
void JobListWidget::inspectItem()
{
// Bail (if applicable).
if(!sender())
return;
// Display details about the job.
emit displayJobDetails(qobject_cast<JobListWidgetItem *>(sender())->job());
}
void JobListWidget::restoreItem()
{
// Bail (if applicable).
if(!sender())
return;
// Get the Job.
JobPtr job = qobject_cast<JobListWidgetItem *>(sender())->job();
// Bail (if applicable).
if(job->archives().isEmpty())
return;
// Get the latest archive belonging to the Job.
ArchivePtr archive = job->archives().first();
// Launch the RestoreDialog.
RestoreDialog *restoreDialog = new RestoreDialog(this, archive);
connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] {
emit restoreArchive(restoreDialog->archive(),
restoreDialog->getOptions());
});
restoreDialog->show();
}
void JobListWidget::deleteItem()
{
execDeleteJob(qobject_cast<JobListWidgetItem *>(sender()));
}
void JobListWidget::execDeleteJob(JobListWidgetItem *jobItem)
{
// Bail (if applicable).
if(!jobItem)
{
DEBUG << "Null JobListWidgetItem passed.";
return;
}
// Get the Job.
JobPtr job = jobItem->job();
// Confirm that the user wants to delete the Job.
QMessageBox::StandardButton confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Are you sure you want to delete job \"%1\" "
"(this cannot be undone)?")
.arg(job->name()));
if(confirm != QMessageBox::Yes)
return;
// Confirm if the user wants to remove archives as well.
bool purgeArchives = false;
if(!job->archives().isEmpty())
{
QMessageBox::StandardButton delArchives =
QMessageBox::question(this, tr("Confirm action"),
tr("Also delete %1 archives "
"belonging to this job "
"(this cannot be undone)?")
.arg(job->archives().count()));
if(delArchives == QMessageBox::Yes)
purgeArchives = true;
}
// Begin deleting the job (and possibly archives as well).
emit deleteJob(job, purgeArchives);
delete jobItem;
// Notify about the number of visible items.
emit countChanged(count(), visibleItemsCount());
}
int JobListWidget::visibleItemsCount()
{
int count = 0;
for(QListWidgetItem *item : findItems("*", Qt::MatchWildcard))
{
if(item && !item->isHidden())
count++;
}
return count;
}
void JobListWidget::setJobs(const QMap<QString, JobPtr> &jobs)
{
setUpdatesEnabled(false);
clear();
for(const JobPtr &job : jobs)
{
addJob(job);
}
setUpdatesEnabled(true);
}
void JobListWidget::addJob(JobPtr job)
{
// Bail (if applicable).
if(!job)
{
DEBUG << "Null JobPtr passed.";
return;
}
// Create new item.
JobListWidgetItem *item = new JobListWidgetItem(job);
connect(item, &JobListWidgetItem::requestBackup, this,
&JobListWidget::backupItem);
connect(item, &JobListWidgetItem::requestInspect, this,
&JobListWidget::inspectItem);
connect(item, &JobListWidgetItem::requestRestore, this,
&JobListWidget::restoreItem);
connect(item, &JobListWidgetItem::requestDelete, this,
&JobListWidget::deleteItem);
// Add it to the end of the list.
insertItem(count(), item);
setItemWidget(item, item->widget());
// Check it against the name filter.
item->setHidden(!job->name().contains(*_filter));
// Notify about the number of visible items.
emit countChanged(count(), visibleItemsCount());
}
void JobListWidget::inspectSelectedItem()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
// Display details about the first of the selected items.
emit displayJobDetails(
static_cast<JobListWidgetItem *>(selectedItems().first())->job());
}
void JobListWidget::restoreSelectedItem()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
// Get the first Job amongst the selected items.
JobPtr job =
static_cast<JobListWidgetItem *>(selectedItems().first())->job();
// Bail (if applicable).
if(job->archives().isEmpty())
return;
// Get the latest archive belonging to the Job.
ArchivePtr archive = job->archives().first();
// Launch the RestoreDialog.
RestoreDialog *restoreDialog = new RestoreDialog(this, archive);
connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] {
emit restoreArchive(restoreDialog->archive(),
restoreDialog->getOptions());
});
restoreDialog->show();
}
void JobListWidget::deleteSelectedItem()
{
// Bail (if applicable).
if(selectedItems().isEmpty())
return;
// Delete the first of the selected items.
execDeleteJob(static_cast<JobListWidgetItem *>(selectedItems().first()));
}
void JobListWidget::setFilter(const QString ®ex)
{
setUpdatesEnabled(false);
// Set up filter.
clearSelection();
_filter->setPattern(regex);
// Check jobs against filter.
for(int i = 0; i < count(); ++i)
{
JobListWidgetItem *jobItem = static_cast<JobListWidgetItem *>(item(i));
if(jobItem)
{
if(jobItem->job()->name().contains(*_filter))
jobItem->setHidden(false);
else
jobItem->setHidden(true);
}
}
setUpdatesEnabled(true);
// Notify about the number of visible items.
emit countChanged(count(), visibleItemsCount());
}
void JobListWidget::keyPressEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Delete:
deleteSelectedItem();
break;
case Qt::Key_Escape:
if(!selectedItems().isEmpty())
clearSelection();
else
QListWidget::keyPressEvent(event);
break;
default:
QListWidget::keyPressEvent(event);
}
}
<|endoftext|> |
<commit_before>#include "pong/state.hpp"
#include <Box2D/Box2D.h>
#include "pong/game.hpp"
#include "pong/defs.hpp"
namespace pong {
sf::RectangleShape createRectangleShape(float width, float height) {
sf::RectangleShape shape;
shape.setOrigin(width / 2, height / 2);
shape.setSize(sf::Vector2f(width, height));
shape.setFillColor(sf::Color::White);
return shape;
}
void syncBodyToTransformable(b2Body* body, sf::Transformable& transformable) {
b2Vec2 position = body->GetPosition();
float angle = body->GetAngle();
transformable.setPosition(position.x * PIXELS_PER_METER,
position.y * PIXELS_PER_METER);
transformable.setRotation(angle);
}
void DefaultState::enter(Game* game) {
game_ = game;
}
void DefaultState::handleInput(const sf::Event& event) {
if (event.type == sf::Event::Closed) {
game_->exit();
}
}
void GameState::enter(Game* game) {
DefaultState::enter(game);
create();
}
void GameState::create() {
setupGameWorld();
setupInputHandlers();
}
void GameState::setupGameWorld() {
gameWorld_.create();
gameWorld_.setScoreListener(this);
gameWorld_.start();
#ifndef NDEBUG
setupDebugDraw();
#endif /* ifndef NDEBUG */
}
void GameState::setupDebugDraw() {
debugDraw_.reset(new SFMLDebugDraw(game_->window(), pong::PIXELS_PER_METER));
gameWorld_.setDebugDraw(debugDraw_.get());
debugDraw_->SetFlags(b2Draw::e_shapeBit);
}
void GameState::setupInputHandlers() {
setupPlayerOneInputHandler();
setupPlayerTwoInputHandler();
}
void GameState::setupPlayerOneInputHandler() {
b2Body* leftRaquet = gameWorld_.leftRaquet();
b2Vec2 upVelocity(0.0f, RAQUET_BASE_SPEED);
b2Vec2 downVelocity(0.0f, -RAQUET_BASE_SPEED);
RaquetInputHandler* leftHandler = new RaquetInputHandler(leftRaquet);
leftHandler->bindKey(sf::Keyboard::W, InputHandler::UP);
leftHandler->bindKey(sf::Keyboard::S, InputHandler::DOWN);
Command* command = new MoveRaquetCommand(leftRaquet, upVelocity);
leftHandler->bindCommand(InputHandler::UP, command);
command = new MoveRaquetCommand(leftRaquet, downVelocity);
leftHandler->bindCommand(InputHandler::DOWN, command);
inputHandlers_[PLAYER_1].reset(leftHandler);
}
void GameState::setupPlayerTwoInputHandler() {
b2Body* leftRaquet = gameWorld_.rightRaquet();
b2Vec2 upVelocity(0.0f, RAQUET_BASE_SPEED);
b2Vec2 downVelocity(0.0f, -RAQUET_BASE_SPEED);
RaquetInputHandler* rightHandler = new RaquetInputHandler(leftRaquet);
rightHandler->bindKey(sf::Keyboard::Up, InputHandler::UP);
rightHandler->bindKey(sf::Keyboard::Down, InputHandler::DOWN);
Command* command = new MoveRaquetCommand(leftRaquet, upVelocity);
rightHandler->bindCommand(InputHandler::UP, command);
command = new MoveRaquetCommand(leftRaquet, downVelocity);
rightHandler->bindCommand(InputHandler::DOWN, command);
inputHandlers_[PLAYER_2].reset(rightHandler);
}
void GameState::exit() {
}
void GameState::handleInput(const sf::Event& event) {
if (event.type == sf::Event::KeyReleased) {
if (event.key.code == sf::Keyboard::R) {
create();
}
} else {
DefaultState::handleInput(event);
}
}
void GameState::update() {
for (auto& handler : inputHandlers_) {
Command* command = handler->handleInput();
command->execute();
}
gameWorld_.update();
}
void GameState::render(sf::RenderTarget& renderTarget) {
#ifndef NDEBUG
gameWorld_.drawDebugData();
#endif /* ifndef NDEBUG */
}
void GameState::leftScored(GameWorld& gameWorld) {
gameWorld.resetBall();
}
void GameState::rightScored(GameWorld& gameWorld) {
gameWorld.resetBall();
}
} /* namespace pong */
<commit_msg>Add pause button<commit_after>#include "pong/state.hpp"
#include <Box2D/Box2D.h>
#include "pong/game.hpp"
#include "pong/defs.hpp"
namespace pong {
sf::RectangleShape createRectangleShape(float width, float height) {
sf::RectangleShape shape;
shape.setOrigin(width / 2, height / 2);
shape.setSize(sf::Vector2f(width, height));
shape.setFillColor(sf::Color::White);
return shape;
}
void syncBodyToTransformable(b2Body* body, sf::Transformable& transformable) {
b2Vec2 position = body->GetPosition();
float angle = body->GetAngle();
transformable.setPosition(position.x * PIXELS_PER_METER,
position.y * PIXELS_PER_METER);
transformable.setRotation(angle);
}
void DefaultState::enter(Game* game) {
game_ = game;
}
void DefaultState::handleInput(const sf::Event& event) {
if (event.type == sf::Event::Closed) {
game_->exit();
}
}
void GameState::enter(Game* game) {
DefaultState::enter(game);
create();
}
void GameState::create() {
setupGameWorld();
setupInputHandlers();
}
void GameState::setupGameWorld() {
gameWorld_.create();
gameWorld_.setScoreListener(this);
gameWorld_.start();
#ifndef NDEBUG
setupDebugDraw();
#endif /* ifndef NDEBUG */
}
void GameState::setupDebugDraw() {
debugDraw_.reset(new SFMLDebugDraw(game_->window(), pong::PIXELS_PER_METER));
gameWorld_.setDebugDraw(debugDraw_.get());
debugDraw_->SetFlags(b2Draw::e_shapeBit);
}
void GameState::setupInputHandlers() {
setupPlayerOneInputHandler();
setupPlayerTwoInputHandler();
}
void GameState::setupPlayerOneInputHandler() {
b2Body* leftRaquet = gameWorld_.leftRaquet();
b2Vec2 upVelocity(0.0f, RAQUET_BASE_SPEED);
b2Vec2 downVelocity(0.0f, -RAQUET_BASE_SPEED);
RaquetInputHandler* leftHandler = new RaquetInputHandler(leftRaquet);
leftHandler->bindKey(sf::Keyboard::W, InputHandler::UP);
leftHandler->bindKey(sf::Keyboard::S, InputHandler::DOWN);
Command* command = new MoveRaquetCommand(leftRaquet, upVelocity);
leftHandler->bindCommand(InputHandler::UP, command);
command = new MoveRaquetCommand(leftRaquet, downVelocity);
leftHandler->bindCommand(InputHandler::DOWN, command);
inputHandlers_[PLAYER_1].reset(leftHandler);
}
void GameState::setupPlayerTwoInputHandler() {
b2Body* leftRaquet = gameWorld_.rightRaquet();
b2Vec2 upVelocity(0.0f, RAQUET_BASE_SPEED);
b2Vec2 downVelocity(0.0f, -RAQUET_BASE_SPEED);
RaquetInputHandler* rightHandler = new RaquetInputHandler(leftRaquet);
rightHandler->bindKey(sf::Keyboard::Up, InputHandler::UP);
rightHandler->bindKey(sf::Keyboard::Down, InputHandler::DOWN);
Command* command = new MoveRaquetCommand(leftRaquet, upVelocity);
rightHandler->bindCommand(InputHandler::UP, command);
command = new MoveRaquetCommand(leftRaquet, downVelocity);
rightHandler->bindCommand(InputHandler::DOWN, command);
inputHandlers_[PLAYER_2].reset(rightHandler);
}
void GameState::exit() {
}
void GameState::handleInput(const sf::Event& event) {
if (event.type == sf::Event::KeyReleased) {
if (event.key.code == sf::Keyboard::R) {
create();
} else if (event.key.code == sf::Keyboard::P) {
gameWorld_.toggleRunning();
}
} else {
DefaultState::handleInput(event);
}
}
void GameState::update() {
for (auto& handler : inputHandlers_) {
Command* command = handler->handleInput();
command->execute();
}
gameWorld_.update();
}
void GameState::render(sf::RenderTarget& renderTarget) {
#ifndef NDEBUG
gameWorld_.drawDebugData();
#endif /* ifndef NDEBUG */
}
void GameState::leftScored(GameWorld& gameWorld) {
gameWorld.resetBall();
}
void GameState::rightScored(GameWorld& gameWorld) {
gameWorld.resetBall();
}
} /* namespace pong */
<|endoftext|> |
<commit_before>#include <iostream>
#include <random>
#include <chrono>
#include <map>
#include <string>
#include <json/json.hpp>
class Civilization {
// I think this is the first time I've ever used friend without feeling bad
friend std::ostream& operator<<(std::ostream&, const Civilization&);
typedef std::normal_distribution<double> normal;
typedef std::gamma_distribution<double> gamma;
typedef std::uniform_real_distribution<double> uniform;
typedef std::string string;
typedef nlohmann::json json;
public:
Civilization(time_t seed=std::chrono::system_clock::now().time_since_epoch().count()) :
unitrand_(0.0, 1.0) {
std::cout << "Using seed " << seed << std::endl;
engine_.seed(seed);
// burn card
engine_.discard(1);
GenCiv();
}
void GenCiv() {
GenBasics();
GenCriticalThinking();
GenSpeech();
GenGovernment();
GenRelations();
GenAppearance();
}
void GenBasics() {
// god this is actually unbelievably fun
normal intelligence_gen(100, 30);
normal friendliness_gen(100, 80);
normal emotionality_gen(100, 80);
normal tribalism_gen(100,25);
gamma age_gen(2, 8200);
// no negative intelligence (despite some people I know)
intelligence_ = Clamp(intelligence_gen(engine_), 0);
friendliness_ = friendliness_gen(engine_);
emotionality_ = emotionality_gen(engine_);
tribalism_ = tribalism_gen(engine_);
age_ = age_gen(engine_) + 2000;
}
void GenCriticalThinking() {
if (intelligence_ > 70 || rand() < .05) {
specifics_["critical_thinking"] = 1;
}
std::cout << engine_() << "\n" << engine_() << std::endl;
}
void GenSpeech() {
}
void GenGovernment() {
}
void GenRelations() {
}
void GenAppearance() {
}
double Clamp(double number, double min, double max=kLargeNumber) {
if (number > max) {
return max;
} else if (number < min) {
return min;
} else {
return number;
}
}
double Rand() {
return unitrand_(engine_);
}
private:
std::mt19937 engine_;
uniform unitrand_;
constexpr const static double kLargeNumber = 999999999999999;
double intelligence_;
double friendliness_;
double emotionality_;
double tribalism_;
double age_;
json specifics_;
};
std::ostream& operator<<(std::ostream &strm, const Civilization &civ) {
return strm << "Civilization"
<< "\nintelligence: " << civ.intelligence_
<< "\nfriendliness: " << civ.friendliness_
<< "\nemotionality: " << civ.emotionality_
<< "\ntribalism: " << civ.tribalism_
<< "\nage: " << civ.age_ << "\n";
}
int main() {
for (size_t i = 0; i < 10; ++i) {
std::cout << Civilization() << std::endl;
}
}
<commit_msg>Doesn't work yet hisssss<commit_after>#include <iostream>
#include <random>
#include <chrono>
#include <list>
#include <map>
#include <string>
#include <json/json.hpp>
#include <limits>
//#include <functional>
class CivAttribute {
protected:
typedef std::string string;
typedef nlohmann::json json;
template <class T>
using list = std::list<T>;
template <class T, class V>
using map = std::map<T, V>;
using AttributeMap = map<string, CivAttribute>;
public:
CivAttribute() {}
virtual string GetName();
virtual double OccurrenceProbability(AttributeMap current_tags) { return 0; }
virtual bool DependenciesSatisfied(AttributeMap potential_tags) { return true; }
virtual bool MutexesSatisfied(AttributeMap current_tags) { return true; }
virtual list<string> GetParents() { return list<string>(); }
virtual list<string> GetChildren() { return list<string>(); }
virtual list<string> GetMutexes() { return list<string>(); }
bool ContainsAll(AttributeMap att_map, list<string> attributes) {
for (string att : attributes) {
if (att_map.find(att) == att_map.end()) {
return false;
}
}
return true;
}
bool ContainsAny(AttributeMap att_map, list<string> attributes) {
for (string att : attributes) {
if (att_map.find(att) == att_map.end()) {
return true;
}
}
return false;
}
};
class Eat : public CivAttribute {
public:
Eat() {}
string GetName() override { return "eat"; }
double OccurrenceProbability(AttributeMap current_tags) override {
return .5;
}
bool DependenciesSatisfied(AttributeMap potential_tags) override {
return ContainsAll(potential_tags, GetParents());
}
bool MutexesSatisfied(AttributeMap current_tags) override {
return !ContainsAny(current_tags, GetMutexes());
}
list<string> GetMutexes() override {
return list<string>();
}
list<string> GetParents() override {
return parents_;
}
list<string> GetChildren() override {
return children_;
}
list<string> parents_ = {};
list<string> children_ = {"choke", "fork"};
};
class Drink : public CivAttribute {
public:
Drink() {}
string GetName() override { return "drink"; }
double OccurrenceProbability(AttributeMap current_tags) override {
return .5;
}
bool DependenciesSatisfied(AttributeMap potential_tags) override {
return ContainsAll(potential_tags, GetParents());
}
bool MutexesSatisfied(AttributeMap current_tags) override {
return !ContainsAny(current_tags, GetMutexes());
}
list<string> GetMutexes() override {
return list<string>();
}
list<string> GetParents() override {
return parents_;
}
list<string> GetChildren() override {
return children_;
}
list<string> parents_ = {};
list<string> children_ = {"choke"};
};
class Choke : public CivAttribute {
public:
Choke() {}
string GetName() override { return "choke"; }
double OccurrenceProbability(AttributeMap current_tags) override {
return .5;
}
bool DependenciesSatisfied(AttributeMap potential_tags) override {
return ContainsAll(potential_tags, GetParents());
}
bool MutexesSatisfied(AttributeMap current_tags) override {
return !ContainsAny(current_tags, GetMutexes());
}
list<string> GetMutexes() override {
return list<string>();
}
list<string> GetParents() override {
return parents_;
}
list<string> GetChildren() override {
return children_;
}
list<string> parents_ = {"eat", "drink"};
list<string> children_ = {};
};
class Fork : public CivAttribute {
public:
Fork() {};
string GetName() override { return "fork"; }
double OccurrenceProbability(AttributeMap current_tags) override {
return .5;
}
bool DependenciesSatisfied(AttributeMap potential_tags) override {
return ContainsAll(potential_tags, GetParents());
}
bool MutexesSatisfied(AttributeMap current_tags) override {
return !ContainsAny(current_tags, GetMutexes());
}
list<string> GetMutexes() override {
return list<string>();
}
list<string> GetParents() override {
return parents_;
}
list<string> GetChildren() override {
return children_;
}
list<string> parents_ = {"eat"};
list<string> children_ = {};
};
class Civilization {
// I think this is the first time I've ever used friend without feeling bad
friend std::ostream& operator<<(std::ostream&, const Civilization&);
typedef std::normal_distribution<double> normal;
typedef std::gamma_distribution<double> gamma;
typedef std::uniform_real_distribution<double> uniform_real;
typedef std::uniform_int_distribution<int> uniform_int;
typedef std::string string;
typedef nlohmann::json json;
public:
Civilization(time_t seed=std::chrono::system_clock::now().time_since_epoch().count()) :
unitrand_(0.0, 1.0) {
std::cout << "Using seed " << seed << std::endl;
engine_.seed(seed);
// burn card
engine_.discard(1);
GenCiv();
}
void GenCiv() {
GenBasics();
GenCriticalThinking();
}
void GenBasics() {
// god this is actually unbelievably fun
normal intelligence_gen(100, 30);
normal friendliness_gen(100, 80);
normal emotionality_gen(100, 80);
normal tribalism_gen(100,25);
normal disgust_gen(100, 25);
gamma age_gen(2, 8200);
// no negative intelligence (despite some people I know)
intelligence_ = Clamp(intelligence_gen(engine_), 0);
friendliness_ = friendliness_gen(engine_);
emotionality_ = emotionality_gen(engine_);
tribalism_ = tribalism_gen(engine_);
disgust_ = disgust_gen(engine_);
age_ = age_gen(engine_) + 2000;
}
void GenCriticalThinking() {
if (intelligence_ > 70 || rand() < .05) {
specifics_["critical_thinking"] = 1;
}
potential_attributes_["eat"] = Eat();
potential_attributes_["drink"] = Drink();
potential_attributes_["choke"] = Choke();
potential_attributes_["fork"] = Fork();
//while (!potential_attributes_.empty()) {
// int idx = RandInt(0, potential_attributes_.size());
//}
for (int i = 0; i < 100; ++i) {
std::cout << RandInt(0, 10) << std::endl;
}
std::cout << engine_() << "\n" << engine_() << std::endl;
}
double Clamp(double number, double min, double max=kLargeNumber) {
if (number > max) {
return max;
} else if (number < min) {
return min;
} else {
return number;
}
}
double Rand() {
return unitrand_(engine_);
}
double RandInt(int low, int high) {
return uniform_int(low, high-1)(engine_);
}
private:
std::mt19937 engine_;
uniform_real unitrand_;
constexpr const static double kLargeNumber = 999999999999999;
double intelligence_;
double friendliness_;
double emotionality_;
double tribalism_;
double disgust_;
double age_;
json specifics_;
std::map<string, CivAttribute> current_attributes_;
std::map<string, CivAttribute> potential_attributes_;
};
std::ostream& operator<<(std::ostream &strm, const Civilization &civ) {
return strm << "Civilization"
<< "\nintelligence: " << civ.intelligence_
<< "\nfriendliness: " << civ.friendliness_
<< "\nemotionality: " << civ.emotionality_
<< "\ntribalism: " << civ.tribalism_
<< "\nage: " << civ.age_ << "\n";
}
int main() {
for (size_t i = 0; i < 10; ++i) {
std::cout << Civilization() << std::endl;
}
}
<|endoftext|> |
<commit_before>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2016 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at [email protected].
/**
* @file
* @brief Implementation of the ADF variants.
*/
#include <xerus/algorithms/xals.h>
#include <xerus/indexedTensorMoveable.h>
#include <xerus/misc/basicArraySupport.h>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace xerus {
class InternalSolver {
const size_t d;
std::vector<Tensor> leftStack;
std::vector<Tensor> rightStack;
TTTensor& x;
const TTOperator& A;
const TTTensor& b;
public:
InternalSolver(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) : d(_x.degree()), x(_x), A(_A), b(_b) {
}
void solve() {
}
};
void xals(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) {
InternalSolver solver(_x, _A, _b);
return solver.solve();
}
}
<commit_msg>Further work on xALS<commit_after>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2016 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at [email protected].
/**
* @file
* @brief Implementation of the ADF variants.
*/
#include <xerus/algorithms/xals.h>
#include <xerus/basic.h>
#include <xerus/misc/internal.h>
#include <xerus/indexedTensorMoveable.h>
#include <xerus/misc/basicArraySupport.h>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace xerus {
class InternalSolver {
const size_t d;
std::vector<Tensor> leftStack;
std::vector<Tensor> rightStack;
std::vector<Tensor> leftBStack;
std::vector<Tensor> rightBStack;
TTTensor& x;
const TTOperator& A;
const TTTensor& b;
Tensor leftStackA,rightStackA;
Tensor leftBStackB,rightBStackB;
public:
InternalSolver(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) : d(_x.degree()),leftStack(d), rightStack(d), x(_x), A(_A), b(_b) {
}
void calc_left_stack(const size_t _position) {
const Tensor& xi = x.get_component(_position);
if(_position == 0) {
Tensor tmp;
Tensor A0 = A.get_component(_position);
A0.reinterpret_dimensions({A0.dimensions[1], A0.dimensions[2], A0.dimensions[3]});
contract(tmp, A0, true, xi, false, 1);
contract(leftStack[_position], A0, true, xi, false, 1);
} else {
contract(leftStack[_position], leftStack[_position-1], x.component(_position), 1);
}
}
void calc_right_stack(const size_t _position) {
}
double calc_residual_norm() {
Index i,j;
Tensor tmp;
tmp(i&0) = A(i/2, j/2)*x(j&0);
return frob_norm(tmp);
}
void solve() {
const double solutionsNorm = frob_norm(b);
std::vector<double> residuals(10, 1000.0);
const size_t maxIterations = 1000;
for(size_t iteration = 0; maxIterations == 0 || iteration < maxIterations; ++iteration) {
x.move_core(0, true);
// Rebuild right stack
for(size_t corePosition = d-1; corePosition > 0; --corePosition) {
calc_right_stack(corePosition);
}
residuals.push_back(calc_residual_norm()/solutionsNorm);
if(residuals.back()/residuals[residuals.size()-10] > 0.99) {
LOG(ALS, "Residual decrease from " << std::scientific << residuals[10] << " to " << std::scientific << residuals.back() << " in " << residuals.size()-10 << " iterations.");
return; // We are done!
}
// Sweep Right -> Left
for(size_t corePosition = 0; corePosition < x.degree(); ++corePosition) {
// Actual Work to do
Tensor op, rhs;
if(corePosition == 0) {
leftStackA = A.get_component(corePosition);
leftStackA.reinterpret_dimensions({leftStackA.dimensions[1], leftStackA.dimensions[2], leftStackA.dimensions[3]});
leftBStackB = B.get_component(corePosition);
leftBStackB.reinterpret_dimensions({leftBStackB.dimensions[1], leftBStackB.dimensions[2]});
} else {
contract(leftStackA, leftStack[corePosition-1], A.get_component(corePosition), 1);
contract(leftBStackB, leftBStack[corePosition-1], b.get_component(corePosition), 1);
}
contract(op, leftStackA, rightStack[corePosition+1], 1);
contract(rhs, leftBStackB, rightBStack[corePosition+1], 1);
solve_least_squares(x.component(corePosition), op, rhs, 0);
// If we have not yet reached the end of the sweep we need to take care of the core and update our stacks
if(corePosition+1 < d) {
x.move_core(corePosition+1, true);
calc_left_stack(corePosition);
}
}
// Sweep Right -> Left
for(size_t corePosition = d-1; corePosition > 0; --corePosition) {
//Actual Work to do
// If we have not yet reached the end of the sweep we need to take care of the core and update our stacks
if(corePosition > 0) {
x.move_core(corePosition-1, true);
calc_right_stack(corePosition);
}
}
}
}
};
void xals(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) {
InternalSolver solver(_x, _A, _b);
return solver.solve();
}
}
<|endoftext|> |
<commit_before>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2016 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at [email protected].
/**
* @file
* @brief Implementation of the ADF variants.
*/
#include <xerus/algorithms/xals.h>
#include <xerus/basic.h>
#include <xerus/misc/internal.h>
#include <xerus/indexedTensorMoveable.h>
#include <xerus/misc/basicArraySupport.h>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace xerus {
class InternalSolver {
const size_t d;
std::vector<Tensor> leftStack;
std::vector<Tensor> rightStack;
std::vector<Tensor> leftBStack;
std::vector<Tensor> rightBStack;
TTTensor& x;
const TTOperator& A;
const TTTensor& b;
Tensor leftStackA,rightStackA;
Tensor leftBStackB,rightBStackB;
public:
InternalSolver(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) : d(_x.degree()),leftStack(d), rightStack(d), x(_x), A(_A), b(_b) {
}
void calc_left_stack(const size_t _position) {
const Tensor& xi = x.get_component(_position);
if(_position == 0) {
Tensor tmp;
Tensor A0 = A.get_component(_position);
A0.reinterpret_dimensions({A0.dimensions[1], A0.dimensions[2], A0.dimensions[3]});
contract(tmp, A0, true, xi, false, 1);
contract(leftStack[_position], A0, true, xi, false, 1);
} else {
contract(leftStack[_position], leftStack[_position-1], x.component(_position), 1);
}
}
void calc_right_stack(const size_t _position) {
}
double calc_residual_norm() {
Index i,j;
Tensor tmp;
tmp(i&0) = A(i/2, j/2)*x(j&0);
return frob_norm(tmp);
}
void solve() {
const double solutionsNorm = frob_norm(b);
std::vector<double> residuals(10, 1000.0);
const size_t maxIterations = 1000;
for(size_t iteration = 0; maxIterations == 0 || iteration < maxIterations; ++iteration) {
x.move_core(0, true);
// Rebuild right stack
for(size_t corePosition = d-1; corePosition > 0; --corePosition) {
calc_right_stack(corePosition);
}
residuals.push_back(calc_residual_norm()/solutionsNorm);
if(residuals.back()/residuals[residuals.size()-10] > 0.99) {
LOG(ALS, "Residual decrease from " << std::scientific << residuals[10] << " to " << std::scientific << residuals.back() << " in " << residuals.size()-10 << " iterations.");
return; // We are done!
}
// Sweep Right -> Left
for(size_t corePosition = 0; corePosition < x.degree(); ++corePosition) {
// Actual Work to do
Tensor op, rhs;
if(corePosition == 0) {
leftStackA = A.get_component(corePosition);
leftStackA.reinterpret_dimensions({leftStackA.dimensions[1], leftStackA.dimensions[2], leftStackA.dimensions[3]});
leftBStackB = B.get_component(corePosition);
leftBStackB.reinterpret_dimensions({leftBStackB.dimensions[1], leftBStackB.dimensions[2]});
} else {
contract(leftStackA, leftStack[corePosition-1], A.get_component(corePosition), 1);
contract(leftBStackB, leftBStack[corePosition-1], b.get_component(corePosition), 1);
}
contract(op, leftStackA, rightStack[corePosition+1], 1);
contract(rhs, leftBStackB, rightBStack[corePosition+1], 1);
solve_least_squares(x.component(corePosition), op, rhs, 0);
// If we have not yet reached the end of the sweep we need to take care of the core and update our stacks
if(corePosition+1 < d) {
x.move_core(corePosition+1, true);
calc_left_stack(corePosition);
}
}
// Sweep Right -> Left
for(size_t corePosition = d-1; corePosition > 0; --corePosition) {
//Actual Work to do
// If we have not yet reached the end of the sweep we need to take care of the core and update our stacks
if(corePosition > 0) {
x.move_core(corePosition-1, true);
calc_right_stack(corePosition);
}
}
}
}
};
void xals(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) {
InternalSolver solver(_x, _A, _b);
return solver.solve();
}
}
<commit_msg>Fixed typo<commit_after>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2016 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at [email protected].
/**
* @file
* @brief Implementation of the ADF variants.
*/
#include <xerus/algorithms/xals.h>
#include <xerus/basic.h>
#include <xerus/misc/internal.h>
#include <xerus/indexedTensorMoveable.h>
#include <xerus/misc/basicArraySupport.h>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace xerus {
class InternalSolver {
const size_t d;
std::vector<Tensor> leftStack;
std::vector<Tensor> rightStack;
std::vector<Tensor> leftBStack;
std::vector<Tensor> rightBStack;
TTTensor& x;
const TTOperator& A;
const TTTensor& b;
Tensor leftStackA,rightStackA;
Tensor leftBStackB,rightBStackB;
public:
InternalSolver(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) : d(_x.degree()),leftStack(d), rightStack(d), x(_x), A(_A), b(_b) {
}
void calc_left_stack(const size_t _position) {
const Tensor& xi = x.get_component(_position);
if(_position == 0) {
Tensor tmp;
Tensor A0 = A.get_component(_position);
A0.reinterpret_dimensions({A0.dimensions[1], A0.dimensions[2], A0.dimensions[3]});
contract(tmp, A0, true, xi, false, 1);
contract(leftStack[_position], A0, true, xi, false, 1);
} else {
contract(leftStack[_position], leftStack[_position-1], x.component(_position), 1);
}
}
void calc_right_stack(const size_t _position) {
}
double calc_residual_norm() {
Index i,j;
Tensor tmp;
tmp(i&0) = A(i/2, j/2)*x(j&0);
return frob_norm(tmp);
}
void solve() {
const double solutionsNorm = frob_norm(b);
std::vector<double> residuals(10, 1000.0);
const size_t maxIterations = 1000;
for(size_t iteration = 0; maxIterations == 0 || iteration < maxIterations; ++iteration) {
x.move_core(0, true);
// Rebuild right stack
for(size_t corePosition = d-1; corePosition > 0; --corePosition) {
calc_right_stack(corePosition);
}
residuals.push_back(calc_residual_norm()/solutionsNorm);
if(residuals.back()/residuals[residuals.size()-10] > 0.99) {
LOG(ALS, "Residual decrease from " << std::scientific << residuals[10] << " to " << std::scientific << residuals.back() << " in " << residuals.size()-10 << " iterations.");
return; // We are done!
}
// Sweep Right -> Left
for(size_t corePosition = 0; corePosition < x.degree(); ++corePosition) {
// Actual Work to do
Tensor op, rhs;
if(corePosition == 0) {
leftStackA = A.get_component(corePosition);
leftStackA.reinterpret_dimensions({leftStackA.dimensions[1], leftStackA.dimensions[2], leftStackA.dimensions[3]});
leftBStackB = b.get_component(corePosition);
leftBStackB.reinterpret_dimensions({leftBStackB.dimensions[1], leftBStackB.dimensions[2]});
} else {
contract(leftStackA, leftStack[corePosition-1], A.get_component(corePosition), 1);
contract(leftBStackB, leftBStack[corePosition-1], b.get_component(corePosition), 1);
}
contract(op, leftStackA, rightStack[corePosition+1], 1);
contract(rhs, leftBStackB, rightBStack[corePosition+1], 1);
solve_least_squares(x.component(corePosition), op, rhs, 0);
// If we have not yet reached the end of the sweep we need to take care of the core and update our stacks
if(corePosition+1 < d) {
x.move_core(corePosition+1, true);
calc_left_stack(corePosition);
}
}
// Sweep Right -> Left
for(size_t corePosition = d-1; corePosition > 0; --corePosition) {
//Actual Work to do
// If we have not yet reached the end of the sweep we need to take care of the core and update our stacks
if(corePosition > 0) {
x.move_core(corePosition-1, true);
calc_right_stack(corePosition);
}
}
}
}
};
void xals(TTTensor& _x, const TTOperator& _A, const TTTensor& _b) {
InternalSolver solver(_x, _A, _b);
return solver.solve();
}
}
<|endoftext|> |
<commit_before>//
// The MIT License (MIT)
//
// Copyright (c) 2017 Tag Games Limited
//
// 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.
//
#ifdef CS_TARGETPLATFORM_RPI
#include <CSBackend/Platform/RPi/Core/Base/DispmanWindow.h>
#include <CSBackend/Platform/RPi/Core/Base/SystemInfoFactory.h>
#include <ChilliSource/Core/Base/StandardMacros.h>
#include <ChilliSource/Core/Base/AppConfig.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/LifecycleManager.h>
#include <ChilliSource/Core/Base/SystemInfo.h>
#include <ChilliSource/Core/Container/VectorUtils.h>
namespace CSBackend
{
namespace RPi
{
//----------------------------------------------------------------------------------
void DispmanWindow::Run() noexcept
{
//The display setup we use mimics Minecraft on the Raspberry Pi. Essentially we use a dispman display
//to take advantage of hardware acceleration but we layer that on top of an X window which we use to listen
//for events and to allow the user to control the size of the dispman display.
//Create an XWindow which will act as a backing to our main display
m_xdisplay = XOpenDisplay(NULL);
if(m_xdisplay == nullptr)
{
printf("[ChilliSource] Failed to create X11 display. Exiting");
return;
}
m_xwindow = XCreateSimpleWindow(m_xdisplay, XDefaultRootWindow(m_xdisplay), 0, 0, 200, 200, 0, 0, 0);
XMapWindow(m_xdisplay, m_xwindow);
XFlush(m_xdisplay);
// Start interfacing with Raspberry Pi.
if(!m_bcmInitialised)
{
bcm_host_init();
m_bcmInitialised = true;
}
// TODO: Get attributes from Config
static const EGLint attributeList[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 16,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
// Set up OpenGL context version
static const EGLint contextAttributeList[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
// Get EGL display & initialize it
m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(m_eglDisplay, NULL, NULL);
// Set up config
eglChooseConfig(m_eglDisplay, attributeList, &m_eglConfig, 1, &m_eglConfigNum);
// Bind to OpenGL ES 2.0
eglBindAPI(EGL_OPENGL_ES_API);
// Create context
m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, EGL_NO_CONTEXT, contextAttributeList);
// Get display size (TODO: from config/X windowing system?)
u32 displayWidth, displayHeight;
graphics_get_display_size(0, &displayWidth, &displayHeight);
m_windowSize.x = (s32)displayWidth;
m_windowSize.y = (s32)displayHeight;
// Set up blit rects.
m_dstRect.x = 0;
m_dstRect.y = 0;
m_dstRect.width = m_windowSize.x;
m_dstRect.height = m_windowSize.y;
m_srcRect.x = 0;
m_srcRect.y = 0;
m_srcRect.width = m_windowSize.x << 16;
m_srcRect.height = m_windowSize.y << 16;
// Set up dispmanx
m_displayManagerDisplay = vc_dispmanx_display_open(0);
m_displayManagerUpdate = vc_dispmanx_update_start(0);
m_displayManagerElement = vc_dispmanx_element_add(m_displayManagerUpdate, m_displayManagerDisplay, 0, &m_dstRect, 0, &m_srcRect, DISPMANX_PROTECTION_NONE, 0, 0, (DISPMANX_TRANSFORM_T)0);
// Set up native window. TODO: Attach to X? Size to X Window?
m_nativeWindow.element = m_displayManagerElement;
m_nativeWindow.width = m_windowSize.x;
m_nativeWindow.height = m_windowSize.y;
// Instruct VC chip to use this display manager to sync
vc_dispmanx_update_submit_sync(m_displayManagerUpdate);
// Set up EGL surface
m_eglSurface = eglCreateWindowSurface(m_eglDisplay, m_eglConfig, &m_nativeWindow, NULL);
// Connect context to surface
eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext);
// MAIN LOOP BEGINS HERE
// Set up LifecycleManager
ChilliSource::ApplicationUPtr app = ChilliSource::ApplicationUPtr(CreateApplication(SystemInfoFactory::CreateSystemInfo()));
m_lifecycleManager = ChilliSource::LifecycleManagerUPtr(new ChilliSource::LifecycleManager(app.get()));
// Load appconfig
auto appConfig = app->GetAppConfig();
m_lifecycleManager->Resume();
m_lifecycleManager->Foreground();
m_isRunning = true;
while(m_isRunning == true)
{
//TODO: Handle backgrounding/foregrounding on window focus
// Get X Events
//Update, render and then flip display buffer
m_lifecycleManager->SystemUpdate();
m_lifecycleManager->Render();
eglSwapBuffers(m_eglDisplay, m_eglSurface);
if(m_quitScheduled)
{
Quit();
}
}
}
//-----------------------------------------------------------------------------------
std::vector<ChilliSource::Integer2> DispmanWindow::GetSupportedResolutions() const noexcept
{
//TODO: Find out if we can query the BCM or dispman for supported resolutions
return std::vector<ChilliSource::Integer2> { m_windowSize };
}
//-----------------------------------------------------------------------------------
void DispmanWindow::Quit() noexcept
{
m_lifecycleManager->Suspend();
m_lifecycleManager.reset();
m_isRunning = false;
}
//-----------------------------------------------------------------------------------
DispmanWindow::~DispmanWindow()
{
if(m_bcmInitialised)
{
bcm_host_deinit();
}
if(m_xdisplay)
{
XDestroyWindow(m_xdisplay, m_xwindow);
XCloseDisplay(m_xdisplay);
}
}
}
}
#endif
<commit_msg>Adding events to X window that we need to listen to<commit_after>//
// The MIT License (MIT)
//
// Copyright (c) 2017 Tag Games Limited
//
// 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.
//
#ifdef CS_TARGETPLATFORM_RPI
#include <CSBackend/Platform/RPi/Core/Base/DispmanWindow.h>
#include <CSBackend/Platform/RPi/Core/Base/SystemInfoFactory.h>
#include <ChilliSource/Core/Base/StandardMacros.h>
#include <ChilliSource/Core/Base/AppConfig.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/LifecycleManager.h>
#include <ChilliSource/Core/Base/SystemInfo.h>
#include <ChilliSource/Core/Container/VectorUtils.h>
namespace CSBackend
{
namespace RPi
{
//----------------------------------------------------------------------------------
void DispmanWindow::Run() noexcept
{
//The display setup we use mimics Minecraft on the Raspberry Pi. Essentially we use a dispman display
//to take advantage of hardware acceleration but we layer that on top of an X window which we use to listen
//for events and to allow the user to control the size of the dispman display.
//Create an XWindow which will act as a backing to our main display
m_xdisplay = XOpenDisplay(NULL);
if(m_xdisplay == nullptr)
{
printf("[ChilliSource] Failed to create X11 display. Exiting");
return;
}
m_xwindow = XCreateSimpleWindow(m_xdisplay, XDefaultRootWindow(m_xdisplay), 0, 0, 200, 200, 0, 0, 0);
XMapWindow(m_xdisplay, m_xwindow);
//All the events we need to listen for
XSelectInput(m_xdisplay, m_xwindow, PointerMotionMask | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | FocusChangeMask);
XFlush(m_xdisplay);
// Start interfacing with Raspberry Pi.
if(!m_bcmInitialised)
{
bcm_host_init();
m_bcmInitialised = true;
}
// TODO: Get attributes from Config
static const EGLint attributeList[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 16,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
// Set up OpenGL context version
static const EGLint contextAttributeList[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
// Get EGL display & initialize it
m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(m_eglDisplay, NULL, NULL);
// Set up config
eglChooseConfig(m_eglDisplay, attributeList, &m_eglConfig, 1, &m_eglConfigNum);
// Bind to OpenGL ES 2.0
eglBindAPI(EGL_OPENGL_ES_API);
// Create context
m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, EGL_NO_CONTEXT, contextAttributeList);
// Get display size (TODO: from config/X windowing system?)
u32 displayWidth, displayHeight;
graphics_get_display_size(0, &displayWidth, &displayHeight);
m_windowSize.x = (s32)displayWidth;
m_windowSize.y = (s32)displayHeight;
// Set up blit rects.
m_dstRect.x = 0;
m_dstRect.y = 0;
m_dstRect.width = m_windowSize.x;
m_dstRect.height = m_windowSize.y;
m_srcRect.x = 0;
m_srcRect.y = 0;
m_srcRect.width = m_windowSize.x << 16;
m_srcRect.height = m_windowSize.y << 16;
// Set up dispmanx
m_displayManagerDisplay = vc_dispmanx_display_open(0);
m_displayManagerUpdate = vc_dispmanx_update_start(0);
m_displayManagerElement = vc_dispmanx_element_add(m_displayManagerUpdate, m_displayManagerDisplay, 0, &m_dstRect, 0, &m_srcRect, DISPMANX_PROTECTION_NONE, 0, 0, (DISPMANX_TRANSFORM_T)0);
// Set up native window. TODO: Attach to X? Size to X Window?
m_nativeWindow.element = m_displayManagerElement;
m_nativeWindow.width = m_windowSize.x;
m_nativeWindow.height = m_windowSize.y;
// Instruct VC chip to use this display manager to sync
vc_dispmanx_update_submit_sync(m_displayManagerUpdate);
// Set up EGL surface
m_eglSurface = eglCreateWindowSurface(m_eglDisplay, m_eglConfig, &m_nativeWindow, NULL);
// Connect context to surface
eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext);
// MAIN LOOP BEGINS HERE
// Set up LifecycleManager
ChilliSource::ApplicationUPtr app = ChilliSource::ApplicationUPtr(CreateApplication(SystemInfoFactory::CreateSystemInfo()));
m_lifecycleManager = ChilliSource::LifecycleManagerUPtr(new ChilliSource::LifecycleManager(app.get()));
// Load appconfig
auto appConfig = app->GetAppConfig();
m_lifecycleManager->Resume();
m_lifecycleManager->Foreground();
m_isRunning = true;
while(m_isRunning == true)
{
//TODO: Handle backgrounding/foregrounding on window focus
// Get X Events
//Update, render and then flip display buffer
m_lifecycleManager->SystemUpdate();
m_lifecycleManager->Render();
eglSwapBuffers(m_eglDisplay, m_eglSurface);
if(m_quitScheduled)
{
Quit();
}
}
}
//-----------------------------------------------------------------------------------
std::vector<ChilliSource::Integer2> DispmanWindow::GetSupportedResolutions() const noexcept
{
//TODO: Find out if we can query the BCM or dispman for supported resolutions
return std::vector<ChilliSource::Integer2> { m_windowSize };
}
//-----------------------------------------------------------------------------------
void DispmanWindow::Quit() noexcept
{
m_lifecycleManager->Suspend();
m_lifecycleManager.reset();
m_isRunning = false;
}
//-----------------------------------------------------------------------------------
DispmanWindow::~DispmanWindow()
{
if(m_bcmInitialised)
{
bcm_host_deinit();
}
if(m_xdisplay)
{
XDestroyWindow(m_xdisplay, m_xwindow);
XCloseDisplay(m_xdisplay);
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Georgia Institute of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file test_reductions.cpp
* @author Patrick Flick <[email protected]>
* @brief GTest Unit Tests for mxx reductions
*/
#include <mpi.h>
#include <gtest/gtest.h>
#include <mxx/comm.hpp>
#include <mxx/reduction.hpp>
// test internal details of custom ops
TEST(MxxImpl, CustomOp) {
// test C++ functors (postive tests)
{
std::plus<int> x;
mxx::custom_op<int> o(x);
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_SUM, o.get_op());
}
{
std::multiplies<double> x;
mxx::custom_op<double> o(x);
EXPECT_EQ(MPI_DOUBLE, o.get_type());
EXPECT_EQ(MPI_PROD, o.get_op());
}
{
std::bit_or<char> x;
mxx::custom_op<char> o(x);
EXPECT_EQ(MPI_CHAR, o.get_type());
EXPECT_EQ(MPI_BOR, o.get_op());
}
{
std::bit_xor<long> x;
mxx::custom_op<long> o(x);
EXPECT_EQ(MPI_LONG, o.get_type());
EXPECT_EQ(MPI_BXOR, o.get_op());
}
{
std::bit_and<unsigned char> x;
mxx::custom_op<unsigned char> o(x);
EXPECT_EQ(MPI_UNSIGNED_CHAR, o.get_type());
EXPECT_EQ(MPI_BAND, o.get_op());
}
{
std::logical_or<unsigned int> x;
mxx::custom_op<unsigned int> o(x);
EXPECT_EQ(MPI_UNSIGNED, o.get_type());
EXPECT_EQ(MPI_LOR, o.get_op());
}
{
std::logical_and<unsigned short> x;
mxx::custom_op<unsigned short> o(x);
EXPECT_EQ(MPI_UNSIGNED_SHORT, o.get_type());
EXPECT_EQ(MPI_LAND, o.get_op());
}
// test std::min and std::max
{
mxx::custom_op<float> o(static_cast<const float&(*)(const float&, const float&)>(&std::min<float>));
EXPECT_EQ(MPI_FLOAT, o.get_type());
EXPECT_EQ(MPI_MIN, o.get_op());
}
{
mxx::custom_op<int> o(static_cast<const int&(*)(const int&, const int&)>(&std::max<int>));
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_MAX, o.get_op());
}
{
mxx::max<int> x;
mxx::custom_op<int> o(x);
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_MAX, o.get_op());
}
{
mxx::min<int> x;
mxx::custom_op<int> o(x);
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_MIN, o.get_op());
}
}
template <typename T>
struct mymax {
T operator()(const T x, T& y){
if (x > y)
return x;
else
return y;
}
};
int mymin(int x, int y) {
if (x < y)
return x;
else
return y;
}
// scatter of size 1
TEST(MxxReduce, ReduceOne) {
mxx::comm c = mxx::comm();
// test min
int x = -13*(c.size() - c.rank());
int y = mxx::reduce(x, c.size()/2, mxx::min<int>(), c);
if (c.rank() == c.size()/2) {
ASSERT_EQ(-13*c.size(), y);
} else {
ASSERT_EQ(0, y);
}
// test sum
int z = mxx::reduce(3, 0, std::plus<int>(), c);
if (c.rank() == 0) {
ASSERT_EQ(3*c.size(), z);
} else {
ASSERT_EQ(0, z);
}
// test lambda op
int g = mxx::reduce(2, c.size()-1, [](int i, int j){return i+j;});
if (c.rank() == c.size()-1) {
ASSERT_EQ(2*c.size(), g);
} else {
ASSERT_EQ(0, g);
}
// test functor
float m = mxx::reduce(1.3333f*c.rank(), 0, mymax<float>(), c);
if (c.rank() == 0) {
ASSERT_EQ(1.3333f*(c.size()-1), m);
} else {
ASSERT_EQ(0, m);
}
// test own function pointer
int v = c.rank() + 1;
int u = mxx::reduce(v, 0, mymin, c);
if (c.rank() == 0) {
ASSERT_EQ(1, u);
} else {
ASSERT_EQ(0, u);
}
}
TEST(MxxReduce, ReduceVec) {
mxx::comm c;
int n = 13;
std::vector<int> v(n);
for (int i = 0; i < n; ++i) {
v[i] = c.rank() + i;
}
int ranksum = (c.size() * (c.size()-1)) / 2;
std::vector<int> w = mxx::reduce(v, c.size()/2, c);
if (c.rank() == c.size()/2) {
ASSERT_EQ(n, (int)w.size());
for (int i = 0; i < n; ++i) {
ASSERT_EQ(ranksum + i*c.size(), w[i]);
}
} else {
ASSERT_EQ(0u, w.size());
}
}
TEST(MxxReduce, AllReduceVec) {
mxx::comm c;
int n = 10; // numbers per rank
std::vector<int> v(n);
for (int i = 0; i < n; ++i) {
v[i] = i;
}
std::vector<int> w = mxx::allreduce(v);
ASSERT_EQ(n, (int)w.size());
for (int i = 0; i < n; ++i) {
ASSERT_EQ(c.size()*i, w[i]);
}
w = mxx::allreduce(v, [](int x, int y) { return x+y; }, c.split(c.rank() % 2));
int mysize = c.size() / 2;
if (c.size() % 2 == 1 && c.rank() % 2 == 0)
++mysize;
ASSERT_EQ(mysize, c.split(c.rank() % 2).size());
ASSERT_EQ(n, (int)w.size());
for (int i = 0; i < n; ++i) {
ASSERT_EQ(mysize*i, w[i]);
}
}
TEST(MxxReduce, Scan) {
mxx::comm c;
int r = c.rank()*2;
int g = mxx::scan(r);
ASSERT_EQ(c.rank()*(c.rank()+1), g);
int m = mxx::exscan(r, mxx::max<int>());
if (r != 0) {
ASSERT_EQ((c.rank()-1)*2, m);
}
int m2 = mxx::exscan(r, mxx::max<int>(), c.split(c.rank() % 3));
if (c.rank() >= 3) {
ASSERT_EQ((c.rank()-3)*2, m2);
}
}
TEST(MxxReduce, GlobalReduce) {
mxx::comm c;
// test reduce with zero elements for some processes
size_t n = 0;
int presize = 0;
if (c.rank() % 2 == 0) {
n = (c.rank()/2+1);
presize = n*(n-1)/2;
}
std::vector<long> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = presize + i + 1;
}
long totalsum = mxx::global_reduce(local, [](int x, int y){ return x+y; }, c);
int nonzero_size = (c.size()+1)/2;
int num_els = nonzero_size*(nonzero_size+1)/2;
ASSERT_EQ(num_els*(num_els+1)/2, totalsum);
}
TEST(MxxReduce, GlobalScan) {
mxx::comm c;
// test reduce with zero elements for some processes
size_t n = 0;
int presize = 0;
if (c.rank() % 2 == 0) {
n = (c.rank()/2+1);
presize = n*(n-1)/2;
}
std::vector<int> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = presize + i + 1;
}
// test inplace scan
std::vector<int> local_cpy(local);
mxx::global_scan_inplace(local_cpy.begin(), local_cpy.end(), c);
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]+1)/2, local_cpy[i]);
}
// test scan
//std::vector<int> result(local.size());
std::vector<int> result = mxx::global_scan(local, [](int x, int y) {return x+y;});
ASSERT_EQ(local.size(), result.size());
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]+1)/2, result[i]);
}
}
TEST(MxxReduce, GlobalExScan) {
mxx::comm c;
// test reduce with zero elements for some processes
size_t n = 0;
int presize = 0;
if (c.rank() % 2 == 0) {
n = (c.rank()/2+1);
presize = n*(n-1)/2;
}
std::vector<int> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = presize + i + 1;
}
// test inplace exscan
std::vector<int> local_cpy(local);
mxx::global_exscan_inplace(local_cpy, std::plus<int>(), c);
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]-1)/2, local_cpy[i]);
}
// test exscan
std::vector<int> result = mxx::global_exscan(local);
ASSERT_EQ(local.size(), result.size());
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]-1)/2, result[i]);
}
}
TEST(MxxReduce, MinMaxLoc) {
mxx::comm c;
std::pair<double, int> maxloc = mxx::max_element(3.1*c.rank(), c);
ASSERT_EQ(c.size()-1, maxloc.second);
ASSERT_EQ(3.1*(c.size()-1), maxloc.first);
std::pair<int, int> minloc = mxx::min_element(c.rank()+13);
ASSERT_EQ(13, minloc.first);
ASSERT_EQ(0, minloc.second);
}
// TODO: test for simple all_of/some_of etc reductions
<commit_msg>Added a test that was failing before the fix in b55a0b6d033f90a75dec5132e380e8c05404d9e4.<commit_after>/*
* Copyright 2015 Georgia Institute of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file test_reductions.cpp
* @author Patrick Flick <[email protected]>
* @brief GTest Unit Tests for mxx reductions
*/
#include <mpi.h>
#include <gtest/gtest.h>
#include <mxx/comm.hpp>
#include <mxx/reduction.hpp>
// test internal details of custom ops
TEST(MxxImpl, CustomOp) {
// test C++ functors (postive tests)
{
std::plus<int> x;
mxx::custom_op<int> o(x);
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_SUM, o.get_op());
}
{
std::multiplies<double> x;
mxx::custom_op<double> o(x);
EXPECT_EQ(MPI_DOUBLE, o.get_type());
EXPECT_EQ(MPI_PROD, o.get_op());
}
{
std::bit_or<char> x;
mxx::custom_op<char> o(x);
EXPECT_EQ(MPI_CHAR, o.get_type());
EXPECT_EQ(MPI_BOR, o.get_op());
}
{
std::bit_xor<long> x;
mxx::custom_op<long> o(x);
EXPECT_EQ(MPI_LONG, o.get_type());
EXPECT_EQ(MPI_BXOR, o.get_op());
}
{
std::bit_and<unsigned char> x;
mxx::custom_op<unsigned char> o(x);
EXPECT_EQ(MPI_UNSIGNED_CHAR, o.get_type());
EXPECT_EQ(MPI_BAND, o.get_op());
}
{
std::logical_or<unsigned int> x;
mxx::custom_op<unsigned int> o(x);
EXPECT_EQ(MPI_UNSIGNED, o.get_type());
EXPECT_EQ(MPI_LOR, o.get_op());
}
{
std::logical_and<unsigned short> x;
mxx::custom_op<unsigned short> o(x);
EXPECT_EQ(MPI_UNSIGNED_SHORT, o.get_type());
EXPECT_EQ(MPI_LAND, o.get_op());
}
// test std::min and std::max
{
mxx::custom_op<float> o(static_cast<const float&(*)(const float&, const float&)>(&std::min<float>));
EXPECT_EQ(MPI_FLOAT, o.get_type());
EXPECT_EQ(MPI_MIN, o.get_op());
}
{
mxx::custom_op<int> o(static_cast<const int&(*)(const int&, const int&)>(&std::max<int>));
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_MAX, o.get_op());
}
{
mxx::max<int> x;
mxx::custom_op<int> o(x);
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_MAX, o.get_op());
}
{
mxx::min<int> x;
mxx::custom_op<int> o(x);
EXPECT_EQ(MPI_INT, o.get_type());
EXPECT_EQ(MPI_MIN, o.get_op());
}
}
template <typename T>
struct mymax {
T operator()(const T x, T& y){
if (x > y)
return x;
else
return y;
}
};
int mymin(int x, int y) {
if (x < y)
return x;
else
return y;
}
// scatter of size 1
TEST(MxxReduce, ReduceOne) {
mxx::comm c = mxx::comm();
// test min
int x = -13*(c.size() - c.rank());
int y = mxx::reduce(x, c.size()/2, mxx::min<int>(), c);
if (c.rank() == c.size()/2) {
ASSERT_EQ(-13*c.size(), y);
} else {
ASSERT_EQ(0, y);
}
// test sum
int z = mxx::reduce(3, 0, std::plus<int>(), c);
if (c.rank() == 0) {
ASSERT_EQ(3*c.size(), z);
} else {
ASSERT_EQ(0, z);
}
// test lambda op
int g = mxx::reduce(2, c.size()-1, [](int i, int j){return i+j;});
if (c.rank() == c.size()-1) {
ASSERT_EQ(2*c.size(), g);
} else {
ASSERT_EQ(0, g);
}
// test functor
float m = mxx::reduce(1.3333f*c.rank(), 0, mymax<float>(), c);
if (c.rank() == 0) {
ASSERT_EQ(1.3333f*(c.size()-1), m);
} else {
ASSERT_EQ(0, m);
}
// test own function pointer
int v = c.rank() + 1;
int u = mxx::reduce(v, 0, mymin, c);
if (c.rank() == 0) {
ASSERT_EQ(1, u);
} else {
ASSERT_EQ(0, u);
}
}
TEST(MxxReduce, ReduceVec) {
mxx::comm c;
int n = 13;
std::vector<int> v(n);
for (int i = 0; i < n; ++i) {
v[i] = c.rank() + i;
}
int ranksum = (c.size() * (c.size()-1)) / 2;
std::vector<int> w = mxx::reduce(v, c.size()/2, c);
if (c.rank() == c.size()/2) {
ASSERT_EQ(n, (int)w.size());
for (int i = 0; i < n; ++i) {
ASSERT_EQ(ranksum + i*c.size(), w[i]);
}
} else {
ASSERT_EQ(0u, w.size());
}
}
TEST(MxxReduce, AllReduceVec) {
mxx::comm c;
int n = 10; // numbers per rank
std::vector<int> v(n);
for (int i = 0; i < n; ++i) {
v[i] = i;
}
std::vector<int> w = mxx::allreduce(v);
ASSERT_EQ(n, (int)w.size());
for (int i = 0; i < n; ++i) {
ASSERT_EQ(c.size()*i, w[i]);
}
w = mxx::allreduce(v, [](int x, int y) { return x+y; }, c.split(c.rank() % 2));
int mysize = c.size() / 2;
if (c.size() % 2 == 1 && c.rank() % 2 == 0)
++mysize;
ASSERT_EQ(mysize, c.split(c.rank() % 2).size());
ASSERT_EQ(n, (int)w.size());
for (int i = 0; i < n; ++i) {
ASSERT_EQ(mysize*i, w[i]);
}
}
TEST(MxxReduce, Scan) {
mxx::comm c;
int r = c.rank()*2;
int g = mxx::scan(r);
ASSERT_EQ(c.rank()*(c.rank()+1), g);
int m = mxx::exscan(r, mxx::max<int>());
if (r != 0) {
ASSERT_EQ((c.rank()-1)*2, m);
}
int m2 = mxx::exscan(r, mxx::max<int>(), c.split(c.rank() % 3));
if (c.rank() >= 3) {
ASSERT_EQ((c.rank()-3)*2, m2);
}
}
TEST(MxxReduce, GlobalReduce) {
mxx::comm c;
// test reduce with zero elements for some processes
size_t n = 0;
int presize = 0;
if (c.rank() % 2 == 0) {
n = (c.rank()/2+1);
presize = n*(n-1)/2;
}
std::vector<long> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = presize + i + 1;
}
long totalsum = mxx::global_reduce(local, [](int x, int y){ return x+y; }, c);
int nonzero_size = (c.size()+1)/2;
int num_els = nonzero_size*(nonzero_size+1)/2;
ASSERT_EQ(num_els*(num_els+1)/2, totalsum);
}
TEST(MxxReduce, GlobalScan) {
mxx::comm c;
// test scan with zero elements for some processes
size_t n = 0;
int presize = 0;
if (c.rank() % 2 == 0) {
n = (c.rank()/2+1);
presize = n*(n-1)/2;
}
std::vector<int> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = presize + i + 1;
}
// test inplace scan
std::vector<int> local_cpy(local);
mxx::global_scan_inplace(local_cpy.begin(), local_cpy.end(), c);
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]+1)/2, local_cpy[i]);
}
// test scan
//std::vector<int> result(local.size());
std::vector<int> result = mxx::global_scan(local, [](int x, int y) {return x+y;});
ASSERT_EQ(local.size(), result.size());
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]+1)/2, result[i]);
}
}
TEST(MxxReduce, GlobalScanMin) {
mxx::comm c;
// test scan with min and an array of positive
// elements sorted in ascending order
size_t n = c.size();
std::vector<int> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = (c.rank()*n)+i+1;
}
// test inplace scan
std::vector<int> local_cpy(local);
mxx::global_scan_inplace(local_cpy.begin(), local_cpy.end(), mxx::min<int>(), c);
for (size_t i = 0; i < n; ++i) {
// 1 is both the first as well as the minimum element
ASSERT_EQ(1, local_cpy[i]);
}
// test scan
std::vector<int> result = mxx::global_scan(local, mxx::min<int>(), c);
ASSERT_EQ(local.size(), result.size());
for (size_t i = 0; i < n; ++i) {
// 1 is both the first as well as the minimum element
ASSERT_EQ(1, result[i]);
}
}
TEST(MxxReduce, GlobalExScan) {
mxx::comm c;
// test reduce with zero elements for some processes
size_t n = 0;
int presize = 0;
if (c.rank() % 2 == 0) {
n = (c.rank()/2+1);
presize = n*(n-1)/2;
}
std::vector<int> local(n);
for (size_t i = 0; i < n; ++i) {
local[i] = presize + i + 1;
}
// test inplace exscan
std::vector<int> local_cpy(local);
mxx::global_exscan_inplace(local_cpy, std::plus<int>(), c);
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]-1)/2, local_cpy[i]);
}
// test exscan
std::vector<int> result = mxx::global_exscan(local);
ASSERT_EQ(local.size(), result.size());
for (size_t i = 0; i < n; ++i) {
ASSERT_EQ(local[i]*(local[i]-1)/2, result[i]);
}
}
TEST(MxxReduce, MinMaxLoc) {
mxx::comm c;
std::pair<double, int> maxloc = mxx::max_element(3.1*c.rank(), c);
ASSERT_EQ(c.size()-1, maxloc.second);
ASSERT_EQ(3.1*(c.size()-1), maxloc.first);
std::pair<int, int> minloc = mxx::min_element(c.rank()+13);
ASSERT_EQ(13, minloc.first);
ASSERT_EQ(0, minloc.second);
}
// TODO: test for simple all_of/some_of etc reductions
<|endoftext|> |
<commit_before>/*
* PyClaw.cpp
*
* Created on: Feb 18, 2012
* Author: kristof
*/
#include "peanoclaw/native/SWEKernel.h"
#include "peanoclaw/Patch.h"
#include "peanoclaw/Area.h"
#include "peanoclaw/interSubgridCommunication/DefaultTransfer.h"
#include "peanoclaw/native/SWE_WavePropagationBlock_patch.hh"
#include "tarch/multicore/MulticoreDefinitions.h"
#include "tarch/timing/Watch.h"
#include "tarch/parallel/Node.h"
tarch::logging::Log peanoclaw::native::SWEKernel::_log("peanoclaw::native::SWEKernel");
void peanoclaw::native::SWEKernel::transformWaterHeight(
peanoclaw::Patch& subgrid,
const Area& area,
bool modifyUOld,
bool absoluteToAboveSeaFloor
) const {
peanoclaw::grid::SubgridAccessor accessor = subgrid.getAccessor();
double sign = absoluteToAboveSeaFloor ? -1 : +1;
if(modifyUOld) {
dfor(internalSubcellIndex, area._size) {
tarch::la::Vector<DIMENSIONS,int> subcellIndex = internalSubcellIndex + area._offset;
accessor.setValueUOld(
subcellIndex,
0,
accessor.getValueUOld(subcellIndex, 0) + sign * accessor.getParameterWithGhostlayer(subcellIndex, 0)
);
}
} else {
dfor(internalSubcellIndex, area._size) {
tarch::la::Vector<DIMENSIONS,int> subcellIndex = internalSubcellIndex + area._offset;
accessor.setValueUNew(
subcellIndex,
0,
accessor.getValueUNew(subcellIndex, 0) + sign * accessor.getParameterWithGhostlayer(subcellIndex, 0)
);
}
}
}
void peanoclaw::native::SWEKernel::advanceBlockInTime(
SWE_WavePropagationBlock_patch& block,
peanoclaw::Patch& subgrid,
double maximumTimestepSize
) {
block.setArrays(
subgrid,
reinterpret_cast<float*>(subgrid.getUOldWithGhostlayerArray(0)),
reinterpret_cast<float*>(subgrid.getUOldWithGhostlayerArray(1)),
reinterpret_cast<float*>(subgrid.getUOldWithGhostlayerArray(2)),
reinterpret_cast<float*>(subgrid.getParameterWithoutGhostlayerArray(0))
);
block.computeNumericalFluxes();
double dt = fmin(block.getMaxTimestep(), maximumTimestepSize);
double estimatedNextTimestepSize = block.getMaxTimestep();
block.updateUnknowns(dt);
peanoclaw::interSubgridCommunication::DefaultTransfer transfer;
transfer.swapUNewAndUOld(subgrid);
assertion4(
tarch::la::greater(subgrid.getTimeIntervals().getTimestepSize(), 0.0)
|| tarch::la::greater(estimatedNextTimestepSize, 0.0)
|| tarch::la::equals(maximumTimestepSize, 0.0)
|| tarch::la::equals(subgrid.getTimeIntervals().getEstimatedNextTimestepSize(), 0.0),
subgrid, maximumTimestepSize, estimatedNextTimestepSize, subgrid.toStringUNew());
assertion(subgrid.getTimeIntervals().getTimestepSize() < std::numeric_limits<double>::infinity());
if (tarch::la::greater(dt, 0.0)) {
subgrid.getTimeIntervals().advanceInTime();
subgrid.getTimeIntervals().setTimestepSize(dt);
}
subgrid.getTimeIntervals().setEstimatedNextTimestepSize(estimatedNextTimestepSize);
}
peanoclaw::native::SWEKernel::SWEKernel(
peanoclaw::native::scenarios::SWEScenario& scenario,
peanoclaw::interSubgridCommunication::DefaultTransfer* transfer,
peanoclaw::interSubgridCommunication::Interpolation* interpolation,
peanoclaw::interSubgridCommunication::Restriction* restriction,
peanoclaw::interSubgridCommunication::FluxCorrection* fluxCorrection
) : Numerics(transfer, interpolation, restriction, fluxCorrection),
_totalSolverCallbackTime(0.0),
_scenario(scenario),
_cachedSubdivisionFactor(-1),
_cachedGhostlayerWidth(-1),
_cachedBlock(0)
{
//import_array();
}
peanoclaw::native::SWEKernel::~SWEKernel()
{
}
void peanoclaw::native::SWEKernel::initializePatch(
Patch& patch
) {
logTraceIn( "initializePatch(...)");
_scenario.initializePatch(patch);
logTraceOutWith1Argument( "initializePatch(...)", demandedMeshWidth);
}
void peanoclaw::native::SWEKernel::update(Patch& subgrid) {
_scenario.update(subgrid);
}
void peanoclaw::native::SWEKernel::solveTimestep(Patch& patch, double maximumTimestepSize, bool useDimensionalSplitting) {
logTraceInWith2Arguments( "solveTimestep(...)", maximumTimestepSize, useDimensionalSplitting);
assertion2(tarch::la::greater(maximumTimestepSize, 0.0), "Timestepsize == 0 should be checked outside.", patch.getTimeIntervals().getMinimalNeighborTimeConstraint());
tarch::timing::Watch solverWatch("", "", false);
solverWatch.startTimer();
#ifdef SharedMemoryParallelisation
SWE_WavePropagationBlock_patch block(patch);
advanceBlockInTime(
block,
patch,
maximumTimestepSize
);
#else
if(
_cachedSubdivisionFactor != patch.getSubdivisionFactor()
|| _cachedGhostlayerWidth != patch.getGhostlayerWidth()
) {
//SWE_WavePropagationBlock_patch swe(patch);
_cachedBlock = std::auto_ptr<SWE_WavePropagationBlock_patch>(new SWE_WavePropagationBlock_patch(patch));
_cachedSubdivisionFactor = patch.getSubdivisionFactor();
_cachedGhostlayerWidth = patch.getGhostlayerWidth();
}
advanceBlockInTime(
*_cachedBlock,
patch,
maximumTimestepSize
);
#endif
solverWatch.stopTimer();
_totalSolverCallbackTime += solverWatch.getCalendarTime();
logTraceOut( "solveTimestep(...)");
}
tarch::la::Vector<DIMENSIONS, double> peanoclaw::native::SWEKernel::getDemandedMeshWidth(Patch& patch, bool isInitializing) {
return _scenario.computeDemandedMeshWidth(patch, isInitializing);
}
void peanoclaw::native::SWEKernel::addPatchToSolution(Patch& patch) {
}
void peanoclaw::native::SWEKernel::fillBoundaryLayer(Patch& patch, int dimension, bool setUpper) {
logTraceInWith3Arguments("fillBoundaryLayerInPyClaw", patch, dimension, setUpper);
logDebug("fillBoundaryLayerInPyClaw", "Setting left boundary for " << patch.getPosition() << ", dim=" << dimension << ", setUpper=" << setUpper);
//std::cout << "------ setUpper " << setUpper << " dimension " << dimension << std::endl;
//std::cout << patch << std::endl;
//std::cout << "++++++" << std::endl;
//std::cout << patch.toStringUOldWithGhostLayer() << std::endl;
//std::cout << "||||||" << std::endl;
// implement a wall boundary
tarch::la::Vector<DIMENSIONS, int> src_subcellIndex;
tarch::la::Vector<DIMENSIONS, int> dest_subcellIndex;
peanoclaw::grid::SubgridAccessor& accessor = patch.getAccessor();
if (dimension == 0) {
for (int yi = -1; yi < patch.getSubdivisionFactor()(1)+1; yi++) {
int xi = setUpper ? patch.getSubdivisionFactor()(0) : -1;
src_subcellIndex(0) = xi;
src_subcellIndex(1) = yi;
src_subcellIndex(dimension) += setUpper ? -1 : +1;
dest_subcellIndex(0) = xi;
dest_subcellIndex(1) = yi;
for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
double q = accessor.getValueUOld(src_subcellIndex, unknown);
if (unknown == dimension + 1) {
accessor.setValueUOld(dest_subcellIndex, unknown, -q);
} else {
accessor.setValueUOld(dest_subcellIndex, unknown, q);
}
}
}
} else {
for (int xi = -1; xi < patch.getSubdivisionFactor()(0)+1; xi++) {
int yi = setUpper ? patch.getSubdivisionFactor()(1) : -1;
src_subcellIndex(0) = xi;
src_subcellIndex(1) = yi;
src_subcellIndex(dimension) += setUpper ? -1 : +1;
dest_subcellIndex(0) = xi;
dest_subcellIndex(1) = yi;
for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
double q = accessor.getValueUOld(src_subcellIndex, unknown);
if (unknown == dimension + 1) {
accessor.setValueUOld(dest_subcellIndex, unknown, -q);
} else {
accessor.setValueUOld(dest_subcellIndex, unknown, q);
}
}
}
}
logTraceOut("fillBoundaryLayerInPyClaw");
}
void peanoclaw::native::SWEKernel::interpolateSolution (
const tarch::la::Vector<DIMENSIONS, int>& destinationSize,
const tarch::la::Vector<DIMENSIONS, int>& destinationOffset,
peanoclaw::Patch& source,
peanoclaw::Patch& destination,
bool interpolateToUOld,
bool interpolateToCurrentTime,
bool useTimeUNewOrTimeUOld
) const {
peanoclaw::grid::SubgridAccessor sourceAccessor = source.getAccessor();
peanoclaw::grid::SubgridAccessor destinationAccessor = destination.getAccessor();
tarch::la::Vector<DIMENSIONS,int> sourceSubdivisionFactor = source.getSubdivisionFactor();
Area destinationArea(destinationOffset, destinationSize);
Area sourceArea = destinationArea.mapToPatch(destination, source);
//Increase sourceArea by one cell in each direction.
for(int d = 0; d < DIMENSIONS; d++) {
if(sourceArea._offset[d] > 0) {
sourceArea._offset[d] = sourceArea._offset[d]-1;
sourceArea._size[d] = std::min(sourceSubdivisionFactor[d], sourceArea._size[d] + 2);
} else {
sourceArea._size[d] = std::min(sourceSubdivisionFactor[d], sourceArea._size[d] + 1);
}
}
//Source: Water Height above Sea Floor -> Absolute Water Height
transformWaterHeight(source, sourceArea, true, false); //UOld
transformWaterHeight(source, sourceArea, false, false); // UNew
//Interpolate
Numerics::interpolateSolution (
destinationSize,
destinationOffset,
source,
destination,
interpolateToUOld,
interpolateToCurrentTime,
useTimeUNewOrTimeUOld
);
//Source: Absolute Water Height -> Water Height above Sea Floor
transformWaterHeight(source, sourceArea, true, true); //UOld
transformWaterHeight(source, sourceArea, false, true); // UNew
//Destination: Absolute Water Height -> Water Height above Sea Floor
transformWaterHeight(destination, destinationArea, interpolateToUOld, true);
}
void peanoclaw::native::SWEKernel::restrict (
peanoclaw::Patch& source,
peanoclaw::Patch& destination,
bool restrictOnlyOverlappedAreas
) const {
Area sourceArea(tarch::la::Vector<DIMENSIONS,int>(0), source.getSubdivisionFactor());
transformWaterHeight(source, sourceArea, true, false); //UOld
transformWaterHeight(source, sourceArea, false, false); //UNew
Numerics::restrict(
source,
destination,
restrictOnlyOverlappedAreas
);
transformWaterHeight(source, sourceArea, true, true); //UOld
transformWaterHeight(source, sourceArea, false, true); //UNew
}
void peanoclaw::native::SWEKernel::postProcessRestriction(
peanoclaw::Patch& destination,
bool restrictOnlyOverlappedAreas
) const {
Area destinationArea(tarch::la::Vector<DIMENSIONS,int>(0), destination.getSubdivisionFactor());
transformWaterHeight(destination, destinationArea, true, true); //UOld
transformWaterHeight(destination, destinationArea, false, true); //UNew
}
<commit_msg>fixed<commit_after>/*
* PyClaw.cpp
*
* Created on: Feb 18, 2012
* Author: kristof
*/
#include "peanoclaw/native/SWEKernel.h"
#include "peanoclaw/Patch.h"
#include "peanoclaw/Area.h"
#include "peanoclaw/interSubgridCommunication/DefaultTransfer.h"
#include "peanoclaw/native/SWE_WavePropagationBlock_patch.hh"
#include "tarch/multicore/MulticoreDefinitions.h"
#include "tarch/timing/Watch.h"
#include "tarch/parallel/Node.h"
tarch::logging::Log peanoclaw::native::SWEKernel::_log("peanoclaw::native::SWEKernel");
void peanoclaw::native::SWEKernel::transformWaterHeight(
peanoclaw::Patch& subgrid,
const Area& area,
bool modifyUOld,
bool absoluteToAboveSeaFloor
) const {
peanoclaw::grid::SubgridAccessor accessor = subgrid.getAccessor();
double sign = absoluteToAboveSeaFloor ? -1 : +1;
if(modifyUOld) {
dfor(internalSubcellIndex, area._size) {
tarch::la::Vector<DIMENSIONS,int> subcellIndex = internalSubcellIndex + area._offset;
accessor.setValueUOld(
subcellIndex,
0,
accessor.getValueUOld(subcellIndex, 0) + sign * accessor.getParameterWithGhostlayer(subcellIndex, 0)
);
}
} else {
dfor(internalSubcellIndex, area._size) {
tarch::la::Vector<DIMENSIONS,int> subcellIndex = internalSubcellIndex + area._offset;
accessor.setValueUNew(
subcellIndex,
0,
accessor.getValueUNew(subcellIndex, 0) + sign * accessor.getParameterWithGhostlayer(subcellIndex, 0)
);
}
}
}
void peanoclaw::native::SWEKernel::advanceBlockInTime(
SWE_WavePropagationBlock_patch& block,
peanoclaw::Patch& subgrid,
double maximumTimestepSize
) {
block.setArrays(
subgrid,
reinterpret_cast<float*>(subgrid.getUOldWithGhostlayerArray(0)),
reinterpret_cast<float*>(subgrid.getUOldWithGhostlayerArray(1)),
reinterpret_cast<float*>(subgrid.getUOldWithGhostlayerArray(2)),
reinterpret_cast<float*>(subgrid.getParameterWithoutGhostlayerArray(0))
);
block.computeNumericalFluxes();
double dt = fmin(block.getMaxTimestep(), maximumTimestepSize);
double estimatedNextTimestepSize = block.getMaxTimestep();
block.updateUnknowns(dt);
peanoclaw::interSubgridCommunication::DefaultTransfer transfer;
transfer.swapUNewAndUOld(subgrid);
assertion4(
tarch::la::greater(subgrid.getTimeIntervals().getTimestepSize(), 0.0)
|| tarch::la::greater(estimatedNextTimestepSize, 0.0)
|| tarch::la::equals(maximumTimestepSize, 0.0)
|| tarch::la::equals(subgrid.getTimeIntervals().getEstimatedNextTimestepSize(), 0.0),
subgrid, maximumTimestepSize, estimatedNextTimestepSize, subgrid.toStringUNew());
assertion(subgrid.getTimeIntervals().getTimestepSize() < std::numeric_limits<double>::infinity());
if (tarch::la::greater(dt, 0.0)) {
subgrid.getTimeIntervals().advanceInTime();
subgrid.getTimeIntervals().setTimestepSize(dt);
}
subgrid.getTimeIntervals().setEstimatedNextTimestepSize(estimatedNextTimestepSize);
}
peanoclaw::native::SWEKernel::SWEKernel(
peanoclaw::native::scenarios::SWEScenario& scenario,
peanoclaw::interSubgridCommunication::DefaultTransfer* transfer,
peanoclaw::interSubgridCommunication::Interpolation* interpolation,
peanoclaw::interSubgridCommunication::Restriction* restriction,
peanoclaw::interSubgridCommunication::FluxCorrection* fluxCorrection
) : Numerics(transfer, interpolation, restriction, fluxCorrection),
_totalSolverCallbackTime(0.0),
_scenario(scenario),
_cachedSubdivisionFactor(-1),
_cachedGhostlayerWidth(-1),
_cachedBlock(0)
{
//import_array();
}
peanoclaw::native::SWEKernel::~SWEKernel()
{
}
void peanoclaw::native::SWEKernel::initializePatch(
Patch& patch
) {
logTraceIn( "initializePatch(...)");
_scenario.initializePatch(patch);
logTraceOutWith1Argument( "initializePatch(...)", demandedMeshWidth);
}
void peanoclaw::native::SWEKernel::update(Patch& subgrid) {
_scenario.update(subgrid);
}
void peanoclaw::native::SWEKernel::solveTimestep(Patch& patch, double maximumTimestepSize, bool useDimensionalSplitting) {
logTraceInWith2Arguments( "solveTimestep(...)", maximumTimestepSize, useDimensionalSplitting);
assertion2(tarch::la::greater(maximumTimestepSize, 0.0), "Timestepsize == 0 should be checked outside.", patch.getTimeIntervals().getMinimalNeighborTimeConstraint());
tarch::timing::Watch solverWatch("", "", false);
solverWatch.startTimer();
#ifdef SharedMemoryParallelisation
SWE_WavePropagationBlock_patch block(patch);
advanceBlockInTime(
block,
patch,
maximumTimestepSize
);
#else
if(
_cachedSubdivisionFactor != patch.getSubdivisionFactor()
|| _cachedGhostlayerWidth != patch.getGhostlayerWidth()
) {
//SWE_WavePropagationBlock_patch swe(patch);
_cachedBlock = std::auto_ptr<SWE_WavePropagationBlock_patch>(new SWE_WavePropagationBlock_patch(patch));
_cachedSubdivisionFactor = patch.getSubdivisionFactor();
_cachedGhostlayerWidth = patch.getGhostlayerWidth();
}
advanceBlockInTime(
*_cachedBlock,
patch,
maximumTimestepSize
);
#endif
solverWatch.stopTimer();
_totalSolverCallbackTime += solverWatch.getCalendarTime();
logTraceOut( "solveTimestep(...)");
}
tarch::la::Vector<DIMENSIONS, double> peanoclaw::native::SWEKernel::getDemandedMeshWidth(Patch& patch, bool isInitializing) {
return _scenario.computeDemandedMeshWidth(patch, isInitializing);
}
void peanoclaw::native::SWEKernel::addPatchToSolution(Patch& patch) {
}
void peanoclaw::native::SWEKernel::fillBoundaryLayer(Patch& patch, int dimension, bool setUpper) {
logTraceInWith3Arguments("fillBoundaryLayerInPyClaw", patch, dimension, setUpper);
logDebug("fillBoundaryLayerInPyClaw", "Setting left boundary for " << patch.getPosition() << ", dim=" << dimension << ", setUpper=" << setUpper);
//std::cout << "------ setUpper " << setUpper << " dimension " << dimension << std::endl;
//std::cout << patch << std::endl;
//std::cout << "++++++" << std::endl;
//std::cout << patch.toStringUOldWithGhostLayer() << std::endl;
//std::cout << "||||||" << std::endl;
// implement a wall boundary
tarch::la::Vector<DIMENSIONS, int> src_subcellIndex;
tarch::la::Vector<DIMENSIONS, int> dest_subcellIndex;
peanoclaw::grid::SubgridAccessor& accessor = patch.getAccessor();
if (dimension == 0) {
for (int yi = -1; yi < patch.getSubdivisionFactor()(1)+1; yi++) {
int xi = setUpper ? patch.getSubdivisionFactor()(0) : -1;
src_subcellIndex(0) = xi;
src_subcellIndex(1) = yi;
src_subcellIndex(dimension) += setUpper ? -1 : +1;
dest_subcellIndex(0) = xi;
dest_subcellIndex(1) = yi;
for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
double q = accessor.getValueUOld(src_subcellIndex, unknown);
if (unknown == dimension + 1) {
accessor.setValueUOld(dest_subcellIndex, unknown, -q);
} else {
accessor.setValueUOld(dest_subcellIndex, unknown, q);
}
}
}
} else {
for (int xi = -1; xi < patch.getSubdivisionFactor()(0)+1; xi++) {
int yi = setUpper ? patch.getSubdivisionFactor()(1) : -1;
src_subcellIndex(0) = xi;
src_subcellIndex(1) = yi;
src_subcellIndex(dimension) += setUpper ? -1 : +1;
dest_subcellIndex(0) = xi;
dest_subcellIndex(1) = yi;
for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
double q = accessor.getValueUOld(src_subcellIndex, unknown);
if (unknown == dimension + 1) {
accessor.setValueUOld(dest_subcellIndex, unknown, -q);
} else {
accessor.setValueUOld(dest_subcellIndex, unknown, q);
}
}
}
}
logTraceOut("fillBoundaryLayerInPyClaw");
}
void peanoclaw::native::SWEKernel::interpolateSolution (
const tarch::la::Vector<DIMENSIONS, int>& destinationSize,
const tarch::la::Vector<DIMENSIONS, int>& destinationOffset,
peanoclaw::Patch& source,
peanoclaw::Patch& destination,
bool interpolateToUOld,
bool interpolateToCurrentTime,
bool useTimeUNewOrTimeUOld
) const {
peanoclaw::grid::SubgridAccessor sourceAccessor = source.getAccessor();
peanoclaw::grid::SubgridAccessor destinationAccessor = destination.getAccessor();
tarch::la::Vector<DIMENSIONS,int> sourceSubdivisionFactor = source.getSubdivisionFactor();
Area destinationArea(destinationOffset, destinationSize);
Area sourceArea = destinationArea.mapToPatch(destination, source);
//Increase sourceArea by one cell in each direction.
for(int d = 0; d < DIMENSIONS; d++) {
if(sourceArea._offset[d] > 0) {
sourceArea._offset[d] = sourceArea._offset[d]-1;
sourceArea._size[d] = std::min(sourceSubdivisionFactor[d], sourceArea._size[d] + 2);
} else {
sourceArea._size[d] = std::min(sourceSubdivisionFactor[d], sourceArea._size[d] + 1);
}
}
//Source: Water Height above Sea Floor -> Absolute Water Height
transformWaterHeight(source, sourceArea, true, false); //UOld
transformWaterHeight(source, sourceArea, false, false); // UNew
//Interpolate
Numerics::interpolateSolution (
destinationSize,
destinationOffset,
source,
destination,
interpolateToUOld,
interpolateToCurrentTime,
useTimeUNewOrTimeUOld
);
//Source: Absolute Water Height -> Water Height above Sea Floor
transformWaterHeight(source, sourceArea, true, true); //UOld
transformWaterHeight(source, sourceArea, false, true); // UNew
//Destination: Absolute Water Height -> Water Height above Sea Floor
transformWaterHeight(destination, destinationArea, interpolateToUOld, true);
}
void peanoclaw::native::SWEKernel::restrictSolution (
peanoclaw::Patch& source,
peanoclaw::Patch& destination,
bool restrictOnlyOverlappedAreas
) const {
Area sourceArea(tarch::la::Vector<DIMENSIONS,int>(0), source.getSubdivisionFactor());
transformWaterHeight(source, sourceArea, true, false); //UOld
transformWaterHeight(source, sourceArea, false, false); //UNew
Numerics::restrictSolution(
source,
destination,
restrictOnlyOverlappedAreas
);
transformWaterHeight(source, sourceArea, true, true); //UOld
transformWaterHeight(source, sourceArea, false, true); //UNew
}
void peanoclaw::native::SWEKernel::postProcessRestriction(
peanoclaw::Patch& destination,
bool restrictOnlyOverlappedAreas
) const {
Area destinationArea(tarch::la::Vector<DIMENSIONS,int>(0), destination.getSubdivisionFactor());
transformWaterHeight(destination, destinationArea, true, true); //UOld
transformWaterHeight(destination, destinationArea, false, true); //UNew
}
<|endoftext|> |
<commit_before>#include <cstddef>
#include <map>
#include "pegr/script/ScriptHelper.hpp"
#include "pegr/script/Script.hpp"
#include "pegr/logger/Logger.hpp"
namespace pegr {
namespace Test {
typedef Script::Regref_Guard RG;
//@Test Script Helper
void test_script_helper() {
RG sandbox(Script::new_sandbox());
RG table_fun(Script::load_lua_function("test/simple_table.lua", sandbox));
Script::run_function(table_fun, 0, 1);
lua_State* l = Script::get_lua_state();
std::map<std::string, std::string> expected = {
{"a", "apple"},
{"b", "banana"},
{"c", "cherry"}
};
std::map<std::string, std::string> got;
bool success = true;
auto body = [l, &got, &expected]() {
std::size_t strlen;
const char* strdata;
lua_pushvalue(l, -2);
lua_pushvalue(l, -2);
strdata = lua_tolstring(l, -2, &strlen);
std::string key(strdata, strlen);
strdata = lua_tolstring(l, -1, &strlen);
std::string val(strdata, strlen);
got[key] = val;
Logger::log()->verbose(1, "%v\t%v", key, val);
lua_pop(l, 2);
};
Script::Helper::for_pairs(-1, [body, l]()->bool {
body();
return true;
}, false);
Script::Helper::for_pairs(-1, [body, l]()->bool {
body();
lua_pop(l, 1);
return true;
}, true);
if (expected != got) {
throw std::runtime_error("Resulting table does not match expectation.");
}
}
}
}
<commit_msg>Fix table comparison<commit_after>#include <cstddef>
#include <sstream>
#include <map>
#include "pegr/script/ScriptHelper.hpp"
#include "pegr/script/Script.hpp"
#include "pegr/logger/Logger.hpp"
namespace pegr {
namespace Test {
typedef Script::Regref_Guard RG;
//@Test Script Helper
void test_script_helper() {
RG sandbox(Script::new_sandbox());
RG table_fun(Script::load_lua_function("test/simple_table.lua", sandbox));
Script::run_function(table_fun, 0, 1);
lua_State* l = Script::get_lua_state();
std::map<std::string, std::string> expected = {
{"a", "apple"},
{"b", "banana"},
{"c", "cherry"}
};
std::map<std::string, std::string> got;
bool success = true;
auto body = [l, &got, &expected]() {
std::size_t strlen;
const char* strdata;
lua_pushvalue(l, -2);
lua_pushvalue(l, -2);
strdata = lua_tolstring(l, -2, &strlen);
std::string key(strdata, strlen);
strdata = lua_tolstring(l, -1, &strlen);
std::string val(strdata, strlen);
got[key] = val;
Logger::log()->verbose(1, "%v\t%v", key, val);
lua_pop(l, 2);
};
Script::Helper::for_pairs(-1, [body, l]()->bool {
body();
return true;
}, false);
Script::Helper::for_pairs(-1, [body, l]()->bool {
body();
lua_pop(l, 1);
return true;
}, true);
for (auto key_value : expected) {
auto iter = got.find(key_value.first);
if (iter == got.end()) {
std::stringstream ss;
ss << "Resulting table missing key: ";
ss << key_value.first;
throw std::runtime_error(ss.str());
}
if (key_value.second != (*iter).second) {
std::stringstream ss;
ss << "Resulting table has wrong value for ";
ss << key_value.first;
ss << ": Expected: ";
ss << key_value.second;
ss << ": Got: ";
ss << (*iter).second;
throw std::runtime_error(ss.str());
}
}
}
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/elastic_membrane.h"
// GRINS
#include "grins_config.h"
#include "grins/assembly_context.h"
#include "grins/solid_mechanics_bc_handling.h"
// libMesh
#include "libmesh/getpot.h"
#include "libmesh/quadrature.h"
#include "libmesh/boundary_info.h"
#include "libmesh/fem_system.h"
namespace GRINS
{
template<typename StressStrainLaw>
ElasticMembrane<StressStrainLaw>::ElasticMembrane( const GRINS::PhysicsName& physics_name, const GetPot& input,
bool lambda_sq_coupled, bool lambda_sq_var )
: ElasticMembraneBase(physics_name,input),
_stress_strain_law(input),
_h0( input("Physics/"+physics_name+"/h0", 1.0 ) ),
_lambda_sq_coupled(lambda_sq_coupled),
_lambda_sq_var(lambda_sq_var)
{
// Force the user to set h0
if( !input.have_variable("Physics/"+physics_name+"/h0") )
{
std::cerr << "Error: Must specify initial thickness for "+physics_name << std::endl
<< " Input the option Physics/"+physics_name+"/h0" << std::endl;
libmesh_error();
}
this->_bc_handler = new SolidMechanicsBCHandling( physics_name, input );
return;
}
template<typename StressStrainLaw>
ElasticMembrane<StressStrainLaw>::~ElasticMembrane()
{
return;
}
template<typename StressStrainLaw>
void ElasticMembrane<StressStrainLaw>::element_time_derivative( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /*cache*/ )
{
const unsigned int n_u_dofs = context.get_dof_indices(_disp_vars.u_var()).size();
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(_disp_vars.u_var())->get_JxW();
const std::vector<std::vector<libMesh::RealGradient> >& u_gradphi =
context.get_element_fe(_disp_vars.u_var())->get_dphi();
libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_disp_vars.u_var());
libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_disp_vars.v_var());
libMesh::DenseSubVector<libMesh::Number> &Fw = context.get_elem_residual(_disp_vars.w_var());
unsigned int n_qpoints = context.get_element_qrule().n_points();
const std::vector<libMesh::RealGradient>& dxdxi = context.get_element_fe(_disp_vars.u_var())->get_dxyzdxi();
const std::vector<libMesh::RealGradient>& dxdeta = context.get_element_fe(_disp_vars.u_var())->get_dxyzdeta();
const std::vector<libMesh::Real>& dxidx = context.get_element_fe(_disp_vars.u_var())->get_dxidx();
const std::vector<libMesh::Real>& dxidy = context.get_element_fe(_disp_vars.u_var())->get_dxidy();
const std::vector<libMesh::Real>& dxidz = context.get_element_fe(_disp_vars.u_var())->get_dxidz();
const std::vector<libMesh::Real>& detadx = context.get_element_fe(_disp_vars.u_var())->get_detadx();
const std::vector<libMesh::Real>& detady = context.get_element_fe(_disp_vars.u_var())->get_detady();
const std::vector<libMesh::Real>& detadz = context.get_element_fe(_disp_vars.u_var())->get_detadz();
const unsigned int dim = 2; // The manifold dimension is always 2 for this physics
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
libMesh::Gradient grad_u = context.interior_gradient(_disp_vars.u_var(), qp);
libMesh::Gradient grad_v = context.interior_gradient(_disp_vars.v_var(), qp);
libMesh::Gradient grad_w = context.interior_gradient(_disp_vars.w_var(), qp);
libMesh::RealGradient grad_x( dxdxi[qp](0), dxdeta[qp](0) );
libMesh::RealGradient grad_y( dxdxi[qp](1), dxdeta[qp](1) );
libMesh::RealGradient grad_z( dxdxi[qp](2), dxdeta[qp](2) );
libMesh::RealGradient dudxi( grad_u(0), grad_v(0), grad_w(0) );
libMesh::RealGradient dudeta( grad_u(1), grad_v(1), grad_w(1) );
libMesh::RealGradient dxi( dxidx[qp], dxidy[qp], dxidz[qp] );
libMesh::RealGradient deta( detadx[qp], detady[qp], detadz[qp] );
// Covariant metric tensor of reference configuration
libMesh::TensorValue<libMesh::Real> a_cov( dxdxi[qp]*dxdxi[qp], dxdxi[qp]*dxdeta[qp], 0.0,
dxdeta[qp]*dxdxi[qp], dxdeta[qp]*dxdeta[qp] );
// Covariant metric tensor of current configuration
libMesh::TensorValue<libMesh::Real> A_cov( (dxdxi[qp] + dudxi)*(dxdxi[qp] + dudxi),
(dxdxi[qp] + dudxi)*(dxdeta[qp] + dudeta), 0.0,
(dxdeta[qp] + dudeta)*(dxdxi[qp] + dudxi),
(dxdeta[qp] + dudeta)*(dxdeta[qp] + dudeta) );
// Contravariant metric tensor of reference configuration
libMesh::TensorValue<libMesh::Real> a_contra( dxi*dxi, dxi*deta, 0.0,
deta*dxi, deta*deta );
// Contravariant metric tensor in current configuration is A_cov^{-1}
libMesh::Real det_A = A_cov(0,0)*A_cov(1,1) - A_cov(0,1)*A_cov(1,0);
libMesh::TensorValue<libMesh::Real> A_contra( A_cov(1,1)/det_A, -A_cov(0,1)/det_A, 0.0,
-A_cov(1,0)/det_A, A_cov(0,0)/det_A );
if( _lambda_sq_coupled )
{
a_cov(2,2) = 1.0;
a_contra(2,2) = 1.0;
libMesh::Real det_a = a_cov.det();
// If the material is incompressible, lambda^2 is known
libMesh::Real lambda_sq = det_a/det_A;
// If the material is compressible, then lambda_sq is an independent variable
if( _lambda_sq_var )
{
libmesh_not_implemented();
}
A_cov(2,2) = lambda_sq;
A_contra(2,2) = 1.0/lambda_sq;
}
// Compute stress tensor
libMesh::TensorValue<libMesh::Real> tau;
_stress_strain_law.compute_stress(dim,a_contra,a_cov,A_contra,A_cov,tau);
libMesh::Real jac = JxW[qp];
for (unsigned int i=0; i != n_u_dofs; i++)
{
for( unsigned int alpha = 0; alpha < dim; alpha++ )
{
for( unsigned int beta = 0; beta < dim; beta++ )
{
Fu(i) -= 0.5*tau(alpha,beta)*_h0*( (grad_x(beta) + grad_u(beta))*u_gradphi[i][qp](alpha) +
(grad_x(alpha) + grad_u(alpha))*u_gradphi[i][qp](beta) )*jac;
Fv(i) -= 0.5*tau(alpha,beta)*_h0*( (grad_y(beta) + grad_v(beta))*u_gradphi[i][qp](alpha) +
(grad_y(alpha) + grad_v(alpha))*u_gradphi[i][qp](beta) )*jac;
Fw(i) -= 0.5*tau(alpha,beta)*_h0*( (grad_z(beta) + grad_w(beta))*u_gradphi[i][qp](alpha) +
(grad_z(alpha) + grad_w(alpha))*u_gradphi[i][qp](beta) )*jac;
}
}
if( compute_jacobian )
{
libmesh_not_implemented();
}
}
}
return;
}
template<typename StressStrainLaw>
void ElasticMembrane<StressStrainLaw>::side_time_derivative( bool /*compute_jacobian*/,
AssemblyContext& /*context*/,
CachedValues& /*cache*/ )
{
/*
std::vector<BoundaryID> ids = context.side_boundary_ids();
for( std::vector<BoundaryID>::const_iterator it = ids.begin();
it != ids.end(); it++ )
{
libmesh_assert (*it != libMesh::BoundaryInfo::invalid_id);
_bc_handler->apply_neumann_bcs( context, cache, compute_jacobian, *it );
}
*/
return;
}
template<typename StressStrainLaw>
void ElasticMembrane<StressStrainLaw>::mass_residual( bool /*compute_jacobian*/,
AssemblyContext& /*context*/,
CachedValues& /*cache*/ )
{
libmesh_not_implemented();
return;
}
} // end namespace GRINS
<commit_msg>Have GenericICHandler there to play with initial conditions<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/elastic_membrane.h"
// GRINS
#include "grins_config.h"
#include "grins/assembly_context.h"
#include "grins/solid_mechanics_bc_handling.h"
#include "grins/generic_ic_handler.h"
// libMesh
#include "libmesh/getpot.h"
#include "libmesh/quadrature.h"
#include "libmesh/boundary_info.h"
#include "libmesh/fem_system.h"
namespace GRINS
{
template<typename StressStrainLaw>
ElasticMembrane<StressStrainLaw>::ElasticMembrane( const GRINS::PhysicsName& physics_name, const GetPot& input,
bool lambda_sq_coupled, bool lambda_sq_var )
: ElasticMembraneBase(physics_name,input),
_stress_strain_law(input),
_h0( input("Physics/"+physics_name+"/h0", 1.0 ) ),
_lambda_sq_coupled(lambda_sq_coupled),
_lambda_sq_var(lambda_sq_var)
{
// Force the user to set h0
if( !input.have_variable("Physics/"+physics_name+"/h0") )
{
std::cerr << "Error: Must specify initial thickness for "+physics_name << std::endl
<< " Input the option Physics/"+physics_name+"/h0" << std::endl;
libmesh_error();
}
this->_bc_handler = new SolidMechanicsBCHandling( physics_name, input );
this->_ic_handler = new GenericICHandler(physics_name, input);
return;
}
template<typename StressStrainLaw>
ElasticMembrane<StressStrainLaw>::~ElasticMembrane()
{
return;
}
template<typename StressStrainLaw>
void ElasticMembrane<StressStrainLaw>::element_time_derivative( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /*cache*/ )
{
const unsigned int n_u_dofs = context.get_dof_indices(_disp_vars.u_var()).size();
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(_disp_vars.u_var())->get_JxW();
const std::vector<std::vector<libMesh::RealGradient> >& u_gradphi =
context.get_element_fe(_disp_vars.u_var())->get_dphi();
libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_disp_vars.u_var());
libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_disp_vars.v_var());
libMesh::DenseSubVector<libMesh::Number> &Fw = context.get_elem_residual(_disp_vars.w_var());
unsigned int n_qpoints = context.get_element_qrule().n_points();
const std::vector<libMesh::RealGradient>& dxdxi = context.get_element_fe(_disp_vars.u_var())->get_dxyzdxi();
const std::vector<libMesh::RealGradient>& dxdeta = context.get_element_fe(_disp_vars.u_var())->get_dxyzdeta();
const std::vector<libMesh::Real>& dxidx = context.get_element_fe(_disp_vars.u_var())->get_dxidx();
const std::vector<libMesh::Real>& dxidy = context.get_element_fe(_disp_vars.u_var())->get_dxidy();
const std::vector<libMesh::Real>& dxidz = context.get_element_fe(_disp_vars.u_var())->get_dxidz();
const std::vector<libMesh::Real>& detadx = context.get_element_fe(_disp_vars.u_var())->get_detadx();
const std::vector<libMesh::Real>& detady = context.get_element_fe(_disp_vars.u_var())->get_detady();
const std::vector<libMesh::Real>& detadz = context.get_element_fe(_disp_vars.u_var())->get_detadz();
const unsigned int dim = 2; // The manifold dimension is always 2 for this physics
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
libMesh::Gradient grad_u = context.interior_gradient(_disp_vars.u_var(), qp);
libMesh::Gradient grad_v = context.interior_gradient(_disp_vars.v_var(), qp);
libMesh::Gradient grad_w = context.interior_gradient(_disp_vars.w_var(), qp);
libMesh::RealGradient grad_x( dxdxi[qp](0), dxdeta[qp](0) );
libMesh::RealGradient grad_y( dxdxi[qp](1), dxdeta[qp](1) );
libMesh::RealGradient grad_z( dxdxi[qp](2), dxdeta[qp](2) );
libMesh::RealGradient dudxi( grad_u(0), grad_v(0), grad_w(0) );
libMesh::RealGradient dudeta( grad_u(1), grad_v(1), grad_w(1) );
libMesh::RealGradient dxi( dxidx[qp], dxidy[qp], dxidz[qp] );
libMesh::RealGradient deta( detadx[qp], detady[qp], detadz[qp] );
// Covariant metric tensor of reference configuration
libMesh::TensorValue<libMesh::Real> a_cov( dxdxi[qp]*dxdxi[qp], dxdxi[qp]*dxdeta[qp], 0.0,
dxdeta[qp]*dxdxi[qp], dxdeta[qp]*dxdeta[qp] );
// Covariant metric tensor of current configuration
libMesh::TensorValue<libMesh::Real> A_cov( (dxdxi[qp] + dudxi)*(dxdxi[qp] + dudxi),
(dxdxi[qp] + dudxi)*(dxdeta[qp] + dudeta), 0.0,
(dxdeta[qp] + dudeta)*(dxdxi[qp] + dudxi),
(dxdeta[qp] + dudeta)*(dxdeta[qp] + dudeta) );
// Contravariant metric tensor of reference configuration
libMesh::TensorValue<libMesh::Real> a_contra( dxi*dxi, dxi*deta, 0.0,
deta*dxi, deta*deta );
// Contravariant metric tensor in current configuration is A_cov^{-1}
libMesh::Real det_A = A_cov(0,0)*A_cov(1,1) - A_cov(0,1)*A_cov(1,0);
libMesh::TensorValue<libMesh::Real> A_contra( A_cov(1,1)/det_A, -A_cov(0,1)/det_A, 0.0,
-A_cov(1,0)/det_A, A_cov(0,0)/det_A );
if( _lambda_sq_coupled )
{
a_cov(2,2) = 1.0;
a_contra(2,2) = 1.0;
libMesh::Real det_a = a_cov.det();
// If the material is incompressible, lambda^2 is known
libMesh::Real lambda_sq = det_a/det_A;
// If the material is compressible, then lambda_sq is an independent variable
if( _lambda_sq_var )
{
libmesh_not_implemented();
}
A_cov(2,2) = lambda_sq;
A_contra(2,2) = 1.0/lambda_sq;
}
// Compute stress tensor
libMesh::TensorValue<libMesh::Real> tau;
_stress_strain_law.compute_stress(dim,a_contra,a_cov,A_contra,A_cov,tau);
libMesh::Real jac = JxW[qp];
for (unsigned int i=0; i != n_u_dofs; i++)
{
for( unsigned int alpha = 0; alpha < dim; alpha++ )
{
for( unsigned int beta = 0; beta < dim; beta++ )
{
Fu(i) -= 0.5*tau(alpha,beta)*_h0*( (grad_x(beta) + grad_u(beta))*u_gradphi[i][qp](alpha) +
(grad_x(alpha) + grad_u(alpha))*u_gradphi[i][qp](beta) )*jac;
Fv(i) -= 0.5*tau(alpha,beta)*_h0*( (grad_y(beta) + grad_v(beta))*u_gradphi[i][qp](alpha) +
(grad_y(alpha) + grad_v(alpha))*u_gradphi[i][qp](beta) )*jac;
Fw(i) -= 0.5*tau(alpha,beta)*_h0*( (grad_z(beta) + grad_w(beta))*u_gradphi[i][qp](alpha) +
(grad_z(alpha) + grad_w(alpha))*u_gradphi[i][qp](beta) )*jac;
}
}
if( compute_jacobian )
{
libmesh_not_implemented();
}
}
}
return;
}
template<typename StressStrainLaw>
void ElasticMembrane<StressStrainLaw>::side_time_derivative( bool /*compute_jacobian*/,
AssemblyContext& /*context*/,
CachedValues& /*cache*/ )
{
/*
std::vector<BoundaryID> ids = context.side_boundary_ids();
for( std::vector<BoundaryID>::const_iterator it = ids.begin();
it != ids.end(); it++ )
{
libmesh_assert (*it != libMesh::BoundaryInfo::invalid_id);
_bc_handler->apply_neumann_bcs( context, cache, compute_jacobian, *it );
}
*/
return;
}
template<typename StressStrainLaw>
void ElasticMembrane<StressStrainLaw>::mass_residual( bool /*compute_jacobian*/,
AssemblyContext& /*context*/,
CachedValues& /*cache*/ )
{
libmesh_not_implemented();
return;
}
} // end namespace GRINS
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef RENDERER_HPP
#define RENDERER_HPP
#include "compare_images.hpp"
// stl
#include <sstream>
#include <iomanip>
#include <fstream>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_renderer.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif
#if defined(SVG_RENDERER)
#include <mapnik/svg/output/svg_renderer.hpp>
#endif
// boost
#include <boost/filesystem.hpp>
namespace visual_tests
{
template <typename ImageType>
struct renderer_base
{
using image_type = ImageType;
static constexpr const char * ext = ".png";
unsigned compare(image_type const & actual, boost::filesystem::path const& reference) const
{
return compare_images(actual, reference.string());
}
void save(image_type const & image, boost::filesystem::path const& path) const
{
mapnik::save_to_file(image, path.string(), "png32");
}
};
struct agg_renderer : renderer_base<mapnik::image_rgba8>
{
static constexpr const char * name = "agg";
image_type render(mapnik::Map const & map, double scale_factor) const
{
image_type image(map.width(), map.height());
mapnik::agg_renderer<image_type> ren(map, image, scale_factor);
ren.apply();
return image;
}
};
#if defined(HAVE_CAIRO)
struct cairo_renderer : renderer_base<mapnik::image_rgba8>
{
static constexpr const char * name = "cairo";
image_type render(mapnik::Map const & map, double scale_factor) const
{
mapnik::cairo_surface_ptr image_surface(
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, map.width(), map.height()),
mapnik::cairo_surface_closer());
mapnik::cairo_ptr image_context(mapnik::create_context(image_surface));
mapnik::cairo_renderer<mapnik::cairo_ptr> ren(map, image_context, scale_factor);
ren.apply();
image_type image(map.width(), map.height());
mapnik::cairo_image_to_rgba8(image, image_surface);
return image;
}
};
#endif
#if defined(SVG_RENDERER)
struct svg_renderer : renderer_base<std::string>
{
static constexpr const char * name = "svg";
static constexpr const char * ext = ".svg";
image_type render(mapnik::Map const & map, double scale_factor) const
{
std::stringstream ss;
std::ostream_iterator<char> output_stream_iterator(ss);
mapnik::svg_renderer<std::ostream_iterator<char>> ren(map, output_stream_iterator, scale_factor);
ren.apply();
return ss.str();
}
unsigned compare(image_type const & actual, boost::filesystem::path const& reference) const
{
std::ifstream stream(reference.string().c_str(),std::ios_base::in|std::ios_base::binary);
if (!stream.is_open())
{
throw std::runtime_error("could not open: '" + reference.string() + "'");
}
std::string expected(std::istreambuf_iterator<char>(stream.rdbuf()),(std::istreambuf_iterator<char>()));
stream.close();
return std::fabs(actual.size() - expected.size());
}
void save(image_type const & image, boost::filesystem::path const& path) const
{
std::ofstream file(path.string().c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if (!file) {
throw std::runtime_error((std::string("cannot open file for writing file ") + path.string()).c_str());
} else {
file << image;
file.close();
}
}
};
#endif
struct grid_renderer : renderer_base<mapnik::image_gray8>
{
static constexpr const char * name = "grid";
image_type render(mapnik::Map const & map, double scale_factor) const
{
image_type image(map.width(), map.height());
// TODO: Render grid here.
return image;
}
};
template <typename Renderer>
class renderer
{
public:
renderer(boost::filesystem::path const & output_dir, boost::filesystem::path const & reference_dir, bool overwrite)
: output_dir(output_dir), reference_dir(reference_dir), overwrite(overwrite)
{
}
result test(std::string const & name, mapnik::Map const & map, double scale_factor) const
{
typename Renderer::image_type image(ren.render(map, scale_factor));
boost::filesystem::path reference = reference_dir / image_file_name(name, map.width(), map.height(), scale_factor, true, Renderer::ext);
bool reference_exists = boost::filesystem::exists(reference);
result res;
res.state = reference_exists ? STATE_OK : STATE_OVERWRITE;
res.name = name;
res.renderer_name = Renderer::name;
res.scale_factor = scale_factor;
res.size = map_size(map.width(), map.height());
res.reference_image_path = reference;
res.diff = reference_exists ? ren.compare(image, reference) : 0;
if (res.diff)
{
boost::filesystem::create_directories(output_dir);
boost::filesystem::path path = output_dir / image_file_name(name, map.width(), map.height(), scale_factor, false, Renderer::ext);
res.actual_image_path = path;
res.state = STATE_FAIL;
ren.save(image, path);
}
if ((res.diff && overwrite) || !reference_exists)
{
ren.save(image, reference);
res.state = STATE_OVERWRITE;
}
return res;
}
private:
std::string image_file_name(std::string const & test_name,
double width,
double height,
double scale_factor,
bool reference,
std::string const& ext) const
{
std::stringstream s;
s << test_name << '-' << width << '-' << height << '-'
<< std::fixed << std::setprecision(1) << scale_factor
<< '-' << Renderer::name << (reference ? "-reference" : "") << ext;
return s.str();
}
Renderer ren;
boost::filesystem::path const & output_dir;
boost::filesystem::path const & reference_dir;
const bool overwrite;
};
}
#endif
<commit_msg>visual tests: apply constness<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef RENDERER_HPP
#define RENDERER_HPP
#include "compare_images.hpp"
// stl
#include <sstream>
#include <iomanip>
#include <fstream>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_renderer.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif
#if defined(SVG_RENDERER)
#include <mapnik/svg/output/svg_renderer.hpp>
#endif
// boost
#include <boost/filesystem.hpp>
namespace visual_tests
{
template <typename ImageType>
struct renderer_base
{
using image_type = ImageType;
static constexpr const char * ext = ".png";
unsigned compare(image_type const & actual, boost::filesystem::path const& reference) const
{
return compare_images(actual, reference.string());
}
void save(image_type const & image, boost::filesystem::path const& path) const
{
mapnik::save_to_file(image, path.string(), "png32");
}
};
struct agg_renderer : renderer_base<mapnik::image_rgba8>
{
static constexpr const char * name = "agg";
image_type render(mapnik::Map const & map, double scale_factor) const
{
image_type image(map.width(), map.height());
mapnik::agg_renderer<image_type> ren(map, image, scale_factor);
ren.apply();
return image;
}
};
#if defined(HAVE_CAIRO)
struct cairo_renderer : renderer_base<mapnik::image_rgba8>
{
static constexpr const char * name = "cairo";
image_type render(mapnik::Map const & map, double scale_factor) const
{
mapnik::cairo_surface_ptr image_surface(
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, map.width(), map.height()),
mapnik::cairo_surface_closer());
mapnik::cairo_ptr image_context(mapnik::create_context(image_surface));
mapnik::cairo_renderer<mapnik::cairo_ptr> ren(map, image_context, scale_factor);
ren.apply();
image_type image(map.width(), map.height());
mapnik::cairo_image_to_rgba8(image, image_surface);
return image;
}
};
#endif
#if defined(SVG_RENDERER)
struct svg_renderer : renderer_base<std::string>
{
static constexpr const char * name = "svg";
static constexpr const char * ext = ".svg";
image_type render(mapnik::Map const & map, double scale_factor) const
{
std::stringstream ss;
std::ostream_iterator<char> output_stream_iterator(ss);
mapnik::svg_renderer<std::ostream_iterator<char>> ren(map, output_stream_iterator, scale_factor);
ren.apply();
return ss.str();
}
unsigned compare(image_type const & actual, boost::filesystem::path const& reference) const
{
std::ifstream stream(reference.string().c_str(),std::ios_base::in|std::ios_base::binary);
if (!stream.is_open())
{
throw std::runtime_error("could not open: '" + reference.string() + "'");
}
std::string expected(std::istreambuf_iterator<char>(stream.rdbuf()),(std::istreambuf_iterator<char>()));
stream.close();
return std::fabs(actual.size() - expected.size());
}
void save(image_type const & image, boost::filesystem::path const& path) const
{
std::ofstream file(path.string().c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if (!file) {
throw std::runtime_error((std::string("cannot open file for writing file ") + path.string()).c_str());
} else {
file << image;
file.close();
}
}
};
#endif
struct grid_renderer : renderer_base<mapnik::image_gray8>
{
static constexpr const char * name = "grid";
image_type render(mapnik::Map const & map, double scale_factor) const
{
image_type image(map.width(), map.height());
// TODO: Render grid here.
return image;
}
};
template <typename Renderer>
class renderer
{
public:
renderer(boost::filesystem::path const & output_dir, boost::filesystem::path const & reference_dir, bool overwrite)
: ren(), output_dir(output_dir), reference_dir(reference_dir), overwrite(overwrite)
{
}
result test(std::string const & name, mapnik::Map const & map, double scale_factor) const
{
typename Renderer::image_type image(ren.render(map, scale_factor));
boost::filesystem::path reference = reference_dir / image_file_name(name, map.width(), map.height(), scale_factor, true, Renderer::ext);
bool reference_exists = boost::filesystem::exists(reference);
result res;
res.state = reference_exists ? STATE_OK : STATE_OVERWRITE;
res.name = name;
res.renderer_name = Renderer::name;
res.scale_factor = scale_factor;
res.size = map_size(map.width(), map.height());
res.reference_image_path = reference;
res.diff = reference_exists ? ren.compare(image, reference) : 0;
if (res.diff)
{
boost::filesystem::create_directories(output_dir);
boost::filesystem::path path = output_dir / image_file_name(name, map.width(), map.height(), scale_factor, false, Renderer::ext);
res.actual_image_path = path;
res.state = STATE_FAIL;
ren.save(image, path);
}
if ((res.diff && overwrite) || !reference_exists)
{
ren.save(image, reference);
res.state = STATE_OVERWRITE;
}
return res;
}
private:
std::string image_file_name(std::string const & test_name,
double width,
double height,
double scale_factor,
bool reference,
std::string const& ext) const
{
std::stringstream s;
s << test_name << '-' << width << '-' << height << '-'
<< std::fixed << std::setprecision(1) << scale_factor
<< '-' << Renderer::name << (reference ? "-reference" : "") << ext;
return s.str();
}
const Renderer ren;
boost::filesystem::path const & output_dir;
boost::filesystem::path const & reference_dir;
const bool overwrite;
};
}
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////
// Copyright (c) 2011 - Hiairrassary Victor
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Console.hpp"
#include <exception>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <functional>
namespace plt
{
Console::Console
(
) :
m_enabled(false)
{
std::function<std::string()> function = std::bind(&Console::getCommands, this);
registerCommand("?", function);
}
void Console::sendChar(char Character)
{
// Si la console n'est pas active on ne traite pas le caractère
if (!m_enabled)
return;
// Traitement du caractère
switch (Character)
{
// Saut de ligne : on traite la commande et on efface la ligne
case '\n' :
case '\r' :
if (!m_current.empty())
{
processCurrent();
m_current.clear();
}
break;
// Backspace : on efface le dernier caractère
case '\b' :
if (!m_current.empty())
m_current.erase(m_current.size() - 1);
break;
// Tout le reste : on ajoute le caractère à la ligne courante
default :
m_current += Character;
break;
}
m_view->textChanged(m_current);
}
void Console::setView
(
const std::shared_ptr<ConsoleView> &view
)
{
if(!view)
throw std::runtime_error("The view is an invalid pointer");
m_view = view;
}
std::string Console::getCommands() const
{
std::string list;
for (auto it = m_commands.begin(); it != m_commands.end(); ++it)
list += it->first + " ";
return list;
}
void Console::processCurrent
(
)
{
std::string command;
std::istringstream iss(m_current);
if( !(iss >> command) )
throw std::runtime_error("Error when parsing the command name");
auto it = m_commands.find(command);
if (it != m_commands.end())
{
std::string params;
std::getline(iss, params);
try
{
m_view->commandCalled(
(it->second)->execute(params)
);
}
catch (const std::exception &e)
{
m_view->error( e.what() );
}
}
else
m_view->error("Commande \"" + command + "\" inconnue");
}
void Console::enable
(
bool state
)
{
m_enabled = state;
m_view->show(state);
}
bool Console::isEnable
(
) const
{
return m_enabled;
}
} // namespace plt
<commit_msg>Traduction en anglais d'une erreur en français<commit_after>////////////////////////////////////////////////////////////
// Copyright (c) 2011 - Hiairrassary Victor
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Console.hpp"
#include <exception>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <functional>
namespace plt
{
Console::Console
(
) :
m_enabled(false)
{
std::function<std::string()> function = std::bind(&Console::getCommands, this);
registerCommand("?", function);
}
void Console::sendChar(char Character)
{
// Si la console n'est pas active on ne traite pas le caractère
if (!m_enabled)
return;
// Traitement du caractère
switch (Character)
{
// Saut de ligne : on traite la commande et on efface la ligne
case '\n' :
case '\r' :
if (!m_current.empty())
{
processCurrent();
m_current.clear();
}
break;
// Backspace : on efface le dernier caractère
case '\b' :
if (!m_current.empty())
m_current.erase(m_current.size() - 1);
break;
// Tout le reste : on ajoute le caractère à la ligne courante
default :
m_current += Character;
break;
}
m_view->textChanged(m_current);
}
void Console::setView
(
const std::shared_ptr<ConsoleView> &view
)
{
if(!view)
throw std::runtime_error("The view is an invalid pointer");
m_view = view;
}
std::string Console::getCommands() const
{
std::string list;
for (auto it = m_commands.begin(); it != m_commands.end(); ++it)
list += it->first + " ";
return list;
}
void Console::processCurrent
(
)
{
std::string command;
std::istringstream iss(m_current);
if( !(iss >> command) )
throw std::runtime_error("Error when parsing the command name");
auto it = m_commands.find(command);
if (it != m_commands.end())
{
std::string params;
std::getline(iss, params);
try
{
m_view->commandCalled(
(it->second)->execute(params)
);
}
catch (const std::exception &e)
{
m_view->error( e.what() );
}
}
else
m_view->error("Unknown command : \"" + command);
}
void Console::enable
(
bool state
)
{
m_enabled = state;
m_view->show(state);
}
bool Console::isEnable
(
) const
{
return m_enabled;
}
} // namespace plt
<|endoftext|> |
<commit_before>#include <iostream>
#include "compressedarray.h"
#include "test_utils.h"
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestCompressedArray
#include <boost/test/unit_test.hpp>
template<int N, class T>
void testCompressedArray(typename vigra::MultiArray<N,T>::difference_type dataShape)
{
vigra::MultiArray<N,T> theData(dataShape);
FillRandom<T, typename vigra::MultiArray<N,T>::iterator>::fillRandom(theData.begin(), theData.end());
typedef CompressedArray<N, T> CA;
//std::cout << "read" << std::endl;
//read
CA ca(theData);
BOOST_CHECK(!ca.isDirty());
BOOST_CHECK(!ca.isCompressed());
BOOST_CHECK_EQUAL(ca.compressedSize(), 0);
BOOST_CHECK_EQUAL(ca.shape(), theData.shape());
vigra::MultiArray<N,T> r(dataShape);
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
//std::cout << "compress & uncompress" << std::endl;
//compress & uncompress
ca.compress();
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
BOOST_CHECK(ca.isCompressed());
BOOST_CHECK(ca.compressedSize() > 0);
ca.uncompress();
BOOST_CHECK(ca.compressedSize() > 0);
BOOST_CHECK(!ca.isCompressed());
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
//std::cout << "compress & read" << std::endl;
//compress and read
ca.compress();
BOOST_CHECK(ca.isCompressed());
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
//std::cout << "copy-construct" << std::endl;
//copy-construct
{
CA ca2(ca);
vigra::MultiArray<N,T> r1(dataShape);
vigra::MultiArray<N,T> r2(dataShape);
ca.readArray(r1);
ca2.readArray(r2);
BOOST_CHECK(arraysEqual(r1, r2));
}
//std::cout << "assignment" << std::endl;
//assignment
{
CA ca2;
ca2 = ca;
vigra::MultiArray<N,T> r1(dataShape);
vigra::MultiArray<N,T> r2(dataShape);
ca.readArray(r1);
ca2.readArray(r2);
BOOST_CHECK(arraysEqual(r1, r2));
}
BOOST_CHECK(!ca.isDirty());
ca.setDirty(true);
BOOST_CHECK(ca.isDirty());
{
vigra::MultiArray<N,T> toWrite(ca.shape());
std::fill(toWrite.begin(), toWrite.end(), 42);
ca.writeArray(typename CA::difference_type(), ca.shape(), toWrite);
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(r, toWrite));
}
ca.compress();
{
vigra::MultiArray<N,T> toWrite(ca.shape());
std::fill(toWrite.begin(), toWrite.end(), 42);
ca.writeArray(typename CA::difference_type(), ca.shape(), toWrite);
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(r, toWrite));
}
}
BOOST_AUTO_TEST_CASE( testDim1 ) {
testCompressedArray<1, vigra::UInt8 >(vigra::Shape1(20));
testCompressedArray<1, vigra::UInt16>(vigra::Shape1(20));
testCompressedArray<1, vigra::UInt32>(vigra::Shape1(20));
testCompressedArray<1, vigra::UInt64>(vigra::Shape1(20));
testCompressedArray<1, vigra::Int32 >(vigra::Shape1(20));
testCompressedArray<1, float >(vigra::Shape1(20));
testCompressedArray<1, vigra::Int64 >(vigra::Shape1(20));
}
BOOST_AUTO_TEST_CASE( testDim2 ) {
testCompressedArray<2, vigra::UInt8 >(vigra::Shape2(20,30));
testCompressedArray<2, vigra::UInt32>(vigra::Shape2(20,30));
testCompressedArray<2, float >(vigra::Shape2(20,30));
testCompressedArray<2, vigra::Int64 >(vigra::Shape2(20,30));
}
BOOST_AUTO_TEST_CASE( testDim3 ) {
testCompressedArray<3, vigra::UInt8 >(vigra::Shape3(20,30,40));
testCompressedArray<3, vigra::UInt32>(vigra::Shape3(20,30,40));
testCompressedArray<3, float >(vigra::Shape3(20,30,40));
testCompressedArray<3, vigra::Int64 >(vigra::Shape3(20,30,40));
}
BOOST_AUTO_TEST_CASE( testDim5 ) {
testCompressedArray<5, vigra::UInt8 >(vigra::Shape5(2,20,30,4,1));
testCompressedArray<5, vigra::UInt32>(vigra::Shape5(2,20,30,4,1));
testCompressedArray<5, float >(vigra::Shape5(2,20,30,4,1));
testCompressedArray<5, vigra::Int64 >(vigra::Shape5(2,20,30,4,1));
}
<commit_msg>minor cleanups + minor additional tests<commit_after>#include <iostream>
#include "compressedarray.h"
#include "test_utils.h"
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestCompressedArray
#include <boost/test/unit_test.hpp>
template<int N, class T>
void testCompressedArray(typename vigra::MultiArray<N,T>::difference_type dataShape)
{
vigra::MultiArray<N,T> theData(dataShape);
FillRandom<T, typename vigra::MultiArray<N,T>::iterator>::fillRandom(theData.begin(), theData.end());
typedef CompressedArray<N, T> CA;
{
CA e; //empty
BOOST_CHECK(!e.isCompressed());
BOOST_CHECK_EQUAL(e.compressedSize(), 0);
BOOST_CHECK(!e.isDirty());
}
//std::cout << "construct" << std::endl;
CA ca(theData);
BOOST_CHECK(!ca.isDirty());
BOOST_CHECK(!ca.isCompressed());
BOOST_CHECK_EQUAL(ca.compressedSize(), 0);
BOOST_CHECK_EQUAL(ca.shape(), theData.shape());
//std::cout << "read" << std::endl;
vigra::MultiArray<N,T> r(dataShape);
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
//std::cout << "compress & uncompress" << std::endl;
ca.compress();
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
BOOST_CHECK(ca.isCompressed());
BOOST_CHECK(ca.compressedSize() > 0);
ca.uncompress();
BOOST_CHECK(ca.compressedSize() > 0);
BOOST_CHECK(!ca.isCompressed());
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
//std::cout << "compress & read" << std::endl;
ca.compress();
BOOST_CHECK(ca.isCompressed());
ca.readArray(r);
BOOST_CHECK(arraysEqual(theData, r));
//std::cout << "copy-construct" << std::endl;
{
CA ca2(ca);
vigra::MultiArray<N,T> r1(dataShape);
vigra::MultiArray<N,T> r2(dataShape);
ca.readArray(r1);
ca2.readArray(r2);
BOOST_CHECK(arraysEqual(r1, r2));
}
//std::cout << "assignment" << std::endl;
{
CA ca2;
ca2 = ca;
vigra::MultiArray<N,T> r1(dataShape);
vigra::MultiArray<N,T> r2(dataShape);
ca.readArray(r1);
ca2.readArray(r2);
BOOST_CHECK(arraysEqual(r1, r2));
}
BOOST_CHECK(!ca.isDirty());
ca.setDirty(true);
BOOST_CHECK(ca.isDirty());
{
vigra::MultiArray<N,T> toWrite(ca.shape());
std::fill(toWrite.begin(), toWrite.end(), 42);
ca.writeArray(typename CA::difference_type(), ca.shape(), toWrite);
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(r, toWrite));
}
ca.compress();
{
vigra::MultiArray<N,T> toWrite(ca.shape());
std::fill(toWrite.begin(), toWrite.end(), 42);
ca.writeArray(typename CA::difference_type(), ca.shape(), toWrite);
std::fill(r.begin(), r.end(), 0);
ca.readArray(r);
BOOST_CHECK(arraysEqual(r, toWrite));
}
}
BOOST_AUTO_TEST_CASE( testDim1 ) {
testCompressedArray<1, vigra::UInt8 >(vigra::Shape1(20));
testCompressedArray<1, vigra::UInt16>(vigra::Shape1(20));
testCompressedArray<1, vigra::UInt32>(vigra::Shape1(20));
testCompressedArray<1, vigra::UInt64>(vigra::Shape1(20));
testCompressedArray<1, vigra::Int32 >(vigra::Shape1(20));
testCompressedArray<1, float >(vigra::Shape1(20));
testCompressedArray<1, vigra::Int64 >(vigra::Shape1(20));
}
BOOST_AUTO_TEST_CASE( testDim2 ) {
testCompressedArray<2, vigra::UInt8 >(vigra::Shape2(20,30));
testCompressedArray<2, vigra::UInt32>(vigra::Shape2(20,30));
testCompressedArray<2, float >(vigra::Shape2(20,30));
testCompressedArray<2, vigra::Int64 >(vigra::Shape2(20,30));
}
BOOST_AUTO_TEST_CASE( testDim3 ) {
testCompressedArray<3, vigra::UInt8 >(vigra::Shape3(20,30,40));
testCompressedArray<3, vigra::UInt32>(vigra::Shape3(20,30,40));
testCompressedArray<3, float >(vigra::Shape3(20,30,40));
testCompressedArray<3, vigra::Int64 >(vigra::Shape3(20,30,40));
}
BOOST_AUTO_TEST_CASE( testDim5 ) {
testCompressedArray<5, vigra::UInt8 >(vigra::Shape5(2,20,30,4,1));
testCompressedArray<5, vigra::UInt32>(vigra::Shape5(2,20,30,4,1));
testCompressedArray<5, float >(vigra::Shape5(2,20,30,4,1));
testCompressedArray<5, vigra::Int64 >(vigra::Shape5(2,20,30,4,1));
}
<|endoftext|> |
<commit_before>#include "UnitTest++/UnitTestPP.h"
#include "RecordingReporter.h"
#include "UnitTest++/ReportAssert.h"
#include "UnitTest++/TestList.h"
#include "UnitTest++/TimeHelpers.h"
#include "UnitTest++/TimeConstraint.h"
#include "UnitTest++/ReportAssertImpl.h"
using namespace UnitTest;
namespace
{
struct MockTest : public Test
{
MockTest(char const* testName, bool const success_, bool const assert_, int const count_ = 1)
: Test(testName)
, success(success_)
, asserted(assert_)
, count(count_)
{
}
virtual void RunImpl() const
{
TestResults& testResults_ = *CurrentTest::Results();
for (int i=0; i < count; ++i)
{
if (asserted)
ReportAssert("desc", "file", 0);
else if (!success)
testResults_.OnTestFailure(m_details, "message");
}
}
bool const success;
bool const asserted;
int const count;
};
struct FixtureBase {
explicit FixtureBase() : runner(reporter) { }
template <class Predicate>
int RunTestsIf(TestList const& list, char const* suiteName,
const Predicate& predicate, int maxTestTimeInMs)
{
TestResults* oldResults = CurrentTest::Results();
const TestDetails* oldDetails = CurrentTest::Details();
int result = runner.RunTestsIf(list, suiteName, predicate, maxTestTimeInMs);
CurrentTest::Results() = oldResults;
CurrentTest::Details() = oldDetails;
return result;
}
TestRunner runner;
RecordingReporter reporter;
};
struct TestRunnerFixture : public FixtureBase
{
TestList list;
};
TEST_FIXTURE(TestRunnerFixture, TestStartIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestFinishIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testFinishedCount);
CHECK_EQUAL("goodtest", reporter.lastFinishedTest);
}
class SlowTest : public Test
{
public:
SlowTest() : Test("slow", "somesuite", "filename", 123) {}
virtual void RunImpl() const
{
TimeHelpers::SleepMs(20);
}
};
TEST_FIXTURE(TestRunnerFixture, TestFinishIsCalledWithCorrectTime)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK(reporter.lastFinishedTestTime >= 0.005f && reporter.lastFinishedTestTime <= 0.050f);
}
TEST_FIXTURE(TestRunnerFixture, FailureCountIsZeroWhenNoTestsAreRun)
{
CHECK_EQUAL(0, RunTestsIf(list, NULL, True(), 0));
CHECK_EQUAL(0, reporter.testRunCount);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, CallsReportFailureOncePerFailingTest)
{
MockTest test1("test", false, false);
list.Add(&test1);
MockTest test2("test", true, false);
list.Add(&test2);
MockTest test3("test", false, false);
list.Add(&test3);
CHECK_EQUAL(2, RunTestsIf(list, NULL, True(), 0));
CHECK_EQUAL(2, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, TestsThatAssertAreReportedAsFailing)
{
MockTest test("test", true, true);
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfTestCount)
{
MockTest test1("test", true, false);
MockTest test2("test", true, false);
MockTest test3("test", true, false);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(3, reporter.summaryTotalTestCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailedTests)
{
MockTest test1("test", false, false, 2);
MockTest test2("test", true, false);
MockTest test3("test", false, false, 3);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(2, reporter.summaryFailedTestCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailures)
{
MockTest test1("test", false, false, 2);
MockTest test2("test", true, false);
MockTest test3("test", false, false, 3);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(5, reporter.summaryFailureCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestPassesForHighTimeThreshold)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestFailsForLowTimeThreshold)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 3);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestHasCorrectFailureInformation)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 3);
using namespace std;
CHECK_EQUAL(test.m_details.testName, reporter.lastFailedTest);
CHECK(strstr(test.m_details.filename, reporter.lastFailedFile));
CHECK_EQUAL(test.m_details.lineNumber, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedMessage, "Global time constraint failed"));
CHECK(strstr(reporter.lastFailedMessage, "3ms"));
}
TEST_FIXTURE(TestRunnerFixture, SlowTestWithTimeExemptionPasses)
{
class SlowExemptedTest : public Test
{
public:
SlowExemptedTest() : Test("slowexempted", "", 0) {}
virtual void RunImpl() const
{
UNITTEST_TIME_CONSTRAINT_EXEMPT();
TimeHelpers::SleepMs(20);
}
};
SlowExemptedTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 3);
CHECK_EQUAL(0, reporter.testFailedCount);
}
struct TestSuiteFixture : FixtureBase
{
TestSuiteFixture()
: test1("TestInDefaultSuite")
, test2("TestInOtherSuite", "OtherSuite")
, test3("SecondTestInDefaultSuite")
{
list.Add(&test1);
list.Add(&test2);
}
Test test1;
Test test2;
Test test3;
TestList list;
};
TEST_FIXTURE(TestSuiteFixture, TestRunnerRunsAllSuitesIfNullSuiteIsPassed)
{
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(2, reporter.summaryTotalTestCount);
}
TEST_FIXTURE(TestSuiteFixture,TestRunnerRunsOnlySpecifiedSuite)
{
RunTestsIf(list, "OtherSuite", True(), 0);
CHECK_EQUAL(1, reporter.summaryTotalTestCount);
CHECK_EQUAL("TestInOtherSuite", reporter.lastFinishedTest);
}
struct RunTestIfNameIs
{
RunTestIfNameIs(char const* name_)
: name(name_)
{
}
bool operator()(const Test* const test) const
{
using namespace std;
return (0 == strcmp(test->m_details.testName, name));
}
char const* name;
};
TEST(TestMockPredicateBehavesCorrectly)
{
RunTestIfNameIs predicate("pass");
Test pass("pass");
Test fail("fail");
CHECK(predicate(&pass));
CHECK(!predicate(&fail));
}
TEST_FIXTURE(TestRunnerFixture, TestRunnerRunsTestsThatPassPredicate)
{
Test should_run("goodtest");
list.Add(&should_run);
Test should_not_run("badtest");
list.Add(&should_not_run);
RunTestsIf(list, NULL, RunTestIfNameIs("goodtest"), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestRunnerOnlyRunsTestsInSpecifiedSuiteAndThatPassPredicate)
{
Test runningTest1("goodtest", "suite");
Test skippedTest2("goodtest");
Test skippedTest3("badtest", "suite");
Test skippedTest4("badtest");
list.Add(&runningTest1);
list.Add(&skippedTest2);
list.Add(&skippedTest3);
list.Add(&skippedTest4);
RunTestsIf(list, "suite", RunTestIfNameIs("goodtest"), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
CHECK_EQUAL("suite", reporter.lastStartedSuite);
}
}<commit_msg>Reformatted code from #54.<commit_after>#include "UnitTest++/UnitTestPP.h"
#include "RecordingReporter.h"
#include "UnitTest++/ReportAssert.h"
#include "UnitTest++/TestList.h"
#include "UnitTest++/TimeHelpers.h"
#include "UnitTest++/TimeConstraint.h"
#include "UnitTest++/ReportAssertImpl.h"
using namespace UnitTest;
namespace
{
struct MockTest : public Test
{
MockTest(char const* testName, bool const success_, bool const assert_, int const count_ = 1)
: Test(testName)
, success(success_)
, asserted(assert_)
, count(count_)
{
}
virtual void RunImpl() const
{
TestResults& testResults_ = *CurrentTest::Results();
for (int i=0; i < count; ++i)
{
if (asserted)
{
ReportAssert("desc", "file", 0);
}
else if (!success)
{
testResults_.OnTestFailure(m_details, "message");
}
}
}
bool const success;
bool const asserted;
int const count;
};
struct FixtureBase
{
FixtureBase()
: runner(reporter)
{
}
template <class Predicate>
int RunTestsIf(TestList const& list, char const* suiteName,
const Predicate& predicate, int maxTestTimeInMs)
{
TestResults* oldResults = CurrentTest::Results();
const TestDetails* oldDetails = CurrentTest::Details();
int result = runner.RunTestsIf(list, suiteName, predicate, maxTestTimeInMs);
CurrentTest::Results() = oldResults;
CurrentTest::Details() = oldDetails;
return result;
}
TestRunner runner;
RecordingReporter reporter;
};
struct TestRunnerFixture : public FixtureBase
{
TestList list;
};
TEST_FIXTURE(TestRunnerFixture, TestStartIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestFinishIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testFinishedCount);
CHECK_EQUAL("goodtest", reporter.lastFinishedTest);
}
class SlowTest : public Test
{
public:
SlowTest()
: Test("slow", "somesuite", "filename", 123)
{
}
virtual void RunImpl() const
{
TimeHelpers::SleepMs(20);
}
};
TEST_FIXTURE(TestRunnerFixture, TestFinishIsCalledWithCorrectTime)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK(reporter.lastFinishedTestTime >= 0.005f && reporter.lastFinishedTestTime <= 0.050f);
}
TEST_FIXTURE(TestRunnerFixture, FailureCountIsZeroWhenNoTestsAreRun)
{
CHECK_EQUAL(0, RunTestsIf(list, NULL, True(), 0));
CHECK_EQUAL(0, reporter.testRunCount);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, CallsReportFailureOncePerFailingTest)
{
MockTest test1("test", false, false);
list.Add(&test1);
MockTest test2("test", true, false);
list.Add(&test2);
MockTest test3("test", false, false);
list.Add(&test3);
CHECK_EQUAL(2, RunTestsIf(list, NULL, True(), 0));
CHECK_EQUAL(2, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, TestsThatAssertAreReportedAsFailing)
{
MockTest test("test", true, true);
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfTestCount)
{
MockTest test1("test", true, false);
MockTest test2("test", true, false);
MockTest test3("test", true, false);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(3, reporter.summaryTotalTestCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailedTests)
{
MockTest test1("test", false, false, 2);
MockTest test2("test", true, false);
MockTest test3("test", false, false, 3);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(2, reporter.summaryFailedTestCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailures)
{
MockTest test1("test", false, false, 2);
MockTest test2("test", true, false);
MockTest test3("test", false, false, 3);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(5, reporter.summaryFailureCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestPassesForHighTimeThreshold)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestFailsForLowTimeThreshold)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 3);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestHasCorrectFailureInformation)
{
SlowTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 3);
using namespace std;
CHECK_EQUAL(test.m_details.testName, reporter.lastFailedTest);
CHECK(strstr(test.m_details.filename, reporter.lastFailedFile));
CHECK_EQUAL(test.m_details.lineNumber, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedMessage, "Global time constraint failed"));
CHECK(strstr(reporter.lastFailedMessage, "3ms"));
}
TEST_FIXTURE(TestRunnerFixture, SlowTestWithTimeExemptionPasses)
{
class SlowExemptedTest : public Test
{
public:
SlowExemptedTest() : Test("slowexempted", "", 0) {}
virtual void RunImpl() const
{
UNITTEST_TIME_CONSTRAINT_EXEMPT();
TimeHelpers::SleepMs(20);
}
};
SlowExemptedTest test;
list.Add(&test);
RunTestsIf(list, NULL, True(), 3);
CHECK_EQUAL(0, reporter.testFailedCount);
}
struct TestSuiteFixture : FixtureBase
{
TestSuiteFixture()
: test1("TestInDefaultSuite")
, test2("TestInOtherSuite", "OtherSuite")
, test3("SecondTestInDefaultSuite")
{
list.Add(&test1);
list.Add(&test2);
}
Test test1;
Test test2;
Test test3;
TestList list;
};
TEST_FIXTURE(TestSuiteFixture, TestRunnerRunsAllSuitesIfNullSuiteIsPassed)
{
RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(2, reporter.summaryTotalTestCount);
}
TEST_FIXTURE(TestSuiteFixture,TestRunnerRunsOnlySpecifiedSuite)
{
RunTestsIf(list, "OtherSuite", True(), 0);
CHECK_EQUAL(1, reporter.summaryTotalTestCount);
CHECK_EQUAL("TestInOtherSuite", reporter.lastFinishedTest);
}
struct RunTestIfNameIs
{
RunTestIfNameIs(char const* name_)
: name(name_)
{
}
bool operator()(const Test* const test) const
{
using namespace std;
return (0 == strcmp(test->m_details.testName, name));
}
char const* name;
};
TEST(TestMockPredicateBehavesCorrectly)
{
RunTestIfNameIs predicate("pass");
Test pass("pass");
Test fail("fail");
CHECK(predicate(&pass));
CHECK(!predicate(&fail));
}
TEST_FIXTURE(TestRunnerFixture, TestRunnerRunsTestsThatPassPredicate)
{
Test should_run("goodtest");
list.Add(&should_run);
Test should_not_run("badtest");
list.Add(&should_not_run);
RunTestsIf(list, NULL, RunTestIfNameIs("goodtest"), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestRunnerOnlyRunsTestsInSpecifiedSuiteAndThatPassPredicate)
{
Test runningTest1("goodtest", "suite");
Test skippedTest2("goodtest");
Test skippedTest3("badtest", "suite");
Test skippedTest4("badtest");
list.Add(&runningTest1);
list.Add(&skippedTest2);
list.Add(&skippedTest3);
list.Add(&skippedTest4);
RunTestsIf(list, "suite", RunTestIfNameIs("goodtest"), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
CHECK_EQUAL("suite", reporter.lastStartedSuite);
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ConfigurationAccess.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: iha $ $Date: 2003-12-10 18:11:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ConfigurationAccess.hxx"
#include "macros.hxx"
// header for class SvtSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
// header for class ConfigItem
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
namespace
{
bool lcl_IsMetric()
{
SvtSysLocale aSysLocale;
const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();
MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();
return ( eSys == MEASURE_METRIC );
}
}//end anonymous namespace
class CalcConfigItem : public ::utl::ConfigItem
{
public:
CalcConfigItem();
virtual ~CalcConfigItem();
FieldUnit getFieldUnit();
};
CalcConfigItem::CalcConfigItem()
: ConfigItem( ::rtl::OUString( C2U( "Office.Calc/Layout" )))
{
}
CalcConfigItem::~CalcConfigItem()
{
}
FieldUnit CalcConfigItem::getFieldUnit()
{
FieldUnit eResult( FUNIT_CM );
uno::Sequence< ::rtl::OUString > aNames( 1 );
if( lcl_IsMetric() )
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/Metric" ));
else
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/NonMetric" ));
uno::Sequence< uno::Any > aResult( GetProperties( aNames ));
sal_Int32 nValue;
if( aResult[ 0 ] >>= nValue )
eResult = static_cast< FieldUnit >( nValue );
return eResult;
}
ConfigurationAccess::ConfigurationAccess()
: m_pCalcConfigItem(0)
{
m_pCalcConfigItem = new CalcConfigItem();
}
ConfigurationAccess::~ConfigurationAccess()
{
delete m_pCalcConfigItem;
}
FieldUnit ConfigurationAccess::getFieldUnit()
{
FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );
return aUnit;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.110); FILE MERGED 2005/09/05 18:42:44 rt 1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConfigurationAccess.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:34:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "ConfigurationAccess.hxx"
#include "macros.hxx"
// header for class SvtSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
// header for class ConfigItem
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
namespace
{
bool lcl_IsMetric()
{
SvtSysLocale aSysLocale;
const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();
MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();
return ( eSys == MEASURE_METRIC );
}
}//end anonymous namespace
class CalcConfigItem : public ::utl::ConfigItem
{
public:
CalcConfigItem();
virtual ~CalcConfigItem();
FieldUnit getFieldUnit();
};
CalcConfigItem::CalcConfigItem()
: ConfigItem( ::rtl::OUString( C2U( "Office.Calc/Layout" )))
{
}
CalcConfigItem::~CalcConfigItem()
{
}
FieldUnit CalcConfigItem::getFieldUnit()
{
FieldUnit eResult( FUNIT_CM );
uno::Sequence< ::rtl::OUString > aNames( 1 );
if( lcl_IsMetric() )
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/Metric" ));
else
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/NonMetric" ));
uno::Sequence< uno::Any > aResult( GetProperties( aNames ));
sal_Int32 nValue;
if( aResult[ 0 ] >>= nValue )
eResult = static_cast< FieldUnit >( nValue );
return eResult;
}
ConfigurationAccess::ConfigurationAccess()
: m_pCalcConfigItem(0)
{
m_pCalcConfigItem = new CalcConfigItem();
}
ConfigurationAccess::~ConfigurationAccess()
{
delete m_pCalcConfigItem;
}
FieldUnit ConfigurationAccess::getFieldUnit()
{
FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );
return aUnit;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BarChartTypeTemplate.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 11:59:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "BarChartTypeTemplate.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "ContainerHelper.hxx"
#include "DataSeriesHelper.hxx"
#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_DATAPOINTGEOMETRY3D_HPP_
#include <com/sun/star/chart2/DataPointGeometry3D.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::beans::Property;
using ::osl::MutexGuard;
using ::rtl::OUString;
namespace
{
static const OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.BarChartTypeTemplate" ));
enum
{
PROP_BAR_TEMPLATE_DIMENSION,
PROP_BAR_TEMPLATE_GEOMETRY3D
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "Dimension" ),
PROP_BAR_TEMPLATE_DIMENSION,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "Geometry3D" ),
PROP_BAR_TEMPLATE_GEOMETRY3D,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::tPropertyValueMap & rOutMap )
{
::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_BAR_TEMPLATE_DIMENSION, 2 );
::chart::PropertyHelper::setPropertyValueDefault( rOutMap, PROP_BAR_TEMPLATE_GEOMETRY3D, ::chart2::DataPointGeometry3D::CUBOID );
}
const Sequence< Property > & lcl_GetPropertySequence()
{
static Sequence< Property > aPropSeq;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
}
return aPropSeq;
}
::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper(
lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
} // anonymous namespace
namespace chart
{
BarChartTypeTemplate::BarChartTypeTemplate(
Reference<
uno::XComponentContext > const & xContext,
const OUString & rServiceName,
StackMode eStackMode,
BarDirection eDirection,
sal_Int32 nDim /* = 2 */ ) :
ChartTypeTemplate( xContext, rServiceName ),
::property::OPropertySet( m_aMutex ),
m_eStackMode( eStackMode ),
m_eBarDirection( eDirection ),
m_nDim( nDim )
{}
BarChartTypeTemplate::~BarChartTypeTemplate()
{}
sal_Int32 BarChartTypeTemplate::getDimension() const
{
return m_nDim;
}
StackMode BarChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
return m_eStackMode;
}
bool BarChartTypeTemplate::isSwapXAndY() const
{
return (m_eBarDirection == HORIZONTAL);
}
// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL BarChartTypeTemplate::matchesTemplate(
const Reference< chart2::XDiagram >& xDiagram,
sal_Bool bAdaptProperties )
throw (uno::RuntimeException)
{
sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );
//check BarDirection
if( bResult )
{
bool bFound = false;
bool bAmbiguous = false;
bool bVertical = DiagramHelper::getVertical( xDiagram, bFound, bAmbiguous );
if( m_eBarDirection == HORIZONTAL )
bResult = sal_Bool( bVertical );
else if( m_eBarDirection == VERTICAL )
bResult = sal_Bool( !bVertical );
}
// adapt solid-type of template according to values in series
if( bAdaptProperties &&
bResult &&
getDimension() == 3 )
{
::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
DiagramHelper::getDataSeriesFromDiagram( xDiagram ));
sal_Int32 aCommonGeom( 0 );
bool bGeomFound = false, bAdaptGeom = false;
for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt =
aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt )
{
try
{
sal_Int32 aGeom = 0;
Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW );
if( xProp->getPropertyValue( C2U( "Geometry3D" )) >>= aGeom )
{
if( ! bGeomFound )
{
// first series
aCommonGeom = aGeom;
bGeomFound = true;
bAdaptGeom = true;
}
else
{
// further series: compare for uniqueness
if( aCommonGeom != aGeom )
{
bAdaptGeom = false;
break;
}
}
}
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
if( bAdaptGeom )
{
setFastPropertyValue_NoBroadcast(
PROP_BAR_TEMPLATE_GEOMETRY3D, uno::makeAny( aCommonGeom ));
}
}
return bResult;
}
Reference< chart2::XChartType > BarChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
Reference< chart2::XChartType > xResult;
try
{
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
xResult.set( xFact->createInstance(
CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY_THROW );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return xResult;
}
Reference< chart2::XChartType > SAL_CALL BarChartTypeTemplate::getChartTypeForNewSeries(
const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
throw (uno::RuntimeException)
{
Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
return xResult;
}
// ____ OPropertySet ____
uno::Any BarChartTypeTemplate::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
// initialize defaults
lcl_AddDefaultsToMap( aStaticDefaults );
}
tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
::cppu::IPropertyArrayHelper & SAL_CALL BarChartTypeTemplate::getInfoHelper()
{
return lcl_getInfoHelper();
}
// ____ XPropertySet ____
Reference< beans::XPropertySetInfo > SAL_CALL
BarChartTypeTemplate::getPropertySetInfo()
throw (uno::RuntimeException)
{
static Reference< beans::XPropertySetInfo > xInfo;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
void SAL_CALL BarChartTypeTemplate::applyStyle(
const Reference< chart2::XDataSeries >& xSeries,
::sal_Int32 nChartTypeIndex,
::sal_Int32 nSeriesIndex,
::sal_Int32 nSeriesCount )
throw (uno::RuntimeException)
{
ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );
if( getDimension() == 3 )
{
try
{
//apply Geometry3D
uno::Any aAGeometry3D;
this->getFastPropertyValue( aAGeometry3D, PROP_BAR_TEMPLATE_GEOMETRY3D );
DataSeriesHelper::setPropertyAlsoToAllAttributedDataPoints( xSeries, C2U( "Geometry3D" ), aAGeometry3D );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
}
void SAL_CALL BarChartTypeTemplate::resetStyles(
const Reference< chart2::XDiagram >& xDiagram )
throw (uno::RuntimeException)
{
ChartTypeTemplate::resetStyles( xDiagram );
if( getDimension() == 3 )
{
::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
DiagramHelper::getDataSeriesFromDiagram( xDiagram ));
uno::Any aLineStyleAny( uno::makeAny( drawing::LineStyle_NONE ));
for( ::std::vector< Reference< chart2::XDataSeries > >::iterator aIt( aSeriesVec.begin());
aIt != aSeriesVec.end(); ++aIt )
{
Reference< beans::XPropertyState > xState( *aIt, uno::UNO_QUERY );
if( xState.is())
{
xState->setPropertyToDefault( C2U("Geometry3D"));
Reference< beans::XPropertySet > xProp( xState, uno::UNO_QUERY );
if( xProp.is() &&
xProp->getPropertyValue( C2U("BorderStyle")) == aLineStyleAny )
{
xState->setPropertyToDefault( C2U("BorderStyle"));
}
}
}
}
DiagramHelper::setVertical( xDiagram, false );
}
void BarChartTypeTemplate::createCoordinateSystems(
const Reference< chart2::XCoordinateSystemContainer > & xCooSysCnt )
{
ChartTypeTemplate::createCoordinateSystems( xCooSysCnt );
Reference< chart2::XDiagram > xDiagram( xCooSysCnt, uno::UNO_QUERY );
DiagramHelper::setVertical( xDiagram, m_eBarDirection == HORIZONTAL );
}
// ----------------------------------------
Sequence< OUString > BarChartTypeTemplate::getSupportedServiceNames_Static()
{
Sequence< OUString > aServices( 2 );
aServices[ 0 ] = lcl_aServiceName;
aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( BarChartTypeTemplate, lcl_aServiceName );
IMPLEMENT_FORWARD_XINTERFACE2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )
} // namespace chart
<commit_msg>INTEGRATION: CWS chart15 (1.11.10); FILE MERGED 2007/12/12 09:51:30 bm 1.11.10.2: RESYNC: (1.11-1.12); FILE MERGED 2007/12/05 13:22:55 bm 1.11.10.1: #i79698# use new helper DiagramHelper::getGeometry3D<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BarChartTypeTemplate.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:02:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "BarChartTypeTemplate.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "ContainerHelper.hxx"
#include "DataSeriesHelper.hxx"
#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_DATAPOINTGEOMETRY3D_HPP_
#include <com/sun/star/chart2/DataPointGeometry3D.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::beans::Property;
using ::osl::MutexGuard;
using ::rtl::OUString;
namespace
{
static const OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.BarChartTypeTemplate" ));
enum
{
PROP_BAR_TEMPLATE_DIMENSION,
PROP_BAR_TEMPLATE_GEOMETRY3D
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "Dimension" ),
PROP_BAR_TEMPLATE_DIMENSION,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "Geometry3D" ),
PROP_BAR_TEMPLATE_GEOMETRY3D,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::tPropertyValueMap & rOutMap )
{
::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_BAR_TEMPLATE_DIMENSION, 2 );
::chart::PropertyHelper::setPropertyValueDefault( rOutMap, PROP_BAR_TEMPLATE_GEOMETRY3D, ::chart2::DataPointGeometry3D::CUBOID );
}
const Sequence< Property > & lcl_GetPropertySequence()
{
static Sequence< Property > aPropSeq;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
}
return aPropSeq;
}
::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper(
lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
} // anonymous namespace
namespace chart
{
BarChartTypeTemplate::BarChartTypeTemplate(
Reference<
uno::XComponentContext > const & xContext,
const OUString & rServiceName,
StackMode eStackMode,
BarDirection eDirection,
sal_Int32 nDim /* = 2 */ ) :
ChartTypeTemplate( xContext, rServiceName ),
::property::OPropertySet( m_aMutex ),
m_eStackMode( eStackMode ),
m_eBarDirection( eDirection ),
m_nDim( nDim )
{}
BarChartTypeTemplate::~BarChartTypeTemplate()
{}
sal_Int32 BarChartTypeTemplate::getDimension() const
{
return m_nDim;
}
StackMode BarChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
return m_eStackMode;
}
bool BarChartTypeTemplate::isSwapXAndY() const
{
return (m_eBarDirection == HORIZONTAL);
}
// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL BarChartTypeTemplate::matchesTemplate(
const Reference< chart2::XDiagram >& xDiagram,
sal_Bool bAdaptProperties )
throw (uno::RuntimeException)
{
sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );
//check BarDirection
if( bResult )
{
bool bFound = false;
bool bAmbiguous = false;
bool bVertical = DiagramHelper::getVertical( xDiagram, bFound, bAmbiguous );
if( m_eBarDirection == HORIZONTAL )
bResult = sal_Bool( bVertical );
else if( m_eBarDirection == VERTICAL )
bResult = sal_Bool( !bVertical );
}
// adapt solid-type of template according to values in series
if( bAdaptProperties &&
bResult &&
getDimension() == 3 )
{
::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
DiagramHelper::getDataSeriesFromDiagram( xDiagram ));
bool bGeomFound = false, bGeomAmbiguous = false;
sal_Int32 aCommonGeom = DiagramHelper::getGeometry3D( xDiagram, bGeomFound, bGeomAmbiguous );
if( !bGeomAmbiguous )
{
setFastPropertyValue_NoBroadcast(
PROP_BAR_TEMPLATE_GEOMETRY3D, uno::makeAny( aCommonGeom ));
}
}
return bResult;
}
Reference< chart2::XChartType > BarChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
Reference< chart2::XChartType > xResult;
try
{
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
xResult.set( xFact->createInstance(
CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY_THROW );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return xResult;
}
Reference< chart2::XChartType > SAL_CALL BarChartTypeTemplate::getChartTypeForNewSeries(
const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
throw (uno::RuntimeException)
{
Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
return xResult;
}
// ____ OPropertySet ____
uno::Any BarChartTypeTemplate::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
// initialize defaults
lcl_AddDefaultsToMap( aStaticDefaults );
}
tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
::cppu::IPropertyArrayHelper & SAL_CALL BarChartTypeTemplate::getInfoHelper()
{
return lcl_getInfoHelper();
}
// ____ XPropertySet ____
Reference< beans::XPropertySetInfo > SAL_CALL
BarChartTypeTemplate::getPropertySetInfo()
throw (uno::RuntimeException)
{
static Reference< beans::XPropertySetInfo > xInfo;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
void SAL_CALL BarChartTypeTemplate::applyStyle(
const Reference< chart2::XDataSeries >& xSeries,
::sal_Int32 nChartTypeIndex,
::sal_Int32 nSeriesIndex,
::sal_Int32 nSeriesCount )
throw (uno::RuntimeException)
{
ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );
if( getDimension() == 3 )
{
try
{
//apply Geometry3D
uno::Any aAGeometry3D;
this->getFastPropertyValue( aAGeometry3D, PROP_BAR_TEMPLATE_GEOMETRY3D );
DataSeriesHelper::setPropertyAlsoToAllAttributedDataPoints( xSeries, C2U( "Geometry3D" ), aAGeometry3D );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
}
void SAL_CALL BarChartTypeTemplate::resetStyles(
const Reference< chart2::XDiagram >& xDiagram )
throw (uno::RuntimeException)
{
ChartTypeTemplate::resetStyles( xDiagram );
if( getDimension() == 3 )
{
::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
DiagramHelper::getDataSeriesFromDiagram( xDiagram ));
uno::Any aLineStyleAny( uno::makeAny( drawing::LineStyle_NONE ));
for( ::std::vector< Reference< chart2::XDataSeries > >::iterator aIt( aSeriesVec.begin());
aIt != aSeriesVec.end(); ++aIt )
{
Reference< beans::XPropertyState > xState( *aIt, uno::UNO_QUERY );
if( xState.is())
{
xState->setPropertyToDefault( C2U("Geometry3D"));
Reference< beans::XPropertySet > xProp( xState, uno::UNO_QUERY );
if( xProp.is() &&
xProp->getPropertyValue( C2U("BorderStyle")) == aLineStyleAny )
{
xState->setPropertyToDefault( C2U("BorderStyle"));
}
}
}
}
DiagramHelper::setVertical( xDiagram, false );
}
void BarChartTypeTemplate::createCoordinateSystems(
const Reference< chart2::XCoordinateSystemContainer > & xCooSysCnt )
{
ChartTypeTemplate::createCoordinateSystems( xCooSysCnt );
Reference< chart2::XDiagram > xDiagram( xCooSysCnt, uno::UNO_QUERY );
DiagramHelper::setVertical( xDiagram, m_eBarDirection == HORIZONTAL );
}
// ----------------------------------------
Sequence< OUString > BarChartTypeTemplate::getSupportedServiceNames_Static()
{
Sequence< OUString > aServices( 2 );
aServices[ 0 ] = lcl_aServiceName;
aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( BarChartTypeTemplate, lcl_aServiceName );
IMPLEMENT_FORWARD_XINTERFACE2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )
} // namespace chart
<|endoftext|> |
<commit_before>//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
/*
* Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
*
* Distributed under 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 <cetty/channel/socket/asio/AsioServicePool.h>
#include <boost/bind.hpp>
#include <cetty/util/Exception.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/channel/socket/asio/AsioService.h>
namespace cetty {
namespace channel {
namespace socket {
namespace asio {
using namespace cetty::logging;
using namespace boost::asio;
class AsioServiceHolder : public EventLoopPool::EventLoopHolder {
public:
enum {
INITIALIZED = 0,
RUNNING = 1,
STOPPED = -1
};
typedef boost::shared_ptr<boost::thread> ThreadPtr;
typedef boost::shared_ptr<boost::asio::io_service::work> WorkPtr;
public:
AsioServiceHolder() : state(INITIALIZED), priority(0) {}
virtual ~AsioServiceHolder() {}
virtual const EventLoopPtr& getEventLoop() const {
return eventLoop;
}
int state;
int priority;
WorkPtr work; /// The work that keeps the io_services running.
ThreadPtr thread;
AsioServicePtr service;
EventLoopPtr eventLoop;
void stop() {
if (state != STOPPED) {
state = STOPPED;
service->stop();
}
}
};
AsioServicePool::AsioServicePool(int threadCnt)
: EventLoopPool(threadCnt),
nextServiceIndex(0) {
// Give all the io_services work to do so that their run() functions will not
// exit until they are explicitly stopped.
for (int i = 0; i < eventLoopCnt; ++i) {
AsioServiceHolder* holder = new AsioServiceHolder();
AsioServicePtr service = new AsioService(shared_from_this());
holder->service = service;
holder->eventLoop = boost::static_pointer_cast<EventLoop>(service);
holder->work = WorkPtr(new io_service::work(service->service()));
eventLoops.push_back(holder);
}
// automatic start
if (!mainThread) {
// Create a pool of threads to run all of the io_services.
for (std::size_t i = 0; i < eventLoops.size(); ++i) {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
holder->thread
= ThreadPtr(new boost::thread(
boost::bind(&AsioServicePool::runIOservice,
this,
holder)));
boost::thread::id id = holder->thread->get_id();
holder->service->setThreadId(id);
allEventLoops.insert(std::make_pair(id, holder->eventLoop));
}
started = true;
}
else {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops.front();
boost::thread::id id = boost::this_thread::get_id();
holder->service->setThreadId(id);
allEventLoops.insert(std::make_pair(id, holder->eventLoop));
}
}
bool AsioServicePool::start() {
if (!started && mainThread) {
LOG_INFO << "AsioServciePool running in main thread mode.";
if (runIOservice((AsioServiceHolder*)eventLoops.front()) < 0) {
LOG_ERROR << "AsioServicePool run the main thread service error.";
return false;
}
}
started = true;
return true;
}
void cetty::channel::socket::asio::AsioServicePool::waitForStop() {
if (mainThread) {
return;
}
// Wait for all threads in the pool to exit.
for (int i = 0; i < eventLoopCnt; ++i) {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
holder->thread->join();
}
}
void AsioServicePool::stop() {
// Explicitly stop all io_services.
for (int i = 0; i < eventLoopCnt; ++i) {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
holder->stop();
}
started = false;
}
const AsioServicePtr& AsioServicePool::getNextService() {
return getNextServiceHolder()->service;
}
int AsioServicePool::runIOservice(AsioServiceHolder* holder) {
BOOST_ASSERT(holder && holder->service && "ioservice can not be NULL.");
AsioServicePtr& service = holder->service;
boost::system::error_code err;
std::size_t opCount = service->service().run(err);
// if error happened, try to recover.
if (err) {
LOG_ERROR << "when runIOservice, the io service has error = " << err.value();
stop();
return -1;
}
LOG_INFO << "runIOservice OK, and " << opCount << "handlers that were executed.";
return opCount;
}
const EventLoopPtr& AsioServicePool::getNextLoop() {
return getNextServiceHolder()->eventLoop;
}
AsioServiceHolder* AsioServicePool::getNextServiceHolder() {
// Only one service.
if (eventLoopCnt == 1) {
return (AsioServiceHolder*)eventLoops.front();
}
// Use a round-robin scheme to choose the next io_service to use.
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[nextServiceIndex];
++nextServiceIndex;
if (nextServiceIndex == eventLoopCnt) {
nextServiceIndex = 0;
}
return holder;
}
}
}
}
}
<commit_msg>在线程启动时候,重新设置thread id<commit_after>//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
/*
* Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
*
* Distributed under 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 <cetty/channel/socket/asio/AsioServicePool.h>
#include <boost/bind.hpp>
#include <cetty/util/Exception.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/channel/socket/asio/AsioService.h>
namespace cetty {
namespace channel {
namespace socket {
namespace asio {
using namespace cetty::logging;
using namespace boost::asio;
class AsioServiceHolder : public EventLoopPool::EventLoopHolder {
public:
enum {
INITIALIZED = 0,
RUNNING = 1,
STOPPED = -1
};
typedef boost::shared_ptr<boost::thread> ThreadPtr;
typedef boost::shared_ptr<boost::asio::io_service::work> WorkPtr;
public:
AsioServiceHolder() : state(INITIALIZED), priority(0) {}
virtual ~AsioServiceHolder() {}
virtual const EventLoopPtr& getEventLoop() const {
return eventLoop;
}
int state;
int priority;
WorkPtr work; /// The work that keeps the io_services running.
ThreadPtr thread;
AsioServicePtr service;
EventLoopPtr eventLoop;
void stop() {
if (state != STOPPED) {
state = STOPPED;
service->stop();
}
}
};
AsioServicePool::AsioServicePool(int threadCnt)
: EventLoopPool(threadCnt),
nextServiceIndex(0) {
// Give all the io_services work to do so that their run() functions will not
// exit until they are explicitly stopped.
for (int i = 0; i < eventLoopCnt; ++i) {
AsioServiceHolder* holder = new AsioServiceHolder();
AsioServicePtr service = new AsioService(shared_from_this());
holder->service = service;
holder->eventLoop = boost::static_pointer_cast<EventLoop>(service);
holder->work = WorkPtr(new io_service::work(service->service()));
eventLoops.push_back(holder);
}
// automatic start
if (!mainThread) {
// Create a pool of threads to run all of the io_services.
for (std::size_t i = 0; i < eventLoops.size(); ++i) {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
holder->thread
= ThreadPtr(new boost::thread(
boost::bind(&AsioServicePool::runIOservice,
this,
holder)));
boost::thread::id id = holder->thread->get_id();
holder->service->setThreadId(id);
allEventLoops.insert(std::make_pair(id, holder->eventLoop));
}
started = true;
}
else {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops.front();
boost::thread::id id = boost::this_thread::get_id();
holder->service->setThreadId(id);
allEventLoops.insert(std::make_pair(id, holder->eventLoop));
}
}
bool AsioServicePool::start() {
if (!started && mainThread) {
LOG_INFO << "AsioServciePool running in main thread mode.";
if (runIOservice((AsioServiceHolder*)eventLoops.front()) < 0) {
LOG_ERROR << "AsioServicePool run the main thread service error.";
return false;
}
}
started = true;
return true;
}
void cetty::channel::socket::asio::AsioServicePool::waitForStop() {
if (mainThread) {
return;
}
// Wait for all threads in the pool to exit.
for (int i = 0; i < eventLoopCnt; ++i) {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
holder->thread->join();
}
}
void AsioServicePool::stop() {
// Explicitly stop all io_services.
for (int i = 0; i < eventLoopCnt; ++i) {
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
holder->stop();
}
started = false;
}
const AsioServicePtr& AsioServicePool::getNextService() {
return getNextServiceHolder()->service;
}
int AsioServicePool::runIOservice(AsioServiceHolder* holder) {
BOOST_ASSERT(holder && holder->service && "ioservice can not be NULL.");
AsioServicePtr& service = holder->service;
service->setThreadId(boost::this_thread::get_id());
boost::system::error_code err;
std::size_t opCount = service->service().run(err);
// if error happened, try to recover.
if (err) {
LOG_ERROR << "when runIOservice, the io service has error = " << err.value();
stop();
return -1;
}
LOG_INFO << "runIOservice OK, and " << opCount << "handlers that were executed.";
return opCount;
}
const EventLoopPtr& AsioServicePool::getNextLoop() {
return getNextServiceHolder()->eventLoop;
}
AsioServiceHolder* AsioServicePool::getNextServiceHolder() {
// Only one service.
if (eventLoopCnt == 1) {
return (AsioServiceHolder*)eventLoops.front();
}
// Use a round-robin scheme to choose the next io_service to use.
AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[nextServiceIndex];
++nextServiceIndex;
if (nextServiceIndex == eventLoopCnt) {
nextServiceIndex = 0;
}
return holder;
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/string_util.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/password_manager/password_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
using webkit_glue::PasswordForm;
using testing::_;
using testing::DoAll;
using ::testing::Exactly;
using ::testing::WithArg;
using ::testing::Return;
class MockPasswordManagerDelegate : public PasswordManager::Delegate {
public:
MOCK_METHOD1(FillPasswordForm, void(
const webkit_glue::PasswordFormDomManager::FillData&));
MOCK_METHOD1(AddSavePasswordInfoBar, void(PasswordFormManager*));
MOCK_METHOD0(GetProfileForPasswordManager, Profile*());
MOCK_METHOD0(DidLastPageLoadEncounterSSLErrors, bool());
};
class TestingProfileWithPasswordStore : public TestingProfile {
public:
explicit TestingProfileWithPasswordStore(PasswordStore* store)
: store_(store) {}
virtual PasswordStore* GetPasswordStore(ServiceAccessType access) {
return store_;
}
private:
PasswordStore* store_;
};
class MockPasswordStore : public PasswordStore {
public:
MOCK_METHOD1(RemoveLogin, void(const PasswordForm&));
MOCK_METHOD0(ReportMetricsImpl void());
MOCK_METHOD2(GetLogins, int(const PasswordForm&, PasswordStoreConsumer*));
MOCK_METHOD1(AddLogin, void(const PasswordForm&));
MOCK_METHOD1(UpdateLogin, void(const PasswordForm&));
MOCK_METHOD1(AddLoginImpl, void(const PasswordForm&));
MOCK_METHOD1(UpdateLoginImpl, void(const PasswordForm&));
MOCK_METHOD1(RemoveLoginImpl, void(const PasswordForm&));
MOCK_METHOD2(RemoveLoginsCreatedBetweenImpl, void(const base::Time&,
const base::Time&));
MOCK_METHOD2(GetLoginsImpl, void(GetLoginsRequest*, const PasswordForm&));
MOCK_METHOD1(GetAutofillableLoginsImpl, void(GetLoginsRequest*));
MOCK_METHOD1(GetBlacklistLoginsImpl, void(GetLoginsRequest*));
MOCK_METHOD1(FillAutofillableLogins,
bool(std::vector<webkit_glue::PasswordForm*>*));
MOCK_METHOD1(FillBlacklistLogins,
bool(std::vector<webkit_glue::PasswordForm*>*));
};
ACTION_P2(InvokeConsumer, handle, forms) {
arg0->OnPasswordStoreRequestDone(handle, forms);
}
ACTION_P(SaveToScopedPtr, scoped) {
scoped->reset(arg0);
}
class PasswordManagerTest : public testing::Test {
public:
PasswordManagerTest() {}
protected:
virtual void SetUp() {
store_ = new MockPasswordStore();
profile_.reset(new TestingProfileWithPasswordStore(store_));
EXPECT_CALL(delegate_, GetProfileForPasswordManager())
.WillRepeatedly(Return(profile_.get()));
manager_.reset(new PasswordManager(&delegate_));
EXPECT_CALL(delegate_, DidLastPageLoadEncounterSSLErrors())
.WillRepeatedly(Return(false));
}
virtual void TearDown() {
manager_.reset();
store_ = NULL;
}
PasswordForm MakeSimpleForm() {
PasswordForm form;
form.origin = GURL("http://www.google.com/a/LoginAuth");
form.action = GURL("http://www.google.com/a/Login");
form.username_element = ASCIIToUTF16("Email");
form.password_element = ASCIIToUTF16("Passwd");
form.username_value = ASCIIToUTF16("google");
form.password_value = ASCIIToUTF16("password");
form.submit_element = ASCIIToUTF16("signIn");
form.signon_realm = "http://www.google.com";
return form;
}
PasswordManager* manager() { return manager_.get(); }
scoped_ptr<Profile> profile_;
scoped_refptr<MockPasswordStore> store_;
MockPasswordManagerDelegate delegate_; // Owned by manager_.
scoped_ptr<PasswordManager> manager_;
};
MATCHER_P(FormMatches, form, "") {
return form.signon_realm == arg.signon_realm &&
form.origin == arg.origin &&
form.action == arg.action &&
form.username_element == arg.username_element &&
form.password_element == arg.password_element &&
form.submit_element == arg.submit_element;
}
TEST_F(PasswordManagerTest, FormSubmitEmptyStore) {
// Test that observing a newly submitted form shows the save password bar.
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
// And the form submit contract is to call ProvisionallySavePassword.
manager()->ProvisionallySavePassword(form);
scoped_ptr<PasswordFormManager> form_to_save;
EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
.WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));
// Now the password manager waits for the navigation to complete.
manager()->DidStopLoading();
ASSERT_FALSE(NULL == form_to_save.get());
EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
// Simulate saving the form, as if the info bar was accepted.
form_to_save->Save();
}
TEST_F(PasswordManagerTest, FormSubmitNoGoodMatch) {
// Same as above, except with an existing form for the same signon realm,
// but different origin. Detailed cases like this are covered by
// PasswordFormManagerTest.
std::vector<PasswordForm*> result;
PasswordForm* existing_different = new PasswordForm(MakeSimpleForm());
existing_different->username_value = ASCIIToUTF16("google2");
result.push_back(existing_different);
EXPECT_CALL(delegate_, FillPasswordForm(_));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->ProvisionallySavePassword(form);
// We still expect an add, since we didn't have a good match.
scoped_ptr<PasswordFormManager> form_to_save;
EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
.WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));
manager()->DidStopLoading();
EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
// Simulate saving the form.
form_to_save->Save();
}
TEST_F(PasswordManagerTest, FormSeenThenLeftPage) {
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->DidNavigate();
// No expected calls.
manager()->DidStopLoading();
}
TEST_F(PasswordManagerTest, FormSubmitFailedLogin) {
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->ProvisionallySavePassword(form);
// The form reappears, and is visible in the layout:
manager()->PasswordFormsFound(observed);
manager()->PasswordFormsVisible(observed);
// No expected calls to the PasswordStore...
manager()->DidStopLoading();
}
TEST_F(PasswordManagerTest, FormSubmitInvisibleLogin) {
// Tests fix of issue 28911: if the login form reappears on the subsequent
// page, but is invisible, it shouldn't count as a failed login.
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->ProvisionallySavePassword(form);
// The form reappears, but is not visible in the layout:
manager()->PasswordFormsFound(observed);
// No call to PasswordFormsVisible.
// Expect info bar to appear:
scoped_ptr<PasswordFormManager> form_to_save;
EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
.WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));
manager()->DidStopLoading();
ASSERT_FALSE(NULL == form_to_save.get());
EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
// Simulate saving the form.
form_to_save->Save();
}
TEST_F(PasswordManagerTest, InitiallyInvisibleForm) {
// Make sure an invisible login form still gets autofilled.
std::vector<PasswordForm*> result;
PasswordForm* existing = new PasswordForm(MakeSimpleForm());
result.push_back(existing);
EXPECT_CALL(delegate_, FillPasswordForm(_));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
// PasswordFormsVisible is not called.
manager()->DidStopLoading();
}
<commit_msg>Unreviewed build fix - fix typo in last unreviewd build fix :(<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/string_util.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/password_manager/password_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
using webkit_glue::PasswordForm;
using testing::_;
using testing::DoAll;
using ::testing::Exactly;
using ::testing::WithArg;
using ::testing::Return;
class MockPasswordManagerDelegate : public PasswordManager::Delegate {
public:
MOCK_METHOD1(FillPasswordForm, void(
const webkit_glue::PasswordFormDomManager::FillData&));
MOCK_METHOD1(AddSavePasswordInfoBar, void(PasswordFormManager*));
MOCK_METHOD0(GetProfileForPasswordManager, Profile*());
MOCK_METHOD0(DidLastPageLoadEncounterSSLErrors, bool());
};
class TestingProfileWithPasswordStore : public TestingProfile {
public:
explicit TestingProfileWithPasswordStore(PasswordStore* store)
: store_(store) {}
virtual PasswordStore* GetPasswordStore(ServiceAccessType access) {
return store_;
}
private:
PasswordStore* store_;
};
class MockPasswordStore : public PasswordStore {
public:
MOCK_METHOD1(RemoveLogin, void(const PasswordForm&));
MOCK_METHOD0(ReportMetricsImpl, void());
MOCK_METHOD2(GetLogins, int(const PasswordForm&, PasswordStoreConsumer*));
MOCK_METHOD1(AddLogin, void(const PasswordForm&));
MOCK_METHOD1(UpdateLogin, void(const PasswordForm&));
MOCK_METHOD1(AddLoginImpl, void(const PasswordForm&));
MOCK_METHOD1(UpdateLoginImpl, void(const PasswordForm&));
MOCK_METHOD1(RemoveLoginImpl, void(const PasswordForm&));
MOCK_METHOD2(RemoveLoginsCreatedBetweenImpl, void(const base::Time&,
const base::Time&));
MOCK_METHOD2(GetLoginsImpl, void(GetLoginsRequest*, const PasswordForm&));
MOCK_METHOD1(GetAutofillableLoginsImpl, void(GetLoginsRequest*));
MOCK_METHOD1(GetBlacklistLoginsImpl, void(GetLoginsRequest*));
MOCK_METHOD1(FillAutofillableLogins,
bool(std::vector<webkit_glue::PasswordForm*>*));
MOCK_METHOD1(FillBlacklistLogins,
bool(std::vector<webkit_glue::PasswordForm*>*));
};
ACTION_P2(InvokeConsumer, handle, forms) {
arg0->OnPasswordStoreRequestDone(handle, forms);
}
ACTION_P(SaveToScopedPtr, scoped) {
scoped->reset(arg0);
}
class PasswordManagerTest : public testing::Test {
public:
PasswordManagerTest() {}
protected:
virtual void SetUp() {
store_ = new MockPasswordStore();
profile_.reset(new TestingProfileWithPasswordStore(store_));
EXPECT_CALL(delegate_, GetProfileForPasswordManager())
.WillRepeatedly(Return(profile_.get()));
manager_.reset(new PasswordManager(&delegate_));
EXPECT_CALL(delegate_, DidLastPageLoadEncounterSSLErrors())
.WillRepeatedly(Return(false));
}
virtual void TearDown() {
manager_.reset();
store_ = NULL;
}
PasswordForm MakeSimpleForm() {
PasswordForm form;
form.origin = GURL("http://www.google.com/a/LoginAuth");
form.action = GURL("http://www.google.com/a/Login");
form.username_element = ASCIIToUTF16("Email");
form.password_element = ASCIIToUTF16("Passwd");
form.username_value = ASCIIToUTF16("google");
form.password_value = ASCIIToUTF16("password");
form.submit_element = ASCIIToUTF16("signIn");
form.signon_realm = "http://www.google.com";
return form;
}
PasswordManager* manager() { return manager_.get(); }
scoped_ptr<Profile> profile_;
scoped_refptr<MockPasswordStore> store_;
MockPasswordManagerDelegate delegate_; // Owned by manager_.
scoped_ptr<PasswordManager> manager_;
};
MATCHER_P(FormMatches, form, "") {
return form.signon_realm == arg.signon_realm &&
form.origin == arg.origin &&
form.action == arg.action &&
form.username_element == arg.username_element &&
form.password_element == arg.password_element &&
form.submit_element == arg.submit_element;
}
TEST_F(PasswordManagerTest, FormSubmitEmptyStore) {
// Test that observing a newly submitted form shows the save password bar.
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
// And the form submit contract is to call ProvisionallySavePassword.
manager()->ProvisionallySavePassword(form);
scoped_ptr<PasswordFormManager> form_to_save;
EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
.WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));
// Now the password manager waits for the navigation to complete.
manager()->DidStopLoading();
ASSERT_FALSE(NULL == form_to_save.get());
EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
// Simulate saving the form, as if the info bar was accepted.
form_to_save->Save();
}
TEST_F(PasswordManagerTest, FormSubmitNoGoodMatch) {
// Same as above, except with an existing form for the same signon realm,
// but different origin. Detailed cases like this are covered by
// PasswordFormManagerTest.
std::vector<PasswordForm*> result;
PasswordForm* existing_different = new PasswordForm(MakeSimpleForm());
existing_different->username_value = ASCIIToUTF16("google2");
result.push_back(existing_different);
EXPECT_CALL(delegate_, FillPasswordForm(_));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->ProvisionallySavePassword(form);
// We still expect an add, since we didn't have a good match.
scoped_ptr<PasswordFormManager> form_to_save;
EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
.WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));
manager()->DidStopLoading();
EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
// Simulate saving the form.
form_to_save->Save();
}
TEST_F(PasswordManagerTest, FormSeenThenLeftPage) {
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->DidNavigate();
// No expected calls.
manager()->DidStopLoading();
}
TEST_F(PasswordManagerTest, FormSubmitFailedLogin) {
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->ProvisionallySavePassword(form);
// The form reappears, and is visible in the layout:
manager()->PasswordFormsFound(observed);
manager()->PasswordFormsVisible(observed);
// No expected calls to the PasswordStore...
manager()->DidStopLoading();
}
TEST_F(PasswordManagerTest, FormSubmitInvisibleLogin) {
// Tests fix of issue 28911: if the login form reappears on the subsequent
// page, but is invisible, it shouldn't count as a failed login.
std::vector<PasswordForm*> result; // Empty password store.
EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
manager()->PasswordFormsVisible(observed); // The initial layout.
manager()->ProvisionallySavePassword(form);
// The form reappears, but is not visible in the layout:
manager()->PasswordFormsFound(observed);
// No call to PasswordFormsVisible.
// Expect info bar to appear:
scoped_ptr<PasswordFormManager> form_to_save;
EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
.WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));
manager()->DidStopLoading();
ASSERT_FALSE(NULL == form_to_save.get());
EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
// Simulate saving the form.
form_to_save->Save();
}
TEST_F(PasswordManagerTest, InitiallyInvisibleForm) {
// Make sure an invisible login form still gets autofilled.
std::vector<PasswordForm*> result;
PasswordForm* existing = new PasswordForm(MakeSimpleForm());
result.push_back(existing);
EXPECT_CALL(delegate_, FillPasswordForm(_));
EXPECT_CALL(*store_, GetLogins(_,_))
.WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
std::vector<PasswordForm> observed;
PasswordForm form(MakeSimpleForm());
observed.push_back(form);
manager()->PasswordFormsFound(observed); // The initial load.
// PasswordFormsVisible is not called.
manager()->DidStopLoading();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* containers/test_block_scheduler.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2010-2011 Raoul Steffen <[email protected]>
*
* 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 <stxxl/bits/mng/block_scheduler.h>
// Thanks Daniel Russel, Stanford University
#include <Argument_helper.h>
#include <iostream>
#include <limits>
using namespace stxxl;
template <class IBT>
void set_pattern_A(IBT & ib)
{
for (int_type i = 0; i < ib.size; ++i)
ib[i] = i;
}
template <class IBT>
int_type test_pattern_A(IBT & ib)
{
int_type num_err = 0;
for (int_type i = 0; i < ib.size; ++i)
num_err += (ib[i] != i);
return num_err;
}
template <class IBT>
void set_pattern_B(IBT & ib)
{
for (int_type i = 0; i < ib.size; ++i)
ib[i] = ib.size - i;
}
template <class IBT>
int_type test_pattern_B(IBT & ib)
{
int_type num_err = 0;
for (int_type i = 0; i < ib.size; ++i)
num_err += (ib[i] != ib.size - i);
return num_err;
}
int main(int argc, char **argv)
{
const int block_size = 1024;
typedef int_type value_type;
int test_case = -1;
int_type internal_memory = 256 * 1024 * 1024;
dsr::Argument_helper ah;
ah.new_named_int('t', "test-case", "I", "number of the test case to run", test_case);
ah.new_named_int('m', "memory", "N", "internal memory to use (in bytes)", internal_memory);
ah.set_description("stxxl block_scheduler test");
ah.set_author("Raoul Steffen, [email protected]");
ah.process(argc, argv);
typedef block_scheduler< swappable_block<value_type, block_size> > bst;
typedef bst::swappable_block_identifier_type sbit;
typedef bst::internal_block_type ibt;
typedef bst::external_block_type ebt;
switch (test_case)
{
case -1:
case 0:
{ // ------------------- call all functions -----------------------
STXXL_MSG("next test: call all functions");
ebt ext_bl; // prepare an external_block with pattern A
block_manager::get_instance()->new_block(striping(), ext_bl);
ibt * int_bl = new ibt;
set_pattern_A(*int_bl);
int_bl->write(ext_bl)->wait();
bst * b_s = new bst(internal_memory); // the block_scheduler may use internal_memory byte for caching
bst & bs = *b_s;
assert(! bs.is_simulating()); // make sure is not just recording a prediction sequence
sbit sbi1 = bs.allocate_swappable_block(); // allocate a swappable_block and store its identifier
if (bs.is_initialized(sbi1)) // it should not be initialized
STXXL_ERRMSG("new block is initialized");
bs.initialize(sbi1, ext_bl); // initialize the swappable_block with the prepared external_block
{
ibt & ib = bs.acquire(sbi1); // acquire the swappable_block to gain access
int_type num_err = 0;
for (int_type i = 0; i < block_size; ++i)
num_err += (ib[i] != i); // read from the swappable_block. it should contain pattern A
if (num_err)
STXXL_ERRMSG("previously initialized block had " << num_err << " errors.");
}
{
ibt & ib = bs.get_internal_block(sbi1); // get a new reference to the already allocated block (because we forgot the old one)
for (int_type i = 0; i < block_size; ++i)
ib[i] = block_size - i; // write pattern B
bs.release(sbi1, true); // release the swappable_block. changes have to be stored. it may now be swapped out.
}
sbit sbi2 = bs.allocate_swappable_block(); // allocate a second swappable_block and store its identifier
if (bs.is_initialized(sbi2)) // it should not be initialized
STXXL_ERRMSG("new block is initialized");
{
ibt & ib1 = bs.acquire(sbi1); // acquire the swappable_block to gain access
ibt & ib2 = bs.acquire(sbi2); // acquire the swappable_block to gain access because it was uninitialized, it now becomes initialized
for (int_type i = 0; i < block_size; ++i)
ib2[i] = ib1[i]; // copy pattern B
bs.release(sbi1, false); // release the swappable_block. no changes happened.
bs.release(sbi2, true);
}
if (! bs.is_initialized(sbi1)) // both blocks should now be initialized
STXXL_ERRMSG("block is not initialized");
if (! bs.is_initialized(sbi2)) // both blocks should now be initialized
STXXL_ERRMSG("block is not initialized");
ext_bl = bs.extract_external_block(sbi2); // get the external_block
if (bs.is_initialized(sbi2)) // should not be initialized any more
STXXL_ERRMSG("block is initialized after extraction");
bs.deinitialize(sbi1);
if (bs.is_initialized(sbi1)) // should not be initialized any more
STXXL_ERRMSG("block is initialized after deinitialize");
bs.free_swappable_block(sbi1); // free the swappable_blocks
bs.free_swappable_block(sbi2);
bs.explicit_timestep();
delete b_s;
int_bl->read(ext_bl)->wait();
int_type num_err = test_pattern_B(*int_bl); // check the block. it should contain pattern B.
if (num_err)
STXXL_ERRMSG("after extraction changed block had " << num_err << " errors.");
delete int_bl;
}
{ // ---------- force swapping ---------------------
STXXL_MSG("next test: force swapping");
const int_type num_sb = 5;
bst * b_s = new bst(block_size * sizeof(value_type) * 3); // only 3 internal_blocks allowed
sbit sbi[num_sb];
for (int_type i = 0; i < num_sb; ++i)
sbi[i] = b_s->allocate_swappable_block();
ibt * ib[num_sb];
ib[0] = &b_s->acquire(sbi[0]); // fill 3 blocks
ib[1] = &b_s->acquire(sbi[1]);
ib[2] = &b_s->acquire(sbi[2]);
set_pattern_A(*ib[0]);
set_pattern_A(*ib[1]);
set_pattern_A(*ib[2]);
b_s->release(sbi[0], true);
b_s->release(sbi[1], true);
b_s->release(sbi[2], true);
ib[3] = &b_s->acquire(sbi[3]); // fill 2 blocks, now some others have to be swapped out
ib[4] = &b_s->acquire(sbi[4]);
set_pattern_A(*ib[3]);
set_pattern_A(*ib[4]);
b_s->release(sbi[3], true);
b_s->release(sbi[4], true);
ib[2] = &b_s->acquire(sbi[2]); // this block can still be cached
ib[3] = &b_s->acquire(sbi[3]); // as can this
ib[1] = &b_s->acquire(sbi[1]); // but not this
if (test_pattern_A(*ib[1]))
STXXL_ERRMSG("Block 1 had errors.");
if (test_pattern_A(*ib[2]))
STXXL_ERRMSG("Block 2 had errors.");
if (test_pattern_A(*ib[3]))
STXXL_ERRMSG("Block 3 had errors.");
b_s->release(sbi[1], false);
b_s->release(sbi[2], false);
b_s->release(sbi[3], false);
for (int_type i = 0; i < num_sb; ++i)
b_s->free_swappable_block(sbi[i]);
delete b_s;
}
break;
case 1:
{ // ---------- do not free uninitialized block ---------------------
STXXL_MSG("next test: do not free uninitialized block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
b_s->release(sbi, false);
// do not free uninitialized block
delete b_s;
}
break;
case 2:
{ // ---------- do not free initialized block ---------------------
STXXL_MSG("next test: do not free initialized block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
b_s->release(sbi, true);
// do not free initialized block
delete b_s;
}
break;
case 3:
{ // ---------- do not release but free block ---------------------
STXXL_MSG("next test: do not release but free block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
// do not release block
b_s->free_swappable_block(sbi);
delete b_s;
}
break;
case 4:
{ // ---------- do neither release nor free block ---------------------
STXXL_MSG("next test: do neither release nor free block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
// do not release block
// do not free block
delete b_s;
}
break;
case 5:
{ // ---------- release block to often ---------------------
STXXL_MSG("next test: release block to often");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
b_s->release(sbi, false);
b_s->release(sbi, false); // release once to often
delete b_s;
}
break;
}
STXXL_MSG("end of test");
return 0;
}
<commit_msg>Give internal memory in megabytes.<commit_after>/***************************************************************************
* containers/test_block_scheduler.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2010-2011 Raoul Steffen <[email protected]>
*
* 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 <stxxl/bits/mng/block_scheduler.h>
// Thanks Daniel Russel, Stanford University
#include <Argument_helper.h>
#include <iostream>
#include <limits>
using namespace stxxl;
template <class IBT>
void set_pattern_A(IBT & ib)
{
for (int_type i = 0; i < ib.size; ++i)
ib[i] = i;
}
template <class IBT>
int_type test_pattern_A(IBT & ib)
{
int_type num_err = 0;
for (int_type i = 0; i < ib.size; ++i)
num_err += (ib[i] != i);
return num_err;
}
template <class IBT>
void set_pattern_B(IBT & ib)
{
for (int_type i = 0; i < ib.size; ++i)
ib[i] = ib.size - i;
}
template <class IBT>
int_type test_pattern_B(IBT & ib)
{
int_type num_err = 0;
for (int_type i = 0; i < ib.size; ++i)
num_err += (ib[i] != ib.size - i);
return num_err;
}
int main(int argc, char **argv)
{
const int block_size = 1024;
typedef int_type value_type;
int test_case = -1;
int internal_memory_megabytes = 256;
dsr::Argument_helper ah;
ah.new_named_int('t', "test-case", "I", "number of the test case to run", test_case);
ah.new_named_int('m', "memory", "N", "internal memory to use (in megabytes)", internal_memory_megabytes);
ah.set_description("stxxl block_scheduler test");
ah.set_author("Raoul Steffen, [email protected]");
ah.process(argc, argv);
int_type internal_memory = int_type(internal_memory_megabytes) * 1024 * 1024;
typedef block_scheduler< swappable_block<value_type, block_size> > bst;
typedef bst::swappable_block_identifier_type sbit;
typedef bst::internal_block_type ibt;
typedef bst::external_block_type ebt;
switch (test_case)
{
case -1:
case 0:
{ // ------------------- call all functions -----------------------
STXXL_MSG("next test: call all functions");
ebt ext_bl; // prepare an external_block with pattern A
block_manager::get_instance()->new_block(striping(), ext_bl);
ibt * int_bl = new ibt;
set_pattern_A(*int_bl);
int_bl->write(ext_bl)->wait();
bst * b_s = new bst(internal_memory); // the block_scheduler may use internal_memory byte for caching
bst & bs = *b_s;
assert(! bs.is_simulating()); // make sure is not just recording a prediction sequence
sbit sbi1 = bs.allocate_swappable_block(); // allocate a swappable_block and store its identifier
if (bs.is_initialized(sbi1)) // it should not be initialized
STXXL_ERRMSG("new block is initialized");
bs.initialize(sbi1, ext_bl); // initialize the swappable_block with the prepared external_block
{
ibt & ib = bs.acquire(sbi1); // acquire the swappable_block to gain access
int_type num_err = 0;
for (int_type i = 0; i < block_size; ++i)
num_err += (ib[i] != i); // read from the swappable_block. it should contain pattern A
if (num_err)
STXXL_ERRMSG("previously initialized block had " << num_err << " errors.");
}
{
ibt & ib = bs.get_internal_block(sbi1); // get a new reference to the already allocated block (because we forgot the old one)
for (int_type i = 0; i < block_size; ++i)
ib[i] = block_size - i; // write pattern B
bs.release(sbi1, true); // release the swappable_block. changes have to be stored. it may now be swapped out.
}
sbit sbi2 = bs.allocate_swappable_block(); // allocate a second swappable_block and store its identifier
if (bs.is_initialized(sbi2)) // it should not be initialized
STXXL_ERRMSG("new block is initialized");
{
ibt & ib1 = bs.acquire(sbi1); // acquire the swappable_block to gain access
ibt & ib2 = bs.acquire(sbi2); // acquire the swappable_block to gain access because it was uninitialized, it now becomes initialized
for (int_type i = 0; i < block_size; ++i)
ib2[i] = ib1[i]; // copy pattern B
bs.release(sbi1, false); // release the swappable_block. no changes happened.
bs.release(sbi2, true);
}
if (! bs.is_initialized(sbi1)) // both blocks should now be initialized
STXXL_ERRMSG("block is not initialized");
if (! bs.is_initialized(sbi2)) // both blocks should now be initialized
STXXL_ERRMSG("block is not initialized");
ext_bl = bs.extract_external_block(sbi2); // get the external_block
if (bs.is_initialized(sbi2)) // should not be initialized any more
STXXL_ERRMSG("block is initialized after extraction");
bs.deinitialize(sbi1);
if (bs.is_initialized(sbi1)) // should not be initialized any more
STXXL_ERRMSG("block is initialized after deinitialize");
bs.free_swappable_block(sbi1); // free the swappable_blocks
bs.free_swappable_block(sbi2);
bs.explicit_timestep();
delete b_s;
int_bl->read(ext_bl)->wait();
int_type num_err = test_pattern_B(*int_bl); // check the block. it should contain pattern B.
if (num_err)
STXXL_ERRMSG("after extraction changed block had " << num_err << " errors.");
delete int_bl;
}
{ // ---------- force swapping ---------------------
STXXL_MSG("next test: force swapping");
const int_type num_sb = 5;
bst * b_s = new bst(block_size * sizeof(value_type) * 3); // only 3 internal_blocks allowed
sbit sbi[num_sb];
for (int_type i = 0; i < num_sb; ++i)
sbi[i] = b_s->allocate_swappable_block();
ibt * ib[num_sb];
ib[0] = &b_s->acquire(sbi[0]); // fill 3 blocks
ib[1] = &b_s->acquire(sbi[1]);
ib[2] = &b_s->acquire(sbi[2]);
set_pattern_A(*ib[0]);
set_pattern_A(*ib[1]);
set_pattern_A(*ib[2]);
b_s->release(sbi[0], true);
b_s->release(sbi[1], true);
b_s->release(sbi[2], true);
ib[3] = &b_s->acquire(sbi[3]); // fill 2 blocks, now some others have to be swapped out
ib[4] = &b_s->acquire(sbi[4]);
set_pattern_A(*ib[3]);
set_pattern_A(*ib[4]);
b_s->release(sbi[3], true);
b_s->release(sbi[4], true);
ib[2] = &b_s->acquire(sbi[2]); // this block can still be cached
ib[3] = &b_s->acquire(sbi[3]); // as can this
ib[1] = &b_s->acquire(sbi[1]); // but not this
if (test_pattern_A(*ib[1]))
STXXL_ERRMSG("Block 1 had errors.");
if (test_pattern_A(*ib[2]))
STXXL_ERRMSG("Block 2 had errors.");
if (test_pattern_A(*ib[3]))
STXXL_ERRMSG("Block 3 had errors.");
b_s->release(sbi[1], false);
b_s->release(sbi[2], false);
b_s->release(sbi[3], false);
for (int_type i = 0; i < num_sb; ++i)
b_s->free_swappable_block(sbi[i]);
delete b_s;
}
break;
case 1:
{ // ---------- do not free uninitialized block ---------------------
STXXL_MSG("next test: do not free uninitialized block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
b_s->release(sbi, false);
// do not free uninitialized block
delete b_s;
}
break;
case 2:
{ // ---------- do not free initialized block ---------------------
STXXL_MSG("next test: do not free initialized block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
b_s->release(sbi, true);
// do not free initialized block
delete b_s;
}
break;
case 3:
{ // ---------- do not release but free block ---------------------
STXXL_MSG("next test: do not release but free block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
// do not release block
b_s->free_swappable_block(sbi);
delete b_s;
}
break;
case 4:
{ // ---------- do neither release nor free block ---------------------
STXXL_MSG("next test: do neither release nor free block");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
// do not release block
// do not free block
delete b_s;
}
break;
case 5:
{ // ---------- release block to often ---------------------
STXXL_MSG("next test: release block to often");
bst * b_s = new bst(block_size * sizeof(value_type));
sbit sbi;
sbi = b_s->allocate_swappable_block();
b_s->acquire(sbi);
b_s->release(sbi, false);
b_s->release(sbi, false); // release once to often
delete b_s;
}
break;
}
STXXL_MSG("end of test");
return 0;
}
<|endoftext|> |
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_SEQUENCES_MAP_HPP
#define BOOST_BRIGAND_SEQUENCES_MAP_HPP
#include <brigand/sequences/append.hpp>
#include <brigand/sequences/list.hpp>
#include <brigand/sequences/pair.hpp>
#include <brigand/types/no_such_type.hpp>
#include <brigand/types/type.hpp>
#include <type_traits>
namespace brigand
{
namespace lazy
{
template <typename M, typename K>
struct lookup_at
{
using target_t = type_<K>;
using type = decltype(M::at(target_t{}));
};
template <typename M, typename K>
struct lookup : lookup_at<M, K>::type
{
};
}
template <typename M, typename K>
using lookup = typename lazy::lookup<M, K>::type;
namespace detail
{
template <class... T>
struct map_impl;
template <>
struct map_impl<>
{
template <typename U>
static type_<no_such_type_> at(U);
template <class K>
static brigand::false_type has_key(type_<K>);
template <class K>
static map_impl erase(type_<K>);
template <class P>
static map_impl<P> insert(type_<P>);
};
template <class... Ts>
struct map_impl
{
private:
struct Pack : pair<typename Ts::first_type, Ts>...
{
};
template <class K, class P>
static type_<typename P::second_type> at_impl(pair<K, P> *);
public:
template <class K>
static decltype(at_impl<K>(static_cast<Pack *>(nullptr))) at(type_<K>);
template <class K>
static type_<no_such_type_> at(K);
template <class K, class = decltype(at_impl<K>(static_cast<Pack *>(nullptr)))>
static brigand::true_type has_key(type_<K>);
template <class K>
static brigand::false_type has_key(K);
template <class K, class X>
using erase_t = typename std::conditional<std::is_same<K, typename X::first_type>::value,
list<>, list<X>>::type;
template <class K, typename... Xs>
struct erase_return_t
{
using type = append<map_impl<>, erase_t<K, Xs>...>;
};
template <class K>
static typename erase_return_t<K, Ts...>::type erase(type_<K>);
template <class P, class = decltype(static_cast<pair<typename P::first_type, P> *>(
static_cast<Pack *>(nullptr)))>
static map_impl insert(type_<P>);
template <class P>
static map_impl<Ts..., typename P::type> insert(P);
};
// if you have a "class already a base" error message, it means you have defined a map with the
// same key present more
// than once, which is an error
template <class... Ts>
struct make_map : type_<typename Ts::first_type>...
{
using type = map_impl<Ts...>;
};
}
template <class... Ts>
using map = typename detail::make_map<Ts...>::type;
}
#endif
<commit_msg>Delete map.hpp<commit_after><|endoftext|> |
<commit_before>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "wfa/virtual_people/common/field_filter/field_filter.h"
#include "absl/status/status.h"
#include "gmock/gmock.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "src/main/cc/wfa/virtual_people/common/field_filter/test/test.pb.h"
#include "src/test/cc/testutil/matchers.h"
#include "src/test/cc/testutil/status_macros.h"
namespace wfa_virtual_people {
namespace {
using ::wfa::StatusIs;
using ::wfa_virtual_people::test::TestProto;
TEST(FieldFilterTest, FromMessageFloatNotSupported) {
TestProto filter_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
float_value: 1.0
}
}
)PROTO", &filter_message));
EXPECT_THAT(
FieldFilter::New(filter_message).status(),
StatusIs(absl::StatusCode::kInvalidArgument, ""));
}
TEST(FieldFilterTest, FromMessageDoubleNotSupported) {
TestProto filter_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
double_value: 1.0
}
}
)PROTO", &filter_message));
EXPECT_THAT(
FieldFilter::New(filter_message).status(),
StatusIs(absl::StatusCode::kInvalidArgument, ""));
}
TEST(FieldFilterTest, FromMessageRepeatedNotSupported) {
TestProto filter_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
int32_values: 1
)PROTO", &filter_message));
EXPECT_THAT(
FieldFilter::New(filter_message).status(),
StatusIs(absl::StatusCode::kInvalidArgument, ""));
}
TEST(FieldFilterTest, FromMessageSuccessful) {
TestProto filter_message, test_proto_1, test_proto_2;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
int32_value: 1
int64_value: 1
uint32_value: 1
uint64_value: 1
bool_value: true
enum_value: TEST_ENUM_1
string_value: "string1"
}
}
)PROTO", &filter_message));
ASSERT_OK_AND_ASSIGN(
std::unique_ptr<FieldFilter> filter, FieldFilter::New(filter_message));
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
int32_value: 1
int64_value: 1
uint32_value: 1
uint64_value: 1
float_value: 1.0
double_value: 1.0
bool_value: true
enum_value: TEST_ENUM_1
string_value: "string1"
}
}
)PROTO", &test_proto_1));
EXPECT_TRUE(filter->IsMatch(test_proto_1));
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
int32_value: 2
int64_value: 1
uint32_value: 1
uint64_value: 1
float_value: 1.0
double_value: 1.0
bool_value: true
enum_value: TEST_ENUM_1
string_value: "string1"
}
}
)PROTO", &test_proto_2));
EXPECT_FALSE(filter->IsMatch(test_proto_2));
}
} // namespace
} // namespace wfa_virtual_people
<commit_msg>Tests improvements.<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "wfa/virtual_people/common/field_filter/field_filter.h"
#include "absl/status/status.h"
#include "gmock/gmock.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "src/main/cc/wfa/virtual_people/common/field_filter/test/test.pb.h"
#include "src/test/cc/testutil/matchers.h"
#include "src/test/cc/testutil/status_macros.h"
namespace wfa_virtual_people {
namespace {
using ::wfa::StatusIs;
using ::wfa_virtual_people::test::TestProto;
TEST(FieldFilterTest, FromMessageFloatNotSupported) {
TestProto filter_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
float_value: 1.0
}
}
)PROTO", &filter_message));
EXPECT_THAT(
FieldFilter::New(filter_message).status(),
StatusIs(absl::StatusCode::kInvalidArgument, ""));
}
TEST(FieldFilterTest, FromMessageDoubleNotSupported) {
TestProto filter_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
double_value: 1.0
}
}
)PROTO", &filter_message));
EXPECT_THAT(
FieldFilter::New(filter_message).status(),
StatusIs(absl::StatusCode::kInvalidArgument, ""));
}
TEST(FieldFilterTest, FromMessageRepeatedNotSupported) {
TestProto filter_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
int32_values: 1
)PROTO", &filter_message));
EXPECT_THAT(
FieldFilter::New(filter_message).status(),
StatusIs(absl::StatusCode::kInvalidArgument, ""));
}
TEST(FieldFilterTest, FromMessageSuccessful) {
TestProto filter_message, test_proto_1, test_proto_2;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
int32_value: 1
int64_value: 1
uint32_value: 1
uint64_value: 1
bool_value: true
enum_value: TEST_ENUM_1
string_value: "string1"
}
}
)PROTO", &filter_message));
ASSERT_OK_AND_ASSIGN(
std::unique_ptr<FieldFilter> filter, FieldFilter::New(filter_message));
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
int32_value: 1
int64_value: 1
uint32_value: 1
uint64_value: 1
float_value: 1.0
double_value: 1.0
bool_value: true
enum_value: TEST_ENUM_1
string_value: "string1"
}
}
int32_values: 1
int32_values: 2
)PROTO", &test_proto_1));
EXPECT_TRUE(filter->IsMatch(test_proto_1));
// a.b.int32_value does not match.
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
a {
b {
int32_value: 2
int64_value: 1
uint32_value: 1
uint64_value: 1
float_value: 1.0
double_value: 1.0
bool_value: true
enum_value: TEST_ENUM_1
string_value: "string1"
}
}
int32_values: 1
int32_values: 2
)PROTO", &test_proto_2));
EXPECT_FALSE(filter->IsMatch(test_proto_2));
}
} // namespace
} // namespace wfa_virtual_people
<|endoftext|> |
<commit_before>#include "contextpanewidget.h"
#include <coreplugin/icore.h>
#include <QFontComboBox>
#include <QComboBox>
#include <QSpinBox>
#include <QToolButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QGridLayout>
#include <QToolButton>
#include <QAction>
#include <qmldesignerplugin.h>
#include "colorwidget.h"
#include "contextpanetextwidget.h"
namespace QmlDesigner {
ContextPaneWidget::ContextPaneWidget(QWidget *parent) : QFrame(parent), m_currentWidget(0), m_xPos(-1)
{
setFrameStyle(QFrame::NoFrame);
setFrameShape(QFrame::StyledPanel);
setFrameShadow(QFrame::Sunken);
m_oldPos = QPoint(-1, -1);
m_dropShadowEffect = new QGraphicsDropShadowEffect;
m_dropShadowEffect->setBlurRadius(6);
m_dropShadowEffect->setOffset(2, 2);
setGraphicsEffect(m_dropShadowEffect);
QGridLayout *layout = new QGridLayout(this);
layout->setMargin(2);
layout->setContentsMargins(2, 4, 2, 2);
QToolButton *toolButton = new QToolButton(this);
QIcon icon(style()->standardIcon(QStyle::SP_DockWidgetCloseButton));
toolButton->setIcon(icon);
toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
toolButton->setFixedSize(icon.availableSizes().first() + QSize(4, 4));
connect(toolButton, SIGNAL(clicked()), this, SLOT(onTogglePane()));
layout->addWidget(toolButton, 0, 0, 1, 1);
colorDialog();
QWidget *fontWidget = createFontWidget();
m_currentWidget = fontWidget;
layout->addWidget(fontWidget, 0, 1, 2, 1);
setAutoFillBackground(true);
setContextMenuPolicy(Qt::ActionsContextMenu);
QAction *resetAction = new QAction(tr("Reset position"), this);
addAction(resetAction);
connect(resetAction, SIGNAL(triggered()), this, SLOT(onResetPosition()));
QAction *disableAction = new QAction(tr("Disable permanently"), this);
addAction(disableAction);
connect(disableAction, SIGNAL(triggered()), this, SLOT(onDisable()));
}
ContextPaneWidget::~ContextPaneWidget()
{
//if the pane was never activated the widget is not in a widget tree
if (!m_bauhausColorDialog.isNull())
delete m_bauhausColorDialog.data();
m_bauhausColorDialog.clear();
}
void ContextPaneWidget::activate(const QPoint &pos, const QPoint &alternative)
{
//uncheck all color buttons
foreach (ColorButton *colorButton, findChildren<ColorButton*>()) {
colorButton->setChecked(false);
}
resize(sizeHint());
show();
rePosition(pos, alternative);
raise();
}
void ContextPaneWidget::rePosition(const QPoint &position, const QPoint &alternative)
{
if (position.y() > 0)
move(position);
else
move(alternative);
m_originalPos = pos();
if (m_xPos > 0)
move(m_xPos, pos().y());
}
void ContextPaneWidget::deactivate()
{
hide();
if (m_bauhausColorDialog)
m_bauhausColorDialog->hide();
}
BauhausColorDialog *ContextPaneWidget::colorDialog()
{
if (m_bauhausColorDialog.isNull()) {
m_bauhausColorDialog = new BauhausColorDialog(parentWidget());
m_bauhausColorDialog->hide();
}
return m_bauhausColorDialog.data();
}
void ContextPaneWidget::setProperties(::QmlJS::PropertyReader *propertyReader)
{
ContextPaneTextWidget *textWidget = qobject_cast<ContextPaneTextWidget*>(m_currentWidget);
if (textWidget)
textWidget->setProperties(propertyReader);
}
bool ContextPaneWidget::setType(const QString &typeName)
{
if (typeName.contains("Text")) {
m_currentWidget = m_textWidget;
m_textWidget->show();
m_textWidget->setStyleVisible(true);
m_textWidget->setVerticalAlignmentVisible(true);
if (typeName.contains("TextInput")) {
m_textWidget->setVerticalAlignmentVisible(false);
m_textWidget->setStyleVisible(false);
} else if (typeName.contains("TextEdit")) {
m_textWidget->setStyleVisible(false);
}
return true;
}
m_textWidget->hide();
return false;
}
void ContextPaneWidget::onTogglePane()
{
if (!m_currentWidget)
return;
deactivate();
}
void ContextPaneWidget::onShowColorDialog(bool checked, const QPoint &p)
{
if (checked) {
colorDialog()->setParent(parentWidget());
colorDialog()->move(p);
colorDialog()->show();
colorDialog()->raise();
} else {
colorDialog()->hide();
}
}
void ContextPaneWidget::mousePressEvent(QMouseEvent * event)
{
if (event->button() == Qt::LeftButton) {
m_oldPos = event->globalPos();
m_opacityEffect = new QGraphicsOpacityEffect;
setGraphicsEffect(m_opacityEffect);
event->accept();
}
QFrame::mousePressEvent(event);
}
void ContextPaneWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_oldPos = QPoint(-1, -1);
m_dropShadowEffect = new QGraphicsDropShadowEffect;
m_dropShadowEffect->setBlurRadius(6);
m_dropShadowEffect->setOffset(2, 2);
setGraphicsEffect(m_dropShadowEffect);
}
QFrame::mouseReleaseEvent(event);
}
void ContextPaneWidget::mouseMoveEvent(QMouseEvent * event)
{
if (event->buttons() && Qt::LeftButton) {
if (pos().x() < 10 && event->pos().x() < -20)
return;
if (m_oldPos != QPoint(-1, -1)) {
QPoint diff = event->globalPos() - m_oldPos;
if (m_bauhausColorDialog) {
QPoint newPos = pos() + diff;
if (newPos.x() > 0 && newPos.y() > 0 && (newPos.x() + width()) < parentWidget()->width() && (newPos.y() + height()) < parentWidget()->height()) {
m_bauhausColorDialog->move(m_bauhausColorDialog->pos() + diff);
move(newPos);
}
}
} else {
m_opacityEffect = new QGraphicsOpacityEffect;
setGraphicsEffect(m_opacityEffect);
}
m_oldPos = event->globalPos();
event->accept();
}
}
void ContextPaneWidget::onDisable()
{
DesignerSettings designerSettings = Internal::BauhausPlugin::pluginInstance()->settings();
designerSettings.enableContextPane = false;
Internal::BauhausPlugin::pluginInstance()->setSettings(designerSettings);
hide();
colorDialog()->hide();
}
void ContextPaneWidget::onResetPosition()
{
move(m_originalPos);
m_xPos = -1;
}
QWidget* ContextPaneWidget::createFontWidget()
{
m_textWidget = new ContextPaneTextWidget(this);
connect(m_textWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
connect(m_textWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
connect(m_textWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant)));
return m_textWidget;
}
} //QmlDesigner
<commit_msg>QmlDesigner.contextPane: do not remeber position<commit_after>#include "contextpanewidget.h"
#include <coreplugin/icore.h>
#include <QFontComboBox>
#include <QComboBox>
#include <QSpinBox>
#include <QToolButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QGridLayout>
#include <QToolButton>
#include <QAction>
#include <qmldesignerplugin.h>
#include "colorwidget.h"
#include "contextpanetextwidget.h"
namespace QmlDesigner {
ContextPaneWidget::ContextPaneWidget(QWidget *parent) : QFrame(parent), m_currentWidget(0), m_xPos(-1)
{
setFrameStyle(QFrame::NoFrame);
setFrameShape(QFrame::StyledPanel);
setFrameShadow(QFrame::Sunken);
m_oldPos = QPoint(-1, -1);
m_dropShadowEffect = new QGraphicsDropShadowEffect;
m_dropShadowEffect->setBlurRadius(6);
m_dropShadowEffect->setOffset(2, 2);
setGraphicsEffect(m_dropShadowEffect);
QGridLayout *layout = new QGridLayout(this);
layout->setMargin(2);
layout->setContentsMargins(2, 4, 2, 2);
QToolButton *toolButton = new QToolButton(this);
QIcon icon(style()->standardIcon(QStyle::SP_DockWidgetCloseButton));
toolButton->setIcon(icon);
toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
toolButton->setFixedSize(icon.availableSizes().first() + QSize(4, 4));
connect(toolButton, SIGNAL(clicked()), this, SLOT(onTogglePane()));
layout->addWidget(toolButton, 0, 0, 1, 1);
colorDialog();
QWidget *fontWidget = createFontWidget();
m_currentWidget = fontWidget;
layout->addWidget(fontWidget, 0, 1, 2, 1);
setAutoFillBackground(true);
setContextMenuPolicy(Qt::ActionsContextMenu);
QAction *resetAction = new QAction(tr("Reset position"), this);
addAction(resetAction);
connect(resetAction, SIGNAL(triggered()), this, SLOT(onResetPosition()));
QAction *disableAction = new QAction(tr("Disable permanently"), this);
addAction(disableAction);
connect(disableAction, SIGNAL(triggered()), this, SLOT(onDisable()));
}
ContextPaneWidget::~ContextPaneWidget()
{
//if the pane was never activated the widget is not in a widget tree
if (!m_bauhausColorDialog.isNull())
delete m_bauhausColorDialog.data();
m_bauhausColorDialog.clear();
}
void ContextPaneWidget::activate(const QPoint &pos, const QPoint &alternative, const QPoint &alternative2)
{
//uncheck all color buttons
foreach (ColorButton *colorButton, findChildren<ColorButton*>()) {
colorButton->setChecked(false);
}
resize(sizeHint());
show();
rePosition(pos, alternative, alternative2);
raise();
}
void ContextPaneWidget::rePosition(const QPoint &position, const QPoint &alternative, const QPoint &alternative2)
{
if ((position.x() + width()) < parentWidget()->width())
move(position);
else
move(alternative);
if (pos().y() < 0)
move(alternative2);
}
void ContextPaneWidget::deactivate()
{
hide();
if (m_bauhausColorDialog)
m_bauhausColorDialog->hide();
}
BauhausColorDialog *ContextPaneWidget::colorDialog()
{
if (m_bauhausColorDialog.isNull()) {
m_bauhausColorDialog = new BauhausColorDialog(parentWidget());
m_bauhausColorDialog->hide();
}
return m_bauhausColorDialog.data();
}
void ContextPaneWidget::setProperties(::QmlJS::PropertyReader *propertyReader)
{
ContextPaneTextWidget *textWidget = qobject_cast<ContextPaneTextWidget*>(m_currentWidget);
if (textWidget)
textWidget->setProperties(propertyReader);
}
bool ContextPaneWidget::setType(const QString &typeName)
{
if (typeName.contains("Text")) {
m_currentWidget = m_textWidget;
m_textWidget->show();
m_textWidget->setStyleVisible(true);
m_textWidget->setVerticalAlignmentVisible(true);
if (typeName.contains("TextInput")) {
m_textWidget->setVerticalAlignmentVisible(false);
m_textWidget->setStyleVisible(false);
} else if (typeName.contains("TextEdit")) {
m_textWidget->setStyleVisible(false);
}
return true;
}
m_textWidget->hide();
return false;
}
void ContextPaneWidget::onTogglePane()
{
if (!m_currentWidget)
return;
deactivate();
}
void ContextPaneWidget::onShowColorDialog(bool checked, const QPoint &p)
{
if (checked) {
colorDialog()->setParent(parentWidget());
colorDialog()->move(p);
colorDialog()->show();
colorDialog()->raise();
} else {
colorDialog()->hide();
}
}
void ContextPaneWidget::mousePressEvent(QMouseEvent * event)
{
if (event->button() == Qt::LeftButton) {
m_oldPos = event->globalPos();
m_opacityEffect = new QGraphicsOpacityEffect;
setGraphicsEffect(m_opacityEffect);
event->accept();
}
QFrame::mousePressEvent(event);
}
void ContextPaneWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_oldPos = QPoint(-1, -1);
m_dropShadowEffect = new QGraphicsDropShadowEffect;
m_dropShadowEffect->setBlurRadius(6);
m_dropShadowEffect->setOffset(2, 2);
setGraphicsEffect(m_dropShadowEffect);
}
QFrame::mouseReleaseEvent(event);
}
void ContextPaneWidget::mouseMoveEvent(QMouseEvent * event)
{
if (event->buttons() && Qt::LeftButton) {
if (pos().x() < 10 && event->pos().x() < -20)
return;
if (m_oldPos != QPoint(-1, -1)) {
QPoint diff = event->globalPos() - m_oldPos;
if (m_bauhausColorDialog) {
QPoint newPos = pos() + diff;
if (newPos.x() > 0 && newPos.y() > 0 && (newPos.x() + width()) < parentWidget()->width() && (newPos.y() + height()) < parentWidget()->height()) {
m_bauhausColorDialog->move(m_bauhausColorDialog->pos() + diff);
move(newPos);
}
}
} else {
m_opacityEffect = new QGraphicsOpacityEffect;
setGraphicsEffect(m_opacityEffect);
}
m_oldPos = event->globalPos();
event->accept();
}
}
void ContextPaneWidget::onDisable()
{
DesignerSettings designerSettings = Internal::BauhausPlugin::pluginInstance()->settings();
designerSettings.enableContextPane = false;
Internal::BauhausPlugin::pluginInstance()->setSettings(designerSettings);
hide();
colorDialog()->hide();
}
void ContextPaneWidget::onResetPosition()
{
move(m_originalPos);
m_xPos = -1;
}
QWidget* ContextPaneWidget::createFontWidget()
{
m_textWidget = new ContextPaneTextWidget(this);
connect(m_textWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
connect(m_textWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
connect(m_textWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant)));
return m_textWidget;
}
} //QmlDesigner
<|endoftext|> |
<commit_before>#include "game/tileview/tileobject_shadow.h"
#include "game/city/vehicle.h"
namespace OpenApoc
{
void TileObjectShadow::draw(Renderer &r, TileView &view, Vec2<float> screenPosition,
TileViewMode mode)
{
std::ignore = view;
auto vehicle = this->owner.lock();
if (!vehicle)
{
LogError("Called with no owning vehicle object");
return;
}
switch (mode)
{
case TileViewMode::Isometric:
{
float closestAngle = FLT_MAX;
sp<Image> closestImage;
for (auto &p : vehicle->def.directionalShadowSprites)
{
float angle =
glm::angle(glm::normalize(p.first), glm::normalize(vehicle->getDirection()));
if (angle < closestAngle)
{
closestAngle = angle;
closestImage = p.second;
}
}
if (!closestImage)
{
LogError("No image found for vehicle");
return;
}
r.draw(closestImage, screenPosition - vehicle->def.shadowOffset);
break;
}
case TileViewMode::Strategy:
{
// No shadows in strategy view
break;
}
default:
LogError("Unsupported view mode");
}
}
void TileObjectShadow::setPosition(Vec3<float> newPosition)
{
// This finds the next scenery tile on or below newPosition and sets the
// real position to that
// Truncate down to int
Vec3<int> pos = {newPosition.x, newPosition.y, newPosition.z};
bool found = false;
// and keep going down until we find a tile with scenery
while (!found && pos.z >= 0)
{
auto *t = map.getTile(pos);
for (auto &obj : t->ownedObjects)
{
if (obj->getType() == TileObject::Type::Scenery)
{
newPosition.z = obj->getPosition().z;
// FIXME: I /think/ this is due to the sprite offset in the pck not being handled,
// but here's a workaround to make it look kinda-right
found = true;
break;
}
}
pos.z--;
}
if (!found)
{
LogWarning("No scenery found below {%f,%f,%f}", newPosition.x, newPosition.y,
newPosition.z);
newPosition.z = 0;
}
TileObject::setPosition(newPosition);
}
TileObjectShadow::~TileObjectShadow() {}
TileObjectShadow::TileObjectShadow(TileMap &map, sp<Vehicle> vehicle)
: TileObject(map, TileObject::Type::Vehicle, vehicle->getPosition(), Vec3<float>{0, 0, 0}),
owner(vehicle)
{
}
} // namespace OpenApoc
<commit_msg>Choose shadow position based on first collideable object below<commit_after>#include "game/tileview/tileobject_shadow.h"
#include "game/tileview/voxel.h"
#include "game/city/vehicle.h"
namespace OpenApoc
{
void TileObjectShadow::draw(Renderer &r, TileView &view, Vec2<float> screenPosition,
TileViewMode mode)
{
std::ignore = view;
auto vehicle = this->owner.lock();
if (!vehicle)
{
LogError("Called with no owning vehicle object");
return;
}
switch (mode)
{
case TileViewMode::Isometric:
{
float closestAngle = FLT_MAX;
sp<Image> closestImage;
for (auto &p : vehicle->def.directionalShadowSprites)
{
float angle =
glm::angle(glm::normalize(p.first), glm::normalize(vehicle->getDirection()));
if (angle < closestAngle)
{
closestAngle = angle;
closestImage = p.second;
}
}
if (!closestImage)
{
LogError("No image found for vehicle");
return;
}
r.draw(closestImage, screenPosition - vehicle->def.shadowOffset);
break;
}
case TileViewMode::Strategy:
{
// No shadows in strategy view
break;
}
default:
LogError("Unsupported view mode");
}
}
void TileObjectShadow::setPosition(Vec3<float> newPosition)
{
// This projects a line downwards and draws places the shadow at the z of the first thing hit
auto shadowPosition = newPosition;
auto c = map.findCollision(newPosition, Vec3<float>{newPosition.x, newPosition.y, 0});
if (c)
{
shadowPosition.z = c.position.z;
}
else
{
// May be a normal occurance (e.g. landing pads have a 'hole'
LogInfo("Nothing beneath {%f,%f,%f} to receive shadow", newPosition.x, newPosition.y,
newPosition.z);
shadowPosition.z = 0;
}
TileObject::setPosition(shadowPosition);
}
TileObjectShadow::~TileObjectShadow() {}
TileObjectShadow::TileObjectShadow(TileMap &map, sp<Vehicle> vehicle)
: TileObject(map, TileObject::Type::Vehicle, vehicle->getPosition(), Vec3<float>{0, 0, 0}),
owner(vehicle)
{
}
} // namespace OpenApoc
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "AnchorLayoutConstraintSolver.h"
#include "FormElement.h"
#include "../VisualizationException.h"
#include <lpsolve/lp_lib.h>
namespace Visualization {
AnchorLayoutConstraintSolver::AnchorLayoutConstraintSolver()
{
// TODO Auto-generated constructor stub
}
AnchorLayoutConstraintSolver::~AnchorLayoutConstraintSolver()
{
cleanUpConstraintSolver();
}
inline int AnchorLayoutConstraintSolver::startVariable(int elementIndex) { return 2 * elementIndex;}
inline int AnchorLayoutConstraintSolver::endVariable(int elementIndex) { return 2 * elementIndex + 1; }
void AnchorLayoutConstraintSolver::placeElements(const QVector<FormElement*>& elements,
QList<AnchorLayoutAnchor*>& anchors, AnchorLayoutAnchor::Orientation orientation, Item* item)
{
Q_ASSERT(numVariables_ == 0 || numVariables_ == elements.size() * 2);
if (!lp_) prepareLP(elements, anchors, orientation, item);
else updateLP(elements, orientation, item);
QVector<float> solution = solveConstraints();
// Apply the solution
for (int i=0; i<elements.size(); ++i)
{
FormElement* element = elements.at(i);
int size = std::ceil(solution[endVariable(i)] - solution[startVariable(i)]);
int position = std::ceil(solution[startVariable(i)]);
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
{
if (size > element->size(item).width())
element->computeSize(item, size, element->size(item).height());
element->setPos(item, QPoint(position, element->pos(item).y()));
}
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
{
if (size > element->size(item).height())
element->computeSize(item, element->size(item).width(), size);
element->setPos(item, QPoint(element->pos(item).x(), position));
}
}
}
void AnchorLayoutConstraintSolver::prepareLP(const QVector<FormElement*>& elements, QList<AnchorLayoutAnchor*>& anchors,
AnchorLayoutAnchor::Orientation orientation, Item* item)
{
// elements already have a minimum size
initializeConstraintSolver(elements.size() * 2);
// add objective function
// minimize the sum of the sizes of all the elements
QVector<float> objectiveRow;
for (int i=0; i<elements.size(); ++i)
{
objectiveRow.append(-1.0); // start variable of i-th element
objectiveRow.append(1.0); // end variable of i-th element
}
setMinimizeObjective(objectiveRow);
// add size constraints for each element
// if element's size depends on parent's size
// element.end - element.start >= element.size
// else
// element.end - element.start = element.size
// NOTE: This set of constraints must come immediately after the objective function and must be the first set
// in lp_. This is assumed in updateLP() where we only update rows [1 .. elements.size()]
for (auto e : elements)
{
int elementIndex = elements.indexOf(e);
QVector<QPair<int, float>> constraintRow = {QPair<int, float>(endVariable(elementIndex), 1.0),
QPair<int, float>(startVariable(elementIndex), -1.0)};
float size;
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
size = (float) e->size(item).width();
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
size = (float) e->size(item).height();
if (e->sizeDependsOnParent(item))
addConstraint(GE, constraintRow, size);
else
addConstraint(EQ, constraintRow, size);
}
// add constraints for each anchor
// placeElement.start + relativePlaceEdgePosition * placeElement.end
// == fixedElement.start + relativeFixedEdgePosition * fixedElement.end + offset
for (auto a : anchors)
{
int placeElementIndex = elements.indexOf(a->placeElement());
int fixedElementIndex = elements.indexOf(a->fixedElement());
QVector<QPair<int, float>> constraintRow =
{
QPair<int, float>(startVariable(placeElementIndex), 1 - a->relativePlaceEdgePosition()),
QPair<int, float>(endVariable(placeElementIndex), a->relativePlaceEdgePosition()),
QPair<int, float>(startVariable(fixedElementIndex), -(1 - a->relativeFixedEdgePosition())),
QPair<int, float>(endVariable(fixedElementIndex), -a->relativeFixedEdgePosition())
};
addConstraint(EQ, constraintRow, (float) a->offset());
}
}
void AnchorLayoutConstraintSolver::updateLP(const QVector<FormElement*>& elements,
AnchorLayoutAnchor::Orientation orientation, Item* item)
{
// Only the size constraints change from run to run.
set_add_rowmode(lp_, true);
// add size constraints for each element
// if element's size depends on parent's size
// element.end - element.start >= element.size
// else
// element.end - element.start = element.size
int i = 1; // Row 0 is something else, perhaps the objective function
for (auto e : elements)
{
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
set_rh(lp_, i, (float) e->size(item).width());
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
set_rh(lp_, i, (float) e->size(item).height());
if (e->sizeDependsOnParent(item)) set_constr_type(lp_, i, GE);
else set_constr_type(lp_, i, EQ);
++i;
}
}
void AnchorLayoutConstraintSolver::addConstraint(int type, QVector<QPair<int, float>> constraintRow,
float result)
{
for (int i=0; i<constraintRow.size(); ++i)
{
columnIndices_[i] = constraintRow[i].first + 1;
rowValues_[i] = (double) constraintRow[i].second;
}
bool success = add_constraintex(lp_, constraintRow.size(), rowValues_, columnIndices_, type, result);
Q_ASSERT(success);
}
void AnchorLayoutConstraintSolver::setMinimizeObjective(QVector<float> objectiveRow)
{
for (int i=0; i<numVariables_; ++i)
{
columnIndices_[i] = i+1;
rowValues_[i] = (double) objectiveRow[i];
}
bool success = set_obj_fnex(lp_, numVariables_, rowValues_, columnIndices_);
Q_ASSERT(success);
}
QVector<float> AnchorLayoutConstraintSolver::solveConstraints()
{
set_add_rowmode(lp_, false);
set_verbose(lp_, CRITICAL);
default_basis(lp_); // Make sure to reset the basis between calls in order to get the correct result
int success = solve(lp_);
if (success != OPTIMAL) throw VisualizationException("Failed to solve anchor constraints.");
get_variables(lp_, rowValues_);
QVector<float> result;
for (int i=0; i<numVariables_; ++i)
result.append((float) rowValues_[i]);
return result;
}
void AnchorLayoutConstraintSolver::initializeConstraintSolver(int numVariables)
{
lp_ = make_lp(0, numVariables);
Q_ASSERT(lp_ != nullptr);
rowValues_ = new double[numVariables];
columnIndices_ = new int[numVariables];
numVariables_ = numVariables;
set_add_rowmode(lp_, true);
}
void AnchorLayoutConstraintSolver::cleanUpConstraintSolver()
{
if (lp_)
{
delete_lp(lp_);
lp_ = nullptr;
}
if (rowValues_)
{
delete [] rowValues_;
rowValues_ = nullptr;
}
if (columnIndices_)
{
delete [] columnIndices_;
columnIndices_ = nullptr;
}
}
}
<commit_msg>move comment<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "AnchorLayoutConstraintSolver.h"
#include "FormElement.h"
#include "../VisualizationException.h"
#include <lpsolve/lp_lib.h>
namespace Visualization {
AnchorLayoutConstraintSolver::AnchorLayoutConstraintSolver()
{
// TODO Auto-generated constructor stub
}
AnchorLayoutConstraintSolver::~AnchorLayoutConstraintSolver()
{
cleanUpConstraintSolver();
}
inline int AnchorLayoutConstraintSolver::startVariable(int elementIndex) { return 2 * elementIndex;}
inline int AnchorLayoutConstraintSolver::endVariable(int elementIndex) { return 2 * elementIndex + 1; }
void AnchorLayoutConstraintSolver::placeElements(const QVector<FormElement*>& elements,
QList<AnchorLayoutAnchor*>& anchors, AnchorLayoutAnchor::Orientation orientation, Item* item)
{
Q_ASSERT(numVariables_ == 0 || numVariables_ == elements.size() * 2);
if (!lp_) prepareLP(elements, anchors, orientation, item);
else updateLP(elements, orientation, item);
QVector<float> solution = solveConstraints();
// Apply the solution
for (int i=0; i<elements.size(); ++i)
{
FormElement* element = elements.at(i);
int size = std::ceil(solution[endVariable(i)] - solution[startVariable(i)]);
int position = std::ceil(solution[startVariable(i)]);
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
{
if (size > element->size(item).width())
element->computeSize(item, size, element->size(item).height());
element->setPos(item, QPoint(position, element->pos(item).y()));
}
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
{
if (size > element->size(item).height())
element->computeSize(item, element->size(item).width(), size);
element->setPos(item, QPoint(element->pos(item).x(), position));
}
}
}
void AnchorLayoutConstraintSolver::prepareLP(const QVector<FormElement*>& elements, QList<AnchorLayoutAnchor*>& anchors,
AnchorLayoutAnchor::Orientation orientation, Item* item)
{
// elements already have a minimum size
initializeConstraintSolver(elements.size() * 2);
// add objective function
// minimize the sum of the sizes of all the elements
QVector<float> objectiveRow;
for (int i=0; i<elements.size(); ++i)
{
objectiveRow.append(-1.0); // start variable of i-th element
objectiveRow.append(1.0); // end variable of i-th element
}
setMinimizeObjective(objectiveRow);
// add size constraints for each element
// if element's size depends on parent's size
// element.end - element.start >= element.size
// else
// element.end - element.start = element.size
// NOTE: This set of constraints must come immediately after the objective function and must be the first set
// in lp_. This is assumed in updateLP() where we only update rows [1 .. elements.size()]
for (auto e : elements)
{
int elementIndex = elements.indexOf(e);
QVector<QPair<int, float>> constraintRow = {QPair<int, float>(endVariable(elementIndex), 1.0),
QPair<int, float>(startVariable(elementIndex), -1.0)};
float size;
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
size = (float) e->size(item).width();
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
size = (float) e->size(item).height();
if (e->sizeDependsOnParent(item))
addConstraint(GE, constraintRow, size);
else
addConstraint(EQ, constraintRow, size);
}
// add constraints for each anchor
// placeElement.start + relativePlaceEdgePosition * placeElement.end
// == fixedElement.start + relativeFixedEdgePosition * fixedElement.end + offset
for (auto a : anchors)
{
int placeElementIndex = elements.indexOf(a->placeElement());
int fixedElementIndex = elements.indexOf(a->fixedElement());
QVector<QPair<int, float>> constraintRow =
{
QPair<int, float>(startVariable(placeElementIndex), 1 - a->relativePlaceEdgePosition()),
QPair<int, float>(endVariable(placeElementIndex), a->relativePlaceEdgePosition()),
QPair<int, float>(startVariable(fixedElementIndex), -(1 - a->relativeFixedEdgePosition())),
QPair<int, float>(endVariable(fixedElementIndex), -a->relativeFixedEdgePosition())
};
addConstraint(EQ, constraintRow, (float) a->offset());
}
}
void AnchorLayoutConstraintSolver::updateLP(const QVector<FormElement*>& elements,
AnchorLayoutAnchor::Orientation orientation, Item* item)
{
// Only the size constraints change from run to run.
set_add_rowmode(lp_, true);
// add size constraints for each element
// if element's size depends on parent's size
// element.end - element.start >= element.size
// else
// element.end - element.start = element.size
int i = 1; // Row 0 is something else, perhaps the objective function
for (auto e : elements)
{
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
set_rh(lp_, i, (float) e->size(item).width());
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
set_rh(lp_, i, (float) e->size(item).height());
if (e->sizeDependsOnParent(item)) set_constr_type(lp_, i, GE);
else set_constr_type(lp_, i, EQ);
++i;
}
}
void AnchorLayoutConstraintSolver::addConstraint(int type, QVector<QPair<int, float>> constraintRow,
float result)
{
for (int i=0; i<constraintRow.size(); ++i)
{
columnIndices_[i] = constraintRow[i].first + 1;
rowValues_[i] = (double) constraintRow[i].second;
}
bool success = add_constraintex(lp_, constraintRow.size(), rowValues_, columnIndices_, type, result);
Q_ASSERT(success);
}
void AnchorLayoutConstraintSolver::setMinimizeObjective(QVector<float> objectiveRow)
{
for (int i=0; i<numVariables_; ++i)
{
columnIndices_[i] = i+1;
rowValues_[i] = (double) objectiveRow[i];
}
bool success = set_obj_fnex(lp_, numVariables_, rowValues_, columnIndices_);
Q_ASSERT(success);
}
QVector<float> AnchorLayoutConstraintSolver::solveConstraints()
{
set_add_rowmode(lp_, false);
set_verbose(lp_, CRITICAL);
// Make sure to reset the basis between calls in order to get the correct result
default_basis(lp_);
int success = solve(lp_);
if (success != OPTIMAL) throw VisualizationException("Failed to solve anchor constraints.");
get_variables(lp_, rowValues_);
QVector<float> result;
for (int i=0; i<numVariables_; ++i)
result.append((float) rowValues_[i]);
return result;
}
void AnchorLayoutConstraintSolver::initializeConstraintSolver(int numVariables)
{
lp_ = make_lp(0, numVariables);
Q_ASSERT(lp_ != nullptr);
rowValues_ = new double[numVariables];
columnIndices_ = new int[numVariables];
numVariables_ = numVariables;
set_add_rowmode(lp_, true);
}
void AnchorLayoutConstraintSolver::cleanUpConstraintSolver()
{
if (lp_)
{
delete_lp(lp_);
lp_ = nullptr;
}
if (rowValues_)
{
delete [] rowValues_;
rowValues_ = nullptr;
}
if (columnIndices_)
{
delete [] columnIndices_;
columnIndices_ = nullptr;
}
}
}
<|endoftext|> |
<commit_before>#include "chainparamsbase.h"
#include "callrpc.h"
#include "util.h"
#include "utilstrencodings.h"
#include "rpc/protocol.h"
#include "support/events.h"
#include "rpc/client.h"
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params, bool connectToMainchain)
{
std::string strhost = "-rpcconnect";
std::string strport = "-rpcport";
std::string struser = "-rpcuser";
std::string strpassword = "-rpcpassword";
int port = GetArg(strport, BaseParams().RPCPort());
if (connectToMainchain) {
strhost = "-mainchainhost";
strport = "-mainchainrpcport";
strpassword = "-mainchainrpcpassword";
struser = "-mainchainrpcuser";
port = GetArg(strport, BaseParams().MainchainRPCPort());
}
std::string host = GetArg(strhost, DEFAULT_RPCCONNECT);
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!connectToMainchain && !GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
// Try fall back to cookie-based authentication if no password is provided
if (connectToMainchain && !GetMainchainAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
if (struser == "")
throw std::runtime_error(
_("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcuser is set in the configuration file"));
else
strRPCUserColonPass = GetArg(struser, "") + ":" + GetArg(strpassword, "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
else if (response.status == HTTP_UNAUTHORIZED)
if (connectToMainchain)
throw std::runtime_error("incorrect mainchainrpcuser or mainchainrpcpassword (authorization failed)");
else
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
bool IsConfirmedBitcoinBlock(const uint256& hash, int nMinConfirmationDepth)
{
try {
UniValue params(UniValue::VARR);
params.push_back(hash.GetHex());
UniValue reply = CallRPC("getblockheader", params, true);
if (!find_value(reply, "error").isNull())
return false;
UniValue result = find_value(reply, "result");
if (!result.isObject())
return false;
result = find_value(result.get_obj(), "confirmations");
return result.isNum() && result.get_int64() >= nMinConfirmationDepth;
} catch (CConnectionFailed& e) {
LogPrintf("ERROR: Lost connection to bitcoind RPC, you will want to restart after fixing this!\n");
return false;
} catch (...) {
LogPrintf("ERROR: Failure connecting to bitcoind RPC, you will want to restart after fixing this!\n");
return false;
}
return true;
}
<commit_msg>callrpc: Check correct mainchainrpc field<commit_after>#include "chainparamsbase.h"
#include "callrpc.h"
#include "util.h"
#include "utilstrencodings.h"
#include "rpc/protocol.h"
#include "support/events.h"
#include "rpc/client.h"
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params, bool connectToMainchain)
{
std::string strhost = "-rpcconnect";
std::string strport = "-rpcport";
std::string struser = "-rpcuser";
std::string strpassword = "-rpcpassword";
int port = GetArg(strport, BaseParams().RPCPort());
if (connectToMainchain) {
strhost = "-mainchainhost";
strport = "-mainchainrpcport";
strpassword = "-mainchainrpcpassword";
struser = "-mainchainrpcuser";
port = GetArg(strport, BaseParams().MainchainRPCPort());
}
std::string host = GetArg(strhost, DEFAULT_RPCCONNECT);
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg(strpassword, "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!connectToMainchain && !GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
// Try fall back to cookie-based authentication if no password is provided
if (connectToMainchain && !GetMainchainAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
if (struser == "")
throw std::runtime_error(
_("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcuser is set in the configuration file"));
else
strRPCUserColonPass = GetArg(struser, "") + ":" + GetArg(strpassword, "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
else if (response.status == HTTP_UNAUTHORIZED)
if (connectToMainchain)
throw std::runtime_error("incorrect mainchainrpcuser or mainchainrpcpassword (authorization failed)");
else
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
bool IsConfirmedBitcoinBlock(const uint256& hash, int nMinConfirmationDepth)
{
try {
UniValue params(UniValue::VARR);
params.push_back(hash.GetHex());
UniValue reply = CallRPC("getblockheader", params, true);
if (!find_value(reply, "error").isNull())
return false;
UniValue result = find_value(reply, "result");
if (!result.isObject())
return false;
result = find_value(result.get_obj(), "confirmations");
return result.isNum() && result.get_int64() >= nMinConfirmationDepth;
} catch (CConnectionFailed& e) {
LogPrintf("ERROR: Lost connection to bitcoind RPC, you will want to restart after fixing this!\n");
return false;
} catch (...) {
LogPrintf("ERROR: Failure connecting to bitcoind RPC, you will want to restart after fixing this!\n");
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/*-
* Copyright (c) 2015 Masayoshi Mizutani <[email protected]>
* 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 FOUNDATION 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 <regex>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include "./gtest.h"
#include "./FluentTest.hpp"
#include "../src/fluent/emitter.hpp"
#include "../src/debug.h"
TEST_F(FluentTest, InetEmitter) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("url", "https://github.com");
msg->set("port", 443);
// msg should be deleted by Emitter after sending
e->emit(msg);
std::string res_tag, res_ts, res_rec;
EXPECT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"port\":443,\"url\":\"https://github.com\"}");
delete e;
}
TEST_F(FluentTest, InetEmitter_with_string_portnum) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", "24224");
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("url", "https://github.com");
msg->set("port", 443);
// msg should be deleted by Emitter after sending
e->emit(msg);
std::string res_tag, res_ts, res_rec;
EXPECT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"port\":443,\"url\":\"https://github.com\"}");
delete e;
}
TEST_F(FluentTest, InetEmitter_QueueLimit) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
std::string res_tag, res_ts, res_rec;
e->set_queue_limit(1);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("num", 0);
// msg should be deleted by Emitter after sending
e->emit(msg);
ASSERT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"num\":0}");
this->stop_fluent();
// First emit after stopping fluentd should be succeess
// because of sending message.
msg = new fluent::Message(tag);
msg->set("num", 1);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Second emit should be succeess because of storing message in buffer.
msg = new fluent::Message(tag);
msg->set("num", 2);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Third emit should be fail because buffer is full.
msg = new fluent::Message(tag);
msg->set("num", 3);
EXPECT_FALSE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
delete e;
}
TEST(FileEmitter, basic) {
struct stat st;
const std::string fname = "fileemitter_test_output.msg";
const std::string tag = "test.file";
if (0 == ::stat(fname.c_str(), &st)) {
ASSERT_TRUE(0 == unlink(fname.c_str()));
}
fluent::FileEmitter *e = new fluent::FileEmitter(fname);
fluent::Message *msg = new fluent::Message(tag);
msgpack::sbuffer sbuf;
msgpack::packer<msgpack::sbuffer> pkr(&sbuf);
msg->set("num", 1);
msg->set_ts(100000);
msg->to_msgpack(&pkr);
EXPECT_TRUE(e->emit(msg));
delete e;
ASSERT_EQ (0, ::stat(fname.c_str(), &st));
uint8_t buf[BUFSIZ];
int fd = ::open(fname.c_str(), O_RDONLY);
ASSERT_TRUE(fd > 0);
int readsize = ::read(fd, buf, sizeof(buf));
ASSERT_TRUE(readsize > 0);
EXPECT_EQ(sbuf.size(), readsize);
EXPECT_TRUE(0 == memcmp(sbuf.data(), buf, sbuf.size()));
EXPECT_TRUE(0 == unlink(fname.c_str()));
}
TEST(QueueEmitter, basic) {
const std::string tag = "test.queue";
fluent::MsgQueue *q = new fluent::MsgQueue();
fluent::QueueEmitter *qe = new fluent::QueueEmitter(q);
fluent::Message *msg1 = new fluent::Message(tag);
msg1->set("seq", 1);
EXPECT_EQ(nullptr, q->pop());
// Emit (store the message)
EXPECT_TRUE(qe->emit(msg1));
fluent::Message *msg2 = new fluent::Message(tag);
msg2->set("seq", 2);
// Emit (store the message)
EXPECT_TRUE(qe->emit(msg2));
// Fetch the stored message.
fluent::Message *pmsg;
// First message
pmsg = q->pop();
ASSERT_NE(nullptr, pmsg);
const fluent::Message::Fixnum &fn1 =
pmsg->get("seq").as<fluent::Message::Fixnum>();
EXPECT_EQ(1, fn1.val());
delete pmsg;
// Second message
pmsg = q->pop();
ASSERT_NE(nullptr, pmsg);
const fluent::Message::Fixnum &fn2 =
pmsg->get("seq").as<fluent::Message::Fixnum>();
EXPECT_EQ(2, fn2.val());
delete pmsg;
// No messages.
EXPECT_EQ(nullptr, q->pop());
}
<commit_msg>change comparison tests for pointers<commit_after>/*-
* Copyright (c) 2015 Masayoshi Mizutani <[email protected]>
* 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 FOUNDATION 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 <regex>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include "./gtest.h"
#include "./FluentTest.hpp"
#include "../src/fluent/emitter.hpp"
#include "../src/debug.h"
TEST_F(FluentTest, InetEmitter) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("url", "https://github.com");
msg->set("port", 443);
// msg should be deleted by Emitter after sending
e->emit(msg);
std::string res_tag, res_ts, res_rec;
EXPECT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"port\":443,\"url\":\"https://github.com\"}");
delete e;
}
TEST_F(FluentTest, InetEmitter_with_string_portnum) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", "24224");
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("url", "https://github.com");
msg->set("port", 443);
// msg should be deleted by Emitter after sending
e->emit(msg);
std::string res_tag, res_ts, res_rec;
EXPECT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"port\":443,\"url\":\"https://github.com\"}");
delete e;
}
TEST_F(FluentTest, InetEmitter_QueueLimit) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
std::string res_tag, res_ts, res_rec;
e->set_queue_limit(1);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("num", 0);
// msg should be deleted by Emitter after sending
e->emit(msg);
ASSERT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"num\":0}");
this->stop_fluent();
// First emit after stopping fluentd should be succeess
// because of sending message.
msg = new fluent::Message(tag);
msg->set("num", 1);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Second emit should be succeess because of storing message in buffer.
msg = new fluent::Message(tag);
msg->set("num", 2);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Third emit should be fail because buffer is full.
msg = new fluent::Message(tag);
msg->set("num", 3);
EXPECT_FALSE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
delete e;
}
TEST(FileEmitter, basic) {
struct stat st;
const std::string fname = "fileemitter_test_output.msg";
const std::string tag = "test.file";
if (0 == ::stat(fname.c_str(), &st)) {
ASSERT_TRUE(0 == unlink(fname.c_str()));
}
fluent::FileEmitter *e = new fluent::FileEmitter(fname);
fluent::Message *msg = new fluent::Message(tag);
msgpack::sbuffer sbuf;
msgpack::packer<msgpack::sbuffer> pkr(&sbuf);
msg->set("num", 1);
msg->set_ts(100000);
msg->to_msgpack(&pkr);
EXPECT_TRUE(e->emit(msg));
delete e;
ASSERT_EQ (0, ::stat(fname.c_str(), &st));
uint8_t buf[BUFSIZ];
int fd = ::open(fname.c_str(), O_RDONLY);
ASSERT_TRUE(fd > 0);
int readsize = ::read(fd, buf, sizeof(buf));
ASSERT_TRUE(readsize > 0);
EXPECT_EQ(sbuf.size(), readsize);
EXPECT_TRUE(0 == memcmp(sbuf.data(), buf, sbuf.size()));
EXPECT_TRUE(0 == unlink(fname.c_str()));
}
TEST(QueueEmitter, basic) {
const std::string tag = "test.queue";
fluent::MsgQueue *q = new fluent::MsgQueue();
fluent::QueueEmitter *qe = new fluent::QueueEmitter(q);
fluent::Message *msg1 = new fluent::Message(tag);
msg1->set("seq", 1);
EXPECT_TRUE(nullptr == q->pop());
// Emit (store the message)
EXPECT_TRUE(qe->emit(msg1));
fluent::Message *msg2 = new fluent::Message(tag);
msg2->set("seq", 2);
// Emit (store the message)
EXPECT_TRUE(qe->emit(msg2));
// Fetch the stored message.
fluent::Message *pmsg;
// First message
pmsg = q->pop();
ASSERT_TRUE(nullptr != pmsg);
const fluent::Message::Fixnum &fn1 =
pmsg->get("seq").as<fluent::Message::Fixnum>();
EXPECT_EQ(1, fn1.val());
delete pmsg;
// Second message
pmsg = q->pop();
ASSERT_TRUE(nullptr != pmsg);
const fluent::Message::Fixnum &fn2 =
pmsg->get("seq").as<fluent::Message::Fixnum>();
EXPECT_EQ(2, fn2.val());
delete pmsg;
// No messages.
EXPECT_TRUE(nullptr == q->pop());
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <TAlienCollection.h>
#include <TFile.h>
#include <TGrid.h>
#include <TGridResult.h>
#include <TMath.h>
#include <TROOT.h>
#include <TString.h>
#include <TSystem.h>
#include "AliCDBManager.h"
#include "AliDAQ.h"
#include "AliLog.h"
#include "AliQA.h"
#include "AliQADataMakerSteer.h"
#include "AliRawReader.h"
#include "AliRawReaderRoot.h"
#include "AliTRDrawStreamBase.h"
#include "AliGeomManager.h"
TString ClassName() { return "rawqa" ; }
//________________________________qa______________________________________
void rawqa(const Int_t runNumber, Int_t maxFiles = 10, const char* year = "08")
{
char * kDefaultOCDBStorage = Form("alien://folder=/alice/data/20%s/LHC%sc/OCDB/", year, year) ;
//AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), year)) ;
AliQA::SetQARefStorage("local://$ALICE_ROOT") ;
AliQA::SetQARefDataDirName(AliQA::kMONTECARLO) ; //RUN_TYPE
UInt_t maxEvents = 99999 ;
if ( maxFiles < 0 ) {
maxEvents = TMath::Abs(maxFiles) ;
maxFiles = 99 ;
}
AliLog::SetGlobalDebugLevel(0) ;
// connect to the grid
TGrid * grid = 0x0 ;
grid = TGrid::Connect("alien://") ;
Bool_t detIn[AliDAQ::kNDetectors] = {kFALSE} ;
char * detNameOff[AliDAQ::kNDetectors] = {"ITS", "ITS", "ITS", "TPC", "TRD", "TOF", "HMPID", "PHOS", "PHOS", "PMD", "MUON", "MUON", "FMD", "T0", "VZERO", "ZDC", "ACORDE", "TRG", "EMCAL", "DAQ_TEST", "HLT"} ;
// make the file name pattern year and run number
TString pattern;
pattern.Form("%9d",runNumber);
pattern.ReplaceAll(" ", "0") ;
pattern.Prepend(year);
pattern.Append("*.root");
// find the files associated to this run
TGridResult * result = 0x0 ;
Bool_t local = kFALSE ;
if (grid) { // get the list of files from AliEn directly
TString collectionFile(pattern) ;
collectionFile.ReplaceAll("*.root", ".xml") ;
if ( gSystem->AccessPathName(collectionFile) == 0 ) { // get the list of files from an a-priori created collection file
TAlienCollection collection(collectionFile.Data(), maxFiles) ;
result = collection.GetGridResult("", 0, 0);
} else {
TString baseDir;
baseDir.Form("/alice/data/20%s/",year);
result = grid->Query(baseDir, pattern) ;
}
} else {
// get the list of files from the local current directory
local = kTRUE ;
char line[100] ;
sprintf(line, ".! ls %s*.root > tempo.txt", pattern.Data()) ;
gROOT->ProcessLine(line) ;
}
AliLog::Flush();
ifstream in ;
if (local)
in.open("tempo.txt", ifstream::in) ;
AliQADataMakerSteer qas ;
TString detectors = "";
TString detectorsW = "";
UShort_t file = 0 ;
UShort_t filesProcessed = 0 ;
UShort_t eventsProcessed = 0 ;
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage(kDefaultOCDBStorage) ;
man->SetRun(runNumber) ;
AliGeomManager::LoadGeometry();
for ( file = 0 ; file < maxFiles ; file++) {
if ( qas.GetCurrentEvent() >= maxEvents)
break ;
TString fileName ;
if ( local) {
in >> fileName ;
}
else
fileName = result->GetKey(file, "turl");
if ( fileName == "" )
break ;
if ( fileName.Contains("tag") )
continue;
filesProcessed++ ;
char input[200] ;
if (local)
sprintf(input, "%s", fileName.Data()) ;
else
sprintf(input, "%s", result->GetKey(file, "turl"));
AliInfo(Form("Proccessing file # %d --> %s", file, input)) ;
AliLog::Flush();
// check which detectors are present
AliRawReader * rawReader = new AliRawReaderRoot(input);
AliTRDrawStreamBase::SetRawStreamVersion("TB");
while ( rawReader->NextEvent() ) {
man->SetRun(rawReader->GetRunNumber());
AliLog::Flush();
UChar_t * data ;
while (rawReader->ReadNextData(data)) {
Int_t detID = rawReader->GetDetectorID();
if (detID < 0 || detID >= AliDAQ::kNDetectors) {
AliError("Wrong detector ID! Skipping payload...");
continue;
}
detIn[detID] = kTRUE ;
}
for (Int_t detID = 0; detID < AliDAQ::kNDetectors ; detID++) {
if (detIn[detID]) {
if ( ! detectors.Contains(detNameOff[detID]) ) {
detectors.Append(detNameOff[detID]) ;
detectors.Append(" ") ;
}
}
}
if ( !detectors.IsNull() )
break ;
}
if ( !detectors.IsNull() ) {
qas.SetMaxEvents(maxEvents) ;
detectorsW = qas.Run(detectors, rawReader) ;
qas.Reset() ;
} else {
AliError("No valid detectors found") ;
}
delete rawReader ;
eventsProcessed += qas.GetCurrentEvent() ;
}
AliLog::Flush();
qas.Merge(runNumber) ;
AliLog::Flush();
// The summary
AliInfo(Form("\n\n********** Summary for run %d **********", runNumber)) ;
printf(" detectors present in the run : %s\n", detectors.Data()) ;
printf(" detectors present in the run with QA: %s\n", detectorsW.Data()) ;
printf(" number of files/events processed : %d/%d\n", filesProcessed, eventsProcessed) ;
TFile * qaResult = TFile::Open(AliQA::GetQAResultFileName()) ;
if ( qaResult ) {
AliQA * qa = dynamic_cast<AliQA *>(qaResult->Get(AliQA::GetQAName())) ;
if ( qa) {
for (Int_t index = 0 ; index < AliQA::kNDET ; index++)
if (detectorsW.Contains(AliQA::GetDetName(AliQA::DETECTORINDEX_t(index))))
qa->ShowStatus(AliQA::DETECTORINDEX_t(index)) ;
} else {
AliError(Form("%s not found in %s !", AliQA::GetQAName(), AliQA::GetQAResultFileName())) ;
}
} else {
AliError(Form("%s has not been produced !", AliQA::GetQAResultFileName())) ;
}
}
<commit_msg>correct call to QADataMakerSteer ctor<commit_after>#include <iostream>
#include <fstream>
#include <TAlienCollection.h>
#include <TFile.h>
#include <TGrid.h>
#include <TGridResult.h>
#include <TMath.h>
#include <TROOT.h>
#include <TString.h>
#include <TSystem.h>
#include "AliCDBManager.h"
#include "AliDAQ.h"
#include "AliLog.h"
#include "AliQA.h"
#include "AliQADataMakerSteer.h"
#include "AliRawReader.h"
#include "AliRawReaderRoot.h"
#include "AliTRDrawStreamBase.h"
#include "AliGeomManager.h"
TString ClassName() { return "rawqa" ; }
//________________________________qa______________________________________
void rawqa(const Int_t runNumber, Int_t maxFiles = 10, const char* year = "08")
{
char * kDefaultOCDBStorage = Form("alien://folder=/alice/data/20%s/LHC%sc/OCDB/", year, year) ;
//AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), year)) ;
AliQA::SetQARefStorage("local://$ALICE_ROOT") ;
AliQA::SetQARefDataDirName(AliQA::kMONTECARLO) ; //RUN_TYPE
UInt_t maxEvents = 99999 ;
if ( maxFiles < 0 ) {
maxEvents = TMath::Abs(maxFiles) ;
maxFiles = 99 ;
}
AliLog::SetGlobalDebugLevel(0) ;
// connect to the grid
TGrid * grid = 0x0 ;
grid = TGrid::Connect("alien://") ;
Bool_t detIn[AliDAQ::kNDetectors] = {kFALSE} ;
char * detNameOff[AliDAQ::kNDetectors] = {"ITS", "ITS", "ITS", "TPC", "TRD", "TOF", "HMPID", "PHOS", "PHOS", "PMD", "MUON", "MUON", "FMD", "T0", "VZERO", "ZDC", "ACORDE", "TRG", "EMCAL", "DAQ_TEST", "HLT"} ;
// make the file name pattern year and run number
TString pattern;
pattern.Form("%9d",runNumber);
pattern.ReplaceAll(" ", "0") ;
pattern.Prepend(year);
pattern.Append("*.root");
// find the files associated to this run
TGridResult * result = 0x0 ;
Bool_t local = kFALSE ;
if (grid) { // get the list of files from AliEn directly
TString collectionFile(pattern) ;
collectionFile.ReplaceAll("*.root", ".xml") ;
if ( gSystem->AccessPathName(collectionFile) == 0 ) { // get the list of files from an a-priori created collection file
TAlienCollection collection(collectionFile.Data(), maxFiles) ;
result = collection.GetGridResult("", 0, 0);
} else {
TString baseDir;
baseDir.Form("/alice/data/20%s/",year);
result = grid->Query(baseDir, pattern) ;
}
} else {
// get the list of files from the local current directory
local = kTRUE ;
char line[100] ;
sprintf(line, ".! ls %s*.root > tempo.txt", pattern.Data()) ;
gROOT->ProcessLine(line) ;
}
AliLog::Flush();
ifstream in ;
if (local)
in.open("tempo.txt", ifstream::in) ;
AliQADataMakerSteer qas("rec") ;
TString detectors = "";
TString detectorsW = "";
UShort_t file = 0 ;
UShort_t filesProcessed = 0 ;
UShort_t eventsProcessed = 0 ;
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage(kDefaultOCDBStorage) ;
man->SetRun(runNumber) ;
AliGeomManager::LoadGeometry();
for ( file = 0 ; file < maxFiles ; file++) {
if ( qas.GetCurrentEvent() >= maxEvents)
break ;
TString fileName ;
if ( local) {
in >> fileName ;
}
else
fileName = result->GetKey(file, "turl");
if ( fileName == "" )
break ;
if ( fileName.Contains("tag") )
continue;
filesProcessed++ ;
char input[200] ;
if (local)
sprintf(input, "%s", fileName.Data()) ;
else
sprintf(input, "%s", result->GetKey(file, "turl"));
AliInfo(Form("Proccessing file # %d --> %s", file, input)) ;
AliLog::Flush();
// check which detectors are present
AliRawReader * rawReader = new AliRawReaderRoot(input);
AliTRDrawStreamBase::SetRawStreamVersion("TB");
while ( rawReader->NextEvent() ) {
man->SetRun(rawReader->GetRunNumber());
AliLog::Flush();
UChar_t * data ;
while (rawReader->ReadNextData(data)) {
Int_t detID = rawReader->GetDetectorID();
if (detID < 0 || detID >= AliDAQ::kNDetectors) {
AliError("Wrong detector ID! Skipping payload...");
continue;
}
detIn[detID] = kTRUE ;
}
for (Int_t detID = 0; detID < AliDAQ::kNDetectors ; detID++) {
if (detIn[detID]) {
if ( ! detectors.Contains(detNameOff[detID]) ) {
detectors.Append(detNameOff[detID]) ;
detectors.Append(" ") ;
}
}
}
if ( !detectors.IsNull() )
break ;
}
if ( !detectors.IsNull() ) {
qas.SetMaxEvents(maxEvents) ;
detectorsW = qas.Run(detectors, rawReader) ;
qas.Reset() ;
} else {
AliError("No valid detectors found") ;
}
delete rawReader ;
eventsProcessed += qas.GetCurrentEvent() ;
}
AliLog::Flush();
qas.Merge(runNumber) ;
AliLog::Flush();
// The summary
AliInfo(Form("\n\n********** Summary for run %d **********", runNumber)) ;
printf(" detectors present in the run : %s\n", detectors.Data()) ;
printf(" detectors present in the run with QA: %s\n", detectorsW.Data()) ;
printf(" number of files/events processed : %d/%d\n", filesProcessed, eventsProcessed) ;
TFile * qaResult = TFile::Open(AliQA::GetQAResultFileName()) ;
if ( qaResult ) {
AliQA * qa = dynamic_cast<AliQA *>(qaResult->Get(AliQA::GetQAName())) ;
if ( qa) {
for (Int_t index = 0 ; index < AliQA::kNDET ; index++)
if (detectorsW.Contains(AliQA::GetDetName(AliQA::DETECTORINDEX_t(index))))
qa->ShowStatus(AliQA::DETECTORINDEX_t(index)) ;
} else {
AliError(Form("%s not found in %s !", AliQA::GetQAName(), AliQA::GetQAResultFileName())) ;
}
} else {
AliError(Form("%s has not been produced !", AliQA::GetQAResultFileName())) ;
}
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MaterialVectorPostprocessor.h"
#include "Material.h"
#include "IndirectSort.h"
#include "libmesh/quadrature.h"
#include <numeric>
template<>
InputParameters validParams<MaterialVectorPostprocessor>()
{
InputParameters params = validParams<ElementVectorPostprocessor>();
params.addRequiredParam<MaterialName>("material", "Material for which all properties will be recorded.");
params.addRequiredParam<std::vector<unsigned int>>("elem_ids", "Element IDs to print data for (others are ignored).");
return params;
}
MaterialVectorPostprocessor::MaterialVectorPostprocessor(const InputParameters & parameters) :
ElementVectorPostprocessor(parameters),
_elem_filter(getParam<std::vector<unsigned int>>("elem_ids").begin(), getParam<std::vector<unsigned int>>("elem_ids").end()),
_elem_ids(declareVector("elem_id")),
_qp_ids(declareVector("qp_id"))
{
auto & mat = getMaterialByName(getParam<MaterialName>("material"), true);
auto & prop_names = mat.getSuppliedItems();
for (auto & prop : prop_names)
{
if (hasMaterialProperty<Real>(prop))
_prop_refs.push_back(&getMaterialProperty<Real>(prop));
else if (hasMaterialProperty<unsigned int>(prop))
_prop_refs.push_back(&getMaterialProperty<unsigned int>(prop));
else if (hasMaterialProperty<int>(prop))
_prop_refs.push_back(&getMaterialProperty<int>(prop));
else
{
mooseWarning("property " + prop + " is of unsupported type and skipped by MaterialVectorPostProcessor");
continue;
}
_prop_vecs.push_back(&declareVector(prop));
_prop_names.push_back(prop);
}
}
void
MaterialVectorPostprocessor::execute()
{
unsigned int elem_id = _current_elem->id();
if (_elem_filter.count(elem_id) == 0)
return;
unsigned int nqp = _qrule->n_points();
for (unsigned int qp = 0; qp < nqp; qp++)
{
_elem_ids.push_back(elem_id);
_qp_ids.push_back(qp);
}
for (unsigned int i = 0; i < _prop_names.size(); i++)
{
auto prop_name = _prop_names[i];
auto prop = _prop_vecs[i];
std::vector<Real> vals;
if (hasMaterialProperty<Real>(prop_name))
{
auto vals = dynamic_cast<const MaterialProperty<Real> *>(_prop_refs[i]);
for (unsigned int qp = 0; qp < nqp; qp++)
prop->push_back((*vals)[qp]);
}
else if (hasMaterialProperty<unsigned int>(prop_name))
{
auto vals = dynamic_cast<const MaterialProperty<unsigned int> *>(_prop_refs[i]);
for (unsigned int qp = 0; qp < nqp; qp++)
prop->push_back((*vals)[qp]);
}
else if (hasMaterialProperty<int>(prop_name))
{
auto vals = dynamic_cast<const MaterialProperty<int> *>(_prop_refs[i]);
for (unsigned int qp = 0; qp < nqp; qp++)
prop->push_back((*vals)[qp]);
}
}
}
void
MaterialVectorPostprocessor::finalize()
{
// collect all processor data
comm().gather(0, _elem_ids);
comm().gather(0, _qp_ids);
for (auto vec : _prop_vecs)
comm().gather(0, *vec);
sortVecs();
}
void
MaterialVectorPostprocessor::threadJoin(const UserObject & y)
{
auto & vpp = static_cast<const MaterialVectorPostprocessor &>(y);
_elem_ids.insert(_elem_ids.end(), vpp._elem_ids.begin(), vpp._elem_ids.end());
_qp_ids.insert(_qp_ids.end(), vpp._qp_ids.begin(), vpp._qp_ids.end());
for (unsigned int i = 0; i < _prop_vecs.size(); i++)
{
auto & vec = *_prop_vecs[i];
auto & othervec = *vpp._prop_vecs[i];
vec.insert(vec.end(), othervec.begin(), othervec.end());
}
sortVecs();
}
void
MaterialVectorPostprocessor::sortVecs()
{
std::vector<size_t> ind;
ind.resize(_elem_ids.size());
std::iota(ind.begin(), ind.end(), 0);
std::sort(ind.begin(), ind.end(), [&](size_t a, size_t b) -> bool {
if (_elem_ids[a] == _elem_ids[b]) {
return _qp_ids[a] < _qp_ids[b];
}
return _elem_ids[a] < _elem_ids[b];
});
Moose::applyIndices(_elem_ids, ind);
Moose::applyIndices(_qp_ids, ind);
for (auto vec : _prop_vecs)
Moose::applyIndices(*vec, ind);
}
<commit_msg>add boundary material check<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MaterialVectorPostprocessor.h"
#include "Material.h"
#include "IndirectSort.h"
#include "libmesh/quadrature.h"
#include <numeric>
template<>
InputParameters validParams<MaterialVectorPostprocessor>()
{
InputParameters params = validParams<ElementVectorPostprocessor>();
params.addRequiredParam<MaterialName>("material", "Material for which all properties will be recorded.");
params.addRequiredParam<std::vector<unsigned int>>("elem_ids", "Element IDs to print data for (others are ignored).");
return params;
}
MaterialVectorPostprocessor::MaterialVectorPostprocessor(const InputParameters & parameters) :
ElementVectorPostprocessor(parameters),
_elem_filter(getParam<std::vector<unsigned int>>("elem_ids").begin(), getParam<std::vector<unsigned int>>("elem_ids").end()),
_elem_ids(declareVector("elem_id")),
_qp_ids(declareVector("qp_id"))
{
auto & mat = getMaterialByName(getParam<MaterialName>("material"), true);
auto & prop_names = mat.getSuppliedItems();
if (mat.isBoundaryMaterial())
mooseError("boundary materials (i.e. ", _mat.name(), ") cannot be used with MaterialVectorPostprocessor");
for (auto & prop : prop_names)
{
if (hasMaterialProperty<Real>(prop))
_prop_refs.push_back(&getMaterialProperty<Real>(prop));
else if (hasMaterialProperty<unsigned int>(prop))
_prop_refs.push_back(&getMaterialProperty<unsigned int>(prop));
else if (hasMaterialProperty<int>(prop))
_prop_refs.push_back(&getMaterialProperty<int>(prop));
else
{
mooseWarning("property " + prop + " is of unsupported type and skipped by MaterialVectorPostprocessor");
continue;
}
_prop_vecs.push_back(&declareVector(prop));
_prop_names.push_back(prop);
}
}
void
MaterialVectorPostprocessor::execute()
{
unsigned int elem_id = _current_elem->id();
if (_elem_filter.count(elem_id) == 0)
return;
unsigned int nqp = _qrule->n_points();
for (unsigned int qp = 0; qp < nqp; qp++)
{
_elem_ids.push_back(elem_id);
_qp_ids.push_back(qp);
}
for (unsigned int i = 0; i < _prop_names.size(); i++)
{
auto prop_name = _prop_names[i];
auto prop = _prop_vecs[i];
std::vector<Real> vals;
if (hasMaterialProperty<Real>(prop_name))
{
auto vals = dynamic_cast<const MaterialProperty<Real> *>(_prop_refs[i]);
for (unsigned int qp = 0; qp < nqp; qp++)
prop->push_back((*vals)[qp]);
}
else if (hasMaterialProperty<unsigned int>(prop_name))
{
auto vals = dynamic_cast<const MaterialProperty<unsigned int> *>(_prop_refs[i]);
for (unsigned int qp = 0; qp < nqp; qp++)
prop->push_back((*vals)[qp]);
}
else if (hasMaterialProperty<int>(prop_name))
{
auto vals = dynamic_cast<const MaterialProperty<int> *>(_prop_refs[i]);
for (unsigned int qp = 0; qp < nqp; qp++)
prop->push_back((*vals)[qp]);
}
}
}
void
MaterialVectorPostprocessor::finalize()
{
// collect all processor data
comm().gather(0, _elem_ids);
comm().gather(0, _qp_ids);
for (auto vec : _prop_vecs)
comm().gather(0, *vec);
sortVecs();
}
void
MaterialVectorPostprocessor::threadJoin(const UserObject & y)
{
auto & vpp = static_cast<const MaterialVectorPostprocessor &>(y);
_elem_ids.insert(_elem_ids.end(), vpp._elem_ids.begin(), vpp._elem_ids.end());
_qp_ids.insert(_qp_ids.end(), vpp._qp_ids.begin(), vpp._qp_ids.end());
for (unsigned int i = 0; i < _prop_vecs.size(); i++)
{
auto & vec = *_prop_vecs[i];
auto & othervec = *vpp._prop_vecs[i];
vec.insert(vec.end(), othervec.begin(), othervec.end());
}
sortVecs();
}
void
MaterialVectorPostprocessor::sortVecs()
{
std::vector<size_t> ind;
ind.resize(_elem_ids.size());
std::iota(ind.begin(), ind.end(), 0);
std::sort(ind.begin(), ind.end(), [&](size_t a, size_t b) -> bool {
if (_elem_ids[a] == _elem_ids[b]) {
return _qp_ids[a] < _qp_ids[b];
}
return _elem_ids[a] < _elem_ids[b];
});
Moose::applyIndices(_elem_ids, ind);
Moose::applyIndices(_qp_ids, ind);
for (auto vec : _prop_vecs)
Moose::applyIndices(*vec, ind);
}
<|endoftext|> |
<commit_before>// -*- c-basic-offset: 2; related-file-name: "loop.h" -*-
/*
* @(#)$Id$
*
*/
#include "loop.h"
#include <time.h>
#include "math.h"
#include "assert.h"
callbackQueueT callbacks;
long callbackID = 0;
timeCBHandle*
delayCB(double secondDelay, b_cbv cb)
{
assert(secondDelay >= 0.0);
// When will this expire?
struct timespec expiration;
getTime(expiration); // now
increment_timespec(expiration, secondDelay);
// Create handle for this request
timeCBHandle* handle = new timeCBHandle(expiration, cb);
// Place it into the priority queue
callbacks.insert(handle);
// Return it
return handle;
}
void
timeCBRemove(timeCBHandle* handle)
{
callbacks.erase(handle);
}
void
fileDescriptorCB(int fileDescriptor,
b_selop op,
b_cbv callback)
{
assert(false);
// Do nothing in here until the need arises
}
tcpHandle*
tcpConnect(in_addr addr, u_int16_t port, b_cbi cb)
{
return NULL;
}
/** Go up to current time and empty out the expired elements from the
callback queue */
void
timeCBCatchup()
{
struct timespec now;
getTime(now);
callbackQueueT::iterator iter = callbacks.begin();
while ((iter != callbacks.end()) &&
(compare_timespec((*iter)->time, now) <= 0)) {
// Remove this callback from the queue
timeCBHandle* theCallback = *iter;
iter++;
// Run it
(theCallback->callback)();
// And erase it
delete theCallback;
}
}
void
eventLoop()
{
while (1) {
timeCBCatchup();
}
}
<commit_msg>Now preparing for select waits in event loop<commit_after>// -*- c-basic-offset: 2; related-file-name: "loop.h" -*-
/*
* @(#)$Id$
*
*/
#include "loop.h"
#include <time.h>
#include "math.h"
#include "assert.h"
callbackQueueT callbacks;
long callbackID = 0;
timeCBHandle*
delayCB(double secondDelay, b_cbv cb)
{
assert(secondDelay >= 0.0);
// When will this expire?
struct timespec expiration;
getTime(expiration); // now
increment_timespec(expiration, secondDelay);
// Create handle for this request
timeCBHandle* handle = new timeCBHandle(expiration, cb);
// Place it into the priority queue
callbacks.insert(handle);
// Return it
return handle;
}
void
timeCBRemove(timeCBHandle* handle)
{
callbacks.erase(handle);
}
void
fileDescriptorCB(int fileDescriptor,
b_selop op,
b_cbv callback)
{
assert(false);
// Do nothing in here until the need arises
}
tcpHandle*
tcpConnect(in_addr addr, u_int16_t port, b_cbi cb)
{
return NULL;
}
/** Go up to current time and empty out the expired elements from the
callback queue */
void
timeCBCatchup(struct timespec& waitDuration)
{
struct timespec now;
getTime(now);
////////////////////////////////////////////////////////////
// Empty the queue prefix that has already expired
callbackQueueT::iterator iter = callbacks.begin();
while ((iter != callbacks.end()) &&
(compare_timespec((*iter)->time, now) <= 0)) {
// Remove this callback from the queue
timeCBHandle* theCallback = *iter;
iter++;
// Run it
(theCallback->callback)();
// And erase it
delete theCallback;
}
////////////////////////////////////////////////////////////
// Set the wait duration to be the time from now till the first
// scheduled event
// Update current time
getTime(now);
// Get first waiting time
if (callbacks.empty()) {
// Nothing to worry about. Set it to a minute
waitDuration.tv_sec = 60;
waitDuration.tv_nsec = 0;
} else {
iter = callbacks.begin();
assert(iter != callbacks.end()); // since it's not empty
if (compare_timespec((*iter)->time, now) < 0) {
// Oops, the first callback has already expired. Don't wait, just
// poll
waitDuration.tv_sec = 0;
waitDuration.tv_nsec = 0;
} else {
subtract_timespec(waitDuration, (*iter)->time, now);
}
}
}
/** Wait for any pending file descriptor actions for the given time
period. */
void
fileDescriptorCatchup(struct timespec& waitDuration)
{
}
void
eventLoop()
{
// The wait duration for file descriptor waits. It is set by
// timeCBCatchup and used by fileDescriptorCatchup. Equivalent to
// selwait in libasync
struct timespec waitDuration;
while (1) {
timeCBCatchup(waitDuration);
fileDescriptorCatchup(waitDuration);
}
}
<|endoftext|> |
<commit_before>#include <PCU.h>
#include <MeshSim.h>
#include <SimPartitionedMesh.h>
#include <SimUtil.h>
#include <apfSIM.h>
#include <apfMDS.h>
#include <gmi.h>
#include <gmi_sim.h>
#include <apf.h>
#include <apfConvert.h>
#include <apfMesh2.h>
#include <ma.h>
static void fixMatches(apf::Mesh2* m)
{
if (m->hasMatching()) {
if (apf::alignMdsMatches(m))
printf("fixed misaligned matches\n");
else
printf("matches were aligned\n");
assert( ! apf::alignMdsMatches(m));
}
}
static void fixPyramids(apf::Mesh2* m)
{
ma::Input* in = ma::configureIdentity(m);
in->shouldCleanupLayer = true;
ma::adapt(in);
}
static void postConvert(apf::Mesh2* m)
{
fixMatches(m);
fixPyramids(m);
m->verify();
}
int main(int argc, char** argv)
{
MPI_Init(&argc, &argv);
PCU_Comm_Init();
if (argc != 4) {
if(0==PCU_Comm_Self())
std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n";
return EXIT_FAILURE;
}
Sim_readLicenseFile(NULL);
SimPartitionedMesh_start(&argc,&argv);
gmi_sim_start();
gmi_register_sim();
pProgress progress = Progress_new();
Progress_setDefaultCallback(progress);
gmi_model* mdl = gmi_load(argv[1]);
pGModel simModel = gmi_export_sim(mdl);
pParMesh sim_mesh = PM_load(argv[2], sthreadNone, simModel, progress);
apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);
apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);
apf::printStats(mesh);
apf::destroyMesh(simApfMesh);
M_release(sim_mesh);
postConvert(mesh);
mesh->writeNative(argv[3]);
mesh->destroyNative();
apf::destroyMesh(mesh);
Progress_delete(progress);
gmi_sim_stop();
SimPartitionedMesh_stop();
Sim_unregisterAllKeys();
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>get convert to work with hex meshes<commit_after>#include <PCU.h>
#include <MeshSim.h>
#include <SimPartitionedMesh.h>
#include <SimUtil.h>
#include <apfSIM.h>
#include <apfMDS.h>
#include <gmi.h>
#include <gmi_sim.h>
#include <apf.h>
#include <apfConvert.h>
#include <apfMesh2.h>
#include <ma.h>
static void fixMatches(apf::Mesh2* m)
{
if (m->hasMatching()) {
if (apf::alignMdsMatches(m))
printf("fixed misaligned matches\n");
else
printf("matches were aligned\n");
assert( ! apf::alignMdsMatches(m));
}
}
static void fixPyramids(apf::Mesh2* m)
{
if (apf::countEntitiesOfType(m, apf::Mesh::HEX))
return; /* meshadapt can't even look at hexes */
ma::Input* in = ma::configureIdentity(m);
in->shouldCleanupLayer = true;
ma::adapt(in);
}
static void postConvert(apf::Mesh2* m)
{
fixMatches(m);
fixPyramids(m);
m->verify();
}
int main(int argc, char** argv)
{
MPI_Init(&argc, &argv);
PCU_Comm_Init();
if (argc != 4) {
if(0==PCU_Comm_Self())
std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n";
return EXIT_FAILURE;
}
Sim_readLicenseFile(NULL);
SimPartitionedMesh_start(&argc,&argv);
gmi_sim_start();
gmi_register_sim();
pProgress progress = Progress_new();
Progress_setDefaultCallback(progress);
gmi_model* mdl = gmi_load(argv[1]);
pGModel simModel = gmi_export_sim(mdl);
pParMesh sim_mesh = PM_load(argv[2], sthreadNone, simModel, progress);
apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);
apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);
apf::printStats(mesh);
apf::destroyMesh(simApfMesh);
M_release(sim_mesh);
postConvert(mesh);
mesh->writeNative(argv[3]);
mesh->destroyNative();
apf::destroyMesh(mesh);
Progress_delete(progress);
gmi_sim_stop();
SimPartitionedMesh_stop();
Sim_unregisterAllKeys();
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stichwort/keywords.hpp>
#include <string>
namespace test
{
const stichwort::ParametersForwarder kwargs;
const stichwort::DefaultValue take_default;
const stichwort::ParameterKeyword<float> a("A float", 1.0);
const stichwort::ParameterKeyword<int> b("B int", 2);
const stichwort::ParameterKeyword<double> c("C double", 3.0);
double sum(double bias, stichwort::ParametersSet kw)
{
float av = kw[a];
int bv = kw[b];
double cv = kw[c];
return bias + av + bv + cv;
}
}
TEST(Minimal,Call)
{
double sum;
ASSERT_NO_THROW(sum = test::sum(4.0,test::kwargs[test::a=test::take_default,test::b=2,test::c=3.0]));
ASSERT_NEAR(sum,10.0,1e-9);
}
<commit_msg>Updated tests<commit_after>#include <gtest/gtest.h>
#include <stichwort/keywords.hpp>
#include <string>
#include <list>
namespace test
{
namespace
{
const stichwort::ParametersForwarder kwargs;
const stichwort::DefaultValue take_default;
const stichwort::ParameterKeyword<float> a("A float", 1.0);
const stichwort::ParameterKeyword<int> b("B int", 2);
const stichwort::ParameterKeyword<double> c("C double", 3.0);
}
float select_a(stichwort::ParametersSet kw)
{
return kw[a];
}
int select_b(stichwort::ParametersSet kw)
{
return kw[b];
}
double select_c(stichwort::ParametersSet kw)
{
return kw[c];
}
struct result
{
result() : a(0.0f), b(0), c(0.0) {}
result(float a_, int b_, double c_) : a(a_), b(b_), c(c_) {}
float a;
int b;
double c;
};
result dispatch(stichwort::ParametersSet kw)
{
return result(kw[a], kw[b], kw[c]);
}
}
using namespace test;
TEST(Minimal,Call)
{
result r;
float av = 89.0f;
int bv = 56;
double cv = 35.0;
ASSERT_NO_THROW(r = dispatch(kwargs[a=av,b=bv,c=cv]));
ASSERT_EQ(r.a, av);
ASSERT_EQ(r.b, bv);
ASSERT_EQ(r.c, cv);
}
TEST(Minimal,CallCombinations)
{
std::list<stichwort::ParametersSet> combs;
stichwort::ParametersSet abc = kwargs[a=take_default,b=take_default,c=take_default];
combs.push_back(abc);
stichwort::ParametersSet acb = kwargs[a=take_default,c=take_default,b=take_default];
combs.push_back(acb);
stichwort::ParametersSet bac = kwargs[b=take_default,a=take_default,c=take_default];
combs.push_back(bac);
stichwort::ParametersSet bca = kwargs[b=take_default,c=take_default,a=take_default];
combs.push_back(bca);
stichwort::ParametersSet cab = kwargs[c=take_default,a=take_default,b=take_default];
combs.push_back(cab);
stichwort::ParametersSet cba = kwargs[c=take_default,b=take_default,a=take_default];
combs.push_back(cba);
for (std::list<stichwort::ParametersSet>::const_iterator iter=combs.begin();
iter!=combs.end();
++iter)
{
ASSERT_EQ(select_a(*iter), a.default_value);
ASSERT_EQ(select_b(*iter), b.default_value);
ASSERT_EQ(select_c(*iter), c.default_value);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbOGRDataToClassStatisticsFilter.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include <fstream>
int otbOGRDataToClassStatisticsFilterNew(int itkNotUsed(argc), char* itkNotUsed(argv) [])
{
typedef otb::VectorImage<float> InputImageType;
typedef otb::Image<unsigned char> MaskImageType;
typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
std::cout << filter << std::endl;
return EXIT_SUCCESS;
}
int otbOGRDataToClassStatisticsFilter(int argc, char* argv[])
{
typedef otb::VectorImage<float> InputImageType;
typedef otb::Image<unsigned char> MaskImageType;
typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;
if (argc < 3)
{
std::cout << "Usage : "<<argv[0]<< " input_vector output_stats" << std::endl;
}
std::string vectorPath(argv[1]);
std::string outputPath(argv[2]);
otb::ogr::DataSource::Pointer vectors = otb::ogr::DataSource::New(vectorPath);
InputImageType::RegionType region;
region.SetSize(0,99);
region.SetSize(1,50);
InputImageType::PointType origin;
origin.Fill(0.5);
InputImageType::SpacingType spacing;
spacing[0] = 1.0;
spacing[1] = -1.0;
InputImageType::PixelType pixel(3);
pixel.Fill(1);
InputImageType::Pointer inputImage = InputImageType::New();
inputImage->SetNumberOfComponentsPerPixel(3);
inputImage->SetRegions(region);
inputImage->SetOrigin(origin);
inputImage->SetSpacing(spacing);
inputImage->Allocate();
inputImage->FillBuffer(pixel);
MaskImageType::Pointer mask = MaskImageType::New();
mask->SetRegions(region);
mask->SetOrigin(origin);
mask->SetSpacing(spacing);
mask->Allocate();
itk::ImageRegionIterator<MaskImageType> it(mask,region);
unsigned int count = 0;
for (it.GoToBegin(); !it.IsAtEnd() ; ++it, ++count)
{
it.Set(count % 2);
}
std::string fieldName("Label");
FilterType::Pointer filter = FilterType::New();
filter->SetInput(inputImage);
filter->SetMask(mask);
filter->SetOGRData(vectors);
filter->SetFieldName(fieldName);
filter->SetLayerIndex(0);
filter->Update();
FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get();
FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get();
FilterType::ClassCountMapType::const_iterator itClass;
FilterType::PolygonSizeMapType::const_iterator itPoly;
std::ofstream ofs;
ofs.open(outputPath.c_str());
ofs << "# Layer 0 : polygons"<<std::endl;
ofs << "# Class sample counts"<<std::endl;
for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
{
ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
}
ofs << "# Vector sizes"<<std::endl;
for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
{
ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
}
filter->SetLayerIndex(1);
filter->Update();
ofs << "# Layer 1 : lines"<<std::endl;
ofs << "# Class sample counts"<<std::endl;
for (itClass = classCount.begin() ; itClass != classCount.end() ; ++itClass)
{
ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
}
ofs << "# Vector sizes"<<std::endl;
for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
{
ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
}
filter->SetLayerIndex(2);
filter->Update();
ofs << "# Layer 2 : points"<<std::endl;
ofs << "# Class sample counts"<<std::endl;
for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
{
ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
}
ofs << "# Vector sizes"<<std::endl;
for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
{
ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
}
ofs.close();
return EXIT_SUCCESS;
}
<commit_msg>TEST: don't allocate input image in test<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbOGRDataToClassStatisticsFilter.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include <fstream>
int otbOGRDataToClassStatisticsFilterNew(int itkNotUsed(argc), char* itkNotUsed(argv) [])
{
typedef otb::VectorImage<float> InputImageType;
typedef otb::Image<unsigned char> MaskImageType;
typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
std::cout << filter << std::endl;
return EXIT_SUCCESS;
}
int otbOGRDataToClassStatisticsFilter(int argc, char* argv[])
{
typedef otb::VectorImage<float> InputImageType;
typedef otb::Image<unsigned char> MaskImageType;
typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;
if (argc < 3)
{
std::cout << "Usage : "<<argv[0]<< " input_vector output_stats" << std::endl;
}
std::string vectorPath(argv[1]);
std::string outputPath(argv[2]);
otb::ogr::DataSource::Pointer vectors = otb::ogr::DataSource::New(vectorPath);
InputImageType::RegionType region;
region.SetSize(0,99);
region.SetSize(1,50);
InputImageType::PointType origin;
origin.Fill(0.5);
InputImageType::SpacingType spacing;
spacing[0] = 1.0;
spacing[1] = -1.0;
InputImageType::PixelType pixel(3);
pixel.Fill(1);
InputImageType::Pointer inputImage = InputImageType::New();
inputImage->SetNumberOfComponentsPerPixel(3);
inputImage->SetLargestPossibleRegion(region);
inputImage->SetOrigin(origin);
inputImage->SetSpacing(spacing);
// Don't allocate the input image, the filter should not need it
//inputImage->Allocate();
//inputImage->FillBuffer(pixel);
MaskImageType::Pointer mask = MaskImageType::New();
mask->SetRegions(region);
mask->SetOrigin(origin);
mask->SetSpacing(spacing);
mask->Allocate();
itk::ImageRegionIterator<MaskImageType> it(mask,region);
unsigned int count = 0;
for (it.GoToBegin(); !it.IsAtEnd() ; ++it, ++count)
{
it.Set(count % 2);
}
std::string fieldName("Label");
FilterType::Pointer filter = FilterType::New();
filter->SetInput(inputImage);
filter->SetMask(mask);
filter->SetOGRData(vectors);
filter->SetFieldName(fieldName);
filter->SetLayerIndex(0);
filter->Update();
FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get();
FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get();
FilterType::ClassCountMapType::const_iterator itClass;
FilterType::PolygonSizeMapType::const_iterator itPoly;
std::ofstream ofs;
ofs.open(outputPath.c_str());
ofs << "# Layer 0 : polygons"<<std::endl;
ofs << "# Class sample counts"<<std::endl;
for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
{
ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
}
ofs << "# Vector sizes"<<std::endl;
for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
{
ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
}
filter->SetLayerIndex(1);
filter->Update();
ofs << "# Layer 1 : lines"<<std::endl;
ofs << "# Class sample counts"<<std::endl;
for (itClass = classCount.begin() ; itClass != classCount.end() ; ++itClass)
{
ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
}
ofs << "# Vector sizes"<<std::endl;
for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
{
ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
}
filter->SetLayerIndex(2);
filter->Update();
ofs << "# Layer 2 : points"<<std::endl;
ofs << "# Class sample counts"<<std::endl;
for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
{
ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
}
ofs << "# Vector sizes"<<std::endl;
for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
{
ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
}
ofs.close();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "k/interrupt.h"
#include "etl/armv7m/nvic.h"
#include "etl/armv7m/scb.h"
#include "etl/assert.h"
#include "k/reply_sender.h"
#include "k/scheduler.h"
using etl::armv7m::nvic;
using etl::armv7m::scb;
using etl::armv7m::Scb;
namespace k {
/******************************************************************************
* InterruptBase
*/
InterruptBase::InterruptBase(uint32_t identifier)
: _saved_brand{0},
_target{},
_sender_item{this},
_priority{0},
_identifier{identifier} {}
void InterruptBase::trigger() {
disable_interrupt();
_target.deliver_from(this);
do_deferred_switch_from_irq();
}
void InterruptBase::deliver_from(Brand const & brand, Sender * sender) {
Message m;
Keys k;
sender->on_delivery_accepted(m, k);
switch (m.d0.get_selector()) {
case 1:
do_set_target(brand, m, k);
break;
case 2:
do_enable(brand, m, k);
break;
default:
do_extension(m.d0.get_selector(), brand, m, k);
break;
}
}
void InterruptBase::do_extension(Selector,
Brand const &,
Message const & m,
Keys & k) {
do_badop(m, k);
}
void InterruptBase::do_set_target(Brand const &, Message const &, Keys & k) {
auto & reply = k.keys[0];
auto & target = k.keys[1];
ScopedReplySender reply_sender{reply};
_target = target;
}
void InterruptBase::do_enable(Brand const &, Message const & m, Keys & k) {
ScopedReplySender reply_sender{k.keys[0]};
bool clear_pending = m.d1 != 0;
if (clear_pending) clear_pending_interrupt();
enable_interrupt();
}
Priority InterruptBase::get_priority() const {
return _priority;
}
void InterruptBase::on_delivery_accepted(Message & m, Keys & k) {
m = {
Descriptor::zero().with_selector(1),
_identifier,
};
k.keys[0] = make_key(0).ref();
for (unsigned ki = 0; ki < config::n_message_keys; ++ki) {
k.keys[ki] = Key::null();
}
}
void InterruptBase::on_delivery_failed(Exception, uint32_t) {
// Our attempt to deliver has failed. This is an indication of a
// configuration error. Do nothing for now.
// TODO: should this be able to raise some sort of alert?
}
void InterruptBase::block_in_send(Brand const & brand,
List<BlockingSender> & list) {
_saved_brand = brand;
list.insert(&_sender_item);
}
void InterruptBase::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) {
b = _saved_brand;
on_delivery_accepted(m, k);
}
void InterruptBase::on_blocked_delivery_failed(Exception, uint32_t) {
// We appear to have been interrupted while blocked.
}
/******************************************************************************
* Interrupt
*/
Interrupt::Interrupt(uint32_t irq)
: InterruptBase{irq} {}
void Interrupt::disable_interrupt() {
nvic.disable_irq(get_identifier());
}
void Interrupt::enable_interrupt() {
nvic.enable_irq(get_identifier());
}
void Interrupt::clear_pending_interrupt() {
nvic.clear_pending_irq(get_identifier());
}
} // namespace k
<commit_msg>k/interrupt: fix error in message key production.<commit_after>#include "k/interrupt.h"
#include "etl/armv7m/nvic.h"
#include "etl/armv7m/scb.h"
#include "etl/assert.h"
#include "k/reply_sender.h"
#include "k/scheduler.h"
using etl::armv7m::nvic;
using etl::armv7m::scb;
using etl::armv7m::Scb;
namespace k {
/******************************************************************************
* InterruptBase
*/
InterruptBase::InterruptBase(uint32_t identifier)
: _saved_brand{0},
_target{},
_sender_item{this},
_priority{0},
_identifier{identifier} {}
void InterruptBase::trigger() {
disable_interrupt();
_target.deliver_from(this);
do_deferred_switch_from_irq();
}
void InterruptBase::deliver_from(Brand const & brand, Sender * sender) {
Message m;
Keys k;
sender->on_delivery_accepted(m, k);
switch (m.d0.get_selector()) {
case 1:
do_set_target(brand, m, k);
break;
case 2:
do_enable(brand, m, k);
break;
default:
do_extension(m.d0.get_selector(), brand, m, k);
break;
}
}
void InterruptBase::do_extension(Selector,
Brand const &,
Message const & m,
Keys & k) {
do_badop(m, k);
}
void InterruptBase::do_set_target(Brand const &, Message const &, Keys & k) {
auto & reply = k.keys[0];
auto & target = k.keys[1];
ScopedReplySender reply_sender{reply};
_target = target;
}
void InterruptBase::do_enable(Brand const &, Message const & m, Keys & k) {
ScopedReplySender reply_sender{k.keys[0]};
bool clear_pending = m.d1 != 0;
if (clear_pending) clear_pending_interrupt();
enable_interrupt();
}
Priority InterruptBase::get_priority() const {
return _priority;
}
void InterruptBase::on_delivery_accepted(Message & m, Keys & k) {
m = {
Descriptor::zero().with_selector(1),
_identifier,
};
k.keys[0] = make_key(0).ref();
for (unsigned ki = 1; ki < config::n_message_keys; ++ki) {
k.keys[ki] = Key::null();
}
}
void InterruptBase::on_delivery_failed(Exception, uint32_t) {
// Our attempt to deliver has failed. This is an indication of a
// configuration error. Do nothing for now.
// TODO: should this be able to raise some sort of alert?
}
void InterruptBase::block_in_send(Brand const & brand,
List<BlockingSender> & list) {
_saved_brand = brand;
list.insert(&_sender_item);
}
void InterruptBase::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) {
b = _saved_brand;
on_delivery_accepted(m, k);
}
void InterruptBase::on_blocked_delivery_failed(Exception, uint32_t) {
// We appear to have been interrupted while blocked.
}
/******************************************************************************
* Interrupt
*/
Interrupt::Interrupt(uint32_t irq)
: InterruptBase{irq} {}
void Interrupt::disable_interrupt() {
nvic.disable_irq(get_identifier());
}
void Interrupt::enable_interrupt() {
nvic.enable_irq(get_identifier());
}
void Interrupt::clear_pending_interrupt() {
nvic.clear_pending_irq(get_identifier());
}
} // namespace k
<|endoftext|> |
<commit_before>#pragma once
#include <bts/blockchain/types.hpp>
namespace bts { namespace blockchain {
static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
{ 1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) },
{ 100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) },
{ 200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) },
{ 300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) },
{ 400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) },
{ 500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) },
{ 600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) },
{ 700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) },
{ 800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) },
{ 900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) },
{ 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) },
{ 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) },
{ 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) },
{ 1300000, bts::blockchain::block_id_type( "623e5c04a77b7e688299a45bfb1d84a0bf3ea318" ) },
{ 1400000, bts::blockchain::block_id_type( "f7645d369b7a818c4acb94f3bedbcb7747dea9dd" ) },
{ 1500000, bts::blockchain::block_id_type( "a9027b880105fa89f4d0c2bf9a0df328fed3108d" ) },
{ 1600000, bts::blockchain::block_id_type( "1c08742243deda31c663130fca9ab8bd825803c5" ) },
{ 1603000, bts::blockchain::block_id_type( "1d85e3e412a5289f76204840bfe77a8176b6cd58" ) }
};
} } // bts::blockchain
<commit_msg>Update checkpoint<commit_after>#pragma once
#include <bts/blockchain/types.hpp>
namespace bts { namespace blockchain {
static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
{ 1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) },
{ 100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) },
{ 200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) },
{ 300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) },
{ 400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) },
{ 500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) },
{ 600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) },
{ 700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) },
{ 800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) },
{ 900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) },
{ 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) },
{ 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) },
{ 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) },
{ 1300000, bts::blockchain::block_id_type( "623e5c04a77b7e688299a45bfb1d84a0bf3ea318" ) },
{ 1400000, bts::blockchain::block_id_type( "f7645d369b7a818c4acb94f3bedbcb7747dea9dd" ) },
{ 1500000, bts::blockchain::block_id_type( "a9027b880105fa89f4d0c2bf9a0df328fed3108d" ) },
{ 1600000, bts::blockchain::block_id_type( "1c08742243deda31c663130fca9ab8bd825803c5" ) },
{ 1637000, bts::blockchain::block_id_type( "e9410f765fc402656ebe3b09073bb2bf28017f66" ) }
};
} } // bts::blockchain
<|endoftext|> |
<commit_before>/*
* Copyright (c) [2016-2019] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include "storage/Devices/EncryptionImpl.h"
#include "storage/Devicegraph.h"
namespace storage
{
using namespace std;
Encryption*
Encryption::create(Devicegraph* devicegraph, const string& name)
{
Encryption* ret = new Encryption(new Encryption::Impl(name));
ret->Device::create(devicegraph);
return ret;
}
Encryption*
Encryption::load(Devicegraph* devicegraph, const xmlNode* node)
{
Encryption* ret = new Encryption(new Encryption::Impl(node));
ret->Device::load(devicegraph);
return ret;
}
Encryption::Encryption(Impl* impl)
: BlkDevice(impl)
{
}
MountByType
Encryption::get_mount_by() const
{
return get_impl().get_mount_by();
}
void
Encryption::set_mount_by(MountByType mount_by)
{
get_impl().set_mount_by(mount_by);
}
void
Encryption::set_default_mount_by()
{
get_impl().set_default_mount_by();
}
const std::vector<string>&
Encryption::get_crypt_options() const
{
return get_impl().get_crypt_options().get_opts();;
}
void
Encryption::set_crypt_options(const vector<string>& crypt_options)
{
get_impl().set_crypt_options(crypt_options);
}
bool
Encryption::is_in_etc_crypttab() const
{
return get_impl().is_in_etc_crypttab();
}
void
Encryption::set_in_etc_crypttab(bool in_etc_crypttab)
{
get_impl().set_in_etc_crypttab(in_etc_crypttab);
}
Encryption*
Encryption::clone() const
{
return new Encryption(get_impl().clone());
}
Encryption::Impl&
Encryption::get_impl()
{
return dynamic_cast<Impl&>(Device::get_impl());
}
const Encryption::Impl&
Encryption::get_impl() const
{
return dynamic_cast<const Impl&>(Device::get_impl());
}
EncryptionType
Encryption::get_type() const
{
return get_impl().get_type();
}
void
Encryption::set_type(EncryptionType type)
{
get_impl().set_type(type);
}
const std::string&
Encryption::get_password() const
{
return get_impl().get_password();
}
void
Encryption::set_password(const std::string& password)
{
get_impl().set_password(password);
}
const std::string&
Encryption::get_key_file() const
{
return get_impl().get_key_file();
}
void
Encryption::set_key_file(const std::string& key_file)
{
get_impl().set_key_file(key_file);
}
const string&
Encryption::get_cipher() const
{
return get_impl().get_cipher();
}
void
Encryption::set_cipher(const string& cipher)
{
get_impl().set_cipher(cipher);
}
unsigned int
Encryption::get_key_size() const
{
return get_impl().get_key_size();
}
void
Encryption::set_key_size(unsigned int key_size)
{
get_impl().set_key_size(key_size);
}
const BlkDevice*
Encryption::get_blk_device() const
{
return get_impl().get_blk_device();
}
const string&
Encryption::get_open_options() const
{
return get_impl().get_open_options();
}
void
Encryption::set_open_options(const std::string& open_options)
{
get_impl().set_open_options(open_options);
}
vector<Encryption*>
Encryption::get_all(Devicegraph* devicegraph)
{
return devicegraph->get_impl().get_devices_of_type<Encryption>();
}
vector<const Encryption*>
Encryption::get_all(const Devicegraph* devicegraph)
{
return devicegraph->get_impl().get_devices_of_type<const Encryption>();
}
bool
is_encryption(const Device* device)
{
return is_device_of_type<const Encryption>(device);
}
Encryption*
to_encryption(Device* device)
{
return to_device_of_type<Encryption>(device);
}
const Encryption*
to_encryption(const Device* device)
{
return to_device_of_type<const Encryption>(device);
}
}
<commit_msg>- coding style<commit_after>/*
* Copyright (c) [2016-2019] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include "storage/Devices/EncryptionImpl.h"
#include "storage/Devicegraph.h"
namespace storage
{
using namespace std;
Encryption*
Encryption::create(Devicegraph* devicegraph, const string& name)
{
Encryption* ret = new Encryption(new Encryption::Impl(name));
ret->Device::create(devicegraph);
return ret;
}
Encryption*
Encryption::load(Devicegraph* devicegraph, const xmlNode* node)
{
Encryption* ret = new Encryption(new Encryption::Impl(node));
ret->Device::load(devicegraph);
return ret;
}
Encryption::Encryption(Impl* impl)
: BlkDevice(impl)
{
}
MountByType
Encryption::get_mount_by() const
{
return get_impl().get_mount_by();
}
void
Encryption::set_mount_by(MountByType mount_by)
{
get_impl().set_mount_by(mount_by);
}
void
Encryption::set_default_mount_by()
{
get_impl().set_default_mount_by();
}
const vector<string>&
Encryption::get_crypt_options() const
{
return get_impl().get_crypt_options().get_opts();;
}
void
Encryption::set_crypt_options(const vector<string>& crypt_options)
{
get_impl().set_crypt_options(crypt_options);
}
bool
Encryption::is_in_etc_crypttab() const
{
return get_impl().is_in_etc_crypttab();
}
void
Encryption::set_in_etc_crypttab(bool in_etc_crypttab)
{
get_impl().set_in_etc_crypttab(in_etc_crypttab);
}
Encryption*
Encryption::clone() const
{
return new Encryption(get_impl().clone());
}
Encryption::Impl&
Encryption::get_impl()
{
return dynamic_cast<Impl&>(Device::get_impl());
}
const Encryption::Impl&
Encryption::get_impl() const
{
return dynamic_cast<const Impl&>(Device::get_impl());
}
EncryptionType
Encryption::get_type() const
{
return get_impl().get_type();
}
void
Encryption::set_type(EncryptionType type)
{
get_impl().set_type(type);
}
const string&
Encryption::get_password() const
{
return get_impl().get_password();
}
void
Encryption::set_password(const string& password)
{
get_impl().set_password(password);
}
const string&
Encryption::get_key_file() const
{
return get_impl().get_key_file();
}
void
Encryption::set_key_file(const string& key_file)
{
get_impl().set_key_file(key_file);
}
const string&
Encryption::get_cipher() const
{
return get_impl().get_cipher();
}
void
Encryption::set_cipher(const string& cipher)
{
get_impl().set_cipher(cipher);
}
unsigned int
Encryption::get_key_size() const
{
return get_impl().get_key_size();
}
void
Encryption::set_key_size(unsigned int key_size)
{
get_impl().set_key_size(key_size);
}
const BlkDevice*
Encryption::get_blk_device() const
{
return get_impl().get_blk_device();
}
const string&
Encryption::get_open_options() const
{
return get_impl().get_open_options();
}
void
Encryption::set_open_options(const string& open_options)
{
get_impl().set_open_options(open_options);
}
vector<Encryption*>
Encryption::get_all(Devicegraph* devicegraph)
{
return devicegraph->get_impl().get_devices_of_type<Encryption>();
}
vector<const Encryption*>
Encryption::get_all(const Devicegraph* devicegraph)
{
return devicegraph->get_impl().get_devices_of_type<const Encryption>();
}
bool
is_encryption(const Device* device)
{
return is_device_of_type<const Encryption>(device);
}
Encryption*
to_encryption(Device* device)
{
return to_device_of_type<Encryption>(device);
}
const Encryption*
to_encryption(const Device* device)
{
return to_device_of_type<const Encryption>(device);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_AtomicOperations_inl_
#define _Stroika_Foundation_Execution_AtomicOperations_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#if qCompilerAndStdLib_Supports_stdatomic
#include <atomic>
#elif qPlatform_Windows
#include <windows.h>
#endif
#include "../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Execution {
//tmphack - this API I think I understand, but not the stdc++ one
#if defined(__GCC__)
#define qDoGCCHackAroundMyBuggyStdcIml 1
#else
#define qDoGCCHackAroundMyBuggyStdcIml 0
#endif
inline int32_t AtomicIncrement (volatile int32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p));
#else
AssertNotImplemented ();
#endif
}
inline uint32_t AtomicIncrement (volatile uint32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p)++;
#elif qPlatform_Windows
return static_cast<uint32_t> (::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p)));
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicIncrement (volatile int64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p)++;
#elif qPlatform_Win64
return ::InterlockedIncrement64 (p);
#endif
}
inline uint64_t AtomicIncrement (volatile uint64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p)++;
#elif qPlatform_Win64
return ::InterlockedIncrement64 (reinterpret_cast<volatile int64_t*> (p));
#endif
}
#endif
inline int32_t AtomicDecrement (volatile int32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicDecrement (volatile int64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement64 (p);
#endif
}
inline uint64_t AtomicDecrement (volatile uint64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement64 (reinterpret_cast<volatile int64_t*> (p));
#endif
}
#endif
inline uint32_t AtomicDecrement (volatile uint32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
#else
AssertNotImplemented ();
#endif
}
inline int32_t AtomicAdd (volatile int32_t* p, int32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicAdd (volatile int64_t* p, int64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, arg) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (p, arg);
#endif
}
#endif
inline uint32_t AtomicAdd (volatile uint32_t* p, uint32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, arg) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline uint64_t AtomicAdd (volatile uint64_t* p, uint64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, arg) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), arg);
#endif
}
#endif
inline int32_t AtomicSubtract (volatile int32_t* p, int32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -arg);
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicSubtract (volatile int64_t* p, int64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (p, -arg);
#endif
}
#endif
inline uint32_t AtomicSubtract (volatile uint32_t* p, uint32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -static_cast<int32_t> (arg));
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline uint64_t AtomicSubtract (volatile uint64_t* p, uint64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), -static_cast<int64_t> (arg));
#endif
}
#endif
}
}
}
#endif /*_Stroika_Foundation_Execution_AtomicOperations_inl_*/
<commit_msg>hopefully fixed gcc BWA for AtomicOperations.inl<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_AtomicOperations_inl_
#define _Stroika_Foundation_Execution_AtomicOperations_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#if qCompilerAndStdLib_Supports_stdatomic
#include <atomic>
#elif qPlatform_Windows
#include <windows.h>
#endif
#include "../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Execution {
//tmphack - this API I think I understand, but not the stdc++ one
#if defined(__GNUC__)
#define qDoGCCHackAroundMyBuggyStdcIml 1
#else
#define qDoGCCHackAroundMyBuggyStdcIml 0
#endif
inline int32_t AtomicIncrement (volatile int32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p));
#else
AssertNotImplemented ();
#endif
}
inline uint32_t AtomicIncrement (volatile uint32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p)++;
#elif qPlatform_Windows
return static_cast<uint32_t> (::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p)));
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicIncrement (volatile int64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p)++;
#elif qPlatform_Win64
return ::InterlockedIncrement64 (p);
#endif
}
inline uint64_t AtomicIncrement (volatile uint64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p)++;
#elif qPlatform_Win64
return ::InterlockedIncrement64 (reinterpret_cast<volatile int64_t*> (p));
#endif
}
#endif
inline int32_t AtomicDecrement (volatile int32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicDecrement (volatile int64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement64 (p);
#endif
}
inline uint64_t AtomicDecrement (volatile uint64_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement64 (reinterpret_cast<volatile int64_t*> (p));
#endif
}
#endif
inline uint32_t AtomicDecrement (volatile uint32_t* p)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, 1) - 1;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p)++;
#elif qPlatform_Windows
return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
#else
AssertNotImplemented ();
#endif
}
inline int32_t AtomicAdd (volatile int32_t* p, int32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, 1) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicAdd (volatile int64_t* p, int64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, arg) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (p, arg);
#endif
}
#endif
inline uint32_t AtomicAdd (volatile uint32_t* p, uint32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, arg) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline uint64_t AtomicAdd (volatile uint64_t* p, uint64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_add (p, arg) + arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), arg);
#endif
}
#endif
inline int32_t AtomicSubtract (volatile int32_t* p, int32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int32_t*> ((int32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -arg);
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline int64_t AtomicSubtract (volatile int64_t* p, int64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<int64_t*> ((int64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (p, -arg);
#endif
}
#endif
inline uint32_t AtomicSubtract (volatile uint32_t* p, uint32_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint32_t*> ((uint32_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -static_cast<int32_t> (arg));
#else
AssertNotImplemented ();
#endif
}
#if qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
inline uint64_t AtomicSubtract (volatile uint64_t* p, uint64_t arg)
{
RequireNotNull (p);
#if qDoGCCHackAroundMyBuggyStdcIml
return __sync_fetch_and_sub (p, arg) - arg;
#endif
#if qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
atomic<uint64_t*> ((uint64_t*)p) += arg;
#elif qPlatform_Windows
return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), -static_cast<int64_t> (arg));
#endif
}
#endif
}
}
}
#endif /*_Stroika_Foundation_Execution_AtomicOperations_inl_*/
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#include <memory>
#include <media/MediaPlayer.h>
#include <media/FileInputDataSource.h>
#include "tc_common.h"
static const char *dummyfilepath = "/mnt/fileinputdatasource.raw";
static void SetUp(void)
{
FILE *fp = fopen(dummyfilepath, "w");
fputs("dummydata", fp);
fclose(fp);
}
static void TearDown()
{
remove(dummyfilepath);
}
static void utc_media_MediaPlayer_create_p(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_create_n(void)
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_ERROR);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_destroy_p(void)
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_OK);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_destroy_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setDataSource_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
source->setSampleRate(20000);
source->setChannels(2);
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(std::move(source)), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setDataSource_n(void)
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(nullptr), media::PLAYER_ERROR);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setObserver_p(void)
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(nullptr), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setObserver_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(nullptr), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_prepare_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_prepare_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_unprepare_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_unprepare_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_start_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_start_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_pause_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
mp.start();
TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_pause_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_stop_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
mp.start();
TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_stop_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_getVolume_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_GEQ("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_getVolume_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_LT("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setVolume_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
auto ret = mp.setVolume(0);
TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", ret, media::PLAYER_OK);
TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.getVolume(), 0);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setVolume_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.setVolume(0), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
int utc_media_MediaPlayer_main(void)
{
SetUp();
utc_media_MediaPlayer_create_p();
utc_media_MediaPlayer_create_n();
utc_media_MediaPlayer_destroy_p();
utc_media_MediaPlayer_destroy_n();
utc_media_MediaPlayer_setDataSource_p();
utc_media_MediaPlayer_setDataSource_n();
utc_media_MediaPlayer_setObserver_p();
utc_media_MediaPlayer_setObserver_n();
utc_media_MediaPlayer_prepare_p();
utc_media_MediaPlayer_prepare_n();
utc_media_MediaPlayer_unprepare_p();
utc_media_MediaPlayer_unprepare_n();
utc_media_MediaPlayer_start_p();
utc_media_MediaPlayer_start_n();
utc_media_MediaPlayer_pause_p();
utc_media_MediaPlayer_pause_n();
utc_media_MediaPlayer_stop_p();
utc_media_MediaPlayer_stop_n();
utc_media_MediaPlayer_getVolume_p();
utc_media_MediaPlayer_getVolume_n();
utc_media_MediaPlayer_setVolume_p();
utc_media_MediaPlayer_setVolume_n();
TearDown();
return 0;
}
<commit_msg>ta_tc/media: Implement MediaPlayer utc<commit_after>/****************************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#include <memory>
#include <media/MediaPlayer.h>
#include <media/FileInputDataSource.h>
#include "tc_common.h"
static const char *dummyfilepath = "/mnt/fileinputdatasource.raw";
class EmptyObserver : public media::MediaPlayerObserverInterface
{
public:
void onPlaybackStarted(Id id) override;
void onPlaybackFinished(Id id) override;
void onPlaybackError(Id id) override;
};
void EmptyObserver::onPlaybackStarted(Id id)
{
}
void EmptyObserver::onPlaybackFinished(Id id)
{
}
void EmptyObserver::onPlaybackError(Id id)
{
}
static void SetUp(void)
{
FILE *fp = fopen(dummyfilepath, "w");
fputs("dummydata", fp);
fclose(fp);
}
static void TearDown()
{
remove(dummyfilepath);
}
static void utc_media_MediaPlayer_create_p(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_create_n(void)
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_ERROR);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_destroy_p(void)
{
media::MediaPlayer mp;
auto observer = std::make_shared<EmptyObserver>();
mp.create();
mp.setObserver(observer);
TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_OK);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_destroy_n(void)
{
/* destroy without create */
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_ERROR);
}
/* destroy At invalid time */
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_ERROR);
mp.unprepare();
mp.destroy();
}
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setDataSource_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
source->setSampleRate(20000);
source->setChannels(2);
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(std::move(source)), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setDataSource_n(void)
{
/* setDataSource without create */
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
source->setSampleRate(20000);
source->setChannels(2);
TC_ASSERT_EQ("setDataSource", mp.setDataSource(std::move(source)), media::PLAYER_ERROR);
}
/* setDataSource with nullptr */
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(nullptr), media::PLAYER_ERROR);
mp.destroy();
}
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setObserver_p(void)
{
media::MediaPlayer mp;
auto observer = std::make_shared<EmptyObserver>();
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(observer), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setObserver_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(nullptr), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_prepare_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_prepare_n(void)
{
/* prepare without create */
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);
}
/* prepare twice */
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);
mp.unprepare();
mp.destroy();
}
/* prepare without setting datasource */
{
media::MediaPlayer mp;
mp.create();
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);
mp.destroy();
}
/* prepare with invalid datasource */
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource("non-exist-file")));
mp.create();
mp.setDataSource(std::move(source));
TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);
mp.destroy();
}
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_unprepare_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_OK);
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_unprepare_n(void)
{
/* unprepare without create */
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_ERROR);
}
/* unprepare twice */
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.unprepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_ERROR);
mp.unprepare();
mp.destroy();
}
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_start_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_start_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_pause_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
mp.start();
TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_pause_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_stop_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
mp.start();
TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_OK);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_stop_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_getVolume_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
TC_ASSERT_GEQ("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_getVolume_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_LT("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setVolume_p(void)
{
media::MediaPlayer mp;
std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
mp.create();
mp.setDataSource(std::move(source));
mp.prepare();
auto ret = mp.setVolume(0);
TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", ret, media::PLAYER_OK);
TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.getVolume(), 0);
mp.unprepare();
mp.destroy();
TC_SUCCESS_RESULT();
}
static void utc_media_MediaPlayer_setVolume_n(void)
{
media::MediaPlayer mp;
TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.setVolume(0), media::PLAYER_ERROR);
TC_SUCCESS_RESULT();
}
int utc_media_MediaPlayer_main(void)
{
SetUp();
utc_media_MediaPlayer_create_p();
utc_media_MediaPlayer_create_n();
utc_media_MediaPlayer_destroy_p();
utc_media_MediaPlayer_destroy_n();
utc_media_MediaPlayer_setDataSource_p();
utc_media_MediaPlayer_setDataSource_n();
utc_media_MediaPlayer_setObserver_p();
utc_media_MediaPlayer_setObserver_n();
utc_media_MediaPlayer_prepare_p();
utc_media_MediaPlayer_prepare_n();
utc_media_MediaPlayer_unprepare_p();
utc_media_MediaPlayer_unprepare_n();
utc_media_MediaPlayer_start_p();
utc_media_MediaPlayer_start_n();
utc_media_MediaPlayer_pause_p();
utc_media_MediaPlayer_pause_n();
utc_media_MediaPlayer_stop_p();
utc_media_MediaPlayer_stop_n();
utc_media_MediaPlayer_getVolume_p();
utc_media_MediaPlayer_getVolume_n();
utc_media_MediaPlayer_setVolume_p();
utc_media_MediaPlayer_setVolume_n();
TearDown();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "ml_metadata/metadata_store/metadata_access_object_factory.h"
#include <memory>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "ml_metadata/metadata_store/query_config_executor.h"
#include "ml_metadata/metadata_store/rdbms_metadata_access_object.h"
#include "ml_metadata/util/return_utils.h"
namespace ml_metadata {
namespace {
// Creates MetadataAccessObject (MAO) with the input query config and the
// MetadataSource and returns the created MAO pointer.
// The query config has template queries and other config information.
// The MetadataSource is used to execute specific queries.
absl::Status CreateRDBMSMetadataAccessObject(
const MetadataSourceQueryConfig& query_config,
MetadataSource* const metadata_source, absl::optional<int64> schema_version,
std::unique_ptr<MetadataAccessObject>* result) {
if (!metadata_source->is_connected())
MLMD_RETURN_IF_ERROR(metadata_source->Connect());
std::unique_ptr<QueryExecutor> executor =
schema_version && *schema_version != query_config.schema_version()
? absl::WrapUnique(new QueryConfigExecutor(
query_config, metadata_source, *schema_version))
: absl::WrapUnique(
new QueryConfigExecutor(query_config, metadata_source));
*result =
absl::WrapUnique(new RDBMSMetadataAccessObject(std::move(executor)));
return absl::OkStatus();
}
} // namespace
absl::Status CreateMetadataAccessObject(
const MetadataSourceQueryConfig& query_config,
MetadataSource* const metadata_source,
std::unique_ptr<MetadataAccessObject>* result) {
return CreateMetadataAccessObject(query_config, metadata_source,
/*schema_version=*/absl::nullopt,
result);
}
absl::Status CreateMetadataAccessObject(
const MetadataSourceQueryConfig& query_config,
MetadataSource* const metadata_source, absl::optional<int64> schema_version,
std::unique_ptr<MetadataAccessObject>* result) {
switch (query_config.metadata_source_type()) {
case UNKNOWN_METADATA_SOURCE:
return absl::InvalidArgumentError(
"Metadata source type is not specified.");
case MYSQL_METADATA_SOURCE:
return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
schema_version, result);
case SQLITE_METADATA_SOURCE:
return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
schema_version, result);
default:
return absl::UnimplementedError("Unknown Metadata source type.");
}
}
} // namespace ml_metadata
<commit_msg>Makes `enable_bufferwrite` available for MLMD Service through CDPush.<commit_after>/* Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "ml_metadata/metadata_store/metadata_access_object_factory.h"
#include <memory>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "ml_metadata/metadata_store/query_config_executor.h"
#include "ml_metadata/metadata_store/rdbms_metadata_access_object.h"
#include "ml_metadata/proto/metadata_source.pb.h"
#include "ml_metadata/util/return_utils.h"
namespace ml_metadata {
namespace {
// Creates MetadataAccessObject (MAO) with the input query config and the
// MetadataSource and returns the created MAO pointer.
// The query config has template queries and other config information.
// The MetadataSource is used to execute specific queries.
absl::Status CreateRDBMSMetadataAccessObject(
const MetadataSourceQueryConfig& query_config,
MetadataSource* const metadata_source, absl::optional<int64> schema_version,
std::unique_ptr<MetadataAccessObject>* result) {
if (!metadata_source->is_connected())
MLMD_RETURN_IF_ERROR(metadata_source->Connect());
std::unique_ptr<QueryExecutor> executor =
schema_version && *schema_version != query_config.schema_version()
? absl::WrapUnique(new QueryConfigExecutor(
query_config, metadata_source, *schema_version))
: absl::WrapUnique(
new QueryConfigExecutor(query_config, metadata_source));
*result =
absl::WrapUnique(new RDBMSMetadataAccessObject(std::move(executor)));
return absl::OkStatus();
}
} // namespace
absl::Status CreateMetadataAccessObject(
const MetadataSourceQueryConfig& query_config,
MetadataSource* const metadata_source,
std::unique_ptr<MetadataAccessObject>* result) {
return CreateMetadataAccessObject(query_config, metadata_source,
/*schema_version=*/absl::nullopt,
result);
}
absl::Status CreateMetadataAccessObject(
const MetadataSourceQueryConfig& query_config,
MetadataSource* const metadata_source, absl::optional<int64> schema_version,
std::unique_ptr<MetadataAccessObject>* result) {
switch (query_config.metadata_source_type()) {
case UNKNOWN_METADATA_SOURCE:
return absl::InvalidArgumentError(
"Metadata source type is not specified.");
case MYSQL_METADATA_SOURCE:
return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
schema_version, result);
case SQLITE_METADATA_SOURCE:
return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
schema_version, result);
default:
return absl::UnimplementedError("Unknown Metadata source type.");
}
}
} // namespace ml_metadata
<|endoftext|> |
<commit_before>#ifndef LOG_HPP
#define LOG_HPP
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include "time.hpp"
#include "scoped_connection_pool.hpp"
#include "config.hpp"
namespace color {
enum color_value : char {
black = 0, red, green, yellow, blue, magenta, cyan, white, normal = -1
};
extern struct reset_t {} reset;
extern struct bold_t {} bold;
struct set {
color_value col_;
bool bold_;
explicit set(color_value col, bool bold = false) : col_(col), bold_(bold) {}
};
std::ostream& operator << (std::ostream& o, set s);
std::ostream& operator << (std::ostream& o, reset_t s);
std::ostream& operator << (std::ostream& o, bold_t s);
}
class logger_base {
protected :
bool color_ = false;
bool stamp_ = false;
virtual void print_(color::set s) {}
virtual void print_(color::reset_t s) {}
virtual void print_(color::bold_t s) {}
public :
virtual ~logger_base() = 0;
virtual bool is_open() const = 0;
void print_stamp() {
if (stamp_) {
print(color::set(color::normal,true)); print("[");
print(color::set(color::cyan, true)); print(today_str("/"));
print(color::set(color::normal,true)); print("|");
print(color::set(color::green, true)); print(time_of_day_str(":"));
print(color::set(color::normal,true)); print("] ");
print(color::set(color::normal,false));
}
}
virtual void print(const std::string& s) = 0;
void print(color::set s) {
if (color_) {
print_(s);
}
}
void print(color::reset_t s) {
if (color_) {
print_(s);
}
}
void print(color::bold_t s) {
if (color_) {
print_(s);
}
}
virtual void endl() = 0;
};
template<typename O>
class ostream_logger_base : public logger_base {
O& out_;
protected :
scoped_connection_pool pool_;
public :
~ostream_logger_base() override {}
ostream_logger_base(O& o) : out_(o) {}
void print(const std::string& t) override {
out_ << t;
}
void print_(color::set s) override {
out_ << s;
}
void print_(color::reset_t s) override {
out_ << s;
}
void print_(color::bold_t s) override {
out_ << s;
}
void endl() override {
out_ << std::endl;
}
};
template<typename O>
class ostream_logger : public ostream_logger_base<O> {
O out_;
public :
~ostream_logger() override {}
ostream_logger(config::state& conf, const std::string& name) :
ostream_logger_base<O>(out_) {
std::string file;
if (conf.get_value("log."+name+".file", file, "") && !file.empty()) {
bool append = true;
conf.get_value("log."+name+".append", append, append);
if (append) {
out_.open(file, std::ios::app);
} else {
out_.open(file);
}
this->pool_ << conf.bind("log."+name+".color", this->color_);
this->pool_ << conf.bind("log."+name+".stamp", this->stamp_);
}
}
bool is_open() const override {
return out_.is_open();
}
};
class cout_logger : public ostream_logger_base<std::ostream> {
public :
~cout_logger() override {}
cout_logger(config::state& conf) : ostream_logger_base<std::ostream>(std::cout) {
pool_ << conf.bind("log.cout.color", color_);
pool_ << conf.bind("log.cout.stamp", stamp_);
}
bool is_open() const override {
return true;
}
};
namespace logger_impl {
template<typename T>
struct has_std_to_string_t {
template <typename U> static std::true_type dummy(typename std::decay<
decltype(std::to_string(std::declval<U>()))>::type*);
template <typename U> static std::false_type dummy(...);
using type = decltype(dummy<T>(0));
};
template<typename T>
struct has_adl_to_string_t {
template <typename U> static std::true_type dummy(typename std::decay<
decltype(to_string(std::declval<U>()))>::type*);
template <typename U> static std::false_type dummy(...);
using type = decltype(dummy<T>(0));
};
template<typename T>
using has_to_string = std::integral_constant<bool, has_std_to_string_t<T>::type::value ||
has_adl_to_string_t<T>::type::value>;
}
class logger {
std::vector<std::unique_ptr<logger_base>> out_;
public :
logger() = default;
private :
template<typename T>
void forward_print_(const T& t) {
for (auto& o : out_) {
if (o->is_open()) {
o->print(t);
}
}
}
template<typename T>
void do_print__(const T& t, std::true_type) {
using std::to_string;
forward_print_(to_string(t));
}
template<typename T>
void do_print__(const T& t, std::false_type) {
std::ostringstream ss;
ss << t;
forward_print_(ss.str());
}
template<typename T>
void print__(const T& t) {
do_print__(t, logger_impl::has_to_string<T>{});
}
void print__(const std::string& str) {
forward_print_(str);
}
void print__(const char* str) {
forward_print_(std::string(str));
}
void print__(color::set s) {
forward_print_(s);
}
void print__(color::reset_t s) {
forward_print_(s);
}
void print__(color::bold_t s) {
forward_print_(s);
}
private :
template<typename ... Args>
void print_(Args&& ... args) {
int v[] = {(print__(std::forward<Args>(args)), 0)...};
}
void print_stamp_() {
for (auto& o : out_) {
if (o->is_open()) {
o->print_stamp();
}
}
}
void endl_() {
for (auto& o : out_) {
if (o->is_open()) {
o->endl();
}
}
}
public :
template<typename T, typename ... Args>
void add_output(Args&&... args) {
out_.emplace_back(new T(std::forward<Args>(args)...));
}
template<typename ... Args>
void print(Args&&... args) {
print_stamp_();
print_(std::forward<Args>(args)...);
endl_();
}
template<typename ... Args>
void print_header(color::color_value v, const std::string hdr, Args&&... args) {
print_stamp_();
print_(color::set(v, true));
print_(hdr+": ");
print_(color::reset);
print_(std::forward<Args>(args)...);
endl_();
}
template<typename ... Args>
void error(Args&& ... args) {
print_header(color::red, "error", std::forward<Args>(args)...);
}
template<typename ... Args>
void warning(Args&& ... args) {
print_header(color::yellow, "warning", std::forward<Args>(args)...);
}
template<typename ... Args>
void note(Args&& ... args) {
print_header(color::blue, "note", std::forward<Args>(args)...);
}
template<typename ... Args>
void reason(Args&& ... args) {
print_header(color::blue, "reason", std::forward<Args>(args)...);
}
};
using file_logger = ostream_logger<std::ofstream>;
extern logger cout;
#endif
<commit_msg>Extended logger to support enumerations.<commit_after>#ifndef LOG_HPP
#define LOG_HPP
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include "time.hpp"
#include "scoped_connection_pool.hpp"
#include "config.hpp"
namespace color {
enum color_value : char {
black = 0, red, green, yellow, blue, magenta, cyan, white, normal = -1
};
extern struct reset_t {} reset;
extern struct bold_t {} bold;
struct set {
color_value col_;
bool bold_;
explicit set(color_value col, bool bold = false) : col_(col), bold_(bold) {}
};
std::ostream& operator << (std::ostream& o, set s);
std::ostream& operator << (std::ostream& o, reset_t s);
std::ostream& operator << (std::ostream& o, bold_t s);
}
class logger_base {
protected :
bool color_ = false;
bool stamp_ = false;
virtual void print_(color::set s) {}
virtual void print_(color::reset_t s) {}
virtual void print_(color::bold_t s) {}
public :
virtual ~logger_base() = 0;
virtual bool is_open() const = 0;
void print_stamp() {
if (stamp_) {
print(color::set(color::normal,true)); print("[");
print(color::set(color::cyan, true)); print(today_str("/"));
print(color::set(color::normal,true)); print("|");
print(color::set(color::green, true)); print(time_of_day_str(":"));
print(color::set(color::normal,true)); print("] ");
print(color::set(color::normal,false));
}
}
virtual void print(const std::string& s) = 0;
void print(color::set s) {
if (color_) {
print_(s);
}
}
void print(color::reset_t s) {
if (color_) {
print_(s);
}
}
void print(color::bold_t s) {
if (color_) {
print_(s);
}
}
virtual void endl() = 0;
};
template<typename O>
class ostream_logger_base : public logger_base {
O& out_;
protected :
scoped_connection_pool pool_;
public :
~ostream_logger_base() override {}
ostream_logger_base(O& o) : out_(o) {}
void print(const std::string& t) override {
out_ << t;
}
void print_(color::set s) override {
out_ << s;
}
void print_(color::reset_t s) override {
out_ << s;
}
void print_(color::bold_t s) override {
out_ << s;
}
void endl() override {
out_ << std::endl;
}
};
template<typename O>
class ostream_logger : public ostream_logger_base<O> {
O out_;
public :
~ostream_logger() override {}
ostream_logger(config::state& conf, const std::string& name) :
ostream_logger_base<O>(out_) {
std::string file;
if (conf.get_value("log."+name+".file", file, "") && !file.empty()) {
bool append = true;
conf.get_value("log."+name+".append", append, append);
if (append) {
out_.open(file, std::ios::app);
} else {
out_.open(file);
}
this->pool_ << conf.bind("log."+name+".color", this->color_);
this->pool_ << conf.bind("log."+name+".stamp", this->stamp_);
}
}
bool is_open() const override {
return out_.is_open();
}
};
class cout_logger : public ostream_logger_base<std::ostream> {
public :
~cout_logger() override {}
cout_logger(config::state& conf) : ostream_logger_base<std::ostream>(std::cout) {
pool_ << conf.bind("log.cout.color", color_);
pool_ << conf.bind("log.cout.stamp", stamp_);
}
bool is_open() const override {
return true;
}
};
namespace logger_impl {
template<typename T>
struct has_std_to_string_t {
template <typename U> static std::true_type dummy(typename std::decay<
decltype(std::to_string(std::declval<U>()))>::type*);
template <typename U> static std::false_type dummy(...);
using type = decltype(dummy<T>(0));
};
template<typename T>
struct has_adl_to_string_t {
template <typename U> static std::true_type dummy(typename std::decay<
decltype(to_string(std::declval<U>()))>::type*);
template <typename U> static std::false_type dummy(...);
using type = decltype(dummy<T>(0));
};
template<typename T>
using has_to_string = std::integral_constant<bool, has_std_to_string_t<T>::type::value ||
has_adl_to_string_t<T>::type::value>;
}
class logger {
std::vector<std::unique_ptr<logger_base>> out_;
public :
logger() = default;
private :
template<typename T>
void forward_print_(const T& t) {
for (auto& o : out_) {
if (o->is_open()) {
o->print(t);
}
}
}
template<typename T>
void do_print__(const T& t, std::true_type, std::false_type) {
using std::to_string;
forward_print_(to_string(t));
}
template<typename T>
void do_print__(const T& t, std::false_type, std::false_type) {
std::ostringstream ss;
ss << t;
forward_print_(ss.str());
}
template<typename T, typename TS>
void do_print__(const T& t, TS, std::true_type) {
using std::to_string;
forward_print_(to_string(static_cast<typename std::underlying_type<T>::type>(t)));
}
template<typename T>
void print__(const T& t) {
do_print__(t, logger_impl::has_to_string<T>{}, std::is_enum<T>{});
}
void print__(const std::string& str) {
forward_print_(str);
}
void print__(const char* str) {
forward_print_(std::string(str));
}
void print__(color::set s) {
forward_print_(s);
}
void print__(color::reset_t s) {
forward_print_(s);
}
void print__(color::bold_t s) {
forward_print_(s);
}
private :
template<typename ... Args>
void print_(Args&& ... args) {
int v[] = {(print__(std::forward<Args>(args)), 0)...};
}
void print_stamp_() {
for (auto& o : out_) {
if (o->is_open()) {
o->print_stamp();
}
}
}
void endl_() {
for (auto& o : out_) {
if (o->is_open()) {
o->endl();
}
}
}
public :
template<typename T, typename ... Args>
void add_output(Args&&... args) {
out_.emplace_back(new T(std::forward<Args>(args)...));
}
template<typename ... Args>
void print(Args&&... args) {
print_stamp_();
print_(std::forward<Args>(args)...);
endl_();
}
template<typename ... Args>
void print_header(color::color_value v, const std::string hdr, Args&&... args) {
print_stamp_();
print_(color::set(v, true));
print_(hdr+": ");
print_(color::reset);
print_(std::forward<Args>(args)...);
endl_();
}
template<typename ... Args>
void error(Args&& ... args) {
print_header(color::red, "error", std::forward<Args>(args)...);
}
template<typename ... Args>
void warning(Args&& ... args) {
print_header(color::yellow, "warning", std::forward<Args>(args)...);
}
template<typename ... Args>
void note(Args&& ... args) {
print_header(color::blue, "note", std::forward<Args>(args)...);
}
template<typename ... Args>
void reason(Args&& ... args) {
print_header(color::blue, "reason", std::forward<Args>(args)...);
}
};
using file_logger = ostream_logger<std::ofstream>;
extern logger cout;
#endif
<|endoftext|> |
<commit_before><commit_msg>Fix android compilation: missing cast when formatting value in string (#22382)<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 National Research Institute of Science and
* Technology for Environment and Agriculture (IRSTEA)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "itkFixedArray.h"
#include "itkObjectFactory.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"
// Application engine
#include "otbStandardFilterWatcher.h"
// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"
namespace otb
{
namespace Wrapper
{
class ZonalStatistics : public Application
{
public:
/** Standard class typedefs. */
typedef ZonalStatistics Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/* Typedefs */
typedef Int32ImageType LabelImageType;
typedef LabelImageType::ValueType LabelValueType;
typedef otb::VectorData<double, 2> VectorDataType;
typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
FloatVectorImageType> VectorDataReprojFilterType;
typedef otb::VectorDataToLabelImageFilter<VectorDataType,
LabelImageType> RasterizeFilterType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef itk::PreOrderTreeIterator<DataTreeType>
TreeIteratorType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef DataNodeType::PolygonListPointerType
PolygonListPointerType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
LabelImageType> StatsFilterType;
typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
StatsWriterType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ZonalStatistics, Application);
void DoInit()
{
SetName("ZonalStatistics");
SetDescription("This application computes zonal statistics");
// Documentation
SetDocName("ZonalStatistics");
SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
"The application inputs one input multiband image, and a label input. "
"If the label input is a raster, the output statistics are exported in a XML file. If the label "
"input is a vector data, the output statistics are exported in a new vector data with statistics "
"in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
SetDocLimitations("The shapefile must fit in memory");
SetDocAuthors("Remi Cresson");
AddDocTag(Tags::Manip);
AddDocTag(Tags::Analysis);
// Input image
AddParameter(ParameterType_InputImage, "in", "Input Image");
AddParameter(ParameterType_Float, "inbv", "Background value to ignore in statistics computation");
// Input zone mode
AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
AddChoice("inzone.vector", "Input objects from vector data");
AddChoice("inzone.labelimage", "Input objects from label image");
// Input for vector mode
AddParameter(ParameterType_InputVectorData, "inzone.vector.in", "Input vector data");
AddParameter(ParameterType_Bool, "inzone.vector.reproject", "Reproject the input vector");
// Input for label image mode
AddParameter(ParameterType_InputImage, "inzone.labelimage.in", "Input label image");
AddParameter(ParameterType_Int, "inzone.labelimage.nodata", "No-data value for the input label image");
MandatoryOff ("inzone.labelimage.nodata");
// Output stats mode
AddParameter(ParameterType_Choice, "out", "Format of the output stats");
AddChoice("out.vector", "Output vector data");
AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
AddChoice("out.xml", "Output XML file");
AddParameter(ParameterType_String, "out.xml.filename", "");
AddChoice("out.raster", "Output raster image");
AddParameter(ParameterType_OutputImage, "out.raster.filename", "");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
// Returns a string of the kind "prefix_i"
const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
{
std::stringstream ss;
ss << prefix << "_" << i;
return ss.str();
}
// Returns a null pixel which has the same number of components per pixels as img
FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
{
const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
FloatVectorImageType::PixelType pix;
pix.SetSize(nBands);
pix.Fill(0);
return pix;
}
void DoExecute()
{
// Get input image
FloatVectorImageType::Pointer img = GetParameterImage("in");
// Statistics filter
m_StatsFilter = StatsFilterType::New();
m_StatsFilter->SetInput(img);
m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
// Internal no-data value
LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();
// Select zone definition mode
if (GetParameterAsString("inzone") == "labelimage")
{
otbAppLogINFO("Zone definition: label image");
// Computing stats
m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
m_StatsFilter->SetUseNoDataValue(HasUserValue("inbv"));
m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
m_StatsFilter->Update();
// In this zone definition mode, the user can provide a no-data value for the labels
if (HasUserValue("inzone.labelimage.nodata"))
intNoData = GetParameterInt("inzone.labelimage.nodata");
otbAppLogINFO("Using no-data value for the label image: " << intNoData);
}
else if (GetParameterAsString("inzone") == "vector")
{
otbAppLogINFO("Zone definition: vector");
otbAppLogINFO("Loading vector data...");
VectorDataType* shp = GetParameterVectorData("inzone.vector.in");
// Reproject vector data
if (GetParameterInt("inzone.vector.reproject") != 0)
{
otbAppLogINFO("Vector data reprojection enabled");
m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
m_VectorDataReprojectionFilter->SetInputVectorData(shp);
m_VectorDataReprojectionFilter->SetInputImage(img);
AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
m_VectorDataReprojectionFilter->Update();
m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
}
else
{
m_VectorDataSrc = shp;
}
// Rasterize vector data
m_RasterizeFilter = RasterizeFilterType::New();
m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
m_RasterizeFilter->SetBurnAttribute("________");
m_RasterizeFilter->SetDefaultBurnValue(0);
m_RasterizeFilter->SetGlobalWarningDisplay(false);
m_RasterizeFilter->SetBackgroundValue(intNoData);
// Computing stats
m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
m_StatsFilter->Update();
}
else
{
otbAppLogFATAL("Unknown zone definition mode");
}
// Remove the no-data entry
StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
|| (GetParameterAsString("inzone") == "vector") )
{
countMap.erase(intNoData);
meanMap.erase(intNoData);
stdMap.erase(intNoData);
minMap.erase(intNoData);
maxMap.erase(intNoData);
}
if (GetParameterAsString("out") == "vector")
{
if (GetParameterAsString("inzone") == "vector")
{
// Add a statistics fields
otbAppLogINFO("Writing output vector data");
LabelValueType internalFID = 0;
m_NewVectorData = VectorDataType::New();
DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
DataNodeType::Pointer document = DataNodeType::New();
document->SetNodeType(otb::DOCUMENT);
m_NewVectorData->GetDataTree()->Add(document, root);
DataNodeType::Pointer folder = DataNodeType::New();
folder->SetNodeType(otb::FOLDER);
m_NewVectorData->GetDataTree()->Add(folder, document);
m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
itVector.GoToBegin();
while (!itVector.IsAtEnd())
{
if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVector.Get();
// Add the geometry with the new fields
if (countMap.count(internalFID) > 0)
{
currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
{
currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), meanMap[internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), minMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), maxMap [internalFID][band] );
}
m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
}
internalFID++;
}
++itVector;
} // next feature
SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
}
else if (GetParameterAsString("inzone") == "labelimage")
{
//vectorize the image
otbAppLogFATAL("Vector output from labelimage input not implemented yet");
}
}
else if (GetParameterAsString("out") == "xml")
{
// Write stats
const std::string outXMLFile = this->GetParameterString("out.xml.filename");
otbAppLogINFO("Writing " + outXMLFile)
StatsWriterType::Pointer statWriter = StatsWriterType::New();
statWriter->SetFileName(outXMLFile);
statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
statWriter->Update();
}
else
{
otbAppLogFATAL("Unknown output mode");
}
}
VectorDataType::Pointer m_VectorDataSrc;
VectorDataType::Pointer m_NewVectorData;
VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
RasterizeFilterType::Pointer m_RasterizeFilter;
StatsFilterType::Pointer m_StatsFilter;
};
}
}
OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<commit_msg>FIX: use inbv for background value for all input modes<commit_after>/*
* Copyright (C) 2017 National Research Institute of Science and
* Technology for Environment and Agriculture (IRSTEA)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "itkFixedArray.h"
#include "itkObjectFactory.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"
// Application engine
#include "otbStandardFilterWatcher.h"
// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"
namespace otb
{
namespace Wrapper
{
class ZonalStatistics : public Application
{
public:
/** Standard class typedefs. */
typedef ZonalStatistics Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/* Typedefs */
typedef Int32ImageType LabelImageType;
typedef LabelImageType::ValueType LabelValueType;
typedef otb::VectorData<double, 2> VectorDataType;
typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
FloatVectorImageType> VectorDataReprojFilterType;
typedef otb::VectorDataToLabelImageFilter<VectorDataType,
LabelImageType> RasterizeFilterType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef itk::PreOrderTreeIterator<DataTreeType>
TreeIteratorType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef DataNodeType::PolygonListPointerType
PolygonListPointerType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
LabelImageType> StatsFilterType;
typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
StatsWriterType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ZonalStatistics, Application);
void DoInit()
{
SetName("ZonalStatistics");
SetDescription("This application computes zonal statistics");
// Documentation
SetDocName("ZonalStatistics");
SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
"The application inputs one input multiband image, and a label input. "
"If the label input is a raster, the output statistics are exported in a XML file. If the label "
"input is a vector data, the output statistics are exported in a new vector data with statistics "
"in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
SetDocLimitations("The shapefile must fit in memory");
SetDocAuthors("Remi Cresson");
AddDocTag(Tags::Manip);
AddDocTag(Tags::Analysis);
// Input image
AddParameter(ParameterType_InputImage, "in", "Input Image");
AddParameter(ParameterType_Float, "inbv", "Background value to ignore in statistics computation");
// Input zone mode
AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
AddChoice("inzone.vector", "Input objects from vector data");
AddChoice("inzone.labelimage", "Input objects from label image");
// Input for vector mode
AddParameter(ParameterType_InputVectorData, "inzone.vector.in", "Input vector data");
AddParameter(ParameterType_Bool, "inzone.vector.reproject", "Reproject the input vector");
// Input for label image mode
AddParameter(ParameterType_InputImage, "inzone.labelimage.in", "Input label image");
AddParameter(ParameterType_Int, "inzone.labelimage.nodata", "No-data value for the input label image");
MandatoryOff ("inzone.labelimage.nodata");
// Output stats mode
AddParameter(ParameterType_Choice, "out", "Format of the output stats");
AddChoice("out.vector", "Output vector data");
AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
AddChoice("out.xml", "Output XML file");
AddParameter(ParameterType_String, "out.xml.filename", "");
AddChoice("out.raster", "Output raster image");
AddParameter(ParameterType_OutputImage, "out.raster.filename", "");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
// Returns a string of the kind "prefix_i"
const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
{
std::stringstream ss;
ss << prefix << "_" << i;
return ss.str();
}
// Returns a null pixel which has the same number of components per pixels as img
FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
{
const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
FloatVectorImageType::PixelType pix;
pix.SetSize(nBands);
pix.Fill(0);
return pix;
}
void DoExecute()
{
// Get input image
FloatVectorImageType::Pointer img = GetParameterImage("in");
// Statistics filter
m_StatsFilter = StatsFilterType::New();
m_StatsFilter->SetInput(img);
m_StatsFilter->SetUseNoDataValue(HasUserValue("inbv"));
m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
// Internal no-data value
LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();
// Select zone definition mode
if (GetParameterAsString("inzone") == "labelimage")
{
otbAppLogINFO("Zone definition: label image");
// Computing stats
m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
m_StatsFilter->Update();
// In this zone definition mode, the user can provide a no-data value for the labels
if (HasUserValue("inzone.labelimage.nodata"))
intNoData = GetParameterInt("inzone.labelimage.nodata");
otbAppLogINFO("Using no-data value for the label image: " << intNoData);
}
else if (GetParameterAsString("inzone") == "vector")
{
otbAppLogINFO("Zone definition: vector");
otbAppLogINFO("Loading vector data...");
VectorDataType* shp = GetParameterVectorData("inzone.vector.in");
// Reproject vector data
if (GetParameterInt("inzone.vector.reproject") != 0)
{
otbAppLogINFO("Vector data reprojection enabled");
m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
m_VectorDataReprojectionFilter->SetInputVectorData(shp);
m_VectorDataReprojectionFilter->SetInputImage(img);
AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
m_VectorDataReprojectionFilter->Update();
m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
}
else
{
m_VectorDataSrc = shp;
}
// Rasterize vector data
m_RasterizeFilter = RasterizeFilterType::New();
m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
m_RasterizeFilter->SetBurnAttribute("________");
m_RasterizeFilter->SetDefaultBurnValue(0);
m_RasterizeFilter->SetGlobalWarningDisplay(false);
m_RasterizeFilter->SetBackgroundValue(intNoData);
// Computing stats
m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
m_StatsFilter->Update();
}
else
{
otbAppLogFATAL("Unknown zone definition mode");
}
// Remove the no-data entry
StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
|| (GetParameterAsString("inzone") == "vector") )
{
countMap.erase(intNoData);
meanMap.erase(intNoData);
stdMap.erase(intNoData);
minMap.erase(intNoData);
maxMap.erase(intNoData);
}
if (GetParameterAsString("out") == "vector")
{
if (GetParameterAsString("inzone") == "vector")
{
// Add a statistics fields
otbAppLogINFO("Writing output vector data");
LabelValueType internalFID = 0;
m_NewVectorData = VectorDataType::New();
DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
DataNodeType::Pointer document = DataNodeType::New();
document->SetNodeType(otb::DOCUMENT);
m_NewVectorData->GetDataTree()->Add(document, root);
DataNodeType::Pointer folder = DataNodeType::New();
folder->SetNodeType(otb::FOLDER);
m_NewVectorData->GetDataTree()->Add(folder, document);
m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
itVector.GoToBegin();
while (!itVector.IsAtEnd())
{
if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVector.Get();
// Add the geometry with the new fields
if (countMap.count(internalFID) > 0)
{
currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
{
currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), meanMap[internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), minMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), maxMap [internalFID][band] );
}
m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
}
internalFID++;
}
++itVector;
} // next feature
SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
}
else if (GetParameterAsString("inzone") == "labelimage")
{
//vectorize the image
otbAppLogFATAL("Vector output from labelimage input not implemented yet");
}
}
else if (GetParameterAsString("out") == "xml")
{
// Write stats
const std::string outXMLFile = this->GetParameterString("out.xml.filename");
otbAppLogINFO("Writing " + outXMLFile)
StatsWriterType::Pointer statWriter = StatsWriterType::New();
statWriter->SetFileName(outXMLFile);
statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
statWriter->Update();
}
else
{
otbAppLogFATAL("Unknown output mode");
}
}
VectorDataType::Pointer m_VectorDataSrc;
VectorDataType::Pointer m_NewVectorData;
VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
RasterizeFilterType::Pointer m_RasterizeFilter;
StatsFilterType::Pointer m_StatsFilter;
};
}
}
OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<|endoftext|> |
<commit_before>//
// luna
//
// Copyright © 2016 D.E. Goodman-Wilson
//
#include <gtest/gtest.h>
#include <luna/luna.h>
#include <cpr/cpr.h>
#include "server_impl.h"
TEST(server_options, set_mime_type)
{
luna::server server{luna::server::mime_type{"howdyho"}
};
server.handle_request(luna::request_method::GET,
"/test",
[](auto matches, auto params) -> luna::response
{
return {"hello"};
});
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
ASSERT_EQ(200, res.status_code);
ASSERT_EQ("hello", res.text);
ASSERT_EQ("howdyho", res.header["Content-Type"]);
}
TEST(server_options, set_error_handler_cb)
{
luna::server server{luna::server::error_handler_cb
{
[](luna::response &response, //a hook for modifying in place to insert default content
luna::request_method method,
const std::string &path)
{
ASSERT_EQ(404, response.status_code);
ASSERT_EQ("/test", path);
ASSERT_EQ(luna::request_method::GET, method);
}
}
};
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
}
TEST(server_options, set_accept_policy_cb)
{
luna::server server{luna::server::accept_policy_cb
{
[](const struct sockaddr *add, socklen_t len) -> bool
{
//we can't really know what address will get passed in so just assert that
// returning "false" does the right thing, and that we got called.
EXPECT_NE(nullptr, add);
return false;
}
}
};
server.handle_request(luna::request_method::POST,
"/test",
[](auto matches, auto params) -> luna::response
{
return {"hello"};
});
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"});
ASSERT_EQ("", res.text);
}
TEST(server_options, set_unescaper_cb)
{
luna::server server{luna::server::unescaper_cb
{
[](const std::string &text) -> std::string
{
if(text == "value") return "ugh";
return text;
}
}
};
server.handle_request(luna::request_method::GET,
"/test",
[](auto matches, auto params) -> luna::response
{
EXPECT_EQ("ugh", params["key"]);
return {params["key"]};
});
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
ASSERT_EQ("ugh", res.text);
}<commit_msg>Autoformatting<commit_after>//
// luna
//
// Copyright © 2016 D.E. Goodman-Wilson
//
#include <gtest/gtest.h>
#include <luna/luna.h>
#include <cpr/cpr.h>
#include "server_impl.h"
TEST(server_options, set_mime_type)
{
luna::server server{luna::server::mime_type{"howdyho"}
};
server.handle_request(luna::request_method::GET,
"/test",
[](auto matches, auto params) -> luna::response
{
return {"hello"};
});
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
ASSERT_EQ(200, res.status_code);
ASSERT_EQ("hello", res.text);
ASSERT_EQ("howdyho", res.header["Content-Type"]);
}
TEST(server_options, set_error_handler_cb)
{
luna::server server{luna::server::error_handler_cb
{
[](luna::response &response, //a hook for modifying in place to insert default content
luna::request_method method,
const std::string &path)
{
ASSERT_EQ(404, response.status_code);
ASSERT_EQ("/test", path);
ASSERT_EQ(luna::request_method::GET, method);
}
}
};
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
}
TEST(server_options, set_accept_policy_cb)
{
luna::server server{luna::server::accept_policy_cb
{
[](const struct sockaddr *add, socklen_t len) -> bool
{
//we can't really know what address will get passed in so just assert that
// returning "false" does the right thing, and that we got called.
EXPECT_NE(nullptr, add);
return false;
}
}
};
server.handle_request(luna::request_method::POST,
"/test",
[](auto matches, auto params) -> luna::response
{
return {"hello"};
});
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"});
ASSERT_EQ("", res.text);
}
TEST(server_options, set_unescaper_cb)
{
luna::server server{luna::server::unescaper_cb
{
[](const std::string &text) -> std::string
{
if (text == "value") return "ugh";
return text;
}
}
};
server.handle_request(luna::request_method::GET,
"/test",
[](auto matches, auto params) -> luna::response
{
EXPECT_EQ("ugh", params["key"]);
return {params["key"]};
});
auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
ASSERT_EQ("ugh", res.text);
}<|endoftext|> |
<commit_before>/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <[email protected]>
* See COPYING for copyright and distribution information.
*/
#include <cstdlib>
#include <sstream>
#include <iostream>
#include "../ndn-cpp/face.hpp"
using namespace std;
using namespace ndn;
using namespace ptr_lib;
using namespace func_lib;
#if HAVE_STD_FUNCTION
// In the std library, the placeholders are in a different namespace than boost.
using namespace func_lib::placeholders;
#endif
class Counter
{
public:
Counter() {
callbackCount_ = 0;
}
void onData(const shared_ptr<const Interest>& interest, const shared_ptr<Data>& data)
{
++callbackCount_;
cout << "Got data packet with name " << data->getName().to_uri() << endl;
for (size_t i = 0; i < data->getContent().size(); ++i)
cout << (*data->getContent())[i];
cout << endl;
}
void onTimeout(const shared_ptr<const Interest>& interest)
{
++callbackCount_;
cout << "Time out for interest " << interest->getName().toUri() << endl;
}
int callbackCount_;
};
int main(int argc, char** argv)
{
try {
// Connect to port 9695 until the testbed hubs use NDNx.
Face face("E.hub.ndn.ucla.edu", 9695);
// Counter holds data used by the callbacks.
Counter counter;
Name name1("/ndn/ucla.edu/apps/ndn-js-test/hello.txt/level2/%FD%05%0B%16%7D%95%0E");
cout << "Express name " << name1.toUri() << endl;
// Use bind to pass the counter object to the callbacks.
face.expressInterest(name1, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));
Name name2("/ndn/ucla.edu/apps/lwndn-test/howdy.txt/%FD%05%05%E8%0C%CE%1D");
cout << "Express name " << name2.toUri() << endl;
face.expressInterest(name2, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));
Name name3("/test/timeout");
cout << "Express name " << name3.toUri() << endl;
face.expressInterest(name3, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));
// The main event loop.
while (counter.callbackCount_ < 3) {
face.processEvents();
// We need to sleep for a few milliseconds so we don't use 100% of the CPU.
usleep(10000);
}
} catch (std::exception& e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
<commit_msg>tests: Change test-get-async to use A.hub.ndn.ucla.edu.<commit_after>/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <[email protected]>
* See COPYING for copyright and distribution information.
*/
#include <cstdlib>
#include <sstream>
#include <iostream>
#include "../ndn-cpp/face.hpp"
using namespace std;
using namespace ndn;
using namespace ptr_lib;
using namespace func_lib;
#if HAVE_STD_FUNCTION
// In the std library, the placeholders are in a different namespace than boost.
using namespace func_lib::placeholders;
#endif
class Counter
{
public:
Counter() {
callbackCount_ = 0;
}
void onData(const shared_ptr<const Interest>& interest, const shared_ptr<Data>& data)
{
++callbackCount_;
cout << "Got data packet with name " << data->getName().to_uri() << endl;
for (size_t i = 0; i < data->getContent().size(); ++i)
cout << (*data->getContent())[i];
cout << endl;
}
void onTimeout(const shared_ptr<const Interest>& interest)
{
++callbackCount_;
cout << "Time out for interest " << interest->getName().toUri() << endl;
}
int callbackCount_;
};
int main(int argc, char** argv)
{
try {
// Connect to port 9695 until the testbed hubs use NDNx.
Face face("A.hub.ndn.ucla.edu", 9695);
// Counter holds data used by the callbacks.
Counter counter;
Name name1("/ndn/ucla.edu/apps/ndn-js-test/hello.txt/level2/%FD%05%0B%16%7D%95%0E");
cout << "Express name " << name1.toUri() << endl;
// Use bind to pass the counter object to the callbacks.
face.expressInterest(name1, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));
Name name2("/ndn/ucla.edu/apps/lwndn-test/howdy.txt/%FD%05%05%E8%0C%CE%1D");
cout << "Express name " << name2.toUri() << endl;
face.expressInterest(name2, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));
Name name3("/test/timeout");
cout << "Express name " << name3.toUri() << endl;
face.expressInterest(name3, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));
// The main event loop.
while (counter.callbackCount_ < 3) {
face.processEvents();
// We need to sleep for a few milliseconds so we don't use 100% of the CPU.
usleep(10000);
}
} catch (std::exception& e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: opengrf.cxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:34:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <tools/urlobj.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include "svdograf.hxx"
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif
#ifndef _SVX_OPENGRF_HXX
#include "opengrf.hxx"
#endif
#include "dialogs.hrc"
#include "impgrf.hrc"
//-----------------------------------------------------------------------------
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
USHORT SvxOpenGrfErr2ResId( short err )
{
switch( err )
{
case GRFILTER_OPENERROR:
return RID_SVXSTR_GRFILTER_OPENERROR;
case GRFILTER_IOERROR:
return RID_SVXSTR_GRFILTER_IOERROR;
case GRFILTER_VERSIONERROR:
return RID_SVXSTR_GRFILTER_VERSIONERROR;
case GRFILTER_FILTERERROR:
return RID_SVXSTR_GRFILTER_FILTERERROR;
case GRFILTER_FORMATERROR:
default:
return RID_SVXSTR_GRFILTER_FORMATERROR;
}
}
struct SvxOpenGrf_Impl
{
SvxOpenGrf_Impl ();
sfx2::FileDialogHelper aFileDlg;
uno::Reference < XFilePickerControlAccess > xCtrlAcc;
};
SvxOpenGrf_Impl::SvxOpenGrf_Impl() :
aFileDlg(SFXWB_GRAPHIC)
{
uno::Reference < XFilePicker > xFP = aFileDlg.GetFilePicker();
xCtrlAcc = uno::Reference < XFilePickerControlAccess >(xFP, UNO_QUERY);
}
SvxOpenGraphicDialog::SvxOpenGraphicDialog( const String& rTitle ) :
mpImpl( new SvxOpenGrf_Impl )
{
mpImpl->aFileDlg.SetTitle(rTitle);
}
SvxOpenGraphicDialog::~SvxOpenGraphicDialog()
{
}
GraphicFilter* GetGrfFilter();
short SvxOpenGraphicDialog::Execute()
{
USHORT nImpRet;
BOOL bQuitLoop(FALSE);
while( bQuitLoop == FALSE &&
mpImpl->aFileDlg.Execute() == ERRCODE_NONE )
{
if( GetPath().Len() )
{
GraphicFilter* pFilter = GetGrfFilter();
INetURLObject aObj( GetPath() );
// check whether we can load the graphic
String aCurFilter( GetCurrentFilter() );
USHORT nFormatNum = pFilter->GetImportFormatNumber( aCurFilter );
USHORT nRetFormat = 0;
USHORT nFound = USHRT_MAX;
// non-local?
if ( INET_PROT_FILE != aObj.GetProtocol() )
{
SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ, TRUE );
aMed.DownLoad();
SvStream* pStream = aMed.GetInStream();
if( pStream )
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream, nFormatNum, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat );
if ( GRFILTER_OK != nImpRet )
{
if ( !pStream )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream,
GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
}
else
{
if( (nImpRet=pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat )) != GRFILTER_OK )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
if ( GRFILTER_OK == nImpRet )
nFound = nRetFormat;
// could not load?
if ( nFound == USHRT_MAX )
{
WarningBox aWarningBox( NULL, WB_3DLOOK | WB_RETRY_CANCEL, SVX_RESSTR( SvxOpenGrfErr2ResId(nImpRet) ) );
bQuitLoop = aWarningBox.Execute()==RET_RETRY ? FALSE : TRUE;
}
else
{
// setup appropriate filter (so next time, it will work)
if( pFilter->GetImportFormatCount() )
{
String aFormatName(pFilter->GetImportFormatName(nFound));
SetCurrentFilter(aFormatName);
}
return nImpRet;
}
}
}
// cancel
return -1;
}
void SvxOpenGraphicDialog::SetPath( const String& rPath )
{
mpImpl->aFileDlg.SetDisplayDirectory(rPath);
}
void SvxOpenGraphicDialog::SetPath( const String& rPath, sal_Bool bLinkState )
{
SetPath(rPath);
AsLink(bLinkState);
}
void SvxOpenGraphicDialog::EnableLink( sal_Bool state )
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
mpImpl->xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, state );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot enable \"link\" checkbox" );
#endif
}
}
}
void SvxOpenGraphicDialog::AsLink(sal_Bool bState)
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
Any aAny; aAny <<= bState;
mpImpl->xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aAny );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot check \"link\" checkbox" );
#endif
}
}
}
sal_Bool SvxOpenGraphicDialog::IsAsLink() const
{
try
{
if( mpImpl->xCtrlAcc.is() )
{
Any aVal = mpImpl->xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
return aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_False;
}
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot access \"link\" checkbox" );
#endif
}
return sal_False;
}
int SvxOpenGraphicDialog::GetGraphic(Graphic& rGraphic) const
{
return mpImpl->aFileDlg.GetGraphic(rGraphic);
}
String SvxOpenGraphicDialog::GetPath() const
{
return mpImpl->aFileDlg.GetPath();
}
String SvxOpenGraphicDialog::GetCurrentFilter() const
{
return mpImpl->aFileDlg.GetCurrentFilter();
}
void SvxOpenGraphicDialog::SetCurrentFilter(const String& rStr)
{
mpImpl->aFileDlg.SetCurrentFilter(rStr);
}
void SvxOpenGraphicDialog::SetControlHelpIds( const INT16* _pControlId, const INT32* _pHelpId )
{
mpImpl->aFileDlg.SetControlHelpIds( _pControlId, _pHelpId );
}
void SvxOpenGraphicDialog::SetDialogHelpId( const INT32 _nHelpId )
{
mpImpl->aFileDlg.SetDialogHelpId( _nHelpId );
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.19.354); FILE MERGED 2007/06/04 13:26:22 vg 1.19.354.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: opengrf.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: hr $ $Date: 2007-06-27 17:23:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <tools/urlobj.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif
#ifndef _SVX_OPENGRF_HXX
#include "opengrf.hxx"
#endif
#include <svx/dialogs.hrc>
#include "impgrf.hrc"
//-----------------------------------------------------------------------------
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
USHORT SvxOpenGrfErr2ResId( short err )
{
switch( err )
{
case GRFILTER_OPENERROR:
return RID_SVXSTR_GRFILTER_OPENERROR;
case GRFILTER_IOERROR:
return RID_SVXSTR_GRFILTER_IOERROR;
case GRFILTER_VERSIONERROR:
return RID_SVXSTR_GRFILTER_VERSIONERROR;
case GRFILTER_FILTERERROR:
return RID_SVXSTR_GRFILTER_FILTERERROR;
case GRFILTER_FORMATERROR:
default:
return RID_SVXSTR_GRFILTER_FORMATERROR;
}
}
struct SvxOpenGrf_Impl
{
SvxOpenGrf_Impl ();
sfx2::FileDialogHelper aFileDlg;
uno::Reference < XFilePickerControlAccess > xCtrlAcc;
};
SvxOpenGrf_Impl::SvxOpenGrf_Impl() :
aFileDlg(SFXWB_GRAPHIC)
{
uno::Reference < XFilePicker > xFP = aFileDlg.GetFilePicker();
xCtrlAcc = uno::Reference < XFilePickerControlAccess >(xFP, UNO_QUERY);
}
SvxOpenGraphicDialog::SvxOpenGraphicDialog( const String& rTitle ) :
mpImpl( new SvxOpenGrf_Impl )
{
mpImpl->aFileDlg.SetTitle(rTitle);
}
SvxOpenGraphicDialog::~SvxOpenGraphicDialog()
{
}
GraphicFilter* GetGrfFilter();
short SvxOpenGraphicDialog::Execute()
{
USHORT nImpRet;
BOOL bQuitLoop(FALSE);
while( bQuitLoop == FALSE &&
mpImpl->aFileDlg.Execute() == ERRCODE_NONE )
{
if( GetPath().Len() )
{
GraphicFilter* pFilter = GetGrfFilter();
INetURLObject aObj( GetPath() );
// check whether we can load the graphic
String aCurFilter( GetCurrentFilter() );
USHORT nFormatNum = pFilter->GetImportFormatNumber( aCurFilter );
USHORT nRetFormat = 0;
USHORT nFound = USHRT_MAX;
// non-local?
if ( INET_PROT_FILE != aObj.GetProtocol() )
{
SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ, TRUE );
aMed.DownLoad();
SvStream* pStream = aMed.GetInStream();
if( pStream )
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream, nFormatNum, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat );
if ( GRFILTER_OK != nImpRet )
{
if ( !pStream )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream,
GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
}
else
{
if( (nImpRet=pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat )) != GRFILTER_OK )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
if ( GRFILTER_OK == nImpRet )
nFound = nRetFormat;
// could not load?
if ( nFound == USHRT_MAX )
{
WarningBox aWarningBox( NULL, WB_3DLOOK | WB_RETRY_CANCEL, SVX_RESSTR( SvxOpenGrfErr2ResId(nImpRet) ) );
bQuitLoop = aWarningBox.Execute()==RET_RETRY ? FALSE : TRUE;
}
else
{
// setup appropriate filter (so next time, it will work)
if( pFilter->GetImportFormatCount() )
{
String aFormatName(pFilter->GetImportFormatName(nFound));
SetCurrentFilter(aFormatName);
}
return nImpRet;
}
}
}
// cancel
return -1;
}
void SvxOpenGraphicDialog::SetPath( const String& rPath )
{
mpImpl->aFileDlg.SetDisplayDirectory(rPath);
}
void SvxOpenGraphicDialog::SetPath( const String& rPath, sal_Bool bLinkState )
{
SetPath(rPath);
AsLink(bLinkState);
}
void SvxOpenGraphicDialog::EnableLink( sal_Bool state )
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
mpImpl->xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, state );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot enable \"link\" checkbox" );
#endif
}
}
}
void SvxOpenGraphicDialog::AsLink(sal_Bool bState)
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
Any aAny; aAny <<= bState;
mpImpl->xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aAny );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot check \"link\" checkbox" );
#endif
}
}
}
sal_Bool SvxOpenGraphicDialog::IsAsLink() const
{
try
{
if( mpImpl->xCtrlAcc.is() )
{
Any aVal = mpImpl->xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
return aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_False;
}
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot access \"link\" checkbox" );
#endif
}
return sal_False;
}
int SvxOpenGraphicDialog::GetGraphic(Graphic& rGraphic) const
{
return mpImpl->aFileDlg.GetGraphic(rGraphic);
}
String SvxOpenGraphicDialog::GetPath() const
{
return mpImpl->aFileDlg.GetPath();
}
String SvxOpenGraphicDialog::GetCurrentFilter() const
{
return mpImpl->aFileDlg.GetCurrentFilter();
}
void SvxOpenGraphicDialog::SetCurrentFilter(const String& rStr)
{
mpImpl->aFileDlg.SetCurrentFilter(rStr);
}
void SvxOpenGraphicDialog::SetControlHelpIds( const INT16* _pControlId, const INT32* _pHelpId )
{
mpImpl->aFileDlg.SetControlHelpIds( _pControlId, _pHelpId );
}
void SvxOpenGraphicDialog::SetDialogHelpId( const INT32 _nHelpId )
{
mpImpl->aFileDlg.SetDialogHelpId( _nHelpId );
}
<|endoftext|> |
<commit_before><commit_msg>SdrMarkView tiled rendering: fix unexpected empty graphic selection events<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.