text
stringlengths
54
60.6k
<commit_before>#include "stdafx.h" #include "MainScene.h" #include "TWScene.h" Scene* TWScene::createScene() { auto scene = Scene::create(); auto layer = TWScene::create(); scene->addChild(layer); return scene; } bool TWScene::init() { if (!CCLayerColor::initWithColor(Color4B::BLUE)) { return false; } //1ȸ ͵ auto mainTitle = Label::createWithTTF("Main Title\n fuck!!!!", "fonts/NanumGothic.ttf", 34); mainTitle->setPosition(Point(160, 240)); mainTitle->setName("MainTitle"); Size winSize = Director::getInstance()->getVisibleSize(); float labelWidth = mainTitle->getContentSize().width; float labelHeight = mainTitle->getContentSize().height; auto action1 = MoveTo::create(10.0 / labelHeight, Point(labelWidth / 2, winSize.height - labelHeight / 2)); auto action2 = MoveTo::create(10.0 / labelWidth, Point(winSize.width - labelWidth / 2, winSize.height - labelHeight / 2)); auto action3 = MoveTo::create(10.0 / labelHeight, Point(winSize.width - labelWidth / 2, labelHeight / 2)); auto action4 = MoveTo::create(10.0 / labelWidth, Point(labelWidth / 2, labelHeight / 2)); auto sequence_action = Sequence::create(action1, action2, action3, action4, NULL); auto forever_repeat_action = RepeatForever::create(sequence_action); mainTitle->runAction(forever_repeat_action); //mainTitle->stopAction(forever_repeat_action); this->addChild(mainTitle); auto listener = EventListenerMouse::create(); listener->onMouseUp = CC_CALLBACK_1(TWScene::onMouseUP, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //2ȸ ͵ Sprite* character = Sprite::create(); this->addChild(character); character->setPosition(Point(winSize.width / 2, winSize.height / 2)); Vector<SpriteFrame*> animFrames; animFrames.reserve(4); for (int i = 0; i < 4; i++) animFrames.pushBack(SpriteFrame::create("res/lisa.png", Rect(0, 48 * i, 27, 48))); // create the animation out of the frame Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* animate = Animate::create(animation); // run it and repeat it forever RepeatForever *action = RepeatForever::create(animate); character->runAction(action); this->schedule(schedule_selector(TWScene::ChangeBackground), 1.0); Layer* bgLayer = Layer::create(); this->addChild(bgLayer, 1); auto spr_0 = Sprite::create("res/mc.jpg"); spr_0->setScaleX(winSize.width); spr_0->setScaleY(winSize.height); spr_0->setAnchorPoint(Point::ZERO); spr_0->setPosition(Point::ZERO); bgLayer->addChild(spr_0); auto action_0 = MoveBy::create(10.0, Point(-2000, 0)); auto action_1 = Place::create(Point::ZERO); auto action_2 = Sequence::create(action_0, action_1, NULL); auto action_3 = RepeatForever::create(action_2); bgLayer->runAction(action_3); return true; } void TWScene::ChangeBackground(float deltaTIme) { Color3B color; int rand = random() % 5; switch (rand){ case 0: color = Color3B::YELLOW; break; case 1: color = Color3B::BLUE; break; case 2: color = Color3B::GREEN; break; case 3: color = Color3B::RED; break; case 4: color = Color3B::MAGENTA; break; case 5: color = Color3B::BLACK; break; case 6: color = Color3B::ORANGE; break; case 7: color = Color3B::GRAY; break; } this->setColor(color); } void TWScene::ChangeToMainScene(Ref* pSender) { Director::getInstance()->replaceScene(MainScene::createScene()); } void TWScene::onMouseUP(cocos2d::Event* event) { auto mainTitle = this->getChildByName("MainTitle"); if (!mainTitle->isVisible()) mainTitle->setVisible(true); else mainTitle->setVisible(false); } <commit_msg>Unsolved<commit_after>#include "stdafx.h" #include "MainScene.h" #include "TWScene.h" Scene* TWScene::createScene() { auto scene = Scene::create(); auto layer = TWScene::create(); scene->addChild(layer); return scene; } bool TWScene::init() { if (!CCLayerColor::initWithColor(Color4B::BLUE)) { return false; } //1ȸ ͵ auto mainTitle = Label::createWithTTF("Main Title\n fuck!!!!", "fonts/NanumGothic.ttf", 34); mainTitle->setPosition(Point(160, 240)); mainTitle->setName("MainTitle"); Size winSize = Director::getInstance()->getVisibleSize(); float labelWidth = mainTitle->getContentSize().width; float labelHeight = mainTitle->getContentSize().height; auto action1 = MoveTo::create(10.0 / labelHeight, Point(labelWidth / 2, winSize.height - labelHeight / 2)); auto action2 = MoveTo::create(10.0 / labelWidth, Point(winSize.width - labelWidth / 2, winSize.height - labelHeight / 2)); auto action3 = MoveTo::create(10.0 / labelHeight, Point(winSize.width - labelWidth / 2, labelHeight / 2)); auto action4 = MoveTo::create(10.0 / labelWidth, Point(labelWidth / 2, labelHeight / 2)); auto sequence_action = Sequence::create(action1, action2, action3, action4, NULL); auto forever_repeat_action = RepeatForever::create(sequence_action); mainTitle->runAction(forever_repeat_action); //mainTitle->stopAction(forever_repeat_action); this->addChild(mainTitle); auto listener = EventListenerMouse::create(); listener->onMouseUp = CC_CALLBACK_1(TWScene::onMouseUP, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //2ȸ ͵ Sprite* character = Sprite::create(); this->addChild(character); character->setPosition(Point(winSize.width / 2, winSize.height / 2)); Vector<SpriteFrame*> animFrames; animFrames.reserve(4); for (int i = 0; i < 4; i++) animFrames.pushBack(SpriteFrame::create("res/lisa.png", Rect(0, 48 * i, 27, 48))); // create the animation out of the frame Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* animate = Animate::create(animation); // run it and repeat it forever RepeatForever *action = RepeatForever::create(animate); character->runAction(action); this->schedule(schedule_selector(TWScene::ChangeBackground), 1.0); Layer* bgLayer = Layer::create(); this->addChild(bgLayer, 1); auto spr_0 = Sprite::create("res/mc.jpg"); spr_0->setScaleX(winSize.width / spr_0->getContentSize().width); spr_0->setScaleY(winSize.height / spr_0->getContentSize().height); spr_0->setAnchorPoint(Point::ZERO); spr_0->setPosition(Point::ZERO); bgLayer->addChild(spr_0); auto spr_1 = Sprite::create("res/mc.jpg"); spr_1->setScaleX(winSize.width / spr_1->getContentSize().width); spr_1->setScaleY(winSize.height / spr_1->getContentSize().height); spr_1->setAnchorPoint(Point::ZERO); spr_1->setPosition(Point(winSize.width, 0)); bgLayer->addChild(spr_1); auto action_0 = MoveBy::create(10.0, Point(-2000, 0)); auto action_1 = Place::create(Point::ZERO); auto action_2 = Sequence::create(action_0, action_1, NULL); auto action_3 = RepeatForever::create(action_2); bgLayer->runAction(action_3); return true; } void TWScene::ChangeBackground(float deltaTIme) { Color3B color; int rand = random() % 5; switch (rand){ case 0: color = Color3B::YELLOW; break; case 1: color = Color3B::BLUE; break; case 2: color = Color3B::GREEN; break; case 3: color = Color3B::RED; break; case 4: color = Color3B::MAGENTA; break; case 5: color = Color3B::BLACK; break; case 6: color = Color3B::ORANGE; break; case 7: color = Color3B::GRAY; break; } this->setColor(color); } void TWScene::ChangeToMainScene(Ref* pSender) { Director::getInstance()->replaceScene(MainScene::createScene()); } void TWScene::onMouseUP(cocos2d::Event* event) { auto mainTitle = this->getChildByName("MainTitle"); if (!mainTitle->isVisible()) mainTitle->setVisible(true); else mainTitle->setVisible(false); } <|endoftext|>
<commit_before>// @(#)root/hist:$Id$ // Author: David Gonzalez Maline 12/11/09 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TFitResultPtr.h" #include "TFitResult.h" #include "TError.h" /** TFitResultPtr provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult. In addition it provides an automatic comversion to an integer. In this way it can be returned from the TH1::Fit method and the change in TH1::Fit be backward compatible. The class */ ClassImp(TFitResultPtr) TFitResultPtr::TFitResultPtr(TFitResult * p) : fStatus(-1), fPointer(p) { // constructor from a TFitResult pointer if (fPointer != 0) fStatus = fPointer->Status(); } TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) : fStatus(rhs.fStatus), fPointer(0) { // copy constructor - create a new TFitResult if needed if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs); } TFitResultPtr::~TFitResultPtr() { // destructor - delete the contained TFitResult pointer if needed if ( fPointer != 0) delete fPointer; } TFitResult& TFitResultPtr::operator*() const { // impelment the de-reference operator to make the class acts as a pointer to a TFitResult // assert in case the class does not contain a pointer to TFitResult if (fPointer == 0) { Error("TFitResultPtr","TFitResult is empty - use the fit option S"); return *(new TFitResult() ); } return *fPointer; } TFitResult* TFitResultPtr::operator->() const { // implement the -> operator to make the class acts as a pointer to a TFitResult // assert in case the class does not contain a pointer to TFitResult if (fPointer == 0) { Error("TFitResultPtr","TFitResult is empty - use the fit option S"); return new TFitResult(); } return fPointer; } TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs) { // assignment operator // if needed copy the TFitResult object and delete previous one if existing if ( &rhs == this) return *this; // self assignment fStatus = rhs.fStatus; if ( fPointer ) delete fPointer; fPointer = 0; if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs); return *this; } <commit_msg>fix minor typo<commit_after>// @(#)root/hist:$Id$ // Author: David Gonzalez Maline 12/11/09 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TFitResultPtr.h" #include "TFitResult.h" #include "TError.h" /** TFitResultPtr provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult. In addition it provides an automatic comversion to an integer. In this way it can be returned from the TH1::Fit method and the change in TH1::Fit be backward compatible. The class */ ClassImp(TFitResultPtr) TFitResultPtr::TFitResultPtr(TFitResult * p) : fStatus(-1), fPointer(p) { // constructor from a TFitResult pointer if (fPointer != 0) fStatus = fPointer->Status(); } TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) : fStatus(rhs.fStatus), fPointer(0) { // copy constructor - create a new TFitResult if needed if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs); } TFitResultPtr::~TFitResultPtr() { // destructor - delete the contained TFitResult pointer if needed if ( fPointer != 0) delete fPointer; } TFitResult& TFitResultPtr::operator*() const { // implement the de-reference operator to make the class acts as a pointer to a TFitResult // assert in case the class does not contain a pointer to TFitResult if (fPointer == 0) { Error("TFitResultPtr","TFitResult is empty - use the fit option S"); return *(new TFitResult() ); } return *fPointer; } TFitResult* TFitResultPtr::operator->() const { // implement the -> operator to make the class acts as a pointer to a TFitResult // assert in case the class does not contain a pointer to TFitResult if (fPointer == 0) { Error("TFitResultPtr","TFitResult is empty - use the fit option S"); return new TFitResult(); } return fPointer; } TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs) { // assignment operator // if needed copy the TFitResult object and delete previous one if existing if ( &rhs == this) return *this; // self assignment fStatus = rhs.fStatus; if ( fPointer ) delete fPointer; fPointer = 0; if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs); return *this; } <|endoftext|>
<commit_before>#include <opencv2\opencv.hpp> #include <opencv2\imgproc.hpp> #include <opencv2\highgui.hpp> #include <opencv2\ml.hpp> #include <vector> #include <iostream> #include <random> #include "AdaBoost.h" #include "VectorData.h" #include "MatData.h" #include "WeakVectorClassifierFactory.h" #include "WeakHaarClassifierFactory.h" #include "AdaBoostEdgeDetector.h" const double PI = 3.14159265; void test2DPoints() { //Mat img = imread("sky.jpg"); //Mat gray; //cv::cvtColor(img, gray, CV_BGR2GRAY); //imshow("Colored Image", img); //imshow("Gray Image", gray); //waitKey(); // generate the data std::vector<DataPoint*> data; int i = 0; cv::Mat img = cv::Mat::zeros(1100, 1100, CV_32FC3); for (double r = 0.1 * 1000; r <= 0.51 * 1000; r += 0.05 * 1000) { for (double theta = 0; theta <= 1.81 * PI; theta += (PI / 5),i++) { std::vector<double> d = std::vector<double>(2, 0); d[0] = 0.5f + r * std::cos(theta); d[1] = 0.5f + (r - 0.05) * std::sin(theta); data.push_back(new VectorData(d)); } } // test //data.clear(); //label.clear(); //for (int i = 0; i < 3; i++) //{ // data.push_back(std::vector<double>(2, 0)); // data[i][0] = i; // data[i][1] = rand() % 10; //} //for (int i = 3; i < 6; i++) //{ // data.push_back(std::vector<double>(2, 0)); // data[i][0] = i; // data[i][1] = rand() % 20; //} // std::cout << data.size() << std::endl; int shift = 510; std::vector<int> label(30,1); label.resize(data.size(), -1); for (int i = 0; i < data.size(); i++) { cv::circle(img, cv::Point(data[i]->getVectorData()[0] + shift, data[i]->getVectorData()[1] + shift), 2, cv::Scalar(((label[i] - 1) / -2) * 255, 0, ((label[i] + 1)/2) * 255), -1); } //freopen("result.csv", "w", stdout); WeakClassifierFactory * factory = new WeakVectorClassifierFactory(); for (int i = 1; i < 30; i+=2) { AdaBoost adaboost(i, factory); std::vector<int> outLabels; double accuracy = adaboost.train(data, label, outLabels); std::cout << i << ", " << accuracy << std::endl; //system("PAUSE"); } cv::imshow("img", img); cv::waitKey(); } void displayIntegralImage(cv::Mat Iimg) { double min, max; cv::minMaxLoc(Iimg, &min, &max); Iimg -= min; Iimg /= (max - min); cv::imshow("image", Iimg); cv::waitKey(); } /* void testMatData() { cv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1); m(cv::Rect(0, 0, 200, 200)) = 50; m(cv::Rect(0, 200, 200, 200)) = 200; m(cv::Rect(200, 0, 200, 200)) = 150; m(cv::Rect(200, 200, 200, 200)) = 100; cv::Mat Iimg, I2img; cv::integral(m, Iimg, I2img, CV_32FC1); // display //displayIntegralImage(Iimg); cv::Mat edges = AdaBoostEdgeDetector::cannyEdgeDetection(m); // prepare data vector std::vector<DataPoint*> trainData; std::vector<int> labels; cv::Mat show; cv::cvtColor(m, show, CV_GRAY2BGR); // make patches 10x10 with step 5 for (int r = 0; r <= 390; r += 5) { for (int c = 0; c <= 390; c += 5) { cv::Rect win = cv::Rect(c, r, 10, 10); trainData.push_back(new MatData(Iimg, win)); //MatData testData(m, win); //cv::imshow("window", testData.getMatData()); //cv::waitKey(); if (cv::sum(edges(win)).val[0] > 1) { // edge labels.push_back(1); cv::rectangle(show, win, cv::Scalar(255, 0, 0)); } else { // non edge labels.push_back(-1); } } } cv::imshow("my edges", show); cv::waitKey(50); // prepare the Haar Classifier Factory std::vector<std::vector<std::vector<int> > > shapes; int arr[] = { -1,1 }; std::vector<std::vector<int> > shape1(2,std::vector<int>(1,1)); shape1[0][0] = -1; std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1)); shape2[0][0] = shape2[1][1] = -1; shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2))); shapes.push_back(shape1); //shapes.push_back(shape2); std::vector<cv::Point> locs(1, cv::Point(0, 0)); std::vector<cv::Size> sizes; sizes.push_back(cv::Size(5, 10)); sizes.push_back(cv::Size(10, 5)); //sizes.push_back(cv::Size(5, 5)); for (int i = 1; i < 30; i ++) { WeakClassifierFactory * factory = new WeakHaarClassifierFactory(shapes, sizes, locs); AdaBoost adaboost(i, factory); std::vector<int> y; double accuracy = adaboost.train(trainData, labels, y); std::cout << i << ", " << accuracy << std::endl; cv::Mat show1; show.copyTo(show1); for (int j = 0; j < y.size(); j++) { if (y[j] == 1) { if (labels[j] == 1) { cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 255, 0)); } else { cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 0, 255)); } } } cv::imshow("my edges", show1); cv::waitKey(0); //system("PAUSE"); } } */ void testAdaBoostEdgeDetection() { cv::Mat testImg = cv::imread("test.png", 0); cv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1); m(cv::Rect(0, 0, 200, 200)) = 50; m(cv::Rect(0, 200, 200, 200)) = 200; m(cv::Rect(200, 0, 200, 200)) = 150; m(cv::Rect(200, 200, 200, 200)) = 100; cv::imwrite("orig.png", m); std::vector<cv::Mat> images; images.push_back(m); std::vector<std::vector<std::vector<int> > > shapes; int arr[] = { -1,1 }; std::vector<std::vector<int> > shape1(2, std::vector<int>(1, 1)); shape1[0][0] = -1; std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1)); shape2[0][0] = shape2[1][1] = -1; shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2))); shapes.push_back(shape1); //shapes.push_back(shape2); for (int t = 1; t < 20; t++) { AdaBoostEdgeDetector adaBoostEdgeDetector(t, shapes, cv::Size(4,4), 2); adaBoostEdgeDetector.train(images, true); adaBoostEdgeDetector.test(testImg, true); } } int main() { //test2DPoints(); //testMatData(); testAdaBoostEdgeDetection(); return 0; }<commit_msg>final test before class<commit_after>#include <opencv2\opencv.hpp> #include <opencv2\imgproc.hpp> #include <opencv2\highgui.hpp> #include <opencv2\ml.hpp> #include <vector> #include <iostream> #include <random> #include "AdaBoost.h" #include "VectorData.h" #include "MatData.h" #include "WeakVectorClassifierFactory.h" #include "WeakHaarClassifierFactory.h" #include "AdaBoostEdgeDetector.h" const double PI = 3.14159265; void test2DPoints() { //Mat img = imread("sky.jpg"); //Mat gray; //cv::cvtColor(img, gray, CV_BGR2GRAY); //imshow("Colored Image", img); //imshow("Gray Image", gray); //waitKey(); // generate the data std::vector<DataPoint*> data; int i = 0; cv::Mat img = cv::Mat::zeros(1100, 1100, CV_32FC3); for (double r = 0.1 * 1000; r <= 0.51 * 1000; r += 0.05 * 1000) { for (double theta = 0; theta <= 1.81 * PI; theta += (PI / 5),i++) { std::vector<double> d = std::vector<double>(2, 0); d[0] = 0.5f + r * std::cos(theta); d[1] = 0.5f + (r - 0.05) * std::sin(theta); data.push_back(new VectorData(d)); } } // test //data.clear(); //label.clear(); //for (int i = 0; i < 3; i++) //{ // data.push_back(std::vector<double>(2, 0)); // data[i][0] = i; // data[i][1] = rand() % 10; //} //for (int i = 3; i < 6; i++) //{ // data.push_back(std::vector<double>(2, 0)); // data[i][0] = i; // data[i][1] = rand() % 20; //} // std::cout << data.size() << std::endl; int shift = 510; std::vector<int> label(30,1); label.resize(data.size(), -1); for (int i = 0; i < data.size(); i++) { cv::circle(img, cv::Point(data[i]->getVectorData()[0] + shift, data[i]->getVectorData()[1] + shift), 2, cv::Scalar(((label[i] - 1) / -2) * 255, 0, ((label[i] + 1)/2) * 255), -1); } //freopen("result.csv", "w", stdout); WeakClassifierFactory * factory = new WeakVectorClassifierFactory(); for (int i = 1; i < 30; i+=2) { AdaBoost adaboost(i, factory); std::vector<int> outLabels; double accuracy = adaboost.train(data, label, outLabels); std::cout << i << ", " << accuracy << std::endl; //system("PAUSE"); } cv::imshow("img", img); cv::waitKey(); } void displayIntegralImage(cv::Mat Iimg) { double min, max; cv::minMaxLoc(Iimg, &min, &max); Iimg -= min; Iimg /= (max - min); cv::imshow("image", Iimg); cv::waitKey(); } /* void testMatData() { cv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1); m(cv::Rect(0, 0, 200, 200)) = 50; m(cv::Rect(0, 200, 200, 200)) = 200; m(cv::Rect(200, 0, 200, 200)) = 150; m(cv::Rect(200, 200, 200, 200)) = 100; cv::Mat Iimg, I2img; cv::integral(m, Iimg, I2img, CV_32FC1); // display //displayIntegralImage(Iimg); cv::Mat edges = AdaBoostEdgeDetector::cannyEdgeDetection(m); // prepare data vector std::vector<DataPoint*> trainData; std::vector<int> labels; cv::Mat show; cv::cvtColor(m, show, CV_GRAY2BGR); // make patches 10x10 with step 5 for (int r = 0; r <= 390; r += 5) { for (int c = 0; c <= 390; c += 5) { cv::Rect win = cv::Rect(c, r, 10, 10); trainData.push_back(new MatData(Iimg, win)); //MatData testData(m, win); //cv::imshow("window", testData.getMatData()); //cv::waitKey(); if (cv::sum(edges(win)).val[0] > 1) { // edge labels.push_back(1); cv::rectangle(show, win, cv::Scalar(255, 0, 0)); } else { // non edge labels.push_back(-1); } } } cv::imshow("my edges", show); cv::waitKey(50); // prepare the Haar Classifier Factory std::vector<std::vector<std::vector<int> > > shapes; int arr[] = { -1,1 }; std::vector<std::vector<int> > shape1(2,std::vector<int>(1,1)); shape1[0][0] = -1; std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1)); shape2[0][0] = shape2[1][1] = -1; shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2))); shapes.push_back(shape1); //shapes.push_back(shape2); std::vector<cv::Point> locs(1, cv::Point(0, 0)); std::vector<cv::Size> sizes; sizes.push_back(cv::Size(5, 10)); sizes.push_back(cv::Size(10, 5)); //sizes.push_back(cv::Size(5, 5)); for (int i = 1; i < 30; i ++) { WeakClassifierFactory * factory = new WeakHaarClassifierFactory(shapes, sizes, locs); AdaBoost adaboost(i, factory); std::vector<int> y; double accuracy = adaboost.train(trainData, labels, y); std::cout << i << ", " << accuracy << std::endl; cv::Mat show1; show.copyTo(show1); for (int j = 0; j < y.size(); j++) { if (y[j] == 1) { if (labels[j] == 1) { cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 255, 0)); } else { cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 0, 255)); } } } cv::imshow("my edges", show1); cv::waitKey(0); //system("PAUSE"); } } */ void testAdaBoostEdgeDetection(int horizontal = 1, int vertical = 1, int t = 6, std::string trainImg = "orig.png",std::string testImage = "test.png") { cv::Mat testImg = cv::imread(testImage, 0); cv::Mat m = cv::imread(trainImg, 0); std::vector<cv::Mat> images; images.push_back(m); std::vector<std::vector<std::vector<int> > > shapes; int arr[] = { -1,1 }; std::vector<std::vector<int> > shape1(2, std::vector<int>(1, 1)); shape1[0][0] = -1; std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1)); shape2[0][0] = shape2[1][1] = -1; if (horizontal) { shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2))); } if (vertical) { shapes.push_back(shape1); } //shapes.push_back(shape2); //for (int t = 1; t < 20; t++) { AdaBoostEdgeDetector adaBoostEdgeDetector(t, shapes, cv::Size(4,4), 2); adaBoostEdgeDetector.train(images, true); adaBoostEdgeDetector.test(testImg, true); } } int main(int argc, char*argv[]) { int horizontal = 1; int vertical = 1; int t = 6; std::string trainImg = "orig.png"; std::string testImage = "test.png"; for (int i = 0; i < argc; i++) { if (std::string(argv[i]) == "-h") { horizontal = std::stoi(argv[i + 1]); } else if (std::string(argv[i]) == "-v") { vertical = std::stoi(argv[i + 1]); } else if (std::string(argv[i]) == "-t") { t = std::stoi(argv[i + 1]); } else if (std::string(argv[i]) == "-i") { trainImg = argv[i + 1]; } else if (std::string(argv[i]) == "-o") { testImage = argv[i + 1]; } else { i--; } i++; } //test2DPoints(); //testMatData(); testAdaBoostEdgeDetection(horizontal,vertical,t,trainImg,testImage); return 0; }<|endoftext|>
<commit_before>// FROM: http://playground.arduino.cc/Code/EEPROMLoadAndSaveSettings /* LoadAndSaveSettings * footswitch 2012-03-05, original code by Joghurt (2010) * Demonstrates how to load and save settings to the EEPROM * Tested on Arduino Uno R2 with Arduino 0023 */ // Contains EEPROM.read() and EEPROM.write() #include <EEPROM.h> #include <Arduino.h> #include "Settings.h" #define MAD_SETTINGS_LOGGING 1 StoreStruct my_settings = { // The default values 0.2f, -0.25f, // 220, 1884, // 'c', // 10000, // {4.5, 5.5, 7, 8.5, 10, 12}, CONFIG_VERSION }; bool my_settings_loaded = false; void loadConfig() { // To make sure there are settings, and they are YOURS! // If nothing is found it will use the default settings. if (//EEPROM.read(CONFIG_START + sizeof(settings) - 1) == settings.version_of_program[3] // this is '\0' EEPROM.read(CONFIG_START + sizeof(my_settings) - 2) == my_settings.version_of_program[2] && EEPROM.read(CONFIG_START + sizeof(my_settings) - 3) == my_settings.version_of_program[1] && EEPROM.read(CONFIG_START + sizeof(my_settings) - 4) == my_settings.version_of_program[0]) { // reads settings from EEPROM for (unsigned int t=0; t<sizeof(my_settings); t++) { *((char*)&my_settings + t) = EEPROM.read(CONFIG_START + t); } #if MAD_SETTINGS_LOGGING // error writing to EEPROM Serial.println("[SETTINGS] Loaded!"); #endif my_settings_loaded = true; } else { // settings aren't valid! will overwrite with default settings saveConfig(); } } void saveConfig() { for (unsigned int t=0; t<sizeof(my_settings); t++) { // writes to EEPROM EEPROM.write(CONFIG_START + t, *((char*)&my_settings + t)); // and verifies the data if (EEPROM.read(CONFIG_START + t) != *((char*)&my_settings + t)) { #if MAD_SETTINGS_LOGGING // error writing to EEPROM Serial.println("[SETTINGS] Write Error"); #endif } else { #if MAD_SETTINGS_LOGGING // error writing to EEPROM Serial.println("[SETTINGS] Write Success!"); #endif } } } // void setup() { // loadConfig(); // } // void loop() { // // [...] // int i = settings.c - 'a'; // // [...] // // [...] // settings.c = 'a'; // if (some_condition) // saveConfig(); // // [...] // } // [Get Code] <commit_msg>minor<commit_after>// FROM: http://playground.arduino.cc/Code/EEPROMLoadAndSaveSettings /* LoadAndSaveSettings * footswitch 2012-03-05, original code by Joghurt (2010) * Demonstrates how to load and save settings to the EEPROM * Tested on Arduino Uno R2 with Arduino 0023 */ // Contains EEPROM.read() and EEPROM.write() #include <EEPROM.h> #include <Arduino.h> #include "Settings.h" #define MAD_SETTINGS_LOGGING 1 StoreStruct my_settings = { // The default values 0.2f, -0.25f, // 220, 1884, // 'c', // 10000, // {4.5, 5.5, 7, 8.5, 10, 12}, CONFIG_VERSION }; bool my_settings_loaded = false; void loadConfig() { // To make sure there are settings, and they are YOURS! // If nothing is found it will use the default settings. if (//EEPROM.read(CONFIG_START + sizeof(settings) - 1) == settings.version_of_program[3] // this is '\0' EEPROM.read(CONFIG_START + sizeof(my_settings) - 2) == my_settings.version_of_program[2] && EEPROM.read(CONFIG_START + sizeof(my_settings) - 3) == my_settings.version_of_program[1] && EEPROM.read(CONFIG_START + sizeof(my_settings) - 4) == my_settings.version_of_program[0]) { // reads settings from EEPROM for (unsigned int t=0; t<sizeof(my_settings); t++) { *((char*)&my_settings + t) = EEPROM.read(CONFIG_START + t); } #if MAD_SETTINGS_LOGGING // error writing to EEPROM Serial.print("[SETTINGS] Loaded! Float Value="); Serial.print(my_settings.accelerometer_angle_positive); Serial.println("!"); #endif my_settings_loaded = true; } else { // settings aren't valid! will overwrite with default settings saveConfig(); } } void saveConfig() { for (unsigned int t=0; t<sizeof(my_settings); t++) { // writes to EEPROM EEPROM.write(CONFIG_START + t, *((char*)&my_settings + t)); // and verifies the data if (EEPROM.read(CONFIG_START + t) != *((char*)&my_settings + t)) { #if MAD_SETTINGS_LOGGING // error writing to EEPROM Serial.println("[SETTINGS] Write Error"); #endif } else { #if MAD_SETTINGS_LOGGING // error writing to EEPROM Serial.println("[SETTINGS] Write Success!"); #endif } } } // void setup() { // loadConfig(); // } // void loop() { // // [...] // int i = settings.c - 'a'; // // [...] // // [...] // settings.c = 'a'; // if (some_condition) // saveConfig(); // // [...] // } // [Get Code] <|endoftext|>
<commit_before><commit_msg>Replace fedpeg template init check for pak one<commit_after><|endoftext|>
<commit_before>#pragma once #include <string> #include <stdexcept> #include <clang-c/Index.h> namespace color_coded { namespace clang { namespace token { inline std::string map_type_kind(CXTypeKind const kind) { switch(kind) { case CXType_Unexposed: return "Variable"; case CXType_Void: case CXType_Bool: case CXType_Char_U: case CXType_UChar: case CXType_Char16: case CXType_Char32: case CXType_UShort: case CXType_UInt: case CXType_ULong: case CXType_ULongLong: case CXType_UInt128: case CXType_Char_S: case CXType_SChar: case CXType_WChar: case CXType_Short: case CXType_Int: case CXType_Long: case CXType_LongLong: case CXType_Int128: case CXType_Float: case CXType_Double: case CXType_LongDouble: case CXType_NullPtr: case CXType_Overload: case CXType_Dependent: case CXType_ObjCId: case CXType_ObjCClass: case CXType_ObjCSel: return "Variable"; case CXType_Complex: case CXType_Pointer: case CXType_BlockPointer: case CXType_LValueReference: case CXType_RValueReference: case CXType_Record: case CXType_Typedef: case CXType_ObjCInterface: case CXType_ObjCObjectPointer: case CXType_ConstantArray: case CXType_Vector: case CXType_IncompleteArray: case CXType_VariableArray: case CXType_DependentSizedArray: return "Variable"; case CXType_MemberPointer: return "Member"; case CXType_Enum: return "EnumConstant"; case CXType_FunctionNoProto: case CXType_FunctionProto: return "Function"; case CXType_Auto: return "Variable"; default: return ""; //return "Error1 " + std::to_string(kind); } } inline std::string map_cursor_kind(CXCursorKind const kind, CXTypeKind const type) { switch(kind) { /********* Declarations **********/ case CXCursor_UnexposedDecl: /* Unknown declaration */ return ""; case CXCursor_StructDecl: return "StructDecl"; case CXCursor_UnionDecl: return "UnionDecl"; case CXCursor_ClassDecl: return "ClassDecl"; case CXCursor_EnumDecl: return "EnumDecl"; case CXCursor_FieldDecl: return "FieldDecl"; case CXCursor_EnumConstantDecl: return "EnumConstantDecl"; case CXCursor_FunctionDecl: return "FunctionDecl"; case CXCursor_VarDecl: return "VarDecl"; case CXCursor_ParmDecl: return "ParmDecl"; case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl"; case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl"; case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl"; case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl"; case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl"; case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl"; case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl"; case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl"; case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl"; case CXCursor_TypedefDecl: return "TypedefDecl"; case CXCursor_CXXMethod: return "CXXMethod"; case CXCursor_Namespace: return "Namespace"; case CXCursor_LinkageSpec: return "LinkageSpec"; case CXCursor_Constructor: return "Constructor"; case CXCursor_Destructor: return "Destructor"; case CXCursor_ConversionFunction: return "ConversionFunction"; case CXCursor_TemplateTypeParameter: return "TemplateTypeParameter"; case CXCursor_NonTypeTemplateParameter: return "NonTypeTemplateParameter"; case CXCursor_TemplateTemplateParameter: return "TemplateTemplateParameter"; case CXCursor_FunctionTemplate: return "FunctionTemplate"; case CXCursor_ClassTemplate: return "ClassTemplate"; case CXCursor_ClassTemplatePartialSpecialization: return "ClassTemplatePartialSpecialization"; case CXCursor_NamespaceAlias: return "NamespaceAlias"; case CXCursor_UsingDirective: return "UsingDirective"; case CXCursor_UsingDeclaration: return "UsingDeclaration"; case CXCursor_TypeAliasDecl: return "TypeAliasDecl"; case CXCursor_ObjCSynthesizeDecl: return "ObjCSynthesizeDecl"; case CXCursor_ObjCDynamicDecl: return "ObjCDynamicDecl"; case CXCursor_CXXAccessSpecifier: return "CXXAccessSpecifier"; /********* References **********/ case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef"; case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef"; case CXCursor_ObjCClassRef: return "ObjCClassRef"; case CXCursor_TypeRef: return "TypeRef"; case CXCursor_CXXBaseSpecifier: return "CXXBaseSpecifier"; case CXCursor_TemplateRef: return "TemplateRef"; case CXCursor_NamespaceRef: return "NamespaceRef"; case CXCursor_MemberRef: return "MemberRef"; case CXCursor_LabelRef: return "LabelRef"; case CXCursor_OverloadedDeclRef: return "OverloadedDeclRef"; case CXCursor_VariableRef: return "VariableRef"; /********* Errors **********/ case CXCursor_InvalidFile: return ""; case CXCursor_NoDeclFound: return ""; case CXCursor_NotImplemented: return ""; case CXCursor_InvalidCode: return ""; /********* Expressions **********/ case CXCursor_UnexposedExpr: break; case CXCursor_DeclRefExpr: return map_type_kind(type); case CXCursor_MemberRefExpr: return "MemberRefExpr"; case CXCursor_CallExpr: return "CallExpr"; case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr"; case CXCursor_BlockExpr: return "BlockExpr"; case CXCursor_MacroDefinition: return "MacroDefinition"; case CXCursor_MacroInstantiation: return "MacroInstantiation"; case CXCursor_PreprocessingDirective: /* XXX: do not want */ return ""; case CXCursor_InclusionDirective: /* XXX: do not want */ return ""; case CXCursor_CompoundStmt: return ""; case CXCursor_ParenExpr: case CXCursor_LambdaExpr: case CXCursor_CXXForRangeStmt: case CXCursor_DeclStmt: return ""; default: return ""; //return "Error2 " + std::to_string(kind); } return ""; //return "Error3 " + std::to_string(kind); } inline std::string map_literal_kind(CXCursorKind const kind) { switch(kind) { case CXCursor_IntegerLiteral: return "Number"; case CXCursor_FloatingLiteral: return "Float"; case CXCursor_ImaginaryLiteral: return "Number"; case CXCursor_StringLiteral: return ""; /* Allow vim to do this. */ case CXCursor_CharacterLiteral: return "Character"; case CXType_Unexposed: return ""; default: return ""; //return "Error4 " + std::to_string(kind); } } /* Clang token/cursor -> Vim highlight group. */ inline std::string map_token_kind(CXTokenKind const token_kind, CXCursorKind const cursor_kind, CXTypeKind const cursor_type) { switch (token_kind) { case CXToken_Punctuation: return ""; /* Allow vim to do this. */ case CXToken_Keyword: return ""; /* Allow vim to do this. */ case CXToken_Identifier: return map_cursor_kind(cursor_kind, cursor_type); case CXToken_Literal: return map_literal_kind(cursor_kind); case CXToken_Comment: return ""; /* Allow vim to do this. */ default: return ""; //return "Error5 " + std::to_string(token_kind); } } } } } <commit_msg>Preserve compatibility with clang 3.6<commit_after>#pragma once #include <string> #include <stdexcept> #include <clang-c/Index.h> namespace color_coded { namespace clang { namespace token { inline std::string map_type_kind(CXTypeKind const kind) { switch(kind) { case CXType_Unexposed: return "Variable"; case CXType_Void: case CXType_Bool: case CXType_Char_U: case CXType_UChar: case CXType_Char16: case CXType_Char32: case CXType_UShort: case CXType_UInt: case CXType_ULong: case CXType_ULongLong: case CXType_UInt128: case CXType_Char_S: case CXType_SChar: case CXType_WChar: case CXType_Short: case CXType_Int: case CXType_Long: case CXType_LongLong: case CXType_Int128: case CXType_Float: case CXType_Double: case CXType_LongDouble: case CXType_NullPtr: case CXType_Overload: case CXType_Dependent: case CXType_ObjCId: case CXType_ObjCClass: case CXType_ObjCSel: return "Variable"; case CXType_Complex: case CXType_Pointer: case CXType_BlockPointer: case CXType_LValueReference: case CXType_RValueReference: case CXType_Record: case CXType_Typedef: case CXType_ObjCInterface: case CXType_ObjCObjectPointer: case CXType_ConstantArray: case CXType_Vector: case CXType_IncompleteArray: case CXType_VariableArray: case CXType_DependentSizedArray: return "Variable"; case CXType_MemberPointer: return "Member"; case CXType_Enum: return "EnumConstant"; case CXType_FunctionNoProto: case CXType_FunctionProto: return "Function"; #if CINDEX_VERSION_MINOR >= 32 case CXType_Auto: return "Variable"; #endif default: return ""; //return "Error1 " + std::to_string(kind); } } inline std::string map_cursor_kind(CXCursorKind const kind, CXTypeKind const type) { switch(kind) { /********* Declarations **********/ case CXCursor_UnexposedDecl: /* Unknown declaration */ return ""; case CXCursor_StructDecl: return "StructDecl"; case CXCursor_UnionDecl: return "UnionDecl"; case CXCursor_ClassDecl: return "ClassDecl"; case CXCursor_EnumDecl: return "EnumDecl"; case CXCursor_FieldDecl: return "FieldDecl"; case CXCursor_EnumConstantDecl: return "EnumConstantDecl"; case CXCursor_FunctionDecl: return "FunctionDecl"; case CXCursor_VarDecl: return "VarDecl"; case CXCursor_ParmDecl: return "ParmDecl"; case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl"; case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl"; case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl"; case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl"; case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl"; case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl"; case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl"; case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl"; case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl"; case CXCursor_TypedefDecl: return "TypedefDecl"; case CXCursor_CXXMethod: return "CXXMethod"; case CXCursor_Namespace: return "Namespace"; case CXCursor_LinkageSpec: return "LinkageSpec"; case CXCursor_Constructor: return "Constructor"; case CXCursor_Destructor: return "Destructor"; case CXCursor_ConversionFunction: return "ConversionFunction"; case CXCursor_TemplateTypeParameter: return "TemplateTypeParameter"; case CXCursor_NonTypeTemplateParameter: return "NonTypeTemplateParameter"; case CXCursor_TemplateTemplateParameter: return "TemplateTemplateParameter"; case CXCursor_FunctionTemplate: return "FunctionTemplate"; case CXCursor_ClassTemplate: return "ClassTemplate"; case CXCursor_ClassTemplatePartialSpecialization: return "ClassTemplatePartialSpecialization"; case CXCursor_NamespaceAlias: return "NamespaceAlias"; case CXCursor_UsingDirective: return "UsingDirective"; case CXCursor_UsingDeclaration: return "UsingDeclaration"; case CXCursor_TypeAliasDecl: return "TypeAliasDecl"; case CXCursor_ObjCSynthesizeDecl: return "ObjCSynthesizeDecl"; case CXCursor_ObjCDynamicDecl: return "ObjCDynamicDecl"; case CXCursor_CXXAccessSpecifier: return "CXXAccessSpecifier"; /********* References **********/ case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef"; case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef"; case CXCursor_ObjCClassRef: return "ObjCClassRef"; case CXCursor_TypeRef: return "TypeRef"; case CXCursor_CXXBaseSpecifier: return "CXXBaseSpecifier"; case CXCursor_TemplateRef: return "TemplateRef"; case CXCursor_NamespaceRef: return "NamespaceRef"; case CXCursor_MemberRef: return "MemberRef"; case CXCursor_LabelRef: return "LabelRef"; case CXCursor_OverloadedDeclRef: return "OverloadedDeclRef"; case CXCursor_VariableRef: return "VariableRef"; /********* Errors **********/ case CXCursor_InvalidFile: return ""; case CXCursor_NoDeclFound: return ""; case CXCursor_NotImplemented: return ""; case CXCursor_InvalidCode: return ""; /********* Expressions **********/ case CXCursor_UnexposedExpr: break; case CXCursor_DeclRefExpr: return map_type_kind(type); case CXCursor_MemberRefExpr: return "MemberRefExpr"; case CXCursor_CallExpr: return "CallExpr"; case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr"; case CXCursor_BlockExpr: return "BlockExpr"; case CXCursor_MacroDefinition: return "MacroDefinition"; case CXCursor_MacroInstantiation: return "MacroInstantiation"; case CXCursor_PreprocessingDirective: /* XXX: do not want */ return ""; case CXCursor_InclusionDirective: /* XXX: do not want */ return ""; case CXCursor_CompoundStmt: return ""; case CXCursor_ParenExpr: case CXCursor_LambdaExpr: case CXCursor_CXXForRangeStmt: case CXCursor_DeclStmt: return ""; default: return ""; //return "Error2 " + std::to_string(kind); } return ""; //return "Error3 " + std::to_string(kind); } inline std::string map_literal_kind(CXCursorKind const kind) { switch(kind) { case CXCursor_IntegerLiteral: return "Number"; case CXCursor_FloatingLiteral: return "Float"; case CXCursor_ImaginaryLiteral: return "Number"; case CXCursor_StringLiteral: return ""; /* Allow vim to do this. */ case CXCursor_CharacterLiteral: return "Character"; case CXType_Unexposed: return ""; default: return ""; //return "Error4 " + std::to_string(kind); } } /* Clang token/cursor -> Vim highlight group. */ inline std::string map_token_kind(CXTokenKind const token_kind, CXCursorKind const cursor_kind, CXTypeKind const cursor_type) { switch (token_kind) { case CXToken_Punctuation: return ""; /* Allow vim to do this. */ case CXToken_Keyword: return ""; /* Allow vim to do this. */ case CXToken_Identifier: return map_cursor_kind(cursor_kind, cursor_type); case CXToken_Literal: return map_literal_kind(cursor_kind); case CXToken_Comment: return ""; /* Allow vim to do this. */ default: return ""; //return "Error5 " + std::to_string(token_kind); } } } } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 <memory> #include "SurgSim/Blocks/BasicSceneElement.h" #include "SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h" #include "SurgSim/Framework/BehaviorManager.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/SceneElement.h" #include "SurgSim/Graphics/OsgCamera.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgPointCloudRepresentation.h" #include "SurgSim/Graphics/OsgView.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/PointCloudRepresentation.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Physics/Fem1DRepresentation.h" #include "SurgSim/Physics/FemElement1DBeam.h" #include "SurgSim/Physics/PhysicsManager.h" using SurgSim::Blocks::BasicSceneElement; using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior; using SurgSim::Framework::SceneElement; using SurgSim::Graphics::OsgPointCloudRepresentation; using SurgSim::Math::Vector3d; using SurgSim::Physics::DeformableRepresentationState; using SurgSim::Physics::Fem1DRepresentation; using SurgSim::Physics::FemElement1DBeam; using SurgSim::Physics::PhysicsManager; ///\file Example of how to put together a very simple demo of Fem1D namespace { void loadModelFem1D(std::shared_ptr<Fem1DRepresentation> physicsRepresentation, unsigned int numNodes) { std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>(); restState->setNumDof(physicsRepresentation->getNumDofPerNode(), numNodes); // Sets the initial state (node positions and boundary conditions) SurgSim::Math::Vector& x = restState->getPositions(); for (unsigned int nodeId = 0; nodeId < numNodes; nodeId++) { SurgSim::Math::getSubVector(x, nodeId, physicsRepresentation->getNumDofPerNode()).segment<3>(0) = Vector3d(static_cast<double>(nodeId) / static_cast<double>(numNodes), 0.0, 0.0); } // Fix the start and end nodes restState->addBoundaryCondition(0 + 0); restState->addBoundaryCondition(0 + 1); restState->addBoundaryCondition(0 + 2); restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 0); restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 1); restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 2); physicsRepresentation->setInitialState(restState); // Adds all the FemElements for (unsigned int beamId = 0; beamId < numNodes - 1; beamId++) { std::array<unsigned int, 2> beamNodeIds = {{beamId, beamId + 1}}; std::shared_ptr<FemElement1DBeam> beam = std::make_shared<FemElement1DBeam>(beamNodeIds); beam->setRadius(0.10); beam->setMassDensity(3000.0); beam->setPoissonRatio(0.45); beam->setYoungModulus(1e6); physicsRepresentation->addFemElement(beam); } } std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height) { using SurgSim::Graphics::OsgViewElement; std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name); viewElement->getView()->setPosition(x, y); viewElement->getView()->setDimensions(width, height); return viewElement; } // Generates a 1d fem comprised of adjacent elements along a straight line. The number of fem elements is determined // by loadModelFem1D. std::shared_ptr<SceneElement> createFem1D(const std::string& name, const SurgSim::Math::RigidTransform3d& gfxPose, const SurgSim::Math::Vector4d& color, SurgSim::Math::IntegrationScheme integrationScheme) { std::shared_ptr<Fem1DRepresentation> physicsRepresentation = std::make_shared<Fem1DRepresentation>("Physics Representation: " + name); // In this example, the physics representations are not transformed, only the graphics will be transformed loadModelFem1D(physicsRepresentation, 10); physicsRepresentation->setIntegrationScheme(integrationScheme); physicsRepresentation->setRayleighDampingMass(5e-2); physicsRepresentation->setRayleighDampingStiffness(5e-3); std::shared_ptr<BasicSceneElement> femSceneElement = std::make_shared<BasicSceneElement>(name); femSceneElement->addComponent(physicsRepresentation); std::shared_ptr<SurgSim::Graphics::PointCloudRepresentation<void>> graphicsRepresentation = std::make_shared<OsgPointCloudRepresentation<void>>("Graphics Representation: " + name); graphicsRepresentation->setInitialPose(gfxPose); graphicsRepresentation->setColor(color); graphicsRepresentation->setPointSize(3.0f); graphicsRepresentation->setVisible(true); femSceneElement->addComponent(graphicsRepresentation); femSceneElement->addComponent( std::make_shared<TransferDeformableStateToVerticesBehavior<void>>("Transfer from Physics to Graphics: " + name, physicsRepresentation->getFinalState(), graphicsRepresentation->getVertices())); return femSceneElement; } } // anonymous namespace int main(int argc, char* argv[]) { using SurgSim::Math::makeRigidTransform; using SurgSim::Math::Vector4d; std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>(); std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager = std::make_shared<SurgSim::Framework::BehaviorManager>(); std::shared_ptr<SurgSim::Framework::Runtime> runtime = std::make_shared<SurgSim::Framework::Runtime>(); runtime->addManager(physicsManager); runtime->addManager(graphicsManager); runtime->addManager(behaviorManager); std::shared_ptr<SurgSim::Graphics::OsgCamera> camera = graphicsManager->getDefaultCamera(); std::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene(); const SurgSim::Math::Quaterniond quaternionIdentity = SurgSim::Math::Quaterniond::Identity(); scene->addSceneElement( createFem1D("Euler Explicit", // name makeRigidTransform(quaternionIdentity, Vector3d(-3.5, 0.5, -3.0)), // graphics pose (rot., trans.) Vector4d(1, 0, 0, 1), // color (r, g, b, a) SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)); // technique to update object scene->addSceneElement( createFem1D("Modified Euler Explicit", makeRigidTransform(quaternionIdentity, Vector3d(-0.5, 0.5, -3.0)), Vector4d(0, 1, 0, 1), SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER)); scene->addSceneElement( createFem1D("Euler Implicit", makeRigidTransform(quaternionIdentity, Vector3d(2.5, 0.5, -3.0)), Vector4d(0, 0, 1, 1), SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER)); scene->addSceneElement(createView("view1", 0, 0, 1023, 768)); camera->setInitialPose(SurgSim::Math::makeRigidTransform(quaternionIdentity, Vector3d(0.0, 0.5, 5.0))); runtime->execute(); return 0; } <commit_msg>Minor fix fem1d example, reduce visual spacing<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 <memory> #include "SurgSim/Blocks/BasicSceneElement.h" #include "SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h" #include "SurgSim/Framework/BehaviorManager.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/SceneElement.h" #include "SurgSim/Graphics/OsgCamera.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgPointCloudRepresentation.h" #include "SurgSim/Graphics/OsgView.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/PointCloudRepresentation.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Physics/Fem1DRepresentation.h" #include "SurgSim/Physics/FemElement1DBeam.h" #include "SurgSim/Physics/PhysicsManager.h" using SurgSim::Blocks::BasicSceneElement; using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior; using SurgSim::Framework::SceneElement; using SurgSim::Graphics::OsgPointCloudRepresentation; using SurgSim::Math::Vector3d; using SurgSim::Physics::DeformableRepresentationState; using SurgSim::Physics::Fem1DRepresentation; using SurgSim::Physics::FemElement1DBeam; using SurgSim::Physics::PhysicsManager; ///\file Example of how to put together a very simple demo of Fem1D namespace { void loadModelFem1D(std::shared_ptr<Fem1DRepresentation> physicsRepresentation, unsigned int numNodes) { std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>(); restState->setNumDof(physicsRepresentation->getNumDofPerNode(), numNodes); // Sets the initial state (node positions and boundary conditions) SurgSim::Math::Vector& x = restState->getPositions(); for (unsigned int nodeId = 0; nodeId < numNodes; nodeId++) { SurgSim::Math::getSubVector(x, nodeId, physicsRepresentation->getNumDofPerNode()).segment<3>(0) = Vector3d(static_cast<double>(nodeId) / static_cast<double>(numNodes), 0.0, 0.0); } // Fix the start and end nodes restState->addBoundaryCondition(0 + 0); restState->addBoundaryCondition(0 + 1); restState->addBoundaryCondition(0 + 2); restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 0); restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 1); restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 2); physicsRepresentation->setInitialState(restState); // Adds all the FemElements for (unsigned int beamId = 0; beamId < numNodes - 1; beamId++) { std::array<unsigned int, 2> beamNodeIds = {{beamId, beamId + 1}}; std::shared_ptr<FemElement1DBeam> beam = std::make_shared<FemElement1DBeam>(beamNodeIds); beam->setRadius(0.10); beam->setMassDensity(3000.0); beam->setPoissonRatio(0.45); beam->setYoungModulus(1e6); physicsRepresentation->addFemElement(beam); } } std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height) { using SurgSim::Graphics::OsgViewElement; std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name); viewElement->getView()->setPosition(x, y); viewElement->getView()->setDimensions(width, height); return viewElement; } // Generates a 1d fem comprised of adjacent elements along a straight line. The number of fem elements is determined // by loadModelFem1D. std::shared_ptr<SceneElement> createFem1D(const std::string& name, const SurgSim::Math::RigidTransform3d& gfxPose, const SurgSim::Math::Vector4d& color, SurgSim::Math::IntegrationScheme integrationScheme) { std::shared_ptr<Fem1DRepresentation> physicsRepresentation = std::make_shared<Fem1DRepresentation>("Physics Representation: " + name); // In this example, the physics representations are not transformed, only the graphics will be transformed loadModelFem1D(physicsRepresentation, 10); physicsRepresentation->setIntegrationScheme(integrationScheme); physicsRepresentation->setRayleighDampingMass(5e-2); physicsRepresentation->setRayleighDampingStiffness(5e-3); std::shared_ptr<BasicSceneElement> femSceneElement = std::make_shared<BasicSceneElement>(name); femSceneElement->addComponent(physicsRepresentation); std::shared_ptr<SurgSim::Graphics::PointCloudRepresentation<void>> graphicsRepresentation = std::make_shared<OsgPointCloudRepresentation<void>>("Graphics Representation: " + name); graphicsRepresentation->setInitialPose(gfxPose); graphicsRepresentation->setColor(color); graphicsRepresentation->setPointSize(3.0f); graphicsRepresentation->setVisible(true); femSceneElement->addComponent(graphicsRepresentation); femSceneElement->addComponent( std::make_shared<TransferDeformableStateToVerticesBehavior<void>>("Transfer from Physics to Graphics: " + name, physicsRepresentation->getFinalState(), graphicsRepresentation->getVertices())); return femSceneElement; } } // anonymous namespace int main(int argc, char* argv[]) { using SurgSim::Math::makeRigidTransform; using SurgSim::Math::Vector4d; std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>(); std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager = std::make_shared<SurgSim::Framework::BehaviorManager>(); std::shared_ptr<SurgSim::Framework::Runtime> runtime = std::make_shared<SurgSim::Framework::Runtime>(); runtime->addManager(physicsManager); runtime->addManager(graphicsManager); runtime->addManager(behaviorManager); std::shared_ptr<SurgSim::Graphics::OsgCamera> camera = graphicsManager->getDefaultCamera(); std::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene(); const SurgSim::Math::Quaterniond quaternionIdentity = SurgSim::Math::Quaterniond::Identity(); scene->addSceneElement( createFem1D("Euler Explicit", // name makeRigidTransform(quaternionIdentity, Vector3d(-3.0, 0.5, -3.0)), // graphics pose (rot., trans.) Vector4d(1, 0, 0, 1), // color (r, g, b, a) SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)); // technique to update object scene->addSceneElement( createFem1D("Modified Euler Explicit", makeRigidTransform(quaternionIdentity, Vector3d(-0.5, 0.5, -3.0)), Vector4d(0, 1, 0, 1), SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER)); scene->addSceneElement( createFem1D("Euler Implicit", makeRigidTransform(quaternionIdentity, Vector3d(2.0, 0.5, -3.0)), Vector4d(0, 0, 1, 1), SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER)); scene->addSceneElement(createView("view1", 0, 0, 1023, 768)); camera->setInitialPose(SurgSim::Math::makeRigidTransform(quaternionIdentity, Vector3d(0.0, 0.5, 5.0))); runtime->execute(); return 0; } <|endoftext|>
<commit_before>// Halide tutorial lesson 16: RGB images and memory layouts part 1 // This lesson demonstrates how to feed Halide RGB images in // interleaved or planar format, and how to write code optimized for // each case. // On linux or os x, you can compile and run it like so: // g++ lesson_16_rgb_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_16_generate // export LD_LIBRARY_PATH=../bin # For linux // export DYLD_LIBRARY_PATH=../bin # For OS X // ./lesson_16_generate -o . -f brighten_planar target=host layout=planar // ./lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved // ./lesson_16_generate -o . -f brighten_either target=host layout=either // ./lesson_16_generate -o . -f brighten_specialized target=host layout=specialized // g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run // ./lesson_16_run // If you have the entire Halide source tree, you can also build it by // running: // make tutorial_lesson_16_rgb_run // in a shell with the current directory at the top of the halide // source tree. #include "Halide.h" #include <stdio.h> using namespace Halide; // We will define a generator that brightens an RGB image. class Brighten : public Halide::Generator<Brighten> { public: // We declare a three-dimensional input image. The first two // dimensions will be x, and y, and the third dimension will be // the color channel. ImageParam input{UInt(8), 3, "input"}; // We will compile this generator in several ways to accept // several different memory layouts for the input and output. This // is a good use of a GeneratorParam (see lesson 15). enum class Layout { Planar, Interleaved, Either, Specialized }; GeneratorParam<Layout> layout{"layout", // default value Layout::Planar, // map from names to values {{ "planar", Layout::Planar }, { "interleaved", Layout::Interleaved }, { "either", Layout::Either }, { "specialized", Layout::Specialized }}}; // We also declare a scalar parameter to control the amount of // brightening. Param<uint8_t> offset{"offset"}; // Declare our Vars Var x, y, c; Func build() { // Define the Func. Func brighter("brighter"); brighter(x, y, c) = input(x, y, c) + offset; // Schedule it. brighter.vectorize(x, 16); // We will compile this pipeline to handle memory layouts in // several different ways, depending on the 'layout' generator // param. if (layout == Layout::Planar) { // This pipeline as written will only work with images in // which each scanline is densely-packed single color // channel. In terms of the strides described in lesson // 10, Halide assumes and asserts that the stride in x is // one. // This constraint permits planar images, where the red, // green, and blue channels are laid out in memory like // this: // RRRRRRRR // RRRRRRRR // RRRRRRRR // RRRRRRRR // GGGGGGGG // GGGGGGGG // GGGGGGGG // GGGGGGGG // BBBBBBBB // BBBBBBBB // BBBBBBBB // BBBBBBBB // It also works with the less-commonly used line-by-line // layout, in which scanlines of red, green, and blue // alternate. // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB } else if (layout == Layout::Interleaved) { // Another common format is 'interleaved', in which the // red, green, and blue values for each pixel occur next // to each other in memory: // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // In this case the stride in x is three, the stride in y // is three times the width of the image, and the stride // in c is one. We can tell Halide to assume (and assert) // that this is the case for the input and output like so: input .set_stride(0, 3) // stride in dimension 0 (x) is three .set_stride(2, 1); // stride in dimension 2 (c) is one brighter.output_buffer() .set_stride(0, 3) .set_stride(2, 1); // For interleaved layout, you may want to use a different // schedule. We'll tell Halide to additionally assume and // assert that there are three color channels, then // exploit this fact to make the loop over 'c' innermost // and unrolled. input.set_bounds(2, 0, 3); // Dimension 2 (c) starts at 0 and has extent 3. brighter.output_buffer().set_bounds(2, 0, 3); // Move the loop over color channels innermost and unroll // it. brighter.reorder(c, x, y).unroll(c); // Note that if we were dealing with an image with an // alpha channel (RGBA), then the stride in x and the // bounds of the channels dimension would both be four // instead of three. } else if (layout == Layout::Either) { // We can also remove all constraints and compile a // pipeline that will work with any memory layout. It will // probably be slow, because all vector loads become // gathers, and all vector stores become scatters. input.set_stride(0, Expr()); // Use a default-constructed // undefined Expr to mean // there is no constraint. brighter.output_buffer().set_stride(0, Expr()); } else if (layout == Layout::Specialized) { // We can accept any memory layout with good performance // by telling Halide to inspect the memory layout at // runtime, and branch to different code depending on the // strides it find. First we relax the default constraint // that stride(0) == 1: input.set_stride(0, Expr()); // Use an undefined Expr to // mean there is no // constraint. brighter.output_buffer().set_stride(0, Expr()); // The we construct boolean Exprs that detect at runtime // whether we're planar or interleaved. The conditions // should check for all the facts we want to exploit in // each case. Expr input_is_planar = (input.stride(0) == 1); Expr input_is_interleaved = (input.stride(0) == 3 && input.stride(2) == 1 && input.extent(2) == 3); Expr output_is_planar = (brighter.output_buffer().stride(0) == 1); Expr output_is_interleaved = (brighter.output_buffer().stride(0) == 3 && brighter.output_buffer().stride(2) == 1 && brighter.output_buffer().extent(2) == 3); // We can then use Func::specialize to write a schedule // that switches at runtime to specialized code based on a // boolean Expr. That code will exploit the fact that the // Expr is known to be true. brighter.specialize(input_is_planar && output_is_planar); // We've already vectorized and parallelized brighter, and // our two specializations will inherit those scheduling // directives. We can also add additional scheduling // directives that apply to a single specialization // only. We'll tell Halide to make a specialized version // of the code for interleaved layouts, and to reorder and // unroll that specialized code. brighter.specialize(input_is_interleaved && output_is_interleaved) .reorder(c, x, y).unroll(c); // We could also add specializations for if the input is // interleaved and the output is planar, and vice versa, // but two specializations is enough to demonstrate the // feature. A later tutorial will explore more creative // uses of Func::specialize. // Adding specializations can improve performance // substantially for the cases they apply to, but it also // increases the amount of code to compile and ship. If // binary sizes are a concern and the input and output // memory layouts are known, you probably want to use // set_stride and set_extent instead. } return brighter; } }; // As in lesson 15, we register our generator and then compile this // file along with tools/GenGen.cpp. RegisterGenerator<Brighten> my_first_generator{"brighten"}; // After compiling this file, see how to use it in // lesson_16_rgb_run.cpp <commit_msg>Fix tutorial convention<commit_after>// Halide tutorial lesson 16: RGB images and memory layouts part 1 // This lesson demonstrates how to feed Halide RGB images in // interleaved or planar format, and how to write code optimized for // each case. // On linux or os x, you can compile and run it like so: // g++ lesson_16_rgb_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_16_generate // export LD_LIBRARY_PATH=../bin # For linux // export DYLD_LIBRARY_PATH=../bin # For OS X // ./lesson_16_generate -o . -f brighten_planar target=host layout=planar // ./lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved // ./lesson_16_generate -o . -f brighten_either target=host layout=either // ./lesson_16_generate -o . -f brighten_specialized target=host layout=specialized // g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run // ./lesson_16_run // If you have the entire Halide source tree, you can also build it by // running: // make tutorial_lesson_16_rgb_run // in a shell with the current directory at the top of the halide // source tree. #include "Halide.h" #include <stdio.h> using namespace Halide; // We will define a generator that brightens an RGB image. class Brighten : public Halide::Generator<Brighten> { public: // We declare a three-dimensional input image. The first two // dimensions will be x, and y, and the third dimension will be // the color channel. ImageParam input{UInt(8), 3, "input"}; // We will compile this generator in several ways to accept // several different memory layouts for the input and output. This // is a good use of a GeneratorParam (see lesson 15). enum class Layout { Planar, Interleaved, Either, Specialized }; GeneratorParam<Layout> layout{"layout", // default value Layout::Planar, // map from names to values {{ "planar", Layout::Planar }, { "interleaved", Layout::Interleaved }, { "either", Layout::Either }, { "specialized", Layout::Specialized }}}; // We also declare a scalar parameter to control the amount of // brightening. Param<uint8_t> offset{"offset"}; // Declare our Vars Var x, y, c; Func build() { // Define the Func. Func brighter("brighter"); brighter(x, y, c) = input(x, y, c) + offset; // Schedule it. brighter.vectorize(x, 16); // We will compile this pipeline to handle memory layouts in // several different ways, depending on the 'layout' generator // param. if (layout == Layout::Planar) { // This pipeline as written will only work with images in // which each scanline is densely-packed single color // channel. In terms of the strides described in lesson // 10, Halide assumes and asserts that the stride in x is // one. // This constraint permits planar images, where the red, // green, and blue channels are laid out in memory like // this: // RRRRRRRR // RRRRRRRR // RRRRRRRR // RRRRRRRR // GGGGGGGG // GGGGGGGG // GGGGGGGG // GGGGGGGG // BBBBBBBB // BBBBBBBB // BBBBBBBB // BBBBBBBB // It also works with the less-commonly used line-by-line // layout, in which scanlines of red, green, and blue // alternate. // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB } else if (layout == Layout::Interleaved) { // Another common format is 'interleaved', in which the // red, green, and blue values for each pixel occur next // to each other in memory: // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // In this case the stride in x is three, the stride in y // is three times the width of the image, and the stride // in c is one. We can tell Halide to assume (and assert) // that this is the case for the input and output like so: input .dim(0).set_stride(3) // stride in dimension 0 (x) is three .dim(2).set_stride(1); // stride in dimension 2 (c) is one brighter.output_buffer() .dim(0).set_stride(3) .dim(2).set_stride(1); // For interleaved layout, you may want to use a different // schedule. We'll tell Halide to additionally assume and // assert that there are three color channels, then // exploit this fact to make the loop over 'c' innermost // and unrolled. input.dim(2).set_bounds(0, 3); // Dimension 2 (c) starts at 0 and has extent 3. brighter.output_buffer().dim(2).set_bounds(0, 3); // Move the loop over color channels innermost and unroll // it. brighter.reorder(c, x, y).unroll(c); // Note that if we were dealing with an image with an // alpha channel (RGBA), then the stride in x and the // bounds of the channels dimension would both be four // instead of three. } else if (layout == Layout::Either) { // We can also remove all constraints and compile a // pipeline that will work with any memory layout. It will // probably be slow, because all vector loads become // gathers, and all vector stores become scatters. input.dim(0).set_stride(Expr()); // Use a default-constructed // undefined Expr to mean // there is no constraint. brighter.output_buffer().dim(0).set_stride(Expr()); } else if (layout == Layout::Specialized) { // We can accept any memory layout with good performance // by telling Halide to inspect the memory layout at // runtime, and branch to different code depending on the // strides it find. First we relax the default constraint // that dim(0).stride() == 1: input.dim(0).set_stride(Expr()); // Use an undefined Expr to // mean there is no // constraint. brighter.output_buffer().dim(0).set_stride(Expr()); // The we construct boolean Exprs that detect at runtime // whether we're planar or interleaved. The conditions // should check for all the facts we want to exploit in // each case. Expr input_is_planar = (input.dim(0).stride() == 1); Expr input_is_interleaved = (input.dim(0).stride() == 3 && input.dim(2).stride() == 1 && input.dim(2).extent() == 3); Expr output_is_planar = (brighter.output_buffer().dim(0).stride() == 1); Expr output_is_interleaved = (brighter.output_buffer().dim(0).stride() == 3 && brighter.output_buffer().dim(2).stride() == 1 && brighter.output_buffer().dim(2).extent() == 3); // We can then use Func::specialize to write a schedule // that switches at runtime to specialized code based on a // boolean Expr. That code will exploit the fact that the // Expr is known to be true. brighter.specialize(input_is_planar && output_is_planar); // We've already vectorized and parallelized brighter, and // our two specializations will inherit those scheduling // directives. We can also add additional scheduling // directives that apply to a single specialization // only. We'll tell Halide to make a specialized version // of the code for interleaved layouts, and to reorder and // unroll that specialized code. brighter.specialize(input_is_interleaved && output_is_interleaved) .reorder(c, x, y).unroll(c); // We could also add specializations for if the input is // interleaved and the output is planar, and vice versa, // but two specializations is enough to demonstrate the // feature. A later tutorial will explore more creative // uses of Func::specialize. // Adding specializations can improve performance // substantially for the cases they apply to, but it also // increases the amount of code to compile and ship. If // binary sizes are a concern and the input and output // memory layouts are known, you probably want to use // set_stride and set_extent instead. } return brighter; } }; // As in lesson 15, we register our generator and then compile this // file along with tools/GenGen.cpp. RegisterGenerator<Brighten> my_first_generator{"brighten"}; // After compiling this file, see how to use it in // lesson_16_rgb_run.cpp <|endoftext|>
<commit_before>// @(#)root/net:$Name: $:$Id: TGrid.cxx,v 1.8 2005/05/13 08:49:54 rdm Exp $ // Author: Fons Rademakers 3/1/2002 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGrid // // // // Abstract base class defining interface to common GRID services. // // // // To open a connection to a GRID use the static method Connect(). // // The argument of Connect() is of the form: // // <grid>[://<host>][:<port>], e.g. // // alien, alien://alice.cern.ch, globus://glsvr1.cern.ch, ... // // Depending on the <grid> specified an appropriate plugin library // // will be loaded which will provide the real interface. // // // // Related classes are TGridResult. // // // ////////////////////////////////////////////////////////////////////////// #include "TGrid.h" #include "TUrl.h" #include "TROOT.h" #include "TPluginManager.h" #include "TFile.h" #include "TList.h" #include "TError.h" #include "TUUID.h" #include "TSystem.h" #include "TH1.h" #include "TChain.h" #include "TKey.h" TGrid *gGrid = 0; ClassImp(TGrid) //______________________________________________________________________________ TGrid::TGrid() : fPort(-1), fMergerOutputFile(0) { // Create grid interface object. fMergerFileList = new TList; fMergerFileList->SetOwner(kTRUE); } //______________________________________________________________________________ TGrid *TGrid::Connect(const char *grid, const char *uid, const char *pw, const char *options) { // The grid should be of the form: <grid>://<host>[:<port>], // e.g.: alien://alice.cern.ch, globus://glsrv1.cern.ch, ... // The uid is the username and pw the password that should be used for // the connection. Depending on the <grid> the shared library (plugin) // for the selected system will be loaded. When the connection could not // be opened 0 is returned. For AliEn the supported options are: // -domain=<domain name> // -debug=<debug level from 1 to 10> // Example: "-domain=cern.ch -debug=5" TPluginHandler *h; TGrid *g = 0; if (!grid) { ::Error("TGrid::Connect", "no grid specified"); return 0; } if (!uid) uid = ""; if (!pw) pw = ""; if (!options) options = ""; if ((h = gROOT->GetPluginManager()->FindHandler("TGrid", grid))) { if (h->LoadPlugin() == -1) return 0; g = (TGrid *) h->ExecPlugin(4, grid, uid, pw, options); } return g; } //______________________________________________________________________________ TGrid::~TGrid() { // Cleanup. if (fMergerFileList) delete fMergerFileList; if (fMergerOutputFile) delete fMergerOutputFile; } //______________________________________________________________________________ void TGrid::PrintProgress(Long64_t bytesread, Long64_t size) { // Print file copy progress. fprintf(stderr, "[TGrid::Cp] Total %.02f MB\t|", (Double_t)size/1048576); for (int l = 0; l < 20; l++) { if (l < 20*bytesread/size) fprintf(stderr, "="); if (l == 20*bytesread/size) fprintf(stderr, ">"); if (l > 20*bytesread/size) fprintf(stderr, "."); } fWatch.Stop(); Double_t lCopy_time = fWatch.RealTime(); fprintf(stderr, "| %.02f %% [%.01f MB/s]\r", 100.0*bytesread/size, bytesread/lCopy_time/1048576.); fWatch.Continue(); } //______________________________________________________________________________ Bool_t TGrid::Cp(const char *src, const char *dst, Bool_t progressbar, UInt_t buffersize) { // Allows to copy file from src to dst URL. Bool_t success = kFALSE; TUrl sURL(src, kTRUE); TUrl dURL(dst, kTRUE); char *copybuffer = 0; TFile *sfile = 0; TFile *dfile = 0; sfile = TFile::Open(src, "-READ"); if (!sfile) { Error("Cp", "cannot open source file %s", src); goto copyout; } dfile = TFile::Open(dst, "-RECREATE"); if (!dfile) { Error("Cp", "cannot open destination file %s", dst); goto copyout; } sfile->Seek(0); dfile->Seek(0); copybuffer = new char[buffersize]; if (!copybuffer) { Error("Cp", "cannot allocate the copy buffer"); goto copyout; } Bool_t readop; Bool_t writeop; Long64_t read; Long64_t written; Long64_t totalread; Long64_t filesize; filesize = sfile->GetSize(); totalread = 0; fWatch.Start(); Long64_t b00 = sfile->GetBytesRead(); do { if (progressbar) PrintProgress(totalread, filesize); Long64_t b1 = sfile->GetBytesRead() - b00; Long64_t readsize; if (filesize - b1 > (Long64_t)buffersize) { readsize = buffersize; } else { readsize = filesize - b1; } Long64_t b0 = sfile->GetBytesRead(); readop = sfile->ReadBuffer(copybuffer, readsize); read = sfile->GetBytesRead() - b0; if (read < 0) { Error("Cp", "cannot read from source file %s", src); goto copyout; } Long64_t w0 = dfile->GetBytesWritten(); writeop = dfile->WriteBuffer(copybuffer, read); written = dfile->GetBytesWritten() - w0; if (written != read) { Error("Cp", "cannot write %d bytes to destination file %s", read, dst); goto copyout; } totalread += read; } while (read == (Long64_t)buffersize); if (progressbar) { PrintProgress(totalread, filesize); fprintf(stderr, "\n"); } success = kTRUE; copyout: if (sfile) sfile->Close(); if (dfile) dfile->Close(); if (sfile) delete sfile; if (dfile) delete dfile; if (copybuffer) delete copybuffer; fWatch.Stop(); fWatch.Reset(); return success; } //______________________________________________________________________________ void TGrid::MergerReset() { // Reset merger file list. fMergerFileList->Clear(); } //______________________________________________________________________________ Bool_t TGrid::MergerAddFile(const char *url) { // Add file to file merger. TUUID uuid; TString localcopy = "file:/tmp/"; localcopy += "ROOTMERGE-"; localcopy += uuid.AsString(); localcopy += ".root"; if (!Cp(url, localcopy)) { Error("MergerAddFile", "cannot get a local copy of file %s", url); return kFALSE; } TFile *newfile = TFile::Open(localcopy, "READ"); if (!newfile) { Error("MergerAddFile", "cannot open local copy %s of URL %s", localcopy.Data(), url); return kFALSE; } else { fMergerFileList->Add(newfile); return kTRUE; } } //______________________________________________________________________________ Bool_t TGrid::MergerOutputFile(const char *outputfile) { // Open merger output file. if (fMergerOutputFile) delete fMergerOutputFile; fMergerOutputFilename = outputfile; TUUID uuid; TString localcopy = "file:/tmp/"; localcopy += "ROOTMERGED-"; localcopy += uuid.AsString(); localcopy += ".root"; fMergerOutputFile = TFile::Open(localcopy, "RECREATE"); fMergerOutputFilename1 = localcopy; if (!fMergerOutputFile) { Error("MergerOutputFile", "cannot open the MERGER outputfile %s", localcopy.Data()); return kFALSE; } return kTRUE; } //______________________________________________________________________________ void TGrid::MergerPrintFiles(Option_t *options) { // Print list of files being merged. fMergerFileList->Print(options); } //______________________________________________________________________________ Bool_t TGrid::MergerMerge() { // Merge the files. if (!fMergerOutputFile) { Info("MergerMerge", "will merge the results to the file " "GridMergerMerged.root in your working directory, " "since you didn't specify a merge filename"); if (!MergerOutputFile("GridMergerMerged.root")) { return kFALSE; } } Bool_t result = MergerMergeRecursive(fMergerOutputFile, fMergerFileList); if (!result) { Error("MergerMerge", "error during merge of your ROOT files"); } else { fMergerOutputFile->Write(); // copy the result file to the final destination Cp(fMergerOutputFilename1, fMergerOutputFilename); } // remove the temporary result file TString path(fMergerOutputFile->GetPath()); path = path(0, path.Index(':',0)); gSystem->Unlink(path); fMergerOutputFile = 0; TIter next(fMergerFileList); TFile *file; while ((file = (TFile*) next())) { // close the files file->Close(); // remove the temporary files TString path(file->GetPath()); path = path(0, path.Index(':',0)); gSystem->Unlink(path); } return result; } //______________________________________________________________________________ Bool_t TGrid::MergerMergeRecursive(TDirectory *target, TList *sourcelist) { // Recursively merge objects in the ROOT files. TString path(strstr(target->GetPath(), ":")); path.Remove(0, 2); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd(path); TDirectory *current_sourcedir = gDirectory; TChain *globChain = 0; TIter nextkey(current_sourcedir->GetListOfKeys()); TKey *key; Bool_t success = kTRUE; // gain time, do not add the objects in the list in memory TH1::AddDirectory(kFALSE); while ((key = (TKey*) nextkey())) { first_source->cd(path); TObject *obj = key->ReadObj(); if (obj->IsA()->InheritsFrom("TH1")) { Info("MergerMergeRecursive", "merging histogram %s", obj->GetName()); TH1 *h1 = (TH1*)obj; TFile *nextsource = (TFile*)sourcelist->After(first_source); while (nextsource) { nextsource->cd(path); TH1 *h2 = (TH1*)gDirectory->Get(h1->GetName()); if (h2) { h1->Add(h2); delete h2; } nextsource = (TFile*)sourcelist->After(nextsource); } } else if (obj->IsA()->InheritsFrom("TTree")) { Info("MergerMergeRecursive", "merging tree %s", obj->GetName()); const char *obj_name= obj->GetName(); globChain = new TChain(obj_name); globChain->Add(first_source->GetName()); TFile *nextsource = (TFile*)sourcelist->After(first_source); while (nextsource) { globChain->Add(nextsource->GetName()); nextsource = (TFile*)sourcelist->After(nextsource); } } else if (obj->IsA()->InheritsFrom("TDirectory")) { target->cd(); TDirectory *newdir = target->mkdir(obj->GetName(), obj->GetTitle()); if (!MergerMergeRecursive(newdir, sourcelist)) { Error("MergerMergeRecursive", "error during merge of directory %s", newdir->GetPath()); success = kFALSE; } } else { Error("MergerMergeRecursive", "unknown object type, name: %s title: %s", obj->GetName(), obj->GetTitle()); success = kFALSE; } if (obj) { target->cd(); if (obj->IsA()->InheritsFrom("TTree")) { globChain->Merge(target->GetFile() ,0, "keep"); delete globChain; } else obj->Write(key->GetName()); } } // nextkey target->Write(); TH1::AddDirectory(kTRUE); return success; } <commit_msg>Fix compile problem on MacOS X.<commit_after>// @(#)root/net:$Name: $:$Id: TGrid.cxx,v 1.9 2005/05/20 09:59:35 rdm Exp $ // Author: Fons Rademakers 3/1/2002 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGrid // // // // Abstract base class defining interface to common GRID services. // // // // To open a connection to a GRID use the static method Connect(). // // The argument of Connect() is of the form: // // <grid>[://<host>][:<port>], e.g. // // alien, alien://alice.cern.ch, globus://glsvr1.cern.ch, ... // // Depending on the <grid> specified an appropriate plugin library // // will be loaded which will provide the real interface. // // // // Related classes are TGridResult. // // // ////////////////////////////////////////////////////////////////////////// #include "TGrid.h" #include "TUrl.h" #include "TROOT.h" #include "TPluginManager.h" #include "TFile.h" #include "TList.h" #include "TError.h" #include "TUUID.h" #include "TSystem.h" #include "TH1.h" #include "TChain.h" #include "TKey.h" TGrid *gGrid = 0; ClassImp(TGrid) //______________________________________________________________________________ TGrid::TGrid() : fPort(-1), fMergerOutputFile(0) { // Create grid interface object. fMergerFileList = new TList; fMergerFileList->SetOwner(kTRUE); } //______________________________________________________________________________ TGrid *TGrid::Connect(const char *grid, const char *uid, const char *pw, const char *options) { // The grid should be of the form: <grid>://<host>[:<port>], // e.g.: alien://alice.cern.ch, globus://glsrv1.cern.ch, ... // The uid is the username and pw the password that should be used for // the connection. Depending on the <grid> the shared library (plugin) // for the selected system will be loaded. When the connection could not // be opened 0 is returned. For AliEn the supported options are: // -domain=<domain name> // -debug=<debug level from 1 to 10> // Example: "-domain=cern.ch -debug=5" TPluginHandler *h; TGrid *g = 0; if (!grid) { ::Error("TGrid::Connect", "no grid specified"); return 0; } if (!uid) uid = ""; if (!pw) pw = ""; if (!options) options = ""; if ((h = gROOT->GetPluginManager()->FindHandler("TGrid", grid))) { if (h->LoadPlugin() == -1) return 0; g = (TGrid *) h->ExecPlugin(4, grid, uid, pw, options); } return g; } //______________________________________________________________________________ TGrid::~TGrid() { // Cleanup. if (fMergerFileList) delete fMergerFileList; if (fMergerOutputFile) delete fMergerOutputFile; } //______________________________________________________________________________ void TGrid::PrintProgress(Long64_t bytesread, Long64_t size) { // Print file copy progress. fprintf(stderr, "[TGrid::Cp] Total %.02f MB\t|", (Double_t)size/1048576); for (int l = 0; l < 20; l++) { if (l < 20*bytesread/size) fprintf(stderr, "="); if (l == 20*bytesread/size) fprintf(stderr, ">"); if (l > 20*bytesread/size) fprintf(stderr, "."); } fWatch.Stop(); Double_t lCopy_time = fWatch.RealTime(); fprintf(stderr, "| %.02f %% [%.01f MB/s]\r", 100.0*bytesread/size, bytesread/lCopy_time/1048576.); fWatch.Continue(); } //______________________________________________________________________________ Bool_t TGrid::Cp(const char *src, const char *dst, Bool_t progressbar, UInt_t buffersize) { // Allows to copy file from src to dst URL. Bool_t success = kFALSE; TUrl sURL(src, kTRUE); TUrl dURL(dst, kTRUE); char *copybuffer = 0; TFile *sfile = 0; TFile *dfile = 0; sfile = TFile::Open(src, "-READ"); if (!sfile) { Error("Cp", "cannot open source file %s", src); goto copyout; } dfile = TFile::Open(dst, "-RECREATE"); if (!dfile) { Error("Cp", "cannot open destination file %s", dst); goto copyout; } sfile->Seek(0); dfile->Seek(0); copybuffer = new char[buffersize]; if (!copybuffer) { Error("Cp", "cannot allocate the copy buffer"); goto copyout; } Bool_t readop; Bool_t writeop; Long64_t read; Long64_t written; Long64_t totalread; Long64_t filesize; Long64_t b00; filesize = sfile->GetSize(); totalread = 0; fWatch.Start(); b00 = (Long64_t)sfile->GetBytesRead(); do { if (progressbar) PrintProgress(totalread, filesize); Long64_t b1 = (Long64_t)sfile->GetBytesRead() - b00; Long64_t readsize; if (filesize - b1 > (Long64_t)buffersize) { readsize = buffersize; } else { readsize = filesize - b1; } Long64_t b0 = (Long64_t)sfile->GetBytesRead(); readop = sfile->ReadBuffer(copybuffer, readsize); read = (Long64_t)sfile->GetBytesRead() - b0; if (read < 0) { Error("Cp", "cannot read from source file %s", src); goto copyout; } Long64_t w0 = (Long64_t)dfile->GetBytesWritten(); writeop = dfile->WriteBuffer(copybuffer, read); written = (Long64_t)dfile->GetBytesWritten() - w0; if (written != read) { Error("Cp", "cannot write %d bytes to destination file %s", read, dst); goto copyout; } totalread += read; } while (read == (Long64_t)buffersize); if (progressbar) { PrintProgress(totalread, filesize); fprintf(stderr, "\n"); } success = kTRUE; copyout: if (sfile) sfile->Close(); if (dfile) dfile->Close(); if (sfile) delete sfile; if (dfile) delete dfile; if (copybuffer) delete copybuffer; fWatch.Stop(); fWatch.Reset(); return success; } //______________________________________________________________________________ void TGrid::MergerReset() { // Reset merger file list. fMergerFileList->Clear(); } //______________________________________________________________________________ Bool_t TGrid::MergerAddFile(const char *url) { // Add file to file merger. TUUID uuid; TString localcopy = "file:/tmp/"; localcopy += "ROOTMERGE-"; localcopy += uuid.AsString(); localcopy += ".root"; if (!Cp(url, localcopy)) { Error("MergerAddFile", "cannot get a local copy of file %s", url); return kFALSE; } TFile *newfile = TFile::Open(localcopy, "READ"); if (!newfile) { Error("MergerAddFile", "cannot open local copy %s of URL %s", localcopy.Data(), url); return kFALSE; } else { fMergerFileList->Add(newfile); return kTRUE; } } //______________________________________________________________________________ Bool_t TGrid::MergerOutputFile(const char *outputfile) { // Open merger output file. if (fMergerOutputFile) delete fMergerOutputFile; fMergerOutputFilename = outputfile; TUUID uuid; TString localcopy = "file:/tmp/"; localcopy += "ROOTMERGED-"; localcopy += uuid.AsString(); localcopy += ".root"; fMergerOutputFile = TFile::Open(localcopy, "RECREATE"); fMergerOutputFilename1 = localcopy; if (!fMergerOutputFile) { Error("MergerOutputFile", "cannot open the MERGER outputfile %s", localcopy.Data()); return kFALSE; } return kTRUE; } //______________________________________________________________________________ void TGrid::MergerPrintFiles(Option_t *options) { // Print list of files being merged. fMergerFileList->Print(options); } //______________________________________________________________________________ Bool_t TGrid::MergerMerge() { // Merge the files. if (!fMergerOutputFile) { Info("MergerMerge", "will merge the results to the file " "GridMergerMerged.root in your working directory, " "since you didn't specify a merge filename"); if (!MergerOutputFile("GridMergerMerged.root")) { return kFALSE; } } Bool_t result = MergerMergeRecursive(fMergerOutputFile, fMergerFileList); if (!result) { Error("MergerMerge", "error during merge of your ROOT files"); } else { fMergerOutputFile->Write(); // copy the result file to the final destination Cp(fMergerOutputFilename1, fMergerOutputFilename); } // remove the temporary result file TString path(fMergerOutputFile->GetPath()); path = path(0, path.Index(':',0)); gSystem->Unlink(path); fMergerOutputFile = 0; TIter next(fMergerFileList); TFile *file; while ((file = (TFile*) next())) { // close the files file->Close(); // remove the temporary files TString path(file->GetPath()); path = path(0, path.Index(':',0)); gSystem->Unlink(path); } return result; } //______________________________________________________________________________ Bool_t TGrid::MergerMergeRecursive(TDirectory *target, TList *sourcelist) { // Recursively merge objects in the ROOT files. TString path(strstr(target->GetPath(), ":")); path.Remove(0, 2); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd(path); TDirectory *current_sourcedir = gDirectory; TChain *globChain = 0; TIter nextkey(current_sourcedir->GetListOfKeys()); TKey *key; Bool_t success = kTRUE; // gain time, do not add the objects in the list in memory TH1::AddDirectory(kFALSE); while ((key = (TKey*) nextkey())) { first_source->cd(path); TObject *obj = key->ReadObj(); if (obj->IsA()->InheritsFrom("TH1")) { Info("MergerMergeRecursive", "merging histogram %s", obj->GetName()); TH1 *h1 = (TH1*)obj; TFile *nextsource = (TFile*)sourcelist->After(first_source); while (nextsource) { nextsource->cd(path); TH1 *h2 = (TH1*)gDirectory->Get(h1->GetName()); if (h2) { h1->Add(h2); delete h2; } nextsource = (TFile*)sourcelist->After(nextsource); } } else if (obj->IsA()->InheritsFrom("TTree")) { Info("MergerMergeRecursive", "merging tree %s", obj->GetName()); const char *obj_name= obj->GetName(); globChain = new TChain(obj_name); globChain->Add(first_source->GetName()); TFile *nextsource = (TFile*)sourcelist->After(first_source); while (nextsource) { globChain->Add(nextsource->GetName()); nextsource = (TFile*)sourcelist->After(nextsource); } } else if (obj->IsA()->InheritsFrom("TDirectory")) { target->cd(); TDirectory *newdir = target->mkdir(obj->GetName(), obj->GetTitle()); if (!MergerMergeRecursive(newdir, sourcelist)) { Error("MergerMergeRecursive", "error during merge of directory %s", newdir->GetPath()); success = kFALSE; } } else { Error("MergerMergeRecursive", "unknown object type, name: %s title: %s", obj->GetName(), obj->GetTitle()); success = kFALSE; } if (obj) { target->cd(); if (obj->IsA()->InheritsFrom("TTree")) { globChain->Merge(target->GetFile() ,0, "keep"); delete globChain; } else obj->Write(key->GetName()); } } // nextkey target->Write(); TH1::AddDirectory(kTRUE); return success; } <|endoftext|>
<commit_before><commit_msg>improved VCOM Toggle<commit_after><|endoftext|>
<commit_before><commit_msg>WaE: possible loss of data<commit_after><|endoftext|>
<commit_before>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Lengths. const I_diff_t src_size = std::distance(src_begin, src_end); const I_diff_t dest_size = std::distance(dest_begin, dest_end); // Ensure the result will fit. assert(src_size <= dest_size); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= src_size); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // The position of the window. I_diff_t window_begin = 0; // Find window offset corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); multiset sorted_window; deque window_iters(2 * half_length + 1); // Get the initial sorted window. // Include the reflection. for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]); } for (I_diff_t j = half_length; j < (2 * half_length + 1); j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]); } typename multiset::iterator rank_point = sorted_window.begin(); for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T prev_value; T next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin == src_size ) { next_value = prev_value; } else if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <commit_msg>Explain purpose of multiset and deque<commit_after>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Lengths. const I_diff_t src_size = std::distance(src_begin, src_end); const I_diff_t dest_size = std::distance(dest_begin, dest_end); // Ensure the result will fit. assert(src_size <= dest_size); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= src_size); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // The position of the window. I_diff_t window_begin = 0; // Find window offset corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Get the initial sorted window. // Include the reflection. for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]); } for (I_diff_t j = half_length; j < (2 * half_length + 1); j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]); } typename multiset::iterator rank_point = sorted_window.begin(); for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T prev_value; T next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin == src_size ) { next_value = prev_value; } else if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <|endoftext|>
<commit_before>/* * Copyright 2016 C. Brett Witherspoon * * This file is part of the signum library * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef SIGNUM_PIPE_HPP_ #define SIGNUM_PIPE_HPP_ #include <string> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> namespace signum { class pipe { public: pipe(const std::string &name) { // Try to open pipe (blocks until other end appears) or create it m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) { if (mkfifo(name.c_str(), 0666) == -1) throw std::runtime_error("Unable to create named pipe: " + name); m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) throw std::runtime_error("Unable to open named pipe: " + name); } } pipe(const pipe&) = delete; ~pipe() { close(m_fd); } pipe &operator=(const pipe&) = delete; bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; } bool operator!=(const pipe &rhs) const { return !operator==(rhs); } operator int() const { return m_fd; } template<typename T> size_t write(T *data, size_t size) { ssize_t n = ::write(m_fd, data, size * sizeof(T)); if (n == -1) throw std::runtime_error("Unable to write to named pipe"); return n; } private: int m_fd; }; } // end namespace signum #endif /* SIGNUM_PIPE_HPP_ */ <commit_msg>pipe: add unlink method<commit_after>/* * Copyright 2016 C. Brett Witherspoon * * This file is part of the signum library * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef SIGNUM_PIPE_HPP_ #define SIGNUM_PIPE_HPP_ #include <string> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> namespace signum { class pipe { public: pipe(const std::string &name) : m_name(name) { // Try to open pipe (blocks until other end appears) or create it m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) { if (mkfifo(name.c_str(), 0666) == -1) throw std::runtime_error("Unable to create named pipe: " + name); m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) throw std::runtime_error("Unable to open named pipe: " + name); } } pipe(const pipe&) = delete; ~pipe() { unlink(); close(m_fd); } pipe &operator=(const pipe&) = delete; bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; } bool operator!=(const pipe &rhs) const { return !operator==(rhs); } operator int() const { return m_fd; } std::string name() const { return m_name; } void unlink() { ::unlink(m_name.c_str()); } template<typename T> size_t write(T *data, size_t size) { ssize_t n = ::write(m_fd, data, size * sizeof(T)); if (n == -1) throw std::runtime_error("Unable to write to named pipe"); return n; } private: const std::string m_name; int m_fd; }; } // end namespace signum #endif /* SIGNUM_PIPE_HPP_ */ <|endoftext|>
<commit_before>/* * Copyright 2016 C. Brett Witherspoon * * This file is part of the signum library * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef SIGNUM_PIPE_HPP_ #define SIGNUM_PIPE_HPP_ #include <stdexcept> #include <string> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> namespace signum { class pipe { public: pipe() : m_name(), m_fd(-1) { } explicit pipe(const std::string &name, mode_t mode = 0660) : m_name(name) { // Try to open pipe (blocks until other end appears) or create it m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) { if (mkfifo(name.c_str(), mode) == -1) throw std::runtime_error("Unable to create named pipe: " + name); m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) throw std::runtime_error("Unable to open named pipe: " + name); } } pipe(const pipe&) = delete; pipe(pipe &&other) : m_name(other.m_name), m_fd(other.m_fd) { other.m_fd = -1; other.m_name = ""; } ~pipe() { unlink(); close(m_fd); } pipe &operator=(const pipe&) = delete; pipe &operator=(pipe &&other) { m_name = other.m_name; other.m_name = ""; m_fd = other.m_fd; other.m_fd = -1; return *this; } bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; } bool operator!=(const pipe &rhs) const { return !operator==(rhs); } operator int() const { return m_fd; } std::string name() const { return m_name; } void unlink() { ::unlink(m_name.c_str()); } template<typename T> size_t write(T *data, size_t size) { ssize_t n = ::write(m_fd, data, size * sizeof(T)); if (n == -1) throw std::runtime_error("Unable to write to named pipe"); return n; } private: std::string m_name; int m_fd; }; } // end namespace signum #endif /* SIGNUM_PIPE_HPP_ */ <commit_msg>pipe: use system error exception<commit_after>/* * Copyright 2016 C. Brett Witherspoon * * This file is part of the signum library * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef SIGNUM_PIPE_HPP_ #define SIGNUM_PIPE_HPP_ #include <system_error> #include <string> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> namespace signum { class pipe { public: pipe() : m_name(), m_fd(-1) { } explicit pipe(const std::string &name, mode_t mode = 0660) : m_name(name) { // Try to open pipe (blocks until other end appears) or create it m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) { if (errno == EACCES) throw std::system_error(EACCES, std::system_category()); if (mkfifo(name.c_str(), mode) == -1) throw std::system_error(errno, std::system_category()); m_fd = open(name.c_str(), O_WRONLY); if (m_fd == -1) throw std::system_error(errno, std::system_category()); } } pipe(const pipe&) = delete; pipe(pipe &&other) : m_name(other.m_name), m_fd(other.m_fd) { other.m_fd = -1; other.m_name = ""; } ~pipe() { unlink(); close(m_fd); } pipe &operator=(const pipe&) = delete; pipe &operator=(pipe &&other) { m_name = other.m_name; other.m_name = ""; m_fd = other.m_fd; other.m_fd = -1; return *this; } bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; } bool operator!=(const pipe &rhs) const { return !operator==(rhs); } operator int() const { return m_fd; } std::string name() const { return m_name; } void unlink() { ::unlink(m_name.c_str()); } template<typename T> size_t write(T *data, size_t size) { ssize_t n = ::write(m_fd, data, size * sizeof(T)); if (n == -1) throw std::system_error(errno, std::system_category()); return n; } private: std::string m_name; int m_fd; }; } // end namespace signum #endif /* SIGNUM_PIPE_HPP_ */ <|endoftext|>
<commit_before>// // linked_list.hpp // DS // // Created by Rahul Goel on 7/26/17. // Copyright © 2017 Rahul Goel. All rights reserved. // #ifndef linked_list_hpp #define linked_list_hpp #include <stdio.h> #include <stdlib.h> //To create a test Single Linked List with four nodes in it struct list_node* linkedlist_testcreate(); //To print all the elements in given single lineked list - O(n) Time void linkedlist_print(struct list_node *base); //To count the number of nodes in given single linked list - O(n) Time int linkedlist_countnodes(struct list_node *base); //To insert a node on given position pos int linkedlist_insert(struct list_node *base,int pos,int data); //To delete a node from given position pos void linkedlist_delete(struct list_node *base, int pos); //To check if given linked list has cycle or not int linkedlist_checkIfCycle(struct list_node *base); //Reverse of given linked list struct list_node* linkedlist_reverse(struct list_node *base); #endif /* linked_list_hpp */ <commit_msg>linkedlist<commit_after>// // linked_list.hpp // DS // // Created by Rahul Goel on 7/26/17. // Copyright © 2017 Rahul Goel. All rights reserved. // #ifndef linked_list_hpp #define linked_list_hpp #include <stdio.h> #include <stdlib.h> //1. To create a test Single Linked List with four nodes in it struct list_node* linkedlist_testcreate(); //2. To print all the elements in given single lineked list - O(n) Time void linkedlist_print(struct list_node *base); //3. To count the number of nodes in given single linked list - O(n) Time int linkedlist_countnodes(struct list_node *base); //4. To insert a node on given position pos int linkedlist_insert(struct list_node *base,int pos,int data); //5. To delete a node from given position pos void linkedlist_delete(struct list_node *base, int pos); //6. To check if given linked list has cycle or not int linkedlist_checkIfCycle(struct list_node *base); //7. Reverse of given linked list struct list_node* linkedlist_reverse(struct list_node *base); //8. Search given element in Linked List bool linkedlist_searchElement(struct list_node *base, int number); //9. Swap two nodes in linked list, without swapping data but with address as Swapping data of nodes may be expensive in many situations when data contains many fields void linkedlist_swapTwoNodes(struct list_node *base, int val1, int val2); //10. Get data in nth node from given linked list int linkedlist_getNthNode(struct list_node *base,int n); //11. Find middle of given linked list int linkedlist_middleIs(struct list_node *base); #endif /* linked_list_hpp */ <|endoftext|>
<commit_before>/* Copyright 2016 Hewlett Packard Enterprise Development LP 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 <cxxabi.h> #include "dynamiclibop.h" #include <dlfcn.h> #include <string> #include <memory> #include <typeinfo> #include <vector> #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/device_base.h" #include "threadpool.h" #if GOOGLE_CUDA // this must be defined for the include file below to actually include anything #define EIGEN_USE_GPU #include <cuda.h> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #endif // GOOGLE_CUDA namespace tensorflow { // Define the operator interface: inputs, outputs and parameters // inputs and outputs are a list of tensors that can be either floats or doubles // and all input tensors do not need to be the same type REGISTER_OP("DynamicLib") .Attr("gpu_func_name: string") .Attr("gpu_lib_path: string") .Attr("cpu_func_name: string") .Attr("cpu_lib_path: string") .Attr("serialized_grad_dag: string") .Attr("cuda_threads_per_block: int") .Attr("out_shapes: list(shape)") .Attr("in_types: list({float, double}) >= 0") .Attr("out_types: list({float, double})") .Input("inputs: in_types") .Output("outputs: out_types") .Doc(R"doc(call a dynamically generated library operation)doc"); typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; // static std::string getDebugString( // const std::vector<std::shared_ptr<const InputParameter>> parameters) { // std::string str; // int status; // char *paramType; // for (uint32_t i = 0; i < parameters.size(); i++) { // const std::type_info &ti = typeid(*(parameters[i])); // paramType = abi::__cxa_demangle(ti.name(), 0, 0, &status); // str.append(paramType + std::string(": ") + // std::to_string(parameters[i]->length()) + ", "); // } // return str; // } // Class which will dynamically load and launch the generated operators // on either CPU or GPU template <typename Device> class DynamicLibLaunch; // Partial specialization for CPU template <> class DynamicLibLaunch<CPUDevice> { public: typedef uint16_t (*FUNPTR)(std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs, int num_threads, int thread_idx, uint16_t *err); DynamicLibLaunch(OpKernelConstruction* context, const string& cpu_func_name, const string& cpu_lib_path, const string&, const string&, const int ) { LOG(INFO) << "*** Standalone DynamicLibLaunch on CPU *****"; // load the compiled op shared library static_assert(sizeof(void *) == sizeof(void (*)(void)), "object pointer and function pointer sizes must equal"); void *handle = dlopen(cpu_lib_path.c_str(), RTLD_LAZY); OP_REQUIRES(context, handle != nullptr, errors::NotFound("Unable to find DynamicLib library " + cpu_lib_path)); // load the function and cast it from void* to a function pointer void *f = dlsym(handle, cpu_func_name.c_str()); func_ = reinterpret_cast<FUNPTR>(f); OP_REQUIRES(context, func_ != nullptr, errors::NotFound("Unable to find DynamicLib function " + cpu_func_name)); } void Run(OpKernelContext* context, const CPUDevice&, std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs) { const int num_threads = context->device()->tensorflow_cpu_worker_threads()->workers->NumThreads(); thread::ThreadPool thread_pool(Env::Default(), "dynamiclibop", num_threads); uint16_t err = 0; for (int thread = 0; thread < num_threads; thread++) { auto fn_work = std::bind(func_, inputs, outputs, num_threads, thread, &err); thread_pool.Schedule(fn_work); } OP_REQUIRES(context, err == 0, errors::InvalidArgument("External function execution error code: ", err)); } private: FUNPTR func_; }; #if GOOGLE_CUDA // Partial specialization for GPU template <> class DynamicLibLaunch<GPUDevice> { public: typedef uint16_t (*FUNPTR)(std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs, CUstream stream, int cuda_threads_per_block); DynamicLibLaunch(OpKernelConstruction* context, const string&, const string&, const string& gpu_func_name, const string& gpu_lib_path, const int cuda_threads_per_block) { LOG(INFO) << "*** Standalone DynamicLibLaunch on GPU *****"; // load the compiled op shared library static_assert(sizeof(void *) == sizeof(void (*)(void)), "object pointer and function pointer sizes must equal"); void *handle = dlopen(gpu_lib_path.c_str(), RTLD_LAZY); OP_REQUIRES(context, handle != nullptr, errors::NotFound("Unable to find DynamicLib library " + gpu_lib_path)); // load the function and cast it from void* to a function pointer void *f = dlsym(handle, gpu_func_name.c_str()); func_ = reinterpret_cast<FUNPTR>(f); OP_REQUIRES(context, func_ != nullptr, errors::NotFound("Unable to find DynamicLib function " + gpu_func_name)); cuda_threads_per_block_ = cuda_threads_per_block; } void Run(OpKernelContext* context, const GPUDevice& d, std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs) { // call the DynamicLib library functions uint16_t err = func_(inputs, outputs, d.stream(), cuda_threads_per_block_); OP_REQUIRES(context, err == 0, errors::InvalidArgument("External function execution error code: ", err)); } private: FUNPTR func_; int cuda_threads_per_block_; }; #endif // GOOGLE_CUDA // General purpose tensorflow user operator class // that allows us to run operators generated and compiled independently // by the Operator Vectorization Library. // Parameters are a list of input tensors, list of output shapes, list of // output types, the location of the DynamicLib shared libraries and the name // of the DynamicLib operator. // See tensorflow/python/kernel_tests/dynamic_lib_op_test.py for example usage template <typename Device> class DynamicLibOp : public OpKernel { public: explicit DynamicLibOp(OpKernelConstruction* context) : OpKernel(context) { // store the passed in parameters OP_REQUIRES_OK(context, context->GetAttr("cpu_func_name", &cpu_func_name_)); OP_REQUIRES_OK(context, context->GetAttr("cpu_lib_path", &cpu_lib_path_)); OP_REQUIRES_OK(context, context->GetAttr("gpu_func_name", &gpu_func_name_)); OP_REQUIRES_OK(context, context->GetAttr("gpu_lib_path", &gpu_lib_path_)); OP_REQUIRES_OK(context, context->GetAttr("cuda_threads_per_block", &cuda_threads_per_block_)); OP_REQUIRES_OK(context, context->GetAttr("out_types", &out_types_)); OP_REQUIRES_OK(context, context->GetAttr("out_shapes", &out_shapes_)); launcher_ = std::unique_ptr<DynamicLibLaunch<Device>>( new DynamicLibLaunch<Device>(context, cpu_func_name_, cpu_lib_path_, gpu_func_name_, gpu_lib_path_, cuda_threads_per_block_)); } // Function that is called when the output tensors of the operator // are evaluated void Compute(OpKernelContext* context) override { // LOG(INFO) << "*** computing DynamicLibOp ***"; // Build the tensor input parameter list OpInputList input_list; context->input_list("inputs", &input_list); std::vector<std::shared_ptr<const InputParameter>> inputs; inputs.reserve(input_list.size()); for (int32_t i = 0; i < input_list.size(); ++i) { const Tensor& cur_input = input_list[i]; switch (cur_input.dtype()) { case (DT_FLOAT): inputs.emplace_back( new TypedInput<float>(cur_input.flat<float>().data(), cur_input.NumElements())); break; case (DT_DOUBLE): inputs.emplace_back( new TypedInput<double>(cur_input.flat<double>().data(), cur_input.NumElements())); break; default: OP_REQUIRES(context, false, errors::InvalidArgument( "Only float and double inputs are supported.")); break; } } // Build the output tensor parameter list const uint32_t num_outputs = context->num_outputs(); OP_REQUIRES(context, num_outputs == out_shapes_.size(), errors::InvalidArgument( "Output shapes inconsistent with output types")) OP_REQUIRES(context, num_outputs == out_types_.size(), errors::InvalidArgument( "Output types inconsistent num_outputs")) Tensor *output_tensor[num_outputs]; std::vector<std::shared_ptr<OutputParameter>> outputs; outputs.reserve(num_outputs); for (uint32_t i = 0; i < num_outputs; ++i) { DataType cur_output_type = out_types_[i]; TensorShape cur_shape = TensorShape(out_shapes_[i]); OP_REQUIRES_OK(context, context->allocate_output(i, cur_shape, &output_tensor[i])); OP_REQUIRES(context, output_tensor[i]->dtype() == cur_output_type, errors::InvalidArgument("Types inconsistent")) switch (cur_output_type) { case (DT_FLOAT): outputs.emplace_back(new TypedOutput<float>( output_tensor[i]->template flat<float>().data(), output_tensor[i]->NumElements())); break; case (DT_DOUBLE): outputs.emplace_back(new TypedOutput<double>( output_tensor[i]->template flat<double>().data(), output_tensor[i]->NumElements())); break; default: OP_REQUIRES(context, false, errors::InvalidArgument( "Only float and double outputs are supported.")); break; } } // call the DynamicLib library function const Device& d = context->eigen_device<Device>(); launcher_->Run(context, d, inputs, outputs); } private: string cpu_func_name_; string cpu_lib_path_; string gpu_func_name_; string gpu_lib_path_; int cuda_threads_per_block_; DataTypeVector out_types_; std::vector<TensorShapeProto> out_shapes_; std::unique_ptr<DynamicLibLaunch<Device>> launcher_; }; // register the operator for each template type with tensorflow // Note: this registration will cause the operator constructors to get called // regardless of whether or not they are used in a tensorflow application REGISTER_KERNEL_BUILDER(Name("DynamicLib") .Device(DEVICE_CPU), DynamicLibOp<CPUDevice>); #if GOOGLE_CUDA REGISTER_KERNEL_BUILDER(Name("DynamicLib") .Device(DEVICE_GPU), DynamicLibOp<GPUDevice>); #endif // GOOGLE_CUDA } // namespace tensorflow <commit_msg>added scoping of threadpool in dynamiclibop.cc<commit_after>/* Copyright 2016 Hewlett Packard Enterprise Development LP 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 <cxxabi.h> #include "dynamiclibop.h" #include <dlfcn.h> #include <string> #include <memory> #include <typeinfo> #include <vector> #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/device_base.h" #include "threadpool.h" #if GOOGLE_CUDA // this must be defined for the include file below to actually include anything #define EIGEN_USE_GPU #include <cuda.h> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #endif // GOOGLE_CUDA namespace tensorflow { // Define the operator interface: inputs, outputs and parameters // inputs and outputs are a list of tensors that can be either floats or doubles // and all input tensors do not need to be the same type REGISTER_OP("DynamicLib") .Attr("gpu_func_name: string") .Attr("gpu_lib_path: string") .Attr("cpu_func_name: string") .Attr("cpu_lib_path: string") .Attr("serialized_grad_dag: string") .Attr("cuda_threads_per_block: int") .Attr("out_shapes: list(shape)") .Attr("in_types: list({float, double}) >= 0") .Attr("out_types: list({float, double})") .Input("inputs: in_types") .Output("outputs: out_types") .Doc(R"doc(call a dynamically generated library operation)doc"); typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; // static std::string getDebugString( // const std::vector<std::shared_ptr<const InputParameter>> parameters) { // std::string str; // int status; // char *paramType; // for (uint32_t i = 0; i < parameters.size(); i++) { // const std::type_info &ti = typeid(*(parameters[i])); // paramType = abi::__cxa_demangle(ti.name(), 0, 0, &status); // str.append(paramType + std::string(": ") + // std::to_string(parameters[i]->length()) + ", "); // } // return str; // } // Class which will dynamically load and launch the generated operators // on either CPU or GPU template <typename Device> class DynamicLibLaunch; // Partial specialization for CPU template <> class DynamicLibLaunch<CPUDevice> { public: typedef uint16_t (*FUNPTR)(std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs, int num_threads, int thread_idx, uint16_t *err); DynamicLibLaunch(OpKernelConstruction* context, const string& cpu_func_name, const string& cpu_lib_path, const string&, const string&, const int ) { LOG(INFO) << "*** Standalone DynamicLibLaunch on CPU *****"; // load the compiled op shared library static_assert(sizeof(void *) == sizeof(void (*)(void)), "object pointer and function pointer sizes must equal"); void *handle = dlopen(cpu_lib_path.c_str(), RTLD_LAZY); OP_REQUIRES(context, handle != nullptr, errors::NotFound("Unable to find DynamicLib library " + cpu_lib_path)); // load the function and cast it from void* to a function pointer void *f = dlsym(handle, cpu_func_name.c_str()); func_ = reinterpret_cast<FUNPTR>(f); OP_REQUIRES(context, func_ != nullptr, errors::NotFound("Unable to find DynamicLib function " + cpu_func_name)); } void Run(OpKernelContext* context, const CPUDevice&, std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs) { const int num_threads = context->device()->tensorflow_cpu_worker_threads()->workers->NumThreads(); uint16_t err = 0; // ThreadPool destructor is what joins all the threads and waits for completion, so we // scope it as a local variable and when it goes out of scope, all the work is done and result // can be used { thread::ThreadPool thread_pool(Env::Default(), "dynamiclibop", num_threads); for (int thread = 0; thread < num_threads; thread++) { auto fn_work = std::bind(func_, inputs, outputs, num_threads, thread, &err); thread_pool.Schedule(fn_work); } } OP_REQUIRES(context, err == 0, errors::InvalidArgument("External function execution error code: ", err)); } private: FUNPTR func_; }; #if GOOGLE_CUDA // Partial specialization for GPU template <> class DynamicLibLaunch<GPUDevice> { public: typedef uint16_t (*FUNPTR)(std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs, CUstream stream, int cuda_threads_per_block); DynamicLibLaunch(OpKernelConstruction* context, const string&, const string&, const string& gpu_func_name, const string& gpu_lib_path, const int cuda_threads_per_block) { LOG(INFO) << "*** Standalone DynamicLibLaunch on GPU *****"; // load the compiled op shared library static_assert(sizeof(void *) == sizeof(void (*)(void)), "object pointer and function pointer sizes must equal"); void *handle = dlopen(gpu_lib_path.c_str(), RTLD_LAZY); OP_REQUIRES(context, handle != nullptr, errors::NotFound("Unable to find DynamicLib library " + gpu_lib_path)); // load the function and cast it from void* to a function pointer void *f = dlsym(handle, gpu_func_name.c_str()); func_ = reinterpret_cast<FUNPTR>(f); OP_REQUIRES(context, func_ != nullptr, errors::NotFound("Unable to find DynamicLib function " + gpu_func_name)); cuda_threads_per_block_ = cuda_threads_per_block; } void Run(OpKernelContext* context, const GPUDevice& d, std::vector<std::shared_ptr<const InputParameter>> inputs, std::vector<std::shared_ptr<OutputParameter>> outputs) { // call the DynamicLib library functions uint16_t err = func_(inputs, outputs, d.stream(), cuda_threads_per_block_); OP_REQUIRES(context, err == 0, errors::InvalidArgument("External function execution error code: ", err)); } private: FUNPTR func_; int cuda_threads_per_block_; }; #endif // GOOGLE_CUDA // General purpose tensorflow user operator class // that allows us to run operators generated and compiled independently // by the Operator Vectorization Library. // Parameters are a list of input tensors, list of output shapes, list of // output types, the location of the DynamicLib shared libraries and the name // of the DynamicLib operator. // See tensorflow/python/kernel_tests/dynamic_lib_op_test.py for example usage template <typename Device> class DynamicLibOp : public OpKernel { public: explicit DynamicLibOp(OpKernelConstruction* context) : OpKernel(context) { // store the passed in parameters OP_REQUIRES_OK(context, context->GetAttr("cpu_func_name", &cpu_func_name_)); OP_REQUIRES_OK(context, context->GetAttr("cpu_lib_path", &cpu_lib_path_)); OP_REQUIRES_OK(context, context->GetAttr("gpu_func_name", &gpu_func_name_)); OP_REQUIRES_OK(context, context->GetAttr("gpu_lib_path", &gpu_lib_path_)); OP_REQUIRES_OK(context, context->GetAttr("cuda_threads_per_block", &cuda_threads_per_block_)); OP_REQUIRES_OK(context, context->GetAttr("out_types", &out_types_)); OP_REQUIRES_OK(context, context->GetAttr("out_shapes", &out_shapes_)); launcher_ = std::unique_ptr<DynamicLibLaunch<Device>>( new DynamicLibLaunch<Device>(context, cpu_func_name_, cpu_lib_path_, gpu_func_name_, gpu_lib_path_, cuda_threads_per_block_)); } // Function that is called when the output tensors of the operator // are evaluated void Compute(OpKernelContext* context) override { // LOG(INFO) << "*** computing DynamicLibOp ***"; // Build the tensor input parameter list OpInputList input_list; context->input_list("inputs", &input_list); std::vector<std::shared_ptr<const InputParameter>> inputs; inputs.reserve(input_list.size()); for (int32_t i = 0; i < input_list.size(); ++i) { const Tensor& cur_input = input_list[i]; switch (cur_input.dtype()) { case (DT_FLOAT): inputs.emplace_back( new TypedInput<float>(cur_input.flat<float>().data(), cur_input.NumElements())); break; case (DT_DOUBLE): inputs.emplace_back( new TypedInput<double>(cur_input.flat<double>().data(), cur_input.NumElements())); break; default: OP_REQUIRES(context, false, errors::InvalidArgument( "Only float and double inputs are supported.")); break; } } // Build the output tensor parameter list const uint32_t num_outputs = context->num_outputs(); OP_REQUIRES(context, num_outputs == out_shapes_.size(), errors::InvalidArgument( "Output shapes inconsistent with output types")) OP_REQUIRES(context, num_outputs == out_types_.size(), errors::InvalidArgument( "Output types inconsistent num_outputs")) Tensor *output_tensor[num_outputs]; std::vector<std::shared_ptr<OutputParameter>> outputs; outputs.reserve(num_outputs); for (uint32_t i = 0; i < num_outputs; ++i) { DataType cur_output_type = out_types_[i]; TensorShape cur_shape = TensorShape(out_shapes_[i]); OP_REQUIRES_OK(context, context->allocate_output(i, cur_shape, &output_tensor[i])); OP_REQUIRES(context, output_tensor[i]->dtype() == cur_output_type, errors::InvalidArgument("Types inconsistent")) switch (cur_output_type) { case (DT_FLOAT): outputs.emplace_back(new TypedOutput<float>( output_tensor[i]->template flat<float>().data(), output_tensor[i]->NumElements())); break; case (DT_DOUBLE): outputs.emplace_back(new TypedOutput<double>( output_tensor[i]->template flat<double>().data(), output_tensor[i]->NumElements())); break; default: OP_REQUIRES(context, false, errors::InvalidArgument( "Only float and double outputs are supported.")); break; } } // call the DynamicLib library function const Device& d = context->eigen_device<Device>(); launcher_->Run(context, d, inputs, outputs); } private: string cpu_func_name_; string cpu_lib_path_; string gpu_func_name_; string gpu_lib_path_; int cuda_threads_per_block_; DataTypeVector out_types_; std::vector<TensorShapeProto> out_shapes_; std::unique_ptr<DynamicLibLaunch<Device>> launcher_; }; // register the operator for each template type with tensorflow // Note: this registration will cause the operator constructors to get called // regardless of whether or not they are used in a tensorflow application REGISTER_KERNEL_BUILDER(Name("DynamicLib") .Device(DEVICE_CPU), DynamicLibOp<CPUDevice>); #if GOOGLE_CUDA REGISTER_KERNEL_BUILDER(Name("DynamicLib") .Device(DEVICE_GPU), DynamicLibOp<GPUDevice>); #endif // GOOGLE_CUDA } // namespace tensorflow <|endoftext|>
<commit_before>/******************************************************************************* Program: Wake Forest University - Virginia Tech CTC Software Id: $Id$ Language: C++ *******************************************************************************/ // command line app to subtract tagged stool from images #include <iostream> #include <cstdlib> using namespace std; // ITK includes #include <itkImageSeriesWriter.h> #include <itkNumericSeriesFileNames.h> #include <itksys/SystemTools.hxx> #include <itkGDCMImageIO.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> // CTC includes #include "ctcConfigure.h" #include "ctcCTCImage.h" #include "ctcCTCImageReader.h" #include "ctcSegmentColonWithContrastFilter.h" #include "vul_arg.h" int main(int argc, char ** argv) { // parse args vul_arg<char const*> infile(0, "Input DICOM directory"); vul_arg<char const*> outfile(0, "Output DICOM directory"); vul_arg<int> replaceval("-r", "Replacement HU value for tagged regions (default -900)", -900); vul_arg_parse(argc, argv); // test if outfile exists, if so bail out if(itksys::SystemTools::FileExists(outfile())) { if(itksys::SystemTools::FileIsDirectory(outfile())) { cerr << "Error: directory " << outfile() << " exists. Halting." << endl; } else { cerr << "Error: file " << outfile() << " exists. Halting." << endl; } return EXIT_FAILURE; } // read in the DICOM series ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New(); reader->SetDirectory(string(infile())); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } // segment air + constrast clog << "Starting Segment"; ctc::SegmentColonWithContrastFilter::Pointer filter = ctc::SegmentColonWithContrastFilter::New(); filter->SetInput( reader->GetOutput() ); filter->Update(); clog << " Done Segmenting." << endl; // loop through the voxels, testing for threshold and lumen test // replace image values with air clog << "Starting Mask"; int replace = replaceval(); typedef itk::ImageRegionIterator<ctc::CTCImageType> InputIteratorType; typedef itk::ImageRegionConstIterator<ctc::BinaryImageType> BinaryIteratorType; InputIteratorType it1(reader->GetOutput(), reader->GetOutput()->GetRequestedRegion()); BinaryIteratorType it2(filter->GetOutput(), filter->GetOutput()->GetRequestedRegion()); for( it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd() || !it2.IsAtEnd(); ++it1, ++it2) { if( (it2.Get() == 255) && (it1.Get() > -800) ) { it1.Set(replace); } } clog << " Done Masking" << endl; // write out modified image typedef itk::Image< short, 2 > Image2DType; typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( reader->GetOutput() ); writer->SetMetaDataDictionaryArray( reader->GetMetaDataDictionaryArray() ); itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New(); writer->SetImageIO( dicomIO ); typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); if( !itksys::SystemTools::MakeDirectory(outfile()) ) { cerr << "Error: could not create output directory" << endl; return EXIT_FAILURE; } std::string format = outfile(); format += "/%03d.dcm"; nameGenerator->SetSeriesFormat( format.c_str() ); ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput(); ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion(); ctc::CTCImageType::IndexType start = region.GetIndex(); ctc::CTCImageType::SizeType size = region.GetSize(); const unsigned int firstSlice = start[2]; const unsigned int lastSlice = start[2] + size[2] - 1; nameGenerator->SetStartIndex( firstSlice ); nameGenerator->SetEndIndex( lastSlice ); nameGenerator->SetIncrementIndex( 1 ); writer->SetFileNames( nameGenerator->GetFileNames() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught !" << endl; cerr << err << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>CLW: added modifier for DICOM tags to facilitate placement in PACS<commit_after>/******************************************************************************* Program: Wake Forest University - Virginia Tech CTC Software Id: $Id$ Language: C++ *******************************************************************************/ // command line app to subtract tagged stool from images #include <iostream> #include <cstdlib> using namespace std; // ITK includes #include <itkImageSeriesWriter.h> #include <itkNumericSeriesFileNames.h> #include <itksys/SystemTools.hxx> #include <itkGDCMImageIO.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> #include <itkMetaDataObject.h> #include <itkMetaDataDictionary.h> // CTC includes #include "ctcConfigure.h" #include "ctcCTCImage.h" #include "ctcCTCImageReader.h" #include "ctcSegmentColonWithContrastFilter.h" #include "vul_arg.h" int main(int argc, char ** argv) { // parse args vul_arg<char const*> infile(0, "Input DICOM directory"); vul_arg<char const*> outfile(0, "Output DICOM directory"); vul_arg<int> replaceval("-r", "Replacement HU value for tagged regions (default -900)", -900); vul_arg_parse(argc, argv); // test if outfile exists, if so bail out if(itksys::SystemTools::FileExists(outfile())) { if(itksys::SystemTools::FileIsDirectory(outfile())) { cerr << "Error: directory " << outfile() << " exists. Halting." << endl; } else { cerr << "Error: file " << outfile() << " exists. Halting." << endl; } return EXIT_FAILURE; } // read in the DICOM series ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New(); reader->SetDirectory(string(infile())); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } // segment air + constrast clog << "Starting Segment"; ctc::SegmentColonWithContrastFilter::Pointer filter = ctc::SegmentColonWithContrastFilter::New(); filter->SetInput( reader->GetOutput() ); filter->Update(); clog << " Done Segmenting." << endl; // loop through the voxels, testing for threshold and lumen test // replace image values with air clog << "Starting Mask"; int replace = replaceval(); typedef itk::ImageRegionIterator<ctc::CTCImageType> InputIteratorType; typedef itk::ImageRegionConstIterator<ctc::BinaryImageType> BinaryIteratorType; InputIteratorType it1(reader->GetOutput(), reader->GetOutput()->GetRequestedRegion()); BinaryIteratorType it2(filter->GetOutput(), filter->GetOutput()->GetRequestedRegion()); for( it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd() || !it2.IsAtEnd(); ++it1, ++it2) { if( (it2.Get() == 255) && (it1.Get() > -800) ) { it1.Set(replace); } } clog << " Done Masking" << endl; // write out modified image typedef itk::Image< short, 2 > Image2DType; typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( reader->GetOutput() ); // modify series number ctc::CTCImageReader::DictionaryArrayRawPointer dictarray = reader->GetMetaDataDictionaryArray(); std::string SeriesNumberTag = "0020|0011"; std::string SeriesNumberValue; for(int slice = 0; slice < dictarray->size(); slice++) { ctc::CTCImageReader::DictionaryRawPointer dict = (*(reader->GetMetaDataDictionaryArray()))[slice]; itk::ExposeMetaData<std::string>(*dict, SeriesNumberTag, SeriesNumberValue); SeriesNumberValue = "90"; itk::EncapsulateMetaData<std::string>(*dict, SeriesNumberTag, SeriesNumberValue); } writer->SetMetaDataDictionaryArray( dictarray ); itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New(); writer->SetImageIO( dicomIO ); typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); if( !itksys::SystemTools::MakeDirectory(outfile()) ) { cerr << "Error: could not create output directory" << endl; return EXIT_FAILURE; } std::string format = outfile(); format += "/%03d.dcm"; nameGenerator->SetSeriesFormat( format.c_str() ); ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput(); ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion(); ctc::CTCImageType::IndexType start = region.GetIndex(); ctc::CTCImageType::SizeType size = region.GetSize(); const unsigned int firstSlice = start[2]; const unsigned int lastSlice = start[2] + size[2] - 1; nameGenerator->SetStartIndex( firstSlice ); nameGenerator->SetEndIndex( lastSlice ); nameGenerator->SetIncrementIndex( 1 ); writer->SetFileNames( nameGenerator->GetFileNames() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught !" << endl; cerr << err << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * File: Sfuck.cpp * Author: Michael Hrcek <hrcekmj@clarkson.edu> * * Created on September 14, 2015, 6:25 PM */ #include <iostream> #include <stdlib.h> #include <fstream> #include <time.h> using namespace std; struct store { int intBank[128][128]; int index, vindex; bool printAsChar; bool notFlaged; store() { index = 0; vindex = 0; printAsChar = true; } void getCommand(char c); }; void store::getCommand(char c) { switch (c) { case '+': intBank[vindex][index]++; break; case '-': intBank[vindex][index]--; break; case '>': if (index == 127) { index = 0; } else { index++; } break; case '<': if (index == 0) { index = 127; } else { index--; } break; case '^': if (vindex == 127) { vindex = 0; } else { vindex++; } break; case '\\': if (vindex == 0) { vindex = 127; } else { vindex--; } break; case '#': index = vindex = 0; break; case ',': intBank[vindex][index] = (int) cin.get(); break; case '.': if (printAsChar) { cout << (char) intBank[vindex][index]; } else { cout << intBank[vindex][index]; } break; case '=': if (intBank[vindex][index] == (int) 'x') { intBank[vindex][index] = 1; } else { intBank[vindex][index] = 0; } break; case '?': intBank[vindex][index] = rand(); break; case '@': printAsChar = !printAsChar; break; case '~': notFlaged = false; break; case '|': if (vindex > 0) { intBank[vindex][index] = intBank[vindex - 1][index]; } else { intBank[vindex][index] = intBank[127][index]; } break; case '}': if (index > 0) { intBank[vindex][index] = intBank[vindex][index - 1]; } else { intBank[vindex][index] = intBank[vindex][127]; } break; } } /* * */ int main(int argc, char** argv) { srand(time(NULL)); store s; string choice; while (true) { cout << "SGFY interpreter v0.1.1\n\n------------------------------------------\n" << "Enter filename (cin if live interpret): "; cin >> choice; cin.clear(); s.notFlaged = true; if (choice == "cin") { while (s.notFlaged) { s.getCommand(cin.get()); } } else { ifstream stream(choice.c_str()); while (!stream.eof()) { s.getCommand(stream.get()); } } cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; } // if (argc <= 1) { // while (true) { // s.getCommand(cin.get()); // } // } else{ // //Get args // } return 0; } <commit_msg>Updated | logic<commit_after>/* * File: Sfuck.cpp * Author: Michael Hrcek <hrcekmj@clarkson.edu> * * Created on September 14, 2015, 6:25 PM */ #include <iostream> #include <stdlib.h> #include <fstream> #include <time.h> using namespace std; struct store { int intBank[128][128]; int index, vindex; bool printAsChar; bool notFlaged; store() { index = 0; vindex = 0; printAsChar = true; } void getCommand(char c); }; void store::getCommand(char c) { switch (c) { case '+': intBank[vindex][index]++; break; case '-': intBank[vindex][index]--; break; case '>': if (index == 127) { index = 0; } else { index++; } break; case '<': if (index == 0) { index = 127; } else { index--; } break; case '^': if (vindex == 127) { vindex = 0; } else { vindex++; } break; case '\\': if (vindex == 0) { vindex = 127; } else { vindex--; } break; case '#': index = vindex = 0; break; case ',': intBank[vindex][index] = (int) cin.get(); break; case '.': if (printAsChar) { cout << (char) intBank[vindex][index]; } else { cout << intBank[vindex][index]; } break; case '=': if (intBank[vindex][index] == (int) 'x') { intBank[vindex][index] = 1; } else { intBank[vindex][index] = 0; } break; case '?': intBank[vindex][index] = rand(); break; case '@': printAsChar = !printAsChar; break; case '~': notFlaged = false; break; case '|': if (vindex < 127) { intBank[vindex][index] = intBank[vindex + 1][index]; } else { intBank[vindex][index] = intBank[0][index]; } break; case '}': if (index > 0) { intBank[vindex][index] = intBank[vindex][index - 1]; } else { intBank[vindex][index] = intBank[vindex][127]; } break; } } /* * */ int main(int argc, char** argv) { srand(time(NULL)); store s; string choice; while (true) { cout << "SGFY interpreter v0.1.1\n\n------------------------------------------\n" << "Enter filename (cin if live interpret): "; cin >> choice; cin.clear(); s.notFlaged = true; if (choice == "cin") { while (s.notFlaged) { s.getCommand(cin.get()); } } else { ifstream stream(choice.c_str()); while (!stream.eof()) { s.getCommand(stream.get()); } } cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; } // if (argc <= 1) { // while (true) { // s.getCommand(cin.get()); // } // } else{ // //Get args // } return 0; } <|endoftext|>
<commit_before>// vimshell.cpp : Defines the entry point for the application. // #include "vimshell.h" #include <iostream> #include <fstream> #include <string> #include <windows.h> #include <shellapi.h> bool cvtLPW2stdstring(std::string& s, const LPWSTR pw, UINT codepage = CP_ACP) { bool res = false; char* p = 0; int bsz; bsz = WideCharToMultiByte(codepage, 0, pw,-1, 0,0, 0,0); if (bsz > 0) { p = new char[bsz]; int rc = WideCharToMultiByte(codepage, 0, pw,-1, p,bsz, 0,0); if (rc != 0) { p[bsz-1] = 0; s = p; res = true; } } delete [] p; return res; } std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace ) { size_t uPos = 0; size_t uFindLen = tFind.length(); size_t uReplaceLen = tReplace.length(); if( uFindLen == 0 ) { return tInput; } while((uPos = tInput.find( tFind, uPos )) != std::string::npos) { tInput.replace( uPos, uFindLen, tReplace ); uPos += uReplaceLen; } return tInput; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { int count; //MessageBox(0, lpCmdLine, 0, 0); LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count); std::string currentDir; cvtLPW2stdstring(currentDir, strings[0]); // Cut off the filename while((currentDir.length() > 0) && (currentDir[currentDir.length()-1] != '/') && (currentDir[currentDir.length()-1] != '\\')) { currentDir = currentDir.substr(0, currentDir.length()-1); } if(currentDir.length() > 0 && currentDir[0] == '"') currentDir = currentDir.substr(1); std::string filename = currentDir + std::string("shell.txt"); std::ifstream fileIn(filename.c_str()); if(!fileIn) { MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0); return 1; } std::string argumentshellcommand; std::string silentshellcommand; std::string interactiveshellcommand; std::getline(fileIn, argumentshellcommand); std::getline(fileIn, silentshellcommand); std::getline(fileIn, interactiveshellcommand); std::string args = lpCmdLine; while(args.length() > 0 && args[0] == ' ') args = args.substr(1); bool execSilently = false; if(args.length() > 3 && args[0] == '-' && args[1] == 's' && args[2] == ' ') { args = args.substr(3); execSilently = true; } size_t spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); std::string cmd; if(spacepos == std::string::npos) args = ""; std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand; if(args.length() == 0) { cmd = interactiveshellcommand; } else { std::string quotedPH = "#QQQQ#"; if(argcmd.find(quotedPH) != std::string::npos) { bool indoubles = false; bool insingles = false; for(size_t i = 0; i < args.length(); i++) { if(args[i] == '"') indoubles = !indoubles; if(args[i] == '\'') insingles = !insingles; if(!indoubles && !insingles && args[i] == '\\') { args.insert(i, "\\"); i++; continue; } if(!indoubles && args[i] == '\'') { args.insert(i, "\\"); i++; continue; } } //args = FindAndReplace(args,"'", "\\'"); // args = FindAndReplace(args, "\\", "\\\\"); cmd = FindAndReplace(argcmd, quotedPH, args); } else { cmd = argcmd + " " + args; } } /*MessageBox(0,cmd.c_str(), 0,0); std::ofstream f("C:/output.txt"); f << cmd.c_str(); f.close();*/ STARTUPINFO si = { sizeof(STARTUPINFO) }; si.dwFlags = STARTF_USESHOWWINDOW; if(execSilently) si.wShowWindow = SW_HIDE; else si.wShowWindow = SW_SHOW; PROCESS_INFORMATION pi; char arr[1024]; strcpy_s(arr, 1024, cmd.c_str()); CreateProcess(NULL, arr, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); DWORD exit_code; GetExitCodeProcess(pi.hProcess, &exit_code); return exit_code; } <commit_msg>Vimshell now works with files instead of inline strings. This assures everything works 100% of the time. Instead of the old #QQQQ# you now enter #F# in your shell.txt to reference the file your shell should read from. If you wish to append (prepending isn't possible at the moment (and would be impossible with this syntax)) something at the end of this file, do so like this: #Fxxx# to append xxx. For example, something useful to append would be #F;read;# on the first line of your shell.txt, so your shell will pauze after running<commit_after>// vimshell.cpp : Defines the entry point for the application. // #include "vimshell.h" #include <iostream> #include <fstream> #include <string> #include <windows.h> #include <shellapi.h> bool cvtLPW2stdstring(std::string& s, const LPWSTR pw, UINT codepage = CP_ACP) { bool res = false; char* p = 0; int bsz; bsz = WideCharToMultiByte(codepage, 0, pw,-1, 0,0, 0,0); if (bsz > 0) { p = new char[bsz]; int rc = WideCharToMultiByte(codepage, 0, pw,-1, p,bsz, 0,0); if (rc != 0) { p[bsz-1] = 0; s = p; res = true; } } delete [] p; return res; } std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace ) { size_t uPos = 0; size_t uFindLen = tFind.length(); size_t uReplaceLen = tReplace.length(); if( uFindLen == 0 ) { return tInput; } while((uPos = tInput.find( tFind, uPos )) != std::string::npos) { tInput.replace( uPos, uFindLen, tReplace ); uPos += uReplaceLen; } return tInput; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { int count; //MessageBox(0, lpCmdLine, 0, 0); LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count); std::string currentDir; cvtLPW2stdstring(currentDir, strings[0]); // Cut off the filename while((currentDir.length() > 0) && (currentDir[currentDir.length()-1] != '/') && (currentDir[currentDir.length()-1] != '\\')) { currentDir = currentDir.substr(0, currentDir.length()-1); } if(currentDir.length() > 0 && currentDir[0] == '"') currentDir = currentDir.substr(1); std::string filename = currentDir + std::string("shell.txt"); std::ifstream fileIn(filename.c_str()); if(!fileIn) { MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0); return 1; } std::string argumentshellcommand; std::string silentshellcommand; std::string interactiveshellcommand; std::getline(fileIn, argumentshellcommand); std::getline(fileIn, silentshellcommand); std::getline(fileIn, interactiveshellcommand); std::string args = lpCmdLine; while(args.length() > 0 && args[0] == ' ') args = args.substr(1); bool execSilently = false; if(args.length() > 3 && args[0] == '-' && args[1] == 's' && args[2] == ' ') { args = args.substr(3); execSilently = true; } size_t spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); std::string cmd; if(spacepos == std::string::npos) args = ""; std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand; if(args.length() == 0) { cmd = interactiveshellcommand; } else { int start = argcmd.find('#F'); int end = argcmd.find('#', start+1); //MessageBox(0, argcmd.c_str(), 0,0); if(start == std::string::npos || end == std::string::npos) MessageBox(0, "Check your shell.txt", 0,0); std::string appendage = argcmd.substr(start+1, end-start-1); std::string filename = "C:/vimshelltmp.txt"; cmd = argcmd.replace(start-1, end-start+2, filename); std::ofstream f(filename.c_str()); f << args.c_str() << appendage; f.close(); } //MessageBox(0,cmd.c_str(), 0,0); std::ofstream f("C:/output.txt"); f << cmd.c_str(); f.close(); STARTUPINFO si = { sizeof(STARTUPINFO) }; si.dwFlags = STARTF_USESHOWWINDOW; if(execSilently) si.wShowWindow = SW_HIDE; else si.wShowWindow = SW_SHOW; PROCESS_INFORMATION pi; char arr[1024]; strcpy_s(arr, 1024, cmd.c_str()); CreateProcess(NULL, arr, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); DWORD exit_code; GetExitCodeProcess(pi.hProcess, &exit_code); return exit_code; } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2018 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #define BOOST_TEST_MODULE "MultiViewGeometry/Essential Matrix" #include <DO/Sara/FeatureMatching.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/ImageProcessing/GemmBasedConvolution.hpp> #include <boost/test/unit_test.hpp> #include <iomanip> #include <sstream> using namespace std; using namespace DO::Sara; void load(Image<Rgb8>& image1, Image<Rgb8>& image2, Set<OERegion, RealDescriptor>& keys1, Set<OERegion, RealDescriptor>& keys2, // vector<Match>& matches) { cout << "Loading images" << endl; auto data_dir = std::string{"/home/david/Desktop/Datasets/sfm/castle_int"}; auto file1 = "0000.png"; auto file2 = "0001.png"; image1 = imread<Rgb8>(data_dir + "/" + file1); image2 = imread<Rgb8>(data_dir + "/" + file2); #ifdef COMPUTE_KEYPOINTS cout << "Computing/Reading keypoints" << endl; auto sifts1 = compute_sift_keypoints(image1.convert<float>()); auto sifts2 = compute_sift_keypoints(image2.convert<float>()); keys1.append(sifts1); keys2.append(sifts2); cout << "Image 1: " << keys1.size() << " keypoints" << endl; cout << "Image 2: " << keys2.size() << " keypoints" << endl; write_keypoints(sifts1.features, sifts1.descriptors, data_dir + "/" + "0000.key"); write_keypoints(sifts2.features, sifts2.descriptors, data_dir + "/" + "0001.key"); #else read_keypoints(keys1.features, keys1.descriptors, data_dir + "/" + "0000.key"); read_keypoints(keys2.features, keys2.descriptors, data_dir + "/" + "0001.key"); #endif // Compute/read matches cout << "Computing Matches" << endl; AnnMatcher matcher{keys1, keys2, 1.0f}; matches = matcher.compute_matches(); cout << matches.size() << " matches" << endl; // Debug this. //write_matches(matches, data_dir + "/" + "0000_0001.match"); } // NumPy-like interface for Tensors auto range(int n) -> Tensor_<int, 1> { auto indices = Tensor_<int, 1>{n}; std::iota(indices.begin(), indices.end(), 0); return indices; } auto random_shuffle(const Tensor_<int, 1>& x) -> Tensor_<int, 1> { Tensor_<int, 1> x_shuffled = x; std::random_shuffle(x_shuffled.begin(), x_shuffled.end()); return x_shuffled; } auto random_samples(int num_samples, int sample_size, int num_data_points) -> Tensor_<int, 2> { auto indices = range(num_data_points); auto samples = Tensor_<int, 2>{sample_size, num_samples}; for (int i = 0; i < sample_size; ++i) samples[i].flat_array() = random_shuffle(indices).flat_array().head(num_samples); samples = samples.transpose({1, 0}); return samples; } // Data transformations. auto extract_centers(const std::vector<OERegion>& features) -> Tensor_<float, 2> { auto centers = Tensor_<float, 2>(features.size(), 3); auto mat = centers.matrix(); for (auto i = 0; i < centers.size(0); ++i) mat.row(i) << features[i].x(), features[i].y(), 1.f; return centers; } auto to_point_indices(const Tensor_<int, 2>& samples, const Tensor_<int, 2>& matches) -> Tensor_<int, 3> { const auto num_samples = samples.size(0); const auto sample_size = samples.size(1); auto point_indices = Tensor_<int, 3>{num_samples, sample_size, 2}; for (auto s = 0; s < num_samples; ++s) for (auto m = 0; m < sample_size; ++m) point_indices[s][m].flat_array() = matches[samples(s, m)].flat_array(); return point_indices; } auto to_coordinates(const Tensor_<int, 3>& point_indices, const Tensor_<float, 2>& p1, const Tensor_<float, 2>& p2) -> Tensor_<float, 4> { auto num_samples = point_indices.size(0); auto sample_size = point_indices.size(1); auto num_points = 2; auto coords_dim = 2; auto p = Tensor_<float, 4>{{num_samples, sample_size, num_points, coords_dim}}; for (auto s = 0; s < num_samples; ++s) for (auto m = 0; m < sample_size; ++m) { auto p1_idx = point_indices(s, m, 0); auto p2_idx = point_indices(s, m, 1); p[s][m][0].flat_array() = p1[p1_idx].flat_array(); p[s][m][1].flat_array() = p2[p2_idx].flat_array(); } return p; } // Point transformations. auto compute_normalizer(const Tensor_<float, 2>& X) -> Matrix3f { const RowVector3f min = X.matrix().colwise().minCoeff(); const RowVector3f max = X.matrix().colwise().maxCoeff(); const Matrix2f scale = (max - min).cwiseInverse().head(2).asDiagonal(); Matrix3f T = Matrix3f::Zero(); T.topLeftCorner<2, 2>() = scale; T.col(2) << -min.cwiseQuotient(max - min).transpose().head(2), 1.f; return T; } auto apply_transform(const Matrix3f& T, const Tensor_<float, 2>& X) -> Tensor_<float, 2> { auto TX = Tensor_<float, 2>{X.sizes()}; auto TX_ = TX.colmajor_view().matrix(); TX_ = T * X.colmajor_view().matrix(); TX_.array().rowwise() /= TX_.array().row(2); return TX; } BOOST_AUTO_TEST_SUITE(TestMultiViewGeometry) BOOST_AUTO_TEST_CASE(test_range) { auto a = range(3); BOOST_CHECK(vec(a) == Vector3i(0, 1, 2)); } BOOST_AUTO_TEST_CASE(test_random_shuffle) { auto a = range(4); a = random_shuffle(a); BOOST_CHECK(vec(a) != Vector4i(0, 1, 2, 3)); } BOOST_AUTO_TEST_CASE(test_random_samples) { constexpr auto num_samples = 2; constexpr auto sample_size = 5; constexpr auto num_data_points = 10; auto samples = random_samples(num_samples, sample_size, num_data_points); BOOST_CHECK_EQUAL(samples.size(0), num_samples); BOOST_CHECK_EQUAL(samples.size(1), sample_size); BOOST_CHECK(samples.matrix().minCoeff() >= 0); BOOST_CHECK(samples.matrix().maxCoeff() < 10); } BOOST_AUTO_TEST_CASE(test_extract_centers) { auto features = std::vector<OERegion>{{Point2f::Ones() * 0, 1.f}, {Point2f::Ones() * 1, 1.f}, {Point2f::Ones() * 2, 1.f}}; auto centers = extract_centers(features); auto expected_centers = Tensor_<float, 2>{centers.sizes()}; expected_centers.matrix() << 0, 0, 1, 1, 1, 1, 2, 2, 1; BOOST_CHECK(centers.matrix() == expected_centers.matrix()); } BOOST_AUTO_TEST_CASE(test_to_point_indices) { constexpr auto num_matches = 5; constexpr auto num_samples = 2; constexpr auto sample_size = 4; auto matches = Tensor_<int, 2>{num_matches, 2}; matches.matrix() << 0, 0, 1, 1, 2, 2, 3, 3, 4, 0; auto samples = Tensor_<int, 2>{num_samples, sample_size}; samples.matrix() << 0, 1, 2, 3, 4, 2, 3, 1; auto point_indices = to_point_indices(samples, matches); auto expected_point_indices = Tensor_<int, 3>{num_samples, sample_size, 2}; expected_point_indices[0].matrix() << 0, 0, 1, 1, 2, 2, 3, 3; expected_point_indices[1].matrix() << 4, 0, 2, 2, 3, 3, 1, 1; BOOST_CHECK(vec(point_indices) == vec(expected_point_indices)); } template <typename T> void print_3d_array(const TensorView_<T, 3>& x) { const auto max = x.flat_array().abs().maxCoeff(); std::stringstream ss; ss << max; const auto pad_size = ss.str().size(); cout << "["; for (auto i = 0; i < x.size(0); ++i) { cout << "["; for (auto j = 0; j < x.size(1); ++j) { cout << "["; for (auto k = 0; k < x.size(2); ++k) { cout << std::setw(pad_size) << x(i,j,k); if (k != x.size(2) - 1) cout << ", "; } cout << "]"; if (j != x.size(1) - 1) cout << ", "; else cout << "]"; } if (i != x.size(0) - 1) cout << ",\n "; } cout << "]" << endl; } BOOST_AUTO_TEST_CASE(test_to_coordinates) { constexpr auto num_matches = 5; constexpr auto num_samples = 2; constexpr auto sample_size = 4; const auto features1 = std::vector<OERegion>{{Point2f::Ones() * 0, 1.f}, {Point2f::Ones() * 1, 1.f}, {Point2f::Ones() * 2, 1.f}}; const auto features2 = std::vector<OERegion>{{Point2f::Ones() * 1, 1.f}, {Point2f::Ones() * 2, 1.f}, {Point2f::Ones() * 3, 1.f}}; const auto points1 = extract_centers(features1); const auto points2 = extract_centers(features2); auto matches = Tensor_<int, 2>{num_matches, 2}; matches.matrix() << 0, 0, 1, 1, 2, 2, 0, 1, 1, 2; auto samples = Tensor_<int, 2>{num_samples, sample_size}; samples.matrix() << 0, 1, 2, 3, 1, 2, 3, 4; const auto point_indices = to_point_indices(samples, matches); const auto coords = to_coordinates(point_indices, points1, points2); // N K P C auto expected_coords = Tensor_<float, 4>{{num_samples, sample_size, 2, 2}}; expected_coords[0].flat_array() << 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, 2.f, 2.f, 2.f, 2.f, 3.f, 3.f, 0.f, 0.f, 2.f, 2.f; expected_coords[1].flat_array() << 1.f, 1.f, 2.f, 2.f, 2.f, 2.f, 3.f, 3.f, 0.f, 0.f, 2.f, 2.f, 1.f, 1.f, 3.f, 3.f; BOOST_CHECK(vec(expected_coords) == vec(coords)); BOOST_CHECK(expected_coords.sizes() == coords.sizes()); const auto coords_t = coords.transpose({0, 2, 1, 3}); const auto sample1 = coords_t[0]; auto expected_sample1 = Tensor_<float, 3>{sample1.sizes()}; expected_sample1.flat_array() << // P1 0.f, 0.f, 1.f, 1.f, 2.f, 2.f, 0.f, 0.f, // P2 1.f, 1.f, 2.f, 2.f, 3.f, 3.f, 2.f, 2.f; //print_3d_array(expected_sample1); //print_3d_array(sample1); BOOST_CHECK(vec(expected_sample1) == vec(sample1)); } BOOST_AUTO_TEST_CASE(test_compute_normalizer) { auto X = Tensor_<float, 2>{3, 3}; X.matrix() << 1, 1, 1, 2, 2, 1, 3, 3, 1; auto T = compute_normalizer(X); Matrix3f expected_T; expected_T << 0.5, 0.0, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0; BOOST_CHECK((T - expected_T).norm() < 1e-12); } BOOST_AUTO_TEST_CASE(test_apply_transform) { auto X = Tensor_<float, 2>{3, 3}; X.matrix() << 1, 1, 1, 2, 2, 1, 3, 3, 1; auto T = compute_normalizer(X); auto TX = apply_transform(T, X); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>WIP: fix tests.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2018 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #define BOOST_TEST_MODULE "MultiViewGeometry/Essential Matrix" #include <DO/Sara/FeatureMatching.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/ImageProcessing/GemmBasedConvolution.hpp> #include <boost/test/unit_test.hpp> #include <iomanip> #include <sstream> using namespace std; using namespace DO::Sara; template <typename T> void print_3d_array(const TensorView_<T, 3>& x) { const auto max = x.flat_array().abs().maxCoeff(); std::stringstream ss; ss << max; const auto pad_size = ss.str().size(); cout << "["; for (auto i = 0; i < x.size(0); ++i) { cout << "["; for (auto j = 0; j < x.size(1); ++j) { cout << "["; for (auto k = 0; k < x.size(2); ++k) { cout << std::setw(pad_size) << x(i,j,k); if (k != x.size(2) - 1) cout << ", "; } cout << "]"; if (j != x.size(1) - 1) cout << ", "; else cout << "]"; } if (i != x.size(0) - 1) cout << ",\n "; } cout << "]" << endl; } void print_3d_array(const TensorView_<float, 3>& x) { cout << "["; for (auto i = 0; i < x.size(0); ++i) { cout << "["; for (auto j = 0; j < x.size(1); ++j) { cout << "["; for (auto k = 0; k < x.size(2); ++k) { cout << fixed << x(i,j,k); if (k != x.size(2) - 1) cout << ", "; } cout << "]"; if (j != x.size(1) - 1) cout << ", "; else cout << "]"; } if (i != x.size(0) - 1) cout << ",\n "; } cout << "]" << endl; } void load(Image<Rgb8>& image1, Image<Rgb8>& image2, Set<OERegion, RealDescriptor>& keys1, Set<OERegion, RealDescriptor>& keys2, // vector<Match>& matches) { cout << "Loading images" << endl; auto data_dir = std::string{"/home/david/Desktop/Datasets/sfm/castle_int"}; auto file1 = "0000.png"; auto file2 = "0001.png"; image1 = imread<Rgb8>(data_dir + "/" + file1); image2 = imread<Rgb8>(data_dir + "/" + file2); #ifdef COMPUTE_KEYPOINTS cout << "Computing/Reading keypoints" << endl; auto sifts1 = compute_sift_keypoints(image1.convert<float>()); auto sifts2 = compute_sift_keypoints(image2.convert<float>()); keys1.append(sifts1); keys2.append(sifts2); cout << "Image 1: " << keys1.size() << " keypoints" << endl; cout << "Image 2: " << keys2.size() << " keypoints" << endl; write_keypoints(sifts1.features, sifts1.descriptors, data_dir + "/" + "0000.key"); write_keypoints(sifts2.features, sifts2.descriptors, data_dir + "/" + "0001.key"); #else read_keypoints(keys1.features, keys1.descriptors, data_dir + "/" + "0000.key"); read_keypoints(keys2.features, keys2.descriptors, data_dir + "/" + "0001.key"); #endif // Compute/read matches cout << "Computing Matches" << endl; AnnMatcher matcher{keys1, keys2, 1.0f}; matches = matcher.compute_matches(); cout << matches.size() << " matches" << endl; // Debug this. //write_matches(matches, data_dir + "/" + "0000_0001.match"); } // NumPy-like interface for Tensors auto range(int n) -> Tensor_<int, 1> { auto indices = Tensor_<int, 1>{n}; std::iota(indices.begin(), indices.end(), 0); return indices; } auto random_shuffle(const Tensor_<int, 1>& x) -> Tensor_<int, 1> { Tensor_<int, 1> x_shuffled = x; std::random_shuffle(x_shuffled.begin(), x_shuffled.end()); return x_shuffled; } auto random_samples(int num_samples, int sample_size, int num_data_points) -> Tensor_<int, 2> { auto indices = range(num_data_points); auto samples = Tensor_<int, 2>{sample_size, num_samples}; for (int i = 0; i < sample_size; ++i) samples[i].flat_array() = random_shuffle(indices).flat_array().head(num_samples); samples = samples.transpose({1, 0}); return samples; } // Data transformations. auto extract_centers(const std::vector<OERegion>& features) -> Tensor_<float, 2> { auto centers = Tensor_<float, 2>{int(features.size()), 2}; auto mat = centers.matrix(); for (auto i = 0; i < centers.size(0); ++i) mat.row(i) = features[i].center().transpose(); return centers; } auto homogeneous(const TensorView_<float, 2>& x) -> Tensor_<float, 2> { auto X = Tensor_<float, 2>(x.size(0), x.size(1) + 1); X.matrix().leftCols(x.size(1)) = x.matrix(); X.matrix().col(x.size(1)).setOnes(); return X; } auto to_point_indices(const TensorView_<int, 2>& samples, const TensorView_<int, 2>& matches) -> Tensor_<int, 3> { const auto num_samples = samples.size(0); const auto sample_size = samples.size(1); auto point_indices = Tensor_<int, 3>{num_samples, sample_size, 2}; for (auto s = 0; s < num_samples; ++s) for (auto m = 0; m < sample_size; ++m) point_indices[s][m].flat_array() = matches[samples(s, m)].flat_array(); return point_indices; } auto to_coordinates(const Tensor_<int, 3>& point_indices, const Tensor_<float, 2>& p1, const Tensor_<float, 2>& p2) -> Tensor_<float, 4> { const auto num_samples = point_indices.size(0); const auto sample_size = point_indices.size(1); const auto num_points = 2; const auto coords_dim = p1.size(1); auto p = Tensor_<float, 4>{{num_samples, sample_size, num_points, coords_dim}}; for (auto s = 0; s < num_samples; ++s) for (auto m = 0; m < sample_size; ++m) { auto p1_idx = point_indices(s, m, 0); auto p2_idx = point_indices(s, m, 1); p[s][m][0].flat_array() = p1[p1_idx].flat_array(); p[s][m][1].flat_array() = p2[p2_idx].flat_array(); } return p; } // Point transformations. auto compute_normalizer(const Tensor_<float, 2>& X) -> Matrix3f { const RowVector3f min = X.matrix().colwise().minCoeff(); const RowVector3f max = X.matrix().colwise().maxCoeff(); const Matrix2f scale = (max - min).cwiseInverse().head(2).asDiagonal(); Matrix3f T = Matrix3f::Zero(); T.topLeftCorner<2, 2>() = scale; T.col(2) << -min.cwiseQuotient(max - min).transpose().head(2), 1.f; return T; } auto apply_transform(const Matrix3f& T, const Tensor_<float, 2>& X) -> Tensor_<float, 2> { auto TX = Tensor_<float, 2>{X.sizes()}; auto TX_ = TX.colmajor_view().matrix(); TX_ = T * X.colmajor_view().matrix(); TX_.array().rowwise() /= TX_.array().row(2); return TX; } BOOST_AUTO_TEST_SUITE(TestMultiViewGeometry) BOOST_AUTO_TEST_CASE(test_range) { auto a = range(3); BOOST_CHECK(vec(a) == Vector3i(0, 1, 2)); } BOOST_AUTO_TEST_CASE(test_random_shuffle) { auto a = range(4); a = random_shuffle(a); BOOST_CHECK(vec(a) != Vector4i(0, 1, 2, 3)); } BOOST_AUTO_TEST_CASE(test_random_samples) { constexpr auto num_samples = 2; constexpr auto sample_size = 5; constexpr auto num_data_points = 10; auto samples = random_samples(num_samples, sample_size, num_data_points); BOOST_CHECK_EQUAL(samples.size(0), num_samples); BOOST_CHECK_EQUAL(samples.size(1), sample_size); BOOST_CHECK(samples.matrix().minCoeff() >= 0); BOOST_CHECK(samples.matrix().maxCoeff() < 10); } BOOST_AUTO_TEST_CASE(test_extract_centers) { auto features = std::vector<OERegion>{{Point2f::Ones() * 0, 1.f}, {Point2f::Ones() * 1, 1.f}, {Point2f::Ones() * 2, 1.f}}; const auto x = extract_centers(features); auto expected_x = Tensor_<float, 2>{x.sizes()}; expected_x.matrix() << 0, 0, 1, 1, 2, 2; BOOST_CHECK(x.matrix() == expected_x.matrix()); const auto X = homogeneous(x); auto expected_X = Tensor_<float, 2>{X.sizes()}; expected_X.matrix() << 0, 0, 1, 1, 1, 1, 2, 2, 1; BOOST_CHECK(X.matrix() == expected_X.matrix()); } BOOST_AUTO_TEST_CASE(test_to_point_indices) { constexpr auto num_matches = 5; constexpr auto num_samples = 2; constexpr auto sample_size = 4; auto matches = Tensor_<int, 2>{num_matches, 2}; matches.matrix() << 0, 0, 1, 1, 2, 2, 3, 3, 4, 0; auto samples = Tensor_<int, 2>{num_samples, sample_size}; samples.matrix() << 0, 1, 2, 3, 4, 2, 3, 1; auto point_indices = to_point_indices(samples, matches); auto expected_point_indices = Tensor_<int, 3>{num_samples, sample_size, 2}; expected_point_indices[0].matrix() << 0, 0, 1, 1, 2, 2, 3, 3; expected_point_indices[1].matrix() << 4, 0, 2, 2, 3, 3, 1, 1; BOOST_CHECK(vec(point_indices) == vec(expected_point_indices)); } BOOST_AUTO_TEST_CASE(test_to_coordinates) { constexpr auto num_matches = 5; constexpr auto num_samples = 2; constexpr auto sample_size = 4; const auto features1 = std::vector<OERegion>{{Point2f::Ones() * 0, 1.f}, {Point2f::Ones() * 1, 1.f}, {Point2f::Ones() * 2, 1.f}}; const auto features2 = std::vector<OERegion>{{Point2f::Ones() * 1, 1.f}, {Point2f::Ones() * 2, 1.f}, {Point2f::Ones() * 3, 1.f}}; const auto points1 = extract_centers(features1); const auto points2 = extract_centers(features2); auto matches = Tensor_<int, 2>{num_matches, 2}; matches.matrix() << 0, 0, 1, 1, 2, 2, 0, 1, 1, 2; auto samples = Tensor_<int, 2>{num_samples, sample_size}; samples.matrix() << 0, 1, 2, 3, 1, 2, 3, 4; const auto point_indices = to_point_indices(samples, matches); const auto coords = to_coordinates(point_indices, points1, points2); // N K P C auto expected_coords = Tensor_<float, 4>{{num_samples, sample_size, 2, 2}}; expected_coords[0].flat_array() << 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, 2.f, 2.f, 2.f, 2.f, 3.f, 3.f, 0.f, 0.f, 2.f, 2.f; expected_coords[1].flat_array() << 1.f, 1.f, 2.f, 2.f, 2.f, 2.f, 3.f, 3.f, 0.f, 0.f, 2.f, 2.f, 1.f, 1.f, 3.f, 3.f; BOOST_CHECK(vec(expected_coords) == vec(coords)); BOOST_CHECK(expected_coords.sizes() == coords.sizes()); const auto coords_t = coords.transpose({0, 2, 1, 3}); const auto sample1 = coords_t[0]; auto expected_sample1 = Tensor_<float, 3>{sample1.sizes()}; expected_sample1.flat_array() << // P1 0.f, 0.f, 1.f, 1.f, 2.f, 2.f, 0.f, 0.f, // P2 1.f, 1.f, 2.f, 2.f, 3.f, 3.f, 2.f, 2.f; //print_3d_array(expected_sample1); //print_3d_array(sample1); BOOST_CHECK(vec(expected_sample1) == vec(sample1)); } BOOST_AUTO_TEST_CASE(test_compute_normalizer) { auto X = Tensor_<float, 2>{3, 3}; X.matrix() << 1, 1, 1, 2, 2, 1, 3, 3, 1; auto T = compute_normalizer(X); Matrix3f expected_T; expected_T << 0.5, 0.0, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0; BOOST_CHECK((T - expected_T).norm() < 1e-12); } BOOST_AUTO_TEST_CASE(test_apply_transform) { auto X = Tensor_<float, 2>{3, 3}; X.matrix() << 1, 1, 1, 2, 2, 1, 3, 3, 1; auto T = compute_normalizer(X); auto TX = apply_transform(T, X); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/******************************************************************************** $Header$ purpose: notes: to do: author(s): - Dirk Farin, farin@ti.uni-mannheim.de University Mannheim, Dept. Circuitry and Simulation L 15,16 room 410 / D-68131 Mannheim / Germany modifications: 24/Jan/2002 - Dirk Farin - Complete reimplementation based on old Image type. 02/Jun/1999 - Dirk Farin - first implementation ******************************************************************************** Copyright (C) 2002 Dirk Farin This program is distributed under GNU Public License (GPL) as outlined in the COPYING file that comes with the source distribution. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ********************************************************************************/ #ifndef LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH #define LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH #include <assert.h> #include <libvideogfx/types.hh> #include <libvideogfx/graphics/basic/bitmap.hh> #include <algorithm> enum Colorspace { Colorspace_RGB, Colorspace_YUV, Colorspace_Greyscale, Colorspace_HSV, Colorspace_Invalid }; enum ChromaFormat { /** Subsampling h:2 v:2 */ Chroma_420, /** Subsampling h:2 v:1 */ Chroma_422, /** No subsampling */ Chroma_444, Chroma_Invalid }; enum BitmapChannel { Bitmap_Red = 0, Bitmap_Green = 1, Bitmap_Blue = 2, Bitmap_Y = 0, Bitmap_Cb = 1, Bitmap_Cr = 2, Bitmap_U = 1, Bitmap_V = 2, Bitmap_Hue = 0, Bitmap_Saturation = 1, Bitmap_Value = 2, Bitmap_Alpha=3 }; /** Check if chroma is horizontally subsampled. Usage of the more general #ChromaSubH()# is recommended. */ inline bool IsSubH(ChromaFormat cf) { return cf != Chroma_444; } /** Check if chroma is vertically subsampled. Usage of the more general #ChromaSubV()# is recommended. */ inline bool IsSubV(ChromaFormat cf) { return cf == Chroma_420; } /** Get horizontal subsampling factor. */ inline int ChromaSubH(ChromaFormat cf) { return (cf != Chroma_444) ? 2 : 1; } /** Get vertical subsampling factor. */ inline int ChromaSubV(ChromaFormat cf) { return (cf == Chroma_420) ? 2 : 1; } struct ImageParam { ImageParam() : width(0), height(0), halign(1), valign(1), border(0), colorspace(Colorspace_Invalid), has_alpha(false), chroma(Chroma_420), reduced_chroma_resolution(true), chroma_border(-1), chroma_halign(-1), chroma_valign(-1) { } int width,height; int halign,valign; int border; Colorspace colorspace; bool has_alpha; ChromaFormat chroma; bool reduced_chroma_resolution; int chroma_border; int chroma_halign; int chroma_valign; #if 0 /** If set to #true#: don't allow the alignment or the border to be greater than specified. {\bf Explanation}: As it is more efficient to keep and older bitmap if the new one is smaller than the old one, the old one is sometimes used instead of creating a new one. This does not work if you are depending on the exact memory layout of the image. So you can disable it by setting exact\_size to true. */ bool exact_size; #endif int AskChromaWidth() const { return (width +ChromaSubH(chroma)-1)/ChromaSubH(chroma); } int AskChromaHeight() const { return (height+ChromaSubV(chroma)-1)/ChromaSubV(chroma); } void AskChromaSizes(int& w,int &h) const; int AskChromaBorder() const; int AskChromaHAlign() const; int AskChromaVAlign() const; }; template <class Pel> class Image { public: virtual ~Image() { } void Create(const ImageParam&); void Release(); /// Get colorspace independent image parameters. ImageParam AskParam() const { return d_param; } int AskWidth() const { return d_param.width; } int AskHeight() const { return d_param.height; } int AskBorder() const { return d_param.border; } void GetSize(int& w,int& h) const { w=d_param.width; h=d_param.height; } Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) { return d_pm[pm_id]; } const Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) const { return d_pm[pm_id]; } Pel*const* AskFrame(BitmapChannel pm_id) { return d_pm[pm_id].AskFrame(); } const Pel*const* AskFrame(BitmapChannel pm_id) const { return d_pm[pm_id].AskFrame(); } /** Replace a complete bitmap. Note that the new bitmap either has to be empty or has to be exactly the same size as the old one. Furthermore you are responsible that all alignments and the border size is sufficient for your application. This is not checked! If you insert or remove (by replacing a bitmap by an empty one) an alpha bitmap, the alphamask-flag in ImageParam will be set accordingly. */ void ReplaceBitmap(BitmapChannel id,const Bitmap<Pel>&); /// Set new image parameters. void SetParam(const ImageParam& param) { d_param=param; } Image<Pel> Clone() const; Image<Pel> CreateSubView (int x0,int y0,int w,int h) const; Image<Pel> CreateFieldView(bool top) const; bool IsEmpty() const { return d_pm[0].IsEmpty(); } Pel*const* AskFrameR() { return d_pm[Bitmap_Red].AskFrame(); } const Pel*const* AskFrameR() const { return d_pm[Bitmap_Red].AskFrame(); } Pel*const* AskFrameG() { return d_pm[Bitmap_Green].AskFrame(); } const Pel*const* AskFrameG() const { return d_pm[Bitmap_Green].AskFrame(); } Pel*const* AskFrameB() { return d_pm[Bitmap_Blue].AskFrame(); } const Pel*const* AskFrameB() const { return d_pm[Bitmap_Blue].AskFrame(); } Pel*const* AskFrameY() { return d_pm[Bitmap_Y].AskFrame(); } const Pel*const* AskFrameY() const { return d_pm[Bitmap_Y].AskFrame(); } Pel*const* AskFrameU() { return d_pm[Bitmap_U].AskFrame(); } const Pel*const* AskFrameU() const { return d_pm[Bitmap_U].AskFrame(); } Pel*const* AskFrameV() { return d_pm[Bitmap_V].AskFrame(); } const Pel*const* AskFrameV() const { return d_pm[Bitmap_V].AskFrame(); } Pel*const* AskFrameCb() { return d_pm[Bitmap_Cb].AskFrame(); } const Pel*const* AskFrameCb() const { return d_pm[Bitmap_Cb].AskFrame(); } Pel*const* AskFrameCr() { return d_pm[Bitmap_Cr].AskFrame(); } const Pel*const* AskFrameCr() const { return d_pm[Bitmap_Cr].AskFrame(); } Pel*const* AskFrameA() { return d_pm[Bitmap_Alpha].AskFrame(); } const Pel*const* AskFrameA() const { return d_pm[Bitmap_Alpha].AskFrame(); } Bitmap<Pel>& AskBitmapR() { return d_pm[Bitmap_Red]; } const Bitmap<Pel>& AskBitmapR() const { return d_pm[Bitmap_Red]; } Bitmap<Pel>& AskBitmapG() { return d_pm[Bitmap_Green]; } const Bitmap<Pel>& AskBitmapG() const { return d_pm[Bitmap_Green]; } Bitmap<Pel>& AskBitmapB() { return d_pm[Bitmap_Blue]; } const Bitmap<Pel>& AskBitmapB() const { return d_pm[Bitmap_Blue]; } Bitmap<Pel>& AskBitmapY() { return d_pm[Bitmap_Y]; } const Bitmap<Pel>& AskBitmapY() const { return d_pm[Bitmap_Y]; } Bitmap<Pel>& AskBitmapU() { return d_pm[Bitmap_U]; } const Bitmap<Pel>& AskBitmapU() const { return d_pm[Bitmap_U]; } Bitmap<Pel>& AskBitmapV() { return d_pm[Bitmap_V]; } const Bitmap<Pel>& AskBitmapV() const { return d_pm[Bitmap_V]; } Bitmap<Pel>& AskBitmapCb() { return d_pm[Bitmap_Cb]; } const Bitmap<Pel>& AskBitmapCb() const { return d_pm[Bitmap_Cb]; } Bitmap<Pel>& AskBitmapCr() { return d_pm[Bitmap_Cr]; } const Bitmap<Pel>& AskBitmapCr() const { return d_pm[Bitmap_Cr]; } Bitmap<Pel>& AskBitmapA() { return d_pm[Bitmap_Alpha]; } const Bitmap<Pel>& AskBitmapA() const { return d_pm[Bitmap_Alpha]; } bool IsShared() const { for (int i=0;i<4;i++) if (d_pm[i].IsShared()) return true; return false; } private: Bitmap<Pel> d_pm[4]; ImageParam d_param; }; template <class Pel> void Image<Pel>::Create(const ImageParam& param) { d_pm[0].Create(param.width, param.height, param.border,param.halign,param.valign); switch (param.colorspace) { case Colorspace_RGB: case Colorspace_HSV: d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign); d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign); break; case Colorspace_YUV: if (param.reduced_chroma_resolution) { d_pm[1].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(), param.AskChromaHAlign(),param.AskChromaVAlign()); d_pm[2].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(), param.AskChromaHAlign(),param.AskChromaVAlign()); } else { d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign); d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign); } break; case Colorspace_Greyscale: d_pm[1].Release(); d_pm[2].Release(); break; } if (param.has_alpha) d_pm[Bitmap_Alpha].Create(param.width, param.height, param.border,param.halign,param.valign); else d_pm[Bitmap_Alpha].Release(); d_param = param; } template <class Pel> void Image<Pel>::Release() { for (int i=0;i<4;i++) d_pm[i].Release(); d_param = ImageParam(); } template <class Pel> Image<Pel> Image<Pel>::Clone() const { Image<Pel> img; for (int i=0;i<4;i++) img.d_pm[i] = d_pm[i].Clone(); img.d_param = d_param; return img; } template <class Pel> Image<Pel> Image<Pel>::CreateSubView(int x0,int y0,int w,int h) const { Image<Pel> newimg; newimg.d_param = d_param; newimg.d_param.width = w; newimg.d_param.height = h; newimg.d_param.halign = 1; newimg.d_param.valign = 1; newimg.d_param.border = 0; newimg.d_param.chroma_border = -1; newimg.d_param.chroma_halign = -1; newimg.d_param.chroma_valign = -1; if (d_param.colorspace == Colorspace_YUV) { newimg.d_pm[0] = d_pm[0].CreateSubView(x0,y0,w,h); newimg.d_pm[3] = d_pm[3].CreateSubView(x0,y0,w,h); int subh = ChromaSubH(d_param.chroma); int subv = ChromaSubV(d_param.chroma); newimg.d_pm[1] = d_pm[1].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv); newimg.d_pm[2] = d_pm[2].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv); } else { for (int i=0;i<4;i++) newimg.d_pm[i] = d_pm[i].CreateSubView(x0,y0,w,h); } return newimg; } template <class Pel> Image<Pel> Image<Pel>::CreateFieldView(bool top) const { if (!top && d_param.colorspace==Colorspace_YUV && d_param.chroma==Chroma_420 && (d_pm[0].AskHeight()%2)==0 && (d_pm[1].AskHeight()%2)==1) { AssertDescr(false,"not enough chroma information for bottom field"); } Image<Pel> newimg; newimg.d_param = d_param; for (int i=0;i<4;i++) newimg.d_pm[i] = d_pm[i].CreateFieldView(top); newimg.d_param.width = newimg.d_pm[0].AskWidth(); newimg.d_param.height = newimg.d_pm[0].AskHeight(); newimg.d_param.halign = 1; newimg.d_param.valign = 1; newimg.d_param.border = 0; newimg.d_param.chroma_border = -1; newimg.d_param.chroma_halign = -1; newimg.d_param.chroma_valign = -1; return newimg; } #endif <commit_msg>utility methods in ImageParam: scale pixel coordinates according to chroma type<commit_after>/******************************************************************************** $Header$ purpose: notes: to do: author(s): - Dirk Farin, farin@ti.uni-mannheim.de University Mannheim, Dept. Circuitry and Simulation L 15,16 room 410 / D-68131 Mannheim / Germany modifications: 24/Jan/2002 - Dirk Farin - Complete reimplementation based on old Image type. 02/Jun/1999 - Dirk Farin - first implementation ******************************************************************************** Copyright (C) 2002 Dirk Farin This program is distributed under GNU Public License (GPL) as outlined in the COPYING file that comes with the source distribution. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ********************************************************************************/ #ifndef LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH #define LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH #include <assert.h> #include <libvideogfx/types.hh> #include <libvideogfx/graphics/basic/bitmap.hh> #include <algorithm> enum Colorspace { Colorspace_RGB, Colorspace_YUV, Colorspace_Greyscale, Colorspace_HSV, Colorspace_Invalid }; enum ChromaFormat { /** Subsampling h:2 v:2 */ Chroma_420, /** Subsampling h:2 v:1 */ Chroma_422, /** No subsampling */ Chroma_444, Chroma_Invalid }; enum BitmapChannel { Bitmap_Red = 0, Bitmap_Green = 1, Bitmap_Blue = 2, Bitmap_Y = 0, Bitmap_Cb = 1, Bitmap_Cr = 2, Bitmap_U = 1, Bitmap_V = 2, Bitmap_Hue = 0, Bitmap_Saturation = 1, Bitmap_Value = 2, Bitmap_Alpha=3 }; /** Check if chroma is horizontally subsampled. Usage of the more general #ChromaSubH()# is recommended. */ inline bool IsSubH(ChromaFormat cf) { return cf != Chroma_444; } /** Check if chroma is vertically subsampled. Usage of the more general #ChromaSubV()# is recommended. */ inline bool IsSubV(ChromaFormat cf) { return cf == Chroma_420; } /** Get horizontal subsampling factor. */ inline int ChromaSubH(ChromaFormat cf) { return (cf != Chroma_444) ? 2 : 1; } /** Get vertical subsampling factor. */ inline int ChromaSubV(ChromaFormat cf) { return (cf == Chroma_420) ? 2 : 1; } struct ImageParam { ImageParam() : width(0), height(0), halign(1), valign(1), border(0), colorspace(Colorspace_Invalid), has_alpha(false), chroma(Chroma_444), reduced_chroma_resolution(true), chroma_border(-1), chroma_halign(-1), chroma_valign(-1) { } int width,height; int halign,valign; int border; Colorspace colorspace; bool has_alpha; ChromaFormat chroma; bool reduced_chroma_resolution; int chroma_border; int chroma_halign; int chroma_valign; #if 0 /** If set to #true#: don't allow the alignment or the border to be greater than specified. {\bf Explanation}: As it is more efficient to keep and older bitmap if the new one is smaller than the old one, the old one is sometimes used instead of creating a new one. This does not work if you are depending on the exact memory layout of the image. So you can disable it by setting exact\_size to true. */ bool exact_size; #endif int AskChromaWidth() const { if (colorspace==Colorspace_YUV) return (width +ChromaSubH(chroma)-1)/ChromaSubH(chroma); else return width; } int AskChromaHeight() const { if (colorspace==Colorspace_YUV) return (height+ChromaSubV(chroma)-1)/ChromaSubV(chroma); else return height; } void AskChromaSizes(int& w,int &h) const; int AskChromaBorder() const; int AskChromaHAlign() const; int AskChromaVAlign() const; int BitmapWidth (BitmapChannel b) const { if (b==1||b==2) return AskChromaWidth(); else return width; } int BitmapHeight(BitmapChannel b) const { if (b==1||b==2) return AskChromaHeight(); else return height; } int ChromaScaleH(BitmapChannel b,int x) const { if ((b==1||b==2) && colorspace==Colorspace_YUV) return x/ChromaSubH(chroma); else return x; } int ChromaScaleV(BitmapChannel b,int y) const { if ((b==1||b==2) && colorspace==Colorspace_YUV) return y/ChromaSubV(chroma); else return y; } }; template <class Pel> class Image { public: virtual ~Image() { } void Create(const ImageParam&); void Release(); /// Get colorspace independent image parameters. ImageParam AskParam() const { return d_param; } int AskWidth() const { return d_param.width; } int AskHeight() const { return d_param.height; } int AskBorder() const { return d_param.border; } void GetSize(int& w,int& h) const { w=d_param.width; h=d_param.height; } Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) { return d_pm[pm_id]; } const Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) const { return d_pm[pm_id]; } Pel*const* AskFrame(BitmapChannel pm_id) { return d_pm[pm_id].AskFrame(); } const Pel*const* AskFrame(BitmapChannel pm_id) const { return d_pm[pm_id].AskFrame(); } /** Replace a complete bitmap. Note that the new bitmap either has to be empty or has to be exactly the same size as the old one. Furthermore you are responsible that all alignments and the border size is sufficient for your application. This is not checked! If you insert or remove (by replacing a bitmap by an empty one) an alpha bitmap, the alphamask-flag in ImageParam will be set accordingly. */ void ReplaceBitmap(BitmapChannel id,const Bitmap<Pel>&); /// Set new image parameters. void SetParam(const ImageParam& param) { d_param=param; } Image<Pel> Clone() const; Image<Pel> CreateSubView (int x0,int y0,int w,int h) const; Image<Pel> CreateFieldView(bool top) const; bool IsEmpty() const { return d_pm[0].IsEmpty(); } Pel*const* AskFrameR() { return d_pm[Bitmap_Red].AskFrame(); } const Pel*const* AskFrameR() const { return d_pm[Bitmap_Red].AskFrame(); } Pel*const* AskFrameG() { return d_pm[Bitmap_Green].AskFrame(); } const Pel*const* AskFrameG() const { return d_pm[Bitmap_Green].AskFrame(); } Pel*const* AskFrameB() { return d_pm[Bitmap_Blue].AskFrame(); } const Pel*const* AskFrameB() const { return d_pm[Bitmap_Blue].AskFrame(); } Pel*const* AskFrameY() { return d_pm[Bitmap_Y].AskFrame(); } const Pel*const* AskFrameY() const { return d_pm[Bitmap_Y].AskFrame(); } Pel*const* AskFrameU() { return d_pm[Bitmap_U].AskFrame(); } const Pel*const* AskFrameU() const { return d_pm[Bitmap_U].AskFrame(); } Pel*const* AskFrameV() { return d_pm[Bitmap_V].AskFrame(); } const Pel*const* AskFrameV() const { return d_pm[Bitmap_V].AskFrame(); } Pel*const* AskFrameCb() { return d_pm[Bitmap_Cb].AskFrame(); } const Pel*const* AskFrameCb() const { return d_pm[Bitmap_Cb].AskFrame(); } Pel*const* AskFrameCr() { return d_pm[Bitmap_Cr].AskFrame(); } const Pel*const* AskFrameCr() const { return d_pm[Bitmap_Cr].AskFrame(); } Pel*const* AskFrameA() { return d_pm[Bitmap_Alpha].AskFrame(); } const Pel*const* AskFrameA() const { return d_pm[Bitmap_Alpha].AskFrame(); } Bitmap<Pel>& AskBitmapR() { return d_pm[Bitmap_Red]; } const Bitmap<Pel>& AskBitmapR() const { return d_pm[Bitmap_Red]; } Bitmap<Pel>& AskBitmapG() { return d_pm[Bitmap_Green]; } const Bitmap<Pel>& AskBitmapG() const { return d_pm[Bitmap_Green]; } Bitmap<Pel>& AskBitmapB() { return d_pm[Bitmap_Blue]; } const Bitmap<Pel>& AskBitmapB() const { return d_pm[Bitmap_Blue]; } Bitmap<Pel>& AskBitmapY() { return d_pm[Bitmap_Y]; } const Bitmap<Pel>& AskBitmapY() const { return d_pm[Bitmap_Y]; } Bitmap<Pel>& AskBitmapU() { return d_pm[Bitmap_U]; } const Bitmap<Pel>& AskBitmapU() const { return d_pm[Bitmap_U]; } Bitmap<Pel>& AskBitmapV() { return d_pm[Bitmap_V]; } const Bitmap<Pel>& AskBitmapV() const { return d_pm[Bitmap_V]; } Bitmap<Pel>& AskBitmapCb() { return d_pm[Bitmap_Cb]; } const Bitmap<Pel>& AskBitmapCb() const { return d_pm[Bitmap_Cb]; } Bitmap<Pel>& AskBitmapCr() { return d_pm[Bitmap_Cr]; } const Bitmap<Pel>& AskBitmapCr() const { return d_pm[Bitmap_Cr]; } Bitmap<Pel>& AskBitmapA() { return d_pm[Bitmap_Alpha]; } const Bitmap<Pel>& AskBitmapA() const { return d_pm[Bitmap_Alpha]; } bool IsShared() const { for (int i=0;i<4;i++) if (d_pm[i].IsShared()) return true; return false; } private: Bitmap<Pel> d_pm[4]; ImageParam d_param; }; template <class Pel> void Image<Pel>::Create(const ImageParam& param) { d_pm[0].Create(param.width, param.height, param.border,param.halign,param.valign); switch (param.colorspace) { case Colorspace_RGB: case Colorspace_HSV: d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign); d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign); break; case Colorspace_YUV: if (param.reduced_chroma_resolution) { d_pm[1].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(), param.AskChromaHAlign(),param.AskChromaVAlign()); d_pm[2].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(), param.AskChromaHAlign(),param.AskChromaVAlign()); } else { d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign); d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign); } break; case Colorspace_Greyscale: d_pm[1].Release(); d_pm[2].Release(); break; } if (param.has_alpha) d_pm[Bitmap_Alpha].Create(param.width, param.height, param.border,param.halign,param.valign); else d_pm[Bitmap_Alpha].Release(); d_param = param; } template <class Pel> void Image<Pel>::Release() { for (int i=0;i<4;i++) d_pm[i].Release(); d_param = ImageParam(); } template <class Pel> Image<Pel> Image<Pel>::Clone() const { Image<Pel> img; for (int i=0;i<4;i++) img.d_pm[i] = d_pm[i].Clone(); img.d_param = d_param; return img; } template <class Pel> Image<Pel> Image<Pel>::CreateSubView(int x0,int y0,int w,int h) const { Image<Pel> newimg; newimg.d_param = d_param; newimg.d_param.width = w; newimg.d_param.height = h; newimg.d_param.halign = 1; newimg.d_param.valign = 1; newimg.d_param.border = 0; newimg.d_param.chroma_border = -1; newimg.d_param.chroma_halign = -1; newimg.d_param.chroma_valign = -1; if (d_param.colorspace == Colorspace_YUV) { newimg.d_pm[0] = d_pm[0].CreateSubView(x0,y0,w,h); newimg.d_pm[3] = d_pm[3].CreateSubView(x0,y0,w,h); int subh = ChromaSubH(d_param.chroma); int subv = ChromaSubV(d_param.chroma); newimg.d_pm[1] = d_pm[1].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv); newimg.d_pm[2] = d_pm[2].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv); } else { for (int i=0;i<4;i++) newimg.d_pm[i] = d_pm[i].CreateSubView(x0,y0,w,h); } return newimg; } template <class Pel> Image<Pel> Image<Pel>::CreateFieldView(bool top) const { if (!top && d_param.colorspace==Colorspace_YUV && d_param.chroma==Chroma_420 && (d_pm[0].AskHeight()%2)==0 && (d_pm[1].AskHeight()%2)==1) { AssertDescr(false,"not enough chroma information for bottom field"); } Image<Pel> newimg; newimg.d_param = d_param; for (int i=0;i<4;i++) newimg.d_pm[i] = d_pm[i].CreateFieldView(top); newimg.d_param.width = newimg.d_pm[0].AskWidth(); newimg.d_param.height = newimg.d_pm[0].AskHeight(); newimg.d_param.halign = 1; newimg.d_param.valign = 1; newimg.d_param.border = 0; newimg.d_param.chroma_border = -1; newimg.d_param.chroma_halign = -1; newimg.d_param.chroma_valign = -1; return newimg; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include "test/opt/pass_fixture.h" #include "test/opt/pass_utils.h" namespace spvtools { namespace opt { namespace { using StripLineReflectInfoTest = PassTest<::testing::Test>; TEST_F(StripLineReflectInfoTest, StripHlslSemantic) { // This is a non-sensical example, but exercises the instructions. std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_decorate_string" OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpDecorateStringGOOGLE %float HlslSemanticGOOGLE "foobar" OpDecorateStringGOOGLE %void HlslSemanticGOOGLE "my goodness" %void = OpTypeVoid %float = OpTypeFloat 32 )"; std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %void = OpTypeVoid %float = OpTypeFloat 32 )"; SinglePassRunAndCheck<StripReflectInfoPass>(before, after, false); } TEST_F(StripLineReflectInfoTest, StripHlslCounterBuffer) { std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpDecorateId %void HlslCounterBufferGOOGLE %float %void = OpTypeVoid %float = OpTypeFloat 32 )"; std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %void = OpTypeVoid %float = OpTypeFloat 32 )"; SinglePassRunAndCheck<StripReflectInfoPass>(before, after, false); } TEST_F(StripLineReflectInfoTest, StripHlslSemanticOnMember) { // This is a non-sensical example, but exercises the instructions. std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_decorate_string" OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpMemberDecorateStringGOOGLE %struct 0 HlslSemanticGOOGLE "foobar" %float = OpTypeFloat 32 %_struct_3 = OpTypeStruct %float )"; std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %float = OpTypeFloat 32 %_struct_3 = OpTypeStruct %float )"; SinglePassRunAndCheck<StripReflectInfoPass>(before, after, false); } } // namespace } // namespace opt } // namespace spvtools <commit_msg>Add test with explicit example of stripping reflection info (#3064)<commit_after>// Copyright (c) 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include "gmock/gmock.h" #include "spirv-tools/optimizer.hpp" #include "test/opt/pass_fixture.h" #include "test/opt/pass_utils.h" namespace spvtools { namespace opt { namespace { using StripLineReflectInfoTest = PassTest<::testing::Test>; // This test acts as an end-to-end code example on how to strip // reflection info from a SPIR-V module. Use this code pattern // when you have compiled HLSL code with Glslang or DXC using // option -fhlsl_functionality1 to insert reflection information, // but then want to filter out the extra instructions before sending // it to a driver that does not implement VK_GOOGLE_hlsl_functionality1. TEST_F(StripLineReflectInfoTest, StripReflectEnd2EndExample) { // This is a non-sensical example, but exercises the instructions. std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_decorate_string" OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpDecorateStringGOOGLE %float HlslSemanticGOOGLE "foobar" OpDecorateStringGOOGLE %void HlslSemanticGOOGLE "my goodness" %void = OpTypeVoid %float = OpTypeFloat 32 )"; SpirvTools tools(SPV_ENV_UNIVERSAL_1_1); std::vector<uint32_t> binary_in; tools.Assemble(before, &binary_in); // Instantiate the optimizer, and run the strip-reflection-info // pass over the |binary_in| module, and place the modified module // into |binary_out|. spvtools::Optimizer optimizer(SPV_ENV_UNIVERSAL_1_1); optimizer.RegisterPass(spvtools::CreateStripReflectInfoPass()); std::vector<uint32_t> binary_out; optimizer.Run(binary_in.data(), binary_in.size(), &binary_out); // Check results std::string disassembly; tools.Disassemble(binary_out.data(), binary_out.size(), &disassembly); std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %void = OpTypeVoid %float = OpTypeFloat 32 )"; EXPECT_THAT(disassembly, testing::Eq(after)); } // This test is functionally the same as the end-to-end test above, // but uses the test SinglePassRunAndCheck test fixture instead. TEST_F(StripLineReflectInfoTest, StripHlslSemantic) { // This is a non-sensical example, but exercises the instructions. std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_decorate_string" OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpDecorateStringGOOGLE %float HlslSemanticGOOGLE "foobar" OpDecorateStringGOOGLE %void HlslSemanticGOOGLE "my goodness" %void = OpTypeVoid %float = OpTypeFloat 32 )"; std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %void = OpTypeVoid %float = OpTypeFloat 32 )"; SinglePassRunAndCheck<StripReflectInfoPass>(before, after, false); } TEST_F(StripLineReflectInfoTest, StripHlslCounterBuffer) { std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpDecorateId %void HlslCounterBufferGOOGLE %float %void = OpTypeVoid %float = OpTypeFloat 32 )"; std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %void = OpTypeVoid %float = OpTypeFloat 32 )"; SinglePassRunAndCheck<StripReflectInfoPass>(before, after, false); } TEST_F(StripLineReflectInfoTest, StripHlslSemanticOnMember) { // This is a non-sensical example, but exercises the instructions. std::string before = R"(OpCapability Shader OpCapability Linkage OpExtension "SPV_GOOGLE_decorate_string" OpExtension "SPV_GOOGLE_hlsl_functionality1" OpMemoryModel Logical Simple OpMemberDecorateStringGOOGLE %struct 0 HlslSemanticGOOGLE "foobar" %float = OpTypeFloat 32 %_struct_3 = OpTypeStruct %float )"; std::string after = R"(OpCapability Shader OpCapability Linkage OpMemoryModel Logical Simple %float = OpTypeFloat 32 %_struct_3 = OpTypeStruct %float )"; SinglePassRunAndCheck<StripReflectInfoPass>(before, after, false); } } // namespace } // namespace opt } // namespace spvtools <|endoftext|>
<commit_before>#include <Halide.h> #include <stdio.h> #include "clock.h" #include <memory> using namespace Halide; enum { scalar_trans, vec_y_trans, vec_x_trans }; void test_transpose(int mode) { Func input, block, block_transpose, output; Var x, y; input(x, y) = cast<uint16_t>(x + y); input.compute_root(); block(x, y) = input(x, y); block_transpose(x, y) = block(y, x); output(x, y) = block_transpose(x, y); Var xi, yi; output.tile(x, y, xi, yi, 8, 8).vectorize(xi).unroll(yi); // Do 8 vectorized loads from the input. block.compute_at(output, x).vectorize(x).unroll(y); std::string algorithm; switch(mode) { case scalar_trans: block_transpose.compute_at(output, x).unroll(x).unroll(y); algorithm = "Scalar transpose"; break; case vec_y_trans: block_transpose.compute_at(output, x).vectorize(y).unroll(x); algorithm = "Transpose vectorized in y"; break; case vec_x_trans: block_transpose.compute_at(output, x).vectorize(x).unroll(y); algorithm = "Transpose vectorized in x"; break; } output.compile_to_lowered_stmt("fast_transpose.stmt"); output.compile_to_assembly("fast_transpose.s", std::vector<Argument>()); Image<uint16_t> result(1024, 1024); output.compile_jit(); output.realize(result); double t1 = current_time(); for (int i = 0; i < 10; i++) { output.realize(result); } double t2 = current_time(); std::cout << algorithm << " bandwidth " << ((1024*1024 / (t2 - t1)) * 1000 * 10) << " byte/s.\n"; } int main(int argc, char **argv) { test_transpose(scalar_trans); test_transpose(vec_y_trans); test_transpose(vec_x_trans); printf("Success!\n"); return 0; } <commit_msg>Modified block_transpose performance test to ouput assembly code for each different algorithm.<commit_after>#include <Halide.h> #include <stdio.h> #include "clock.h" #include <memory> using namespace Halide; enum { scalar_trans, vec_y_trans, vec_x_trans }; void test_transpose(int mode) { Func input, block, block_transpose, output; Var x, y; input(x, y) = cast<uint16_t>(x + y); input.compute_root(); block(x, y) = input(x, y); block_transpose(x, y) = block(y, x); output(x, y) = block_transpose(x, y); Var xi, yi; output.tile(x, y, xi, yi, 8, 8).vectorize(xi).unroll(yi); // Do 8 vectorized loads from the input. block.compute_at(output, x).vectorize(x).unroll(y); std::string algorithm; switch(mode) { case scalar_trans: block_transpose.compute_at(output, x).unroll(x).unroll(y); algorithm = "Scalar transpose"; output.compile_to_assembly("scalar_transpose.s", std::vector<Argument>()); break; case vec_y_trans: block_transpose.compute_at(output, x).vectorize(y).unroll(x); algorithm = "Transpose vectorized in y"; output.compile_to_assembly("fast_transpose_y.s", std::vector<Argument>()); break; case vec_x_trans: block_transpose.compute_at(output, x).vectorize(x).unroll(y); algorithm = "Transpose vectorized in x"; output.compile_to_assembly("fast_transpose_x.s", std::vector<Argument>()); break; } Image<uint16_t> result(1024, 1024); output.compile_jit(); output.realize(result); double t1 = current_time(); for (int i = 0; i < 10; i++) { output.realize(result); } double t2 = current_time(); std::cout << algorithm << " bandwidth " << ((1024*1024 / (t2 - t1)) * 1000 * 10) << " byte/s.\n"; } int main(int argc, char **argv) { test_transpose(scalar_trans); test_transpose(vec_y_trans); test_transpose(vec_x_trans); printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>#include <memory.h> #include <string.h> #include "wrapper.h" extern "C" { /* bitmap/image helpers */ EWXWEXPORT(wxBitmap*,wxBitmap_CreateFromImage)(wxImage* image,int depth) { return new wxBitmap(*image,depth); } EWXWEXPORT(wxImage*,wxImage_CreateFromDataEx)(int width,int height,wxUint8* data,bool isStaticData) { return new wxImage(width, height, data, isStaticData); } EWXWEXPORT(void,wxImage_Delete)(wxImage* image) { delete image; } /* colours */ EWXWEXPORT(wxColour*,wxColour_CreateFromInt)(int rgb) { return new wxColour((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF); } EWXWEXPORT(int,wxColour_GetInt)(wxColour* colour) { int r = colour->Red(); int g = colour->Green(); int b = colour->Blue(); return ((r << 16) | (g << 8) | b); } /* basic pixel manipulation */ EWXWEXPORT(void,wxcSetPixelRGB)(wxUint8* buffer,int width,int x,int y,int rgb) { int indexR = 3*(width*y + x); buffer[indexR] = rgb >> 16; buffer[indexR+1] = rgb >> 8; buffer[indexR+2] = rgb; } EWXWEXPORT(int,wxcGetPixelRGB)(wxUint8* buffer,int width,int x,int y) { int indexR = 3*(width*y + x); int r,g,b; r = buffer[indexR]; g = buffer[indexR+1]; b = buffer[indexR+2]; return ((r << 16) | (g << 8) | b); } EWXWEXPORT(void,wxcSetPixelRowRGB)(wxUint8* buffer,int width,int x,int y,int rgb0,int rgb1,int count) { int r0 = ((rgb0 >> 16) && 0xFF); int g0 = ((rgb0 >> 8) && 0xFF); int b0 = (rgb0 && 0xFF); int start = 3*(width*y+x); int i; if (rgb0 == rgb1) { /* same color */ for( i=0; i < count*3; i +=3) { buffer[start+i] = r0; buffer[start+i+1] = g0; buffer[start+i+2] = b0; } } else { /* do linear interpolation of the color */ int r1 = ((rgb1 >> 16) && 0xFF); int g1 = ((rgb1 >> 8) && 0xFF); int b1 = (rgb1 && 0xFF); int rd = ((r1 - r0) << 16) / (count-1); int gd = ((g1 - g0) << 16) / (count-1); int bd = ((b1 - b0) << 16) / (count-1); int r = r0 << 16; int g = g0 << 16; int b = b0 << 16; for( i = 0; i < count*3; i += 3 ) { buffer[start+i] = (r >> 16); buffer[start+i+1] = (g >> 16); buffer[start+i+2] = (b >> 16); r += rd; g += gd; b += bd; } } } EWXWEXPORT(void,wxcInitPixelsRGB)(wxUint8* buffer,int width,int height,int rgb) { int count = width*height*3; wxUint8 r = ((rgb >> 16) && 0xFF); wxUint8 g = ((rgb >> 8) && 0xFF); wxUint8 b = rgb && 0xFF; int i; if (r==g && g==b) { for( i=0; i < count; i++ ) { buffer[i] = r; } } else { for( i=0; i < count; i += 3) { buffer[i] = r; buffer[i+1] = g; buffer[i+2] = b; } } } EWXWEXPORT(wxColour*,wxColour_CreateFromUnsignedInt)(unsigned int rgba) { return new wxColour((rgba >> 24) & 0xFF, (rgba >> 16) & 0xFF, (rgba >> 8) & 0xFF, rgba & 0xFF); } EWXWEXPORT(unsigned int,wxColour_GetUnsignedInt)(wxColour* colour) { int r = colour->Red(); int g = colour->Green(); int b = colour->Blue(); int a = colour->Alpha(); return ((r << 24) | (g << 16) | (b << 8) | a); } /* basic pixel manipulation */ EWXWEXPORT(void,wxcSetPixelRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba) { unsigned int indexR = 4*(width*y + x); buffer[indexR] = rgba >> 24; buffer[indexR+1] = rgba >> 16; buffer[indexR+2] = rgba >> 8; buffer[indexR+3] = rgba; } EWXWEXPORT(int,wxcGetPixelRGBA)(wxUint8* buffer,int width,int x,int y) { unsigned int indexR = 4*(width*y + x); int r,g,b,a; r = buffer[indexR]; g = buffer[indexR+1]; b = buffer[indexR+2]; a = buffer[indexR+3]; return ((r << 24) | (g << 16) | (b << 8) | a); } EWXWEXPORT(void,wxcSetPixelRowRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba0,unsigned int rgba1,unsigned int count) { int r0 = ((rgba0 >> 24) && 0xFF); int g0 = ((rgba0 >> 16) && 0xFF); int b0 = ((rgba0 >> 8) && 0xFF); int a0 = (rgba0 && 0xFF); unsigned int start = 4*(width*y+x); unsigned int i; if (rgba0 == rgba1) { /* same color */ for( i=0; i < count*4; i +=4) { buffer[start+i] = r0; buffer[start+i+1] = g0; buffer[start+i+2] = b0; buffer[start+i+3] = a0; } } else { /* do linear interpolation of the color */ int r1 = ((rgba1 >> 24) && 0xFF); int g1 = ((rgba1 >> 16) && 0xFF); int b1 = ((rgba1 >> 8) && 0xFF); int a1 = (rgba1 && 0xFF); int rd = ((r1 - r0) << 24) / (count-1); int gd = ((g1 - g0) << 24) / (count-1); int bd = ((b1 - b0) << 24) / (count-1); int ad = ((a1 - a0) << 24) / (count-1); int r = r0 << 24; int g = g0 << 24; int b = b0 << 24; int a = b0 << 24; for( i = 0; i < count*4; i += 4 ) { buffer[start+i] = (r >> 24); buffer[start+i+1] = (g >> 24); buffer[start+i+2] = (b >> 24); buffer[start+i+3] = (a >> 24); r += rd; g += gd; b += bd; a += ad; } } } EWXWEXPORT(void,wxcInitPixelsRGBA)(wxUint8* buffer,int width,int height,int rgba) { unsigned int count = width*height*4; wxUint8 r = ((rgba >> 24) && 0xFF); wxUint8 g = ((rgba >> 16) && 0xFF); wxUint8 b = ((rgba >> 8) && 0xFF); wxUint8 a = rgba && 0xFF; unsigned int i; if (r==g && g==b && b==a) { for( i=0; i < count; i++ ) { buffer[i] = r; } } else { for( i=0; i < count; i += 4) { buffer[i] = r; buffer[i+1] = g; buffer[i+2] = b; buffer[i+3] = a; } } } } <commit_msg>Replaced '&&' with '&' several times in wxc/src/cpp/image.cpp<commit_after>#include <memory.h> #include <string.h> #include "wrapper.h" extern "C" { /* bitmap/image helpers */ EWXWEXPORT(wxBitmap*,wxBitmap_CreateFromImage)(wxImage* image,int depth) { return new wxBitmap(*image,depth); } EWXWEXPORT(wxImage*,wxImage_CreateFromDataEx)(int width,int height,wxUint8* data,bool isStaticData) { return new wxImage(width, height, data, isStaticData); } EWXWEXPORT(void,wxImage_Delete)(wxImage* image) { delete image; } /* colours */ EWXWEXPORT(wxColour*,wxColour_CreateFromInt)(int rgb) { return new wxColour((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF); } EWXWEXPORT(int,wxColour_GetInt)(wxColour* colour) { int r = colour->Red(); int g = colour->Green(); int b = colour->Blue(); return ((r << 16) | (g << 8) | b); } /* basic pixel manipulation */ EWXWEXPORT(void,wxcSetPixelRGB)(wxUint8* buffer,int width,int x,int y,int rgb) { int indexR = 3*(width*y + x); buffer[indexR] = rgb >> 16; buffer[indexR+1] = rgb >> 8; buffer[indexR+2] = rgb; } EWXWEXPORT(int,wxcGetPixelRGB)(wxUint8* buffer,int width,int x,int y) { int indexR = 3*(width*y + x); int r,g,b; r = buffer[indexR]; g = buffer[indexR+1]; b = buffer[indexR+2]; return ((r << 16) | (g << 8) | b); } EWXWEXPORT(void,wxcSetPixelRowRGB)(wxUint8* buffer,int width,int x,int y,int rgb0,int rgb1,int count) { int r0 = ((rgb0 >> 16) & 0xFF); int g0 = ((rgb0 >> 8) & 0xFF); int b0 = (rgb0 & 0xFF); int start = 3*(width*y+x); int i; if (rgb0 == rgb1) { /* same color */ for( i=0; i < count*3; i +=3) { buffer[start+i] = r0; buffer[start+i+1] = g0; buffer[start+i+2] = b0; } } else { /* do linear interpolation of the color */ int r1 = ((rgb1 >> 16) & 0xFF); int g1 = ((rgb1 >> 8) & 0xFF); int b1 = (rgb1 & 0xFF); int rd = ((r1 - r0) << 16) / (count-1); int gd = ((g1 - g0) << 16) / (count-1); int bd = ((b1 - b0) << 16) / (count-1); int r = r0 << 16; int g = g0 << 16; int b = b0 << 16; for( i = 0; i < count*3; i += 3 ) { buffer[start+i] = (r >> 16); buffer[start+i+1] = (g >> 16); buffer[start+i+2] = (b >> 16); r += rd; g += gd; b += bd; } } } EWXWEXPORT(void,wxcInitPixelsRGB)(wxUint8* buffer,int width,int height,int rgb) { int count = width*height*3; wxUint8 r = ((rgb >> 16) & 0xFF); wxUint8 g = ((rgb >> 8) & 0xFF); wxUint8 b = rgb & 0xFF; int i; if (r==g && g==b) { for( i=0; i < count; i++ ) { buffer[i] = r; } } else { for( i=0; i < count; i += 3) { buffer[i] = r; buffer[i+1] = g; buffer[i+2] = b; } } } EWXWEXPORT(wxColour*,wxColour_CreateFromUnsignedInt)(unsigned int rgba) { return new wxColour((rgba >> 24) & 0xFF, (rgba >> 16) & 0xFF, (rgba >> 8) & 0xFF, rgba & 0xFF); } EWXWEXPORT(unsigned int,wxColour_GetUnsignedInt)(wxColour* colour) { int r = colour->Red(); int g = colour->Green(); int b = colour->Blue(); int a = colour->Alpha(); return ((r << 24) | (g << 16) | (b << 8) | a); } /* basic pixel manipulation */ EWXWEXPORT(void,wxcSetPixelRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba) { unsigned int indexR = 4*(width*y + x); buffer[indexR] = rgba >> 24; buffer[indexR+1] = rgba >> 16; buffer[indexR+2] = rgba >> 8; buffer[indexR+3] = rgba; } EWXWEXPORT(int,wxcGetPixelRGBA)(wxUint8* buffer,int width,int x,int y) { unsigned int indexR = 4*(width*y + x); int r,g,b,a; r = buffer[indexR]; g = buffer[indexR+1]; b = buffer[indexR+2]; a = buffer[indexR+3]; return ((r << 24) | (g << 16) | (b << 8) | a); } EWXWEXPORT(void,wxcSetPixelRowRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba0,unsigned int rgba1,unsigned int count) { int r0 = ((rgba0 >> 24) & 0xFF); int g0 = ((rgba0 >> 16) & 0xFF); int b0 = ((rgba0 >> 8) & 0xFF); int a0 = (rgba0 & 0xFF); unsigned int start = 4*(width*y+x); unsigned int i; if (rgba0 == rgba1) { /* same color */ for( i=0; i < count*4; i +=4) { buffer[start+i] = r0; buffer[start+i+1] = g0; buffer[start+i+2] = b0; buffer[start+i+3] = a0; } } else { /* do linear interpolation of the color */ int r1 = ((rgba1 >> 24) & 0xFF); int g1 = ((rgba1 >> 16) & 0xFF); int b1 = ((rgba1 >> 8) & 0xFF); int a1 = (rgba1 & 0xFF); int rd = ((r1 - r0) << 24) / (count-1); int gd = ((g1 - g0) << 24) / (count-1); int bd = ((b1 - b0) << 24) / (count-1); int ad = ((a1 - a0) << 24) / (count-1); int r = r0 << 24; int g = g0 << 24; int b = b0 << 24; int a = b0 << 24; for( i = 0; i < count*4; i += 4 ) { buffer[start+i] = (r >> 24); buffer[start+i+1] = (g >> 24); buffer[start+i+2] = (b >> 24); buffer[start+i+3] = (a >> 24); r += rd; g += gd; b += bd; a += ad; } } } EWXWEXPORT(void,wxcInitPixelsRGBA)(wxUint8* buffer,int width,int height,int rgba) { unsigned int count = width*height*4; wxUint8 r = ((rgba >> 24) & 0xFF); wxUint8 g = ((rgba >> 16) & 0xFF); wxUint8 b = ((rgba >> 8) & 0xFF); wxUint8 a = rgba & 0xFF; unsigned int i; if (r==g && g==b && b==a) { for( i=0; i < count; i++ ) { buffer[i] = r; } } else { for( i=0; i < count; i += 4) { buffer[i] = r; buffer[i+1] = g; buffer[i+2] = b; buffer[i+3] = a; } } } } <|endoftext|>
<commit_before>#ifndef __ENVIRE_MAPS_LOCAL_MAP_HPP__ #define __ENVIRE_MAPS_LOCAL_MAP_HPP__ #include <base/Eigen.hpp> #include <boost/shared_ptr.hpp> #include <string> namespace envire { namespace maps { /**@brief LocalMapType * The type of the LocalMap */ // TODO: do we need unknown type? enum LocalMapType { GRID_MAP = 0, GEOMETRIC_MAP = 1, MLS_MAP = 2, TOPOLOGICAL_MAP = 3 }; struct LocalMapData { // TODO: which map_type should be set by default LocalMapData() : offset(base::Transform3d::Identity()) {}; /** string id of this local map **/ std::string id; /** Offset within the grid. The description of the local map frame. * It will be the offset with respect * to the bottom left corner (origin) of the map. * For the time being we use 3D transformation. * * **/ base::Transform3d offset; /** map_type of this local map **/ LocalMapType map_type; /** EPSG_code that provides the geo-localized coordinate system **/ std::string EPSG_code; /** The EPSG code depends in the coordinate system used for the * local map "NONE" in case of not geo-referenced map. * Example: "EPSG::4978" for the World Geodetic System 1984 (WGS-84) * Example: "EPSG::3199" Spain - Canary Islands onshore and offshore. * with bounds are [-21.93W, -11.75E] and [24.6S, 11.75N] using the * World Geodetic System 1984 (WGS-84) coordinate reference system * (CRS). * Example: "EPSG::5243" ETRS89 / LCC Germany (E-N) Bremen area with * WGS084 CRS * Reference: https://www.epsg-registry.org **/ }; /**@brief LocalMap * Local map with respect to a given reference frame * A local map is the basic element to form a global * map (set of local maps structured in a tree). */ class LocalMap { public: typedef boost::shared_ptr<LocalMap> Ptr; LocalMap() : data_ptr(new LocalMapData()) { } /** * @brief [brief description] * @details to share same content (LocalMapData) between various instance of LocalMap * * @param data [description] */ LocalMap(const boost::shared_ptr<LocalMapData> &data) : data_ptr(data) { } /** * @brief make copy without sharing the content * @details the copy instance owns a new content (LocalMapData) * * @param other [description] */ LocalMap(const LocalMap& other) : data_ptr(new LocalMapData(*(other.data_ptr.get()))) { } virtual ~LocalMap() {}; const std::string& getId() const { return data_ptr->id; } std::string& getId() { return data_ptr->id; } const base::Transform3d& getOffset() const { return data_ptr->offset; } base::Transform3d& getOffset() { return data_ptr->offset; } const boost::shared_ptr<LocalMapData>& getLocalMap() const { return data_ptr; } protected: boost::shared_ptr<LocalMapData> data_ptr; }; }} #endif // __ENVIRE_MAPS_LOCAL_MAP_HPP__ <commit_msg>src: default LocalMap information and constructor<commit_after>#ifndef __ENVIRE_MAPS_LOCAL_MAP_HPP__ #define __ENVIRE_MAPS_LOCAL_MAP_HPP__ #include <base/Eigen.hpp> #include <boost/shared_ptr.hpp> #include <string> namespace envire { namespace maps { /**@brief LocalMapType * The type of the LocalMap */ enum LocalMapType { GRID_MAP = 0, GEOMETRIC_MAP = 1, MLS_MAP = 2, TOPOLOGICAL_MAP = 3 }; const std::string DEFAULT_GRID_MAP_ID = "DEFAULT_GRID_MAP"; const std::string DEFAULT_EPSG_CODE = "NONE"; struct LocalMapData { /** Grid map is the map by default **/ LocalMapData() :id(DEFAULT_GRID_MAP_ID), offset(base::Transform3d::Identity()), map_type(GRID_MAP), EPSG_code(DEFAULT_EPSG_CODE){}; LocalMapData(const std::string _id, const base::Transform3d &_offset, const LocalMapType _map_type, const std::string _EPSG_code) :id(_id), offset(_offset), map_type(_map_type), EPSG_code(_EPSG_code) {}; /** string id of this local map **/ std::string id; /** Offset within the grid. The description of the local map frame. * It will be the offset with respect * to the bottom left corner (origin) of the map. * For the time being we use 3D transformation. * * **/ base::Transform3d offset; /** map_type of this local map **/ LocalMapType map_type; /** EPSG_code that provides the geo-localized coordinate system **/ std::string EPSG_code; /** The EPSG code depends in the coordinate system used for the * local map "NONE" in case of not geo-referenced map. * Example: "EPSG::4978" for the World Geodetic System 1984 (WGS-84) * Example: "EPSG::3199" Spain - Canary Islands onshore and offshore. * with bounds are [-21.93W, -11.75E] and [24.6S, 11.75N] using the * World Geodetic System 1984 (WGS-84) coordinate reference system * (CRS). * Example: "EPSG::5243" ETRS89 / LCC Germany (E-N) Bremen area with * WGS084 CRS * Reference: https://www.epsg-registry.org **/ }; /**@brief LocalMap * Local map with respect to a given reference frame * A local map is the basic element to form a global * map (set of local maps structured in a tree). */ class LocalMap { public: typedef boost::shared_ptr<LocalMap> Ptr; LocalMap() : data_ptr(new LocalMapData()) { } /** * @brief [brief description] * @details to share same content (LocalMapData) between various instance of LocalMap * * @param data [description] */ LocalMap(const boost::shared_ptr<LocalMapData> &data) : data_ptr(data) { } /** * @brief make copy without sharing the content * @details the copy instance owns a new content (LocalMapData) * * @param other [description] */ LocalMap(const LocalMap& other) : data_ptr(new LocalMapData(*(other.data_ptr.get()))) { } virtual ~LocalMap() {}; const std::string& getId() const { return data_ptr->id; } std::string& getId() { return data_ptr->id; } const base::Transform3d& getOffset() const { return data_ptr->offset; } base::Transform3d& getOffset() { return data_ptr->offset; } const boost::shared_ptr<LocalMapData>& getLocalMap() const { return data_ptr; } protected: boost::shared_ptr<LocalMapData> data_ptr; }; }} #endif // __ENVIRE_MAPS_LOCAL_MAP_HPP__ <|endoftext|>
<commit_before>#include "LuaTable.h" #include "LuaObjectImpl.h" LuaTable::LuaTable(LuaState* L) :LuaObject(L) { } LuaTable::LuaTable(LuaObjectImpl* impl) :LuaObject(impl) { } LuaTable::LuaTable(const LuaObject& rfs) :LuaObject(rfs) { } LuaTable::LuaTable(const LuaTable& rfs) :LuaObject(rfs) { } bool LuaTable::isValid() { return getType()==LUA_TTABLE; } LuaObject LuaTable::getTable(const char* key) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key); } LuaObject LuaTable::getTable(lua_Integer key) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key); } LuaObject LuaTable::operator[](const char* key) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key); } LuaObject LuaTable::operator[](lua_Integer idx) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,idx); } bool LuaTable::setTable(const char* key,LuaObject val) { if(isValid()) { lua_State* L=m_ptr->getLuaState(); lua_pushstring(L,key);//key lua_pushvalue(L,val.getIndex());//value lua_settable(L,getIndex()); return true; } return false; } bool LuaTable::setTable(lua_Integer key,LuaObject val) { if(isValid()) { lua_State* L=m_ptr->getLuaState(); lua_pushinteger(L,key);//key lua_pushvalue(L,val.getIndex());//value lua_settable(L,getIndex()); return true; } return false; }<commit_msg>fixbug<commit_after>#include "LuaTable.h" #include "LuaObjectImpl.h" LuaTable::LuaTable(LuaState* L) :LuaObject(L) { } LuaTable::LuaTable(LuaObjectImpl* impl) :LuaObject(impl) { } LuaTable::LuaTable(const LuaObject& rfs) :LuaObject(rfs) { } LuaTable::LuaTable(const LuaTable& rfs) :LuaObject(rfs) { } bool LuaTable::isValid() { return getType()==LUA_TTABLE; } LuaObject LuaTable::getTable(const char* key) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key); } LuaObject LuaTable::getTable(lua_Integer key) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key); } LuaObject LuaTable::operator[](const char* key) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key); } LuaObject LuaTable::operator[](lua_Integer idx) { assert(isValid()); return LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,idx); } bool LuaTable::setTable(const char* key,LuaObject val) { if(isValid()) { lua_State* L=m_ptr->getLuaState(); lua_pushstring(L,key);//key if(val.isNone()) lua_pushnil(L); else lua_pushvalue(L,val.getIndex());//value lua_settable(L,getIndex()); return true; } return false; } bool LuaTable::setTable(lua_Integer key,LuaObject val) { if(isValid()) { lua_State* L=m_ptr->getLuaState(); lua_pushinteger(L,key);//key if(val.isNone()) lua_pushnil(L); else lua_pushvalue(L,val.getIndex());//value lua_settable(L,getIndex()); return true; } return false; }<|endoftext|>
<commit_before>// 'operator delete' redeclared without throw() // originally found in package drscheme_1:208-1 // %%% progress: 0ms: done type checking (1 ms) // a.ii:3:6: error: prior declaration of `operator delete' at <init>:1:1 had type `void ()(void *p) throw()', but this one uses `void ()(void */*anon*/)' // typechecking results: // errors: 1 // warnings: 0 void operator delete(void *) { } <commit_msg>(Comment)<commit_after>// 'operator delete' redeclared without throw() // originally found in package drscheme_1:208-1 // a.ii:3:6: error: prior declaration of `operator delete' at <init>:1:1 had // type `void ()(void *p) throw()', but this one uses `void ()(void // */*anon*/)' void operator delete(void *) { } <|endoftext|>
<commit_before>/*! \file MatTools.cpp \brief Implements the MatTools class used by the Generic Repository \author Kathryn D. Huff */ #include <iostream> #include <fstream> #include <deque> #include <time.h> #include <assert.h> #include "CycException.h" #include "CycLimits.h" #include "MatTools.h" #include "Material.h" #include "Logger.h" #include "Timer.h" using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){ IsoVector vec; CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS)); double tot = 0; double kg = 0; if( !mats.empty() ){ CompMapPtr comp_to_add; deque<mat_rsrc_ptr>::iterator mat; int iso; CompMap::const_iterator comp; for(mat = mats.begin(); mat != mats.end(); ++mat){ kg = (*mat)->mass(MassUnit(KG)); tot += kg; comp_to_add = (*mat)->isoVector().comp(); comp_to_add->massify(); for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) { iso = comp->first; if(sum_comp->count(iso)!=0) { (*sum_comp)[iso] += (comp->second)*kg; } else { (*sum_comp)[iso] = (comp->second)*kg; } } } } else { (*sum_comp)[92235] = 0; } vec = IsoVector(sum_comp); return make_pair(vec, tot); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){ comp_to_rem->normalize(); mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem)); left_over->setQuantity(0); while(!mat_list.empty()) { left_over->absorb(mat_list.back()); mat_list.pop_back(); } mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem); if(left_over->mass(KG) > cyclus::eps_rsrc()){ mat_list.push_back(left_over); } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){ MatTools::validate_finite_pos(vol); MatTools::validate_finite_pos(mass); IsoConcMap to_ret; if( vol==0 ) { to_ret = zeroConcMap(); } else { int iso; double m_iso; CompMap::const_iterator it; it=(*comp).begin(); while(it!= (*comp).end() ){ iso = (*it).first; m_iso=((*it).second)*mass; to_ret.insert(make_pair(iso, m_iso/vol)); ++it; } } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::zeroConcMap(){ IsoConcMap to_ret; to_ret[92235] = 0; return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){ MatTools::validate_finite_pos(vol); CompMapPtr comp = CompMapPtr(new CompMap(MASS)); double mass(0); int iso; double c_iso; double m_iso; CompMap::const_iterator it; it=conc.begin(); while(it!= conc.end() ){ iso = (*it).first; c_iso=((*it).second); m_iso = c_iso*vol; (*comp)[iso] = m_iso; mass+=m_iso; ++it; } (*comp).normalize(); pair<CompMapPtr, double> to_ret = make_pair(CompMapPtr(comp), mass); return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_f(double V_T, double theta){ validate_percent(theta); validate_finite_pos(V_T); return theta*V_T; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_ff(double V_T, double theta, double d){ validate_percent(d); return d*V_f(V_T, theta); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_mf(double V_T, double theta, double d){ return (V_f(V_T,theta) - V_ff(V_T, theta, d)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_s(double V_T, double theta){ return (V_T - V_f(V_T, theta)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_ds(double V_T, double theta, double d){ validate_percent(d); return d*V_s(V_T, theta); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_ms(double V_T, double theta, double d){ return (V_s(V_T, theta) - V_ds(V_T, theta, d)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_percent(double per){ if( per <= 1 && per >= 0 ){ return; } else if ( per < 0) { throw CycRangeException("The value is not a valid percent. It is less than zero."); } else if ( per > 1) { throw CycRangeException("The value is not a valid percent. It is greater than one."); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_finite_pos(double pos){ if ( pos >= numeric_limits<double>::infinity() ) { throw CycRangeException("The value is not positive and finite. It is infinite."); } validate_pos(pos); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_pos(double pos){ if ( pos < 0) { throw CycRangeException("The value is not positive and finite. It is less than zero."); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_nonzero(double nonzero){ if ( nonzero == 0 ) throw CycRangeException("The value is zero."); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){ MatTools::validate_finite_pos(scalar); double orig; IsoConcMap::iterator it; for(it = C_0.begin(); it != C_0.end(); ++it) { orig = C_0[(*it).first]; C_0[(*it).first] = orig*scalar; } return C_0; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::addConcMaps(IsoConcMap orig, IsoConcMap to_add){ IsoConcMap to_ret; IsoConcMap::iterator it; for(it = orig.begin(); it != orig.end(); ++it) { Iso iso=(*it).first; if(to_add.find(iso) != to_add.end()) { to_ret[iso] = (*it).second + to_add[iso]; } else { to_ret[iso] = (*it).second; } } for(it = to_add.begin(); it != to_add.end(); ++it) { Iso iso=(*it).first; if(orig.find(iso) == orig.end()) { to_ret[iso] = (*it).second; } } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int MatTools::isoToElem(int iso) { int N = iso % 1000; return (iso-N)/1000; } <commit_msg>extraction in grams<commit_after>/*! \file MatTools.cpp \brief Implements the MatTools class used by the Generic Repository \author Kathryn D. Huff */ #include <iostream> #include <fstream> #include <deque> #include <time.h> #include <assert.h> #include "CycException.h" #include "CycLimits.h" #include "MatTools.h" #include "Material.h" #include "Logger.h" #include "Timer.h" using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){ IsoVector vec; CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS)); double tot = 0; double kg = 0; if( !mats.empty() ){ CompMapPtr comp_to_add; deque<mat_rsrc_ptr>::iterator mat; int iso; CompMap::const_iterator comp; for(mat = mats.begin(); mat != mats.end(); ++mat){ kg = (*mat)->mass(MassUnit(KG)); tot += kg; comp_to_add = (*mat)->isoVector().comp(); comp_to_add->massify(); for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) { iso = comp->first; if(sum_comp->count(iso)!=0) { (*sum_comp)[iso] += (comp->second)*kg; } else { (*sum_comp)[iso] = (comp->second)*kg; } } } } else { (*sum_comp)[92235] = 0; } vec = IsoVector(sum_comp); return make_pair(vec, tot); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){ comp_to_rem->normalize(); mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem)); left_over->setQuantity(0); while(!mat_list.empty()) { left_over->absorb(mat_list.back()); mat_list.pop_back(); } mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem*1000, G); if(left_over->mass(KG) > cyclus::eps_rsrc()){ mat_list.push_back(left_over); } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){ MatTools::validate_finite_pos(vol); MatTools::validate_finite_pos(mass); IsoConcMap to_ret; if( vol==0 ) { to_ret = zeroConcMap(); } else { int iso; double m_iso; CompMap::const_iterator it; it=(*comp).begin(); while(it!= (*comp).end() ){ iso = (*it).first; m_iso=((*it).second)*mass; to_ret.insert(make_pair(iso, m_iso/vol)); ++it; } } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::zeroConcMap(){ IsoConcMap to_ret; to_ret[92235] = 0; return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){ MatTools::validate_finite_pos(vol); CompMapPtr comp = CompMapPtr(new CompMap(MASS)); double mass(0); int iso; double c_iso; double m_iso; CompMap::const_iterator it; it=conc.begin(); while(it!= conc.end() ){ iso = (*it).first; c_iso=((*it).second); m_iso = c_iso*vol; (*comp)[iso] = m_iso; mass+=m_iso; ++it; } (*comp).normalize(); pair<CompMapPtr, double> to_ret = make_pair(CompMapPtr(comp), mass); return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_f(double V_T, double theta){ validate_percent(theta); validate_finite_pos(V_T); return theta*V_T; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_ff(double V_T, double theta, double d){ validate_percent(d); return d*V_f(V_T, theta); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_mf(double V_T, double theta, double d){ return (V_f(V_T,theta) - V_ff(V_T, theta, d)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_s(double V_T, double theta){ return (V_T - V_f(V_T, theta)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_ds(double V_T, double theta, double d){ validate_percent(d); return d*V_s(V_T, theta); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MatTools::V_ms(double V_T, double theta, double d){ return (V_s(V_T, theta) - V_ds(V_T, theta, d)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_percent(double per){ if( per <= 1 && per >= 0 ){ return; } else if ( per < 0) { throw CycRangeException("The value is not a valid percent. It is less than zero."); } else if ( per > 1) { throw CycRangeException("The value is not a valid percent. It is greater than one."); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_finite_pos(double pos){ if ( pos >= numeric_limits<double>::infinity() ) { throw CycRangeException("The value is not positive and finite. It is infinite."); } validate_pos(pos); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_pos(double pos){ if ( pos < 0) { throw CycRangeException("The value is not positive and finite. It is less than zero."); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MatTools::validate_nonzero(double nonzero){ if ( nonzero == 0 ) throw CycRangeException("The value is zero."); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){ MatTools::validate_finite_pos(scalar); double orig; IsoConcMap::iterator it; for(it = C_0.begin(); it != C_0.end(); ++it) { orig = C_0[(*it).first]; C_0[(*it).first] = orig*scalar; } return C_0; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IsoConcMap MatTools::addConcMaps(IsoConcMap orig, IsoConcMap to_add){ IsoConcMap to_ret; IsoConcMap::iterator it; for(it = orig.begin(); it != orig.end(); ++it) { Iso iso=(*it).first; if(to_add.find(iso) != to_add.end()) { to_ret[iso] = (*it).second + to_add[iso]; } else { to_ret[iso] = (*it).second; } } for(it = to_add.begin(); it != to_add.end(); ++it) { Iso iso=(*it).first; if(orig.find(iso) == orig.end()) { to_ret[iso] = (*it).second; } } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int MatTools::isoToElem(int iso) { int N = iso % 1000; return (iso-N)/1000; } <|endoftext|>
<commit_before><commit_msg>Spiral1 Soltuion from interviewbit<commit_after><|endoftext|>
<commit_before>/** @file main.cpp * @brief * * @author Viacheslav Kroilov (metopa) <slavakroilov@gmail.com> */ #include <iostream> #include "murmurhash2functor.h" int main() { mmh2::MurmurHash2<int> h; std::cout << h(700) << std::endl; return 0; } <commit_msg>Update example<commit_after>/** @file main.cpp * @brief * * @author Viacheslav Kroilov (metopa) <slavakroilov@gmail.com> */ #include <iostream> #include "murmurhash2functor.h" #include "murmurhash2_stl_specializations.h" int main() { std::cout << mmh2::getMurmurHash2(std::string("")) << std::endl; std::cout << mmh2::getMurmurHash2(std::string("AB")) << std::endl; std::cout << mmh2::getMurmurHash2(std::string("BA")) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_pair(0.f, 0.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(0., 0.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(-0., 0.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(0.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(0., 0., 0.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(1., 0.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(0., 1.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(1., 1.)) << std::endl; std::cout << mmh2::getMurmurHash2(std::make_tuple(-1., 1.)) << std::endl; return 0; } <|endoftext|>
<commit_before>/* COPYRIGHT (c) 2015 Sam Westrick, Laxman Dhulipala, Umut Acar, * Arthur Chargueraud, and Michael Rainey. * All rights reserved. * * \file pwsa.cpp * */ #include "benchmark.hpp" #include "treap-frontier.hpp" #include "weighted-graph.hpp" #include "native.hpp" #include "defaults.hpp" #include <cstring> static inline void pmemset(char * ptr, int value, size_t num) { const size_t cutoff = 100000; if (num <= cutoff) { std::memset(ptr, value, num); } else { long m = num/2; pasl::sched::native::fork2([&] { pmemset(ptr, value, m); }, [&] { pmemset(ptr+m, value, num-m); }); } } template <class Number, class Size> void fill_array_par(std::atomic<Number>* array, Size sz, Number val) { pmemset((char*)array, val, sz*sizeof(Number)); } template <class Body> void print(const Body& b) { pasl::util::atomic::msg(b); } template <class FRONTIER, class HEURISTIC, class VERTEX> std::atomic<long>* pwsa(graph<VERTEX>& graph, const HEURISTIC& heuristic, const intT& source, const intT& destination, int split_cutoff, int poll_cutoff) { intT N = graph.number_vertices(); std::atomic<long>* finalized = pasl::data::mynew_array<std::atomic<long>>(N); fill_array_par(finalized, N, -1l); FRONTIER initF = FRONTIER(); int heur = heuristic(source); VertexPackage vtxPackage = graph.make_vertex_package(source, false, 0); initF.insert(heur, vtxPackage); pasl::data::perworker::array<int> work_since_split; work_since_split.init(0); auto size = [&] (FRONTIER& frontier) { auto sz = frontier.total_weight(); if (sz == 0) { work_since_split.mine() = 0; return 0; // no work left } if (sz > split_cutoff || (work_since_split.mine() > split_cutoff && sz > 1)) { return 2; // split } else { return 1; // don't split } }; auto fork = [&] (FRONTIER& src, FRONTIER& dst) { print([&] { std::cout << "splitting "; src.display(); std::cout << std::endl; }); src.split_at(src.total_weight() / 2, dst); print([&] { std::cout << "produced "; src.display(); std::cout << "; "; dst.display(); std::cout << std::endl; }); work_since_split.mine() = 0; }; auto set_in_env = [&] (FRONTIER& f) { ; // nothing to do }; auto do_work = [&] (FRONTIER& frontier) { print([&] { std::cout << "Frontier dump: "; frontier.display(); std::cout << std::endl; }); int work_this_round = 0; while (work_this_round < poll_cutoff && frontier.total_weight() > 0) { auto pair = frontier.delete_min(); VertexPackage vpack = pair.second; long orig = -1l; if (vpack.mustProcess || (finalized[vpack.vertexId].load() == -1 && finalized[vpack.vertexId].compare_exchange_strong(orig, vpack.distance))) { if (vpack.vertexId == destination) { print([&] { std::cout << "FOUND DESTINATION: distance " << finalized[destination].load() << std::endl; }); return true; } if (work_this_round + vpack.weight() > poll_cutoff) { // need to split vpack VertexPackage other = VertexPackage(); vpack.split_at(poll_cutoff - work_this_round, other); other.mustProcess = true; if (other.weight() != 0) frontier.insert(pair.first, other); } // Have to process our vpack graph.apply_to_each_in_range(vpack, [&] (intT ngh, intT weight) { VertexPackage nghpack = graph.make_vertex_package(ngh, false, vpack.distance + weight); int heur = heuristic(ngh) + vpack.distance + weight; frontier.insert(heur, nghpack); print([&] { std::cout << "inserted pack "; nghpack.display(); std::cout << ": "; frontier.display(); std::cout << std::endl; }); }); work_this_round += vpack.weight(); } else { // Account 1 for popping. work_this_round += 1; } } work_since_split.mine() += work_this_round; return false; }; pasl::sched::native::parallel_while_pwsa(initF, size, fork, set_in_env, do_work); return finalized; } int main(int argc, char** argv) { long n; int split_cutoff; int poll_cutoff; std::string fname; int src; int dst; auto init = [&] { n = (long)pasl::util::cmdline::parse_or_default_long("n", 24); split_cutoff = (int)pasl::util::cmdline::parse_or_default_int("K", 100); poll_cutoff = (int)pasl::util::cmdline::parse_or_default_int("D", 100); fname = pasl::util::cmdline::parse_or_default_string("graph", "simple_weighted.txt"); src = (int)pasl::util::cmdline::parse_or_default_int("src", 0); dst = (int)pasl::util::cmdline::parse_or_default_int("dst", 0); }; auto run = [&] (bool sequential) { std::cout << n << std::endl; //char const* fname = "simple_weighted.txt"; //char const* fname = "simple_weighted_2.txt"; bool isSym = false; graph<asymmetricVertex> g = readGraphFromFile<asymmetricVertex>(fname.c_str(), isSym); g.printGraph(); auto heuristic = [] (intT vtx) { return 0; }; std::atomic<long>* res = pwsa<Treap<intT, VertexPackage>, decltype(heuristic), asymmetricVertex>(g, heuristic, src, dst, split_cutoff, poll_cutoff); for (int i = 0; i < g.n; i++) { std::cout << "res[" << i << "] = " << res[i].load() << std::endl; } }; auto output = [&] { ; }; auto destroy = [&] { ; }; pasl::sched::launch(argc, argv, init, run, output, destroy); return 0; } <commit_msg>cleanup<commit_after>/* COPYRIGHT (c) 2015 Sam Westrick, Laxman Dhulipala, Umut Acar, * Arthur Chargueraud, and Michael Rainey. * All rights reserved. * * \file pwsa.cpp * */ #include "benchmark.hpp" #include "treap-frontier.hpp" #include "weighted-graph.hpp" #include "native.hpp" #include "defaults.hpp" #include <cstring> static inline void pmemset(char * ptr, int value, size_t num) { const size_t cutoff = 100000; if (num <= cutoff) { std::memset(ptr, value, num); } else { long m = num/2; pasl::sched::native::fork2([&] { pmemset(ptr, value, m); }, [&] { pmemset(ptr+m, value, num-m); }); } } template <class Number, class Size> void fill_array_par(std::atomic<Number>* array, Size sz, Number val) { pmemset((char*)array, val, sz*sizeof(Number)); } bool shouldPrint = false; template <class Body> void print(const Body& b) { if (shouldPrint) { pasl::util::atomic::msg(b); } } template <class FRONTIER, class HEURISTIC, class VERTEX> std::atomic<long>* pwsa(graph<VERTEX>& graph, const HEURISTIC& heuristic, const intT& source, const intT& destination, int split_cutoff, int poll_cutoff) { intT N = graph.number_vertices(); std::atomic<long>* finalized = pasl::data::mynew_array<std::atomic<long>>(N); fill_array_par(finalized, N, -1l); FRONTIER initF = FRONTIER(); int heur = heuristic(source); VertexPackage vtxPackage = graph.make_vertex_package(source, false, 0); initF.insert(heur, vtxPackage); pasl::data::perworker::array<int> work_since_split; work_since_split.init(0); auto size = [&] (FRONTIER& frontier) { auto sz = frontier.total_weight(); if (sz == 0) { work_since_split.mine() = 0; return 0; // no work left } if (sz > split_cutoff || (work_since_split.mine() > split_cutoff && sz > 1)) { return 2; // split } else { return 1; // don't split } }; auto fork = [&] (FRONTIER& src, FRONTIER& dst) { print([&] { std::cout << "splitting "; src.display(); std::cout << std::endl; }); src.split_at(src.total_weight() / 2, dst); print([&] { std::cout << "produced "; src.display(); std::cout << "; "; dst.display(); std::cout << std::endl; }); work_since_split.mine() = 0; }; auto set_in_env = [&] (FRONTIER& f) {;}; auto do_work = [&] (FRONTIER& frontier) { print([&] { std::cout << "Frontier dump: "; frontier.display(); std::cout << std::endl; }); int work_this_round = 0; while (work_this_round < poll_cutoff && frontier.total_weight() > 0) { auto pair = frontier.delete_min(); VertexPackage vpack = pair.second; long orig = -1l; if (vpack.mustProcess || (finalized[vpack.vertexId].load() == -1 && finalized[vpack.vertexId].compare_exchange_strong(orig, vpack.distance))) { if (vpack.vertexId == destination) { print([&] { std::cout << "Found destination: distance = " << finalized[destination].load() << std::endl; }); return true; } if (work_this_round + vpack.weight() > poll_cutoff) { // need to split vpack VertexPackage other = VertexPackage(); vpack.split_at(poll_cutoff - work_this_round, other); other.mustProcess = true; if (other.weight() != 0) { frontier.insert(pair.first, other); } } // Have to process our vpack graph.apply_to_each_in_range(vpack, [&] (intT ngh, intT weight) { VertexPackage nghpack = graph.make_vertex_package(ngh, false, vpack.distance + weight); int heur = heuristic(ngh) + vpack.distance + weight; frontier.insert(heur, nghpack); print([&] { std::cout << "inserted pack "; nghpack.display(); std::cout << ": "; frontier.display(); std::cout << std::endl; }); }); work_this_round += vpack.weight(); } else { // Account 1 for popping. work_this_round += 1; } } work_since_split.mine() += work_this_round; return false; }; pasl::sched::native::parallel_while_pwsa(initF, size, fork, set_in_env, do_work); return finalized; } int main(int argc, char** argv) { int split_cutoff; // (K) int poll_cutoff; // (D) std::string fname; int src; int dst; auto init = [&] { split_cutoff = (int)pasl::util::cmdline::parse_or_default_int("K", 100); poll_cutoff = (int)pasl::util::cmdline::parse_or_default_int("D", 100); fname = pasl::util::cmdline::parse_or_default_string("graph", "graphs/simple_weighted.txt"); src = (int)pasl::util::cmdline::parse_or_default_int("src", 0); dst = (int)pasl::util::cmdline::parse_or_default_int("dst", 0); }; auto run = [&] (bool sequential) { bool isSym = false; graph<asymmetricVertex> g = readGraphFromFile<asymmetricVertex>(fname.c_str(), isSym); // g.printGraph(); auto heuristic = [] (intT vtx) { return 0; }; std::atomic<long>* res = pwsa<Treap<intT, VertexPackage>, decltype(heuristic), asymmetricVertex>(g, heuristic, src, dst, split_cutoff, poll_cutoff); int numExpanded = 0; for (int i = 0; i < g.n; i++) { if (res[i].load() != -1) { numExpanded++; } } std::cout << "expanded : " << numExpanded << " many nodes out of " << g.n; std::cout << "path lengh is : " << res[dst].load(); // for (int i = 0; i < g.n; i++) { // std::cout << "res[" << i << "] = " << res[i].load() << std::endl; // } }; auto output = [&] {;}; auto destroy = [&] {;}; pasl::sched::launch(argc, argv, init, run, output, destroy); return 0; } <|endoftext|>
<commit_before>/* * Priority.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "PortabilityImpl.hh" #include <log4cpp/Priority.hh> #include <cstdlib> namespace log4cpp { namespace { const std::string names[10] = { "FATAL", "ALERT", "CRIT", "ERROR", "WARN", "NOTICE", "INFO", "DEBUG", "NOTSET", "UNKNOWN" }; } const int log4cpp::Priority::MESSAGE_SIZE = 8; const std::string& Priority::getPriorityName(int priority) throw() { priority++; priority /= 100; return names[((priority < 0) || (priority > 8)) ? 8 : priority]; } Priority::Value Priority::getPriorityValue(const std::string& priorityName) throw(std::invalid_argument) { Priority::Value value = -1; for (unsigned int i = 0; i < 10; i++) { if (priorityName == names[i]) { value = i * 100; break; } } if (value == -1) { if (priorityName == "EMERG") { value = 0; } else { char* endPointer; value = std::strtoul(priorityName.c_str(), &endPointer, 10); if (*endPointer != 0) { throw std::invalid_argument( std::string("unknown priority name: '") + priorityName + "'" ); } } } return value; } } <commit_msg>Fix for bug#3198140<commit_after>/* * Priority.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "PortabilityImpl.hh" #include <log4cpp/Priority.hh> #include <cstdlib> namespace log4cpp { namespace { const std::string *names() { static const std::string priority_names[10] = { "FATAL", "ALERT", "CRIT", "ERROR", "WARN", "NOTICE", "INFO", "DEBUG", "NOTSET", "UNKNOWN" }; return priority_names; } } const int log4cpp::Priority::MESSAGE_SIZE = 8; const std::string& Priority::getPriorityName(int priority) throw() { priority++; priority /= 100; return names()[((priority < 0) || (priority > 8)) ? 8 : priority]; } Priority::Value Priority::getPriorityValue(const std::string& priorityName) throw(std::invalid_argument) { Priority::Value value = -1; for (unsigned int i = 0; i < 10; i++) { if (priorityName == names()[i]) { value = i * 100; break; } } if (value == -1) { if (priorityName == "EMERG") { value = 0; } else { char* endPointer; value = std::strtoul(priorityName.c_str(), &endPointer, 10); if (*endPointer != 0) { throw std::invalid_argument( std::string("unknown priority name: '") + priorityName + "'" ); } } } return value; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // based on // https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp #ifndef JSON_V8_RENDERER_HPP #define JSON_V8_RENDERER_HPP #include <osrm/json_container.hpp> // v8 #include <nan.h> #include <functional> namespace node_osrm { struct V8Renderer : mapbox::util::static_visitor<> { explicit V8Renderer(v8::Local<v8::Value> &_out) : out(_out) {} void operator()(const osrm::json::String &string) const { out = Nan::New(std::cref(string.value)).ToLocalChecked(); } void operator()(const osrm::json::Number &number) const { out = Nan::New(number.value); } void operator()(const osrm::json::Object &object) const { v8::Local<v8::Object> obj = Nan::New<v8::Object>(); for (const auto &keyValue : object.values) { v8::Local<v8::Value> child; mapbox::util::apply_visitor(v8_renderer(child), keyValue.second); obj->Set(Nan::New(keyValue.first).ToLocalChecked(), child); } out = obj; } void operator()(const osrm::json::Array &array) const { v8::Local<v8::Array> a = Nan::New<v8::Array>(array.values.size()); for (auto i = 0u; i < array.values.size(); ++i) { v8::Local<v8::Value> child; mapbox::util::apply_visitor(v8_renderer(child), array.values[i]); a->Set(i, child); } out = a; } void operator()(const osrm::json::True &) const { out = Nan::New(true); } void operator()(const osrm::json::False &) const { out = Nan::New(false); } void operator()(const osrm::json::Null &) const { out = Nan::Null(); } private: v8::Local<v8::Value> &out; }; inline void renderToV8(v8::Local<v8::Value> &out, const osrm::json::Object &object) { // FIXME this should be a cast? osrm::json::Value value = object; mapbox::util::apply_visitor(V8Renderer(out), value); } } #endif // JSON_V8_RENDERER_HPP <commit_msg>Fix v8 renderer<commit_after>/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // based on // https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp #ifndef JSON_V8_RENDERER_HPP #define JSON_V8_RENDERER_HPP #include <osrm/json_container.hpp> // v8 #include <nan.h> #include <functional> namespace node_osrm { struct V8Renderer : mapbox::util::static_visitor<> { explicit V8Renderer(v8::Local<v8::Value> &_out) : out(_out) {} void operator()(const osrm::json::String &string) const { out = Nan::New(std::cref(string.value)).ToLocalChecked(); } void operator()(const osrm::json::Number &number) const { out = Nan::New(number.value); } void operator()(const osrm::json::Object &object) const { v8::Local<v8::Object> obj = Nan::New<v8::Object>(); for (const auto &keyValue : object.values) { v8::Local<v8::Value> child; mapbox::util::apply_visitor(V8Renderer(child), keyValue.second); obj->Set(Nan::New(keyValue.first).ToLocalChecked(), child); } out = obj; } void operator()(const osrm::json::Array &array) const { v8::Local<v8::Array> a = Nan::New<v8::Array>(array.values.size()); for (auto i = 0u; i < array.values.size(); ++i) { v8::Local<v8::Value> child; mapbox::util::apply_visitor(V8Renderer(child), array.values[i]); a->Set(i, child); } out = a; } void operator()(const osrm::json::True &) const { out = Nan::New(true); } void operator()(const osrm::json::False &) const { out = Nan::New(false); } void operator()(const osrm::json::Null &) const { out = Nan::Null(); } private: v8::Local<v8::Value> &out; }; inline void renderToV8(v8::Local<v8::Value> &out, const osrm::json::Object &object) { // FIXME this should be a cast? osrm::json::Value value = object; mapbox::util::apply_visitor(V8Renderer(out), value); } } #endif // JSON_V8_RENDERER_HPP <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: k_means_iteration.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: hjm211324@gmail.com * Date: Jul 19, 2015 * Time: 20:55:38 * Description: *****************************************************************************/ #include <iostream> #include <fstream> #include <cassert> #include <unordered_map> #include <algorithm> #include "hadoop/Pipes.hh" #include "hadoop/TemplateFactory.hh" #include "hadoop/StringUtils.hh" #include "netflix_movie.h" constexpr size_t canopy_threshold = 2; const std::string canopy_centers_path = "canopy_centers"; const std::string k_means_center_path = "k_means_centers"; inline std::string to_hex_string(const size_t x) { char buff[32] = { 0 }; sprintf(buff, "%zx", x); return buff; } inline std::vector<uint32_t> string_split(const std::string& str) { std::vector<uint32_t> numbers; char* offset; const char* end = str.data() + str.length(); const char* tmp = str.data(); while (tmp < end) { uint32_t movie_id = strtoul(tmp, &offset, 16); numbers.emplace_back(movie_id); tmp = offset + 1; } return numbers; } class kMeansMapper: public HadoopPipes::Mapper { public: kMeansMapper(HadoopPipes::TaskContext& /* context */) { load_canopy_centers(); load_kmeans_centers(); // no use anymore canopy_centers.clear(); } void map(HadoopPipes::MapContext& context) { std::string input_value = context.getInputValue(); std::string movie_string = input_value.substr(0, input_value.find_first_of('\t')) + ':' + input_value.substr(input_value.find_first_of(';') + 1); Movie movie = movie_string; size_t start_pos = input_value.find_first_of('\t'); size_t end_pos = input_value.find_first_of(';', start_pos); std::vector<uint32_t> canopy_ids = string_split(input_value.substr(start_pos + 1, end_pos - start_pos - 1)); float max_distance = -1; const Movie* max_distance_movie = nullptr; for (const auto canopy_id: canopy_ids) { if (canopy_id == movie.movie_id()) continue; for (const auto& k_means_center: centers[canopy_id]) { float distance = movie.cos_distance(k_means_center); if (distance > max_distance) { max_distance = distance; max_distance_movie = &k_means_center; } } } std::string emit_key = max_distance_movie->to_string(); std::string emit_value = movie_string; context.emit(emit_key, emit_value); } private: void load_canopy_centers() { std::ifstream fin(canopy_centers_path); std::string line; while (std::getline(fin, line)) canopy_centers.emplace_back(line); } void load_kmeans_centers() { std::ifstream fin(k_means_center_path); std::string line; while (std::getline(fin, line)) { Movie k_means_center(line); for (const auto& canopy_center: canopy_centers) if (k_means_center.user_match_count(canopy_center) > canopy_threshold) { auto ite = centers.emplace(canopy_center.movie_id(), std::vector<Movie>()).first; ite->second.push_back(k_means_center); } } } std::vector<Movie> canopy_centers; // canopy movie_id, vector of k-means centers std::unordered_map< uint32_t, std::vector<Movie> > centers; }; class kMeansReducer: public HadoopPipes::Reducer { public: kMeansReducer(const HadoopPipes::TaskContext& /* context */) { } void reduce(HadoopPipes::ReduceContext& context) { Movie k_means_center(context.getInputKey()); // <user id, < number of users, total user ratings > > std::unordered_map<uint32_t, std::pair<uint32_t, uint32_t> > new_features; while (context.nextValue()) { Movie movie(context.getInputValue()); for (size_t i = 0; i < movie.num_users(); ++i) { auto ite = new_features.emplace(movie.user_id(i), std::make_pair(0, 0)).first; ite->second.first += 1; ite->second.second += movie.rating(i); } } std::vector< std::pair<uint32_t, uint32_t> > new_features_vec; for (const auto i: new_features) new_features_vec.push_back({ i.first, i.second.second / i.second.first }); sort(new_features_vec.begin(), new_features_vec.end()); std::string emit_key = to_hex_string(k_means_center.movie_id()); std::string emit_value; for (const auto i: new_features_vec) emit_value += to_hex_string(i.first) + ',' + to_hex_string(i.second) + ','; if (emit_value.size()) { emit_value.pop_back(); context.emit(emit_key, emit_value); } } }; int main(int, char**) { return HadoopPipes::runTask(HadoopPipes::TemplateFactory<kMeansMapper, kMeansReducer>()); } <commit_msg>fix bug<commit_after>/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: k_means_iteration.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: hjm211324@gmail.com * Date: Jul 19, 2015 * Time: 20:55:38 * Description: *****************************************************************************/ #include <iostream> #include <fstream> #include <cassert> #include <unordered_map> #include <algorithm> #include "hadoop/Pipes.hh" #include "hadoop/TemplateFactory.hh" #include "hadoop/StringUtils.hh" #include "netflix_movie.h" constexpr size_t canopy_threshold = 2; const std::string canopy_centers_path = "canopy_centers"; const std::string k_means_center_path = "k_means_centers"; inline std::string to_hex_string(const size_t x) { char buff[32] = { 0 }; sprintf(buff, "%zx", x); return buff; } inline std::vector<uint32_t> string_split(const std::string& str) { std::vector<uint32_t> numbers; char* offset; const char* end = str.data() + str.length(); const char* tmp = str.data(); while (tmp < end) { uint32_t movie_id = strtoul(tmp, &offset, 16); numbers.emplace_back(movie_id); tmp = offset + 1; } return numbers; } class kMeansMapper: public HadoopPipes::Mapper { public: kMeansMapper(HadoopPipes::TaskContext& /* context */) { load_canopy_centers(); load_kmeans_centers(); // no use anymore canopy_centers.clear(); } void map(HadoopPipes::MapContext& context) { std::string input_value = context.getInputValue(); std::string movie_string = input_value.substr(0, input_value.find_first_of('\t')) + ':' + input_value.substr(input_value.find_first_of(';') + 1); Movie movie = movie_string; std::cout << "Load input movie: " << movie.to_string() << std::endl; size_t start_pos = input_value.find_first_of('\t'); size_t end_pos = input_value.find_first_of(';', start_pos); std::vector<uint32_t> canopy_ids = string_split(input_value.substr(start_pos + 1, end_pos - start_pos - 1)); std::cout << "canopy_ids: "; for (const auto i: canopy_ids) std::cout << i << ' '; std::cout << std::endl; float max_distance = -1; const Movie* max_distance_movie = nullptr; for (const auto canopy_id: canopy_ids) { if (canopy_id == movie.movie_id()) continue; for (const auto& k_means_center: centers[canopy_id]) { float distance = movie.cos_distance(k_means_center); std::cout << "Distance with " << k_means_center.to_string() << " is " << distance; if (distance > max_distance) { std::cout << " is max. "; max_distance = distance; max_distance_movie = &k_means_center; } std::cout << std::endl; } } if (max_distance_movie == nullptr) return; std::string emit_key = max_distance_movie->to_string(); std::string emit_value = movie_string; std::cout << "emit_key = " << emit_key << std::endl; std::cout << "emit_value = " << emit_value << std::endl; context.emit(emit_key, emit_value); } private: void load_canopy_centers() { std::ifstream fin(canopy_centers_path); std::string line; while (std::getline(fin, line)) { canopy_centers.emplace_back(line); std::cout << "Load cannopy center: " << canopy_centers.back().to_string() << std::endl; } } void load_kmeans_centers() { std::ifstream fin(k_means_center_path); std::string line; while (std::getline(fin, line)) { Movie k_means_center(line); std::cout << "k-means center: " << k_means_center.to_string() << " "; for (const auto& canopy_center: canopy_centers) if (k_means_center.user_match_count(canopy_center) > canopy_threshold) { std::cout << "applied to canopy " << canopy_center.to_string() << " "; auto ite = centers.emplace(canopy_center.movie_id(), std::vector<Movie>()).first; ite->second.push_back(k_means_center); } std::cout << std::endl; } } std::vector<Movie> canopy_centers; // canopy movie_id, vector of k-means centers std::unordered_map< uint32_t, std::vector<Movie> > centers; }; class kMeansReducer: public HadoopPipes::Reducer { public: kMeansReducer(const HadoopPipes::TaskContext& /* context */) { } void reduce(HadoopPipes::ReduceContext& context) { Movie k_means_center(context.getInputKey()); // <user id, < number of users, total user ratings > > std::unordered_map<uint32_t, std::pair<uint32_t, uint32_t> > new_features; while (context.nextValue()) { Movie movie(context.getInputValue()); for (size_t i = 0; i < movie.num_users(); ++i) { auto ite = new_features.emplace(movie.user_id(i), std::make_pair(0, 0)).first; ite->second.first += 1; ite->second.second += movie.rating(i); } } std::vector< std::pair<uint32_t, uint32_t> > new_features_vec; for (const auto i: new_features) new_features_vec.push_back({ i.first, i.second.second / i.second.first }); sort(new_features_vec.begin(), new_features_vec.end()); std::string emit_key = to_hex_string(k_means_center.movie_id()); std::string emit_value; for (const auto i: new_features_vec) emit_value += to_hex_string(i.first) + ',' + to_hex_string(i.second) + ','; if (emit_value.size()) { emit_value.pop_back(); context.emit(emit_key, emit_value); } } }; int main(int, char**) { return HadoopPipes::runTask(HadoopPipes::TemplateFactory<kMeansMapper, kMeansReducer>()); } <|endoftext|>
<commit_before>/* GG is a GUI for SDL and OpenGL. Copyright (C) 2003 T. Zachary Laine 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 If you do not wish to comply with the terms of the LGPL please contact the author as other terms are available for a fee. Zach Laine whatwasthataddress@hotmail.com */ /* $Header$ */ #include "SDLGGApp.h" using std::string; // member functions SDLGGApp::SDLGGApp(int w/* = 1024*/, int h/* = 768*/, bool calc_FPS/* = false*/, const std::string& app_name/* = "GG"*/) : GG::App(this, app_name), m_app_width(w), m_app_height(h), m_delta_t(1), m_FPS(-1.0), m_calc_FPS(calc_FPS) { } SDLGGApp::~SDLGGApp() { SDLQuit(); } SDLGGApp* SDLGGApp::GetApp() { return dynamic_cast<SDLGGApp*>(GG::App::GetApp()); } void SDLGGApp::Exit(int code) { Logger().fatalStream() << "Initiating Exit (code " << code << " - " << (code ? "error" : "normal") << " termination)"; SDLQuit(); exit(code); } void SDLGGApp::CalcuateFPS(bool b/* = true*/) { m_calc_FPS = b; if (!b) m_FPS = -1.0f; } const string& SDLGGApp::FPSString() const { static string retval; char buf[64]; sprintf(buf, "%.2f frames per second", m_FPS); retval = buf; return retval; } GG::Key SDLGGApp::GGKeyFromSDLKey(const SDL_keysym& key) { GG::Key retval = GG::Key(key.sym); bool shift = key.mod & KMOD_SHIFT; bool caps_lock = key.mod & KMOD_CAPS; // this code works because both SDLKey and GG::Key map (at least // partially) to the printable ASCII characters if (shift || caps_lock) { if (shift != caps_lock && (retval >= 'a' && retval <= 'z')) { retval = GG::Key(toupper(retval)); } else if (shift) { // the caps lock key should not affect these // this assumes a US keyboard layout switch (retval) { case '`': retval = GG::Key('~'); break; case '1': retval = GG::Key('!'); break; case '2': retval = GG::Key('@'); break; case '3': retval = GG::Key('#'); break; case '4': retval = GG::Key('$'); break; case '5': retval = GG::Key('%'); break; case '6': retval = GG::Key('^'); break; case '7': retval = GG::Key('&'); break; case '8': retval = GG::Key('*'); break; case '9': retval = GG::Key('('); break; case '0': retval = GG::Key(')'); break; case '-': retval = GG::Key('_'); break; case '=': retval = GG::Key('+'); break; case '[': retval = GG::Key('{'); break; case ']': retval = GG::Key('}'); break; case '\\': retval = GG::Key('|'); break; case ';': retval = GG::Key(':'); break; case '\'': retval = GG::Key('"'); break; case ',': retval = GG::Key('<'); break; case '.': retval = GG::Key('>'); break; case '/': retval = GG::Key('?'); break; default: break; } } } return retval; } void SDLGGApp::SDLInit() { const SDL_VideoInfo* vid_info = 0; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { Logger().errorStream() << "SDL initialization failed: " << SDL_GetError(); Exit(1); } if (SDLNet_Init() < 0) { Logger().errorStream() << "SDL Net initialization failed: " << SDLNet_GetError(); Exit(1); } if (TTF_Init() < 0) { Logger().errorStream() << "TTF initialization failed: " << TTF_GetError(); Exit(1); } if (FE_Init() < 0) { Logger().errorStream() << "FastEvents initialization failed: " << FE_GetError(); Exit(1); } vid_info = SDL_GetVideoInfo(); if (!vid_info) { Logger().errorStream() << "Video info query failed: " << SDL_GetError(); Exit(1); } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (SDL_SetVideoMode(m_app_width, m_app_height, 16, SDL_OPENGL) == 0) { Logger().errorStream() << "Video mode set failed: " << SDL_GetError(); Exit(1); } if (NET2_Init() < 0) { Logger().errorStream() << "SDL Net2 initialization failed: " << NET2_GetError(); Exit(1); } SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); EnableMouseDragRepeat(SDL_DEFAULT_REPEAT_DELAY / 2, SDL_DEFAULT_REPEAT_INTERVAL / 2); Logger().debugStream() << "SDLInit() complete."; GLInit(); } void SDLGGApp::GLInit() { double ratio = m_app_width / (float)(m_app_height); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0); glViewport(0, 0, m_app_width - 1, m_app_height - 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(50.0, ratio, 1.0, 10.0); Logger().debugStream() << "GLInit() complete."; } void SDLGGApp::HandleSDLEvent(const SDL_Event& event) { bool send_to_gg = false; GG::App::EventType gg_event; GG::Key key = GGKeyFromSDLKey(event.key.keysym); Uint32 key_mods = SDL_GetModState(); GG::Pt mouse_pos(event.motion.x, event.motion.y); GG::Pt mouse_rel(event.motion.xrel, event.motion.yrel); switch(event.type) { case SDL_KEYDOWN: if (key < GG::GGK_NUMLOCK) send_to_gg = true; gg_event = GG::App::KEYPRESS; break; case SDL_MOUSEMOTION: send_to_gg = true; gg_event = GG::App::MOUSEMOVE; break; case SDL_MOUSEBUTTONDOWN: send_to_gg = true; switch (event.button.button) { case SDL_BUTTON_LEFT: gg_event = GG::App::LPRESS; break; case SDL_BUTTON_MIDDLE: gg_event = GG::App::MPRESS; break; case SDL_BUTTON_RIGHT: gg_event = GG::App::RPRESS; break; case SDL_BUTTON_WHEELUP: gg_event = GG::App::MOUSEWHEEL; mouse_rel = GG::Pt(0, 1); break; case SDL_BUTTON_WHEELDOWN: gg_event = GG::App::MOUSEWHEEL; mouse_rel = GG::Pt(0, -1); break; } key_mods = SDL_GetModState(); break; case SDL_MOUSEBUTTONUP: send_to_gg = true; switch (event.button.button) { case SDL_BUTTON_LEFT: gg_event = GG::App::LRELEASE; break; case SDL_BUTTON_MIDDLE: gg_event = GG::App::MRELEASE; break; case SDL_BUTTON_RIGHT: gg_event = GG::App::RRELEASE; break; } key_mods = SDL_GetModState(); break; case SDL_QUIT: Exit(0); break; } if (send_to_gg) GG::App::HandleEvent(gg_event, key, key_mods, mouse_pos, mouse_rel); } void SDLGGApp::RenderBegin() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void SDLGGApp::RenderEnd() { SDL_GL_SwapBuffers(); } void SDLGGApp::SDLQuit() { FinalCleanup(); NET2_Quit(); FE_Quit(); TTF_Quit(); SDLNet_Quit(); SDL_Quit(); Logger().debugStream() << "SDLQuit() complete."; } void SDLGGApp::PollAndRender() { static int last_FPS_time = 0; static int most_recent_time = 0; static int time = 0; static int frames = 0; static int last_mouse_event_time = 0; static int mouse_drag_repeat_start_time = 0; static int last_mouse_drag_repeat_time = 0; static int old_mouse_repeat_delay = MouseRepeatDelay(); static int old_mouse_repeat_interval = MouseRepeatInterval(); // handle events SDL_Event event; while (0 < FE_PollEvent(&event)) { if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEMOTION) last_mouse_event_time = time; HandleSDLEvent(event); } // update time and track FPS if needed time = SDL_GetTicks(); m_delta_t = time - most_recent_time; if (m_calc_FPS) { ++frames; if (time - last_FPS_time > 1000) { // calculate FPS at most once a second m_FPS = frames / ((time - last_FPS_time) / 1000.0f); last_FPS_time = time; frames = 0; } } most_recent_time = time; // handle mouse drag repeats if (old_mouse_repeat_delay != MouseRepeatDelay() || old_mouse_repeat_interval != MouseRepeatInterval()) { // if there's a change in the values, zero everything out and start the counting over old_mouse_repeat_delay = MouseRepeatDelay(); old_mouse_repeat_interval = MouseRepeatInterval(); mouse_drag_repeat_start_time = 0; last_mouse_drag_repeat_time = 0; } int x, y; // if drag repeat is enabled, the left mouse button is depressed (a drag is ocurring), and the last event processed wasn't too recent if (MouseRepeatDelay() && SDL_GetMouseState(&x, &y) & SDL_BUTTON_LEFT && time - last_mouse_event_time > old_mouse_repeat_interval) { if (!mouse_drag_repeat_start_time) { // if we're just starting the drag, mark the time we started mouse_drag_repeat_start_time = time; } else if (mouse_drag_repeat_start_time == MouseRepeatDelay()) { // if we're counting repeat intervals if (time - last_mouse_drag_repeat_time > MouseRepeatInterval()) { last_mouse_drag_repeat_time = time; event.type = SDL_MOUSEMOTION; event.motion.x = x; event.motion.y = y; event.motion.xrel = event.motion.yrel = 0; // this is just an update, so set the motion to 0 HandleSDLEvent(event); } } else if (time - mouse_drag_repeat_start_time > MouseRepeatDelay()) { // if we're done waiting for the initial delay period mouse_drag_repeat_start_time = MouseRepeatDelay(); // set this as equal so we know later that we've passed the delay interval last_mouse_drag_repeat_time = time; event.type = SDL_MOUSEMOTION; event.motion.x = x; event.motion.y = y; event.motion.xrel = event.motion.yrel = 0; HandleSDLEvent(event); } } else { // otherwise, reset the mouse drag repeat start time to zero mouse_drag_repeat_start_time = 0; } // do one iteration of the render loop Update(); RenderBegin(); Render(); RenderEnd(); } void SDLGGApp::Run() { try { SDLInit(); Initialize(); while (1) PollAndRender(); } catch (const std::invalid_argument& exception) { Logger().fatal("std::invalid_argument Exception caught in App::Run(): " + string(exception.what())); Exit(1); } catch (const std::runtime_error& exception) { Logger().fatal("std::runtime_error Exception caught in App::Run(): " + string(exception.what())); Exit(1); } catch (const GG::GGException& exception) { Logger().fatal("GG::GGException (subclass " + string(exception.what()) + ") caught in App::Run(): " + exception.Message()); Exit(1); } } <commit_msg>Moved to its own directory.<commit_after><|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <service> #include <info> #define ARGS_MAX 64 __attribute__((weak)) extern "C" int main(int, const char*[]); __attribute__((weak)) void Service::start(const std::string& cmd) { std::string st(cmd); // mangled copy int argc = 0; const char* argv[ARGS_MAX]; // Populate argv char* begin = (char*) st.data(); char* end = begin + st.size(); for (char* ptr = begin; ptr < end; ptr++) if (std::isspace(*ptr)) { argv[argc++] = begin; *ptr = 0; // zero terminate begin = ptr+1; // next arg if (argc >= ARGS_MAX) break; } int exit_status = main(argc, argv); INFO("main","returned with status %d", exit_status); //exit(exit_status); } <commit_msg>main: new argparser now finds last arg and handles n spaces<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <service> #include <info> #define ARGS_MAX 64 __attribute__((weak)) extern "C" int main(int, const char*[]); __attribute__((weak)) void Service::start(const std::string& cmd) { std::string st(cmd); // mangled copy int argc = 0; const char* argv[ARGS_MAX]; // Get pointers to null-terminated string char* word = (char*) st.c_str(); char* end = word + st.size() + 1; bool new_word = false; for (char* ptr = word; ptr < end; ptr++) { // Replace all spaces with 0 if(std::isspace(*ptr)) { *ptr = 0; new_word = true; continue; } // At the start of each word, or last byte, add previous pointer to array if (new_word or ptr == end - 1) { argv[argc++] = word; word = ptr; // next arg if (argc >= ARGS_MAX) break; new_word = false; } } int exit_status = main(argc, argv); INFO("main","returned with status %d", exit_status); } <|endoftext|>
<commit_before>/************************************************************************* > Author: Wayne Ho > Purpose: TODO > Created Time: Wed 03 Jun 2015 11:01:35 AM CST > Mail: hewr2010@gmail.com ************************************************************************/ #include "storage/graph_builder.h" #include <iostream> #include <cstdio> #include <fstream> using namespace std; using namespace sae::io; int main(int argc, char **argv) { GraphBuilder<int> graph; ifstream fin("./resource/amazon0312.txt"); string buf; for (int i = 0; i < 4; ++i) getline(fin, buf); int v_cnt(-1); while (1) { int x, y; if (!(fin >> x >> y)) break; int z = max(max(v_cnt, x), y); while (v_cnt < z) graph.AddVertex(++v_cnt, 0); graph.AddEdge(x, y, 0); } cout << graph.VertexCount() << " " << graph.EdgeCount() << endl; graph.Save("./data/graph"); return 0; } <commit_msg>update<commit_after>/************************************************************************* > Author: Wayne Ho > Purpose: TODO > Created Time: Wed 03 Jun 2015 11:01:35 AM CST > Mail: hewr2010@gmail.com ************************************************************************/ #include "storage/graph_builder.h" #include <iostream> #include <cstdio> #include <fstream> #include <map> using namespace std; using namespace sae::io; map<string, int> nodeMap; int GetOrInsert(const string& key) { map<string, int>::iterator it = nodeMap.find(key); if (it != nodeMap.end()) return it -> second; int id = (int) nodeMap.size(); nodeMap.insert(make_pair(key, id)); return id; } int main(int argc, char **argv) { GraphBuilder<int> graph; //ifstream fin("./resource/amazon0312.txt"); ifstream fin("./resource/twitter_combined.txt"); string buf; //for (int i = 0; i < 4; ++i) getline(fin, buf); int v_cnt(-1); map<string, int> nodeMap; while (1) { string x, y; if (!(fin >> x >> y)) break; int a = GetOrInsert(x); int b = GetOrInsert(y); int c = max(max(v_cnt, a), b); while (v_cnt < c) graph.AddVertex(++v_cnt, 0); graph.AddEdge(a, b, 0); } cout << graph.VertexCount() << " " << graph.EdgeCount() << endl; graph.Save("./data/twitter"); return 0; } <|endoftext|>
<commit_before>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #ifndef _WORLDMAP_HPP_ #define _WORLDMAP_HPP_ #include <memory> #include <vector> #include <unordered_map> #include "globals.hpp" class Field; class Map; class WorldMap { using map_t = std::shared_ptr<Map>; using map_vector_t = std::vector<map_t>; map_vector_t maps; std::unordered_map<position, map_t> world_map; size_t ageIndex = 0; public: void clear(); Field &at(const position &pos) const; Field &walkableNear(position &pos) const; bool intersects(const Map &map) const; bool insert(map_t newMap); bool allMapsAged(); bool import(const std::string &importDir, const std::string &mapName); bool exportTo(const std::string &exportDir) const; bool loadFromDisk(const std::string &prefix); void saveToDisk(const std::string &prefix) const; bool createMap(const std::string &name, const position &origin, uint16_t width, uint16_t height, uint16_t tile); private: static map_t createMapFromHeaderFile(const std::string &importDir, const std::string &mapName); static int16_t readHeaderLine(const std::string &mapName, char header, std::ifstream &headerFile, int &lineNumber); static bool isCommentOrEmpty(const std::string &line); }; #endif <commit_msg>Make inserting maps private to WorldMap<commit_after>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #ifndef _WORLDMAP_HPP_ #define _WORLDMAP_HPP_ #include <memory> #include <vector> #include <unordered_map> #include "globals.hpp" class Field; class Map; class WorldMap { using map_t = std::shared_ptr<Map>; using map_vector_t = std::vector<map_t>; map_vector_t maps; std::unordered_map<position, map_t> world_map; size_t ageIndex = 0; public: void clear(); Field &at(const position &pos) const; Field &walkableNear(position &pos) const; bool intersects(const Map &map) const; bool allMapsAged(); bool import(const std::string &importDir, const std::string &mapName); bool exportTo(const std::string &exportDir) const; bool loadFromDisk(const std::string &prefix); void saveToDisk(const std::string &prefix) const; bool createMap(const std::string &name, const position &origin, uint16_t width, uint16_t height, uint16_t tile); private: bool insert(map_t newMap); static map_t createMapFromHeaderFile(const std::string &importDir, const std::string &mapName); static int16_t readHeaderLine(const std::string &mapName, char header, std::ifstream &headerFile, int &lineNumber); static bool isCommentOrEmpty(const std::string &line); }; #endif <|endoftext|>
<commit_before><commit_msg>Grabber class now receives objects names when collision<commit_after><|endoftext|>
<commit_before>// //#include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <ctime> #include <algorithm> #include <cmath> #include "GPIOClass.h" using namespace std; void Pulse(GPIOClass* pin, double cycles); void Wait(double seconds); clock_t timer; double time_to_complete; double resolution = 100; #define PI 4*atan(1) int main (int argc, char *argv[]) { string type = argv[1]; transform(type.begin(), type.end(), type.begin(), :: tolower); // lets assume that the way to run this is // pwm.exe [rising/falling/sine/constant] if (argc != 2) { cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl; return -1; } while (time_to_complete <= 0) { cout << "Input How Long To Run (in seconds)" << endl; cin >> time_to_complete; } GPIOClass* out1 = new GPIOClass("4"); GPIOClass* in2 = new GPIOClass("17"); out1->export_gpio(); in2->export_gpio(); out1->setdir_gpio("out"); in2->setdir_gpio("in"); cout << "Pins are setup." << endl; // avoiding flickering will be at 100hz // aka turn on and off 100 times a sec // a cycle of 0 is off // a cycle of 100 is on if (type == "rising") { clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, sin((PI/2) * time_to_complete)); Wait(sin((PI/2) * time_to_complete)); } } if (type == "falling") { } if (type == "sine") { } if (type == "constant") { out1->setval_gpio("1"); // turn the pin on Wait(time_to_complete); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; out1->setval_gpio("0"); // turn the pin off } if (type == "blink") { // aka. TESTR clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, 1 * resolution); Wait(0.5); } } cout << "Done." << endl; } //1 cycle is 1/100th of a second //100 cycles is 1 sec void Pulse(GPIOClass* pin, double cycles) { bool running = true; while (running) { pin->setval_gpio("1"); // turn the pin on Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; pin->setval_gpio("0"); // turn the pin off running = false; // this is unnessesary but could be useful if modified a bit. } } void Wait ( double seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } <commit_msg>Update pwm.cpp<commit_after>// //#include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <ctime> #include <algorithm> #include <cmath> #include "GPIOClass.h" using namespace std; void Pulse(GPIOClass* pin, double cycles); void Wait(double seconds); clock_t timer; double time_to_complete; double resolution = 100; #define PI 4*atan(1) int main (int argc, char *argv[]) { string type = argv[1]; transform(type.begin(), type.end(), type.begin(), :: tolower); // lets assume that the way to run this is // pwm.exe [rising/falling/sine/constant] if (argc != 2) { cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl; return -1; } while (time_to_complete <= 0) { cout << "Input How Long To Run (in seconds)" << endl; cin >> time_to_complete; } GPIOClass* out1 = new GPIOClass("4"); GPIOClass* in2 = new GPIOClass("17"); out1->export_gpio(); in2->export_gpio(); out1->setdir_gpio("out"); in2->setdir_gpio("in"); cout << "Pins are setup." << endl; // avoiding flickering will be at 100hz // aka turn on and off 100 times a sec // a cycle of 0 is off // a cycle of 100 is on if (type == "rising") { clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, sin((PI/2) * (1/time_to_complete))); Wait(sin((PI/2) * (1/time_to_complete))); } } if (type == "falling") { } if (type == "sine") { } if (type == "constant") { out1->setval_gpio("1"); // turn the pin on Wait(time_to_complete); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; out1->setval_gpio("0"); // turn the pin off } if (type == "blink") { // aka. TESTR clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, 1 * resolution); Wait(0.5); } } cout << "Done." << endl; } //1 cycle is 1/100th of a second //100 cycles is 1 sec void Pulse(GPIOClass* pin, double cycles) { bool running = true; while (running) { pin->setval_gpio("1"); // turn the pin on Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; pin->setval_gpio("0"); // turn the pin off running = false; // this is unnessesary but could be useful if modified a bit. } } void Wait ( double seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } <|endoftext|>
<commit_before><commit_msg>Fix voxel grid<commit_after><|endoftext|>
<commit_before> #include "pin.H" #include "Triton.h" static std::string replaceEq(std::string str, const std::string from, const std::string to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return NULL; str.replace(start_pos, from.length(), to); return str; } static std::string formulaReconstruction(UINT64 id) { int value; std::size_t found; std::stringstream formula; std::stringstream from; std::stringstream to; formula.str(symbolicEngine->getElementFromId(id)->getSource()); while (formula.str().find("#") != std::string::npos){ from.str(""); to.str(""); found = formula.str().find("#") + 1; std::string subs = formula.str().substr(found, std::string::npos); value = atoi(subs.c_str()); from << "#" << value; to.str(symbolicEngine->getElementFromId(value)->getSource()); formula.str(replaceEq(formula.str(), from.str(), to.str())); } return formula.str(); } SolverEngine::SolverEngine(SymbolicEngine *symEngine) { this->symEngine = symEngine; } SolverEngine::~SolverEngine() { } VOID SolverEngine::solveFromID(UINT64 id) { std::stringstream formula; std::cout << 1 << std::endl; formula.str(formulaReconstruction(symEngine->symbolicReg[ID_ZF])); this->formula << this->symEngine->getSmt2LibVarsDecl(); this->formula << formula.str(); this->ctx = new z3::context(); Z3_ast ast = Z3_parse_smtlib2_string(*this->ctx, this->formula.str().c_str(), 0, 0, 0, 0, 0, 0); z3::expr eq(*this->ctx, ast); this->solver = new z3::solver(*this->ctx); this->solver->add(eq); this->solver->check(); } VOID SolverEngine::displayModel() { z3::model m = this->solver->get_model(); std::cout << "----- Model -----" << std::endl << m << std::endl << "-----------------" << std::endl; } z3::model SolverEngine::getModel() { return this->solver->get_model(); } std::string SolverEngine::getFormula() { return this->formula.str(); } <commit_msg>Feature #10: Use QF_AUFBV<commit_after> #include "pin.H" #include "Triton.h" static std::string replaceEq(std::string str, const std::string from, const std::string to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return NULL; str.replace(start_pos, from.length(), to); return str; } static std::string formulaReconstruction(UINT64 id) { int value; std::size_t found; std::stringstream formula; std::stringstream from; std::stringstream to; formula.str(symbolicEngine->getElementFromId(id)->getSource()); while (formula.str().find("#") != std::string::npos){ from.str(""); to.str(""); found = formula.str().find("#") + 1; std::string subs = formula.str().substr(found, std::string::npos); value = atoi(subs.c_str()); from << "#" << value; to.str(symbolicEngine->getElementFromId(value)->getSource()); formula.str(replaceEq(formula.str(), from.str(), to.str())); } return formula.str(); } SolverEngine::SolverEngine(SymbolicEngine *symEngine) { this->symEngine = symEngine; } SolverEngine::~SolverEngine() { } VOID SolverEngine::solveFromID(UINT64 id) { std::stringstream formula; formula.str(formulaReconstruction(symEngine->symbolicReg[ID_ZF])); this->formula << "(set-logic QF_AUFBV)"; this->formula << this->symEngine->getSmt2LibVarsDecl(); this->formula << formula.str(); this->ctx = new z3::context(); Z3_ast ast = Z3_parse_smtlib2_string(*this->ctx, this->formula.str().c_str(), 0, 0, 0, 0, 0, 0); z3::expr eq(*this->ctx, ast); this->solver = new z3::solver(*this->ctx); this->solver->add(eq); this->solver->check(); } VOID SolverEngine::displayModel() { z3::model m = this->solver->get_model(); std::cout << "----- Model -----" << std::endl << m << std::endl << "-----------------" << std::endl; } z3::model SolverEngine::getModel() { return this->solver->get_model(); } std::string SolverEngine::getFormula() { return this->formula.str(); } <|endoftext|>
<commit_before>#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP #define STAN_IO_ARRAY_VAR_CONTEXT_HPP #include <stan/io/var_context.hpp> #include <boost/throw_exception.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <algorithm> #include <functional> #include <numeric> #include <sstream> #include <string> #include <type_traits> #include <vector> #include <utility> namespace stan { namespace io { /** * An array_var_context object represents a named arrays * with dimensions constructed from an array, a vector * of names, and a vector of all dimensions for each element. */ class array_var_context : public var_context { private: // Pairs template <typename T> using pair_ = std::pair<std::string, std::pair<std::vector<T>, std::vector<size_t>>>; // Map holding reals using map_r_ = std::vector<pair_<double>>; map_r_ vars_r_; using map_i_ = std::vector<pair_<int>>; map_i_ vars_i_; // When search for variable name fails, return one these std::vector<double> const empty_vec_r_; std::vector<int> const empty_vec_i_; std::vector<size_t> const empty_vec_ui_; template <typename Str> auto find_var_r(Str&& name) const { return std::find_if(vars_r_.begin(), vars_r_.end(), [&](auto&& element){ return element.first == name;}); } template <typename Str> auto find_var_i(Str&& name) const { return std::find_if(vars_i_.begin(), vars_i_.end(), [&](auto&& element){ return element.first == name;}); } // Find method bool contains_r_only(const std::string& name) const { return find_var_r(name) != vars_r_.end(); } /** * Check (1) if the vector size of dimensions is no smaller * than the name vector size; (2) if the size of the input * array is large enough for what is needed. * * @param names The names for each variable * @param array_size The total size of the vector holding the values we want * to access. * @param dims Vector holding the dimensions for each variable. * @return If the array size is equal to the number of dimensions, * a vector of the cumulative sum of the dimensions of each inner element of * dims. The return of this function is used in the add_* methods to get the * sequence of values For each variable. */ template <typename T> std::vector<size_t> validate_dims( const std::vector<std::string>& names, const T array_size, const std::vector<std::vector<size_t>>& dims) { const size_t num_par = names.size(); if (num_par > dims.size()) { std::stringstream msg; msg << "size of vector of dimensions (found " << dims.size() << ") " << "should be no smaller than number of parameters (found " << num_par << ")."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } std::vector<size_t> elem_dims_total(dims.size() + 1); elem_dims_total[0] = 0; int i = 0; for (i = 0; i < dims.size(); i++) { elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(), 1, std::multiplies<T>()); elem_dims_total[i + 1] += elem_dims_total[i]; } if (elem_dims_total[i] > array_size) { std::stringstream msg; msg << "array is not long enough for all elements: " << array_size << " is found, but " << elem_dims_total[i] << " is needed."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } return elem_dims_total; } /** * Adds a set of floating point variables to the floating point map. * @param names Names of each variable. * @param values The real values of variable in a contiguous * column major order container. * @param dims the dimensions for each variable. */ void add_r(const std::vector<std::string>& names, const std::vector<double>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); for (size_t i = 0; i < names.size(); i++) { vars_r_[i] = {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}; } } void add_r(const std::vector<std::string>& names, const Eigen::VectorXd& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); using val_d_t = decltype(values.data()); for (size_t i = 0; i < names.size(); i++) { vars_r_[i] = {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}; } } /** * Adds a set of integer variables to the integer map. * @param names Names of each variable. * @param values The integer values of variable in a vector. * @param dims the dimensions for each variable. */ void add_i(const std::vector<std::string>& names, const std::vector<int>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); for (size_t i = 0; i < names.size(); i++) { vars_i_[i] = {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}; } } public: /** * Construct an array_var_context from only real value arrays. * * @param names_r names for each element * @param values_r a vector of double values for all elements * @param dim_r a vector of dimensions */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } /** * Construct an array_var_context from only integer value arrays. * * @param names_i names for each element * @param values_i a vector of integer values for all elements * @param dim_i a vector of dimensions */ array_var_context(const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); } /** * Construct an array_var_context from arrays of both double * and integer separately * */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } /** * Return <code>true</code> if this dump contains the specified * variable name is defined. This method returns <code>true</code> * even if the values are all integers. * * @param name Variable name to test. * @return <code>true</code> if the variable exists. */ bool contains_r(const std::string& name) const { return contains_r_only(name) || contains_i(name); } /** * Return <code>true</code> if this dump contains an integer * valued array with the specified name. * * @param name Variable name to test. * @return <code>true</code> if the variable name has an integer * array value. */ bool contains_i(const std::string& name) const { return find_var_i(name) != vars_i_.end(); } /** * Return the double values for the variable with the specified * name or null. * * @param name Name of variable. * @return Values of variable. * */ std::vector<double> vals_r(const std::string& name) const { auto ret_val_r = find_var_r(name); if (ret_val_r != vars_r_.end()) { return ret_val_r->second.first; } else { auto ret_val_i = find_var_i(name); if (ret_val_i != vars_i_.end()) { return {ret_val_i->second.first.begin(), ret_val_i->second.first.end()}; } } return empty_vec_r_; } /** * Return the dimensions for the double variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_r(const std::string& name) const { auto ret_val_r = find_var_r(name); if (ret_val_r != vars_r_.end()) { return ret_val_r->second.second; } else { auto ret_val_i = find_var_i(name); if (ret_val_i != vars_i_.end()) { return ret_val_i->second.second; } } return empty_vec_ui_; } /** * Return the integer values for the variable with the specified * name. * * @param name Name of variable. * @return Values. */ std::vector<int> vals_i(const std::string& name) const { auto ret_val_i = find_var_i(name); if (ret_val_i != vars_i_.end()) { return ret_val_i->second.first; } return empty_vec_i_; } /** * Return the dimensions for the integer variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_i(const std::string& name) const { auto ret_val_i = find_var_i(name); if (ret_val_i != vars_i_.end()) { return ret_val_i->second.second; } return empty_vec_ui_; } /** * Return a list of the names of the floating point variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_r(std::vector<std::string>& names) const { names.clear(); for (const auto& vars_r_iter : vars_r_) { names.push_back(vars_r_iter.first); } } /** * Return a list of the names of the integer variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_i(std::vector<std::string>& names) const { names.clear(); for (const auto& vars_i_iter : vars_r_) { names.push_back(vars_i_iter.first); } } /** * Remove variable from the object. * * @param name Name of the variable to remove. * @return If variable is removed returns <code>true</code>, else * returns <code>false</code>. */ bool remove(const std::string& name) { vars_i_.erase(find_var_i(name)); vars_r_.erase(find_var_r(name)); return true; } }; } // namespace io } // namespace stan #endif <commit_msg>testing with an unordered map and emplace<commit_after>#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP #define STAN_IO_ARRAY_VAR_CONTEXT_HPP #include <stan/io/var_context.hpp> #include <boost/throw_exception.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <unordered_map> #include <algorithm> #include <functional> #include <numeric> #include <sstream> #include <string> #include <type_traits> #include <vector> #include <utility> namespace stan { namespace io { /** * An array_var_context object represents a named arrays * with dimensions constructed from an array, a vector * of names, and a vector of all dimensions for each element. */ class array_var_context : public var_context { private: // Pairs template <typename T> using pair_ = std::pair<std::vector<T>, std::vector<size_t>>; // Map holding reals using map_r_ = std::unordered_map<std::string, pair_<double>>; map_r_ vars_r_; using map_i_ = std::unordered_map<std::string, pair_<int>>; map_i_ vars_i_; // When search for variable name fails, return one these std::vector<double> const empty_vec_r_{0}; std::vector<int> const empty_vec_i_{0}; std::vector<size_t> const empty_vec_ui_{0}; // Find method bool contains_r_only(const std::string& name) const { return vars_r_.find(name) != vars_r_.end(); } /** * Check (1) if the vector size of dimensions is no smaller * than the name vector size; (2) if the size of the input * array is large enough for what is needed. * * @param names The names for each variable * @param array_size The total size of the vector holding the values we want * to access. * @param dims Vector holding the dimensions for each variable. * @return If the array size is equal to the number of dimensions, * a vector of the cumulative sum of the dimensions of each inner element of * dims. The return of this function is used in the add_* methods to get the * sequence of values For each variable. */ template <typename T> std::vector<size_t> validate_dims( const std::vector<std::string>& names, const T array_size, const std::vector<std::vector<size_t>>& dims) { const size_t num_par = names.size(); if (num_par > dims.size()) { std::stringstream msg; msg << "size of vector of dimensions (found " << dims.size() << ") " << "should be no smaller than number of parameters (found " << num_par << ")."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } std::vector<size_t> elem_dims_total(dims.size() + 1); elem_dims_total[0] = 0; int i = 0; for (i = 0; i < dims.size(); i++) { elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(), 1, std::multiplies<T>()) + elem_dims_total[i];; } if (elem_dims_total[i] > array_size) { std::stringstream msg; msg << "array is not long enough for all elements: " << array_size << " is found, but " << elem_dims_total[i] << " is needed."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } return elem_dims_total; } /** * Adds a set of floating point variables to the floating point map. * @param names Names of each variable. * @param values The real values of variable in a contiguous * column major order container. * @param dims the dimensions for each variable. */ void add_r(const std::vector<std::string>& names, const std::vector<double>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); for (size_t i = 0; i < names.size(); i++) { vars_r_.emplace(names[i], pair_<double>{{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}); } } void add_r(const std::vector<std::string>& names, const Eigen::VectorXd& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); const auto name_size = names.size(); for (size_t i = 0; i < name_size; i++) { vars_r_.emplace(names[i], pair_<double>{{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}); } } /** * Adds a set of integer variables to the integer map. * @param names Names of each variable. * @param values The integer values of variable in a vector. * @param dims the dimensions for each variable. */ void add_i(const std::vector<std::string>& names, const std::vector<int>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); for (size_t i = 0; i < names.size(); i++) { vars_i_.emplace(names[i], pair_<int>{{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}); } } public: /** * Construct an array_var_context from only real value arrays. * * @param names_r names for each element * @param values_r a vector of double values for all elements * @param dim_r a vector of dimensions */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } /** * Construct an array_var_context from only integer value arrays. * * @param names_i names for each element * @param values_i a vector of integer values for all elements * @param dim_i a vector of dimensions */ array_var_context(const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); } /** * Construct an array_var_context from arrays of both double * and integer separately * */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } /** * Return <code>true</code> if this dump contains the specified * variable name is defined. This method returns <code>true</code> * even if the values are all integers. * * @param name Variable name to test. * @return <code>true</code> if the variable exists. */ bool contains_r(const std::string& name) const { return contains_r_only(name) || contains_i(name); } /** * Return <code>true</code> if this dump contains an integer * valued array with the specified name. * * @param name Variable name to test. * @return <code>true</code> if the variable name has an integer * array value. */ bool contains_i(const std::string& name) const { return vars_i_.find(name) != vars_i_.end(); } /** * Return the double values for the variable with the specified * name or null. * * @param name Name of variable. * @return Values of variable. * */ std::vector<double> vals_r(const std::string& name) const { const auto ret_val_r = vars_r_.find(name); if (ret_val_r != vars_r_.end()) { return ret_val_r->second.first; } else { const auto ret_val_i = vars_i_.find(name); if (ret_val_i != vars_i_.end()) { return {ret_val_i->second.first.begin(), ret_val_i->second.first.end()}; } } return empty_vec_r_; } /** * Return the dimensions for the double variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_r(const std::string& name) const { const auto ret_val_r = vars_r_.find(name); if (ret_val_r != vars_r_.end()) { return ret_val_r->second.second; } else { const auto ret_val_i = vars_i_.find(name); if (ret_val_i != vars_i_.end()) { return ret_val_i->second.second; } } return empty_vec_ui_; } /** * Return the integer values for the variable with the specified * name. * * @param name Name of variable. * @return Values. */ std::vector<int> vals_i(const std::string& name) const { auto ret_val_i = vars_i_.find(name); if (ret_val_i != vars_i_.end()) { return ret_val_i->second.first; } return empty_vec_i_; } /** * Return the dimensions for the integer variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_i(const std::string& name) const { auto ret_val_i = vars_i_.find(name); if (ret_val_i != vars_i_.end()) { return ret_val_i->second.second; } return empty_vec_ui_; } /** * Return a list of the names of the floating point variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_r(std::vector<std::string>& names) const { names.clear(); names.reserve(vars_r_.size()); for (const auto& vars_r_iter : vars_r_) { names.push_back(vars_r_iter.first); } } /** * Return a list of the names of the integer variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_i(std::vector<std::string>& names) const { names.clear(); names.reserve(vars_i_.size()); for (const auto& vars_i_iter : vars_r_) { names.push_back(vars_i_iter.first); } } /** * Remove variable from the object. * * @param name Name of the variable to remove. * @return If variable is removed returns <code>true</code>, else * returns <code>false</code>. */ bool remove(const std::string& name) { vars_i_.erase(name); vars_r_.erase(name); return true; } }; } // namespace io } // namespace stan #endif <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw2d_forestclaw.h> #include <fclaw2d_clawpatch.hpp> #include <fclaw2d_partition.h> #include <sc_statistics.h> #define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \ SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \ "Timer " #NAME " still running in amrreset"); \ sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \ (ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \ } while (0) static void delete_ghost_patches(fclaw2d_domain_t* domain) { for(int i = 0; i < domain->num_ghost_patches; i++) { fclaw2d_patch_t* ghost_patch = &domain->ghost_patches[i]; fclaw2d_patch_delete_cp(ghost_patch); fclaw2d_patch_delete_data(ghost_patch); } } void amrreset(fclaw2d_domain_t **domain) { fclaw2d_domain_data_t *ddata = get_domain_data (*domain); for(int i = 0; i < (*domain)->num_blocks; i++) { fclaw2d_block_t *block = (*domain)->blocks + i; fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user; for(int j = 0; j < block->num_patches; j++) { fclaw2d_patch_t *patch = block->patches + j; fclaw2d_patch_delete_cp(patch); fclaw2d_patch_delete_data(patch); #if 0 fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user; delete pdata->cp; pdata->cp = NULL; FCLAW2D_FREE (pdata); patch->user = NULL; #endif ++ddata->count_delete_clawpatch; } FCLAW2D_FREE (bd); block->user = NULL; } // Free old parallel ghost patch data structure, must exist by construction. delete_ghost_patches(*domain); fclaw2d_domain_exchange_t *e_old = fclaw2d_partition_get_exchange_data(*domain); fclaw2d_domain_free_after_exchange (*domain, e_old); // Output memory discrepancy for the ClawPatch if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) { printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n", (*domain)->mpirank, ddata->count_set_clawpatch, ddata->count_delete_clawpatch); } // Evaluate timers if this domain has not been superseded yet. if (ddata->is_latest_domain) { sc_statinfo_t stats[FCLAW2D_TIMER_COUNT]; fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]); FCLAW2D_STATS_SET (stats, ddata, INIT); FCLAW2D_STATS_SET (stats, ddata, REGRID); FCLAW2D_STATS_SET (stats, ddata, OUTPUT); FCLAW2D_STATS_SET (stats, ddata, CHECK); FCLAW2D_STATS_SET (stats, ddata, ADVANCE); FCLAW2D_STATS_SET (stats, ddata, EXCHANGE); FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES); FCLAW2D_STATS_SET (stats, ddata, WALLTIME); sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED], ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative - (ddata->timers[FCLAW2D_TIMER_INIT].cumulative + ddata->timers[FCLAW2D_TIMER_REGRID].cumulative + ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative + ddata->timers[FCLAW2D_TIMER_CHECK].cumulative + ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative + ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative), "UNACCOUNTED"); sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats); sc_stats_print (sc_package_id, SC_LP_PRODUCTION, FCLAW2D_TIMER_COUNT, stats, 1, 0); SC_GLOBAL_PRODUCTIONF ("Procs %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].average, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].average, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].average); SC_GLOBAL_PRODUCTIONF ("Max/P %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].max, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].max, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].max); } delete_domain_data(*domain); // Delete allocated pointers to set of functions. fclaw2d_domain_destroy(*domain); *domain = NULL; } <commit_msg>Lowered log level for timing stats output at end of run<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw2d_forestclaw.h> #include <fclaw2d_clawpatch.hpp> #include <fclaw2d_partition.h> #include <sc_statistics.h> #define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \ SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \ "Timer " #NAME " still running in amrreset"); \ sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \ (ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \ } while (0) static void delete_ghost_patches(fclaw2d_domain_t* domain) { for(int i = 0; i < domain->num_ghost_patches; i++) { fclaw2d_patch_t* ghost_patch = &domain->ghost_patches[i]; fclaw2d_patch_delete_cp(ghost_patch); fclaw2d_patch_delete_data(ghost_patch); } } void amrreset(fclaw2d_domain_t **domain) { fclaw2d_domain_data_t *ddata = get_domain_data (*domain); for(int i = 0; i < (*domain)->num_blocks; i++) { fclaw2d_block_t *block = (*domain)->blocks + i; fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user; for(int j = 0; j < block->num_patches; j++) { fclaw2d_patch_t *patch = block->patches + j; fclaw2d_patch_delete_cp(patch); fclaw2d_patch_delete_data(patch); #if 0 fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user; delete pdata->cp; pdata->cp = NULL; FCLAW2D_FREE (pdata); patch->user = NULL; #endif ++ddata->count_delete_clawpatch; } FCLAW2D_FREE (bd); block->user = NULL; } // Free old parallel ghost patch data structure, must exist by construction. delete_ghost_patches(*domain); fclaw2d_domain_exchange_t *e_old = fclaw2d_partition_get_exchange_data(*domain); fclaw2d_domain_free_after_exchange (*domain, e_old); // Output memory discrepancy for the ClawPatch if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) { printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n", (*domain)->mpirank, ddata->count_set_clawpatch, ddata->count_delete_clawpatch); } // Evaluate timers if this domain has not been superseded yet. if (ddata->is_latest_domain) { sc_statinfo_t stats[FCLAW2D_TIMER_COUNT]; fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]); FCLAW2D_STATS_SET (stats, ddata, INIT); FCLAW2D_STATS_SET (stats, ddata, REGRID); FCLAW2D_STATS_SET (stats, ddata, OUTPUT); FCLAW2D_STATS_SET (stats, ddata, CHECK); FCLAW2D_STATS_SET (stats, ddata, ADVANCE); FCLAW2D_STATS_SET (stats, ddata, EXCHANGE); FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES); FCLAW2D_STATS_SET (stats, ddata, WALLTIME); sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED], ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative - (ddata->timers[FCLAW2D_TIMER_INIT].cumulative + ddata->timers[FCLAW2D_TIMER_REGRID].cumulative + ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative + ddata->timers[FCLAW2D_TIMER_CHECK].cumulative + ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative + ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative), "UNACCOUNTED"); sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats); sc_stats_print (sc_package_id, SC_LP_ESSENTIAL, FCLAW2D_TIMER_COUNT, stats, 1, 0); SC_GLOBAL_ESSENTIALF ("Procs %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].average, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].average, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].average); SC_GLOBAL_ESSENTIALF ("Max/P %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].max, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].max, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].max); } delete_domain_data(*domain); // Delete allocated pointers to set of functions. fclaw2d_domain_destroy(*domain); *domain = NULL; } <|endoftext|>
<commit_before>#include "Text.h" namespace hm { Text::Text() { // Initialize. font = NULL; sdltext = NULL; text = "Hume Library"; } Text::Text(Font *font) { // Initialize and set default text. this->font = font; sdltext = NULL; text = "Hume Library"; std::cout << "constructor invoked and calling updateSurface()" << std::endl; updateSurface(); } Text::Text(std::string text, Font *font) { // Initialize and set custom text. this->font = font; sdltext = NULL; this->text = text; updateSurface(); } SDL_Surface* Text::getSurface() { return sdltext; } void Text::setText(std::string text) { this->text = text; updateSurface(); } std::string Text::getText() { return text; } void Text::setPosition(int x, int y) { position.x = x; position.y = y; return; } SDL_Rect* Text::getPosition() { return &position; } void Text::updateSurface() { // See if TTF_WasInit(). if(TTF_WasInit() == 0) { std::cout << "SDL_ttf was not initialized. Cannot update surface." << std::endl; return; } else std::cout << "SDL_ttf was initialized. Continuing..." << std::endl; // Check if the font is null. if(font == NULL) { std::cout << "Cannot update surface. Font is nulled." << std::endl; return; } // Output. std::cout << "Font: " << font << std::endl; std::cout << "Text: " << text.c_str() << std::endl; std::cout << "FGColor: " << font->getFgColor().r << ", " << font->getFgColor().g << ", " << font->getFgColor().b << std::endl; std::cout << "BGColor: " << font->getBgColor().r << ", " << font->getBgColor().g << ", " << font->getBgColor().b << std::endl; if(font->getRenderMode() == SOLID) { std::cout << "Rendering text solid..." << std::endl; sdltext = TTF_RenderText_Solid(font->getFont(), text.c_str(), font->getFgColor()); } if(font->getRenderMode() == SHADED) { std::cout << "Rendering text shaded..." << std::endl; sdltext = TTF_RenderText_Shaded(font->getFont(), text.c_str(), font->getFgColor(), font->getBgColor()); } if(font->getRenderMode() == BLENDED) { std::cout << "Rendering text blended..." << std::endl; sdltext = TTF_RenderText_Blended(font->getFont(), text.c_str(), font->getFgColor()); } std::cout << "Surface is located at " << sdltext << "." << std::endl; return; } } <commit_msg>Got rid of output of TTF_RenderText_*() parameters.<commit_after>#include "Text.h" namespace hm { Text::Text() { // Initialize. font = NULL; sdltext = NULL; text = "Hume Library"; } Text::Text(Font *font) { // Initialize and set default text. this->font = font; sdltext = NULL; text = "Hume Library"; std::cout << "constructor invoked and calling updateSurface()" << std::endl; updateSurface(); } Text::Text(std::string text, Font *font) { // Initialize and set custom text. this->font = font; sdltext = NULL; this->text = text; updateSurface(); } SDL_Surface* Text::getSurface() { return sdltext; } void Text::setText(std::string text) { this->text = text; updateSurface(); } std::string Text::getText() { return text; } void Text::setPosition(int x, int y) { position.x = x; position.y = y; return; } SDL_Rect* Text::getPosition() { return &position; } void Text::updateSurface() { // See if TTF_WasInit(). if(TTF_WasInit() == 0) { std::cout << "SDL_ttf was not initialized. Cannot update surface." << std::endl; return; } else std::cout << "SDL_ttf was initialized. Continuing..." << std::endl; // Check if the font is null. if(font == NULL) { std::cout << "Cannot update surface. Font is nulled." << std::endl; return; } // Output. std::cout << "Font: " << font << std::endl; std::cout << "Text: " << text.c_str() << std::endl; if(font->getRenderMode() == SOLID) { std::cout << "Rendering text solid..." << std::endl; sdltext = TTF_RenderText_Solid(font->getFont(), text.c_str(), font->getFgColor()); } if(font->getRenderMode() == SHADED) { std::cout << "Rendering text shaded..." << std::endl; sdltext = TTF_RenderText_Shaded(font->getFont(), text.c_str(), font->getFgColor(), font->getBgColor()); } if(font->getRenderMode() == BLENDED) { std::cout << "Rendering text blended..." << std::endl; sdltext = TTF_RenderText_Blended(font->getFont(), text.c_str(), font->getFgColor()); } std::cout << "Surface is located at " << sdltext << "." << std::endl; return; } } <|endoftext|>
<commit_before>/* * File: Zone.cpp * Author: Aztyu * * Created on 22 décembre 2014, 15:50 */ #include "Zone.h" using namespace std; Zone::Zone(char* name){ zone_name = name; tableau.reserve(10); for(int i=0; i < 8; i++){ type_number[i] = 0; } cout << "Creation de la zone " << zone_name << endl; } Zone::Zone(const Zone& orig) { } Zone::~Zone() { } void Zone::addObjet(Objet* objet){ tableau.push_back(objet); } void Zone::removeObjet(int index){ tableau[index]->getSceneNode()->remove(); delete tableau[index]->getPointer(); tableau.erase(tableau.begin()+index); } void Zone::createObjet(object form){ char name[50]; string type = "ressources/"; switch((int)form){ case 0: if(type_number[0] > 0){ sprintf (name, "Rectangle%d", type_number[0]); }else{ sprintf (name, "Rectangle"); } type += "rectangle"; type_number[0]++; break; case 1: if(type_number[1] > 0){ sprintf (name, "Line%d", type_number[1]); }else{ sprintf (name, "Line"); } type += "line"; type_number[1]++; break; case 2: if(type_number[2] > 0){ sprintf (name, "Circle%d", type_number[2]); }else{ sprintf (name, "Circle"); } type += "circle"; type_number[2]++; break; case 3: if(type_number[3] > 0){ sprintf (name, "Trapeze%d", type_number[3]); }else{ sprintf (name, "Trapeze"); } type += "trapeze"; type_number[3]++; break; case 4: if(type_number[4] > 0){ sprintf (name, "Cube%d", type_number[4]); }else{ sprintf (name, "Cube"); } type += "cube"; type_number[4]++; break; case 5: if(type_number[5] > 0){ sprintf (name, "Pyramid%d", type_number[5]); }else{ sprintf (name, "Pyramid"); } type += "pyramide"; type_number[5]++; break; case 6: if(type_number[6] > 0){ sprintf (name, "Sphere%d", type_number[6]); }else{ sprintf (name, "Sphere"); } type += "sphere"; type_number[6]++; break; case 7: if(type_number[7] > 0){ sprintf (name, "Cylinder%d", type_number[7]); }else{ sprintf (name, "Cylinder"); } type += "cylinder"; type_number[7]++; break; } type += ".obj"; tableau.push_back(new Objet(current_scene->addMeshSceneNode(current_scene->getMesh(type.c_str())), name)); wchar_t buffer [100]; swprintf( buffer, 100, L"%s", name); //box_global->addItem(buffer); } int Zone::getObjectCount(){ return tableau.size(); } void Zone::printZone(){ cout << "La zone s'appelle " << zone_name << endl; for(int i=0; i < tableau.size(); i++){ tableau[i]->printObjet(); } } Objet* Zone::getObjetPointer(int index){ if(index >= 0 && index < tableau.size()){ return tableau[index]; }else{ return 0; } } Zone* Zone::getPointer(){ return this; } <commit_msg>forgot one file<commit_after>/* * File: Zone.cpp * Author: Aztyu * * Created on 22 décembre 2014, 15:50 */ #include "Zone.h" using namespace std; Zone::Zone(char* name, irr::scene::ISceneManager* scene){ zone_name = name; tableau.reserve(10); for(int i=0; i < 8; i++){ type_number[i] = 0; } current_scene = scene; cout << "Creation de la zone " << zone_name << endl; } Zone::Zone(const Zone& orig) { } Zone::~Zone() { } void Zone::addObjet(Objet* objet){ tableau.push_back(objet); } void Zone::removeObjet(int index){ tableau[index]->getSceneNode()->remove(); delete tableau[index]->getPointer(); tableau.erase(tableau.begin()+index); } void Zone::createObjet(object form){ char name[50]; string type = "ressources/"; switch((int)form){ case 0: if(type_number[0] > 0){ sprintf (name, "Rectangle%d", type_number[0]); }else{ sprintf (name, "Rectangle"); } type += "rectangle"; type_number[0]++; break; case 1: if(type_number[1] > 0){ sprintf (name, "Line%d", type_number[1]); }else{ sprintf (name, "Line"); } type += "line"; type_number[1]++; break; case 2: if(type_number[2] > 0){ sprintf (name, "Circle%d", type_number[2]); }else{ sprintf (name, "Circle"); } type += "circle"; type_number[2]++; break; case 3: if(type_number[3] > 0){ sprintf (name, "Trapeze%d", type_number[3]); }else{ sprintf (name, "Trapeze"); } type += "trapeze"; type_number[3]++; break; case 4: if(type_number[4] > 0){ sprintf (name, "Cube%d", type_number[4]); }else{ sprintf (name, "Cube"); } type += "cube"; type_number[4]++; break; case 5: if(type_number[5] > 0){ sprintf (name, "Pyramid%d", type_number[5]); }else{ sprintf (name, "Pyramid"); } type += "pyramide"; type_number[5]++; break; case 6: if(type_number[6] > 0){ sprintf (name, "Sphere%d", type_number[6]); }else{ sprintf (name, "Sphere"); } type += "sphere"; type_number[6]++; break; case 7: if(type_number[7] > 0){ sprintf (name, "Cylinder%d", type_number[7]); }else{ sprintf (name, "Cylinder"); } type += "cylinder"; type_number[7]++; break; } type += ".obj"; tableau.push_back(new Objet(current_scene->addMeshSceneNode(current_scene->getMesh(type.c_str())), name)); //wchar_t buffer [100]; //swprintf( buffer, 100, L"%s", name); //box_global->addItem(buffer); } int Zone::getObjectCount(){ return tableau.size(); } void Zone::printZone(){ cout << "La zone s'appelle " << zone_name << endl; for(int i=0; i < tableau.size(); i++){ tableau[i]->printObjet(); } } Objet* Zone::getObjetPointer(int index){ if(index >= 0 && index < tableau.size()){ return tableau[index]; }else{ return 0; } } Zone* Zone::getPointer(){ return this; } <|endoftext|>
<commit_before>/* Copyright 2014-2015 Adam Grandquist Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL.hpp" #include <cstring> namespace ReQL { Result::Result() : type(REQL_R_JSON) {} Result::Result(const Result &other) { value.copy(other.value, type); } Result::Result(Result &&other) { value.move(std::move(other.value), type); } Result::~Result() { value.release(type); } Result & Result::operator=(const Result &other) { if (this != &other) { type = other.type; value.copy(other.value, type); } return *this; } Result & Result::operator=(Result &&other) { if (this != &other) { type = std::move(other.type); value.move(std::move(other.value), type); } return *this; } Result::JSON_Value::JSON_Value() { std::memset(this, 0, sizeof(Result::JSON_Value)); } void Result::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t a_type) { release(a_type); switch (a_type) { case REQL_R_ARRAY: { array = new std::vector<Result>(*other.array); break; } case REQL_R_BOOL: { boolean = new bool(*other.boolean); break; } case REQL_R_NUM: { num = new double(*other.num); break; } case REQL_R_OBJECT: { object = new std::map<std::string, Result>(*other.object); break; } case REQL_R_STR: { string = new std::string(*other.string); break; } case REQL_R_NULL: case REQL_R_JSON: case REQL_R_REQL: break; } } void Result::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t a_type) { release(a_type); switch (a_type) { case REQL_R_ARRAY: { array = std::move(other.array); break; } case REQL_R_BOOL: { boolean = std::move(other.boolean); break; } case REQL_R_NUM: { num = std::move(other.num); break; } case REQL_R_OBJECT: { object = std::move(other.object); break; } case REQL_R_STR: { string = std::move(other.string); break; } case REQL_R_NULL: case REQL_R_JSON: case REQL_R_REQL: break; } } void Result::JSON_Value::release(ReQL_Datum_t a_type) { switch (a_type) { case REQL_R_ARRAY: { if (array != nullptr) { delete array; } break; } case REQL_R_OBJECT: { if (object != nullptr) { delete object; } break; } case REQL_R_STR: { if (string != nullptr) { delete string; } break; } case REQL_R_BOOL: { if (boolean != nullptr) { delete boolean; } break; } case REQL_R_NUM: { if (num != nullptr) { delete num; } break; } case REQL_R_JSON: case REQL_R_NULL: case REQL_R_REQL: break; } } Result::JSON_Value::~JSON_Value() { std::memset(this, 0, sizeof(Result::JSON_Value)); } void Parser::parse(ReQL_Obj_t *val) { switch (reql_datum_type(val)) { case REQL_R_ARRAY: { startArray(); ReQL_Iter_t it = reql_new_iter(val); ReQL_Obj_t *elem = NULL; while ((elem = reql_iter_next(&it)) != NULL) { parse(elem); } endArray(); break; } case REQL_R_BOOL: { addElement(static_cast<bool>(reql_to_bool(val))); break; } case REQL_R_JSON: case REQL_R_REQL: break; case REQL_R_NULL: { addElement(); break; } case REQL_R_NUM: { addElement(reql_to_number(val)); break; } case REQL_R_OBJECT: { startObject(); ReQL_Iter_t it = reql_new_iter(val); ReQL_Obj_t *key = NULL; ReQL_Obj_t *value = NULL; while ((key = reql_iter_next(&it)) != NULL) { value = reql_object_get(val, key); std::string key_string((char *)reql_string_buf(key), reql_size(key)); switch (reql_datum_type(value)) { case REQL_R_BOOL: { addKeyValue(key_string, static_cast<bool>(reql_to_bool(val))); break; } case REQL_R_ARRAY: case REQL_R_OBJECT: { addKey(key_string); parse(value); break; } case REQL_R_NULL: { addKeyValue(key_string); break; } case REQL_R_NUM: { addKeyValue(key_string, reql_to_number(value)); break; } case REQL_R_JSON: case REQL_R_REQL: break; case REQL_R_STR: { addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value))); break; } } } endObject(); break; } case REQL_R_STR: { addElement(std::string((char *)reql_string_buf(val), reql_size(val))); break; } } } class ResultBuilder : public Parser { public: Result result() { return p_result; } private: void startObject() { p_stack.push_back(Result()); p_stack.end()->type = REQL_R_OBJECT; } void addKey(std::string key) { p_keys.push_back(key); } void addKeyValue(std::string key) { Result res; res.type = REQL_R_NULL; p_stack.end()->value.object->insert({key, res}); } void addKeyValue(std::string key, bool value) { Result res; res.type = REQL_R_BOOL; res.value.boolean = new bool(value); p_stack.end()->value.object->insert({key, res}); } void addKeyValue(std::string key, double value) { Result res; res.type = REQL_R_NUM; res.value.num = new double(value); p_stack.end()->value.object->insert({key, res}); } void addKeyValue(std::string key, std::string value) { Result res; res.type = REQL_R_STR; res.value.string = new std::string(value); p_stack.end()->value.object->insert({key, res}); } void endObject() { end(); } void startArray() { p_stack.push_back(Result()); p_stack.end()->type = REQL_R_ARRAY; p_stack.end()->value.array = new std::vector<Result>; } void addElement() { Result res; res.type = REQL_R_NULL; addElement(std::move(res)); } void addElement(bool value) { Result res; res.type = REQL_R_BOOL; res.value.boolean = new bool(value); addElement(std::move(res)); } void addElement(double value) { Result res; res.type = REQL_R_NUM; res.value.num = new double(value); addElement(std::move(res)); } void addElement(std::string value) { Result res; res.type = REQL_R_STR; res.value.string = new std::string(value); addElement(std::move(res)); } void endArray() { end(); } void addElement(Result &&val) { if (p_stack.empty()) { p_result = std::move(val); } else if (p_stack.end()->type == REQL_R_ARRAY) { std::vector<Result> *array = p_stack.end()->value.array; array->insert(array->end(), std::move(val)); } else { } } void end() { Result last = *p_stack.end().base(); p_stack.pop_back(); if (p_stack.empty()) { p_result = last; } else if (p_stack.end()->type == REQL_R_OBJECT) { std::string key = *p_keys.end(); p_keys.pop_back(); p_stack.end()->value.object->insert({key, last}); } else if (p_stack.end()->type == REQL_R_ARRAY) { addElement(std::move(last)); } else { } } std::vector<Result> p_stack; std::vector<std::string> p_keys; Result p_result; }; Cursor::Cursor() : cur(new ReQL_Cur_t) { reql_cursor_init(data()); } Cursor::~Cursor() { } bool Cursor::isOpen() const { return reql_cur_open(data()); } Result Cursor::next() { ResultBuilder builder; next(builder); return builder.result(); } void Cursor::next(Parser &p) { p.parse(reql_cursor_next(data())); } ReQL_Cur_t * Cursor::data() const { return cur.get(); } void Cursor::close() { } Connection::Connection() : conn(new ReQL_Conn_t) { reql_connection_init(data()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const std::string &host) : conn(new ReQL_Conn_t) { reql_connection_init(data()); reql_conn_set_addr(data(), (char *)host.c_str()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) { reql_connection_init(data()); reql_conn_set_addr(data(), (char *)host.c_str()); reql_conn_set_port(data(), (char *)std::to_string(port).c_str()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) { reql_connection_init(data()); if (key.size() > UINT32_MAX) { } std::uint32_t key_len = (std::uint32_t)key.size(); reql_conn_set_addr(data(), (char *)host.c_str()); reql_conn_set_port(data(), (char *)std::to_string(port).c_str()); reql_conn_set_auth(data(), key_len, (char *)key.c_str()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const Connection &other) : conn(new ReQL_Conn_t) { reql_connection_init(data()); ReQL_Conn_t *o_conn = other.data(); reql_conn_set_addr(data(), o_conn->addr); reql_conn_set_port(data(), o_conn->port); reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(Connection &&other) { conn = std::move(other.conn); } Connection::~Connection() { reql_ensure_conn_close(data()); } Connection &Connection::operator=(const Connection &other) { if (this != &other) { reql_ensure_conn_close(data()); reql_connection_init(data()); ReQL_Conn_t *o_conn = other.data(); reql_conn_set_addr(data(), o_conn->addr); reql_conn_set_port(data(), o_conn->port); reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } return *this; } Connection &Connection::operator=(Connection &&other) { reql_ensure_conn_close(data()); conn = std::move(other.conn); return *this; } void Connection::close() { reql_close_conn(data()); } bool Connection::isOpen() const { return reql_conn_open(data()); } ReQL_Conn_t * Connection::data() const { return conn.get(); } Cursor Query::run(const Connection &conn) const { if (!conn.isOpen()) { } Cursor cur; reql_run(cur.data(), p_query.data(), conn.data(), nullptr); return cur; } Query &Query::operator=(const Query &other) { Expr::operator=(other); return *this; } Query &Query::operator=(Query &&other) { Expr::operator=(std::move(other)); return *this; } bool Query::operator<(const Query &other) const { return Expr::operator<(other); } } <commit_msg>Compare type limits from c++.<commit_after>/* Copyright 2014-2015 Adam Grandquist Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL.hpp" #include <cstring> namespace ReQL { Result::Result() : type(REQL_R_JSON) {} Result::Result(const Result &other) { value.copy(other.value, type); } Result::Result(Result &&other) { value.move(std::move(other.value), type); } Result::~Result() { value.release(type); } Result & Result::operator=(const Result &other) { if (this != &other) { type = other.type; value.copy(other.value, type); } return *this; } Result & Result::operator=(Result &&other) { if (this != &other) { type = std::move(other.type); value.move(std::move(other.value), type); } return *this; } Result::JSON_Value::JSON_Value() { std::memset(this, 0, sizeof(Result::JSON_Value)); } void Result::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t a_type) { release(a_type); switch (a_type) { case REQL_R_ARRAY: { array = new std::vector<Result>(*other.array); break; } case REQL_R_BOOL: { boolean = new bool(*other.boolean); break; } case REQL_R_NUM: { num = new double(*other.num); break; } case REQL_R_OBJECT: { object = new std::map<std::string, Result>(*other.object); break; } case REQL_R_STR: { string = new std::string(*other.string); break; } case REQL_R_NULL: case REQL_R_JSON: case REQL_R_REQL: break; } } void Result::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t a_type) { release(a_type); switch (a_type) { case REQL_R_ARRAY: { array = std::move(other.array); break; } case REQL_R_BOOL: { boolean = std::move(other.boolean); break; } case REQL_R_NUM: { num = std::move(other.num); break; } case REQL_R_OBJECT: { object = std::move(other.object); break; } case REQL_R_STR: { string = std::move(other.string); break; } case REQL_R_NULL: case REQL_R_JSON: case REQL_R_REQL: break; } } void Result::JSON_Value::release(ReQL_Datum_t a_type) { switch (a_type) { case REQL_R_ARRAY: { if (array != nullptr) { delete array; } break; } case REQL_R_OBJECT: { if (object != nullptr) { delete object; } break; } case REQL_R_STR: { if (string != nullptr) { delete string; } break; } case REQL_R_BOOL: { if (boolean != nullptr) { delete boolean; } break; } case REQL_R_NUM: { if (num != nullptr) { delete num; } break; } case REQL_R_JSON: case REQL_R_NULL: case REQL_R_REQL: break; } } Result::JSON_Value::~JSON_Value() { std::memset(this, 0, sizeof(Result::JSON_Value)); } void Parser::parse(ReQL_Obj_t *val) { switch (reql_datum_type(val)) { case REQL_R_ARRAY: { startArray(); ReQL_Iter_t it = reql_new_iter(val); ReQL_Obj_t *elem = NULL; while ((elem = reql_iter_next(&it)) != NULL) { parse(elem); } endArray(); break; } case REQL_R_BOOL: { addElement(static_cast<bool>(reql_to_bool(val))); break; } case REQL_R_JSON: case REQL_R_REQL: break; case REQL_R_NULL: { addElement(); break; } case REQL_R_NUM: { addElement(reql_to_number(val)); break; } case REQL_R_OBJECT: { startObject(); ReQL_Iter_t it = reql_new_iter(val); ReQL_Obj_t *key = NULL; ReQL_Obj_t *value = NULL; while ((key = reql_iter_next(&it)) != NULL) { value = reql_object_get(val, key); std::string key_string((char *)reql_string_buf(key), reql_size(key)); switch (reql_datum_type(value)) { case REQL_R_BOOL: { addKeyValue(key_string, static_cast<bool>(reql_to_bool(val))); break; } case REQL_R_ARRAY: case REQL_R_OBJECT: { addKey(key_string); parse(value); break; } case REQL_R_NULL: { addKeyValue(key_string); break; } case REQL_R_NUM: { addKeyValue(key_string, reql_to_number(value)); break; } case REQL_R_JSON: case REQL_R_REQL: break; case REQL_R_STR: { addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value))); break; } } } endObject(); break; } case REQL_R_STR: { addElement(std::string((char *)reql_string_buf(val), reql_size(val))); break; } } } class ResultBuilder : public Parser { public: Result result() { return p_result; } private: void startObject() { p_stack.push_back(Result()); p_stack.end()->type = REQL_R_OBJECT; } void addKey(std::string key) { p_keys.push_back(key); } void addKeyValue(std::string key) { Result res; res.type = REQL_R_NULL; p_stack.end()->value.object->insert({key, res}); } void addKeyValue(std::string key, bool value) { Result res; res.type = REQL_R_BOOL; res.value.boolean = new bool(value); p_stack.end()->value.object->insert({key, res}); } void addKeyValue(std::string key, double value) { Result res; res.type = REQL_R_NUM; res.value.num = new double(value); p_stack.end()->value.object->insert({key, res}); } void addKeyValue(std::string key, std::string value) { Result res; res.type = REQL_R_STR; res.value.string = new std::string(value); p_stack.end()->value.object->insert({key, res}); } void endObject() { end(); } void startArray() { p_stack.push_back(Result()); p_stack.end()->type = REQL_R_ARRAY; p_stack.end()->value.array = new std::vector<Result>; } void addElement() { Result res; res.type = REQL_R_NULL; addElement(std::move(res)); } void addElement(bool value) { Result res; res.type = REQL_R_BOOL; res.value.boolean = new bool(value); addElement(std::move(res)); } void addElement(double value) { Result res; res.type = REQL_R_NUM; res.value.num = new double(value); addElement(std::move(res)); } void addElement(std::string value) { Result res; res.type = REQL_R_STR; res.value.string = new std::string(value); addElement(std::move(res)); } void endArray() { end(); } void addElement(Result &&val) { if (p_stack.empty()) { p_result = std::move(val); } else if (p_stack.end()->type == REQL_R_ARRAY) { std::vector<Result> *array = p_stack.end()->value.array; array->insert(array->end(), std::move(val)); } else { } } void end() { Result last = *p_stack.end().base(); p_stack.pop_back(); if (p_stack.empty()) { p_result = last; } else if (p_stack.end()->type == REQL_R_OBJECT) { std::string key = *p_keys.end(); p_keys.pop_back(); p_stack.end()->value.object->insert({key, last}); } else if (p_stack.end()->type == REQL_R_ARRAY) { addElement(std::move(last)); } else { } } std::vector<Result> p_stack; std::vector<std::string> p_keys; Result p_result; }; Cursor::Cursor() : cur(new ReQL_Cur_t) { reql_cursor_init(data()); } Cursor::~Cursor() { } bool Cursor::isOpen() const { return reql_cur_open(data()); } Result Cursor::next() { ResultBuilder builder; next(builder); return builder.result(); } void Cursor::next(Parser &p) { p.parse(reql_cursor_next(data())); } ReQL_Cur_t * Cursor::data() const { return cur.get(); } void Cursor::close() { } Connection::Connection() : conn(new ReQL_Conn_t) { reql_connection_init(data()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const std::string &host) : conn(new ReQL_Conn_t) { reql_connection_init(data()); reql_conn_set_addr(data(), (char *)host.c_str()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) { reql_connection_init(data()); reql_conn_set_addr(data(), (char *)host.c_str()); reql_conn_set_port(data(), (char *)std::to_string(port).c_str()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) { reql_connection_init(data()); std::size_t auth_size = key.size(); if (auth_size > std::numeric_limits<std::uint32_t>::max()) { return; } reql_conn_set_addr(data(), (char *)host.c_str()); reql_conn_set_port(data(), (char *)std::to_string(port).c_str()); reql_conn_set_auth(data(), key_len, (char *)key.c_str()); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(const Connection &other) : conn(new ReQL_Conn_t) { reql_connection_init(data()); ReQL_Conn_t *o_conn = other.data(); reql_conn_set_addr(data(), o_conn->addr); reql_conn_set_port(data(), o_conn->port); reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } Connection::Connection(Connection &&other) { conn = std::move(other.conn); } Connection::~Connection() { reql_ensure_conn_close(data()); } Connection &Connection::operator=(const Connection &other) { if (this != &other) { reql_ensure_conn_close(data()); reql_connection_init(data()); ReQL_Conn_t *o_conn = other.data(); reql_conn_set_addr(data(), o_conn->addr); reql_conn_set_port(data(), o_conn->port); reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth); std::uint8_t buf[500]; if (reql_connect(data(), buf, 500)) { } } return *this; } Connection &Connection::operator=(Connection &&other) { reql_ensure_conn_close(data()); conn = std::move(other.conn); return *this; } void Connection::close() { reql_close_conn(data()); } bool Connection::isOpen() const { return reql_conn_open(data()); } ReQL_Conn_t * Connection::data() const { return conn.get(); } Cursor Query::run(const Connection &conn) const { if (!conn.isOpen()) { } Cursor cur; reql_run(cur.data(), p_query.data(), conn.data(), nullptr); return cur; } Query &Query::operator=(const Query &other) { Expr::operator=(other); return *this; } Query &Query::operator=(Query &&other) { Expr::operator=(std::move(other)); return *this; } bool Query::operator<(const Query &other) const { return Expr::operator<(other); } } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MIDDLEWARE_COOKIE_PARSER_HPP #define MIDDLEWARE_COOKIE_PARSER_HPP #include "../cookie/cookie.hpp" #include "middleware.hpp" namespace middleware { /** * @brief A way to parse cookies: Reading cookies that the browser is sending to the server * @details * */ // hpp-declarations first and implement methods further down? Or in own cpp-file? class CookieParser : public server::Middleware { public: virtual void process(server::Request_ptr req, server::Response_ptr res, server::Next next) override { using namespace cookie; if(!has_cookie(req)) { //No Cookie in header field: We want to create a cookie then??: // //create cookie: (*next)(); return; } // Found Cookie in header } // Just name this method cookie? // Return bool or void? bool create_cookie(std::string& key, std::string& value); // new Cookie(...) and add_header: Set-Cookie ? // Just name this method cookie? // Return bool or void? bool create_cookie(std::string& key, std::string& value, std::string& options); // new Cookie(...) and add_header: Set-Cookie ? // options: map eller enum // Return bool or void? bool clear_cookie(std::string& key); // remove Cookie from client private: bool has_cookie(server::Request_ptr req) const { auto c_type = http::header_fields::Request::Cookie; return req->has_header(c_type); } }; } //< namespace middleware #endif <commit_msg>Refactored CookieParser::has_cookie<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MIDDLEWARE_COOKIE_PARSER_HPP #define MIDDLEWARE_COOKIE_PARSER_HPP #include "../cookie/cookie.hpp" #include "middleware.hpp" namespace middleware { /** * @brief A way to parse cookies: Reading cookies that the browser is sending to the server * @details * */ // hpp-declarations first and implement methods further down? Or in own cpp-file? class CookieParser : public server::Middleware { public: virtual void process(server::Request_ptr req, server::Response_ptr res, server::Next next) override { using namespace cookie; if(!has_cookie(req)) { //No Cookie in header field: We want to create a cookie then??: // //create cookie: (*next)(); return; } // Found Cookie in header } // Just name this method cookie? // Return bool or void? bool create_cookie(std::string& key, std::string& value); // new Cookie(...) and add_header: Set-Cookie ? // Just name this method cookie? // Return bool or void? bool create_cookie(std::string& key, std::string& value, std::string& options); // new Cookie(...) and add_header: Set-Cookie ? // options: map eller enum // Return bool or void? bool clear_cookie(std::string& key); // remove Cookie from client private: bool has_cookie(server::Request_ptr req) const noexcept; }; inline bool CookieParser::has_cookie(server::Request_ptr req) const noexcept { return req->has_header(http::header_fields::Request::Cookie); } } //< namespace middleware #endif <|endoftext|>
<commit_before>#include <cassert> #include "html-escape.hh" namespace mimosa { namespace stream { HtmlEscape::HtmlEscape(Stream::Ptr stream) : Filter(stream) { } int64_t HtmlEscape::write(const char * data, uint64_t nbytes, runtime::Time timeout) { const char * const start = data; const char * const end = data + nbytes; const char * p = data; while (data < end) { while (p < end && *p != '<' && *p != '>' && *p != '&' && *p != '"' && *p != '\'') ++p; if (data < p) { auto bytes = stream_->write(data, p - data, timeout); if (bytes < 0) return data == start ? bytes : data - start; if (bytes < p - data) return data - start + bytes; data = p; } if (p < end) { const char * replace = nullptr; int size = 0; switch (*p) { case '<': replace = "&lt;"; size = 4; break; case '>': replace = "&gt;"; size = 4; break; case '&': replace = "&amp;"; size = 5; break; case '\'': replace = "&apos;"; size = 6; break; case '"': replace = "&quot;"; size = 6; break; default: assert(false); break; } auto wrote = stream_->loopWrite(replace, size, timeout); if (wrote < 0) return data - start; if (wrote < size) return -1; ++data; ++p; } } return nbytes; } int64_t HtmlEscape::read(char * data, uint64_t nbytes, runtime::Time timeout) { assert(false && "TODO"); } } } <commit_msg>fix a return value error<commit_after>#include <cassert> #include "html-escape.hh" namespace mimosa { namespace stream { HtmlEscape::HtmlEscape(Stream::Ptr stream) : Filter(stream) { } int64_t HtmlEscape::write(const char * data, uint64_t nbytes, runtime::Time timeout) { const char * const start = data; const char * const end = data + nbytes; const char * p = data; while (data < end) { while (p < end && *p != '<' && *p != '>' && *p != '&' && *p != '"' && *p != '\'') ++p; if (data < p) { auto bytes = stream_->write(data, p - data, timeout); if (bytes < 0) return data == start ? bytes : data - start; if (bytes < p - data) return data - start + bytes; data = p; } if (p < end) { const char * replace = nullptr; int size = 0; switch (*p) { case '<': replace = "&lt;"; size = 4; break; case '>': replace = "&gt;"; size = 4; break; case '&': replace = "&amp;"; size = 5; break; case '\'': replace = "&apos;"; size = 6; break; case '"': replace = "&quot;"; size = 6; break; default: assert(false); break; } auto wrote = stream_->loopWrite(replace, size, timeout); if (wrote < 0) return data - start; if (wrote < size) return -1; ++data; ++p; } } return nbytes; } int64_t HtmlEscape::read(char * data, uint64_t nbytes, runtime::Time timeout) { assert(false && "TODO"); return -1; } } } <|endoftext|>
<commit_before>#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH # define MIMOSA_TPL_ABSTRACT_VALUE_HH # include "../ref-countable.hh" # include "../stream/stream.hh" # include "../string/string-ref.hh" namespace mimosa { namespace tpl { class AbstractValue { public: virtual const AbstractValue * lookup(const string::StringRef & var) const = 0; virtual void write(stream::Stream::Ptr stream) const = 0; AbstractValue * parent_; }; } } #endif /* !MIMOSA_TPL_ABSTRACT_VALUE_HH */ <commit_msg>template: added some mechanism to iterate on "repeated" values<commit_after>#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH # define MIMOSA_TPL_ABSTRACT_VALUE_HH # include "../ref-countable.hh" # include "../stream/stream.hh" # include "../string/string-ref.hh" namespace mimosa { namespace tpl { class AbstractValue { public: virtual const AbstractValue * lookup(const string::StringRef & var) const = 0; virtual void write(stream::Stream::Ptr stream) const = 0; class Iterator { virtual const AbstractValue & operator*() const = 0; virtual const AbstractValue * operator->() const = 0; virtual Iterator & operator++() = 0; virtual bool operator==(const Iterator &) const = 0; }; virtual Iterator begin() const = 0; virtual Iterator end() const = 0; virtual bool empty() const = 0; AbstractValue * parent_; }; } } #endif /* !MIMOSA_TPL_ABSTRACT_VALUE_HH */ <|endoftext|>
<commit_before>/************************************************************************* * * * OU library interface file for Open Dynamics Engine, * * Copyright (C) 2008 Oleh Derevenko. All rights reserved. * * Email: odar@eleks.com (change all "a" to "e") * * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) 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. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ /* ODE interface to OU library implementation. */ #include <ode/common.h> #include <ode/memory.h> #include "config.h" #include "odeou.h" #if dOU_ENABLED template<> const char *const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *>::m_aetElementArray[] = { "assert", // AFS_ASSERT, "check", // AFS_CHECK, }; static const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *> g_aszAssertionFailureSeverityNames; static void _OU_CONVENTION_CALLBACK ForwardOUAssertionFailure(EASSERTIONFAILURESEVERITY fsFailureSeverity, const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine) { dDebug(d_ERR_IASSERT, "Assertion failure in OU Library. Kind: %s, expression: \"%s\", file: \"%s\", line: %u", g_aszAssertionFailureSeverityNames.Encode(fsFailureSeverity), szAssertionExpression, szAssertionFileName, uiAssertionSourceLine); } static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryAlloc(size_t nBlockSize) { return dAlloc(nBlockSize); } static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryRealloc(void *pv_ExistingBlock, size_t nBlockNewSize) { return dRealloc(pv_ExistingBlock, 0, nBlockNewSize); } static void _OU_CONVENTION_CALLBACK ForwardOUMemoryFree(void *pv_ExistingBlock) { return dFree(pv_ExistingBlock, 0); } bool COdeOu::DoOUCustomizations() { CMemoryManagerCustomization::CustomizeMemoryManager(&ForwardOUMemoryAlloc, &ForwardOUMemoryRealloc, &ForwardOUMemoryFree); CAssertionCheckCustomization::CustomizeAssertionChecks(&ForwardOUAssertionFailure); return true; } void COdeOu::UndoOUCustomizations() { CAssertionCheckCustomization::CustomizeAssertionChecks(NULL); CMemoryManagerCustomization::CustomizeMemoryManager(NULL, NULL, NULL); } #endif // dOU_ENABLED <commit_msg>Cosmetic: A warning fixed in LLVM compiler<commit_after>/************************************************************************* * * * OU library interface file for Open Dynamics Engine, * * Copyright (C) 2008 Oleh Derevenko. All rights reserved. * * Email: odar@eleks.com (change all "a" to "e") * * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) 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. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ /* ODE interface to OU library implementation. */ #include <ode/common.h> #include <ode/memory.h> #include "config.h" #include "odeou.h" #if dOU_ENABLED BEGIN_NAMESPACE_OU(); template<> const char *const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *>::m_aetElementArray[] = { "assert", // AFS_ASSERT, "check", // AFS_CHECK, }; END_NAMESPACE_OU(); static const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *> g_aszAssertionFailureSeverityNames; static void _OU_CONVENTION_CALLBACK ForwardOUAssertionFailure(EASSERTIONFAILURESEVERITY fsFailureSeverity, const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine) { dDebug(d_ERR_IASSERT, "Assertion failure in OU Library. Kind: %s, expression: \"%s\", file: \"%s\", line: %u", g_aszAssertionFailureSeverityNames.Encode(fsFailureSeverity), szAssertionExpression, szAssertionFileName, uiAssertionSourceLine); } static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryAlloc(size_t nBlockSize) { return dAlloc(nBlockSize); } static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryRealloc(void *pv_ExistingBlock, size_t nBlockNewSize) { return dRealloc(pv_ExistingBlock, 0, nBlockNewSize); } static void _OU_CONVENTION_CALLBACK ForwardOUMemoryFree(void *pv_ExistingBlock) { return dFree(pv_ExistingBlock, 0); } bool COdeOu::DoOUCustomizations() { CMemoryManagerCustomization::CustomizeMemoryManager(&ForwardOUMemoryAlloc, &ForwardOUMemoryRealloc, &ForwardOUMemoryFree); CAssertionCheckCustomization::CustomizeAssertionChecks(&ForwardOUAssertionFailure); return true; } void COdeOu::UndoOUCustomizations() { CAssertionCheckCustomization::CustomizeAssertionChecks(NULL); CMemoryManagerCustomization::CustomizeMemoryManager(NULL, NULL, NULL); } #endif // dOU_ENABLED <|endoftext|>
<commit_before>/* Sirikata Transfer * DiskManager.hpp * * Copyright (c) 2010, Jeff Terrace * 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 Sirikata 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. */ #ifndef SIRIKATA_DiskManager_HPP__ #define SIRIKATA_DiskManager_HPP__ #include <sirikata/core/queue/ThreadSafeQueue.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/Singleton.hpp> #include <sirikata/core/transfer/TransferData.hpp> #include <boost/filesystem.hpp> namespace Sirikata { namespace Transfer { namespace fs = boost::filesystem; namespace Filesystem { typedef boost::filesystem::path Path; typedef boost::filesystem::file_status FileStatus; typedef boost::filesystem::file_type FileType; namespace boost_fs = boost::filesystem; class PathInfo { public: Path mPath; FileStatus mFileStatus; PathInfo(Path p, FileStatus f) : mPath(p), mFileStatus(f) {} }; } class SIRIKATA_EXPORT DiskManager : public AutoSingleton<DiskManager> { public: class DiskRequest { protected: virtual void execute() = 0; virtual ~DiskRequest() {} friend class DiskManager; }; class ScanRequest : public DiskRequest { public: typedef std::vector<Filesystem::PathInfo> DirectoryListing; typedef std::tr1::function<void( std::tr1::shared_ptr<DirectoryListing> dirListing )> ScanRequestCallback; ScanRequest(Filesystem::Path path, ScanRequestCallback cb); private: ScanRequestCallback mCb; Filesystem::Path mPath; protected: void execute(); }; class ReadRequest : public DiskRequest { public: typedef std::tr1::function<void( std::tr1::shared_ptr<DenseData> fileContents )> ReadRequestCallback; ReadRequest(Filesystem::Path path, ReadRequestCallback cb); private: ReadRequestCallback mCb; Filesystem::Path mPath; protected: void execute(); }; class WriteRequest : public DiskRequest { public: typedef std::tr1::function<void( bool status )> WriteRequestCallback; WriteRequest(Filesystem::Path path, std::tr1::shared_ptr<DenseData> fileContents, WriteRequestCallback cb); private: WriteRequestCallback mCb; Filesystem::Path mPath; std::tr1::shared_ptr<DenseData> mFileContents; protected: void execute(); }; DiskManager(); ~DiskManager(); void addRequest(std::tr1::shared_ptr<DiskRequest> req); static DiskManager& getSingleton(); static void destroy(); private: ThreadSafeQueue<std::tr1::shared_ptr<DiskRequest> > mRequestQueue; Thread *mWorkerThread; boost::mutex destroyLock; boost::condition_variable destroyCV; void workerThread(); }; } } #endif /* SIRIKATA_DiskManager_HPP__ */ <commit_msg>Add missing SIRIKATA_EXPORT to public nested classes, which some platforms require even when the parent class has SIRIKATA_EXPORT.<commit_after>/* Sirikata Transfer * DiskManager.hpp * * Copyright (c) 2010, Jeff Terrace * 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 Sirikata 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. */ #ifndef SIRIKATA_DiskManager_HPP__ #define SIRIKATA_DiskManager_HPP__ #include <sirikata/core/queue/ThreadSafeQueue.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/Singleton.hpp> #include <sirikata/core/transfer/TransferData.hpp> #include <boost/filesystem.hpp> namespace Sirikata { namespace Transfer { namespace fs = boost::filesystem; namespace Filesystem { typedef boost::filesystem::path Path; typedef boost::filesystem::file_status FileStatus; typedef boost::filesystem::file_type FileType; namespace boost_fs = boost::filesystem; class PathInfo { public: Path mPath; FileStatus mFileStatus; PathInfo(Path p, FileStatus f) : mPath(p), mFileStatus(f) {} }; } class SIRIKATA_EXPORT DiskManager : public AutoSingleton<DiskManager> { public: class DiskRequest { protected: virtual void execute() = 0; virtual ~DiskRequest() {} friend class DiskManager; }; class SIRIKATA_EXPORT ScanRequest : public DiskRequest { public: typedef std::vector<Filesystem::PathInfo> DirectoryListing; typedef std::tr1::function<void( std::tr1::shared_ptr<DirectoryListing> dirListing )> ScanRequestCallback; ScanRequest(Filesystem::Path path, ScanRequestCallback cb); private: ScanRequestCallback mCb; Filesystem::Path mPath; protected: void execute(); }; class SIRIKATA_EXPORT ReadRequest : public DiskRequest { public: typedef std::tr1::function<void( std::tr1::shared_ptr<DenseData> fileContents )> ReadRequestCallback; ReadRequest(Filesystem::Path path, ReadRequestCallback cb); private: ReadRequestCallback mCb; Filesystem::Path mPath; protected: void execute(); }; class SIRIKATA_EXPORT WriteRequest : public DiskRequest { public: typedef std::tr1::function<void( bool status )> WriteRequestCallback; WriteRequest(Filesystem::Path path, std::tr1::shared_ptr<DenseData> fileContents, WriteRequestCallback cb); private: WriteRequestCallback mCb; Filesystem::Path mPath; std::tr1::shared_ptr<DenseData> mFileContents; protected: void execute(); }; DiskManager(); ~DiskManager(); void addRequest(std::tr1::shared_ptr<DiskRequest> req); static DiskManager& getSingleton(); static void destroy(); private: ThreadSafeQueue<std::tr1::shared_ptr<DiskRequest> > mRequestQueue; Thread *mWorkerThread; boost::mutex destroyLock; boost::condition_variable destroyCV; void workerThread(); }; } } #endif /* SIRIKATA_DiskManager_HPP__ */ <|endoftext|>
<commit_before>// --*- Mode: C++; c-basic-offset: 8 -*-- #include <complex> #include "EigenLab.h" int main(int argc, const char * argv[]) { EigenLab::ParserXd parserXd; auto failXd = parserXd.test(); EigenLab::ParserXf parserXf; auto failXf = parserXf.test(); EigenLab::ParserXi parserXi; auto failXi = parserXi.test(); EigenLab::Parser<Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic > > parserXcd; auto failXcd = parserXcd.test(); std::cout << "Test summary, number of failures: Xd=" << failXd << " Xf=" << failXf << " Xi=" << failXi << " Xcd=" << failXcd << std::endl; return 0; } <commit_msg>make test return -1 if fail<commit_after>// --*- Mode: C++; c-basic-offset: 8 -*-- #include <complex> #include "EigenLab.h" int main(int argc, const char * argv[]) { EigenLab::ParserXd parserXd; auto failXd = parserXd.test(); EigenLab::ParserXf parserXf; auto failXf = parserXf.test(); EigenLab::ParserXi parserXi; auto failXi = parserXi.test(); EigenLab::Parser<Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic > > parserXcd; auto failXcd = parserXcd.test(); std::cout << "Test summary, number of failures: Xd=" << failXd << " Xf=" << failXf << " Xi=" << failXi << " Xcd=" << failXcd << std::endl; return (failXd || failXf || failXi || failXcd) ? -1 : 0; } <|endoftext|>
<commit_before>#include <../recurse.hpp> #include <QHash> int main(int argc, char *argv[]) { Recurse app(argc, argv); // http options QHash<QString, QVariant> http_options; http_options["port"] = 3000; // https options QHash<QString, QVariant> https_options; https_options["port"] = 3020; https_options["private_key"] = "./priv.pem"; https_options["certificate"] = "./cert.pem"; app.http_server(http_options); app.https_server(https_options); qDebug() << "start listening..."; auto ret = app.listen(); if (ret.error()) { qDebug() << "error upon listening:" << ret.lastError(); } }; <commit_msg>example: update for middleware changes<commit_after>#include <../recurse.hpp> #include <QHash> int main(int argc, char *argv[]) { Recurse app(argc, argv); // http options QHash<QString, QVariant> http_options; http_options["port"] = 3000; // https options QHash<QString, QVariant> https_options; https_options["port"] = 3020; https_options["private_key"] = "./priv.pem"; https_options["certificate"] = "./cert.pem"; app.http_server(http_options); app.https_server(https_options); app.use([](auto &ctx, auto next) { qDebug() << "got a new request from" << ctx.request.ip; next(); }); app.use([](auto &ctx) { ctx.response.send("Hello, world"); }); qDebug() << "start listening..."; auto ret = app.listen(); if (ret.error()) { qDebug() << "error upon listening:" << ret.lastError(); } }; <|endoftext|>
<commit_before>#include <iostream> #include <vlf/Types.h> #include <FaceEngine.h> #include <IEstimator.h> int main(int argn, char** argv) { if(argn != 2) { std::cout << "USAGE: " << argv[0] << " <imagePath>\n"; return -1; } const std::string dataPath = "/opt/visionlabs/data/"; vlf::Image image; if( !image.loadFromPPM(argv[1]) ) { std::cout << "Cant load image: " << argv[1] << '\n'; return -1; } // Need only R-channel image for feature extraction vlf::Image imageR; image.convert(imageR, vlf::Format::R8); // Create FaceEngine main object fsdk::Ref<fsdk::IFaceEngine> faceEngine = fsdk::acquire(fsdk::createFaceEngine()); // Creating detector fsdk::Ref<fsdk::IDetectorFactory> detectorFactory = fsdk::acquire(faceEngine->createDetectorFactory()); detectorFactory->setDataDirectory(dataPath.c_str()); fsdk::Ref<fsdk::IDetector> detector = fsdk::acquire(detectorFactory->createDetector(fsdk::ODT_DPM)); // Creating feature extractor fsdk::Ref<fsdk::IFeatureFactory> featureFactory = fsdk::acquire(faceEngine->createFeatureFactory()); featureFactory->setDataDirectory(dataPath.c_str()); fsdk::Ref<fsdk::IFeatureDetector> featureDetector = fsdk::acquire(featureFactory->createDetector(fsdk::FT_VGG)); fsdk::Ref<fsdk::IFeatureSet> featureSet = fsdk::acquire(featureFactory->createFeatureSet()); // Create warper fsdk::Ref<fsdk::IDescriptorFactory> descriptorFactory = fsdk::acquire(faceEngine->createDescriptorFactory()); fsdk::Ref<fsdk::ICNNDescriptor> descriptor = fsdk::acquire(static_cast<fsdk::ICNNDescriptor*>(descriptorFactory->createDescriptor(fsdk::DT_CNN))); fsdk::Ref<fsdk::ICNNWarper> warper = fsdk::acquire(static_cast<fsdk::ICNNWarper*>(descriptorFactory->createWarper(fsdk::DT_CNN))); // Creating estimator fsdk::Ref<fsdk::IEstimatorFactory> estimatorFactory = fsdk::acquire(faceEngine->createEstimatorFactory()); estimatorFactory->setDataDirectory(dataPath.c_str()); fsdk::Ref<fsdk::IComplexEstimator> complexEstimator = fsdk::acquire(static_cast<fsdk::IComplexEstimator*>(estimatorFactory->createEstimator(fsdk::ET_COMPLEX))); fsdk::Ref<fsdk::IQualityEstimator> qualityEstimator = fsdk::acquire(static_cast<fsdk::IQualityEstimator*>(estimatorFactory->createEstimator(fsdk::ET_QUALITY))); // Detecting faces on the photo fsdk::Detection detections[10]; int count = 10; fsdk::Result<fsdk::FSDKError> res = detector->detect(image, image.getRect(), detections, &count); if(res.isError()) { std::cout << "Face detection error\n"; return -1; } std::cout << "Detections found: " << count << "\n\n"; for(int i = 0; i < count; i++) { fsdk::Detection& detection = detections[i]; std::cout << "Detection " << i << "\n"; std::cout << "Rect: x=" << detection.rect.x << " y=" << detection.rect.y << " w=" << detection.rect.width << " h=" << detection.rect.height << '\n'; // Extracting face features fsdk::Result<fsdk::FSDKError> res = featureDetector->detect(imageR, detection, featureSet); if(res.isError()) { std::cout << "Feature extraction error\n"; continue; } // Get warped face from detection fsdk::Image warp; warper->warp(image, detection, featureSet, warp); warp.saveAsPPM(("warp_" + std::to_string(i) + ".ppm").c_str()); // Quality estimating float qualityOut; res = qualityEstimator->estimate(warp, &qualityOut); if(res.isError()) { std::cout << "Quality estimating error\n"; return -1; } std::cout << "Quality estimated\n"; std::cout << "Quality: " << qualityOut << "\n"; // Complex attributes estimating fsdk::ComplexEstimation complexEstimationOut; res = complexEstimator->estimate(warp, complexEstimationOut); if(res.isError()) { std::cout << "Complex attributes estimating error\n"; return -1; } std::cout << "Complex attributes estimated\n"; std::cout << "Gender: " << complexEstimationOut.gender << " (1 - man, 0 - woman)\n"; std::cout << "Natural skin color: " << complexEstimationOut.naturSkinColor << " (1 - natural color of skin, 0 - not natural color of skin color)\n"; std::cout << "Over exposed: " << complexEstimationOut.overExposed << " (1 - image is overexposed, 0 - image isn't overexposed)\n"; std::cout << "Wear glasses: " << complexEstimationOut.wearGlasses << " (1 - person wears glasses, 0 - person doesn't wear glasses)\n"; std::cout << "Age: " << complexEstimationOut.age << " (in years)\n"; std::cout << '\n'; } return 0; } <commit_msg>remove dataPath in the example2<commit_after>#include <iostream> #include <vlf/Types.h> #include <FaceEngine.h> #include <IEstimator.h> int main(int argn, char** argv) { if(argn != 2) { std::cout << "USAGE: " << argv[0] << " <imagePath>\n"; return -1; } vlf::Image image; if( !image.loadFromPPM(argv[1]) ) { std::cout << "Cant load image: " << argv[1] << '\n'; return -1; } // Need only R-channel image for feature extraction vlf::Image imageR; image.convert(imageR, vlf::Format::R8); // Create FaceEngine main object fsdk::Ref<fsdk::IFaceEngine> faceEngine = fsdk::acquire(fsdk::createFaceEngine()); // Creating detector fsdk::Ref<fsdk::IDetectorFactory> detectorFactory = fsdk::acquire(faceEngine->createDetectorFactory()); fsdk::Ref<fsdk::IDetector> detector = fsdk::acquire(detectorFactory->createDetector(fsdk::ODT_DPM)); // Creating feature extractor fsdk::Ref<fsdk::IFeatureFactory> featureFactory = fsdk::acquire(faceEngine->createFeatureFactory()); fsdk::Ref<fsdk::IFeatureDetector> featureDetector = fsdk::acquire(featureFactory->createDetector(fsdk::FT_VGG)); fsdk::Ref<fsdk::IFeatureSet> featureSet = fsdk::acquire(featureFactory->createFeatureSet()); // Create warper fsdk::Ref<fsdk::IDescriptorFactory> descriptorFactory = fsdk::acquire(faceEngine->createDescriptorFactory()); fsdk::Ref<fsdk::ICNNDescriptor> descriptor = fsdk::acquire(static_cast<fsdk::ICNNDescriptor*>(descriptorFactory->createDescriptor(fsdk::DT_CNN))); fsdk::Ref<fsdk::ICNNWarper> warper = fsdk::acquire(static_cast<fsdk::ICNNWarper*>(descriptorFactory->createWarper(fsdk::DT_CNN))); // Creating estimator fsdk::Ref<fsdk::IEstimatorFactory> estimatorFactory = fsdk::acquire(faceEngine->createEstimatorFactory()); fsdk::Ref<fsdk::IComplexEstimator> complexEstimator = fsdk::acquire(static_cast<fsdk::IComplexEstimator*>(estimatorFactory->createEstimator(fsdk::ET_COMPLEX))); fsdk::Ref<fsdk::IQualityEstimator> qualityEstimator = fsdk::acquire(static_cast<fsdk::IQualityEstimator*>(estimatorFactory->createEstimator(fsdk::ET_QUALITY))); // Detecting faces on the photo fsdk::Detection detections[10]; int count = 10; fsdk::Result<fsdk::FSDKError> res = detector->detect(image, image.getRect(), detections, &count); if(res.isError()) { std::cout << "Face detection error\n"; return -1; } std::cout << "Detections found: " << count << "\n\n"; for(int i = 0; i < count; i++) { fsdk::Detection& detection = detections[i]; std::cout << "Detection " << i << "\n"; std::cout << "Rect: x=" << detection.rect.x << " y=" << detection.rect.y << " w=" << detection.rect.width << " h=" << detection.rect.height << '\n'; // Extracting face features fsdk::Result<fsdk::FSDKError> res = featureDetector->detect(imageR, detection, featureSet); if(res.isError()) { std::cout << "Feature extraction error\n"; continue; } // Get warped face from detection fsdk::Image warp; warper->warp(image, detection, featureSet, warp); warp.saveAsPPM(("warp_" + std::to_string(i) + ".ppm").c_str()); // Quality estimating float qualityOut; res = qualityEstimator->estimate(warp, &qualityOut); if(res.isError()) { std::cout << "Quality estimating error\n"; return -1; } std::cout << "Quality estimated\n"; std::cout << "Quality: " << qualityOut << "\n"; // Complex attributes estimating fsdk::ComplexEstimation complexEstimationOut; res = complexEstimator->estimate(warp, complexEstimationOut); if(res.isError()) { std::cout << "Complex attributes estimating error\n"; return -1; } std::cout << "Complex attributes estimated\n"; std::cout << "Gender: " << complexEstimationOut.gender << " (1 - man, 0 - woman)\n"; std::cout << "Natural skin color: " << complexEstimationOut.naturSkinColor << " (1 - natural color of skin, 0 - not natural color of skin color)\n"; std::cout << "Over exposed: " << complexEstimationOut.overExposed << " (1 - image is overexposed, 0 - image isn't overexposed)\n"; std::cout << "Wear glasses: " << complexEstimationOut.wearGlasses << " (1 - person wears glasses, 0 - person doesn't wear glasses)\n"; std::cout << "Age: " << complexEstimationOut.age << " (in years)\n"; std::cout << '\n'; } return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ // $Id$ #include <mapnik/map.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/agg_renderer.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/image_util.hpp> #include <mapnik/config_error.hpp> #include <iostream> int main ( int argc , char** argv) { if (argc != 2) { std::cout << "usage: ./rundemo <plugins_dir>\n"; return EXIT_SUCCESS; } using namespace mapnik; try { std::cout << " running demo ... \n"; datasource_cache::instance()->register_datasources(argv[1]); freetype_engine::register_font("/usr/local/lib/mapnik/fonts/DejaVuSans.ttf"); Map m(800,600); m.set_background(color_factory::from_string("white")); // create styles // Provinces (polygon) feature_type_style provpoly_style; rule_type provpoly_rule_on; provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'")); provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183))); provpoly_style.add_rule(provpoly_rule_on); rule_type provpoly_rule_qc; provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'")); provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203))); provpoly_style.add_rule(provpoly_rule_qc); m.insert_style("provinces",provpoly_style); // Provinces (polyline) feature_type_style provlines_style; stroke provlines_stk (Color(0,0,0),1.0); provlines_stk.add_dash(8, 4); provlines_stk.add_dash(2, 2); provlines_stk.add_dash(2, 2); rule_type provlines_rule; provlines_rule.append(line_symbolizer(provlines_stk)); provlines_style.add_rule(provlines_rule); m.insert_style("provlines",provlines_style); // Drainage feature_type_style qcdrain_style; rule_type qcdrain_rule; qcdrain_rule.set_filter(create_filter("[HYC] = 8")); qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255))); qcdrain_style.add_rule(qcdrain_rule); m.insert_style("drainage",qcdrain_style); // Roads 3 and 4 (The "grey" roads) feature_type_style roads34_style; rule_type roads34_rule; roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4")); stroke roads34_rule_stk(Color(171,158,137),2.0); roads34_rule_stk.set_line_cap(ROUND_CAP); roads34_rule_stk.set_line_join(ROUND_JOIN); roads34_rule.append(line_symbolizer(roads34_rule_stk)); roads34_style.add_rule(roads34_rule); m.insert_style("smallroads",roads34_style); // Roads 2 (The thin yellow ones) feature_type_style roads2_style_1; rule_type roads2_rule_1; roads2_rule_1.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_1(Color(171,158,137),4.0); roads2_rule_stk_1.set_line_cap(ROUND_CAP); roads2_rule_stk_1.set_line_join(ROUND_JOIN); roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1)); roads2_style_1.add_rule(roads2_rule_1); m.insert_style("road-border", roads2_style_1); feature_type_style roads2_style_2; rule_type roads2_rule_2; roads2_rule_2.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_2(Color(255,250,115),2.0); roads2_rule_stk_2.set_line_cap(ROUND_CAP); roads2_rule_stk_2.set_line_join(ROUND_JOIN); roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2)); roads2_style_2.add_rule(roads2_rule_2); m.insert_style("road-fill", roads2_style_2); // Roads 1 (The big orange ones, the highways) feature_type_style roads1_style_1; rule_type roads1_rule_1; roads1_rule_1.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_1(Color(188,149,28),7.0); roads1_rule_stk_1.set_line_cap(ROUND_CAP); roads1_rule_stk_1.set_line_join(ROUND_JOIN); roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1)); roads1_style_1.add_rule(roads1_rule_1); m.insert_style("highway-border", roads1_style_1); feature_type_style roads1_style_2; rule_type roads1_rule_2; roads1_rule_2.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_2(Color(242,191,36),5.0); roads1_rule_stk_2.set_line_cap(ROUND_CAP); roads1_rule_stk_2.set_line_join(ROUND_JOIN); roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2)); roads1_style_2.add_rule(roads1_rule_2); m.insert_style("highway-fill", roads1_style_2); // Populated Places feature_type_style popplaces_style; rule_type popplaces_rule; text_symbolizer popplaces_text_symbolizer("GEONAME","DejaVu Sans Book",10,Color(0,0,0)); popplaces_text_symbolizer.set_halo_fill(Color(255,255,200)); popplaces_text_symbolizer.set_halo_radius(1); popplaces_rule.append(popplaces_text_symbolizer); popplaces_style.add_rule(popplaces_rule); m.insert_style("popplaces",popplaces_style ); // Layers // Provincial polygons { parameters p; p["type"]="shape"; p["file"]="../data/boundaries"; Layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provinces"); m.addLayer(lyr); } // Drainage { parameters p; p["type"]="shape"; p["file"]="../data/qcdrainage"; Layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } { parameters p; p["type"]="shape"; p["file"]="../data/ontdrainage"; Layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } // Provincial boundaries { parameters p; p["type"]="shape"; p["file"]="../data/boundaries_l"; Layer lyr("Provincial borders"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provlines"); m.addLayer(lyr); } // Roads { parameters p; p["type"]="shape"; p["file"]="../data/roads"; Layer lyr("Roads"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("smallroads"); lyr.add_style("road-border"); lyr.add_style("road-fill"); lyr.add_style("highway-border"); lyr.add_style("highway-fill"); m.addLayer(lyr); } // popplaces { parameters p; p["type"]="shape"; p["file"]="../data/popplaces"; p["encoding"] = "latin1"; Layer lyr("Populated Places"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("popplaces"); m.addLayer(lyr); } m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447, 1706357.31328276,-25098.593149577)); Image32 buf(m.getWidth(),m.getHeight()); agg_renderer<Image32> ren(m,buf); ren.apply(); save_to_file<ImageData32>("demo.jpg","jpeg",buf.data()); save_to_file<ImageData32>("demo.png","png",buf.data()); std::cout << "Two maps have been rendered in the current directory:\n" "- demo.jpg\n" "- demo.png\n" "Have a look!\n"; } catch ( const mapnik::config_error & ex ) { std::cerr << "### Configuration error: " << ex.what(); return EXIT_FAILURE; } catch ( const std::exception & ex ) { std::cerr << "### std::exception: " << ex.what(); return EXIT_FAILURE; } catch ( ... ) { std::cerr << "### Unknown exception." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>1. define BOOST_SPIRIT_THREADSAFE (should be defined in config.hpp??) to be compatible with the core library. 2. use mapnik install_dir as input argument. 3. Generate three images as in rundemo.py<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ // $Id$ // define before any includes #define BOOST_SPIRIT_THREADSAFE #include <mapnik/map.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/agg_renderer.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/image_util.hpp> #include <mapnik/config_error.hpp> #include <iostream> int main ( int argc , char** argv) { if (argc != 2) { std::cout << "usage: ./rundemo <mapnik_install_dir>\n"; return EXIT_SUCCESS; } using namespace mapnik; try { std::cout << " running demo ... \n"; std::string mapnik_dir(argv[1]); datasource_cache::instance()->register_datasources(mapnik_dir + "/lib/mapnik/input/"); freetype_engine::register_font(mapnik_dir + "/lib/mapnik/fonts/DejaVuSans.ttf"); Map m(800,600); m.set_background(color_factory::from_string("white")); // create styles // Provinces (polygon) feature_type_style provpoly_style; rule_type provpoly_rule_on; provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'")); provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183))); provpoly_style.add_rule(provpoly_rule_on); rule_type provpoly_rule_qc; provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'")); provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203))); provpoly_style.add_rule(provpoly_rule_qc); m.insert_style("provinces",provpoly_style); // Provinces (polyline) feature_type_style provlines_style; stroke provlines_stk (Color(0,0,0),1.0); provlines_stk.add_dash(8, 4); provlines_stk.add_dash(2, 2); provlines_stk.add_dash(2, 2); rule_type provlines_rule; provlines_rule.append(line_symbolizer(provlines_stk)); provlines_style.add_rule(provlines_rule); m.insert_style("provlines",provlines_style); // Drainage feature_type_style qcdrain_style; rule_type qcdrain_rule; qcdrain_rule.set_filter(create_filter("[HYC] = 8")); qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255))); qcdrain_style.add_rule(qcdrain_rule); m.insert_style("drainage",qcdrain_style); // Roads 3 and 4 (The "grey" roads) feature_type_style roads34_style; rule_type roads34_rule; roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4")); stroke roads34_rule_stk(Color(171,158,137),2.0); roads34_rule_stk.set_line_cap(ROUND_CAP); roads34_rule_stk.set_line_join(ROUND_JOIN); roads34_rule.append(line_symbolizer(roads34_rule_stk)); roads34_style.add_rule(roads34_rule); m.insert_style("smallroads",roads34_style); // Roads 2 (The thin yellow ones) feature_type_style roads2_style_1; rule_type roads2_rule_1; roads2_rule_1.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_1(Color(171,158,137),4.0); roads2_rule_stk_1.set_line_cap(ROUND_CAP); roads2_rule_stk_1.set_line_join(ROUND_JOIN); roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1)); roads2_style_1.add_rule(roads2_rule_1); m.insert_style("road-border", roads2_style_1); feature_type_style roads2_style_2; rule_type roads2_rule_2; roads2_rule_2.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_2(Color(255,250,115),2.0); roads2_rule_stk_2.set_line_cap(ROUND_CAP); roads2_rule_stk_2.set_line_join(ROUND_JOIN); roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2)); roads2_style_2.add_rule(roads2_rule_2); m.insert_style("road-fill", roads2_style_2); // Roads 1 (The big orange ones, the highways) feature_type_style roads1_style_1; rule_type roads1_rule_1; roads1_rule_1.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_1(Color(188,149,28),7.0); roads1_rule_stk_1.set_line_cap(ROUND_CAP); roads1_rule_stk_1.set_line_join(ROUND_JOIN); roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1)); roads1_style_1.add_rule(roads1_rule_1); m.insert_style("highway-border", roads1_style_1); feature_type_style roads1_style_2; rule_type roads1_rule_2; roads1_rule_2.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_2(Color(242,191,36),5.0); roads1_rule_stk_2.set_line_cap(ROUND_CAP); roads1_rule_stk_2.set_line_join(ROUND_JOIN); roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2)); roads1_style_2.add_rule(roads1_rule_2); m.insert_style("highway-fill", roads1_style_2); // Populated Places feature_type_style popplaces_style; rule_type popplaces_rule; text_symbolizer popplaces_text_symbolizer("GEONAME","DejaVu Sans Book",10,Color(0,0,0)); popplaces_text_symbolizer.set_halo_fill(Color(255,255,200)); popplaces_text_symbolizer.set_halo_radius(1); popplaces_rule.append(popplaces_text_symbolizer); popplaces_style.add_rule(popplaces_rule); m.insert_style("popplaces",popplaces_style ); // Layers // Provincial polygons { parameters p; p["type"]="shape"; p["file"]="../data/boundaries"; Layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provinces"); m.addLayer(lyr); } // Drainage { parameters p; p["type"]="shape"; p["file"]="../data/qcdrainage"; Layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } { parameters p; p["type"]="shape"; p["file"]="../data/ontdrainage"; Layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } // Provincial boundaries { parameters p; p["type"]="shape"; p["file"]="../data/boundaries_l"; Layer lyr("Provincial borders"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provlines"); m.addLayer(lyr); } // Roads { parameters p; p["type"]="shape"; p["file"]="../data/roads"; Layer lyr("Roads"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("smallroads"); lyr.add_style("road-border"); lyr.add_style("road-fill"); lyr.add_style("highway-border"); lyr.add_style("highway-fill"); m.addLayer(lyr); } // popplaces { parameters p; p["type"]="shape"; p["file"]="../data/popplaces"; p["encoding"] = "latin1"; Layer lyr("Populated Places"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("popplaces"); m.addLayer(lyr); } m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447, 1706357.31328276,-25098.593149577)); Image32 buf(m.getWidth(),m.getHeight()); agg_renderer<Image32> ren(m,buf); ren.apply(); save_to_file<ImageData32>("demo.jpg","jpeg",buf.data()); save_to_file<ImageData32>("demo.png","png",buf.data()); save_to_file<ImageData32>("demo256.png","png256",buf.data()); std::cout << "Three maps have been rendered in the current directory:\n" "- demo.jpg\n" "- demo.png\n" "- demo256.png\n" "Have a look!\n"; } catch ( const mapnik::config_error & ex ) { std::cerr << "### Configuration error: " << ex.what(); return EXIT_FAILURE; } catch ( const std::exception & ex ) { std::cerr << "### std::exception: " << ex.what(); return EXIT_FAILURE; } catch ( ... ) { std::cerr << "### Unknown exception." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <liboauthcpp/liboauthcpp.h> /* These are input settings that make this demo actually work -- you need to get * these, e.g. by referring to the Twitter documentation and by registering an * application with them. Here we have examples from Twitter. If you * don't enter any, you'll be prompted to enter them at runtime. */ std::string consumer_key = ""; // Key from Twitter std::string consumer_secret = ""; // Secret from Twitter std::string request_token_url = "http://twitter.com/oauth/request_token"; std::string authorize_url = "http://twitter.com/oauth/authorize"; std::string access_token_url = "http://twitter.com/oauth/access_token"; std::string getUserString(std::string prompt) { std::cout << prompt << " "; std::string res; std::cin >> res; std::cout << std::endl; return res; } int main(int argc, char** argv) { // Initialization if (consumer_key.empty()) consumer_key = getUserString("Enter consumer key:"); if (consumer_secret.empty()) consumer_secret = getUserString("Enter consumer secret:"); OAuth::Consumer consumer(consumer_key, consumer_secret); OAuth::Client oauth(&consumer); // Step 1: Get a request token. This is a temporary token that is used for // having the user authorize an access token and to sign the request to // obtain said access token. std::string oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, request_token_url); std::cout << "Enter the following in your browser to get the request token: " << std::endl; std::cout << request_token_url << "?" << oAuthQueryString << std::endl; std::cout << std::endl; // Extract the token and token_secret from the response std::string request_token_resp = getUserString("Enter the response:"); // This time we pass the response directly and have the library do the // parsing (see next extractToken call for alternative) OAuth::Token request_token = OAuth::Token::extract( request_token_resp ); // Get access token and secret from OAuth object std::cout << "Request Token:" << std::endl; std::cout << " - oauth_token = " << request_token.key() << std::endl; std::cout << " - oauth_token_secret = " << request_token.secret() << std::endl; std::cout << std::endl; // Step 2: Redirect to the provider. Since this is a CLI script we // do not redirect. In a web application you would redirect the // user to the URL below. std::cout << "Go to the following link in your browser to authorize this application on a user's account:" << std::endl; std::cout << authorize_url << "?oauth_token=" << request_token.key() << std::endl; // After the user has granted access to you, the consumer, the // provider will redirect you to whatever URL you have told them // to redirect to. You can usually define this in the // oauth_callback argument as well. std::string pin = getUserString("What is the PIN?"); request_token.setPin(pin); // Step 3: Once the consumer has redirected the user back to the // oauth_callback URL you can request the access token the user // has approved. You use the request token to sign this // request. After this is done you throw away the request token // and use the access token returned. You should store the oauth // token and token secret somewhere safe, like a database, for // future use. oauth = OAuth::Client(&consumer, &request_token); // Note that we explicitly specify an empty body here (it's a GET) so we can // also specify to include the oauth_verifier parameter oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( "" ), true ); std::cout << "Enter the following in your browser to get the final access token & secret: " << std::endl; std::cout << access_token_url << "?" << oAuthQueryString; std::cout << std::endl; // Once they've come back from the browser, extract the token and token_secret from the response std::string access_token_resp = getUserString("Enter the response:"); // On this extractToken, we do the parsing ourselves (via the library) so we // can extract additional keys that are sent back, in the case of twitter, // the screen_name OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp); OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data ); std::cout << "Access token:" << std::endl; std::cout << " - oauth_token = " << access_token.key() << std::endl; std::cout << " - oauth_token_secret = " << access_token.secret() << std::endl; std::cout << std::endl; std::cout << "You may now access protected resources using the access tokens above." << std::endl; std::cout << std::endl; if (access_token_resp_data.find("screen_name") != access_token_resp_data.end()) std::cout << "Also extracted screen name from access token response: " << access_token_resp_data["screen_name"] << std::endl; // E.g., to use the access token, you'd create a new OAuth using // it, discarding the request_token: // oauth = OAuth::Client(&consumer, &access_token); return 0; } <commit_msg>Update Twitter demo URLs in simple_auth.<commit_after>#include <iostream> #include <string> #include <liboauthcpp/liboauthcpp.h> /* These are input settings that make this demo actually work -- you need to get * these, e.g. by referring to the Twitter documentation and by registering an * application with them. Here we have examples from Twitter. If you * don't enter any, you'll be prompted to enter them at runtime. */ std::string consumer_key = ""; // Key from Twitter std::string consumer_secret = ""; // Secret from Twitter std::string request_token_url = "https://api.twitter.com/oauth/request_token"; std::string authorize_url = "https://api.twitter.com/oauth/authorize"; std::string access_token_url = "https://api.twitter.com/oauth/access_token"; std::string getUserString(std::string prompt) { std::cout << prompt << " "; std::string res; std::cin >> res; std::cout << std::endl; return res; } int main(int argc, char** argv) { // Initialization if (consumer_key.empty()) consumer_key = getUserString("Enter consumer key:"); if (consumer_secret.empty()) consumer_secret = getUserString("Enter consumer secret:"); OAuth::Consumer consumer(consumer_key, consumer_secret); OAuth::Client oauth(&consumer); // Step 1: Get a request token. This is a temporary token that is used for // having the user authorize an access token and to sign the request to // obtain said access token. std::string oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, request_token_url); std::cout << "Enter the following in your browser to get the request token: " << std::endl; std::cout << request_token_url << "?" << oAuthQueryString << std::endl; std::cout << std::endl; // Extract the token and token_secret from the response std::string request_token_resp = getUserString("Enter the response:"); // This time we pass the response directly and have the library do the // parsing (see next extractToken call for alternative) OAuth::Token request_token = OAuth::Token::extract( request_token_resp ); // Get access token and secret from OAuth object std::cout << "Request Token:" << std::endl; std::cout << " - oauth_token = " << request_token.key() << std::endl; std::cout << " - oauth_token_secret = " << request_token.secret() << std::endl; std::cout << std::endl; // Step 2: Redirect to the provider. Since this is a CLI script we // do not redirect. In a web application you would redirect the // user to the URL below. std::cout << "Go to the following link in your browser to authorize this application on a user's account:" << std::endl; std::cout << authorize_url << "?oauth_token=" << request_token.key() << std::endl; // After the user has granted access to you, the consumer, the // provider will redirect you to whatever URL you have told them // to redirect to. You can usually define this in the // oauth_callback argument as well. std::string pin = getUserString("What is the PIN?"); request_token.setPin(pin); // Step 3: Once the consumer has redirected the user back to the // oauth_callback URL you can request the access token the user // has approved. You use the request token to sign this // request. After this is done you throw away the request token // and use the access token returned. You should store the oauth // token and token secret somewhere safe, like a database, for // future use. oauth = OAuth::Client(&consumer, &request_token); // Note that we explicitly specify an empty body here (it's a GET) so we can // also specify to include the oauth_verifier parameter oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( "" ), true ); std::cout << "Enter the following in your browser to get the final access token & secret: " << std::endl; std::cout << access_token_url << "?" << oAuthQueryString; std::cout << std::endl; // Once they've come back from the browser, extract the token and token_secret from the response std::string access_token_resp = getUserString("Enter the response:"); // On this extractToken, we do the parsing ourselves (via the library) so we // can extract additional keys that are sent back, in the case of twitter, // the screen_name OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp); OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data ); std::cout << "Access token:" << std::endl; std::cout << " - oauth_token = " << access_token.key() << std::endl; std::cout << " - oauth_token_secret = " << access_token.secret() << std::endl; std::cout << std::endl; std::cout << "You may now access protected resources using the access tokens above." << std::endl; std::cout << std::endl; if (access_token_resp_data.find("screen_name") != access_token_resp_data.end()) std::cout << "Also extracted screen name from access token response: " << access_token_resp_data["screen_name"] << std::endl; // E.g., to use the access token, you'd create a new OAuth using // it, discarding the request_token: // oauth = OAuth::Client(&consumer, &access_token); return 0; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <unsupported/Eigen/AlignedVector3> namespace Eigen { template<typename T,typename Derived> T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b) { return test_relative_error(a.coeffs().template head<3>(), b); } } template<typename Scalar> void alignedvector3() { Scalar s1 = internal::random<Scalar>(); Scalar s2 = internal::random<Scalar>(); typedef Matrix<Scalar,3,1> RefType; typedef Matrix<Scalar,3,3> Mat33; typedef AlignedVector3<Scalar> FastType; RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()), r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random()); FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6); Mat33 m1(Mat33::Random()); VERIFY_IS_APPROX(f1,r1); VERIFY_IS_APPROX(f4,r4); VERIFY_IS_APPROX(f4+f1,r4+r1); VERIFY_IS_APPROX(f4-f1,r4-r1); VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2); VERIFY_IS_APPROX(f4+=f3,r4+=r3); VERIFY_IS_APPROX(f4-=f5,r4-=r5); VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1); VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2); VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2); VERIFY_IS_APPROX(m1*f4,m1*r4); VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1); VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3)); VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3)); VERIFY_IS_APPROX(f2.norm(),r2.norm()); VERIFY_IS_APPROX(f2.normalized(),r2.normalized()); VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized()); f2.normalize(); r2.normalize(); VERIFY_IS_APPROX(f2,r2); std::stringstream ss1, ss2; ss1 << f1; ss2 << r1; VERIFY(ss1.str()==ss2.str()); } void test_alignedvector3() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( alignedvector3<float>() ); } } <commit_msg>add regression unit test for previous changeset<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <unsupported/Eigen/AlignedVector3> namespace Eigen { template<typename T,typename Derived> T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b) { return test_relative_error(a.coeffs().template head<3>(), b); } } template<typename Scalar> void alignedvector3() { Scalar s1 = internal::random<Scalar>(); Scalar s2 = internal::random<Scalar>(); typedef Matrix<Scalar,3,1> RefType; typedef Matrix<Scalar,3,3> Mat33; typedef AlignedVector3<Scalar> FastType; RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()), r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random()); FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6); Mat33 m1(Mat33::Random()); VERIFY_IS_APPROX(f1,r1); VERIFY_IS_APPROX(f4,r4); VERIFY_IS_APPROX(f4+f1,r4+r1); VERIFY_IS_APPROX(f4-f1,r4-r1); VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2); VERIFY_IS_APPROX(f4+=f3,r4+=r3); VERIFY_IS_APPROX(f4-=f5,r4-=r5); VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1); VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2); VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2); VERIFY_IS_APPROX(m1*f4,m1*r4); VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1); VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3)); VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3)); VERIFY_IS_APPROX(f2.norm(),r2.norm()); VERIFY_IS_APPROX(f2.normalized(),r2.normalized()); VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized()); f2.normalize(); r2.normalize(); VERIFY_IS_APPROX(f2,r2); { FastType f6 = RefType::Zero(); FastType f7 = FastType::Zero(); VERIFY_IS_APPROX(f6,f7); f6 = r4+r1; VERIFY_IS_APPROX(f6,r4+r1); f6 -= Scalar(2)*r4; VERIFY_IS_APPROX(f6,r1-r4); } std::stringstream ss1, ss2; ss1 << f1; ss2 << r1; VERIFY(ss1.str()==ss2.str()); } void test_alignedvector3() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( alignedvector3<float>() ); } } <|endoftext|>
<commit_before>#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__ #define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__ #include <aleph/geometry/distances/Traits.hh> #include <aleph/math/Statistics.hh> #include <algorithm> #include <map> #include <stdexcept> #include <vector> #include <cmath> namespace aleph { namespace containers { /* Wrapper class for representing a sequence of correlation dimension integral values. I want the interface to be as clear as possible. */ struct CorrelationDimensionSequence { std::vector<double> x; std::vector<double> y; }; /** Calculates samples of the correlation dimension integral for a given point cloud. This does *not* yet result in a dimension estimate, but only produces a set of points. */ template < class Distance, class Container > CorrelationDimensionSequence correlationDimensionIntegral( const Container& container, Distance dist = Distance() ) { auto n = container.size(); auto d = container.dimension(); std::map<double, unsigned> distances; aleph::geometry::distances::Traits<Distance> traits; for( decltype(n) i = 0; i < n; i++ ) { auto&& p = container[i]; for( decltype(n) j = i+1; j < n; j++ ) { auto&& q = container[j]; auto distance = dist( p.begin(), q.begin(), d ); distances[ traits.from( distance ) ] += 1; } } CorrelationDimensionSequence cds; cds.x.reserve( distances.size() ); cds.y.reserve( distances.size() ); // Determine the correlation dimension integral for all potential // values. This only requires counting how many *pairs* have been // seen by the algorithm. unsigned seen = 0; for( auto&& pair : distances ) { auto&& distance = pair.first; auto&& count = pair.second; seen += count; if( distance > 0 ) { cds.x.push_back( distance ); cds.y.push_back( seen / static_cast<double>( 0.5 * n * (n-1) ) ); } } return cds; } /** Estimates the correlation dimension from a correlation dimension sequence, which involves calculating a log-log plot of the data, and determining the best coefficient for a linear fit. */ double correlationDimension( const CorrelationDimensionSequence& cds ) { if( cds.x.size() != cds.y.size() ) throw std::runtime_error( "Inconsistent correlation dimension sequence" ); std::vector<double> X; std::vector<double> Y; X.reserve( cds.x.size() ); Y.reserve( cds.y.size() ); auto log = [] ( double x ) { return std::log( x ); }; std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log ); std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log ); // This is a simple linear regression model. We are only interested in // the slope of the regression line, so this is sufficient. auto cov = aleph::math::sampleCovariance( X.begin(), X.end(), Y.begin(), Y.end() ); auto var = aleph::math::sampleVariance( X.begin(), X.end() ); return cov / var; } } // namespace containers } // namespace aleph #endif <commit_msg>Fixed conversion error<commit_after>#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__ #define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__ #include <aleph/geometry/distances/Traits.hh> #include <aleph/math/Statistics.hh> #include <algorithm> #include <map> #include <stdexcept> #include <vector> #include <cmath> namespace aleph { namespace containers { /* Wrapper class for representing a sequence of correlation dimension integral values. I want the interface to be as clear as possible. */ struct CorrelationDimensionSequence { std::vector<double> x; std::vector<double> y; }; /** Calculates samples of the correlation dimension integral for a given point cloud. This does *not* yet result in a dimension estimate, but only produces a set of points. */ template < class Distance, class Container > CorrelationDimensionSequence correlationDimensionIntegral( const Container& container, Distance dist = Distance() ) { auto n = container.size(); auto d = container.dimension(); std::map<double, unsigned> distances; aleph::geometry::distances::Traits<Distance> traits; for( decltype(n) i = 0; i < n; i++ ) { auto&& p = container[i]; for( decltype(n) j = i+1; j < n; j++ ) { auto&& q = container[j]; auto distance = dist( p.begin(), q.begin(), d ); distances[ traits.from( distance ) ] += 1; } } CorrelationDimensionSequence cds; cds.x.reserve( distances.size() ); cds.y.reserve( distances.size() ); // Determine the correlation dimension integral for all potential // values. This only requires counting how many *pairs* have been // seen by the algorithm. unsigned seen = 0; for( auto&& pair : distances ) { auto&& distance = pair.first; auto&& count = pair.second; seen += count; if( distance > 0 ) { cds.x.push_back( distance ); cds.y.push_back( seen / ( static_cast<double>( n * (n-1) ) * 0.5 ) ); } } return cds; } /** Estimates the correlation dimension from a correlation dimension sequence, which involves calculating a log-log plot of the data, and determining the best coefficient for a linear fit. */ double correlationDimension( const CorrelationDimensionSequence& cds ) { if( cds.x.size() != cds.y.size() ) throw std::runtime_error( "Inconsistent correlation dimension sequence" ); std::vector<double> X; std::vector<double> Y; X.reserve( cds.x.size() ); Y.reserve( cds.y.size() ); auto log = [] ( double x ) { return std::log( x ); }; std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log ); std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log ); // This is a simple linear regression model. We are only interested in // the slope of the regression line, so this is sufficient. auto cov = aleph::math::sampleCovariance( X.begin(), X.end(), Y.begin(), Y.end() ); auto var = aleph::math::sampleVariance( X.begin(), X.end() ); return cov / var; } } // namespace containers } // namespace aleph #endif <|endoftext|>
<commit_before>#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_ #define CLOTHO_BIT_BLOCK_FITNESS_HPP_ #include <iostream> #include "clotho/fitness/bit_block_genotyper.hpp" #include "clotho/utility/bit_block_iterator.hpp" namespace clotho { namespace fitness { struct no_fit {}; template < class HetFit, class AltHomFit, class RefHomFit, class Result = double > class bit_block_fitness { public: typedef Result result_type; bit_block_fitness() {} bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) : m_hets( hets ) , m_ahoms(ahoms) , m_rhoms(rhoms) { } template < class Block, class ElementIterator > result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) { result_type res = f; typedef bit_block_genotyper< Block > genotyper; computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets); computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms); computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms); return res; } virtual ~bit_block_fitness() {} protected: template < class Block, class ElementIterator, class FitOp > void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) { typedef clotho::utility::bit_block_iterator< Block > iterator; iterator it( b ), end; while( it != end ) { (*op)( res, *(first + *it++)); } } template < class Block, class ElementIterator, class SetOp, class FitOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) { Block bits = ( (*sop)(b0, b1) & keep ); computeFitness( res, bits, first, op ); } template < class Block, class ElementIterator, class SetOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { } HetFit m_hets; AltHomFit m_ahoms; RefHomFit m_rhoms; }; template < class HetFit, class HomFit, class Result > class bit_block_fitness< HetFit, HomFit, HomFit, Result > { public: typedef Result result_type; bit_block_fitness( ) {} bit_block_fitness( const HetFit & hets, const HomFit & homs ) : m_hets( hets ) , m_homs(homs) { } template < class Block, class ElementIterator > result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) { result_type res = f; typedef bit_block_genotyper< Block > genotyper; computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets); computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs); return res; } virtual ~bit_block_fitness() {} protected: template < class Block, class ElementIterator, class FitOp > inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) { typedef clotho::utility::bit_block_iterator< Block > iterator; iterator it( b ), end; while( it != end ) { (*op)( res, *(first + *it++)); } } template < class Block, class ElementIterator, class SetOp, class FitOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) { Block bits = ( (*sop)(b0, b1) & keep ); computeFitness( res, bits, first, op ); } template < class Block, class ElementIterator, class SetOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { } HetFit m_hets; HomFit m_homs; }; template < class Result > class bit_block_fitness< no_fit, no_fit, no_fit, Result > { public: typedef Result result_type; bit_block_fitness( ) {} template < class Block, class ElementIterator > result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) { return f; } virtual ~bit_block_fitness() {} }; } // namespace fitness { } // namespace clotho { #endif // CLOTHO_BIT_BLOCK_FITNESS_HPP_ <commit_msg>utilizing new bit walking based iterator<commit_after>#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_ #define CLOTHO_BIT_BLOCK_FITNESS_HPP_ #include <iostream> #include "clotho/fitness/bit_block_genotyper.hpp" #include "clotho/utility/bit_block_iterator.hpp" namespace clotho { namespace fitness { struct no_fit {}; template < class HetFit, class AltHomFit, class RefHomFit, class Result = double > class bit_block_fitness { public: typedef Result result_type; bit_block_fitness() {} bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) : m_hets( hets ) , m_ahoms(ahoms) , m_rhoms(rhoms) { } template < class Block, class ElementIterator > result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) { result_type res = f; typedef bit_block_genotyper< Block > genotyper; computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets); computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms); computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms); return res; } virtual ~bit_block_fitness() {} protected: template < class Block, class ElementIterator, class FitOp > void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) { typedef clotho::utility::bit_block_iterator< Block, clotho::utility::walk_iterator_tag > iterator; iterator it( b ), end; while( it != end ) { (*op)( res, *(first + *it++)); } } template < class Block, class ElementIterator, class SetOp, class FitOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) { Block bits = ( (*sop)(b0, b1) & keep ); computeFitness( res, bits, first, op ); } template < class Block, class ElementIterator, class SetOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { } HetFit m_hets; AltHomFit m_ahoms; RefHomFit m_rhoms; }; template < class HetFit, class HomFit, class Result > class bit_block_fitness< HetFit, HomFit, HomFit, Result > { public: typedef Result result_type; bit_block_fitness( ) {} bit_block_fitness( const HetFit & hets, const HomFit & homs ) : m_hets( hets ) , m_homs(homs) { } template < class Block, class ElementIterator > result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) { result_type res = f; typedef bit_block_genotyper< Block > genotyper; computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets); computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs); return res; } virtual ~bit_block_fitness() {} protected: template < class Block, class ElementIterator, class FitOp > inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) { typedef clotho::utility::bit_block_iterator< Block > iterator; iterator it( b ), end; while( it != end ) { (*op)( res, *(first + *it++)); } } template < class Block, class ElementIterator, class SetOp, class FitOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) { Block bits = ( (*sop)(b0, b1) & keep ); computeFitness( res, bits, first, op ); } template < class Block, class ElementIterator, class SetOp > inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { } HetFit m_hets; HomFit m_homs; }; template < class Result > class bit_block_fitness< no_fit, no_fit, no_fit, Result > { public: typedef Result result_type; bit_block_fitness( ) {} template < class Block, class ElementIterator > result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) { return f; } virtual ~bit_block_fitness() {} }; } // namespace fitness { } // namespace clotho { #endif // CLOTHO_BIT_BLOCK_FITNESS_HPP_ <|endoftext|>
<commit_before>#include <ros/ros.h> #include <geometry_msgs/Pose.h> #include <sensor_msgs/PointCloud.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib_msgs/GoalStatusArray.h> #include <tf/transform_listener.h> #include <stdlib.h> double goal_tolerance, frontier_tolerance; bool random_frontier; std::string map_frame, base_frame, goal_topic; sensor_msgs::PointCloud global_frontiers; geometry_msgs::Point32 frontier, old_frontier; tf::TransformListener* listener; actionlib_msgs::GoalStatusArray global_status; std::vector<geometry_msgs::Point32> reached_frontiers; template <class T1, class T2> double distance(T1 from, T2 to) { return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2)); } bool my_pose(geometry_msgs::Pose *pose) { tf::StampedTransform transform; try { listener->lookupTransform(map_frame, base_frame, ros::Time(0), transform); } catch(tf::TransformException ex) { //ROS_ERROR("TF %s - %s: %s", map_frame.c_str(), base_frame.c_str(), ex.what()); return false; } pose->position.x = transform.getOrigin().getX(); pose->position.y = transform.getOrigin().getY(); pose->position.z = transform.getOrigin().getZ(); pose->orientation.x = transform.getRotation().getX(); pose->orientation.y = transform.getRotation().getY(); pose->orientation.z = transform.getRotation().getZ(); return true; } void frontier_callback(const sensor_msgs::PointCloud::ConstPtr &msg) { global_frontiers = *msg; } void status_callback(const actionlib_msgs::GoalStatusArray::ConstPtr &msg){ global_status = *msg; } bool frontier_blacklisting( geometry_msgs::Point32 p) { std::vector<geometry_msgs::Point32>::iterator it; for(it = reached_frontiers.begin(); it != reached_frontiers.end(); it++) { double dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(*it, p); if(dist < goal_tolerance) return false; } return true; } bool find_next_frontier() { geometry_msgs::Pose pose; if(!my_pose(&pose)) { //ROS_WARN("Cannot find my pose"); return false; } double dist = distance<geometry_msgs::Point, geometry_msgs::Point32>(pose.position, frontier); if(dist > goal_tolerance) { for (int i = 0; i < global_status.status_list.size(); i++) { int stat = global_status.status_list[i].status; if (stat == 1) return false; } } else { reached_frontiers.push_back(frontier); } if(global_frontiers.points.size() == 0) { ROS_WARN("No frontier to allocate at this time"); return false; } if(random_frontier ) { old_frontier = frontier; frontier = global_frontiers.points[ rand() % global_frontiers.points.size()]; return true; } // nearest frontier allocation double mindist = 0, fr_dist; bool allocated = false; old_frontier = frontier; for (int i = 0; i < global_frontiers.points.size(); i++) { if(!frontier_blacklisting(global_frontiers.points[i])) continue; dist = distance<geometry_msgs::Point, geometry_msgs::Point32>(pose.position, global_frontiers.points[i]); fr_dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(old_frontier, global_frontiers.points[i]); if ( ( old_frontier.x == 0 && old_frontier.y == 0 ) ||( (mindist == 0 || dist < mindist) && dist > goal_tolerance && fr_dist > frontier_tolerance)) { frontier = global_frontiers.points[i]; mindist = dist; allocated = true; } } return allocated; } int main(int argc, char**argv) { ros::init(argc, argv, "frontier_allocator"); ros::NodeHandle private_nh("~"); listener = new tf::TransformListener(); private_nh.param<double>("goal_tolerance", goal_tolerance, 0.3); private_nh.param<double>("frontier_tolerance", frontier_tolerance, 0.3); private_nh.param<bool>("random_frontier", random_frontier, false); private_nh.param<std::string>("map_frame", map_frame, "map"); private_nh.param<std::string>("base_frame", base_frame, "base_link"); private_nh.param<std::string>("goal_topic", goal_topic, "/move_base_simple/goal"); ros::Subscriber sub_ph = private_nh.subscribe<sensor_msgs::PointCloud>("/phrontier_global", 100, &frontier_callback); ros::Publisher pub_goal = private_nh.advertise<geometry_msgs::PoseStamped>(goal_topic, 10); ros::Subscriber sub_status = private_nh.subscribe<actionlib_msgs::GoalStatusArray>("/move_base/status", 10, &status_callback); srand(time(NULL)); ros::Rate loop_rate(3.0); while (ros::ok()) { ros::spinOnce(); if (find_next_frontier()) { geometry_msgs::PoseStamped goal; goal.header.frame_id = map_frame; goal.pose.position.x = frontier.x; goal.pose.position.y = frontier.y; goal.pose.orientation.x = 0; goal.pose.orientation.y = 0; goal.pose.orientation.z = 0; goal.pose.orientation.w = 1; pub_goal.publish(goal); } loop_rate.sleep(); } }<commit_msg>fix frontier allocation<commit_after>#include <ros/ros.h> #include <geometry_msgs/Pose.h> #include <sensor_msgs/PointCloud.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib_msgs/GoalStatusArray.h> #include <tf/transform_listener.h> #include <stdlib.h> typedef struct { geometry_msgs::Point32 position; int weight; } frontier_t; double goal_tolerance, frontier_tolerance; bool random_frontier; std::string map_frame, base_frame, goal_topic; sensor_msgs::PointCloud global_frontiers; frontier_t frontier, old_frontier; tf::TransformListener* listener; actionlib_msgs::GoalStatusArray global_status; std::vector<frontier_t> reached_frontiers; template <class T1, class T2> double distance(T1 from, T2 to) { return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2)); } bool my_pose(geometry_msgs::Pose *pose) { tf::StampedTransform transform; try { listener->lookupTransform(map_frame, base_frame, ros::Time(0), transform); } catch(tf::TransformException ex) { //ROS_ERROR("TF %s - %s: %s", map_frame.c_str(), base_frame.c_str(), ex.what()); return false; } pose->position.x = transform.getOrigin().getX(); pose->position.y = transform.getOrigin().getY(); pose->position.z = transform.getOrigin().getZ(); pose->orientation.x = transform.getRotation().getX(); pose->orientation.y = transform.getRotation().getY(); pose->orientation.z = transform.getRotation().getZ(); return true; } void frontier_callback(const sensor_msgs::PointCloud::ConstPtr &msg) { global_frontiers = *msg; } void status_callback(const actionlib_msgs::GoalStatusArray::ConstPtr &msg){ global_status = *msg; } frontier_t frontier_blacklisting( geometry_msgs::Point32 p) { frontier_t fr; fr.weight = 0; fr.position = p; std::vector<frontier_t>::iterator it; for(it = reached_frontiers.begin(); it != reached_frontiers.end(); it++) { double dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(it->position, p); if(dist < goal_tolerance) { fr.weight++; return fr; } } return fr; } bool find_next_frontier() { geometry_msgs::Pose pose; if(!my_pose(&pose)) { //ROS_WARN("Cannot find my pose"); return false; } double dist = distance<geometry_msgs::Point, geometry_msgs::Point32>(pose.position, frontier.position); if(dist > goal_tolerance) { for (int i = 0; i < global_status.status_list.size(); i++) { int stat = global_status.status_list[i].status; if (stat == 1) return false; } } else { frontier.weight++; reached_frontiers.push_back(frontier); } if(global_frontiers.points.size() == 0) { ROS_WARN("No frontier to allocate at this time"); return false; } if(random_frontier ) { old_frontier = frontier; frontier.weight=0; frontier.position = global_frontiers.points[ rand() % global_frontiers.points.size()]; return true; } // nearest frontier allocation double mindist = 0, fr_dist; bool allocated = false; old_frontier = frontier; frontier_t fr; for (int i = 0; i < global_frontiers.points.size(); i++) { dist = distance<geometry_msgs::Point, geometry_msgs::Point32>(pose.position, global_frontiers.points[i]); fr_dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(old_frontier.position, global_frontiers.points[i]); if ( ( old_frontier.position.x == 0 && old_frontier.position.y == 0 ) ||( (mindist == 0 || dist < mindist) && dist > goal_tolerance && fr_dist > frontier_tolerance)) { fr = frontier_blacklisting(global_frontiers.points[i]); if(fr.weight <= frontier.weight) { frontier = fr; mindist = dist; allocated = true; } } } return allocated; } int main(int argc, char**argv) { ros::init(argc, argv, "frontier_allocator"); ros::NodeHandle private_nh("~"); listener = new tf::TransformListener(); private_nh.param<double>("goal_tolerance", goal_tolerance, 0.3); private_nh.param<double>("frontier_tolerance", frontier_tolerance, 0.3); private_nh.param<bool>("random_frontier", random_frontier, false); private_nh.param<std::string>("map_frame", map_frame, "map"); private_nh.param<std::string>("base_frame", base_frame, "base_link"); private_nh.param<std::string>("goal_topic", goal_topic, "/move_base_simple/goal"); ros::Subscriber sub_ph = private_nh.subscribe<sensor_msgs::PointCloud>("/phrontier_global", 100, &frontier_callback); ros::Publisher pub_goal = private_nh.advertise<geometry_msgs::PoseStamped>(goal_topic, 10); ros::Subscriber sub_status = private_nh.subscribe<actionlib_msgs::GoalStatusArray>("/move_base/status", 10, &status_callback); srand(time(NULL)); ros::Rate loop_rate(3.0); while (ros::ok()) { ros::spinOnce(); if (find_next_frontier()) { geometry_msgs::PoseStamped goal; goal.header.frame_id = map_frame; goal.pose.position.x = frontier.position.x; goal.pose.position.y = frontier.position.y; goal.pose.orientation.x = 0; goal.pose.orientation.y = 0; goal.pose.orientation.z = 0; goal.pose.orientation.w = 1; pub_goal.publish(goal); } loop_rate.sleep(); } }<|endoftext|>
<commit_before>#pragma once #include <string> #include <unordered_map> #include <vector> #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraInfo.hpp" #include "depthai-shared/common/Extrinsics.hpp" #include "depthai-shared/common/Point3f.hpp" #include "depthai-shared/common/StereoRectification.hpp" // libraries #include "nlohmann/json.hpp" namespace dai { /** * EepromData structure * * Contains the Calibration and Board data stored on device */ struct EepromData { uint32_t version = 6; bool swapLeftRightCam = false; std::string boardName, boardRev; std::unordered_map<CameraBoardSocket, CameraInfo> cameraData; StereoRectification stereoRectificationData; Extrinsics imuExtrinsics; std::vector<uint8_t> miscellaneousData; NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData); }; } // namespace dai <commit_msg>remvoed swap<commit_after>#pragma once #include <string> #include <unordered_map> #include <vector> #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraInfo.hpp" #include "depthai-shared/common/Extrinsics.hpp" #include "depthai-shared/common/Point3f.hpp" #include "depthai-shared/common/StereoRectification.hpp" // libraries #include "nlohmann/json.hpp" namespace dai { /** * EepromData structure * * Contains the Calibration and Board data stored on device */ struct EepromData { uint32_t version = 6; std::string boardName, boardRev; std::unordered_map<CameraBoardSocket, CameraInfo> cameraData; StereoRectification stereoRectificationData; Extrinsics imuExtrinsics; std::vector<uint8_t> miscellaneousData; NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData); }; } // namespace dai <|endoftext|>
<commit_before>// Copyright (c) 2014, Salesforce.com, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // - Neither the name of Salesforce.com 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. #pragma once #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/io/gzip_stream.h> #include <distributions/common.hpp> namespace distributions { namespace protobuf { inline bool startswith (const char * filename, const char * prefix) { return strlen(filename) >= strlen(prefix) and strncmp(filename, prefix, strlen(prefix)) == 0; } inline bool endswith (const char * filename, const char * suffix) { return strlen(filename) >= strlen(suffix) and strcmp(filename + strlen(filename) - strlen(suffix), suffix) == 0; } class InFile { public: InFile (const char * filename) : filename_(filename) { if (startswith(filename, "-")) { fid_ = -1; raw_ = new google::protobuf::io::IstreamInputStream(& std::cin); } else { fid_ = open(filename, O_RDONLY | O_NOATIME); DIST_ASSERT(fid_ != -1, "failed to open input file " << filename); raw_ = new google::protobuf::io::FileInputStream(fid_); } if (endswith(filename, ".gz")) { gzip_ = new google::protobuf::io::GzipInputStream(raw_); coded_ = new google::protobuf::io::CodedInputStream(gzip_); } else { gzip_ = nullptr; coded_ = new google::protobuf::io::CodedInputStream(raw_); } } ~InFile () { delete coded_; delete gzip_; delete raw_; if (fid_ != -1) { close(fid_); } } template<class Message> void read (Message & message) { bool success = message.ParseFromCodedStream(coded_); DIST_ASSERT(success, "failed to parse message from " << filename_); } template<class Message> bool try_read_stream (Message & message) { uint32_t message_size = 0; if (DIST_LIKELY(coded_->ReadLittleEndian32(& message_size))) { auto old_limit = coded_->PushLimit(message_size); bool success = message.ParseFromCodedStream(coded_); DIST_ASSERT(success, "failed to parse message from " << filename_); coded_->PopLimit(old_limit); return true; } else { return false; } } private: const std::string filename_; int fid_; google::protobuf::io::ZeroCopyInputStream * raw_; google::protobuf::io::GzipInputStream * gzip_; google::protobuf::io::CodedInputStream * coded_; }; class OutFile { public: OutFile (const char * filename) : filename_(filename) { if (startswith(filename, "-")) { fid_ = -1; raw_ = new google::protobuf::io::OstreamOutputStream(& std::cout); } else { fid_ = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664); DIST_ASSERT(fid_ != -1, "failed to open output file " << filename); raw_ = new google::protobuf::io::FileOutputStream(fid_); } if (endswith(filename, ".gz")) { gzip_ = new google::protobuf::io::GzipOutputStream(raw_); coded_ = new google::protobuf::io::CodedOutputStream(gzip_); } else { gzip_ = nullptr; coded_ = new google::protobuf::io::CodedOutputStream(raw_); } } ~OutFile () { delete coded_; delete gzip_; delete raw_; if (fid_ != -1) { close(fid_); } } template<class Message> void write (Message & message) { DIST_ASSERT1(message.IsInitialized(), "message not initialized"); message.ByteSize(); message.SerializeWithCachedSizes(coded_); } template<class Message> void write_stream (Message & message) { DIST_ASSERT1(message.IsInitialized(), "message not initialized"); uint32_t message_size = message.ByteSize(); DIST_ASSERT1(message_size > 0, "zero sized message"); coded_->WriteLittleEndian32(message_size); message.SerializeWithCachedSizes(coded_); } private: const std::string filename_; int fid_; google::protobuf::io::ZeroCopyOutputStream * raw_; google::protobuf::io::GzipOutputStream * gzip_; google::protobuf::io::CodedOutputStream * coded_; }; } // namespace protobuf } // namespace distributions <commit_msg>Add assertion to protobuf::OutFile::write<commit_after>// Copyright (c) 2014, Salesforce.com, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // - Neither the name of Salesforce.com 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. #pragma once #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/io/gzip_stream.h> #include <distributions/common.hpp> namespace distributions { namespace protobuf { inline bool startswith (const char * filename, const char * prefix) { return strlen(filename) >= strlen(prefix) and strncmp(filename, prefix, strlen(prefix)) == 0; } inline bool endswith (const char * filename, const char * suffix) { return strlen(filename) >= strlen(suffix) and strcmp(filename + strlen(filename) - strlen(suffix), suffix) == 0; } class InFile { public: InFile (const char * filename) : filename_(filename) { if (startswith(filename, "-")) { fid_ = -1; raw_ = new google::protobuf::io::IstreamInputStream(& std::cin); } else { fid_ = open(filename, O_RDONLY | O_NOATIME); DIST_ASSERT(fid_ != -1, "failed to open input file " << filename); raw_ = new google::protobuf::io::FileInputStream(fid_); } if (endswith(filename, ".gz")) { gzip_ = new google::protobuf::io::GzipInputStream(raw_); coded_ = new google::protobuf::io::CodedInputStream(gzip_); } else { gzip_ = nullptr; coded_ = new google::protobuf::io::CodedInputStream(raw_); } } ~InFile () { delete coded_; delete gzip_; delete raw_; if (fid_ != -1) { close(fid_); } } template<class Message> void read (Message & message) { bool success = message.ParseFromCodedStream(coded_); DIST_ASSERT(success, "failed to parse message from " << filename_); } template<class Message> bool try_read_stream (Message & message) { uint32_t message_size = 0; if (DIST_LIKELY(coded_->ReadLittleEndian32(& message_size))) { auto old_limit = coded_->PushLimit(message_size); bool success = message.ParseFromCodedStream(coded_); DIST_ASSERT(success, "failed to parse message from " << filename_); coded_->PopLimit(old_limit); return true; } else { return false; } } private: const std::string filename_; int fid_; google::protobuf::io::ZeroCopyInputStream * raw_; google::protobuf::io::GzipInputStream * gzip_; google::protobuf::io::CodedInputStream * coded_; }; class OutFile { public: OutFile (const char * filename) : filename_(filename) { if (startswith(filename, "-")) { fid_ = -1; raw_ = new google::protobuf::io::OstreamOutputStream(& std::cout); } else { fid_ = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664); DIST_ASSERT(fid_ != -1, "failed to open output file " << filename); raw_ = new google::protobuf::io::FileOutputStream(fid_); } if (endswith(filename, ".gz")) { gzip_ = new google::protobuf::io::GzipOutputStream(raw_); coded_ = new google::protobuf::io::CodedOutputStream(gzip_); } else { gzip_ = nullptr; coded_ = new google::protobuf::io::CodedOutputStream(raw_); } } ~OutFile () { delete coded_; delete gzip_; delete raw_; if (fid_ != -1) { close(fid_); } } template<class Message> void write (Message & message) { DIST_ASSERT1(message.IsInitialized(), "message not initialized"); bool success = message.SerializeToCodedStream(coded_); DIST_ASSERT(success, "failed to serialize message to " << filename_); } template<class Message> void write_stream (Message & message) { DIST_ASSERT1(message.IsInitialized(), "message not initialized"); uint32_t message_size = message.ByteSize(); DIST_ASSERT1(message_size > 0, "zero sized message"); coded_->WriteLittleEndian32(message_size); message.SerializeWithCachedSizes(coded_); } private: const std::string filename_; int fid_; google::protobuf::io::ZeroCopyOutputStream * raw_; google::protobuf::io::GzipOutputStream * gzip_; google::protobuf::io::CodedOutputStream * coded_; }; } // namespace protobuf } // namespace distributions <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../../include/SQLiteDatabase.h" #include <iostream> #include <fstream> #include <vector> bool fexists(const std::string& filename) { std::ifstream ifile(filename.c_str()); return ifile; }; class SQLiteDatabaseTestFixture : public ::testing::Test { public: SQLiteDatabaseTestFixture( ) { test_database_filename_ = "test.db"; } void SetUp( ) { // code here will execute just before the test ensues } void TearDown( ) { // code here will be called just after the test completes // ok to through exceptions from here if need be } ~SQLiteDatabaseTestFixture( ) { remove("test.db"); } // Test Member Variables std::string test_database_filename_; }; TEST_F(SQLiteDatabaseTestFixture, create_database_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); db.close(); } catch (const std::exception & e) { std::cout << e.what() << std::endl; } ASSERT_TRUE(fexists(test_database_filename_)); } TEST_F(SQLiteDatabaseTestFixture, database_version_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } int expected_version = 1; db.setVersion(expected_version); auto version = db.getVersion(); db.close(); EXPECT_EQ(expected_version, version); } TEST_F(SQLiteDatabaseTestFixture, get_readonly_database_test) { sqlite::SQLiteDatabase db; int expected_version = 1; int version = 0; try{ db.open(test_database_filename_, SQLITE_OPEN_READONLY); EXPECT_ANY_THROW(db.setVersion(expected_version)); db.close(); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } } TEST_F(SQLiteDatabaseTestFixture, query_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); // Create Cars table test data const std::string kCreateTable = "CREATE TABLE IF NOT EXISTS cars " "(mpg text, " "weight text)"; db.execQuery(kCreateTable); db.execQuery("INSERT INTO cars " "VALUES('34', '2000')"); db.execQuery("INSERT INTO cars " "VALUES('27', '25000')"); db.execQuery("INSERT INTO cars " "VALUES('16', '5000')"); std::vector<std::string> columns; columns.push_back("mpg"); columns.push_back("weight"); std::string selection; std::vector<std::string> selectionArgs; auto c = db.query(true, "cars", columns, selection, selectionArgs, "", "", ""); c.next(); EXPECT_STREQ(c.getString(1).c_str(), "34"); EXPECT_STREQ(c.getString(2).c_str(), "2000"); c.next(); EXPECT_STREQ(c.getString(1).c_str(), "27"); EXPECT_STREQ(c.getString(2).c_str(), "25000"); c.next(); EXPECT_STREQ(c.getString(1).c_str(), "16"); EXPECT_STREQ(c.getString(2).c_str(), "5000"); db.close(); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } } <commit_msg>added insert unit test<commit_after>#include <gtest/gtest.h> #include "../../include/SQLiteDatabase.h" #include <iostream> #include <fstream> #include <vector> bool fexists(const std::string& filename) { std::ifstream ifile(filename.c_str()); return ifile; }; class SQLiteDatabaseTestFixture : public ::testing::Test { public: SQLiteDatabaseTestFixture( ) { test_database_filename_ = "test.db"; } void SetUp( ) { // code here will execute just before the test ensues } void TearDown( ) { // code here will be called just after the test completes // ok to through exceptions from here if need be } ~SQLiteDatabaseTestFixture( ) { remove("test.db"); } // Test Member Variables std::string test_database_filename_; }; TEST_F(SQLiteDatabaseTestFixture, create_database_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); db.close(); } catch (const std::exception & e) { std::cout << e.what() << std::endl; } ASSERT_TRUE(fexists(test_database_filename_)); } TEST_F(SQLiteDatabaseTestFixture, database_version_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } int expected_version = 1; db.setVersion(expected_version); auto version = db.getVersion(); db.close(); EXPECT_EQ(expected_version, version); } TEST_F(SQLiteDatabaseTestFixture, get_readonly_database_test) { sqlite::SQLiteDatabase db; int expected_version = 1; int version = 0; try{ db.open(test_database_filename_, SQLITE_OPEN_READONLY); EXPECT_ANY_THROW(db.setVersion(expected_version)); db.close(); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } } TEST_F(SQLiteDatabaseTestFixture, query_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); // Create Cars table test data const std::string kCreateTable = "CREATE TABLE IF NOT EXISTS cars " "(mpg text, " "weight text)"; db.execQuery(kCreateTable); db.execQuery("INSERT INTO cars " "VALUES('34', '2000')"); db.execQuery("INSERT INTO cars " "VALUES('27', '25000')"); db.execQuery("INSERT INTO cars " "VALUES('16', '5000')"); std::vector<std::string> columns; columns.push_back("mpg"); columns.push_back("weight"); std::string selection; std::vector<std::string> selectionArgs; auto c = db.query(true, "cars", columns, selection, selectionArgs, "", "", ""); c.next(); EXPECT_STREQ(c.getString(1).c_str(), "34"); EXPECT_STREQ(c.getString(2).c_str(), "2000"); c.next(); EXPECT_STREQ(c.getString(1).c_str(), "27"); EXPECT_STREQ(c.getString(2).c_str(), "25000"); c.next(); EXPECT_STREQ(c.getString(1).c_str(), "16"); EXPECT_STREQ(c.getString(2).c_str(), "5000"); db.close(); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } } TEST_F(SQLiteDatabaseTestFixture, insert_test) { sqlite::SQLiteDatabase db; try{ db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); // Create Cars table test data const std::string kCreateTable = "CREATE TABLE IF NOT EXISTS cars " "(mpg text, " "weight text)"; db.execQuery(kCreateTable); const std::string table = "cars"; long id = db.insert(table, std::vector<std::string>{"mpg", "weight"}, std::vector<std::string>{"34", "2000"}, "", std::vector<std::string>{}); long id2 = db.insert(table, std::vector<std::string>{"mpg", "weight"}, std::vector<std::string>{"20", "1500"}, "", std::vector<std::string>{}); EXPECT_EQ(id, 1); EXPECT_EQ(id2, 2); db.close(); } catch (const std::exception & e){ std::cout << e.what() << std::endl; } } <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, 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 <chrono> #include <iostream> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete) { auto node = rclcpp::Node::make_shared("test_spin"); // Construct a fake future to wait on std::promise<bool> promise; std::shared_future<bool> future(promise.get_future()); // Make a timer to complete the promise in the future int i = 0; auto callback = [&promise, &i]() { if (i > 0) { promise.set_value(true); } ++i; }; auto timer = node->create_wall_timer(std::chrono::milliseconds(25), callback); ASSERT_EQ(rclcpp::spin_until_future_complete(node, future), rclcpp::executors::FutureReturnCode::SUCCESS); EXPECT_EQ(future.get(), true); } TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_timeout) { auto node = rclcpp::Node::make_shared("test_spin"); // Construct a fake future to wait on std::promise<bool> promise; std::shared_future<bool> future(promise.get_future()); // Make a timer to complete the promise in the future int i = 0; auto callback = [&promise, &i]() { if (i > 0) { promise.set_value(true); } ++i; }; auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback); ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(25)), rclcpp::executors::FutureReturnCode::TIMEOUT); // If we wait a little longer, we should complete the future ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)), rclcpp::executors::FutureReturnCode::SUCCESS); EXPECT_EQ(future.get(), true); } TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_interrupted) { auto node = rclcpp::Node::make_shared("test_spin"); // Construct a fake future to wait on std::promise<bool> promise; std::shared_future<bool> future(promise.get_future()); // Make a timer to complete the promise in the future int i = 0; auto callback = [&promise, &i]() { if (i > 0) { promise.set_value(true); } ++i; }; auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback); // Create a timer that will shut down rclcpp before auto shutdown_callback = []() { rclcpp::utilities::shutdown(); }; auto shutdown_timer = node->create_wall_timer(std::chrono::milliseconds(25), shutdown_callback); ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)), rclcpp::executors::FutureReturnCode::INTERRUPTED); } int main(int argc, char ** argv) { // NOTE: use custom main to ensure that rclcpp::init is called only once rclcpp::init(0, nullptr); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>fix timer behavior in test_spin<commit_after>// Copyright 2015 Open Source Robotics Foundation, 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 <chrono> #include <iostream> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete) { auto node = rclcpp::Node::make_shared("test_spin"); // Construct a fake future to wait on std::promise<bool> promise; std::shared_future<bool> future(promise.get_future()); // Make a timer to complete the promise in the future auto callback = [&promise]() { promise.set_value(true); }; auto timer = node->create_wall_timer(std::chrono::milliseconds(25), callback); ASSERT_EQ(rclcpp::spin_until_future_complete(node, future), rclcpp::executors::FutureReturnCode::SUCCESS); EXPECT_EQ(future.get(), true); } TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_timeout) { auto node = rclcpp::Node::make_shared("test_spin"); // Construct a fake future to wait on std::promise<bool> promise; std::shared_future<bool> future(promise.get_future()); // Make a timer to complete the promise in the future auto callback = [&promise]() { promise.set_value(true); }; auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback); ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(25)), rclcpp::executors::FutureReturnCode::TIMEOUT); // If we wait a little longer, we should complete the future ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)), rclcpp::executors::FutureReturnCode::SUCCESS); EXPECT_EQ(future.get(), true); } TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_interrupted) { auto node = rclcpp::Node::make_shared("test_spin"); // Construct a fake future to wait on std::promise<bool> promise; std::shared_future<bool> future(promise.get_future()); // Make a timer to complete the promise in the future auto callback = [&promise]() { promise.set_value(true); }; auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback); // Create a timer that will shut down rclcpp before auto shutdown_callback = []() { rclcpp::utilities::shutdown(); }; auto shutdown_timer = node->create_wall_timer(std::chrono::milliseconds(25), shutdown_callback); ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)), rclcpp::executors::FutureReturnCode::INTERRUPTED); } int main(int argc, char ** argv) { // NOTE: use custom main to ensure that rclcpp::init is called only once rclcpp::init(0, nullptr); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "mocca/base/ByteArray.h" #include <limits> #include <algorithm> static_assert(std::numeric_limits<float>::is_iec559 == true, "Unsupported floating point type"); static_assert(std::numeric_limits<double>::is_iec559 == true, "Unsupported floating point type"); namespace mocca { const unsigned char ByteArray::trueConst; const unsigned char ByteArray::falseConst; ByteArray::ByteArray(uint32_t capacity) : data_(new unsigned char[capacity]) , capacity_(capacity) , size_(0) , readPos_(0) {} ByteArray::ByteArray(const ByteArray& other) : data_(new unsigned char[other.capacity_]) , capacity_(other.capacity_) , size_(other.size_) , readPos_(other.readPos_) { memcpy(data_.get(), other.data_.get(), other.size_); } ByteArray::ByteArray(ByteArray&& other) : data_(std::move(other.data_)) , capacity_(other.capacity_) , size_(other.size_) , readPos_(other.readPos_) { other.capacity_ = 0; other.size_ = 0; other.readPos_ = 0; } ByteArray& ByteArray::operator=(ByteArray other) { swap(other, *this); return *this; } void swap(ByteArray& lhs, ByteArray& rhs) { using std::swap; swap(lhs.data_, rhs.data_); swap(lhs.capacity_, rhs.capacity_); swap(lhs.size_, rhs.size_); swap(lhs.readPos_, rhs.readPos_); } unsigned char* ByteArray::data() { return data_.get(); } const unsigned char* ByteArray::data() const { return data_.get(); } uint32_t ByteArray::size() const { return size_; } void ByteArray::setSize(uint32_t size) { if (size > capacity_) { throw Error("Size exceeds capacity of the byte array", __FILE__, __LINE__); } size_ = size; } bool ByteArray::isEmpty() const { return size_ == 0; } uint32_t ByteArray::capacity() const { return capacity_; } void ByteArray::resize(uint32_t newCapacity) { auto newData = std::unique_ptr<unsigned char[]>(new unsigned char[newCapacity]); memcpy(newData.get(), data_.get(), size_); data_ = std::move(newData); capacity_ = newCapacity; } void ByteArray::append(const void* data, uint32_t size) { if (capacity_ < size_ + size) { resize(size_ + std::max(2 * size, 256u)); } memcpy(data_.get() + size_, data, size); size_ += size; } void mocca::ByteArray::append(const ByteArray& byteArray) { append(byteArray.data(), byteArray.size()); } ByteArray ByteArray::createFromRaw(const void* raw, uint32_t size) { auto byteArray = ByteArray(size); memcpy(byteArray.data_.get(), raw, size); byteArray.size_ = size; return byteArray; } ByteArray& ByteArray::operator<<(int32_t val) { append(&val, sizeof(int32_t)); return *this; } ByteArray& ByteArray::operator>>(int32_t& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(int32_t) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(int32_t)); readPos_ += sizeof(int32_t); return *this; } ByteArray& ByteArray::operator<<(uint32_t val) { return (*this << (int32_t)val); } ByteArray& ByteArray::operator>>(uint32_t& val) { return (*this >> (int32_t&)val); } ByteArray& ByteArray::operator<<(int64_t val) { append(&val, sizeof(int64_t)); return *this; } ByteArray& ByteArray::operator>>(int64_t& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(int64_t) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(int64_t)); readPos_ += sizeof(int64_t); return *this; } ByteArray& ByteArray::operator<<(uint64_t val) { return (*this << (int64_t)val); } ByteArray& ByteArray::operator>>(uint64_t& val) { return (*this >> (int64_t&)val); } ByteArray& ByteArray::operator<<(bool val) { if (val) { append(&trueConst, sizeof(unsigned char)); } else { append(&falseConst, sizeof(unsigned char)); } return *this; } ByteArray& ByteArray::operator>>(bool& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(unsigned char) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif unsigned char code; memcpy(&code, data_.get() + readPos_, sizeof(unsigned char)); #ifdef MOCCA_BYTEARRAY_CHECKS if (code != trueConst && code != falseConst) { throw Error("Package corrupted", __FILE__, __LINE__); } #endif val = (code & trueConst) != 0; readPos_ += sizeof(unsigned char); return *this; } ByteArray& ByteArray::operator<<(float val) { append(&val, sizeof(float)); return *this; } ByteArray& ByteArray::operator>>(float& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(float) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(float)); readPos_ += sizeof(float); return *this; } ByteArray& ByteArray::operator<<(double val) { append(&val, sizeof(double)); return *this; } ByteArray& ByteArray::operator>>(double& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(double) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(double)); readPos_ += sizeof(double); return *this; } ByteArray& ByteArray::operator<<(const std::string& val) { *this << (uint32_t)val.size(); append(val.c_str(), (uint32_t)val.size()); return *this; } ByteArray& ByteArray::operator>>(std::string& val) { uint32_t strSize; *this >> strSize; #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + strSize > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif val.reserve(strSize); val = std::string((char*)data_.get() + readPos_, strSize); readPos_ += strSize; return *this; } ByteArray& ByteArray::operator<<(const char* val) { return (*this << std::string(val)); } ByteArray& ByteArray::operator<<(const ByteArray& val) { *this << (int32_t)val.size(); append(val.data(), val.size()); return *this; } ByteArray& ByteArray::operator>>(ByteArray& val) { int32_t innerSize; *this >> innerSize; #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + innerSize > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif val.append(data_.get() + readPos_, innerSize); readPos_ += innerSize; return *this; } unsigned char& mocca::ByteArray::operator[](uint32_t index) { #ifdef MOCCA_BYTEARRAY_CHECKS if (index < 0 || index >= size_) { throw Error("Index out of bounds", __FILE__, __LINE__); } #endif return data_[index]; } const unsigned char& mocca::ByteArray::operator[](uint32_t index) const { #ifdef MOCCA_BYTEARRAY_CHECKS if (index < 0 || index >= size_) { throw Error("Index out of bounds", __FILE__, __LINE__); } #endif return data_[index]; } void ByteArray::resetReadPos() { readPos_ = 0; } }<commit_msg>fixed clang warning <commit_after>#include "mocca/base/ByteArray.h" #include <limits> #include <algorithm> static_assert(std::numeric_limits<float>::is_iec559 == true, "Unsupported floating point type"); static_assert(std::numeric_limits<double>::is_iec559 == true, "Unsupported floating point type"); namespace mocca { const unsigned char ByteArray::trueConst; const unsigned char ByteArray::falseConst; ByteArray::ByteArray(uint32_t capacity) : data_(new unsigned char[capacity]) , capacity_(capacity) , size_(0) , readPos_(0) {} ByteArray::ByteArray(const ByteArray& other) : data_(new unsigned char[other.capacity_]) , capacity_(other.capacity_) , size_(other.size_) , readPos_(other.readPos_) { memcpy(data_.get(), other.data_.get(), other.size_); } ByteArray::ByteArray(ByteArray&& other) : data_(std::move(other.data_)) , capacity_(other.capacity_) , size_(other.size_) , readPos_(other.readPos_) { other.capacity_ = 0; other.size_ = 0; other.readPos_ = 0; } ByteArray& ByteArray::operator=(ByteArray other) { swap(other, *this); return *this; } void swap(ByteArray& lhs, ByteArray& rhs) { using std::swap; swap(lhs.data_, rhs.data_); swap(lhs.capacity_, rhs.capacity_); swap(lhs.size_, rhs.size_); swap(lhs.readPos_, rhs.readPos_); } unsigned char* ByteArray::data() { return data_.get(); } const unsigned char* ByteArray::data() const { return data_.get(); } uint32_t ByteArray::size() const { return size_; } void ByteArray::setSize(uint32_t size) { if (size > capacity_) { throw Error("Size exceeds capacity of the byte array", __FILE__, __LINE__); } size_ = size; } bool ByteArray::isEmpty() const { return size_ == 0; } uint32_t ByteArray::capacity() const { return capacity_; } void ByteArray::resize(uint32_t newCapacity) { auto newData = std::unique_ptr<unsigned char[]>(new unsigned char[newCapacity]); memcpy(newData.get(), data_.get(), size_); data_ = std::move(newData); capacity_ = newCapacity; } void ByteArray::append(const void* data, uint32_t size) { if (capacity_ < size_ + size) { resize(size_ + std::max(2 * size, 256u)); } memcpy(data_.get() + size_, data, size); size_ += size; } void mocca::ByteArray::append(const ByteArray& byteArray) { append(byteArray.data(), byteArray.size()); } ByteArray ByteArray::createFromRaw(const void* raw, uint32_t size) { auto byteArray = ByteArray(size); memcpy(byteArray.data_.get(), raw, size); byteArray.size_ = size; return byteArray; } ByteArray& ByteArray::operator<<(int32_t val) { append(&val, sizeof(int32_t)); return *this; } ByteArray& ByteArray::operator>>(int32_t& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(int32_t) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(int32_t)); readPos_ += sizeof(int32_t); return *this; } ByteArray& ByteArray::operator<<(uint32_t val) { return (*this << (int32_t)val); } ByteArray& ByteArray::operator>>(uint32_t& val) { return (*this >> (int32_t&)val); } ByteArray& ByteArray::operator<<(int64_t val) { append(&val, sizeof(int64_t)); return *this; } ByteArray& ByteArray::operator>>(int64_t& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(int64_t) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(int64_t)); readPos_ += sizeof(int64_t); return *this; } ByteArray& ByteArray::operator<<(uint64_t val) { return (*this << (int64_t)val); } ByteArray& ByteArray::operator>>(uint64_t& val) { return (*this >> (int64_t&)val); } ByteArray& ByteArray::operator<<(bool val) { if (val) { append(&trueConst, sizeof(unsigned char)); } else { append(&falseConst, sizeof(unsigned char)); } return *this; } ByteArray& ByteArray::operator>>(bool& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(unsigned char) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif unsigned char code; memcpy(&code, data_.get() + readPos_, sizeof(unsigned char)); #ifdef MOCCA_BYTEARRAY_CHECKS if (code != trueConst && code != falseConst) { throw Error("Package corrupted", __FILE__, __LINE__); } #endif val = (code & trueConst) != 0; readPos_ += sizeof(unsigned char); return *this; } ByteArray& ByteArray::operator<<(float val) { append(&val, sizeof(float)); return *this; } ByteArray& ByteArray::operator>>(float& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(float) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(float)); readPos_ += sizeof(float); return *this; } ByteArray& ByteArray::operator<<(double val) { append(&val, sizeof(double)); return *this; } ByteArray& ByteArray::operator>>(double& val) { #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + sizeof(double) > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif memcpy(&val, data_.get() + readPos_, sizeof(double)); readPos_ += sizeof(double); return *this; } ByteArray& ByteArray::operator<<(const std::string& val) { *this << (uint32_t)val.size(); append(val.c_str(), (uint32_t)val.size()); return *this; } ByteArray& ByteArray::operator>>(std::string& val) { uint32_t strSize; *this >> strSize; #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + strSize > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif val.reserve(strSize); val = std::string((char*)data_.get() + readPos_, strSize); readPos_ += strSize; return *this; } ByteArray& ByteArray::operator<<(const char* val) { return (*this << std::string(val)); } ByteArray& ByteArray::operator<<(const ByteArray& val) { *this << (int32_t)val.size(); append(val.data(), val.size()); return *this; } ByteArray& ByteArray::operator>>(ByteArray& val) { int32_t innerSize; *this >> innerSize; #ifdef MOCCA_BYTEARRAY_CHECKS if (readPos_ + innerSize > size_) { throw Error("Reading beyond end of packet", __FILE__, __LINE__); } #endif val.append(data_.get() + readPos_, innerSize); readPos_ += innerSize; return *this; } unsigned char& mocca::ByteArray::operator[](uint32_t index) { #ifdef MOCCA_BYTEARRAY_CHECKS if (index >= size_) { throw Error("Index out of bounds", __FILE__, __LINE__); } #endif return data_[index]; } const unsigned char& mocca::ByteArray::operator[](uint32_t index) const { #ifdef MOCCA_BYTEARRAY_CHECKS if (index >= size_) { throw Error("Index out of bounds", __FILE__, __LINE__); } #endif return data_[index]; } void ByteArray::resetReadPos() { readPos_ = 0; } }<|endoftext|>
<commit_before>#include "stdafx.hpp" #include <functional> #include "CppUnitTest.h" #include "..\TestUtilities\TestUtilities.hpp" #include "..\TestUtilities\QuantityComparisons.hpp" #include "..\TestUtilities\GeometryComparisons.hpp" #include "..\TestUtilities\Algebra.hpp" #include "..\Quantities\Dimensionless.hpp" #include "..\Quantities\Quantities.hpp" #include "..\Quantities\SI.hpp" #include "..\Quantities\Constants.hpp" #include "..\Quantities\UK.hpp" #include "..\Quantities\BIPM.hpp" #include "..\Quantities\Astronomy.hpp" #include "..\Geometry\R3Element.hpp" #include "..\Geometry\Grassmann.hpp" #include "..\Quantities\ElementaryFunctions.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Principia { namespace GeometryTests { using namespace Geometry; using namespace Quantities; using namespace SI; using namespace UK; using namespace BIPM; using namespace Astronomy; using namespace Constants; using namespace TestUtilities; TEST_CLASS(GeometryTests) { public: struct World; TEST_METHOD(Dumb3Vector) { R3Element<Speed> nullVector(0 * Metre / Second, 0 * Metre / Second, 0 * Metre / Second); R3Element<Speed> u(1 * Metre / Second, 120 * Kilo(Metre) / Hour, -SpeedOfLight); R3Element<Speed> v(-20 * Knot, 2 * π * AstronomicalUnit / JulianYear, 1 * Admiralty::NauticalMile / Hour); R3Element<Speed> w(-1 * Mile / Hour, -2 * Foot / Second, -3 * Knot); R3Element<Speed> a(88 * Mile / Hour, 300 * Metre / Second, 46 * Knot); AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v)); TestVectorSpace<R3Element<Speed>, Dimensionless>(nullVector, u, v, w, Dimensionless(0), Dimensionless(1), e, Dimensionless(42)); TestAlternatingBilinearMap(Cross<Speed, Speed>, u, v, w, a, Dimensionless(42)); TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>, u, v, w, a, Dimensionless(42)); } TEST_METHOD(SpecialOrthogonalLieAlgebra) { R3Element<Dimensionless> u(3, -42, 0); R3Element<Dimensionless> v(-π, -e, -1); R3Element<Dimensionless> w(2, 2, 2); R3Element<Dimensionless> a(1.2, 2.3, 3.4); TestLieBracket(Commutator<Dimensionless, Dimensionless, World>, Bivector<Dimensionless, World>(u), Bivector<Dimensionless, World>(v), Bivector<Dimensionless, World>(w), Bivector<Dimensionless, World>(a), Dimensionless(0.42)); } TEST_METHOD(VectorSpaces) { R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre); R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre); R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre); R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre); R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom); { std::function<Area(Vector<Length, World>, Vector<Length, World>)> vectorInnerProduct = [](Vector<Length, World> a, Vector<Length, World> b) { return InnerProduct(a, b); }; std::function<Area(Bivector<Length, World>, Bivector<Length, World>)> bivectorInnerProduct = [](Bivector<Length, World> a, Bivector<Length, World> b) { return InnerProduct(a, b); }; std::function<Area(Trivector<Length, World>, Trivector<Length, World>)> trivectorInnerProduct = [](Trivector<Length, World> a, Trivector<Length, World> b) { return InnerProduct(a, b); }; TestInnerProductSpace(vectorInnerProduct, Vector<Length, World>(nullDisplacement), Vector<Length, World>(u), Vector<Length, World>(v), Vector<Length, World>(w), Vector<Length, World>(a), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(bivectorInnerProduct, Bivector<Length, World>(nullDisplacement), Bivector<Length, World>(u), Bivector<Length, World>(v), Bivector<Length, World>(w), Bivector<Length, World>(a), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(trivectorInnerProduct, Trivector<Length, World>(nullDisplacement.x), Trivector<Length, World>(u.y), Trivector<Length, World>(v.z), Trivector<Length, World>(w.x), Trivector<Length, World>(a.y), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); } { std::function<Dimensionless(Vector<Dimensionless, World>, Vector<Dimensionless, World>)> vectorInnerProduct = [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) { return InnerProduct(a, b); }; std::function<Dimensionless(Bivector<Dimensionless, World>, Bivector<Dimensionless, World>)> bivectorInnerProduct = [](Bivector<Dimensionless, World> a, Bivector<Dimensionless, World> b) { return InnerProduct(a, b); }; std::function<Dimensionless(Trivector<Dimensionless, World>, Trivector<Dimensionless, World>)> trivectorInnerProduct = [](Trivector<Dimensionless, World> a, Trivector<Dimensionless, World> b) { return InnerProduct(a, b); }; TestInnerProductSpace(vectorInnerProduct, Vector<Dimensionless, World>(nullDisplacement / Metre), Vector<Dimensionless, World>(u / Metre), Vector<Dimensionless, World>(v / Metre), Vector<Dimensionless, World>(w / Metre), Vector<Dimensionless, World>(a / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(bivectorInnerProduct, Bivector<Dimensionless, World>(nullDisplacement / Metre), Bivector<Dimensionless, World>(u / Metre), Bivector<Dimensionless, World>(v / Metre), Bivector<Dimensionless, World>(w / Metre), Bivector<Dimensionless, World>(a / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(trivectorInnerProduct, Trivector<Dimensionless, World>(nullDisplacement.x / Metre), Trivector<Dimensionless, World>(u.y / Metre), Trivector<Dimensionless, World>(v.z / Metre), Trivector<Dimensionless, World>(w.x / Metre), Trivector<Dimensionless, World>(a.y / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); } } TEST_METHOD(GrassmannAlgebra) { R3Element<Dimensionless> u(3, -42, 0); R3Element<Dimensionless> v(-π, -e, -1); R3Element<Dimensionless> w(2, 2, 2); R3Element<Dimensionless> a(1.2, 2.3, 3.4); std::function<Bivector<Dimensionless, World>(Vector<Dimensionless, World>, Vector<Dimensionless, World>)> vectorWedge = [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) { return Wedge(a, b); }; TestAlternatingBilinearMap(vectorWedge, Vector<Dimensionless, World>(u), Vector<Dimensionless, World>(u), Vector<Dimensionless, World>(u), Vector<Dimensionless, World>(u), Dimensionless(6 * 9)); } }; } // namespace GeometryTests } // namespace Principia <commit_msg>Not sure that's a good idea, but then it's easy to get confused between all these '}'s.<commit_after>#include "stdafx.hpp" #include <functional> #include "CppUnitTest.h" #include "..\TestUtilities\TestUtilities.hpp" #include "..\TestUtilities\QuantityComparisons.hpp" #include "..\TestUtilities\GeometryComparisons.hpp" #include "..\TestUtilities\Algebra.hpp" #include "..\Quantities\Dimensionless.hpp" #include "..\Quantities\Quantities.hpp" #include "..\Quantities\SI.hpp" #include "..\Quantities\Constants.hpp" #include "..\Quantities\UK.hpp" #include "..\Quantities\BIPM.hpp" #include "..\Quantities\Astronomy.hpp" #include "..\Geometry\R3Element.hpp" #include "..\Geometry\Grassmann.hpp" #include "..\Quantities\ElementaryFunctions.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Principia { namespace GeometryTests { using namespace Geometry; using namespace Quantities; using namespace SI; using namespace UK; using namespace BIPM; using namespace Astronomy; using namespace Constants; using namespace TestUtilities; TEST_CLASS(GeometryTests) { public: struct World; TEST_METHOD(Dumb3Vector) { R3Element<Speed> nullVector(0 * Metre / Second, 0 * Metre / Second, 0 * Metre / Second); R3Element<Speed> u(1 * Metre / Second, 120 * Kilo(Metre) / Hour, -SpeedOfLight); R3Element<Speed> v(-20 * Knot, 2 * π * AstronomicalUnit / JulianYear, 1 * Admiralty::NauticalMile / Hour); R3Element<Speed> w(-1 * Mile / Hour, -2 * Foot / Second, -3 * Knot); R3Element<Speed> a(88 * Mile / Hour, 300 * Metre / Second, 46 * Knot); AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v)); TestVectorSpace<R3Element<Speed>, Dimensionless>(nullVector, u, v, w, Dimensionless(0), Dimensionless(1), e, Dimensionless(42)); TestAlternatingBilinearMap(Cross<Speed, Speed>, u, v, w, a, Dimensionless(42)); TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>, u, v, w, a, Dimensionless(42)); } // TEST_METHOD Dumb3Vector TEST_METHOD(SpecialOrthogonalLieAlgebra) { R3Element<Dimensionless> u(3, -42, 0); R3Element<Dimensionless> v(-π, -e, -1); R3Element<Dimensionless> w(2, 2, 2); R3Element<Dimensionless> a(1.2, 2.3, 3.4); TestLieBracket(Commutator<Dimensionless, Dimensionless, World>, Bivector<Dimensionless, World>(u), Bivector<Dimensionless, World>(v), Bivector<Dimensionless, World>(w), Bivector<Dimensionless, World>(a), Dimensionless(0.42)); } // TEST_METHOD SpecialOrthogonalLieAlgebra TEST_METHOD(VectorSpaces) { R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre); R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre); R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre); R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre); R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom); { std::function<Area(Vector<Length, World>, Vector<Length, World>)> vectorInnerProduct = [](Vector<Length, World> a, Vector<Length, World> b) { return InnerProduct(a, b); }; std::function<Area(Bivector<Length, World>, Bivector<Length, World>)> bivectorInnerProduct = [](Bivector<Length, World> a, Bivector<Length, World> b) { return InnerProduct(a, b); }; std::function<Area(Trivector<Length, World>, Trivector<Length, World>)> trivectorInnerProduct = [](Trivector<Length, World> a, Trivector<Length, World> b) { return InnerProduct(a, b); }; TestInnerProductSpace(vectorInnerProduct, Vector<Length, World>(nullDisplacement), Vector<Length, World>(u), Vector<Length, World>(v), Vector<Length, World>(w), Vector<Length, World>(a), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(bivectorInnerProduct, Bivector<Length, World>(nullDisplacement), Bivector<Length, World>(u), Bivector<Length, World>(v), Bivector<Length, World>(w), Bivector<Length, World>(a), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(trivectorInnerProduct, Trivector<Length, World>(nullDisplacement.x), Trivector<Length, World>(u.y), Trivector<Length, World>(v.z), Trivector<Length, World>(w.x), Trivector<Length, World>(a.y), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); } { std::function<Dimensionless(Vector<Dimensionless, World>, Vector<Dimensionless, World>)> vectorInnerProduct = [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) { return InnerProduct(a, b); }; std::function<Dimensionless(Bivector<Dimensionless, World>, Bivector<Dimensionless, World>)> bivectorInnerProduct = [](Bivector<Dimensionless, World> a, Bivector<Dimensionless, World> b) { return InnerProduct(a, b); }; std::function<Dimensionless(Trivector<Dimensionless, World>, Trivector<Dimensionless, World>)> trivectorInnerProduct = [](Trivector<Dimensionless, World> a, Trivector<Dimensionless, World> b) { return InnerProduct(a, b); }; TestInnerProductSpace(vectorInnerProduct, Vector<Dimensionless, World>(nullDisplacement / Metre), Vector<Dimensionless, World>(u / Metre), Vector<Dimensionless, World>(v / Metre), Vector<Dimensionless, World>(w / Metre), Vector<Dimensionless, World>(a / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(bivectorInnerProduct, Bivector<Dimensionless, World>(nullDisplacement / Metre), Bivector<Dimensionless, World>(u / Metre), Bivector<Dimensionless, World>(v / Metre), Bivector<Dimensionless, World>(w / Metre), Bivector<Dimensionless, World>(a / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(trivectorInnerProduct, Trivector<Dimensionless, World>(nullDisplacement.x / Metre), Trivector<Dimensionless, World>(u.y / Metre), Trivector<Dimensionless, World>(v.z / Metre), Trivector<Dimensionless, World>(w.x / Metre), Trivector<Dimensionless, World>(a.y / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); } } // TEST_METHOD VectorSpaces TEST_METHOD(GrassmannAlgebra) { R3Element<Dimensionless> u(3, -42, 0); R3Element<Dimensionless> v(-π, -e, -1); R3Element<Dimensionless> w(2, 2, 2); R3Element<Dimensionless> a(1.2, 2.3, 3.4); std::function<Bivector<Dimensionless, World>(Vector<Dimensionless, World>, Vector<Dimensionless, World>)> vectorWedge = [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) { return Wedge(a, b); }; TestAlternatingBilinearMap(vectorWedge, Vector<Dimensionless, World>(u), Vector<Dimensionless, World>(u), Vector<Dimensionless, World>(u), Vector<Dimensionless, World>(u), Dimensionless(6 * 9)); } // TEST_METHOD GrassmannAlgebra }; // TEST_CLASS GeometryTests } // namespace GeometryTests } // namespace Principia <|endoftext|>
<commit_before>/** * \file dcs/testbed/application.hpp * * \brief Generic application. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DCS_TESTBED_APPLICATION_HPP #define DCS_TESTBED_APPLICATION_HPP #include <cstddef> #include <dcs/assert.hpp> #include <dcs/exception.hpp> #include <dcs/testbed/application_performance_category.hpp> #include <dcs/testbed/base_application.hpp> #include <dcs/testbed/base_virtual_machine.hpp> #include <map> #include <stdexcept> #include <vector> namespace dcs { namespace testbed { template <typename TraitsT> class application: public base_application<TraitsT> { private: typedef base_application<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::vm_pointer vm_pointer; public: typedef typename base_type::sensor_pointer sensor_pointer; public: typedef typename base_type::slo_checker_type slo_checker_type; public: typedef typename base_type::real_type real_type; // private: typedef typename base_type::vm_type::identifier_type vm _identifier_type; // private: typedef ::std::map<vm_identifier_type,vm_pointer> vm_container; private: typedef ::std::vector<vm_pointer> vm_container; private: typedef ::std::map<application_performance_category,sensor_pointer> sensor_map; private: typedef ::std::map<application_performance_category,slo_checker_type> slo_checker_map; public: application() { } public: template <typename IterT> application(IterT vm_first, IterT vm_last) : vms_(vm_first,vm_last) { // while (vm_first != vm_last) // { // vms_[*(vm_first)->id()] = *vm_first; // ++vm_first; // } } private: ::std::size_t do_num_vms() const { return vms_.size(); } private: ::std::vector<vm_pointer> do_vms() const { // ::std::vector<vm_pointer> vms(vms_.size()); // // ::std::size_t i(0); // typename vm_container::const_iterator end_it(vms_.end()); // for (typename vm_container::const_iterator it = vms_.begin(); // it != end_it; // ++it) // { // vms[i] = *it; // ++i; // } // // return vms; return vms_; } // private: vm_pointer do_vm(vm_identifier_type id) const // { // DCS_ASSERT(vms_.count(id) > 0, // DCS_EXCEPTION_THROW(::std::invalid_argument, // "Invalid VM identifier")); // // return vms_.at(id); // } private: void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens) { DCS_ASSERT(p_sens, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid sensor")); sensors_[cat] = p_sens; } private: void do_deregister_sensor(application_performance_category cat) { DCS_ASSERT(sensors_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: sensor not found")); sensors_.erase(cat); } private: sensor_pointer do_sensor(application_performance_category cat) { DCS_ASSERT(sensors_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: sensor not found")); return sensors_.at(cat); } private: sensor_pointer do_sensor(application_performance_category cat) const { DCS_ASSERT(sensors_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: sensor not found")); return sensors_.at(cat); } private: void do_slo(application_performance_category cat, slo_checker_type const& checker) { slo_map_[cat] = checker; } private: bool do_slo(application_performance_category cat, real_type val) const { DCS_ASSERT(slo_map_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: SLO checker not found")); return slo_map_.at(cat)(val); } private: vm_container vms_; private: sensor_map sensors_; private: slo_checker_map slo_map_; }; // application }} // Namespace dcs::testbed #endif // DCS_TESTBED_APPLICATION_HPP <commit_msg>Improved inline doc<commit_after>/** * \file dcs/testbed/application.hpp * * \brief Generic application. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DCS_TESTBED_APPLICATION_HPP #define DCS_TESTBED_APPLICATION_HPP #include <cstddef> #include <dcs/assert.hpp> #include <dcs/exception.hpp> #include <dcs/testbed/application_performance_category.hpp> #include <dcs/testbed/base_application.hpp> #include <dcs/testbed/base_virtual_machine.hpp> #include <map> #include <stdexcept> #include <vector> namespace dcs { namespace testbed { /** * \brief Generic application. * * \tparam TraitsT Traits type. * * \author Marco Guazzone (marco.guazzone@gmail.com) */ template <typename TraitsT> class application: public base_application<TraitsT> { private: typedef base_application<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::vm_pointer vm_pointer; public: typedef typename base_type::sensor_pointer sensor_pointer; public: typedef typename base_type::slo_checker_type slo_checker_type; public: typedef typename base_type::real_type real_type; // private: typedef typename base_type::vm_type::identifier_type vm _identifier_type; // private: typedef ::std::map<vm_identifier_type,vm_pointer> vm_container; private: typedef ::std::vector<vm_pointer> vm_container; private: typedef ::std::map<application_performance_category,sensor_pointer> sensor_map; private: typedef ::std::map<application_performance_category,slo_checker_type> slo_checker_map; public: application() { // Empty } public: template <typename IterT> application(IterT vm_first, IterT vm_last) : vms_(vm_first,vm_last) { // while (vm_first != vm_last) // { // vms_[*(vm_first)->id()] = *vm_first; // ++vm_first; // } } private: ::std::size_t do_num_vms() const { return vms_.size(); } private: ::std::vector<vm_pointer> do_vms() const { // ::std::vector<vm_pointer> vms(vms_.size()); // // ::std::size_t i(0); // typename vm_container::const_iterator end_it(vms_.end()); // for (typename vm_container::const_iterator it = vms_.begin(); // it != end_it; // ++it) // { // vms[i] = *it; // ++i; // } // // return vms; return vms_; } // private: vm_pointer do_vm(vm_identifier_type id) const // { // DCS_ASSERT(vms_.count(id) > 0, // DCS_EXCEPTION_THROW(::std::invalid_argument, // "Invalid VM identifier")); // // return vms_.at(id); // } private: void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens) { DCS_ASSERT(p_sens, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid sensor")); sensors_[cat] = p_sens; } private: void do_deregister_sensor(application_performance_category cat) { DCS_ASSERT(sensors_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: sensor not found")); sensors_.erase(cat); } private: sensor_pointer do_sensor(application_performance_category cat) { DCS_ASSERT(sensors_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: sensor not found")); return sensors_.at(cat); } private: sensor_pointer do_sensor(application_performance_category cat) const { DCS_ASSERT(sensors_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: sensor not found")); return sensors_.at(cat); } private: void do_slo(application_performance_category cat, slo_checker_type const& checker) { slo_map_[cat] = checker; } private: bool do_slo(application_performance_category cat, real_type val) const { DCS_ASSERT(slo_map_.count(cat) > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid category: SLO checker not found")); return slo_map_.at(cat)(val); } private: vm_container vms_; private: sensor_map sensors_; private: slo_checker_map slo_map_; }; // application }} // Namespace dcs::testbed #endif // DCS_TESTBED_APPLICATION_HPP <|endoftext|>
<commit_before>#include "stdafx.h" #include <windows.h> typedef LONG KPRIORITY; typedef struct _CLIENT_ID { DWORD UniqueProcess; DWORD UniqueThread; } CLIENT_ID; typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; //from http://boinc.berkeley.edu/android-boinc/boinc/lib/diagnostics_win.h typedef struct _VM_COUNTERS { #ifdef _WIN64 // the following was inferred by painful reverse engineering SIZE_T PeakVirtualSize; // not actually SIZE_T PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; SIZE_T VirtualSize; // not actually #else SIZE_T PeakVirtualSize; SIZE_T VirtualSize; ULONG PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; #endif } VM_COUNTERS; typedef enum _KWAIT_REASON { Executive = 0, FreePage = 1, PageIn = 2, PoolAllocation = 3, DelayExecution = 4, Suspended = 5, UserRequest = 6, WrExecutive = 7, WrFreePage = 8, WrPageIn = 9, WrPoolAllocation = 10, WrDelayExecution = 11, WrSuspended = 12, WrUserRequest = 13, WrEventPair = 14, WrQueue = 15, WrLpcReceive = 16, WrLpcReply = 17, WrVirtualMemory = 18, WrPageOut = 19, WrRendezvous = 20, Spare2 = 21, Spare3 = 22, Spare4 = 23, Spare5 = 24, WrCalloutStack = 25, WrKernel = 26, WrResource = 27, WrPushLock = 28, WrMutex = 29, WrQuantumEnd = 30, WrDispatchInt = 31, WrPreempted = 32, WrYieldExecution = 33, WrFastMutex = 34, WrGuardedMutex = 35, WrRundown = 36, MaximumWaitReason = 37 } KWAIT_REASON; typedef struct _SYSTEM_THREAD_INFORMATION { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; KPRIORITY Priority; LONG BasePriority; ULONG ContextSwitchCount; ULONG ThreadState; KWAIT_REASON WaitReason; #ifdef _WIN64 ULONG Reserved[4]; #endif }SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION { SYSTEM_THREAD_INFORMATION ThreadInfo; PVOID StackBase; PVOID StackLimit; PVOID Win32StartAddress; PVOID TebAddress; /* This is only filled in on Vista and above */ ULONG Reserved1; ULONG Reserved2; ULONG Reserved3; } SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION; typedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION { ULONG NextEntryOffset; ULONG NumberOfThreads; LARGE_INTEGER SpareLi1; LARGE_INTEGER SpareLi2; LARGE_INTEGER SpareLi3; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ImageName; KPRIORITY BasePriority; ULONG ProcessId; ULONG InheritedFromUniqueProcessId; ULONG HandleCount; ULONG SessionId; PVOID PageDirectoryBase; VM_COUNTERS VirtualMemoryCounters; SIZE_T PrivatePageCount; IO_COUNTERS IoCounters; SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1]; } SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION; typedef enum _SYSTEM_INFORMATION_CLASS { SystemExtendedProcessInformation = 57 } SYSTEM_INFORMATION_CLASS; typedef NTSTATUS(WINAPI *PNtQuerySystemInformation)( __in SYSTEM_INFORMATION_CLASS SystemInformationClass, __inout PVOID SystemInformation, __in ULONG SystemInformationLength, __out_opt PULONG ReturnLength ); int main() { HMODULE ntdll = GetModuleHandle(TEXT("ntdll")); PNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, "NtQuerySystemInformation"); if (query == NULL) { printf("GetProcAddress() failed.\n"); return 1; } ULONG len = 2000; NTSTATUS status = NULL; PSYSTEM_EXTENDED_PROCESS_INFORMATION pProcessInfo = NULL; do { len *= 2; pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len); status = query(SystemExtendedProcessInformation, pProcessInfo, len, &len); } while (status == (NTSTATUS)0xc0000004); if (status != (NTSTATUS)0x0) { printf("NtQuerySystemInformation failed with error code 0x%X\n", status); return 1; } while (pProcessInfo->NextEntryOffset != NULL) { for (unsigned int i = 0; i < pProcessInfo->NumberOfThreads; i++) { PVOID stackBase = pProcessInfo->Threads[i].StackBase; PVOID stackLimit = pProcessInfo->Threads[i].StackLimit; #ifdef _WIN64 printf("Stack base 0x%llx\t", stackBase); printf("Stack limit 0x%llx\r\n", stackLimit); #else printf("Stack base 0x%X\t", stackBase); printf("Stack limit 0x%X\r\n", stackLimit); #endif } pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)((ULONG_PTR)pProcessInfo + pProcessInfo->NextEntryOffset); } return 0; } <commit_msg>remove unneeded ifdef struct change<commit_after>#include "stdafx.h" #include <windows.h> typedef LONG KPRIORITY; typedef struct _CLIENT_ID { DWORD UniqueProcess; DWORD UniqueThread; } CLIENT_ID; typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; //from http://boinc.berkeley.edu/android-boinc/boinc/lib/diagnostics_win.h typedef struct _VM_COUNTERS { // the following was inferred by painful reverse engineering SIZE_T PeakVirtualSize; // not actually SIZE_T PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; SIZE_T VirtualSize; // not actually } VM_COUNTERS; typedef enum _KWAIT_REASON { Executive = 0, FreePage = 1, PageIn = 2, PoolAllocation = 3, DelayExecution = 4, Suspended = 5, UserRequest = 6, WrExecutive = 7, WrFreePage = 8, WrPageIn = 9, WrPoolAllocation = 10, WrDelayExecution = 11, WrSuspended = 12, WrUserRequest = 13, WrEventPair = 14, WrQueue = 15, WrLpcReceive = 16, WrLpcReply = 17, WrVirtualMemory = 18, WrPageOut = 19, WrRendezvous = 20, Spare2 = 21, Spare3 = 22, Spare4 = 23, Spare5 = 24, WrCalloutStack = 25, WrKernel = 26, WrResource = 27, WrPushLock = 28, WrMutex = 29, WrQuantumEnd = 30, WrDispatchInt = 31, WrPreempted = 32, WrYieldExecution = 33, WrFastMutex = 34, WrGuardedMutex = 35, WrRundown = 36, MaximumWaitReason = 37 } KWAIT_REASON; typedef struct _SYSTEM_THREAD_INFORMATION { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; KPRIORITY Priority; LONG BasePriority; ULONG ContextSwitchCount; ULONG ThreadState; KWAIT_REASON WaitReason; #ifdef _WIN64 ULONG Reserved[4]; #endif }SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION { SYSTEM_THREAD_INFORMATION ThreadInfo; PVOID StackBase; PVOID StackLimit; PVOID Win32StartAddress; PVOID TebAddress; /* This is only filled in on Vista and above */ ULONG Reserved1; ULONG Reserved2; ULONG Reserved3; } SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION; typedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION { ULONG NextEntryOffset; ULONG NumberOfThreads; LARGE_INTEGER SpareLi1; LARGE_INTEGER SpareLi2; LARGE_INTEGER SpareLi3; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ImageName; KPRIORITY BasePriority; ULONG ProcessId; ULONG InheritedFromUniqueProcessId; ULONG HandleCount; ULONG SessionId; PVOID PageDirectoryBase; VM_COUNTERS VirtualMemoryCounters; SIZE_T PrivatePageCount; IO_COUNTERS IoCounters; SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1]; } SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION; typedef enum _SYSTEM_INFORMATION_CLASS { SystemExtendedProcessInformation = 57 } SYSTEM_INFORMATION_CLASS; typedef NTSTATUS(WINAPI *PNtQuerySystemInformation)( __in SYSTEM_INFORMATION_CLASS SystemInformationClass, __inout PVOID SystemInformation, __in ULONG SystemInformationLength, __out_opt PULONG ReturnLength ); int main() { HMODULE ntdll = GetModuleHandle(TEXT("ntdll")); PNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, "NtQuerySystemInformation"); if (query == NULL) { printf("GetProcAddress() failed.\n"); return 1; } ULONG len = 2000; NTSTATUS status = NULL; PSYSTEM_EXTENDED_PROCESS_INFORMATION pProcessInfo = NULL; do { len *= 2; pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len); status = query(SystemExtendedProcessInformation, pProcessInfo, len, &len); } while (status == (NTSTATUS)0xc0000004); if (status != (NTSTATUS)0x0) { printf("NtQuerySystemInformation failed with error code 0x%X\n", status); return 1; } while (pProcessInfo->NextEntryOffset != NULL) { for (unsigned int i = 0; i < pProcessInfo->NumberOfThreads; i++) { PVOID stackBase = pProcessInfo->Threads[i].StackBase; PVOID stackLimit = pProcessInfo->Threads[i].StackLimit; #ifdef _WIN64 printf("Stack base 0x%llx\t", stackBase); printf("Stack limit 0x%llx\r\n", stackLimit); #else printf("Stack base 0x%X\t", stackBase); printf("Stack limit 0x%X\r\n", stackLimit); #endif } pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)((ULONG_PTR)pProcessInfo + pProcessInfo->NextEntryOffset); } return 0; } <|endoftext|>
<commit_before>/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE Team. All rights reserved. ** ** 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. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goremovetagsdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "goremovetagsdialog.h" #include "ui_goremovetagsdialog.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::GoRemoveTagsDialog) { ui->setupUi(this); connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); } GoRemoveTagsDialog::~GoRemoveTagsDialog() { delete ui; } void GoRemoveTagsDialog::setInfo(const QString &info) { ui->infoLabel->setText(info); } QString GoRemoveTagsDialog::arguments() const { return ui->argumentsEdit->toPlainText().trimmed(); } static QString removeHead(const QString &text, const QString &head) { if (text.startsWith(head)) { return text.mid(head.length()); } return text; } void GoRemoveTagsDialog::updateArguments() { QString args; if (ui->clearAllTagsRadioButton->isChecked()) { args = "-clear-tags"; } else if (ui->clearAllOptionsRadioButton->isChecked()) { args = "-clear-options"; } else if (ui->removeJsonTagRadioButton->isChecked()) { args = "-remove-tags json"; } else if (ui->removeXmlTagRadioButton->isChecked()) { args = "-remove-tags xml"; } else if (ui->removeCustomTagRadioButton->isChecked()) { QString tag = ui->customTaglineEdit->text().trimmed(); if (!tag.isEmpty()) { args = "-remove-tags "+tag; } } else if (ui->removeJsonOptionRadioButton->isChecked()) { QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts); QStringList options; foreach (QString opt, optList) { options << "json="+opt; } if (!options.isEmpty()) { args = "-remove-options "+options.join(","); } } else if (ui->removeXmlOptionRadioButton->isChecked()) { QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts); QStringList options; foreach (QString opt, optList) { options << "json="+opt; } if (!options.isEmpty()) { args = "-remove-options "+options.join(","); } } else if(ui->removeCustomOptionRadioButton->isChecked()) { QString opt = ui->customOptionLineEdit->text().trimmed(); if (opt == ui->customOptionLineEdit->placeholderText()) { if (ui->customOptionLineEdit->cursorPosition() == 0) { opt.clear(); } } if (opt.contains("=")) { args = "-remove-options "+opt; } } ui->argumentsEdit->setPlainText(args); } <commit_msg>golangedit: fix removetags xml option<commit_after>/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE Team. All rights reserved. ** ** 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. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goremovetagsdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "goremovetagsdialog.h" #include "ui_goremovetagsdialog.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::GoRemoveTagsDialog) { ui->setupUi(this); connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); } GoRemoveTagsDialog::~GoRemoveTagsDialog() { delete ui; } void GoRemoveTagsDialog::setInfo(const QString &info) { ui->infoLabel->setText(info); } QString GoRemoveTagsDialog::arguments() const { return ui->argumentsEdit->toPlainText().trimmed(); } static QString removeHead(const QString &text, const QString &head) { if (text.startsWith(head)) { return text.mid(head.length()); } return text; } void GoRemoveTagsDialog::updateArguments() { QString args; if (ui->clearAllTagsRadioButton->isChecked()) { args = "-clear-tags"; } else if (ui->clearAllOptionsRadioButton->isChecked()) { args = "-clear-options"; } else if (ui->removeJsonTagRadioButton->isChecked()) { args = "-remove-tags json"; } else if (ui->removeXmlTagRadioButton->isChecked()) { args = "-remove-tags xml"; } else if (ui->removeCustomTagRadioButton->isChecked()) { QString tag = ui->customTaglineEdit->text().trimmed(); if (!tag.isEmpty()) { args = "-remove-tags "+tag; } } else if (ui->removeJsonOptionRadioButton->isChecked()) { QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts); QStringList options; foreach (QString opt, optList) { options << "json="+opt; } if (!options.isEmpty()) { args = "-remove-options "+options.join(","); } } else if (ui->removeXmlOptionRadioButton->isChecked()) { QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts); QStringList options; foreach (QString opt, optList) { options << "xml="+opt; } if (!options.isEmpty()) { args = "-remove-options "+options.join(","); } } else if(ui->removeCustomOptionRadioButton->isChecked()) { QString opt = ui->customOptionLineEdit->text().trimmed(); if (opt == ui->customOptionLineEdit->placeholderText()) { if (ui->customOptionLineEdit->cursorPosition() == 0) { opt.clear(); } } if (opt.contains("=")) { args = "-remove-options "+opt; } } ui->argumentsEdit->setPlainText(args); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <gsl/gsl_multiroots.h> #ifndef ATOM_PRINT_FUNCTIONS_HPP #define ATOM_PRINT_FUNCTIONS_HPP namespace atom { //! Print Cartesian-state-to-TLE converter solver summary table header. /*! * Prints header to string for table containing summary of status of non-linear solver used to * convert a Cartesian state to a TLE. * * @sa convertCartesianStateToTwoLineElements * @return String containing table header for non-linear solver status. */ inline std::string printCartesianToTleSolverStateTableHeader( ); //! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter. /*! * Prints current state of non-linear solver used to convert a Cartesian state to a TLE, as row * for a summary table. * * @sa convertCartesianStateToTwoLineElements * @param iteration Current iteration of solver * @param solver Pointer to GSL solver * @return String containing row-data for non-linear solver status summary table */ inline std::string printCartesianToTleSolverState( const int iteration, gsl_multiroot_fsolver* solver ); //! Print Atom solver summary table header. /*! * Prints header to string for table containing summary of status of non-linear solver used to * execute Atom solver. * * @sa executeAtomSolver * @return String containing table header for non-linear solver status. */ inline std::string printAtomSolverStateTableHeader( ); //! Print summary of current state of non-linear solver for Atom solver. /*! * Prints current state of non-linear solver used to execute Atom solver, as row for a summary * table. * * @sa executeAtomSolver * @param iteration Current iteration of solver * @param solver Pointer to GSL solver * @return String containing row-data for non-linear solver status summary table */ inline std::string printAtomSolverState( const int iteration, gsl_multiroot_fsolver* solver ); //! Print data element to console. /*! * Prints a specified data element to string, given a specified width and a filler character. * This function is auxilliary to the print-functions used to the print the state of the non-linear * solver. * * @sa printSolverStateTableHeader, printSolverState * @tparam DataType Type for specified data element * @param datum Specified data element to print * @param width Width of datum printed to console, in terms of number of characters * @param filler Character used to fill fixed-width, [default: ' '] * @return String containing printed data element */ template< typename DataType > inline std::string printElement( const DataType datum, const int width, const char filler = ' ' ); //! Print Cartesian-state-to-TLE converter solver summary table header. inline std::string printCartesianToTleSolverStateTableHeader( ) { std::ostringstream headerBuffer; headerBuffer << printElement( "#", 3, ' ' ) << printElement( "a", 15, ' ' ) << printElement( "e", 15, ' ' ) << printElement( "i", 15, ' ' ) << printElement( "AoP", 15, ' ' ) << printElement( "RAAN", 15, ' ' ) << printElement( "TA", 15, ' ' ) << printElement( "f1", 15, ' ' ) << printElement( "f2", 15, ' ' ) << printElement( "f3", 15, ' ' ) << printElement( "f4", 15, ' ' ) << printElement( "f5", 15, ' ' ) << printElement( "f6", 15, ' ' ) << std::endl; return headerBuffer.str( ); } //! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter. inline std::string printCartesianToTleSolverState( const int iteration, gsl_multiroot_fsolver* solver ) { std::ostringstream buffer; buffer << printElement( iteration, 3, ' ' ) << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 3 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 4 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 5 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 3 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 4 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 5 ), 15, ' ' ) << std::endl; return buffer.str( ); } //! Print Atom solver summary table header. inline std::string printAtomSolverStateTableHeader( ) { std::ostringstream headerBuffer; headerBuffer << printElement( "#", 3, ' ' ) << printElement( "v1_x", 15, ' ' ) << printElement( "v1_y", 15, ' ' ) << printElement( "v1_z", 15, ' ' ) << printElement( "f1", 15, ' ' ) << printElement( "f2", 15, ' ' ) << printElement( "f3", 15, ' ' ) << std::endl; return headerBuffer.str( ); } //! Print summary of current state of non-linear solver for Atom solver. inline std::string printAtomSolverState( const int iteration, gsl_multiroot_fsolver* solver ) { std::ostringstream buffer; buffer << printElement( iteration, 3, ' ' ) << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' ) << std::endl; return buffer.str( ); } //! Print data element to console. template< typename DataType > inline std::string printElement( const DataType datum, const int width, const char filler ) { std::ostringstream buffer; buffer << std::left << std::setw( width ) << std::setfill( filler ) << datum; return buffer.str( ); } } // namespace atom #endif // ATOM_PRINT_FUNCTIONS_HPP <commit_msg>Move header include guard above include statements in print functions header.<commit_after>/* * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #ifndef ATOM_PRINT_FUNCTIONS_HPP #define ATOM_PRINT_FUNCTIONS_HPP #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <gsl/gsl_multiroots.h> namespace atom { //! Print Cartesian-state-to-TLE converter solver summary table header. /*! * Prints header to string for table containing summary of status of non-linear solver used to * convert a Cartesian state to a TLE. * * @sa convertCartesianStateToTwoLineElements * @return String containing table header for non-linear solver status. */ inline std::string printCartesianToTleSolverStateTableHeader( ); //! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter. /*! * Prints current state of non-linear solver used to convert a Cartesian state to a TLE, as row * for a summary table. * * @sa convertCartesianStateToTwoLineElements * @param iteration Current iteration of solver * @param solver Pointer to GSL solver * @return String containing row-data for non-linear solver status summary table */ inline std::string printCartesianToTleSolverState( const int iteration, gsl_multiroot_fsolver* solver ); //! Print Atom solver summary table header. /*! * Prints header to string for table containing summary of status of non-linear solver used to * execute Atom solver. * * @sa executeAtomSolver * @return String containing table header for non-linear solver status. */ inline std::string printAtomSolverStateTableHeader( ); //! Print summary of current state of non-linear solver for Atom solver. /*! * Prints current state of non-linear solver used to execute Atom solver, as row for a summary * table. * * @sa executeAtomSolver * @param iteration Current iteration of solver * @param solver Pointer to GSL solver * @return String containing row-data for non-linear solver status summary table */ inline std::string printAtomSolverState( const int iteration, gsl_multiroot_fsolver* solver ); //! Print data element to console. /*! * Prints a specified data element to string, given a specified width and a filler character. * This function is auxilliary to the print-functions used to the print the state of the non-linear * solver. * * @sa printSolverStateTableHeader, printSolverState * @tparam DataType Type for specified data element * @param datum Specified data element to print * @param width Width of datum printed to console, in terms of number of characters * @param filler Character used to fill fixed-width, [default: ' '] * @return String containing printed data element */ template< typename DataType > inline std::string printElement( const DataType datum, const int width, const char filler = ' ' ); //! Print Cartesian-state-to-TLE converter solver summary table header. inline std::string printCartesianToTleSolverStateTableHeader( ) { std::ostringstream headerBuffer; headerBuffer << printElement( "#", 3, ' ' ) << printElement( "a", 15, ' ' ) << printElement( "e", 15, ' ' ) << printElement( "i", 15, ' ' ) << printElement( "AoP", 15, ' ' ) << printElement( "RAAN", 15, ' ' ) << printElement( "TA", 15, ' ' ) << printElement( "f1", 15, ' ' ) << printElement( "f2", 15, ' ' ) << printElement( "f3", 15, ' ' ) << printElement( "f4", 15, ' ' ) << printElement( "f5", 15, ' ' ) << printElement( "f6", 15, ' ' ) << std::endl; return headerBuffer.str( ); } //! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter. inline std::string printCartesianToTleSolverState( const int iteration, gsl_multiroot_fsolver* solver ) { std::ostringstream buffer; buffer << printElement( iteration, 3, ' ' ) << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 3 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 4 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 5 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 3 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 4 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 5 ), 15, ' ' ) << std::endl; return buffer.str( ); } //! Print Atom solver summary table header. inline std::string printAtomSolverStateTableHeader( ) { std::ostringstream headerBuffer; headerBuffer << printElement( "#", 3, ' ' ) << printElement( "v1_x", 15, ' ' ) << printElement( "v1_y", 15, ' ' ) << printElement( "v1_z", 15, ' ' ) << printElement( "f1", 15, ' ' ) << printElement( "f2", 15, ' ' ) << printElement( "f3", 15, ' ' ) << std::endl; return headerBuffer.str( ); } //! Print summary of current state of non-linear solver for Atom solver. inline std::string printAtomSolverState( const int iteration, gsl_multiroot_fsolver* solver ) { std::ostringstream buffer; buffer << printElement( iteration, 3, ' ' ) << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' ) << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' ) << std::endl; return buffer.str( ); } //! Print data element to console. template< typename DataType > inline std::string printElement( const DataType datum, const int width, const char filler ) { std::ostringstream buffer; buffer << std::left << std::setw( width ) << std::setfill( filler ) << datum; return buffer.str( ); } } // namespace atom #endif // ATOM_PRINT_FUNCTIONS_HPP <|endoftext|>
<commit_before>#pragma once #ifndef RAZ_MATERIAL_HPP #define RAZ_MATERIAL_HPP #include <unordered_map> #include "RaZ/Math/Vector.hpp" #include "RaZ/Render/Shader.hpp" #include "RaZ/Render/ShaderProgram.hpp" #include "RaZ/Render/Texture.hpp" namespace Raz { enum class MaterialType { MATERIAL_TYPE_STANDARD = 0, MATERIAL_TYPE_COOK_TORRANCE }; enum class MaterialPreset { CHARCOAL, GRASS, SAND, ICE, SNOW, // Dielectric presets IRON, SILVER, ALUMINIUM, GOLD, COPPER, CHROMIUM, NICKEL, TITANIUM, COBALT, PLATINUM // Metallic presets }; class MaterialCookTorrance; class Material { public: Material(const Material&) = default; virtual MaterialType getType() const = 0; static std::unique_ptr<MaterialCookTorrance> recoverMaterial(MaterialPreset preset, float roughnessFactor); virtual std::unique_ptr<Material> clone() const = 0; virtual void initTextures(const ShaderProgram& program) const = 0; virtual void bindAttributes(const ShaderProgram& program) const = 0; virtual ~Material() = default; protected: Material() = default; }; using MaterialPtr = std::unique_ptr<Material>; class MaterialStandard : public Material { public: MaterialStandard() = default; explicit MaterialStandard(TexturePtr diffuseMap) : m_diffuseMap{ std::move(diffuseMap) } {} explicit MaterialStandard(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); } MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_STANDARD; } const Vec3f& getAmbient() const { return m_ambient; } const Vec3f& getDiffuse() const { return m_diffuse; } const Vec3f& getSpecular() const { return m_specular; } const Vec3f& getEmissive() const { return m_emissive; } float getTransparency() const { return m_transparency; } const TexturePtr& getAmbientMap() const { return m_ambientMap; } const TexturePtr& getDiffuseMap() const { return m_diffuseMap; } const TexturePtr& getSpecularMap() const { return m_specularMap; } const TexturePtr& getEmissiveMap() const { return m_emissiveMap; } const TexturePtr& getTransparencyMap() const { return m_transparencyMap; } const TexturePtr& getBumpMap() const { return m_bumpMap; } void setDiffuse(float red, float green, float blue) { setDiffuse(Vec3f({ red, green, blue })); } void setDiffuse(const Vec3f& val) { m_diffuse = val; } void setAmbient(float red, float green, float blue) { setAmbient(Vec3f({ red, green, blue })); } void setAmbient(const Vec3f& val) { m_ambient = val; } void setSpecular(float red, float green, float blue) { setSpecular(Vec3f({ red, green, blue })); } void setSpecular(const Vec3f& val) { m_specular = val; } void setEmissive(float red, float green, float blue) { setEmissive(Vec3f({ red, green, blue })); } void setEmissive(const Vec3f& val) { m_emissive = val; } void setTransparency(float transparency) { m_transparency = transparency; } void setAmbientMap(const TexturePtr& ambientMap) { m_ambientMap = ambientMap; } void setDiffuseMap(const TexturePtr& diffuseMap) { m_diffuseMap = diffuseMap; } void setSpecularMap(const TexturePtr& specularMap) { m_specularMap = specularMap; } void setEmissiveMap(const TexturePtr& emissiveMap) { m_emissiveMap = emissiveMap; } void setTransparencyMap(const TexturePtr& transparencyMap) { m_transparencyMap = transparencyMap; } void setBumpMap(const TexturePtr& bumpMap) { m_bumpMap = bumpMap; } void loadAmbientMap(const std::string& fileName) { m_ambientMap = std::make_shared<Texture>(fileName); } void loadDiffuseMap(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); } void loadSpecularMap(const std::string& fileName) { m_specularMap = std::make_shared<Texture>(fileName); } void loadEmissiveMap(const std::string& fileName) { m_emissiveMap = std::make_shared<Texture>(fileName); } void loadTransparencyMap(const std::string& fileName) { m_transparencyMap = std::make_shared<Texture>(fileName); } void loadBumpMap(const std::string& fileName) { m_bumpMap = std::make_shared<Texture>(fileName); } std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialStandard>(*this); } void initTextures(const ShaderProgram& program) const override; void bindAttributes(const ShaderProgram& program) const override; private: Vec3f m_ambient = Vec3f(1.f); Vec3f m_diffuse = Vec3f(1.f); Vec3f m_specular = Vec3f(1.f); Vec3f m_emissive = Vec3f(1.f); float m_transparency = 1.f; TexturePtr m_ambientMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_diffuseMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_specularMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_emissiveMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_transparencyMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_bumpMap = Texture::recoverTexture(TexturePreset::WHITE); }; class MaterialCookTorrance : public Material { public: MaterialCookTorrance() = default; explicit MaterialCookTorrance(TexturePtr albedoMap) : m_albedoMap{ std::move(albedoMap) } {} explicit MaterialCookTorrance(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); } MaterialCookTorrance(const Vec3f& baseColor, float metallicFactor, float roughnessFactor) : m_baseColor{ baseColor }, m_metallicFactor{ metallicFactor }, m_roughnessFactor{ roughnessFactor } {} MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_COOK_TORRANCE; } const Vec3f& getBaseColor() const { return m_baseColor; } float getMetallicFactor() const { return m_metallicFactor; } float getRoughnessFactor() const { return m_roughnessFactor; } const TexturePtr& getAlbedoMap() const { return m_albedoMap; } const TexturePtr& getMetallicMap() const { return m_metallicMap; } const TexturePtr& getNormalMap() const { return m_normalMap; } const TexturePtr& getRoughnessMap() const { return m_roughnessMap; } const TexturePtr& getAmbientOcclusionMap() const { return m_ambientOcclusionMap; } void setBaseColor(float red, float green, float blue) { setBaseColor(Vec3f({ red, green, blue })); } void setBaseColor(const Vec3f& color) { m_baseColor = color; } void setMetallicFactor(float metallicFactor) { m_metallicFactor = metallicFactor; } void setRoughnessFactor(float roughnessFactor) { m_roughnessFactor = roughnessFactor; } void setAlbedoMap(const TexturePtr& albedoMap) { m_albedoMap = albedoMap; } void setNormalMap(const TexturePtr& normalMap) { m_normalMap = normalMap; } void setMetallicMap(const TexturePtr& metallicMap) { m_metallicMap = metallicMap; } void setRoughnessMap(const TexturePtr& roughnessMap) { m_roughnessMap = roughnessMap; } void setAmbientOcclusionMap(const TexturePtr& ambientOcclusionMap) { m_ambientOcclusionMap = ambientOcclusionMap; } void loadAlbedoMap(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); } void loadNormalMap(const std::string& fileName) { m_normalMap = std::make_shared<Texture>(fileName); } void loadMetallicMap(const std::string& fileName) { m_metallicMap = std::make_shared<Texture>(fileName); } void loadRoughnessMap(const std::string& fileName) { m_roughnessMap = std::make_shared<Texture>(fileName); } void loadAmbientOcclusionMap(const std::string& fileName) { m_ambientOcclusionMap = std::make_shared<Texture>(fileName); } std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialCookTorrance>(*this); } void initTextures(const ShaderProgram& program) const override; void bindAttributes(const ShaderProgram& program) const override; private: Vec3f m_baseColor = Vec3f(1.f); float m_metallicFactor = 1.f; float m_roughnessFactor = 1.f; TexturePtr m_albedoMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_normalMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_metallicMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_roughnessMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_ambientOcclusionMap = Texture::recoverTexture(TexturePreset::WHITE); }; } // namespace Raz #endif // RAZ_MATERIAL_HPP <commit_msg>[Update] Standard material's emissive factor is now defaulted to 0<commit_after>#pragma once #ifndef RAZ_MATERIAL_HPP #define RAZ_MATERIAL_HPP #include <unordered_map> #include "RaZ/Math/Vector.hpp" #include "RaZ/Render/Shader.hpp" #include "RaZ/Render/ShaderProgram.hpp" #include "RaZ/Render/Texture.hpp" namespace Raz { enum class MaterialType { MATERIAL_TYPE_STANDARD = 0, MATERIAL_TYPE_COOK_TORRANCE }; enum class MaterialPreset { CHARCOAL, GRASS, SAND, ICE, SNOW, // Dielectric presets IRON, SILVER, ALUMINIUM, GOLD, COPPER, CHROMIUM, NICKEL, TITANIUM, COBALT, PLATINUM // Metallic presets }; class MaterialCookTorrance; class Material { public: Material(const Material&) = default; virtual MaterialType getType() const = 0; static std::unique_ptr<MaterialCookTorrance> recoverMaterial(MaterialPreset preset, float roughnessFactor); virtual std::unique_ptr<Material> clone() const = 0; virtual void initTextures(const ShaderProgram& program) const = 0; virtual void bindAttributes(const ShaderProgram& program) const = 0; virtual ~Material() = default; protected: Material() = default; }; using MaterialPtr = std::unique_ptr<Material>; class MaterialStandard : public Material { public: MaterialStandard() = default; explicit MaterialStandard(TexturePtr diffuseMap) : m_diffuseMap{ std::move(diffuseMap) } {} explicit MaterialStandard(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); } MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_STANDARD; } const Vec3f& getAmbient() const { return m_ambient; } const Vec3f& getDiffuse() const { return m_diffuse; } const Vec3f& getSpecular() const { return m_specular; } const Vec3f& getEmissive() const { return m_emissive; } float getTransparency() const { return m_transparency; } const TexturePtr& getAmbientMap() const { return m_ambientMap; } const TexturePtr& getDiffuseMap() const { return m_diffuseMap; } const TexturePtr& getSpecularMap() const { return m_specularMap; } const TexturePtr& getEmissiveMap() const { return m_emissiveMap; } const TexturePtr& getTransparencyMap() const { return m_transparencyMap; } const TexturePtr& getBumpMap() const { return m_bumpMap; } void setDiffuse(float red, float green, float blue) { setDiffuse(Vec3f({ red, green, blue })); } void setDiffuse(const Vec3f& val) { m_diffuse = val; } void setAmbient(float red, float green, float blue) { setAmbient(Vec3f({ red, green, blue })); } void setAmbient(const Vec3f& val) { m_ambient = val; } void setSpecular(float red, float green, float blue) { setSpecular(Vec3f({ red, green, blue })); } void setSpecular(const Vec3f& val) { m_specular = val; } void setEmissive(float red, float green, float blue) { setEmissive(Vec3f({ red, green, blue })); } void setEmissive(const Vec3f& val) { m_emissive = val; } void setTransparency(float transparency) { m_transparency = transparency; } void setAmbientMap(const TexturePtr& ambientMap) { m_ambientMap = ambientMap; } void setDiffuseMap(const TexturePtr& diffuseMap) { m_diffuseMap = diffuseMap; } void setSpecularMap(const TexturePtr& specularMap) { m_specularMap = specularMap; } void setEmissiveMap(const TexturePtr& emissiveMap) { m_emissiveMap = emissiveMap; } void setTransparencyMap(const TexturePtr& transparencyMap) { m_transparencyMap = transparencyMap; } void setBumpMap(const TexturePtr& bumpMap) { m_bumpMap = bumpMap; } void loadAmbientMap(const std::string& fileName) { m_ambientMap = std::make_shared<Texture>(fileName); } void loadDiffuseMap(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); } void loadSpecularMap(const std::string& fileName) { m_specularMap = std::make_shared<Texture>(fileName); } void loadEmissiveMap(const std::string& fileName) { m_emissiveMap = std::make_shared<Texture>(fileName); } void loadTransparencyMap(const std::string& fileName) { m_transparencyMap = std::make_shared<Texture>(fileName); } void loadBumpMap(const std::string& fileName) { m_bumpMap = std::make_shared<Texture>(fileName); } std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialStandard>(*this); } void initTextures(const ShaderProgram& program) const override; void bindAttributes(const ShaderProgram& program) const override; private: Vec3f m_ambient = Vec3f(1.f); Vec3f m_diffuse = Vec3f(1.f); Vec3f m_specular = Vec3f(1.f); Vec3f m_emissive = Vec3f(0.f); float m_transparency = 1.f; TexturePtr m_ambientMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_diffuseMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_specularMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_emissiveMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_transparencyMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_bumpMap = Texture::recoverTexture(TexturePreset::WHITE); }; class MaterialCookTorrance : public Material { public: MaterialCookTorrance() = default; explicit MaterialCookTorrance(TexturePtr albedoMap) : m_albedoMap{ std::move(albedoMap) } {} explicit MaterialCookTorrance(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); } MaterialCookTorrance(const Vec3f& baseColor, float metallicFactor, float roughnessFactor) : m_baseColor{ baseColor }, m_metallicFactor{ metallicFactor }, m_roughnessFactor{ roughnessFactor } {} MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_COOK_TORRANCE; } const Vec3f& getBaseColor() const { return m_baseColor; } float getMetallicFactor() const { return m_metallicFactor; } float getRoughnessFactor() const { return m_roughnessFactor; } const TexturePtr& getAlbedoMap() const { return m_albedoMap; } const TexturePtr& getMetallicMap() const { return m_metallicMap; } const TexturePtr& getNormalMap() const { return m_normalMap; } const TexturePtr& getRoughnessMap() const { return m_roughnessMap; } const TexturePtr& getAmbientOcclusionMap() const { return m_ambientOcclusionMap; } void setBaseColor(float red, float green, float blue) { setBaseColor(Vec3f({ red, green, blue })); } void setBaseColor(const Vec3f& color) { m_baseColor = color; } void setMetallicFactor(float metallicFactor) { m_metallicFactor = metallicFactor; } void setRoughnessFactor(float roughnessFactor) { m_roughnessFactor = roughnessFactor; } void setAlbedoMap(const TexturePtr& albedoMap) { m_albedoMap = albedoMap; } void setNormalMap(const TexturePtr& normalMap) { m_normalMap = normalMap; } void setMetallicMap(const TexturePtr& metallicMap) { m_metallicMap = metallicMap; } void setRoughnessMap(const TexturePtr& roughnessMap) { m_roughnessMap = roughnessMap; } void setAmbientOcclusionMap(const TexturePtr& ambientOcclusionMap) { m_ambientOcclusionMap = ambientOcclusionMap; } void loadAlbedoMap(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); } void loadNormalMap(const std::string& fileName) { m_normalMap = std::make_shared<Texture>(fileName); } void loadMetallicMap(const std::string& fileName) { m_metallicMap = std::make_shared<Texture>(fileName); } void loadRoughnessMap(const std::string& fileName) { m_roughnessMap = std::make_shared<Texture>(fileName); } void loadAmbientOcclusionMap(const std::string& fileName) { m_ambientOcclusionMap = std::make_shared<Texture>(fileName); } std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialCookTorrance>(*this); } void initTextures(const ShaderProgram& program) const override; void bindAttributes(const ShaderProgram& program) const override; private: Vec3f m_baseColor = Vec3f(1.f); float m_metallicFactor = 1.f; float m_roughnessFactor = 1.f; TexturePtr m_albedoMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_normalMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_metallicMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_roughnessMap = Texture::recoverTexture(TexturePreset::WHITE); TexturePtr m_ambientOcclusionMap = Texture::recoverTexture(TexturePreset::WHITE); }; } // namespace Raz #endif // RAZ_MATERIAL_HPP <|endoftext|>
<commit_before>// // embed.hpp // ********* // // Copyright (c) 2018 Sharon W (sharon at aegis dot gg) // // Distributed under the MIT License. (See accompanying file LICENSE) // #pragma once #include "aegis/config.hpp" #include "aegis/snowflake.hpp" #include "field.hpp" #include "footer.hpp" #include "image.hpp" #include "thumbnail.hpp" #include "video.hpp" #include "provider.hpp" #include <nlohmann/json.hpp> #include <string> #include <vector> namespace aegis { namespace gateway { namespace objects { /**\todo Needs documentation */ class embed { public: /// Adds a new embed field /** * @param name Name of the field * @param value Text to be shown within field * @param is_inline Sets whether the field is inline */ void add_field(const std::string & name, const std::string & value, bool is_inline = false) { fields.emplace_back(name, value, is_inline); } /// Sets the title of the embed /** * @param str Title to set */ void set_title(const std::string & str) { title = str; } /// Sets the footer of the embed /** * @param str Footer to set */ void set_footer(const footer ftr) { footer_ = ftr; } /// Sets the description of the embed /** * @param str Description to set */ void set_description(const std::string & str) { description = str; } /// Sets the url of the embed /** * @param str Url to set */ void set_url(const std::string & str) { url = str; } /// Sets the timestamp of the embed /** * @param str Timestamp to set */ void set_timestamp(const std::string & str) { timestamp = str; } /// Sets the color of the embed /** * @param clr Color to set */ void set_color(const int32_t clr) { color = clr; } // Combined Limit: 6000 std::string title; /**<\todo Needs documentation */ // Limit: 256 std::string type; /**<\todo Needs documentation */ std::string description; /**<\todo Needs documentation */ // Limit: 2048 std::string url; /**<\todo Needs documentation */ std::string timestamp; /**<\todo Needs documentation */ int32_t color = 0; /**<\todo Needs documentation */ footer footer_; /**<\todo Needs documentation */ // Limit: 2048 image image_; /**<\todo Needs documentation */ thumbnail thumbnail_; /**<\todo Needs documentation */ video video_; /**<\todo Needs documentation */ provider provider_; /**<\todo Needs documentation */ std::vector<field> fields; /**<\todo Needs documentation */ // Limit: 25 name:256 value:1024 }; /// \cond TEMPLATES inline void from_json(const nlohmann::json& j, embed& m) { if (j.count("title") && !j["title"].is_null()) m.title = j["title"]; if (j.count("type")) m.type = j["type"]; if (j.count("description") && !j["description"].is_null()) m.description = j["description"]; if (j.count("url") && !j["url"].is_null()) m.url = j["url"]; if (j.count("timestamp") && !j["timestamp"].is_null()) m.timestamp = j["timestamp"]; if (j.count("color") && !j["color"].is_null()) m.color = j["color"]; if (j.count("footer") && !j["footer"].is_null()) m.footer_ = j["footer"]; if (j.count("image") && !j["image"].is_null()) m.image_ = j["image"]; if (j.count("thumbnail") && !j["thumbnail"].is_null()) m.thumbnail_ = j["thumbnail"]; if (j.count("video") && !j["video"].is_null()) m.video_ = j["video"]; if (j.count("provider") && !j["provider"].is_null()) m.provider_ = j["provider"]; if (j.count("fields") && !j["fields"].is_null()) for (const auto & _field : j["fields"]) m.fields.push_back(_field); } /// \endcond /// \cond TEMPLATES inline void to_json(nlohmann::json& j, const embed& m) { j["title"] = m.title; j["type"] = m.type; j["description"] = m.description; j["url"] = m.url; j["timestamp"] = m.timestamp; j["color"] = m.color; j["footer"] = m.footer_; j["image"] = m.image_; j["thumbnail"] = m.thumbnail_; j["video"] = m.video_; j["provider"] = m.provider_; for (const auto & _field : m.fields) j["fields"].push_back(_field); } /// \endcond } } } <commit_msg>Changed embed to fluent-style interface<commit_after>// // embed.hpp // ********* // // Copyright (c) 2018 Sharon W (sharon at aegis dot gg) // // Distributed under the MIT License. (See accompanying file LICENSE) // #pragma once #include "aegis/config.hpp" #include "aegis/snowflake.hpp" #include "field.hpp" #include "footer.hpp" #include "image.hpp" #include "thumbnail.hpp" #include "video.hpp" #include "provider.hpp" #include <nlohmann/json.hpp> #include <string> #include <vector> namespace aegis { namespace gateway { namespace objects { /**\todo Needs documentation */ class embed { public: /// Adds a new embed field /** * @param name Name of the field * @param value Text to be shown within field * @param is_inline Sets whether the field is inline */ embed & fields(std::vector<objects::field> flds) { _fields = flds; return *this; } /// Sets the title of the embed /** * @param str Title to set */ embed & title(const std::string & str) { _title = str; return *this; } /// Sets the footer of the embed /** * @param str Footer to set */ embed & footer(const footer ftr) { _footer = ftr; return *this; } /// Sets the description of the embed /** * @param str Description to set */ embed & description(const std::string & str) { _description = str; return *this; } /// Sets the url of the embed /** * @param str Url to set */ embed & url(std::string & str) { _url = str; return *this; } /// Sets the timestamp of the embed /** * @param str Timestamp to set */ embed & timestamp(const std::string & str) { _timestamp = str; return *this; } /// Sets the color of the embed /** * @param clr Color to set */ embed & color(const int32_t clr) { _color = clr; return *this; } // Combined Limit: 6000 std::string _title; /**<\todo Needs documentation */ // Limit: 256 std::string _type; /**<\todo Needs documentation */ std::string _description; /**<\todo Needs documentation */ // Limit: 2048 std::string _url; /**<\todo Needs documentation */ std::string _timestamp; /**<\todo Needs documentation */ int32_t _color = 0; /**<\todo Needs documentation */ objects::footer _footer; /**<\todo Needs documentation */ // Limit: 2048 objects::image _image; /**<\todo Needs documentation */ objects::thumbnail _thumbnail; /**<\todo Needs documentation */ objects::video _video; /**<\todo Needs documentation */ objects::provider _provider; /**<\todo Needs documentation */ std::vector<objects::field> _fields; /**<\todo Needs documentation */ // Limit: 25 name:256 value:1024 friend void from_json(const nlohmann::json& j, embed& m); friend void to_json(nlohmann::json& j, const embed& m); }; /// \cond TEMPLATES inline void from_json(const nlohmann::json& j, embed& m) { if (j.count("title") && !j["title"].is_null()) m._title = j["title"].get<std::string>(); if (j.count("type")) m._type = j["type"].get<std::string>(); if (j.count("description") && !j["description"].is_null()) m._description = j["description"].get<std::string>(); if (j.count("url") && !j["url"].is_null()) m._url = j["url"].get<std::string>(); if (j.count("timestamp") && !j["timestamp"].is_null()) m._timestamp = j["timestamp"].get<std::string>(); if (j.count("color") && !j["color"].is_null()) m._color = j["color"]; if (j.count("footer") && !j["footer"].is_null()) m._footer = j["footer"]; if (j.count("image") && !j["image"].is_null()) m._image = j["image"]; if (j.count("thumbnail") && !j["thumbnail"].is_null()) m._thumbnail = j["thumbnail"]; if (j.count("video") && !j["video"].is_null()) m._video = j["video"]; if (j.count("provider") && !j["provider"].is_null()) m._provider = j["provider"]; if (j.count("fields") && !j["fields"].is_null()) for (const auto & _field : j["fields"]) m._fields.push_back(_field); } /// \endcond /// \cond TEMPLATES inline void to_json(nlohmann::json& j, const embed& m) { j["title"] = m._title; j["type"] = m._type; j["description"] = m._description; j["url"] = m._url; j["timestamp"] = m._timestamp; j["color"] = m._color; j["footer"] = m._footer; j["image"] = m._image; j["thumbnail"] = m._thumbnail; j["video"] = m._video; j["provider"] = m._provider; for (const auto & _field : m._fields) j["fields"].push_back(_field); } /// \endcond } } } <|endoftext|>
<commit_before>#pragma once #include <array> #include <baka/variadic.hpp> #include <cstddef> #include <ffi.h> #include <functional> #include <type_traits> #include <utility> #include <vector> namespace baka { namespace detail { template<typename T> ffi_type* type(); template<> ffi_type* type<int>() { return &ffi_type_sint; } } template<typename T> class bound_function; template<typename Ret, typename... Args> class bound_function<Ret(Args...)> { using fptr_t = Ret(*)(Args...); public: template<typename F> explicit bound_function(F&& function_) : function(std::forward<F>(function_)) { return_type = detail::type<Ret>(); argument_types = { detail::type<Args>()... }; ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argument_types.size(), return_type, argument_types.data()); closure = ffi_closure_alloc(sizeof(ffi_closure), &thunk); ffi_prep_closure_loc(static_cast<ffi_closure*>(closure), &cif, &call, this, reinterpret_cast<void*>(thunk)); } operator fptr_t() const { return reinterpret_cast<fptr_t>(thunk); } private: static void call(ffi_cif*, void* ret, void** args, void* self_void) { auto self = static_cast<bound_function*>(self_void); self->template call_<0>(static_cast<Ret*>(ret), args); } template<std::size_t N, typename... CallArgs> typename std::enable_if<N != sizeof...(Args)>::type call_(Ret* ret, void** args, CallArgs&&... call_args) { call_<N + 1>(ret, args, std::forward<CallArgs>(call_args)..., *static_cast<NthType<N, Args...>*>(args[N])); } template<std::size_t N, typename... CallArgs> typename std::enable_if<N == sizeof...(Args)>::type call_(Ret* ret, void**, CallArgs&&... call_args) { *ret = function(std::forward<CallArgs>(call_args)...); } std::function<Ret(Args...)> function; ffi_cif cif; ffi_type* return_type; std::vector<ffi_type*> argument_types; void* closure; void* thunk; }; } <commit_msg>Free closure when bound_function is destroyed<commit_after>#pragma once #include <array> #include <baka/variadic.hpp> #include <cstddef> #include <ffi.h> #include <functional> #include <memory> #include <type_traits> #include <utility> #include <vector> namespace baka { namespace detail { template<typename T> ffi_type* type(); template<> ffi_type* type<int>() { return &::ffi_type_sint; } } template<typename T> class bound_function; template<typename Ret, typename... Args> class bound_function<Ret(Args...)> { using fptr_t = Ret(*)(Args...); public: template<typename F> explicit bound_function(F&& function_) : function(std::forward<F>(function_)) , closure(nullptr, &::ffi_closure_free) { return_type = detail::type<Ret>(); argument_types = { detail::type<Args>()... }; ::ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argument_types.size(), return_type, argument_types.data()); closure.reset(static_cast<::ffi_closure*>(::ffi_closure_alloc(sizeof(::ffi_closure), &thunk))); ::ffi_prep_closure_loc(closure.get(), &cif, &call, this, reinterpret_cast<void*>(thunk)); } operator fptr_t() const { return reinterpret_cast<fptr_t>(thunk); } private: static void call(ffi_cif*, void* ret, void** args, void* self_void) { auto self = static_cast<bound_function*>(self_void); self->template call_<0>(static_cast<Ret*>(ret), args); } template<std::size_t N, typename... CallArgs> typename std::enable_if<N != sizeof...(Args)>::type call_(Ret* ret, void** args, CallArgs&&... call_args) { call_<N + 1>(ret, args, std::forward<CallArgs>(call_args)..., *static_cast<NthType<N, Args...>*>(args[N])); } template<std::size_t N, typename... CallArgs> typename std::enable_if<N == sizeof...(Args)>::type call_(Ret* ret, void**, CallArgs&&... call_args) { *ret = function(std::forward<CallArgs>(call_args)...); } std::function<Ret(Args...)> function; ::ffi_cif cif; ::ffi_type* return_type; std::vector<::ffi_type*> argument_types; std::unique_ptr<::ffi_closure, decltype(&::ffi_closure_free)> closure; void* thunk; // freed by ::ffi_closure_free }; } <|endoftext|>
<commit_before><commit_msg>the variable is only available on linux<commit_after><|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 "content/browser/accessibility/browser_accessibility_manager.h" #include "base/logging.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/common/accessibility_messages.h" namespace content { BrowserAccessibility* BrowserAccessibilityFactory::Create() { return BrowserAccessibility::Create(); } #if !defined(OS_MACOSX) && \ !defined(OS_WIN) && \ !defined(TOOLKIT_GTK) && \ !defined(OS_ANDROID) \ // We have subclassess of BrowserAccessibilityManager on Mac, Linux/GTK, // and Win. For any other platform, instantiate the base class. // static BrowserAccessibilityManager* BrowserAccessibilityManager::Create( const AccessibilityNodeData& src, BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory) { return new BrowserAccessibilityManager(src, delegate, factory); } #endif BrowserAccessibilityManager::BrowserAccessibilityManager( BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory) : delegate_(delegate), factory_(factory), root_(NULL), focus_(NULL), osk_state_(OSK_ALLOWED) { } BrowserAccessibilityManager::BrowserAccessibilityManager( const AccessibilityNodeData& src, BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory) : delegate_(delegate), factory_(factory), root_(NULL), focus_(NULL), osk_state_(OSK_ALLOWED) { Initialize(src); } BrowserAccessibilityManager::~BrowserAccessibilityManager() { if (root_) root_->Destroy(); } void BrowserAccessibilityManager::Initialize(const AccessibilityNodeData src) { std::vector<AccessibilityNodeData> nodes; nodes.push_back(src); if (!UpdateNodes(nodes)) return; if (!focus_) SetFocus(root_, false); } // static AccessibilityNodeData BrowserAccessibilityManager::GetEmptyDocument() { AccessibilityNodeData empty_document; empty_document.id = 0; empty_document.role = blink::WebAXRoleRootWebArea; return empty_document; } BrowserAccessibility* BrowserAccessibilityManager::GetRoot() { return root_; } BrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID( int32 renderer_id) { base::hash_map<int32, BrowserAccessibility*>::iterator iter = renderer_id_map_.find(renderer_id); if (iter != renderer_id_map_.end()) return iter->second; return NULL; } void BrowserAccessibilityManager::GotFocus(bool touch_event_context) { if (!touch_event_context) osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED; if (!focus_) return; NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_); } void BrowserAccessibilityManager::WasHidden() { osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_HIDDEN; } void BrowserAccessibilityManager::GotMouseDown() { osk_state_ = OSK_ALLOWED_WITHIN_FOCUSED_OBJECT; NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_); } bool BrowserAccessibilityManager::IsOSKAllowed(const gfx::Rect& bounds) { if (!delegate_ || !delegate_->HasFocus()) return false; gfx::Point touch_point = delegate_->GetLastTouchEventLocation(); return bounds.Contains(touch_point); } bool BrowserAccessibilityManager::UseRootScrollOffsetsWhenComputingBounds() { return true; } void BrowserAccessibilityManager::RemoveNode(BrowserAccessibility* node) { if (node == focus_) SetFocus(root_, false); int renderer_id = node->renderer_id(); renderer_id_map_.erase(renderer_id); } void BrowserAccessibilityManager::OnAccessibilityEvents( const std::vector<AccessibilityHostMsg_EventParams>& params) { for (uint32 index = 0; index < params.size(); index++) { const AccessibilityHostMsg_EventParams& param = params[index]; // Update nodes that changed. if (!UpdateNodes(param.nodes)) return; // Find the node corresponding to the id that's the target of the // event (which may not be the root of the update tree). BrowserAccessibility* node = GetFromRendererID(param.id); if (!node) continue; blink::WebAXEvent event_type = param.event_type; if (event_type == blink::WebAXEventFocus || event_type == blink::WebAXEventBlur) { SetFocus(node, false); if (osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_HIDDEN && osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED) osk_state_ = OSK_ALLOWED; // Don't send a native focus event if the window itself doesn't // have focus. if (delegate_ && !delegate_->HasFocus()) continue; } // Send the event event to the operating system. NotifyAccessibilityEvent(event_type, node); // Set initial focus when a page is loaded. if (event_type == blink::WebAXEventLoadComplete) { if (!focus_) SetFocus(root_, false); if (!delegate_ || delegate_->HasFocus()) NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_); } } } BrowserAccessibility* BrowserAccessibilityManager::GetFocus( BrowserAccessibility* root) { if (focus_ && (!root || focus_->IsDescendantOf(root))) return focus_; return NULL; } void BrowserAccessibilityManager::SetFocus( BrowserAccessibility* node, bool notify) { if (focus_ != node) focus_ = node; if (notify && node && delegate_) delegate_->SetAccessibilityFocus(node->renderer_id()); } void BrowserAccessibilityManager::SetRoot(BrowserAccessibility* node) { root_ = node; NotifyRootChanged(); } void BrowserAccessibilityManager::DoDefaultAction( const BrowserAccessibility& node) { if (delegate_) delegate_->AccessibilityDoDefaultAction(node.renderer_id()); } void BrowserAccessibilityManager::ScrollToMakeVisible( const BrowserAccessibility& node, gfx::Rect subfocus) { if (delegate_) { delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus); } } void BrowserAccessibilityManager::ScrollToPoint( const BrowserAccessibility& node, gfx::Point point) { if (delegate_) { delegate_->AccessibilityScrollToPoint(node.renderer_id(), point); } } void BrowserAccessibilityManager::SetTextSelection( const BrowserAccessibility& node, int start_offset, int end_offset) { if (delegate_) { delegate_->AccessibilitySetTextSelection( node.renderer_id(), start_offset, end_offset); } } gfx::Rect BrowserAccessibilityManager::GetViewBounds() { if (delegate_) return delegate_->GetViewBounds(); return gfx::Rect(); } void BrowserAccessibilityManager::UpdateNodesForTesting( const AccessibilityNodeData& node1, const AccessibilityNodeData& node2 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node3 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node4 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node5 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node6 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node7 /* = AccessibilityNodeData() */) { std::vector<AccessibilityNodeData> nodes; nodes.push_back(node1); if (node2.id != AccessibilityNodeData().id) nodes.push_back(node2); if (node3.id != AccessibilityNodeData().id) nodes.push_back(node3); if (node4.id != AccessibilityNodeData().id) nodes.push_back(node4); if (node5.id != AccessibilityNodeData().id) nodes.push_back(node5); if (node6.id != AccessibilityNodeData().id) nodes.push_back(node6); if (node7.id != AccessibilityNodeData().id) nodes.push_back(node7); UpdateNodes(nodes); } bool BrowserAccessibilityManager::UpdateNodes( const std::vector<AccessibilityNodeData>& nodes) { bool success = true; // First, update all of the nodes in the tree. for (size_t i = 0; i < nodes.size() && success; i++) { if (!UpdateNode(nodes[i])) success = false; } // In a second pass, call PostInitialize on each one - this must // be called after all of each node's children are initialized too. for (size_t i = 0; i < nodes.size() && success; i++) { // Note: it's not a bug for nodes[i].id to not be found in the tree. // Consider this example: // Before: // A // B // C // D // E // F // After: // A // B // C // F // D // In this example, F is being reparented. The renderer scans the tree // in order. If can't update "C" to add "F" as a child, when "F" is still // a child of "E". So it first updates "E", to remove "F" as a child. // Later, it ends up deleting "E". So when we get here, "E" was updated as // part of this sequence but it no longer exists in the final tree, so // there's nothing to postinitialize. BrowserAccessibility* instance = GetFromRendererID(nodes[i].id); if (instance) instance->PostInitialize(); } if (!success) { // A bad accessibility tree could lead to memory corruption. // Ask the delegate to crash the renderer, or if not available, // crash the browser. if (delegate_) delegate_->FatalAccessibilityTreeError(); else CHECK(false); } return success; } BrowserAccessibility* BrowserAccessibilityManager::CreateNode( BrowserAccessibility* parent, int32 renderer_id, int32 index_in_parent) { BrowserAccessibility* node = factory_->Create(); node->InitializeTreeStructure( this, parent, renderer_id, index_in_parent); AddNodeToMap(node); return node; } void BrowserAccessibilityManager::AddNodeToMap(BrowserAccessibility* node) { renderer_id_map_[node->renderer_id()] = node; } bool BrowserAccessibilityManager::UpdateNode(const AccessibilityNodeData& src) { // This method updates one node in the tree based on serialized data // received from the renderer. // Create a set of child ids in |src| for fast lookup. If a duplicate id is // found, exit now with a fatal error before changing anything else. std::set<int32> new_child_ids; for (size_t i = 0; i < src.child_ids.size(); ++i) { if (new_child_ids.find(src.child_ids[i]) != new_child_ids.end()) return false; new_child_ids.insert(src.child_ids[i]); } // Look up the node by id. If it's not found, then either the root // of the tree is being swapped, or we're out of sync with the renderer // and this is a serious error. BrowserAccessibility* instance = GetFromRendererID(src.id); if (!instance) { if (src.role != blink::WebAXRoleRootWebArea) return false; instance = CreateNode(NULL, src.id, 0); } // TODO(dmazzoni): avoid a linear scan here. for (size_t i = 0; i < src.bool_attributes.size(); i++) { if (src.bool_attributes[i].first == AccessibilityNodeData::ATTR_UPDATE_LOCATION_ONLY) { instance->SetLocation(src.location); return true; } } // Update all of the node-specific data, like its role, state, name, etc. instance->InitializeData(src); // // Update the children in three steps: // // 1. Iterate over the old children and delete nodes that are no longer // in the tree. // 2. Build up a vector of new children, reusing children that haven't // changed (but may have been reordered) and adding new empty // objects for new children. // 3. Swap in the new children vector for the old one. // Delete any previous children of this instance that are no longer // children first. We make a deletion-only pass first to prevent a // node that's being reparented from being the child of both its old // parent and new parent, which could lead to a double-free. // If a node is reparented, the renderer will always send us a fresh // copy of the node. const std::vector<BrowserAccessibility*>& old_children = instance->children(); for (size_t i = 0; i < old_children.size(); ++i) { int old_id = old_children[i]->renderer_id(); if (new_child_ids.find(old_id) == new_child_ids.end()) old_children[i]->Destroy(); } // Now build a vector of new children, reusing objects that were already // children of this node before. std::vector<BrowserAccessibility*> new_children; bool success = true; for (size_t i = 0; i < src.child_ids.size(); i++) { int32 child_renderer_id = src.child_ids[i]; int32 index_in_parent = static_cast<int32>(i); BrowserAccessibility* child = GetFromRendererID(child_renderer_id); if (child) { if (child->parent() != instance) { // This is a serious error - nodes should never be reparented. // If this case occurs, continue so this node isn't left in an // inconsistent state, but return failure at the end. success = false; continue; } child->UpdateParent(instance, index_in_parent); } else { child = CreateNode(instance, child_renderer_id, index_in_parent); } new_children.push_back(child); } // Finally, swap in the new children vector for the old. instance->SwapChildren(new_children); // Handle the case where this node is the new root of the tree. if (src.role == blink::WebAXRoleRootWebArea && (!root_ || root_->renderer_id() != src.id)) { if (root_) root_->Destroy(); if (focus_ == root_) SetFocus(instance, false); SetRoot(instance); } // Keep track of what node is focused. if (src.role != blink::WebAXRoleRootWebArea && src.role != blink::WebAXRoleWebArea && (src.state >> blink::WebAXStateFocused & 1)) { SetFocus(instance, false); } return success; } } // namespace content <commit_msg>Update accessibility tree before sending events.<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 "content/browser/accessibility/browser_accessibility_manager.h" #include "base/logging.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/common/accessibility_messages.h" namespace content { BrowserAccessibility* BrowserAccessibilityFactory::Create() { return BrowserAccessibility::Create(); } #if !defined(OS_MACOSX) && \ !defined(OS_WIN) && \ !defined(TOOLKIT_GTK) && \ !defined(OS_ANDROID) \ // We have subclassess of BrowserAccessibilityManager on Mac, Linux/GTK, // and Win. For any other platform, instantiate the base class. // static BrowserAccessibilityManager* BrowserAccessibilityManager::Create( const AccessibilityNodeData& src, BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory) { return new BrowserAccessibilityManager(src, delegate, factory); } #endif BrowserAccessibilityManager::BrowserAccessibilityManager( BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory) : delegate_(delegate), factory_(factory), root_(NULL), focus_(NULL), osk_state_(OSK_ALLOWED) { } BrowserAccessibilityManager::BrowserAccessibilityManager( const AccessibilityNodeData& src, BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory) : delegate_(delegate), factory_(factory), root_(NULL), focus_(NULL), osk_state_(OSK_ALLOWED) { Initialize(src); } BrowserAccessibilityManager::~BrowserAccessibilityManager() { if (root_) root_->Destroy(); } void BrowserAccessibilityManager::Initialize(const AccessibilityNodeData src) { std::vector<AccessibilityNodeData> nodes; nodes.push_back(src); if (!UpdateNodes(nodes)) return; if (!focus_) SetFocus(root_, false); } // static AccessibilityNodeData BrowserAccessibilityManager::GetEmptyDocument() { AccessibilityNodeData empty_document; empty_document.id = 0; empty_document.role = blink::WebAXRoleRootWebArea; return empty_document; } BrowserAccessibility* BrowserAccessibilityManager::GetRoot() { return root_; } BrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID( int32 renderer_id) { base::hash_map<int32, BrowserAccessibility*>::iterator iter = renderer_id_map_.find(renderer_id); if (iter != renderer_id_map_.end()) return iter->second; return NULL; } void BrowserAccessibilityManager::GotFocus(bool touch_event_context) { if (!touch_event_context) osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED; if (!focus_) return; NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_); } void BrowserAccessibilityManager::WasHidden() { osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_HIDDEN; } void BrowserAccessibilityManager::GotMouseDown() { osk_state_ = OSK_ALLOWED_WITHIN_FOCUSED_OBJECT; NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_); } bool BrowserAccessibilityManager::IsOSKAllowed(const gfx::Rect& bounds) { if (!delegate_ || !delegate_->HasFocus()) return false; gfx::Point touch_point = delegate_->GetLastTouchEventLocation(); return bounds.Contains(touch_point); } bool BrowserAccessibilityManager::UseRootScrollOffsetsWhenComputingBounds() { return true; } void BrowserAccessibilityManager::RemoveNode(BrowserAccessibility* node) { if (node == focus_) SetFocus(root_, false); int renderer_id = node->renderer_id(); renderer_id_map_.erase(renderer_id); } void BrowserAccessibilityManager::OnAccessibilityEvents( const std::vector<AccessibilityHostMsg_EventParams>& params) { bool should_send_initial_focus = false; // Process all changes to the accessibility tree first. for (uint32 index = 0; index < params.size(); index++) { const AccessibilityHostMsg_EventParams& param = params[index]; if (!UpdateNodes(param.nodes)) return; // Set initial focus when a page is loaded. blink::WebAXEvent event_type = param.event_type; if (event_type == blink::WebAXEventLoadComplete) { if (!focus_) { SetFocus(root_, false); should_send_initial_focus = true; } } } if (should_send_initial_focus && (!delegate_ || delegate_->HasFocus())) { NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_); } // Now iterate over the events again and fire the events. for (uint32 index = 0; index < params.size(); index++) { const AccessibilityHostMsg_EventParams& param = params[index]; // Find the node corresponding to the id that's the target of the // event (which may not be the root of the update tree). BrowserAccessibility* node = GetFromRendererID(param.id); if (!node) continue; blink::WebAXEvent event_type = param.event_type; if (event_type == blink::WebAXEventFocus || event_type == blink::WebAXEventBlur) { SetFocus(node, false); if (osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_HIDDEN && osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED) osk_state_ = OSK_ALLOWED; // Don't send a native focus event if the window itself doesn't // have focus. if (delegate_ && !delegate_->HasFocus()) continue; } // Send the event event to the operating system. NotifyAccessibilityEvent(event_type, node); } } BrowserAccessibility* BrowserAccessibilityManager::GetFocus( BrowserAccessibility* root) { if (focus_ && (!root || focus_->IsDescendantOf(root))) return focus_; return NULL; } void BrowserAccessibilityManager::SetFocus( BrowserAccessibility* node, bool notify) { if (focus_ != node) focus_ = node; if (notify && node && delegate_) delegate_->SetAccessibilityFocus(node->renderer_id()); } void BrowserAccessibilityManager::SetRoot(BrowserAccessibility* node) { root_ = node; NotifyRootChanged(); } void BrowserAccessibilityManager::DoDefaultAction( const BrowserAccessibility& node) { if (delegate_) delegate_->AccessibilityDoDefaultAction(node.renderer_id()); } void BrowserAccessibilityManager::ScrollToMakeVisible( const BrowserAccessibility& node, gfx::Rect subfocus) { if (delegate_) { delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus); } } void BrowserAccessibilityManager::ScrollToPoint( const BrowserAccessibility& node, gfx::Point point) { if (delegate_) { delegate_->AccessibilityScrollToPoint(node.renderer_id(), point); } } void BrowserAccessibilityManager::SetTextSelection( const BrowserAccessibility& node, int start_offset, int end_offset) { if (delegate_) { delegate_->AccessibilitySetTextSelection( node.renderer_id(), start_offset, end_offset); } } gfx::Rect BrowserAccessibilityManager::GetViewBounds() { if (delegate_) return delegate_->GetViewBounds(); return gfx::Rect(); } void BrowserAccessibilityManager::UpdateNodesForTesting( const AccessibilityNodeData& node1, const AccessibilityNodeData& node2 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node3 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node4 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node5 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node6 /* = AccessibilityNodeData() */, const AccessibilityNodeData& node7 /* = AccessibilityNodeData() */) { std::vector<AccessibilityNodeData> nodes; nodes.push_back(node1); if (node2.id != AccessibilityNodeData().id) nodes.push_back(node2); if (node3.id != AccessibilityNodeData().id) nodes.push_back(node3); if (node4.id != AccessibilityNodeData().id) nodes.push_back(node4); if (node5.id != AccessibilityNodeData().id) nodes.push_back(node5); if (node6.id != AccessibilityNodeData().id) nodes.push_back(node6); if (node7.id != AccessibilityNodeData().id) nodes.push_back(node7); UpdateNodes(nodes); } bool BrowserAccessibilityManager::UpdateNodes( const std::vector<AccessibilityNodeData>& nodes) { bool success = true; // First, update all of the nodes in the tree. for (size_t i = 0; i < nodes.size() && success; i++) { if (!UpdateNode(nodes[i])) success = false; } // In a second pass, call PostInitialize on each one - this must // be called after all of each node's children are initialized too. for (size_t i = 0; i < nodes.size() && success; i++) { // Note: it's not a bug for nodes[i].id to not be found in the tree. // Consider this example: // Before: // A // B // C // D // E // F // After: // A // B // C // F // D // In this example, F is being reparented. The renderer scans the tree // in order. If can't update "C" to add "F" as a child, when "F" is still // a child of "E". So it first updates "E", to remove "F" as a child. // Later, it ends up deleting "E". So when we get here, "E" was updated as // part of this sequence but it no longer exists in the final tree, so // there's nothing to postinitialize. BrowserAccessibility* instance = GetFromRendererID(nodes[i].id); if (instance) instance->PostInitialize(); } if (!success) { // A bad accessibility tree could lead to memory corruption. // Ask the delegate to crash the renderer, or if not available, // crash the browser. if (delegate_) delegate_->FatalAccessibilityTreeError(); else CHECK(false); } return success; } BrowserAccessibility* BrowserAccessibilityManager::CreateNode( BrowserAccessibility* parent, int32 renderer_id, int32 index_in_parent) { BrowserAccessibility* node = factory_->Create(); node->InitializeTreeStructure( this, parent, renderer_id, index_in_parent); AddNodeToMap(node); return node; } void BrowserAccessibilityManager::AddNodeToMap(BrowserAccessibility* node) { renderer_id_map_[node->renderer_id()] = node; } bool BrowserAccessibilityManager::UpdateNode(const AccessibilityNodeData& src) { // This method updates one node in the tree based on serialized data // received from the renderer. // Create a set of child ids in |src| for fast lookup. If a duplicate id is // found, exit now with a fatal error before changing anything else. std::set<int32> new_child_ids; for (size_t i = 0; i < src.child_ids.size(); ++i) { if (new_child_ids.find(src.child_ids[i]) != new_child_ids.end()) return false; new_child_ids.insert(src.child_ids[i]); } // Look up the node by id. If it's not found, then either the root // of the tree is being swapped, or we're out of sync with the renderer // and this is a serious error. BrowserAccessibility* instance = GetFromRendererID(src.id); if (!instance) { if (src.role != blink::WebAXRoleRootWebArea) return false; instance = CreateNode(NULL, src.id, 0); } // TODO(dmazzoni): avoid a linear scan here. for (size_t i = 0; i < src.bool_attributes.size(); i++) { if (src.bool_attributes[i].first == AccessibilityNodeData::ATTR_UPDATE_LOCATION_ONLY) { instance->SetLocation(src.location); return true; } } // Update all of the node-specific data, like its role, state, name, etc. instance->InitializeData(src); // // Update the children in three steps: // // 1. Iterate over the old children and delete nodes that are no longer // in the tree. // 2. Build up a vector of new children, reusing children that haven't // changed (but may have been reordered) and adding new empty // objects for new children. // 3. Swap in the new children vector for the old one. // Delete any previous children of this instance that are no longer // children first. We make a deletion-only pass first to prevent a // node that's being reparented from being the child of both its old // parent and new parent, which could lead to a double-free. // If a node is reparented, the renderer will always send us a fresh // copy of the node. const std::vector<BrowserAccessibility*>& old_children = instance->children(); for (size_t i = 0; i < old_children.size(); ++i) { int old_id = old_children[i]->renderer_id(); if (new_child_ids.find(old_id) == new_child_ids.end()) old_children[i]->Destroy(); } // Now build a vector of new children, reusing objects that were already // children of this node before. std::vector<BrowserAccessibility*> new_children; bool success = true; for (size_t i = 0; i < src.child_ids.size(); i++) { int32 child_renderer_id = src.child_ids[i]; int32 index_in_parent = static_cast<int32>(i); BrowserAccessibility* child = GetFromRendererID(child_renderer_id); if (child) { if (child->parent() != instance) { // This is a serious error - nodes should never be reparented. // If this case occurs, continue so this node isn't left in an // inconsistent state, but return failure at the end. success = false; continue; } child->UpdateParent(instance, index_in_parent); } else { child = CreateNode(instance, child_renderer_id, index_in_parent); } new_children.push_back(child); } // Finally, swap in the new children vector for the old. instance->SwapChildren(new_children); // Handle the case where this node is the new root of the tree. if (src.role == blink::WebAXRoleRootWebArea && (!root_ || root_->renderer_id() != src.id)) { if (root_) root_->Destroy(); if (focus_ == root_) SetFocus(instance, false); SetRoot(instance); } // Keep track of what node is focused. if (src.role != blink::WebAXRoleRootWebArea && src.role != blink::WebAXRoleWebArea && (src.state >> blink::WebAXStateFocused & 1)) { SetFocus(instance, false); } return success; } } // namespace content <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef CPM_BOOTSTRAP_THEME_HPP #define CPM_BOOTSTRAP_THEME_HPP #include "cpm/io.hpp" #include "cpm/data.hpp" namespace cpm { struct bootstrap_theme { const reports_data& data; cxxopts::Options& options; std::ostream& stream; std::string current_compiler; std::string current_configuration; bootstrap_theme(const reports_data& data, cxxopts::Options& options, std::ostream& stream, std::string compiler, std::string configuration) : data(data), options(options), stream(stream), current_compiler(std::move(compiler)), current_configuration(std::move(configuration)) {} void include(){ stream << "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>\n"; stream << "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\" rel=\"stylesheet\">\n"; stream << "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css\" rel=\"stylesheet\">\n"; } void header(){ stream << R"=====( <nav id="myNavbar" class="navbar navbar-default navbar-inverse navbar-fixed-top" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarCollapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Results</a> </div> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="nav navbar-nav"> <li class="active"><a href="index.html">Home</a></li> <li><a href="http://github.com/wichtounet/cpm">Generated with CPM</a></li> </ul> </div> </div> </nav> )====="; } void footer(){ stream << R"=====( <hr> <div class="row"> <div class="col-xs-12"> <footer> <p>Generated with <a href="https://github.com/wichtounet/cpm">CPM</a></p> </footer> </div> </div> </div> )====="; } void before_information(){ stream << "<div class=\"jumbotron\">\n"; stream << "<div class=\"container-fluid\">\n"; } void after_information(){ stream << "</div>\n"; stream << "</div>\n"; stream << "<div class=\"container-fluid\">\n"; } void compiler_buttons(){ stream << R"=====(<div class="row">)====="; stream << R"=====(<div class="col-xs-12">)====="; stream << R"=====(<span>Select compiler: </span>)====="; stream << R"=====(<div class="btn-group" role="group">)====="; for(auto& compiler : data.compilers){ if(compiler == current_compiler){ stream << "<a class=\"btn btn-primary\" href=\"" << cpm::filify(compiler, current_configuration) << "\">" << compiler << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << cpm::filify(compiler, current_configuration) << "\">" << compiler << "</a>\n"; } } stream << "</div>\n"; stream << "</div>\n"; stream << "</div>\n"; } void configuration_buttons(){ if(data.compilers.size() > 1){ stream << R"=====(<div class="row" style="padding-top:5px;">)====="; } else { stream << R"=====(<div class="row">)====="; } stream << R"=====(<div class="col-xs-12">)====="; stream << R"=====(<span>Select configuration: </span>)====="; stream << R"=====(<div class="btn-group" role="group">)====="; for(auto& configuration : data.configurations){ if(configuration == current_configuration){ stream << "<a class=\"btn btn-primary\" href=\"" << cpm::filify(current_compiler, configuration) << "\">" << configuration << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << cpm::filify(current_compiler, configuration) << "\">" << configuration << "</a>\n"; } } stream << "</div>\n"; stream << "</div>\n"; stream << "</div>\n"; } virtual void start_column(const std::string& style = ""){ std::size_t columns = 1; //Always the first grapah if(data.documents.size() > 1 && !options.count("disable-time")){ ++columns; } if(data.compilers.size() > 1 && !options.count("disable-compiler")){ ++columns; } if(data.configurations.size() > 1 && !options.count("disable-configuration")){ ++columns; } if(!options.count("disable-summary")){ ++columns; } stream << "<div class=\"col-xs-" << 12 / columns << "\"" << style << ">\n"; } virtual void close_column(){ stream << "</div>\n"; } void before_graph(std::size_t id){ start_column(); stream << "<div id=\"chart_" << id << "\" style=\"height: 400px;\"></div>\n"; } void after_graph(){ close_column(); } void before_result(const std::string& title, bool sub = false){ stream << "<div class=\"page-header\">\n"; stream << "<h2>" << title << "</h2>\n"; stream << "</div>\n"; if(sub){ stream << "<div class=\"row\" style=\"display:flex; align-items: flex-end\">\n"; } else { stream << "<div class=\"row\">\n"; } } void after_result(){ stream << "</div>\n"; } void before_sub_graphs(std::size_t id, std::vector<std::string> graphs){ start_column("style=\"align-self: flex-start; \""); stream << "<div role=\"tabpanel\">\n"; stream << "<ul class=\"nav nav-tabs\" role=\"tablist\">\n"; std::string active = "class=\"active\""; std::size_t sub = 0; for(auto& g : graphs){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub++); stream << "<li " << active << " role=\"presentation\"><a href=\"#" << sub_id << "\" aria-controls=\"" << sub_id << "\" role=\"tab\" data-toggle=\"tab\">" << g << "</a></li>\n"; active = ""; } stream << "</ul>\n"; stream << "<div class=\"tab-content\">\n"; } void after_sub_graphs(){ stream << "</div>\n"; stream << "</div>\n"; close_column(); } void before_sub_graph(std::size_t id, std::size_t sub){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub); std::string active; if(sub == 0){ active = " active"; } stream << "<div role=\"tabpanel\" class=\"tab-pane" << active << "\" id=\"" << sub_id << "\">\n"; stream << "<div id=\"chart_" << id << "-" << sub << "\" style=\"height: 400px;\"></div>\n"; } void after_sub_graph(){ stream << "</div>\n"; } void before_summary(){ start_column(); stream << "<table class=\"table\">\n"; } void after_summary(){ stream << "</table>\n"; close_column(); } void before_sub_summary(std::size_t id, std::size_t sub){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub); std::string active; if(sub == 0){ active = " active"; } stream << "<div role=\"tabpanel\" class=\"tab-pane" << active << "\" id=\"" << sub_id << "\">\n"; stream << "<table class=\"table\">\n"; } void after_sub_summary(){ stream << "</table>\n"; stream << "</div>\n"; } void cell(const std::string& v){ stream << "<td>" << v << "</td>\n"; } void red_cell(const std::string& v){ stream << "<td class=\"danger\">"<< v << "</td>\n"; } void green_cell(const std::string& v){ stream << "<td class=\"success\">" << v << "</td>\n"; } template<typename T> bootstrap_theme& operator<<(const T& v){ stream << v; return *this; } }; } //end of namespace cpm #endif //CPM_BOOTSTRAP_THEME_HPP <commit_msg>Improve the theme<commit_after>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef CPM_BOOTSTRAP_THEME_HPP #define CPM_BOOTSTRAP_THEME_HPP #include "cpm/io.hpp" #include "cpm/data.hpp" namespace cpm { struct bootstrap_theme { const reports_data& data; cxxopts::Options& options; std::ostream& stream; std::string current_compiler; std::string current_configuration; std::size_t current_column = 0; bootstrap_theme(const reports_data& data, cxxopts::Options& options, std::ostream& stream, std::string compiler, std::string configuration) : data(data), options(options), stream(stream), current_compiler(std::move(compiler)), current_configuration(std::move(configuration)) {} void include(){ stream << "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>\n"; stream << "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\" rel=\"stylesheet\">\n"; stream << "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css\" rel=\"stylesheet\">\n"; } void header(){ stream << R"=====( <nav id="myNavbar" class="navbar navbar-default navbar-inverse navbar-fixed-top" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarCollapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Results</a> </div> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="nav navbar-nav"> <li class="active"><a href="index.html">Home</a></li> <li><a href="http://github.com/wichtounet/cpm">Generated with CPM</a></li> </ul> </div> </div> </nav> )====="; } void footer(){ stream << R"=====( <hr> <div class="row"> <div class="col-xs-12"> <footer> <p>Generated with <a href="https://github.com/wichtounet/cpm">CPM</a></p> </footer> </div> </div> </div> )====="; } void before_information(){ stream << "<div class=\"jumbotron\">\n"; stream << "<div class=\"container-fluid\">\n"; } void after_information(){ stream << "</div>\n"; stream << "</div>\n"; stream << "<div class=\"container-fluid\">\n"; } void compiler_buttons(){ stream << R"=====(<div class="row">)====="; stream << R"=====(<div class="col-xs-12">)====="; stream << R"=====(<span>Select compiler: </span>)====="; stream << R"=====(<div class="btn-group" role="group">)====="; for(auto& compiler : data.compilers){ if(compiler == current_compiler){ stream << "<a class=\"btn btn-primary\" href=\"" << cpm::filify(compiler, current_configuration) << "\">" << compiler << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << cpm::filify(compiler, current_configuration) << "\">" << compiler << "</a>\n"; } } stream << "</div>\n"; stream << "</div>\n"; stream << "</div>\n"; } void configuration_buttons(){ if(data.compilers.size() > 1){ stream << R"=====(<div class="row" style="padding-top:5px;">)====="; } else { stream << R"=====(<div class="row">)====="; } stream << R"=====(<div class="col-xs-12">)====="; stream << R"=====(<span>Select configuration: </span>)====="; stream << R"=====(<div class="btn-group" role="group">)====="; for(auto& configuration : data.configurations){ if(configuration == current_configuration){ stream << "<a class=\"btn btn-primary\" href=\"" << cpm::filify(current_compiler, configuration) << "\">" << configuration << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << cpm::filify(current_compiler, configuration) << "\">" << configuration << "</a>\n"; } } stream << "</div>\n"; stream << "</div>\n"; stream << "</div>\n"; } virtual void start_column(const std::string& style = ""){ std::size_t columns = 1; //Always the first grapah if(data.documents.size() > 1 && !options.count("disable-time")){ ++columns; } if(data.compilers.size() > 1 && !options.count("disable-compiler")){ ++columns; } if(data.configurations.size() > 1 && !options.count("disable-configuration")){ ++columns; } if(!options.count("disable-summary")){ ++columns; } if(columns < 4){ stream << "<div class=\"col-xs-" << 12 / columns << "\"" << style << ">\n"; } else if(columns == 4){ if(current_column == 2){ stream << "</div>\n"; stream << "<div class=\"row\" style=\"display:flex; margin-top: 10px;\">\n"; } stream << "<div class=\"col-xs-6\"" << style << ">\n"; } else if(columns == 5){ if(current_column == 3){ stream << "</div>\n"; stream << "<div class=\"row\" style=\"display:flex; margin-top: 10px;\">\n"; } if(current_column < 3){ stream << "<div class=\"col-xs-4\"" << style << ">\n"; } else if(current_column == 3){ stream << "<div class=\"col-xs-4\"" << style << ">\n"; } else if(current_column == 4){ stream << "<div class=\"col-xs-8\"" << style << ">\n"; } } ++current_column; } virtual void close_column(){ stream << "</div>\n"; } void before_graph(std::size_t id){ start_column(); stream << "<div id=\"chart_" << id << "\" style=\"height: 400px;\"></div>\n"; } void after_graph(){ close_column(); } void before_result(const std::string& title, bool sub = false){ stream << "<div class=\"page-header\">\n"; stream << "<h2>" << title << "</h2>\n"; stream << "</div>\n"; if(sub){ stream << "<div class=\"row\" style=\"display:flex; align-items: flex-end\">\n"; } else { stream << "<div class=\"row\">\n"; } current_column = 0; } void after_result(){ stream << "</div>\n"; } void before_sub_graphs(std::size_t id, std::vector<std::string> graphs){ start_column("style=\"align-self: flex-start; \""); stream << "<div role=\"tabpanel\">\n"; stream << "<ul class=\"nav nav-tabs\" role=\"tablist\">\n"; std::string active = "class=\"active\""; std::size_t sub = 0; for(auto& g : graphs){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub++); stream << "<li " << active << " role=\"presentation\"><a href=\"#" << sub_id << "\" aria-controls=\"" << sub_id << "\" role=\"tab\" data-toggle=\"tab\">" << g << "</a></li>\n"; active = ""; } stream << "</ul>\n"; stream << "<div class=\"tab-content\">\n"; } void after_sub_graphs(){ stream << "</div>\n"; stream << "</div>\n"; close_column(); } void before_sub_graph(std::size_t id, std::size_t sub){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub); std::string active; if(sub == 0){ active = " active"; } stream << "<div role=\"tabpanel\" class=\"tab-pane" << active << "\" id=\"" << sub_id << "\">\n"; stream << "<div id=\"chart_" << id << "-" << sub << "\" style=\"height: 400px;\"></div>\n"; } void after_sub_graph(){ stream << "</div>\n"; } void before_summary(){ start_column(); stream << "<table class=\"table\">\n"; } void after_summary(){ stream << "</table>\n"; close_column(); } void before_sub_summary(std::size_t id, std::size_t sub){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub); std::string active; if(sub == 0){ active = " active"; } stream << "<div role=\"tabpanel\" class=\"tab-pane" << active << "\" id=\"" << sub_id << "\">\n"; stream << "<table class=\"table\">\n"; } void after_sub_summary(){ stream << "</table>\n"; stream << "</div>\n"; } void cell(const std::string& v){ stream << "<td>" << v << "</td>\n"; } void red_cell(const std::string& v){ stream << "<td class=\"danger\">"<< v << "</td>\n"; } void green_cell(const std::string& v){ stream << "<td class=\"success\">" << v << "</td>\n"; } template<typename T> bootstrap_theme& operator<<(const T& v){ stream << v; return *this; } }; } //end of namespace cpm #endif //CPM_BOOTSTRAP_THEME_HPP <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: gtkdata.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-05-10 15:54:49 $ * * 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: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _VCL_GTKDATA_HXX #define _VCL_GTKDATA_HXX #include <prex.h> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <gtk/gtk.h> #include <postx.h> #include <saldisp.hxx> #include <saldata.hxx> #include <ptrstyle.hxx> #include <list> class GtkData : public SalData { public: GtkData() {} virtual ~GtkData(); virtual void Init(); virtual void initNWF(); virtual void deInitNWF(); }; class GtkSalFrame; class GtkSalDisplay : public SalDisplay { GdkDisplay* m_pGdkDisplay; GdkCursor *m_aCursors[ POINTER_COUNT ]; GdkCursor* getFromXPM( const char *pBitmap, const char *pMask, int nWidth, int nHeight, int nXHot, int nYHot ); public: GtkSalDisplay( GdkDisplay* pDisplay, Visual* pVis, Colormap aCol ); virtual ~GtkSalDisplay(); GdkDisplay* GetGdkDisplay() const { return m_pGdkDisplay; } virtual void deregisterFrame( SalFrame* pFrame ); GdkCursor *getCursor( PointerStyle ePointerStyle ); virtual int CaptureMouse( SalFrame* pFrame ); virtual long Dispatch( XEvent *pEvent ); static GdkFilterReturn filterGdkEvent( GdkXEvent* sys_event, GdkEvent* event, gpointer data ); inline bool HasMoreEvents() { return m_aUserEvents.size() > 1; } inline void EventGuardAcquire() { osl_acquireMutex( hEventGuard_ ); } inline void EventGuardRelease() { osl_releaseMutex( hEventGuard_ ); } }; #endif // _VCL_GTKDATA_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.454); FILE MERGED 2005/09/05 14:45:33 rt 1.3.454.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gtkdata.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:51:01 $ * * 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 * ************************************************************************/ #ifndef _VCL_GTKDATA_HXX #define _VCL_GTKDATA_HXX #include <prex.h> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <gtk/gtk.h> #include <postx.h> #include <saldisp.hxx> #include <saldata.hxx> #include <ptrstyle.hxx> #include <list> class GtkData : public SalData { public: GtkData() {} virtual ~GtkData(); virtual void Init(); virtual void initNWF(); virtual void deInitNWF(); }; class GtkSalFrame; class GtkSalDisplay : public SalDisplay { GdkDisplay* m_pGdkDisplay; GdkCursor *m_aCursors[ POINTER_COUNT ]; GdkCursor* getFromXPM( const char *pBitmap, const char *pMask, int nWidth, int nHeight, int nXHot, int nYHot ); public: GtkSalDisplay( GdkDisplay* pDisplay, Visual* pVis, Colormap aCol ); virtual ~GtkSalDisplay(); GdkDisplay* GetGdkDisplay() const { return m_pGdkDisplay; } virtual void deregisterFrame( SalFrame* pFrame ); GdkCursor *getCursor( PointerStyle ePointerStyle ); virtual int CaptureMouse( SalFrame* pFrame ); virtual long Dispatch( XEvent *pEvent ); static GdkFilterReturn filterGdkEvent( GdkXEvent* sys_event, GdkEvent* event, gpointer data ); inline bool HasMoreEvents() { return m_aUserEvents.size() > 1; } inline void EventGuardAcquire() { osl_acquireMutex( hEventGuard_ ); } inline void EventGuardRelease() { osl_releaseMutex( hEventGuard_ ); } }; #endif // _VCL_GTKDATA_HXX <|endoftext|>
<commit_before>/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-12-09 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue : private scheduler::FifoQueueBase { public: /// type of uninitialized storage for data using Storage = Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : FifoQueueBase{storage, maxElements, TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return FifoQueueBase::pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return FifoQueueBase::push(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(T&& value) { return FifoQueueBase::push(std::move(value)); } /** * \brief Tries to pop the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::tryPop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPop(T& value) { return FifoQueueBase::tryPop(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(const T& value) { return FifoQueueBase::tryPush(value); } }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ <commit_msg>FifoQueue: add FifoQueue::tryPush(T&&)<commit_after>/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-12-09 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue : private scheduler::FifoQueueBase { public: /// type of uninitialized storage for data using Storage = Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : FifoQueueBase{storage, maxElements, TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return FifoQueueBase::pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return FifoQueueBase::push(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(T&& value) { return FifoQueueBase::push(std::move(value)); } /** * \brief Tries to pop the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::tryPop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPop(T& value) { return FifoQueueBase::tryPop(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(const T& value) { return FifoQueueBase::tryPush(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(T&& value) { return FifoQueueBase::tryPush(std::move(value)); } }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ <|endoftext|>
<commit_before>/** * Jsonpack - Reals traits for json operations * * Copyright (c) 2015 Yadiel Martinez Gonzalez <ymglez2015@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef JSONPACK_REALS_HPP #define JSONPACK_REALS_HPP #include "jsonpack/type/json_traits_base.hpp" JSONPACK_API_BEGIN_NAMESPACE TYPE_BEGIN_NAMESPACE //-------------------------- FLOAT -------------------------------- template<> struct json_traits<float> { static void append(buffer &json, const char *key, const float &value) { util::json_builder::append_real(json, key, value); } static void append(buffer &json, const float &value) { util::json_builder::append_real(json, value); } }; template<> struct json_traits<float&> { static void extract(const object_t &json, char* json_ptr, const char *key, const std::size_t &len, float &value) { jsonpack::key k; k._bytes = len; k._ptr = key; object_t::const_iterator found = json.find(k); if( found != json.end() ) // exist the current key { if( match_token_type(found->second) ) { extract(found->second, json_ptr, value); } else { std::string msg = "Invalid float value for key: "; msg += key; throw type_error( msg.data() ); } } } static void extract(const jsonpack::value &v, char* json_ptr, float &value) { position p = v._pos; char * str_value = json_ptr+p._pos; //pointing to the start char buffer[DOUBLE_MAX_DIGITS + 1]; memcpy(buffer, str_value, p._count < DOUBLE_MAX_DIGITS + 1 ? p._count : DOUBLE_MAX_DIGITS + 1); buffer[p._count] = '\0'; //null-terminated #ifndef _MSC_VER value = std::strtof(buffer, nullptr); if(errno) // check range throw type_error("Float out of range"); #else double v_cpy = std::strtod(buffer, nullptr); if(errno || v_cpy > std::numeric_limits<float>::max() || v_cpy < std::numeric_limits<float>::min() ) throw type_error("Float out of range"); value = static_cast<float>(v_cpy); #endif } static bool match_token_type(const jsonpack::value &v) { return (v._field == _POS && (v._pos._type == JTK_INTEGER || v._pos._type == JTK_REAL ) ); } }; //-------------------------- DOUBLE -------------------------------- template<> struct json_traits<double> { static void append(buffer &json, const char *key, const double &value) { util::json_builder::append_real(json, key, value); } static void append(buffer &json, const double &value) { util::json_builder::append_real(json, value); } }; template<> struct json_traits<double&> { static void extract(const object_t &json, char* json_ptr, const char *key, const std::size_t &len, double &value) { jsonpack::key k; k._bytes = len; k._ptr = key; object_t::const_iterator found = json.find(k); if( found != json.end() ) // exist the current key { if( match_token_type(found->second) ) { extract(found->second, json_ptr, value); } else { std::string msg = "Invalid double value for key: "; msg += key; throw type_error( msg.data() ); } } } static void extract(const jsonpack::value &v, char* json_ptr, double &value) { position p = v._pos; char * str_value = json_ptr+p._pos; //pointing to the start char buffer[DOUBLE_MAX_DIGITS + 1]; memcpy(buffer, str_value, p._count < DOUBLE_MAX_DIGITS + 1 ? p._count : DOUBLE_MAX_DIGITS + 1); buffer[p._count] = '\0'; //null-terminated value = std::strtod(buffer, nullptr); if(errno) // check range throw type_error("Double out of range"); } static bool match_token_type(const jsonpack::value &v) { return (v._field == _POS && (v._pos._type == JTK_INTEGER || v._pos._type == JTK_REAL ) ); } }; JSONPACK_API_END_NAMESPACE //type JSONPACK_API_END_NAMESPACE //jsonpack #endif // JSONPACK_REALS_HPP <commit_msg>Fix size check in reals<commit_after>/** * Jsonpack - Reals traits for json operations * * Copyright (c) 2015 Yadiel Martinez Gonzalez <ymglez2015@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef JSONPACK_REALS_HPP #define JSONPACK_REALS_HPP #include "jsonpack/type/json_traits_base.hpp" JSONPACK_API_BEGIN_NAMESPACE TYPE_BEGIN_NAMESPACE //-------------------------- FLOAT -------------------------------- template<> struct json_traits<float> { static void append(buffer &json, const char *key, const float &value) { util::json_builder::append_real(json, key, value); } static void append(buffer &json, const float &value) { util::json_builder::append_real(json, value); } }; template<> struct json_traits<float&> { static void extract(const object_t &json, char* json_ptr, const char *key, const std::size_t &len, float &value) { jsonpack::key k; k._bytes = len; k._ptr = key; object_t::const_iterator found = json.find(k); if( found != json.end() ) // exist the current key { if( match_token_type(found->second) ) { extract(found->second, json_ptr, value); } else { std::string msg = "Invalid float value for key: "; msg += key; throw type_error( msg.data() ); } } } static void extract(const jsonpack::value &v, char* json_ptr, float &value) { position p = v._pos; char * str_value = json_ptr + p._pos; //pointing to the start char buffer[DOUBLE_MAX_DIGITS + 1]; const unsigned long len = p._count < DOUBLE_MAX_DIGITS + 1 ? p._count : DOUBLE_MAX_DIGITS ; memcpy(buffer, str_value, len); buffer[len] = '\0'; //null-terminated #ifndef _MSC_VER value = std::strtof(buffer, nullptr); if(errno) // check range throw type_error("Float out of range"); #else double v_cpy = std::strtod(buffer, nullptr); if(errno || v_cpy > std::numeric_limits<float>::max() || v_cpy < std::numeric_limits<float>::min() ) throw type_error("Float out of range"); value = static_cast<float>(v_cpy); #endif } static bool match_token_type(const jsonpack::value &v) { return (v._field == _POS && (v._pos._type == JTK_INTEGER || v._pos._type == JTK_REAL ) ); } }; //-------------------------- DOUBLE -------------------------------- template<> struct json_traits<double> { static void append(buffer &json, const char *key, const double &value) { util::json_builder::append_real(json, key, value); } static void append(buffer &json, const double &value) { util::json_builder::append_real(json, value); } }; template<> struct json_traits<double&> { static void extract(const object_t &json, char* json_ptr, const char *key, const std::size_t &len, double &value) { jsonpack::key k; k._bytes = len; k._ptr = key; object_t::const_iterator found = json.find(k); if( found != json.end() ) // exist the current key { if( match_token_type(found->second) ) { extract(found->second, json_ptr, value); } else { std::string msg = "Invalid double value for key: "; msg += key; throw type_error( msg.data() ); } } } static void extract(const jsonpack::value &v, char* json_ptr, double &value) { position p = v._pos; char * str_value = json_ptr + p._pos; //pointing to the start char buffer[DOUBLE_MAX_DIGITS + 1]; const unsigned long len = p._count < DOUBLE_MAX_DIGITS + 1 ? p._count : DOUBLE_MAX_DIGITS ; memcpy(buffer, str_value, len); buffer[len] = '\0'; //null-terminated value = std::strtod(buffer, nullptr); if(errno) // check range throw type_error("Double out of range"); } static bool match_token_type(const jsonpack::value &v) { return (v._field == _POS && (v._pos._type == JTK_INTEGER || v._pos._type == JTK_REAL ) ); } }; JSONPACK_API_END_NAMESPACE //type JSONPACK_API_END_NAMESPACE //jsonpack #endif // JSONPACK_REALS_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2013, Arvid Norberg 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 author 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. */ #ifndef TORRENT_IP_VOTER_HPP_INCLUDED #define TORRENT_IP_VOTER_HPP_INCLUDED #include <vector> #include "libtorrent/address.hpp" #include "libtorrent/bloom_filter.hpp" namespace libtorrent { // this is an object that keeps the state for a single external IP // based on peoples votes struct TORRENT_EXTRA_EXPORT ip_voter { // returns true if a different IP is the top vote now // i.e. we changed our idea of what our external IP is bool cast_vote(address const& ip, int source_type, address const& sorce); address external_address() const { return m_external_address; } private: struct external_ip_t { external_ip_t(): sources(0), num_votes(0) {} bool add_vote(sha1_hash const& k, int type); bool operator<(external_ip_t const& rhs) const { if (num_votes < rhs.num_votes) return true; if (num_votes > rhs.num_votes) return false; return sources < rhs.sources; } // this is a bloom filter of the IPs that have // reported this address bloom_filter<16> voters; // this is the actual external address address addr; // a bitmask of sources the reporters have come from boost::uint16_t sources; // the total number of votes for this IP boost::uint16_t num_votes; }; // this is a bloom filter of all the IPs that have // been the first to report an external address. Each // IP only gets to add a new item once. bloom_filter<32> m_external_address_voters; std::vector<external_ip_t> m_external_addresses; address m_external_address; }; // this keeps track of multiple external IPs (for now, just IPv6 and IPv4, but // it could be extended to deal with loopback and local network addresses as well) struct external_ip { // returns true if a different IP is the top vote now // i.e. we changed our idea of what our external IP is bool cast_vote(address const& ip, int source_type, address const& source); // the external IP as it would be observed from `ip` address external_address(address const& ip) const; private: // for now, assume one external IPv4 and one external IPv6 address // 0 = IPv4 1 = IPv6 // TODO: instead, have one instance per possible subnet, global IPv4, global IPv6, loopback, 192.168.x.x, 10.x.x.x, etc. ip_voter m_vote_group[2]; }; } #endif <commit_msg>fix mingw test link issue<commit_after>/* Copyright (c) 2013, Arvid Norberg 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 author 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. */ #ifndef TORRENT_IP_VOTER_HPP_INCLUDED #define TORRENT_IP_VOTER_HPP_INCLUDED #include <vector> #include "libtorrent/address.hpp" #include "libtorrent/bloom_filter.hpp" namespace libtorrent { // this is an object that keeps the state for a single external IP // based on peoples votes struct TORRENT_EXTRA_EXPORT ip_voter { // returns true if a different IP is the top vote now // i.e. we changed our idea of what our external IP is bool cast_vote(address const& ip, int source_type, address const& sorce); address external_address() const { return m_external_address; } private: struct external_ip_t { external_ip_t(): sources(0), num_votes(0) {} bool add_vote(sha1_hash const& k, int type); bool operator<(external_ip_t const& rhs) const { if (num_votes < rhs.num_votes) return true; if (num_votes > rhs.num_votes) return false; return sources < rhs.sources; } // this is a bloom filter of the IPs that have // reported this address bloom_filter<16> voters; // this is the actual external address address addr; // a bitmask of sources the reporters have come from boost::uint16_t sources; // the total number of votes for this IP boost::uint16_t num_votes; }; // this is a bloom filter of all the IPs that have // been the first to report an external address. Each // IP only gets to add a new item once. bloom_filter<32> m_external_address_voters; std::vector<external_ip_t> m_external_addresses; address m_external_address; }; // this keeps track of multiple external IPs (for now, just IPv6 and IPv4, but // it could be extended to deal with loopback and local network addresses as well) struct TORRENT_EXTRA_EXPORT external_ip { // returns true if a different IP is the top vote now // i.e. we changed our idea of what our external IP is bool cast_vote(address const& ip, int source_type, address const& source); // the external IP as it would be observed from `ip` address external_address(address const& ip) const; private: // for now, assume one external IPv4 and one external IPv6 address // 0 = IPv4 1 = IPv6 // TODO: instead, have one instance per possible subnet, global IPv4, global IPv6, loopback, 192.168.x.x, 10.x.x.x, etc. ip_voter m_vote_group[2]; }; } #endif <|endoftext|>
<commit_before>// Flaschenautomazt.v.6.0.cpp : Definiert den Einstiegspunkt fr die Konsolenanwendung. // #include "stdafx.h" #include <iostream> using namespace std; int auswahlGetraenkeSorte(); int eingabeMenge(); float ermittlePreis(int sorte); void bezahlen (float zuZahlen); void ausgabeGetraenke(int sorte, int menge); int main() { cout << "Getraenkeautomat v.6.0" << endl; int sorte, menge, bezahlen; float preis, zuZahlen; sorte = auswahlGetraenkeSorte(); preis = ermittlePreis(sorte); menge = eingabeMenge(); zuZahlen = preis * menge; float bezahlen(zuZahlen); ausgabeGetraenke(sorte, menge); cout << "Vielen Dank, bitte entnehmen Sie ihre Getrnke" << endl; getchar(); getchar(); return 0; } // Funktionen int auswahlGetraenkeSorte() { int sorte; cout("Waehlen sie ihr Getraenk aus:\n"); cout("1) Wasser (0,50 Euro)\n"); cout("2) Limonade (1,00 Euro)\n"); cout("3) Bier (2,00 Euro)\n\n"); cout("Geben sie 1, 2 oder 3 ein: "); cin >> sorte; return sorte; } int eingabeMenge() { int menge = 1; cout << "Geben sie die gewuenschte Menge ein: "; cin >> menge; return menge; } /* ermittelt den Preis zu einer Sorte Parameter: sorte, Nummer der Sorte Return-Value: Preis */ float ermittlePreis(int sorte) { float preis = 0; switch (sorte) { case 1: preis = 0.5; break; case 2: preis = 1.0; break; case 3: preis = 2.0; break; } return preis; } bool bezahlen (float zuZahlen) { cout << "--- Bezahlvorgang ---" << endl; cout << "Bezahlvorgang abbrechen mit 0"; float einwurf; do { cout << "Es fehlen noch " << zuZahlen <<" Euro."; cout << "Bitte werfen sie ein Geldstueck ein: "; cin >>einwurf; // eingeworfenen Betrag anrechnen zuZahlen -= einwurf; } while (zuZahlen > 0.0); return true; } void ausgabeGetraenke(int sorte, int menge) { cout << "--- Getraenkeausgabe ---" <<endl; int i; for (i = 0; i < menge; i++) { cout << " Flasche " << i << "von " << menge << " der Sorte " << sorte << " wurde ausgegeben.", i + 1, menge, sorte; } } <commit_msg>fixed and done<commit_after>// Flaschenautomazt.v.6.0.cpp : Definiert den Einstiegspunkt fr die Konsolenanwendung. // #include "stdafx.h" #include <iostream> using namespace std; int auswahlGetraenkeSorte(); int eingabeMenge(); float ermittlePreis(int sorte); void bezahlen (float zuZahlen); void ausgabeGetraenke(int sorte, int menge); int main() { cout << "Getraenkeautomat v.6.0" << endl; int sorte, menge; float preis, zuZahlen; sorte = auswahlGetraenkeSorte(); preis = ermittlePreis(sorte); menge = eingabeMenge(); zuZahlen = preis * menge; bezahlen (zuZahlen); ausgabeGetraenke(sorte, menge); cout << "Vielen Dank, bitte entnehmen Sie ihre Getrnke" << endl; getchar(); getchar(); return 0; } // Funktionen int auswahlGetraenkeSorte() { int sorte; cout <<"Waehlen sie ihr Getraenk aus:\n"; cout <<"1) Wasser (0,50 Euro)\n"; cout <<"2) Limonade (1,00 Euro)\n"; cout <<"3) Bier (2,00 Euro)\n\n"; cout <<"Geben sie 1, 2 oder 3 ein: "; cin >> sorte; return sorte; } int eingabeMenge() { int menge = 1; cout << "Geben sie die gewuenschte Menge ein: "; cin >> menge; return menge; } /* ermittelt den Preis zu einer Sorte Parameter: sorte, Nummer der Sorte Return-Value: Preis */ float ermittlePreis(int sorte) { float preis = 0; switch (sorte) { case 1: preis = 0.5; break; case 2: preis = 1.0; break; case 3: preis = 2.0; break; } return preis; } void bezahlen (float zuZahlen) { cout << "--- Bezahlvorgang ---" << endl; cout << "Bezahlvorgang abbrechen mit 0"; float einwurf; do { cout << "Es fehlen noch " << zuZahlen <<" Euro."; cout << "Bitte werfen sie ein Geldstueck ein: "; cin >>einwurf; // eingeworfenen Betrag anrechnen zuZahlen -= einwurf; } while (zuZahlen > 0.0); return; } void ausgabeGetraenke(int sorte, int menge) { cout << "--- Getraenkeausgabe ---" <<endl; int i; for (i = 0; i < menge; i++) { cout << " Flasche " << i << "von " << menge << " der Sorte " << sorte << " wurde ausgegeben.", i + 1, menge, sorte; } } <|endoftext|>
<commit_before>#ifndef __MIPSSIMULATOR_PROCESSOR_MIPSPROCESSOR_HPP_ #define __MIPSSIMULATOR_PROCESSOR_MIPSPROCESSOR_HPP_ #include <function> #include <map> #include <string> #include <os/os.hpp> #include <processor/memory.hpp> #include <processor/register/register_file.hpp> #include <processor/register/register.hpp> // These are the states the processor can be in. #define MIPS_IF 0 #define MIPS_ID 1 #define MIPS_EX 2 #define MIPS_MEM 3 #define MIPS_WB 4 class MIPSProcessor { public: // CONSTRUCTORS /** * @brief Construct a MIPS processor with references to the necessary * components. * * @param[in] */ MIPSProcessor (Memory& memory, RegisterFile& register_file); // DESTRUCTORS /** * @brief Destructor. */ ~MIPSProcessor (); // FUNCTIONS // /** // * @brief Begin execution. // * // * Start executing the program that was loaded into memory (this must be // * done by the <code>OS</code>). // */ // void // begin_execution (); /** * @brief Execute the functionality at the current state this * <code>MIPSProcessor</code> is in. */ void tick (); private: // Friend required classes. friend class RegisterFile; // FUNCTIONS /** * @brief What this processor does in the if state. */ void mips_if (); /** * @brief What this processor does in the id state. */ void mips_id (); /** * @brief What this processor does in the ex state. */ void mips_ex (); /** * @brief What this processor does in the mem state. */ void mips_mem (); /** * @brief What this processor does in the wb state. */ void mips_wb (); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS add operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_add (Register& rd, const Register& rs, const Register& rt); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS addi operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] immediate The immediate. */ void mips_addi (Register& rd, const Register& rs, int immediate); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS addiu operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] immediate The immediate. */ void mips_addiu (Register& rd, const Register& rs, unsigned immediate); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS addu operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_addu (Register& rd, const Register& rs, const Register& rt); /** * @brief if (R[rs] == R[rt]) PC = PC + 4 + BranchAddr * MIPS beq operation. * @param[in] rs The first source register. * @param[in] rt The second source register. * @param[in] branch_address The branch address. */ void mips_beq (const Register& rs, const Register& rt, unsigned branch_address); /** * @brief PC = JumpAddr * MIPS j operation. * @param[in] jump_address The jump address. */ void mips_j (unsigned jump_address); /** * @brief R[31] = PC + 8; PC = JumpAddr * MIPS jal operation. * @param[in] jump_address The jump address. */ void mips_jal (unsigned jump_address); /** * @brief PC = R[rs] * MIPS jal operation. * @param[in] rs The source register. */ void mips_jr (const Register& rs); /** * @brief R[rt] = {imm, 16'b0} * MIPS lui operation. * @param[out] rt The destination register. * @param[in] rs The source register. * @param[in] immediate The immediate. */ void mips_lui (Register& rt, const Register& rs, unsigned immediate); /** * @brief R[rt] = M[R[rs] + SignExtImm] * MIPS lw operation. * @param[out] rt The destination register. * @param[in] rs The source register. * @param[in] offset The offset (default <code>0</code>).. */ void mips_lw (Register& rt, const Register& rs, int offset = 0); /** * @brief R[rd] = Hi * MIPS mfhi operation. * @param[out] rd The destination register. */ void mips_mfhi (Register& rd); /** * @brief R[rd] = Lo * MIPS mflo operation. * @param[out] rd The destination register. */ void mips_mflo (Register& rd); /** * @brief {Hi, Lo} = R[rs] * R[rt] * MIPS mult operation. * @param[out] rs The first source register. * @param[out] rt The second source register. */ void mips_mult (const Register& rs, const Register& rt); /** * @brief R[rd] = R[rs] | ZeroExtImm * MIPS ori operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] immediate The immediate. */ void mips_ori (Register& rd, const Register& rs, unsigned immediate); /** * @brief R[rd] = R[rs] << shamt * MIPS sll operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] shamt The shift amount. */ void mips_sll (Register& rd, const Register& rs, unsigned shamt); /** * @brief R[rd] = (R[rs] < R[rt]) ? 1 : 0 * MIPS slt operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_slt (Register& rd, const Register& rs, const Register& rt); /** * @brief R[rd] = (R[rs] < SignExtImm) ? 1 : 0 * MIPS slti operation. * @param[out] rd The destination register. * @param[in] rs The source register. * @param[in] immediate The immediate. */ void mips_slti (Register& rd, const Register& rs, int immediate); /** * @brief R[rd] = R[rs] - SignExtImm * MIPS sub operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_sub (Register& rd, const Register& rs, const Register& rt); /** * @brief R[rd] = R[rs] - SignExtImm * MIPS subu operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_subu (Register& rd, const Register& rs, const Register& rt); /** * @brief M[R[rs] + SignExtImm] = R[rt] * MIPS sw operation. * @param[out] rt The destination register. * @param[in] rs The source register. * @param[in] offset The offset (default <code>0</code>).. */ void mips_sw (const Register& rt, const Register& rs, int offset = 0); /** * @brief MIPS syscall operation. */ void mips_syscall (); /** * @brief Exit simulation. * * Transfer control to the OS and exit this simulation. */ void mips_syscall_exit (); // VARIABLES /** The state in the instruction pipeline we are in. */ int m_processor_state; /** The memory for this <code>MIPSProcessor</code>. */ Memory& m_memory; /** The register file for this <code>MIPSProcessor</code>. */ RegisterFile& m_register_file; /** The functions at each state in this <code>MIPSProcessor</code>. */ std::map<std::string, std::function<void()> > m_state_functions; /** The operations that this <code>MIPSProcessor</code> supports. */ std::map<std::string, std::function<void()> > m_operations; /** The syscalls that this <code>MIPSProcessor</code> supports. */ std::map<int, std::function<void()> > m_syscalls; // Temporary registers. }; #endif // __MIPSSIMULATOR_PROCESSOR_MIPSPROCESSOR_HPP_ <commit_msg>Refactoring...<commit_after>#ifndef __MIPSSIMULATOR_PROCESSOR_MIPSPROCESSOR_HPP_ #define __MIPSSIMULATOR_PROCESSOR_MIPSPROCESSOR_HPP_ #include <function> #include <map> #include <string> #include <os/os.hpp> #include <processor/memory.hpp> #include <processor/register/register_file.hpp> #include <processor/register/register.hpp> // These are the states the processor can be in. #define MIPS_IF 0 #define MIPS_ID 1 #define MIPS_EX 2 #define MIPS_MEM 3 #define MIPS_WB 4 class MIPSProcessor { public: // CONSTRUCTORS /** * @brief Construct a MIPS processor with references to the necessary * components. * * @param[in] */ MIPSProcessor (Memory& memory, RegisterFile& register_file); // DESTRUCTORS /** * @brief Destructor. */ ~MIPSProcessor (); // FUNCTIONS /** * @brief Execute the functionality at the current state this * <code>MIPSProcessor</code> is in. */ void tick (); private: // Friend required classes. friend class RegisterFile; // FUNCTIONS /** * @brief What this processor does in the if state. */ void mips_if (); /** * @brief What this processor does in the id state. */ void mips_id (); /** * @brief What this processor does in the ex state. */ void mips_ex (); /** * @brief What this processor does in the mem state. */ void mips_mem (); /** * @brief What this processor does in the wb state. */ void mips_wb (); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS add operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_add (Register& rd, const Register& rs, const Register& rt); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS addi operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] immediate The immediate. */ void mips_addi (Register& rd, const Register& rs, int immediate); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS addiu operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] immediate The immediate. */ void mips_addiu (Register& rd, const Register& rs, unsigned immediate); /** * @brief R[rd] = R[rs] + SignExtImm * MIPS addu operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_addu (Register& rd, const Register& rs, const Register& rt); /** * @brief if (R[rs] == R[rt]) PC = PC + 4 + BranchAddr * MIPS beq operation. * @param[in] rs The first source register. * @param[in] rt The second source register. * @param[in] branch_address The branch address. */ void mips_beq (const Register& rs, const Register& rt, unsigned branch_address); /** * @brief PC = JumpAddr * MIPS j operation. * @param[in] jump_address The jump address. */ void mips_j (unsigned jump_address); /** * @brief R[31] = PC + 8; PC = JumpAddr * MIPS jal operation. * @param[in] jump_address The jump address. */ void mips_jal (unsigned jump_address); /** * @brief PC = R[rs] * MIPS jal operation. * @param[in] rs The source register. */ void mips_jr (const Register& rs); /** * @brief R[rt] = {imm, 16'b0} * MIPS lui operation. * @param[out] rt The destination register. * @param[in] rs The source register. * @param[in] immediate The immediate. */ void mips_lui (Register& rt, const Register& rs, unsigned immediate); /** * @brief R[rt] = M[R[rs] + SignExtImm] * MIPS lw operation. * @param[out] rt The destination register. * @param[in] rs The source register. * @param[in] offset The offset (default <code>0</code>).. */ void mips_lw (Register& rt, const Register& rs, int offset = 0); /** * @brief R[rd] = Hi * MIPS mfhi operation. * @param[out] rd The destination register. */ void mips_mfhi (Register& rd); /** * @brief R[rd] = Lo * MIPS mflo operation. * @param[out] rd The destination register. */ void mips_mflo (Register& rd); /** * @brief {Hi, Lo} = R[rs] * R[rt] * MIPS mult operation. * @param[out] rs The first source register. * @param[out] rt The second source register. */ void mips_mult (const Register& rs, const Register& rt); /** * @brief R[rd] = R[rs] | ZeroExtImm * MIPS ori operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] immediate The immediate. */ void mips_ori (Register& rd, const Register& rs, unsigned immediate); /** * @brief R[rd] = R[rs] << shamt * MIPS sll operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] shamt The shift amount. */ void mips_sll (Register& rd, const Register& rs, unsigned shamt); /** * @brief R[rd] = (R[rs] < R[rt]) ? 1 : 0 * MIPS slt operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_slt (Register& rd, const Register& rs, const Register& rt); /** * @brief R[rd] = (R[rs] < SignExtImm) ? 1 : 0 * MIPS slti operation. * @param[out] rd The destination register. * @param[in] rs The source register. * @param[in] immediate The immediate. */ void mips_slti (Register& rd, const Register& rs, int immediate); /** * @brief R[rd] = R[rs] - SignExtImm * MIPS sub operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_sub (Register& rd, const Register& rs, const Register& rt); /** * @brief R[rd] = R[rs] - SignExtImm * MIPS subu operation. * @param[out] rd The destination register. * @param[in] rs The first source register. * @param[in] rt The second source register. */ void mips_subu (Register& rd, const Register& rs, const Register& rt); /** * @brief M[R[rs] + SignExtImm] = R[rt] * MIPS sw operation. * @param[out] rt The destination register. * @param[in] rs The source register. * @param[in] offset The offset (default <code>0</code>).. */ void mips_sw (const Register& rt, const Register& rs, int offset = 0); /** * @brief MIPS syscall operation. */ void mips_syscall (); /** * @brief Exit simulation. * * Transfer control to the OS and exit this simulation. */ void mips_syscall_exit (); // VARIABLES /** The state in the instruction pipeline we are in. */ int m_processor_state; /** The memory for this <code>MIPSProcessor</code>. */ Memory& m_memory; /** The register file for this <code>MIPSProcessor</code>. */ RegisterFile& m_register_file; /** The functions at each state in this <code>MIPSProcessor</code>. */ std::map<std::string, std::function<void()> > m_state_functions; /** The operations that this <code>MIPSProcessor</code> supports. */ std::map<std::string, std::function<void()> > m_operations; /** The syscalls that this <code>MIPSProcessor</code> supports. */ std::map<int, std::function<void()> > m_syscalls; // Temporary registers. }; #endif // __MIPSSIMULATOR_PROCESSOR_MIPSPROCESSOR_HPP_ <|endoftext|>
<commit_before>#ifndef PROTOZERO_DATA_VIEW_HPP #define PROTOZERO_DATA_VIEW_HPP /***************************************************************************** protozero - Minimalistic protocol buffer decoder and encoder in C++. This file is from https://github.com/mapbox/protozero where you can find more documentation. *****************************************************************************/ /** * @file data_view.hpp * * @brief Contains the implementation of the data_view class. */ #include <algorithm> #include <cstddef> #include <cstring> #include <string> #include <utility> #include <protozero/config.hpp> namespace protozero { #ifdef PROTOZERO_USE_VIEW using data_view = PROTOZERO_USE_VIEW; #else /** * Holds a pointer to some data and a length. * * This class is supposed to be compatible with the std::string_view * that will be available in C++17. */ class data_view { const char* m_data = nullptr; std::size_t m_size = 0; public: /** * Default constructor. Construct an empty data_view. */ constexpr data_view() noexcept = default; /** * Create data_view from pointer and size. * * @param ptr Pointer to the data. * @param length Length of the data. */ constexpr data_view(const char* ptr, std::size_t length) noexcept : m_data(ptr), m_size(length) { } /** * Create data_view from string. * * @param str String with the data. */ data_view(const std::string& str) noexcept // NOLINT clang-tidy: google-explicit-constructor : m_data(str.data()), m_size(str.size()) { } /** * Create data_view from zero-terminated string. * * @param ptr Pointer to the data. */ data_view(const char* ptr) noexcept // NOLINT clang-tidy: google-explicit-constructor : m_data(ptr), m_size(std::strlen(ptr)) { } /** * Swap the contents of this object with the other. * * @param other Other object to swap data with. */ void swap(data_view& other) noexcept { using std::swap; swap(m_data, other.m_data); swap(m_size, other.m_size); } /// Return pointer to data. constexpr const char* data() const noexcept { return m_data; } /// Return length of data in bytes. constexpr std::size_t size() const noexcept { return m_size; } /// Returns true if size is 0. constexpr bool empty() const noexcept { return m_size == 0; } #ifndef PROTOZERO_STRICT_API /** * Convert data view to string. * * @pre Must not be default constructed data_view. * * @deprecated to_string() is not available in C++17 string_view so it * should not be used to make conversion to that class easier * in the future. */ std::string to_string() const { protozero_assert(m_data); return {m_data, m_size}; } #endif /** * Convert data view to string. * * @pre Must not be default constructed data_view. */ explicit operator std::string() const { protozero_assert(m_data); return {m_data, m_size}; } /** * Compares the contents of this object with the given other object. * * @returns 0 if they are the same, <0 if this object is smaller than * the other or >0 if it is larger. If both objects have the * same size returns <0 if this object is lexicographically * before the other, >0 otherwise. * * @pre Must not be default constructed data_view. */ int compare(data_view other) const { protozero_assert(m_data && other.m_data); const int cmp = std::memcmp(data(), other.data(), std::min(size(), other.size())); if (cmp == 0) { if (size() == other.size()) { return 0; } return size() < other.size() ? -1 : 1; } return cmp; } }; // class data_view /** * Swap two data_view objects. * * @param lhs First object. * @param rhs Second object. */ inline void swap(data_view& lhs, data_view& rhs) noexcept { lhs.swap(rhs); } /** * Two data_view instances are equal if they have the same size and the * same content. * * @param lhs First object. * @param rhs Second object. */ inline bool operator==(const data_view lhs, const data_view rhs) noexcept { return lhs.size() == rhs.size() && std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data()); } /** * Two data_view instances are not equal if they have different sizes or the * content differs. * * @param lhs First object. * @param rhs Second object. */ inline bool operator!=(const data_view lhs, const data_view rhs) noexcept { return !(lhs == rhs); } /** * Returns true if lhs.compare(rhs) < 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator<(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) < 0; } /** * Returns true if lhs.compare(rhs) <= 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator<=(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) <= 0; } /** * Returns true if lhs.compare(rhs) > 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator>(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) > 0; } /** * Returns true if lhs.compare(rhs) >= 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator>=(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) >= 0; } #endif } // end namespace protozero #endif // PROTOZERO_DATA_VIEW_HPP <commit_msg>Make operator== and operator!= on data_view constexpr.<commit_after>#ifndef PROTOZERO_DATA_VIEW_HPP #define PROTOZERO_DATA_VIEW_HPP /***************************************************************************** protozero - Minimalistic protocol buffer decoder and encoder in C++. This file is from https://github.com/mapbox/protozero where you can find more documentation. *****************************************************************************/ /** * @file data_view.hpp * * @brief Contains the implementation of the data_view class. */ #include <algorithm> #include <cstddef> #include <cstring> #include <string> #include <utility> #include <protozero/config.hpp> namespace protozero { #ifdef PROTOZERO_USE_VIEW using data_view = PROTOZERO_USE_VIEW; #else /** * Holds a pointer to some data and a length. * * This class is supposed to be compatible with the std::string_view * that will be available in C++17. */ class data_view { const char* m_data = nullptr; std::size_t m_size = 0; public: /** * Default constructor. Construct an empty data_view. */ constexpr data_view() noexcept = default; /** * Create data_view from pointer and size. * * @param ptr Pointer to the data. * @param length Length of the data. */ constexpr data_view(const char* ptr, std::size_t length) noexcept : m_data(ptr), m_size(length) { } /** * Create data_view from string. * * @param str String with the data. */ data_view(const std::string& str) noexcept // NOLINT clang-tidy: google-explicit-constructor : m_data(str.data()), m_size(str.size()) { } /** * Create data_view from zero-terminated string. * * @param ptr Pointer to the data. */ data_view(const char* ptr) noexcept // NOLINT clang-tidy: google-explicit-constructor : m_data(ptr), m_size(std::strlen(ptr)) { } /** * Swap the contents of this object with the other. * * @param other Other object to swap data with. */ void swap(data_view& other) noexcept { using std::swap; swap(m_data, other.m_data); swap(m_size, other.m_size); } /// Return pointer to data. constexpr const char* data() const noexcept { return m_data; } /// Return length of data in bytes. constexpr std::size_t size() const noexcept { return m_size; } /// Returns true if size is 0. constexpr bool empty() const noexcept { return m_size == 0; } #ifndef PROTOZERO_STRICT_API /** * Convert data view to string. * * @pre Must not be default constructed data_view. * * @deprecated to_string() is not available in C++17 string_view so it * should not be used to make conversion to that class easier * in the future. */ std::string to_string() const { protozero_assert(m_data); return {m_data, m_size}; } #endif /** * Convert data view to string. * * @pre Must not be default constructed data_view. */ explicit operator std::string() const { protozero_assert(m_data); return {m_data, m_size}; } /** * Compares the contents of this object with the given other object. * * @returns 0 if they are the same, <0 if this object is smaller than * the other or >0 if it is larger. If both objects have the * same size returns <0 if this object is lexicographically * before the other, >0 otherwise. * * @pre Must not be default constructed data_view. */ int compare(data_view other) const { protozero_assert(m_data && other.m_data); const int cmp = std::memcmp(data(), other.data(), std::min(size(), other.size())); if (cmp == 0) { if (size() == other.size()) { return 0; } return size() < other.size() ? -1 : 1; } return cmp; } }; // class data_view /** * Swap two data_view objects. * * @param lhs First object. * @param rhs Second object. */ inline void swap(data_view& lhs, data_view& rhs) noexcept { lhs.swap(rhs); } /** * Two data_view instances are equal if they have the same size and the * same content. * * @param lhs First object. * @param rhs Second object. */ inline constexpr bool operator==(const data_view lhs, const data_view rhs) noexcept { return lhs.size() == rhs.size() && std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data()); } /** * Two data_view instances are not equal if they have different sizes or the * content differs. * * @param lhs First object. * @param rhs Second object. */ inline constexpr bool operator!=(const data_view lhs, const data_view rhs) noexcept { return !(lhs == rhs); } /** * Returns true if lhs.compare(rhs) < 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator<(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) < 0; } /** * Returns true if lhs.compare(rhs) <= 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator<=(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) <= 0; } /** * Returns true if lhs.compare(rhs) > 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator>(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) > 0; } /** * Returns true if lhs.compare(rhs) >= 0. * * @param lhs First object. * @param rhs Second object. */ inline bool operator>=(const data_view lhs, const data_view rhs) noexcept { return lhs.compare(rhs) >= 0; } #endif } // end namespace protozero #endif // PROTOZERO_DATA_VIEW_HPP <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- /// \file Performance histogram printer of usec latencies. //---------------------------------------------------------------------------- /// \brief Performance histogram printer. // // When building include -lrt //---------------------------------------------------------------------------- // Copyright (c) 2012 Omnibius, LLC // Author: Serge Aleynikov <saleyn@gmail.com> // Created: 2012-03-20 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of utxx open-source project. Copyright (C) 2012 Serge Aleynikov <saleyn@gmail.com> 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 ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_PERF_HISTOGRAM_HPP_ #define _UTXX_PERF_HISTOGRAM_HPP_ #include <string> #include <cstring> #include <time.h> #include <ostream> #include <iomanip> #include <boost/concept_check.hpp> namespace utxx { struct perf_histogram { enum clock_type { REALTIME = CLOCK_REALTIME , MONOTONIC = CLOCK_MONOTONIC , HIGH_RES = CLOCK_PROCESS_CPUTIME_ID , THREAD_SPEC = CLOCK_THREAD_CPUTIME_ID }; private: enum { MIN_RES = 10 , MAX_RES = MIN_RES + 500/25 + 1000/250 , BUCKETS = MAX_RES+1 }; int m_latencies[BUCKETS]; double m_minTime, m_maxTime, m_sumTime; struct timespec m_last_start; int m_count; const std::string m_header; const clock_type m_clock_type; static int to_bucket(double d) { if (d < 0.000001 * MIN_RES) return (int) (d * 1000000.0); else if (d < 0.000500) return MIN_RES + (int)(d * 1000000.0) / 25; else if (d > 1.0) return MIN_RES + 500/25 + 1000/250; else return MIN_RES + 500/25 + (int)(d * 1000000.0) / 250; } static int from_bucket(int i) { if (i < MIN_RES) return i; else if (i < MIN_RES + 24) return MIN_RES + (i-MIN_RES)*25; else return MIN_RES + 500/25 + (i - MIN_RES - 500/25)*250; } public: class sample { perf_histogram& h; public: sample(perf_histogram& a_h) : h(a_h) { h.start(); } ~sample() { h.stop(); } }; perf_histogram(const std::string& header = std::string(), clock_type ct = HIGH_RES) : m_header(header) , m_clock_type(ct) { reset(); } /// Reset internal statistics counters void reset() { m_count = 0; m_minTime = 9999999; m_maxTime = m_sumTime = 0; memset(m_latencies, 0, sizeof(m_latencies)); memset(&m_last_start, 0, sizeof(struct timespec)); } /// Start a measurement sample void start() { clock_gettime(m_clock_type, &m_last_start); } /// Stop the measurement sample started with start(). void stop() { struct timespec now; clock_gettime(m_clock_type, &now); static const double fraction = 1 / 1000000000.0; double diff = (double)(now.tv_sec - m_last_start.tv_sec) + (double)(now.tv_nsec - m_last_start.tv_nsec) * fraction; if (diff < 0) return; if (m_minTime > diff) m_minTime = diff; if (m_maxTime < diff) m_maxTime = diff; m_sumTime += diff; m_count++; int k = to_bucket(diff); if (k < BUCKETS) m_latencies[k]++; } /// Add statistics from another histogram void operator+= (const perf_histogram& a_rhs) { if (!a_rhs.m_count) return; if (m_maxTime < a_rhs.m_maxTime) m_maxTime = a_rhs.m_maxTime; if (m_minTime > a_rhs.m_minTime) m_minTime = a_rhs.m_minTime; m_sumTime += a_rhs.m_sumTime; m_count += a_rhs.m_count; for (int i = 0; i < BUCKETS; i++) m_latencies[i] += a_rhs.m_latencies[i]; } /// Dump a latency report to stdout void dump(std::ostream& out, int a_filter = -1) { if (m_count == 0) { out << " No data samples" << std::endl; return; } out << m_header.c_str() << std::endl << std::fixed << std::setprecision(6) << " MinTime = " << m_minTime << std::endl << " MaxTime = " << m_maxTime << std::endl << " AvgTime = " << m_sumTime / m_count << std::endl; double tot = 0; for (int i = 0; i < BUCKETS; i++) if (m_latencies[i] > 0 && (a_filter < 0 || from_bucket(i) < a_filter)) { double pcnt = 100.0 * (double)m_latencies[i] / m_count; tot += pcnt; out << " " << std::setw(6) << from_bucket(i) << "us = " << std::setw(9) << m_latencies[i] << '(' << std::setw(6) << std::setprecision(3) << pcnt << ") (total: " << std::setw(7) << std::setprecision(3) << tot << ') ' << std::string('*', (int)(30*pcnt/100)) << std::endl; } } }; } // namespace utxx #endif // _UTXX_PERF_HISTOGRAM_HPP_ <commit_msg>Output enhancement in perf_histogram<commit_after>//---------------------------------------------------------------------------- /// \file Performance histogram printer of usec latencies. //---------------------------------------------------------------------------- /// \brief Performance histogram printer. // // When building include -lrt //---------------------------------------------------------------------------- // Copyright (c) 2012 Omnibius, LLC // Author: Serge Aleynikov <saleyn@gmail.com> // Created: 2012-03-20 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of utxx open-source project. Copyright (C) 2012 Serge Aleynikov <saleyn@gmail.com> 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 ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_PERF_HISTOGRAM_HPP_ #define _UTXX_PERF_HISTOGRAM_HPP_ #include <string> #include <cstring> #include <time.h> #include <ostream> #include <iomanip> #include <boost/concept_check.hpp> namespace utxx { struct perf_histogram { enum clock_type { REALTIME = CLOCK_REALTIME , MONOTONIC = CLOCK_MONOTONIC , HIGH_RES = CLOCK_PROCESS_CPUTIME_ID , THREAD_SPEC = CLOCK_THREAD_CPUTIME_ID }; private: enum { MIN_RES = 10 , MAX_RES = MIN_RES + 500/25 + 1000/250 , BUCKETS = MAX_RES+1 }; int m_latencies[BUCKETS]; double m_minTime, m_maxTime, m_sumTime; struct timespec m_last_start; int m_count; const std::string m_header; const clock_type m_clock_type; static int to_bucket(double d) { if (d < 0.000001 * MIN_RES) return (int) (d * 1000000.0); else if (d < 0.000500) return MIN_RES + (int)(d * 1000000.0) / 25; else if (d > 1.0) return MIN_RES + 500/25 + 1000/250; else return MIN_RES + 500/25 + (int)(d * 1000000.0) / 250; } static int from_bucket(int i) { if (i < MIN_RES) return i; else if (i < MIN_RES + 24) return MIN_RES + (i-MIN_RES)*25; else return MIN_RES + 500/25 + (i - MIN_RES - 500/25)*250; } public: class sample { perf_histogram& h; public: sample(perf_histogram& a_h) : h(a_h) { h.start(); } ~sample() { h.stop(); } }; perf_histogram(const std::string& header = std::string(), clock_type ct = HIGH_RES) : m_header(header) , m_clock_type(ct) { reset(); } /// Reset internal statistics counters void reset() { m_count = 0; m_minTime = 9999999; m_maxTime = m_sumTime = 0; memset(m_latencies, 0, sizeof(m_latencies)); memset(&m_last_start, 0, sizeof(struct timespec)); } /// Start a measurement sample void start() { clock_gettime(m_clock_type, &m_last_start); } /// Stop the measurement sample started with start(). void stop() { struct timespec now; clock_gettime(m_clock_type, &now); static const double fraction = 1 / 1000000000.0; double diff = (double)(now.tv_sec - m_last_start.tv_sec) + (double)(now.tv_nsec - m_last_start.tv_nsec) * fraction; if (diff < 0) return; if (m_minTime > diff) m_minTime = diff; if (m_maxTime < diff) m_maxTime = diff; m_sumTime += diff; m_count++; int k = to_bucket(diff); if (k < BUCKETS) m_latencies[k]++; } /// Add statistics from another histogram void operator+= (const perf_histogram& a_rhs) { if (!a_rhs.m_count) return; if (m_maxTime < a_rhs.m_maxTime) m_maxTime = a_rhs.m_maxTime; if (m_minTime > a_rhs.m_minTime) m_minTime = a_rhs.m_minTime; m_sumTime += a_rhs.m_sumTime; m_count += a_rhs.m_count; for (int i = 0; i < BUCKETS; i++) m_latencies[i] += a_rhs.m_latencies[i]; } /// Dump a latency report to stdout void dump(std::ostream& out, int a_filter = -1) { if (m_count == 0) { out << " No data samples" << std::endl; return; } out << m_header.c_str() << std::endl << std::fixed << std::setprecision(6) << " MinTime = " << m_minTime << std::endl << " MaxTime = " << m_maxTime << std::endl << " AvgTime = " << m_sumTime / m_count << std::endl; double tot = 0; for (int i = 0; i < BUCKETS; i++) if (m_latencies[i] > 0 && (a_filter < 0 || from_bucket(i) < a_filter)) { double pcnt = 100.0 * (double)m_latencies[i] / m_count; tot += pcnt; out << " " << std::setw(6) << from_bucket(i) << "us = " << std::setw(9) << m_latencies[i] << '(' << std::setw(6) << std::setprecision(3) << pcnt << ") (total: " << std::setw(7) << std::setprecision(3) << tot << ') ' << std::string((int)(30*pcnt/100), '*') << std::endl; } } }; } // namespace utxx #endif // _UTXX_PERF_HISTOGRAM_HPP_ <|endoftext|>
<commit_before>#pragma once #include <type_traits> namespace gcl::mp::type_traits { template <class T> struct is_template : std::false_type {}; template <class... T_args, template <class...> class T> struct is_template<T<T_args...>> : std::true_type {}; template <auto... values, template <auto...> class T> struct is_template<T<values...>> : std::true_type {}; template <class T> static inline constexpr auto is_template_v = is_template<T>::value; template <class T_concrete, template <class...> class T> struct is_instance_of : std::false_type {}; template <template <class...> class T, class... T_args> struct is_instance_of<T<T_args...>, T> : std::true_type {}; template <class T_concrete, template <class...> class T> static inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value; template <class T, typename... Args> class is_brace_constructible { template <typename /*= void*/, typename U, typename... U_args> struct impl : std::false_type {}; template <typename U, typename... U_args> struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {}; public: constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value; }; template <class T, typename... Args> constexpr static inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value; template <bool evaluation> using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>; template <bool evaluation> constexpr static inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value; } #include <bitset> #include <tuple> #include <array> namespace gcl::mp::type_traits { template <template <typename> class trait, typename... Ts> struct trait_result { constexpr static auto as_bitset_v = []() consteval { using bitset_type = std::bitset<sizeof...(Ts)>; using bitset_initializer_t = unsigned long long; bitset_initializer_t value{0}; return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)}; } (); template <template <typename...> class T> using as_t = T<typename trait<Ts>::type...>; template <template <typename...> class T> constexpr static auto as_v = T{trait<Ts>::value...}; using as_tuple_t = as_t<std::tuple>; constexpr static auto as_tuple_v = std::tuple{trait<Ts>::value...}; template <class Int = int> using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>; // constexpr static auto as_array_v = std::array{trait<Ts>::value...}; // OK with GCC 10.2 using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>; constexpr static auto as_array_v = as_array_t{trait<Ts>::value...}; }; } namespace gcl::mp::type_traits::tests::is_brace_constructible_v { struct toto { int i; }; struct titi { explicit titi(int) {} }; static_assert(type_traits::is_brace_constructible_v<toto>); static_assert(type_traits::is_brace_constructible_v<toto, int>); static_assert(type_traits::is_brace_constructible_v<toto, char>); static_assert(not type_traits::is_brace_constructible_v<toto, char*>); static_assert(not type_traits::is_brace_constructible_v<titi>); static_assert(type_traits::is_brace_constructible_v<titi, int>); static_assert(type_traits::is_brace_constructible_v<titi, char>); static_assert(not type_traits::is_brace_constructible_v<titi, char*>); } namespace gcl::mp::type_traits::tests::if_t { static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>); static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>); static_assert(type_traits::if_v<true> == true); static_assert(type_traits::if_v<false> == false); } #if __cpp_concepts #include <concepts> namespace gcl::mp::type_traits::tests::if_t { // clang-format off template <typename T> concept is_red_colored = requires(T) { { T::color == decltype(T::color)::red } -> std::convertible_to<bool>; { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>; }; enum colors { red, blue, green }; struct smthg_blue { constexpr static auto color = colors::blue; }; struct smthg_red { constexpr static auto color = colors::red; }; // clang-format on static_assert(not is_red_colored<smthg_blue>); static_assert(is_red_colored<smthg_red>); } #endif namespace gcl::mp::type_traits::tests::trait_results { template <typename T> using is_int = std::is_same<int, T>; using results = trait_result<is_int, char, int, bool>; using results_as_tuple = results::as_t<std::tuple>; using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>; static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>); // WIP }<commit_msg>[gcl::mp] trait_result : add tests<commit_after>#pragma once #include <type_traits> namespace gcl::mp::type_traits { template <class T> struct is_template : std::false_type {}; template <class... T_args, template <class...> class T> struct is_template<T<T_args...>> : std::true_type {}; template <auto... values, template <auto...> class T> struct is_template<T<values...>> : std::true_type {}; template <class T> static inline constexpr auto is_template_v = is_template<T>::value; template <class T_concrete, template <class...> class T> struct is_instance_of : std::false_type {}; template <template <class...> class T, class... T_args> struct is_instance_of<T<T_args...>, T> : std::true_type {}; template <class T_concrete, template <class...> class T> static inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value; template <class T, typename... Args> class is_brace_constructible { template <typename /*= void*/, typename U, typename... U_args> struct impl : std::false_type {}; template <typename U, typename... U_args> struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {}; public: constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value; }; template <class T, typename... Args> constexpr static inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value; template <bool evaluation> using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>; template <bool evaluation> constexpr static inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value; } #include <bitset> #include <tuple> #include <array> namespace gcl::mp::type_traits { template <template <typename> class trait, typename... Ts> struct trait_result { constexpr static auto as_bitset_v = []() consteval { using bitset_type = std::bitset<sizeof...(Ts)>; using bitset_initializer_t = unsigned long long; bitset_initializer_t value{0}; return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)}; } (); template <template <typename...> class T> using as_t = T<typename trait<Ts>::type...>; template <template <typename...> class T> constexpr static auto as_v = T{trait<Ts>::value...}; using as_tuple_t = as_t<std::tuple>; constexpr static auto as_tuple_v = std::tuple{trait<Ts>::value...}; template <class Int = int> using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>; // constexpr static auto as_array_v = std::array{trait<Ts>::value...}; // OK with GCC 10.2 using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>; constexpr static auto as_array_v = as_array_t{trait<Ts>::value...}; }; } namespace gcl::mp::type_traits::tests::is_brace_constructible_v { struct toto { int i; }; struct titi { explicit titi(int) {} }; static_assert(type_traits::is_brace_constructible_v<toto>); static_assert(type_traits::is_brace_constructible_v<toto, int>); static_assert(type_traits::is_brace_constructible_v<toto, char>); static_assert(not type_traits::is_brace_constructible_v<toto, char*>); static_assert(not type_traits::is_brace_constructible_v<titi>); static_assert(type_traits::is_brace_constructible_v<titi, int>); static_assert(type_traits::is_brace_constructible_v<titi, char>); static_assert(not type_traits::is_brace_constructible_v<titi, char*>); } namespace gcl::mp::type_traits::tests::if_t { static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>); static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>); static_assert(type_traits::if_v<true> == true); static_assert(type_traits::if_v<false> == false); } #if __cpp_concepts #include <concepts> namespace gcl::mp::type_traits::tests::if_t { // clang-format off template <typename T> concept is_red_colored = requires(T) { { T::color == decltype(T::color)::red } -> std::convertible_to<bool>; { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>; }; enum colors { red, blue, green }; struct smthg_blue { constexpr static auto color = colors::blue; }; struct smthg_red { constexpr static auto color = colors::red; }; // clang-format on static_assert(not is_red_colored<smthg_blue>); static_assert(is_red_colored<smthg_red>); } #endif namespace gcl::mp::type_traits::tests::trait_results { template <typename T> using is_int = std::is_same<int, T>; using results = trait_result<is_int, char, int, bool>; // static_assert(decltype(results::as_bitset_v){2UL} == results::as_bitset_v); // std::bitset::operator== is not cx constexpr auto expected_result_as_bitset = decltype(results::as_bitset_v){2UL}; static_assert(expected_result_as_bitset[0] == results::as_bitset_v[0]); static_assert(expected_result_as_bitset[1] == results::as_bitset_v[1]); static_assert(expected_result_as_bitset[2] == results::as_bitset_v[2]); using results_as_tuple = results::as_t<std::tuple>; using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>; static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>); using expected_result_as_tuple = std::tuple<std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results::as_t<std::tuple>, expected_result_as_tuple>); static_assert(std::is_same_v<results::as_integer_sequence<int>, std::integer_sequence<int, 0, 1, 0>>); static_assert(results::as_array_v == std::array{false, true, false}); template <typename... Ts> struct type_pack {}; using results_as_type_pack = results::as_t<type_pack>; using expected_result_as_type_pack = type_pack<std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results_as_type_pack, expected_result_as_type_pack>); }<|endoftext|>
<commit_before>/** * Copyright (c) 2020, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "auto_mem.hh" #include "ansi_scrubber.hh" #include "view_curses.hh" #include "attr_line.hh" attr_line_t &attr_line_t::with_ansi_string(const char *str, ...) { auto_mem<char> formatted_str; va_list args; va_start(args, str); auto ret = vasprintf(formatted_str.out(), str, args); va_end(args); if (ret >= 0 && formatted_str != nullptr) { this->al_string = formatted_str; scrub_ansi_string(this->al_string, this->al_attrs); } return *this; } attr_line_t &attr_line_t::with_ansi_string(const std::string &str) { this->al_string = str; scrub_ansi_string(this->al_string, this->al_attrs); return *this; } attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_settings *tws) { if (index < this->al_string.length()) { shift_string_attrs(this->al_attrs, index, al.al_string.length()); } this->al_string.insert(index, al.al_string); for (auto &sa : al.al_attrs) { this->al_attrs.emplace_back(sa); line_range &lr = this->al_attrs.back().sa_range; lr.shift(0, index); if (lr.lr_end == -1) { lr.lr_end = index + al.al_string.length(); } } if (tws != nullptr && (int)this->al_string.length() > tws->tws_width) { ssize_t start_pos = index; ssize_t line_start = this->al_string.rfind('\n', start_pos); if (line_start == (ssize_t) std::string::npos) { line_start = 0; } else { line_start += 1; } ssize_t line_len = index - line_start; ssize_t usable_width = tws->tws_width - tws->tws_indent; ssize_t avail = std::max((ssize_t) 0, (ssize_t) tws->tws_width - line_len); if (avail == 0) { avail = INT_MAX; } while (start_pos < (int)this->al_string.length()) { ssize_t lpc; // Find the end of a word or a breakpoint. for (lpc = start_pos; lpc < (int)this->al_string.length() && (isalnum(this->al_string[lpc]) || this->al_string[lpc] == ',' || this->al_string[lpc] == '_' || this->al_string[lpc] == '.' || this->al_string[lpc] == ';'); lpc++) { if (this->al_string[lpc] == '-' || this->al_string[lpc] == '.') { lpc += 1; break; } } if ((avail != usable_width) && (lpc - start_pos > avail)) { // Need to wrap the word. Do the wrap. this->insert(start_pos, 1, '\n') .insert(start_pos + 1, tws->tws_indent, ' '); start_pos += 1 + tws->tws_indent; avail = tws->tws_width - tws->tws_indent; } else { // There's still room to add stuff. avail -= (lpc - start_pos); while (lpc < (int)this->al_string.length() && avail) { if (this->al_string[lpc] == '\n') { this->insert(lpc + 1, tws->tws_indent, ' '); avail = usable_width; lpc += 1 + tws->tws_indent; break; } if (isalnum(this->al_string[lpc]) || this->al_string[lpc] == '_') { break; } avail -= 1; lpc += 1; } start_pos = lpc; if (!avail) { this->insert(start_pos, 1, '\n') .insert(start_pos + 1, tws->tws_indent, ' '); start_pos += 1 + tws->tws_indent; avail = usable_width; for (lpc = start_pos; lpc < (int)this->al_string.length() && this->al_string[lpc] == ' '; lpc++) { } if (lpc != start_pos) { this->erase(start_pos, (lpc - start_pos)); } } } } } return *this; } attr_line_t attr_line_t::subline(size_t start, size_t len) const { if (len == std::string::npos) { len = this->al_string.length() - start; } line_range lr{(int) start, (int) (start + len)}; attr_line_t retval; retval.al_string = this->al_string.substr(start, len); for (auto &sa : this->al_attrs) { if (!lr.intersects(sa.sa_range)) { continue; } retval.al_attrs.emplace_back(lr.intersection(sa.sa_range) .shift(lr.lr_start, -lr.lr_start), sa.sa_type, sa.sa_value); line_range &last_lr = retval.al_attrs.back().sa_range; ensure(last_lr.lr_end <= (int) retval.al_string.length()); } return retval; } void attr_line_t::split_lines(std::vector<attr_line_t> &lines) const { size_t pos = 0, next_line; while ((next_line = this->al_string.find('\n', pos)) != std::string::npos) { lines.emplace_back(this->subline(pos, next_line - pos)); pos = next_line + 1; } lines.emplace_back(this->subline(pos)); } attr_line_t &attr_line_t::right_justify(unsigned long width) { long padding = width - this->length(); if (padding > 0) { this->al_string.insert(0, padding, ' '); for (auto &al_attr : this->al_attrs) { if (al_attr.sa_range.lr_start > 0) { al_attr.sa_range.lr_start += padding; } if (al_attr.sa_range.lr_end != -1) { al_attr.sa_range.lr_end += padding; } } } return *this; } size_t attr_line_t::nearest_text(size_t x) const { if (x > 0 && (int)x >= this->length()) { if (this->empty()) { x = 0; } else { x = this->length() - 1; } } while (x > 0 && isspace(this->al_string[x])) { x -= 1; } return x; } void attr_line_t::apply_hide() { auto& vc = view_colors::singleton(); auto& sa = this->al_attrs; for (auto &sattr : sa) { if (sattr.sa_type == &SA_HIDDEN && sattr.sa_range.length() > 3) { struct line_range &lr = sattr.sa_range; std::for_each(sa.begin(), sa.end(), [&] (string_attr &attr) { if (attr.sa_type == &view_curses::VC_STYLE && lr.contains(attr.sa_range)) { attr.sa_type = &SA_REMOVED; } }); this->al_string.replace(lr.lr_start, lr.length(), "\xE2\x8B\xAE"); shift_string_attrs(sa, lr.lr_start + 1, -(lr.length() - 3)); sattr.sa_type = &view_curses::VC_STYLE; sattr.sa_value.sav_int = vc.attrs_for_role(view_colors::VCR_HIDDEN); lr.lr_end = lr.lr_start + 3; } } } <commit_msg>[build] missing include<commit_after>/** * Copyright (c) 2020, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <algorithm> #include "auto_mem.hh" #include "ansi_scrubber.hh" #include "view_curses.hh" #include "attr_line.hh" attr_line_t &attr_line_t::with_ansi_string(const char *str, ...) { auto_mem<char> formatted_str; va_list args; va_start(args, str); auto ret = vasprintf(formatted_str.out(), str, args); va_end(args); if (ret >= 0 && formatted_str != nullptr) { this->al_string = formatted_str; scrub_ansi_string(this->al_string, this->al_attrs); } return *this; } attr_line_t &attr_line_t::with_ansi_string(const std::string &str) { this->al_string = str; scrub_ansi_string(this->al_string, this->al_attrs); return *this; } attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_settings *tws) { if (index < this->al_string.length()) { shift_string_attrs(this->al_attrs, index, al.al_string.length()); } this->al_string.insert(index, al.al_string); for (auto &sa : al.al_attrs) { this->al_attrs.emplace_back(sa); line_range &lr = this->al_attrs.back().sa_range; lr.shift(0, index); if (lr.lr_end == -1) { lr.lr_end = index + al.al_string.length(); } } if (tws != nullptr && (int)this->al_string.length() > tws->tws_width) { ssize_t start_pos = index; ssize_t line_start = this->al_string.rfind('\n', start_pos); if (line_start == (ssize_t) std::string::npos) { line_start = 0; } else { line_start += 1; } ssize_t line_len = index - line_start; ssize_t usable_width = tws->tws_width - tws->tws_indent; ssize_t avail = std::max((ssize_t) 0, (ssize_t) tws->tws_width - line_len); if (avail == 0) { avail = INT_MAX; } while (start_pos < (int)this->al_string.length()) { ssize_t lpc; // Find the end of a word or a breakpoint. for (lpc = start_pos; lpc < (int)this->al_string.length() && (isalnum(this->al_string[lpc]) || this->al_string[lpc] == ',' || this->al_string[lpc] == '_' || this->al_string[lpc] == '.' || this->al_string[lpc] == ';'); lpc++) { if (this->al_string[lpc] == '-' || this->al_string[lpc] == '.') { lpc += 1; break; } } if ((avail != usable_width) && (lpc - start_pos > avail)) { // Need to wrap the word. Do the wrap. this->insert(start_pos, 1, '\n') .insert(start_pos + 1, tws->tws_indent, ' '); start_pos += 1 + tws->tws_indent; avail = tws->tws_width - tws->tws_indent; } else { // There's still room to add stuff. avail -= (lpc - start_pos); while (lpc < (int)this->al_string.length() && avail) { if (this->al_string[lpc] == '\n') { this->insert(lpc + 1, tws->tws_indent, ' '); avail = usable_width; lpc += 1 + tws->tws_indent; break; } if (isalnum(this->al_string[lpc]) || this->al_string[lpc] == '_') { break; } avail -= 1; lpc += 1; } start_pos = lpc; if (!avail) { this->insert(start_pos, 1, '\n') .insert(start_pos + 1, tws->tws_indent, ' '); start_pos += 1 + tws->tws_indent; avail = usable_width; for (lpc = start_pos; lpc < (int)this->al_string.length() && this->al_string[lpc] == ' '; lpc++) { } if (lpc != start_pos) { this->erase(start_pos, (lpc - start_pos)); } } } } } return *this; } attr_line_t attr_line_t::subline(size_t start, size_t len) const { if (len == std::string::npos) { len = this->al_string.length() - start; } line_range lr{(int) start, (int) (start + len)}; attr_line_t retval; retval.al_string = this->al_string.substr(start, len); for (auto &sa : this->al_attrs) { if (!lr.intersects(sa.sa_range)) { continue; } retval.al_attrs.emplace_back(lr.intersection(sa.sa_range) .shift(lr.lr_start, -lr.lr_start), sa.sa_type, sa.sa_value); line_range &last_lr = retval.al_attrs.back().sa_range; ensure(last_lr.lr_end <= (int) retval.al_string.length()); } return retval; } void attr_line_t::split_lines(std::vector<attr_line_t> &lines) const { size_t pos = 0, next_line; while ((next_line = this->al_string.find('\n', pos)) != std::string::npos) { lines.emplace_back(this->subline(pos, next_line - pos)); pos = next_line + 1; } lines.emplace_back(this->subline(pos)); } attr_line_t &attr_line_t::right_justify(unsigned long width) { long padding = width - this->length(); if (padding > 0) { this->al_string.insert(0, padding, ' '); for (auto &al_attr : this->al_attrs) { if (al_attr.sa_range.lr_start > 0) { al_attr.sa_range.lr_start += padding; } if (al_attr.sa_range.lr_end != -1) { al_attr.sa_range.lr_end += padding; } } } return *this; } size_t attr_line_t::nearest_text(size_t x) const { if (x > 0 && (int)x >= this->length()) { if (this->empty()) { x = 0; } else { x = this->length() - 1; } } while (x > 0 && isspace(this->al_string[x])) { x -= 1; } return x; } void attr_line_t::apply_hide() { auto& vc = view_colors::singleton(); auto& sa = this->al_attrs; for (auto &sattr : sa) { if (sattr.sa_type == &SA_HIDDEN && sattr.sa_range.length() > 3) { struct line_range &lr = sattr.sa_range; std::for_each(sa.begin(), sa.end(), [&] (string_attr &attr) { if (attr.sa_type == &view_curses::VC_STYLE && lr.contains(attr.sa_range)) { attr.sa_type = &SA_REMOVED; } }); this->al_string.replace(lr.lr_start, lr.length(), "\xE2\x8B\xAE"); shift_string_attrs(sa, lr.lr_start + 1, -(lr.length() - 3)); sattr.sa_type = &view_curses::VC_STYLE; sattr.sa_value.sav_int = vc.attrs_for_role(view_colors::VCR_HIDDEN); lr.lr_end = lr.lr_start + 3; } } } <|endoftext|>
<commit_before> #include "rtkTestConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayBoxIntersectionImageFilter.h" #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkConstantImageSource.h" #ifdef USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #else # include "rtkJosephForwardProjectionImageFilter.h" #endif template<class TImage1, class TImage2> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1; typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2; ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage1::PixelType TestVal = itTest.Get(); typename TImage2::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 1.28) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.28" << std::endl; //exit( EXIT_FAILURE); } if (PSNR < 44.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 44" << std::endl; //exit( EXIT_FAILURE); } #endif } int main(int , char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif typedef itk::Image< OutputPixelType, Dimension > OutputImageType2; typedef itk::Vector<double, 3> VectorType; #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 45; #endif // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // The test projects a volume filled with ones. The forward projector should // then return the intersection of the ray with the box and it is compared // with the analytical intersection of a box with a ray. // Create Joseph Forward Projector volume input. const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New(); origin[0] = -126; origin[1] = -126; origin[2] = -126; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 1. ); volInput->UpdateOutputInformation(); // Initialization Volume, it is used in the Joseph Forward Projector and in the // Ray Box Intersection Filter in order to initialize the stack of projections. const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New(); size[2] = NumberOfProjectionImages; projInput->SetOrigin( origin ); projInput->SetSpacing( spacing ); projInput->SetSize( size ); projInput->SetConstant( 0. ); projInput->Update(); // Joseph Forward Projection filter #ifdef USE_CUDA typedef rtk::CudaForwardProjectionImageFilter JFPType; #else typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType; #endif JFPType::Pointer jfp = JFPType::New(); jfp->InPlaceOff(); jfp->SetInput( projInput->GetOutput() ); jfp->SetInput( 1, volInput->GetOutput() ); // Ray Box Intersection filter (reference) typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType; RBIType::Pointer rbi = RBIType::New(); rbi->InPlaceOff(); rbi->SetInput( projInput->GetOutput() ); VectorType boxMin, boxMax; boxMin[0] = -126.0; boxMin[1] = -126.0; boxMin[2] = -126.0; boxMax[0] = 126.0; boxMax[1] = 126.0; boxMax[2] = 47.6; rbi->SetBoxMin(boxMin); rbi->SetBoxMax(boxMax); std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl; // The circle is divided in 4 quarters for(int q=0; q<4; q++) { // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages;i++) { const double angle = -45. + i*2.; geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle); } if(q==0) { rbi->SetGeometry( geometry ); rbi->Update(); } jfp->SetGeometry(geometry); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl; } std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl; boxMax[2] = 126.0; rbi->SetBoxMax(boxMax); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(500., 1000., i*8.); rbi->SetGeometry( geometry ); rbi->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl; // Create Shepp Logan reference projections typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType; SLPType::Pointer slp = SLPType::New(); slp->InPlaceOff(); slp->SetInput( projInput->GetOutput() ); slp->SetGeometry(geometry); slp->Update(); // Create a Shepp Logan reference volume (finer resolution) origin.Fill(-127); size.Fill(128); spacing.Fill(2.); volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 0. ); typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->InPlaceOff(); dsl->SetInput( volInput->GetOutput() ); dsl->Update(); // Forward projection jfp->SetInput( 1, dsl->GetOutput() ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl; geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(120., 1000., i*8.); slp->SetGeometry(geometry); slp->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <commit_msg>Fixed compilation error in rtkforwardprojectiontest<commit_after> #include "rtkTestConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayBoxIntersectionImageFilter.h" #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkConstantImageSource.h" #ifdef USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #else # include "rtkJosephForwardProjectionImageFilter.h" #endif template<class TImage1, class TImage2> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1; typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2; ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage1::PixelType TestVal = itTest.Get(); typename TImage2::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 1.28) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.28" << std::endl; //exit( EXIT_FAILURE); } if (PSNR < 44.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 44" << std::endl; //exit( EXIT_FAILURE); } } #endif int main(int , char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif typedef itk::Image< OutputPixelType, Dimension > OutputImageType2; typedef itk::Vector<double, 3> VectorType; #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 45; #endif // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // The test projects a volume filled with ones. The forward projector should // then return the intersection of the ray with the box and it is compared // with the analytical intersection of a box with a ray. // Create Joseph Forward Projector volume input. const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New(); origin[0] = -126; origin[1] = -126; origin[2] = -126; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 1. ); volInput->UpdateOutputInformation(); // Initialization Volume, it is used in the Joseph Forward Projector and in the // Ray Box Intersection Filter in order to initialize the stack of projections. const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New(); size[2] = NumberOfProjectionImages; projInput->SetOrigin( origin ); projInput->SetSpacing( spacing ); projInput->SetSize( size ); projInput->SetConstant( 0. ); projInput->Update(); // Joseph Forward Projection filter #ifdef USE_CUDA typedef rtk::CudaForwardProjectionImageFilter JFPType; #else typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType; #endif JFPType::Pointer jfp = JFPType::New(); jfp->InPlaceOff(); jfp->SetInput( projInput->GetOutput() ); jfp->SetInput( 1, volInput->GetOutput() ); // Ray Box Intersection filter (reference) typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType; RBIType::Pointer rbi = RBIType::New(); rbi->InPlaceOff(); rbi->SetInput( projInput->GetOutput() ); VectorType boxMin, boxMax; boxMin[0] = -126.0; boxMin[1] = -126.0; boxMin[2] = -126.0; boxMax[0] = 126.0; boxMax[1] = 126.0; boxMax[2] = 47.6; rbi->SetBoxMin(boxMin); rbi->SetBoxMax(boxMax); std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl; // The circle is divided in 4 quarters for(int q=0; q<4; q++) { // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages;i++) { const double angle = -45. + i*2.; geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle); } if(q==0) { rbi->SetGeometry( geometry ); rbi->Update(); } jfp->SetGeometry(geometry); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl; } std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl; boxMax[2] = 126.0; rbi->SetBoxMax(boxMax); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(500., 1000., i*8.); rbi->SetGeometry( geometry ); rbi->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl; // Create Shepp Logan reference projections typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType; SLPType::Pointer slp = SLPType::New(); slp->InPlaceOff(); slp->SetInput( projInput->GetOutput() ); slp->SetGeometry(geometry); slp->Update(); // Create a Shepp Logan reference volume (finer resolution) origin.Fill(-127); size.Fill(128); spacing.Fill(2.); volInput->SetOrigin( origin ); volInput->SetSpacing( spacing ); volInput->SetSize( size ); volInput->SetConstant( 0. ); typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->InPlaceOff(); dsl->SetInput( volInput->GetOutput() ); dsl->Update(); // Forward projection jfp->SetInput( 1, dsl->GetOutput() ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl; geometry = GeometryType::New(); for(unsigned int i=0; i<NumberOfProjectionImages; i++) geometry->AddProjection(120., 1000., i*8.); slp->SetGeometry(geometry); slp->Update(); jfp->SetGeometry( geometry ); jfp->Update(); CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLPageExport.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:47:53 $ * * 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_xmloff.hxx" #ifndef _XMLOFF_XMLPAGEEXPORT_HXX #include <xmloff/XMLPageExport.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _COM_SUN_STAR_STYLE_XSTYLEFAMILIESSUPPLIER_HPP_ #include <com/sun/star/style/XStyleFamiliesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_ #include <com/sun/star/style/XStyle.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _XMLOFF_FAMILIES_HXX_ #include <xmloff/families.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX #include "PageMasterPropHdlFactory.hxx" #endif #ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX #include <xmloff/PageMasterStyleMap.hxx> #endif #ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX #include "PageMasterPropMapper.hxx" #endif #ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX #include "PageMasterExportPropMapper.hxx" #endif #ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX #include "PageMasterExportPropMapper.hxx" #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::style; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::xmloff::token; //______________________________________________________________________________ sal_Bool XMLPageExport::findPageMasterName( const OUString& rStyleName, OUString& rPMName ) const { for( ::std::vector< XMLPageExportNameEntry >::const_iterator pEntry = aNameVector.begin(); pEntry != aNameVector.end(); pEntry++ ) { if( pEntry->sStyleName == rStyleName ) { rPMName = pEntry->sPageMasterName; return sal_True; } } return sal_False; } void XMLPageExport::collectPageMasterAutoStyle( const Reference < XPropertySet > & rPropSet, OUString& rPageMasterName ) { DBG_ASSERT( xPageMasterPropSetMapper.is(), "page master family/XMLPageMasterPropSetMapper not found" ); if( xPageMasterPropSetMapper.is() ) { ::std::vector<XMLPropertyState> xPropStates = xPageMasterExportPropMapper->Filter( rPropSet ); if( !xPropStates.empty()) { OUString sParent; rPageMasterName = rExport.GetAutoStylePool()->Find( XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates ); if (!rPageMasterName.getLength()) rPageMasterName = rExport.GetAutoStylePool()->Add(XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates); } } } void XMLPageExport::exportMasterPageContent( const Reference < XPropertySet > &, sal_Bool /*bAutoStyles*/ ) { } sal_Bool XMLPageExport::exportStyle( const Reference< XStyle >& rStyle, sal_Bool bAutoStyles ) { Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY ); Reference< XPropertySetInfo > xPropSetInfo = xPropSet->getPropertySetInfo(); // Don't export styles that aren't existing really. This may be the // case for StarOffice Writer's pool styles. if( xPropSetInfo->hasPropertyByName( sIsPhysical ) ) { Any aAny = xPropSet->getPropertyValue( sIsPhysical ); if( !*(sal_Bool *)aAny.getValue() ) return sal_False; } if( bAutoStyles ) { XMLPageExportNameEntry aEntry; collectPageMasterAutoStyle( xPropSet, aEntry.sPageMasterName ); aEntry.sStyleName = rStyle->getName(); aNameVector.push_back( aEntry ); exportMasterPageContent( xPropSet, sal_True ); } else { OUString sName( rStyle->getName() ); sal_Bool bEncoded = sal_False; GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NAME, GetExport().EncodeStyleName( sName, &bEncoded ) ); if( bEncoded ) GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME, sName); OUString sPMName; if( findPageMasterName( sName, sPMName ) ) GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_PAGE_LAYOUT_NAME, GetExport().EncodeStyleName( sPMName ) ); Reference<XPropertySetInfo> xInfo = xPropSet->getPropertySetInfo(); if ( xInfo.is() && xInfo->hasPropertyByName(sFollowStyle) ) { OUString sNextName; xPropSet->getPropertyValue( sFollowStyle ) >>= sNextName; if( sName != sNextName && sNextName.getLength() ) { GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NEXT_STYLE_NAME, GetExport().EncodeStyleName( sNextName ) ); } } // OUString sPageMaster = GetExport().GetAutoStylePool()->Find( // XML_STYLE_FAMILY_PAGE_MASTER, // xPropSet ); // if( sPageMaster.getLength() ) // GetExport().AddAttribute( XML_NAMESPACE_STYLE, // XML_PAGE_MASTER_NAME, // sPageMaster ); SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_MASTER_PAGE, sal_True, sal_True ); exportMasterPageContent( xPropSet, sal_False ); } return sal_True; } XMLPageExport::XMLPageExport( SvXMLExport& rExp ) : rExport( rExp ), sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ), sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) ) { xPageMasterPropHdlFactory = new XMLPageMasterPropHdlFactory; xPageMasterPropSetMapper = new XMLPageMasterPropSetMapper( (XMLPropertyMapEntry*) aXMLPageMasterStyleMap, xPageMasterPropHdlFactory ); xPageMasterExportPropMapper = new XMLPageMasterExportPropMapper( xPageMasterPropSetMapper, rExp); rExport.GetAutoStylePool()->AddFamily( XML_STYLE_FAMILY_PAGE_MASTER, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_NAME ) ), xPageMasterExportPropMapper, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_PREFIX ) ), sal_False ); Reference< XStyleFamiliesSupplier > xFamiliesSupp( GetExport().GetModel(), UNO_QUERY ); DBG_ASSERT( xFamiliesSupp.is(), "No XStyleFamiliesSupplier from XModel for export!" ); if( xFamiliesSupp.is() ) { Reference< XNameAccess > xFamilies( xFamiliesSupp->getStyleFamilies() ); DBG_ASSERT( xFamiliesSupp.is(), "getStyleFamilies() from XModel failed for export!" ); if( xFamilies.is() ) { const OUString aPageStyleName( RTL_CONSTASCII_USTRINGPARAM( "PageStyles" )); if( xFamilies->hasByName( aPageStyleName ) ) { xPageStyles.set(xFamilies->getByName( aPageStyleName ),uno::UNO_QUERY); DBG_ASSERT( xPageStyles.is(), "Page Styles not found for export!" ); } } } } XMLPageExport::~XMLPageExport() { } void XMLPageExport::exportStyles( sal_Bool bUsed, sal_Bool bAutoStyles ) { if( xPageStyles.is() ) { uno::Sequence< ::rtl::OUString> aSeq = xPageStyles->getElementNames(); const ::rtl::OUString* pIter = aSeq.getConstArray(); const ::rtl::OUString* pEnd = pIter + aSeq.getLength(); for(;pIter != pEnd;++pIter) { Reference< XStyle > xStyle(xPageStyles->getByName( *pIter ),uno::UNO_QUERY); if( !bUsed || xStyle->isInUse() ) exportStyle( xStyle, bAutoStyles ); } } } void XMLPageExport::exportAutoStyles() { rExport.GetAutoStylePool()->exportXML(XML_STYLE_FAMILY_PAGE_MASTER , rExport.GetDocHandler(), rExport.GetMM100UnitConverter(), rExport.GetNamespaceMap() ); } void XMLPageExport::exportDefaultStyle() { Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY); if (xFactory.is()) { OUString sTextDefaults ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) ); Reference < XPropertySet > xPropSet (xFactory->createInstance ( sTextDefaults ), UNO_QUERY); if (xPropSet.is()) { // <style:default-style ...> GetExport().CheckAttrList(); ::std::vector< XMLPropertyState > xPropStates = xPageMasterExportPropMapper->FilterDefaults( xPropSet ); sal_Bool bExport = sal_False; UniReference < XMLPropertySetMapper > aPropMapper(xPageMasterExportPropMapper->getPropertySetMapper()); for( ::std::vector< XMLPropertyState >::iterator aIter = xPropStates.begin(); aIter != xPropStates.end(); ++aIter ) { XMLPropertyState *pProp = &(*aIter); sal_Int16 nContextId = aPropMapper->GetEntryContextId( pProp->mnIndex ); if( nContextId == CTF_PM_STANDARD_MODE ) { bExport = sal_True; break; } } // if ( xPropStates.size() != 0 && // ( xPropStates.size() != 1 || xPropStates[0].mnIndex != -1 ) ) if( bExport ) { //<style:default-page-layout> SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_DEFAULT_PAGE_LAYOUT, sal_True, sal_True ); xPageMasterExportPropMapper->exportXML( GetExport(), xPropStates, XML_EXPORT_FLAG_IGN_WS ); } } } } <commit_msg>INTEGRATION: CWS changefileheader (1.19.18); FILE MERGED 2008/04/01 16:09:54 thb 1.19.18.3: #i85898# Stripping all external header guards 2008/04/01 13:05:00 thb 1.19.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:21 rt 1.19.18.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLPageExport.cxx,v $ * $Revision: 1.20 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include <xmloff/XMLPageExport.hxx> #include <tools/debug.hxx> #include "xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <com/sun/star/style/XStyleFamiliesSupplier.hpp> #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/container/XIndexReplace.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <xmloff/families.hxx> #include <xmloff/xmlexp.hxx> #include "PageMasterPropHdlFactory.hxx" #ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX #include <xmloff/PageMasterStyleMap.hxx> #endif #ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX #include "PageMasterPropMapper.hxx" #endif #include "PageMasterExportPropMapper.hxx" #include "PageMasterExportPropMapper.hxx" using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::style; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::xmloff::token; //______________________________________________________________________________ sal_Bool XMLPageExport::findPageMasterName( const OUString& rStyleName, OUString& rPMName ) const { for( ::std::vector< XMLPageExportNameEntry >::const_iterator pEntry = aNameVector.begin(); pEntry != aNameVector.end(); pEntry++ ) { if( pEntry->sStyleName == rStyleName ) { rPMName = pEntry->sPageMasterName; return sal_True; } } return sal_False; } void XMLPageExport::collectPageMasterAutoStyle( const Reference < XPropertySet > & rPropSet, OUString& rPageMasterName ) { DBG_ASSERT( xPageMasterPropSetMapper.is(), "page master family/XMLPageMasterPropSetMapper not found" ); if( xPageMasterPropSetMapper.is() ) { ::std::vector<XMLPropertyState> xPropStates = xPageMasterExportPropMapper->Filter( rPropSet ); if( !xPropStates.empty()) { OUString sParent; rPageMasterName = rExport.GetAutoStylePool()->Find( XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates ); if (!rPageMasterName.getLength()) rPageMasterName = rExport.GetAutoStylePool()->Add(XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates); } } } void XMLPageExport::exportMasterPageContent( const Reference < XPropertySet > &, sal_Bool /*bAutoStyles*/ ) { } sal_Bool XMLPageExport::exportStyle( const Reference< XStyle >& rStyle, sal_Bool bAutoStyles ) { Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY ); Reference< XPropertySetInfo > xPropSetInfo = xPropSet->getPropertySetInfo(); // Don't export styles that aren't existing really. This may be the // case for StarOffice Writer's pool styles. if( xPropSetInfo->hasPropertyByName( sIsPhysical ) ) { Any aAny = xPropSet->getPropertyValue( sIsPhysical ); if( !*(sal_Bool *)aAny.getValue() ) return sal_False; } if( bAutoStyles ) { XMLPageExportNameEntry aEntry; collectPageMasterAutoStyle( xPropSet, aEntry.sPageMasterName ); aEntry.sStyleName = rStyle->getName(); aNameVector.push_back( aEntry ); exportMasterPageContent( xPropSet, sal_True ); } else { OUString sName( rStyle->getName() ); sal_Bool bEncoded = sal_False; GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NAME, GetExport().EncodeStyleName( sName, &bEncoded ) ); if( bEncoded ) GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME, sName); OUString sPMName; if( findPageMasterName( sName, sPMName ) ) GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_PAGE_LAYOUT_NAME, GetExport().EncodeStyleName( sPMName ) ); Reference<XPropertySetInfo> xInfo = xPropSet->getPropertySetInfo(); if ( xInfo.is() && xInfo->hasPropertyByName(sFollowStyle) ) { OUString sNextName; xPropSet->getPropertyValue( sFollowStyle ) >>= sNextName; if( sName != sNextName && sNextName.getLength() ) { GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NEXT_STYLE_NAME, GetExport().EncodeStyleName( sNextName ) ); } } // OUString sPageMaster = GetExport().GetAutoStylePool()->Find( // XML_STYLE_FAMILY_PAGE_MASTER, // xPropSet ); // if( sPageMaster.getLength() ) // GetExport().AddAttribute( XML_NAMESPACE_STYLE, // XML_PAGE_MASTER_NAME, // sPageMaster ); SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_MASTER_PAGE, sal_True, sal_True ); exportMasterPageContent( xPropSet, sal_False ); } return sal_True; } XMLPageExport::XMLPageExport( SvXMLExport& rExp ) : rExport( rExp ), sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ), sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) ) { xPageMasterPropHdlFactory = new XMLPageMasterPropHdlFactory; xPageMasterPropSetMapper = new XMLPageMasterPropSetMapper( (XMLPropertyMapEntry*) aXMLPageMasterStyleMap, xPageMasterPropHdlFactory ); xPageMasterExportPropMapper = new XMLPageMasterExportPropMapper( xPageMasterPropSetMapper, rExp); rExport.GetAutoStylePool()->AddFamily( XML_STYLE_FAMILY_PAGE_MASTER, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_NAME ) ), xPageMasterExportPropMapper, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_PREFIX ) ), sal_False ); Reference< XStyleFamiliesSupplier > xFamiliesSupp( GetExport().GetModel(), UNO_QUERY ); DBG_ASSERT( xFamiliesSupp.is(), "No XStyleFamiliesSupplier from XModel for export!" ); if( xFamiliesSupp.is() ) { Reference< XNameAccess > xFamilies( xFamiliesSupp->getStyleFamilies() ); DBG_ASSERT( xFamiliesSupp.is(), "getStyleFamilies() from XModel failed for export!" ); if( xFamilies.is() ) { const OUString aPageStyleName( RTL_CONSTASCII_USTRINGPARAM( "PageStyles" )); if( xFamilies->hasByName( aPageStyleName ) ) { xPageStyles.set(xFamilies->getByName( aPageStyleName ),uno::UNO_QUERY); DBG_ASSERT( xPageStyles.is(), "Page Styles not found for export!" ); } } } } XMLPageExport::~XMLPageExport() { } void XMLPageExport::exportStyles( sal_Bool bUsed, sal_Bool bAutoStyles ) { if( xPageStyles.is() ) { uno::Sequence< ::rtl::OUString> aSeq = xPageStyles->getElementNames(); const ::rtl::OUString* pIter = aSeq.getConstArray(); const ::rtl::OUString* pEnd = pIter + aSeq.getLength(); for(;pIter != pEnd;++pIter) { Reference< XStyle > xStyle(xPageStyles->getByName( *pIter ),uno::UNO_QUERY); if( !bUsed || xStyle->isInUse() ) exportStyle( xStyle, bAutoStyles ); } } } void XMLPageExport::exportAutoStyles() { rExport.GetAutoStylePool()->exportXML(XML_STYLE_FAMILY_PAGE_MASTER , rExport.GetDocHandler(), rExport.GetMM100UnitConverter(), rExport.GetNamespaceMap() ); } void XMLPageExport::exportDefaultStyle() { Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY); if (xFactory.is()) { OUString sTextDefaults ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) ); Reference < XPropertySet > xPropSet (xFactory->createInstance ( sTextDefaults ), UNO_QUERY); if (xPropSet.is()) { // <style:default-style ...> GetExport().CheckAttrList(); ::std::vector< XMLPropertyState > xPropStates = xPageMasterExportPropMapper->FilterDefaults( xPropSet ); sal_Bool bExport = sal_False; UniReference < XMLPropertySetMapper > aPropMapper(xPageMasterExportPropMapper->getPropertySetMapper()); for( ::std::vector< XMLPropertyState >::iterator aIter = xPropStates.begin(); aIter != xPropStates.end(); ++aIter ) { XMLPropertyState *pProp = &(*aIter); sal_Int16 nContextId = aPropMapper->GetEntryContextId( pProp->mnIndex ); if( nContextId == CTF_PM_STANDARD_MODE ) { bExport = sal_True; break; } } // if ( xPropStates.size() != 0 && // ( xPropStates.size() != 1 || xPropStates[0].mnIndex != -1 ) ) if( bExport ) { //<style:default-page-layout> SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_DEFAULT_PAGE_LAYOUT, sal_True, sal_True ); xPageMasterExportPropMapper->exportXML( GetExport(), xPropStates, XML_EXPORT_FLAG_IGN_WS ); } } } } <|endoftext|>
<commit_before><commit_msg>Moved the definition of the UserViewMap to the IPTVTopologyOracle, as it belonged here, and added a comment to explain its functionality<commit_after><|endoftext|>
<commit_before>#include <ros/ros.h> #include <humanoid_catching/CalculateTorques.h> #include <Moby/qpOASES.h> #include <Ravelin/VectorNd.h> #include <Ravelin/MatrixNd.h> #include <Ravelin/Quatd.h> #include <Ravelin/Opsd.h> #include <Moby/qpOASES.h> #include <Ravelin/LinAlgd.h> namespace { using namespace std; using namespace humanoid_catching; using namespace Ravelin; static const double GRAVITY = 9.81; class Balancer { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Balancer Service ros::ServiceServer balancerService; public: Balancer() : pnh("~") { balancerService = nh.advertiseService("/balancer/torques", &Balancer::calculateTorques, this); } private: /** * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d * @param v3 geometry_msgs::Vector3 * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Vector3& v3) { Vector3d v; v[0] = v3.x; v[1] = v3.y; v[2] = v3.z; return v; } /** * Convert a geometry_msgs::Point to a Ravelin::Vector3d * @param p geometry_msgs::Point * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Point& p) { Vector3d v; v[0] = p.x; v[1] = p.y; v[2] = p.z; return v; } /** * Calculate balancing torques * @param req Request * @param res Response * @return Success */ bool calculateTorques(humanoid_catching::CalculateTorques::Request& req, humanoid_catching::CalculateTorques::Response& res) { ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str()); // x // linear velocity of body const Vector3d x = toVector(req.body_velocity.linear); // w // angular velocity of body const Vector3d w = toVector(req.body_velocity.angular); // v(t) // | x | // | w | VectorNd v(6); v.set_sub_vec(0, x); v.set_sub_vec(3, w); // R // Pole rotation matrix const Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w)); // J // Pole inertia matrix const Matrix3d J = MatrixNd(VectorNd(req.body_inertia_matrix.size(), &req.body_inertia_matrix[0])); // JRobot // Robot end effector jacobian matrix const Matrix3d JRobot = MatrixNd(VectorNd(req.jacobian_matrix.size(), &req.jacobian_matrix[0])); // RJR_t Matrix3d RJR; Matrix3d RTranspose = R.transpose(RTranspose); RJR = R.mult(J, RJR).mult(RTranspose, RJR); // M // | Im 0 | // | 0 RJR_t| MatrixNd M(6, 6); M.set_zero(M.rows(), M.columns()); M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass); M.set_sub_mat(3, 3, RJR); // delta t double deltaT = req.time_delta.toSec(); // Working vector Vector3d tempVector; // fext // | g | // | -w x RJR_tw | VectorNd fExt(6); fExt[0] = 0; fExt[1] = 0; fExt[2] = GRAVITY; fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector))); // n_hat // x component of ground contact position Vector3d nHat; nHat[0] = req.ground_contact.x; nHat[1] = 0; nHat[2] = 0; // s_hat // s component of contact position Vector3d sHat; nHat[0] = 0; nHat[1] = req.ground_contact.y; nHat[2] = 0; // t_hat // z component of contact position Vector3d tHat; tHat[0] = 0; tHat[1] = 0; tHat[2] = req.ground_contact.z; // q_hat // contact normal const Vector3d qHat = toVector(req.contact_normal); // p // contact point const Vector3d p = toVector(req.ground_contact); // x_bar // pole COM const Vector3d xBar = toVector(req.body_com.position); // r const Vector3d r = p - xBar; // N // | n_hat | // | r x n_hat | VectorNd N(6); N.set_sub_vec(0, nHat); N.set_sub_vec(3, r.cross(nHat, tempVector)); // S // | s_hat | // | r x s_hat | VectorNd S(6); S.set_sub_vec(0, sHat); S.set_sub_vec(3, r.cross(sHat, tempVector)); // T // | t_hat | // | r x t_hat | VectorNd T(6); T.set_sub_vec(0, tHat); T.set_sub_vec(3, r.cross(tHat, tempVector)); // Q VectorNd Q(6); Q.set_sub_vec(0, qHat); Q.set_sub_vec(3, -r.cross(qHat, tempVector)); // Result vector // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta) const int torqueIdx = 0; const int fNIdx = req.torque_limits.size(); const int fSIdx = fNIdx + 1; const int fTIdx = fSIdx + 1; const int fRobotIdx = fTIdx + 1; const int vTDeltaIdx = fRobotIdx + 1; VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6); // Set up minimization function MatrixNd H(6, z.size()); H.set_sub_mat(0, vTDeltaIdx, M); VectorNd c(6); c.set_zero(c.rows()); // Linear equality constraints MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size()); VectorNd b(1 * 2 + req.torque_limits.size() + 6); // Sv(t + t_delta) = 0 (no tangent velocity) unsigned idx = 0; A.set_sub_mat(idx, vTDeltaIdx, S); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; // Tv(t + t_delta) = 0 (no tangent velocity) A.set_sub_mat(idx, vTDeltaIdx, T); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; // J_robot(transpose) * Q(transpose) * f_robot = torques // Transformed to: // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0 MatrixNd JQ(req.torque_limits.size(), 1); MatrixNd Jt(JRobot.columns(), JRobot.rows()); JRobot.transpose(Jt); Jt.mult(MatrixNd(Q, eTranspose), JQ); A.set_sub_mat(idx, fRobotIdx, JQ); A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate()); b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size())); idx += req.torque_limits.size(); // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot) // Manipulated to fit constraint form // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta) LinAlgd linAlgd; MatrixNd MInverse = M; linAlgd.pseudo_invert(MInverse); MatrixNd MInverseN(MInverse.rows(), N.columns()); MInverse.mult(N, MInverseN); A.set_sub_mat(idx, fNIdx, MInverseN); MatrixNd MInverseS(MInverse.rows(), S.columns()); MInverse.mult(S, MInverseS); A.set_sub_mat(idx, fSIdx, MInverseS); MatrixNd MInverseT(MInverse.rows(), T.columns()); MInverse.mult(T, MInverseT); A.set_sub_mat(idx, fTIdx, MInverseT); MatrixNd MInverseQ(MInverse.rows(), Q.columns()); MInverse.mult(Q, MInverseQ); MInverseQ *= deltaT; A.set_sub_mat(idx, fRobotIdx, MInverseQ); A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate()); VectorNd MInverseFExt(6); MInverseFExt.set_zero(); MInverse.mult(fExt, MInverseFExt, deltaT); MInverseFExt.negate() -= v; b.set_sub_vec(idx, MInverseFExt); // Linear inequality constraints MatrixNd Mc(6, z.size()); VectorNd q(6); // Nv(t) >= 0 (non-negative normal velocity) Mc.set_sub_mat(0, vTDeltaIdx, N); q.set_sub_vec(0, VectorNd::zero(6)); // Solution variable constraint VectorNd lb(z.size()); VectorNd ub(z.size()); // Torque constraints unsigned int bound = 0; for (bound; bound < req.torque_limits.size(); ++bound) { lb[bound] = req.torque_limits[bound].minimum; ub[bound] = req.torque_limits[bound].maximum; } // f_n >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // f_s (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_t (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_robot >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // v_t (no constraints) for (bound; bound < z.size(); ++bound) { lb[bound] = INFINITY; ub[bound] = INFINITY; } // Call solver Moby::QPOASES qp; if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){ ROS_ERROR("QP failed to find feasible point"); return false; } ROS_INFO_STREAM("QP solved successfully: " << z); // Copy over result res.torques.resize(req.torque_limits.size()); for (unsigned int i = 0; i < z.size(); ++i) { res.torques[i] = z[i]; } return true; } }; } int main(int argc, char** argv) { ros::init(argc, argv, "balancer"); Balancer bal; ros::spin(); } <commit_msg>Add printing code<commit_after>#include <ros/ros.h> #include <humanoid_catching/CalculateTorques.h> #include <Moby/qpOASES.h> #include <Ravelin/VectorNd.h> #include <Ravelin/MatrixNd.h> #include <Ravelin/Quatd.h> #include <Ravelin/Opsd.h> #include <Moby/qpOASES.h> #include <Ravelin/LinAlgd.h> namespace { using namespace std; using namespace humanoid_catching; using namespace Ravelin; static const double GRAVITY = 9.81; class Balancer { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Balancer Service ros::ServiceServer balancerService; public: Balancer() : pnh("~") { balancerService = nh.advertiseService("/balancer/torques", &Balancer::calculateTorques, this); } private: /** * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d * @param v3 geometry_msgs::Vector3 * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Vector3& v3) { Vector3d v; v[0] = v3.x; v[1] = v3.y; v[2] = v3.z; return v; } /** * Convert a geometry_msgs::Point to a Ravelin::Vector3d * @param p geometry_msgs::Point * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Point& p) { Vector3d v; v[0] = p.x; v[1] = p.y; v[2] = p.z; return v; } /** * Calculate balancing torques * @param req Request * @param res Response * @return Success */ bool calculateTorques(humanoid_catching::CalculateTorques::Request& req, humanoid_catching::CalculateTorques::Response& res) { ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str()); // x // linear velocity of body ROS_INFO("Calculating x vector"); const Vector3d x = toVector(req.body_velocity.linear); ROS_INFO_STREAM("x: " << x); // w // angular velocity of body ROS_INFO("Calculating w vector"); const Vector3d w = toVector(req.body_velocity.angular); ROS_INFO_STREAM("w: " << w); // v(t) // | x | // | w | ROS_INFO("Calculating v vector"); VectorNd v(6); v.set_sub_vec(0, x); v.set_sub_vec(3, w); ROS_INFO_STREAM("v: " << v); // R // Pole rotation matrix ROS_INFO("Calculating R matrix"); const Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w)); ROS_INFO_STREAM("R: " << R); // J // Pole inertia matrix ROS_INFO("Calculating J matrix"); ROS_INFO_STREAM("BIM: " << req.body_inertia_matrix.size()); const Matrix3d J = Matrix3d(&req.body_inertia_matrix[0]); ROS_INFO_STREAM("J: " << J); // JRobot // Robot end effector jacobian matrix ROS_INFO("Calculating JRobot"); const MatrixNd JRobot = MatrixNd(req.torque_limits.size(), 6, &req.jacobian_matrix[0]); ROS_INFO_STREAM("JRobot: " << JRobot); // RJR_t ROS_INFO("Calculating RJR"); Matrix3d RJR; Matrix3d RTranspose = R.transpose(RTranspose); RJR = R.mult(J, RJR).mult(RTranspose, RJR); ROS_INFO_STREAM("RJR: " << RJR); // M // | Im 0 | // | 0 RJR_t| ROS_INFO("Calculating M"); MatrixNd M(6, 6); M.set_zero(M.rows(), M.columns()); M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass); M.set_sub_mat(3, 3, RJR); ROS_INFO_STREAM("M: " << M); // delta t double deltaT = req.time_delta.toSec(); // Working vector Vector3d tempVector; // fext // | g | // | -w x RJR_tw | ROS_INFO("Calculating fExt"); VectorNd fExt(6); fExt[0] = 0; fExt[1] = 0; fExt[2] = GRAVITY; fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector))); ROS_INFO_STREAM("fExt: " << fExt); // n_hat // x component of ground contact position ROS_INFO("Calculating nHat"); Vector3d nHat; nHat[0] = req.ground_contact.x; nHat[1] = 0; nHat[2] = 0; ROS_INFO_STREAM("nHat: " << nHat); // s_hat // s component of contact position ROS_INFO("Calculating sHat"); Vector3d sHat; nHat[0] = 0; nHat[1] = req.ground_contact.y; nHat[2] = 0; ROS_INFO_STREAM("sHat: " << sHat); // t_hat // z component of contact position ROS_INFO("Calculating tHat"); Vector3d tHat; tHat[0] = 0; tHat[1] = 0; tHat[2] = req.ground_contact.z; ROS_INFO_STREAM("tHat: " << tHat); // q_hat // contact normal ROS_INFO("Calculating qHat"); const Vector3d qHat = toVector(req.contact_normal); ROS_INFO_STREAM("qHat: " << qHat); // p // contact point ROS_INFO("Calculating P"); const Vector3d p = toVector(req.ground_contact); ROS_INFO_STREAM("p: " << p); // x_bar // pole COM ROS_INFO("Calculating xBar"); const Vector3d xBar = toVector(req.body_com.position); ROS_INFO_STREAM("xBar: " << xBar); // r ROS_INFO("Calculating r"); const Vector3d r = p - xBar; ROS_INFO_STREAM("r: " << r); // N // | n_hat | // | r x n_hat | ROS_INFO("Calculating N"); VectorNd N(6); N.set_sub_vec(0, nHat); N.set_sub_vec(3, r.cross(nHat, tempVector)); ROS_INFO_STREAM("N: " << N); // S // | s_hat | // | r x s_hat | ROS_INFO("Calculating S"); VectorNd S(6); S.set_sub_vec(0, sHat); S.set_sub_vec(3, r.cross(sHat, tempVector)); ROS_INFO_STREAM("S: " << S); // T // | t_hat | // | r x t_hat | ROS_INFO("Calculating T"); VectorNd T(6); T.set_sub_vec(0, tHat); T.set_sub_vec(3, r.cross(tHat, tempVector)); ROS_INFO_STREAM("T: " << T); // Q ROS_INFO("Calculating Q"); VectorNd Q(6); Q.set_sub_vec(0, qHat); Q.set_sub_vec(3, -r.cross(qHat, tempVector)); ROS_INFO_STREAM("Q: " << Q); // Result vector // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta) const int torqueIdx = 0; const int fNIdx = req.torque_limits.size(); const int fSIdx = fNIdx + 1; const int fTIdx = fSIdx + 1; const int fRobotIdx = fTIdx + 1; const int vTDeltaIdx = fRobotIdx + 1; VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6); // Set up minimization function ROS_INFO("Calculating H"); MatrixNd H(6, z.size()); H.set_sub_mat(0, vTDeltaIdx, M); ROS_INFO_STREAM("H: " << H); ROS_INFO("Calculating c"); VectorNd c(6); c.set_zero(c.rows()); ROS_INFO_STREAM("c: " << c); // Linear equality constraints ROS_INFO("Calculating A + b"); MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size()); VectorNd b(1 * 2 + req.torque_limits.size() + 6); ROS_INFO("Setting Sv constraint"); // Sv(t + t_delta) = 0 (no tangent velocity) unsigned idx = 0; A.set_sub_mat(idx, vTDeltaIdx, S); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting Tv constraint"); // Tv(t + t_delta) = 0 (no tangent velocity) A.set_sub_mat(idx, vTDeltaIdx, T); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting torque constraint"); // J_robot(transpose) * Q(transpose) * f_robot = torques // Transformed to: // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0 MatrixNd JQ(req.torque_limits.size(), 1); MatrixNd Jt = JRobot; Jt.transpose(); MatrixNd Qt(Q, eTranspose); Jt.mult(Qt, JQ); A.set_sub_mat(idx, fRobotIdx, JQ); A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate()); b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size())); idx += req.torque_limits.size(); ROS_INFO("Setting velocity constraint"); // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot) // Manipulated to fit constraint form // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta) LinAlgd linAlgd; MatrixNd MInverse = M; linAlgd.pseudo_invert(MInverse); MatrixNd MInverseN(MInverse.rows(), N.columns()); MInverse.mult(N, MInverseN); A.set_sub_mat(idx, fNIdx, MInverseN); MatrixNd MInverseS(MInverse.rows(), S.columns()); MInverse.mult(S, MInverseS); A.set_sub_mat(idx, fSIdx, MInverseS); MatrixNd MInverseT(MInverse.rows(), T.columns()); MInverse.mult(T, MInverseT); A.set_sub_mat(idx, fTIdx, MInverseT); MatrixNd MInverseQ(MInverse.rows(), Q.columns()); MInverse.mult(Q, MInverseQ); MInverseQ *= deltaT; A.set_sub_mat(idx, fRobotIdx, MInverseQ); A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate()); VectorNd MInverseFExt(6); MInverseFExt.set_zero(); MInverse.mult(fExt, MInverseFExt, deltaT); MInverseFExt.negate() -= v; b.set_sub_vec(idx, MInverseFExt); ROS_INFO_STREAM("A: " << A); ROS_INFO_STREAM("b: " << b); // Linear inequality constraints ROS_INFO("Calculating Mc and q"); MatrixNd Mc(6, z.size()); VectorNd q(6); // Nv(t) >= 0 (non-negative normal velocity) Mc.set_sub_mat(0, vTDeltaIdx, N); q.set_sub_vec(0, VectorNd::zero(6)); ROS_INFO_STREAM("Mc: " << Mc); ROS_INFO_STREAM("q: " << q); // Solution variable constraint ROS_INFO("Calculating lb and ub"); VectorNd lb(z.size()); VectorNd ub(z.size()); // Torque constraints unsigned int bound = 0; for (bound; bound < req.torque_limits.size(); ++bound) { lb[bound] = req.torque_limits[bound].minimum; ub[bound] = req.torque_limits[bound].maximum; } // f_n >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // f_s (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_t (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_robot >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // v_t (no constraints) for (bound; bound < z.size(); ++bound) { lb[bound] = INFINITY; ub[bound] = INFINITY; } ROS_INFO_STREAM("lb: " << lb); ROS_INFO_STREAM("ub: " << ub); // Call solver ROS_INFO("Calling solver"); Moby::QPOASES qp; if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){ ROS_ERROR("QP failed to find feasible point"); return false; } ROS_INFO_STREAM("QP solved successfully: " << z); // Copy over result res.torques.resize(req.torque_limits.size()); for (unsigned int i = 0; i < z.size(); ++i) { res.torques[i] = z[i]; } return true; } }; } int main(int argc, char** argv) { ros::init(argc, argv, "balancer"); Balancer bal; ros::spin(); } <|endoftext|>
<commit_before>/** @file * * @ingroup foundationLibrary * * @brief #TTDictionaryTest is an class used for unit tests of the #TTDictionary class. * * @details * * @authors Théo de la Hogue, Tim Place * * @copyright Copyright © 2013, Théo de la Hogue, Tim Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTDictionary.test.h" #define thisTTClass TTDictionaryTest #define thisTTClassName "dictionary.test" #define thisTTClassTags "test, foundation" TT_OBJECT_CONSTRUCTOR {;} TTDictionaryTest::~TTDictionaryTest() {;} void TTDictionaryTestBasic(int& errorCount, int& testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing dictionary creation"); // creation using a random name TTDictionary d1; TTTestAssertion("TTDictionary random name : Test fails if the dictionary have no name", d1.name() != kTTSymEmpty, testAssertionCount, errorCount); // creation using a specific string name TTDictionary d2("dictionary2"); TTTestAssertion("TTDictionary string name : Test fails if the dictionary name is not \"dictionary2\"", d2.name() == TTSymbol("dictionary2"), testAssertionCount, errorCount); // creation using a specific symbol name TTDictionary d3(kTTSym_symbol); TTTestAssertion("TTDictionary symbol name : Test fails if the dictionary name is not \"symbol\"", d2.name() == kTTSym_symbol, testAssertionCount, errorCount); TTTestLog("\n"); TTTestLog("Testing dictionary schema"); TTTestAssertion("TTDictionary schema : dictionary schema should default to 'none' ", d1.getSchema() == "none", testAssertionCount, errorCount); d1.setSchema(TTSymbol("aSchemaName")); TTTestAssertion("TTDictionary schema : Test fails if the dictionary schema is not \"aSchemaName\"", d1.getSchema() == TTSymbol("aSchemaName"), testAssertionCount, errorCount); TTTestLog("\n"); TTTestLog("Testing dictionary value"); TTValue v; d1.getValue(v); TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not empty", v == kTTValNONE, testAssertionCount, errorCount); d1.setValue(kTTVal1); d1.getValue(v); TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not kTTVal1", v == kTTVal1, testAssertionCount, errorCount); TTTestLog("\n"); TTTestLog("Testing dictionary keys"); d1.append(kTTSym_gain, kTTVal1); TTErr err = d1.lookup(kTTSym_gain, v); TTTestAssertion("TTDictionary append key : Test fails if the dictionary key \"gain\" doesn't exist or its value is not kTTVal1", err == kTTErrNone && v == kTTVal1, testAssertionCount, errorCount); d1.getKeys(v); TTSymbol k1 = v[0]; TTSymbol k2 = v[1]; TTSymbol k3 = v[2]; TTTestAssertion("TTDictionary get keys : Test fails if the dictionary keys are not \"schema\", \"value\" and \"gain\" or the size is not 3", k1 == kTTSym_schema && k2 == kTTSym_value && k3 == kTTSym_gain && d1.size() == 3, testAssertionCount, errorCount); d1.remove(kTTSym_gain); d1.getKeys(v); k1 = v[0]; k2 = v[1]; TTTestAssertion("TTDictionary remove key : Test fails if the dictionary keys are not \"schema\" and \"value\" or the size is not 2", k1 == kTTSym_schema && k2 == kTTSym_value && d1.size() == 2, testAssertionCount, errorCount); d1.clear(); TTTestAssertion("TTDictionary clear keys : Test fails if the dictionary keys are not empty or the size is not 0", d1.empty() && d1.size() == 0, testAssertionCount, errorCount); } TTErr TTDictionaryTest::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; TTDictionaryTestBasic(errorCount, testAssertionCount); return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>Fixing a bad test<commit_after>/** @file * * @ingroup foundationLibrary * * @brief #TTDictionaryTest is an class used for unit tests of the #TTDictionary class. * * @details * * @authors Théo de la Hogue, Tim Place * * @copyright Copyright © 2013, Théo de la Hogue, Tim Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTDictionary.test.h" #define thisTTClass TTDictionaryTest #define thisTTClassName "dictionary.test" #define thisTTClassTags "test, foundation" TT_OBJECT_CONSTRUCTOR {;} TTDictionaryTest::~TTDictionaryTest() {;} void TTDictionaryTestBasic(int& errorCount, int& testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing dictionary creation"); // creation using a random name TTDictionary d1; TTTestAssertion("TTDictionary random name : Test fails if the dictionary have no name", d1.name() != kTTSymEmpty, testAssertionCount, errorCount); // creation using a specific string name TTDictionary d2("dictionary2"); TTTestAssertion("TTDictionary string name : Test fails if the dictionary name is not \"dictionary2\"", d2.name() == TTSymbol("dictionary2"), testAssertionCount, errorCount); // creation using a specific symbol name TTDictionary d3(kTTSym_symbol); TTTestAssertion("TTDictionary symbol name : Test fails if the dictionary name is not \"symbol\"", d3.name() == kTTSym_symbol, testAssertionCount, errorCount); TTTestLog("\n"); TTTestLog("Testing dictionary schema"); TTTestAssertion("TTDictionary schema : dictionary schema should default to 'none' ", d1.getSchema() == "none", testAssertionCount, errorCount); d1.setSchema(TTSymbol("aSchemaName")); TTTestAssertion("TTDictionary schema : Test fails if the dictionary schema is not \"aSchemaName\"", d1.getSchema() == TTSymbol("aSchemaName"), testAssertionCount, errorCount); TTTestLog("\n"); TTTestLog("Testing dictionary value"); TTValue v; d1.getValue(v); TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not empty", v == kTTValNONE, testAssertionCount, errorCount); d1.setValue(kTTVal1); d1.getValue(v); TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not kTTVal1", v == kTTVal1, testAssertionCount, errorCount); TTTestLog("\n"); TTTestLog("Testing dictionary keys"); d1.append(kTTSym_gain, kTTVal1); TTErr err = d1.lookup(kTTSym_gain, v); TTTestAssertion("TTDictionary append key : Test fails if the dictionary key \"gain\" doesn't exist or its value is not kTTVal1", err == kTTErrNone && v == kTTVal1, testAssertionCount, errorCount); d1.getKeys(v); TTSymbol k1 = v[0]; TTSymbol k2 = v[1]; TTSymbol k3 = v[2]; TTTestAssertion("TTDictionary get keys : Test fails if the dictionary keys are not \"schema\", \"value\" and \"gain\" or the size is not 3", k1 == kTTSym_schema && k2 == kTTSym_value && k3 == kTTSym_gain && d1.size() == 3, testAssertionCount, errorCount); d1.remove(kTTSym_gain); d1.getKeys(v); k1 = v[0]; k2 = v[1]; TTTestAssertion("TTDictionary remove key : Test fails if the dictionary keys are not \"schema\" and \"value\" or the size is not 2", k1 == kTTSym_schema && k2 == kTTSym_value && d1.size() == 2, testAssertionCount, errorCount); d1.clear(); TTTestAssertion("TTDictionary clear keys : Test fails if the dictionary keys are not empty or the size is not 0", d1.empty() && d1.size() == 0, testAssertionCount, errorCount); } TTErr TTDictionaryTest::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; TTDictionaryTestBasic(errorCount, testAssertionCount); return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>/** * @file llcolorswatch.cpp * @brief LLColorSwatch class implementation * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // File include #include "llcolorswatch.h" // Linden library includes #include "v4color.h" #include "llwindow.h" // setCursor() // Project includes #include "llui.h" #include "llrender.h" #include "lluiconstants.h" #include "llviewercontrol.h" #include "llbutton.h" #include "lltextbox.h" #include "llfloatercolorpicker.h" #include "llviewborder.h" #include "llviewertexturelist.h" #include "llfocusmgr.h" static LLDefaultChildRegistry::Register<LLColorSwatchCtrl> r("color_swatch"); LLColorSwatchCtrl::Params::Params() : color("color", LLColor4::white), can_apply_immediately("can_apply_immediately", false), alpha_background_image("alpha_background_image"), border_color("border_color"), label_width("label_width", -1), caption_text("caption_text"), border("border") { name = "colorswatch"; } LLColorSwatchCtrl::LLColorSwatchCtrl(const Params& p) : LLUICtrl(p), mValid( TRUE ), mColor(p.color()), mCanApplyImmediately(p.can_apply_immediately), mAlphaGradientImage(p.alpha_background_image), mOnCancelCallback(p.cancel_callback()), mOnSelectCallback(p.select_callback()), mBorderColor(p.border_color()), mLabelWidth(p.label_width) { LLTextBox::Params tp = p.caption_text; // label_width is specified, not -1 if(mLabelWidth!= -1) { tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, mLabelWidth, 0 )); } else { tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, getRect().getWidth(), 0 )); } tp.initial_value(p.label()); mCaption = LLUICtrlFactory::create<LLTextBox>(tp); addChild( mCaption ); LLRect border_rect = getLocalRect(); border_rect.mTop -= 1; border_rect.mRight -=1; border_rect.mBottom += BTN_HEIGHT_SMALL; LLViewBorder::Params params = p.border; params.rect(border_rect); mBorder = LLUICtrlFactory::create<LLViewBorder> (params); addChild(mBorder); } LLColorSwatchCtrl::~LLColorSwatchCtrl () { // parent dialog is destroyed so we are too and we need to cancel selection LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->cancelSelection(); pickerp->closeFloater(); } } BOOL LLColorSwatchCtrl::handleDoubleClick(S32 x, S32 y, MASK mask) { return handleMouseDown(x, y, mask); } BOOL LLColorSwatchCtrl::handleHover(S32 x, S32 y, MASK mask) { getWindow()->setCursor(UI_CURSOR_HAND); return TRUE; } BOOL LLColorSwatchCtrl::handleUnicodeCharHere(llwchar uni_char) { if( ' ' == uni_char ) { showPicker(TRUE); } return LLUICtrl::handleUnicodeCharHere(uni_char); } // forces color of this swatch and any associated floater to the input value, if currently invalid void LLColorSwatchCtrl::setOriginal(const LLColor4& color) { mColor = color; LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->setOrigRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]); } } void LLColorSwatchCtrl::set(const LLColor4& color, BOOL update_picker, BOOL from_event) { mColor = color; LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp && update_picker) { pickerp->setCurRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]); } if (!from_event) { setControlValue(mColor.getValue()); } } void LLColorSwatchCtrl::setLabel(const std::string& label) { mCaption->setText(label); } BOOL LLColorSwatchCtrl::handleMouseDown(S32 x, S32 y, MASK mask) { // Route future Mouse messages here preemptively. (Release on mouse up.) // No handler is needed for capture lost since this object has no state that depends on it. gFocusMgr.setMouseCapture( this ); return TRUE; } BOOL LLColorSwatchCtrl::handleMouseUp(S32 x, S32 y, MASK mask) { // We only handle the click if the click both started and ended within us if( hasMouseCapture() ) { // Release the mouse gFocusMgr.setMouseCapture( NULL ); // If mouseup in the widget, it's been clicked if ( pointInView(x, y) ) { llassert(getEnabled()); llassert(getVisible()); showPicker(FALSE); } } return TRUE; } // assumes GL state is set for 2D void LLColorSwatchCtrl::draw() { F32 alpha = getDrawContext().mAlpha; mBorder->setKeyboardFocusHighlight(hasFocus()); // Draw border LLRect border( 0, getRect().getHeight(), getRect().getWidth(), BTN_HEIGHT_SMALL ); gl_rect_2d( border, mBorderColor.get(), FALSE ); LLRect interior = border; interior.stretch( -1 ); // Check state if ( mValid ) { // Draw the color swatch gl_rect_2d_checkerboard( interior ); gl_rect_2d(interior, mColor, TRUE); LLColor4 opaque_color = mColor; opaque_color.mV[VALPHA] = 1.f; gGL.color4fv(opaque_color.mV); if (mAlphaGradientImage.notNull()) { gGL.pushMatrix(); { mAlphaGradientImage->draw(interior, mColor); } gGL.popMatrix(); } } else { if (!mFallbackImageName.empty()) { LLPointer<LLViewerFetchedTexture> fallback_image = LLViewerTextureManager::getFetchedTextureFromFile(mFallbackImageName, TRUE, LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE); if( fallback_image->getComponents() == 4 ) { gl_rect_2d_checkerboard( interior ); } gl_draw_scaled_image( interior.mLeft, interior.mBottom, interior.getWidth(), interior.getHeight(), fallback_image, LLColor4::white % alpha); fallback_image->addTextureStats( (F32)(interior.getWidth() * interior.getHeight()) ); } else { // Draw grey and an X gl_rect_2d(interior, LLColor4::grey % alpha, TRUE); gl_draw_x(interior, LLColor4::black % alpha); } } LLUICtrl::draw(); } void LLColorSwatchCtrl::setEnabled( BOOL enabled ) { mCaption->setEnabled( enabled ); LLView::setEnabled( enabled ); if (!enabled) { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->cancelSelection(); pickerp->closeFloater(); } } } void LLColorSwatchCtrl::setValue(const LLSD& value) { set(LLColor4(value), TRUE, TRUE); } ////////////////////////////////////////////////////////////////////////////// // called (infrequently) when the color changes so the subject of the swatch can be updated. void LLColorSwatchCtrl::onColorChanged ( void* data, EColorPickOp pick_op ) { LLColorSwatchCtrl* subject = ( LLColorSwatchCtrl* )data; if ( subject ) { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)subject->mPickerHandle.get(); if (pickerp) { // move color across from selector to internal widget storage LLColor4 updatedColor ( pickerp->getCurR (), pickerp->getCurG (), pickerp->getCurB (), subject->mColor.mV[VALPHA] ); // keep current alpha subject->mColor = updatedColor; subject->setControlValue(updatedColor.getValue()); if (pick_op == COLOR_CANCEL && subject->mOnCancelCallback) { subject->mOnCancelCallback( subject, LLSD()); } else if (pick_op == COLOR_SELECT && subject->mOnSelectCallback) { subject->mOnSelectCallback( subject, LLSD() ); } else { // just commit change subject->onCommit (); } } } } // This is called when the main floatercustomize panel is closed. // Since this class has pointers up to its parents, we need to cleanup // this class first in order to avoid a crash. void LLColorSwatchCtrl::onParentFloaterClosed() { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->setSwatch(NULL); pickerp->closeFloater(); } mPickerHandle.markDead(); } void LLColorSwatchCtrl::setValid(BOOL valid ) { mValid = valid; LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->setActive(valid); } } void LLColorSwatchCtrl::showPicker(BOOL take_focus) { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (!pickerp) { pickerp = new LLFloaterColorPicker(this, mCanApplyImmediately); //gFloaterView->getParentFloater(this)->addDependentFloater(pickerp); mPickerHandle = pickerp->getHandle(); } // initialize picker with current color pickerp->initUI ( mColor.mV [ VRED ], mColor.mV [ VGREEN ], mColor.mV [ VBLUE ] ); // display it pickerp->showUI (); if (take_focus) { pickerp->setFocus(TRUE); } } <commit_msg>EXT-7736 FIXED Reverted fix for EXT-2819 (crash in color picker).<commit_after>/** * @file llcolorswatch.cpp * @brief LLColorSwatch class implementation * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // File include #include "llcolorswatch.h" // Linden library includes #include "v4color.h" #include "llwindow.h" // setCursor() // Project includes #include "llui.h" #include "llrender.h" #include "lluiconstants.h" #include "llviewercontrol.h" #include "llbutton.h" #include "lltextbox.h" #include "llfloatercolorpicker.h" #include "llviewborder.h" #include "llviewertexturelist.h" #include "llfocusmgr.h" static LLDefaultChildRegistry::Register<LLColorSwatchCtrl> r("color_swatch"); LLColorSwatchCtrl::Params::Params() : color("color", LLColor4::white), can_apply_immediately("can_apply_immediately", false), alpha_background_image("alpha_background_image"), border_color("border_color"), label_width("label_width", -1), caption_text("caption_text"), border("border") { name = "colorswatch"; } LLColorSwatchCtrl::LLColorSwatchCtrl(const Params& p) : LLUICtrl(p), mValid( TRUE ), mColor(p.color()), mCanApplyImmediately(p.can_apply_immediately), mAlphaGradientImage(p.alpha_background_image), mOnCancelCallback(p.cancel_callback()), mOnSelectCallback(p.select_callback()), mBorderColor(p.border_color()), mLabelWidth(p.label_width) { LLTextBox::Params tp = p.caption_text; // label_width is specified, not -1 if(mLabelWidth!= -1) { tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, mLabelWidth, 0 )); } else { tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, getRect().getWidth(), 0 )); } tp.initial_value(p.label()); mCaption = LLUICtrlFactory::create<LLTextBox>(tp); addChild( mCaption ); LLRect border_rect = getLocalRect(); border_rect.mTop -= 1; border_rect.mRight -=1; border_rect.mBottom += BTN_HEIGHT_SMALL; LLViewBorder::Params params = p.border; params.rect(border_rect); mBorder = LLUICtrlFactory::create<LLViewBorder> (params); addChild(mBorder); } LLColorSwatchCtrl::~LLColorSwatchCtrl () { // parent dialog is destroyed so we are too and we need to cancel selection LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->cancelSelection(); pickerp->closeFloater(); } } BOOL LLColorSwatchCtrl::handleDoubleClick(S32 x, S32 y, MASK mask) { return handleMouseDown(x, y, mask); } BOOL LLColorSwatchCtrl::handleHover(S32 x, S32 y, MASK mask) { getWindow()->setCursor(UI_CURSOR_HAND); return TRUE; } BOOL LLColorSwatchCtrl::handleUnicodeCharHere(llwchar uni_char) { if( ' ' == uni_char ) { showPicker(TRUE); } return LLUICtrl::handleUnicodeCharHere(uni_char); } // forces color of this swatch and any associated floater to the input value, if currently invalid void LLColorSwatchCtrl::setOriginal(const LLColor4& color) { mColor = color; LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->setOrigRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]); } } void LLColorSwatchCtrl::set(const LLColor4& color, BOOL update_picker, BOOL from_event) { mColor = color; LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp && update_picker) { pickerp->setCurRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]); } if (!from_event) { setControlValue(mColor.getValue()); } } void LLColorSwatchCtrl::setLabel(const std::string& label) { mCaption->setText(label); } BOOL LLColorSwatchCtrl::handleMouseDown(S32 x, S32 y, MASK mask) { // Route future Mouse messages here preemptively. (Release on mouse up.) // No handler is needed for capture lost since this object has no state that depends on it. gFocusMgr.setMouseCapture( this ); return TRUE; } BOOL LLColorSwatchCtrl::handleMouseUp(S32 x, S32 y, MASK mask) { // We only handle the click if the click both started and ended within us if( hasMouseCapture() ) { // Release the mouse gFocusMgr.setMouseCapture( NULL ); // If mouseup in the widget, it's been clicked if ( pointInView(x, y) ) { llassert(getEnabled()); llassert(getVisible()); showPicker(FALSE); } } return TRUE; } // assumes GL state is set for 2D void LLColorSwatchCtrl::draw() { F32 alpha = getDrawContext().mAlpha; mBorder->setKeyboardFocusHighlight(hasFocus()); // Draw border LLRect border( 0, getRect().getHeight(), getRect().getWidth(), BTN_HEIGHT_SMALL ); gl_rect_2d( border, mBorderColor.get(), FALSE ); LLRect interior = border; interior.stretch( -1 ); // Check state if ( mValid ) { // Draw the color swatch gl_rect_2d_checkerboard( interior ); gl_rect_2d(interior, mColor, TRUE); LLColor4 opaque_color = mColor; opaque_color.mV[VALPHA] = 1.f; gGL.color4fv(opaque_color.mV); if (mAlphaGradientImage.notNull()) { gGL.pushMatrix(); { mAlphaGradientImage->draw(interior, mColor); } gGL.popMatrix(); } } else { if (!mFallbackImageName.empty()) { LLPointer<LLViewerFetchedTexture> fallback_image = LLViewerTextureManager::getFetchedTextureFromFile(mFallbackImageName, TRUE, LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE); if( fallback_image->getComponents() == 4 ) { gl_rect_2d_checkerboard( interior ); } gl_draw_scaled_image( interior.mLeft, interior.mBottom, interior.getWidth(), interior.getHeight(), fallback_image, LLColor4::white % alpha); fallback_image->addTextureStats( (F32)(interior.getWidth() * interior.getHeight()) ); } else { // Draw grey and an X gl_rect_2d(interior, LLColor4::grey % alpha, TRUE); gl_draw_x(interior, LLColor4::black % alpha); } } LLUICtrl::draw(); } void LLColorSwatchCtrl::setEnabled( BOOL enabled ) { mCaption->setEnabled( enabled ); LLView::setEnabled( enabled ); if (!enabled) { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->cancelSelection(); pickerp->closeFloater(); } } } void LLColorSwatchCtrl::setValue(const LLSD& value) { set(LLColor4(value), TRUE, TRUE); } ////////////////////////////////////////////////////////////////////////////// // called (infrequently) when the color changes so the subject of the swatch can be updated. void LLColorSwatchCtrl::onColorChanged ( void* data, EColorPickOp pick_op ) { LLColorSwatchCtrl* subject = ( LLColorSwatchCtrl* )data; if ( subject ) { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)subject->mPickerHandle.get(); if (pickerp) { // move color across from selector to internal widget storage LLColor4 updatedColor ( pickerp->getCurR (), pickerp->getCurG (), pickerp->getCurB (), subject->mColor.mV[VALPHA] ); // keep current alpha subject->mColor = updatedColor; subject->setControlValue(updatedColor.getValue()); if (pick_op == COLOR_CANCEL && subject->mOnCancelCallback) { subject->mOnCancelCallback( subject, LLSD()); } else if (pick_op == COLOR_SELECT && subject->mOnSelectCallback) { subject->mOnSelectCallback( subject, LLSD() ); } else { // just commit change subject->onCommit (); } } } } // This is called when the main floatercustomize panel is closed. // Since this class has pointers up to its parents, we need to cleanup // this class first in order to avoid a crash. void LLColorSwatchCtrl::onParentFloaterClosed() { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->setSwatch(NULL); pickerp->closeFloater(); } mPickerHandle.markDead(); } void LLColorSwatchCtrl::setValid(BOOL valid ) { mValid = valid; LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (pickerp) { pickerp->setActive(valid); } } void LLColorSwatchCtrl::showPicker(BOOL take_focus) { LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get(); if (!pickerp) { pickerp = new LLFloaterColorPicker(this, mCanApplyImmediately); LLFloater* parent = gFloaterView->getParentFloater(this); if (parent) { parent->addDependentFloater(pickerp); } mPickerHandle = pickerp->getHandle(); } // initialize picker with current color pickerp->initUI ( mColor.mV [ VRED ], mColor.mV [ VGREEN ], mColor.mV [ VBLUE ] ); // display it pickerp->showUI (); if (take_focus) { pickerp->setFocus(TRUE); } } <|endoftext|>
<commit_before>#include "model/PhysicsCar.h" #include "model/PhysicsWorld.h" #include <btBulletDynamicsCommon.h> #include <sstream> #include <iostream> namespace Rally { namespace Model { namespace { const btVector3 CAR_DIMENSIONS(2.0f, 1.0f, 4.0f); const float CAR_MASS = 1.0f; // The rolling torque from each wheel is scaled with this (to prevent rollover). // 0.0f = no rolling, 1.0f = rolling like in reality. const float ROLL_INFLUENCE = 0.1f; const float SUSPENSION_REST_LENGTH = 0.6f; // (see also maxSuspensionTravelCm) const float WHEEL_RADIUS = 0.5f; // (There is no wheel width.) // The wheel distance is calculated from the origin = center of the car. // The wheel (including radius) should be located inside the car body: // - Below the car and it might sink into the ground (rays goes into infinity) // - Above the car and it confuses the body with the ground => weird behavior. // (The official demo does this though... Maybe the suspension is included?) // Values below represent the right wheel (mirrored in the yz-plane for left). const btVector3 FRONT_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.3f - WHEEL_RADIUS); const btVector3 BACK_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.1f - WHEEL_RADIUS); } PhysicsCar::PhysicsCar() : dynamicsWorld(NULL), bodyShape(NULL), bodyMotionState(btTransform(btQuaternion(0.0f, 0.0f, 0.0f, 1.0f), btVector3(0.0f, 10.0f, 0.0f))), bodyConstructionInfo(NULL), bodyRigidBody(NULL), vehicleRaycaster(NULL), raycastVehicle(NULL), leftFrontWheel(NULL), rightFrontWheel(NULL), leftBackWheel(NULL), rightBackWheel(NULL) { } PhysicsCar::~PhysicsCar() { } void PhysicsCar::initializeConstructionInfo() { if(bodyConstructionInfo != NULL) { return; } bodyShape = new btBoxShape(CAR_DIMENSIONS / 2); // Takes half-extents // Initialize what I think is the diagonal in the inertia tensor btVector3 inertia(0, 0, 0); bodyShape->calculateLocalInertia(CAR_MASS, inertia); // TODO: We might want to lower/move center of gravity... bodyConstructionInfo = new btRigidBody::btRigidBodyConstructionInfo(CAR_MASS, &bodyMotionState, bodyShape, inertia); } void PhysicsCar::attachTo(PhysicsWorld& physicsWorld) { dynamicsWorld = physicsWorld.getDynamicsWorld(); // Create car body this->initializeConstructionInfo(); bodyRigidBody = new btRigidBody(*bodyConstructionInfo); bodyRigidBody->setActivationState(DISABLE_DEACTIVATION); // Needed for btRaycastVehicles dynamicsWorld->addRigidBody(bodyRigidBody); // Tuning for car (applied to all the wheels internally). btRaycastVehicle::btVehicleTuning tuning; tuning.m_suspensionStiffness = 20.0f; tuning.m_suspensionDamping = 2.3f; tuning.m_suspensionCompression = 4.4f; tuning.m_frictionSlip = 0.8f;// no drift = 1000.0f; // rollInfluence cannot be set here, so we have to apply it to every wheel individually. // Create the raycasting part for the "wheels" vehicleRaycaster = new btDefaultVehicleRaycaster(dynamicsWorld); raycastVehicle = new btRaycastVehicle(tuning, bodyRigidBody, vehicleRaycaster); dynamicsWorld->addVehicle(raycastVehicle); // Create the actual wheels: const btVector3 wheelDirection(0, -1.0f, 0); // This is the direction of the raycast. const btVector3 wheelAxle(-1.0f, 0, 0); // This is spinning direction (using right hand rule). // Right front wheel. rightFrontWheel = &raycastVehicle->addWheel( FRONT_WHEEL_DISTANCE, // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, true // isFrontWheel ); rightFrontWheel->m_rollInfluence = ROLL_INFLUENCE; // Left front wheel. leftFrontWheel = &raycastVehicle->addWheel( btVector3(-FRONT_WHEEL_DISTANCE.x(), FRONT_WHEEL_DISTANCE.y(), -FRONT_WHEEL_DISTANCE.z()), // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, true // isFrontWheel ); leftFrontWheel->m_rollInfluence = ROLL_INFLUENCE; // Right back wheel. rightBackWheel = &raycastVehicle->addWheel( BACK_WHEEL_DISTANCE, // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, false // isFrontWheel ); rightBackWheel->m_rollInfluence = ROLL_INFLUENCE; // Left back wheel. leftBackWheel = &raycastVehicle->addWheel( btVector3(-BACK_WHEEL_DISTANCE.x(), BACK_WHEEL_DISTANCE.y(), -BACK_WHEEL_DISTANCE.z()), // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, false // isFrontWheel ); leftBackWheel->m_rollInfluence = ROLL_INFLUENCE; } Rally::Vector3 PhysicsCar::getPosition() const { // Note that we cannot ask the rigidbody or use raycastVehicle->getForwardVector(), // as we won't get interpolated values then. That's motion-state exclusive info. const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans; const btVector3& position = graphicsTransform.getOrigin(); return Rally::Vector3(position.x(), position.y(), position.z()); } Rally::Vector3 PhysicsCar::getOrientation() const { const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans; return Rally::Vector3( graphicsTransform.getBasis()[0][2], // The z-column basis vector graphicsTransform.getBasis()[1][2], // The z-column basis vector graphicsTransform.getBasis()[2][2] // The z-column basis vector ); //const btQuaternion orientation = graphicsTransform.getRotation(); //return Rally::Quaternion(orientation.x(), orientation.y(), orientation.z(), orientation.w()); } Rally::Vector3 PhysicsCar::getVelocity() const { if(bodyRigidBody == NULL) { return Rally::Vector3(0, 0, 0); } const btVector3 velocity = bodyRigidBody->getLinearVelocity(); return Rally::Vector3(velocity.x(), velocity.y(), velocity.z()); } float PhysicsCar::getRightFrontWheelTraction() const { return rightFrontWheel->m_skidInfo; } float PhysicsCar::getLeftFrontWheelTraction() const { return leftFrontWheel->m_skidInfo; } float PhysicsCar::getRightBackWheelTraction() const { return rightBackWheel->m_skidInfo; } float PhysicsCar::getLeftBackWheelTraction() const { return leftBackWheel->m_skidInfo; } } } <commit_msg>Fixed rallycar bug: left wheels pointing in the wrong direction.<commit_after>#include "model/PhysicsCar.h" #include "model/PhysicsWorld.h" #include <btBulletDynamicsCommon.h> #include <sstream> #include <iostream> namespace Rally { namespace Model { namespace { const btVector3 CAR_DIMENSIONS(2.0f, 1.0f, 4.0f); const float CAR_MASS = 1.0f; // The rolling torque from each wheel is scaled with this (to prevent rollover). // 0.0f = no rolling, 1.0f = rolling like in reality. const float ROLL_INFLUENCE = 0.1f; const float SUSPENSION_REST_LENGTH = 0.6f; // (see also maxSuspensionTravelCm) const float WHEEL_RADIUS = 0.5f; // (There is no wheel width.) // The wheel distance is calculated from the origin = center of the car. // The wheel (including radius) should be located inside the car body: // - Below the car and it might sink into the ground (rays goes into infinity) // - Above the car and it confuses the body with the ground => weird behavior. // (The official demo does this though... Maybe the suspension is included?) // Values below represent the right wheel (mirrored in the yz-plane for left). const btVector3 FRONT_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.3f - WHEEL_RADIUS); const btVector3 BACK_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.1f - WHEEL_RADIUS); } PhysicsCar::PhysicsCar() : dynamicsWorld(NULL), bodyShape(NULL), bodyMotionState(btTransform(btQuaternion(0.0f, 0.0f, 0.0f, 1.0f), btVector3(0.0f, 10.0f, 0.0f))), bodyConstructionInfo(NULL), bodyRigidBody(NULL), vehicleRaycaster(NULL), raycastVehicle(NULL), leftFrontWheel(NULL), rightFrontWheel(NULL), leftBackWheel(NULL), rightBackWheel(NULL) { } PhysicsCar::~PhysicsCar() { } void PhysicsCar::initializeConstructionInfo() { if(bodyConstructionInfo != NULL) { return; } bodyShape = new btBoxShape(CAR_DIMENSIONS / 2); // Takes half-extents // Initialize what I think is the diagonal in the inertia tensor btVector3 inertia(0, 0, 0); bodyShape->calculateLocalInertia(CAR_MASS, inertia); // TODO: We might want to lower/move center of gravity... bodyConstructionInfo = new btRigidBody::btRigidBodyConstructionInfo(CAR_MASS, &bodyMotionState, bodyShape, inertia); } void PhysicsCar::attachTo(PhysicsWorld& physicsWorld) { dynamicsWorld = physicsWorld.getDynamicsWorld(); // Create car body this->initializeConstructionInfo(); bodyRigidBody = new btRigidBody(*bodyConstructionInfo); bodyRigidBody->setActivationState(DISABLE_DEACTIVATION); // Needed for btRaycastVehicles dynamicsWorld->addRigidBody(bodyRigidBody); // Tuning for car (applied to all the wheels internally). btRaycastVehicle::btVehicleTuning tuning; tuning.m_suspensionStiffness = 20.0f; tuning.m_suspensionDamping = 2.3f; tuning.m_suspensionCompression = 4.4f; tuning.m_frictionSlip = 0.8f;// no drift = 1000.0f; // rollInfluence cannot be set here, so we have to apply it to every wheel individually. // Create the raycasting part for the "wheels" vehicleRaycaster = new btDefaultVehicleRaycaster(dynamicsWorld); raycastVehicle = new btRaycastVehicle(tuning, bodyRigidBody, vehicleRaycaster); dynamicsWorld->addVehicle(raycastVehicle); // Create the actual wheels: const btVector3 wheelDirection(0, -1.0f, 0); // This is the direction of the raycast. const btVector3 wheelAxle(-1.0f, 0, 0); // This is spinning direction (using right hand rule). // Right front wheel. rightFrontWheel = &raycastVehicle->addWheel( FRONT_WHEEL_DISTANCE, // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, true // isFrontWheel ); rightFrontWheel->m_rollInfluence = ROLL_INFLUENCE; // Left front wheel. leftFrontWheel = &raycastVehicle->addWheel( btVector3(-FRONT_WHEEL_DISTANCE.x(), FRONT_WHEEL_DISTANCE.y(), FRONT_WHEEL_DISTANCE.z()), // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, true // isFrontWheel ); leftFrontWheel->m_rollInfluence = ROLL_INFLUENCE; // Right back wheel. rightBackWheel = &raycastVehicle->addWheel( BACK_WHEEL_DISTANCE, // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, false // isFrontWheel ); rightBackWheel->m_rollInfluence = ROLL_INFLUENCE; // Left back wheel. leftBackWheel = &raycastVehicle->addWheel( btVector3(-BACK_WHEEL_DISTANCE.x(), BACK_WHEEL_DISTANCE.y(), BACK_WHEEL_DISTANCE.z()), // connection point wheelDirection, // wheel direction wheelAxle, // axle SUSPENSION_REST_LENGTH, WHEEL_RADIUS, tuning, false // isFrontWheel ); leftBackWheel->m_rollInfluence = ROLL_INFLUENCE; } Rally::Vector3 PhysicsCar::getPosition() const { // Note that we cannot ask the rigidbody or use raycastVehicle->getForwardVector(), // as we won't get interpolated values then. That's motion-state exclusive info. const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans; const btVector3& position = graphicsTransform.getOrigin(); return Rally::Vector3(position.x(), position.y(), position.z()); } Rally::Vector3 PhysicsCar::getOrientation() const { const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans; return Rally::Vector3( graphicsTransform.getBasis()[0][2], // The z-column basis vector graphicsTransform.getBasis()[1][2], // The z-column basis vector graphicsTransform.getBasis()[2][2] // The z-column basis vector ); //const btQuaternion orientation = graphicsTransform.getRotation(); //return Rally::Quaternion(orientation.x(), orientation.y(), orientation.z(), orientation.w()); } Rally::Vector3 PhysicsCar::getVelocity() const { if(bodyRigidBody == NULL) { return Rally::Vector3(0, 0, 0); } const btVector3 velocity = bodyRigidBody->getLinearVelocity(); return Rally::Vector3(velocity.x(), velocity.y(), velocity.z()); } float PhysicsCar::getRightFrontWheelTraction() const { return rightFrontWheel->m_skidInfo; } float PhysicsCar::getLeftFrontWheelTraction() const { return leftFrontWheel->m_skidInfo; } float PhysicsCar::getRightBackWheelTraction() const { return rightBackWheel->m_skidInfo; } float PhysicsCar::getLeftBackWheelTraction() const { return leftBackWheel->m_skidInfo; } } } <|endoftext|>
<commit_before>// // TexturesHandler.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 19/06/12. // Copyright (c) 2012 IGO Software SL. All rights reserved. // #ifndef G3MiOSSDK_TexturesHandler_hpp #define G3MiOSSDK_TexturesHandler_hpp #include <string> #include <vector> #include "TextureBuilder.hpp" #include "TextureHolder.hpp" class IImage; class RenderContext; //class TextureHolder; class IGL; class IFactory; class TexturesHandler { private: std::vector<TextureHolder*> _textureHolders; IGL * const _gl; const IFactory * const _factory; const TextureBuilder* _texBuilder; const bool _verbose; public: TexturesHandler(IGL* const gl, const IFactory const * factory, const TextureBuilder* texBuilder, bool verbose): _gl(gl), _factory(factory), _texBuilder(texBuilder), _verbose(verbose) { } ~TexturesHandler(); int getTextureIdFromFileName(const std::string& filename, int textureWidth, int textureHeight); int getTextureId(const std::vector<const IImage*>& images, const std::string& textureId, int textureWidth, int textureHeight); int getTextureId(const std::vector<const IImage*>& images, const std::vector<const Rectangle*>& rectangles, const std::string& textureId, int textureWidth, int textureHeight); int getTextureId(const IImage* image, const std::string& textureId, int textureWidth, int textureHeight); int getTextureIdIfAvailable(const std::string& textureId, int textureWidth, int textureHeight); void takeTexture(int glTextureId); }; #endif <commit_msg>Java conversion tasks<commit_after>// // TexturesHandler.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 19/06/12. // Copyright (c) 2012 IGO Software SL. All rights reserved. // #ifndef G3MiOSSDK_TexturesHandler_hpp #define G3MiOSSDK_TexturesHandler_hpp #include <string> #include <vector> #include "TextureBuilder.hpp" class IImage; class RenderContext; class TextureHolder; class IGL; class IFactory; class TexturesHandler { private: std::vector<TextureHolder*> _textureHolders; IGL * const _gl; const IFactory * const _factory; const TextureBuilder* _texBuilder; const bool _verbose; public: TexturesHandler(IGL* const gl, const IFactory const * factory, const TextureBuilder* texBuilder, bool verbose): _gl(gl), _factory(factory), _texBuilder(texBuilder), _verbose(verbose) { } ~TexturesHandler(); int getTextureIdFromFileName(const std::string& filename, int textureWidth, int textureHeight); int getTextureId(const std::vector<const IImage*>& images, const std::string& textureId, int textureWidth, int textureHeight); int getTextureId(const std::vector<const IImage*>& images, const std::vector<const Rectangle*>& rectangles, const std::string& textureId, int textureWidth, int textureHeight); int getTextureId(const IImage* image, const std::string& textureId, int textureWidth, int textureHeight); int getTextureIdIfAvailable(const std::string& textureId, int textureWidth, int textureHeight); void takeTexture(int glTextureId); }; #endif <|endoftext|>
<commit_before>#include "Sketch.h" #include "chr/gl/draw/Torus.h" #include "chr/gl/draw/Sphere.h" using namespace std; using namespace chr; using namespace gl; using namespace draw; Sketch::Sketch() : shader(InputSource::resource("Shader.vert"), InputSource::resource("Shader.frag")) {} void Sketch::setup() { Torus() .setFrontFace(CW) .setSliceCount(20) .setLoopCount(60) .setInnerRadius(25) .setOuterRadius(100) .append(modelBatch, Matrix()); lightBatch .setShader(colorShader) .setShaderColor(1, 1, 1, 1); // --- glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void Sketch::resize() { camera .setFov(60) .setClip(0.1f, 1000.0f) .setWindowSize(windowInfo.size); } void Sketch::draw() { glClearColor(0.5f, 0.5f, 0.5f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // --- camera.getViewMatrix() .setIdentity() .translate(0, 0, -300) .rotateY(clock()->getTime() * 0.125f); // float t = clock()->getTime() * 1.0f; float radius = 150; float x = cosf(t) * radius; float y = 0; float z = sinf(t) * radius; glm::vec3 lightPosition(x, y, z); // State() .setShaderMatrix<MVP>(camera.getViewProjectionMatrix()) .apply(); lightBatch.clear(); Sphere() .setFrontFace(CW) .setSectorCount(16) .setStackCount(8) .setRadius(4) .append(lightBatch, Matrix().setTranslate(lightPosition)); lightBatch.flush(); // State() .setShader(shader) .setShaderMatrix<MODEL>(Matrix()) .setShaderMatrix<VIEW>(camera.getViewMatrix()) .setShaderMatrix<PROJECTION>(camera.getProjectionMatrix()) .setShaderMatrix<NORMAL>(camera.getNormalMatrix()) .setShaderUniform("u_light_position", lightPosition) .setShaderUniform("u_light_color", glm::vec3(1.0, 1.0, 1.0)) .setShaderUniform("u_light_intensity", 1.0f) .setShaderUniform("u_ambient_color", glm::vec3(0, 0, 0)) .setShaderUniform("u_diffuse_color", glm::vec3(1.0f, 0.5f, 0.0f)) .setShaderUniform("u_specular_color", glm::vec3(1, 1, 1)) .setShaderUniform("u_shininess", 25.0f) .apply(); modelBatch.flush(); } <commit_msg>TestingLighting: Cosmetic tweaks<commit_after>#include "Sketch.h" #include "chr/gl/draw/Torus.h" #include "chr/gl/draw/Sphere.h" using namespace std; using namespace chr; using namespace gl; using namespace draw; Sketch::Sketch() : shader(InputSource::resource("Shader.vert"), InputSource::resource("Shader.frag")) {} void Sketch::setup() { Torus() .setFrontFace(CW) .setSliceCount(20) .setLoopCount(60) .setInnerRadius(25) .setOuterRadius(100) .append(modelBatch, Matrix()); modelBatch.setShader(shader); lightBatch .setShader(colorShader) .setShaderColor(1, 1, 1, 1); // --- glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void Sketch::resize() { camera .setFov(60) .setClip(0.1f, 1000.0f) .setWindowSize(windowInfo.size); } void Sketch::draw() { glClearColor(0.5f, 0.5f, 0.5f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // --- camera.getViewMatrix() .setIdentity() .translate(0, 0, -300) .rotateY(clock()->getTime() * 0.125f); // float t = clock()->getTime() * 1.0f; float radius = 150; float x = cosf(t) * radius; float y = 0; float z = sinf(t) * radius; glm::vec3 lightPosition(x, y, z); // State() .setShaderMatrix<MVP>(camera.getViewProjectionMatrix()) .apply(); lightBatch.clear(); Sphere() .setFrontFace(CW) .setSectorCount(16) .setStackCount(8) .setRadius(4) .append(lightBatch, Matrix().translate(lightPosition)); lightBatch.flush(); // State() .setShaderMatrix<MODEL>(Matrix()) .setShaderMatrix<VIEW>(camera.getViewMatrix()) .setShaderMatrix<PROJECTION>(camera.getProjectionMatrix()) .setShaderMatrix<NORMAL>(camera.getNormalMatrix()) .setShaderUniform("u_light_position", lightPosition) .setShaderUniform("u_light_color", glm::vec3(1.0, 1.0, 1.0)) .setShaderUniform("u_light_intensity", 1.0f) .setShaderUniform("u_ambient_color", glm::vec3(0, 0, 0)) .setShaderUniform("u_diffuse_color", glm::vec3(1.0f, 0.5f, 0.0f)) .setShaderUniform("u_specular_color", glm::vec3(1, 1, 1)) .setShaderUniform("u_shininess", 25.0f) .apply(); modelBatch.flush(); } <|endoftext|>
<commit_before>/*! * \file x11/RandR/iRandR_reload.cpp * \brief \b Classes: \a iRandR */ /* * Copyright (C) 2015 EEnginE project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if D_LOG_XRANDR #include "iRandR.hpp" #include "uLog.hpp" #include "eCMDColor.hpp" namespace e_engine { namespace unix_x11 { namespace { /*! * \brief Fill a string with chars until it has a specific size. * * \param _str [in] The string to resize * \param _size [in] The wished size * \param _fill [in] Fill it with these chars * * \returns The result */ std::string placeStringLeft( std::string _str, unsigned int _size, char _fill ) { if ( _str.size() == _size ) return _str; std::string lResult_str = _str; if ( lResult_str.size() > _size ) { lResult_str.resize( _size ); return lResult_str; } lResult_str.append( _size - lResult_str.size(), _fill ); return lResult_str; } } /*! * \brief Prints a (more or less) fancy table with all XRandR information */ void iRandR::printRandRStatus() { if ( !vIsRandRSupported_B ) return; reload( false ); std::wstring lOFF_C = eCMDColor::color( 'O', 'W' ); std::wstring lBW_C = eCMDColor::color( 'B', 'W' ); std::wstring lBR_C = eCMDColor::color( 'B', 'R' ); std::wstring lBG_C = eCMDColor::color( 'B', 'G' ); std::wstring lBB_C = eCMDColor::color( 'B', 'B' ); std::wstring lBC_C = eCMDColor::color( 'B', 'C' ); std::wstring lR_C = eCMDColor::color( 'O', 'R' ); std::wstring lG_C = eCMDColor::color( 'O', 'G' ); std::wstring lB_C = eCMDColor::color( 'O', 'B' ); std::wstring lC_C = eCMDColor::color( 'O', 'C' ); // // -- HEADDER // // |============|======|=========|===========|============|=========================| // | Output | CRTC | Primary | Connected | Position | MODE | // | | | | | | Resolutions | Rates | // |------------|------|---------|-----------|------------|---------------|---------| iLOG( "RandR Info -- Screen Size: ", lBG_C, vScreenWidth_uI, 'x', vScreenHeight_uI, "\n" ); LOG( _hD, "|============|======|=========|===========|============|=========================|" ); LOG( _hD, "| ", lBW_C, "Output", lOFF_C, " | ", lBW_C, "CRTC", lOFF_C, " | ", lBW_C, "Primary", lOFF_C, " | ", lBW_C, "Connected", lOFF_C, " | ", lBW_C, "Position", lOFF_C, " | ", lBW_C, "MODE", lOFF_C, " |" ); LOG( _hD, "| | | | | | ", lBW_C, "Resolutions", lOFF_C, " | ", lBW_C, "Rates", lOFF_C, " |" ); LOG( _hD, "|------------|------|---------|-----------|------------|---------------|---------|" ); // // -- Entries // for ( internal::_output const &fOutput : vOutput_V_RandR ) { internal::_crtc lCRTC_RandR; std::string lCRTC_str = ( fOutput.crtc == 0 ) ? "OFF" : std::to_string( fOutput.crtc ); std::string lPrimary_str = ( vLatestConfig_RandR.primary == fOutput.id ) ? "YES" : "NO"; std::string lConnected_str = ( fOutput.connection == 0 ) ? "YES" : ( fOutput.connection == 2 ) ? "???" : "NO"; std::string lPosition_str = " NONE"; char lBold_C = ( fOutput.connection == 0 ) ? 'B' : 'O'; char lCRTC_C = ( lCRTC_str != "OFF" ) ? 'G' : 'R'; if ( !( fOutput.crtc == 0 ) ) { for ( internal::_crtc const &fCRTC : vCRTC_V_RandR ) { if ( fCRTC.id == fOutput.crtc ) { lCRTC_RandR = fCRTC; lPosition_str = ""; if ( fCRTC.posX >= 0 ) lPosition_str += '+'; lPosition_str += std::to_string( fCRTC.posX ); if ( fCRTC.posY >= 0 ) lPosition_str += '+'; lPosition_str += std::to_string( fCRTC.posY ); break; } } } std::wstring lCO_C = eCMDColor::color( 'O', 'W' ); std::wstring lC1_C = eCMDColor::color( lBold_C, 'W' ); std::wstring lC2_C = eCMDColor::color( lBold_C, lCRTC_C ); if ( lBold_C == 'B' ) { LOG( _hD, "| | | | | | | " " |" ); } if ( lBold_C == 'O' || fOutput.modes.size() == 0 ) { LOG( _hD, "| ", lC1_C, placeStringLeft( fOutput.name, 11, ' ' ), lCO_C, "| ", lC2_C, placeStringLeft( lCRTC_str, 5, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPrimary_str, 6, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lConnected_str, 7, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPosition_str, 11, ' ' ), lCO_C, "| OFFLINE | OFF |" ); } unsigned int lWidth_uI = 0; unsigned int lHeight_uI = 0; std::string lModeSize_str; // Unfortunately std::to_string doesn't support precision, so we must use sprintf if we want // to avoid the slow stringstreams char lModeFreq_CSTR[15]; std::string lModeFreq_str; bool lIsFirstModePrinted_B = true; // // -- Modes // for ( internal::_mode const &fMode : vMode_V_RandR ) { bool lFoundMode_B = false; bool lModePrefered_B = false; char lAtrib_C = 'O'; char lColor_C = 'W'; unsigned int lModeCounter_uI = 0; //!< Needed for preferred check // Check if the mode is supported by the output for ( RRMode const &fTempMode : fOutput.modes ) { ++lModeCounter_uI; if ( fTempMode == fMode.id ) { lFoundMode_B = true; if ( lModeCounter_uI == static_cast<unsigned int>( fOutput.npreferred ) ) lModePrefered_B = true; break; } } if ( !lFoundMode_B ) continue; if ( fMode.width == lWidth_uI && fMode.height == lHeight_uI ) { lModeSize_str.clear(); } else { lWidth_uI = fMode.width; lHeight_uI = fMode.height; lModeSize_str = std::to_string( lWidth_uI ) + 'x' + std::to_string( lHeight_uI ); } snprintf( lModeFreq_CSTR, 15, "%.2f", fMode.refresh ); lModeFreq_str = lModeFreq_CSTR; // This should never happen if ( !lFoundMode_B ) { lModeSize_str = "RandR"; lModeFreq_str = "ERROR"; } // This is a (!) mode with the current width and height of the CRTC if ( lWidth_uI == lCRTC_RandR.width && lHeight_uI == lCRTC_RandR.height ) { lAtrib_C = 'B'; if ( !lModeSize_str.empty() ) lModeSize_str += '*'; } // This is the (!) mode of the CRTC if ( fMode.id == lCRTC_RandR.mode ) { lAtrib_C = 'B'; lModeFreq_str += '*'; } // This is the preferred mode if ( lModePrefered_B ) { lColor_C = 'G'; lModeFreq_str += '+'; } std::wstring lC3_C = eCMDColor::color( lAtrib_C, lColor_C ); if ( !lIsFirstModePrinted_B ) { LOG( _hD, "| | | | | | ", lC3_C, placeStringLeft( lModeSize_str, 12, ' ' ), lCO_C, "| ", lC3_C, placeStringLeft( lModeFreq_str, 8, ' ' ), lCO_C, '|' ); } else { LOG( _hD, "| ", lC1_C, placeStringLeft( fOutput.name, 11, ' ' ), lCO_C, "| ", lC2_C, placeStringLeft( lCRTC_str, 5, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPrimary_str, 6, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lConnected_str, 7, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPosition_str, 11, ' ' ), lCO_C, "| ", lC3_C, placeStringLeft( lModeSize_str, 12, ' ' ), lCO_C, "| ", lC3_C, placeStringLeft( lModeFreq_str, 8, ' ' ), lCO_C, '|' ); } lIsFirstModePrinted_B = false; } } LOG( _hD, "|============|======|=========|===========|============|=========================|\n\n" ); } } // unix_x11 } // e_engine #endif // D_LOG_XRANDR // kate: indent-mode cstyle; indent-width 3; replace-tabs on; line-numbers on; <commit_msg>Fix log activated build.<commit_after>/*! * \file x11/RandR/iRandR_reload.cpp * \brief \b Classes: \a iRandR */ /* * Copyright (C) 2015 EEnginE project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "defines.hpp" #if D_LOG_XRANDR #include "iRandR.hpp" #include "uLog.hpp" #include "eCMDColor.hpp" namespace e_engine { namespace unix_x11 { namespace { /*! * \brief Fill a string with chars until it has a specific size. * * \param _str [in] The string to resize * \param _size [in] The wished size * \param _fill [in] Fill it with these chars * * \returns The result */ std::string placeStringLeft( std::string _str, unsigned int _size, char _fill ) { if ( _str.size() == _size ) return _str; std::string lResult_str = _str; if ( lResult_str.size() > _size ) { lResult_str.resize( _size ); return lResult_str; } lResult_str.append( _size - lResult_str.size(), _fill ); return lResult_str; } } /*! * \brief Prints a (more or less) fancy table with all XRandR information */ void iRandR::printRandRStatus() { if ( !vIsRandRSupported_B ) return; reload( false ); std::wstring lOFF_C = eCMDColor::color( 'O', 'W' ); std::wstring lBW_C = eCMDColor::color( 'B', 'W' ); std::wstring lBR_C = eCMDColor::color( 'B', 'R' ); std::wstring lBG_C = eCMDColor::color( 'B', 'G' ); std::wstring lBB_C = eCMDColor::color( 'B', 'B' ); std::wstring lBC_C = eCMDColor::color( 'B', 'C' ); std::wstring lR_C = eCMDColor::color( 'O', 'R' ); std::wstring lG_C = eCMDColor::color( 'O', 'G' ); std::wstring lB_C = eCMDColor::color( 'O', 'B' ); std::wstring lC_C = eCMDColor::color( 'O', 'C' ); // // -- HEADDER // // |============|======|=========|===========|============|=========================| // | Output | CRTC | Primary | Connected | Position | MODE | // | | | | | | Resolutions | Rates | // |------------|------|---------|-----------|------------|---------------|---------| iLOG( "RandR Info -- Screen Size: ", lBG_C, vScreenWidth_uI, 'x', vScreenHeight_uI, "\n" ); LOG( _hD, "|============|======|=========|===========|============|=========================|" ); LOG( _hD, "| ", lBW_C, "Output", lOFF_C, " | ", lBW_C, "CRTC", lOFF_C, " | ", lBW_C, "Primary", lOFF_C, " | ", lBW_C, "Connected", lOFF_C, " | ", lBW_C, "Position", lOFF_C, " | ", lBW_C, "MODE", lOFF_C, " |" ); LOG( _hD, "| | | | | | ", lBW_C, "Resolutions", lOFF_C, " | ", lBW_C, "Rates", lOFF_C, " |" ); LOG( _hD, "|------------|------|---------|-----------|------------|---------------|---------|" ); // // -- Entries // for ( internal::_output const &fOutput : vOutput_V_RandR ) { internal::_crtc lCRTC_RandR; std::string lCRTC_str = ( fOutput.crtc == 0 ) ? "OFF" : std::to_string( fOutput.crtc ); std::string lPrimary_str = ( vLatestConfig_RandR.primary == fOutput.id ) ? "YES" : "NO"; std::string lConnected_str = ( fOutput.connection == 0 ) ? "YES" : ( fOutput.connection == 2 ) ? "???" : "NO"; std::string lPosition_str = " NONE"; char lBold_C = ( fOutput.connection == 0 ) ? 'B' : 'O'; char lCRTC_C = ( lCRTC_str != "OFF" ) ? 'G' : 'R'; if ( !( fOutput.crtc == 0 ) ) { for ( internal::_crtc const &fCRTC : vCRTC_V_RandR ) { if ( fCRTC.id == fOutput.crtc ) { lCRTC_RandR = fCRTC; lPosition_str = ""; if ( fCRTC.posX >= 0 ) lPosition_str += '+'; lPosition_str += std::to_string( fCRTC.posX ); if ( fCRTC.posY >= 0 ) lPosition_str += '+'; lPosition_str += std::to_string( fCRTC.posY ); break; } } } std::wstring lCO_C = eCMDColor::color( 'O', 'W' ); std::wstring lC1_C = eCMDColor::color( lBold_C, 'W' ); std::wstring lC2_C = eCMDColor::color( lBold_C, lCRTC_C ); if ( lBold_C == 'B' ) { LOG( _hD, "| | | | | | | " " |" ); } if ( lBold_C == 'O' || fOutput.modes.size() == 0 ) { LOG( _hD, "| ", lC1_C, placeStringLeft( fOutput.name, 11, ' ' ), lCO_C, "| ", lC2_C, placeStringLeft( lCRTC_str, 5, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPrimary_str, 6, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lConnected_str, 7, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPosition_str, 11, ' ' ), lCO_C, "| OFFLINE | OFF |" ); } unsigned int lWidth_uI = 0; unsigned int lHeight_uI = 0; std::string lModeSize_str; // Unfortunately std::to_string doesn't support precision, so we must use sprintf if we want // to avoid the slow stringstreams char lModeFreq_CSTR[15]; std::string lModeFreq_str; bool lIsFirstModePrinted_B = true; // // -- Modes // for ( internal::_mode const &fMode : vMode_V_RandR ) { bool lFoundMode_B = false; bool lModePrefered_B = false; char lAtrib_C = 'O'; char lColor_C = 'W'; unsigned int lModeCounter_uI = 0; //!< Needed for preferred check // Check if the mode is supported by the output for ( RRMode const &fTempMode : fOutput.modes ) { ++lModeCounter_uI; if ( fTempMode == fMode.id ) { lFoundMode_B = true; if ( lModeCounter_uI == static_cast<unsigned int>( fOutput.npreferred ) ) lModePrefered_B = true; break; } } if ( !lFoundMode_B ) continue; if ( fMode.width == lWidth_uI && fMode.height == lHeight_uI ) { lModeSize_str.clear(); } else { lWidth_uI = fMode.width; lHeight_uI = fMode.height; lModeSize_str = std::to_string( lWidth_uI ) + 'x' + std::to_string( lHeight_uI ); } snprintf( lModeFreq_CSTR, 15, "%.2f", fMode.refresh ); lModeFreq_str = lModeFreq_CSTR; // This should never happen if ( !lFoundMode_B ) { lModeSize_str = "RandR"; lModeFreq_str = "ERROR"; } // This is a (!) mode with the current width and height of the CRTC if ( lWidth_uI == lCRTC_RandR.width && lHeight_uI == lCRTC_RandR.height ) { lAtrib_C = 'B'; if ( !lModeSize_str.empty() ) lModeSize_str += '*'; } // This is the (!) mode of the CRTC if ( fMode.id == lCRTC_RandR.mode ) { lAtrib_C = 'B'; lModeFreq_str += '*'; } // This is the preferred mode if ( lModePrefered_B ) { lColor_C = 'G'; lModeFreq_str += '+'; } std::wstring lC3_C = eCMDColor::color( lAtrib_C, lColor_C ); if ( !lIsFirstModePrinted_B ) { LOG( _hD, "| | | | | | ", lC3_C, placeStringLeft( lModeSize_str, 12, ' ' ), lCO_C, "| ", lC3_C, placeStringLeft( lModeFreq_str, 8, ' ' ), lCO_C, '|' ); } else { LOG( _hD, "| ", lC1_C, placeStringLeft( fOutput.name, 11, ' ' ), lCO_C, "| ", lC2_C, placeStringLeft( lCRTC_str, 5, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPrimary_str, 6, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lConnected_str, 7, ' ' ), lCO_C, "| ", lC1_C, placeStringLeft( lPosition_str, 11, ' ' ), lCO_C, "| ", lC3_C, placeStringLeft( lModeSize_str, 12, ' ' ), lCO_C, "| ", lC3_C, placeStringLeft( lModeFreq_str, 8, ' ' ), lCO_C, '|' ); } lIsFirstModePrinted_B = false; } } LOG( _hD, "|============|======|=========|===========|============|=========================|\n\n" ); } } // unix_x11 } // e_engine #endif // D_LOG_XRANDR // kate: indent-mode cstyle; indent-width 3; replace-tabs on; line-numbers on; <|endoftext|>
<commit_before>// dui-demo.cpp : main source file // #include "stdafx.h" #include "DuiSystem.h" #ifdef _DEBUG #include <vld.h>//ʹVitural Leaker Detectorڴй©Դhttp://vld.codeplex.com/ #endif #include "MainDlg.h" #ifndef DLL_SOUI #include "../render-skia/render-skia.h" #include "../imgdecoder-wic/imgdecoder-wic.h" #ifdef _DEBUG #pragma comment(lib,"utilities_d.lib") #pragma comment(lib,"render-skia_d.lib") #pragma comment(lib,"imgdecoder-wic_d.lib") #pragma comment(lib,"skcore_d.lib") #else #pragma comment(lib,"utilities.lib") #pragma comment(lib,"render-skia.lib") #pragma comment(lib,"imgdecoder-wic.lib") #pragma comment(lib,"skcore.lib") #endif #endif int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpstrCmdLine*/, int /*nCmdShow*/) { HRESULT hRes = OleInitialize(NULL); DUIASSERT(SUCCEEDED(hRes)); CAutoRefPtr<SOUI::IImgDecoderFactory> pImgDecoderFactory; CAutoRefPtr<SOUI::IRenderFactory> pRenderFactory; #ifndef _LIB #ifdef _DEBUG HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic_d.dll")); HMODULE hRender = LoadLibrary(_T("render-skia_d.dll")); #else HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic.dll")); HMODULE hRender = LoadLibrary(_T("render-skia.dll")); #endif typedef BOOL (*fnCreateImgDecoderFactory)(SOUI::IImgDecoderFactory**); fnCreateImgDecoderFactory funImg = (fnCreateImgDecoderFactory)GetProcAddress(hImgDecoder,"CreateImgDecoderFactory"); funImg(&pImgDecoderFactory); typedef BOOL (*fnCreateRenderFactory)(SOUI::IRenderFactory **,SOUI::IImgDecoderFactory *); fnCreateRenderFactory funRender = (fnCreateRenderFactory)GetProcAddress(hRender,"CreateRenderFactory"); funRender(&pRenderFactory,pImgDecoderFactory); #else SOUI::CreateImgDecoderFactory(&pImgDecoderFactory); RENDER_SKIA::CreateRenderFactory(&pRenderFactory,pImgDecoderFactory); #endif DuiSystem *pDuiSystem=new DuiSystem(pRenderFactory,hInstance); #if 1 TCHAR szCurrentDir[MAX_PATH]; memset( szCurrentDir, 0, sizeof(szCurrentDir) ); GetModuleFileName( NULL, szCurrentDir, sizeof(szCurrentDir) ); LPTSTR lpInsertPos = _tcsrchr( szCurrentDir, _T('\\') ); *lpInsertPos = _T('\0'); _tcscat( szCurrentDir, _T("\\..\\demo\\skin") ); DuiResProviderFiles *pResProvider=new DuiResProviderFiles; if(!pResProvider->Init(szCurrentDir)) { DUIASSERT(0); return 1; } #else DuiResProviderPE *pResProvider = new DuiResProviderPE(hInstance); #endif pDuiSystem->AddResProvider(pResProvider); BOOL bOK=pDuiSystem->Init(_T("IDR_DUI_INIT")); //ʼDUIϵͳ,ԭϵͳʼʽȻʹá pDuiSystem->SetMsgBoxTemplate(_T("IDR_DUI_MSGBOX")); int nRet = 0; // BLOCK: Run application { CMainDlg dlgMain; nRet = dlgMain.DoModal(); } delete pDuiSystem; delete pResProvider; pRenderFactory=NULL; pImgDecoderFactory=NULL; OleUninitialize(); return nRet; } <commit_msg><commit_after>// dui-demo.cpp : main source file // #include "stdafx.h" #include "DuiSystem.h" #ifdef _DEBUG #include <vld.h>//ʹVitural Leaker Detectorڴй©Դhttp://vld.codeplex.com/ #endif #include "MainDlg.h" #ifndef DLL_SOUI #include "../render-skia/render-skia.h" #include "../imgdecoder-wic/imgdecoder-wic.h" #ifdef _DEBUG #pragma comment(lib,"utilities_d.lib") #pragma comment(lib,"render-skia_d.lib") #pragma comment(lib,"imgdecoder-wic_d.lib") #pragma comment(lib,"skcore_d.lib") #else #pragma comment(lib,"utilities.lib") #pragma comment(lib,"render-skia.lib") #pragma comment(lib,"imgdecoder-wic.lib") #pragma comment(lib,"skcore.lib") #endif #endif int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpstrCmdLine*/, int /*nCmdShow*/) { HRESULT hRes = OleInitialize(NULL); DUIASSERT(SUCCEEDED(hRes)); CAutoRefPtr<SOUI::IImgDecoderFactory> pImgDecoderFactory; CAutoRefPtr<SOUI::IRenderFactory> pRenderFactory; #ifndef _LIB #ifdef _DEBUG HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic_d.dll")); HMODULE hRender = LoadLibrary(_T("render-skia_d.dll")); #else HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic.dll")); HMODULE hRender = LoadLibrary(_T("render-skia.dll")); #endif typedef BOOL (*fnCreateImgDecoderFactory)(SOUI::IImgDecoderFactory**,BOOL); fnCreateImgDecoderFactory funImg = (fnCreateImgDecoderFactory)GetProcAddress(hImgDecoder,"CreateImgDecoderFactory_WIC"); funImg(&pImgDecoderFactory,TRUE); typedef BOOL (*fnCreateRenderFactory)(SOUI::IRenderFactory **,SOUI::IImgDecoderFactory *); fnCreateRenderFactory funRender = (fnCreateRenderFactory)GetProcAddress(hRender,"CreateRenderFactory"); funRender(&pRenderFactory,pImgDecoderFactory); #else SOUI::CreateImgDecoderFactory_WIC(&pImgDecoderFactory,TRUE); RENDER_SKIA::CreateRenderFactory(&pRenderFactory,pImgDecoderFactory); #endif DuiSystem *pDuiSystem=new DuiSystem(pRenderFactory,hInstance); #if 1 TCHAR szCurrentDir[MAX_PATH]; memset( szCurrentDir, 0, sizeof(szCurrentDir) ); GetModuleFileName( NULL, szCurrentDir, sizeof(szCurrentDir) ); LPTSTR lpInsertPos = _tcsrchr( szCurrentDir, _T('\\') ); *lpInsertPos = _T('\0'); _tcscat( szCurrentDir, _T("\\..\\demo\\skin") ); DuiResProviderFiles *pResProvider=new DuiResProviderFiles; if(!pResProvider->Init(szCurrentDir)) { DUIASSERT(0); return 1; } #else DuiResProviderPE *pResProvider = new DuiResProviderPE(hInstance); #endif pDuiSystem->AddResProvider(pResProvider); BOOL bOK=pDuiSystem->Init(_T("IDR_DUI_INIT")); //ʼDUIϵͳ,ԭϵͳʼʽȻʹá pDuiSystem->SetMsgBoxTemplate(_T("IDR_DUI_MSGBOX")); int nRet = 0; // BLOCK: Run application { CMainDlg dlgMain; nRet = dlgMain.DoModal(); } delete pDuiSystem; delete pResProvider; pRenderFactory=NULL; pImgDecoderFactory=NULL; OleUninitialize(); return nRet; } <|endoftext|>
<commit_before>#include "mainview.h" #include "ui_mainview.h" #include "mibittip.h" #include "mibitdialog.h" #include <QDebug> #include <QTimer> mainView::mainView(QWidget *parent) : QWidget(parent), ui(new Ui::mainView) { ui->setupUi(this); tip1 = new MibitTip(this, ui->dtedit, "tip.svg",QPixmap("important.png") ); tip2 = new MibitTip(this, ui->edit1, "tip.svg", QPixmap("important.png") ); tip3 = new MibitTip(this, ui->btnTest3, "tip.svg", QPixmap("important.png"), tpAbove ); dialog1 = new MibitDialog(this,"Welcome to mibitWidgets Demo!","dialog-theme.svg",QPixmap("face-smile.png"), atSlideDown ); dialog1->setSize(200,100); connect(ui->btnTest1, SIGNAL(clicked()), SLOT(showTip1())); connect(ui->btnTest2, SIGNAL(clicked()), SLOT(showTip2())); connect(ui->btnTest3, SIGNAL(clicked()), SLOT(showTip3())); connect(ui->btnDialog2, SIGNAL(clicked()), SLOT(showDialog2())); QTimer::singleShot(500,this,SLOT(showDialog1())); } mainView::~mainView() { delete ui; } void mainView::showTip1() { tip1->showTip("This is a demo for the mibitTip class.. The tip slides down below its partner control."); } void mainView::showTip2() { tip2->showTip("This is a demo for the mibitTip class.. Just more text to display."); } void mainView::showTip3() { tip3->showTip("This is a demo for the mibitTip class.. We also can draw it above the control, sliding up.."); } void mainView::showDialog1() { dialog1->showDialog(); } void mainView::showDialog2() { dialog1->showDialog("Dialog with a slide down animation!", atSlideDown); } <commit_msg>Fixing broken build due to modifing code location<commit_after>#include "mainview.h" #include "ui_mainview.h" #include "../mibittip.h" #include "../mibitdialog.h" #include <QDebug> #include <QTimer> mainView::mainView(QWidget *parent) : QWidget(parent), ui(new Ui::mainView) { ui->setupUi(this); tip1 = new MibitTip(this, ui->dtedit, "tip.svg",QPixmap("important.png") ); tip2 = new MibitTip(this, ui->edit1, "tip.svg", QPixmap("important.png") ); tip3 = new MibitTip(this, ui->btnTest3, "tip.svg", QPixmap("important.png"), tpAbove ); dialog1 = new MibitDialog(this,"Welcome to mibitWidgets Demo!","dialog-theme.svg",QPixmap("face-smile.png"), atSlideDown ); dialog1->setSize(200,100); connect(ui->btnTest1, SIGNAL(clicked()), SLOT(showTip1())); connect(ui->btnTest2, SIGNAL(clicked()), SLOT(showTip2())); connect(ui->btnTest3, SIGNAL(clicked()), SLOT(showTip3())); connect(ui->btnDialog2, SIGNAL(clicked()), SLOT(showDialog2())); QTimer::singleShot(500,this,SLOT(showDialog1())); } mainView::~mainView() { delete ui; } void mainView::showTip1() { tip1->showTip("This is a demo for the mibitTip class.. The tip slides down below its partner control."); } void mainView::showTip2() { tip2->showTip("This is a demo for the mibitTip class.. Just more text to display."); } void mainView::showTip3() { tip3->showTip("This is a demo for the mibitTip class.. We also can draw it above the control, sliding up.."); } void mainView::showDialog1() { dialog1->showDialog(); } void mainView::showDialog2() { dialog1->showDialog("Dialog with a slide down animation!", atSlideDown); } <|endoftext|>
<commit_before>#ifndef GLOBAL_H_INCLUDED #define GLOBAL_H_INCLUDED // C++11 Standard. #include <string> #include <sstream> #include <utility> #include <type_traits> /// for is_class, ... using namespace std; /// /// GLOBAL_DEBUG /// namespace wiz{ #define COL_BASED #define ROW_BASED #define WIZ_IN const #define IN #define OUT #define INOUT #define AND && #define OR || #define NOT ! #define EQUAL == /* template <class T> inline T max( const T& t1, const T& t2 ) { if( t2 < t1 ) { return t1; } return t2; } template <class T> inline T min( const T& t1, const T& t2 ) { if( t1 < t2 ) { return t1; } return t2; } */ /// template <class T> class STD_SWAP { public: void operator()( T& t1, T& t2 ) { std::swap( t1, t2 ); /// if c++11, maybe move...or make Move } }; template <class T> class NORMAL_SWAP { public: void operator()( T& t1, T& t2 ) { T temp = t1; t1 = t2; t2 = temp; } }; template <class T> class HAS_SWAP_METHOD { public: void operator()( T& t1, T& t2 ) { t1.swap( t2 ); } }; template <class T> class WIZ_SWAP { public: void operator()( T& t1, T& t2 ) { std::swap( t1, t2 ); } }; template < class T, class SWAP=STD_SWAP<T> > inline void Swap( T& t1, T& t2 ) { SWAP()( t1, t2 ); } /// TO DO /// MOVE, NO_MOVE /// ( T& t1, T& t2 ) /// t1 = t2; // NO_MOVE /// t1 = move( t2 ); // MOVE template <class T> class ASC { public: bool operator() (const T& t1, const T& t2) const { return t1 < t2; } }; template <class T> class DSC // DESC { public: bool operator() (const T& t1, const T& t2) const { return t1 > t2; } }; template <class T> class EQ { // EE -> EQ! public: bool operator() (const T& t1, const T& t2) const { return t1 == t2; } }; /// TO DO /// ASC_EE, DSC_EE, NOT_EE, EE_SAME_VALUE, NOT_EE_SAME_VALUE , chk red-black tree!! template <class T> class ASC_EE { public: bool operator() (const T& t1, const T& t2) const { return t1 <= t2; } }; template <class T> class DSC_EE { public: bool operator() (const T& t1, const T& t2) const { return t1 >= t2; } }; template <class T> class NOT_EE { public: bool operator() (const T& t1, const T& t2) const { return t1 != t2; } }; template <class T> class EE_SAME_VALUE { public: bool operator() (const T& t1, const T& t2) const { return t1.isSameValue( t2 ); } }; template <class T> class NOT_EE_SAME_VALUE { /// chk.. public: bool operator() (const T& t1, const T& t2) const { return !t1.isSameValue( t2 ); } }; template <class T> /// T is pointer type.. class PASC { public: bool operator() (const T t1, const T t2) const { return *t1 < *t2; } }; template <class T> /// T is pointer type.. class PDSC // PDESC { public: bool operator() ( const T t1, const T t2 ) const { return *t1 > *t2; } }; template <class T> /// T is pointer type.. class PEE { public: bool operator() (const T t1, const T t2) const { return *t1 == *t2; } }; /// TO DO /// PASC_PEE, PDSC_PEE, PNOT_EE, PEE_SAME_VALUE, PNOT_EE_SAME_VALUE /// LEFT_HAS_SMALL_VALUE, LEFT_HAS_LARGE_VALUE, PLEFT_HAS_SMALL_VALUE, PLEFT_HAS_LARGE_VALUE template <typename T> /// T <- char, int, long, long long... string toStr(const T x, const int base); /// chk!! template <class T, class COMP = ASC<T>, class COMP2 = ASC<int>, class EE = EQ<T> > /// 쒖꽌 諛붽씀湲 - 2015.07.18 class WrapForInfinity { enum Op{ MIF = 0, GR = 1, IF = 2 }; COMP comp; COMP2 comp2; EE ee; Op op; // Option private: explicit WrapForInfinity(const T& val, const Op& op) : val(val), op(op) { } public: explicit WrapForInfinity(const T& val = T()) : val(val), op(GR) { } public: T val; bool operator>(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const { return wfi < (*this); } bool operator<(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const { if (GR == this->op&& GR == wfi.op) { return comp(this->val, wfi.val); } else { return comp2( this->op, wfi.op ); /// chk... } } bool operator==(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const { if( wfi.op == IF && this->op == IF ) { return true; } if( wfi.op == MIF && this->op == MIF ) { return true; } return (ee(wfi.val, this->val) && wfi.op == this->op); } bool operator!=( const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const { return !( *this == wfi ); } bool operator<=(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const { return *this < wfi || *this == wfi; } bool operator>=(const WrapForInfinity <T,COMP, COMP2, EE>& wfi)const { return wfi <= *this; } WrapForInfinity<T> operator+(const WrapForInfinity<T>& other)const { if (other.op == this->op) { return WrapForInfinity<T>(this->val + other.val, this->op); } else if (this->op == MIF && other.op == GR) { return WrapForInfinity<T>::GetMinusInfinity(); } else if (this->op == IF && other.op == GR) { return WrapForInfinity<T>::GetInfinity(); } else if (this->op == GR && other.op == IF) { return WrapForInfinity<T>::GetInfinity(); } else if (this->op == GR && other.op == MIF) { return WrapForInfinity<T>::GetMinusInfinity(); } else if (this->op == MIF && other.op == MIF) { return WrapForInfinity<T>::GetMinusInfinity(); } else if (this->op == IF && other.op == IF) { return WrapForInfinity<T>::GetInfinity(); } else { throw string(" + Error in wrapforinfiinity"); } } WrapForInfinity<T> operator-(const WrapForInfinity<T>& other)const { if (other.op == this->op && this->op == GR) { return WrapForInfinity<T>(this->val - other.val, this->op); } else if (this->op == MIF && other.op == GR) { return WrapForInfinity<T>::GetMinusInfinity(); } else if (this->op == GR && other.op == MIF) { return WrapForInfinity<T>::GetInfinity(); } else if (this->op == IF && other.op == GR) { return WrapForInfinity<T>::GetInfinity(); } else if (this->op == GR && other.op == IF) { return WrapForInfinity<T>::GetMinusInfinity(); } else if (this->op == MIF && other.op == IF) { return WrapForInfinity<T>::GetMinusInfinity(); } else if (this->op == IF && other.op == MIF) { return WrapForInfinity<T>::GetInfinity(); } else { throw string(" - Error in wrapforinfiinity"); } } string toString()const { if (this->op == MIF) return "minus infinity"; else if (this->op == IF) return "plus infinity"; else return wiz::toStr(this->val); } friend ostream& operator<<(ostream& stream, const WrapForInfinity<T,COMP,COMP2,EE>& wfi) { if( wfi.op == MIF ) stream << "minus infinity"; else if(wfi.op == IF ) stream << "plus infinity"; else stream << wfi.val; return stream; } static WrapForInfinity<T, COMP, COMP2,EE > GetInfinity() { return WrapForInfinity<T, COMP, COMP2, EE >(T(), IF); } static WrapForInfinity<T, COMP, COMP2, EE > GetMinusInfinity() { return WrapForInfinity<T, COMP, COMP2, EE >(T(), MIF); } }; template <typename T> /// x is 10吏꾩닔.. inline T pos_1(const T x, const int base=10) // 1먮━ 媛怨꾩궛 { if( x >= 0 ) { return x % base; }// x - ( x / 10 ) * 10; } else{ return (x / base) * base - x; } // -( x - ( (x/10) * 10 ) ) } template <typename T> /// T <- char, int, long, long long... string toStr(const T x, const int base=10 ) /// chk!! { if( base < 2 || base > 16 ) { return "base is not valid"; } T i = x; const int INT_SIZE = sizeof(T) << 3; ///*8 char* temp = new char[INT_SIZE + 1 + 1]; /// 1 NULL, 1 minus string tempString; int k; bool isMinus = (i < 0); temp[INT_SIZE+1] = '\0'; ///臾몄옄쒖떆.. for (k = INT_SIZE; k >= 1; k--){ T val = pos_1<T>(i, base); /// 0 ~ base-1 /// number to ['0'~'9'] or ['A'~'F'] if( val < 10 ) { temp[k] = val + '0'; } else { temp[k] = val-10 + 'A'; } i /= base; if (0 == i){ // レ옄. k--; break; } } if (isMinus){ temp[k] = '-'; tempString = string(temp + k);// } else{ tempString = string(temp + k + 1); // } delete[] temp; return tempString; } /// chk.... need more thinking..., ToDo... template <typename T> /// T <- char, int, long, long long... string toStr2(const T x, const int str_space, const int base=10 ) /// chk!! { if( base < 2 || base > 16 ) { return "base is not valid"; } T i = x; T k2 = 0; const int INT_SIZE = sizeof(T) << 3; ///*8 char* temp = new char[INT_SIZE + 1 + 1]; /// 1 NULL, 1 minus for(int i=0; i < INT_SIZE+2; ++i ) { temp[i] = '0'; }// string tempString; int k; bool isMinus = (i < 0); temp[INT_SIZE+1] = '\0'; ///臾몄옄쒖떆.. for (k = INT_SIZE; k >= 1; k--){ T val = pos_1<T>(i, base); /// 0 ~ base-1 /// number to ['0'~'9'] or ['A'~'F'] if( val < 10 ) { temp[k] = val + '0'; } else { temp[k] = val-10 + 'A'; } i /= base; if (0 == i){ // レ옄. k--; break; } } if (isMinus){ temp[k] = '-'; tempString = string(temp + k);// } else{ if( INT_SIZE+1 - (k+1) +1 < str_space+1 ) { k2 = str_space+1 - ( INT_SIZE+1 - (k+1) + 1 ); } else { k2 = 0; } tempString = string(temp + k + 1 - k2 ); // } delete[] temp; return tempString; } inline string str(const int x) { return toStr<int>(x); } template <typename T> /// 몄텧좊븣 뚯븘泥댄겕쒕떎 inline string _toString(const T x) { std::stringstream strs; strs << x; return strs.str(); } template <> inline string _toString(const long double x) { std::stringstream strs; strs << x; string temp = strs.str(); size_t idx = temp.find('.'); if (idx == temp.size()-1) { temp.push_back('0'); } else if (idx == string::npos) { temp.push_back('.'); temp.push_back('0'); } return temp; } template <> inline string _toString(const long long x) { return toStr(x); } template <> inline string _toString(const int x) { return str(x); } template <> inline string _toString(const bool x) { if (x) { return "true"; } return "false"; } // following remove inline bool isWhitespace( const char ch ) { switch( ch ) { case ' ': case '\t': case '\r': case '\n': return true; } return false; } template <typename T> // T must be unsigned type! inline T Unsigned_Maximum() { return -1; } template <typename T> // T must be signed type! T Signed_Maximum() { size_t byteSize = sizeof(T); T val = 0; val = 0x7F; for (size_t i = 1; i < byteSize; i++) { val = val << 8; // left shift 1 byte val = val | 0xFF; } return val; } // C++11 template <typename T> inline T Maximum() { if( std::is_signed<T>::value ) { return Signed_Maximum<T>(); } if( std::is_unsigned<T>::value ) { return Unsigned_Maximum<T>(); } throw string( "unsupport type : double, class, and etc..." ); } inline int getFirstIndex(const string& str, const char ch) { for (int i = 0; i < str.size(); ++i) { if (ch == str[i]) { return i; } } return -1; } class wizObject { private: public: wizObject() { } wizObject(const wizObject& object) { } virtual ~wizObject() { } virtual std::string toString()const = 0; //virtual void initial( const wizObject& object )=0; virtual wizObject& operator=(const wizObject& object) { return *this; } virtual wizObject* clone()const = 0; }; template <typename T> T Rand() // T : maybe int, long, long long,.., Àüü ¹üÀ§ Rand... { size_t byteSize = sizeof(T); T val = 0; for (size_t i = 0; i < byteSize; i++) { val = val << 8; // left shift 1 byte val = val | (rand() % 256); } return val; } template <typename T> inline T Rand2() /// T : must be signed! and no return minus value. { T val = Rand<T>(); return val & Signed_Maximum<T>(); } } #endif <commit_msg>Delete GLOBAL.H<commit_after><|endoftext|>