commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
894f8401a1749fe97e896c9d4f915a4c5c17d775
src/libpsl-native/test/test-createsymlink.cpp
src/libpsl-native/test/test-createsymlink.cpp
//! @file test-createsymlink.cpp //! @author George Fleming <[email protected]> //! @brief Implements test for CreateSymLink() and FollowSymLink() #include <gtest/gtest.h> #include <errno.h> #include <unistd.h> #include "issymlink.h" #include "createsymlink.h" #include "followsymlink.h" using namespace std; class CreateSymLinkTest : public ::testing::Test { protected: static const int bufSize = 64; const string fileTemplate = "/tmp/symlinktest.fXXXXXX"; const string dirTemplate = "/tmp/symlinktest.dXXXXXX"; const string fileSymLink = "/tmp/symlinktest.flink"; const string dirSymLink = "/tmp/symlinktest.dlink"; char *file, *dir; char fileTemplateBuf[bufSize], dirTemplateBuf[bufSize]; CreateSymLinkTest() { // since mkstemp and mkdtemp modifies the template string, let's give them writable buffers strcpy(fileTemplateBuf, fileTemplate.c_str()); strcpy(dirTemplateBuf, dirTemplate.c_str()); // First create a temp file int fd = mkstemp(fileTemplateBuf); EXPECT_TRUE(fd != -1); file = fileTemplateBuf; // Create a temp directory dir = mkdtemp(dirTemplateBuf); EXPECT_TRUE(dir != NULL); // Create symbolic link to file int ret1 = CreateSymLink(fileSymLink.c_str(), file); EXPECT_EQ(ret1, 1); // Create symbolic link to directory int ret2 = CreateSymLink(dirSymLink.c_str(), dir); EXPECT_EQ(ret2, 1); } ~CreateSymLinkTest() { int ret; ret = unlink(fileSymLink.c_str()); EXPECT_EQ(0, ret); ret = unlink(dirSymLink.c_str()); EXPECT_EQ(0, ret); ret = unlink(file); EXPECT_EQ(0, ret); ret = rmdir(dir); EXPECT_EQ(0, ret); } }; TEST_F(CreateSymLinkTest, FilePathNameIsNull) { int retVal = CreateSymLink(NULL, NULL); EXPECT_EQ(retVal, 0); EXPECT_EQ(ERROR_INVALID_PARAMETER, errno); } TEST_F(CreateSymLinkTest, FilePathNameDoesNotExist) { std::string invalidFile = "/tmp/symlinktest_invalidFile"; std::string invalidLink = "/tmp/symlinktest_invalidLink"; // make sure neither exists unlink(invalidFile.c_str()); unlink(invalidLink.c_str()); // Linux allows creation of symbolic link that points to an invalid file int retVal = CreateSymLink(invalidLink.c_str(), invalidFile.c_str()); EXPECT_EQ(retVal, 1); std::string target = FollowSymLink(invalidLink.c_str()); EXPECT_EQ(target, invalidFile); unlink(invalidLink.c_str()); } TEST_F(CreateSymLinkTest, SymLinkToFile) { int retVal = IsSymLink(fileSymLink.c_str()); EXPECT_EQ(1, retVal); std::string target = FollowSymLink(fileSymLink.c_str()); EXPECT_EQ(target, file); } TEST_F(CreateSymLinkTest, SymLinkToDirectory) { int retVal = IsSymLink(dirSymLink.c_str()); EXPECT_EQ(1, retVal); std::string target = FollowSymLink(dirSymLink.c_str()); EXPECT_EQ(target, dir); } TEST_F(CreateSymLinkTest, SymLinkAgain) { int retVal = CreateSymLink(fileSymLink.c_str(), file); EXPECT_EQ(0, retVal); EXPECT_EQ(ERROR_FILE_EXISTS, errno); }
//! @file test-createsymlink.cpp //! @author George Fleming <[email protected]> //! @brief Implements test for CreateSymLink() and FollowSymLink() #include <gtest/gtest.h> #include <errno.h> #include <unistd.h> #include "issymlink.h" #include "createsymlink.h" #include "followsymlink.h" using namespace std; class CreateSymLinkTest : public ::testing::Test { protected: static const int bufSize = 64; const string fileTemplate = "/tmp/symlinktest.fXXXXXX"; const string dirTemplate = "/tmp/symlinktest.dXXXXXX"; const string fileSymLink = "/tmp/symlinktest.flink"; const string dirSymLink = "/tmp/symlinktest.dlink"; char *file, *dir; char fileTemplateBuf[bufSize], dirTemplateBuf[bufSize]; CreateSymLinkTest() { // since mkstemp and mkdtemp modifies the template string, let's give them writable buffers strcpy(fileTemplateBuf, fileTemplate.c_str()); strcpy(dirTemplateBuf, dirTemplate.c_str()); // First create a temp file int fd = mkstemp(fileTemplateBuf); EXPECT_TRUE(fd != -1); file = fileTemplateBuf; // Create a temp directory dir = mkdtemp(dirTemplateBuf); EXPECT_TRUE(dir != NULL); // Create symbolic link to file int ret1 = CreateSymLink(fileSymLink.c_str(), file); EXPECT_EQ(ret1, 1); // Create symbolic link to directory int ret2 = CreateSymLink(dirSymLink.c_str(), dir); EXPECT_EQ(ret2, 1); } ~CreateSymLinkTest() { int ret; ret = unlink(fileSymLink.c_str()); EXPECT_EQ(0, ret); ret = unlink(dirSymLink.c_str()); EXPECT_EQ(0, ret); ret = unlink(file); EXPECT_EQ(0, ret); ret = rmdir(dir); EXPECT_EQ(0, ret); } }; TEST_F(CreateSymLinkTest, FilePathNameIsNull) { int retVal = CreateSymLink(NULL, NULL); EXPECT_EQ(retVal, 0); EXPECT_EQ(ERROR_INVALID_PARAMETER, errno); } TEST_F(CreateSymLinkTest, FilePathNameDoesNotExist) { std::string invalidFile = "/tmp/symlinktest_invalidFile"; std::string invalidLink = "/tmp/symlinktest_invalidLink"; // make sure neither exists unlink(invalidFile.c_str()); unlink(invalidLink.c_str()); // Linux allows creation of symbolic link that points to an invalid file int retVal = CreateSymLink(invalidLink.c_str(), invalidFile.c_str()); EXPECT_EQ(retVal, 1); std::string target = FollowSymLink(invalidLink.c_str()); EXPECT_EQ(target, invalidFile); unlink(invalidLink.c_str()); } TEST_F(CreateSymLinkTest, SymLinkToFile) { int retVal = IsSymLink(fileSymLink.c_str()); EXPECT_EQ(1, retVal); std::string target = FollowSymLink(fileSymLink.c_str()); char buffer[PATH_MAX]; std::string expected = realpath(file, buffer); EXPECT_EQ(target, expected); } TEST_F(CreateSymLinkTest, SymLinkToDirectory) { int retVal = IsSymLink(dirSymLink.c_str()); EXPECT_EQ(1, retVal); std::string target = FollowSymLink(dirSymLink.c_str()); char buffer[PATH_MAX]; std::string expected = realpath(dir, buffer); EXPECT_EQ(target, expected); } TEST_F(CreateSymLinkTest, SymLinkAgain) { int retVal = CreateSymLink(fileSymLink.c_str(), file); EXPECT_EQ(0, retVal); EXPECT_EQ(ERROR_FILE_EXISTS, errno); }
Fix CreateSymLink tests for OS X
Fix CreateSymLink tests for OS X /tmp is symlinked to /private/tmp and since we're testing symlink resolution through FollowSymlink, we need to change what we expect to the realpath.
C++
mit
KarolKaczmarek/PowerShell,PaulHigin/PowerShell,bingbing8/PowerShell,kmosher/PowerShell,TravisEz13/PowerShell,bmanikm/PowerShell,bmanikm/PowerShell,TravisEz13/PowerShell,KarolKaczmarek/PowerShell,JamesWTruher/PowerShell-1,TravisEz13/PowerShell,PaulHigin/PowerShell,bmanikm/PowerShell,kmosher/PowerShell,bingbing8/PowerShell,jsoref/PowerShell,jsoref/PowerShell,kmosher/PowerShell,daxian-dbw/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,KarolKaczmarek/PowerShell,bmanikm/PowerShell,JamesWTruher/PowerShell-1,PaulHigin/PowerShell,bingbing8/PowerShell,TravisEz13/PowerShell,daxian-dbw/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,jsoref/PowerShell,bingbing8/PowerShell,bmanikm/PowerShell,jsoref/PowerShell,bingbing8/PowerShell,jsoref/PowerShell,KarolKaczmarek/PowerShell,daxian-dbw/PowerShell,kmosher/PowerShell,PaulHigin/PowerShell
d4a3edf70039538231032fb14a1079a8a5422ff1
src/Tests/Tests/Test_FastConv.cpp
src/Tests/Tests/Test_FastConv.cpp
#include "MUSI8903Config.h" #ifdef WITH_TESTS #include <cassert> #include <cstdio> #include <iostream> #include "UnitTest++.h" #include "Vector.h" #include "FastConv.h" SUITE(FastConv) { struct FastConvData { FastConvData(): m_pCFastConv(0), inputData(0), outputData(0), inputTmp(0), outputTmp(0), dataLength(125), blockLength(1897), lengthOfIr(105), impulseResponse(0), convBlockLength(32) { CFastConv::create(m_pCFastConv); inputData = new float [dataLength]; outputData = new float [dataLength + lengthOfIr - 1]; impulseResponse = new float [lengthOfIr]; for (int i = 0; i < lengthOfIr; i++) { //impulseResponse[i] = static_cast<float>(rand())/RAND_MAX; impulseResponse[i] = i; } CVectorFloat::setZero(inputData, dataLength); CVectorFloat::setZero(outputData, dataLength); } ~FastConvData() { delete[] inputData; delete[] outputData; //delete[] inputTmp; //delete[] outputTmp; delete[] impulseResponse; CFastConv::destroy(m_pCFastConv); } void TestProcess() { int numFramesRemaining = dataLength; while (numFramesRemaining > 0) { int numFrames = std::min(numFramesRemaining, blockLength); inputTmp = &inputData[dataLength - numFramesRemaining]; outputTmp = &outputData[dataLength - numFramesRemaining]; m_pCFastConv->process(inputTmp, outputTmp, numFrames); numFramesRemaining -= numFrames; } int sizeOfTail = 0; m_pCFastConv->getSizeOfTail(sizeOfTail); CHECK_EQUAL(lengthOfIr-1, sizeOfTail); outputTmp = &outputData[dataLength]; m_pCFastConv->flushBuffer(outputTmp); } void resetIOData() { for (int i = 0; i < dataLength; i++) { inputData[i] = 0; } for (int i = 0; i < dataLength + lengthOfIr - 1; i++) { outputData[i] = 0; } } CFastConv *m_pCFastConv; float* inputData; float* outputData; float* inputTmp; float* outputTmp; int dataLength; int blockLength; int lengthOfIr; float* impulseResponse; int convBlockLength; }; TEST_FIXTURE(FastConvData, IrTest) { // initialise fast conv m_pCFastConv->init(impulseResponse, lengthOfIr, convBlockLength); // set input data for (int i = 0; i < dataLength; i++) { inputData[i] = 0; } int delay = 5; inputData[delay] = 1; TestProcess(); for (int i = 0; i < dataLength + lengthOfIr - 1; i++) { if (i < delay) { CHECK_CLOSE(0, outputData[i], 1e-3F); } else if (i <= delay + lengthOfIr - 1) { CHECK_CLOSE(impulseResponse[i-delay], outputData[i], 1e-3F); } else if (i > delay + lengthOfIr - 1) { CHECK_CLOSE(0, outputData[i], 1e-3F); } } resetIOData(); } /*TEST_FIXTURE(FastConvData, InputBlockLengthTest) { int blockSizes[] = {1023, 1023, 13, 17, 13, 17, 1023}; int numBlockSizes = 7; for (int i = 0; i < numBlockSizes; i++) { blockLength = blockSizes[i]; // initialise fast conv m_pCFastConv->init(impulseResponse, lengthOfIr); // set input data for (int i = 0; i < dataLength; i++) { inputData[i] = 0; } int delay = 5; inputData[delay] = 1; TestProcess(); // check output for (int i = 0; i < dataLength + lengthOfIr - 1; i++) { if (i < delay) { CHECK_CLOSE(0, outputData[i], 1e-3F); } else if (i <= delay + lengthOfIr - 1) { CHECK_CLOSE(impulseResponse[i-delay], outputData[i], 1e-3F); } else if (i > delay + lengthOfIr - 1) { CHECK_CLOSE(0, outputData[i], 1e-3F); } } resetIOData(); } }*/ } #endif //WITH_TESTS
#include "MUSI8903Config.h" #ifdef WITH_TESTS #include <cassert> #include <cstdio> #include <iostream> #include "UnitTest++.h" #include "Vector.h" #include "FastConv.h" SUITE(FastConv) { struct FastConvData { FastConvData(): m_pCFastConv(0), inputData(0), outputData(0), inputTmp(0), outputTmp(0), dataLength(125), blockLength(1897), lengthOfIr(105), impulseResponse(0), convBlockLength(32) { CFastConv::create(m_pCFastConv); inputData = new float [dataLength]; outputData = new float [dataLength + lengthOfIr - 1]; impulseResponse = new float [lengthOfIr]; for (int i = 0; i < lengthOfIr; i++) { //impulseResponse[i] = static_cast<float>(rand())/RAND_MAX; impulseResponse[i] = i; } CVectorFloat::setZero(inputData, dataLength); CVectorFloat::setZero(outputData, dataLength); } ~FastConvData() { delete[] inputData; delete[] outputData; //delete[] inputTmp; //delete[] outputTmp; delete[] impulseResponse; CFastConv::destroy(m_pCFastConv); } void TestProcess() { int numFramesRemaining = dataLength; while (numFramesRemaining > 0) { int numFrames = std::min(numFramesRemaining, blockLength); inputTmp = &inputData[dataLength - numFramesRemaining]; outputTmp = &outputData[dataLength - numFramesRemaining]; m_pCFastConv->process(inputTmp, outputTmp, numFrames); numFramesRemaining -= numFrames; } int sizeOfTail = 0; m_pCFastConv->getSizeOfTail(sizeOfTail); CHECK_EQUAL(lengthOfIr-1, sizeOfTail); outputTmp = &outputData[dataLength]; m_pCFastConv->flushBuffer(outputTmp); } void resetIOData() { for (int i = 0; i < dataLength; i++) { inputData[i] = 0; } for (int i = 0; i < dataLength + lengthOfIr - 1; i++) { outputData[i] = 0; } } CFastConv *m_pCFastConv; float* inputData; float* outputData; float* inputTmp; float* outputTmp; int dataLength; int blockLength; int lengthOfIr; float* impulseResponse; int convBlockLength; }; TEST_FIXTURE(FastConvData, IrTest) { // initialise fast conv m_pCFastConv->init(impulseResponse, lengthOfIr, convBlockLength); // set input data for (int i = 0; i < dataLength; i++) { inputData[i] = 0; } int delay = 5; inputData[delay] = 1; TestProcess(); for (int i = 0; i < dataLength + lengthOfIr - 1; i++) { if (i < delay) { CHECK_CLOSE(0, outputData[i], 1e-3F); } else if (i <= delay + lengthOfIr - 1) { CHECK_CLOSE(impulseResponse[i-delay], outputData[i], 1e-3F); } else if (i > delay + lengthOfIr - 1) { CHECK_CLOSE(0, outputData[i], 1e-3F); } } resetIOData(); } TEST_FIXTURE(FastConvData, InputBlockLengthTest) { int blockSizes[] = {1023, 1023, 13, 17, 13, 17, 1023}; int numBlockSizes = 7; for (int i = 0; i < numBlockSizes; i++) { blockLength = blockSizes[i]; // initialise fast conv m_pCFastConv->init(impulseResponse, lengthOfIr); // set input data for (int i = 0; i < dataLength; i++) { inputData[i] = 0; } int delay = 5; inputData[delay] = 1; TestProcess(); // check output for (int i = 0; i < dataLength + lengthOfIr - 1; i++) { if (i < delay) { CHECK_CLOSE(0, outputData[i], 1e-3F); } else if (i <= delay + lengthOfIr - 1) { CHECK_CLOSE(impulseResponse[i-delay], outputData[i], 1e-3F); } else if (i > delay + lengthOfIr - 1) { CHECK_CLOSE(0, outputData[i], 1e-3F); } } resetIOData(); } } } #endif //WITH_TESTS
add back test fixture
add back test fixture both tests running.
C++
mit
ashispati/MUSIC-8903-2016-assignment3-fastconv,ashispati/MUSIC-8903-2016-assignment3-fastconv
3f5ca536d8bb25fdeec1c3dc72dc6c0cead76951
Modules/DiffusionImaging/FiberTracking/cmdapps/Tractography/RfTraining.cpp
Modules/DiffusionImaging/FiberTracking/cmdapps/Tractography/RfTraining.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkBaseData.h> #include <mitkImageCast.h> #include <mitkImageToItk.h> #include <metaCommand.h> #include "mitkCommandLineParser.h" #include <usAny.h> #include <itkImageFileWriter.h> #include <mitkIOUtil.h> #include <iostream> #include <fstream> #include <itksys/SystemTools.hxx> #include <mitkCoreObjectFactory.h> #include <mitkPreferenceListReaderOptionsFunctor.h> #include <mitkFiberBundle.h> #include <mitkTrackingHandlerRandomForest.h> #include <mitkTractographyForest.h> #define _USE_MATH_DEFINES #include <math.h> /*! \brief Train random forest classifier for machine learning based streamline tractography */ int main(int argc, char* argv[]) { MITK_INFO << "RfTraining"; mitkCommandLineParser parser; parser.setTitle("Trains Random Forests for Machine Learning Based Tractography"); parser.setCategory("Fiber Tracking and Processing Methods"); parser.setDescription("Train random forest classifier for machine learning based streamline tractography"); parser.setContributor("MIC"); parser.setArgumentPrefix("--", "-"); parser.beginGroup("1. Mandatory arguments:"); parser.addArgument("images", "i", mitkCommandLineParser::StringList, "DWIs:", "input diffusion-weighted images", us::Any(), false); parser.addArgument("tractograms", "t", mitkCommandLineParser::StringList, "Tractograms:", "input training tractograms (.fib, vtk ascii file format)", us::Any(), false); parser.addArgument("forest", "f", mitkCommandLineParser::OutputFile, "Forest:", "output random forest (HDF5)", us::Any(), false); parser.endGroup(); parser.beginGroup("2. Additional input images:"); parser.addArgument("masks", "", mitkCommandLineParser::StringList, "Masks:", "restrict training using a binary mask image", us::Any()); parser.addArgument("wm_masks", "", mitkCommandLineParser::StringList, "WM-Masks:", "if no binary white matter mask is specified, the envelope of the input tractogram is used", us::Any()); parser.addArgument("volume_modification_images", "", mitkCommandLineParser::StringList, "Volume modification images:", "specify a list of float images that modify the fiber density", us::Any()); parser.addArgument("additional_feature_images", "", mitkCommandLineParser::StringList, "Additional feature images:", "specify a list of float images that hold additional features (float)", us::Any()); parser.endGroup(); parser.beginGroup("3. Forest parameters:"); parser.addArgument("num_trees", "", mitkCommandLineParser::Int, "Number of trees:", "number of trees", 30); parser.addArgument("max_tree_depth", "", mitkCommandLineParser::Int, "Max. tree depth:", "maximum tree depth", 25); parser.addArgument("sample_fraction", "", mitkCommandLineParser::Float, "Sample fraction:", "fraction of samples used per tree", 0.7); parser.endGroup(); parser.beginGroup("4. Feature parameters:"); parser.addArgument("use_sh_features", "", mitkCommandLineParser::Bool, "Use SH features:", "use SH features", false); parser.addArgument("sampling_distance", "", mitkCommandLineParser::Float, "Sampling distance:", "resampling parameter for the input tractogram in mm (determines number of white-matter samples)", us::Any()); parser.addArgument("max_wm_samples", "", mitkCommandLineParser::Int, "Max. num. WM samples:", "upper limit for the number of WM samples"); parser.addArgument("num_gm_samples", "", mitkCommandLineParser::Int, "Number of gray matter samples per voxel:", "Number of gray matter samples per voxel", us::Any()); parser.endGroup(); std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; bool shfeatures = false; if (parsedArgs.count("use_sh_features")) shfeatures = us::any_cast<bool>(parsedArgs["use_sh_features"]); mitkCommandLineParser::StringContainerType imageFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["images"]); mitkCommandLineParser::StringContainerType wmMaskFiles; if (parsedArgs.count("wm_masks")) wmMaskFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["wm_masks"]); mitkCommandLineParser::StringContainerType volModFiles; if (parsedArgs.count("volume_modification_images")) volModFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["volume_modification_images"]); mitkCommandLineParser::StringContainerType addFeatFiles; if (parsedArgs.count("additional_feature_images")) addFeatFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["additional_feature_images"]); mitkCommandLineParser::StringContainerType maskFiles; if (parsedArgs.count("masks")) maskFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["masks"]); std::string forestFile = us::any_cast<std::string>(parsedArgs["forest"]); mitkCommandLineParser::StringContainerType tractogramFiles; if (parsedArgs.count("tractograms")) tractogramFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["tractograms"]); int num_trees = 30; if (parsedArgs.count("num_trees")) num_trees = us::any_cast<int>(parsedArgs["num_trees"]); int gm_samples = -1; if (parsedArgs.count("num_gm_samples")) gm_samples = us::any_cast<int>(parsedArgs["num_gm_samples"]); float sampling_distance = -1; if (parsedArgs.count("sampling_distance")) sampling_distance = us::any_cast<float>(parsedArgs["sampling_distance"]); int max_tree_depth = 25; if (parsedArgs.count("max_tree_depth")) max_tree_depth = us::any_cast<int>(parsedArgs["max_tree_depth"]); double sample_fraction = 0.7; if (parsedArgs.count("sample_fraction")) sample_fraction = us::any_cast<float>(parsedArgs["sample_fraction"]); int maxWmSamples = -1; if (parsedArgs.count("max_wm_samples")) maxWmSamples = us::any_cast<int>(parsedArgs["max_wm_samples"]); MITK_INFO << "loading diffusion-weighted images"; std::vector< mitk::Image::Pointer > rawData; mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor({"Diffusion Weighted Images"}, {}); for (auto imgFile : imageFiles) { auto dwi = mitk::IOUtil::Load<mitk::Image>(imgFile, &functor)); rawData.push_back(dwi); } typedef itk::Image<float, 3> ItkFloatImgType; typedef itk::Image<unsigned char, 3> ItkUcharImgType; MITK_INFO << "loading mask images"; std::vector< ItkUcharImgType::Pointer > maskImageVector; for (auto maskFile : maskFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(maskFile); ItkUcharImgType::Pointer mask = ItkUcharImgType::New(); mitk::CastToItkImage(img, mask); maskImageVector.push_back(mask); } MITK_INFO << "loading white matter mask images"; std::vector< ItkUcharImgType::Pointer > wmMaskImageVector; for (auto wmFile : wmMaskFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(wmFile); ItkUcharImgType::Pointer wmmask = ItkUcharImgType::New(); mitk::CastToItkImage(img, wmmask); wmMaskImageVector.push_back(wmmask); } MITK_INFO << "loading tractograms"; std::vector< mitk::FiberBundle::Pointer > tractograms; for (auto tractFile : tractogramFiles) { mitk::FiberBundle::Pointer fib = mitk::IOUtil::Load<mitk::FiberBundle>(tractFile); tractograms.push_back(fib); } MITK_INFO << "loading white volume modification images"; std::vector< ItkFloatImgType::Pointer > volumeModImages; for (auto file : volModFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(file); ItkFloatImgType::Pointer itkimg = ItkFloatImgType::New(); mitk::CastToItkImage(img, itkimg); volumeModImages.push_back(itkimg); } MITK_INFO << "loading additional feature images"; std::vector< std::vector< ItkFloatImgType::Pointer > > addFeatImages; for (std::size_t i=0; i<rawData.size(); ++i) addFeatImages.push_back(std::vector< ItkFloatImgType::Pointer >()); int c = 0; for (auto file : addFeatFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(file); ItkFloatImgType::Pointer itkimg = ItkFloatImgType::New(); mitk::CastToItkImage(img, itkimg); addFeatImages.at(c%addFeatImages.size()).push_back(itkimg); c++; } mitk::TractographyForest::Pointer forest = nullptr; if (shfeatures) { mitk::TrackingHandlerRandomForest<6,28> forestHandler; forestHandler.SetDwis(rawData); forestHandler.SetMaskImages(maskImageVector); forestHandler.SetWhiteMatterImages(wmMaskImageVector); forestHandler.SetFiberVolumeModImages(volumeModImages); forestHandler.SetAdditionalFeatureImages(addFeatImages); forestHandler.SetTractograms(tractograms); forestHandler.SetNumTrees(num_trees); forestHandler.SetMaxTreeDepth(max_tree_depth); forestHandler.SetGrayMatterSamplesPerVoxel(gm_samples); forestHandler.SetSampleFraction(sample_fraction); forestHandler.SetFiberSamplingStep(sampling_distance); forestHandler.SetMaxNumWmSamples(maxWmSamples); forestHandler.StartTraining(); forest = forestHandler.GetForest(); } else { mitk::TrackingHandlerRandomForest<6,100> forestHandler; forestHandler.SetDwis(rawData); forestHandler.SetMaskImages(maskImageVector); forestHandler.SetWhiteMatterImages(wmMaskImageVector); forestHandler.SetFiberVolumeModImages(volumeModImages); forestHandler.SetAdditionalFeatureImages(addFeatImages); forestHandler.SetTractograms(tractograms); forestHandler.SetNumTrees(num_trees); forestHandler.SetMaxTreeDepth(max_tree_depth); forestHandler.SetGrayMatterSamplesPerVoxel(gm_samples); forestHandler.SetSampleFraction(sample_fraction); forestHandler.SetFiberSamplingStep(sampling_distance); forestHandler.SetMaxNumWmSamples(maxWmSamples); forestHandler.StartTraining(); forest = forestHandler.GetForest(); } mitk::IOUtil::Save(forest, forestFile); return EXIT_SUCCESS; }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkBaseData.h> #include <mitkImageCast.h> #include <mitkImageToItk.h> #include <metaCommand.h> #include "mitkCommandLineParser.h" #include <usAny.h> #include <itkImageFileWriter.h> #include <mitkIOUtil.h> #include <iostream> #include <fstream> #include <itksys/SystemTools.hxx> #include <mitkCoreObjectFactory.h> #include <mitkPreferenceListReaderOptionsFunctor.h> #include <mitkFiberBundle.h> #include <mitkTrackingHandlerRandomForest.h> #include <mitkTractographyForest.h> #define _USE_MATH_DEFINES #include <math.h> /*! \brief Train random forest classifier for machine learning based streamline tractography */ int main(int argc, char* argv[]) { MITK_INFO << "RfTraining"; mitkCommandLineParser parser; parser.setTitle("Trains Random Forests for Machine Learning Based Tractography"); parser.setCategory("Fiber Tracking and Processing Methods"); parser.setDescription("Train random forest classifier for machine learning based streamline tractography"); parser.setContributor("MIC"); parser.setArgumentPrefix("--", "-"); parser.beginGroup("1. Mandatory arguments:"); parser.addArgument("images", "i", mitkCommandLineParser::StringList, "DWIs:", "input diffusion-weighted images", us::Any(), false); parser.addArgument("tractograms", "t", mitkCommandLineParser::StringList, "Tractograms:", "input training tractograms (.fib, vtk ascii file format)", us::Any(), false); parser.addArgument("forest", "f", mitkCommandLineParser::OutputFile, "Forest:", "output random forest (HDF5)", us::Any(), false); parser.endGroup(); parser.beginGroup("2. Additional input images:"); parser.addArgument("masks", "", mitkCommandLineParser::StringList, "Masks:", "restrict training using a binary mask image", us::Any()); parser.addArgument("wm_masks", "", mitkCommandLineParser::StringList, "WM-Masks:", "if no binary white matter mask is specified, the envelope of the input tractogram is used", us::Any()); parser.addArgument("volume_modification_images", "", mitkCommandLineParser::StringList, "Volume modification images:", "specify a list of float images that modify the fiber density", us::Any()); parser.addArgument("additional_feature_images", "", mitkCommandLineParser::StringList, "Additional feature images:", "specify a list of float images that hold additional features (float)", us::Any()); parser.endGroup(); parser.beginGroup("3. Forest parameters:"); parser.addArgument("num_trees", "", mitkCommandLineParser::Int, "Number of trees:", "number of trees", 30); parser.addArgument("max_tree_depth", "", mitkCommandLineParser::Int, "Max. tree depth:", "maximum tree depth", 25); parser.addArgument("sample_fraction", "", mitkCommandLineParser::Float, "Sample fraction:", "fraction of samples used per tree", 0.7); parser.endGroup(); parser.beginGroup("4. Feature parameters:"); parser.addArgument("use_sh_features", "", mitkCommandLineParser::Bool, "Use SH features:", "use SH features", false); parser.addArgument("sampling_distance", "", mitkCommandLineParser::Float, "Sampling distance:", "resampling parameter for the input tractogram in mm (determines number of white-matter samples)", us::Any()); parser.addArgument("max_wm_samples", "", mitkCommandLineParser::Int, "Max. num. WM samples:", "upper limit for the number of WM samples"); parser.addArgument("num_gm_samples", "", mitkCommandLineParser::Int, "Number of gray matter samples per voxel:", "Number of gray matter samples per voxel", us::Any()); parser.endGroup(); std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; bool shfeatures = false; if (parsedArgs.count("use_sh_features")) shfeatures = us::any_cast<bool>(parsedArgs["use_sh_features"]); mitkCommandLineParser::StringContainerType imageFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["images"]); mitkCommandLineParser::StringContainerType wmMaskFiles; if (parsedArgs.count("wm_masks")) wmMaskFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["wm_masks"]); mitkCommandLineParser::StringContainerType volModFiles; if (parsedArgs.count("volume_modification_images")) volModFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["volume_modification_images"]); mitkCommandLineParser::StringContainerType addFeatFiles; if (parsedArgs.count("additional_feature_images")) addFeatFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["additional_feature_images"]); mitkCommandLineParser::StringContainerType maskFiles; if (parsedArgs.count("masks")) maskFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["masks"]); std::string forestFile = us::any_cast<std::string>(parsedArgs["forest"]); mitkCommandLineParser::StringContainerType tractogramFiles; if (parsedArgs.count("tractograms")) tractogramFiles = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["tractograms"]); int num_trees = 30; if (parsedArgs.count("num_trees")) num_trees = us::any_cast<int>(parsedArgs["num_trees"]); int gm_samples = -1; if (parsedArgs.count("num_gm_samples")) gm_samples = us::any_cast<int>(parsedArgs["num_gm_samples"]); float sampling_distance = -1; if (parsedArgs.count("sampling_distance")) sampling_distance = us::any_cast<float>(parsedArgs["sampling_distance"]); int max_tree_depth = 25; if (parsedArgs.count("max_tree_depth")) max_tree_depth = us::any_cast<int>(parsedArgs["max_tree_depth"]); double sample_fraction = 0.7; if (parsedArgs.count("sample_fraction")) sample_fraction = us::any_cast<float>(parsedArgs["sample_fraction"]); int maxWmSamples = -1; if (parsedArgs.count("max_wm_samples")) maxWmSamples = us::any_cast<int>(parsedArgs["max_wm_samples"]); MITK_INFO << "loading diffusion-weighted images"; std::vector< mitk::Image::Pointer > rawData; mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor({"Diffusion Weighted Images"}, {}); for (auto imgFile : imageFiles) { auto dwi = mitk::IOUtil::Load<mitk::Image>(imgFile, &functor); rawData.push_back(dwi); } typedef itk::Image<float, 3> ItkFloatImgType; typedef itk::Image<unsigned char, 3> ItkUcharImgType; MITK_INFO << "loading mask images"; std::vector< ItkUcharImgType::Pointer > maskImageVector; for (auto maskFile : maskFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(maskFile); ItkUcharImgType::Pointer mask = ItkUcharImgType::New(); mitk::CastToItkImage(img, mask); maskImageVector.push_back(mask); } MITK_INFO << "loading white matter mask images"; std::vector< ItkUcharImgType::Pointer > wmMaskImageVector; for (auto wmFile : wmMaskFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(wmFile); ItkUcharImgType::Pointer wmmask = ItkUcharImgType::New(); mitk::CastToItkImage(img, wmmask); wmMaskImageVector.push_back(wmmask); } MITK_INFO << "loading tractograms"; std::vector< mitk::FiberBundle::Pointer > tractograms; for (auto tractFile : tractogramFiles) { mitk::FiberBundle::Pointer fib = mitk::IOUtil::Load<mitk::FiberBundle>(tractFile); tractograms.push_back(fib); } MITK_INFO << "loading white volume modification images"; std::vector< ItkFloatImgType::Pointer > volumeModImages; for (auto file : volModFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(file); ItkFloatImgType::Pointer itkimg = ItkFloatImgType::New(); mitk::CastToItkImage(img, itkimg); volumeModImages.push_back(itkimg); } MITK_INFO << "loading additional feature images"; std::vector< std::vector< ItkFloatImgType::Pointer > > addFeatImages; for (std::size_t i=0; i<rawData.size(); ++i) addFeatImages.push_back(std::vector< ItkFloatImgType::Pointer >()); int c = 0; for (auto file : addFeatFiles) { mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(file); ItkFloatImgType::Pointer itkimg = ItkFloatImgType::New(); mitk::CastToItkImage(img, itkimg); addFeatImages.at(c%addFeatImages.size()).push_back(itkimg); c++; } mitk::TractographyForest::Pointer forest = nullptr; if (shfeatures) { mitk::TrackingHandlerRandomForest<6,28> forestHandler; forestHandler.SetDwis(rawData); forestHandler.SetMaskImages(maskImageVector); forestHandler.SetWhiteMatterImages(wmMaskImageVector); forestHandler.SetFiberVolumeModImages(volumeModImages); forestHandler.SetAdditionalFeatureImages(addFeatImages); forestHandler.SetTractograms(tractograms); forestHandler.SetNumTrees(num_trees); forestHandler.SetMaxTreeDepth(max_tree_depth); forestHandler.SetGrayMatterSamplesPerVoxel(gm_samples); forestHandler.SetSampleFraction(sample_fraction); forestHandler.SetFiberSamplingStep(sampling_distance); forestHandler.SetMaxNumWmSamples(maxWmSamples); forestHandler.StartTraining(); forest = forestHandler.GetForest(); } else { mitk::TrackingHandlerRandomForest<6,100> forestHandler; forestHandler.SetDwis(rawData); forestHandler.SetMaskImages(maskImageVector); forestHandler.SetWhiteMatterImages(wmMaskImageVector); forestHandler.SetFiberVolumeModImages(volumeModImages); forestHandler.SetAdditionalFeatureImages(addFeatImages); forestHandler.SetTractograms(tractograms); forestHandler.SetNumTrees(num_trees); forestHandler.SetMaxTreeDepth(max_tree_depth); forestHandler.SetGrayMatterSamplesPerVoxel(gm_samples); forestHandler.SetSampleFraction(sample_fraction); forestHandler.SetFiberSamplingStep(sampling_distance); forestHandler.SetMaxNumWmSamples(maxWmSamples); forestHandler.StartTraining(); forest = forestHandler.GetForest(); } mitk::IOUtil::Save(forest, forestFile); return EXIT_SUCCESS; }
Remove unmatching closing parenthesis
Remove unmatching closing parenthesis
C++
bsd-3-clause
MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,fmilano/mitk,fmilano/mitk,MITK/MITK,MITK/MITK,fmilano/mitk,MITK/MITK,MITK/MITK,MITK/MITK,fmilano/mitk
5d119377ce4b3b4f46e2b3736038f493ba4ca3be
Sources/hspp/Policy/BasicPolicy.cpp
Sources/hspp/Policy/BasicPolicy.cpp
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Policy/BasicPolicy.hpp> namespace Hearthstonepp { TaskMeta BasicPolicy::Next(const Game& game) { return TaskMeta(); } TaskMeta BasicPolicy::Require(Player& player, TaskID id) { if (auto iter = m_require.find(id); iter != m_require.end()) { return iter->second(*this, player); } return TaskMeta(id); } } // namespace Hearthstonepp
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Policy/BasicPolicy.hpp> namespace Hearthstonepp { TaskMeta BasicPolicy::Next(const Game& game) { (void)game; return TaskMeta(); } TaskMeta BasicPolicy::Require(Player& player, TaskID id) { if (auto iter = m_require.find(id); iter != m_require.end()) { return iter->second(*this, player); } return TaskMeta(id); } } // namespace Hearthstonepp
Make unused variable void
fix: Make unused variable void
C++
mit
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
ef9b9fbf09e723b7adeebd5e365b33e8d0671542
include/Bull/Math/Vector/Vector.inl
include/Bull/Math/Vector/Vector.inl
#include <cmath> namespace Bull { template <typename T, Index S> Vector<T, S> Vector<T, S>::normalize(const Vector<T, S>& vector) { return Vector<T, S>(vector).normalize(); } template <typename T, Index S> T Vector<T, S>::dotProduct(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left).dotProduct(right); } template <typename T, Index S> Vector<T, S>::Vector() : Vector<T, S>(0) { /// Nothing } template <typename T, Index S> Vector<T, S>::Vector(T value) { m_components.fill(value); } template <typename T, Index S> template <typename U, Index US> Vector<T, S>::Vector(const Vector<U, US>& copy) : Vector<T, S>() { for(Index i = 0; i < std::min(S, US); i++) { at(i) = static_cast<T>(copy.at(i)); } } template <typename T, Index S> template <typename U, Index US> Vector<T, S>& Vector<T, S>::operator=(const Vector<U, US>& copy) { m_components.fill(0); for(Index i = 0; i < std::min(S, US); i++) { at(i) = static_cast<T>(copy.at(i)); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::set(T value) { m_components.fill(value); return (*this); } template <typename T, Index S> float Vector<T, S>::getLength() const { float length = 0; for(T component : m_components) { length += std::pow(component, 2); } return std::sqrt(length); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::normalize() { float length = getLength(); if(length > 1.f) { for(T& component : m_components) { component /= length; } } return (*this); } template <typename T, Index S> T Vector<T, S>::dotProduct(const Vector<T, S>& right) const { float sum = 0; for(Index i = 0; i < S; i++) { sum += at(i) + right.at(i); } return sum; } template <typename T, Index S> bool Vector<T, S>::operator==(const Vector<T, S>& right) const { return m_components == right.m_components; } template <typename T, Index S> bool Vector<T, S>::operator!=(const Vector<T, S>& right) const { return m_components != right.m_components; } template <typename T, Index S> T& Vector<T, S>::at(Index index) { RangeCheck(index, S); return m_components.at(index); } template <typename T, Index S> const T& Vector<T, S>::at(Index index) const { RangeCheck(index, S); return m_components.at(index); } template <typename T, Index S> Vector<T, S> Vector<T, S>::operator-() const { Vector<T, S> negation; for(Index i = 0; i < S; i++) { negation.at(i) = -at(i); } return negation; }; template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator+=(T right) { for(Index i = 0; i < S; i++) { at(i) += right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator+=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) += right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator-=(T right) { for(Index i = 0; i < S; i++) { at(i) -= right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator-=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) -= right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator*=(T right) { for(Index i = 0; i < S; i++) { at(i) *= right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator*=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) *= right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator/=(T right) { for(Index i = 0; i < S; i++) { at(i) /= right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator/=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) /= right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S> operator+(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) += right; }; template <typename T, Index S> Vector<T, S> operator+(T left, const Vector<T, S>& right) { return Vector<T, S>(left) += right; }; template <typename T, Index S> Vector<T, S> operator+(const Vector<T, S>& left, T right) { return Vector<T, S>(left) += right; }; template <typename T, Index S> Vector<T, S> operator-(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) -= right; }; template <typename T, Index S> Vector<T, S> operator-(T left, const Vector<T, S>& right) { return Vector<T, S>(left) -= right; }; template <typename T, Index S> Vector<T, S> operator-(const Vector<T, S>& left, T right) { return Vector<T, S>(left) -= right; }; template <typename T, Index S> Vector<T, S> operator*(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) *= right; }; template <typename T, Index S> Vector<T, S> operator*(T left, const Vector<T, S>& right) { return Vector<T, S>(left) *= right; }; template <typename T, Index S> Vector<T, S> operator*(const Vector<T, S>& left, T right) { return Vector<T, S>(left) *= right; }; template <typename T, Index S> Vector<T, S> operator/(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) /= right; }; template <typename T, Index S> Vector<T, S> operator/(T left, const Vector<T, S>& right) { return Vector<T, S>(left) /= right; }; template <typename T, Index S> Vector<T, S> operator/(const Vector<T, S>& left, T right) { return Vector<T, S>(left) /= right; }; }
#include <cmath> namespace Bull { template <typename T, Index S> Vector<T, S> Vector<T, S>::normalize(const Vector<T, S>& vector) { return Vector<T, S>(vector).normalize(); } template <typename T, Index S> T Vector<T, S>::dotProduct(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left).dotProduct(right); } template <typename T, Index S> Vector<T, S>::Vector() : Vector<T, S>(0) { /// Nothing } template <typename T, Index S> Vector<T, S>::Vector(T value) { m_components.fill(value); } template <typename T, Index S> template <typename U, Index US> Vector<T, S>::Vector(const Vector<U, US>& copy) : Vector<T, S>() { for(Index i = 0; i < std::min(S, US); i++) { at(i) = static_cast<T>(copy.at(i)); } } template <typename T, Index S> template <typename U, Index US> Vector<T, S>& Vector<T, S>::operator=(const Vector<U, US>& copy) { m_components.fill(0); for(Index i = 0; i < std::min(S, US); i++) { at(i) = static_cast<T>(copy.at(i)); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::set(T value) { m_components.fill(value); return (*this); } template <typename T, Index S> float Vector<T, S>::getLength() const { float length = 0; for(T component : m_components) { length += std::pow(component, 2); } return std::sqrt(length); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::normalize() { float length = getLength(); if(length > 1.f) { for(T& component : m_components) { component /= length; } } return (*this); } template <typename T, Index S> T Vector<T, S>::dotProduct(const Vector<T, S>& right) const { float sum = 0; for(Index i = 0; i < S; i++) { sum += at(i) * right.at(i); } return sum; } template <typename T, Index S> bool Vector<T, S>::operator==(const Vector<T, S>& right) const { return m_components == right.m_components; } template <typename T, Index S> bool Vector<T, S>::operator!=(const Vector<T, S>& right) const { return m_components != right.m_components; } template <typename T, Index S> T& Vector<T, S>::at(Index index) { RangeCheck(index, S); return m_components.at(index); } template <typename T, Index S> const T& Vector<T, S>::at(Index index) const { RangeCheck(index, S); return m_components.at(index); } template <typename T, Index S> Vector<T, S> Vector<T, S>::operator-() const { Vector<T, S> negation; for(Index i = 0; i < S; i++) { negation.at(i) = -at(i); } return negation; }; template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator+=(T right) { for(Index i = 0; i < S; i++) { at(i) += right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator+=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) += right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator-=(T right) { for(Index i = 0; i < S; i++) { at(i) -= right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator-=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) -= right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator*=(T right) { for(Index i = 0; i < S; i++) { at(i) *= right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator*=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) *= right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator/=(T right) { for(Index i = 0; i < S; i++) { at(i) /= right; } return (*this); } template <typename T, Index S> Vector<T, S>& Vector<T, S>::operator/=(const Vector<T, S>& right) { for(Index i = 0; i < S; i++) { at(i) /= right.at(i); } return (*this); } template <typename T, Index S> Vector<T, S> operator+(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) += right; }; template <typename T, Index S> Vector<T, S> operator+(T left, const Vector<T, S>& right) { return Vector<T, S>(left) += right; }; template <typename T, Index S> Vector<T, S> operator+(const Vector<T, S>& left, T right) { return Vector<T, S>(left) += right; }; template <typename T, Index S> Vector<T, S> operator-(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) -= right; }; template <typename T, Index S> Vector<T, S> operator-(T left, const Vector<T, S>& right) { return Vector<T, S>(left) -= right; }; template <typename T, Index S> Vector<T, S> operator-(const Vector<T, S>& left, T right) { return Vector<T, S>(left) -= right; }; template <typename T, Index S> Vector<T, S> operator*(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) *= right; }; template <typename T, Index S> Vector<T, S> operator*(T left, const Vector<T, S>& right) { return Vector<T, S>(left) *= right; }; template <typename T, Index S> Vector<T, S> operator*(const Vector<T, S>& left, T right) { return Vector<T, S>(left) *= right; }; template <typename T, Index S> Vector<T, S> operator/(const Vector<T, S>& left, const Vector<T, S>& right) { return Vector<T, S>(left) /= right; }; template <typename T, Index S> Vector<T, S> operator/(T left, const Vector<T, S>& right) { return Vector<T, S>(left) /= right; }; template <typename T, Index S> Vector<T, S> operator/(const Vector<T, S>& left, T right) { return Vector<T, S>(left) /= right; }; }
Fix dot product
[Math/Vector] Fix dot product
C++
mit
siliace/Bull
c345a6a6c9af634cda82dc699d5dc83686be5864
include/seastar/websocket/server.hh
include/seastar/websocket/server.hh
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright 2021 ScyllaDB */ #pragma once #include <map> #include <functional> #include <seastar/http/request_parser.hh> #include <seastar/core/seastar.hh> #include <seastar/core/sstring.hh> #include <seastar/net/api.hh> #include <seastar/core/gate.hh> #include <seastar/core/queue.hh> #include <seastar/core/when_all.hh> namespace seastar::experimental::websocket { using handler_t = std::function<future<>(input_stream<char>&, output_stream<char>&)>; class server; /*! * \brief an error in handling a WebSocket connection */ class exception : public std::exception { std::string _msg; public: exception(std::string_view msg) : _msg(msg) {} virtual const char* what() const noexcept { return _msg.c_str(); } }; /*! * \brief Possible type of a websocket frame. */ enum opcodes { CONTINUATION = 0x0, TEXT = 0x1, BINARY = 0x2, CLOSE = 0x8, PING = 0x9, PONG = 0xA, INVALID = 0xFF, }; struct frame_header { static constexpr uint8_t FIN = 7; static constexpr uint8_t RSV1 = 6; static constexpr uint8_t RSV2 = 5; static constexpr uint8_t RSV3 = 4; static constexpr uint8_t MASKED = 7; uint8_t fin : 1; uint8_t rsv1 : 1; uint8_t rsv2 : 1; uint8_t rsv3 : 1; uint8_t opcode : 4; uint8_t masked : 1; uint8_t length : 7; frame_header(const char* input) { this->fin = (input[0] >> FIN) & 1; this->rsv1 = (input[0] >> RSV1) & 1; this->rsv2 = (input[0] >> RSV2) & 1; this->rsv3 = (input[0] >> RSV3) & 1; this->opcode = input[0] & 0b1111; this->masked = (input[1] >> MASKED) & 1; this->length = (input[1] & 0b1111111); } // Returns length of the rest of the header. uint64_t get_rest_of_header_length() { size_t next_read_length = sizeof(uint32_t); // Masking key if (length == 126) { next_read_length += sizeof(uint16_t); } else if (length == 127) { next_read_length += sizeof(uint64_t); } return next_read_length; } uint8_t get_fin() {return fin;} uint8_t get_rsv1() {return rsv1;} uint8_t get_rsv2() {return rsv2;} uint8_t get_rsv3() {return rsv3;} uint8_t get_opcode() {return opcode;} uint8_t get_masked() {return masked;} uint8_t get_length() {return length;} bool is_opcode_known() { //https://datatracker.ietf.org/doc/html/rfc6455#section-5.1 return opcode < 0xA && !(opcode < 0x8 && opcode > 0x2); } }; class websocket_parser { enum class parsing_state : uint8_t { flags_and_payload_data, payload_length_and_mask, payload }; enum class connection_state : uint8_t { valid, closed, error }; using consumption_result_t = consumption_result<char>; using buff_t = temporary_buffer<char>; // What parser is currently doing. parsing_state _state; // State of connection - can be valid, closed or should be closed // due to error. connection_state _cstate; sstring _buffer; std::unique_ptr<frame_header> _header; uint64_t _payload_length; uint32_t _masking_key; buff_t _result; static future<consumption_result_t> dont_stop() { return make_ready_future<consumption_result_t>(continue_consuming{}); } static future<consumption_result_t> stop(buff_t data) { return make_ready_future<consumption_result_t>(stop_consuming(std::move(data))); } // Removes mask from payload given in p. void remove_mask(buff_t& p, size_t n) { char *payload = p.get_write(); for (uint64_t i = 0, j = 0; i < n; ++i, j = (j + 1) % 4) { payload[i] ^= static_cast<char>(((_masking_key << (j * 8)) >> 24)); } } public: websocket_parser() : _state(parsing_state::flags_and_payload_data), _cstate(connection_state::valid), _payload_length(0), _masking_key(0) {} future<consumption_result_t> operator()(temporary_buffer<char> data); bool is_valid() { return _cstate == connection_state::valid; } bool eof() { return _cstate == connection_state::closed; } opcodes opcode() const; buff_t result(); }; /*! * \brief a WebSocket connection */ class connection : public boost::intrusive::list_base_hook<> { using buff_t = temporary_buffer<char>; /*! * \brief Internal error that is thrown when there is no more data to read. */ class eof_exception : public std::exception { public: eof_exception() {} virtual const char* what() const noexcept { return "Websocket connection: stream closed"; } }; /*! * \brief Implementation of connection's data source. */ class connection_source_impl final : public data_source_impl { queue<buff_t>* data; public: connection_source_impl(queue<buff_t>* data) : data(data) {} virtual future<buff_t> get() override { return data->pop_eventually().then_wrapped([](future<buff_t> f){ try { return make_ready_future<buff_t>(std::move(f.get())); } catch (const eof_exception&) { return make_ready_future<buff_t>(0); } catch(...) { return current_exception_as_future<buff_t>(); } }); } virtual future<> close() override { data->abort(std::make_exception_ptr(eof_exception())); return make_ready_future<>(); } }; /*! * \brief Implementation of connection's data sink. */ class connection_sink_impl final : public data_sink_impl { queue<buff_t>* data; public: connection_sink_impl(queue<buff_t>* data) : data(data) {} virtual future<> put(net::packet d) override { net::fragment f = d.frag(0); return data->push_eventually(temporary_buffer<char>{std::move(f.base), f.size}); } size_t buffer_size() const noexcept override { return data->max_size(); } virtual future<> close() override { data->abort(std::make_exception_ptr(eof_exception())); return make_ready_future<>(); } }; future<> close(bool send_close); /*! * \brief This function processess received PING frame. * https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 */ future<> handle_ping(); /*! * \brief This function processess received PONG frame. * https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 */ future<> handle_pong(); static const size_t PIPE_SIZE = 512; server& _server; connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; http_request_parser _http_parser; bool _done = false; websocket_parser _websocket_parser; queue <temporary_buffer<char>> _input_buffer; input_stream<char> _input; queue <temporary_buffer<char>> _output_buffer; output_stream<char> _output; sstring _subprotocol; handler_t _handler; public: /*! * \param server owning \ref server * \param fd established socket used for communication */ connection(server& server, connected_socket&& fd) : _server(server) , _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) , _input_buffer{PIPE_SIZE} , _output_buffer{PIPE_SIZE} { _input = input_stream<char>{data_source{ std::make_unique<connection_source_impl>(&_input_buffer)}}; _output = output_stream<char>{data_sink{ std::make_unique<connection_sink_impl>(&_output_buffer)}}; on_new_connection(); } ~connection(); /*! * \brief serve WebSocket protocol on a connection */ future<> process(); /*! * \brief close the socket */ void shutdown(); future<> close(); protected: future<> read_loop(); future<> read_one(); future<> read_http_upgrade_request(); future<> response_loop(); void on_new_connection(); /*! * \brief Packs buff in websocket frame and sends it to the client. */ future<> send_data(opcodes opcode, temporary_buffer<char>&& buff); }; /*! * \brief a WebSocket server * * A server capable of establishing and serving connections * over WebSocket protocol. */ class server { std::vector<server_socket> _listeners; boost::intrusive::list<connection> _connections; std::map<std::string, handler_t> _handlers; future<> _accept_fut = make_ready_future<>(); bool _stopped = false; public: /*! * \brief listen for a WebSocket connection on given address * \param addr address to listen on */ void listen(socket_address addr); /*! * \brief listen for a WebSocket connection on given address with custom options * \param addr address to listen on * \param lo custom listen options (\ref listen_options) */ void listen(socket_address addr, listen_options lo); /*! * Stops the server and shuts down all active connections */ future<> stop(); bool is_handler_registered(std::string const& name); void register_handler(std::string&& name, handler_t handler); friend class connection; protected: void do_accepts(int which); future<> do_accept_one(int which); }; }
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright 2021 ScyllaDB */ #pragma once #include <map> #include <functional> #include <seastar/http/request_parser.hh> #include <seastar/core/seastar.hh> #include <seastar/core/sstring.hh> #include <seastar/net/api.hh> #include <seastar/core/gate.hh> #include <seastar/core/queue.hh> #include <seastar/core/when_all.hh> namespace seastar::experimental::websocket { using handler_t = std::function<future<>(input_stream<char>&, output_stream<char>&)>; class server; /*! * \brief an error in handling a WebSocket connection */ class exception : public std::exception { std::string _msg; public: exception(std::string_view msg) : _msg(msg) {} virtual const char* what() const noexcept { return _msg.c_str(); } }; /*! * \brief Possible type of a websocket frame. */ enum opcodes { CONTINUATION = 0x0, TEXT = 0x1, BINARY = 0x2, CLOSE = 0x8, PING = 0x9, PONG = 0xA, INVALID = 0xFF, }; struct frame_header { static constexpr uint8_t FIN = 7; static constexpr uint8_t RSV1 = 6; static constexpr uint8_t RSV2 = 5; static constexpr uint8_t RSV3 = 4; static constexpr uint8_t MASKED = 7; uint8_t fin : 1; uint8_t rsv1 : 1; uint8_t rsv2 : 1; uint8_t rsv3 : 1; uint8_t opcode : 4; uint8_t masked : 1; uint8_t length : 7; frame_header(const char* input) { this->fin = (input[0] >> FIN) & 1; this->rsv1 = (input[0] >> RSV1) & 1; this->rsv2 = (input[0] >> RSV2) & 1; this->rsv3 = (input[0] >> RSV3) & 1; this->opcode = input[0] & 0b1111; this->masked = (input[1] >> MASKED) & 1; this->length = (input[1] & 0b1111111); } // Returns length of the rest of the header. uint64_t get_rest_of_header_length() { size_t next_read_length = sizeof(uint32_t); // Masking key if (length == 126) { next_read_length += sizeof(uint16_t); } else if (length == 127) { next_read_length += sizeof(uint64_t); } return next_read_length; } uint8_t get_fin() {return fin;} uint8_t get_rsv1() {return rsv1;} uint8_t get_rsv2() {return rsv2;} uint8_t get_rsv3() {return rsv3;} uint8_t get_opcode() {return opcode;} uint8_t get_masked() {return masked;} uint8_t get_length() {return length;} bool is_opcode_known() { //https://datatracker.ietf.org/doc/html/rfc6455#section-5.1 return opcode < 0xA && !(opcode < 0x8 && opcode > 0x2); } }; class websocket_parser { enum class parsing_state : uint8_t { flags_and_payload_data, payload_length_and_mask, payload }; enum class connection_state : uint8_t { valid, closed, error }; using consumption_result_t = consumption_result<char>; using buff_t = temporary_buffer<char>; // What parser is currently doing. parsing_state _state; // State of connection - can be valid, closed or should be closed // due to error. connection_state _cstate; sstring _buffer; std::unique_ptr<frame_header> _header; uint64_t _payload_length; uint32_t _masking_key; buff_t _result; static future<consumption_result_t> dont_stop() { return make_ready_future<consumption_result_t>(continue_consuming{}); } static future<consumption_result_t> stop(buff_t data) { return make_ready_future<consumption_result_t>(stop_consuming(std::move(data))); } // Removes mask from payload given in p. void remove_mask(buff_t& p, size_t n) { char *payload = p.get_write(); for (uint64_t i = 0, j = 0; i < n; ++i, j = (j + 1) % 4) { payload[i] ^= static_cast<char>(((_masking_key << (j * 8)) >> 24)); } } public: websocket_parser() : _state(parsing_state::flags_and_payload_data), _cstate(connection_state::valid), _payload_length(0), _masking_key(0) {} future<consumption_result_t> operator()(temporary_buffer<char> data); bool is_valid() { return _cstate == connection_state::valid; } bool eof() { return _cstate == connection_state::closed; } opcodes opcode() const; buff_t result(); }; /*! * \brief a WebSocket connection */ class connection : public boost::intrusive::list_base_hook<> { using buff_t = temporary_buffer<char>; /*! * \brief Implementation of connection's data source. */ class connection_source_impl final : public data_source_impl { queue<buff_t>* data; public: connection_source_impl(queue<buff_t>* data) : data(data) {} virtual future<buff_t> get() override { return data->pop_eventually().then_wrapped([](future<buff_t> f){ try { return make_ready_future<buff_t>(std::move(f.get())); } catch(...) { return current_exception_as_future<buff_t>(); } }); } virtual future<> close() override { data->push(buff_t(0)); return make_ready_future<>(); } }; /*! * \brief Implementation of connection's data sink. */ class connection_sink_impl final : public data_sink_impl { queue<buff_t>* data; public: connection_sink_impl(queue<buff_t>* data) : data(data) {} virtual future<> put(net::packet d) override { net::fragment f = d.frag(0); return data->push_eventually(temporary_buffer<char>{std::move(f.base), f.size}); } size_t buffer_size() const noexcept override { return data->max_size(); } virtual future<> close() override { data->push(buff_t(0)); return make_ready_future<>(); } }; future<> close(bool send_close); /*! * \brief This function processess received PING frame. * https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 */ future<> handle_ping(); /*! * \brief This function processess received PONG frame. * https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 */ future<> handle_pong(); static const size_t PIPE_SIZE = 512; server& _server; connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; http_request_parser _http_parser; bool _done = false; websocket_parser _websocket_parser; queue <temporary_buffer<char>> _input_buffer; input_stream<char> _input; queue <temporary_buffer<char>> _output_buffer; output_stream<char> _output; sstring _subprotocol; handler_t _handler; public: /*! * \param server owning \ref server * \param fd established socket used for communication */ connection(server& server, connected_socket&& fd) : _server(server) , _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) , _input_buffer{PIPE_SIZE} , _output_buffer{PIPE_SIZE} { _input = input_stream<char>{data_source{ std::make_unique<connection_source_impl>(&_input_buffer)}}; _output = output_stream<char>{data_sink{ std::make_unique<connection_sink_impl>(&_output_buffer)}}; on_new_connection(); } ~connection(); /*! * \brief serve WebSocket protocol on a connection */ future<> process(); /*! * \brief close the socket */ void shutdown(); future<> close(); protected: future<> read_loop(); future<> read_one(); future<> read_http_upgrade_request(); future<> response_loop(); void on_new_connection(); /*! * \brief Packs buff in websocket frame and sends it to the client. */ future<> send_data(opcodes opcode, temporary_buffer<char>&& buff); }; /*! * \brief a WebSocket server * * A server capable of establishing and serving connections * over WebSocket protocol. */ class server { std::vector<server_socket> _listeners; boost::intrusive::list<connection> _connections; std::map<std::string, handler_t> _handlers; future<> _accept_fut = make_ready_future<>(); bool _stopped = false; public: /*! * \brief listen for a WebSocket connection on given address * \param addr address to listen on */ void listen(socket_address addr); /*! * \brief listen for a WebSocket connection on given address with custom options * \param addr address to listen on * \param lo custom listen options (\ref listen_options) */ void listen(socket_address addr, listen_options lo); /*! * Stops the server and shuts down all active connections */ future<> stop(); bool is_handler_registered(std::string const& name); void register_handler(std::string&& name, handler_t handler); friend class connection; protected: void do_accepts(int which); future<> do_accept_one(int which); }; }
remove eof_exception and use empty buffer instead
websocket: remove eof_exception and use empty buffer instead In order to signal EOF, an exception is no longer used - instead, an empty buffer is appended to the queue, and it's later recognized as end-of-stream.
C++
apache-2.0
syuu1228/seastar,scylladb/seastar,avikivity/seastar,syuu1228/seastar,syuu1228/seastar,avikivity/seastar,scylladb/seastar,scylladb/seastar,avikivity/seastar
24a4766597af0e91443803c11693aac06121cd83
include/tudocomp_stat/StatPhase.hpp
include/tudocomp_stat/StatPhase.hpp
#pragma once #include <cstring> #include <ctime> #include <tudocomp_stat/Json.hpp> namespace tdc { class StatPhase { private: static StatPhase* s_current; inline static unsigned long current_time_millis() { timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1000L + t.tv_nsec / 1000000L; } class Data { friend class StatPhase; public: static constexpr size_t STR_BUFFER_SIZE = 64; private: struct keyval { keyval* next; char key[STR_BUFFER_SIZE]; char val[STR_BUFFER_SIZE]; inline keyval() : next(nullptr) { } ~keyval() { if(next) delete next; } }; private: char title[STR_BUFFER_SIZE]; unsigned long time_start; unsigned long time_end; ssize_t mem_off; ssize_t mem_current; ssize_t mem_peak; keyval* first_stat; Data* first_child; Data* next_sibling; inline Data() : first_stat(nullptr), first_child(nullptr), next_sibling(nullptr) { } ~Data() { if(first_stat) delete first_stat; if(first_child) delete first_child; if(next_sibling) delete next_sibling; } template<typename T> inline void log_stat(const char* key, const T& value) { keyval* kv = new keyval(); { json::TValue<T> t(value); std::stringstream ss; t.str(ss); strncpy(kv->key, key, STR_BUFFER_SIZE); strncpy(kv->val, ss.str().c_str(), STR_BUFFER_SIZE); } if(first_stat) { keyval* last = first_stat; while(last->next) { last = last->next; } last->next = kv; } else { first_stat = kv; } } public: inline json::Object to_json() const { json::Object obj; obj.set("title", title); obj.set("timeStart", time_start); obj.set("timeEnd", time_end); obj.set("memOff", mem_off); obj.set("memPeak", mem_peak); obj.set("memFinal", mem_current); json::Array stats; keyval* kv = first_stat; while(kv) { json::Object pair; pair.set("key", std::string(kv->key)); pair.set("value", std::string(kv->val)); stats.add(pair); kv = kv->next; } obj.set("stats", stats); json::Array sub; Data* child = first_child; while(child) { sub.add(child->to_json()); child = child->next_sibling; } obj.set("sub", sub); return obj; } }; StatPhase* m_parent; Data* m_data; bool m_track_memory; inline void append_child(Data* data) { if(m_data->first_child) { Data* last = m_data->first_child; while(last->next_sibling) { last = last->next_sibling; } last->next_sibling = data; } else { m_data->first_child = data; } } inline void track_alloc_internal(size_t bytes) { if(m_track_memory) { m_data->mem_current += bytes; m_data->mem_peak = std::max(m_data->mem_peak, m_data->mem_current); if(m_parent) m_parent->track_alloc_internal(bytes); } } inline void track_free_internal(size_t bytes) { if(m_track_memory) { m_data->mem_current -= bytes; if(m_parent) m_parent->track_free_internal(bytes); } } public: template<typename F> inline static auto wrap(const char* title, F func) -> typename std::result_of<F(StatPhase&)>::type { StatPhase phase(title); return func(phase); } template<typename F> inline static auto wrap(const char* title, F func) -> typename std::result_of<F()>::type { StatPhase phase(title); return func(); } inline static void track_alloc(size_t bytes) { if(s_current) s_current->track_alloc_internal(bytes); } inline static void track_free(size_t bytes) { if(s_current) s_current->track_free_internal(bytes); } template<typename T> inline static void current_log_stat(const char* key, const T& value) { if(s_current) s_current->log_stat(key, value); } inline StatPhase(const char* title) { m_parent = s_current; if(m_parent) m_parent->m_track_memory = false; m_data = new Data(); if(m_parent) m_parent->m_track_memory = true; strncpy(m_data->title, title, Data::STR_BUFFER_SIZE); s_current = this; m_track_memory = true; m_data->mem_off = m_parent ? m_parent->m_data->mem_current : 0; m_data->mem_current = 0; m_data->mem_peak = 0; m_data->time_end = 0; m_data->time_start = current_time_millis(); m_track_memory = true; } ~StatPhase() { // finish m_track_memory = false; m_data->time_end = current_time_millis(); if(m_parent) { // add data to parent's data m_parent->append_child(m_data); } else { // if this was the root, delete data delete m_data; } // pop parent s_current = m_parent; } template<typename T> inline void log_stat(const char* key, const T& value) { m_track_memory = false; m_data->log_stat(key, value); m_track_memory = true; } inline json::Object to_json() { m_data->time_end = current_time_millis(); m_track_memory = false; json::Object obj = m_data->to_json(); //m_data->to_json().str(out); m_track_memory = true; return obj; } }; }
#pragma once #include <cstring> #include <ctime> #include <tudocomp_stat/Json.hpp> namespace tdc { class StatPhase { private: static StatPhase* s_current; inline static unsigned long current_time_millis() { timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1000L + t.tv_nsec / 1000000L; } class Data { friend class StatPhase; public: static constexpr size_t STR_BUFFER_SIZE = 64; private: struct keyval { keyval* next; char key[STR_BUFFER_SIZE]; char val[STR_BUFFER_SIZE]; inline keyval() : next(nullptr) { } ~keyval() { if(next) delete next; } }; private: char title[STR_BUFFER_SIZE]; unsigned long time_start; unsigned long time_end; ssize_t mem_off; ssize_t mem_current; ssize_t mem_peak; keyval* first_stat; Data* first_child; Data* next_sibling; inline Data() : first_stat(nullptr), first_child(nullptr), next_sibling(nullptr) { } ~Data() { if(first_stat) delete first_stat; if(first_child) delete first_child; if(next_sibling) delete next_sibling; } template<typename T> inline void log_stat(const char* key, const T& value) { keyval* kv = new keyval(); { json::TValue<T> t(value); std::stringstream ss; t.str(ss); strncpy(kv->key, key, STR_BUFFER_SIZE); strncpy(kv->val, ss.str().c_str(), STR_BUFFER_SIZE); } if(first_stat) { keyval* last = first_stat; while(last->next) { last = last->next; } last->next = kv; } else { first_stat = kv; } } public: inline json::Object to_json() const { json::Object obj; obj.set("title", title); obj.set("timeStart", time_start); obj.set("timeEnd", time_end); obj.set("memOff", mem_off); obj.set("memPeak", mem_peak); obj.set("memFinal", mem_current); json::Array stats; keyval* kv = first_stat; while(kv) { json::Object pair; pair.set("key", std::string(kv->key)); pair.set("value", std::string(kv->val)); stats.add(pair); kv = kv->next; } obj.set("stats", stats); json::Array sub; Data* child = first_child; while(child) { sub.add(child->to_json()); child = child->next_sibling; } obj.set("sub", sub); return obj; } }; StatPhase* m_parent; Data* m_data; bool m_track_memory; inline void append_child(Data* data) { if(m_data->first_child) { Data* last = m_data->first_child; while(last->next_sibling) { last = last->next_sibling; } last->next_sibling = data; } else { m_data->first_child = data; } } inline void track_alloc_internal(size_t bytes) { if(m_track_memory) { m_data->mem_current += bytes; m_data->mem_peak = std::max(m_data->mem_peak, m_data->mem_current); if(m_parent) m_parent->track_alloc_internal(bytes); } } inline void track_free_internal(size_t bytes) { if(m_track_memory) { m_data->mem_current -= bytes; if(m_parent) m_parent->track_free_internal(bytes); } } public: template<typename F> inline static auto wrap(const char* title, F func) -> typename std::result_of<F(StatPhase&)>::type { StatPhase phase(title); return func(phase); } template<typename F> inline static auto wrap(const char* title, F func) -> typename std::result_of<F()>::type { StatPhase phase(title); return func(); } inline static void track_alloc(size_t bytes) { if(s_current) s_current->track_alloc_internal(bytes); } inline static void track_free(size_t bytes) { if(s_current) s_current->track_free_internal(bytes); } template<typename T> inline static void current_log_stat(const char* key, const T& value) { if(s_current) s_current->log_stat(key, value); } private: inline void init(const char* title) { m_parent = s_current; if(m_parent) m_parent->m_track_memory = false; m_data = new Data(); if(m_parent) m_parent->m_track_memory = true; strncpy(m_data->title, title, Data::STR_BUFFER_SIZE); m_data->mem_off = m_parent ? m_parent->m_data->mem_current : 0; m_data->mem_current = 0; m_data->mem_peak = 0; m_data->time_end = 0; m_data->time_start = current_time_millis(); s_current = this; } inline void finish() { m_data->time_end = current_time_millis(); if(m_parent) { // add data to parent's data m_parent->append_child(m_data); } else { // if this was the root, delete data delete m_data; m_data = nullptr; } // pop parent s_current = m_parent; } public: inline StatPhase(const char* title) { m_track_memory = false; init(title); m_track_memory = true; } ~StatPhase() { m_track_memory = false; finish(); } inline void split(const char* new_title) { m_track_memory = false; finish(); Data* old_data = m_data; init(new_title); if(old_data) m_data->mem_off = old_data->mem_current; m_track_memory = true; } template<typename T> inline void log_stat(const char* key, const T& value) { m_track_memory = false; m_data->log_stat(key, value); m_track_memory = true; } inline json::Object to_json() { m_data->time_end = current_time_millis(); m_track_memory = false; json::Object obj = m_data->to_json(); //m_data->to_json().str(out); m_track_memory = true; return obj; } }; }
Implement split method for StatPhase
Implement split method for StatPhase
C++
apache-2.0
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
8b8735229b4c6e42dacc804f05a35b7465550e06
Xcode/SmartSensors/src/tuneable.cpp
Xcode/SmartSensors/src/tuneable.cpp
#include "tuneable.h" #include <cmath> #include "ofApp.h" static std::map<void*, Tuneable*> allTuneables; void Tuneable::onSliderEvent(ofxDatGuiSliderEvent e) { for (const auto& t : allTuneables) { void* data_ptr = t.second->getDataAddress(); void* ui_ptr = t.second->getUIAddress(); if (e.target == ui_ptr) { if (t.second->getType() == Tuneable::INT_RANGE) { int* value = static_cast<int*>(data_ptr); int set_value = std::round(e.value); *value = set_value; // Because slider only supports double, we have to manually round it to // match integer semantics. e.target->setValue(set_value); } else { double* value = static_cast<double*>(data_ptr); *value = e.value; } ((ofApp *) ofGetAppPtr())->reloadPipelineModules(); } } } void Tuneable::onToggleEvent(ofxDatGuiButtonEvent e) { for (const auto& t : allTuneables) { void* data_ptr = t.second->getDataAddress(); void* ui_ptr = t.second->getUIAddress(); if (e.target == ui_ptr) { bool* value = static_cast<bool*>(data_ptr); *value = e.enabled; ((ofApp *) ofGetAppPtr())->reloadPipelineModules(); } } } void registerTuneable(int& value, int min, int max, const string& description) { void* address = &value; if (allTuneables.find(address) != allTuneables.end()) { return; } Tuneable* t = new Tuneable(&value, min, max, description); allTuneables[address] = t; ((ofApp *) ofGetAppPtr())->registerTuneable(t); } void registerTuneable(double& value, int min, int max, const string& description) { void* address = &value; if (allTuneables.find(address) != allTuneables.end()) { return; } Tuneable* t = new Tuneable(&value, min, max, description); allTuneables[address] = t; ((ofApp *) ofGetAppPtr())->registerTuneable(t); } void registerTuneable(bool& value, const string& description) { void* address = &value; if (allTuneables.find(address) != allTuneables.end()) { return; } Tuneable* t = new Tuneable(&value, description); allTuneables[address] = t; ((ofApp *) ofGetAppPtr())->registerTuneable(t); }
#include "tuneable.h" #include <cmath> #include "ofApp.h" static std::map<void*, Tuneable*> allTuneables; void Tuneable::onSliderEvent(ofxDatGuiSliderEvent e) { for (const auto& t : allTuneables) { void* data_ptr = t.second->getDataAddress(); void* ui_ptr = t.second->getUIAddress(); if (e.target == ui_ptr) { if (t.second->getType() == Tuneable::INT_RANGE) { int* value = static_cast<int*>(data_ptr); int set_value = std::round(e.value); *value = set_value; // Because slider only supports double, we have to manually // round it to match integer semantics. e.target->setValue(set_value); } else { double* value = static_cast<double*>(data_ptr); *value = e.value; } ((ofApp *) ofGetAppPtr())->reloadPipelineModules(); } } } void Tuneable::onToggleEvent(ofxDatGuiButtonEvent e) { for (const auto& t : allTuneables) { void* data_ptr = t.second->getDataAddress(); void* ui_ptr = t.second->getUIAddress(); if (e.target == ui_ptr) { bool* value = static_cast<bool*>(data_ptr); *value = e.enabled; ((ofApp *) ofGetAppPtr())->reloadPipelineModules(); } } } void registerTuneable(int& value, int min, int max, const string& description) { void* address = &value; if (allTuneables.find(address) != allTuneables.end()) { return; } Tuneable* t = new Tuneable(&value, min, max, description); allTuneables[address] = t; ((ofApp *) ofGetAppPtr())->registerTuneable(t); } void registerTuneable(double& value, int min, int max, const string& description) { void* address = &value; if (allTuneables.find(address) != allTuneables.end()) { return; } Tuneable* t = new Tuneable(&value, min, max, description); allTuneables[address] = t; ((ofApp *) ofGetAppPtr())->registerTuneable(t); } void registerTuneable(bool& value, const string& description) { void* address = &value; if (allTuneables.find(address) != allTuneables.end()) { return; } Tuneable* t = new Tuneable(&value, description); allTuneables[address] = t; ((ofApp *) ofGetAppPtr())->registerTuneable(t); }
Comment styling.
Comment styling.
C++
bsd-3-clause
damellis/ESP,damellis/ESP
7c1c7f81d2589ca86223aa9f4adfb9b684eab436
faiss/MetaIndexes.cpp
faiss/MetaIndexes.cpp
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // -*- c++ -*- #include <faiss/MetaIndexes.h> #include <cinttypes> #include <cstdio> #include <stdint.h> #include <faiss/impl/FaissAssert.h> #include <faiss/utils/Heap.h> #include <faiss/impl/AuxIndexStructures.h> #include <faiss/utils/WorkerThread.h> namespace faiss { namespace { } // namespace /***************************************************** * IndexIDMap implementation *******************************************************/ template <typename IndexT> IndexIDMapTemplate<IndexT>::IndexIDMapTemplate (IndexT *index): index (index), own_fields (false) { FAISS_THROW_IF_NOT_MSG (index->ntotal == 0, "index must be empty on input"); this->is_trained = index->is_trained; this->metric_type = index->metric_type; this->verbose = index->verbose; this->d = index->d; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::add (idx_t, const typename IndexT::component_t *) { FAISS_THROW_MSG ("add does not make sense with IndexIDMap, " "use add_with_ids"); } template <typename IndexT> void IndexIDMapTemplate<IndexT>::train (idx_t n, const typename IndexT::component_t *x) { index->train (n, x); this->is_trained = index->is_trained; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::reset () { index->reset (); id_map.clear(); this->ntotal = 0; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::add_with_ids (idx_t n, const typename IndexT::component_t * x, const typename IndexT::idx_t *xids) { index->add (n, x); for (idx_t i = 0; i < n; i++) id_map.push_back (xids[i]); this->ntotal = index->ntotal; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::search (idx_t n, const typename IndexT::component_t *x, idx_t k, typename IndexT::distance_t *distances, typename IndexT::idx_t *labels) const { index->search (n, x, k, distances, labels); idx_t *li = labels; #pragma omp parallel for for (idx_t i = 0; i < n * k; i++) { li[i] = li[i] < 0 ? li[i] : id_map[li[i]]; } } template <typename IndexT> void IndexIDMapTemplate<IndexT>::range_search (typename IndexT::idx_t n, const typename IndexT::component_t *x, typename IndexT::distance_t radius, RangeSearchResult *result) const { index->range_search(n, x, radius, result); #pragma omp parallel for for (idx_t i = 0; i < result->lims[result->nq]; i++) { result->labels[i] = result->labels[i] < 0 ? result->labels[i] : id_map[result->labels[i]]; } } namespace { struct IDTranslatedSelector: IDSelector { const std::vector <int64_t> & id_map; const IDSelector & sel; IDTranslatedSelector (const std::vector <int64_t> & id_map, const IDSelector & sel): id_map (id_map), sel (sel) {} bool is_member(idx_t id) const override { return sel.is_member(id_map[id]); } }; } template <typename IndexT> size_t IndexIDMapTemplate<IndexT>::remove_ids (const IDSelector & sel) { // remove in sub-index first IDTranslatedSelector sel2 (id_map, sel); size_t nremove = index->remove_ids (sel2); int64_t j = 0; for (idx_t i = 0; i < this->ntotal; i++) { if (sel.is_member (id_map[i])) { // remove } else { id_map[j] = id_map[i]; j++; } } FAISS_ASSERT (j == index->ntotal); this->ntotal = j; id_map.resize(this->ntotal); return nremove; } template <typename IndexT> IndexIDMapTemplate<IndexT>::~IndexIDMapTemplate () { if (own_fields) delete index; } /***************************************************** * IndexIDMap2 implementation *******************************************************/ template <typename IndexT> IndexIDMap2Template<IndexT>::IndexIDMap2Template (IndexT *index): IndexIDMapTemplate<IndexT> (index) {} template <typename IndexT> void IndexIDMap2Template<IndexT>::add_with_ids (idx_t n, const typename IndexT::component_t* x, const typename IndexT::idx_t* xids) { size_t prev_ntotal = this->ntotal; IndexIDMapTemplate<IndexT>::add_with_ids (n, x, xids); for (size_t i = prev_ntotal; i < this->ntotal; i++) { rev_map [this->id_map [i]] = i; } } template <typename IndexT> void IndexIDMap2Template<IndexT>::construct_rev_map () { rev_map.clear (); for (size_t i = 0; i < this->ntotal; i++) { rev_map [this->id_map [i]] = i; } } template <typename IndexT> size_t IndexIDMap2Template<IndexT>::remove_ids(const IDSelector& sel) { // This is quite inefficient size_t nremove = IndexIDMapTemplate<IndexT>::remove_ids (sel); construct_rev_map (); return nremove; } template <typename IndexT> void IndexIDMap2Template<IndexT>::reconstruct (idx_t key, typename IndexT::component_t * recons) const { try { this->index->reconstruct (rev_map.at (key), recons); } catch (const std::out_of_range& e) { FAISS_THROW_FMT ("key %" PRId64 " not found", key); } } // explicit template instantiations template struct IndexIDMapTemplate<Index>; template struct IndexIDMapTemplate<IndexBinary>; template struct IndexIDMap2Template<Index>; template struct IndexIDMap2Template<IndexBinary>; /***************************************************** * IndexSplitVectors implementation *******************************************************/ IndexSplitVectors::IndexSplitVectors (idx_t d, bool threaded): Index (d), own_fields (false), threaded (threaded), sum_d (0) { } void IndexSplitVectors::add_sub_index (Index *index) { sub_indexes.push_back (index); sync_with_sub_indexes (); } void IndexSplitVectors::sync_with_sub_indexes () { if (sub_indexes.empty()) return; Index * index0 = sub_indexes[0]; sum_d = index0->d; metric_type = index0->metric_type; is_trained = index0->is_trained; ntotal = index0->ntotal; for (int i = 1; i < sub_indexes.size(); i++) { Index * index = sub_indexes[i]; FAISS_THROW_IF_NOT (metric_type == index->metric_type); FAISS_THROW_IF_NOT (ntotal == index->ntotal); sum_d += index->d; } } void IndexSplitVectors::add(idx_t /*n*/, const float* /*x*/) { FAISS_THROW_MSG("not implemented"); } void IndexSplitVectors::search ( idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const { FAISS_THROW_IF_NOT_MSG (k == 1, "search implemented only for k=1"); FAISS_THROW_IF_NOT_MSG (sum_d == d, "not enough indexes compared to # dimensions"); int64_t nshard = sub_indexes.size(); float *all_distances = new float [nshard * k * n]; idx_t *all_labels = new idx_t [nshard * k * n]; ScopeDeleter<float> del (all_distances); ScopeDeleter<idx_t> del2 (all_labels); auto query_func = [n, x, k, distances, labels, all_distances, all_labels, this] (int no) { const IndexSplitVectors *index = this; float *distances1 = no == 0 ? distances : all_distances + no * k * n; idx_t *labels1 = no == 0 ? labels : all_labels + no * k * n; if (index->verbose) printf ("begin query shard %d on %" PRId64 " points\n", no, n); const Index * sub_index = index->sub_indexes[no]; int64_t sub_d = sub_index->d, d = index->d; idx_t ofs = 0; for (int i = 0; i < no; i++) ofs += index->sub_indexes[i]->d; float *sub_x = new float [sub_d * n]; ScopeDeleter<float> del1 (sub_x); for (idx_t i = 0; i < n; i++) memcpy (sub_x + i * sub_d, x + ofs + i * d, sub_d * sizeof (sub_x)); sub_index->search (n, sub_x, k, distances1, labels1); if (index->verbose) printf ("end query shard %d\n", no); }; if (!threaded) { for (int i = 0; i < nshard; i++) { query_func(i); } } else { std::vector<std::unique_ptr<WorkerThread> > threads; std::vector<std::future<bool>> v; for (int i = 0; i < nshard; i++) { threads.emplace_back(new WorkerThread()); WorkerThread *wt = threads.back().get(); v.emplace_back(wt->add([i, query_func](){query_func(i); })); } // Blocking wait for completion for (auto& func : v) { func.get(); } } int64_t factor = 1; for (int i = 0; i < nshard; i++) { if (i > 0) { // results of 0 are already in the table const float *distances_i = all_distances + i * k * n; const idx_t *labels_i = all_labels + i * k * n; for (int64_t j = 0; j < n; j++) { if (labels[j] >= 0 && labels_i[j] >= 0) { labels[j] += labels_i[j] * factor; distances[j] += distances_i[j]; } else { labels[j] = -1; distances[j] = 0.0 / 0.0; } } } factor *= sub_indexes[i]->ntotal; } } void IndexSplitVectors::train(idx_t /*n*/, const float* /*x*/) { FAISS_THROW_MSG("not implemented"); } void IndexSplitVectors::reset () { FAISS_THROW_MSG ("not implemented"); } IndexSplitVectors::~IndexSplitVectors () { if (own_fields) { for (int s = 0; s < sub_indexes.size(); s++) delete sub_indexes [s]; } } } // namespace faiss
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // -*- c++ -*- #include <faiss/MetaIndexes.h> #include <cinttypes> #include <cstdio> #include <limits> #include <stdint.h> #include <faiss/impl/FaissAssert.h> #include <faiss/utils/Heap.h> #include <faiss/impl/AuxIndexStructures.h> #include <faiss/utils/WorkerThread.h> namespace faiss { namespace { } // namespace /***************************************************** * IndexIDMap implementation *******************************************************/ template <typename IndexT> IndexIDMapTemplate<IndexT>::IndexIDMapTemplate (IndexT *index): index (index), own_fields (false) { FAISS_THROW_IF_NOT_MSG (index->ntotal == 0, "index must be empty on input"); this->is_trained = index->is_trained; this->metric_type = index->metric_type; this->verbose = index->verbose; this->d = index->d; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::add (idx_t, const typename IndexT::component_t *) { FAISS_THROW_MSG ("add does not make sense with IndexIDMap, " "use add_with_ids"); } template <typename IndexT> void IndexIDMapTemplate<IndexT>::train (idx_t n, const typename IndexT::component_t *x) { index->train (n, x); this->is_trained = index->is_trained; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::reset () { index->reset (); id_map.clear(); this->ntotal = 0; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::add_with_ids (idx_t n, const typename IndexT::component_t * x, const typename IndexT::idx_t *xids) { index->add (n, x); for (idx_t i = 0; i < n; i++) id_map.push_back (xids[i]); this->ntotal = index->ntotal; } template <typename IndexT> void IndexIDMapTemplate<IndexT>::search (idx_t n, const typename IndexT::component_t *x, idx_t k, typename IndexT::distance_t *distances, typename IndexT::idx_t *labels) const { index->search (n, x, k, distances, labels); idx_t *li = labels; #pragma omp parallel for for (idx_t i = 0; i < n * k; i++) { li[i] = li[i] < 0 ? li[i] : id_map[li[i]]; } } template <typename IndexT> void IndexIDMapTemplate<IndexT>::range_search (typename IndexT::idx_t n, const typename IndexT::component_t *x, typename IndexT::distance_t radius, RangeSearchResult *result) const { index->range_search(n, x, radius, result); #pragma omp parallel for for (idx_t i = 0; i < result->lims[result->nq]; i++) { result->labels[i] = result->labels[i] < 0 ? result->labels[i] : id_map[result->labels[i]]; } } namespace { struct IDTranslatedSelector: IDSelector { const std::vector <int64_t> & id_map; const IDSelector & sel; IDTranslatedSelector (const std::vector <int64_t> & id_map, const IDSelector & sel): id_map (id_map), sel (sel) {} bool is_member(idx_t id) const override { return sel.is_member(id_map[id]); } }; } template <typename IndexT> size_t IndexIDMapTemplate<IndexT>::remove_ids (const IDSelector & sel) { // remove in sub-index first IDTranslatedSelector sel2 (id_map, sel); size_t nremove = index->remove_ids (sel2); int64_t j = 0; for (idx_t i = 0; i < this->ntotal; i++) { if (sel.is_member (id_map[i])) { // remove } else { id_map[j] = id_map[i]; j++; } } FAISS_ASSERT (j == index->ntotal); this->ntotal = j; id_map.resize(this->ntotal); return nremove; } template <typename IndexT> IndexIDMapTemplate<IndexT>::~IndexIDMapTemplate () { if (own_fields) delete index; } /***************************************************** * IndexIDMap2 implementation *******************************************************/ template <typename IndexT> IndexIDMap2Template<IndexT>::IndexIDMap2Template (IndexT *index): IndexIDMapTemplate<IndexT> (index) {} template <typename IndexT> void IndexIDMap2Template<IndexT>::add_with_ids (idx_t n, const typename IndexT::component_t* x, const typename IndexT::idx_t* xids) { size_t prev_ntotal = this->ntotal; IndexIDMapTemplate<IndexT>::add_with_ids (n, x, xids); for (size_t i = prev_ntotal; i < this->ntotal; i++) { rev_map [this->id_map [i]] = i; } } template <typename IndexT> void IndexIDMap2Template<IndexT>::construct_rev_map () { rev_map.clear (); for (size_t i = 0; i < this->ntotal; i++) { rev_map [this->id_map [i]] = i; } } template <typename IndexT> size_t IndexIDMap2Template<IndexT>::remove_ids(const IDSelector& sel) { // This is quite inefficient size_t nremove = IndexIDMapTemplate<IndexT>::remove_ids (sel); construct_rev_map (); return nremove; } template <typename IndexT> void IndexIDMap2Template<IndexT>::reconstruct (idx_t key, typename IndexT::component_t * recons) const { try { this->index->reconstruct (rev_map.at (key), recons); } catch (const std::out_of_range& e) { FAISS_THROW_FMT ("key %" PRId64 " not found", key); } } // explicit template instantiations template struct IndexIDMapTemplate<Index>; template struct IndexIDMapTemplate<IndexBinary>; template struct IndexIDMap2Template<Index>; template struct IndexIDMap2Template<IndexBinary>; /***************************************************** * IndexSplitVectors implementation *******************************************************/ IndexSplitVectors::IndexSplitVectors (idx_t d, bool threaded): Index (d), own_fields (false), threaded (threaded), sum_d (0) { } void IndexSplitVectors::add_sub_index (Index *index) { sub_indexes.push_back (index); sync_with_sub_indexes (); } void IndexSplitVectors::sync_with_sub_indexes () { if (sub_indexes.empty()) return; Index * index0 = sub_indexes[0]; sum_d = index0->d; metric_type = index0->metric_type; is_trained = index0->is_trained; ntotal = index0->ntotal; for (int i = 1; i < sub_indexes.size(); i++) { Index * index = sub_indexes[i]; FAISS_THROW_IF_NOT (metric_type == index->metric_type); FAISS_THROW_IF_NOT (ntotal == index->ntotal); sum_d += index->d; } } void IndexSplitVectors::add(idx_t /*n*/, const float* /*x*/) { FAISS_THROW_MSG("not implemented"); } void IndexSplitVectors::search ( idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const { FAISS_THROW_IF_NOT_MSG (k == 1, "search implemented only for k=1"); FAISS_THROW_IF_NOT_MSG (sum_d == d, "not enough indexes compared to # dimensions"); int64_t nshard = sub_indexes.size(); float *all_distances = new float [nshard * k * n]; idx_t *all_labels = new idx_t [nshard * k * n]; ScopeDeleter<float> del (all_distances); ScopeDeleter<idx_t> del2 (all_labels); auto query_func = [n, x, k, distances, labels, all_distances, all_labels, this] (int no) { const IndexSplitVectors *index = this; float *distances1 = no == 0 ? distances : all_distances + no * k * n; idx_t *labels1 = no == 0 ? labels : all_labels + no * k * n; if (index->verbose) printf ("begin query shard %d on %" PRId64 " points\n", no, n); const Index * sub_index = index->sub_indexes[no]; int64_t sub_d = sub_index->d, d = index->d; idx_t ofs = 0; for (int i = 0; i < no; i++) ofs += index->sub_indexes[i]->d; float *sub_x = new float [sub_d * n]; ScopeDeleter<float> del1 (sub_x); for (idx_t i = 0; i < n; i++) memcpy (sub_x + i * sub_d, x + ofs + i * d, sub_d * sizeof (sub_x)); sub_index->search (n, sub_x, k, distances1, labels1); if (index->verbose) printf ("end query shard %d\n", no); }; if (!threaded) { for (int i = 0; i < nshard; i++) { query_func(i); } } else { std::vector<std::unique_ptr<WorkerThread> > threads; std::vector<std::future<bool>> v; for (int i = 0; i < nshard; i++) { threads.emplace_back(new WorkerThread()); WorkerThread *wt = threads.back().get(); v.emplace_back(wt->add([i, query_func](){query_func(i); })); } // Blocking wait for completion for (auto& func : v) { func.get(); } } int64_t factor = 1; for (int i = 0; i < nshard; i++) { if (i > 0) { // results of 0 are already in the table const float *distances_i = all_distances + i * k * n; const idx_t *labels_i = all_labels + i * k * n; for (int64_t j = 0; j < n; j++) { if (labels[j] >= 0 && labels_i[j] >= 0) { labels[j] += labels_i[j] * factor; distances[j] += distances_i[j]; } else { labels[j] = -1; distances[j] = std::numeric_limits<float>::quiet_NaN(); } } } factor *= sub_indexes[i]->ntotal; } } void IndexSplitVectors::train(idx_t /*n*/, const float* /*x*/) { FAISS_THROW_MSG("not implemented"); } void IndexSplitVectors::reset () { FAISS_THROW_MSG ("not implemented"); } IndexSplitVectors::~IndexSplitVectors () { if (own_fields) { for (int s = 0; s < sub_indexes.size(); s++) delete sub_indexes [s]; } } } // namespace faiss
Fix division by zero. (#1339)
Fix division by zero. (#1339) Summary: Pull Request resolved: https://github.com/facebookresearch/faiss/pull/1339 Test Plan: Imported from OSS Reviewed By: mdouze Differential Revision: D23234966 Pulled By: beauby fbshipit-source-id: 43142bbf2e30ce69dd15dfc1818d3e3079c7ec48
C++
mit
facebookresearch/faiss,facebookresearch/faiss,facebookresearch/faiss,facebookresearch/faiss
78a565b6c4498da241dfe3991e63024e1f66330c
MQWeb/src/StaticRequestHandler.cpp
MQWeb/src/StaticRequestHandler.cpp
/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include <MQ/Web/StaticRequestHandler.h> #include <Poco/Net/HTTPRequestHandlerFactory.h> #include <Poco/Net/HTTPServerRequest.h> #include <Poco/Net/HTTPServerResponse.h> #include <Poco/DateTimeFormat.h> #include <Poco/DateTimeParser.h> #include <Poco/Util/Application.h> #include <Poco/URI.h> #include <Poco/Path.h> #include <Poco/File.h> namespace MQ { namespace Web { StaticRequestHandler::StaticRequestHandler() { } void StaticRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { std::string lastModifiedHeader = request.get("If-Modified-Since", ""); Poco::URI uri(request.getURI()); Poco::Util::Application& app = Poco::Util::Application::instance(); std::string staticPathname = app.config().getString("mq.web.static", ""); if ( staticPathname.empty() ) { staticPathname = app.config().getString("application.dir"); } if ( ! staticPathname.empty() ) { Poco::Path staticPath(staticPathname); staticPath.makeDirectory(); std::vector<std::string> uriPathSegments; uri.getPathSegments(uriPathSegments); std::vector<std::string>::iterator it = uriPathSegments.begin(); it++; for(; it != uriPathSegments.end(); ++it) { staticPath.append(*it); } Poco::File staticFile(staticPath); Poco::Logger& logger = Poco::Logger::get("mq.web.access"); if ( staticFile.exists() ) { if ( !lastModifiedHeader.empty() ) { Poco::DateTime lastModifiedDate; int timeZoneDifferential = 0; if ( Poco::DateTimeParser::tryParse(Poco::DateTimeFormat::HTTP_FORMAT, lastModifiedHeader, lastModifiedDate, timeZoneDifferential) ) { if ( staticFile.getLastModified() <= lastModifiedDate.timestamp() ) { logger.information(Poco::Logger::format("$0 : HTTP_NOT_MODIFIED", staticPath.toString())); response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED); response.send(); return; } } } logger.information(Poco::Logger::format("$0 : HTTP_OK", staticPath.toString())); std::string mimeType; if ( staticPath.getExtension().compare("gif") == 0 ) { mimeType = "image/gif"; } else if ( staticPath.getExtension().compare("css") == 0 ) { mimeType = "text/css"; } else if ( staticPath.getExtension().compare("html") == 0 || staticPath.getExtension().compare("htm") == 0) { mimeType = "text/html"; } else if ( staticPath.getExtension().compare("js") == 0 ) { mimeType = "text/plain"; } else if ( staticPath.getExtension().compare("png") == 0 ) { mimeType = "image/png"; } else if ( staticPath.getExtension().compare("jpg") == 0 || staticPath.getExtension().compare("jpeg") == 0) { mimeType = "image/jpeg"; } response.sendFile(staticPath.toString(), mimeType); response.setStatus(Poco::Net::HTTPResponse::HTTP_OK); return; } else { logger.error(Poco::Logger::format("$0 : HTTP_NOT_FOUND", staticFile.path())); } } response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND); response.send(); } } } // Namespace MQ::Web
/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include <MQ/Web/StaticRequestHandler.h> #include <Poco/Net/HTTPRequestHandlerFactory.h> #include <Poco/Net/HTTPServerRequest.h> #include <Poco/Net/HTTPServerResponse.h> #include <Poco/DateTimeFormat.h> #include <Poco/DateTimeParser.h> #include <Poco/Util/Application.h> #include <Poco/URI.h> #include <Poco/Path.h> #include <Poco/File.h> namespace MQ { namespace Web { StaticRequestHandler::StaticRequestHandler() { } void StaticRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { // Check for the favicon.ico request, we don't have one for now, // so set status code to HTTP_NOT_FOUND if ( request.getURI().compare("/favicon.ico") == 0 ) { response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND); response.send(); return; } std::string lastModifiedHeader = request.get("If-Modified-Since", ""); Poco::URI uri(request.getURI()); Poco::Util::Application& app = Poco::Util::Application::instance(); std::string staticPathname = app.config().getString("mq.web.static", ""); if ( staticPathname.empty() ) { staticPathname = app.config().getString("application.dir"); } if ( ! staticPathname.empty() ) { Poco::Path staticPath(staticPathname); staticPath.makeDirectory(); std::vector<std::string> uriPathSegments; uri.getPathSegments(uriPathSegments); std::vector<std::string>::iterator it = uriPathSegments.begin(); it++; for(; it != uriPathSegments.end(); ++it) { staticPath.append(*it); } Poco::File staticFile(staticPath); Poco::Logger& logger = Poco::Logger::get("mq.web.access"); if ( staticFile.exists() ) { if ( !lastModifiedHeader.empty() ) { Poco::DateTime lastModifiedDate; int timeZoneDifferential = 0; if ( Poco::DateTimeParser::tryParse(Poco::DateTimeFormat::HTTP_FORMAT, lastModifiedHeader, lastModifiedDate, timeZoneDifferential) ) { if ( staticFile.getLastModified() <= lastModifiedDate.timestamp() ) { logger.information(Poco::Logger::format("$0 : HTTP_NOT_MODIFIED", staticPath.toString())); response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED); response.send(); return; } } } logger.information(Poco::Logger::format("$0 : HTTP_OK", staticPath.toString())); std::string mimeType; if ( staticPath.getExtension().compare("gif") == 0 ) { mimeType = "image/gif"; } else if ( staticPath.getExtension().compare("css") == 0 ) { mimeType = "text/css"; } else if ( staticPath.getExtension().compare("html") == 0 || staticPath.getExtension().compare("htm") == 0) { mimeType = "text/html"; } else if ( staticPath.getExtension().compare("js") == 0 ) { mimeType = "text/plain"; } else if ( staticPath.getExtension().compare("png") == 0 ) { mimeType = "image/png"; } else if ( staticPath.getExtension().compare("jpg") == 0 || staticPath.getExtension().compare("jpeg") == 0) { mimeType = "image/jpeg"; } response.sendFile(staticPath.toString(), mimeType); response.setStatus(Poco::Net::HTTPResponse::HTTP_OK); return; } else { logger.error(Poco::Logger::format("$0 : HTTP_NOT_FOUND", staticFile.path())); } } response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND); response.send(); } } } // Namespace MQ::Web
Return HTTP_NOT_FOUND for favicon.ico
Return HTTP_NOT_FOUND for favicon.ico
C++
mit
fbraem/mqweb,fbraem/mqweb,fbraem/mqweb
aba9a594b6d2b79058110b68714faf997f4a5e74
OSVRUpdateCallback.cpp
OSVRUpdateCallback.cpp
/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, 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. // Internal Includes #include "OSVRUpdateCallback.h" #include "OSVRContext.h" // Library/third-party includes #include <osg/Node> #include <boost/assert.hpp> // Standard includes // - none OSVRUpdateCallback::OSVRUpdateCallback() {} void OSVRUpdateCallback::operator()(osg::Node *node, osg::NodeVisitor *nv) { OSVRContext *ctx = dynamic_cast<OSVRContext *>(node->getUserData()); BOOST_ASSERT(ctx); ctx->update(); // continue traversal traverse(node, nv); } OSVRUpdateCallback::~OSVRUpdateCallback() {}
/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, 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. // Internal Includes #include "OSVRUpdateCallback.h" #include "OSVRContext.h" // Library/third-party includes #include <osg/Node> #include <osg/NodeVisitor> #include <boost/assert.hpp> // Standard includes // - none OSVRUpdateCallback::OSVRUpdateCallback() {} void OSVRUpdateCallback::operator()(osg::Node *node, osg::NodeVisitor *nv) { OSVRContext *ctx = dynamic_cast<OSVRContext *>(node->getUserData()); BOOST_ASSERT(ctx); ctx->update(); // continue traversal traverse(node, nv); } OSVRUpdateCallback::~OSVRUpdateCallback() {}
Add missing include
Add missing include
C++
apache-2.0
OSVR/OSVR-Tracker-Viewer
2830825c563ef1f5315030fb7988665679095d15
src/buffer_iterator.inl.hh
src/buffer_iterator.inl.hh
#ifndef buffer_iterator_inl_h_INCLUDED #define buffer_iterator_inl_h_INCLUDED #include "assert.hh" namespace Kakoune { inline BufferIterator::BufferIterator(const Buffer& buffer, BufferCoord coord) : m_buffer(&buffer), m_coord(coord) { assert(is_valid()); } inline const Buffer& BufferIterator::buffer() const { assert(m_buffer); return *m_buffer; } inline bool BufferIterator::is_valid() const { return m_buffer and ((line() < m_buffer->line_count() and column() < m_buffer->m_lines[line()].length()) or ((line() == m_buffer->line_count() and column() == 0)) or (line() == m_buffer->line_count() - 1 and column() == m_buffer->m_lines.back().length())); } inline BufferIterator& BufferIterator::operator=(const BufferIterator& iterator) { m_buffer = iterator.m_buffer; m_coord = iterator.m_coord; assert(is_valid()); return *this; } inline bool BufferIterator::operator==(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord == iterator.m_coord); } inline bool BufferIterator::operator!=(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord != iterator.m_coord); } inline bool BufferIterator::operator<(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord < iterator.m_coord); } inline bool BufferIterator::operator<=(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord <= iterator.m_coord); } inline bool BufferIterator::operator>(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord > iterator.m_coord); } inline bool BufferIterator::operator>=(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord >= iterator.m_coord); } inline void BufferIterator::on_insert(const BufferCoord& begin, const BufferCoord& end) { if (m_coord < begin) return; if (begin.line == line()) m_coord.column = end.column + m_coord.column - begin.column; m_coord.line += end.line - begin.line; assert(is_valid()); } inline void BufferIterator::on_erase(const BufferCoord& begin, const BufferCoord& end) { if (m_coord < begin) return; if (m_coord <= end) m_coord = begin; else { if (end.line == m_coord.line) { m_coord.line = begin.line; m_coord.column = begin.column + m_coord.column - end.column; } else m_coord.line -= end.line - begin.line; } if (is_end()) operator--(); assert(is_valid()); } inline Character BufferIterator::operator*() const { assert(m_buffer); return m_buffer->m_lines[line()].content[column()]; } inline BufferSize BufferIterator::offset() const { assert(m_buffer); return line() == 0 ? column() : m_buffer->m_lines[line()].start + column(); } inline BufferSize BufferIterator::operator-(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return offset() - iterator.offset(); } inline BufferIterator BufferIterator::operator+(BufferSize size) const { assert(m_buffer); if (size >= 0) { BufferSize o = std::min(m_buffer->character_count(), offset() + size); for (int i = line() + 1; i < m_buffer->line_count(); ++i) { if (m_buffer->m_lines[i].start > o) return BufferIterator(*m_buffer, { i-1, o - m_buffer->m_lines[i-1].start }); } int last_line = m_buffer->line_count() - 1; return BufferIterator(*m_buffer, { last_line, o - m_buffer->m_lines[last_line].start }); } return operator-(-size); } inline BufferIterator BufferIterator::operator-(BufferSize size) const { assert(m_buffer); if (size >= 0) { BufferSize o = std::max(0, offset() - size); for (int i = line(); i >= 0; --i) { if (m_buffer->m_lines[i].start <= o) return BufferIterator(*m_buffer, { i, o - m_buffer->m_lines[i].start }); } assert(false); } return operator+(-size); } inline BufferIterator& BufferIterator::operator+=(BufferSize size) { return *this = (*this + size); } inline BufferIterator& BufferIterator::operator-=(BufferSize size) { return *this = (*this - size); } inline BufferIterator& BufferIterator::operator++() { if (column() < m_buffer->m_lines[line()].length() - 1) ++m_coord.column; else if (line() == m_buffer->line_count() - 1) m_coord.column = m_buffer->m_lines.back().length(); else { ++m_coord.line; m_coord.column = 0; } return *this; } inline BufferIterator& BufferIterator::operator--() { if (column() == 0) { if (line() > 0) { --m_coord.line; m_coord.column = m_buffer->m_lines[m_coord.line].length() - 1; } } else --m_coord.column; return *this; } inline bool BufferIterator::is_begin() const { assert(m_buffer); return m_coord.line == 0 and m_coord.column == 0; } inline bool BufferIterator::is_end() const { assert(m_buffer); return offset() == m_buffer->character_count(); } } #endif // buffer_iterator_inl_h_INCLUDED
#ifndef buffer_iterator_inl_h_INCLUDED #define buffer_iterator_inl_h_INCLUDED #include "assert.hh" namespace Kakoune { inline BufferIterator::BufferIterator(const Buffer& buffer, BufferCoord coord) : m_buffer(&buffer), m_coord(coord) { assert(is_valid()); } inline const Buffer& BufferIterator::buffer() const { assert(m_buffer); return *m_buffer; } inline bool BufferIterator::is_valid() const { return m_buffer and ((line() < m_buffer->line_count() and column() < m_buffer->m_lines[line()].length()) or ((line() == m_buffer->line_count() and column() == 0)) or (line() == m_buffer->line_count() - 1 and column() == m_buffer->m_lines.back().length())); } inline BufferIterator& BufferIterator::operator=(const BufferIterator& iterator) { m_buffer = iterator.m_buffer; m_coord = iterator.m_coord; return *this; } inline bool BufferIterator::operator==(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord == iterator.m_coord); } inline bool BufferIterator::operator!=(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord != iterator.m_coord); } inline bool BufferIterator::operator<(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord < iterator.m_coord); } inline bool BufferIterator::operator<=(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord <= iterator.m_coord); } inline bool BufferIterator::operator>(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord > iterator.m_coord); } inline bool BufferIterator::operator>=(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return (m_coord >= iterator.m_coord); } inline void BufferIterator::on_insert(const BufferCoord& begin, const BufferCoord& end) { if (m_coord < begin) return; if (begin.line == line()) m_coord.column = end.column + m_coord.column - begin.column; m_coord.line += end.line - begin.line; assert(is_valid()); } inline void BufferIterator::on_erase(const BufferCoord& begin, const BufferCoord& end) { if (m_coord < begin) return; if (m_coord <= end) m_coord = begin; else { if (end.line == m_coord.line) { m_coord.line = begin.line; m_coord.column = begin.column + m_coord.column - end.column; } else m_coord.line -= end.line - begin.line; } if (is_end()) operator--(); assert(is_valid()); } inline Character BufferIterator::operator*() const { assert(m_buffer); return m_buffer->m_lines[line()].content[column()]; } inline BufferSize BufferIterator::offset() const { assert(m_buffer); return line() == 0 ? column() : m_buffer->m_lines[line()].start + column(); } inline BufferSize BufferIterator::operator-(const BufferIterator& iterator) const { assert(m_buffer == iterator.m_buffer); return offset() - iterator.offset(); } inline BufferIterator BufferIterator::operator+(BufferSize size) const { assert(m_buffer); if (size >= 0) { BufferSize o = std::min(m_buffer->character_count(), offset() + size); for (int i = line() + 1; i < m_buffer->line_count(); ++i) { if (m_buffer->m_lines[i].start > o) return BufferIterator(*m_buffer, { i-1, o - m_buffer->m_lines[i-1].start }); } int last_line = m_buffer->line_count() - 1; return BufferIterator(*m_buffer, { last_line, o - m_buffer->m_lines[last_line].start }); } return operator-(-size); } inline BufferIterator BufferIterator::operator-(BufferSize size) const { assert(m_buffer); if (size >= 0) { BufferSize o = std::max(0, offset() - size); for (int i = line(); i >= 0; --i) { if (m_buffer->m_lines[i].start <= o) return BufferIterator(*m_buffer, { i, o - m_buffer->m_lines[i].start }); } assert(false); } return operator+(-size); } inline BufferIterator& BufferIterator::operator+=(BufferSize size) { return *this = (*this + size); } inline BufferIterator& BufferIterator::operator-=(BufferSize size) { return *this = (*this - size); } inline BufferIterator& BufferIterator::operator++() { if (column() < m_buffer->m_lines[line()].length() - 1) ++m_coord.column; else if (line() == m_buffer->line_count() - 1) m_coord.column = m_buffer->m_lines.back().length(); else { ++m_coord.line; m_coord.column = 0; } return *this; } inline BufferIterator& BufferIterator::operator--() { if (column() == 0) { if (line() > 0) { --m_coord.line; m_coord.column = m_buffer->m_lines[m_coord.line].length() - 1; } } else --m_coord.column; return *this; } inline bool BufferIterator::is_begin() const { assert(m_buffer); return m_coord.line == 0 and m_coord.column == 0; } inline bool BufferIterator::is_end() const { assert(m_buffer); return offset() == m_buffer->character_count(); } } #endif // buffer_iterator_inl_h_INCLUDED
allow invalid iterator in operator=
BufferIterator: allow invalid iterator in operator=
C++
unlicense
rstacruz/kakoune,jjthrash/kakoune,occivink/kakoune,xificurC/kakoune,danielma/kakoune,elegios/kakoune,jkonecny12/kakoune,casimir/kakoune,alexherbo2/kakoune,Asenar/kakoune,Asenar/kakoune,jkonecny12/kakoune,ekie/kakoune,jjthrash/kakoune,zakgreant/kakoune,danielma/kakoune,danielma/kakoune,xificurC/kakoune,xificurC/kakoune,lenormf/kakoune,Somasis/kakoune,rstacruz/kakoune,casimir/kakoune,alpha123/kakoune,Somasis/kakoune,flavius/kakoune,Asenar/kakoune,elegios/kakoune,jkonecny12/kakoune,Somasis/kakoune,danielma/kakoune,danr/kakoune,occivink/kakoune,alpha123/kakoune,mawww/kakoune,ekie/kakoune,occivink/kakoune,alexherbo2/kakoune,rstacruz/kakoune,flavius/kakoune,jjthrash/kakoune,mawww/kakoune,zakgreant/kakoune,casimir/kakoune,flavius/kakoune,danr/kakoune,zakgreant/kakoune,lenormf/kakoune,alexherbo2/kakoune,lenormf/kakoune,elegios/kakoune,rstacruz/kakoune,jjthrash/kakoune,Somasis/kakoune,alpha123/kakoune,zakgreant/kakoune,flavius/kakoune,Asenar/kakoune,lenormf/kakoune,casimir/kakoune,ekie/kakoune,danr/kakoune,alexherbo2/kakoune,danr/kakoune,occivink/kakoune,jkonecny12/kakoune,xificurC/kakoune,mawww/kakoune,mawww/kakoune,ekie/kakoune,elegios/kakoune,alpha123/kakoune
05edabff5e8a09ebace6446d370fa3eb6fbda431
stdlib/public/stubs/UnicodeNormalization.cpp
stdlib/public/stubs/UnicodeNormalization.cpp
//===--- UnicodeNormalization.cpp - Unicode Normalization Helpers ---------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Functions that use ICU to do unicode normalization and collation. // //===----------------------------------------------------------------------===// #include "../SwiftShims/UnicodeShims.h" #include <stdint.h> #if defined(__APPLE__) // Declare a few external functions to avoid a dependency on ICU headers. extern "C" { typedef struct UBreakIterator UBreakIterator; typedef enum UBreakIteratorType {} UBreakIteratorType; typedef enum UErrorCode {} UErrorCode; typedef uint16_t UChar; void ubrk_close(UBreakIterator *); UBreakIterator *ubrk_open(UBreakIteratorType, const char *, const UChar *, int32_t, UErrorCode *); int32_t ubrk_preceding(UBreakIterator *, int32_t); int32_t ubrk_following(UBreakIterator *, int32_t); void ubrk_setText(UBreakIterator *, const UChar *, int32_t, UErrorCode *); } #else #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #include <unicode/ustring.h> #include <unicode/ucol.h> #include <unicode/ucoleitr.h> #include <unicode/uiter.h> #include <unicode/ubrk.h> #pragma clang diagnostic pop #endif #if !defined(__APPLE__) #include "swift/Basic/Lazy.h" #include "swift/Runtime/Config.h" #include "swift/Runtime/Debug.h" #include <algorithm> #include <mutex> #include <assert.h> static const UCollator *MakeRootCollator() { UErrorCode ErrorCode = U_ZERO_ERROR; UCollator *root = ucol_open("", &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_open: Failure setting up default collation."); } ucol_setAttribute(root, UCOL_NORMALIZATION_MODE, UCOL_ON, &ErrorCode); ucol_setAttribute(root, UCOL_STRENGTH, UCOL_TERTIARY, &ErrorCode); ucol_setAttribute(root, UCOL_NUMERIC_COLLATION, UCOL_OFF, &ErrorCode); ucol_setAttribute(root, UCOL_CASE_LEVEL, UCOL_OFF, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_setAttribute: Failure setting up default collation."); } return root; } // According to this thread in the ICU mailing list, it should be safe // to assume the UCollator object is thread safe so long as you're only // passing it to functions that take a const pointer to it. So, we make it // const here to make sure we don't misuse it. // http://sourceforge.net/p/icu/mailman/message/27427062/ static const UCollator *GetRootCollator() { return SWIFT_LAZY_CONSTANT(MakeRootCollator()); } /// This class caches the collation element results for the ASCII subset of /// unicode. class ASCIICollation { public: friend class swift::Lazy<ASCIICollation>; static swift::Lazy<ASCIICollation> theTable; static const ASCIICollation *getTable() { return &theTable.get(); } int32_t CollationTable[128]; /// Maps an ASCII character to a collation element priority as would be /// returned by a call to ucol_next(). int32_t map(unsigned char c) const { return CollationTable[c]; } private: /// Construct the ASCII collation table. ASCIICollation() { const UCollator *Collator = GetRootCollator(); for (unsigned char c = 0; c < 128; ++c) { UErrorCode ErrorCode = U_ZERO_ERROR; intptr_t NumCollationElts = 0; UChar Buffer[1]; Buffer[0] = c; UCollationElements *CollationIterator = ucol_openElements(Collator, Buffer, 1, &ErrorCode); while (U_SUCCESS(ErrorCode)) { intptr_t Elem = ucol_next(CollationIterator, &ErrorCode); if (Elem != UCOL_NULLORDER) { CollationTable[c] = Elem; ++NumCollationElts; } else { break; } } ucol_closeElements(CollationIterator); if (U_FAILURE(ErrorCode) || NumCollationElts != 1) { swift::crash("Error setting up the ASCII collation table"); } } } ASCIICollation &operator=(const ASCIICollation &) = delete; ASCIICollation(const ASCIICollation &) = delete; }; /// Compares the strings via the Unicode Collation Algorithm on the root locale. /// Results are the usual string comparison results: /// <0 the left string is less than the right string. /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t swift::_swift_stdlib_unicode_compare_utf16_utf16(const uint16_t *LeftString, int32_t LeftLength, const uint16_t *RightString, int32_t RightLength) { // ICU UChar type is platform dependent. In Cygwin, it is defined // as wchar_t which size is 2. It seems that the underlying binary // representation is same with swift utf16 representation. // On Clang 4.0 under a recent Linux, ICU uses the built-in char16_t type. return ucol_strcoll(GetRootCollator(), reinterpret_cast<const UChar *>(LeftString), LeftLength, reinterpret_cast<const UChar *>(RightString), RightLength); } /// Compares the strings via the Unicode Collation Algorithm on the root locale. /// Results are the usual string comparison results: /// <0 the left string is less than the right string. /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t swift::_swift_stdlib_unicode_compare_utf8_utf16(const unsigned char *LeftString, int32_t LeftLength, const uint16_t *RightString, int32_t RightLength) { UCharIterator LeftIterator; UCharIterator RightIterator; UErrorCode ErrorCode = U_ZERO_ERROR; uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength); uiter_setString(&RightIterator, reinterpret_cast<const UChar *>(RightString), RightLength); uint32_t Diff = ucol_strcollIter(GetRootCollator(), &LeftIterator, &RightIterator, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf16 string comparison."); } return Diff; } /// Compares the strings via the Unicode Collation Algorithm on the root locale. /// Results are the usual string comparison results: /// <0 the left string is less than the right string. /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t swift::_swift_stdlib_unicode_compare_utf8_utf8(const unsigned char *LeftString, int32_t LeftLength, const unsigned char *RightString, int32_t RightLength) { UCharIterator LeftIterator; UCharIterator RightIterator; UErrorCode ErrorCode = U_ZERO_ERROR; uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength); uiter_setUTF8(&RightIterator, reinterpret_cast<const char *>(RightString), RightLength); uint32_t Diff = ucol_strcollIter(GetRootCollator(), &LeftIterator, &RightIterator, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf8 string comparison."); } return Diff; } void *swift::_swift_stdlib_unicodeCollationIterator_create( const __swift_uint16_t *Str, __swift_uint32_t Length) { UErrorCode ErrorCode = U_ZERO_ERROR; UCollationElements *CollationIterator = ucol_openElements(GetRootCollator(), reinterpret_cast<const UChar *>(Str), Length, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("_swift_stdlib_unicodeCollationIterator_create: ucol_openElements() failed."); } return CollationIterator; } __swift_int32_t swift::_swift_stdlib_unicodeCollationIterator_next( void *CollationIterator, bool *HitEnd) { UErrorCode ErrorCode = U_ZERO_ERROR; auto Result = ucol_next( static_cast<UCollationElements *>(CollationIterator), &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("_swift_stdlib_unicodeCollationIterator_next: ucol_next() failed."); } *HitEnd = (Result == UCOL_NULLORDER); return Result; } void swift::_swift_stdlib_unicodeCollationIterator_delete( void *CollationIterator) { ucol_closeElements(static_cast<UCollationElements *>(CollationIterator)); } const __swift_int32_t *swift::_swift_stdlib_unicode_getASCIICollationTable() { return ASCIICollation::getTable()->CollationTable; } /// Convert the unicode string to uppercase. This function will return the /// required buffer length as a result. If this length does not match the /// 'DestinationCapacity' this function must be called again with a buffer of /// the required length to get an uppercase version of the string. int32_t swift::_swift_stdlib_unicode_strToUpper(uint16_t *Destination, int32_t DestinationCapacity, const uint16_t *Source, int32_t SourceLength) { UErrorCode ErrorCode = U_ZERO_ERROR; uint32_t OutputLength = u_strToUpper(reinterpret_cast<UChar *>(Destination), DestinationCapacity, reinterpret_cast<const UChar *>(Source), SourceLength, "", &ErrorCode); if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) { swift::crash("u_strToUpper: Unexpected error uppercasing unicode string."); } return OutputLength; } /// Convert the unicode string to lowercase. This function will return the /// required buffer length as a result. If this length does not match the /// 'DestinationCapacity' this function must be called again with a buffer of /// the required length to get a lowercase version of the string. int32_t swift::_swift_stdlib_unicode_strToLower(uint16_t *Destination, int32_t DestinationCapacity, const uint16_t *Source, int32_t SourceLength) { UErrorCode ErrorCode = U_ZERO_ERROR; uint32_t OutputLength = u_strToLower(reinterpret_cast<UChar *>(Destination), DestinationCapacity, reinterpret_cast<const UChar *>(Source), SourceLength, "", &ErrorCode); if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) { swift::crash("u_strToLower: Unexpected error lowercasing unicode string."); } return OutputLength; } swift::Lazy<ASCIICollation> ASCIICollation::theTable; #endif namespace { template <typename T, typename U> T *ptr_cast(U *p) { return static_cast<T *>(static_cast<void *>(p)); } template <typename T, typename U> const T *ptr_cast(const U *p) { return static_cast<const T *>(static_cast<const void *>(p)); } } void swift::__swift_stdlib_ubrk_close( swift::__swift_stdlib_UBreakIterator *bi) { ubrk_close(ptr_cast<UBreakIterator>(bi)); } swift::__swift_stdlib_UBreakIterator *swift::__swift_stdlib_ubrk_open( swift::__swift_stdlib_UBreakIteratorType type, const char *locale, const uint16_t *text, int32_t textLength, __swift_stdlib_UErrorCode *status) { return ptr_cast<swift::__swift_stdlib_UBreakIterator>( ubrk_open(static_cast<UBreakIteratorType>(type), locale, reinterpret_cast<const UChar *>(text), textLength, ptr_cast<UErrorCode>(status))); } int32_t swift::__swift_stdlib_ubrk_preceding(swift::__swift_stdlib_UBreakIterator *bi, int32_t offset) { return ubrk_preceding(ptr_cast<UBreakIterator>(bi), offset); } int32_t swift::__swift_stdlib_ubrk_following(swift::__swift_stdlib_UBreakIterator *bi, int32_t offset) { return ubrk_following(ptr_cast<UBreakIterator>(bi), offset); } void swift::__swift_stdlib_ubrk_setText( swift::__swift_stdlib_UBreakIterator *bi, const __swift_stdlib_UChar *text, __swift_int32_t textLength, __swift_stdlib_UErrorCode *status) { return ubrk_setText(ptr_cast<UBreakIterator>(bi), ptr_cast<UChar>(text), textLength, ptr_cast<UErrorCode>(status)); } // Force an autolink with ICU #if defined(__MACH__) asm(".linker_option \"-licucore\"\n"); #elif defined(_WIN32) #pragma comment(lib, "icucore.lib") #endif // defined(__MACH__)
//===--- UnicodeNormalization.cpp - Unicode Normalization Helpers ---------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Functions that use ICU to do unicode normalization and collation. // //===----------------------------------------------------------------------===// #include "../SwiftShims/UnicodeShims.h" #include <stdint.h> #if defined(__APPLE__) // Declare a few external functions to avoid a dependency on ICU headers. extern "C" { typedef struct UBreakIterator UBreakIterator; typedef enum UBreakIteratorType {} UBreakIteratorType; typedef enum UErrorCode {} UErrorCode; typedef uint16_t UChar; void ubrk_close(UBreakIterator *); UBreakIterator *ubrk_open(UBreakIteratorType, const char *, const UChar *, int32_t, UErrorCode *); int32_t ubrk_preceding(UBreakIterator *, int32_t); int32_t ubrk_following(UBreakIterator *, int32_t); void ubrk_setText(UBreakIterator *, const UChar *, int32_t, UErrorCode *); } #else #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #include <unicode/ustring.h> #include <unicode/ucol.h> #include <unicode/ucoleitr.h> #include <unicode/uiter.h> #include <unicode/ubrk.h> #pragma clang diagnostic pop #endif #if !defined(__APPLE__) #include "swift/Basic/Lazy.h" #include "swift/Runtime/Config.h" #include "swift/Runtime/Debug.h" #include <algorithm> #include <mutex> #include <assert.h> static const UCollator *MakeRootCollator() { UErrorCode ErrorCode = U_ZERO_ERROR; UCollator *root = ucol_open("", &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_open: Failure setting up default collation."); } ucol_setAttribute(root, UCOL_NORMALIZATION_MODE, UCOL_ON, &ErrorCode); ucol_setAttribute(root, UCOL_STRENGTH, UCOL_TERTIARY, &ErrorCode); ucol_setAttribute(root, UCOL_NUMERIC_COLLATION, UCOL_OFF, &ErrorCode); ucol_setAttribute(root, UCOL_CASE_LEVEL, UCOL_OFF, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_setAttribute: Failure setting up default collation."); } return root; } // According to this thread in the ICU mailing list, it should be safe // to assume the UCollator object is thread safe so long as you're only // passing it to functions that take a const pointer to it. So, we make it // const here to make sure we don't misuse it. // http://sourceforge.net/p/icu/mailman/message/27427062/ static const UCollator *GetRootCollator() { return SWIFT_LAZY_CONSTANT(MakeRootCollator()); } /// This class caches the collation element results for the ASCII subset of /// unicode. class ASCIICollation { public: friend class swift::Lazy<ASCIICollation>; static swift::Lazy<ASCIICollation> theTable; static const ASCIICollation *getTable() { return &theTable.get(); } int32_t CollationTable[128]; /// Maps an ASCII character to a collation element priority as would be /// returned by a call to ucol_next(). int32_t map(unsigned char c) const { return CollationTable[c]; } private: /// Construct the ASCII collation table. ASCIICollation() { const UCollator *Collator = GetRootCollator(); for (unsigned char c = 0; c < 128; ++c) { UErrorCode ErrorCode = U_ZERO_ERROR; intptr_t NumCollationElts = 0; UChar Buffer[1]; Buffer[0] = c; UCollationElements *CollationIterator = ucol_openElements(Collator, Buffer, 1, &ErrorCode); while (U_SUCCESS(ErrorCode)) { intptr_t Elem = ucol_next(CollationIterator, &ErrorCode); if (Elem != UCOL_NULLORDER) { CollationTable[c] = Elem; ++NumCollationElts; } else { break; } } ucol_closeElements(CollationIterator); if (U_FAILURE(ErrorCode) || NumCollationElts != 1) { swift::crash("Error setting up the ASCII collation table"); } } } ASCIICollation &operator=(const ASCIICollation &) = delete; ASCIICollation(const ASCIICollation &) = delete; }; /// Compares the strings via the Unicode Collation Algorithm on the root locale. /// Results are the usual string comparison results: /// <0 the left string is less than the right string. /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t swift::_swift_stdlib_unicode_compare_utf16_utf16(const uint16_t *LeftString, int32_t LeftLength, const uint16_t *RightString, int32_t RightLength) { // ICU UChar type is platform dependent. In Cygwin, it is defined // as wchar_t which size is 2. It seems that the underlying binary // representation is same with swift utf16 representation. // On Clang 4.0 under a recent Linux, ICU uses the built-in char16_t type. return ucol_strcoll(GetRootCollator(), reinterpret_cast<const UChar *>(LeftString), LeftLength, reinterpret_cast<const UChar *>(RightString), RightLength); } /// Compares the strings via the Unicode Collation Algorithm on the root locale. /// Results are the usual string comparison results: /// <0 the left string is less than the right string. /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t swift::_swift_stdlib_unicode_compare_utf8_utf16(const unsigned char *LeftString, int32_t LeftLength, const uint16_t *RightString, int32_t RightLength) { UCharIterator LeftIterator; UCharIterator RightIterator; UErrorCode ErrorCode = U_ZERO_ERROR; uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength); uiter_setString(&RightIterator, reinterpret_cast<const UChar *>(RightString), RightLength); uint32_t Diff = ucol_strcollIter(GetRootCollator(), &LeftIterator, &RightIterator, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf16 string comparison."); } return Diff; } /// Compares the strings via the Unicode Collation Algorithm on the root locale. /// Results are the usual string comparison results: /// <0 the left string is less than the right string. /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t swift::_swift_stdlib_unicode_compare_utf8_utf8(const unsigned char *LeftString, int32_t LeftLength, const unsigned char *RightString, int32_t RightLength) { UCharIterator LeftIterator; UCharIterator RightIterator; UErrorCode ErrorCode = U_ZERO_ERROR; uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength); uiter_setUTF8(&RightIterator, reinterpret_cast<const char *>(RightString), RightLength); uint32_t Diff = ucol_strcollIter(GetRootCollator(), &LeftIterator, &RightIterator, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf8 string comparison."); } return Diff; } void *swift::_swift_stdlib_unicodeCollationIterator_create( const __swift_uint16_t *Str, __swift_uint32_t Length) { UErrorCode ErrorCode = U_ZERO_ERROR; UCollationElements *CollationIterator = ucol_openElements(GetRootCollator(), reinterpret_cast<const UChar *>(Str), Length, &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("_swift_stdlib_unicodeCollationIterator_create: ucol_openElements() failed."); } return CollationIterator; } __swift_int32_t swift::_swift_stdlib_unicodeCollationIterator_next( void *CollationIterator, bool *HitEnd) { UErrorCode ErrorCode = U_ZERO_ERROR; auto Result = ucol_next( static_cast<UCollationElements *>(CollationIterator), &ErrorCode); if (U_FAILURE(ErrorCode)) { swift::crash("_swift_stdlib_unicodeCollationIterator_next: ucol_next() failed."); } *HitEnd = (Result == UCOL_NULLORDER); return Result; } void swift::_swift_stdlib_unicodeCollationIterator_delete( void *CollationIterator) { ucol_closeElements(static_cast<UCollationElements *>(CollationIterator)); } const __swift_int32_t *swift::_swift_stdlib_unicode_getASCIICollationTable() { return ASCIICollation::getTable()->CollationTable; } /// Convert the unicode string to uppercase. This function will return the /// required buffer length as a result. If this length does not match the /// 'DestinationCapacity' this function must be called again with a buffer of /// the required length to get an uppercase version of the string. int32_t swift::_swift_stdlib_unicode_strToUpper(uint16_t *Destination, int32_t DestinationCapacity, const uint16_t *Source, int32_t SourceLength) { UErrorCode ErrorCode = U_ZERO_ERROR; uint32_t OutputLength = u_strToUpper(reinterpret_cast<UChar *>(Destination), DestinationCapacity, reinterpret_cast<const UChar *>(Source), SourceLength, "", &ErrorCode); if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) { swift::crash("u_strToUpper: Unexpected error uppercasing unicode string."); } return OutputLength; } /// Convert the unicode string to lowercase. This function will return the /// required buffer length as a result. If this length does not match the /// 'DestinationCapacity' this function must be called again with a buffer of /// the required length to get a lowercase version of the string. int32_t swift::_swift_stdlib_unicode_strToLower(uint16_t *Destination, int32_t DestinationCapacity, const uint16_t *Source, int32_t SourceLength) { UErrorCode ErrorCode = U_ZERO_ERROR; uint32_t OutputLength = u_strToLower(reinterpret_cast<UChar *>(Destination), DestinationCapacity, reinterpret_cast<const UChar *>(Source), SourceLength, "", &ErrorCode); if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) { swift::crash("u_strToLower: Unexpected error lowercasing unicode string."); } return OutputLength; } swift::Lazy<ASCIICollation> ASCIICollation::theTable; #endif namespace { template <typename T, typename U> T *ptr_cast(U *p) { return static_cast<T *>(static_cast<void *>(p)); } template <typename T, typename U> const T *ptr_cast(const U *p) { return static_cast<const T *>(static_cast<const void *>(p)); } } void swift::__swift_stdlib_ubrk_close( swift::__swift_stdlib_UBreakIterator *bi) { ubrk_close(ptr_cast<UBreakIterator>(bi)); } swift::__swift_stdlib_UBreakIterator *swift::__swift_stdlib_ubrk_open( swift::__swift_stdlib_UBreakIteratorType type, const char *locale, const uint16_t *text, int32_t textLength, __swift_stdlib_UErrorCode *status) { return ptr_cast<swift::__swift_stdlib_UBreakIterator>( ubrk_open(static_cast<UBreakIteratorType>(type), locale, reinterpret_cast<const UChar *>(text), textLength, ptr_cast<UErrorCode>(status))); } int32_t swift::__swift_stdlib_ubrk_preceding(swift::__swift_stdlib_UBreakIterator *bi, int32_t offset) { return ubrk_preceding(ptr_cast<UBreakIterator>(bi), offset); } int32_t swift::__swift_stdlib_ubrk_following(swift::__swift_stdlib_UBreakIterator *bi, int32_t offset) { return ubrk_following(ptr_cast<UBreakIterator>(bi), offset); } void swift::__swift_stdlib_ubrk_setText( swift::__swift_stdlib_UBreakIterator *bi, const __swift_stdlib_UChar *text, __swift_int32_t textLength, __swift_stdlib_UErrorCode *status) { return ubrk_setText(ptr_cast<UBreakIterator>(bi), ptr_cast<UChar>(text), textLength, ptr_cast<UErrorCode>(status)); } // Force an autolink with ICU #if defined(__MACH__) asm(".linker_option \"-licucore\"\n"); #endif // defined(__MACH__)
fix Windows link
stubs: fix Windows link There is no icucore.lib in the official ICU distribution for Windows. Remove the autolink directive for now.
C++
apache-2.0
parkera/swift,hooman/swift,tkremenek/swift,sschiau/swift,shajrawi/swift,brentdax/swift,alblue/swift,austinzheng/swift,gregomni/swift,aschwaighofer/swift,devincoughlin/swift,benlangmuir/swift,brentdax/swift,parkera/swift,glessard/swift,jopamer/swift,natecook1000/swift,devincoughlin/swift,huonw/swift,hooman/swift,ahoppen/swift,nathawes/swift,devincoughlin/swift,austinzheng/swift,swiftix/swift,jckarter/swift,JGiola/swift,CodaFi/swift,swiftix/swift,sschiau/swift,OscarSwanros/swift,devincoughlin/swift,brentdax/swift,hooman/swift,parkera/swift,swiftix/swift,hooman/swift,OscarSwanros/swift,apple/swift,JGiola/swift,apple/swift,amraboelela/swift,sschiau/swift,nathawes/swift,stephentyrone/swift,allevato/swift,karwa/swift,huonw/swift,xedin/swift,lorentey/swift,natecook1000/swift,gregomni/swift,rudkx/swift,shajrawi/swift,alblue/swift,xedin/swift,danielmartin/swift,rudkx/swift,apple/swift,natecook1000/swift,airspeedswift/swift,practicalswift/swift,karwa/swift,alblue/swift,atrick/swift,tjw/swift,karwa/swift,tjw/swift,brentdax/swift,ahoppen/swift,benlangmuir/swift,tkremenek/swift,frootloops/swift,practicalswift/swift,nathawes/swift,roambotics/swift,stephentyrone/swift,tkremenek/swift,shajrawi/swift,huonw/swift,glessard/swift,jckarter/swift,jopamer/swift,frootloops/swift,frootloops/swift,jmgc/swift,brentdax/swift,natecook1000/swift,frootloops/swift,harlanhaskins/swift,frootloops/swift,nathawes/swift,xwu/swift,lorentey/swift,shahmishal/swift,CodaFi/swift,OscarSwanros/swift,devincoughlin/swift,parkera/swift,amraboelela/swift,stephentyrone/swift,jckarter/swift,ahoppen/swift,allevato/swift,danielmartin/swift,tjw/swift,zisko/swift,austinzheng/swift,JGiola/swift,ahoppen/swift,austinzheng/swift,gribozavr/swift,zisko/swift,airspeedswift/swift,airspeedswift/swift,CodaFi/swift,swiftix/swift,xwu/swift,amraboelela/swift,karwa/swift,ahoppen/swift,apple/swift,atrick/swift,harlanhaskins/swift,gregomni/swift,jopamer/swift,xedin/swift,allevato/swift,shajrawi/swift,benlangmuir/swift,shahmishal/swift,jckarter/swift,roambotics/swift,frootloops/swift,stephentyrone/swift,tjw/swift,practicalswift/swift,zisko/swift,harlanhaskins/swift,shahmishal/swift,allevato/swift,shajrawi/swift,huonw/swift,zisko/swift,gribozavr/swift,alblue/swift,lorentey/swift,roambotics/swift,JGiola/swift,jopamer/swift,apple/swift,xedin/swift,devincoughlin/swift,zisko/swift,xwu/swift,tkremenek/swift,gribozavr/swift,CodaFi/swift,danielmartin/swift,lorentey/swift,tjw/swift,gribozavr/swift,practicalswift/swift,tkremenek/swift,swiftix/swift,shajrawi/swift,alblue/swift,xwu/swift,amraboelela/swift,stephentyrone/swift,natecook1000/swift,rudkx/swift,OscarSwanros/swift,gregomni/swift,zisko/swift,gregomni/swift,austinzheng/swift,tjw/swift,aschwaighofer/swift,nathawes/swift,huonw/swift,natecook1000/swift,shahmishal/swift,allevato/swift,airspeedswift/swift,harlanhaskins/swift,shajrawi/swift,shahmishal/swift,OscarSwanros/swift,lorentey/swift,austinzheng/swift,jmgc/swift,harlanhaskins/swift,tjw/swift,gregomni/swift,gribozavr/swift,xedin/swift,amraboelela/swift,shahmishal/swift,allevato/swift,sschiau/swift,hooman/swift,xwu/swift,huonw/swift,parkera/swift,glessard/swift,benlangmuir/swift,sschiau/swift,lorentey/swift,lorentey/swift,xedin/swift,gribozavr/swift,karwa/swift,parkera/swift,jopamer/swift,roambotics/swift,aschwaighofer/swift,roambotics/swift,tkremenek/swift,danielmartin/swift,danielmartin/swift,OscarSwanros/swift,devincoughlin/swift,benlangmuir/swift,shahmishal/swift,JGiola/swift,practicalswift/swift,rudkx/swift,glessard/swift,jmgc/swift,benlangmuir/swift,atrick/swift,sschiau/swift,aschwaighofer/swift,roambotics/swift,karwa/swift,jopamer/swift,zisko/swift,karwa/swift,karwa/swift,devincoughlin/swift,atrick/swift,OscarSwanros/swift,natecook1000/swift,rudkx/swift,nathawes/swift,danielmartin/swift,airspeedswift/swift,huonw/swift,harlanhaskins/swift,gribozavr/swift,hooman/swift,frootloops/swift,sschiau/swift,CodaFi/swift,xwu/swift,glessard/swift,jmgc/swift,xedin/swift,brentdax/swift,atrick/swift,airspeedswift/swift,austinzheng/swift,airspeedswift/swift,hooman/swift,alblue/swift,danielmartin/swift,sschiau/swift,stephentyrone/swift,ahoppen/swift,parkera/swift,lorentey/swift,jopamer/swift,apple/swift,jckarter/swift,jmgc/swift,practicalswift/swift,xwu/swift,CodaFi/swift,aschwaighofer/swift,harlanhaskins/swift,parkera/swift,atrick/swift,aschwaighofer/swift,nathawes/swift,glessard/swift,practicalswift/swift,shajrawi/swift,gribozavr/swift,brentdax/swift,practicalswift/swift,jmgc/swift,alblue/swift,swiftix/swift,allevato/swift,amraboelela/swift,amraboelela/swift,swiftix/swift,jckarter/swift,stephentyrone/swift,shahmishal/swift,jmgc/swift,rudkx/swift,CodaFi/swift,JGiola/swift,xedin/swift,jckarter/swift,tkremenek/swift,aschwaighofer/swift
982cc3b15c9ec5e0757e93876d74a3eb178d7e4e
CoreUI/Bundles/org.mitk.gui.qt.common/src/QmitkStdMultiWidgetEditor.cpp
CoreUI/Bundles/org.mitk.gui.qt.common/src/QmitkStdMultiWidgetEditor.cpp
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkStdMultiWidgetEditor.h" #include <berryUIException.h> #include <berryIWorkbenchPage.h> #include <berryIPreferencesService.h> #include <QWidget> #include <mitkColorProperty.h> #include <mitkGlobalInteraction.h> #include <mitkDataStorageEditorInput.h> #include <mitkIDataStorageService.h> #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" const std::string QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : m_StdMultiWidget(0) { } QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor(const QmitkStdMultiWidgetEditor& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { // we need to wrap the RemovePartListener call inside a // register/unregister block to prevent infinite recursion // due to the destruction of temporary smartpointer to this this->Register(); this->GetSite()->GetPage()->RemovePartListener(berry::IPartListener::Pointer(this)); this->UnRegister(false); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return m_StdMultiWidget; } void QmitkStdMultiWidgetEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { if (input.Cast<mitk::DataStorageEditorInput>().IsNull()) throw berry::PartInitException("Invalid Input: Must be IFileEditorInput"); this->SetSite(site); this->SetInput(input); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (m_StdMultiWidget == 0) { m_DndFrameWidget = new QmitkDnDFrameWidget(parent); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DndFrameWidget); layout->setContentsMargins(0,0,0,0); m_StdMultiWidget = new QmitkStdMultiWidget(m_DndFrameWidget); QVBoxLayout* layout2 = new QVBoxLayout(m_DndFrameWidget); layout2->addWidget(m_StdMultiWidget); layout2->setContentsMargins(0,0,0,0); mitk::DataStorage::Pointer ds = this->GetEditorInput().Cast<mitk::DataStorageEditorInput>() ->GetDataStorageReference()->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render m_StdMultiWidget->SetDataStorage(ds); // Initialize views as transversal, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D m_StdMultiWidget->AddDisplayPlaneSubTree(); m_StdMultiWidget->EnableNavigationControllerEventListening(); mitk::GlobalInteraction::GetInstance()->AddListener( m_StdMultiWidget->GetMoveAndZoomInteractor() ); this->GetSite()->GetPage()->AddPartListener(berry::IPartListener::Pointer(this)); // enable change of logo berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID); berry::IPreferences::Pointer logoPref = prefService->GetSystemPreferences()->Node("DepartmentLogo"); std::string departmentLogoLocation = logoPref->Get("DepartmentLogo",""); //# Preferences berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node(EDITOR_ID)) .Cast<berry::IBerryPreferences>(); assert( prefs ); prefs->OnChanged.AddListener( berry::MessageDelegate1<QmitkStdMultiWidgetEditor , const berry::IBerryPreferences*>( this , &QmitkStdMultiWidgetEditor::OnPreferencesChanged ) ); bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_StdMultiWidget->SetDepartmentLogoPath(departmentLogoLocation.c_str()); m_StdMultiWidget->DisableDepartmentLogo(); m_StdMultiWidget->EnableDepartmentLogo(); this->OnPreferencesChanged(prefs.GetPointer()); } } void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { // preferences for gradient background float color = 255.0; QString firstColorName = QString::fromStdString (prefs->GetByteArray("first background color", "")); QColor firstColor(firstColorName); mitk::Color upper; upper[0] = firstColor.red() / color; upper [1] = firstColor.green() / color; upper[2] = firstColor.blue() / color; QString secondColorName = QString::fromStdString (prefs->GetByteArray("second background color", "")); QColor secondColor(secondColorName); mitk::Color lower; lower[0] = secondColor.red() / color; lower[1] = secondColor.green() / color; lower[2] = secondColor.blue() / color; m_StdMultiWidget->SetGradientBackgroundColors(upper, lower); m_StdMultiWidget->EnableGradientBackground(); // Set preferences respecting zooming and padding bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } mitk::DataStorage::Pointer QmitkStdMultiWidgetEditor::GetDataStorage() const { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry().GetServiceById<mitk::IDataStorageService>(mitk::IDataStorageService::ID); if (service.IsNotNull()) { return service->GetDefaultDataStorage()->GetDataStorage(); } return 0; } berry::IPartListener::Events::Types QmitkStdMultiWidgetEditor::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void QmitkStdMultiWidgetEditor::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->AddPlanesToDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::SetFocus() { if (m_StdMultiWidget != 0) m_StdMultiWidget->setFocus(); }
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkStdMultiWidgetEditor.h" #include <berryUIException.h> #include <berryIWorkbenchPage.h> #include <berryIPreferencesService.h> #include <QWidget> #include <mitkColorProperty.h> #include <mitkGlobalInteraction.h> #include <mitkDataStorageEditorInput.h> #include <mitkIDataStorageService.h> #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" const std::string QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : m_StdMultiWidget(0) { } QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor(const QmitkStdMultiWidgetEditor& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { // we need to wrap the RemovePartListener call inside a // register/unregister block to prevent infinite recursion // due to the destruction of temporary smartpointer to this this->Register(); this->GetSite()->GetPage()->RemovePartListener(berry::IPartListener::Pointer(this)); this->UnRegister(false); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return m_StdMultiWidget; } void QmitkStdMultiWidgetEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { if (input.Cast<mitk::DataStorageEditorInput>().IsNull()) throw berry::PartInitException("Invalid Input: Must be IFileEditorInput"); this->SetSite(site); this->SetInput(input); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (m_StdMultiWidget == 0) { m_DndFrameWidget = new QmitkDnDFrameWidget(parent); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DndFrameWidget); layout->setContentsMargins(0,0,0,0); m_StdMultiWidget = new QmitkStdMultiWidget(m_DndFrameWidget); QVBoxLayout* layout2 = new QVBoxLayout(m_DndFrameWidget); layout2->addWidget(m_StdMultiWidget); layout2->setContentsMargins(0,0,0,0); mitk::DataStorage::Pointer ds = this->GetEditorInput().Cast<mitk::DataStorageEditorInput>() ->GetDataStorageReference()->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render m_StdMultiWidget->SetDataStorage(ds); // Initialize views as transversal, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D m_StdMultiWidget->AddDisplayPlaneSubTree(); m_StdMultiWidget->EnableNavigationControllerEventListening(); mitk::GlobalInteraction::GetInstance()->AddListener( m_StdMultiWidget->GetMoveAndZoomInteractor() ); this->GetSite()->GetPage()->AddPartListener(berry::IPartListener::Pointer(this)); // enable change of logo berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID); berry::IPreferences::Pointer logoPref = prefService->GetSystemPreferences()->Node("DepartmentLogo"); std::string departmentLogoLocation = logoPref->Get("DepartmentLogo",""); //# Preferences berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node(EDITOR_ID)) .Cast<berry::IBerryPreferences>(); assert( prefs ); prefs->OnChanged.AddListener( berry::MessageDelegate1<QmitkStdMultiWidgetEditor , const berry::IBerryPreferences*>( this , &QmitkStdMultiWidgetEditor::OnPreferencesChanged ) ); bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_StdMultiWidget->SetDepartmentLogoPath(departmentLogoLocation.c_str()); m_StdMultiWidget->DisableDepartmentLogo(); m_StdMultiWidget->EnableDepartmentLogo(); this->OnPreferencesChanged(prefs.GetPointer()); } } void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { // preferences for gradient background float color = 255.0; QString firstColorName = QString::fromStdString (prefs->GetByteArray("first background color", "")); QColor firstColor(firstColorName); mitk::Color upper; if (firstColorName=="") // default values { upper[0] = 0.1; upper[1] = 0.1; upper[2] = 0.1; } else { upper[0] = firstColor.red() / color; upper[1] = firstColor.green() / color; upper[2] = firstColor.blue() / color; } QString secondColorName = QString::fromStdString (prefs->GetByteArray("second background color", "")); QColor secondColor(secondColorName); mitk::Color lower; if (secondColorName=="") // default values { lower[0] = 0.5; lower[1] = 0.5; lower[2] = 0.5; } else { lower[0] = secondColor.red() / color; lower[1] = secondColor.green() / color; lower[2] = secondColor.blue() / color; } m_StdMultiWidget->SetGradientBackgroundColors(upper, lower); m_StdMultiWidget->EnableGradientBackground(); // Set preferences respecting zooming and padding bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } mitk::DataStorage::Pointer QmitkStdMultiWidgetEditor::GetDataStorage() const { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry().GetServiceById<mitk::IDataStorageService>(mitk::IDataStorageService::ID); if (service.IsNotNull()) { return service->GetDefaultDataStorage()->GetDataStorage(); } return 0; } berry::IPartListener::Events::Types QmitkStdMultiWidgetEditor::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void QmitkStdMultiWidgetEditor::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->AddPlanesToDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::SetFocus() { if (m_StdMultiWidget != 0) m_StdMultiWidget->setFocus(); }
Add default colors if no preferences are saved.
Add default colors if no preferences are saved.
C++
bsd-3-clause
iwegner/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,rfloca/MITK,danielknorr/MITK,NifTK/MITK,nocnokneo/MITK,RabadanLab/MITKats,danielknorr/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,fmilano/mitk,MITK/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,NifTK/MITK,iwegner/MITK,rfloca/MITK,RabadanLab/MITKats,nocnokneo/MITK,nocnokneo/MITK,NifTK/MITK,MITK/MITK,danielknorr/MITK,iwegner/MITK,nocnokneo/MITK,danielknorr/MITK,fmilano/mitk,MITK/MITK,MITK/MITK,MITK/MITK,rfloca/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,fmilano/mitk,iwegner/MITK,fmilano/mitk,rfloca/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,iwegner/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,rfloca/MITK,NifTK/MITK,MITK/MITK,danielknorr/MITK,nocnokneo/MITK,rfloca/MITK,nocnokneo/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,RabadanLab/MITKats,iwegner/MITK,lsanzdiaz/MITK-BiiG
5d6b0e0b169f5b64f05bd23448373e0a90167470
src/appleseed/renderer/kernel/lighting/bdpt/bdptlightingengine.cpp
src/appleseed/renderer/kernel/lighting/bdpt/bdptlightingengine.cpp
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2017 Aytek Aman, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "bdptlightingengine.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/forwardlightsampler.h" #include "renderer/kernel/lighting/pathtracer.h" #include "renderer/modeling/camera/camera.h" #include "renderer/modeling/project/project.h" // appleseed.foundation headers. #include "foundation/utility/statistics.h" using namespace foundation; namespace renderer { namespace { // // Bidirectional Path Tracing lighting engine. // class BDPTLightingEngine : public ILightingEngine { public: struct Parameters { explicit Parameters(const ParamArray& params) { } void print() const { RENDERER_LOG_INFO( "bdpt settings:\n"); } }; BDPTLightingEngine( const Project& project, const ForwardLightSampler& light_sampler, const ParamArray& params) : m_light_sampler(light_sampler) , m_params(params) { const Camera* camera = project.get_uncached_active_camera(); m_shutter_open_time = camera->get_shutter_open_time(); m_shutter_close_time = camera->get_shutter_close_time(); } void release() override { delete this; } void compute_lighting( SamplingContext& sampling_context, const PixelContext& pixel_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingComponents& radiance) override // output radiance, in W.sr^-1.m^-2 { PathVisitor light_path_visitor; VolumeVisitor volume_visitor; PathTracer<PathVisitor, VolumeVisitor, true> light_path_tracer( // true = adjoint light_path_visitor, volume_visitor, ~0, 1, ~0, ~0, ~0, ~0, shading_context.get_max_iterations()); } void trace_light( SamplingContext& sampling_context, const ShadingContext& shading_context) { // Sample the light sources. sampling_context.split_in_place(4, 1); const Vector4f s = sampling_context.next2<Vector4f>(); LightSample light_sample; m_light_sampler.sample( ShadingRay::Time::create_with_normalized_time( s[0], m_shutter_open_time, m_shutter_close_time), Vector3f(s[1], s[2], s[3]), light_sample); light_sample.m_triangle ? trace_emitting_triangle( sampling_context, shading_context, light_sample) : trace_non_physical_light( sampling_context, shading_context, light_sample); } void trace_emitting_triangle( SamplingContext& sampling_context, const ShadingContext& shading_context, LightSample& light_sample) { } void trace_non_physical_light( SamplingContext& sampling_context, const ShadingContext& shading_context, LightSample& light_sample) { } StatisticsVector get_statistics() const override { Statistics stats; return StatisticsVector::make("bdpt statistics", stats); } private: const Parameters m_params; const ForwardLightSampler& m_light_sampler; float m_shutter_open_time; float m_shutter_close_time; struct PathVisitor { PathVisitor() { } }; struct VolumeVisitor { VolumeVisitor() { } }; }; } BDPTLightingEngineFactory::BDPTLightingEngineFactory( const Project& project, const ForwardLightSampler& light_sampler, const ParamArray& params) : m_project(project) , m_light_sampler(light_sampler) , m_params(params) { BDPTLightingEngine::Parameters(params).print(); } void BDPTLightingEngineFactory::release() { delete this; } ILightingEngine* BDPTLightingEngineFactory::create() { return new BDPTLightingEngine( m_project, m_light_sampler, m_params); } Dictionary BDPTLightingEngineFactory::get_params_metadata() { Dictionary metadata; add_common_params_metadata(metadata, true); return metadata; } } // namespace renderer
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2017 Aytek Aman, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "bdptlightingengine.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/forwardlightsampler.h" #include "renderer/kernel/lighting/pathtracer.h" #include "renderer/modeling/camera/camera.h" #include "renderer/modeling/edf/edf.h" #include "renderer/modeling/material/material.h" #include "renderer/modeling/project/project.h" // appleseed.foundation headers. #include "foundation/utility/statistics.h" using namespace foundation; namespace renderer { namespace { // // Bidirectional Path Tracing lighting engine. // class BDPTLightingEngine : public ILightingEngine { public: struct Parameters { explicit Parameters(const ParamArray& params) { } void print() const { RENDERER_LOG_INFO( "bdpt settings:\n"); } }; BDPTLightingEngine( const Project& project, const ForwardLightSampler& light_sampler, const ParamArray& params) : m_light_sampler(light_sampler) , m_params(params) { const Camera* camera = project.get_uncached_active_camera(); m_shutter_open_time = camera->get_shutter_open_time(); m_shutter_close_time = camera->get_shutter_close_time(); } void release() override { delete this; } void compute_lighting( SamplingContext& sampling_context, const PixelContext& pixel_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingComponents& radiance) override // output radiance, in W.sr^-1.m^-2 { PathVisitor light_path_visitor; VolumeVisitor volume_visitor; PathTracer<PathVisitor, VolumeVisitor, true> light_path_tracer( // true = adjoint light_path_visitor, volume_visitor, ~0, 1, ~0, ~0, ~0, ~0, shading_context.get_max_iterations()); } void trace_light( SamplingContext& sampling_context, const ShadingContext& shading_context) { // Sample the light sources. sampling_context.split_in_place(4, 1); const Vector4f s = sampling_context.next2<Vector4f>(); LightSample light_sample; m_light_sampler.sample( ShadingRay::Time::create_with_normalized_time( s[0], m_shutter_open_time, m_shutter_close_time), Vector3f(s[1], s[2], s[3]), light_sample); light_sample.m_triangle ? trace_emitting_triangle( sampling_context, shading_context, light_sample) : trace_non_physical_light( sampling_context, shading_context, light_sample); } void trace_emitting_triangle( SamplingContext& sampling_context, const ShadingContext& shading_context, LightSample& light_sample) { // Make sure the geometric normal of the light sample is in the same hemisphere as the shading normal. light_sample.m_geometric_normal = flip_to_same_hemisphere( light_sample.m_geometric_normal, light_sample.m_shading_normal); const Material* material = light_sample.m_triangle->m_material; const Material::RenderData& material_data = material->get_render_data(); // Build a shading point on the light source. ShadingPoint light_shading_point; light_sample.make_shading_point( light_shading_point, light_sample.m_shading_normal, shading_context.get_intersector()); if (material_data.m_shader_group) { shading_context.execute_osl_emission( *material_data.m_shader_group, light_shading_point); } // Sample the EDF. sampling_context.split_in_place(2, 1); Vector3f emission_direction; Spectrum edf_value(Spectrum::Illuminance); float edf_prob; material_data.m_edf->sample( sampling_context, material_data.m_edf->evaluate_inputs(shading_context, light_shading_point), Vector3f(light_sample.m_geometric_normal), Basis3f(Vector3f(light_sample.m_shading_normal)), sampling_context.next2<Vector2f>(), emission_direction, edf_value, edf_prob); // Compute the initial particle weight. Spectrum initial_flux = edf_value; initial_flux *= dot(emission_direction, Vector3f(light_sample.m_shading_normal)) / (light_sample.m_probability * edf_prob); // Make a shading point that will be used to avoid self-intersections with the light sample. ShadingPoint parent_shading_point; light_sample.make_shading_point( parent_shading_point, Vector3d(emission_direction), shading_context.get_intersector()); // Build the light ray. sampling_context.split_in_place(1, 1); const ShadingRay::Time time = ShadingRay::Time::create_with_normalized_time( sampling_context.next2<float>(), m_shutter_open_time, m_shutter_close_time); const ShadingRay light_ray( light_sample.m_point, Vector3d(emission_direction), time, VisibilityFlags::LightRay, 0); // Build the path tracer. PathVisitor path_visitor; VolumeVisitor volume_visitor; PathTracer<PathVisitor, VolumeVisitor, true> path_tracer( path_visitor, volume_visitor, ~0, 1, ~0, ~0, ~0, ~0, shading_context.get_max_iterations()); // don't illuminate points closer than the light near start value const size_t path_length = path_tracer.trace( sampling_context, shading_context, light_ray, &parent_shading_point); } void trace_non_physical_light( SamplingContext& sampling_context, const ShadingContext& shading_context, LightSample& light_sample) { } StatisticsVector get_statistics() const override { Statistics stats; return StatisticsVector::make("bdpt statistics", stats); } private: const Parameters m_params; const ForwardLightSampler& m_light_sampler; //Intersector m_intersector; float m_shutter_open_time; float m_shutter_close_time; struct PathVisitor { PathVisitor() { } bool accept_scattering( const ScatteringMode::Mode prev_mode, const ScatteringMode::Mode next_mode) const { return false; } void on_miss(const PathVertex& vertex) { } void on_hit(const PathVertex& vertex) { } void on_scatter(const PathVertex& vertex) { } }; struct VolumeVisitor { VolumeVisitor() { } bool accept_scattering( const ScatteringMode::Mode prev_mode) { return true; } void on_scatter(PathVertex& vertex) {} void visit_ray(PathVertex& vertex, const ShadingRay& volume_ray) {} }; }; } BDPTLightingEngineFactory::BDPTLightingEngineFactory( const Project& project, const ForwardLightSampler& light_sampler, const ParamArray& params) : m_project(project) , m_light_sampler(light_sampler) , m_params(params) { BDPTLightingEngine::Parameters(params).print(); } void BDPTLightingEngineFactory::release() { delete this; } ILightingEngine* BDPTLightingEngineFactory::create() { return new BDPTLightingEngine( m_project, m_light_sampler, m_params); } Dictionary BDPTLightingEngineFactory::get_params_metadata() { Dictionary metadata; add_common_params_metadata(metadata, true); return metadata; } } // namespace renderer
Implement tracing of emitting triangles
Implement tracing of emitting triangles -Right now, most functionality is copied from LightTracingSampleGenerator class
C++
mit
dictoon/appleseed,pjessesco/appleseed,appleseedhq/appleseed,dictoon/appleseed,dictoon/appleseed,est77/appleseed,Biart95/appleseed,Biart95/appleseed,Biart95/appleseed,luisbarrancos/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,pjessesco/appleseed,Biart95/appleseed,Vertexwahn/appleseed,pjessesco/appleseed,appleseedhq/appleseed,dictoon/appleseed,luisbarrancos/appleseed,est77/appleseed,aytekaman/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,appleseedhq/appleseed,Biart95/appleseed,luisbarrancos/appleseed,aytekaman/appleseed,est77/appleseed,Vertexwahn/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,luisbarrancos/appleseed,est77/appleseed,dictoon/appleseed,pjessesco/appleseed,appleseedhq/appleseed
4a7dbbe9e9d675dbf3ab47878d16cce23c26e8da
chrome/browser/ui/views/frame/app_non_client_frame_view_ash_browsertest.cc
chrome/browser/ui/views/frame/app_non_client_frame_view_ash_browsertest.cc
// 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 "chrome/browser/chrome_notification_types.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/frame/app_non_client_frame_view_ash.h" #include "chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/test_utils.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/root_window.h" #include "ui/aura/test/event_generator.h" #include "ui/aura/window.h" #include "ui/gfx/screen.h" using aura::Window; namespace { Window* GetChildWindowNamed(Window* window, const char* name) { for (size_t i = 0; i < window->children().size(); ++i) { Window* child = window->children()[i]; if (child->name() == name) return child; } return NULL; } bool HasChildWindowNamed(Window* window, const char* name) { return GetChildWindowNamed(window, name) != NULL; } void MaximizeWindow(aura::Window* window) { window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); } void MinimizeWindow(aura::Window* window) { window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); } void RestoreWindow(Window* window) { window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); } } // namespace class AppNonClientFrameViewAshTest : public InProcessBrowserTest { public: AppNonClientFrameViewAshTest() : InProcessBrowserTest(), app_browser_(NULL) { } virtual ~AppNonClientFrameViewAshTest() {} virtual void SetUpOnMainThread() OVERRIDE { Browser::CreateParams params = Browser::CreateParams::CreateForApp( Browser::TYPE_POPUP, std::string("Test"), gfx::Rect(), browser()->profile(), browser()->host_desktop_type()); params.initial_show_state = ui::SHOW_STATE_MAXIMIZED; params.app_type = Browser::APP_TYPE_HOST; app_browser_ = new Browser(params); chrome::AddBlankTabAt(app_browser_, -1, true); app_browser_->window()->Show(); } // Returns the class name of the NonClientFrameView. std::string GetFrameClassName() const { BrowserView* browser_view = static_cast<BrowserView*>(app_browser_->window()); BrowserFrame* browser_frame = browser_view->frame(); return browser_frame->GetFrameView()->GetClassName(); } aura::RootWindow* GetRootWindow() const { BrowserView* browser_view = static_cast<BrowserView*>(app_browser_->window()); views::Widget* widget = browser_view->GetWidget(); aura::Window* window = static_cast<aura::Window*>(widget->GetNativeWindow()); return window->GetRootWindow(); } Browser* app_browser() const { return app_browser_; } private: Browser *app_browser_; }; #if defined(USE_ASH) // Ensure that restoring the app window replaces the frame with a normal one, // and maximizing again brings back the app frame. This has been the source of // some crash bugs like crbug.com/155634 IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, SwitchFrames) { // Convert to std::string so Windows can match EXPECT_EQ. const std::string kAppFrameClassName = AppNonClientFrameViewAsh::kViewClassName; const std::string kNormalFrameClassName = BrowserNonClientFrameViewAsh::kViewClassName; // We start with the app frame. EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); // Restoring the window gives us the normal frame. Window* native_window = app_browser()->window()->GetNativeWindow(); RestoreWindow(native_window); EXPECT_EQ(kNormalFrameClassName, GetFrameClassName()); // Maximizing the window switches back to the app frame. MaximizeWindow(native_window); EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); // Minimizing the window switches to normal frame. // TODO(jamescook): This seems wasteful, since the user is likely to bring // the window back to the maximized state. MinimizeWindow(native_window); EXPECT_EQ(kNormalFrameClassName, GetFrameClassName()); // Coming back to maximized switches to app frame. MaximizeWindow(native_window); EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); // One more restore/maximize cycle for good measure. RestoreWindow(native_window); EXPECT_EQ(kNormalFrameClassName, GetFrameClassName()); MaximizeWindow(native_window); EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); } #endif // USE_ASH // Ensure that we can click the close button when the controls are shown. // In particular make sure that we can click it on the top pixel of the button. IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, ClickClose) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window, gfx::Point(0, 1)); // Click close button. eg.MoveMouseTo(root_window->bounds().width() - 1, 0); content::WindowedNotificationObserver signal( chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(app_browser())); eg.ClickLeftButton(); signal.Wait(); EXPECT_EQ(1u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); } // Ensure that closing a maximized app with Ctrl-W does not crash the // application. crbug.com/147635 IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, KeyboardClose) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window); // Base browser and app browser. EXPECT_EQ(2u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); // Send Control-W. content::WindowedNotificationObserver signal( chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(app_browser())); eg.PressKey(ui::VKEY_W, ui::EF_CONTROL_DOWN); eg.ReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN); signal.Wait(); // App browser is closed. EXPECT_EQ(1u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); } // Ensure that snapping left with Alt-[ closes the control window. IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, SnapLeftClosesControls) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window); aura::Window* native_window = app_browser()->window()->GetNativeWindow(); // Control window exists. EXPECT_TRUE(HasChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName)); // Send Alt-[ eg.PressKey(ui::VKEY_OEM_4, ui::EF_ALT_DOWN); eg.ReleaseKey(ui::VKEY_OEM_4, ui::EF_ALT_DOWN); content::RunAllPendingInMessageLoop(); // Control window is gone. EXPECT_FALSE(HasChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName)); } // Ensure that the controls are at the proper locations. IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, ControlsAtRightSide) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window); aura::Window* native_window = app_browser()->window()->GetNativeWindow(); const gfx::Rect work_area = gfx::Screen::GetScreenFor(native_window)->GetPrimaryDisplay().work_area(); // Control window exists. aura::Window* window = GetChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName); ASSERT_TRUE(window); gfx::Rect rect = window->bounds(); EXPECT_EQ(work_area.right(), rect.right()); EXPECT_EQ(work_area.y(), rect.y()); MinimizeWindow(native_window); content::RunAllPendingInMessageLoop(); window = GetChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName); EXPECT_FALSE(window); MaximizeWindow(native_window); content::RunAllPendingInMessageLoop(); // Control window exists. aura::Window* window_after = GetChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName); ASSERT_TRUE(window_after); gfx::Rect rect_after = window_after->bounds(); EXPECT_EQ(work_area.right(), rect_after.right()); EXPECT_EQ(work_area.y(), rect_after.y()); }
// 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 "chrome/browser/chrome_notification_types.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/frame/app_non_client_frame_view_ash.h" #include "chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/test_utils.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/root_window.h" #include "ui/aura/test/event_generator.h" #include "ui/aura/window.h" #include "ui/gfx/screen.h" using aura::Window; namespace { Window* GetChildWindowNamed(Window* window, const char* name) { for (size_t i = 0; i < window->children().size(); ++i) { Window* child = window->children()[i]; if (child->name() == name) return child; } return NULL; } bool HasChildWindowNamed(Window* window, const char* name) { return GetChildWindowNamed(window, name) != NULL; } void MaximizeWindow(aura::Window* window) { window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); } void MinimizeWindow(aura::Window* window) { window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); } void RestoreWindow(Window* window) { window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); } } // namespace class AppNonClientFrameViewAshTest : public InProcessBrowserTest { public: AppNonClientFrameViewAshTest() : InProcessBrowserTest(), app_browser_(NULL) { } virtual ~AppNonClientFrameViewAshTest() {} virtual void SetUpOnMainThread() OVERRIDE { Browser::CreateParams params = Browser::CreateParams::CreateForApp( Browser::TYPE_POPUP, std::string("Test"), gfx::Rect(), browser()->profile(), browser()->host_desktop_type()); params.initial_show_state = ui::SHOW_STATE_MAXIMIZED; params.app_type = Browser::APP_TYPE_HOST; app_browser_ = new Browser(params); chrome::AddBlankTabAt(app_browser_, -1, true); app_browser_->window()->Show(); } // Returns the class name of the NonClientFrameView. std::string GetFrameClassName() const { BrowserView* browser_view = static_cast<BrowserView*>(app_browser_->window()); BrowserFrame* browser_frame = browser_view->frame(); return browser_frame->GetFrameView()->GetClassName(); } aura::RootWindow* GetRootWindow() const { BrowserView* browser_view = static_cast<BrowserView*>(app_browser_->window()); views::Widget* widget = browser_view->GetWidget(); aura::Window* window = static_cast<aura::Window*>(widget->GetNativeWindow()); return window->GetRootWindow(); } Browser* app_browser() const { return app_browser_; } private: Browser *app_browser_; }; #if defined(USE_ASH) // Ensure that restoring the app window replaces the frame with a normal one, // and maximizing again brings back the app frame. This has been the source of // some crash bugs like crbug.com/155634 // Disabled because it's failing flakily: crbug.com/290240 IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, DISABLED_SwitchFrames) { // Convert to std::string so Windows can match EXPECT_EQ. const std::string kAppFrameClassName = AppNonClientFrameViewAsh::kViewClassName; const std::string kNormalFrameClassName = BrowserNonClientFrameViewAsh::kViewClassName; // We start with the app frame. EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); // Restoring the window gives us the normal frame. Window* native_window = app_browser()->window()->GetNativeWindow(); RestoreWindow(native_window); EXPECT_EQ(kNormalFrameClassName, GetFrameClassName()); // Maximizing the window switches back to the app frame. MaximizeWindow(native_window); EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); // Minimizing the window switches to normal frame. // TODO(jamescook): This seems wasteful, since the user is likely to bring // the window back to the maximized state. MinimizeWindow(native_window); EXPECT_EQ(kNormalFrameClassName, GetFrameClassName()); // Coming back to maximized switches to app frame. MaximizeWindow(native_window); EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); // One more restore/maximize cycle for good measure. RestoreWindow(native_window); EXPECT_EQ(kNormalFrameClassName, GetFrameClassName()); MaximizeWindow(native_window); EXPECT_EQ(kAppFrameClassName, GetFrameClassName()); } #endif // USE_ASH // Ensure that we can click the close button when the controls are shown. // In particular make sure that we can click it on the top pixel of the button. IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, ClickClose) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window, gfx::Point(0, 1)); // Click close button. eg.MoveMouseTo(root_window->bounds().width() - 1, 0); content::WindowedNotificationObserver signal( chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(app_browser())); eg.ClickLeftButton(); signal.Wait(); EXPECT_EQ(1u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); } // Ensure that closing a maximized app with Ctrl-W does not crash the // application. crbug.com/147635 IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, KeyboardClose) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window); // Base browser and app browser. EXPECT_EQ(2u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); // Send Control-W. content::WindowedNotificationObserver signal( chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(app_browser())); eg.PressKey(ui::VKEY_W, ui::EF_CONTROL_DOWN); eg.ReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN); signal.Wait(); // App browser is closed. EXPECT_EQ(1u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); } // Ensure that snapping left with Alt-[ closes the control window. IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, SnapLeftClosesControls) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window); aura::Window* native_window = app_browser()->window()->GetNativeWindow(); // Control window exists. EXPECT_TRUE(HasChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName)); // Send Alt-[ eg.PressKey(ui::VKEY_OEM_4, ui::EF_ALT_DOWN); eg.ReleaseKey(ui::VKEY_OEM_4, ui::EF_ALT_DOWN); content::RunAllPendingInMessageLoop(); // Control window is gone. EXPECT_FALSE(HasChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName)); } // Ensure that the controls are at the proper locations. IN_PROC_BROWSER_TEST_F(AppNonClientFrameViewAshTest, ControlsAtRightSide) { aura::RootWindow* root_window = GetRootWindow(); aura::test::EventGenerator eg(root_window); aura::Window* native_window = app_browser()->window()->GetNativeWindow(); const gfx::Rect work_area = gfx::Screen::GetScreenFor(native_window)->GetPrimaryDisplay().work_area(); // Control window exists. aura::Window* window = GetChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName); ASSERT_TRUE(window); gfx::Rect rect = window->bounds(); EXPECT_EQ(work_area.right(), rect.right()); EXPECT_EQ(work_area.y(), rect.y()); MinimizeWindow(native_window); content::RunAllPendingInMessageLoop(); window = GetChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName); EXPECT_FALSE(window); MaximizeWindow(native_window); content::RunAllPendingInMessageLoop(); // Control window exists. aura::Window* window_after = GetChildWindowNamed( native_window, AppNonClientFrameViewAsh::kControlWindowName); ASSERT_TRUE(window_after); gfx::Rect rect_after = window_after->bounds(); EXPECT_EQ(work_area.right(), rect_after.right()); EXPECT_EQ(work_area.y(), rect_after.y()); }
Disable AppNonClientFrameViewAshTest.SwitchFrames
Disable AppNonClientFrameViewAshTest.SwitchFrames BUG=290240 [email protected],[email protected],[email protected] Review URL: https://codereview.chromium.org/23536044 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@222806 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
littlstar/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,patrickm/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,jaruba/chromium.src,ltilve/chromium,ondra-novak/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,anirudhSK/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,ltilve/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,ltilve/chromium,Jonekee/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,M4sse/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,jaruba/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,ltilve/chromium,anirudhSK/chromium,M4sse/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src
1dfd3a0f41d3cf07688416091594145d3531d066
Modules/Filtering/Projection/test/otbGeometriesProjectionFilterFromMapToGeo.cxx
Modules/Filtering/Projection/test/otbGeometriesProjectionFilterFromMapToGeo.cxx
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*===========================================================================*/ /*===============================[ Includes ]================================*/ /*===========================================================================*/ #include "otbGeometriesProjectionFilter.h" #include "otbGeometriesSet.h" #include "otbImage.h" #include "otbImageFileReader.h" /*===========================================================================*/ /*==============================[ other stuff ]==============================*/ /*===========================================================================*/ int otbGeometriesProjectionFilterFromMapToGeo(int argc, char* argv[]) { if (argc < 2) { std::cerr << argv[0] << " <input vector filename> <output vector filename>\n"; return EXIT_FAILURE; } // Input Geometries set typedef otb::GeometriesSet InputGeometriesType; typedef otb::GeometriesSet OutputGeometriesType; otb::ogr::DataSource::Pointer input = otb::ogr::DataSource::New( argv[1], otb::ogr::DataSource::Modes::Read); InputGeometriesType::Pointer in_set = InputGeometriesType::New(input); // Output Geometries Set otb::ogr::DataSource::Pointer output = otb::ogr::DataSource::New( argv[2], otb::ogr::DataSource::Modes::Overwrite); OutputGeometriesType::Pointer out_set = OutputGeometriesType::New(output); // Filter typedef otb::GeometriesProjectionFilter GeometriesFilterType; GeometriesFilterType::Pointer filter = GeometriesFilterType::New(); filter->SetInput(in_set); filter->SetOutput(out_set); filter->Update(); return EXIT_SUCCESS; }
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*===========================================================================*/ /*===============================[ Includes ]================================*/ /*===========================================================================*/ #include "otbGeometriesProjectionFilter.h" #include "otbGeometriesSet.h" #include "otbImage.h" #include "otbImageFileReader.h" // #include "otbSpatialReference.h" /*===========================================================================*/ /*==============================[ other stuff ]==============================*/ /*===========================================================================*/ int otbGeometriesProjectionFilterFromMapToGeo(int argc, char* argv[]) { if (argc < 2) { std::cerr << argv[0] << " <input vector filename> <output vector filename>\n"; return EXIT_FAILURE; } // Input Geometries set typedef otb::GeometriesSet InputGeometriesType; typedef otb::GeometriesSet OutputGeometriesType; otb::ogr::DataSource::Pointer input = otb::ogr::DataSource::New( argv[1], otb::ogr::DataSource::Modes::Read); InputGeometriesType::Pointer in_set = InputGeometriesType::New(input); // Output Geometries Set otb::ogr::DataSource::Pointer output = otb::ogr::DataSource::New( argv[2], otb::ogr::DataSource::Modes::Overwrite); OutputGeometriesType::Pointer out_set = OutputGeometriesType::New(output); // Filter typedef otb::GeometriesProjectionFilter GeometriesFilterType; GeometriesFilterType::Pointer filter = GeometriesFilterType::New(); filter->SetInput(in_set); filter->SetOutput(out_set); filter->SetOutputProjectionRef(otb::SpatialReference::FromWGS84().ToWkt()); filter->Update(); return EXIT_SUCCESS; }
fix prTvGeometriesProjectionFilterFromMapToGeo test
TEST: fix prTvGeometriesProjectionFilterFromMapToGeo test
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
c524443b4c8f2b0cf82b8e1032fd7c7c136d52aa
Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp
Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatConnectionPreferencePage.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include "berryIPreferencesService.h" #include "berryPlatform.h" #include <QFileDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> #include <QMap> #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include <mitkIOUtil.h> using namespace berry; QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(0) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { IPreferencesService* prefService = Platform::GetPreferencesService(); berry::IPreferences::Pointer _XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID); m_XnatConnectionPreferencesNode = _XnatConnectionPreferencesNode; m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { session = nullptr; } if (session != nullptr && session->isOpen()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.xnatTestConnectionLabel->setText("Already connected."); m_Controls.xnatTestConnectionButton->setEnabled(false); } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked())); m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { _XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text()); // Network proxy settings _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text(), m_Controls.cbUseNetworkProxy->isChecked()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text()); // Silent Mode _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text(), m_Controls.cbUseSilentMode->isChecked()); //Write _XnatConnectionPreferencesNode->Flush(); return true; } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { m_Controls.inXnatHostAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text())); m_Controls.inXnatPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text())); m_Controls.inXnatUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text())); m_Controls.inXnatPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text())); m_Controls.inXnatDownloadPath->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text())); // Network proxy settings m_Controls.cbUseNetworkProxy->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseNetworkProxy->text(), false)); m_Controls.inProxyAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text())); m_Controls.inProxyPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text())); m_Controls.inProxyUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text())); m_Controls.inProxyPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text())); // Silent Mode m_Controls.cbUseSilentMode->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseSilentMode->text(), false)); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: white; }"); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: red; }"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: white; }"); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: red; }"); } } } void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status) { m_Controls.groupBoxProxySettings->setVisible(status); } void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked() { QString dir = QFileDialog::getExistingDirectory(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void QmitkXnatConnectionPreferencePage::TestConnection() { if(UserInformationEmpty()) { return; } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (const std::invalid_argument &) { if (!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting successful."); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkXnatAuthenticationException& auth) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Adress\nPossibly due to missing OpenSSL for HTTPS connections"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatConnectionPreferencePage.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include "berryIPreferencesService.h" #include "berryPlatform.h" #include <QFileDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> #include <QMap> #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include <mitkIOUtil.h> using namespace berry; QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(0) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { IPreferencesService* prefService = Platform::GetPreferencesService(); berry::IPreferences::Pointer _XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID); m_XnatConnectionPreferencesNode = _XnatConnectionPreferencesNode; m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { session = nullptr; } if (session != nullptr && session->isOpen()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green"); m_Controls.xnatTestConnectionLabel->setText("Already connected."); m_Controls.xnatTestConnectionButton->setEnabled(false); } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked())); m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { _XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text()); // Network proxy settings _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text(), m_Controls.cbUseNetworkProxy->isChecked()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text()); // Silent Mode _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text(), m_Controls.cbUseSilentMode->isChecked()); //Write _XnatConnectionPreferencesNode->Flush(); return true; } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { m_Controls.inXnatHostAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text())); m_Controls.inXnatPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text())); m_Controls.inXnatUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text())); m_Controls.inXnatPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text())); m_Controls.inXnatDownloadPath->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text())); // Network proxy settings m_Controls.cbUseNetworkProxy->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseNetworkProxy->text(), false)); m_Controls.inProxyAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text())); m_Controls.inProxyPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text())); m_Controls.inProxyUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text())); m_Controls.inProxyPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text())); // Silent Mode m_Controls.cbUseSilentMode->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseSilentMode->text(), false)); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet(""); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("background-color: red"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet(""); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("background-color: red"); } } } void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status) { m_Controls.groupBoxProxySettings->setVisible(status); } void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked() { QString dir = QFileDialog::getExistingDirectory(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void QmitkXnatConnectionPreferencePage::TestConnection() { if(UserInformationEmpty()) { return; } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (const std::invalid_argument &) { if (!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green"); m_Controls.xnatTestConnectionLabel->setText("Connecting successful."); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkXnatAuthenticationException& auth) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Adress\nPossibly due to missing OpenSSL for HTTPS connections"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } }
Fix hard-coded style modifications
Fix hard-coded style modifications
C++
bsd-3-clause
fmilano/mitk,fmilano/mitk,fmilano/mitk,fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk
e89d712f296b8de5e6c5ecc5194ad1af1f6b76d4
include/stack.hpp
include/stack.hpp
#include <iostream> #include <algorithm> template <typename T> class stack { public: stack(); size_t count() const; size_t array_size() const; T * operator[](unsigned int index) const; void push(T const &); T pop(); T last()const; void print(); void swap(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() { array_ = nullptr; array_size_ = 0; count_ = 0; } template <typename T> size_t stack<T>::array_size() const { return array_size_; } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> T * stack<T>::operator[](unsigned int index) const { return array_[index]; } template <typename T> void stack<T>::push(T const & value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; swap(); } array_[count_++] = value; } template <typename T> T stack<T>::pop() { if (count_ == 0) throw std::logic_error("Stack is empty"); else { if (count_ - 1 == array_size_ / 2) array_size_ /= 2; T value = array_[--count_]; swap(); return value; } } template <typename T> T stack<T>::last()const { if (count_ == 0) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print() { for (unsigned int i = 0; i < count_; ++i) std::cout << array_[i] << " "; std::cout << std::endl; } template <typename T> void stack<T>::swap() { T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, stdext::checked_array_iterator<T*>(new_array, count_)); delete[] array_; array_ = new_array; }
#include <iostream> #include <algorithm> template <typename T> class stack { public: stack(); size_t count() const; size_t array_size() const; T * operator[](unsigned int index) const; void push(T const &); void pop(); T top(); T last()const; void print(); void swap(); bool empty(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() { array_ = nullptr; array_size_ = 0; count_ = 0; } template <typename T> size_t stack<T>::array_size() const { return array_size_; } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> T * stack<T>::operator[](unsigned int index) const { return array_[index]; } template <typename T> void stack<T>::push(T const & value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; swap(); } array_[count_++] = value; } template <typename T> void stack<T>::pop() { if (empty()) throw std::logic_error("Stack is empty"); else { if (count_ - 1 == array_size_ / 2) array_size_ /= 2; swap(); } } T stack<T>::top() { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count - 1]; } template <typename T> T stack<T>::last()const { if (count_ == 0) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print() { for (unsigned int i = 0; i < count_; ++i) std::cout << array_[i] << " "; std::cout << std::endl; } template <typename T> void stack<T>::swap() { T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } template <typename T> bool stack<T>::empty() { return (count_ == 0) ? true : false; }
Update stack.hpp
Update stack.hpp
C++
mit
kate-lozovaya/stack-0.0.3
d2f0cf398d2cba498205a024b4b71536883034f5
MerlionServerCore/NodeClientSocket.cpp
MerlionServerCore/NodeClientSocket.cpp
/** * Copyright (C) 2014 yvt <[email protected]>. * * 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 "Prefix.pch" #include "NodeClientSocket.hpp" #include "Library.hpp" #include "Exceptions.hpp" using boost::format; namespace asio = boost::asio; namespace ip = boost::asio::ip; using pipes = asio::local::stream_protocol; namespace mcore { NodeClientSocket::NodeClientSocket(std::shared_ptr<Library> library, const std::string& displayName, int stream) : library(library), socket(library->ioService()), _strand(library->ioService()), webSocket(socket) { log.setChannel(displayName); socket.assign(pipes(), stream); } NodeClientSocket::~NodeClientSocket() { } void NodeClientSocket::shutdown() { auto self = shared_from_this(); bool done = false; std::mutex doneMutex; std::condition_variable doneCond; down_ = true; _strand.dispatch([self, this, &done, &doneMutex, &doneCond] { decltype(shutdownListeners) listeners; listeners.swap(shutdownListeners); for (auto& f: listeners) f(); webSocket.async_shutdown(asiows::web_socket_close_status_codes::normal_closure, "", false, _strand.wrap([self, this] (const boost::system::error_code &) { boost::system::error_code error; socket.close(error); })); std::lock_guard<std::mutex> lock(doneMutex); done = true; doneCond.notify_all(); }); std::unique_lock<std::mutex> lock(doneMutex); while (!done) { doneCond.wait(lock); } } template <class Callback> void NodeClientSocket::receive(Callback &&cb) { struct ReceiveOperation { enum class State { ReceiveMessage, ReadMessage }; State state = State::ReceiveMessage; std::shared_ptr<NodeClientSocket> socket; typename std::remove_reference<Callback>::type callback; decltype(shutdownListeners)::iterator shutdownListenersIter; ReceiveOperation(const std::shared_ptr<NodeClientSocket> &socket, Callback &&cb) : socket(socket), callback(cb) { } void done() { socket->receiving_ = false; if (!socket->shutdownListeners.empty()) { socket->shutdownListeners.erase(shutdownListenersIter); } } void operator () (const boost::system::error_code& error, std::size_t count = 0) { switch (state) { case State::ReceiveMessage: if (error) { socket->receiveBuffer.resize(0); done(); callback(socket->receiveBuffer, error.message()); } else { state = State::ReadMessage; perform(); } break; case State::ReadMessage: if (error) { socket->receiveBuffer.resize(0); done(); callback(socket->receiveBuffer, error.message()); } else if (count == 0) { socket->receiveBuffer.resize(socket->receiveBufferLen); done(); try { if (!socket->down_) callback(socket->receiveBuffer, std::string()); } catch (...) { BOOST_LOG_SEV(socket->log, LogLevel::Error) << "Error occured in packet receive handler.: " << boost::current_exception_diagnostic_information(); } } else { socket->receiveBufferLen += count; if (socket->receiveBufferLen > 65536) { // Too long. socket->receiveBuffer.resize(0); auto self = socket; socket->webSocket.async_shutdown(asiows::web_socket_close_status_codes::too_big, "Packet size is limited to 65536 bytes.", true, socket->_strand.wrap([self](const boost::system::error_code&){})); callback(socket->receiveBuffer, "Received packet is too long."); return; } socket->receiveBuffer.resize(socket->receiveBufferLen); perform(); } break; } } void perform() { switch (state) { case State::ReceiveMessage: { auto cb = callback; socket->shutdownListeners.emplace_back([cb] { std::vector<char> dummyBuffer; cb(dummyBuffer, "Socket is disconnected."); }); } shutdownListenersIter = socket->shutdownListeners.begin(); socket->webSocket.async_receive_message(std::move(*this)); break; case State::ReadMessage: socket->receiveBuffer.resize(socket->receiveBufferLen + 4096); socket->webSocket.async_read_some(asio::buffer(socket->receiveBuffer.data() + socket->receiveBufferLen, 4096), std::move(*this)); break; } } }; auto self = shared_from_this(); _strand.dispatch([self, this, cb] () mutable { if (receiving_) { cb(receiveBuffer, std::string("Cannot perform multiple reads at once.")); return; } else if (down_) { cb(receiveBuffer, std::string("Socket is disconnected.")); return; } receiving_ = true; receiveBufferLen = 0; receiveBuffer.resize(0); ReceiveOperation op(shared_from_this(), std::move(cb)); op.perform(); }); } template <class Callback> void NodeClientSocket::send(const void *data, std::size_t length, Callback &&cb) { if (length > 65536) { // Too long. (limitation of Merlion, not WebSocket) MSCThrow(InvalidArgumentException("Packet cannot be longer than 65536 bytes.", "length")); } auto self = shared_from_this(); auto buffer = std::make_shared<std::vector<char>>(length); std::memcpy(buffer->data(), data, length); _strand.dispatch([self, buffer, cb, this] () mutable { if (down_) { cb(std::string("Socket is disconnected.")); return; } { shutdownListeners.emplace_back([cb] { cb("Socket is disconnected."); }); } auto it = shutdownListeners.begin(); asiows::web_socket_message_header header; webSocket.async_send_message(header, asio::buffer(*buffer), _strand.wrap([self, buffer, cb, this, it] (const boost::system::error_code& error) { if (!shutdownListeners.empty()) { shutdownListeners.erase(it); } if (error) { cb(error.message()); } else { cb(std::string()); } })); }); } } extern "C" { MSCResult MSCClientSocketDestroy(MSCClientSocket socket) { return mcore::convertExceptionsToResultCode([&] { if (!socket) MSCThrow(mcore::InvalidArgumentException("socket")); auto &h = mcore::NodeClientSocket::fromHandle(socket); h->shutdown(); delete &h; }); } MSCResult MSCClientSocketReceive(MSCClientSocket socket, MSCClientSocketReceiveCallback callback, void *userdata) { return mcore::convertExceptionsToResultCode([&] { if (!socket) MSCThrow(mcore::InvalidArgumentException("socket")); auto &h = mcore::NodeClientSocket::fromHandle(socket); h->receive([callback, userdata] (const std::vector<char>& buffer, const std::string& error) { std::uint32_t ret; if (error.empty()) { ret = callback(buffer.data(), static_cast<std::uint32_t>(buffer.size()), nullptr, userdata); } else { ret = callback(nullptr, 0, error.c_str(), userdata); } if (ret) { MSCThrow(mcore::InvalidOperationException("MSCClientSocketReceiveCallback failed.")); } }); }); } MSCResult MSCClientSocketSend(MSCClientSocket socket, const void *data, std::uint32_t dataLength, MSCClientSocketSendCallback callback, void *userdata) { return mcore::convertExceptionsToResultCode([&] { if (!socket) MSCThrow(mcore::InvalidArgumentException("socket")); if (!data) MSCThrow(mcore::InvalidArgumentException("data")); auto &h = mcore::NodeClientSocket::fromHandle(socket); h->send(data, dataLength, [callback, userdata] (const std::string& error) { std::uint32_t ret; if (error.empty()) { ret = callback(nullptr, userdata); } else { ret = callback(error.c_str(), userdata); } if (ret) { MSCThrow(mcore::InvalidOperationException("MSCClientSocketSendCallback failed.")); } }); }); } }
/** * Copyright (C) 2014 yvt <[email protected]>. * * 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 "Prefix.pch" #include "NodeClientSocket.hpp" #include "Library.hpp" #include "Exceptions.hpp" using boost::format; namespace asio = boost::asio; namespace ip = boost::asio::ip; using pipes = asio::local::stream_protocol; namespace mcore { NodeClientSocket::NodeClientSocket(std::shared_ptr<Library> library, const std::string& displayName, int stream) : library(library), socket(library->ioService()), _strand(library->ioService()), webSocket(socket) { log.setChannel(displayName); socket.assign(pipes(), stream); } NodeClientSocket::~NodeClientSocket() { } void NodeClientSocket::shutdown() { auto self = shared_from_this(); bool done = false; std::mutex doneMutex; std::condition_variable doneCond; down_ = true; _strand.dispatch([self, this, &done, &doneMutex, &doneCond] { decltype(shutdownListeners) listeners; listeners.swap(shutdownListeners); for (auto& f: listeners) f(); webSocket.async_shutdown(asiows::web_socket_close_status_codes::normal_closure, "", false, _strand.wrap([self, this] (const boost::system::error_code &) { boost::system::error_code error; socket.close(error); })); std::lock_guard<std::mutex> lock(doneMutex); done = true; doneCond.notify_all(); }); std::unique_lock<std::mutex> lock(doneMutex); while (!done) { doneCond.wait(lock); } } template <class Callback> void NodeClientSocket::receive(Callback &&cb) { struct ReceiveOperation { enum class State { ReceiveMessage, ReadMessage }; State state = State::ReceiveMessage; std::shared_ptr<NodeClientSocket> socket; typename std::remove_reference<Callback>::type callback; decltype(shutdownListeners)::iterator shutdownListenersIter; ReceiveOperation(const std::shared_ptr<NodeClientSocket> &socket, Callback &&cb) : socket(socket), callback(cb) { } void done() { socket->receiving_ = false; if (!socket->shutdownListeners.empty()) { socket->shutdownListeners.erase(shutdownListenersIter); } } void operator () (const boost::system::error_code& error, std::size_t count = 0) { switch (state) { case State::ReceiveMessage: if (error) { socket->receiveBuffer.resize(0); done(); callback(socket->receiveBuffer, error.message()); } else { state = State::ReadMessage; perform(); } break; case State::ReadMessage: if (error) { socket->receiveBuffer.resize(0); done(); callback(socket->receiveBuffer, error.message()); } else if (count == 0) { socket->receiveBuffer.resize(socket->receiveBufferLen); done(); try { if (!socket->down_) callback(socket->receiveBuffer, std::string()); } catch (...) { BOOST_LOG_SEV(socket->log, LogLevel::Error) << "Error occured in packet receive handler.: " << boost::current_exception_diagnostic_information(); } } else { socket->receiveBufferLen += count; if (socket->receiveBufferLen > 65536) { // Too long. socket->receiveBuffer.resize(0); auto self = socket; socket->webSocket.async_shutdown(asiows::web_socket_close_status_codes::too_big, "Packet size is limited to 65536 bytes.", true, socket->_strand.wrap([self](const boost::system::error_code&){})); callback(socket->receiveBuffer, "Received packet is too long."); return; } socket->receiveBuffer.resize(socket->receiveBufferLen); perform(); } break; } } void perform() { switch (state) { case State::ReceiveMessage: { auto cb = callback; socket->shutdownListeners.emplace_back([cb] { std::vector<char> dummyBuffer; cb(dummyBuffer, "Socket is disconnected."); }); } shutdownListenersIter = socket->shutdownListeners.begin(); socket->webSocket.async_receive_message(std::move(*this)); break; case State::ReadMessage: socket->receiveBuffer.resize(socket->receiveBufferLen + 4096); socket->webSocket.async_read_some(asio::buffer(socket->receiveBuffer.data() + socket->receiveBufferLen, 4096), std::move(*this)); break; } } }; auto self = shared_from_this(); _strand.dispatch([self, this, cb] () mutable { if (receiving_) { cb(receiveBuffer, std::string("Cannot perform multiple reads at once.")); return; } else if (down_) { cb(receiveBuffer, std::string("Socket is disconnected.")); return; } receiving_ = true; receiveBufferLen = 0; receiveBuffer.resize(0); ReceiveOperation op(shared_from_this(), std::move(cb)); op.perform(); }); } template <class Callback> void NodeClientSocket::send(const void *data, std::size_t length, Callback &&cb) { if (length > 65536) { // Too long. (limitation of Merlion, not WebSocket) MSCThrow(InvalidArgumentException("Packet cannot be longer than 65536 bytes.", "length")); } auto self = shared_from_this(); auto buffer = std::make_shared<std::vector<char>>(length); std::memcpy(buffer->data(), data, length); _strand.dispatch([self, buffer, cb, this] () mutable { if (down_) { cb(std::string("Socket is disconnected.")); return; } { shutdownListeners.emplace_back([cb] { cb("Socket is disconnected."); }); } auto it = shutdownListeners.begin(); asiows::web_socket_message_header header; webSocket.async_send_message(header, asio::buffer(*buffer), _strand.wrap([self, buffer, cb, this, it] (const boost::system::error_code& error) { if (!shutdownListeners.empty()) { shutdownListeners.erase(it); } if (error) { cb(error.message()); } else { cb(std::string()); } })); }); } } extern "C" { MSCResult MSCClientSocketDestroy(MSCClientSocket socket) { return mcore::convertExceptionsToResultCode([&] { if (!socket) MSCThrow(mcore::InvalidArgumentException("socket")); auto &h = mcore::NodeClientSocket::fromHandle(socket); h->shutdown(); delete &h; }); } MSCResult MSCClientSocketReceive(MSCClientSocket socket, MSCClientSocketReceiveCallback callback, void *userdata) { return mcore::convertExceptionsToResultCode([&] { if (!socket) MSCThrow(mcore::InvalidArgumentException("socket")); auto &h = mcore::NodeClientSocket::fromHandle(socket); h->receive([callback, userdata] (const std::vector<char>& buffer, const std::string& error) { std::uint32_t ret; if (error.empty()) { ret = callback(buffer.data(), static_cast<std::uint32_t>(buffer.size()), nullptr, userdata); } else { ret = callback(nullptr, 0, error.c_str(), userdata); } if (ret) { MSCThrow(mcore::InvalidOperationException("MSCClientSocketReceiveCallback failed.")); } }); }); } MSCResult MSCClientSocketSend(MSCClientSocket socket, const void *data, std::uint32_t dataLength, MSCClientSocketSendCallback callback, void *userdata) { return mcore::convertExceptionsToResultCode([&] { if (!socket) MSCThrow(mcore::InvalidArgumentException("socket")); if (dataLength > 0 && !data) MSCThrow(mcore::InvalidArgumentException("data")); auto &h = mcore::NodeClientSocket::fromHandle(socket); h->send(data, dataLength, [callback, userdata] (const std::string& error) { std::uint32_t ret; if (error.empty()) { ret = callback(nullptr, userdata); } else { ret = callback(error.c_str(), userdata); } if (ret) { MSCThrow(mcore::InvalidOperationException("MSCClientSocketSendCallback failed.")); } }); }); } }
Support for sending an empty message
Support for sending an empty message
C++
apache-2.0
yvt/Merlion,yvt/Merlion,yvt/Merlion,yvt/Merlion,yvt/Merlion
e37091931cc409d3189a69eb581871c6e743832d
lib/Target/PowerPC/PPCSubtarget.cpp
lib/Target/PowerPC/PPCSubtarget.cpp
//===-- PowerPCSubtarget.cpp - PPC Subtarget Information ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PPC specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "PPCSubtarget.h" #include "PPCRegisterInfo.h" #include "PPC.h" #include "llvm/GlobalValue.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetRegistry.h" #include <cstdlib> #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "PPCGenSubtargetInfo.inc" using namespace llvm; PPCSubtarget::PPCSubtarget(const std::string &TT, const std::string &CPU, const std::string &FS, bool is64Bit) : PPCGenSubtargetInfo(TT, CPU, FS) , StackAlignment(16) , DarwinDirective(PPC::DIR_NONE) , HasMFOCRF(false) , Has64BitSupport(false) , Use64BitRegs(false) , IsPPC64(is64Bit) , HasAltivec(false) , HasFSQRT(false) , HasSTFIWX(false) , HasISEL(false) , IsBookE(false) , HasLazyResolverStubs(false) , IsJITCodeModel(false) , TargetTriple(TT) { // Determine default and user specified characteristics std::string CPUName = CPU; if (CPUName.empty()) CPUName = "generic"; #if (defined(__APPLE__) || defined(__linux__)) && \ (defined(__ppc__) || defined(__powerpc__)) if (CPUName == "generic") CPUName = sys::getHostCPUName(); #endif // Parse features string. ParseSubtargetFeatures(CPUName, FS); // Initialize scheduling itinerary for the specified CPU. InstrItins = getInstrItineraryForCPU(CPUName); // If we are generating code for ppc64, verify that options make sense. if (is64Bit) { Has64BitSupport = true; // Silently force 64-bit register use on ppc64. Use64BitRegs = true; } // If the user requested use of 64-bit regs, but the cpu selected doesn't // support it, ignore. if (use64BitRegs() && !has64BitSupport()) Use64BitRegs = false; // Set up darwin-specific properties. if (isDarwin()) HasLazyResolverStubs = true; } /// SetJITMode - This is called to inform the subtarget info that we are /// producing code for the JIT. void PPCSubtarget::SetJITMode() { // JIT mode doesn't want lazy resolver stubs, it knows exactly where // everything is. This matters for PPC64, which codegens in PIC mode without // stubs. HasLazyResolverStubs = false; // Calls to external functions need to use indirect calls IsJITCodeModel = true; } /// hasLazyResolverStub - Return true if accesses to the specified global have /// to go through a dyld lazy resolution stub. This means that an extra load /// is required to get the address of the global. bool PPCSubtarget::hasLazyResolverStub(const GlobalValue *GV, const TargetMachine &TM) const { // We never have stubs if HasLazyResolverStubs=false or if in static mode. if (!HasLazyResolverStubs || TM.getRelocationModel() == Reloc::Static) return false; // If symbol visibility is hidden, the extra load is not needed if // the symbol is definitely defined in the current translation unit. bool isDecl = GV->isDeclaration() && !GV->isMaterializable(); if (GV->hasHiddenVisibility() && !isDecl && !GV->hasCommonLinkage()) return false; return GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() || GV->hasCommonLinkage() || isDecl; } bool PPCSubtarget::enablePostRAScheduler( CodeGenOpt::Level OptLevel, TargetSubtargetInfo::AntiDepBreakMode& Mode, RegClassVector& CriticalPathRCs) const { // FIXME: It would be best to use TargetSubtargetInfo::ANTIDEP_ALL here, // but we can't because we can't reassign the cr registers. There is a // dependence between the cr register and the RLWINM instruction used // to extract its value which the anti-dependency breaker can't currently // see. Maybe we should make a late-expanded pseudo to encode this dependency. // (the relevant code is in PPCDAGToDAGISel::SelectSETCC) Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL; CriticalPathRCs.clear(); if (isPPC64()) CriticalPathRCs.push_back(&PPC::G8RCRegClass); else CriticalPathRCs.push_back(&PPC::GPRCRegClass); CriticalPathRCs.push_back(&PPC::F8RCRegClass); CriticalPathRCs.push_back(&PPC::VRRCRegClass); return OptLevel >= CodeGenOpt::Default; }
//===-- PowerPCSubtarget.cpp - PPC Subtarget Information ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PPC specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "PPCSubtarget.h" #include "PPCRegisterInfo.h" #include "PPC.h" #include "llvm/GlobalValue.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetRegistry.h" #include <cstdlib> #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "PPCGenSubtargetInfo.inc" using namespace llvm; PPCSubtarget::PPCSubtarget(const std::string &TT, const std::string &CPU, const std::string &FS, bool is64Bit) : PPCGenSubtargetInfo(TT, CPU, FS) , StackAlignment(16) , DarwinDirective(PPC::DIR_NONE) , HasMFOCRF(false) , Has64BitSupport(false) , Use64BitRegs(false) , IsPPC64(is64Bit) , HasAltivec(false) , HasFSQRT(false) , HasSTFIWX(false) , HasISEL(false) , IsBookE(false) , HasLazyResolverStubs(false) , IsJITCodeModel(false) , TargetTriple(TT) { // Determine default and user specified characteristics std::string CPUName = CPU; if (CPUName.empty()) CPUName = "generic"; #if (defined(__APPLE__) || defined(__linux__)) && \ (defined(__ppc__) || defined(__powerpc__)) if (CPUName == "generic") CPUName = sys::getHostCPUName(); #endif // Parse features string. ParseSubtargetFeatures(CPUName, FS); // Initialize scheduling itinerary for the specified CPU. InstrItins = getInstrItineraryForCPU(CPUName); // If we are generating code for ppc64, verify that options make sense. if (is64Bit) { Has64BitSupport = true; // Silently force 64-bit register use on ppc64. Use64BitRegs = true; } // If the user requested use of 64-bit regs, but the cpu selected doesn't // support it, ignore. if (use64BitRegs() && !has64BitSupport()) Use64BitRegs = false; // Set up darwin-specific properties. if (isDarwin()) HasLazyResolverStubs = true; } /// SetJITMode - This is called to inform the subtarget info that we are /// producing code for the JIT. void PPCSubtarget::SetJITMode() { // JIT mode doesn't want lazy resolver stubs, it knows exactly where // everything is. This matters for PPC64, which codegens in PIC mode without // stubs. HasLazyResolverStubs = false; // Calls to external functions need to use indirect calls IsJITCodeModel = true; } /// hasLazyResolverStub - Return true if accesses to the specified global have /// to go through a dyld lazy resolution stub. This means that an extra load /// is required to get the address of the global. bool PPCSubtarget::hasLazyResolverStub(const GlobalValue *GV, const TargetMachine &TM) const { // We never have stubs if HasLazyResolverStubs=false or if in static mode. if (!HasLazyResolverStubs || TM.getRelocationModel() == Reloc::Static) return false; // If symbol visibility is hidden, the extra load is not needed if // the symbol is definitely defined in the current translation unit. bool isDecl = GV->isDeclaration() && !GV->isMaterializable(); if (GV->hasHiddenVisibility() && !isDecl && !GV->hasCommonLinkage()) return false; return GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() || GV->hasCommonLinkage() || isDecl; } bool PPCSubtarget::enablePostRAScheduler( CodeGenOpt::Level OptLevel, TargetSubtargetInfo::AntiDepBreakMode& Mode, RegClassVector& CriticalPathRCs) const { // FIXME: It would be best to use TargetSubtargetInfo::ANTIDEP_ALL here, // but we can't because we can't reassign the cr registers. There is a // dependence between the cr register and the RLWINM instruction used // to extract its value which the anti-dependency breaker can't currently // see. Maybe we should make a late-expanded pseudo to encode this dependency. // (the relevant code is in PPCDAGToDAGISel::SelectSETCC) Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL; CriticalPathRCs.clear(); if (isPPC64()) CriticalPathRCs.push_back(&PPC::G8RCRegClass); else CriticalPathRCs.push_back(&PPC::GPRCRegClass); CriticalPathRCs.push_back(&PPC::F8RCRegClass); CriticalPathRCs.push_back(&PPC::VRRCRegClass); return OptLevel >= CodeGenOpt::Default; }
test commit / whitespace
test commit / whitespace git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@165233 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm
020ea75f8d61fce949857aaa11bc9913fc144371
include/stack.hpp
include/stack.hpp
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> #include <thread> #include <mutex> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0){} auto bitset::set(size_t index)->void { if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; } else throw("bad_index"); } auto bitset::reset(size_t index)->void { if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; } else throw("bad_index"); } auto bitset::test(size_t index)->bool { if (index >= 0 && index < size_) return !ptr_[index]; else throw("bad_index"); } auto bitset::size()->size_t{ return size_; } auto bitset::counter()->size_t{ return counter_; } template <typename T> class allocator{ public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; auto swap(allocator & other) /*noexcept*/ -> void; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; size_t count_; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template<typename T> allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size)), count_(0) {} template<typename T> allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) { for (size_t i = 0; i < other.count_; i++) if(map_->test(i)) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator(){ if (this->count() > 0) { destroy(ptr_, ptr_ + size_); } operator delete(ptr_); } template<typename T> auto allocator<T>::resize()->void{ allocator<T> al(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; ++i) if (al.map_->test(i)) al.construct(al.get() + i, ptr_[i]); al.swap(*this); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void{ if (ptr >= ptr_&&ptr < ptr_ + size_){ new(ptr)T(value); map_->set(ptr - ptr_); ++count_; } else { throw("error"); } } template<typename T> auto allocator<T>::destroy(T* ptr)->void{ if (!map_->test(ptr - ptr_) && ptr >= ptr_&&ptr <= ptr_ + this->count()) { ptr->~T(); map_->reset(ptr - ptr_); --count_; } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t{ return count_; } template<typename T> auto allocator<T>::full() const -> bool { return (map_->counter() == size_); } template<typename T> auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); } template<typename T> auto allocator<T>::destroy(T * first, T * last)->void{ if (first >= ptr_&&last <= ptr_ + this->count()) for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::swap(allocator & other)->void{ std::swap(ptr_, other.ptr_); std::swap(size_, other.size_); std::swap(map_, other.map_); std::swap(count_, other.count_); } template <typename T> class stack { public: explicit stack(size_t size = 0); stack(stack const & other); /*strong*/ auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> std::shared_ptr<T>; //auto top()const -> const T&; private: allocator<T> allocator_; auto throw_is_empty()/*strong*/ const -> void; mutable std::mutex m; }; template <typename T> stack<T>::stack(size_t size) : allocator_(size), m() {}; template <typename T> stack<T>::stack(stack const & other) : allocator_(0), m() { std::lock_guard<std::mutex> locker2(other.m); allocator_.swap(allocator<T>(other.allocator_)); } template <typename T> auto stack<T>::operator=(const stack &other)->stack& { if (this != &other) { std::lock(m, other.m); std::lock_guard<std::mutex> locker1(m, std::adopt_lock); std::lock_guard<std::mutex> locker2(other.m, std::adopt_lock); (allocator<T>(other.allocator_)).swap(allocator_); } return *this; } template<typename T> auto stack<T>::empty() const->bool { std::lock_guard<std::mutex> locker(m); return (allocator_.count() == 0); } template <typename T> auto stack<T>::count() const ->size_t { std::lock_guard<std::mutex> lockerk(m); return allocator_.count(); } template <typename T> auto stack<T>::push(T const &val)->void { std::lock_guard<std::mutex> locker(m); if (allocator_.full()) { allocator_.resize(); } allocator_.construct(allocator_.get() + allocator_.count(), val); } template <typename T> auto stack<T>::pop()->std::shared_ptr<T> { std::lock_guard<std::mutex> locker(m); if (allocator_.count() == 0) throw_is_empty(); std::shared_ptr<T> top_(std::make_shared<T>(std::move(allocator_.get()[allocator_.count() - 1]))); allocator_.destroy(allocator_.get() + allocator_.count() - 1); return top_; } template <typename T> auto stack<T>::throw_is_empty()const->void { std::lock_guard<std::mutex> lk(m); throw("EMPTY!"); } #endif
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> #include <thread> #include <mutex> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0){} auto bitset::set(size_t index)->void { if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; } else throw("bad_index"); } auto bitset::reset(size_t index)->void { if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; } else throw("bad_index"); } auto bitset::test(size_t index)->bool { if (index >= 0 && index < size_) return !ptr_[index]; else throw("bad_index"); } auto bitset::size()->size_t{ return size_; } auto bitset::counter()->size_t{ return counter_; } template <typename T> class allocator{ public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; auto swap(allocator & other) /*noexcept*/ -> void; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; size_t count_; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template<typename T> allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size)), count_(0) {} template<typename T> allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) { for (size_t i = 0; i < other.count_; i++) if(map_->test(i)) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator(){ if (this->count() > 0) { destroy(ptr_, ptr_ + size_); } operator delete(ptr_); } template<typename T> auto allocator<T>::resize()->void{ allocator<T> al(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; ++i) if (al.map_->test(i)) al.construct(al.get() + i, ptr_[i]); al.swap(*this); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void{ if (ptr >= ptr_&&ptr < ptr_ + size_){ new(ptr)T(value); map_->set(ptr - ptr_); ++count_; } else { throw("error"); } } template<typename T> auto allocator<T>::destroy(T* ptr)->void{ if (!map_->test(ptr - ptr_) && ptr >= ptr_&&ptr <= ptr_ + this->count()) { ptr->~T(); map_->reset(ptr - ptr_); --count_; } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t{ return count_; } template<typename T> auto allocator<T>::full() const -> bool { return (map_->counter() == size_); } template<typename T> auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); } template<typename T> auto allocator<T>::destroy(T * first, T * last)->void{ if (first >= ptr_&&last <= ptr_ + this->count()) for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::swap(allocator & other)->void{ std::swap(ptr_, other.ptr_); std::swap(size_, other.size_); std::swap(map_, other.map_); std::swap(count_, other.count_); } template <typename T> class stack { public: explicit stack(size_t size = 0); stack(stack const & other); /*strong*/ auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> std::shared_ptr<T>; private: allocator<T> allocator_; auto throw_is_empty()/*strong*/ const -> void; mutable std::mutex m; }; template <typename T> stack<T>::stack(size_t size) : allocator_(size), m() {}; template <typename T> stack<T>::stack(stack const & other) : allocator_(0), m() { std::lock_guard<std::mutex> locker2(other.m); allocator_.swap(allocator<T>(other.allocator_)); } template <typename T> auto stack<T>::operator=(const stack &other)->stack& { if (this != &other) { std::lock(m, other.m); std::lock_guard<std::mutex> locker1(m, std::adopt_lock); std::lock_guard<std::mutex> locker2(other.m, std::adopt_lock); (allocator<T>(other.allocator_)).swap(allocator_); } return *this; } template<typename T> auto stack<T>::empty() const->bool { std::lock_guard<std::mutex> locker(m); return (allocator_.count() == 0); } template <typename T> auto stack<T>::count() const ->size_t { std::lock_guard<std::mutex> lockerk(m); return allocator_.count(); } template <typename T> auto stack<T>::push(T const &val)->void { std::lock_guard<std::mutex> locker(m); if (allocator_.full()) { allocator_.resize(); } allocator_.construct(allocator_.get() + allocator_.count(), val); } template <typename T> auto stack<T>::pop()->std::shared_ptr<T> { std::lock_guard<std::mutex> locker(m); if (allocator_.count() == 0) throw_is_empty(); std::shared_ptr<T> top_(std::make_shared<T>(std::move(allocator_.get()[allocator_.count() - 1]))); allocator_.destroy(allocator_.get() + allocator_.count() - 1); return top_; } template <typename T> auto stack<T>::throw_is_empty()const->void { std::lock_guard<std::mutex> lk(m); throw("EMPTY!"); } #endif
Update stack.hpp
Update stack.hpp
C++
mit
DANTEpolaris/stack
dc48ad725e41a1e7de5723dec47ecefd9dd9d80d
Source/ArticyEditor/Private/CodeGeneration/ExpressoScriptsGenerator.cpp
Source/ArticyEditor/Private/CodeGeneration/ExpressoScriptsGenerator.cpp
// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "ExpressoScriptsGenerator.h" #include "CodeFileGenerator.h" #include "ArticyPluginSettings.h" void GenerateMethodInterface(CodeFileGenerator* header, const UArticyImportData* Data, bool bCreateBlueprintableUserMethods) { header->UInterface(CodeGenerator::GetMethodsProviderClassname(Data, true), "Blueprintable", "", [&] { header->Line("public:", false, true, -1); for(const auto method : Data->GetUserMethods()) { auto returnOrEmpty = method.GetCPPDefaultReturn(); if(!returnOrEmpty.IsEmpty()) returnOrEmpty = "return " + returnOrEmpty + ";"; header->Line(); if(bCreateBlueprintableUserMethods) { FString displayName = method.Name; if(method.bIsOverloadedFunction && method.OriginalParameterTypes.Num() > 0) displayName = FString::Printf(TEXT("%s (%s)"), *method.Name, *method.GetOriginalParametersForDisplayName()); header->Method(method.GetCPPReturnType(), method.BlueprintName, method.GetCPPParameters(), nullptr, "", true, FString::Printf(TEXT("BlueprintCallable, BlueprintNativeEvent, Category=\"Articy Methods Provider\", meta=(DisplayName=\"%s\")"), *displayName)); header->Method("virtual " + method.GetCPPReturnType(), method.BlueprintName + "_Implementation", method.GetCPPParameters(), nullptr, "", false, "", FString::Printf(TEXT("{ %s }"), *returnOrEmpty)); } else { header->Method("virtual " + method.GetCPPReturnType(), method.Name, method.GetCPPParameters(), nullptr, "", false, "", FString::Printf(TEXT("{ %s }"), *returnOrEmpty)); } } }); } void GenerateUserMethods(CodeFileGenerator* header, const UArticyImportData* Data, bool bCreateBlueprintableUserMethods) { header->Line("private:", false, true, -1); header->Line(); auto iClass = "I"+CodeGenerator::GetMethodsProviderClassname(Data, true); for(const auto method : Data->GetUserMethods()) { const bool bIsVoid = method.GetCPPReturnType() == "void"; header->Method(method.GetCPPReturnType(), method.Name, method.GetCPPParameters(), [&] { header->Line(FString::Printf(TEXT("auto methodProvider = GetUserMethodsProviderObject();"))); header->Line(FString::Printf(TEXT("if(!methodProvider) return %s;"), *method.GetCPPDefaultReturn())); const FString returnOrEmpty = bIsVoid ? TEXT("") : TEXT("return "); if(bCreateBlueprintableUserMethods) { FString args = ""; if(!method.ArgumentList.Num() == 0) { args = FString::Printf(TEXT(", %s"), *method.GetArguments()); } header->Line(FString::Printf(TEXT("%s%s::Execute_%s(methodProvider%s);"), *returnOrEmpty, *iClass, *method.BlueprintName, *args)); } else header->Line(FString::Printf(TEXT("%sCast<%s>(methodProvider)->%s(%s);"), *returnOrEmpty, *iClass, *method.Name, *method.GetArguments())); }, "", false, "", "const"); } } void GenerateExpressoScripts(CodeFileGenerator* header, const UArticyImportData* Data) { header->Line("private:", false, true, -1); header->Line(); /** * We define all the GV namespaces as (anonymous) structs again here, * so expresso scripts can just write things like: * * Namespace.Variable = value; * * See declaration of GlobalVariableRef for details. */ auto gvTypeName = CodeGenerator::GetGlobalVarsClassname(Data); for(const auto ns : Data->GetGlobalVars().Namespaces) header->Variable("mutable TWeakObjectPtr<" + ns.CppTypename + ">", ns.Namespace, "nullptr"); header->Line(); header->Method("void", "SetGV", "UArticyGlobalVariables* GV", [&] { header->Variable("auto", "gv", FString::Printf(TEXT("Cast<%s>(GV)"), *gvTypeName)); header->Line("if(ensure(gv))"); header->Block(true, [&] { header->Comment("Initialize all GV namespace references"); for(const auto ns : Data->GetGlobalVars().Namespaces) header->Line(FString::Printf(TEXT("%s = gv->%s;"), *ns.Namespace, *ns.Namespace)); }); }, "", false, "", "const override"); header->Line(); header->Method("UClass*", "GetUserMethodsProviderInterface", "", [&] { header->Line(FString::Printf(TEXT("return %s::StaticClass();"), *CodeGenerator::GetMethodsProviderClassname(Data))); }, "", false, "", "override"); header->Line(); header->Method("UObject*", "GetUserMethodsProviderObject", "", [&] { header->Line("if(UserMethodsProvider)"); header->Line(" return UserMethodsProvider;"); header->Line("if(DefaultUserMethodsProvider)"); header->Line(" return DefaultUserMethodsProvider;"); header->Line("return nullptr;"); }, "", false, "", "const"); header->Line(); header->Line("public:", false, true, -1); header->Line(); // disable "optimization cannot be applied due to function size" compile error. This error is caused by the huge constructor when all expresso // scripts are added to the collection and this pragma disables the optimizations. header->Line("#pragma warning(push)"); header->Line("#pragma warning(disable: 4883) //<disable \"optimization cannot be applied due to function size\" compile error."); header->Method("", CodeGenerator::GetExpressoScriptsClassname(Data), "", [&] { const auto fragments = Data->GetScriptFragments(); for(auto script : fragments) { if(script.OriginalFragment.IsEmpty()) continue; int cleanScriptHash = GetTypeHash(script.OriginalFragment); if(script.bIsInstruction) { header->Line(FString::Printf(TEXT("Instructions.Add(%d, [&]"), cleanScriptHash)); header->Line("{"); { header->Line(script.ParsedFragment, false, true, 1); } header->Line("});"); } else { header->Line(FString::Printf(TEXT("Conditions.Add(%d, [&]"), cleanScriptHash)); header->Line("{"); { //the fragment might be empty or contain only a comment, so we need to wrap it in //the ConditionOrTrue method header->Line("return ConditionOrTrue(", false, true, 1); //now comes the fragment (in next line and indented) header->Line(script.ParsedFragment, false, true, 2); //make sure there is a final semicolon //we put it into the next line, since the fragment might contain a line-comment header->Line(");", false, true, 1); } header->Line("});"); } } }); header->Line("#pragma warning(pop)"); } void ExpressoScriptsGenerator::GenerateCode(const UArticyImportData* Data) { // Determine if we want to make the user methods blueprintable. // (if true, we use a different naming to allow something like overloaded functions) bool bCreateBlueprintableUserMethods = UArticyPluginSettings::Get()->bCreateBlueprintTypeForScriptMethods; CodeFileGenerator(GetFilename(Data), true, [&](CodeFileGenerator* header) { header->Line("#include \"ArticyRuntime/Public/ArticyExpressoScripts.h\""); header->Line("#include \"" + CodeGenerator::GetGlobalVarsClassname(Data, true) + ".h\""); header->Line("#include \"" + CodeGenerator::GetExpressoScriptsClassname(Data, true) + ".generated.h\""); header->Line(); //========================================// GenerateMethodInterface(header, Data, bCreateBlueprintableUserMethods); header->Line(); const auto className = CodeGenerator::GetExpressoScriptsClassname(Data); header->Class(className + " : public UArticyExpressoScripts", "", true, [&] { //if script support is disabled, the class remains empty if(Data->GetSettings().set_UseScriptSupport) { GenerateUserMethods(header, Data, bCreateBlueprintableUserMethods); header->Line(); GenerateExpressoScripts(header, Data); } }, "BlueprintType, Blueprintable"); }); } FString ExpressoScriptsGenerator::GetFilename(const UArticyImportData* Data) { return CodeGenerator::GetExpressoScriptsClassname(Data, true) + ".h"; }
// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "ExpressoScriptsGenerator.h" #include "CodeFileGenerator.h" #include "ArticyPluginSettings.h" void GenerateMethodInterface(CodeFileGenerator* header, const UArticyImportData* Data, bool bCreateBlueprintableUserMethods) { header->UInterface(CodeGenerator::GetMethodsProviderClassname(Data, true), "Blueprintable", "", [&] { header->Line("public:", false, true, -1); for(const auto method : Data->GetUserMethods()) { auto returnOrEmpty = method.GetCPPDefaultReturn(); if(!returnOrEmpty.IsEmpty()) returnOrEmpty = "return " + returnOrEmpty + ";"; header->Line(); if(bCreateBlueprintableUserMethods) { FString displayName = method.Name; if(method.bIsOverloadedFunction && method.OriginalParameterTypes.Num() > 0) displayName = FString::Printf(TEXT("%s (%s)"), *method.Name, *method.GetOriginalParametersForDisplayName()); header->Method(method.GetCPPReturnType(), method.BlueprintName, method.GetCPPParameters(), nullptr, "", true, FString::Printf(TEXT("BlueprintCallable, BlueprintNativeEvent, Category=\"Articy Methods Provider\", meta=(DisplayName=\"%s\")"), *displayName)); header->Method("virtual " + method.GetCPPReturnType(), method.BlueprintName + "_Implementation", method.GetCPPParameters(), nullptr, "", false, "", FString::Printf(TEXT("{ %s }"), *returnOrEmpty)); } else { header->Method("virtual " + method.GetCPPReturnType(), method.Name, method.GetCPPParameters(), nullptr, "", false, "", FString::Printf(TEXT("{ %s }"), *returnOrEmpty)); } } }); } void GenerateUserMethods(CodeFileGenerator* header, const UArticyImportData* Data, bool bCreateBlueprintableUserMethods) { header->Line("private:", false, true, -1); header->Line(); auto iClass = "I"+CodeGenerator::GetMethodsProviderClassname(Data, true); for(const auto method : Data->GetUserMethods()) { const bool bIsVoid = method.GetCPPReturnType() == "void"; header->Method(method.GetCPPReturnType(), method.Name, method.GetCPPParameters(), [&] { header->Line(FString::Printf(TEXT("auto methodProvider = GetUserMethodsProviderObject();"))); header->Line(FString::Printf(TEXT("if(!methodProvider) return %s;"), *method.GetCPPDefaultReturn())); const FString returnOrEmpty = bIsVoid ? TEXT("") : TEXT("return "); if(bCreateBlueprintableUserMethods) { FString args = ""; if(method.ArgumentList.Num() != 0) { args = FString::Printf(TEXT(", %s"), *method.GetArguments()); } header->Line(FString::Printf(TEXT("%s%s::Execute_%s(methodProvider%s);"), *returnOrEmpty, *iClass, *method.BlueprintName, *args)); } else header->Line(FString::Printf(TEXT("%sCast<%s>(methodProvider)->%s(%s);"), *returnOrEmpty, *iClass, *method.Name, *method.GetArguments())); }, "", false, "", "const"); } } void GenerateExpressoScripts(CodeFileGenerator* header, const UArticyImportData* Data) { header->Line("private:", false, true, -1); header->Line(); /** * We define all the GV namespaces as (anonymous) structs again here, * so expresso scripts can just write things like: * * Namespace.Variable = value; * * See declaration of GlobalVariableRef for details. */ auto gvTypeName = CodeGenerator::GetGlobalVarsClassname(Data); for(const auto ns : Data->GetGlobalVars().Namespaces) header->Variable("mutable TWeakObjectPtr<" + ns.CppTypename + ">", ns.Namespace, "nullptr"); header->Line(); header->Method("void", "SetGV", "UArticyGlobalVariables* GV", [&] { header->Variable("auto", "gv", FString::Printf(TEXT("Cast<%s>(GV)"), *gvTypeName)); header->Line("if(ensure(gv))"); header->Block(true, [&] { header->Comment("Initialize all GV namespace references"); for(const auto ns : Data->GetGlobalVars().Namespaces) header->Line(FString::Printf(TEXT("%s = gv->%s;"), *ns.Namespace, *ns.Namespace)); }); }, "", false, "", "const override"); header->Line(); header->Method("UClass*", "GetUserMethodsProviderInterface", "", [&] { header->Line(FString::Printf(TEXT("return %s::StaticClass();"), *CodeGenerator::GetMethodsProviderClassname(Data))); }, "", false, "", "override"); header->Line(); header->Method("UObject*", "GetUserMethodsProviderObject", "", [&] { header->Line("if(UserMethodsProvider)"); header->Line(" return UserMethodsProvider;"); header->Line("if(DefaultUserMethodsProvider)"); header->Line(" return DefaultUserMethodsProvider;"); header->Line("return nullptr;"); }, "", false, "", "const"); header->Line(); header->Line("public:", false, true, -1); header->Line(); // disable "optimization cannot be applied due to function size" compile error. This error is caused by the huge constructor when all expresso // scripts are added to the collection and this pragma disables the optimizations. header->Line("#pragma warning(push)"); header->Line("#pragma warning(disable: 4883) //<disable \"optimization cannot be applied due to function size\" compile error."); header->Method("", CodeGenerator::GetExpressoScriptsClassname(Data), "", [&] { const auto fragments = Data->GetScriptFragments(); for(auto script : fragments) { if(script.OriginalFragment.IsEmpty()) continue; int cleanScriptHash = GetTypeHash(script.OriginalFragment); if(script.bIsInstruction) { header->Line(FString::Printf(TEXT("Instructions.Add(%d, [&]"), cleanScriptHash)); header->Line("{"); { header->Line(script.ParsedFragment, false, true, 1); } header->Line("});"); } else { header->Line(FString::Printf(TEXT("Conditions.Add(%d, [&]"), cleanScriptHash)); header->Line("{"); { //the fragment might be empty or contain only a comment, so we need to wrap it in //the ConditionOrTrue method header->Line("return ConditionOrTrue(", false, true, 1); //now comes the fragment (in next line and indented) header->Line(script.ParsedFragment, false, true, 2); //make sure there is a final semicolon //we put it into the next line, since the fragment might contain a line-comment header->Line(");", false, true, 1); } header->Line("});"); } } }); header->Line("#pragma warning(pop)"); } void ExpressoScriptsGenerator::GenerateCode(const UArticyImportData* Data) { // Determine if we want to make the user methods blueprintable. // (if true, we use a different naming to allow something like overloaded functions) bool bCreateBlueprintableUserMethods = UArticyPluginSettings::Get()->bCreateBlueprintTypeForScriptMethods; CodeFileGenerator(GetFilename(Data), true, [&](CodeFileGenerator* header) { header->Line("#include \"ArticyRuntime/Public/ArticyExpressoScripts.h\""); header->Line("#include \"" + CodeGenerator::GetGlobalVarsClassname(Data, true) + ".h\""); header->Line("#include \"" + CodeGenerator::GetExpressoScriptsClassname(Data, true) + ".generated.h\""); header->Line(); //========================================// GenerateMethodInterface(header, Data, bCreateBlueprintableUserMethods); header->Line(); const auto className = CodeGenerator::GetExpressoScriptsClassname(Data); header->Class(className + " : public UArticyExpressoScripts", "", true, [&] { //if script support is disabled, the class remains empty if(Data->GetSettings().set_UseScriptSupport) { GenerateUserMethods(header, Data, bCreateBlueprintableUserMethods); header->Line(); GenerateExpressoScripts(header, Data); } }, "BlueprintType, Blueprintable"); }); } FString ExpressoScriptsGenerator::GetFilename(const UArticyImportData* Data) { return CodeGenerator::GetExpressoScriptsClassname(Data, true) + ".h"; }
Fix according to marketplace feedback.
Fix according to marketplace feedback.
C++
mit
ArticySoftware/ArticyImporterForUnreal,ArticySoftware/ArticyImporterForUnreal,ArticySoftware/ArticyImporterForUnreal
ff2c3ac850b0bc3d894880ea3a007c1964088b38
src/qblowfish.cpp
src/qblowfish.cpp
/* This file is part of QBlowfish and is licensed under the MIT License Copyright 2012 Roopesh Chander <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "qblowfish.h" #include "qblowfish_p.h" #include <QtEndian> #include <QDebug> QBlowfish::QBlowfish(const QByteArray &key) : m_key(key) , m_initialized(false) , m_paddingEnabled(false) { } void QBlowfish::setPaddingEnabled(bool enabled) { m_paddingEnabled = enabled; } bool QBlowfish::paddingEnabled() const { return m_paddingEnabled; } QByteArray QBlowfish::encrypted(const QByteArray &_clearText) { QByteArray clearText(_clearText); if (clearText.isEmpty()) { return QByteArray(); } if (paddingEnabled()) { // Add padding as per PKCS5 // Ref: RFC 5652 http://tools.ietf.org/html/rfc5652#section-6.3 quint8 paddingLength = 8 - (clearText.size() % 8); if (paddingLength == 0) { paddingLength = 8; } QByteArray paddingBa(paddingLength, static_cast<char>(paddingLength)); clearText.append(paddingBa); } else { if (clearText.size() % 8 != 0) { qWarning("Cannot encrypt. Clear-text length is not a multiple of 8 and padding is not enabled."); return QByteArray(); } } Q_ASSERT(clearText.size() % 8 == 0); if ((clearText.size() % 8 == 0) && init()) { QByteArray copyBa(clearText.constData(), clearText.size()); for (int i = 0; i < clearText.size(); i += 8) { coreEncrypt(copyBa.data() + i); } return copyBa; } return QByteArray(); } QByteArray QBlowfish::decrypted(const QByteArray &cipherText) { if (cipherText.isEmpty()) { return QByteArray(); } Q_ASSERT(cipherText.size() % 8 == 0); if ((cipherText.size() % 8 == 0) && init()) { QByteArray copyBa(cipherText.constData(), cipherText.size()); for (int i = 0; i < cipherText.size(); i += 8) { coreDecrypt(copyBa.data() + i); } if (paddingEnabled()) { // Remove padding as per PKCS5 quint8 paddingLength = static_cast<quint8>(copyBa.right(1).at(0)); QByteArray paddingBa(paddingLength, static_cast<char>(paddingLength)); if (copyBa.right(paddingLength) == paddingBa) { return copyBa.left(copyBa.length() - paddingLength); } return QByteArray(); } return copyBa; } return QByteArray(); } /* Core encryption code follows. This is an implementation of the Blowfish algorithm as described at: http://www.schneier.com/paper-blowfish-fse.html */ bool QBlowfish::init() { if (m_initialized) { return true; } if (m_key.isEmpty()) { qWarning("Cannot init. Key is empty."); return false; } m_sbox1 = QByteArray::fromHex(QByteArray::fromRawData(sbox0, SBOX_SIZE_BYTES * 2)); m_sbox2 = QByteArray::fromHex(QByteArray::fromRawData(sbox1, SBOX_SIZE_BYTES * 2)); m_sbox3 = QByteArray::fromHex(QByteArray::fromRawData(sbox2, SBOX_SIZE_BYTES * 2)); m_sbox4 = QByteArray::fromHex(QByteArray::fromRawData(sbox3, SBOX_SIZE_BYTES * 2)); m_parray = QByteArray::fromHex(QByteArray::fromRawData(parray, PARRAY_SIZE_BYTES * 2)); const QByteArray &key = m_key; int keyLength = key.length(); for (int i = 0; i < PARRAY_SIZE_BYTES; i++) { m_parray[i] = static_cast<char>(static_cast<quint8>(m_parray[i]) ^ static_cast<quint8>(key[i % keyLength])); } char seed[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // Update p-array for (int i = 0; i < (PARRAY_SIZE_BYTES / 4); i += 2) { coreEncrypt(seed); for (int j = 0; j < 8; j++) { // P1 = xL; P2 = xR m_parray[i * 4 + j] = seed[j]; } } // Update s-boxes for (int sboxIndex = 1; sboxIndex <= 4; sboxIndex++) { QByteArray *sbox = 0; switch (sboxIndex) { case 1: sbox = &m_sbox1; break; case 2: sbox = &m_sbox2; break; case 3: sbox = &m_sbox3; break; case 4: sbox = &m_sbox4; break; default: Q_ASSERT(false); } Q_ASSERT(sbox != 0); for (int i = 0; i < (SBOX_SIZE_BYTES / 4); i += 2) { coreEncrypt(seed); for (int j = 0; j < 8; j++) { // S1,1 = xL; S1,2 = xR sbox->operator[](i * 4 + j) = seed[j]; } } } m_initialized = true; return true; } void QBlowfish::coreEncrypt(char *x) // encrypts 8 bytes pointed to by x, result is written to the same location { // Divide x into two 32-bit halves: xL, xR char *xL = x; char *xR = x + 4; uchar f_xL_bytes[4] = { 0, 0, 0, 0 }; for (int i = 0; i < 16; i++) { // xL = xL XOR Pi for (int j = 0; j < 4; j++) { // quint8 old_xL = xL[j]; xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[i * 4 + j])); } // Divide xL into four eight-bit quarters: a, b, c, and d quint8 a = static_cast<quint8>(xL[0]); quint8 b = static_cast<quint8>(xL[1]); quint8 c = static_cast<quint8>(xL[2]); quint8 d = static_cast<quint8>(xL[3]); // F(xL) = ((S1,a + S2,b mod 2**32) XOR S3,c) + S4,d mod 2**32 quint32 s1a = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox1.constData() + a * 4)); quint32 s2b = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox2.constData() + b * 4)); quint32 s3c = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox3.constData() + c * 4)); quint32 s4d = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox4.constData() + d * 4)); quint32 f_xL = ((((s1a + s2b) & 0xffffffff) ^ s3c) + s4d) & 0xffffffff; qToBigEndian<quint32>(f_xL, f_xL_bytes); // xR = F(xL) XOR xR for (int j = 0; j < 4; j++) { xR[j] = static_cast<char>(static_cast<quint8>(f_xL_bytes[j]) ^ static_cast<quint8>(xR[j])); } // Swap xL and xR, but not in the last iteration if (i != 15) { for (int j = 0; j < 4; j++) { char temp = xL[j]; xL[j] = xR[j]; xR[j] = temp; } } } // xR = xR XOR P17 // xL = xL XOR P18 for (int j = 0; j < 4; j++) { xR[j] = static_cast<char>(static_cast<quint8>(xR[j]) ^ static_cast<quint8>(m_parray[16 * 4 + j])); xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[17 * 4 + j])); } } void QBlowfish::coreDecrypt(char *x) // decrypts 8 bytes pointed to by x, result is written to the same location { // Divide x into two 32-bit halves: xL, xR char *xL = x; char *xR = x + 4; uchar f_xL_bytes[4] = { 0, 0, 0, 0 }; // xL = xL XOR P18 // xR = xR XOR P17 for (int j = 0; j < 4; j++) { xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[17 * 4 + j])); xR[j] = static_cast<char>(static_cast<quint8>(xR[j]) ^ static_cast<quint8>(m_parray[16 * 4 + j])); } for (int i = 15; i >= 0; i--) { // Swap xL and xR, but not in the first iteration if (i != 15) { for (int j = 0; j < 4; j++) { char temp = xL[j]; xL[j] = xR[j]; xR[j] = temp; } } // Divide xL into four eight-bit quarters: a, b, c, and d quint8 a = static_cast<quint8>(xL[0]); quint8 b = static_cast<quint8>(xL[1]); quint8 c = static_cast<quint8>(xL[2]); quint8 d = static_cast<quint8>(xL[3]); // F(xL) = ((S1,a + S2,b mod 2**32) XOR S3,c) + S4,d mod 2**32 quint32 s1a = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox1.constData() + a * 4)); quint32 s2b = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox2.constData() + b * 4)); quint32 s3c = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox3.constData() + c * 4)); quint32 s4d = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox4.constData() + d * 4)); quint32 f_xL = ((((s1a + s2b) & 0xffffffff) ^ s3c) + s4d) & 0xffffffff; qToBigEndian<quint32>(f_xL, f_xL_bytes); // xR = F(xL) XOR xR for (int j = 0; j < 4; j++) { xR[j] = static_cast<char>(static_cast<quint8>(f_xL_bytes[j]) ^ static_cast<quint8>(xR[j])); } // xL = xL XOR Pi for (int j = 0; j < 4; j++) { xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[i * 4 + j])); } } }
/* This file is part of QBlowfish and is licensed under the MIT License Copyright (C) 2012 Roopesh Chander <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "qblowfish.h" #include "qblowfish_p.h" #include <QtEndian> #include <QDebug> QBlowfish::QBlowfish(const QByteArray &key) : m_key(key) , m_initialized(false) , m_paddingEnabled(false) { } void QBlowfish::setPaddingEnabled(bool enabled) { m_paddingEnabled = enabled; } bool QBlowfish::paddingEnabled() const { return m_paddingEnabled; } QByteArray QBlowfish::encrypted(const QByteArray &_clearText) { QByteArray clearText(_clearText); if (clearText.isEmpty()) { return QByteArray(); } if (paddingEnabled()) { // Add padding as per PKCS5 // Ref: RFC 5652 http://tools.ietf.org/html/rfc5652#section-6.3 quint8 paddingLength = 8 - (clearText.size() % 8); if (paddingLength == 0) { paddingLength = 8; } QByteArray paddingBa(paddingLength, static_cast<char>(paddingLength)); clearText.append(paddingBa); } else { if (clearText.size() % 8 != 0) { qWarning("Cannot encrypt. Clear-text length is not a multiple of 8 and padding is not enabled."); return QByteArray(); } } Q_ASSERT(clearText.size() % 8 == 0); if ((clearText.size() % 8 == 0) && init()) { QByteArray copyBa(clearText.constData(), clearText.size()); for (int i = 0; i < clearText.size(); i += 8) { coreEncrypt(copyBa.data() + i); } return copyBa; } return QByteArray(); } QByteArray QBlowfish::decrypted(const QByteArray &cipherText) { if (cipherText.isEmpty()) { return QByteArray(); } Q_ASSERT(cipherText.size() % 8 == 0); if ((cipherText.size() % 8 == 0) && init()) { QByteArray copyBa(cipherText.constData(), cipherText.size()); for (int i = 0; i < cipherText.size(); i += 8) { coreDecrypt(copyBa.data() + i); } if (paddingEnabled()) { // Remove padding as per PKCS5 quint8 paddingLength = static_cast<quint8>(copyBa.right(1).at(0)); QByteArray paddingBa(paddingLength, static_cast<char>(paddingLength)); if (copyBa.right(paddingLength) == paddingBa) { return copyBa.left(copyBa.length() - paddingLength); } return QByteArray(); } return copyBa; } return QByteArray(); } /* Core encryption code follows. This is an implementation of the Blowfish algorithm as described at: http://www.schneier.com/paper-blowfish-fse.html */ bool QBlowfish::init() { if (m_initialized) { return true; } if (m_key.isEmpty()) { qWarning("Cannot init. Key is empty."); return false; } m_sbox1 = QByteArray::fromHex(QByteArray::fromRawData(sbox0, SBOX_SIZE_BYTES * 2)); m_sbox2 = QByteArray::fromHex(QByteArray::fromRawData(sbox1, SBOX_SIZE_BYTES * 2)); m_sbox3 = QByteArray::fromHex(QByteArray::fromRawData(sbox2, SBOX_SIZE_BYTES * 2)); m_sbox4 = QByteArray::fromHex(QByteArray::fromRawData(sbox3, SBOX_SIZE_BYTES * 2)); m_parray = QByteArray::fromHex(QByteArray::fromRawData(parray, PARRAY_SIZE_BYTES * 2)); const QByteArray &key = m_key; int keyLength = key.length(); for (int i = 0; i < PARRAY_SIZE_BYTES; i++) { m_parray[i] = static_cast<char>(static_cast<quint8>(m_parray[i]) ^ static_cast<quint8>(key[i % keyLength])); } char seed[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // Update p-array for (int i = 0; i < (PARRAY_SIZE_BYTES / 4); i += 2) { coreEncrypt(seed); for (int j = 0; j < 8; j++) { // P1 = xL; P2 = xR m_parray[i * 4 + j] = seed[j]; } } // Update s-boxes for (int sboxIndex = 1; sboxIndex <= 4; sboxIndex++) { QByteArray *sbox = 0; switch (sboxIndex) { case 1: sbox = &m_sbox1; break; case 2: sbox = &m_sbox2; break; case 3: sbox = &m_sbox3; break; case 4: sbox = &m_sbox4; break; default: Q_ASSERT(false); } Q_ASSERT(sbox != 0); for (int i = 0; i < (SBOX_SIZE_BYTES / 4); i += 2) { coreEncrypt(seed); for (int j = 0; j < 8; j++) { // S1,1 = xL; S1,2 = xR sbox->operator[](i * 4 + j) = seed[j]; } } } m_initialized = true; return true; } void QBlowfish::coreEncrypt(char *x) // encrypts 8 bytes pointed to by x, result is written to the same location { // Divide x into two 32-bit halves: xL, xR char *xL = x; char *xR = x + 4; uchar f_xL_bytes[4] = { 0, 0, 0, 0 }; for (int i = 0; i < 16; i++) { // xL = xL XOR Pi for (int j = 0; j < 4; j++) { // quint8 old_xL = xL[j]; xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[i * 4 + j])); } // Divide xL into four eight-bit quarters: a, b, c, and d quint8 a = static_cast<quint8>(xL[0]); quint8 b = static_cast<quint8>(xL[1]); quint8 c = static_cast<quint8>(xL[2]); quint8 d = static_cast<quint8>(xL[3]); // F(xL) = ((S1,a + S2,b mod 2**32) XOR S3,c) + S4,d mod 2**32 quint32 s1a = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox1.constData() + a * 4)); quint32 s2b = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox2.constData() + b * 4)); quint32 s3c = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox3.constData() + c * 4)); quint32 s4d = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox4.constData() + d * 4)); quint32 f_xL = ((((s1a + s2b) & 0xffffffff) ^ s3c) + s4d) & 0xffffffff; qToBigEndian<quint32>(f_xL, f_xL_bytes); // xR = F(xL) XOR xR for (int j = 0; j < 4; j++) { xR[j] = static_cast<char>(static_cast<quint8>(f_xL_bytes[j]) ^ static_cast<quint8>(xR[j])); } // Swap xL and xR, but not in the last iteration if (i != 15) { for (int j = 0; j < 4; j++) { char temp = xL[j]; xL[j] = xR[j]; xR[j] = temp; } } } // xR = xR XOR P17 // xL = xL XOR P18 for (int j = 0; j < 4; j++) { xR[j] = static_cast<char>(static_cast<quint8>(xR[j]) ^ static_cast<quint8>(m_parray[16 * 4 + j])); xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[17 * 4 + j])); } } void QBlowfish::coreDecrypt(char *x) // decrypts 8 bytes pointed to by x, result is written to the same location { // Divide x into two 32-bit halves: xL, xR char *xL = x; char *xR = x + 4; uchar f_xL_bytes[4] = { 0, 0, 0, 0 }; // xL = xL XOR P18 // xR = xR XOR P17 for (int j = 0; j < 4; j++) { xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[17 * 4 + j])); xR[j] = static_cast<char>(static_cast<quint8>(xR[j]) ^ static_cast<quint8>(m_parray[16 * 4 + j])); } for (int i = 15; i >= 0; i--) { // Swap xL and xR, but not in the first iteration if (i != 15) { for (int j = 0; j < 4; j++) { char temp = xL[j]; xL[j] = xR[j]; xR[j] = temp; } } // Divide xL into four eight-bit quarters: a, b, c, and d quint8 a = static_cast<quint8>(xL[0]); quint8 b = static_cast<quint8>(xL[1]); quint8 c = static_cast<quint8>(xL[2]); quint8 d = static_cast<quint8>(xL[3]); // F(xL) = ((S1,a + S2,b mod 2**32) XOR S3,c) + S4,d mod 2**32 quint32 s1a = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox1.constData() + a * 4)); quint32 s2b = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox2.constData() + b * 4)); quint32 s3c = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox3.constData() + c * 4)); quint32 s4d = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_sbox4.constData() + d * 4)); quint32 f_xL = ((((s1a + s2b) & 0xffffffff) ^ s3c) + s4d) & 0xffffffff; qToBigEndian<quint32>(f_xL, f_xL_bytes); // xR = F(xL) XOR xR for (int j = 0; j < 4; j++) { xR[j] = static_cast<char>(static_cast<quint8>(f_xL_bytes[j]) ^ static_cast<quint8>(xR[j])); } // xL = xL XOR Pi for (int j = 0; j < 4; j++) { xL[j] = static_cast<char>(static_cast<quint8>(xL[j]) ^ static_cast<quint8>(m_parray[i * 4 + j])); } } }
Remove special char - Qt Creator on Linux doesn't seem to like it
Remove special char - Qt Creator on Linux doesn't seem to like it
C++
mit
roop/qblowfish,roop/qblowfish
00be69755160399756152eed8f1fbbcba8ec115a
test/core/end2end/tests/keepalive_timeout.cc
test/core/end2end/tests/keepalive_timeout.cc
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "test/core/end2end/end2end_tests.h" #include <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/ext/transport/chttp2/transport/frame_ping.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/useful.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "test/core/end2end/cq_verifier.h" static void* tag(intptr_t t) { return (void*)t; } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, grpc_channel_args* client_args, grpc_channel_args* server_args) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "%s/%s", test_name, config.name); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_server(grpc_end2end_test_fixture* f) { if (!f->server) return; grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000)); GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000), five_seconds_from_now(), nullptr) .type == GRPC_OP_COMPLETE); grpc_server_destroy(f->server); f->server = nullptr; } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { shutdown_server(f); shutdown_client(f); grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); grpc_completion_queue_destroy(f->shutdown_cq); } /* Client sends a request, server replies with a payload, then waits for the keepalive watchdog timeouts before returning status. */ static void test_keepalive_timeout(grpc_end2end_test_config config) { grpc_call* c; grpc_call* s; grpc_slice response_payload_slice = grpc_slice_from_copied_string("hello world"); grpc_byte_buffer* response_payload = grpc_raw_byte_buffer_create(&response_payload_slice, 1); grpc_arg keepalive_arg_elems[3]; keepalive_arg_elems[0].type = GRPC_ARG_INTEGER; keepalive_arg_elems[0].key = const_cast<char*>(GRPC_ARG_KEEPALIVE_TIME_MS); keepalive_arg_elems[0].value.integer = 3500; keepalive_arg_elems[1].type = GRPC_ARG_INTEGER; keepalive_arg_elems[1].key = const_cast<char*>(GRPC_ARG_KEEPALIVE_TIMEOUT_MS); keepalive_arg_elems[1].value.integer = 0; keepalive_arg_elems[2].type = GRPC_ARG_INTEGER; keepalive_arg_elems[2].key = const_cast<char*>(GRPC_ARG_HTTP2_BDP_PROBE); keepalive_arg_elems[2].value.integer = 0; grpc_channel_args keepalive_args = {GPR_ARRAY_SIZE(keepalive_arg_elems), keepalive_arg_elems}; grpc_end2end_test_fixture f = begin_test(config, "keepalive_timeout", &keepalive_args, nullptr); cq_verifier* cqv = cq_verifier_create(f.cq); grpc_op ops[6]; grpc_op* op; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_metadata_array request_metadata_recv; grpc_byte_buffer* response_payload_recv = nullptr; grpc_call_details call_details; grpc_status_code status; grpc_call_error error; grpc_slice details; /* Disable ping ack to trigger the keepalive timeout */ grpc_set_disable_ping_ack(true); gpr_timespec deadline = five_seconds_from_now(); c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq, grpc_slice_from_static_string("/foo"), nullptr, deadline, nullptr); GPR_ASSERT(c); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload_recv; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101))); CQ_EXPECT_COMPLETION(cqv, tag(101), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(102), 1); CQ_EXPECT_COMPLETION(cqv, tag(1), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(3), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(3), 1); cq_verify(cqv); char* details_str = grpc_slice_to_c_string(details); char* method_str = grpc_slice_to_c_string(call_details.method); GPR_ASSERT(status == GRPC_STATUS_INTERNAL); GPR_ASSERT(0 == grpc_slice_str_cmp(details, "keepalive watchdog timeout")); GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo")); gpr_free(details_str); gpr_free(method_str); grpc_slice_unref(details); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); grpc_call_unref(c); grpc_call_unref(s); cq_verifier_destroy(cqv); grpc_byte_buffer_destroy(response_payload); grpc_byte_buffer_destroy(response_payload_recv); end_test(&f); config.tear_down_data(&f); } void keepalive_timeout(grpc_end2end_test_config config) { test_keepalive_timeout(config); } void keepalive_timeout_pre_init(void) {}
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "test/core/end2end/end2end_tests.h" #include <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/ext/transport/chttp2/transport/frame_ping.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/useful.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "test/core/end2end/cq_verifier.h" static void* tag(intptr_t t) { return (void*)t; } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, grpc_channel_args* client_args, grpc_channel_args* server_args) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "%s/%s", test_name, config.name); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_server(grpc_end2end_test_fixture* f) { if (!f->server) return; grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000)); GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000), five_seconds_from_now(), nullptr) .type == GRPC_OP_COMPLETE); grpc_server_destroy(f->server); f->server = nullptr; } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { shutdown_server(f); shutdown_client(f); grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); grpc_completion_queue_destroy(f->shutdown_cq); } /* Client sends a request, server replies with a payload, then waits for the keepalive watchdog timeouts before returning status. */ static void test_keepalive_timeout(grpc_end2end_test_config config) { grpc_call* c; grpc_call* s; grpc_slice response_payload_slice = grpc_slice_from_copied_string("hello world"); grpc_byte_buffer* response_payload = grpc_raw_byte_buffer_create(&response_payload_slice, 1); grpc_arg keepalive_arg_elems[3]; keepalive_arg_elems[0].type = GRPC_ARG_INTEGER; keepalive_arg_elems[0].key = const_cast<char*>(GRPC_ARG_KEEPALIVE_TIME_MS); keepalive_arg_elems[0].value.integer = 3500; keepalive_arg_elems[1].type = GRPC_ARG_INTEGER; keepalive_arg_elems[1].key = const_cast<char*>(GRPC_ARG_KEEPALIVE_TIMEOUT_MS); keepalive_arg_elems[1].value.integer = 0; keepalive_arg_elems[2].type = GRPC_ARG_INTEGER; keepalive_arg_elems[2].key = const_cast<char*>(GRPC_ARG_HTTP2_BDP_PROBE); keepalive_arg_elems[2].value.integer = 0; grpc_channel_args keepalive_args = {GPR_ARRAY_SIZE(keepalive_arg_elems), keepalive_arg_elems}; grpc_end2end_test_fixture f = begin_test(config, "keepalive_timeout", &keepalive_args, nullptr); cq_verifier* cqv = cq_verifier_create(f.cq); grpc_op ops[6]; grpc_op* op; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_metadata_array request_metadata_recv; grpc_byte_buffer* response_payload_recv = nullptr; grpc_call_details call_details; grpc_status_code status; grpc_call_error error; grpc_slice details; /* Disable ping ack to trigger the keepalive timeout */ grpc_set_disable_ping_ack(true); gpr_timespec deadline = five_seconds_from_now(); c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq, grpc_slice_from_static_string("/foo"), nullptr, deadline, nullptr); GPR_ASSERT(c); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload_recv; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101))); CQ_EXPECT_COMPLETION(cqv, tag(101), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(102), 1); CQ_EXPECT_COMPLETION(cqv, tag(1), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(3), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(3), 1); cq_verify(cqv); char* details_str = grpc_slice_to_c_string(details); char* method_str = grpc_slice_to_c_string(call_details.method); GPR_ASSERT(status == GRPC_STATUS_UNAVAILABLE); GPR_ASSERT(0 == grpc_slice_str_cmp(details, "keepalive watchdog timeout")); GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo")); gpr_free(details_str); gpr_free(method_str); grpc_slice_unref(details); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); grpc_call_unref(c); grpc_call_unref(s); cq_verifier_destroy(cqv); grpc_byte_buffer_destroy(response_payload); grpc_byte_buffer_destroy(response_payload_recv); end_test(&f); config.tear_down_data(&f); } void keepalive_timeout(grpc_end2end_test_config config) { test_keepalive_timeout(config); } void keepalive_timeout_pre_init(void) {}
Test changes
Test changes
C++
apache-2.0
vjpai/grpc,stanley-cheung/grpc,vjpai/grpc,stanley-cheung/grpc,grpc/grpc,vjpai/grpc,sreecha/grpc,sreecha/grpc,muxi/grpc,carl-mastrangelo/grpc,carl-mastrangelo/grpc,mehrdada/grpc,nicolasnoble/grpc,stanley-cheung/grpc,nicolasnoble/grpc,nicolasnoble/grpc,pszemus/grpc,grpc/grpc,pszemus/grpc,sreecha/grpc,donnadionne/grpc,sreecha/grpc,donnadionne/grpc,jtattermusch/grpc,jboeuf/grpc,donnadionne/grpc,firebase/grpc,grpc/grpc,sreecha/grpc,firebase/grpc,donnadionne/grpc,vjpai/grpc,nicolasnoble/grpc,muxi/grpc,jtattermusch/grpc,mehrdada/grpc,ctiller/grpc,sreecha/grpc,jboeuf/grpc,sreecha/grpc,muxi/grpc,grpc/grpc,nicolasnoble/grpc,sreecha/grpc,grpc/grpc,jboeuf/grpc,jtattermusch/grpc,firebase/grpc,grpc/grpc,grpc/grpc,vjpai/grpc,firebase/grpc,jboeuf/grpc,stanley-cheung/grpc,stanley-cheung/grpc,sreecha/grpc,donnadionne/grpc,jboeuf/grpc,mehrdada/grpc,jtattermusch/grpc,pszemus/grpc,ejona86/grpc,pszemus/grpc,donnadionne/grpc,jboeuf/grpc,firebase/grpc,ctiller/grpc,firebase/grpc,muxi/grpc,stanley-cheung/grpc,donnadionne/grpc,ctiller/grpc,sreecha/grpc,mehrdada/grpc,ctiller/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,jboeuf/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,mehrdada/grpc,stanley-cheung/grpc,muxi/grpc,firebase/grpc,ejona86/grpc,firebase/grpc,carl-mastrangelo/grpc,jboeuf/grpc,sreecha/grpc,mehrdada/grpc,grpc/grpc,pszemus/grpc,ejona86/grpc,jtattermusch/grpc,vjpai/grpc,nicolasnoble/grpc,jtattermusch/grpc,carl-mastrangelo/grpc,carl-mastrangelo/grpc,donnadionne/grpc,stanley-cheung/grpc,pszemus/grpc,vjpai/grpc,ejona86/grpc,muxi/grpc,jboeuf/grpc,jboeuf/grpc,muxi/grpc,mehrdada/grpc,ctiller/grpc,carl-mastrangelo/grpc,stanley-cheung/grpc,jboeuf/grpc,carl-mastrangelo/grpc,ejona86/grpc,jtattermusch/grpc,jboeuf/grpc,muxi/grpc,firebase/grpc,firebase/grpc,vjpai/grpc,jtattermusch/grpc,ejona86/grpc,pszemus/grpc,carl-mastrangelo/grpc,stanley-cheung/grpc,jtattermusch/grpc,vjpai/grpc,nicolasnoble/grpc,pszemus/grpc,donnadionne/grpc,ejona86/grpc,mehrdada/grpc,ejona86/grpc,firebase/grpc,grpc/grpc,pszemus/grpc,mehrdada/grpc,nicolasnoble/grpc,vjpai/grpc,ctiller/grpc,muxi/grpc,jtattermusch/grpc,ejona86/grpc,grpc/grpc,mehrdada/grpc,carl-mastrangelo/grpc,grpc/grpc,donnadionne/grpc,pszemus/grpc,grpc/grpc,stanley-cheung/grpc,ctiller/grpc,muxi/grpc,muxi/grpc,ctiller/grpc,ejona86/grpc,sreecha/grpc,nicolasnoble/grpc,vjpai/grpc,jtattermusch/grpc,nicolasnoble/grpc,ctiller/grpc,donnadionne/grpc,ejona86/grpc,carl-mastrangelo/grpc,nicolasnoble/grpc,mehrdada/grpc,firebase/grpc,carl-mastrangelo/grpc,vjpai/grpc,mehrdada/grpc,stanley-cheung/grpc,jtattermusch/grpc,pszemus/grpc,muxi/grpc,ctiller/grpc,pszemus/grpc,donnadionne/grpc
8fe8321285e6ca79094a90ef8e46c4cbc586beb4
content/browser/renderer_host/media/desktop_capture_device_ash_unittest.cc
content/browser/renderer_host/media/desktop_capture_device_ash_unittest.cc
// Copyright 2013 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/renderer_host/media/desktop_capture_device_ash.h" #include "base/synchronization/waitable_event.h" #include "content/browser/browser_thread_impl.h" #include "media/video/capture/video_capture_types.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/client/window_tree_client.h" #include "ui/aura/test/aura_test_helper.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::DoAll; using ::testing::Expectation; using ::testing::InvokeWithoutArgs; using ::testing::SaveArg; namespace content { namespace { const int kFrameRate = 30; class MockDeviceClient : public media::VideoCaptureDevice::Client { public: MOCK_METHOD2(ReserveOutputBuffer, scoped_refptr<Buffer>(media::VideoFrame::Format format, const gfx::Size& dimensions)); MOCK_METHOD0(OnError, void()); MOCK_METHOD7(OnIncomingCapturedFrame, void(const uint8* data, int length, base::Time timestamp, int rotation, bool flip_vert, bool flip_horiz, const media::VideoCaptureFormat& frame_format)); MOCK_METHOD5(OnIncomingCapturedBuffer, void(const scoped_refptr<Buffer>& buffer, media::VideoFrame::Format format, const gfx::Size& dimensions, base::Time timestamp, int frame_rate)); }; // Test harness that sets up a minimal environment with necessary stubs. class DesktopCaptureDeviceAshTest : public testing::Test { public: DesktopCaptureDeviceAshTest() : browser_thread_for_ui_(BrowserThread::UI, &message_loop_) {} virtual ~DesktopCaptureDeviceAshTest() {} protected: virtual void SetUp() OVERRIDE { helper_.reset(new aura::test::AuraTestHelper(&message_loop_)); helper_->SetUp(); // We need a window to cover desktop area so that DesktopCaptureDeviceAsh // can use gfx::NativeWindow::GetWindowAtScreenPoint() to locate the // root window associated with the primary display. gfx::Rect desktop_bounds = root_window()->bounds(); window_delegate_.reset(new aura::test::TestWindowDelegate()); desktop_window_.reset(new aura::Window(window_delegate_.get())); desktop_window_->Init(ui::LAYER_TEXTURED); desktop_window_->SetBounds(desktop_bounds); aura::client::ParentWindowWithContext( desktop_window_.get(), root_window(), desktop_bounds); desktop_window_->Show(); } virtual void TearDown() OVERRIDE { helper_->RunAllPendingInMessageLoop(); root_window()->RemoveChild(desktop_window_.get()); desktop_window_.reset(); window_delegate_.reset(); helper_->TearDown(); } aura::Window* root_window() { return helper_->root_window(); } private: base::MessageLoopForUI message_loop_; BrowserThreadImpl browser_thread_for_ui_; scoped_ptr<aura::test::AuraTestHelper> helper_; scoped_ptr<aura::Window> desktop_window_; scoped_ptr<aura::test::TestWindowDelegate> window_delegate_; DISALLOW_COPY_AND_ASSIGN(DesktopCaptureDeviceAshTest); }; TEST_F(DesktopCaptureDeviceAshTest, StartAndStop) { DesktopMediaID source(DesktopMediaID::TYPE_SCREEN, 0); scoped_ptr<media::VideoCaptureDevice> capture_device( DesktopCaptureDeviceAsh::Create(source)); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); EXPECT_CALL(*client, OnError()).Times(0); media::VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(640, 480); capture_params.requested_format.frame_rate = kFrameRate; capture_params.requested_format.pixel_format = media::PIXEL_FORMAT_I420; capture_params.allow_resolution_change = false; capture_device->AllocateAndStart( capture_params, client.PassAs<media::VideoCaptureDevice::Client>()); capture_device->StopAndDeAllocate(); } } // namespace } // namespace content
// Copyright 2013 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/renderer_host/media/desktop_capture_device_ash.h" #include "base/synchronization/waitable_event.h" #include "content/browser/browser_thread_impl.h" #include "media/video/capture/video_capture_types.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/client/window_tree_client.h" #include "ui/aura/test/aura_test_helper.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::DoAll; using ::testing::Expectation; using ::testing::InvokeWithoutArgs; using ::testing::SaveArg; namespace content { namespace { const int kFrameRate = 30; class MockDeviceClient : public media::VideoCaptureDevice::Client { public: MOCK_METHOD2(ReserveOutputBuffer, scoped_refptr<Buffer>(media::VideoFrame::Format format, const gfx::Size& dimensions)); MOCK_METHOD0(OnError, void()); MOCK_METHOD7(OnIncomingCapturedFrame, void(const uint8* data, int length, base::Time timestamp, int rotation, bool flip_vert, bool flip_horiz, const media::VideoCaptureFormat& frame_format)); MOCK_METHOD5(OnIncomingCapturedBuffer, void(const scoped_refptr<Buffer>& buffer, media::VideoFrame::Format format, const gfx::Size& dimensions, base::Time timestamp, int frame_rate)); }; // Test harness that sets up a minimal environment with necessary stubs. class DesktopCaptureDeviceAshTest : public testing::Test { public: DesktopCaptureDeviceAshTest() : browser_thread_for_ui_(BrowserThread::UI, &message_loop_) {} virtual ~DesktopCaptureDeviceAshTest() {} protected: virtual void SetUp() OVERRIDE { helper_.reset(new aura::test::AuraTestHelper(&message_loop_)); helper_->SetUp(); // We need a window to cover desktop area so that DesktopCaptureDeviceAsh // can use gfx::NativeWindow::GetWindowAtScreenPoint() to locate the // root window associated with the primary display. gfx::Rect desktop_bounds = root_window()->bounds(); desktop_window_.reset(new aura::Window( new aura::test::TestWindowDelegate())); desktop_window_->Init(ui::LAYER_TEXTURED); desktop_window_->SetBounds(desktop_bounds); aura::client::ParentWindowWithContext( desktop_window_.get(), root_window(), desktop_bounds); desktop_window_->Show(); } virtual void TearDown() OVERRIDE { helper_->RunAllPendingInMessageLoop(); root_window()->RemoveChild(desktop_window_.get()); desktop_window_.reset(); helper_->TearDown(); } aura::Window* root_window() { return helper_->root_window(); } private: base::MessageLoopForUI message_loop_; BrowserThreadImpl browser_thread_for_ui_; scoped_ptr<aura::test::AuraTestHelper> helper_; scoped_ptr<aura::Window> desktop_window_; DISALLOW_COPY_AND_ASSIGN(DesktopCaptureDeviceAshTest); }; TEST_F(DesktopCaptureDeviceAshTest, StartAndStop) { DesktopMediaID source(DesktopMediaID::TYPE_SCREEN, 0); scoped_ptr<media::VideoCaptureDevice> capture_device( DesktopCaptureDeviceAsh::Create(source)); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); EXPECT_CALL(*client, OnError()).Times(0); media::VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(640, 480); capture_params.requested_format.frame_rate = kFrameRate; capture_params.requested_format.pixel_format = media::PIXEL_FORMAT_I420; capture_params.allow_resolution_change = false; capture_device->AllocateAndStart( capture_params, client.PassAs<media::VideoCaptureDevice::Client>()); capture_device->StopAndDeAllocate(); } } // namespace } // namespace content
Revert 237645 "Fix memory leak in DesktopCaptureDeviceAshTest on..."
Revert 237645 "Fix memory leak in DesktopCaptureDeviceAshTest on..." DesktopCaptureApiTest.ChooseDesktopMedia still failing. > Fix memory leak in DesktopCaptureDeviceAshTest on Linux Chromium OS ASAN. > > The aura::test::TestWindowDelegate should be held in a scoped_ptr. > > [email protected] > TEST=run content_unittests locally. > BUG= > > Review URL: https://codereview.chromium.org/93123002 [email protected] Review URL: https://codereview.chromium.org/93363002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@237652 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,dednal/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Just-D/chromium-1,Jonekee/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,anirudhSK/chromium,patrickm/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,dednal/chromium.src,jaruba/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,dednal/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,patrickm/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,M4sse/chromium.src,ltilve/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,jaruba/chromium.src,littlstar/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,Just-D/chromium-1,dednal/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,ltilve/chromium,dednal/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,anirudhSK/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,dednal/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src
1d3e74a14e2fccede719cbe63ef34689bc5f33ce
src/robotskirt.cc
src/robotskirt.cc
#include <v8.h> #include <node.h> #include <node_buffer.h> #include <string> #include "markdownWrapper.hpp" using namespace std; using namespace node; using namespace v8; using namespace mkd; #define OUTPUT_UNIT 64 //////////////////////////////////////////////////////////////////////////////// // UTILITIES to ease wrapping and interfacing with V8 //////////////////////////////////////////////////////////////////////////////// // Credit: @samcday // http://sambro.is-super-awesome.com/2011/03/03/creating-a-proper-buffer-in-a-node-c-addon/ #define MAKE_FAST_BUFFER(NG_SLOW_BUFFER, NG_FAST_BUFFER) \ Local<Function> NG_JS_BUFFER = Local<Function>::Cast( \ Context::GetCurrent()->Global()->Get( \ String::New("Buffer"))); \ \ Handle<Value> NG_JS_ARGS[3] = { \ NG_SLOW_BUFFER->handle_, \ Integer::New(Buffer::Length(NG_SLOW_BUFFER)), \ Integer::New(0) \ }; \ \ NG_FAST_BUFFER = NG_JS_BUFFER->NewInstance(3, NG_JS_ARGS); // V8 exception wrapping #define V8_WRAP_START() \ HandleScope scope; \ try { #define V8_WRAP_END() \ } catch (Handle<Value> err) { \ return ThrowException(err); \ } catch (exception err) { \ return ThrowException(Exception::Error(String::New(err.what()))); \ } #define V8_WRAP_END_NR() \ } catch (Handle<Value> err) { \ ThrowException(err); \ } catch (exception err) { \ ThrowException(Exception::Error(String::New(err.what()))); \ } // Dealing with V8 persistent handles template <class T> void ClearPersistent(Persistent<T>& handle) { if (handle.IsEmpty()) return; handle.Dispose(); handle.Clear(); } template <class T> void SetPersistent(Persistent<T>& handle, Handle<T> value) { ClearPersistent<T>(handle); if (value.IsEmpty()) return; handle = Persistent<T>::New(value); } //////////////////////////////////////////////////////////////////////////////// // MODULE DECLARATION //////////////////////////////////////////////////////////////////////////////// extern "C" { void init (Handle<Object> target) { HandleScope scope; //Static functions & properties target->Set(String::NewSymbol("version"), String::New("1.0.0")); NODE_SET_METHOD(target, "markdown", markdown); NODE_SET_METHOD(target, "markdownSync", markdownSync); //Extension constants target->Set(String::NewSymbol("EXT_AUTOLINK"), Integer::New(MKDEXT_AUTOLINK)); target->Set(String::NewSymbol("EXT_FENCED_CODE"), Integer::New(MKDEXT_FENCED_CODE)); target->Set(String::NewSymbol("EXT_LAX_HTML_BLOCKS"), Integer::New(MKDEXT_LAX_HTML_BLOCKS)); target->Set(String::NewSymbol("EXT_NO_INTRA_EMPHASIS"), Integer::New(MKDEXT_NO_INTRA_EMPHASIS)); target->Set(String::NewSymbol("EXT_SPACE_HEADERS"), Integer::New(MKDEXT_SPACE_HEADERS)); target->Set(String::NewSymbol("EXT_STRIKETHROUGH"), Integer::New(MKDEXT_STRIKETHROUGH)); target->Set(String::NewSymbol("EXT_TABLES"), Integer::New(MKDEXT_TABLES)); //TODO: html renderer flags //TODO } NODE_MODULE(robotskirt, init) }
#include <v8.h> #include <node.h> #include <node_buffer.h> #include <string> #include "markdownWrapper.hpp" using namespace std; using namespace node; using namespace v8; using namespace mkd; #define OUTPUT_UNIT 64 //////////////////////////////////////////////////////////////////////////////// // UTILITIES to ease wrapping and interfacing with V8 //////////////////////////////////////////////////////////////////////////////// // Credit: @samcday // http://sambro.is-super-awesome.com/2011/03/03/creating-a-proper-buffer-in-a-node-c-addon/ #define MAKE_FAST_BUFFER(NG_SLOW_BUFFER, NG_FAST_BUFFER) \ Local<Function> NG_JS_BUFFER = Local<Function>::Cast( \ Context::GetCurrent()->Global()->Get( \ String::New("Buffer"))); \ \ Handle<Value> NG_JS_ARGS[3] = { \ NG_SLOW_BUFFER->handle_, \ Integer::New(Buffer::Length(NG_SLOW_BUFFER)), \ Integer::New(0) \ }; \ \ NG_FAST_BUFFER = NG_JS_BUFFER->NewInstance(3, NG_JS_ARGS); // V8 exception wrapping #define V8_WRAP_START() \ HandleScope scope; \ try { #define V8_WRAP_END() \ } catch (Handle<Value> err) { \ return ThrowException(err); \ } catch (exception err) { \ return ThrowException(Exception::Error(String::New(err.what()))); \ } #define V8_WRAP_END_NR() \ } catch (Handle<Value> err) { \ ThrowException(err); \ } catch (exception err) { \ ThrowException(Exception::Error(String::New(err.what()))); \ } // Dealing with V8 persistent handles template <class T> void ClearPersistent(Persistent<T>& handle) { if (handle.IsEmpty()) return; handle.Dispose(); handle.Clear(); } template <class T> void SetPersistent(Persistent<T>& handle, Handle<T> value) { ClearPersistent<T>(handle); if (value.IsEmpty()) return; handle = Persistent<T>::New(value); } //////////////////////////////////////////////////////////////////////////////// // MODULE DECLARATION //////////////////////////////////////////////////////////////////////////////// extern "C" { void init (Handle<Object> target) { HandleScope scope; //Static functions & properties target->Set(String::NewSymbol("version"), String::New("1.0.0")); NODE_SET_METHOD(target, "markdown", markdown); NODE_SET_METHOD(target, "markdownSync", markdownSync); //Extension constants target->Set(String::NewSymbol("EXT_AUTOLINK"), Integer::New(MKDEXT_AUTOLINK)); target->Set(String::NewSymbol("EXT_FENCED_CODE"), Integer::New(MKDEXT_FENCED_CODE)); target->Set(String::NewSymbol("EXT_LAX_SPACING"), Integer::New(MKDEXT_LAX_SPACING)); target->Set(String::NewSymbol("EXT_NO_INTRA_EMPHASIS"), Integer::New(MKDEXT_NO_INTRA_EMPHASIS)); target->Set(String::NewSymbol("EXT_SPACE_HEADERS"), Integer::New(MKDEXT_SPACE_HEADERS)); target->Set(String::NewSymbol("EXT_STRIKETHROUGH"), Integer::New(MKDEXT_STRIKETHROUGH)); target->Set(String::NewSymbol("EXT_SUPERSCRIPT"), Integer::New(MKDEXT_SUPERSCRIPT)); target->Set(String::NewSymbol("EXT_TABLES"), Integer::New(MKDEXT_TABLES)); //TODO: html renderer flags //TODO } NODE_MODULE(robotskirt, init) }
Update extension flags
Update extension flags
C++
mit
benmills/robotskirt,benmills/robotskirt,benmills/robotskirt,benmills/robotskirt,benmills/robotskirt
d26521b41d259f79e8a4579d39d22737ffdf788c
Runtime/MP1/World/CElitePirate.hpp
Runtime/MP1/World/CElitePirate.hpp
#pragma once #include "Runtime/Character/CBoneTracking.hpp" #include "Runtime/Collision/CCollisionActorManager.hpp" #include "Runtime/Collision/CJointCollisionDescription.hpp" #include "Runtime/MP1/World/CGrenadeLauncher.hpp" #include "Runtime/MP1/World/CShockWave.hpp" #include "Runtime/World/CActorParameters.hpp" #include "Runtime/World/CAnimationParameters.hpp" #include "Runtime/World/CPathFindSearch.hpp" #include "Runtime/World/CPatterned.hpp" namespace urde::MP1 { class CElitePirateData { private: float x0_tauntInterval; float x4_tauntVariance; float x8_; float xc_; float x10_attackChance; float x14_shotAtTime; float x18_shotAtTimeVariance; float x1c_; CAssetId x20_; u16 x24_sfxAbsorb; CActorParameters x28_launcherActParams; CAnimationParameters x90_launcherAnimParams; CAssetId x9c_; u16 xa0_; CAssetId xa4_; CDamageInfo xa8_; float xc4_launcherHp; CAssetId xc8_; CAssetId xcc_; CAssetId xd0_; CAssetId xd4_; SGrenadeUnknownStruct xd8_; SGrenadeTrajectoryInfo xe0_trajectoryInfo; u32 xf0_grenadeNumBounces; u16 xf4_; u16 xf6_; CAssetId xf8_; CDamageInfo xfc_; CAssetId x118_; u16 x11c_; bool x11e_; bool x11f_; public: CElitePirateData(CInputStream&, u32 propCount); [[nodiscard]] float GetTauntInterval() const { return x0_tauntInterval; } [[nodiscard]] float GetTauntVariance() const { return x4_tauntVariance; } [[nodiscard]] float GetAttackChance() const { return x10_attackChance; } [[nodiscard]] float GetShotAtTime() const { return x14_shotAtTime; } [[nodiscard]] float GetShotAtTimeVariance() const { return x18_shotAtTimeVariance; } [[nodiscard]] float GetX1C() const { return x1c_; } [[nodiscard]] CAssetId GetX20() const { return x20_; } [[nodiscard]] u16 GetSFXAbsorb() const { return x24_sfxAbsorb; } [[nodiscard]] const CActorParameters& GetLauncherActParams() const { return x28_launcherActParams; } [[nodiscard]] const CAnimationParameters& GetLauncherAnimParams() const { return x90_launcherAnimParams; } [[nodiscard]] float GetLauncherHP() const { return xc4_launcherHp; } [[nodiscard]] const SGrenadeTrajectoryInfo& GetGrenadeTrajectoryInfo() const { return xe0_trajectoryInfo; } [[nodiscard]] CAssetId GetXF8() const { return xf8_; } [[nodiscard]] const CDamageInfo& GetXFC() const { return xfc_; } [[nodiscard]] CAssetId GetX118() const { return x118_; } [[nodiscard]] u16 GetX11C() const { return x11c_; } [[nodiscard]] bool GetX11E() const { return x11e_; } [[nodiscard]] bool GetX11F() const { return x11f_; } [[nodiscard]] SBouncyGrenadeData GetBouncyGrenadeData() const { return {xd8_, xa8_, xc8_, xcc_, xd0_, xd4_, xf0_grenadeNumBounces, xf4_, xf6_}; } [[nodiscard]] SGrenadeLauncherData GetGrenadeLauncherData() const { return {GetBouncyGrenadeData(), xa4_, x9c_, xa0_, xe0_trajectoryInfo}; } }; class CElitePirate : public CPatterned { private: struct SUnknownStruct { private: float x0_; rstl::reserved_vector<zeus::CVector3f, 16> x4_; public: explicit SUnknownStruct(float f) : x0_(f * f) {} zeus::CVector3f GetValue(const zeus::CVector3f& v1, const zeus::CVector3f& v2); void AddValue(const zeus::CVector3f& vec); void Clear() { x4_.clear(); } }; enum class EState { Invalid = -1, Zero = 0, One = 1, Two = 2, Over = 3, }; EState x568_state = EState::Invalid; CDamageVulnerability x56c_vulnerability; std::unique_ptr<CCollisionActorManager> x5d4_collisionActorMgr; CElitePirateData x5d8_data; CBoneTracking x6f8_boneTracking; std::unique_ptr<CCollisionActorManager> x730_collisionActorMgrHead; // s32 x734_; CCollidableAABox x738_collisionAabb; std::optional<TLockedToken<CGenDescription>> x760_energyAbsorbDesc; TUniqueId x770_collisionHeadId = kInvalidUniqueId; TUniqueId x772_launcherId = kInvalidUniqueId; rstl::reserved_vector<TUniqueId, 7> x774_collisionRJointIds; rstl::reserved_vector<TUniqueId, 7> x788_collisionLJointIds; TUniqueId x79c_ = kInvalidUniqueId; float x7a0_initialSpeed; float x7a4_steeringSpeed = 1.f; float x7a8_pathShaggedTime = 0.f; float x7ac_energyAbsorbCooldown = 0.f; float x7b0_ = 1.f; float x7b4_hp = 0.f; float x7b8_attackTimer = 0.f; float x7bc_tauntTimer = 0.f; float x7c0_shotAtTimer = 0.f; float x7c4_absorbUpdateTimer = 0.f; s32 x7c8_currAnimId = -1; u32 x7cc_activeMaterialSet = 0; CPathFindSearch x7d0_pathFindSearch; zeus::CVector3f x8b4_targetDestPos; SUnknownStruct x8c0_; bool x988_24_damageOn : 1; bool x988_25_attackingRightClaw : 1; bool x988_26_attackingLeftClaw : 1; bool x988_27_shotAt : 1; bool x988_28_alert : 1; bool x988_29_shockWaveAnim : 1; bool x988_30_calledForBackup : 1; bool x988_31_running : 1; bool x989_24_onPath : 1; public: DEFINE_PATTERNED(ElitePirate) CElitePirate(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, CModelData&& mData, const CPatternedInfo& pInfo, const CActorParameters& actParms, CElitePirateData data); void Accept(IVisitor& visitor) override; void Think(float dt, CStateManager& mgr) override; void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) override; void PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) override; const CDamageVulnerability* GetDamageVulnerability() const override; const CDamageVulnerability* GetDamageVulnerability(const zeus::CVector3f& pos, const zeus::CVector3f& dir, const CDamageInfo& dInfo) const override; zeus::CVector3f GetOrbitPosition(const CStateManager& mgr) const override; zeus::CVector3f GetAimPosition(const CStateManager& mgr, float) const override; void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) override; const CCollisionPrimitive* GetCollisionPrimitive() const override; void KnockBack(const zeus::CVector3f&, CStateManager& mgr, const CDamageInfo& info, EKnockBackType type, bool inDeferred, float magnitude) override; void TakeDamage(const zeus::CVector3f&, float arg) override; void Patrol(CStateManager& mgr, EStateMsg msg, float dt) override; void PathFind(CStateManager& mgr, EStateMsg msg, float dt) override; void TargetPatrol(CStateManager& mgr, EStateMsg msg, float dt) override; void Halt(CStateManager& mgr, EStateMsg msg, float dt) override; void Run(CStateManager& mgr, EStateMsg msg, float dt) override; void Generate(CStateManager& mgr, EStateMsg msg, float dt) override; void Attack(CStateManager& mgr, EStateMsg msg, float dt) override; void Taunt(CStateManager& mgr, EStateMsg msg, float dt) override; void ProjectileAttack(CStateManager& mgr, EStateMsg msg, float dt) override; void Cover(CStateManager& mgr, EStateMsg msg, float dt) override; void SpecialAttack(CStateManager& mgr, EStateMsg msg, float dt) override; void CallForBackup(CStateManager& mgr, EStateMsg msg, float dt) override; bool TooClose(CStateManager& mgr, float arg) override; bool InDetectionRange(CStateManager& mgr, float arg) override; bool SpotPlayer(CStateManager& mgr, float arg) override; bool AnimOver(CStateManager& mgr, float arg) override; bool ShouldAttack(CStateManager& mgr, float arg) override; bool InPosition(CStateManager& mgr, float arg) override; bool ShouldTurn(CStateManager& mgr, float arg) override; bool AggressionCheck(CStateManager& mgr, float arg) override; bool ShouldTaunt(CStateManager& mgr, float arg) override; bool ShouldFire(CStateManager& mgr, float arg) override; bool ShotAt(CStateManager& mgr, float arg) override; bool ShouldSpecialAttack(CStateManager& mgr, float arg) override; bool ShouldCallForBackup(CStateManager& mgr, float arg) override; CPathFindSearch* GetSearchPath() override; virtual bool HasWeakPointHead() const { return true; } virtual bool IsElitePirate() const { return true; } virtual void SetupHealthInfo(CStateManager& mgr); virtual void SetLaunchersActive(CStateManager& mgr, bool val); virtual SShockWaveData GetShockWaveData() const { return {x5d8_data.GetXF8(), x5d8_data.GetXFC(), x5d8_data.GetX118(), x5d8_data.GetX11C()}; } private: void SetupPathFindSearch(); void SetShotAt(bool val, CStateManager& mgr); bool IsArmClawCollider(TUniqueId uid, const rstl::reserved_vector<TUniqueId, 7>& vec) const; void AddSphereCollisionList(const SSphereJointInfo* joints, size_t count, std::vector<CJointCollisionDescription>& outJoints) const; void AddCollisionList(const SJointInfo* joints, size_t count, std::vector<CJointCollisionDescription>& outJoints) const; void SetupCollisionManager(CStateManager& mgr); void SetupCollisionActorInfo(CStateManager& mgr); bool IsArmClawCollider(std::string_view name, std::string_view locator, const SJointInfo* info, size_t infoCount); void CreateGrenadeLauncher(CStateManager& mgr, TUniqueId uid); void ApplyDamageToHead(CStateManager& mgr, TUniqueId uid); void CreateEnergyAbsorb(CStateManager& mgr, const zeus::CTransform& xf); void SetupLauncherHealthInfo(CStateManager& mgr, TUniqueId uid); void SetLauncherActive(CStateManager& mgr, bool val, TUniqueId uid); zeus::CVector3f GetLockOnPosition(const CActor* actor) const; bool CanKnockBack(const CDamageInfo& info) const; void UpdateDestPos(CStateManager& mgr); void CheckAttackChance(CStateManager& mgr); void AttractProjectiles(CStateManager& mgr); void UpdateAbsorbBodyState(CStateManager& mgr, float dt); bool IsAttractingEnergy(); void UpdateTimers(float dt); void UpdatePositionHistory(); void UpdateActorTransform(CStateManager& mgr, TUniqueId& uid, std::string_view name); void UpdateHealthInfo(CStateManager& mgr); void ExtendTouchBounds(const CStateManager& mgr, const rstl::reserved_vector<TUniqueId, 7>& uids, const zeus::CVector3f& vec) const; bool ShouldFireFromLauncher(CStateManager& mgr, TUniqueId launcherId); bool ShouldCallForBackupFromLauncher(const CStateManager& mgr, TUniqueId uid) const; bool IsClosestEnergyAttractor(const CStateManager& mgr, const rstl::reserved_vector<TUniqueId, 1024>& charNearList, const zeus::CVector3f& projectilePos) const; }; } // namespace urde
#pragma once #include "Runtime/Character/CBoneTracking.hpp" #include "Runtime/Collision/CCollisionActorManager.hpp" #include "Runtime/Collision/CJointCollisionDescription.hpp" #include "Runtime/MP1/World/CGrenadeLauncher.hpp" #include "Runtime/MP1/World/CShockWave.hpp" #include "Runtime/World/CActorParameters.hpp" #include "Runtime/World/CAnimationParameters.hpp" #include "Runtime/World/CPathFindSearch.hpp" #include "Runtime/World/CPatterned.hpp" namespace urde::MP1 { class CElitePirateData { private: float x0_tauntInterval; float x4_tauntVariance; float x8_; float xc_; float x10_attackChance; float x14_shotAtTime; float x18_shotAtTimeVariance; float x1c_; CAssetId x20_; u16 x24_sfxAbsorb; CActorParameters x28_launcherActParams; CAnimationParameters x90_launcherAnimParams; CAssetId x9c_; u16 xa0_; CAssetId xa4_; CDamageInfo xa8_; float xc4_launcherHp; CAssetId xc8_; CAssetId xcc_; CAssetId xd0_; CAssetId xd4_; SGrenadeUnknownStruct xd8_; SGrenadeTrajectoryInfo xe0_trajectoryInfo; u32 xf0_grenadeNumBounces; u16 xf4_; u16 xf6_; CAssetId xf8_; CDamageInfo xfc_; CAssetId x118_; u16 x11c_; bool x11e_; bool x11f_; public: CElitePirateData(CInputStream&, u32 propCount); [[nodiscard]] float GetTauntInterval() const { return x0_tauntInterval; } [[nodiscard]] float GetTauntVariance() const { return x4_tauntVariance; } [[nodiscard]] float GetAttackChance() const { return x10_attackChance; } [[nodiscard]] float GetShotAtTime() const { return x14_shotAtTime; } [[nodiscard]] float GetShotAtTimeVariance() const { return x18_shotAtTimeVariance; } [[nodiscard]] float GetX1C() const { return x1c_; } [[nodiscard]] CAssetId GetX20() const { return x20_; } [[nodiscard]] u16 GetSFXAbsorb() const { return x24_sfxAbsorb; } [[nodiscard]] const CActorParameters& GetLauncherActParams() const { return x28_launcherActParams; } [[nodiscard]] const CAnimationParameters& GetLauncherAnimParams() const { return x90_launcherAnimParams; } [[nodiscard]] float GetLauncherHP() const { return xc4_launcherHp; } [[nodiscard]] const SGrenadeTrajectoryInfo& GetGrenadeTrajectoryInfo() const { return xe0_trajectoryInfo; } [[nodiscard]] CAssetId GetXF8() const { return xf8_; } [[nodiscard]] const CDamageInfo& GetXFC() const { return xfc_; } [[nodiscard]] CAssetId GetX118() const { return x118_; } [[nodiscard]] u16 GetX11C() const { return x11c_; } [[nodiscard]] bool GetX11E() const { return x11e_; } [[nodiscard]] bool GetX11F() const { return x11f_; } [[nodiscard]] SBouncyGrenadeData GetBouncyGrenadeData() const { return {xd8_, xa8_, xc8_, xcc_, xd0_, xd4_, xf0_grenadeNumBounces, xf4_, xf6_}; } [[nodiscard]] SGrenadeLauncherData GetGrenadeLauncherData() const { return {GetBouncyGrenadeData(), xa4_, x9c_, xa0_, xe0_trajectoryInfo}; } }; class CElitePirate : public CPatterned { private: struct SUnknownStruct { private: float x0_; rstl::reserved_vector<zeus::CVector3f, 16> x4_; public: explicit SUnknownStruct(float f) : x0_(f * f) {} zeus::CVector3f GetValue(const zeus::CVector3f& v1, const zeus::CVector3f& v2); void AddValue(const zeus::CVector3f& vec); void Clear() { x4_.clear(); } }; enum class EState { Invalid = -1, Zero = 0, One = 1, Two = 2, Over = 3, }; EState x568_state = EState::Invalid; CDamageVulnerability x56c_vulnerability; std::unique_ptr<CCollisionActorManager> x5d4_collisionActorMgr; CElitePirateData x5d8_data; CBoneTracking x6f8_boneTracking; std::unique_ptr<CCollisionActorManager> x730_collisionActorMgrHead; // s32 x734_; CCollidableAABox x738_collisionAabb; std::optional<TLockedToken<CGenDescription>> x760_energyAbsorbDesc; TUniqueId x770_collisionHeadId = kInvalidUniqueId; TUniqueId x772_launcherId = kInvalidUniqueId; rstl::reserved_vector<TUniqueId, 7> x774_collisionRJointIds; rstl::reserved_vector<TUniqueId, 7> x788_collisionLJointIds; TUniqueId x79c_ = kInvalidUniqueId; float x7a0_initialSpeed; float x7a4_steeringSpeed = 1.f; float x7a8_pathShaggedTime = 0.f; float x7ac_energyAbsorbCooldown = 0.f; float x7b0_ = 1.f; float x7b4_hp = 0.f; float x7b8_attackTimer = 0.f; float x7bc_tauntTimer = 0.f; float x7c0_shotAtTimer = 0.f; float x7c4_absorbUpdateTimer = 0.f; s32 x7c8_currAnimId = -1; u32 x7cc_activeMaterialSet = 0; CPathFindSearch x7d0_pathFindSearch; zeus::CVector3f x8b4_targetDestPos; SUnknownStruct x8c0_; bool x988_24_damageOn : 1; bool x988_25_attackingRightClaw : 1; bool x988_26_attackingLeftClaw : 1; bool x988_27_shotAt : 1; bool x988_28_alert : 1; bool x988_29_shockWaveAnim : 1; bool x988_30_calledForBackup : 1; bool x988_31_running : 1; bool x989_24_onPath : 1; public: DEFINE_PATTERNED(ElitePirate) CElitePirate(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, CModelData&& mData, const CPatternedInfo& pInfo, const CActorParameters& actParms, CElitePirateData data); void Accept(IVisitor& visitor) override; void Think(float dt, CStateManager& mgr) override; void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) override; void PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) override; const CDamageVulnerability* GetDamageVulnerability() const override; const CDamageVulnerability* GetDamageVulnerability(const zeus::CVector3f& pos, const zeus::CVector3f& dir, const CDamageInfo& dInfo) const override; zeus::CVector3f GetOrbitPosition(const CStateManager& mgr) const override; zeus::CVector3f GetAimPosition(const CStateManager& mgr, float) const override; void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) override; const CCollisionPrimitive* GetCollisionPrimitive() const override; void KnockBack(const zeus::CVector3f&, CStateManager& mgr, const CDamageInfo& info, EKnockBackType type, bool inDeferred, float magnitude) override; void TakeDamage(const zeus::CVector3f&, float arg) override; void Patrol(CStateManager& mgr, EStateMsg msg, float dt) override; void PathFind(CStateManager& mgr, EStateMsg msg, float dt) override; void TargetPatrol(CStateManager& mgr, EStateMsg msg, float dt) override; void Halt(CStateManager& mgr, EStateMsg msg, float dt) override; void Run(CStateManager& mgr, EStateMsg msg, float dt) override; void Generate(CStateManager& mgr, EStateMsg msg, float dt) override; void Attack(CStateManager& mgr, EStateMsg msg, float dt) override; void Taunt(CStateManager& mgr, EStateMsg msg, float dt) override; void ProjectileAttack(CStateManager& mgr, EStateMsg msg, float dt) override; void Cover(CStateManager& mgr, EStateMsg msg, float dt) override; void SpecialAttack(CStateManager& mgr, EStateMsg msg, float dt) override; void CallForBackup(CStateManager& mgr, EStateMsg msg, float dt) override; bool TooClose(CStateManager& mgr, float arg) override; bool InDetectionRange(CStateManager& mgr, float arg) override; bool SpotPlayer(CStateManager& mgr, float arg) override; bool AnimOver(CStateManager& mgr, float arg) override; bool ShouldAttack(CStateManager& mgr, float arg) override; bool InPosition(CStateManager& mgr, float arg) override; bool ShouldTurn(CStateManager& mgr, float arg) override; bool AggressionCheck(CStateManager& mgr, float arg) override; bool ShouldTaunt(CStateManager& mgr, float arg) override; bool ShouldFire(CStateManager& mgr, float arg) override; bool ShotAt(CStateManager& mgr, float arg) override; bool ShouldSpecialAttack(CStateManager& mgr, float arg) override; bool ShouldCallForBackup(CStateManager& mgr, float arg) override; CPathFindSearch* GetSearchPath() override; virtual bool HasWeakPointHead() const { return true; } virtual bool IsElitePirate() const { return true; } virtual void SetupHealthInfo(CStateManager& mgr); virtual void SetLaunchersActive(CStateManager& mgr, bool val); virtual SShockWaveData GetShockWaveData() const { return {x5d8_data.GetXF8(), x5d8_data.GetXFC(), x5d8_data.GetX118(), x5d8_data.GetX11C()}; } private: void SetupPathFindSearch(); void SetShotAt(bool val, CStateManager& mgr); bool IsArmClawCollider(TUniqueId uid, const rstl::reserved_vector<TUniqueId, 7>& vec) const; void AddSphereCollisionList(const SSphereJointInfo* joints, size_t count, std::vector<CJointCollisionDescription>& outJoints) const; void AddCollisionList(const SJointInfo* joints, size_t count, std::vector<CJointCollisionDescription>& outJoints) const; void SetupCollisionManager(CStateManager& mgr); void SetupCollisionActorInfo(CStateManager& mgr); bool IsArmClawCollider(std::string_view name, std::string_view locator, const SJointInfo* info, size_t infoCount) const; void CreateGrenadeLauncher(CStateManager& mgr, TUniqueId uid); void ApplyDamageToHead(CStateManager& mgr, TUniqueId uid); void CreateEnergyAbsorb(CStateManager& mgr, const zeus::CTransform& xf); void SetupLauncherHealthInfo(CStateManager& mgr, TUniqueId uid); void SetLauncherActive(CStateManager& mgr, bool val, TUniqueId uid); zeus::CVector3f GetLockOnPosition(const CActor* actor) const; bool CanKnockBack(const CDamageInfo& info) const; void UpdateDestPos(CStateManager& mgr); void CheckAttackChance(CStateManager& mgr); void AttractProjectiles(CStateManager& mgr); void UpdateAbsorbBodyState(CStateManager& mgr, float dt); bool IsAttractingEnergy() const; void UpdateTimers(float dt); void UpdatePositionHistory(); void UpdateActorTransform(CStateManager& mgr, TUniqueId& uid, std::string_view name); void UpdateHealthInfo(CStateManager& mgr); void ExtendTouchBounds(const CStateManager& mgr, const rstl::reserved_vector<TUniqueId, 7>& uids, const zeus::CVector3f& vec) const; bool ShouldFireFromLauncher(CStateManager& mgr, TUniqueId launcherId); bool ShouldCallForBackupFromLauncher(const CStateManager& mgr, TUniqueId uid) const; bool IsClosestEnergyAttractor(const CStateManager& mgr, const rstl::reserved_vector<TUniqueId, 1024>& charNearList, const zeus::CVector3f& projectilePos) const; }; } // namespace urde
Add missing const specifiers
CElitePirate: Add missing const specifiers Note to self: Remember to stage all of the necessary changes in commits.
C++
mit
AxioDL/PathShagged,AxioDL/PathShagged,AxioDL/PathShagged
cb1fb695d385e0d6186c3e37bfbf89f0ba5f60df
src/rpcclient.cpp
src/rpcclient.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcprotocol.h" #include "ui_interface.h" #include "util.h" #include <set> #include <stdint.h> using namespace std; using namespace json_spirit; class CRPCConvertParam { public: std::string methodName; //! method whose params want conversion int paramIdx; //! 0-based idx of param to convert }; // ***TODO*** static const CRPCConvertParam vRPCConvertParams[] = { {"stop", 0}, {"setmocktime", 0}, {"getaddednodeinfo", 0}, {"setgenerate", 0}, {"setgenerate", 1}, {"getnetworkhashps", 0}, {"getnetworkhashps", 1}, {"sendtoaddress", 1}, {"sendtoaddressix", 1}, {"settxfee", 0}, {"getreceivedbyaddress", 1}, {"getreceivedbyaccount", 1}, {"listreceivedbyaddress", 0}, {"listreceivedbyaddress", 1}, {"listreceivedbyaddress", 2}, {"listreceivedbyaccount", 0}, {"listreceivedbyaccount", 1}, {"listreceivedbyaccount", 2}, {"getbalance", 1}, {"getbalance", 2}, {"getblockhash", 0}, {"move", 2}, {"move", 3}, {"sendfrom", 2}, {"sendfrom", 3}, {"listtransactions", 1}, {"listtransactions", 2}, {"listtransactions", 3}, {"listaccounts", 0}, {"listaccounts", 1}, {"walletpassphrase", 1}, {"walletpassphrase", 2}, {"getblocktemplate", 0}, {"listsinceblock", 1}, {"listsinceblock", 2}, {"sendmany", 1}, {"sendmany", 2}, {"addmultisigaddress", 0}, {"addmultisigaddress", 1}, {"createmultisig", 0}, {"createmultisig", 1}, {"listunspent", 0}, {"listunspent", 1}, {"listunspent", 2}, {"getblock", 1}, {"getblockheader", 1}, {"gettransaction", 1}, {"getrawtransaction", 1}, {"createrawtransaction", 0}, {"createrawtransaction", 1}, {"signrawtransaction", 1}, {"signrawtransaction", 2}, {"sendrawtransaction", 1}, {"gettxout", 1}, {"gettxout", 2}, {"lockunspent", 0}, {"lockunspent", 1}, {"importprivkey", 2}, {"importaddress", 2}, {"verifychain", 0}, {"verifychain", 1}, {"keypoolrefill", 0}, {"getrawmempool", 0}, {"estimatefee", 0}, {"estimatepriority", 0}, {"prioritisetransaction", 1}, {"prioritisetransaction", 2}, {"spork", 1}, {"mnbudget", 4}, {"mnbudget", 6}, {"mnbudget", 8}, {"mnbudgetvoteraw", 1}, {"mnbudgetvoteraw", 4}, {"reservebalance", 0}, {"reservebalance", 1}, {"setstakesplitthreshold", 0}, {"autocombinerewards", 0}, {"autocombinerewards", 1}}; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; /** Convert strings to command-specific RPC representation */ Array RPCConvertValues(const std::string& strMethod, const std::vector<std::string>& strParams) { Array params; for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; // insert string value directly if (!rpcCvtTable.convert(strMethod, idx)) { params.push_back(strVal); } // parse string as JSON, insert bool/number/object/etc. value else { Value jVal; if (!read_string(strVal, jVal)) throw runtime_error(string("Error parsing JSON:") + strVal); params.push_back(jVal); } } return params; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The Phore developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcprotocol.h" #include "ui_interface.h" #include "util.h" #include <set> #include <stdint.h> using namespace std; using namespace json_spirit; class CRPCConvertParam { public: std::string methodName; //! method whose params want conversion int paramIdx; //! 0-based idx of param to convert }; // ***TODO*** static const CRPCConvertParam vRPCConvertParams[] = { {"stop", 0}, {"setmocktime", 0}, {"getaddednodeinfo", 0}, {"setgenerate", 0}, {"setgenerate", 1}, {"getnetworkhashps", 0}, {"getnetworkhashps", 1}, {"sendtoaddress", 1}, {"sendtoaddressix", 1}, {"settxfee", 0}, {"getreceivedbyaddress", 1}, {"getreceivedbyaccount", 1}, {"listreceivedbyaddress", 0}, {"listreceivedbyaddress", 1}, {"listreceivedbyaddress", 2}, {"listreceivedbyaccount", 0}, {"listreceivedbyaccount", 1}, {"listreceivedbyaccount", 2}, {"getbalance", 1}, {"getbalance", 2}, {"getblockhash", 0}, {"move", 2}, {"move", 3}, {"sendfrom", 2}, {"sendfrom", 3}, {"listtransactions", 1}, {"listtransactions", 2}, {"listtransactions", 3}, {"listaccounts", 0}, {"listaccounts", 1}, {"walletpassphrase", 1}, {"walletpassphrase", 2}, {"getblocktemplate", 0}, {"listsinceblock", 1}, {"listsinceblock", 2}, {"sendmany", 1}, {"sendmany", 2}, {"addmultisigaddress", 0}, {"addmultisigaddress", 1}, {"createmultisig", 0}, {"createmultisig", 1}, {"listunspent", 0}, {"listunspent", 1}, {"listunspent", 2}, {"getblock", 1}, {"getblockheader", 1}, {"gettransaction", 1}, {"getrawtransaction", 1}, {"createrawtransaction", 0}, {"createrawtransaction", 1}, {"signrawtransaction", 1}, {"signrawtransaction", 2}, {"sendrawtransaction", 1}, {"gettxout", 1}, {"gettxout", 2}, {"lockunspent", 0}, {"lockunspent", 1}, {"importprivkey", 2}, {"importaddress", 2}, {"verifychain", 0}, {"verifychain", 1}, {"keypoolrefill", 0}, {"getrawmempool", 0}, {"estimatefee", 0}, {"estimatepriority", 0}, {"prioritisetransaction", 1}, {"prioritisetransaction", 2}, {"spork", 1}, {"mnbudget", 4}, {"mnbudget", 6}, {"mnbudget", 8}, {"mnbudgetvoteraw", 1}, {"mnbudgetvoteraw", 4}, {"reservebalance", 0}, {"reservebalance", 1}, {"setstakesplitthreshold", 0}, {"autocombinerewards", 0}, {"autocombinerewards", 1}}; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; /** Convert strings to command-specific RPC representation */ Array RPCConvertValues(const std::string& strMethod, const std::vector<std::string>& strParams) { Array params; for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; // insert string value directly if (!rpcCvtTable.convert(strMethod, idx)) { params.push_back(strVal); } // parse string as JSON, insert bool/number/object/etc. value else { Value jVal; if (!read_string(strVal, jVal)) throw runtime_error(string("Error parsing JSON:") + strVal); params.push_back(jVal); } } return params; }
Update rpcclient.cpp
Update rpcclient.cpp
C++
mit
48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P
f18001c06a3c894358b45ecc761a439e2049b755
src/rpcclient.cpp
src/rpcclient.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "ui_interface.h" #include "chainparams.h" // for Params().RPCPort() #include <stdint.h> #include <boost/lexical_cast.hpp> using namespace std; using namespace json_spirit; template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<bool>(params[1], true); if (strMethod == "gettxout" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "verifychain" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "verifychain" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "getrawmempool" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "estimatefee" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "estimatepriority" && n > 0) ConvertTo<boost::int64_t>(params[0]); return params; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "ui_interface.h" #include <stdint.h> #include <boost/lexical_cast.hpp> using namespace std; using namespace json_spirit; template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<bool>(params[1], true); if (strMethod == "gettxout" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "verifychain" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "verifychain" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "getrawmempool" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "estimatefee" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "estimatepriority" && n > 0) ConvertTo<boost::int64_t>(params[0]); return params; }
remove include of chainparams.h
remove include of chainparams.h chainparams.h has not been used in this cpp file already, consider to remove it for clean.
C++
mit
langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin
d9f16cf23c39d929b38afde99f2f5a2542c06f87
utils/config_file.cc
utils/config_file.cc
/* * Copyright (C) 2017 ScyllaDB * */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <unordered_map> #include <regex> #include <yaml-cpp/yaml.h> #include <boost/program_options.hpp> #include <boost/any.hpp> #include <boost/range/adaptor/filtered.hpp> #include <seastar/core/file.hh> #include <seastar/core/reactor.hh> #include <seastar/core/shared_ptr.hh> #include <seastar/core/fstream.hh> #include <seastar/core/do_with.hh> #include <seastar/core/print.hh> #include "config_file.hh" #include "config_file_impl.hh" namespace bpo = boost::program_options; template<> std::istream& std::operator>>(std::istream& is, std::unordered_map<seastar::sstring, seastar::sstring>& map) { std::istreambuf_iterator<char> i(is), e; int level = 0; bool sq = false, dq = false, qq = false; sstring key, val; sstring* ps = &key; auto add = [&] { if (!key.empty()) { map[key] = std::move(val); } key = {}; val = {}; ps = &key; }; while (i != e && level >= 0) { auto c = *i++; switch (c) { case '\\': qq = !qq; if (qq) { continue; } break; case '\'': if (!qq) { sq = !sq; } break; case '"': if (!qq) { dq = !dq; } break; case '=': if (level <= 1 && !sq && !dq && !qq) { ps = &val; continue; } break; case '{': case '[': if (!sq && !dq && !qq) { ++level; continue; } break; case ']': case '}': if (!sq && !dq && !qq && level > 0) { --level; continue; } break; case ',': if (level == 1 && !sq && !dq && !qq) { add(); continue; } break; case ' ': case '\t': case '\n': if (!sq && !dq && !qq) { continue; } break; default: break; } if (level == 0) { ++level; } qq = false; ps->append(&c, 1); } add(); return is; } template<> std::istream& std::operator>>(std::istream& is, std::vector<seastar::sstring>& res) { std::istreambuf_iterator<char> i(is), e; int level = 0; bool sq = false, dq = false, qq = false; sstring val; auto add = [&] { if (!val.empty()) { res.emplace_back(std::exchange(val, {})); } val = {}; }; while (i != e && level >= 0) { auto c = *i++; switch (c) { case '\\': qq = !qq; if (qq) { continue; } break; case '\'': if (!qq) { sq = !sq; } break; case '"': if (!qq) { dq = !dq; } break; case '{': case '[': if (!sq && !dq && !qq) { ++level; continue; } break; case '}': case ']': if (!sq && !dq && !qq && level > 0) { --level; continue; } break; case ',': if (level == 1 && !sq && !dq && !qq) { add(); continue; } break; case ' ': case '\t': case '\n': if (!sq && !dq && !qq) { continue; } break; default: break; } if (level == 0) { ++level; } qq = false; val.append(&c, 1); } add(); return is; } template std::istream& std::operator>>(std::istream&, std::unordered_map<seastar::sstring, seastar::sstring>&); sstring utils::hyphenate(const stdx::string_view& v) { sstring result(v.begin(), v.end()); std::replace(result.begin(), result.end(), '_', '-'); return result; } utils::config_file::config_file(std::initializer_list<cfg_ref> cfgs) : _cfgs(cfgs) {} void utils::config_file::add(cfg_ref cfg) { _cfgs.emplace_back(cfg); } void utils::config_file::add(std::initializer_list<cfg_ref> cfgs) { _cfgs.insert(_cfgs.end(), cfgs.begin(), cfgs.end()); } bpo::options_description utils::config_file::get_options_description() { bpo::options_description opts(""); return get_options_description(opts); } bpo::options_description utils::config_file::get_options_description(boost::program_options::options_description opts) { auto init = opts.add_options(); add_options(init); return std::move(opts); } bpo::options_description_easy_init& utils::config_file::add_options(bpo::options_description_easy_init& init) { for (config_src& src : _cfgs) { if (src.status() == value_status::Used) { auto&& name = src.name(); sstring tmp(name.begin(), name.end()); std::replace(tmp.begin(), tmp.end(), '_', '-'); src.add_command_line_option(init, tmp, src.desc()); } } return init; } void utils::config_file::read_from_yaml(const sstring& yaml) { read_from_yaml(yaml.c_str()); } void utils::config_file::read_from_yaml(const char* yaml) { std::unordered_map<sstring, cfg_ref> values; /* * Note: this is not very "half-fault" tolerant. I.e. there could be * yaml syntax errors that origin handles and still sets the options * where as we don't... * There are no exhaustive attempts at converting, we rely on syntax of * file mapping to the data type... */ auto doc = YAML::Load(yaml); for (auto node : doc) { auto label = node.first.as<sstring>(); auto i = std::find_if(_cfgs.begin(), _cfgs.end(), [&label](const config_src& cfg) { return cfg.name() == label; }); if (i == _cfgs.end()) { throw std::invalid_argument("Unknown option " + label); } config_src& cfg = *i; if (cfg.source() > config_source::SettingsFile) { // already set continue; } switch (cfg.status()) { case value_status::Invalid: throw std::invalid_argument("Option " + label + "is not applicable"); case value_status::Unused: default: break; } if (node.second.IsNull()) { continue; } // Still, a syntax error is an error warning, not a fail cfg.set_value(node.second); } } utils::config_file::configs utils::config_file::set_values() const { return boost::copy_range<configs>(_cfgs | boost::adaptors::filtered([] (const config_src& cfg) { return cfg.status() > value_status::Used || cfg.source() > config_source::None; })); } utils::config_file::configs utils::config_file::unset_values() const { configs res; for (config_src& cfg : _cfgs) { if (cfg.status() > value_status::Used) { continue; } if (cfg.source() > config_source::None) { continue; } res.emplace_back(cfg); } return res; } future<> utils::config_file::read_from_file(file f) { return f.size().then([this, f](size_t s) { return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) { return in.read_exactly(s).then([this](temporary_buffer<char> buf) { read_from_yaml(sstring(buf.begin(), buf.end())); }); }); }); } future<> utils::config_file::read_from_file(const sstring& filename) { return open_file_dma(filename, open_flags::ro).then([this](file f) { return read_from_file(std::move(f)); }); }
/* * Copyright (C) 2017 ScyllaDB * */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <unordered_map> #include <regex> #include <yaml-cpp/yaml.h> #include <boost/program_options.hpp> #include <boost/any.hpp> #include <boost/range/adaptor/filtered.hpp> #include <seastar/core/file.hh> #include <seastar/core/reactor.hh> #include <seastar/core/shared_ptr.hh> #include <seastar/core/fstream.hh> #include <seastar/core/do_with.hh> #include <seastar/core/print.hh> #include "config_file.hh" #include "config_file_impl.hh" namespace bpo = boost::program_options; template<> std::istream& std::operator>>(std::istream& is, std::unordered_map<seastar::sstring, seastar::sstring>& map) { std::istreambuf_iterator<char> i(is), e; int level = 0; bool sq = false, dq = false, qq = false; sstring key, val; sstring* ps = &key; auto add = [&] { if (!key.empty()) { map[key] = std::move(val); } key = {}; val = {}; ps = &key; }; while (i != e && level >= 0) { auto c = *i++; switch (c) { case '\\': qq = !qq; if (qq) { continue; } break; case '\'': if (!qq) { sq = !sq; } break; case '"': if (!qq) { dq = !dq; } break; case '=': if (level <= 1 && !sq && !dq && !qq) { ps = &val; continue; } break; case '{': case '[': if (!sq && !dq && !qq) { ++level; continue; } break; case ']': case '}': if (!sq && !dq && !qq && level > 0) { --level; continue; } break; case ',': if (level == 1 && !sq && !dq && !qq) { add(); continue; } break; case ' ': case '\t': case '\n': if (!sq && !dq && !qq) { continue; } break; default: break; } if (level == 0) { ++level; } qq = false; ps->append(&c, 1); } add(); return is; } template<> std::istream& std::operator>>(std::istream& is, std::vector<seastar::sstring>& res) { std::istreambuf_iterator<char> i(is), e; int level = 0; bool sq = false, dq = false, qq = false; sstring val; auto add = [&] { if (!val.empty()) { res.emplace_back(std::exchange(val, {})); } val = {}; }; while (i != e && level >= 0) { auto c = *i++; switch (c) { case '\\': qq = !qq; if (qq) { continue; } break; case '\'': if (!qq) { sq = !sq; } break; case '"': if (!qq) { dq = !dq; } break; case '{': case '[': if (!sq && !dq && !qq) { ++level; continue; } break; case '}': case ']': if (!sq && !dq && !qq && level > 0) { --level; continue; } break; case ',': if (level == 1 && !sq && !dq && !qq) { add(); continue; } break; case ' ': case '\t': case '\n': if (!sq && !dq && !qq) { continue; } break; default: break; } if (level == 0) { ++level; } qq = false; val.append(&c, 1); } add(); return is; } template std::istream& std::operator>>(std::istream&, std::unordered_map<seastar::sstring, seastar::sstring>&); sstring utils::hyphenate(const stdx::string_view& v) { sstring result(v.begin(), v.end()); std::replace(result.begin(), result.end(), '_', '-'); return result; } utils::config_file::config_file(std::initializer_list<cfg_ref> cfgs) : _cfgs(cfgs) {} void utils::config_file::add(cfg_ref cfg) { _cfgs.emplace_back(cfg); } void utils::config_file::add(std::initializer_list<cfg_ref> cfgs) { _cfgs.insert(_cfgs.end(), cfgs.begin(), cfgs.end()); } bpo::options_description utils::config_file::get_options_description() { bpo::options_description opts(""); return get_options_description(opts); } bpo::options_description utils::config_file::get_options_description(boost::program_options::options_description opts) { auto init = opts.add_options(); add_options(init); return std::move(opts); } bpo::options_description_easy_init& utils::config_file::add_options(bpo::options_description_easy_init& init) { for (config_src& src : _cfgs) { if (src.status() == value_status::Used) { auto&& name = src.name(); sstring tmp(name.begin(), name.end()); std::replace(tmp.begin(), tmp.end(), '_', '-'); src.add_command_line_option(init, tmp, src.desc()); } } return init; } void utils::config_file::read_from_yaml(const sstring& yaml) { read_from_yaml(yaml.c_str()); } void utils::config_file::read_from_yaml(const char* yaml) { std::unordered_map<sstring, cfg_ref> values; /* * Note: this is not very "half-fault" tolerant. I.e. there could be * yaml syntax errors that origin handles and still sets the options * where as we don't... * There are no exhaustive attempts at converting, we rely on syntax of * file mapping to the data type... */ auto doc = YAML::Load(yaml); for (auto node : doc) { auto label = node.first.as<sstring>(); auto i = std::find_if(_cfgs.begin(), _cfgs.end(), [&label](const config_src& cfg) { return cfg.name() == label; }); if (i == _cfgs.end()) { throw std::invalid_argument("Unknown option " + label); } config_src& cfg = *i; if (cfg.source() > config_source::SettingsFile) { // already set continue; } switch (cfg.status()) { case value_status::Invalid: throw std::invalid_argument("Option " + label + " is not applicable"); case value_status::Unused: default: break; } if (node.second.IsNull()) { continue; } // Still, a syntax error is an error warning, not a fail cfg.set_value(node.second); } } utils::config_file::configs utils::config_file::set_values() const { return boost::copy_range<configs>(_cfgs | boost::adaptors::filtered([] (const config_src& cfg) { return cfg.status() > value_status::Used || cfg.source() > config_source::None; })); } utils::config_file::configs utils::config_file::unset_values() const { configs res; for (config_src& cfg : _cfgs) { if (cfg.status() > value_status::Used) { continue; } if (cfg.source() > config_source::None) { continue; } res.emplace_back(cfg); } return res; } future<> utils::config_file::read_from_file(file f) { return f.size().then([this, f](size_t s) { return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) { return in.read_exactly(s).then([this](temporary_buffer<char> buf) { read_from_yaml(sstring(buf.begin(), buf.end())); }); }); }); } future<> utils::config_file::read_from_file(const sstring& filename) { return open_file_dma(filename, open_flags::ro).then([this](file f) { return read_from_file(std::move(f)); }); }
fix a typo in warning message
trivial: fix a typo in warning message > std::invalid_argument: Option memtable_allocation_typeis not applicable Signed-off-by: Amos Kong <[email protected]> Message-Id: <37d293a4eadfb8a58acaf96f80b1d2e943530c6b.1509947604.git.eb01d8f828a6c9a20be4534e72e049aaf41503df@scylladb.com>
C++
agpl-3.0
avikivity/scylla,avikivity/scylla,duarten/scylla,scylladb/scylla,scylladb/scylla,duarten/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla,duarten/scylla
b5072ce6d3d295150128706e5d95aa787cdb3480
src/v4l2/V4L2DeviceProperties.cpp
src/v4l2/V4L2DeviceProperties.cpp
/* * Copyright 2021 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "V4l2Device.h" #include "logging.h" #include "utils.h" #include "v4l2_genicam_mapping.h" #include "v4l2_property_impl.h" #include "v4l2_utils.h" #include <linux/videodev2.h> #include <unistd.h> // pipe, usleep using namespace tcam; using namespace tcam::v4l2; std::shared_ptr<tcam::property::IPropertyBase> V4l2Device::new_control(struct v4l2_queryctrl* qctrl) { if (qctrl->flags & V4L2_CTRL_FLAG_DISABLED) { return nullptr; } if (qctrl->type == V4L2_CTRL_TYPE_CTRL_CLASS) { // ignore unneccesary controls descriptions such as control "groups" return nullptr; } struct v4l2_ext_control ext_ctrl = {}; struct v4l2_ext_controls ctrls = {}; ext_ctrl.id = qctrl->id; ctrls.ctrl_class = V4L2_CTRL_ID2CLASS(qctrl->id); ctrls.count = 1; ctrls.controls = &ext_ctrl; if (V4L2_CTRL_ID2CLASS(qctrl->id) != V4L2_CTRL_CLASS_USER && qctrl->id < V4L2_CID_PRIVATE_BASE) { if (qctrl->type == V4L2_CTRL_TYPE_STRING) { ext_ctrl.size = qctrl->maximum + 1; ext_ctrl.string = (char*)malloc(ext_ctrl.size); ext_ctrl.string[0] = 0; } if (qctrl->flags & V4L2_CTRL_FLAG_WRITE_ONLY) { SPDLOG_INFO("Encountered write only control."); } else if (tcam_xioctl(fd, VIDIOC_G_EXT_CTRLS, &ctrls)) { SPDLOG_ERROR("Errno {} getting ext_ctrl {}", errno, qctrl->name); return nullptr; } } else { struct v4l2_control ctrl = {}; ctrl.id = qctrl->id; if (tcam_xioctl(fd, VIDIOC_G_CTRL, &ctrl)) { SPDLOG_ERROR("error {} getting ctrl {}", errno, qctrl->name); return nullptr; } ext_ctrl.value = ctrl.value; } const struct v4l2_genicam_mapping* mapping = find_mapping(qctrl->id); // decide what property type to use through TCAM_PROPERTY_TYPE and not v4l2 property type // this way we can generate types v4l2 does not have, i.e. double TCAM_PROPERTY_TYPE type = v4l2_property_type_to_tcam(qctrl->type); if (mapping) { SPDLOG_DEBUG("Conversion requried for qtrcl->name {}", qctrl->name); if (mapping->gen_type != TCAM_PROPERTY_TYPE_UNKNOWN) { type = mapping->gen_type; } } switch (type) { case TCAM_PROPERTY_TYPE_INTEGER: { return std::make_shared<tcam::property::V4L2PropertyIntegerImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_DOUBLE: { return std::make_shared<tcam::property::V4L2PropertyDoubleImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_ENUMERATION: { return std::make_shared<tcam::property::V4L2PropertyEnumImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_BUTTON: { return std::make_shared<tcam::property::V4L2PropertyCommandImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_BOOLEAN: { return std::make_shared<tcam::property::V4L2PropertyBoolImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_STRING: default: { SPDLOG_WARN("Unknown v4l2 property type - %d.", qctrl->type); return nullptr; } } return 0; } void V4l2Device::sort_properties(std::map<uint32_t, std::shared_ptr<tcam::property::IPropertyBase>> properties) { if (properties.empty()) { return; } auto preserve_id = [&properties](uint32_t v4l2_id, const std::string& name) { int count = 0; for (const auto p : properties) { if (p.second->get_name() == name) { count++; } } // this means there is only one interface provider // nothing to remove if (count <= 1) { return; } auto p = properties.begin(); while (p != properties.end()) { if (p->first != v4l2_id && (p->second->get_name() == name)) { SPDLOG_DEBUG("Found additional interface for {}({:x}). Hiding", name, v4l2_id); p = properties.erase(p); } p++; } }; preserve_id(0x199e201, "ExposureTime"); preserve_id(0x0199e202, "ExposureTimeAuto"); preserve_id(V4L2_CID_PRIVACY, "TriggerMode"); preserve_id(0x199e204, "Gain"); m_properties.reserve(properties.size()); for( auto it = properties.begin(); it != properties.end(); ++it ) { m_properties.push_back(it->second); } } void V4l2Device::index_controls() { bool extension_unit_exists = false; // test for loaded extension unit. for (unsigned int i = 0; i < 3; ++i) { if (extension_unit_is_loaded()) { extension_unit_exists = true; break; } else { usleep(500); } } if (!extension_unit_exists) { SPDLOG_WARN( "The property extension unit does not exist. Not all properties will be accessible."); } std::map<uint32_t, std::shared_ptr<tcam::property::IPropertyBase>> new_properties; struct v4l2_queryctrl qctrl = {}; qctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL; while (tcam_xioctl(this->fd, VIDIOC_QUERYCTRL, &qctrl) == 0) { auto prop = new_control(&qctrl); if (prop) { new_properties.emplace(qctrl.id, prop); //sort_properties(qctrl.id, prop); } qctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL; } sort_properties(new_properties); }
/* * Copyright 2021 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "V4l2Device.h" #include "logging.h" #include "utils.h" #include "v4l2_genicam_mapping.h" #include "v4l2_property_impl.h" #include "v4l2_utils.h" #include <linux/videodev2.h> #include <unistd.h> // pipe, usleep using namespace tcam; using namespace tcam::v4l2; std::shared_ptr<tcam::property::IPropertyBase> V4l2Device::new_control(struct v4l2_queryctrl* qctrl) { if (qctrl->flags & V4L2_CTRL_FLAG_DISABLED) { return nullptr; } if (qctrl->type == V4L2_CTRL_TYPE_CTRL_CLASS) { // ignore unneccesary controls descriptions such as control "groups" return nullptr; } struct v4l2_ext_control ext_ctrl = {}; struct v4l2_ext_controls ctrls = {}; ext_ctrl.id = qctrl->id; ctrls.ctrl_class = V4L2_CTRL_ID2CLASS(qctrl->id); ctrls.count = 1; ctrls.controls = &ext_ctrl; if (V4L2_CTRL_ID2CLASS(qctrl->id) != V4L2_CTRL_CLASS_USER && qctrl->id < V4L2_CID_PRIVATE_BASE) { if (qctrl->type == V4L2_CTRL_TYPE_STRING) { ext_ctrl.size = qctrl->maximum + 1; ext_ctrl.string = (char*)malloc(ext_ctrl.size); ext_ctrl.string[0] = 0; } if (qctrl->flags & V4L2_CTRL_FLAG_WRITE_ONLY) { SPDLOG_INFO("Encountered write only control."); } else if (tcam_xioctl(m_fd, VIDIOC_G_EXT_CTRLS, &ctrls)) { SPDLOG_ERROR("Errno {} getting ext_ctrl {}", errno, qctrl->name); return nullptr; } } else { struct v4l2_control ctrl = {}; ctrl.id = qctrl->id; if (tcam_xioctl(m_fd, VIDIOC_G_CTRL, &ctrl)) { SPDLOG_ERROR("error {} getting ctrl {}", errno, qctrl->name); return nullptr; } ext_ctrl.value = ctrl.value; } const struct v4l2_genicam_mapping* mapping = find_mapping(qctrl->id); // decide what property type to use through TCAM_PROPERTY_TYPE and not v4l2 property type // this way we can generate types v4l2 does not have, i.e. double TCAM_PROPERTY_TYPE type = v4l2_property_type_to_tcam(qctrl->type); if (mapping) { SPDLOG_DEBUG("Conversion requried for qtrcl->name {}", qctrl->name); if (mapping->gen_type != TCAM_PROPERTY_TYPE_UNKNOWN) { type = mapping->gen_type; } } switch (type) { case TCAM_PROPERTY_TYPE_INTEGER: { return std::make_shared<tcam::property::V4L2PropertyIntegerImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_DOUBLE: { return std::make_shared<tcam::property::V4L2PropertyDoubleImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_ENUMERATION: { return std::make_shared<tcam::property::V4L2PropertyEnumImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_BUTTON: { return std::make_shared<tcam::property::V4L2PropertyCommandImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_BOOLEAN: { return std::make_shared<tcam::property::V4L2PropertyBoolImpl>(qctrl, &ext_ctrl, p_property_backend, mapping); } case TCAM_PROPERTY_TYPE_STRING: default: { SPDLOG_WARN("Unknown v4l2 property type - %d.", qctrl->type); return nullptr; } } return 0; } void V4l2Device::sort_properties(std::map<uint32_t, std::shared_ptr<tcam::property::IPropertyBase>> properties) { if (properties.empty()) { return; } auto preserve_id = [&properties](uint32_t v4l2_id, const std::string& name) { int count = 0; for (const auto p : properties) { if (p.second->get_name() == name) { count++; } } // this means there is only one interface provider // nothing to remove if (count <= 1) { return; } auto p = properties.begin(); while (p != properties.end()) { if (p->first != v4l2_id && (p->second->get_name() == name)) { SPDLOG_DEBUG("Found additional interface for {}({:x}). Hiding", name, v4l2_id); p = properties.erase(p); } p++; } }; preserve_id(0x199e201, "ExposureTime"); preserve_id(0x0199e202, "ExposureTimeAuto"); preserve_id(V4L2_CID_PRIVACY, "TriggerMode"); preserve_id(0x199e204, "Gain"); m_properties.reserve(properties.size()); for( auto it = properties.begin(); it != properties.end(); ++it ) { m_properties.push_back(it->second); } } void V4l2Device::index_controls() { bool extension_unit_exists = false; // test for loaded extension unit. for (unsigned int i = 0; i < 3; ++i) { if (extension_unit_is_loaded()) { extension_unit_exists = true; break; } else { usleep(500); } } if (!extension_unit_exists) { SPDLOG_WARN( "The property extension unit does not exist. Not all properties will be accessible."); } std::map<uint32_t, std::shared_ptr<tcam::property::IPropertyBase>> new_properties; struct v4l2_queryctrl qctrl = {}; qctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL; while (tcam_xioctl(this->m_fd, VIDIOC_QUERYCTRL, &qctrl) == 0) { auto prop = new_control(&qctrl); if (prop) { new_properties.emplace(qctrl.id, prop); //sort_properties(qctrl.id, prop); } qctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL; } sort_properties(new_properties); }
Add missing renames
v4l2: Add missing renames
C++
apache-2.0
TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera
73bec3a0910249d73cc0e1179fdde2cb1b4d1169
Modules/Wrappers/ApplicationEngine/src/otbWrapperElevationParametersHandler.cxx
Modules/Wrappers/ApplicationEngine/src/otbWrapperElevationParametersHandler.cxx
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperElevationParametersHandler.h" #include "otbDEMHandler.h" namespace otb { namespace Wrapper { void ElevationParametersHandler::AddElevationParameters(Application::Pointer app, const std::string& key) { app->AddParameter(ParameterType_Group, key, "Elevation management"); app->SetParameterDescription(key, "This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles " "application could be a useful tool to list/download tiles related to a product."); // DEM directory std::ostringstream oss; oss << key << ".dem"; app->AddParameter(ParameterType_Directory, oss.str(), "DEM directory"); app->SetParameterDescription(oss.str(), "This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain " "only DEM files. Unexpected behaviour might occurs if other images are found in this directory."); app->MandatoryOff(oss.str()); std::string demDirFromConfig = otb::ConfigurationManager::GetDEMDirectory(); if (demDirFromConfig != "") { app->SetParameterString(oss.str(), demDirFromConfig); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Geoid file oss.str(""); oss << key << ".geoid"; app->AddParameter(ParameterType_InputFilename, oss.str(), "Geoid File"); app->SetParameterDescription(oss.str(), "Use a geoid grid to get the height " "above the ellipsoid in case there is no DEM available, no coverage for " "some points or pixels with no_data in the DEM tiles. A version of the " "geoid can be found on the OTB website" "(https://gitlab.orfeo-toolbox.org/orfeotoolbox/otb-data/blob/master/Input/DEM/egm96.grd)."); app->MandatoryOff(oss.str()); std::string geoidFromConfig = otb::ConfigurationManager::GetGeoidFile(); if (geoidFromConfig != "") { app->SetParameterString(oss.str(), geoidFromConfig); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Average elevation oss.str(""); oss << key << ".default"; app->AddParameter(ParameterType_Float, oss.str(), "Default elevation"); app->SetParameterDescription(oss.str(), "This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points " "or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average " "elevation value."); app->SetDefaultParameterFloat(oss.str(), 0.); // TODO : not implemented yet // // Tiff image // oss << ".tiff"; // app->AddChoice(oss.str(), "Tiff file"); // app->AddParameter(ParameterType_InputImage, oss.str(), "Tiff file"); // app->SetParameterDescription(oss.str(),"Tiff file used to get elevation for each location in the image"); } void ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(const Application::Pointer app, const std::string& key) { auto & demHandler = otb::DEMHandler::GetInstance(); // Set default elevation demHandler.SetDefaultHeightAboveEllipsoid(GetDefaultElevation(app, key)); std::ostringstream oss; oss << "Elevation management: setting default height above ellipsoid to " << GetDefaultElevation(app, key) << " meters" << std::endl; app->GetLogger()->Info(oss.str()); // Set geoid if available if (IsGeoidUsed(app, key)) { oss.str(""); oss << "Elevation management: using geoid file (" << GetGeoidFile(app, key) << ")" << std::endl; demHandler.OpenGeoidFile(GetGeoidFile(app, key)); app->GetLogger()->Info(oss.str()); } // Set DEM directory if available if (IsDEMUsed(app, key)) { std::string demDirectory = GetDEMDirectory(app, key); if (demHandler.IsValidDEMDirectory(demDirectory.c_str())) { oss.str(""); oss << "Elevation management: using DEM directory (" << demDirectory << ")" << std::endl; demHandler.OpenDEMDirectory(demDirectory); app->GetLogger()->Info(oss.str()); } else { oss.str(""); oss << "DEM directory : " << demDirectory << " is not a valid DEM directory"; app->GetLogger()->Warning(oss.str()); } } } /** * * Get the Average elevation value */ float ElevationParametersHandler::GetDefaultElevation(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key << ".default"; return app->GetParameterFloat(oss.str()); } /** * Get the Geoid file */ const std::string ElevationParametersHandler::GetGeoidFile(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key << ".geoid"; if (IsGeoidUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } /** * Is Geoid used */ bool ElevationParametersHandler::IsGeoidUsed(const Application::Pointer app, const std::string& key) { std::ostringstream geoidKey; geoidKey << key << ".geoid"; return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str()); } /** * * Is Geoid used */ bool ElevationParametersHandler::IsDEMUsed(const Application::Pointer app, const std::string& key) { std::ostringstream demKey; demKey << key << ".dem"; return app->IsParameterEnabled(demKey.str()) && app->HasValue(demKey.str()); } const std::string ElevationParametersHandler::GetDEMDirectory(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key << ".dem"; if (IsDEMUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } } // End namespace Wrapper } // End namespace otb
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperElevationParametersHandler.h" #include "otbDEMHandler.h" namespace otb { namespace Wrapper { void ElevationParametersHandler::AddElevationParameters(Application::Pointer app, const std::string& key) { app->AddParameter(ParameterType_Group, key, "Elevation management"); app->SetParameterDescription(key, "This group of parameters allows managing elevation values."); // DEM directory std::ostringstream oss; oss << key << ".dem"; app->AddParameter(ParameterType_Directory, oss.str(), "DEM directory"); app->SetParameterDescription(oss.str(), "This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain " "only DEM files. Unexpected behaviour might occurs if other images are found in this directory. Input DEM tiles should be in a raster format supported by GDAL."); app->MandatoryOff(oss.str()); std::string demDirFromConfig = otb::ConfigurationManager::GetDEMDirectory(); if (demDirFromConfig != "") { app->SetParameterString(oss.str(), demDirFromConfig); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Geoid file oss.str(""); oss << key << ".geoid"; app->AddParameter(ParameterType_InputFilename, oss.str(), "Geoid File"); app->SetParameterDescription(oss.str(), "Use a geoid grid to get the height " "above the ellipsoid in case there is no DEM available, no coverage for " "some points or pixels with no_data in the DEM tiles. A version of the " "geoid can be found on the OTB website" "(https://gitlab.orfeo-toolbox.org/orfeotoolbox/otb-data/blob/master/Input/DEM/egm96.grd)."); app->MandatoryOff(oss.str()); std::string geoidFromConfig = otb::ConfigurationManager::GetGeoidFile(); if (geoidFromConfig != "") { app->SetParameterString(oss.str(), geoidFromConfig); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Average elevation oss.str(""); oss << key << ".default"; app->AddParameter(ParameterType_Float, oss.str(), "Default elevation"); app->SetParameterDescription(oss.str(), "This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points " "or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average " "elevation value."); app->SetDefaultParameterFloat(oss.str(), 0.); // TODO : not implemented yet // // Tiff image // oss << ".tiff"; // app->AddChoice(oss.str(), "Tiff file"); // app->AddParameter(ParameterType_InputImage, oss.str(), "Tiff file"); // app->SetParameterDescription(oss.str(),"Tiff file used to get elevation for each location in the image"); } void ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(const Application::Pointer app, const std::string& key) { auto & demHandler = otb::DEMHandler::GetInstance(); // Set default elevation demHandler.SetDefaultHeightAboveEllipsoid(GetDefaultElevation(app, key)); std::ostringstream oss; oss << "Elevation management: setting default height above ellipsoid to " << GetDefaultElevation(app, key) << " meters" << std::endl; app->GetLogger()->Info(oss.str()); // Set geoid if available if (IsGeoidUsed(app, key)) { oss.str(""); oss << "Elevation management: using geoid file (" << GetGeoidFile(app, key) << ")" << std::endl; demHandler.OpenGeoidFile(GetGeoidFile(app, key)); app->GetLogger()->Info(oss.str()); } // Set DEM directory if available if (IsDEMUsed(app, key)) { std::string demDirectory = GetDEMDirectory(app, key); if (demHandler.IsValidDEMDirectory(demDirectory.c_str())) { oss.str(""); oss << "Elevation management: using DEM directory (" << demDirectory << ")" << std::endl; demHandler.OpenDEMDirectory(demDirectory); app->GetLogger()->Info(oss.str()); } else { oss.str(""); oss << "DEM directory : " << demDirectory << " is not a valid DEM directory"; app->GetLogger()->Warning(oss.str()); } } } /** * * Get the Average elevation value */ float ElevationParametersHandler::GetDefaultElevation(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key << ".default"; return app->GetParameterFloat(oss.str()); } /** * Get the Geoid file */ const std::string ElevationParametersHandler::GetGeoidFile(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key << ".geoid"; if (IsGeoidUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } /** * Is Geoid used */ bool ElevationParametersHandler::IsGeoidUsed(const Application::Pointer app, const std::string& key) { std::ostringstream geoidKey; geoidKey << key << ".geoid"; return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str()); } /** * * Is Geoid used */ bool ElevationParametersHandler::IsDEMUsed(const Application::Pointer app, const std::string& key) { std::ostringstream demKey; demKey << key << ".dem"; return app->IsParameterEnabled(demKey.str()) && app->HasValue(demKey.str()); } const std::string ElevationParametersHandler::GetDEMDirectory(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key << ".dem"; if (IsDEMUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } } // End namespace Wrapper } // End namespace otb
update the elevation parameter documentation for OTB 8.0
DOC: update the elevation parameter documentation for OTB 8.0
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
a9514a388278524e2a261c32f15cad3503e33522
src/plugins/qt4projectmanager/qmldumptool.cpp
src/plugins/qt4projectmanager/qmldumptool.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmldumptool.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include <coreplugin/icore.h> #include <projectexplorer/project.h> #include <projectexplorer/projectexplorer.h> #include <QDesktopServices> #include <QCoreApplication> #include <QDir> #include <QDebug> namespace Qt4ProjectManager { static inline QStringList validBinaryFilenames() { return QStringList() << QLatin1String("debug/qmldump.exe") << QLatin1String("qmldump.exe") << QLatin1String("qmldump") << QLatin1String("qmldump.app/Contents/MacOS/qmldump"); } bool QmlDumpTool::canBuild(const QString &installHeadersDir) { QString qDeclHeader = installHeadersDir + QLatin1String("/QtDeclarative/private/qdeclarativemetatype_p.h"); return QFile::exists(qDeclHeader); } QString QmlDumpTool::toolForProject(ProjectExplorer::Project *project) { if (project && project->id() == Qt4ProjectManager::Constants::QT4PROJECT_ID) { Qt4Project *qt4Project = static_cast<Qt4Project*>(project); if (qt4Project && qt4Project->activeTarget() && qt4Project->activeTarget()->activeBuildConfiguration()) { QtVersion *version = qt4Project->activeTarget()->activeBuildConfiguration()->qtVersion(); if (version->isValid()) { QString qtInstallData = version->versionInfo().value("QT_INSTALL_DATA"); QString toolPath = toolByInstallData(qtInstallData); return toolPath; } } } return QString(); } QString QmlDumpTool::toolByInstallData(const QString &qtInstallData) { if (!Core::ICore::instance()) return QString(); const QString mainFilename = Core::ICore::instance()->resourcePath() + QLatin1String("/qml/qmldump/main.cpp"); const QStringList directories = installDirectories(qtInstallData); const QStringList binFilenames = validBinaryFilenames(); return byInstallDataHelper(mainFilename, directories, binFilenames); } QStringList QmlDumpTool::locationsByInstallData(const QString &qtInstallData) { QStringList result; QFileInfo fileInfo; const QStringList binFilenames = validBinaryFilenames(); foreach(const QString &directory, installDirectories(qtInstallData)) { if (getHelperFileInfoFor(binFilenames, directory, &fileInfo)) result << fileInfo.filePath(); } return result; } QString QmlDumpTool::build(const QString &directory, const QString &makeCommand, const QString &qmakeCommand, const QString &mkspec, const Utils::Environment &env, const QString &targetMode) { return buildHelper(QCoreApplication::tr("qmldump"), QLatin1String("qmldump.pro"), directory, makeCommand, qmakeCommand, mkspec, env, targetMode); } QString QmlDumpTool::copy(const QString &qtInstallData, QString *errorMessage) { const QStringList directories = QmlDumpTool::installDirectories(qtInstallData); QStringList files; files << QLatin1String("main.cpp") << QLatin1String("qmldump.pro") << QLatin1String("LICENSE.LGPL") << QLatin1String("LGPL_EXCEPTION.TXT"); QString sourcePath = Core::ICore::instance()->resourcePath() + QLatin1String("/qml/qmldump/"); // Try to find a writeable directory. foreach(const QString &directory, directories) if (copyFiles(sourcePath, files, directory, errorMessage)) { errorMessage->clear(); return directory; } *errorMessage = QCoreApplication::translate("ProjectExplorer::QmlDumpTool", "qmldump could not be built in any of the directories:\n- %1\n\nReason: %2") .arg(directories.join(QLatin1String("\n- ")), *errorMessage); return QString(); } QStringList QmlDumpTool::installDirectories(const QString &qtInstallData) { const QChar slash = QLatin1Char('/'); const uint hash = qHash(qtInstallData); QStringList directories; directories << (qtInstallData + QLatin1String("/qtc-qmldump/")) << QDir::cleanPath((QCoreApplication::applicationDirPath() + QLatin1String("/../qtc-qmldump/") + QString::number(hash))) + slash << (QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QLatin1String("/qtc-qmldump/") + QString::number(hash)) + slash; return directories; } QString QmlDumpTool::qmlDumpPath() { QString path; ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject(); path = Qt4ProjectManager::QmlDumpTool::toolForProject(activeProject); // ### this is needed for qmlproject and cmake project support, but may not work in all cases. if (path.isEmpty()) { // Try to locate default path in Qt Versions QtVersionManager *qtVersions = QtVersionManager::instance(); foreach (QtVersion *version, qtVersions->validVersions()) { if (version->supportsTargetId(Constants::DESKTOP_TARGET_ID)) { const QString qtInstallData = version->versionInfo().value("QT_INSTALL_DATA"); path = QmlDumpTool::toolByInstallData(qtInstallData); if (!path.isEmpty()) { break; } } } } QFileInfo qmldumpFileInfo(path); if (!qmldumpFileInfo.exists()) { qWarning() << "QmlDumpTool::qmlDumpPath: qmldump executable does not exist at" << path; path.clear(); } else if (!qmldumpFileInfo.isFile()) { qWarning() << "QmlDumpTool::qmlDumpPath: " << path << " is not a file"; path.clear(); } return path; } } // namespace
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmldumptool.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include <coreplugin/icore.h> #include <projectexplorer/project.h> #include <projectexplorer/projectexplorer.h> #include <QDesktopServices> #include <QCoreApplication> #include <QDir> #include <QDebug> namespace Qt4ProjectManager { static inline QStringList validBinaryFilenames() { return QStringList() << QLatin1String("debug/qmldump.exe") << QLatin1String("qmldump.exe") << QLatin1String("qmldump") << QLatin1String("qmldump.app/Contents/MacOS/qmldump"); } bool QmlDumpTool::canBuild(const QString &installHeadersDir) { QString qDeclHeader = installHeadersDir + QLatin1String("/QtDeclarative/private/qdeclarativemetatype_p.h"); return QFile::exists(qDeclHeader); } QString QmlDumpTool::toolForProject(ProjectExplorer::Project *project) { if (project && project->id() == Qt4ProjectManager::Constants::QT4PROJECT_ID) { Qt4Project *qt4Project = static_cast<Qt4Project*>(project); if (qt4Project && qt4Project->activeTarget() && qt4Project->activeTarget()->activeBuildConfiguration()) { QtVersion *version = qt4Project->activeTarget()->activeBuildConfiguration()->qtVersion(); if (version->isValid()) { QString qtInstallData = version->versionInfo().value("QT_INSTALL_DATA"); QString toolPath = toolByInstallData(qtInstallData); return toolPath; } } } return QString(); } QString QmlDumpTool::toolByInstallData(const QString &qtInstallData) { if (!Core::ICore::instance()) return QString(); const QString mainFilename = Core::ICore::instance()->resourcePath() + QLatin1String("/qml/qmldump/main.cpp"); const QStringList directories = installDirectories(qtInstallData); const QStringList binFilenames = validBinaryFilenames(); return byInstallDataHelper(mainFilename, directories, binFilenames); } QStringList QmlDumpTool::locationsByInstallData(const QString &qtInstallData) { QStringList result; QFileInfo fileInfo; const QStringList binFilenames = validBinaryFilenames(); foreach(const QString &directory, installDirectories(qtInstallData)) { if (getHelperFileInfoFor(binFilenames, directory, &fileInfo)) result << fileInfo.filePath(); } return result; } QString QmlDumpTool::build(const QString &directory, const QString &makeCommand, const QString &qmakeCommand, const QString &mkspec, const Utils::Environment &env, const QString &targetMode) { return buildHelper(QCoreApplication::tr("qmldump"), QLatin1String("qmldump.pro"), directory, makeCommand, qmakeCommand, mkspec, env, targetMode); } QString QmlDumpTool::copy(const QString &qtInstallData, QString *errorMessage) { const QStringList directories = QmlDumpTool::installDirectories(qtInstallData); QStringList files; files << QLatin1String("main.cpp") << QLatin1String("qmldump.pro") << QLatin1String("LICENSE.LGPL") << QLatin1String("LGPL_EXCEPTION.TXT"); QString sourcePath = Core::ICore::instance()->resourcePath() + QLatin1String("/qml/qmldump/"); // Try to find a writeable directory. foreach(const QString &directory, directories) if (copyFiles(sourcePath, files, directory, errorMessage)) { errorMessage->clear(); return directory; } *errorMessage = QCoreApplication::translate("ProjectExplorer::QmlDumpTool", "qmldump could not be built in any of the directories:\n- %1\n\nReason: %2") .arg(directories.join(QLatin1String("\n- ")), *errorMessage); return QString(); } QStringList QmlDumpTool::installDirectories(const QString &qtInstallData) { const QChar slash = QLatin1Char('/'); const uint hash = qHash(qtInstallData); QStringList directories; directories << (qtInstallData + QLatin1String("/qtc-qmldump/")) << QDir::cleanPath((QCoreApplication::applicationDirPath() + QLatin1String("/../qtc-qmldump/") + QString::number(hash))) + slash << (QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QLatin1String("/qtc-qmldump/") + QString::number(hash)) + slash; return directories; } QString QmlDumpTool::qmlDumpPath() { QString path; ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject(); path = Qt4ProjectManager::QmlDumpTool::toolForProject(activeProject); // ### this is needed for qmlproject and cmake project support, but may not work in all cases. if (path.isEmpty()) { // Try to locate default path in Qt Versions QtVersionManager *qtVersions = QtVersionManager::instance(); foreach (QtVersion *version, qtVersions->validVersions()) { if (version->supportsTargetId(Constants::DESKTOP_TARGET_ID)) { const QString qtInstallData = version->versionInfo().value("QT_INSTALL_DATA"); path = QmlDumpTool::toolByInstallData(qtInstallData); if (!path.isEmpty()) { break; } } } } QFileInfo qmldumpFileInfo(path); if (!qmldumpFileInfo.exists()) { //qWarning() << "QmlDumpTool::qmlDumpPath: qmldump executable does not exist at" << path; path.clear(); } else if (!qmldumpFileInfo.isFile()) { qWarning() << "QmlDumpTool::qmlDumpPath: " << path << " is not a file"; path.clear(); } return path; } } // namespace
Disable warning message for qmldump
Disable warning message for qmldump Discussed-with: fkleint
C++
lgpl-2.1
azat/qtcreator,KDE/android-qt-creator,syntheticpp/qt-creator,xianian/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,duythanhphan/qt-creator,danimo/qt-creator,darksylinc/qt-creator,dmik/qt-creator-os2,colede/qtcreator,duythanhphan/qt-creator,farseerri/git_code,azat/qtcreator,martyone/sailfish-qtcreator,renatofilho/QtCreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,hdweiss/qt-creator-visualizer,AltarBeastiful/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,darksylinc/qt-creator,yinyunqiao/qtcreator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,yinyunqiao/qtcreator,Distrotech/qtcreator,ostash/qt-creator-i18n-uk,xianian/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,sandsmark/qtcreator-minimap,kuba1/qtcreator,syntheticpp/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,duythanhphan/qt-creator,danimo/qt-creator,bakaiadam/collaborative_qt_creator,jonnor/qt-creator,sandsmark/qtcreator-minimap,KDAB/KDAB-Creator,omniacreator/qtcreator,farseerri/git_code,ostash/qt-creator-i18n-uk,amyvmiwei/qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,azat/qtcreator,AltarBeastiful/qt-creator,renatofilho/QtCreator,dmik/qt-creator-os2,omniacreator/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,xianian/qt-creator,ostash/qt-creator-i18n-uk,bakaiadam/collaborative_qt_creator,yinyunqiao/qtcreator,KDAB/KDAB-Creator,colede/qtcreator,jonnor/qt-creator,dmik/qt-creator-os2,jonnor/qt-creator,yinyunqiao/qtcreator,ostash/qt-creator-i18n-uk,darksylinc/qt-creator,yinyunqiao/qtcreator,richardmg/qtcreator,sandsmark/qtcreator-minimap,danimo/qt-creator,farseerri/git_code,farseerri/git_code,AltarBeastiful/qt-creator,richardmg/qtcreator,syntheticpp/qt-creator,farseerri/git_code,sandsmark/qtcreator-minimap,malikcjm/qtcreator,danimo/qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,dmik/qt-creator-os2,yinyunqiao/qtcreator,Distrotech/qtcreator,darksylinc/qt-creator,duythanhphan/qt-creator,azat/qtcreator,dmik/qt-creator-os2,Distrotech/qtcreator,yinyunqiao/qtcreator,azat/qtcreator,malikcjm/qtcreator,pcacjr/qt-creator,duythanhphan/qt-creator,martyone/sailfish-qtcreator,KDAB/KDAB-Creator,jonnor/qt-creator,hdweiss/qt-creator-visualizer,bakaiadam/collaborative_qt_creator,syntheticpp/qt-creator,renatofilho/QtCreator,dmik/qt-creator-os2,colede/qtcreator,sandsmark/qtcreator-minimap,danimo/qt-creator,farseerri/git_code,ostash/qt-creator-i18n-uk,kuba1/qtcreator,colede/qtcreator,pcacjr/qt-creator,omniacreator/qtcreator,xianian/qt-creator,renatofilho/QtCreator,maui-packages/qt-creator,KDE/android-qt-creator,richardmg/qtcreator,malikcjm/qtcreator,KDE/android-qt-creator,malikcjm/qtcreator,kuba1/qtcreator,omniacreator/qtcreator,amyvmiwei/qt-creator,KDAB/KDAB-Creator,maui-packages/qt-creator,syntheticpp/qt-creator,kuba1/qtcreator,syntheticpp/qt-creator,richardmg/qtcreator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,pcacjr/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,pcacjr/qt-creator,colede/qtcreator,pcacjr/qt-creator,AltarBeastiful/qt-creator,bakaiadam/collaborative_qt_creator,xianian/qt-creator,amyvmiwei/qt-creator,malikcjm/qtcreator,richardmg/qtcreator,maui-packages/qt-creator,darksylinc/qt-creator,KDE/android-qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,Distrotech/qtcreator,Distrotech/qtcreator,ostash/qt-creator-i18n-uk,duythanhphan/qt-creator,jonnor/qt-creator,xianian/qt-creator,hdweiss/qt-creator-visualizer,richardmg/qtcreator,kuba1/qtcreator,KDAB/KDAB-Creator,renatofilho/QtCreator,darksylinc/qt-creator,azat/qtcreator,bakaiadam/collaborative_qt_creator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,martyone/sailfish-qtcreator,malikcjm/qtcreator,danimo/qt-creator,jonnor/qt-creator,colede/qtcreator,kuba1/qtcreator,KDAB/KDAB-Creator,danimo/qt-creator,dmik/qt-creator-os2,danimo/qt-creator,pcacjr/qt-creator,duythanhphan/qt-creator,Distrotech/qtcreator,xianian/qt-creator,darksylinc/qt-creator,pcacjr/qt-creator,omniacreator/qtcreator,danimo/qt-creator,syntheticpp/qt-creator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,hdweiss/qt-creator-visualizer,sandsmark/qtcreator-minimap,farseerri/git_code,renatofilho/QtCreator,xianian/qt-creator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,farseerri/git_code
19b4cdc7292d400a5f63f20f69a20f89c3a478cf
src/breakpad/DumpSyms.cpp
src/breakpad/DumpSyms.cpp
/* * DumpSyms.cpp * OpenLieroX * * Created by Albert Zeyer on 18.10.09. * Code under LGPL. * */ #include "DumpSyms.h" #ifdef WIN32 #include <stdio.h> #include <string> #include "FindFile.h" #include "common/windows/pdb_source_line_writer.h" using std::wstring; using google_breakpad::PDBSourceLineWriter; bool DumpSyms(const std::string& bin, const std::string& symfile) { FILE* out = fopen(Utf8ToSystemNative(symfile).c_str(), "wb"); if(!out) return false; PDBSourceLineWriter writer; if (!writer.Open(Utf8ToSystemNative(bin), PDBSourceLineWriter::ANY_FILE)) { fclose(out); return false; } if (!writer.WriteMap(out)) { fclose(out); return false; } writer.Close(); fclose(out); return true; } #else #include <string> #include <cstdio> #include "common/linux/dump_symbols.h" using namespace google_breakpad; bool DumpSyms(const std::string& bin, const std::string& symfile) { FILE* out = fopen(symfile.c_str(), "wb"); if(!out) return false; DumpSymbols dumper; bool res = dumper.WriteSymbolFile(bin, out); fclose(out); return res; } #endif
/* * DumpSyms.cpp * OpenLieroX * * Created by Albert Zeyer on 18.10.09. * Code under LGPL. * */ #include "DumpSyms.h" #ifdef WIN32 #include <stdio.h> #include <string> #include "FindFile.h" #include "common/windows/pdb_source_line_writer.h" using std::wstring; using google_breakpad::PDBSourceLineWriter; bool DumpSyms(const std::string& bin, const std::string& symfile) { FILE* out = fopen(Utf8ToSystemNative(symfile).c_str(), "wb"); if(!out) return false; PDBSourceLineWriter writer; if (!writer.Open(Utf8ToUtf16(bin), PDBSourceLineWriter::ANY_FILE)) { fclose(out); return false; } if (!writer.WriteMap(out)) { fclose(out); return false; } writer.Close(); fclose(out); return true; } #else #include <string> #include <cstdio> #include "common/linux/dump_symbols.h" using namespace google_breakpad; bool DumpSyms(const std::string& bin, const std::string& symfile) { FILE* out = fopen(symfile.c_str(), "wb"); if(!out) return false; DumpSymbols dumper; bool res = dumper.WriteSymbolFile(bin, out); fclose(out); return res; } #endif
Fix for Utf8->Utf16 conversion
Fix for Utf8->Utf16 conversion
C++
lgpl-2.1
ProfessorKaos64/openlierox,ProfessorKaos64/openlierox,ProfessorKaos64/openlierox,ProfessorKaos64/openlierox,ProfessorKaos64/openlierox,ProfessorKaos64/openlierox,ProfessorKaos64/openlierox
28a16e852dd82d987f8ee4465e063e0a26d5ede6
Infovis/vtkStatisticsAlgorithm.cxx
Infovis/vtkStatisticsAlgorithm.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkStatisticsAlgorithm.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkToolkits.h" #include "vtkStatisticsAlgorithm.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include "vtkTable.h" vtkCxxRevisionMacro(vtkStatisticsAlgorithm, "1.20"); // ---------------------------------------------------------------------- vtkStatisticsAlgorithm::vtkStatisticsAlgorithm() { this->SetNumberOfInputPorts( 2 ); this->SetNumberOfOutputPorts( 2 ); // If not told otherwise, only run Learn option this->Learn = true; this->Derive = true; this->FullWasDerived = false; this->Assess = false; this->AssessNames = vtkStringArray::New(); this->AssessParameters = 0; } // ---------------------------------------------------------------------- vtkStatisticsAlgorithm::~vtkStatisticsAlgorithm() { if ( this->AssessNames ) { this->AssessNames->Delete(); } } // ---------------------------------------------------------------------- void vtkStatisticsAlgorithm::PrintSelf( ostream &os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "NumberOfVariables: " << this->NumberOfVariables << endl; os << indent << "SampleSize: " << this->SampleSize << endl; os << indent << "Learn: " << this->Learn << endl; os << indent << "Derive: " << this->Derive << endl; os << indent << "FullWasDerived: " << this->FullWasDerived << endl; os << indent << "Assess: " << this->Assess << endl; if ( this->AssessParameters ) { this->AssessParameters->PrintSelf( os, indent.GetNextIndent() ); } if ( this->AssessNames ) { this->AssessNames->PrintSelf( os, indent.GetNextIndent() ); } } // ---------------------------------------------------------------------- void vtkStatisticsAlgorithm::SetAssessParameter( vtkIdType id, vtkStdString name ) { if ( id >= 0 && id < this->AssessParameters->GetNumberOfValues() ) { this->AssessParameters->SetValue( id, name ); this->Modified(); } } // ---------------------------------------------------------------------- vtkStdString vtkStatisticsAlgorithm::SetAssessParameter( vtkIdType id ) { if ( id >= 0 && id < this->AssessParameters->GetNumberOfValues() ) { return this->AssessParameters->GetValue( id ); } return 0; } // ---------------------------------------------------------------------- int vtkStatisticsAlgorithm::RequestData( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) { // Extract input data table vtkTable* inData = vtkTable::GetData( inputVector[0], 0 ); if ( ! inData ) { return 1; } this->SampleSize = inData->GetNumberOfRows(); // Extract output tables vtkTable* outData = vtkTable::GetData( outputVector, 0 ); vtkTable* outMeta1 = vtkTable::GetData( outputVector, 1 ); vtkTable* outMeta2 = vtkTable::GetData( outputVector, 2 ); outData->ShallowCopy( inData ); vtkTable* inMeta; if ( this->Learn ) { this->ExecuteLearn( inData, outMeta1 ); // The full model (if available) is no longer in sync this->FullWasDerived = false; } else { // Extract input meta table inMeta = vtkTable::GetData( inputVector[1], 0 ); if ( ! inMeta ) { vtkWarningMacro( "No model available. Doing nothing." ); return 1; } outMeta1->ShallowCopy( inMeta ); // A full model was not derived so far this->FullWasDerived = false; } if ( this->Derive ) { this->ExecuteDerive( outMeta1 ); // A full model was derived from the minimal model this->FullWasDerived = true; } if ( this->Assess ) { this->ExecuteAssess( inData, outMeta1, outData, outMeta2 ); } return 1; } // ---------------------------------------------------------------------- int vtkStatisticsAlgorithm::FillInputPortInformation( int port, vtkInformation* info ) { if ( port == 0 ) { info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable" ); return 1; } else if ( port == 1 ) { info->Set( vtkAlgorithm::INPUT_IS_OPTIONAL(), 1 ); info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable" ); return 1; } return 0; } // ---------------------------------------------------------------------- int vtkStatisticsAlgorithm::FillOutputPortInformation( int port, vtkInformation* info ) { if ( port >= 0 ) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTable" ); return 1; } return 0; } //--------------------------------------------------------------------------- void vtkStatisticsAlgorithm::SetInputStatisticsConnection( vtkAlgorithmOutput* in ) { this->SetInputConnection( 1, in ); }
/*========================================================================= Program: Visualization Toolkit Module: vtkStatisticsAlgorithm.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkToolkits.h" #include "vtkStatisticsAlgorithm.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include "vtkTable.h" vtkCxxRevisionMacro(vtkStatisticsAlgorithm, "1.21"); // ---------------------------------------------------------------------- vtkStatisticsAlgorithm::vtkStatisticsAlgorithm() { this->SetNumberOfInputPorts( 2 ); this->SetNumberOfOutputPorts( 2 ); // If not told otherwise, only run Learn option this->Learn = true; this->Derive = true; this->FullWasDerived = false; this->Assess = false; this->AssessNames = vtkStringArray::New(); this->AssessParameters = 0; } // ---------------------------------------------------------------------- vtkStatisticsAlgorithm::~vtkStatisticsAlgorithm() { if ( this->AssessNames ) { this->AssessNames->Delete(); } } // ---------------------------------------------------------------------- void vtkStatisticsAlgorithm::PrintSelf( ostream &os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "NumberOfVariables: " << this->NumberOfVariables << endl; os << indent << "SampleSize: " << this->SampleSize << endl; os << indent << "Learn: " << this->Learn << endl; os << indent << "Derive: " << this->Derive << endl; os << indent << "FullWasDerived: " << this->FullWasDerived << endl; os << indent << "Assess: " << this->Assess << endl; if ( this->AssessParameters ) { this->AssessParameters->PrintSelf( os, indent.GetNextIndent() ); } if ( this->AssessNames ) { this->AssessNames->PrintSelf( os, indent.GetNextIndent() ); } } // ---------------------------------------------------------------------- void vtkStatisticsAlgorithm::SetAssessParameter( vtkIdType id, vtkStdString name ) { if ( id >= 0 && id < this->AssessParameters->GetNumberOfValues() ) { this->AssessParameters->SetValue( id, name ); this->Modified(); } } // ---------------------------------------------------------------------- vtkStdString vtkStatisticsAlgorithm::SetAssessParameter( vtkIdType id ) { if ( id >= 0 && id < this->AssessParameters->GetNumberOfValues() ) { return this->AssessParameters->GetValue( id ); } return 0; } // ---------------------------------------------------------------------- int vtkStatisticsAlgorithm::RequestData( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) { // Extract input data table vtkTable* inData = vtkTable::GetData( inputVector[0], 0 ); if ( ! inData ) { return 1; } this->SampleSize = inData->GetNumberOfRows(); // Extract output tables vtkTable* outData = vtkTable::GetData( outputVector, 0 ); vtkTable* outMeta1 = vtkTable::GetData( outputVector, 1 ); vtkTable* outMeta2; // Unused for now outData->ShallowCopy( inData ); vtkTable* inMeta; if ( this->Learn ) { this->ExecuteLearn( inData, outMeta1 ); // The full model (if available) is no longer in sync this->FullWasDerived = false; } else { // Extract input meta table inMeta = vtkTable::GetData( inputVector[1], 0 ); if ( ! inMeta ) { vtkWarningMacro( "No model available. Doing nothing." ); return 1; } outMeta1->ShallowCopy( inMeta ); // A full model was not derived so far this->FullWasDerived = false; } if ( this->Derive ) { this->ExecuteDerive( outMeta1 ); // A full model was derived from the minimal model this->FullWasDerived = true; } if ( this->Assess ) { this->ExecuteAssess( inData, outMeta1, outData, outMeta2 ); } return 1; } // ---------------------------------------------------------------------- int vtkStatisticsAlgorithm::FillInputPortInformation( int port, vtkInformation* info ) { if ( port == 0 ) { info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable" ); return 1; } else if ( port == 1 ) { info->Set( vtkAlgorithm::INPUT_IS_OPTIONAL(), 1 ); info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable" ); return 1; } return 0; } // ---------------------------------------------------------------------- int vtkStatisticsAlgorithm::FillOutputPortInformation( int port, vtkInformation* info ) { if ( port >= 0 ) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTable" ); return 1; } return 0; } //--------------------------------------------------------------------------- void vtkStatisticsAlgorithm::SetInputStatisticsConnection( vtkAlgorithmOutput* in ) { this->SetInputConnection( 1, in ); }
document the fact that the Validate output port (3rd -- #2) is not used for now.
STYLE: document the fact that the Validate output port (3rd -- #2) is not used for now.
C++
bsd-3-clause
jmerkow/VTK,cjh1/VTK,jmerkow/VTK,keithroe/vtkoptix,johnkit/vtk-dev,naucoin/VTKSlicerWidgets,aashish24/VTK-old,daviddoria/PointGraphsPhase1,biddisco/VTK,gram526/VTK,demarle/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,spthaolt/VTK,hendradarwin/VTK,candy7393/VTK,aashish24/VTK-old,sumedhasingla/VTK,sumedhasingla/VTK,jmerkow/VTK,spthaolt/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,arnaudgelas/VTK,collects/VTK,jmerkow/VTK,msmolens/VTK,keithroe/vtkoptix,sumedhasingla/VTK,demarle/VTK,jeffbaumes/jeffbaumes-vtk,johnkit/vtk-dev,sankhesh/VTK,candy7393/VTK,aashish24/VTK-old,demarle/VTK,biddisco/VTK,naucoin/VTKSlicerWidgets,demarle/VTK,msmolens/VTK,sankhesh/VTK,keithroe/vtkoptix,SimVascular/VTK,sumedhasingla/VTK,sankhesh/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,sumedhasingla/VTK,hendradarwin/VTK,gram526/VTK,spthaolt/VTK,mspark93/VTK,berendkleinhaneveld/VTK,msmolens/VTK,msmolens/VTK,hendradarwin/VTK,collects/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,candy7393/VTK,gram526/VTK,jmerkow/VTK,gram526/VTK,biddisco/VTK,arnaudgelas/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,arnaudgelas/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,spthaolt/VTK,cjh1/VTK,sankhesh/VTK,spthaolt/VTK,sankhesh/VTK,ashray/VTK-EVM,mspark93/VTK,spthaolt/VTK,ashray/VTK-EVM,SimVascular/VTK,aashish24/VTK-old,demarle/VTK,cjh1/VTK,hendradarwin/VTK,keithroe/vtkoptix,johnkit/vtk-dev,cjh1/VTK,keithroe/vtkoptix,sumedhasingla/VTK,SimVascular/VTK,johnkit/vtk-dev,demarle/VTK,SimVascular/VTK,biddisco/VTK,sankhesh/VTK,hendradarwin/VTK,Wuteyan/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,daviddoria/PointGraphsPhase1,gram526/VTK,sankhesh/VTK,aashish24/VTK-old,mspark93/VTK,Wuteyan/VTK,candy7393/VTK,arnaudgelas/VTK,ashray/VTK-EVM,mspark93/VTK,demarle/VTK,mspark93/VTK,ashray/VTK-EVM,arnaudgelas/VTK,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,candy7393/VTK,mspark93/VTK,keithroe/vtkoptix,cjh1/VTK,hendradarwin/VTK,SimVascular/VTK,biddisco/VTK,johnkit/vtk-dev,candy7393/VTK,daviddoria/PointGraphsPhase1,arnaudgelas/VTK,biddisco/VTK,collects/VTK,Wuteyan/VTK,spthaolt/VTK,jmerkow/VTK,gram526/VTK,msmolens/VTK,SimVascular/VTK,mspark93/VTK,daviddoria/PointGraphsPhase1,keithroe/vtkoptix,jmerkow/VTK,johnkit/vtk-dev,collects/VTK,ashray/VTK-EVM,gram526/VTK,candy7393/VTK,Wuteyan/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,ashray/VTK-EVM,collects/VTK,hendradarwin/VTK,johnkit/vtk-dev,biddisco/VTK,sankhesh/VTK,berendkleinhaneveld/VTK,aashish24/VTK-old,ashray/VTK-EVM,cjh1/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,Wuteyan/VTK,sumedhasingla/VTK,candy7393/VTK,collects/VTK,jmerkow/VTK,keithroe/vtkoptix,Wuteyan/VTK
66a73128dd94ebc2fe86613e99895e451b0b4260
src/xenia/base/debugging_posix.cc
src/xenia/base/debugging_posix.cc
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2017 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/debugging.h" #include <signal.h> #include "xenia/base/string_buffer.h" namespace xe { namespace debugging { bool IsDebuggerAttached() { return false; } void Break() { raise(SIGTRAP); } void DebugPrint(const char* fmt, ...) { StringBuffer buff; va_list va; va_start(va, fmt); buff.AppendVarargs(fmt, va); va_end(va); // OutputDebugStringA(buff.GetString()); } } // namespace debugging } // namespace xe
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2017 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/debugging.h" #include <cstdarg> #include <signal.h> #include "xenia/base/string_buffer.h" namespace xe { namespace debugging { bool IsDebuggerAttached() { return false; } void Break() { raise(SIGTRAP); } void DebugPrint(const char* fmt, ...) { StringBuffer buff; va_list va; va_start(va, fmt); buff.AppendVarargs(fmt, va); va_end(va); // OutputDebugStringA(buff.GetString()); } } // namespace debugging } // namespace xe
Fix debugging_posix.cc
Fix debugging_posix.cc
C++
bsd-3-clause
sephiroth99/xenia,maxton/xenia,maxton/xenia,maxton/xenia,sephiroth99/xenia,sephiroth99/xenia
90b8163d5465adcaa3e56c6c30f3060ace85a71e
Machines/Enterprise/Enterprise.cpp
Machines/Enterprise/Enterprise.cpp
// // Enterprise.cpp // Clock Signal // // Created by Thomas Harte on 10/06/2021. // Copyright © 2021 Thomas Harte. All rights reserved. // #include "Enterprise.hpp" #include "Nick.hpp" #include "../MachineTypes.hpp" #include "../../Processors/Z80/Z80.hpp" #include "../../Analyser/Static/Enterprise/Target.hpp" #include "../../ClockReceiver/JustInTime.hpp" namespace Enterprise { /* Notes to self on timing: Nick divides each line into 57 windows; each window lasts 16 cycles and dedicates the first 10 of those to VRAM accesses, leaving the final six for a Z80 video RAM access if one has been requested. The Z80 has a separate, asynchronous 4Mhz clock. That's that. The documentation is also very forward in emphasising that Nick generates phaselocked (i.e. in-phase) PAL video. So: 57*16 = 912 cycles/line. A standard PAL line lasts 64µs and during that time outputs 283.7516 colour cycles. I shall _guess_ that the Enterprise stretches each line to 284 colour cycles rather than reducing it to 283. Therefore 912 cycles occurs in 284/283.7516 * 64 µs, which would appear to give an ideal clock rate of around: 14,237,536.27 Hz. Given that there's always some leeway in a receiver, I'm modelling that as 14,237,536 cycles, which means that Nick runs 444923/125000 times as fast as the Z80. Which is around 3.56 times as fast. If that's true then the 6-cycle window is around 1.69 Z80 cycles long. Given that the Z80 clock in an Enterprise can be stopped in half-cycle increments only, the Z80 can only be guaranteed to have around a 1.19 cycle minimum for its actual access. I'm therefore further postulating that the clock stoppage takes place so as to align the final cycle of a relevant access over the available window. */ class ConcreteMachine: public CPU::Z80::BusHandler, public Machine, public MachineTypes::ScanProducer, public MachineTypes::TimedMachine { public: ConcreteMachine([[maybe_unused]] const Analyser::Static::Enterprise::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) : z80_(*this), nick_(ram_.end() - 65536) { // Request a clock of 4Mhz; this'll be mapped upwards for Nick and Dave elsewhere. set_clock_rate(4'000'000); constexpr ROM::Name exos_name = ROM::Name::EnterpriseEXOS; const auto request = ROM::Request(exos_name); auto roms = rom_fetcher(request); if(!request.validate(roms)) { throw ROMMachine::Error::MissingROMs; } const auto &exos = roms.find(exos_name)->second; memcpy(exos_.data(), exos.data(), std::min(exos_.size(), exos.size())); // Take a reasonable guess at the initial memory configuration: // put EXOS into the first bank since this is a Z80 and therefore // starts from address 0; the third instruction in EXOS is a jump // to $c02e so it's reasonable to assume EXOS is in the highest bank // too, and it appears to act correctly if it's the first 16kb that's // in the highest bank. From there I guess: all banks are initialised // to 0. page<0>(0x00); page<1>(0x00); page<2>(0x00); page<3>(0x00); } // MARK: - Z80::BusHandler. forceinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) { using PartialMachineCycle = CPU::Z80::PartialMachineCycle; const uint16_t address = cycle.address ? *cycle.address : 0x0000; // TODO: possibly apply an access penalty. nick_ += cycle.length; switch(cycle.operation) { default: break; case CPU::Z80::PartialMachineCycle::Input: switch(address & 0xff) { default: printf("Unhandled input: %04x\n", address); assert(false); break; case 0xb0: *cycle.value = pages_[0]; break; case 0xb1: *cycle.value = pages_[1]; break; case 0xb2: *cycle.value = pages_[2]; break; case 0xb3: *cycle.value = pages_[3]; break; case 0xb4: printf("TODO: interrupt enable/reset read\n"); *cycle.value = 0xff; break; case 0xb5: printf("TODO: Keyboard/joystick input\n"); *cycle.value = 0xff; break; } break; case CPU::Z80::PartialMachineCycle::Output: switch(address & 0xff) { default: printf("Unhandled output: %04x\n", address); assert(false); break; case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: nick_->write(address, *cycle.value); break; case 0xb0: page<0>(*cycle.value); break; case 0xb1: page<1>(*cycle.value); break; case 0xb2: page<2>(*cycle.value); break; case 0xb3: page<3>(*cycle.value); break; case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: printf("TODO: audio adjust %04x <- %02x\n", address, *cycle.value); break; case 0xb4: printf("TODO: interrupt enable/reset write %02x\n", *cycle.value); break; case 0xb5: printf("TODO: Keyboard/etc %02x\n", *cycle.value); break; case 0xb6: printf("TODO: printer output %02x\n", *cycle.value); break; case 0xbf: printf("TODO: Dave sysconfig %02x\n", *cycle.value); break; } break; case CPU::Z80::PartialMachineCycle::Read: case CPU::Z80::PartialMachineCycle::ReadOpcode: if(read_pointers_[address >> 14]) { *cycle.value = read_pointers_[address >> 14][address]; } else { *cycle.value = 0xff; } break; case CPU::Z80::PartialMachineCycle::Write: if(write_pointers_[address >> 14]) { write_pointers_[address >> 14][address] = *cycle.value; } break; } return HalfCycles(0); } void flush() { nick_.flush(); } private: // MARK: - Memory layout std::array<uint8_t, 256 * 1024> ram_; std::array<uint8_t, 32 * 1024> exos_; const uint8_t min_ram_slot_ = 0xff - 3; const uint8_t *read_pointers_[4] = {nullptr, nullptr, nullptr, nullptr}; uint8_t *write_pointers_[4] = {nullptr, nullptr, nullptr, nullptr}; uint8_t pages_[4] = {0x80, 0x80, 0x80, 0x80}; template <size_t slot> void page(uint8_t offset) { pages_[slot] = offset; if(offset < 2) { page<slot>(&exos_[offset * 0x4000], nullptr); return; } if(offset >= min_ram_slot_) { const auto ram_floor = 4194304 - ram_.size(); const size_t address = offset * 0x4000 - ram_floor; page<slot>(&ram_[address], &ram_[address]); return; } page<slot>(nullptr, nullptr); } template <size_t slot> void page(const uint8_t *read, uint8_t *write) { read_pointers_[slot] = read ? read - (slot * 0x4000) : nullptr; write_pointers_[slot] = write ? write - (slot * 0x4000) : nullptr; } // MARK: - ScanProducer void set_scan_target(Outputs::Display::ScanTarget *scan_target) override { nick_.last_valid()->set_scan_target(scan_target); } Outputs::Display::ScanStatus get_scaled_scan_status() const override { return nick_.last_valid()->get_scaled_scan_status(); } // MARK: - TimedMachine void run_for(const Cycles cycles) override { z80_.run_for(cycles); } // MARK: - Chips. CPU::Z80::Processor<ConcreteMachine, false, false> z80_; JustInTimeActor<Nick, HalfCycles, 444923, 125000> nick_; // Cf. timing guesses above. }; } using namespace Enterprise; Machine *Machine::Enterprise(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) { using Target = Analyser::Static::Enterprise::Target; const Target *const enterprise_target = dynamic_cast<const Target *>(target); return new Enterprise::ConcreteMachine(*enterprise_target, rom_fetcher); } Machine::~Machine() {}
// // Enterprise.cpp // Clock Signal // // Created by Thomas Harte on 10/06/2021. // Copyright © 2021 Thomas Harte. All rights reserved. // #include "Enterprise.hpp" #include "Nick.hpp" #include "../MachineTypes.hpp" #include "../../Processors/Z80/Z80.hpp" #include "../../Analyser/Static/Enterprise/Target.hpp" #include "../../ClockReceiver/JustInTime.hpp" namespace Enterprise { /* Notes to self on timing: Nick divides each line into 57 windows; each window lasts 16 cycles and dedicates the first 10 of those to VRAM accesses, leaving the final six for a Z80 video RAM access if one has been requested. The Z80 has a separate, asynchronous 4Mhz clock. That's that. The documentation is also very forward in emphasising that Nick generates phaselocked (i.e. in-phase) PAL video. So: 57*16 = 912 cycles/line. A standard PAL line lasts 64µs and during that time outputs 283.7516 colour cycles. I shall _guess_ that the Enterprise stretches each line to 284 colour cycles rather than reducing it to 283. Therefore 912 cycles occurs in 284/283.7516 * 64 µs, which would appear to give an ideal clock rate of around: 14,237,536.27 Hz. Given that there's always some leeway in a receiver, I'm modelling that as 14,237,536 cycles, which means that Nick runs 444923/125000 times as fast as the Z80. Which is around 3.56 times as fast. If that's true then the 6-cycle window is around 1.69 Z80 cycles long. Given that the Z80 clock in an Enterprise can be stopped in half-cycle increments only, the Z80 can only be guaranteed to have around a 1.19 cycle minimum for its actual access. I'm therefore further postulating that the clock stoppage takes place so as to align the final cycle of a relevant access over the available window. */ class ConcreteMachine: public CPU::Z80::BusHandler, public Machine, public MachineTypes::ScanProducer, public MachineTypes::TimedMachine { public: ConcreteMachine([[maybe_unused]] const Analyser::Static::Enterprise::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) : z80_(*this), nick_(ram_.end() - 65536) { // Request a clock of 4Mhz; this'll be mapped upwards for Nick and Dave elsewhere. set_clock_rate(4'000'000); constexpr ROM::Name exos_name = ROM::Name::EnterpriseEXOS; const auto request = ROM::Request(exos_name); auto roms = rom_fetcher(request); if(!request.validate(roms)) { throw ROMMachine::Error::MissingROMs; } const auto &exos = roms.find(exos_name)->second; memcpy(exos_.data(), exos.data(), std::min(exos_.size(), exos.size())); // Take a reasonable guess at the initial memory configuration: // put EXOS into the first bank since this is a Z80 and therefore // starts from address 0; the third instruction in EXOS is a jump // to $c02e so it's reasonable to assume EXOS is in the highest bank // too, and it appears to act correctly if it's the first 16kb that's // in the highest bank. From there I guess: all banks are initialised // to 0. page<0>(0x00); page<1>(0x00); page<2>(0x00); page<3>(0x00); } // MARK: - Z80::BusHandler. forceinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) { using PartialMachineCycle = CPU::Z80::PartialMachineCycle; const uint16_t address = cycle.address ? *cycle.address : 0x0000; // TODO: possibly apply an access penalty. nick_ += cycle.length; switch(cycle.operation) { default: break; case CPU::Z80::PartialMachineCycle::Input: switch(address & 0xff) { default: printf("Unhandled input: %04x\n", address); assert(false); break; case 0xb0: *cycle.value = pages_[0]; break; case 0xb1: *cycle.value = pages_[1]; break; case 0xb2: *cycle.value = pages_[2]; break; case 0xb3: *cycle.value = pages_[3]; break; case 0xb4: printf("TODO: interrupt enable/reset read\n"); *cycle.value = 0xff; break; case 0xb5: printf("TODO: Keyboard/joystick input\n"); *cycle.value = 0xff; break; } break; case CPU::Z80::PartialMachineCycle::Output: switch(address & 0xff) { default: printf("Unhandled output: %04x\n", address); assert(false); break; case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: nick_->write(address, *cycle.value); break; case 0xb0: page<0>(*cycle.value); break; case 0xb1: page<1>(*cycle.value); break; case 0xb2: page<2>(*cycle.value); break; case 0xb3: page<3>(*cycle.value); break; case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: printf("TODO: audio adjust %04x <- %02x\n", address, *cycle.value); break; case 0xb4: printf("TODO: interrupt enable/reset write %02x\n", *cycle.value); break; case 0xb5: printf("TODO: Keyboard/etc %02x\n", *cycle.value); break; case 0xb6: printf("TODO: printer output %02x\n", *cycle.value); break; case 0xbf: printf("TODO: Dave sysconfig %02x\n", *cycle.value); break; } break; case CPU::Z80::PartialMachineCycle::Read: case CPU::Z80::PartialMachineCycle::ReadOpcode: if(read_pointers_[address >> 14]) { *cycle.value = read_pointers_[address >> 14][address]; } else { *cycle.value = 0xff; } break; case CPU::Z80::PartialMachineCycle::Write: if(write_pointers_[address >> 14]) { write_pointers_[address >> 14][address] = *cycle.value; } break; } return HalfCycles(0); } void flush() { nick_.flush(); } private: // MARK: - Memory layout std::array<uint8_t, 256 * 1024> ram_; std::array<uint8_t, 32 * 1024> exos_; const uint8_t min_ram_slot_ = 0xff - 3; const uint8_t *read_pointers_[4] = {nullptr, nullptr, nullptr, nullptr}; uint8_t *write_pointers_[4] = {nullptr, nullptr, nullptr, nullptr}; uint8_t pages_[4] = {0x80, 0x80, 0x80, 0x80}; template <size_t slot> void page(uint8_t offset) { pages_[slot] = offset; if(offset < 2) { page<slot>(&exos_[offset * 0x4000], nullptr); return; } // Of whatever size of RAM I've declared above, use only the final portion. // This correlated with Nick always having been handed the final 64kb and, // at least while the RAM is the first thing declared above, does a little // to benefit data locality. Albeit not in a useful sense. if(offset >= min_ram_slot_) { const auto ram_floor = 4194304 - ram_.size(); const size_t address = offset * 0x4000 - ram_floor; page<slot>(&ram_[address], &ram_[address]); return; } page<slot>(nullptr, nullptr); } template <size_t slot> void page(const uint8_t *read, uint8_t *write) { read_pointers_[slot] = read ? read - (slot * 0x4000) : nullptr; write_pointers_[slot] = write ? write - (slot * 0x4000) : nullptr; } // MARK: - ScanProducer void set_scan_target(Outputs::Display::ScanTarget *scan_target) override { nick_.last_valid()->set_scan_target(scan_target); } Outputs::Display::ScanStatus get_scaled_scan_status() const override { return nick_.last_valid()->get_scaled_scan_status(); } // MARK: - TimedMachine void run_for(const Cycles cycles) override { z80_.run_for(cycles); } // MARK: - Chips. CPU::Z80::Processor<ConcreteMachine, false, false> z80_; JustInTimeActor<Nick, HalfCycles, 444923, 125000> nick_; // Cf. timing guesses above. }; } using namespace Enterprise; Machine *Machine::Enterprise(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) { using Target = Analyser::Static::Enterprise::Target; const Target *const enterprise_target = dynamic_cast<const Target *>(target); return new Enterprise::ConcreteMachine(*enterprise_target, rom_fetcher); } Machine::~Machine() {}
Add exposition.
Add exposition.
C++
mit
TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK
12907b6c94c13dc08baf7f8bb8b626ceb6be95a1
src/chemkit/conformer.cpp
src/chemkit/conformer.cpp
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <[email protected]> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ #include "conformer.h" #include <QHash> #include "molecule.h" namespace chemkit { // === ConformerPrivate ==================================================== // class ConformerPrivate { public: const Molecule *molecule; QHash<const Atom *, Point3> coordinates; }; // === Conformer =========================================================== // /// \class Conformer conformer.h chemkit/conformer.h /// \ingroup chemkit /// \brief The Conformer class represents an alternative set of atomic /// coordinates for a molecule. /// /// Conformer objects are created using the Molecule::addConformer() /// method and destroyed with the Molecule::removeConformer() method. // --- Construction and Destruction ---------------------------------------- // Conformer::Conformer(const Molecule *molecule) : d(new ConformerPrivate) { d->molecule = molecule; Q_FOREACH(const Atom *atom, molecule->atoms()){ setPosition(atom, atom->position()); } } Conformer::~Conformer() { delete d; } // --- Properties ---------------------------------------------------------- // /// Returns the molecule for the conformer. const Molecule* Conformer::molecule() const { return d->molecule; } // --- Coordinates --------------------------------------------------------- // /// Sets the coordinates for \p atom to \p position. void Conformer::setPosition(const Atom *atom, const Point3 &position) { d->coordinates[atom] = position; } /// Returns the position of the atom in the conformer. Point3 Conformer::position(const Atom *atom) const { return d->coordinates.value(atom, atom->position()); } } // end chemkit namespace
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <[email protected]> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ #include "conformer.h" #include <map> #include "molecule.h" namespace chemkit { // === ConformerPrivate ==================================================== // class ConformerPrivate { public: const Molecule *molecule; std::map<const Atom *, Point3> coordinates; }; // === Conformer =========================================================== // /// \class Conformer conformer.h chemkit/conformer.h /// \ingroup chemkit /// \brief The Conformer class represents an alternative set of atomic /// coordinates for a molecule. /// /// Conformer objects are created using the Molecule::addConformer() /// method and destroyed with the Molecule::removeConformer() method. // --- Construction and Destruction ---------------------------------------- // Conformer::Conformer(const Molecule *molecule) : d(new ConformerPrivate) { d->molecule = molecule; Q_FOREACH(const Atom *atom, molecule->atoms()){ setPosition(atom, atom->position()); } } Conformer::~Conformer() { delete d; } // --- Properties ---------------------------------------------------------- // /// Returns the molecule for the conformer. const Molecule* Conformer::molecule() const { return d->molecule; } // --- Coordinates --------------------------------------------------------- // /// Sets the coordinates for \p atom to \p position. void Conformer::setPosition(const Atom *atom, const Point3 &position) { d->coordinates[atom] = position; } /// Returns the position of the atom in the conformer. Point3 Conformer::position(const Atom *atom) const { std::map<const Atom *, Point3>::const_iterator location = d->coordinates.find(atom); if(location != d->coordinates.end()){ return location->second; } else{ return atom->position(); } } } // end chemkit namespace
Change Conformer to use std::map
Change Conformer to use std::map This changes the Conformer class to use a std::map instead of a QHash.
C++
bsd-3-clause
kylelutz/chemkit,kylelutz/chemkit,kylelutz/chemkit,kylelutz/chemkit
e1e5db7e88d3d0734fa6e7a64e6674dc7bcba8c7
tools/debugserver/source/DNBRegisterInfo.cpp
tools/debugserver/source/DNBRegisterInfo.cpp
//===-- DNBRegisterInfo.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Created by Greg Clayton on 8/3/07. // //===----------------------------------------------------------------------===// #include "DNBRegisterInfo.h" #include "DNBLog.h" #include <string.h> DNBRegisterValueClass::DNBRegisterValueClass(const DNBRegisterInfo *regInfo) { Clear(); if (regInfo) info = *regInfo; } void DNBRegisterValueClass::Clear() { memset(&info, 0, sizeof(DNBRegisterInfo)); memset(&value, 0, sizeof(value)); } bool DNBRegisterValueClass::IsValid() const { return info.name != NULL && info.type != InvalidRegType && info.size > 0 && info.size <= sizeof(value); } #define PRINT_COMMA_SEPARATOR \ do { \ if (pos < end) { \ if (i > 0) { \ strlcpy(pos, ", ", end - pos); \ pos += 2; \ } \ } \ } while (0) void DNBRegisterValueClass::Dump(const char *pre, const char *post) const { if (info.name != NULL) { char str[1024]; char *pos; char *end = str + sizeof(str); if (info.format == Hex) { switch (info.size) { case 0: snprintf(str, sizeof(str), "%s", "error: invalid register size of zero."); break; case 1: snprintf(str, sizeof(str), "0x%2.2x", value.uint8); break; case 2: snprintf(str, sizeof(str), "0x%4.4x", value.uint16); break; case 4: snprintf(str, sizeof(str), "0x%8.8x", value.uint32); break; case 8: snprintf(str, sizeof(str), "0x%16.16llx", value.uint64); break; case 16: snprintf(str, sizeof(str), "0x%16.16llx%16.16llx", value.v_uint64[0], value.v_uint64[1]); break; default: strlcpy(str, "0x", 3); pos = str + 2; for (uint32_t i = 0; i < info.size; ++i) { if (pos < end) pos += snprintf(pos, end - pos, "%2.2x", (uint32_t)value.v_uint8[i]); } break; } } else { switch (info.type) { case Uint: switch (info.size) { case 1: snprintf(str, sizeof(str), "%u", value.uint8); break; case 2: snprintf(str, sizeof(str), "%u", value.uint16); break; case 4: snprintf(str, sizeof(str), "%u", value.uint32); break; case 8: snprintf(str, sizeof(str), "%llu", value.uint64); break; default: snprintf(str, sizeof(str), "error: unsupported uint byte size %d.", info.size); break; } break; case Sint: switch (info.size) { case 1: snprintf(str, sizeof(str), "%d", value.sint8); break; case 2: snprintf(str, sizeof(str), "%d", value.sint16); break; case 4: snprintf(str, sizeof(str), "%d", value.sint32); break; case 8: snprintf(str, sizeof(str), "%lld", value.sint64); break; default: snprintf(str, sizeof(str), "error: unsupported sint byte size %d.", info.size); break; } break; case IEEE754: switch (info.size) { case 4: snprintf(str, sizeof(str), "%f", value.float32); break; case 8: snprintf(str, sizeof(str), "%g", value.float64); break; default: snprintf(str, sizeof(str), "error: unsupported float byte size %d.", info.size); break; } break; case Vector: if (info.size > 0) { switch (info.format) { case VectorOfSInt8: snprintf(str, sizeof(str), "%s", "sint8 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%d", (int32_t)value.v_sint8[i]); } strlcat(str, " }", sizeof(str)); break; default: DNBLogError( "unsupported vector format %d, defaulting to hex bytes.", info.format); LLVM_FALLTHROUGH; case VectorOfUInt8: snprintf(str, sizeof(str), "%s", "uint8 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%u", (uint32_t)value.v_uint8[i]); } break; case VectorOfSInt16: snprintf(str, sizeof(str), "%s", "sint16 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 2; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%d", (int32_t)value.v_sint16[i]); } break; case VectorOfUInt16: snprintf(str, sizeof(str), "%s", "uint16 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 2; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%u", (uint32_t)value.v_uint16[i]); } break; case VectorOfSInt32: snprintf(str, sizeof(str), "%s", "sint32 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 4; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%d", (int32_t)value.v_sint32[i]); } break; case VectorOfUInt32: snprintf(str, sizeof(str), "%s", "uint32 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 4; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%u", (uint32_t)value.v_uint32[i]); } break; case VectorOfFloat32: snprintf(str, sizeof(str), "%s", "float32 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 4; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%f", value.v_float32[i]); } break; case VectorOfUInt128: snprintf(str, sizeof(str), "%s", "uint128 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 16; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "0x%16.16llx%16.16llx", value.v_uint64[i], value.v_uint64[i + 1]); } break; } strlcat(str, " }", sizeof(str)); } else { snprintf(str, sizeof(str), "error: unsupported vector size %d.", info.size); } break; default: snprintf(str, sizeof(str), "error: unsupported register type %d.", info.type); break; } } DNBLog("%s%4s = %s%s", pre ? pre : "", info.name, str, post ? post : ""); } }
//===-- DNBRegisterInfo.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Created by Greg Clayton on 8/3/07. // //===----------------------------------------------------------------------===// #include "DNBRegisterInfo.h" #include "DNBLog.h" #include <llvm/Support/Compiler.h> #include <string.h> DNBRegisterValueClass::DNBRegisterValueClass(const DNBRegisterInfo *regInfo) { Clear(); if (regInfo) info = *regInfo; } void DNBRegisterValueClass::Clear() { memset(&info, 0, sizeof(DNBRegisterInfo)); memset(&value, 0, sizeof(value)); } bool DNBRegisterValueClass::IsValid() const { return info.name != NULL && info.type != InvalidRegType && info.size > 0 && info.size <= sizeof(value); } #define PRINT_COMMA_SEPARATOR \ do { \ if (pos < end) { \ if (i > 0) { \ strlcpy(pos, ", ", end - pos); \ pos += 2; \ } \ } \ } while (0) void DNBRegisterValueClass::Dump(const char *pre, const char *post) const { if (info.name != NULL) { char str[1024]; char *pos; char *end = str + sizeof(str); if (info.format == Hex) { switch (info.size) { case 0: snprintf(str, sizeof(str), "%s", "error: invalid register size of zero."); break; case 1: snprintf(str, sizeof(str), "0x%2.2x", value.uint8); break; case 2: snprintf(str, sizeof(str), "0x%4.4x", value.uint16); break; case 4: snprintf(str, sizeof(str), "0x%8.8x", value.uint32); break; case 8: snprintf(str, sizeof(str), "0x%16.16llx", value.uint64); break; case 16: snprintf(str, sizeof(str), "0x%16.16llx%16.16llx", value.v_uint64[0], value.v_uint64[1]); break; default: strlcpy(str, "0x", 3); pos = str + 2; for (uint32_t i = 0; i < info.size; ++i) { if (pos < end) pos += snprintf(pos, end - pos, "%2.2x", (uint32_t)value.v_uint8[i]); } break; } } else { switch (info.type) { case Uint: switch (info.size) { case 1: snprintf(str, sizeof(str), "%u", value.uint8); break; case 2: snprintf(str, sizeof(str), "%u", value.uint16); break; case 4: snprintf(str, sizeof(str), "%u", value.uint32); break; case 8: snprintf(str, sizeof(str), "%llu", value.uint64); break; default: snprintf(str, sizeof(str), "error: unsupported uint byte size %d.", info.size); break; } break; case Sint: switch (info.size) { case 1: snprintf(str, sizeof(str), "%d", value.sint8); break; case 2: snprintf(str, sizeof(str), "%d", value.sint16); break; case 4: snprintf(str, sizeof(str), "%d", value.sint32); break; case 8: snprintf(str, sizeof(str), "%lld", value.sint64); break; default: snprintf(str, sizeof(str), "error: unsupported sint byte size %d.", info.size); break; } break; case IEEE754: switch (info.size) { case 4: snprintf(str, sizeof(str), "%f", value.float32); break; case 8: snprintf(str, sizeof(str), "%g", value.float64); break; default: snprintf(str, sizeof(str), "error: unsupported float byte size %d.", info.size); break; } break; case Vector: if (info.size > 0) { switch (info.format) { case VectorOfSInt8: snprintf(str, sizeof(str), "%s", "sint8 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%d", (int32_t)value.v_sint8[i]); } strlcat(str, " }", sizeof(str)); break; default: DNBLogError( "unsupported vector format %d, defaulting to hex bytes.", info.format); LLVM_FALLTHROUGH; case VectorOfUInt8: snprintf(str, sizeof(str), "%s", "uint8 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%u", (uint32_t)value.v_uint8[i]); } break; case VectorOfSInt16: snprintf(str, sizeof(str), "%s", "sint16 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 2; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%d", (int32_t)value.v_sint16[i]); } break; case VectorOfUInt16: snprintf(str, sizeof(str), "%s", "uint16 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 2; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%u", (uint32_t)value.v_uint16[i]); } break; case VectorOfSInt32: snprintf(str, sizeof(str), "%s", "sint32 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 4; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%d", (int32_t)value.v_sint32[i]); } break; case VectorOfUInt32: snprintf(str, sizeof(str), "%s", "uint32 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 4; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%u", (uint32_t)value.v_uint32[i]); } break; case VectorOfFloat32: snprintf(str, sizeof(str), "%s", "float32 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 4; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "%f", value.v_float32[i]); } break; case VectorOfUInt128: snprintf(str, sizeof(str), "%s", "uint128 { "); pos = str + strlen(str); for (uint32_t i = 0; i < info.size / 16; ++i) { PRINT_COMMA_SEPARATOR; if (pos < end) pos += snprintf(pos, end - pos, "0x%16.16llx%16.16llx", value.v_uint64[i], value.v_uint64[i + 1]); } break; } strlcat(str, " }", sizeof(str)); } else { snprintf(str, sizeof(str), "error: unsupported vector size %d.", info.size); } break; default: snprintf(str, sizeof(str), "error: unsupported register type %d.", info.type); break; } } DNBLog("%s%4s = %s%s", pre ? pre : "", info.name, str, post ? post : ""); } }
Add missing include
Add missing include git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@346525 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb
4cca13ca50c4d95571d9007065747e789d0b2875
src/croi/roombaRoowifi.cpp
src/croi/roombaRoowifi.cpp
#include "roombaRoowifi.h" #include "croiUtil.h" #include "mapQGraphicsView.h" namespace Croi { RoombaRoowifi::RoombaRoowifi(PoiQGraphicsEllipseItem *startPoint, MapQGraphicsView* map, FleetManager *parent): IRoomba(startPoint, map, parent), reconnectCounter_(0), ip_("") { roowifi_ = new RooWifi(this); //TODO: implement own timer connect(roowifi_,SIGNAL(AutoCaptureUpdated()), qobject_cast<IRoomba*>(this), SLOT(sensorUpdateTimerTimeout())); IRoomba::updateState(); //call needed to have no null pointer in polygon_ } RoombaRoowifi::~RoombaRoowifi() { roowifi_->StopAutoCapture(); roowifi_->Disconnect(); } int RoombaRoowifi::rmb_connect(std::string ip) { if (reconnectCounter_ > 2) { reconnectCounter_ = 0; emit connectionFailed(); return -1; } ip_ = ip; QString qip = QString::fromStdString(ip); qDebug() << "set ip to:" << qip; roowifi_->SetIP(qip); roowifi_->Connect(); roowifi_->SetAutoCaptureTime(500); roowifi_->StartAutoCapture(); //Check after one second if the connection was established QTimer::singleShot(2000, this, SLOT(reconnectCallback_timerTimeout())); } void RoombaRoowifi::reconnectCallback_timerTimeout() { qDebug() << "reconnectCallback_timerTimeout"; //TODO: Better way needed, Checking charge rate is a hack to ensure that Roomba has waken up from sleep mode if (roowifi_->IsConnected() && roowifi_->Sensors.Charge > 0) { safeMode(); // Switch to safe mode automatically in connect reconnectCounter_ = 0; emit connectionEstablished(); } else { ++reconnectCounter_; this->disconnect(); // Try connecting again after 2 seconds QTimer::singleShot(2000, this, SLOT(disconnectCallback_timerTimeout())); qDebug() << "Trying to connect for: " << reconnectCounter_ << " time"; } } void RoombaRoowifi::disconnectCallback_timerTimeout() { qDebug() << "disconnectCallback_timerTimeout"; rmb_connect(ip_); } int RoombaRoowifi::disconnect() { roowifi_->StopAutoCapture(); roowifi_->Disconnect(); IRoomba::disconnect(); } void RoombaRoowifi::safeMode() { roowifi_->SafeMode(); int Song[14]; int SongDuration[14]; //Pop Corn part1 Song[0] = 82; SongDuration[0] = RooWifi::NotesDuration::SemiQuaver; Song[1] = 80; SongDuration[1] = RooWifi::NotesDuration::SemiQuaver; Song[2] = 82; SongDuration[2] = RooWifi::NotesDuration::SemiQuaver; Song[3] = 77; SongDuration[3] = RooWifi::NotesDuration::SemiQuaver; Song[4] = 73; SongDuration[4] = RooWifi::NotesDuration::SemiQuaver; Song[5] = 75; SongDuration[5] = RooWifi::NotesDuration::SemiQuaver; Song[6] = 70; SongDuration[6] = RooWifi::NotesDuration::Quaver; Song[7] = 82; SongDuration[7] = RooWifi::NotesDuration::SemiQuaver; Song[8] = 80; SongDuration[8] = RooWifi::NotesDuration::SemiQuaver; Song[9] = 82; SongDuration[9] = RooWifi::NotesDuration::SemiQuaver; Song[10] = 77; SongDuration[10] = RooWifi::NotesDuration::SemiQuaver; Song[11] = 73; SongDuration[11] = RooWifi::NotesDuration::SemiQuaver; Song[12] = 75; SongDuration[12] = RooWifi::NotesDuration::SemiQuaver; Song[13] = 70; SongDuration[13] = RooWifi::NotesDuration::Quaver; roowifi_->StoreSong( 1, 14, Song, SongDuration ); IRoomba::safeMode(); } void RoombaRoowifi::fullMode() { roowifi_->FullMode(); IRoomba::fullMode(); } void RoombaRoowifi::allMotorsOn() { roowifi_->AllCleaningMotors_On(); } void RoombaRoowifi::allMotorsOff() { roowifi_->AllCleaningMotors_Off(); } void RoombaRoowifi::clean() { // roowifi_->Clean(); IRoomba::clean(); } void RoombaRoowifi::goDock() { roowifi_->GoDock(); } float RoombaRoowifi::getBatteryLevel() { roowifi_->GetBatteryLevel(); } char RoombaRoowifi::getTemperature() { return roowifi_->Sensors.Temperature; } unsigned short RoombaRoowifi::getChargeLevel() { return roowifi_->Sensors.Charge; } double RoombaRoowifi::getDistance() { return roowifi_->Sensors.Distance; } double RoombaRoowifi::getAngle() { return roowifi_->Sensors.Angle; } bool RoombaRoowifi::getLeftBumb() { unsigned char bumps = roowifi_->Sensors.BumpsWheeldrops; if (bumps & 0x02) { return true; } return false; } bool RoombaRoowifi::getRightBumb() { unsigned char bumps = roowifi_->Sensors.BumpsWheeldrops; if (bumps & 0x01) { return true; } return false; } void RoombaRoowifi::drive(int velocity, int radius) { roowifi_->Drive(velocity, radius); IRoomba::drive(velocity, radius); } void RoombaRoowifi::drive(int velocity) { roowifi_->Drive(velocity, getRadius()); IRoomba::drive(velocity); } void RoombaRoowifi::playSong(int songNumber) { roowifi_->PlaySong(songNumber); } } //namespace Croi
#include "roombaRoowifi.h" #include "croiUtil.h" #include "mapQGraphicsView.h" namespace Croi { RoombaRoowifi::RoombaRoowifi(PoiQGraphicsEllipseItem *startPoint, MapQGraphicsView* map, FleetManager *parent): IRoomba(startPoint, map, parent), reconnectCounter_(0), ip_("") { roowifi_ = new RooWifi(this); //TODO: implement own timer connect(roowifi_,SIGNAL(AutoCaptureUpdated()), qobject_cast<IRoomba*>(this), SLOT(sensorUpdateTimerTimeout())); IRoomba::updateState(); //call needed to have no null pointer in polygon_ } RoombaRoowifi::~RoombaRoowifi() { roowifi_->StopAutoCapture(); roowifi_->Disconnect(); } int RoombaRoowifi::rmb_connect(std::string ip) { if (reconnectCounter_ > 2) { reconnectCounter_ = 0; emit connectionFailed(); return -1; } ip_ = ip; QString qip = QString::fromStdString(ip); qDebug() << "set ip to:" << qip; roowifi_->SetIP(qip); roowifi_->Connect(); roowifi_->SetAutoCaptureTime(500); roowifi_->StartAutoCapture(); //Check after one second if the connection was established QTimer::singleShot(2000, this, SLOT(reconnectCallback_timerTimeout())); } void RoombaRoowifi::reconnectCallback_timerTimeout() { qDebug() << "reconnectCallback_timerTimeout"; //TODO: Better way needed, Checking charge rate is a hack to ensure that Roomba has waken up from sleep mode if (roowifi_->IsConnected() && roowifi_->Sensors.Charge > 0) { safeMode(); // Switch to safe mode automatically in connect reconnectCounter_ = 0; emit connectionEstablished(); } else { ++reconnectCounter_; this->disconnect(); // Try connecting again after 2 seconds QTimer::singleShot(2000, this, SLOT(disconnectCallback_timerTimeout())); qDebug() << "Trying to connect for: " << reconnectCounter_ << " time"; } } void RoombaRoowifi::disconnectCallback_timerTimeout() { qDebug() << "disconnectCallback_timerTimeout"; rmb_connect(ip_); } int RoombaRoowifi::disconnect() { roowifi_->StopAutoCapture(); roowifi_->Disconnect(); IRoomba::disconnect(); } void RoombaRoowifi::safeMode() { roowifi_->SafeMode(); int Song[14]; int SongDuration[14]; //Pop Corn part1 Song[0] = 82; SongDuration[0] = RooWifi::NotesDuration::SemiQuaver; Song[1] = 80; SongDuration[1] = RooWifi::NotesDuration::SemiQuaver; Song[2] = 82; SongDuration[2] = RooWifi::NotesDuration::SemiQuaver; Song[3] = 77; SongDuration[3] = RooWifi::NotesDuration::SemiQuaver; Song[4] = 73; SongDuration[4] = RooWifi::NotesDuration::SemiQuaver; Song[5] = 75; SongDuration[5] = RooWifi::NotesDuration::SemiQuaver; Song[6] = 70; SongDuration[6] = RooWifi::NotesDuration::Quaver; Song[7] = 82; SongDuration[7] = RooWifi::NotesDuration::SemiQuaver; Song[8] = 80; SongDuration[8] = RooWifi::NotesDuration::SemiQuaver; Song[9] = 82; SongDuration[9] = RooWifi::NotesDuration::SemiQuaver; Song[10] = 77; SongDuration[10] = RooWifi::NotesDuration::SemiQuaver; Song[11] = 73; SongDuration[11] = RooWifi::NotesDuration::SemiQuaver; Song[12] = 75; SongDuration[12] = RooWifi::NotesDuration::SemiQuaver; Song[13] = 70; SongDuration[13] = RooWifi::NotesDuration::Quaver; roowifi_->StoreSong( 1, 14, Song, SongDuration ); IRoomba::safeMode(); } void RoombaRoowifi::fullMode() { roowifi_->FullMode(); IRoomba::fullMode(); } void RoombaRoowifi::allMotorsOn() { roowifi_->AllCleaningMotors_On(); } void RoombaRoowifi::allMotorsOff() { roowifi_->AllCleaningMotors_Off(); } void RoombaRoowifi::clean() { // roowifi_->Clean(); IRoomba::clean(); } void RoombaRoowifi::goDock() { roowifi_->GoDock(); } float RoombaRoowifi::getBatteryLevel() { return roowifi_->GetBatteryLevel(); } char RoombaRoowifi::getTemperature() { return roowifi_->Sensors.Temperature; } unsigned short RoombaRoowifi::getChargeLevel() { return roowifi_->Sensors.Charge; } double RoombaRoowifi::getDistance() { return roowifi_->Sensors.Distance; } double RoombaRoowifi::getAngle() { return roowifi_->Sensors.Angle; } bool RoombaRoowifi::getLeftBumb() { unsigned char bumps = roowifi_->Sensors.BumpsWheeldrops; if (bumps & 0x02) { return true; } return false; } bool RoombaRoowifi::getRightBumb() { unsigned char bumps = roowifi_->Sensors.BumpsWheeldrops; if (bumps & 0x01) { return true; } return false; } void RoombaRoowifi::drive(int velocity, int radius) { roowifi_->Drive(velocity, radius); IRoomba::drive(velocity, radius); } void RoombaRoowifi::drive(int velocity) { roowifi_->Drive(velocity, getRadius()); IRoomba::drive(velocity); } void RoombaRoowifi::playSong(int songNumber) { roowifi_->PlaySong(songNumber); } } //namespace Croi
Fix the battery level
ROOWIFI: Fix the battery level
C++
mit
joonaspessi/rotfl
24e325fdd98555d9fceffb0feeb1582d411b3c6d
include/stack.hpp
include/stack.hpp
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {} auto bitset::set(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; } else throw; } auto bitset::reset(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; } else throw; } auto bitset::test(size_t index) -> bool { if (index >= 0 && index < size_) { return !ptr_[index]; } else throw; } auto bitset::size() -> size_t { return size_; } auto bitset::counter() -> size_t { return counter_; } template <typename T> class allocator { public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; auto swap(allocator & other) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> class stack { public: explicit stack(size_t size = 0); auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; auto throw_is_empty() const -> void; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {}; template<typename T> allocator<T>::allocator(allocator const& other) : ptr_(static_cast<T*>(operator new(other.size_))), size_(other.size_), map_(std::make_unique<bitset>(size_)){ for (size_t i; i < size_; i++) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator() { operator delete(ptr_); } template<typename T> auto allocator<T>::resize() -> void { allocator<T> buff(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]); this->swap(buff); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void { if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) { new(ptr)T(value); map_->set(ptr - ptr_); } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * ptr) -> void { ptr->~T(); map_->reset(ptr-ptr_); } template<typename T> auto allocator<T>::destroy(T * first, T * last) -> void { for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t { return map_->counter_; } template<typename T> auto allocator<T>::full() const -> bool { return map_->counter_==size_; } template<typename T> auto allocator<T>::empty() const -> bool { return map_->counter_==0; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(map_, other.map_); std::swap(size_, other.size_); } template <typename T> size_t stack<T>::count() const { return allocator_.count_; } template <typename T> stack<T>::stack(size_t size) :allocator<T>(size) {} template <typename T> void stack<T>::push(T const &item) { if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_> 0) { --allocator<T>::count_; } else throw_is_empty(); } template<typename T> auto stack<T>::top() -> T & { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::top() const -> T const & { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::throw_is_empty() const -> void { throw("Stack is empty!"); } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp(right.size_); while (temp.count_ < right.count_) { construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this->swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { return allocator_.empty; #endif
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {} auto bitset::set(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; } else throw; } auto bitset::reset(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; } else throw; } auto bitset::test(size_t index) -> bool { if (index >= 0 && index < size_) { return !ptr_[index]; } else throw; } auto bitset::size() -> size_t { return size_; } auto bitset::counter() -> size_t { return counter_; } template <typename T> class allocator { public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; auto swap(allocator & other) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> class stack { public: explicit stack(size_t size = 0); auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; auto throw_is_empty() const -> void; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {}; template<typename T> allocator<T>::allocator(allocator const& other) : ptr_(static_cast<T*>(operator new(other.size_))), size_(other.size_), map_(std::make_unique<bitset>(size_)){ for (size_t i; i < size_; i++) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator() { operator delete(ptr_); } template<typename T> auto allocator<T>::resize() -> void { allocator<T> buff(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]); this->swap(buff); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void { if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) { new(ptr)T(value); map_->set(ptr - ptr_); } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * ptr) -> void { ptr->~T(); map_->reset(ptr-ptr_); } template<typename T> auto allocator<T>::destroy(T * first, T * last) -> void { for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t { return map_->counter(); } template<typename T> auto allocator<T>::full() const -> bool { return map_->counter()==size_; } template<typename T> auto allocator<T>::empty() const -> bool { return map_->counter()==0; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(map_, other.map_); std::swap(size_, other.size_); } template <typename T> size_t stack<T>::count() const { return allocator_.count_; } template <typename T> stack<T>::stack(size_t size) :allocator<T>(size) {} template <typename T> void stack<T>::push(T const &item) { if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_> 0) { --allocator<T>::count_; } else throw_is_empty(); } template<typename T> auto stack<T>::top() -> T & { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::top() const -> T const & { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::throw_is_empty() const -> void { throw("Stack is empty!"); } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp(right.size_); while (temp.count_ < right.count_) { construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this->swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { return allocator_.empty; #endif
Update stack.hpp
Update stack.hpp
C++
mit
DANTEpolaris/stack
e44597980b0afd27098f087e3c080e4cca2011ca
include/stack.hpp
include/stack.hpp
#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); size_t count() const; size_t array_size() const; T * operator[](unsigned int index) const; void push(T const &); void pop(); T top(); T last()const; void print(); void swap(); bool empty(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() { array_ = nullptr; array_size_ = 0; count_ = 0; } template <typename T> size_t stack<T>::array_size() const { return array_size_; } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> T * stack<T>::operator[](unsigned int index) const { return array_[index]; } template <typename T> void stack<T>::push(T const & value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; swap(); } array_[count_++] = value; } template <typename T> void stack<T>::pop() { if (empty()) throw std::logic_error("Stack is empty"); else { if (count_ - 1 == array_size_ / 2) array_size_ /= 2; swap(); } } T stack<T>::top() { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count - 1]; } template <typename T> T stack<T>::last()const { if (count_ == 0) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print() { for (unsigned int i = 0; i < count_; ++i) std::cout << array_[i] << " "; std::cout << std::endl; } template <typename T> void stack<T>::swap() { T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } template <typename T> bool stack<T>::empty() { return (count_ == 0) ? true : false; }
#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); size_t count() const; size_t array_size() const; T * operator[](unsigned int index) const; void push(T const &); void pop(); T top(); T last()const; void print(); void swap(); bool empty(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() { array_ = nullptr; array_size_ = 0; count_ = 0; } template <typename T> size_t stack<T>::array_size() const { return array_size_; } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> T * stack<T>::operator[](unsigned int index) const { return array_[index]; } template <typename T> void stack<T>::push(T const & value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; swap(); } array_[count_++] = value; } template <typename T> void stack<T>::pop() { if (empty()) throw std::logic_error("Stack is empty"); else { if (count_ - 1 == array_size_ / 2) array_size_ /= 2; swap(); } } template <typename T> T stack<T>::top()const { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count - 1]; } template <typename T> void stack<T>::print() { for (unsigned int i = 0; i < count_; ++i) std::cout << array_[i] << " "; std::cout << std::endl; } template <typename T> void stack<T>::swap() { T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } template <typename T> bool stack<T>::empty() { return (count_ == 0) ? true : false; }
Update stack.hpp
Update stack.hpp
C++
mit
kate-lozovaya/stack-0.0.3
f82014ff4ac359d0e2f79b8dba692cad0a4493a4
TableGen/ClangASTNodesEmitter.cpp
TableGen/ClangASTNodesEmitter.cpp
#include "ClangASTNodesEmitter.h" #include "Record.h" #include <vector> #include <stack> #include <string> #include <map> #include <utility> #include <clocale> using namespace llvm; //===----------------------------------------------------------------------===// // Statement Node Tables (.inc file) generation. //===----------------------------------------------------------------------===// // Sort to create a tree-like structure based on the 'Base' field. namespace { // Create a macro-ized version of a name std::string macroName(std::string S) { for (unsigned i = 0; i < S.size(); ++i) S[i] = std::toupper(S[i]); return S; } // A map from a node to each of its derived nodes. typedef std::multimap<Record*, Record*> ChildMap; typedef ChildMap::const_iterator ChildIterator; // Returns the first and last non-abstract subrecords std::pair<Record *, Record *> EmitStmtNode(const ChildMap &Tree, raw_ostream &OS, Record *Base) { std::string BaseName = macroName(Base->getName()); ChildIterator i = Tree.lower_bound(Base), e = Tree.upper_bound(Base); Record *First = 0, *Last = 0; // This might be the pseudo-node for Stmt; don't assume it has an Abstract // bit if (Base->getValue("Abstract") && !Base->getValueAsBit("Abstract")) First = Last = Base; for (; i != e; ++i) { Record *R = i->second; bool Abstract = R->getValueAsBit("Abstract"); std::string NodeName = macroName(R->getName()); OS << "#ifndef " << NodeName << "\n"; OS << "# define " << NodeName << "(Type, Base) " << BaseName << "(Type, Base)\n"; OS << "#endif\n"; if (Abstract) OS << "ABSTRACT(" << NodeName << "(" << R->getName() << ", " << Base->getName() << "))\n"; else OS << NodeName << "(" << R->getName() << ", " << Base->getName() << ")\n"; if (Tree.find(R) != Tree.end()) { const std::pair<Record *, Record *> &Result = EmitStmtNode(Tree, OS, R); if (!First && Result.first) First = Result.first; if (Result.second) Last = Result.second; } else { if (!Abstract) { Last = R; if (!First) First = R; } } OS << "#undef " << NodeName << "\n\n"; } assert(!First == !Last && "Got a first or last node, but not the other"); if (First) { OS << "#ifndef FIRST_" << BaseName << "\n"; OS << "# define FIRST_" << BaseName << "(CLASS)\n"; OS << "#endif\n"; OS << "#ifndef LAST_" << BaseName << "\n"; OS << "# define LAST_" << BaseName << "(CLASS)\n"; OS << "#endif\n\n"; OS << "FIRST_" << BaseName << "(" << First->getName() << ")\n"; OS << "LAST_" << BaseName << "(" << Last->getName() << ")\n\n"; } OS << "#undef FIRST_" << BaseName << "\n"; OS << "#undef LAST_" << BaseName << "\n\n"; return std::make_pair(First, Last); } } void ClangStmtNodesEmitter::run(raw_ostream &OS) { // Write the preamble OS << "#ifndef ABSTRACT\n"; OS << "# define ABSTRACT(Stmt) Stmt\n"; OS << "#endif\n\n"; // Emit statements const std::vector<Record*> Stmts = Records.getAllDerivedDefinitions("Stmt"); ChildMap Tree; // Create a pseudo-record to serve as the Stmt node, which isn't actually // output. Record Stmt ("Stmt", SMLoc()); for (unsigned i = 0, e = Stmts.size(); i != e; ++i) { Record *R = Stmts[i]; if (R->getValue("Base")) Tree.insert(std::make_pair(R->getValueAsDef("Base"), R)); else Tree.insert(std::make_pair(&Stmt, R)); } EmitStmtNode(Tree, OS, &Stmt); OS << "#undef STMT\n"; OS << "#undef ABSTRACT\n"; }
#include "ClangASTNodesEmitter.h" #include "Record.h" #include <vector> #include <stack> #include <string> #include <map> #include <utility> #include <cctype> using namespace llvm; //===----------------------------------------------------------------------===// // Statement Node Tables (.inc file) generation. //===----------------------------------------------------------------------===// // Sort to create a tree-like structure based on the 'Base' field. namespace { // Create a macro-ized version of a name std::string macroName(std::string S) { for (unsigned i = 0; i < S.size(); ++i) S[i] = std::toupper(S[i]); return S; } // A map from a node to each of its derived nodes. typedef std::multimap<Record*, Record*> ChildMap; typedef ChildMap::const_iterator ChildIterator; // Returns the first and last non-abstract subrecords std::pair<Record *, Record *> EmitStmtNode(const ChildMap &Tree, raw_ostream &OS, Record *Base) { std::string BaseName = macroName(Base->getName()); ChildIterator i = Tree.lower_bound(Base), e = Tree.upper_bound(Base); Record *First = 0, *Last = 0; // This might be the pseudo-node for Stmt; don't assume it has an Abstract // bit if (Base->getValue("Abstract") && !Base->getValueAsBit("Abstract")) First = Last = Base; for (; i != e; ++i) { Record *R = i->second; bool Abstract = R->getValueAsBit("Abstract"); std::string NodeName = macroName(R->getName()); OS << "#ifndef " << NodeName << "\n"; OS << "# define " << NodeName << "(Type, Base) " << BaseName << "(Type, Base)\n"; OS << "#endif\n"; if (Abstract) OS << "ABSTRACT(" << NodeName << "(" << R->getName() << ", " << Base->getName() << "))\n"; else OS << NodeName << "(" << R->getName() << ", " << Base->getName() << ")\n"; if (Tree.find(R) != Tree.end()) { const std::pair<Record *, Record *> &Result = EmitStmtNode(Tree, OS, R); if (!First && Result.first) First = Result.first; if (Result.second) Last = Result.second; } else { if (!Abstract) { Last = R; if (!First) First = R; } } OS << "#undef " << NodeName << "\n\n"; } assert(!First == !Last && "Got a first or last node, but not the other"); if (First) { OS << "#ifndef FIRST_" << BaseName << "\n"; OS << "# define FIRST_" << BaseName << "(CLASS)\n"; OS << "#endif\n"; OS << "#ifndef LAST_" << BaseName << "\n"; OS << "# define LAST_" << BaseName << "(CLASS)\n"; OS << "#endif\n\n"; OS << "FIRST_" << BaseName << "(" << First->getName() << ")\n"; OS << "LAST_" << BaseName << "(" << Last->getName() << ")\n\n"; } OS << "#undef FIRST_" << BaseName << "\n"; OS << "#undef LAST_" << BaseName << "\n\n"; return std::make_pair(First, Last); } } void ClangStmtNodesEmitter::run(raw_ostream &OS) { // Write the preamble OS << "#ifndef ABSTRACT\n"; OS << "# define ABSTRACT(Stmt) Stmt\n"; OS << "#endif\n\n"; // Emit statements const std::vector<Record*> Stmts = Records.getAllDerivedDefinitions("Stmt"); ChildMap Tree; // Create a pseudo-record to serve as the Stmt node, which isn't actually // output. Record Stmt ("Stmt", SMLoc()); for (unsigned i = 0, e = Stmts.size(); i != e; ++i) { Record *R = Stmts[i]; if (R->getValue("Base")) Tree.insert(std::make_pair(R->getValueAsDef("Base"), R)); else Tree.insert(std::make_pair(&Stmt, R)); } EmitStmtNode(Tree, OS, &Stmt); OS << "#undef STMT\n"; OS << "#undef ABSTRACT\n"; }
Include the right header for toupper
Include the right header for toupper git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@103073 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-3-clause
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
347f19ad919083dbcf414dddf2a82ee877c22b0f
backends/jitrt/lib/memory_mapper.cc
backends/jitrt/lib/memory_mapper.cc
/* * Copyright 2022 The TensorFlow Runtime Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //===- memory_mapper.cc - -------------------------------------------------===// // Support for managing memory from a SectionMemoryManager via a memfd. // This allows profilers to correctly label JIT-executed code. //===----------------------------------------------------------------------===// #include "tfrt/jitrt/memory_mapper.h" #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> #include <system_error> #include "llvm/ExecutionEngine/SectionMemoryManager.h" // Support for memfd_create(2) was added in glibc v2.27. #if defined(__linux__) && defined(__GLIBC__) && defined(__GLIBC_PREREQ) #if __GLIBC_PREREQ(2, 27) #define ENABLE_JITRT_MEMORY_MAPPER #endif // __GLIBC_PREREQ(2, 27) #endif // __linux__ and __GLIBC__ and __GLIBC_PREREQ #ifndef ENABLE_JITRT_MEMORY_MAPPER namespace tfrt { namespace jitrt { std::unique_ptr<JitRtMemoryMapper> JitRtMemoryMapper::Create( llvm::StringRef name) { return nullptr; } } // namespace jitrt } // namespace tfrt #else // ENABLE_JITRT_MEMORY_MAPPER namespace { using MemoryMapper = llvm::SectionMemoryManager::MemoryMapper; using AllocationPurpose = llvm::SectionMemoryManager::AllocationPurpose; // Some syscalls can be interrupted by a signal handler; retry if that happens. template <typename FunctionType> static auto RetryOnEINTR(FunctionType func, decltype(func()) failure_value) -> decltype(func()) { using ReturnType = decltype(func()); ReturnType ret; do { ret = func(); } while (ret == failure_value && errno == EINTR); return ret; } int retrying_close(int fd) { return RetryOnEINTR([&]() { return close(fd); }, -1); } int retrying_ftruncate(int fd, off_t length) { return RetryOnEINTR([&]() { return ftruncate(fd, length); }, -1); } int retrying_memfd_create(const char* name, unsigned int flags) { return RetryOnEINTR([&]() { return memfd_create(name, flags); }, -1); } void* retrying_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { return RetryOnEINTR( [&]() { return mmap(addr, length, prot, flags, fd, offset); }, MAP_FAILED); } int retrying_mprotect(void* addr, size_t len, int prot) { return RetryOnEINTR([&]() { return mprotect(addr, len, prot); }, -1); } int retrying_munmap(void* addr, size_t length) { return RetryOnEINTR([&]() { return munmap(addr, length); }, -1); } int64_t retrying_sysconf(int name) { return RetryOnEINTR([&]() { return sysconf(name); }, -1); } static int ToPosixProtectionFlags(unsigned flags) { int ret = 0; if (flags & llvm::sys::Memory::MF_READ) { ret |= PROT_READ; } if (flags & llvm::sys::Memory::MF_WRITE) { ret |= PROT_WRITE; } if (flags & llvm::sys::Memory::MF_EXEC) { ret |= PROT_EXEC; } return ret; } } // namespace namespace tfrt { namespace jitrt { std::unique_ptr<JitRtMemoryMapper> JitRtMemoryMapper::Create( llvm::StringRef name) { std::unique_ptr<JitRtMemoryMapper> ret(new JitRtMemoryMapper(name)); return ret; } llvm::sys::MemoryBlock JitRtMemoryMapper::allocateMappedMemory( AllocationPurpose purpose, size_t len, const llvm::sys::MemoryBlock* const near_block, unsigned prot_flags, std::error_code& error_code) { auto round_up = [](size_t size, size_t align) { return (size + align - 1) & ~(align - 1); }; int64_t page_size = retrying_sysconf(_SC_PAGESIZE); len = round_up(len, page_size); int fd = -1; int mmap_flags = MAP_PRIVATE; if (purpose == llvm::SectionMemoryManager::AllocationPurpose::Code) { // Try to get a truncated memfd. If that fails, use an anonymous mapping. fd = retrying_memfd_create(name_.c_str(), 0); if (fd != -1 && retrying_ftruncate(fd, len) == -1) { retrying_close(fd); fd = -1; } } if (fd == -1) { mmap_flags |= MAP_ANONYMOUS; } prot_flags = ToPosixProtectionFlags(prot_flags); void* map = retrying_mmap(nullptr, len, prot_flags, mmap_flags, fd, 0); // Regardless of the outcome of the mmap, we can close the fd now. if (fd != -1) retrying_close(fd); if (map == MAP_FAILED) { error_code = std::error_code(errno, std::generic_category()); return llvm::sys::MemoryBlock(); } return llvm::sys::MemoryBlock(map, len); } std::error_code JitRtMemoryMapper::protectMappedMemory( const llvm::sys::MemoryBlock& block, unsigned prot_flags) { int64_t page_size = retrying_sysconf(_SC_PAGESIZE); uintptr_t base = reinterpret_cast<uintptr_t>(block.base()); uintptr_t rounded_down_base = base & ~(page_size - 1); size_t size = block.allocatedSize(); size += base - rounded_down_base; prot_flags = ToPosixProtectionFlags(prot_flags); void* addr = reinterpret_cast<void*>(rounded_down_base); if (retrying_mprotect(addr, size, prot_flags) == -1) { return std::error_code(errno, std::generic_category()); } return std::error_code(); } std::error_code JitRtMemoryMapper::releaseMappedMemory( llvm::sys::MemoryBlock& block) { if (retrying_munmap(block.base(), block.allocatedSize()) == -1) { return std::error_code(errno, std::generic_category()); } return std::error_code(); } } // namespace jitrt } // namespace tfrt #endif // ENABLE_JITRT_MEMORY_MAPPER
/* * Copyright 2022 The TensorFlow Runtime Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //===- memory_mapper.cc - -------------------------------------------------===// // Support for managing memory from a SectionMemoryManager via a memfd. // This allows profilers to correctly label JIT-executed code. //===----------------------------------------------------------------------===// #include "tfrt/jitrt/memory_mapper.h" #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> #include "llvm/ExecutionEngine/SectionMemoryManager.h" // Support for memfd_create(2) was added in glibc v2.27. #if defined(__linux__) && defined(__GLIBC__) && defined(__GLIBC_PREREQ) #if __GLIBC_PREREQ(2, 27) #define ENABLE_JITRT_MEMORY_MAPPER #endif // __GLIBC_PREREQ(2, 27) #endif // __linux__ and __GLIBC__ and __GLIBC_PREREQ #ifndef ENABLE_JITRT_MEMORY_MAPPER namespace tfrt { namespace jitrt { std::unique_ptr<JitRtMemoryMapper> JitRtMemoryMapper::Create( llvm::StringRef name) { return nullptr; } llvm::sys::MemoryBlock JitRtMemoryMapper::allocateMappedMemory( llvm::SectionMemoryManager::AllocationPurpose purpose, size_t len, const llvm::sys::MemoryBlock* const near_block, unsigned prot_flags, std::error_code& error_code) { llvm_unreachable("JitRtMemoryMapper is not implemented"); } std::error_code JitRtMemoryMapper::protectMappedMemory( const llvm::sys::MemoryBlock& block, unsigned prot_flags) { llvm_unreachable("JitRtMemoryMapper is not implemented"); } std::error_code JitRtMemoryMapper::releaseMappedMemory( llvm::sys::MemoryBlock& block) { llvm_unreachable("JitRtMemoryMapper is not implemented"); } } // namespace jitrt } // namespace tfrt #else // ENABLE_JITRT_MEMORY_MAPPER namespace { using MemoryMapper = llvm::SectionMemoryManager::MemoryMapper; using AllocationPurpose = llvm::SectionMemoryManager::AllocationPurpose; // Some syscalls can be interrupted by a signal handler; retry if that happens. template <typename FunctionType> static auto RetryOnEINTR(FunctionType func, decltype(func()) failure_value) -> decltype(func()) { using ReturnType = decltype(func()); ReturnType ret; do { ret = func(); } while (ret == failure_value && errno == EINTR); return ret; } int retrying_close(int fd) { return RetryOnEINTR([&]() { return close(fd); }, -1); } int retrying_ftruncate(int fd, off_t length) { return RetryOnEINTR([&]() { return ftruncate(fd, length); }, -1); } int retrying_memfd_create(const char* name, unsigned int flags) { return RetryOnEINTR([&]() { return memfd_create(name, flags); }, -1); } void* retrying_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { return RetryOnEINTR( [&]() { return mmap(addr, length, prot, flags, fd, offset); }, MAP_FAILED); } int retrying_mprotect(void* addr, size_t len, int prot) { return RetryOnEINTR([&]() { return mprotect(addr, len, prot); }, -1); } int retrying_munmap(void* addr, size_t length) { return RetryOnEINTR([&]() { return munmap(addr, length); }, -1); } int64_t retrying_sysconf(int name) { return RetryOnEINTR([&]() { return sysconf(name); }, -1); } static int ToPosixProtectionFlags(unsigned flags) { int ret = 0; if (flags & llvm::sys::Memory::MF_READ) { ret |= PROT_READ; } if (flags & llvm::sys::Memory::MF_WRITE) { ret |= PROT_WRITE; } if (flags & llvm::sys::Memory::MF_EXEC) { ret |= PROT_EXEC; } return ret; } } // namespace namespace tfrt { namespace jitrt { std::unique_ptr<JitRtMemoryMapper> JitRtMemoryMapper::Create( llvm::StringRef name) { std::unique_ptr<JitRtMemoryMapper> ret(new JitRtMemoryMapper(name)); return ret; } llvm::sys::MemoryBlock JitRtMemoryMapper::allocateMappedMemory( AllocationPurpose purpose, size_t len, const llvm::sys::MemoryBlock* const near_block, unsigned prot_flags, std::error_code& error_code) { auto round_up = [](size_t size, size_t align) { return (size + align - 1) & ~(align - 1); }; int64_t page_size = retrying_sysconf(_SC_PAGESIZE); len = round_up(len, page_size); int fd = -1; int mmap_flags = MAP_PRIVATE; if (purpose == llvm::SectionMemoryManager::AllocationPurpose::Code) { // Try to get a truncated memfd. If that fails, use an anonymous mapping. fd = retrying_memfd_create(name_.c_str(), 0); if (fd != -1 && retrying_ftruncate(fd, len) == -1) { retrying_close(fd); fd = -1; } } if (fd == -1) { mmap_flags |= MAP_ANONYMOUS; } prot_flags = ToPosixProtectionFlags(prot_flags); void* map = retrying_mmap(nullptr, len, prot_flags, mmap_flags, fd, 0); // Regardless of the outcome of the mmap, we can close the fd now. if (fd != -1) retrying_close(fd); if (map == MAP_FAILED) { error_code = std::error_code(errno, std::generic_category()); return llvm::sys::MemoryBlock(); } return llvm::sys::MemoryBlock(map, len); } std::error_code JitRtMemoryMapper::protectMappedMemory( const llvm::sys::MemoryBlock& block, unsigned prot_flags) { int64_t page_size = retrying_sysconf(_SC_PAGESIZE); uintptr_t base = reinterpret_cast<uintptr_t>(block.base()); uintptr_t rounded_down_base = base & ~(page_size - 1); size_t size = block.allocatedSize(); size += base - rounded_down_base; prot_flags = ToPosixProtectionFlags(prot_flags); void* addr = reinterpret_cast<void*>(rounded_down_base); if (retrying_mprotect(addr, size, prot_flags) == -1) { return std::error_code(errno, std::generic_category()); } return std::error_code(); } std::error_code JitRtMemoryMapper::releaseMappedMemory( llvm::sys::MemoryBlock& block) { if (retrying_munmap(block.base(), block.allocatedSize()) == -1) { return std::error_code(errno, std::generic_category()); } return std::error_code(); } } // namespace jitrt } // namespace tfrt #endif // ENABLE_JITRT_MEMORY_MAPPER
Implement fake MemoryMapper virtual methods
[tfrt:jitrt] Implement fake MemoryMapper virtual methods PiperOrigin-RevId: 431578673
C++
apache-2.0
tensorflow/runtime,tensorflow/runtime,tensorflow/runtime,tensorflow/runtime
338db008b3f7dc090226ed52a5be5e22c581c336
index/MMIndex.cpp
index/MMIndex.cpp
#include <iostream> #include <MMIndex.h> #include <PostingStream.h> void MMIndex::add(const string &term, size_t fieldID, size_t docID, size_t pos) { vector<Posting> &pstList = index[term][fieldID]; const size_t N = pstList.size(); if ( N > 0 && pstList[N - 1].docID == docID ) { pstList[N - 1].addPos(pos); sizeByte += sizeof(docID); } else { pstList.push_back(Posting(docID, pos)); sizeByte += sizeof(docID) + sizeof(pos); } } void MMIndex::add(const string &term, size_t fieldID, const Posting &posting) { vector<Posting> &pstList = index[term][fieldID]; const size_t N = pstList.size(); if ( N > 0 && pstList[N - 1].docID == posting.docID ) { sizeByte += pstList[N - 1].merge(posting); } else { pstList.push_back(posting); sizeByte += posting.size(); } } void MMIndex::writeTo(ostream &idxOut, ostream &fldOut, ostream &trmOut, ostream &pstOut, size_t fieldNum) const { fldOut.write((char*)&fieldNum, sizeof(fieldNum)); for (auto termIt = index.begin(); termIt != index.end(); termIt ++) { size_t termBegin = trmOut.tellp(); idxOut.write((char*)&termBegin, sizeof(termBegin)); trmOut.write(termIt->first.c_str(), termIt->first.length() + 1); /* Write each field. */ for (size_t fieldIt = 1; fieldIt <= fieldNum; fieldIt ++) { auto pstListIt = termIt->second.find(fieldIt); if ( pstListIt == termIt->second.end() ) { size_t pstListBegin = pstOut.tellp(); size_t pstListEnd = pstListBegin; idxOut.write((char*)&pstListBegin, sizeof(pstListBegin)); idxOut.write((char*)&pstListEnd, sizeof(pstListEnd)); continue; } PostingStream ps(pstOut, pstOut.tellp(), pstOut.tellp()); // cout << termIt->first << endl; /* Write each posting. */ const vector<Posting> &pstList = pstListIt->second; for (auto pstIt = pstList.begin(); pstIt != pstList.end(); pstIt ++) { // cout << pstIt->toString() << endl; ps.write(*pstIt); } ps.writeSkips(); size_t pstListBegin = ps.getBegin(); size_t pstListEnd = ps.getEnd(); // cout << pstListBegin << " " << pstListEnd << endl; idxOut.write((char*)&pstListBegin, sizeof(pstListBegin)); idxOut.write((char*)&pstListEnd, sizeof(pstListEnd)); } } } void MMIndex::reset() { index.clear(); // map<string, map<size_t, vector<Posting>>> index; // index.swap(this->index); sizeByte = 0; } string MMIndex::toString() const { string res; for (auto idxIt = index.begin(); idxIt != index.end(); idxIt ++) { res += idxIt->first; res += ": "; for (auto pstIt = idxIt->second.begin(); pstIt != idxIt->second.end(); pstIt ++) { res += to_string(pstIt->first); res += "'["; for (auto it = pstIt->second.begin(); it != pstIt->second.end(); it ++) { res += it->toString(); res += ","; } if ( res.back() == ',' ) res.erase(res.length() - 1); res += "],"; } if ( res.back() == ',' ) res.erase(res.length() - 1); res += "\n"; } return res; }
#include <iostream> #include <MMIndex.h> #include <PostingStream.h> void MMIndex::add(const string &term, size_t fieldID, size_t docID, size_t pos) { vector<Posting> &pstList = index[term][fieldID]; const size_t N = pstList.size(); if ( N > 0 && pstList[N - 1].docID == docID ) { pstList[N - 1].addPos(pos); sizeByte += sizeof(pos); } else { pstList.push_back(Posting(docID, pos)); sizeByte += sizeof(docID) + sizeof(pos); } } void MMIndex::add(const string &term, size_t fieldID, const Posting &posting) { vector<Posting> &pstList = index[term][fieldID]; const size_t N = pstList.size(); if ( N > 0 && pstList[N - 1].docID == posting.docID ) { sizeByte += pstList[N - 1].merge(posting); } else { pstList.push_back(posting); sizeByte += posting.size(); } } void MMIndex::writeTo(ostream &idxOut, ostream &fldOut, ostream &trmOut, ostream &pstOut, size_t fieldNum) const { fldOut.write((char*)&fieldNum, sizeof(fieldNum)); for (auto termIt = index.begin(); termIt != index.end(); termIt ++) { size_t termBegin = trmOut.tellp(); idxOut.write((char*)&termBegin, sizeof(termBegin)); trmOut.write(termIt->first.c_str(), termIt->first.length() + 1); /* Write each field. */ for (size_t fieldIt = 1; fieldIt <= fieldNum; fieldIt ++) { auto pstListIt = termIt->second.find(fieldIt); if ( pstListIt == termIt->second.end() ) { size_t pstListBegin = pstOut.tellp(); size_t pstListEnd = pstListBegin; idxOut.write((char*)&pstListBegin, sizeof(pstListBegin)); idxOut.write((char*)&pstListEnd, sizeof(pstListEnd)); continue; } PostingStream ps(pstOut, pstOut.tellp(), pstOut.tellp()); // cout << termIt->first << endl; /* Write each posting. */ const vector<Posting> &pstList = pstListIt->second; for (auto pstIt = pstList.begin(); pstIt != pstList.end(); pstIt ++) { // cout << pstIt->toString() << endl; ps.write(*pstIt); } ps.writeSkips(); size_t pstListBegin = ps.getBegin(); size_t pstListEnd = ps.getEnd(); // cout << pstListBegin << " " << pstListEnd << endl; idxOut.write((char*)&pstListBegin, sizeof(pstListBegin)); idxOut.write((char*)&pstListEnd, sizeof(pstListEnd)); } } } void MMIndex::reset() { index.clear(); // map<string, map<size_t, vector<Posting>>> index; // index.swap(this->index); sizeByte = 0; } string MMIndex::toString() const { string res; for (auto idxIt = index.begin(); idxIt != index.end(); idxIt ++) { res += idxIt->first; res += ": "; for (auto pstIt = idxIt->second.begin(); pstIt != idxIt->second.end(); pstIt ++) { res += to_string(pstIt->first); res += "'["; for (auto it = pstIt->second.begin(); it != pstIt->second.end(); it ++) { res += it->toString(); res += ","; } if ( res.back() == ',' ) res.erase(res.length() - 1); res += "],"; } if ( res.back() == ',' ) res.erase(res.length() - 1); res += "\n"; } return res; }
Update MMIndex.cpp
Update MMIndex.cpp sizeof(docID) -> sizeof(pos)
C++
apache-2.0
Da-Huang/Search-Engine,Da-Huang/Search-Engine
f7e7ed6aaf600d99e9db6a4af51eec9d8983cb84
base/i18n/icu_encoding_detection.cc
base/i18n/icu_encoding_detection.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/icu_encoding_detection.h" #include <set> #include "base/string_util.h" #include "unicode/ucsdet.h" namespace base { bool DetectEncoding(const std::string& text, std::string* encoding) { if (IsStringASCII(text)) { *encoding = std::string(); return true; } UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.data(), static_cast<int32_t>(text.length()), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); const char* detected_encoding = ucsdet_getName(match, &status); ucsdet_close(detector); if (U_FAILURE(status)) return false; *encoding = detected_encoding; return true; } bool DetectAllEncodings(const std::string& text, std::vector<std::string>* encodings) { UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.data(), static_cast<int32_t>(text.length()), &status); int matches_count = 0; const UCharsetMatch** matches = ucsdet_detectAll(detector, &matches_count, &status); if (U_FAILURE(status)) { ucsdet_close(detector); return false; } // ICU has some heuristics for encoding detection, such that the more likely // encodings should be returned first. However, it doesn't always return // all encodings that properly decode |text|, so we'll append more encodings // later. To make that efficient, keep track of encodings sniffed in this // first phase. std::set<std::string> sniffed_encodings; encodings->clear(); for (int i = 0; i < matches_count; i++) { UErrorCode get_name_status = U_ZERO_ERROR; const char* encoding_name = ucsdet_getName(matches[i], &get_name_status); // If we failed to get the encoding's name, ignore the error. if (U_FAILURE(get_name_status)) continue; int32_t confidence = ucsdet_getConfidence(matches[i], &get_name_status); // We also treat this error as non-fatal. if (U_FAILURE(get_name_status)) continue; // A confidence level >= 10 means that the encoding is expected to properly // decode the text. Drop all encodings with lower confidence level. if (confidence < 10) continue; encodings->push_back(encoding_name); sniffed_encodings.insert(encoding_name); } // Append all encodings not included earlier, in arbitrary order. // TODO(jshin): This shouldn't be necessary, possible ICU bug. // See also http://crbug.com/65917. UEnumeration* detectable_encodings = ucsdet_getAllDetectableCharsets(detector, &status); int detectable_count = uenum_count(detectable_encodings, &status); for (int i = 0; i < detectable_count; i++) { int name_length; const char* name_raw = uenum_next(detectable_encodings, &name_length, &status); std::string name(name_raw, name_length); if (sniffed_encodings.find(name) == sniffed_encodings.end()) encodings->push_back(name); } uenum_close(detectable_encodings); ucsdet_close(detector); return !encodings->empty(); } } // namespace base
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/icu_encoding_detection.h" #include <set> #include "base/string_util.h" #include "unicode/ucsdet.h" namespace base { bool DetectEncoding(const std::string& text, std::string* encoding) { if (IsStringASCII(text)) { *encoding = std::string(); return true; } UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.data(), static_cast<int32_t>(text.length()), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match == NULL) return false; const char* detected_encoding = ucsdet_getName(match, &status); ucsdet_close(detector); if (U_FAILURE(status)) return false; *encoding = detected_encoding; return true; } bool DetectAllEncodings(const std::string& text, std::vector<std::string>* encodings) { UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.data(), static_cast<int32_t>(text.length()), &status); int matches_count = 0; const UCharsetMatch** matches = ucsdet_detectAll(detector, &matches_count, &status); if (U_FAILURE(status)) { ucsdet_close(detector); return false; } // ICU has some heuristics for encoding detection, such that the more likely // encodings should be returned first. However, it doesn't always return // all encodings that properly decode |text|, so we'll append more encodings // later. To make that efficient, keep track of encodings sniffed in this // first phase. std::set<std::string> sniffed_encodings; encodings->clear(); for (int i = 0; i < matches_count; i++) { UErrorCode get_name_status = U_ZERO_ERROR; const char* encoding_name = ucsdet_getName(matches[i], &get_name_status); // If we failed to get the encoding's name, ignore the error. if (U_FAILURE(get_name_status)) continue; int32_t confidence = ucsdet_getConfidence(matches[i], &get_name_status); // We also treat this error as non-fatal. if (U_FAILURE(get_name_status)) continue; // A confidence level >= 10 means that the encoding is expected to properly // decode the text. Drop all encodings with lower confidence level. if (confidence < 10) continue; encodings->push_back(encoding_name); sniffed_encodings.insert(encoding_name); } // Append all encodings not included earlier, in arbitrary order. // TODO(jshin): This shouldn't be necessary, possible ICU bug. // See also http://crbug.com/65917. UEnumeration* detectable_encodings = ucsdet_getAllDetectableCharsets(detector, &status); int detectable_count = uenum_count(detectable_encodings, &status); for (int i = 0; i < detectable_count; i++) { int name_length; const char* name_raw = uenum_next(detectable_encodings, &name_length, &status); std::string name(name_raw, name_length); if (sniffed_encodings.find(name) == sniffed_encodings.end()) encodings->push_back(name); } uenum_close(detectable_encodings); ucsdet_close(detector); return !encodings->empty(); } } // namespace base
Make DetectEncoding() failed when ucsdet_detect() returls NULL.
Make DetectEncoding() failed when ucsdet_detect() returls NULL. In some cases, DetectEncoding() crashes and the reason may be becasue ucsdet_detect() returns NULL with no error status. (cf. http://crosbug.com/15691) BUG=http://crosbug.com/15691 TEST=none Review URL: http://codereview.chromium.org/7064039 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@86509 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,rogerwang/chromium,keishi/chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dednal/chromium.src,robclark/chromium,markYoungH/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ltilve/chromium,robclark/chromium,dednal/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,robclark/chromium,Just-D/chromium-1,markYoungH/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,rogerwang/chromium,timopulkkinen/BubbleFish,anirudhSK/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,hujiajie/pa-chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,dednal/chromium.src,rogerwang/chromium,robclark/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,markYoungH/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,rogerwang/chromium,nacl-webkit/chrome_deps,dednal/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,dushu1203/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,patrickm/chromium.src,jaruba/chromium.src,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,axinging/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,jaruba/chromium.src,robclark/chromium,M4sse/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,Just-D/chromium-1,M4sse/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,keishi/chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,littlstar/chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,robclark/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,rogerwang/chromium,anirudhSK/chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,ondra-novak/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,Chilledheart/chromium,M4sse/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,dednal/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,Jonekee/chromium.src,ltilve/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,robclark/chromium,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,axinging/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,rogerwang/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,robclark/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,keishi/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,patrickm/chromium.src,M4sse/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,markYoungH/chromium.src,Just-D/chromium-1
76ff0bed5c6e597fd808bc921c4338bbce32fb1b
bench/tests/qdb/tag/attach_blob.hpp
bench/tests/qdb/tag/attach_blob.hpp
#pragma once #include <bench/tests/qdb/qdb_test_template.hpp> namespace bench { namespace tests { namespace qdb { namespace tag { class attach_blob : public qdb_test_template<attach_blob> { public: attach_blob(bench::test_config config) : qdb_test_template(config) { _tag = alias(0) + "-tag"; } void setup() override { qdb_test_template::setup(); setup_each([=](std::uint32_t iteration) { _qdb.blob_put(alias(iteration), "hello world!"); }); } void run_iteration(std::uint32_t iteration) { _qdb.attach_tag(alias(iteration), _tag); } void cleanup() override { _qdb.remove(_tag); cleanup_each([=](std::uint32_t iteration) { _qdb.remove(alias(iteration)); }); qdb_test_template::cleanup(); } static std::string name() { return "qdb_tag_attach_blob"; } static std::string description() { return "Each thread repeats qdb_attach_tag() on many blobs"; } static bool size_dependent() { return false; } private: std::string _tag; }; } // namespace tag } // namespace qdb } // namespace tests } // namespace bench
#pragma once #include <bench/tests/qdb/qdb_test_template.hpp> namespace bench { namespace tests { namespace qdb { namespace tag { class attach_blob : public qdb_test_template<attach_blob> { public: attach_blob(bench::test_config config) : qdb_test_template(config) { _tag = alias(0) + "-tag"; } void setup() override { qdb_test_template::setup(); setup_each([=](std::uint32_t iteration) { _qdb.blob_put(alias(iteration), "hello world!"); }); } void run_iteration(std::uint32_t iteration) { _qdb.attach_tag(alias(iteration), _tag); } void cleanup() override { cleanup_each([=](std::uint32_t iteration) { _qdb.remove(alias(iteration)); }); _qdb.remove(_tag); // <- we delete the tag once it's empty, because it's much faster qdb_test_template::cleanup(); } static std::string name() { return "qdb_tag_attach_blob"; } static std::string description() { return "Each thread repeats qdb_attach_tag() on many blobs"; } static bool size_dependent() { return false; } private: std::string _tag; }; } // namespace tag } // namespace qdb } // namespace tests } // namespace bench
Improve qdb_tag_attach_blob cleanup time
Improve qdb_tag_attach_blob cleanup time
C++
bsd-2-clause
bureau14/qdb-benchmark,bureau14/qdb-benchmark,bureau14/qdb-benchmark,bureau14/qdb-benchmark
f4ce1e270bb661e9092e1b5de651d7ea5a7bd3d2
src/stdexcept.cpp
src/stdexcept.cpp
//===------------------------ stdexcept.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "stdexcept" #include "new" #include <cstdlib> #include <cstring> #include <cstdint> #include <cstddef> // Note: optimize for size #pragma GCC visibility push(hidden) namespace { class __libcpp_nmstr { private: const char* str_; typedef std::size_t unused_t; typedef std::int32_t count_t; static const std::ptrdiff_t offset = static_cast<std::ptrdiff_t>(2*sizeof(unused_t) + sizeof(count_t)); count_t& count() const _NOEXCEPT {return (count_t&)(*(str_ - sizeof(count_t)));} public: explicit __libcpp_nmstr(const char* msg); __libcpp_nmstr(const __libcpp_nmstr& s) _LIBCPP_CANTTHROW; __libcpp_nmstr& operator=(const __libcpp_nmstr& s) _LIBCPP_CANTTHROW; ~__libcpp_nmstr() _LIBCPP_CANTTHROW; const char* c_str() const _NOEXCEPT {return str_;} }; __libcpp_nmstr::__libcpp_nmstr(const char* msg) { std::size_t len = strlen(msg); str_ = new char[len + 1 + offset]; unused_t* c = (unused_t*)str_; c[0] = c[1] = len; str_ += offset; count() = 0; std::strcpy(const_cast<char*>(c_str()), msg); } inline __libcpp_nmstr::__libcpp_nmstr(const __libcpp_nmstr& s) : str_(s.str_) { __sync_add_and_fetch(&count(), 1); } __libcpp_nmstr& __libcpp_nmstr::operator=(const __libcpp_nmstr& s) { const char* p = str_; str_ = s.str_; __sync_add_and_fetch(&count(), 1); if (__sync_add_and_fetch((count_t*)(p-sizeof(count_t)), -1) < 0) delete [] (p-offset); return *this; } inline __libcpp_nmstr::~__libcpp_nmstr() { if (__sync_add_and_fetch(&count(), -1) < 0) delete [] (str_ - offset); } } #pragma GCC visibility pop namespace std // purposefully not using versioning namespace { logic_error::~logic_error() _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; s.~__libcpp_nmstr(); } const char* logic_error::what() const _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; return s.c_str(); } runtime_error::~runtime_error() _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; s.~__libcpp_nmstr(); } const char* runtime_error::what() const _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; return s.c_str(); } domain_error::~domain_error() _NOEXCEPT {} invalid_argument::~invalid_argument() _NOEXCEPT {} length_error::~length_error() _NOEXCEPT {} out_of_range::~out_of_range() _NOEXCEPT {} range_error::~range_error() _NOEXCEPT {} overflow_error::~overflow_error() _NOEXCEPT {} underflow_error::~underflow_error() _NOEXCEPT {} } // std
//===------------------------ stdexcept.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "stdexcept" #include "new" #include <cstdlib> #include <cstring> #include <cstdint> #include <cstddef> // Note: optimize for size #pragma GCC visibility push(hidden) namespace { class __libcpp_nmstr { private: const char* str_; typedef std::size_t unused_t; typedef std::ptrdiff_t count_t; static const std::ptrdiff_t offset = static_cast<std::ptrdiff_t>(2*sizeof(unused_t) + sizeof(count_t)); count_t& count() const _NOEXCEPT {return (count_t&)(*(str_ - sizeof(count_t)));} public: explicit __libcpp_nmstr(const char* msg); __libcpp_nmstr(const __libcpp_nmstr& s) _LIBCPP_CANTTHROW; __libcpp_nmstr& operator=(const __libcpp_nmstr& s) _LIBCPP_CANTTHROW; ~__libcpp_nmstr() _LIBCPP_CANTTHROW; const char* c_str() const _NOEXCEPT {return str_;} }; __libcpp_nmstr::__libcpp_nmstr(const char* msg) { std::size_t len = strlen(msg); str_ = new char[len + 1 + offset]; unused_t* c = (unused_t*)str_; c[0] = c[1] = len; str_ += offset; count() = 0; std::strcpy(const_cast<char*>(c_str()), msg); } inline __libcpp_nmstr::__libcpp_nmstr(const __libcpp_nmstr& s) : str_(s.str_) { __sync_add_and_fetch(&count(), 1); } __libcpp_nmstr& __libcpp_nmstr::operator=(const __libcpp_nmstr& s) { const char* p = str_; str_ = s.str_; __sync_add_and_fetch(&count(), 1); if (__sync_add_and_fetch((count_t*)(p-sizeof(count_t)), count_t(-1)) < 0) delete [] (p-offset); return *this; } inline __libcpp_nmstr::~__libcpp_nmstr() { if (__sync_add_and_fetch(&count(), count_t(-1)) < 0) delete [] (str_ - offset); } } #pragma GCC visibility pop namespace std // purposefully not using versioning namespace { logic_error::~logic_error() _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; s.~__libcpp_nmstr(); } const char* logic_error::what() const _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; return s.c_str(); } runtime_error::~runtime_error() _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; s.~__libcpp_nmstr(); } const char* runtime_error::what() const _NOEXCEPT { __libcpp_nmstr& s = (__libcpp_nmstr&)__imp_; return s.c_str(); } domain_error::~domain_error() _NOEXCEPT {} invalid_argument::~invalid_argument() _NOEXCEPT {} length_error::~length_error() _NOEXCEPT {} out_of_range::~out_of_range() _NOEXCEPT {} range_error::~range_error() _NOEXCEPT {} overflow_error::~overflow_error() _NOEXCEPT {} underflow_error::~underflow_error() _NOEXCEPT {} } // std
Change size of reference count field in __libcpp_nmstr from 32 bits to 64 bits for 64 bit targets. This is controls the data layout of all exceptions defined in <stdexcept>. This aligns the ABI with that of gcc-4.2.
Change size of reference count field in __libcpp_nmstr from 32 bits to 64 bits for 64 bit targets. This is controls the data layout of all exceptions defined in <stdexcept>. This aligns the ABI with that of gcc-4.2. git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@161496 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxxabi,llvm-mirror/libcxxabi,llvm-mirror/libcxxabi,llvm-mirror/libcxxabi,llvm-mirror/libcxxabi
00ba49f9abe13b0a659217c9036841f70a08abb2
src/common/KeyManager.cxx
src/common/KeyManager.cxx
/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #if defined(_MSC_VER) #pragma warning(4:4503) #endif // interface header #include "KeyManager.h" // system headers #include <assert.h> #include <ctype.h> #include <string.h> // strstr, etc #include <string> // std::string #include <vector> // local implementation headers #include "BzfEvent.h" // initialize the singleton template <> KeyManager* Singleton<KeyManager>::_instance = (KeyManager*)0; const char* KeyManager::buttonNames[] = { "???", "Pause", "Home", "End", "Left Arrow", "Right Arrow", "Up Arrow", "Down Arrow", "Page Up", "Page Down", "Insert", "Backspace", "Delete", "Kp0", "Kp1", "Kp2", "Kp3", "Kp4", "Kp5", "Kp6", "Kp7", "Kp8", "Kp9", "Kp_Period", "Kp_Divide", "Kp_Multiply", "Kp_Minus", "Kp_Plus", "Kp_Enter", "Kp_Equals", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "Help", "Print", "Sysreq", "Break", "Menu", "Power", "Euro", "Undo", "Left Mouse", "Middle Mouse", "Right Mouse", "Wheel Up", "Wheel Down", "Mouse Button 6", "Mouse Button 7", "Mouse Button 8", "Mouse Button 9", "Mouse Button 10", "Joystick Button 1", "Joystick Button 2", "Joystick Button 3", "Joystick Button 4", "Joystick Button 5", "Joystick Button 6", "Joystick Button 7", "Joystick Button 8", "Joystick Button 9", "Joystick Button 10", "LastButton" // should always be last item listed }; const char* KeyManager::asciiNames[][2] = { { "Tab", "\t" }, { "Backspace", "\b" }, { "Enter", "\r" }, { "Space", " " } }; KeyManager::KeyManager() { unsigned int i; // prep string to key map BzfKeyEvent key; key.ascii = 0; key.shift = 0; for (i = BzfKeyEvent::Pause; i < BzfKeyEvent::LastButton; ++i) { key.button = static_cast<BzfKeyEvent::Button>(i); stringToEvent.insert(std::make_pair(std::string(buttonNames[i]), key)); } key.button = BzfKeyEvent::NoButton; for (i = 0; i < countof(asciiNames); ++i) { key.ascii = asciiNames[i][1][0]; stringToEvent.insert(std::make_pair(std::string(asciiNames[i][0]), key)); } char buffer[2]; buffer[1] = 0; for (i = 0x21; i < 0x7f; ++i) { buffer[0] = key.ascii = static_cast<char>(i); stringToEvent.insert(std::make_pair(std::string(buffer), key)); } } KeyManager::~KeyManager() { } void KeyManager::bind(const BzfKeyEvent& key, bool press, const std::string& cmd) { if (press) { pressEventToCommand.erase(key); pressEventToCommand.insert(std::make_pair(key, cmd)); } else { releaseEventToCommand.erase(key); releaseEventToCommand.insert(std::make_pair(key, cmd)); } notify(key, press, cmd); } void KeyManager::unbind(const BzfKeyEvent& key, bool press) { if (press) pressEventToCommand.erase(key); else releaseEventToCommand.erase(key); notify(key, press, ""); } void KeyManager::unbindCommand(const char* command) { EventToCommandMap::iterator index; index = pressEventToCommand.begin(); while (index != pressEventToCommand.end()) { if (index->second == command) { unbind(index->first, true); index = pressEventToCommand.erase(index); } else { index++; } } index = releaseEventToCommand.begin(); while (index != releaseEventToCommand.end()) { if (index->second == command) { unbind(index->first, true); index = releaseEventToCommand.erase(index); } else { index++; } } } std::string KeyManager::get(const BzfKeyEvent& key, bool press) const { const EventToCommandMap* map = press ? &pressEventToCommand : &releaseEventToCommand; EventToCommandMap::const_iterator index = map->find(key); if (index == map->end()) return ""; else return index->second; } std::vector<std::string> KeyManager::getKeysFromCommand(std::string command, bool press) const { std::vector<std::string> keys; EventToCommandMap::const_iterator index; if (press) { for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index) { if (index->second == command) { keys.push_back(this->keyEventToString(index->first)); } } } else { for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index) { if (index->second == command) { keys.push_back(this->keyEventToString(index->first)); } } } return keys; } std::string KeyManager::keyEventToString( const BzfKeyEvent& key) const { std::string name; if (key.shift & BzfKeyEvent::ShiftKey) name += "Shift+"; if (key.shift & BzfKeyEvent::ControlKey) name += "Ctrl+"; if (key.shift & BzfKeyEvent::AltKey) name += "Alt+"; switch (key.ascii) { case 0: return name + buttonNames[key.button]; case '\b': return name + "Backspace"; case '\t': return name + "Tab"; case '\r': return name + "Enter"; case ' ': return name + "Space"; default: if (!isspace(key.ascii)) return name + std::string(&key.ascii, 1); return name + "???"; } } bool KeyManager::stringToKeyEvent( const std::string& name, BzfKeyEvent& key) const { // find last + in name const char* shiftDelimiter = strrchr(name.c_str(), '+'); // split name into shift part and key name part std::string shiftPart, keyPart; if (shiftDelimiter == NULL) { keyPart = name; } else { shiftPart = "+"; shiftPart += name.substr(0, shiftDelimiter - name.c_str() + 1); keyPart = shiftDelimiter + 1; } // find key name StringToEventMap::const_iterator index = stringToEvent.find(keyPart); if (index == stringToEvent.end()) return false; // get key event sans shift state key = index->second; // apply shift state if (strstr(shiftPart.c_str(), "+Shift+") != NULL || strstr(shiftPart.c_str(), "+shift+") != NULL) key.shift |= BzfKeyEvent::ShiftKey; if (strstr(shiftPart.c_str(), "+Ctrl+") != NULL || strstr(shiftPart.c_str(), "+ctrl+") != NULL) key.shift |= BzfKeyEvent::ControlKey; if (strstr(shiftPart.c_str(), "+Alt+") != NULL || strstr(shiftPart.c_str(), "+alt+") != NULL) key.shift |= BzfKeyEvent::AltKey; // success return true; } void KeyManager::iterate( IterateCallback callback, void* userData) { assert(callback != NULL); EventToCommandMap::const_iterator index; for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index) (*callback)(keyEventToString(index->first), true, index->second, userData); for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index) (*callback)(keyEventToString(index->first), false, index->second, userData); } void KeyManager::addCallback( ChangeCallback callback, void* userData) { callbacks.add(callback, userData); } void KeyManager::removeCallback( ChangeCallback callback, void* userData) { callbacks.remove(callback, userData); } void KeyManager::notify( const BzfKeyEvent& key, bool press, const std::string& cmd) { CallbackInfo info; info.name = keyEventToString(key); info.press = press; info.cmd = cmd; callbacks.iterate(&onCallback, &info); } bool KeyManager::onCallback( ChangeCallback callback, void* userData, void* vinfo) { CallbackInfo* info = reinterpret_cast<CallbackInfo*>(vinfo); callback(info->name, info->press, info->cmd, userData); return true; } bool KeyManager::KeyEventLess::operator()( const BzfKeyEvent& a, const BzfKeyEvent& b) const { if (a.ascii == 0 && b.ascii == 0) { if (a.button < b.button) return true; if (a.button > b.button) return false; // check shift if (a.shift < b.shift) return true; } else if (a.ascii == 0 && b.ascii != 0) { return true; } else if (a.ascii != 0 && b.ascii == 0) { return false; } else { if (toupper(a.ascii) < toupper(b.ascii)) return true; if (toupper(a.ascii) > toupper(b.ascii)) return false; // check shift state without shift key if ((a.shift & ~BzfKeyEvent::ShiftKey) < (b.shift & ~BzfKeyEvent::ShiftKey)) return true; } return false; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #if defined(_MSC_VER) #pragma warning(4:4503) #endif // interface header #include "KeyManager.h" // system headers #include <assert.h> #include <ctype.h> #include <string.h> // strstr, etc #include <string> // std::string #include <vector> // local implementation headers #include "BzfEvent.h" // initialize the singleton template <> KeyManager* Singleton<KeyManager>::_instance = (KeyManager*)0; const char* KeyManager::buttonNames[] = { "???", "Pause", "Home", "End", "Left Arrow", "Right Arrow", "Up Arrow", "Down Arrow", "Page Up", "Page Down", "Insert", "Backspace", "Delete", "Kp0", "Kp1", "Kp2", "Kp3", "Kp4", "Kp5", "Kp6", "Kp7", "Kp8", "Kp9", "Kp_Period", "Kp_Divide", "Kp_Multiply", "Kp_Minus", "Kp_Plus", "Kp_Enter", "Kp_Equals", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "Help", "Print", "Sysreq", "Break", "Menu", "Power", "Euro", "Undo", "Left Mouse", "Middle Mouse", "Right Mouse", "Wheel Up", "Wheel Down", "Mouse Button 6", "Mouse Button 7", "Mouse Button 8", "Mouse Button 9", "Mouse Button 10", "Joystick Button 1", "Joystick Button 2", "Joystick Button 3", "Joystick Button 4", "Joystick Button 5", "Joystick Button 6", "Joystick Button 7", "Joystick Button 8", "Joystick Button 9", "Joystick Button 10", "LastButton" // should always be last item listed }; const char* KeyManager::asciiNames[][2] = { { "Tab", "\t" }, { "Backspace", "\b" }, { "Enter", "\r" }, { "Space", " " } }; KeyManager::KeyManager() { unsigned int i; // prep string to key map BzfKeyEvent key; key.ascii = 0; key.shift = 0; for (i = BzfKeyEvent::Pause; i < BzfKeyEvent::LastButton; ++i) { key.button = static_cast<BzfKeyEvent::Button>(i); stringToEvent.insert(std::make_pair(std::string(buttonNames[i]), key)); } key.button = BzfKeyEvent::NoButton; for (i = 0; i < countof(asciiNames); ++i) { key.ascii = asciiNames[i][1][0]; stringToEvent.insert(std::make_pair(std::string(asciiNames[i][0]), key)); } char buffer[2]; buffer[1] = 0; for (i = 0x21; i < 0x7f; ++i) { buffer[0] = key.ascii = static_cast<char>(i); stringToEvent.insert(std::make_pair(std::string(buffer), key)); } } KeyManager::~KeyManager() { } void KeyManager::bind(const BzfKeyEvent& key, bool press, const std::string& cmd) { if (press) { pressEventToCommand.erase(key); pressEventToCommand.insert(std::make_pair(key, cmd)); } else { releaseEventToCommand.erase(key); releaseEventToCommand.insert(std::make_pair(key, cmd)); } notify(key, press, cmd); } void KeyManager::unbind(const BzfKeyEvent& key, bool press) { if (press) pressEventToCommand.erase(key); else releaseEventToCommand.erase(key); notify(key, press, ""); } void KeyManager::unbindCommand(const char* command) { EventToCommandMap::iterator index; EventToCommandMap::iterator deleteme; index = pressEventToCommand.begin(); while (index != pressEventToCommand.end()) { if (index->second == command) { deleteme = index; index++; unbind(deleteme->first, true); } else { index++; } } index = releaseEventToCommand.begin(); while (index != releaseEventToCommand.end()) { if (index->second == command) { deleteme = index; index++; unbind(deleteme->first, true); } else { index++; } } } std::string KeyManager::get(const BzfKeyEvent& key, bool press) const { const EventToCommandMap* map = press ? &pressEventToCommand : &releaseEventToCommand; EventToCommandMap::const_iterator index = map->find(key); if (index == map->end()) return ""; else return index->second; } std::vector<std::string> KeyManager::getKeysFromCommand(std::string command, bool press) const { std::vector<std::string> keys; EventToCommandMap::const_iterator index; if (press) { for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index) { if (index->second == command) { keys.push_back(this->keyEventToString(index->first)); } } } else { for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index) { if (index->second == command) { keys.push_back(this->keyEventToString(index->first)); } } } return keys; } std::string KeyManager::keyEventToString( const BzfKeyEvent& key) const { std::string name; if (key.shift & BzfKeyEvent::ShiftKey) name += "Shift+"; if (key.shift & BzfKeyEvent::ControlKey) name += "Ctrl+"; if (key.shift & BzfKeyEvent::AltKey) name += "Alt+"; switch (key.ascii) { case 0: return name + buttonNames[key.button]; case '\b': return name + "Backspace"; case '\t': return name + "Tab"; case '\r': return name + "Enter"; case ' ': return name + "Space"; default: if (!isspace(key.ascii)) return name + std::string(&key.ascii, 1); return name + "???"; } } bool KeyManager::stringToKeyEvent( const std::string& name, BzfKeyEvent& key) const { // find last + in name const char* shiftDelimiter = strrchr(name.c_str(), '+'); // split name into shift part and key name part std::string shiftPart, keyPart; if (shiftDelimiter == NULL) { keyPart = name; } else { shiftPart = "+"; shiftPart += name.substr(0, shiftDelimiter - name.c_str() + 1); keyPart = shiftDelimiter + 1; } // find key name StringToEventMap::const_iterator index = stringToEvent.find(keyPart); if (index == stringToEvent.end()) return false; // get key event sans shift state key = index->second; // apply shift state if (strstr(shiftPart.c_str(), "+Shift+") != NULL || strstr(shiftPart.c_str(), "+shift+") != NULL) key.shift |= BzfKeyEvent::ShiftKey; if (strstr(shiftPart.c_str(), "+Ctrl+") != NULL || strstr(shiftPart.c_str(), "+ctrl+") != NULL) key.shift |= BzfKeyEvent::ControlKey; if (strstr(shiftPart.c_str(), "+Alt+") != NULL || strstr(shiftPart.c_str(), "+alt+") != NULL) key.shift |= BzfKeyEvent::AltKey; // success return true; } void KeyManager::iterate( IterateCallback callback, void* userData) { assert(callback != NULL); EventToCommandMap::const_iterator index; for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index) (*callback)(keyEventToString(index->first), true, index->second, userData); for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index) (*callback)(keyEventToString(index->first), false, index->second, userData); } void KeyManager::addCallback( ChangeCallback callback, void* userData) { callbacks.add(callback, userData); } void KeyManager::removeCallback( ChangeCallback callback, void* userData) { callbacks.remove(callback, userData); } void KeyManager::notify( const BzfKeyEvent& key, bool press, const std::string& cmd) { CallbackInfo info; info.name = keyEventToString(key); info.press = press; info.cmd = cmd; callbacks.iterate(&onCallback, &info); } bool KeyManager::onCallback( ChangeCallback callback, void* userData, void* vinfo) { CallbackInfo* info = reinterpret_cast<CallbackInfo*>(vinfo); callback(info->name, info->press, info->cmd, userData); return true; } bool KeyManager::KeyEventLess::operator()( const BzfKeyEvent& a, const BzfKeyEvent& b) const { if (a.ascii == 0 && b.ascii == 0) { if (a.button < b.button) return true; if (a.button > b.button) return false; // check shift if (a.shift < b.shift) return true; } else if (a.ascii == 0 && b.ascii != 0) { return true; } else if (a.ascii != 0 && b.ascii == 0) { return false; } else { if (toupper(a.ascii) < toupper(b.ascii)) return true; if (toupper(a.ascii) > toupper(b.ascii)) return false; // check shift state without shift key if ((a.shift & ~BzfKeyEvent::ShiftKey) < (b.shift & ~BzfKeyEvent::ShiftKey)) return true; } return false; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
increment the iterator before deleting the object it points to
increment the iterator before deleting the object it points to git-svn-id: 67bf12f30ddf2081c31403e0b02b2123541f1680@7816 08b3d480-bf2c-0410-a26f-811ee3361c24
C++
lgpl-2.1
adamsdadakaeti/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag
a6e5887d73ba5ce5e2a8538594dafa4674465337
src/engine/Application.cpp
src/engine/Application.cpp
#include "Application.hpp" #include "input/Input.hpp" #include "graphics/GLUtilities.hpp" #include "graphics/Framebuffer.hpp" #include "system/System.hpp" Application::Application(RenderingConfig & config) : _config(config) { } void Application::update() { // Handle window resize. if(Input::manager().resized()) { const unsigned int width = uint(Input::manager().size()[0]); const unsigned int height = uint(Input::manager().size()[1]); _config.screenResolution[0] = float(width > 0 ? width : 1); _config.screenResolution[1] = float(height > 0 ? height : 1); resize(); } // Perform screenshot capture in the current working directory. if(Input::manager().triggered(Input::Key::O) || (Input::manager().controllerAvailable() && Input::manager().controller()->triggered(Controller::ButtonView))) { //\todo Generate timestamp. GLUtilities::saveFramebuffer(Framebuffer::backbuffer(), uint(_config.screenResolution[0]), uint(_config.screenResolution[1]), "./test-default", true, true); } } CameraApp::CameraApp(RenderingConfig & config) : Application(config) { _timer = System::time(); _userCamera.ratio(config.screenResolution[0] / config.screenResolution[1]); } void CameraApp::update(){ Application::update(); _userCamera.update(); // We separate punctual events from the main physics/movement update loop. // Compute the time elapsed since last frame const double currentTime = System::time(); double frameTime = currentTime - _timer; _timer = currentTime; // Physics simulation // First avoid super high frametime by clamping. if(frameTime > 0.2) { frameTime = 0.2; } // Accumulate new frame time. _remainingTime += frameTime; // Instead of bounding at dt, we lower our requirement (1 order of magnitude). while(_remainingTime > 0.2 * _dt) { const double deltaTime = std::min(_remainingTime, _dt); if(!_freezeCamera){ _userCamera.physics(deltaTime); } // Update physics. physics(_fullTime, deltaTime); // Update timers. _fullTime += deltaTime; _remainingTime -= deltaTime; } } void CameraApp::physics(double, double){ } void CameraApp::freezeCamera(bool shouldFreeze){ _freezeCamera = shouldFreeze; }
#include "Application.hpp" #include "input/Input.hpp" #include "graphics/GLUtilities.hpp" #include "graphics/Framebuffer.hpp" #include "system/System.hpp" Application::Application(RenderingConfig & config) : _config(config) { } void Application::update() { // Handle window resize. if(Input::manager().resized()) { const unsigned int width = uint(Input::manager().size()[0]); const unsigned int height = uint(Input::manager().size()[1]); _config.screenResolution[0] = float(width > 0 ? width : 1); _config.screenResolution[1] = float(height > 0 ? height : 1); resize(); } // Perform screenshot capture in the current working directory. if(Input::manager().triggered(Input::Key::O) || (Input::manager().controllerAvailable() && Input::manager().controller()->triggered(Controller::ButtonView))) { const std::string filename = System::timestamp(); GLUtilities::saveFramebuffer(Framebuffer::backbuffer(), uint(_config.screenResolution[0]), uint(_config.screenResolution[1]), "./" + filename, true, true); } } CameraApp::CameraApp(RenderingConfig & config) : Application(config) { _timer = System::time(); _userCamera.ratio(config.screenResolution[0] / config.screenResolution[1]); } void CameraApp::update(){ Application::update(); _userCamera.update(); // We separate punctual events from the main physics/movement update loop. // Compute the time elapsed since last frame const double currentTime = System::time(); double frameTime = currentTime - _timer; _timer = currentTime; // Physics simulation // First avoid super high frametime by clamping. if(frameTime > 0.2) { frameTime = 0.2; } // Accumulate new frame time. _remainingTime += frameTime; // Instead of bounding at dt, we lower our requirement (1 order of magnitude). while(_remainingTime > 0.2 * _dt) { const double deltaTime = std::min(_remainingTime, _dt); if(!_freezeCamera){ _userCamera.physics(deltaTime); } // Update physics. physics(_fullTime, deltaTime); // Update timers. _fullTime += deltaTime; _remainingTime -= deltaTime; } } void CameraApp::physics(double, double){ } void CameraApp::freezeCamera(bool shouldFreeze){ _freezeCamera = shouldFreeze; }
use timestamp for saving screenshot.
Application: use timestamp for saving screenshot.
C++
mit
kosua20/GL_Template,kosua20/GL_Template
18e3b8b7fa087a208f85e7f2ea07cded79033b59
openCherry/Bundles/org.opencherry.ui/src/internal/cherryLayoutPartSash.cpp
openCherry/Bundles/org.opencherry.ui/src/internal/cherryLayoutPartSash.cpp
/*========================================================================= Program: openCherry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "cherryLayoutPartSash.h" #include "cherryLayoutTree.h" #include "cherryLayoutTreeNode.h" #include "cherryWorkbenchPlugin.h" #include "../cherryConstants.h" #include "../tweaklets/cherryGuiWidgetsTweaklet.h" namespace cherry { LayoutPartSash::SelectionListener::SelectionListener(LayoutPartSash* lp) : layoutPartSash(lp) { } void LayoutPartSash::SelectionListener::WidgetSelected(GuiTk::SelectionEvent::Pointer e) { layoutPartSash->CheckDragLimit(e); if (e->detail != Constants::DRAG) { layoutPartSash->WidgetSelected(e->x, e->y, e->width, e->height); } } LayoutPartSash::LayoutPartSash(PartSashContainer* rootContainer, int style) : LayoutPart(""), sash(0), enabled(false), rootContainer(rootContainer), style(style), left(300), right(300), presFactory(0), isVisible(false) { selectionListener = new SelectionListener(this); } LayoutPartSash::~LayoutPartSash() { this->Dispose(); } void LayoutPartSash::CheckDragLimit(GuiTk::SelectionEvent::Pointer event) { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); Rectangle eventRect(event->x, event->y, event->width, event->height); bool vertical = (style == Constants::VERTICAL); // If a horizontal sash, flip the coordinate system so that we // can handle horizontal and vertical sashes without special cases if (!vertical) { nodeBounds.FlipXY(); eventRect.FlipXY(); } int eventX = eventRect.x; int left = std::max<int>(0, eventX - nodeBounds.x); left = std::min<int>(left, nodeBounds.width - this->GetSashSize()); int right = nodeBounds.width - left - this->GetSashSize(); LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width, nodeBounds.height, left, right, nodeBounds.width); eventRect.x = nodeBounds.x + sizes.left; // If it's a horizontal sash, restore eventRect to its original coordinate system if (!vertical) { eventRect.FlipXY(); } event->x = eventRect.x; event->y = eventRect.y; } void LayoutPartSash::CreateControl(void* /*parent*/) { // Defer creation of the control until it becomes visible if (isVisible) { this->DoCreateControl(); } } void LayoutPartSash::DoCreateControl() { if (sash == 0) { // ask the presentation factory to create the sash IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; sash = factory->CreateSash(this->rootContainer->GetParent(), sashStyle); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddSelectionListener(sash, selectionListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(sash, bounds); //sash.addSelectionListener(selectionListener); //sash.setEnabled(enabled); //sash.setBounds(bounds); } } void LayoutPartSash::SetBounds(const Rectangle& r) { LayoutPart::SetBounds(r); bounds = r; } void LayoutPartSash::SetVisible(bool visible) { if (visible == isVisible) { return; } if (visible) { this->DoCreateControl(); } else { this->Dispose(); } LayoutPart::SetVisible(visible); isVisible = visible; } bool LayoutPartSash::IsVisible() { return isVisible; } void LayoutPartSash::Dispose() { if (sash != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(sash); } sash = 0; isVisible = false; } Rectangle LayoutPartSash::GetBounds() { if (sash == 0) { return bounds; } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); } void* LayoutPartSash::GetControl() { return sash; } std::string LayoutPartSash::GetID() { return ""; } LayoutPartSash::Pointer LayoutPartSash::GetPostLimit() { return postLimit; } LayoutPartSash::Pointer LayoutPartSash::GetPreLimit() { return preLimit; } int LayoutPartSash::GetLeft() { return left; } int LayoutPartSash::GetRight() { return right; } bool LayoutPartSash::IsHorizontal() { return ((style & Constants::HORIZONTAL) == Constants::HORIZONTAL); } bool LayoutPartSash::IsVertical() { return ((style & Constants::VERTICAL) == Constants::VERTICAL); } void LayoutPartSash::SetPostLimit(LayoutPartSash::Pointer newPostLimit) { postLimit = newPostLimit; } void LayoutPartSash::SetPreLimit(LayoutPartSash::Pointer newPreLimit) { preLimit = newPreLimit; } void LayoutPartSash::SetRatio(float newRatio) { int total = left + right; int newLeft = (int) (total * newRatio); this->SetSizes(newLeft, total - newLeft); } void LayoutPartSash::SetSizes(int left, int right) { if (left < 0 || right < 0) { return; } if (left == this->left && right == this->right) { return; } this->left = left; this->right = right; this->FlushCache(); } void LayoutPartSash::FlushCache() { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); if (root != 0) { LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); if (node != 0) { node->FlushCache(); } } } void LayoutPartSash::WidgetSelected(int x, int y, int /*width*/, int /*height*/) { if (!enabled) { return; } LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); //Recompute ratio x -= nodeBounds.x; y -= nodeBounds.y; if (style == Constants::VERTICAL) { this->SetSizes(x, nodeBounds.width - x - this->GetSashSize()); } else { this->SetSizes(y, nodeBounds.height - y - this->GetSashSize()); } node->SetBounds(nodeBounds); } void LayoutPartSash::SetEnabled(bool resizable) { this->enabled = resizable; if (sash != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); } } int LayoutPartSash::GetSashSize() const { IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; int size = factory->GetSashSize(sashStyle); return size; } }
/*========================================================================= Program: openCherry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "cherryLayoutPartSash.h" #include "cherryLayoutTree.h" #include "cherryLayoutTreeNode.h" #include "cherryWorkbenchPlugin.h" #include "../cherryConstants.h" #include "../tweaklets/cherryGuiWidgetsTweaklet.h" namespace cherry { LayoutPartSash::SelectionListener::SelectionListener(LayoutPartSash* lp) : layoutPartSash(lp) { } void LayoutPartSash::SelectionListener::WidgetSelected(GuiTk::SelectionEvent::Pointer e) { layoutPartSash->CheckDragLimit(e); if (e->detail != Constants::DRAG) { layoutPartSash->WidgetSelected(e->x, e->y, e->width, e->height); } } LayoutPartSash::LayoutPartSash(PartSashContainer* rootContainer, int style) : LayoutPart(""), sash(0), enabled(false), rootContainer(rootContainer), style(style), left(300), right(300), presFactory(0), isVisible(false) { selectionListener = new SelectionListener(this); } LayoutPartSash::~LayoutPartSash() { this->Dispose(); } void LayoutPartSash::CheckDragLimit(GuiTk::SelectionEvent::Pointer event) { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); Rectangle eventRect(event->x, event->y, event->width, event->height); bool vertical = (style == Constants::VERTICAL); // If a horizontal sash, flip the coordinate system so that we // can handle horizontal and vertical sashes without special cases if (!vertical) { nodeBounds.FlipXY(); eventRect.FlipXY(); } int eventX = eventRect.x; int left = std::max<int>(0, eventX - nodeBounds.x); left = std::min<int>(left, nodeBounds.width - this->GetSashSize()); int right = nodeBounds.width - left - this->GetSashSize(); LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width, nodeBounds.height, left, right, nodeBounds.width); eventRect.x = nodeBounds.x + sizes.left; // If it's a horizontal sash, restore eventRect to its original coordinate system if (!vertical) { eventRect.FlipXY(); } event->x = eventRect.x; event->y = eventRect.y; } void LayoutPartSash::CreateControl(void* /*parent*/) { // Defer creation of the control until it becomes visible if (isVisible) { this->DoCreateControl(); } } void LayoutPartSash::DoCreateControl() { if (sash == 0) { // ask the presentation factory to create the sash IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; sash = factory->CreateSash(this->rootContainer->GetParent(), sashStyle); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddSelectionListener(sash, selectionListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(sash, bounds); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(sash, isVisible); } } void LayoutPartSash::SetBounds(const Rectangle& r) { LayoutPart::SetBounds(r); bounds = r; } void LayoutPartSash::SetVisible(bool visible) { if (visible == isVisible) { return; } if (visible) { this->DoCreateControl(); } else { this->Dispose(); } LayoutPart::SetVisible(visible); isVisible = visible; } bool LayoutPartSash::IsVisible() { return isVisible; } void LayoutPartSash::Dispose() { if (sash != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(sash); } sash = 0; } Rectangle LayoutPartSash::GetBounds() { if (sash == 0) { return bounds; } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); } void* LayoutPartSash::GetControl() { return sash; } std::string LayoutPartSash::GetID() { return ""; } LayoutPartSash::Pointer LayoutPartSash::GetPostLimit() { return postLimit; } LayoutPartSash::Pointer LayoutPartSash::GetPreLimit() { return preLimit; } int LayoutPartSash::GetLeft() { return left; } int LayoutPartSash::GetRight() { return right; } bool LayoutPartSash::IsHorizontal() { return ((style & Constants::HORIZONTAL) == Constants::HORIZONTAL); } bool LayoutPartSash::IsVertical() { return ((style & Constants::VERTICAL) == Constants::VERTICAL); } void LayoutPartSash::SetPostLimit(LayoutPartSash::Pointer newPostLimit) { postLimit = newPostLimit; } void LayoutPartSash::SetPreLimit(LayoutPartSash::Pointer newPreLimit) { preLimit = newPreLimit; } void LayoutPartSash::SetRatio(float newRatio) { int total = left + right; int newLeft = (int) (total * newRatio); this->SetSizes(newLeft, total - newLeft); } void LayoutPartSash::SetSizes(int left, int right) { if (left < 0 || right < 0) { return; } if (left == this->left && right == this->right) { return; } this->left = left; this->right = right; this->FlushCache(); } void LayoutPartSash::FlushCache() { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); if (root != 0) { LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); if (node != 0) { node->FlushCache(); } } } void LayoutPartSash::WidgetSelected(int x, int y, int /*width*/, int /*height*/) { if (!enabled) { return; } LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); //Recompute ratio x -= nodeBounds.x; y -= nodeBounds.y; if (style == Constants::VERTICAL) { this->SetSizes(x, nodeBounds.width - x - this->GetSashSize()); } else { this->SetSizes(y, nodeBounds.height - y - this->GetSashSize()); } node->SetBounds(nodeBounds); } void LayoutPartSash::SetEnabled(bool resizable) { this->enabled = resizable; if (sash != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); } } int LayoutPartSash::GetSashSize() const { IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; int size = factory->GetSashSize(sashStyle); return size; } }
FIX (#2904): The sash widget was invisible by default after creating it, and not synchronized with the state of LayoutPartSash. Fixed by calling setVisible on the sash with the current visibility of LayoutPartSash.
FIX (#2904): The sash widget was invisible by default after creating it, and not synchronized with the state of LayoutPartSash. Fixed by calling setVisible on the sash with the current visibility of LayoutPartSash.
C++
bsd-3-clause
fmilano/mitk,iwegner/MITK,danielknorr/MITK,NifTK/MITK,danielknorr/MITK,rfloca/MITK,rfloca/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,rfloca/MITK,fmilano/mitk,iwegner/MITK,MITK/MITK,nocnokneo/MITK,iwegner/MITK,NifTK/MITK,rfloca/MITK,rfloca/MITK,fmilano/mitk,iwegner/MITK,nocnokneo/MITK,RabadanLab/MITKats,nocnokneo/MITK,MITK/MITK,fmilano/mitk,iwegner/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,MITK/MITK,danielknorr/MITK,nocnokneo/MITK,NifTK/MITK,iwegner/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,RabadanLab/MITKats,danielknorr/MITK,fmilano/mitk,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,NifTK/MITK,fmilano/mitk,MITK/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,nocnokneo/MITK,rfloca/MITK,RabadanLab/MITKats,danielknorr/MITK,nocnokneo/MITK,RabadanLab/MITKats,rfloca/MITK,NifTK/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,fmilano/mitk,NifTK/MITK,lsanzdiaz/MITK-BiiG
6c5d02d2f15cd3bf47e2a7da1f88c346a9454d92
src/filemgr_ops_windows.cc
src/filemgr_ops_windows.cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <string.h> #include "filemgr.h" #include "filemgr_ops.h" #if defined(WIN32) || defined(_WIN32) #include <windows.h> #include <io.h> static inline HANDLE handle_to_win(int fd) { return (HANDLE)_get_osfhandle(fd); } fdb_fileops_handle _filemgr_win_constructor(void *ctx) { return fd_to_handle(-1); } fdb_status _filemgr_win_open(const char *pathname, fdb_fileops_handle *fileops_handle, int flags, mode_t mode) { #ifdef _MSC_VER int fd = _open(pathname, flags, mode); if (fd < 0) { errno_t err; _get_errno(&err); return (fdb_status) convert_errno_to_fdb_status(err, FDB_RESULT_OPEN_FAIL); } *fileops_handle = fd_to_handle(fd); return FDB_RESULT_SUCCESS; #else int fd; do { fd = open(pathname, flags | O_LARGEFILE, mode); } while (fd == -1 && errno == EINTR); if (fd < 0) { return (fdb_status) convert_errno_to_fdb_status(errno, FDB_RESULT_OPEN_FAIL); } *fileops_handle = fd_to_handle(fd); return FDB_RESULT_SUCCESS; #endif } ssize_t _filemgr_win_pwrite(fdb_fileops_handle fileops_handle, void *buf, size_t count, cs_off_t offset) { int fd = handle_to_fd(fileops_handle); HANDLE file = handle_to_win(fd); BOOL rv; DWORD byteswritten; OVERLAPPED winoffs; memset(&winoffs, 0, sizeof(winoffs)); winoffs.Offset = offset & 0xFFFFFFFF; winoffs.OffsetHigh = ((uint64_t)offset >> 32) & 0x7FFFFFFF; rv = WriteFile(file, buf, count, &byteswritten, &winoffs); if(!rv) { #ifdef _MSC_VER errno_t err; _get_errno(&err); return (ssize_t) convert_errno_to_fdb_status(err, FDB_RESULT_WRITE_FAIL); #else return (sszie_t) convert_errno_to_fdb_status(errno, FDB_RESULT_WRITE_FAIL); #endif } return (ssize_t) byteswritten; } ssize_t _filemgr_win_pread(fdb_fileops_handle fileops_handle, void *buf, size_t count, cs_off_t offset) { int fd = handle_to_fd(fileops_handle); HANDLE file = handle_to_win(fd); BOOL rv; DWORD bytesread; OVERLAPPED winoffs; memset(&winoffs, 0, sizeof(winoffs)); winoffs.Offset = offset & 0xFFFFFFFF; winoffs.OffsetHigh = ((uint64_t)offset >> 32) & 0x7FFFFFFF; rv = ReadFile(file, buf, count, &bytesread, &winoffs); if(!rv) { #ifdef _MSC_VER errno_t err; _get_errno(&err); return (ssize_t) convert_errno_to_fdb_status(err, FDB_RESULT_READ_FAIL); #else return (ssize_t) convert_errno_to_fdb_status(errno, FDB_RESULT_READ_FAIL); #endif } return (ssize_t) bytesread; } int _filemgr_win_close(fdb_fileops_handle fileops_handle) { int fd = handle_to_fd(fileops_handle); #ifdef _MSC_VER int rv = 0; if (fd != -1) { rv = _close(fd); } if (rv < 0) { errno_t err; _get_errno(&err); return (int) convert_errno_to_fdb_status(err, FDB_RESULT_CLOSE_FAIL); } return FDB_RESULT_SUCCESS; #else int rv = 0; if (fd != -1) { do { rv = close(fd); } while (rv == -1 && errno == EINTR); } if (rv < 0) { return (int) convert_errno_to_fdb_status(errno, FDB_RESULT_CLOSE_FAIL); } return FDB_RESULT_SUCCESS; #endif } cs_off_t _filemgr_win_goto_eof(fdb_fileops_handle fileops_handle) { #ifdef _MSC_VER cs_off_t rv = _lseeki64(handle_to_fd(fileops_handle), 0, SEEK_END); if (rv < 0) { errno_t err; _get_errno(&err); return (cs_off_t) convert_errno_to_fdb_status(err, FDB_RESULT_SEEK_FAIL); } return rv; #else cs_off_t rv = lseek(handle_to_fd(fileops_handle), 0, SEEK_END); if (rv < 0) { return (cs_off_t) convert_errno_to_fdb_status(errno, FDB_RESULT_SEEK_FAIL); } return rv; #endif } cs_off_t _filemgr_win_file_size(fdb_fileops_handle fileops_handle, const char *filename) { #ifdef _MSC_VER struct _stat st; if (_stat(filename, &st) == -1) { errno_t err; _get_errno(&err); return (cs_off_t) convert_errno_to_fdb_status(err, FDB_RESULT_READ_FAIL); } return st.st_size; #else struct stat st; if (stat(filename, &st) == -1) { return (cs_off_t) convert_errno_to_fdb_status(errno, FDB_RESULT_READ_FAIL); } return st.st_size; #endif } int _filemgr_win_fsync(fdb_fileops_handle fileops_handle) { int fd = handle_to_fd(fileops_handle); HANDLE file = handle_to_win(fd); if (!FlushFileBuffers(file)) { #ifdef _MSC_VER errno_t err; _get_errno(&err); return (int) convert_errno_to_fdb_status(err, FDB_RESULT_FSYNC_FAIL); #else return (int) convert_errno_to_fdb_status(errno, FDB_RESULT_FSYNC_FAIL); #endif } return FDB_RESULT_SUCCESS; } int _filemgr_win_fdatasync(fdb_fileops_handle fileops_handle) { return _filemgr_win_fsync(fileops_handle); } void _filemgr_win_get_errno_str(fdb_fileops_handle fileops_handle, char *buf, size_t size) { if (!buf) { return; } char* win_msg = NULL; DWORD err = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &win_msg, 0, NULL); _snprintf(buf, size, "errno = %d: '%s'", err, win_msg); LocalFree(win_msg); } int _filemgr_aio_init(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_prep_read(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle, size_t aio_idx, size_t read_size, uint64_t offset) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_submit(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle, int num_subs) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_getevents(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle, int min, int max, unsigned int timeout) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_destroy(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_win_get_fs_type(fdb_fileops_handle src_fileops_handle) { return FILEMGR_FS_NO_COW; } int _filemgr_win_copy_file_range(int fstype, fdb_fileops_handle src_fileops_handle, fdb_fileops_handle dst_fileops_handle, uint64_t src_off, uint64_t dst_off, uint64_t len) { return FDB_RESULT_INVALID_ARGS; } void _filemgr_win_destructor(fdb_fileops_handle fileops_handle) { (void)fileops_handle; } struct filemgr_ops win_ops = { _filemgr_win_constructor, _filemgr_win_open, _filemgr_win_pwrite, _filemgr_win_pread, _filemgr_win_close, _filemgr_win_goto_eof, _filemgr_win_file_size, _filemgr_win_fdatasync, _filemgr_win_fsync, _filemgr_win_get_errno_str, // Async I/O operations _filemgr_aio_init, _filemgr_aio_prep_read, _filemgr_aio_submit, _filemgr_aio_getevents, _filemgr_aio_destroy, _filemgr_win_get_fs_type, _filemgr_win_copy_file_range, _filemgr_win_destructor, NULL }; struct filemgr_ops * get_win_filemgr_ops() { return &win_ops; } #endif
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <string.h> #include "filemgr.h" #include "filemgr_ops.h" #if defined(WIN32) || defined(_WIN32) #include <windows.h> #include <io.h> static inline HANDLE handle_to_win(int fd) { return (HANDLE)_get_osfhandle(fd); } fdb_fileops_handle _filemgr_win_constructor(void *ctx) { return fd_to_handle(-1); } fdb_status _filemgr_win_open(const char *pathname, fdb_fileops_handle *fileops_handle, int flags, mode_t mode) { #ifdef _MSC_VER int fd = _open(pathname, flags, mode); if (fd < 0) { errno_t err; _get_errno(&err); return (fdb_status) convert_errno_to_fdb_status(err, FDB_RESULT_OPEN_FAIL); } *fileops_handle = fd_to_handle(fd); return FDB_RESULT_SUCCESS; #else int fd; do { fd = open(pathname, flags | O_LARGEFILE, mode); } while (fd == -1 && errno == EINTR); if (fd < 0) { return (fdb_status) convert_errno_to_fdb_status(errno, FDB_RESULT_OPEN_FAIL); } *fileops_handle = fd_to_handle(fd); return FDB_RESULT_SUCCESS; #endif } ssize_t _filemgr_win_pwrite(fdb_fileops_handle fileops_handle, void *buf, size_t count, cs_off_t offset) { int fd = handle_to_fd(fileops_handle); HANDLE file = handle_to_win(fd); BOOL rv; DWORD byteswritten; OVERLAPPED winoffs; memset(&winoffs, 0, sizeof(winoffs)); winoffs.Offset = offset & 0xFFFFFFFF; winoffs.OffsetHigh = ((uint64_t)offset >> 32) & 0x7FFFFFFF; rv = WriteFile(file, buf, count, &byteswritten, &winoffs); if(!rv) { #ifdef _MSC_VER errno_t err; _get_errno(&err); return (ssize_t) convert_errno_to_fdb_status(err, FDB_RESULT_WRITE_FAIL); #else return (ssize_t) convert_errno_to_fdb_status(errno, FDB_RESULT_WRITE_FAIL); #endif } return (ssize_t) byteswritten; } ssize_t _filemgr_win_pread(fdb_fileops_handle fileops_handle, void *buf, size_t count, cs_off_t offset) { int fd = handle_to_fd(fileops_handle); HANDLE file = handle_to_win(fd); BOOL rv; DWORD bytesread; OVERLAPPED winoffs; memset(&winoffs, 0, sizeof(winoffs)); winoffs.Offset = offset & 0xFFFFFFFF; winoffs.OffsetHigh = ((uint64_t)offset >> 32) & 0x7FFFFFFF; rv = ReadFile(file, buf, count, &bytesread, &winoffs); if(!rv) { #ifdef _MSC_VER errno_t err; _get_errno(&err); return (ssize_t) convert_errno_to_fdb_status(err, FDB_RESULT_READ_FAIL); #else return (ssize_t) convert_errno_to_fdb_status(errno, FDB_RESULT_READ_FAIL); #endif } return (ssize_t) bytesread; } int _filemgr_win_close(fdb_fileops_handle fileops_handle) { int fd = handle_to_fd(fileops_handle); #ifdef _MSC_VER int rv = 0; if (fd != -1) { rv = _close(fd); } if (rv < 0) { errno_t err; _get_errno(&err); return (int) convert_errno_to_fdb_status(err, FDB_RESULT_CLOSE_FAIL); } return FDB_RESULT_SUCCESS; #else int rv = 0; if (fd != -1) { do { rv = close(fd); } while (rv == -1 && errno == EINTR); } if (rv < 0) { return (int) convert_errno_to_fdb_status(errno, FDB_RESULT_CLOSE_FAIL); } return FDB_RESULT_SUCCESS; #endif } cs_off_t _filemgr_win_goto_eof(fdb_fileops_handle fileops_handle) { #ifdef _MSC_VER cs_off_t rv = _lseeki64(handle_to_fd(fileops_handle), 0, SEEK_END); if (rv < 0) { errno_t err; _get_errno(&err); return (cs_off_t) convert_errno_to_fdb_status(err, FDB_RESULT_SEEK_FAIL); } return rv; #else cs_off_t rv = lseek(handle_to_fd(fileops_handle), 0, SEEK_END); if (rv < 0) { return (cs_off_t) convert_errno_to_fdb_status(errno, FDB_RESULT_SEEK_FAIL); } return rv; #endif } cs_off_t _filemgr_win_file_size(fdb_fileops_handle fileops_handle, const char *filename) { #ifdef _MSC_VER struct _stat st; if (_stat(filename, &st) == -1) { errno_t err; _get_errno(&err); return (cs_off_t) convert_errno_to_fdb_status(err, FDB_RESULT_READ_FAIL); } return st.st_size; #else struct stat st; if (stat(filename, &st) == -1) { return (cs_off_t) convert_errno_to_fdb_status(errno, FDB_RESULT_READ_FAIL); } return st.st_size; #endif } int _filemgr_win_fsync(fdb_fileops_handle fileops_handle) { int fd = handle_to_fd(fileops_handle); HANDLE file = handle_to_win(fd); if (!FlushFileBuffers(file)) { #ifdef _MSC_VER errno_t err; _get_errno(&err); return (int) convert_errno_to_fdb_status(err, FDB_RESULT_FSYNC_FAIL); #else return (int) convert_errno_to_fdb_status(errno, FDB_RESULT_FSYNC_FAIL); #endif } return FDB_RESULT_SUCCESS; } int _filemgr_win_fdatasync(fdb_fileops_handle fileops_handle) { return _filemgr_win_fsync(fileops_handle); } void _filemgr_win_get_errno_str(fdb_fileops_handle fileops_handle, char *buf, size_t size) { if (!buf) { return; } char* win_msg = NULL; DWORD err = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &win_msg, 0, NULL); _snprintf(buf, size, "errno = %d: '%s'", err, win_msg); LocalFree(win_msg); } int _filemgr_aio_init(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_prep_read(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle, size_t aio_idx, size_t read_size, uint64_t offset) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_submit(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle, int num_subs) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_getevents(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle, int min, int max, unsigned int timeout) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_aio_destroy(fdb_fileops_handle fileops_handle, struct async_io_handle *aio_handle) { return FDB_RESULT_AIO_NOT_SUPPORTED; } int _filemgr_win_get_fs_type(fdb_fileops_handle src_fileops_handle) { return FILEMGR_FS_NO_COW; } int _filemgr_win_copy_file_range(int fstype, fdb_fileops_handle src_fileops_handle, fdb_fileops_handle dst_fileops_handle, uint64_t src_off, uint64_t dst_off, uint64_t len) { return FDB_RESULT_INVALID_ARGS; } void _filemgr_win_destructor(fdb_fileops_handle fileops_handle) { (void)fileops_handle; } struct filemgr_ops win_ops = { _filemgr_win_constructor, _filemgr_win_open, _filemgr_win_pwrite, _filemgr_win_pread, _filemgr_win_close, _filemgr_win_goto_eof, _filemgr_win_file_size, _filemgr_win_fdatasync, _filemgr_win_fsync, _filemgr_win_get_errno_str, // Async I/O operations _filemgr_aio_init, _filemgr_aio_prep_read, _filemgr_aio_submit, _filemgr_aio_getevents, _filemgr_aio_destroy, _filemgr_win_get_fs_type, _filemgr_win_copy_file_range, _filemgr_win_destructor, NULL }; struct filemgr_ops * get_win_filemgr_ops() { return &win_ops; } #endif
Fix typo in filemgr_ops_windows
Fix typo in filemgr_ops_windows sszie_t --> ssize_t Change-Id: I7ddb61581b4df13a99c5b7d8e85f2add1f9f52d6 Reviewed-on: http://review.couchbase.org/65692 Reviewed-by: Chiyoung Seo <[email protected]> Tested-by: Chiyoung Seo <[email protected]>
C++
apache-2.0
couchbase/forestdb,hisundar/forestdb,couchbase/forestdb,wurikiji/forestdb,hisundar/forestdb,wurikiji/forestdb
73a3f9680e468b6062d90e9ebe0d3c2c38dcbe66
src/test_parse.cc
src/test_parse.cc
#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include "lhef.h" int main(int argc, char* argv[]) { if (argc != 2) { std::cout << "Usage: testparse input\n" << " - input: Input file in " << "Les Houches Event File format\n"; return 1; } std::ifstream filename(argv[1]); if (!filename) { std::cerr << "-- Cannot open input file \"" << argv[1] << "\".\n"; return 1; } else { std::cout << "-- Reading \"" << argv[1] << "\" ...\n"; } lhef::Event lhe = lhef::ParseEvent(&filename); lhef::Particles initstates; lhef::Particles finalstates; lhef::ParticleID is_lepton; std::merge(lhef::Electron.cbegin(), lhef::Electron.cend(), lhef::Muon.cbegin(), lhef::Muon.cend(), std::back_inserter(is_lepton)); lhef::Particles leptons; lhef::Particle lep_anc; lhef::ParticleLines toplines; lhef::Particles daughters_of_top; int num_eve = 0; for ( ; !lhe.empty(); lhe = lhef::ParseEvent(&filename)) { ++num_eve; std::cout << "-- Event number: " << num_eve << '\n' << lhef::show(lhe) << '\n'; initstates = lhef::InitialStates(lhe); std::cout << "---- Initial-state particles:\n" << lhef::show(initstates) << '\n'; finalstates = lhef::FinalStates(lhe); std::cout << "---- Final-state particles:\n" << lhef::show(finalstates) << '\n'; leptons = lhef::ParticlesOf(is_lepton, lhe); std::cout << "---- Leptons:\n" << lhef::show(leptons) << '\n'; lep_anc = lhef::Ancestor(leptons.front(), lhe); std::cout << "---- Ancestor of one lepton:\n" << lhef::show(lep_anc) << '\n'; toplines = lhef::ParticleLinesOf(lhef::Top, lhe); std::cout << "---- Lines of top quarks:\n"; std::copy(toplines.cbegin(), toplines.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; daughters_of_top = lhef::FinalDaughters(toplines.front(), lhe); std::cout << "---- Daughters of one top quark:\n" << lhef::show(daughters_of_top) << '\n'; } std::cout << "-- " << num_eve << " events parsed.\n"; filename.close(); }
#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include "lhef.h" int main(int argc, char* argv[]) { if (argc != 2) { std::cout << "Usage: test_parse input\n" << " - input: Input file in " << "Les Houches Event File format\n"; return 1; } std::ifstream filename(argv[1]); if (!filename) { std::cerr << "-- Cannot open input file \"" << argv[1] << "\".\n"; return 1; } else { std::cout << "-- Reading \"" << argv[1] << "\" ...\n"; } lhef::Event lhe = lhef::ParseEvent(&filename); lhef::Particles initstates; lhef::Particles finalstates; lhef::ParticleID is_lepton; std::merge(lhef::Electron.cbegin(), lhef::Electron.cend(), lhef::Muon.cbegin(), lhef::Muon.cend(), std::back_inserter(is_lepton)); lhef::Particles leptons; lhef::Particle lep_anc; lhef::ParticleLines toplines; lhef::Particles daughters_of_top; int num_eve = 0; for ( ; !lhe.empty(); lhe = lhef::ParseEvent(&filename)) { ++num_eve; std::cout << "-- Event number: " << num_eve << '\n' << lhef::show(lhe) << '\n'; initstates = lhef::InitialStates(lhe); std::cout << "---- Initial-state particles:\n" << lhef::show(initstates) << '\n'; finalstates = lhef::FinalStates(lhe); std::cout << "---- Final-state particles:\n" << lhef::show(finalstates) << '\n'; leptons = lhef::ParticlesOf(is_lepton, lhe); std::cout << "---- Leptons:\n" << lhef::show(leptons) << '\n'; lep_anc = lhef::Ancestor(leptons.front(), lhe); std::cout << "---- Ancestor of one lepton:\n" << lhef::show(lep_anc) << '\n'; toplines = lhef::ParticleLinesOf(lhef::Top, lhe); std::cout << "---- Lines of top quarks:\n"; std::copy(toplines.cbegin(), toplines.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; daughters_of_top = lhef::FinalDaughters(toplines.front(), lhe); std::cout << "---- Daughters of one top quark:\n" << lhef::show(daughters_of_top) << '\n'; } std::cout << "-- " << num_eve << " events parsed.\n"; filename.close(); }
Fix test_parse.cc
Fix test_parse.cc
C++
bsd-3-clause
cbpark/CLHEF,cbpark/CLHEF
eba33db61a3fca15d623ff9cd8e7681cbfecf5ea
src/textcat++.hxx
src/textcat++.hxx
#ifndef TEXTCAT_HXX #define TEXTCAT_HXX #include <iterator> #include <iostream> #include <fstream> #include <tuple> #include <functional> #include <unordered_map> #include <vector> #include <algorithm> #include <limits> extern "C" { //:TODO: adjust configure #include <unicode/uchar.h> } #include "utf_codecs.hxx" #include "ranks.hxx" /* various data structures : ngrams : compact array of bitfields :TODO: make a generic reusable template: how to specialize std::rotate for it ? hash_table of ngrams and counts vector of ngrams and counts vector or ngrams and ranks : fingerprints vector of fingerprints and names : smart pointers ? iterators ? how to avoid copy ? ony one needed per app, maybe no copyes at all */ namespace textcat { char32_t constexpr placeholder_char= U'_'; // char32_t to_normal(char32_t c) { return u_isalpha(c) ? u_toupper(c) : placeholder_char; } //u_isUAlphabetic char32_t to_normal(char32_t c) { return (u_isspace(c) || u_isdigit(c)) ? placeholder_char : c; } //u_isUAlphabetic // storing ngrams for 1 <= n <= N template<unsigned char N> struct ngram { static unsigned char const size=N; ngram(char32_t init=0):data(static_cast<data_type>(init)){} char32_t operator()(char32_t to_push) { char32_t const to_pop( data >> (21*(N-1))); data= ((data << 21) & ( (static_cast<data_type>(1)<< (21*N))-1)) | static_cast<data_type>(to_push); return to_pop; } std::size_t hash() const { return static_cast<std::size_t>(data) ^ static_cast<std::size_t>(data>>(8*sizeof(std::size_t))); } template<unsigned char NN> friend bool operator<(ngram<NN> const& n1, ngram<NN> const& n2); template<unsigned char NN> friend bool operator==(ngram<NN> const& n1, ngram<NN> const& n2); template<typename Os, unsigned char NN> friend Os& operator<<(Os& os, ngram<NN> const& n); typedef __int128 data_type; data_type data; }; template<unsigned char N> bool operator<(ngram<N> const& n1, ngram<N> const& n2) { return n1.data < n2.data; } template<unsigned char N> bool operator==(ngram<N> const& n1, ngram<N> const& n2) { return n1.data == n2.data; } template<typename Os, unsigned char N> Os& operator<<(Os& os, ngram<N> const& n) { for(unsigned char i(0); i != N; ++i){ char32_t const c (static_cast<char32_t>(n.data >> 21*i) & ((1 << 21)-1)); if(c) { to_utf8(c, os);} else { os << '\0'; break; } } return os; } } namespace std { template<unsigned char N> struct hash<textcat::ngram<N> > { std::size_t operator()(textcat::ngram<N> const& ng) const { return ng.hash() ; } }; } namespace textcat { template<unsigned char N, typename SizeType= std::size_t> struct counts { typedef ngram<N> ngram_type; typedef SizeType size_type; typedef std::unordered_map<ngram_type, size_type> map_type; typedef typename std::pair<ngram_type, size_type> value_type; typedef std::vector<value_type> fingerprint_type; }; template<unsigned char N, typename In> typename counts<N>::map_type make_counts(In b, In e, std::size_t max_ngrams){ typename counts<N>::map_type counters; typedef typename counts<N>::ngram_type ngram_type; ngram_type ng; std::size_t n; bool was_invalid, invalid; for( n=0, ng(placeholder_char), was_invalid=true; (b != e) && (n != max_ngrams) ; was_invalid= invalid) { char32_t const new_codepoint(to_normal(from_utf8(b, e))); invalid= (new_codepoint == placeholder_char); if(! (invalid && was_invalid)) { ng(new_codepoint); ++counters[ng]; ++n; } if(invalid && !was_invalid) { ng= ngram_type(placeholder_char);} } return counters; } template<unsigned char N> typename counts<N>::fingerprint_type to_vector(typename counts<N>::map_type const& c, std::size_t maxngrams){ typedef typename counts<N>::value_type value_type; typename counts<N>::fingerprint_type result(c.begin(), c.end()); typedef typename value_type::second_type size_type; if(maxngrams > result.size()) { maxngrams= result.size(); } std::partial_sort(result.begin(), result.begin()+maxngrams, result.end() ,[](value_type const& v1, value_type const& v2){ return v1.second > v2.second; }); result.resize(maxngrams); return result; } template<typename InOut> InOut count_to_rank(InOut b, InOut e){ if(b!= e){ for(typename std::iterator_traits<InOut>::value_type::second_type last((*b).second), rnk(0) ; b != e; ++b) { if((*b).second != last){ last= (*b).second; ++rnk;} (*b).second= rnk; } } return b; } // Input Stream data is supposed to be already sorted // imbue maxngrams and >> ? template<unsigned char N, typename Is> typename counts<N>::fingerprint_type read(Is& is, std::size_t maxngrams= std::numeric_limits<std::size_t>::max()) { typename counts<N>::fingerprint_type result; std::string tmp; std::size_t count; while(std::getline(is, tmp, '\t') && (maxngrams--)){ is >> count; if(!is) { break; } ngram<N> ng; result.push_back(std::make_pair(std::for_each(tmp.begin(), tmp.end(), ng) , count)); } count_to_rank(result.begin(), result.end()); return result; } template<unsigned char N, typename Os> Os& operator<<(Os& os, typename counts<N>::fingerprint_type fp) { std::for_each(fp.begin(), fp.end() , [&os](typename counts<N>::value_type const& v) {os << v.first << '\t' << v.second << '\n';}); // for(typename counts<N>::fingerprint_type::const_iterator it(fp.begin()); it != fp.end(); ++it){ // os<<(*it).first << '\t' << (*it).second << '\n'; // } return os; } struct scorer { scorer(float ratio=1.03, std::size_t oop= 400 , std::size_t max_s= std::numeric_limits<std::size_t>::max() ): out_of_place(oop), max_score(max_s) , cutoff(max_s), treshold_ratio(ratio){} template<unsigned char N> std::size_t operator()(typename counts<N>::fingerprint_type const& f1 , typename counts<N>::fingerprint_type const& f2){ typedef typename counts<N>::fingerprint_type fp_type; std::size_t result(0); for(typename fp_type::const_iterator it1(f1.begin()), it2(f2.begin()) ; (it1 != f1.end()) && (it2 != f2.end()) && (result != max_score) ; ) { if( (*it1).first < (*it2).first) { ++it1; } else { result += ((*it1).first == (*it2).first) ? std::abs((*(it1++)).second - (*it2).second) : out_of_place; if(result > cutoff) { result= max_score; } ++it2; } } cutoff= std::min(cutoff, static_cast<std::size_t>(result* treshold_ratio));// check no overflow return result; } std::size_t const out_of_place, max_score; std::size_t cutoff; float const treshold_ratio; }; template<unsigned char N> struct classifier { typedef typename counts<N>::fingerprint_type fingerprint_type; typedef std::tuple<std::string, fingerprint_type> language_type; std::vector<language_type> languages; // for now, taking iterators to std::pairs of languagename, filename template<typename In> classifier(In b, In e) { std::transform(b, e, std::back_inserter(languages) , [](typename std::iterator_traits<In>::value_type const& v) -> language_type { std::ifstream ifs(std::get<1>(v)); return language_type(std::get<0>(v) , read<N>(ifs)); }); } template<typename In, typename Out> Out operator()(In b, In e, Out o , std::size_t max_read=std::numeric_limits<std::size_t>::max()) const { float const treshold_ratio (1.03); //:TODO: LRU caching of detected languages typename counts<N>::fingerprint_type fp(to_vector<N>(make_counts<N>(b, e, max_read), max_read)); count_to_rank(fp.begin(), fp.end()); typename counts<N>::fingerprint_type const& cfp(fp); std::vector<std::size_t> scores(languages.size()), idx(languages.size()); scorer s(treshold_ratio); std::transform(languages.begin(), languages.end(), scores.begin() ,[&s, &fp](language_type const& lang){ return s.operator()<N>(fp, std::get<1>(lang));}); indexes(scores.begin(), scores.end(), idx.begin()); std::size_t const best(scores[idx.front()]); for(auto it(idx.begin()); (it != idx.end()) || (scores[*it] <= best*treshold_ratio); ++it, ++o) { *o= std::get<0>(languages[*it]); } return o; } }; } #endif
#ifndef TEXTCAT_HXX #define TEXTCAT_HXX #include <iterator> #include <iostream> #include <fstream> #include <tuple> #include <functional> #include <unordered_map> #include <vector> #include <algorithm> #include <limits> extern "C" { //:TODO: adjust configure #include <unicode/uchar.h> } #include "utf_codecs.hxx" #include "ranks.hxx" /* various data structures : ngrams : compact array of bitfields :TODO: make a generic reusable template: how to specialize std::rotate for it ? hash_table of ngrams and counts vector of ngrams and counts vector or ngrams and ranks : fingerprints vector of fingerprints and names : smart pointers ? iterators ? how to avoid copy ? ony one needed per app, maybe no copyes at all */ namespace textcat { char32_t constexpr placeholder_char= U'_'; // char32_t to_normal(char32_t c) { return u_isalpha(c) ? u_toupper(c) : placeholder_char; } //u_isUAlphabetic char32_t to_normal(char32_t c) { return (u_isspace(c) || u_isdigit(c)) ? placeholder_char : c; } //u_isUAlphabetic // storing ngrams for 1 <= n <= N template<unsigned char N> struct ngram { static unsigned char const size=N; ngram(char32_t init=0):data(static_cast<data_type>(init)){} char32_t operator()(char32_t to_push) { char32_t const to_pop( data >> (21*(N-1))); data= ((data << 21) & ( (static_cast<data_type>(1)<< (21*N))-1)) | static_cast<data_type>(to_push); return to_pop; } std::size_t hash() const { return static_cast<std::size_t>(data) ^ static_cast<std::size_t>(data>>(8*sizeof(std::size_t))); } template<unsigned char NN> friend bool operator<(ngram<NN> const& n1, ngram<NN> const& n2); template<unsigned char NN> friend bool operator==(ngram<NN> const& n1, ngram<NN> const& n2); template<typename Os, unsigned char NN> friend Os& operator<<(Os& os, ngram<NN> const& n); typedef __int128 data_type; data_type data; }; template<unsigned char N> bool operator<(ngram<N> const& n1, ngram<N> const& n2) { return n1.data < n2.data; } template<unsigned char N> bool operator==(ngram<N> const& n1, ngram<N> const& n2) { return n1.data == n2.data; } template<typename Os, unsigned char N> Os& operator<<(Os& os, ngram<N> const& n) { for(unsigned char i(0); i != N; ++i){ char32_t const c (static_cast<char32_t>(n.data >> 21*i) & ((1 << 21)-1)); if(c) { to_utf8(c, os);} else { os << '\0'; break; } } return os; } } namespace std { template<unsigned char N> struct hash<textcat::ngram<N> > { std::size_t operator()(textcat::ngram<N> const& ng) const { return ng.hash() ; } }; } namespace textcat { template<unsigned char N, typename SizeType= std::size_t> struct counts { typedef ngram<N> ngram_type; typedef SizeType size_type; typedef std::unordered_map<ngram_type, size_type> map_type; typedef typename std::pair<ngram_type, size_type> value_type; typedef std::vector<value_type> fingerprint_type; }; template<unsigned char N, typename In> typename counts<N>::map_type make_counts(In b, In e, std::size_t max_ngrams){ typename counts<N>::map_type counters; typedef typename counts<N>::ngram_type ngram_type; ngram_type ng; std::size_t n; bool was_invalid, invalid; for( n=0, ng(placeholder_char), was_invalid=true; (b != e) && (n != max_ngrams) ; was_invalid= invalid) { char32_t const new_codepoint(to_normal(from_utf8(b, e))); invalid= (new_codepoint == placeholder_char); if(! (invalid && was_invalid)) { ng(new_codepoint); ++counters[ng]; ++n; } if(invalid && !was_invalid) { ng= ngram_type(placeholder_char);} } return counters; } template<unsigned char N> typename counts<N>::fingerprint_type to_vector(typename counts<N>::map_type const& c, std::size_t maxngrams){ typedef typename counts<N>::value_type value_type; typename counts<N>::fingerprint_type result(c.begin(), c.end()); if(maxngrams > result.size()) { maxngrams= result.size(); } std::partial_sort(result.begin(), result.begin()+maxngrams, result.end() ,[](value_type const& v1, value_type const& v2){ return v1.second > v2.second; }); result.resize(maxngrams); return result; } template<typename InOut> InOut count_to_rank(InOut b, InOut e){ if(b!= e){ for(typename std::iterator_traits<InOut>::value_type::second_type last((*b).second), rnk(0) ; b != e; ++b) { if((*b).second != last){ last= (*b).second; ++rnk;} (*b).second= rnk; } } return b; } // Input Stream data is supposed to be already sorted // imbue maxngrams and >> ? template<unsigned char N, typename Is> typename counts<N>::fingerprint_type read(Is& is, std::size_t maxngrams= std::numeric_limits<std::size_t>::max()) { typename counts<N>::fingerprint_type result; std::string tmp; std::size_t count; while(std::getline(is, tmp, '\t') && (maxngrams--)){ is >> count; if(!is) { break; } ngram<N> ng; result.push_back(std::make_pair(std::for_each(tmp.begin(), tmp.end(), ng) , count)); } count_to_rank(result.begin(), result.end()); return result; } template<unsigned char N, typename Os> Os& operator<<(Os& os, typename counts<N>::fingerprint_type fp) { std::for_each(fp.begin(), fp.end() , [&os](typename counts<N>::value_type const& v) {os << v.first << '\t' << v.second << '\n';}); return os; } struct scorer { scorer(float ratio=1.03, std::size_t oop= 400 , std::size_t max_s= std::numeric_limits<std::size_t>::max()): out_of_place(oop), max_score(max_s) , cutoff(max_s), treshold_ratio(ratio){} template<unsigned char N> std::size_t operator()(typename counts<N>::fingerprint_type const& f1 , typename counts<N>::fingerprint_type const& f2){ std::size_t result(0); for(auto it1(f1.begin()), it2(f2.begin()) ; (it1 != f1.end()) && (it2 != f2.end()) && (result != max_score) ; ) { if( (*it1).first < (*it2).first) { ++it1; } else { result += ((*it1).first == (*it2).first) ? std::abs((*(it1++)).second - (*it2).second) : out_of_place; if(result > cutoff) { result= max_score; } ++it2; } } cutoff= std::min(cutoff, static_cast<std::size_t>(result * treshold_ratio));// check no overflow return result; } std::size_t const out_of_place, max_score; std::size_t cutoff; float const treshold_ratio; }; template<unsigned char N> struct classifier { typedef typename counts<N>::fingerprint_type fingerprint_type; typedef std::tuple<std::string, fingerprint_type> language_type; std::vector<language_type> languages; // for now, taking iterators to std::pairs of languagename, filename template<typename In> classifier(In b, In e) { std::transform(b, e, std::back_inserter(languages) , [](typename std::iterator_traits<In>::value_type const& v) -> language_type { std::ifstream ifs(std::get<1>(v)); return language_type(std::get<0>(v) , read<N>(ifs)); }); } template<typename In, typename Out> Out operator()(In b, In e, Out o , std::size_t max_read=std::numeric_limits<std::size_t>::max()) const { float const treshold_ratio (1.03); //:TODO: LRU caching of detected languages typename counts<N>::fingerprint_type fp(to_vector<N>(make_counts<N>(b, e, max_read), max_read)); count_to_rank(fp.begin(), fp.end()); std::vector<std::size_t> scores(languages.size()), idx(languages.size()); scorer s(treshold_ratio); std::transform(languages.begin(), languages.end(), scores.begin() ,[&s, &fp](language_type const& lang){ return s.operator()<N>(fp, std::get<1>(lang));}); indexes(scores.begin(), scores.end(), idx.begin()); std::size_t const best(scores[idx.front()]); for(auto it(idx.begin()); (it != idx.end()) || (scores[*it] <= best*treshold_ratio); ++it, ++o) { *o= std::get<0>(languages[*it]); } return o; } }; } #endif
remove dead code
remove dead code
C++
bsd-3-clause
scientific-coder/libtextcat,scientific-coder/libtextcat,scientific-coder/libtextcat
457e8b7046a0ab6fec1498e1e6026721bf3a7f3d
nanocv/func/function_rosenbrock.cpp
nanocv/func/function_rosenbrock.cpp
#include "function_rosenbrock.h" #include "math/numeric.hpp" #include "text/to_string.hpp" namespace ncv { struct function_rosenbrock_t : public function_t { explicit function_rosenbrock_t(const size_t dims) : m_dims(dims) { } virtual string_t name() const override { return "Rosenbrock" + text::to_string(m_dims) + "D"; } virtual opt_problem_t problem() const override { const opt_opsize_t fn_size = [=] () { return m_dims; }; const opt_opfval_t fn_fval = [=] (const vector_t& x) { scalar_t fx = 0; for (size_t i = 0; i + 1 < m_dims; i ++) { fx += 100.0 * math::square(x(i + 1) - x(i) * x(i)) + math::square(x(i) - 1); } return fx; }; const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx) { gx.resize(m_dims); gx.setZero(); for (size_t i = 0; i + 1 < m_dims; i ++) { gx(i) += 2.0 * (x(i) - 1); gx(i) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i)) * (- 2.0 * x(i)); gx(i + 1) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i)); } return fn_fval(x); }; return opt_problem_t(fn_size, fn_fval, fn_grad); } virtual bool is_valid(const vector_t&) const override { return true; } virtual bool is_minima(const vector_t& x, const scalar_t epsilon) const { { const vector_t xmin = vector_t::Ones(m_dims); if (distance(x, xmin) < epsilon) { return true; } } if (m_dims >= 4 && m_dims <= 7) { vector_t xmin = vector_t::Ones(m_dims); xmin(0) = -1; if (distance(x, xmin) < epsilon) { return true; } } return false; } size_t m_dims; }; functions_t make_rosenbrock_funcs(size_t max_dims) { functions_t functions; for (size_t dims = 2; dims <= max_dims; dims ++) { functions.push_back(std::make_shared<function_rosenbrock_t>(dims)); } return functions; } }
#include "function_rosenbrock.h" #include "math/numeric.hpp" #include "text/to_string.hpp" namespace ncv { struct function_rosenbrock_t : public function_t { explicit function_rosenbrock_t(const size_t dims) : m_dims(dims) { } virtual string_t name() const override { return "Rosenbrock" + text::to_string(m_dims) + "D"; } virtual opt_problem_t problem() const override { const opt_opsize_t fn_size = [=] () { return m_dims; }; const opt_opfval_t fn_fval = [=] (const vector_t& x) { scalar_t fx = 0; for (size_t i = 0; i + 1 < m_dims; i ++) { fx += 100.0 * math::square(x(i + 1) - x(i) * x(i)) + math::square(x(i) - 1); } return fx; }; const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx) { gx.resize(m_dims); gx.setZero(); for (size_t i = 0; i + 1 < m_dims; i ++) { gx(i) += 2.0 * (x(i) - 1); gx(i) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i)) * (- 2.0 * x(i)); gx(i + 1) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i)); } return fn_fval(x); }; return opt_problem_t(fn_size, fn_fval, fn_grad); } virtual bool is_valid(const vector_t&) const override { return true; } virtual bool is_minima(const vector_t& x, const scalar_t epsilon) const override { { const vector_t xmin = vector_t::Ones(m_dims); if (distance(x, xmin) < epsilon) { return true; } } if (m_dims >= 4 && m_dims <= 7) { vector_t xmin = vector_t::Ones(m_dims); xmin(0) = -1; if (distance(x, xmin) < epsilon) { return true; } } return false; } size_t m_dims; }; functions_t make_rosenbrock_funcs(size_t max_dims) { functions_t functions; for (size_t dims = 2; dims <= max_dims; dims ++) { functions.push_back(std::make_shared<function_rosenbrock_t>(dims)); } return functions; } }
fix warning
fix warning
C++
mit
accosmin/nanocv,accosmin/nano,accosmin/nano,accosmin/nanocv,accosmin/nano,accosmin/nanocv
2e62c62b1bd4d25a6fc55b27d71805ca9e2e4aea
telepathy-handler-application.cpp
telepathy-handler-application.cpp
/* * Copyright (C) 2011 Daniele E. Domenichelli <[email protected]> * Copyright (C) 1999 Preston Brown <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "telepathy-handler-application.h" #include <QTimer> #include <KCmdLineArgs> #include <KDebug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Debug> extern bool kde_kdebug_enable_dbus_interface; namespace KTelepathy { class TelepathyHandlerApplication::Private { public: Private(TelepathyHandlerApplication *q); ~Private(); void _k_onInitialTimeout(); void _k_onTimeout(); static KComponentData initHack(); void init(int initialTimeout, int timeout); TelepathyHandlerApplication *q; static bool s_persist; static bool s_debug; int initialTimeout; int timeout; QTimer *timer; bool firstJobStarted; QAtomicInt jobCount; }; TelepathyHandlerApplication::Private::Private(TelepathyHandlerApplication *q) : q(q), firstJobStarted(false), jobCount(0) { } TelepathyHandlerApplication::Private::~Private() { } void TelepathyHandlerApplication::Private::_k_onInitialTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "No job received. Exiting"; QCoreApplication::quit(); } } void TelepathyHandlerApplication::Private::_k_onTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "Timeout. Exiting"; QCoreApplication::quit(); } } // this gets called before even entering QApplication::QApplication() KComponentData TelepathyHandlerApplication::Private::initHack() { KComponentData cData(KCmdLineArgs::aboutData()); KCmdLineOptions handler_options; handler_options.add("persist", ki18n("Persistent mode (do not exit on timeout)")); handler_options.add("debug", ki18n("Show Telepathy debugging information")); KCmdLineArgs::addCmdLineOptions(handler_options, ki18n("KDE Telepathy"), "kde-telepathy", "kde"); KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde-telepathy"); Private::s_persist = args->isSet("persist"); Private::s_debug = args->isSet("debug"); return cData; } void TelepathyHandlerApplication::Private::init(int initialTimeout, int timeout) { this->initialTimeout = timeout; this->timeout = timeout; // If timeout < 0 we let the application exit when the last window is closed, // Otherwise we handle it with the timeout if (timeout >= 0) { q->setQuitOnLastWindowClosed(false); } Tp::registerTypes(); //Enable telepathy-Qt4 debug Tp::enableDebug(s_debug); Tp::enableWarnings(true); if (s_debug) { kde_kdebug_enable_dbus_interface = true; } if (!Private::s_persist) { timer = new QTimer(q); if (initialTimeout >= 0) { q->connect(timer, SIGNAL(timeout()), q, SLOT(_k_onInitialTimeout())); timer->start(initialTimeout); } } } bool TelepathyHandlerApplication::Private::s_persist = false; bool TelepathyHandlerApplication::Private::s_debug = false; TelepathyHandlerApplication::TelepathyHandlerApplication(bool GUIenabled, int initialTimeout, int timeout) : KApplication(GUIenabled, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::TelepathyHandlerApplication(Display *display, Qt::HANDLE visual, Qt::HANDLE colormap, int initialTimeout, int timeout) : KApplication(display, visual, colormap, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::~TelepathyHandlerApplication() { delete d; } int TelepathyHandlerApplication::newJob() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; int ret = d->jobCount.fetchAndAddOrdered(1); if (!Private::s_persist) { if (d->timer->isActive()) { d->timer->stop(); } if (!d->firstJobStarted) { if (d->initialTimeout) { disconnect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onInitialTimeout())); } if (d->timeout >= 0) { connect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onTimeout())); } d->firstJobStarted = true; } } return ret; } void TelepathyHandlerApplication::jobFinished() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; if (d->jobCount.fetchAndAddOrdered(-1) <= 1) { if (!Private::s_persist && d->timeout >= 0) { kDebug() << "No other jobs at the moment. Starting timer."; d->timer->start(d->timeout); } } } } // namespace KTelepathy #include "telepathy-handler-application.moc"
/* * Copyright (C) 2011 Daniele E. Domenichelli <[email protected]> * Copyright (C) 1999 Preston Brown <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "telepathy-handler-application.h" #include <QTimer> #include <KCmdLineArgs> #include <KDebug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Debug> extern bool kde_kdebug_enable_dbus_interface; namespace KTelepathy { class TelepathyHandlerApplication::Private { public: Private(TelepathyHandlerApplication *q); ~Private(); void _k_onInitialTimeout(); void _k_onTimeout(); static KComponentData initHack(); void init(int initialTimeout, int timeout); TelepathyHandlerApplication *q; static bool s_persist; static bool s_debug; int initialTimeout; int timeout; QTimer *timer; bool firstJobStarted; QAtomicInt jobCount; }; TelepathyHandlerApplication::Private::Private(TelepathyHandlerApplication *q) : q(q), firstJobStarted(false), jobCount(0) { } TelepathyHandlerApplication::Private::~Private() { } void TelepathyHandlerApplication::Private::_k_onInitialTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "No job received. Exiting"; QCoreApplication::quit(); } } void TelepathyHandlerApplication::Private::_k_onTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "Timeout. Exiting"; QCoreApplication::quit(); } } // this gets called before even entering QApplication::QApplication() KComponentData TelepathyHandlerApplication::Private::initHack() { KComponentData cData(KCmdLineArgs::aboutData()); KCmdLineOptions handler_options; handler_options.add("persist", ki18n("Persistent mode (do not exit on timeout)")); handler_options.add("debug", ki18n("Show Telepathy debugging information")); KCmdLineArgs::addCmdLineOptions(handler_options, ki18n("KDE Telepathy"), "kde-telepathy", "kde"); KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde-telepathy"); Private::s_persist = args->isSet("persist"); Private::s_debug = args->isSet("debug"); return cData; } void TelepathyHandlerApplication::Private::init(int initialTimeout, int timeout) { this->initialTimeout = initialTimeout; this->timeout = timeout; // If timeout < 0 we let the application exit when the last window is closed, // Otherwise we handle it with the timeout if (timeout >= 0) { q->setQuitOnLastWindowClosed(false); } Tp::registerTypes(); //Enable telepathy-Qt4 debug Tp::enableDebug(s_debug); Tp::enableWarnings(true); if (s_debug) { kde_kdebug_enable_dbus_interface = true; } if (!Private::s_persist) { timer = new QTimer(q); if (initialTimeout >= 0) { q->connect(timer, SIGNAL(timeout()), q, SLOT(_k_onInitialTimeout())); timer->start(initialTimeout); } } } bool TelepathyHandlerApplication::Private::s_persist = false; bool TelepathyHandlerApplication::Private::s_debug = false; TelepathyHandlerApplication::TelepathyHandlerApplication(bool GUIenabled, int initialTimeout, int timeout) : KApplication(GUIenabled, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::TelepathyHandlerApplication(Display *display, Qt::HANDLE visual, Qt::HANDLE colormap, int initialTimeout, int timeout) : KApplication(display, visual, colormap, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::~TelepathyHandlerApplication() { delete d; } int TelepathyHandlerApplication::newJob() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; int ret = d->jobCount.fetchAndAddOrdered(1); if (!Private::s_persist) { if (d->timer->isActive()) { d->timer->stop(); } if (!d->firstJobStarted) { if (d->initialTimeout) { disconnect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onInitialTimeout())); } if (d->timeout >= 0) { connect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onTimeout())); } d->firstJobStarted = true; } } return ret; } void TelepathyHandlerApplication::jobFinished() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; if (d->jobCount.fetchAndAddOrdered(-1) <= 1) { if (!Private::s_persist && d->timeout >= 0) { kDebug() << "No other jobs at the moment. Starting timer."; d->timer->start(d->timeout); } } } } // namespace KTelepathy #include "telepathy-handler-application.moc"
Initialize initialTimeout with the correct value
Initialize initialTimeout with the correct value
C++
lgpl-2.1
leonhandreke/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,KDE/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals
78d36c58f95ab26f99651c0815b15a5a22af6527
test/JsonTest/src/JsonTestApp.cpp
test/JsonTest/src/JsonTestApp.cpp
#include "cinder/app/AppBasic.h" #include "cinder/Json.h" #include "Resources.h" class JsonTestApp : public ci::app::AppBasic { public: void draw(); void mouseDown( ci::app::MouseEvent event ); void setup(); }; using namespace ci; using namespace ci::app; using namespace std; void JsonTestApp::draw() { gl::clear(); } void JsonTestApp::setup() { JsonTree value( "key", "value" ); console() << value << endl; JsonTree doc( loadResource( RES_JSON ) ); JsonTree musicLibrary( doc.getChild( "library" ) ); JsonTree owner = doc.getChild( "library.owner" ); for( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) { console() << "Node: " << item->getKey() << " Value: " << item->getValue<string>() << endl; } JsonTree tracks = doc.getChild( "library.albums[0].tracks" ); for( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) { console() << track->getChild( "id" ).getValue<int>() << endl; } for( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) { JsonTree track = * trackIt; console() << track["id"].getValue<int>() << endl; } JsonTree firstAlbum = doc.getChild( "library.albums[0]" ); for( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) { if ( !child->hasChildren() ) { console() << "Key: " << child->getKey() << " Value: " << child->getValue<string>() << endl; } } console() << doc.getChild( "library.owner" ); JsonTree &ownerCity = doc.getChild( "library.owner.city" ); string s = ownerCity.getPath(); console() << "Path: " << ownerCity.getPath() << "\n Value: " << ownerCity.getValue<string>() << endl; console() << doc; JsonTree firstTrackCopy = doc.getChild( "library.albums[0].tracks[0].title" ); firstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( "Replacement name" ) ); console() << doc.getChild( "library.albums[0].tracks[0]['title']" ) << endl; JsonTree &firstTrackRef = doc.getChild( "library.albums[0].tracks[2].title" ); console() << firstTrackRef.getPath() << endl; firstTrackRef = JsonTree( firstTrackRef.getKey(), string( "Replacement name" ) ); console() << doc.getChild( "library.albums[0].tracks[0].title" ) << endl; try { JsonTree invalid( "%%%%%%%%" ); } catch ( JsonTree::ExcJsonParserError ex ) { console() << ex.what() << endl; } JsonTree test32u( "uint32", uint32_t( math<uint64_t>::pow( 2, 32 ) ) - 1 ); console() << test32u; console() << test32u.getValue() << endl; JsonTree test32( "int32", int32_t( math<int32_t>::pow( 2, 32 ) ) - 1 ); console() << test32; console() << test32.getValue() << endl; JsonTree test64u( "uint64", uint64_t( math<uint64_t>::pow( 2, 64 ) ) - 1 ); console() << test64u; console() << test64u.getValue() << endl; JsonTree test64( "int64", int64_t( math<int64_t>::pow( 2, 64 ) ) - 1 ); console() << test64; console() << test64.getValue() << endl; } void JsonTestApp::mouseDown( MouseEvent event ) { JsonTree doc; JsonTree library = JsonTree::makeObject( "library" ); JsonTree album = JsonTree::makeArray( "album" ); album.pushBack( JsonTree( "musician", string( "Sufjan Stevens" ) ) ); album.pushBack( JsonTree( "year", string( "2004" ) ) ); album.pushBack( JsonTree( "title", string( "Seven Swans" ) ) ); JsonTree tracks = JsonTree::makeArray( "tracks" ); for ( int32_t i = 0; i < 6; i ++ ) { JsonTree track; track.pushBack( JsonTree( "id", i + 1 ) ); JsonTree title; switch ( i ) { case 0: title = JsonTree( "title", "All the Trees of the Field Will Clap Their Hands" ); break; case 1: title = JsonTree( "title", "The Dress Looks Nice on You" ); break; case 2: title = JsonTree( "title", "In the Dev Hole's Territory" ); break; case 3: title = JsonTree( "title", "To Be a Clone With You" ); break; case 4: title = JsonTree( "title", "To Be Removed" ); break; case 5: title = JsonTree( "title", "To Be Removed" ); break; } track.pushBack( title ); tracks.pushBack( track ); } for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) { if ( trackIt->getChild( "id" ).getValue<int>() == 3 ) { JsonTree track; track.pushBack( JsonTree( "id", 3 ) ); track.pushBack( JsonTree( "title", "In the Devil's Territory" ) ); tracks.replaceChild( trackIt, track ); } } JsonTree track; track.pushBack( JsonTree( "id", 4 ) ); track.pushBack( JsonTree( "title", "To Be Alone With You" ) ); tracks.replaceChild( 3, track ); tracks.removeChild( 4 ); for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) { if ( trackIt->getChild( "id" ).getValue<int>() == 6 ) { trackIt = tracks.removeChild( trackIt ); } else { ++trackIt; } } album.pushBack( tracks ); library.pushBack( album ); doc.pushBack( library ); console() << doc; doc.write( writeFile( getDocumentsDirectory() + "testoutput.json" ), JsonTree::WriteOptions() ); doc.write( writeFile( getDocumentsDirectory() + "testoutput_fast.json" ), JsonTree::WriteOptions().indented( false ) ); } CINDER_APP_BASIC( JsonTestApp, RendererGl )
#include "cinder/app/AppBasic.h" #include "cinder/Json.h" #include "Resources.h" class JsonTestApp : public ci::app::AppBasic { public: void draw(); void mouseDown( ci::app::MouseEvent event ); void setup(); }; using namespace ci; using namespace ci::app; using namespace std; void JsonTestApp::draw() { gl::clear(); } void JsonTestApp::setup() { JsonTree value( "key", "value" ); console() << value << endl; JsonTree doc( loadResource( RES_JSON ) ); JsonTree musicLibrary( doc.getChild( "library" ) ); JsonTree owner = doc.getChild( "library.owner" ); for( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) { console() << "Node: " << item->getKey() << " Value: " << item->getValue<string>() << endl; } JsonTree tracks = doc.getChild( "library.albums[0].tracks" ); for( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) { console() << track->getChild( "id" ).getValue<int>() << endl; } for( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) { JsonTree track = * trackIt; console() << track["id"].getValue<int>() << endl; } JsonTree firstAlbum = doc.getChild( "library.albums[0]" ); for( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) { if ( !child->hasChildren() ) { console() << "Key: " << child->getKey() << " Value: " << child->getValue<string>() << endl; } } console() << doc.getChild( "library.owner" ); JsonTree &ownerCity = doc.getChild( "library.owner.city" ); string s = ownerCity.getPath(); console() << "Path: " << ownerCity.getPath() << "\n Value: " << ownerCity.getValue<string>() << endl; console() << doc; JsonTree firstTrackCopy = doc.getChild( "library.albums[0].tracks[0].title" ); firstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( "Replacement name" ) ); console() << doc.getChild( "library.albums[0].tracks[0]['title']" ) << endl; JsonTree &firstTrackRef = doc.getChild( "library.albums[0].tracks[2].title" ); console() << firstTrackRef.getPath() << endl; firstTrackRef = JsonTree( firstTrackRef.getKey(), string( "Replacement name" ) ); console() << doc.getChild( "library.albums[0].tracks[0].title" ) << endl; try { JsonTree invalid( "%%%%%%%%" ); } catch ( JsonTree::ExcJsonParserError ex ) { console() << ex.what() << endl; } JsonTree test32u( "uint32", uint32_t( math<uint64_t>::pow( 2, 32 ) ) - 1 ); console() << test32u; console() << test32u.getValue() << endl; JsonTree test32( "int32", int32_t( math<int32_t>::pow( 2, 32 ) ) - 1 ); console() << test32; console() << test32.getValue() << endl; JsonTree test64u( "uint64", uint64_t( math<uint64_t>::pow( 2, 64 ) ) - 1 ); console() << test64u; console() << test64u.getValue() << endl; JsonTree test64( "int64", int64_t( math<int64_t>::pow( 2, 64 ) ) - 1 ); console() << test64; console() << test64.getValue() << endl; } void JsonTestApp::mouseDown( MouseEvent event ) { JsonTree doc; JsonTree library = JsonTree::makeObject( "library" ); JsonTree album = JsonTree::makeArray( "album" ); album.pushBack( JsonTree( "musician", string( "Sufjan Stevens" ) ) ); album.pushBack( JsonTree( "year", string( "2004" ) ) ); album.pushBack( JsonTree( "title", string( "Seven Swans" ) ) ); JsonTree tracks = JsonTree::makeArray( "tracks" ); for ( int32_t i = 0; i < 6; i ++ ) { JsonTree track; track.pushBack( JsonTree( "id", i + 1 ) ); JsonTree title; switch ( i ) { case 0: title = JsonTree( "title", "All the Trees of the Field Will Clap Their Hands" ); break; case 1: title = JsonTree( "title", "The Dress Looks Nice on You" ); break; case 2: title = JsonTree( "title", "In the Dev Hole's Territory" ); break; case 3: title = JsonTree( "title", "To Be a Clone With You" ); break; case 4: title = JsonTree( "title", "To Be Removed" ); break; case 5: title = JsonTree( "title", "To Be Removed" ); break; } track.pushBack( title ); tracks.pushBack( track ); } for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) { if ( trackIt->getChild( "id" ).getValue<int>() == 3 ) { JsonTree track; track.pushBack( JsonTree( "id", 3 ) ); track.pushBack( JsonTree( "title", "In the Devil's Territory" ) ); tracks.replaceChild( trackIt, track ); } } JsonTree track; track.pushBack( JsonTree( "id", 4 ) ); track.pushBack( JsonTree( "title", "To Be Alone With You" ) ); tracks.replaceChild( 3, track ); tracks.removeChild( 4 ); for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) { if ( trackIt->getChild( "id" ).getValue<int>() == 6 ) { trackIt = tracks.removeChild( trackIt ); } else { ++trackIt; } } album.pushBack( tracks ); library.pushBack( album ); doc.pushBack( library ); console() << doc; doc.write( writeFile( getDocumentsDirectory() / "testoutput.json" ), JsonTree::WriteOptions() ); doc.write( writeFile( getDocumentsDirectory() / "testoutput_fast.json" ), JsonTree::WriteOptions().indented( false ) ); } CINDER_APP_BASIC( JsonTestApp, RendererGl )
use operator/= for appending file name
JsonTest: use operator/= for appending file name
C++
bsd-2-clause
sosolimited/Cinder,morbozoo/sonyHeadphones,sosolimited/Cinder,sosolimited/Cinder,2666hz/Cinder,morbozoo/sonyHeadphones,2666hz/Cinder,morbozoo/sonyHeadphones,2666hz/Cinder,sosolimited/Cinder,2666hz/Cinder,morbozoo/sonyHeadphones
1747fe2156e99b9509da6b2c2d344c55b6d5daad
src/tiltshift.cpp
src/tiltshift.cpp
#include <iostream> #include <cmath> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; double start_focus = 20; int start_focus_slider = 20; int start_focus_slider_max = 100; double decay_strength = 100; int decay_strength_slider = 100; int decay_strength_slider_max = 100; double center_focus = 50; int center_focus_slider = 50; int center_focus_slider_max = 100; int hue_gain = 0; int hue_gain_slider = 0; int hue_gain_slider_max = 255; Mat image, temp_image, blurred_image; Mat func_image, compl_image; Mat m_image, m_bimage; Mat result; char TrackbarName[50]; void drawFuncImage() { uchar pixel_value; double x; double den = (decay_strength > 0 ? decay_strength/10 : 0.1); double func_val; for (int i = 0; i < func_image.rows; ++i) { x = (double) i*100.0 /func_image.rows; func_val = ( tanh( (x-start_focus)/den ) - tanh ( ( x-(2*center_focus-start_focus) )/den ) ) / 2; pixel_value = (uchar) (255*func_val); for (int j = 0; j < func_image.cols; ++j) { func_image.at<uchar>(i,j) = pixel_value; compl_image.at<uchar>(i,j) = 255 - pixel_value; } } imshow( "func_image", func_image); } void composeResult() { drawFuncImage(); Mat image_f, blurred_image_f; image.convertTo(image_f, CV_32F); blurred_image.convertTo(blurred_image_f, CV_32F); Mat func_image3, compl_image3; Mat t_func[] = { func_image, func_image, func_image}; Mat t_compl[] = {compl_image, compl_image, compl_image}; merge( t_func, 3, func_image3); merge(t_compl, 3, compl_image3); Mat func_image3_f, compl_image3_f; func_image3.convertTo(func_image3_f, CV_32F, 1.0/255.0); compl_image3.convertTo(compl_image3_f, CV_32F, 1.0/255.0); multiply(image_f, func_image3_f, m_image); multiply(blurred_image_f, compl_image3_f, m_bimage); Mat result_f; addWeighted(m_image, 1, m_bimage, 1, 0, result_f); result_f.convertTo(result, CV_8UC3); Mat result_hsv; Mat planes_hsv[3]; Mat hue_saturated; cvtColor(result, result_hsv, CV_BGR2HSV); split(result_hsv, planes_hsv); planes_hsv[1].convertTo(hue_saturated, -1, 1, hue_gain); hue_saturated.copyTo(planes_hsv[1]); merge(planes_hsv, 3, result_hsv); cvtColor(result_hsv, result, CV_HSV2BGR); imshow("result", result); } void on_trackbar_start_focus(int, void*) { if (start_focus_slider > center_focus_slider) { setTrackbarPos("Start", "func_image", center_focus_slider); start_focus = (double) center_focus_slider; } else if (2*center_focus_slider - start_focus_slider > 100) { setTrackbarPos("Start", "func_image", 2*center_focus_slider - 100); start_focus = 2*center_focus_slider - 100; } else { start_focus = (double) start_focus_slider; } start_focus = (double) start_focus_slider; composeResult(); } void on_trackbar_decay_strength(int, void*) { decay_strength = (double) decay_strength_slider; composeResult(); } void on_trackbar_center_focus(int, void*) { if ( center_focus_slider < start_focus_slider ) { setTrackbarPos("Center", "func_image", start_focus_slider); center_focus = (double) start_focus_slider; } else if (2*center_focus_slider - start_focus_slider > 100) { setTrackbarPos("Center", "func_image", (100 + start_focus_slider)/2); center_focus = (100 + start_focus_slider)/2; } else { center_focus = (double) center_focus_slider; } composeResult(); } void on_trackbar_hue_gain(int, void*) { hue_gain = hue_gain_slider; composeResult(); } int main(int argc, char** argv) { if (argc != 2) { cout << "usage: " << argv[0] << " <img1>" << endl; exit(1); } image = imread(argv[1]); temp_image = image.clone(); for (int i = 0; i < 100; ++i) { GaussianBlur(temp_image, blurred_image, Size(3, 3), 0, 0); temp_image = blurred_image.clone(); } func_image = Mat(image.rows, image.cols, CV_8UC1, Scalar(255)); compl_image = Mat(image.rows, image.cols, CV_8UC1, Scalar(255)); namedWindow( "func_image", WINDOW_NORMAL); namedWindow( "result", WINDOW_NORMAL); sprintf( TrackbarName, "Start" ); createTrackbar( TrackbarName, "func_image", &start_focus_slider, start_focus_slider_max, on_trackbar_start_focus ); on_trackbar_start_focus(start_focus_slider, 0 ); sprintf( TrackbarName, "Decay" ); createTrackbar( TrackbarName, "func_image", &decay_strength_slider, decay_strength_slider_max, on_trackbar_decay_strength ); on_trackbar_decay_strength(decay_strength_slider, 0); sprintf( TrackbarName, "Center" ); createTrackbar( TrackbarName, "func_image", &center_focus_slider, center_focus_slider_max, on_trackbar_center_focus ); on_trackbar_center_focus(center_focus_slider, 0); sprintf( TrackbarName, "Hue Gain" ); createTrackbar( TrackbarName, "func_image", &hue_gain_slider, hue_gain_slider_max, on_trackbar_hue_gain ); on_trackbar_hue_gain(hue_gain_slider, 0); waitKey(0); exit(0); }
#include <iostream> #include <cmath> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; double start_focus = 20; int start_focus_slider = 20; int start_focus_slider_max = 100; double decay_strength = 100; int decay_strength_slider = 100; int decay_strength_slider_max = 100; double center_focus = 50; int center_focus_slider = 50; int center_focus_slider_max = 100; int hue_gain = 0; int hue_gain_slider = 0; int hue_gain_slider_max = 255; Mat image, temp_image, blurred_image; Mat func_image, compl_image; Mat m_image, m_bimage; Mat result; char TrackbarName[50]; void drawFuncImage() { uchar pixel_value; double x; double den = (decay_strength > 0 ? decay_strength/10 : 0.1); double func_val; for (int i = 0; i < func_image.rows; ++i) { x = (double) i*100.0 /func_image.rows; func_val = ( tanh( (x-start_focus)/den ) - tanh ( ( x-(2*center_focus-start_focus) )/den ) ) / 2; pixel_value = (uchar) (255*func_val); for (int j = 0; j < func_image.cols; ++j) { func_image.at<uchar>(i,j) = pixel_value; compl_image.at<uchar>(i,j) = 255 - pixel_value; } } imshow( "func_image", func_image); } void composeResult() { drawFuncImage(); Mat image_f, blurred_image_f; image.convertTo(image_f, CV_32F); blurred_image.convertTo(blurred_image_f, CV_32F); Mat func_image3, compl_image3; Mat t_func[] = { func_image, func_image, func_image}; Mat t_compl[] = {compl_image, compl_image, compl_image}; merge( t_func, 3, func_image3); merge(t_compl, 3, compl_image3); Mat func_image3_f, compl_image3_f; func_image3.convertTo(func_image3_f, CV_32F, 1.0/255.0); compl_image3.convertTo(compl_image3_f, CV_32F, 1.0/255.0); multiply(image_f, func_image3_f, m_image); multiply(blurred_image_f, compl_image3_f, m_bimage); Mat result_f; addWeighted(m_image, 1, m_bimage, 1, 0, result_f); result_f.convertTo(result, CV_8UC3); Mat result_hsv; Mat planes_hsv[3]; Mat hue_saturated; cvtColor(result, result_hsv, CV_BGR2HSV); split(result_hsv, planes_hsv); planes_hsv[1].convertTo(hue_saturated, -1, 1, hue_gain); hue_saturated.copyTo(planes_hsv[1]); merge(planes_hsv, 3, result_hsv); cvtColor(result_hsv, result, CV_HSV2BGR); imshow("result", result); } void on_trackbar_start_focus(int, void*) { if (start_focus_slider > center_focus_slider) { setTrackbarPos("Start", "func_image", center_focus_slider); start_focus = (double) center_focus_slider; } else if (2*center_focus_slider - start_focus_slider > 100) { setTrackbarPos("Start", "func_image", 2*center_focus_slider - 100); start_focus = 2*center_focus_slider - 100; } else { start_focus = (double) start_focus_slider; } start_focus = (double) start_focus_slider; composeResult(); } void on_trackbar_decay_strength(int, void*) { decay_strength = (double) decay_strength_slider; composeResult(); } void on_trackbar_center_focus(int, void*) { if ( center_focus_slider < start_focus_slider ) { setTrackbarPos("Center", "func_image", start_focus_slider); center_focus = (double) start_focus_slider; } else if (2*center_focus_slider - start_focus_slider > 100) { setTrackbarPos("Center", "func_image", (100 + start_focus_slider)/2); center_focus = (100 + start_focus_slider)/2; } else { center_focus = (double) center_focus_slider; } composeResult(); } void on_trackbar_hue_gain(int, void*) { hue_gain = hue_gain_slider; composeResult(); } int main(int argc, char** argv) { if (argc != 2) { cout << "usage: " << argv[0] << " <img1>" << endl; exit(1); } image = imread(argv[1]); temp_image = image.clone(); for (int i = 0; i < 100; ++i) { GaussianBlur(temp_image, blurred_image, Size(3, 3), 0, 0); temp_image = blurred_image.clone(); } func_image = Mat(image.rows, image.cols, CV_8UC1, Scalar(255)); compl_image = Mat(image.rows, image.cols, CV_8UC1, Scalar(255)); namedWindow("func_image", WINDOW_NORMAL); namedWindow( "result", WINDOW_NORMAL); sprintf( TrackbarName, "Start" ); createTrackbar( TrackbarName, "func_image", &start_focus_slider, start_focus_slider_max, on_trackbar_start_focus ); on_trackbar_start_focus(start_focus_slider, 0 ); sprintf( TrackbarName, "Decay" ); createTrackbar( TrackbarName, "func_image", &decay_strength_slider, decay_strength_slider_max, on_trackbar_decay_strength ); on_trackbar_decay_strength(decay_strength_slider, 0); sprintf( TrackbarName, "Center" ); createTrackbar( TrackbarName, "func_image", &center_focus_slider, center_focus_slider_max, on_trackbar_center_focus ); on_trackbar_center_focus(center_focus_slider, 0); sprintf( TrackbarName, "Hue Gain" ); createTrackbar( TrackbarName, "func_image", &hue_gain_slider, hue_gain_slider_max, on_trackbar_hue_gain ); on_trackbar_hue_gain(hue_gain_slider, 0); waitKey(0); exit(0); }
remove unnecessary whitespace
remove unnecessary whitespace
C++
mit
cadubentzen/pdi-ufrn
339c91215f0bae4af44fe3124f41244541607a2b
src/declarative/qml/qmlrewrite.cpp
src/declarative/qml/qmlrewrite.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmlrewrite_p.h" QT_BEGIN_NAMESPACE namespace QmlRewrite { QString RewriteBinding::operator()(const QString &code) { Engine engine; NodePool pool(QString(), &engine); Lexer lexer(&engine); Parser parser(&engine); lexer.setCode(code, 0); parser.parseStatement(); return rewrite(code, 0, parser.statement()); } void RewriteBinding::accept(AST::Node *node) { AST::Node::acceptChild(node, this); } QString RewriteBinding::rewrite(QString code, unsigned position, AST::Statement *node) { TextWriter w; _writer = &w; _position = position; accept(node); unsigned startOfStatement = node->firstSourceLocation().begin() - _position; unsigned endOfStatement = node->lastSourceLocation().end() - _position; _writer->replace(startOfStatement, 0, QLatin1String("(function() { ")); _writer->replace(endOfStatement, 0, QLatin1String(" })")); w.write(&code); return code; } bool RewriteBinding::visit(AST::Block *ast) { for (AST::StatementList *it = ast->statements; it; it = it->next) { if (! it->next) { // we need to rewrite only the last statement of a block. accept(it->statement); } } return false; } bool RewriteBinding::visit(AST::ExpressionStatement *ast) { unsigned startOfExpressionStatement = ast->firstSourceLocation().begin() - _position; _writer->replace(startOfExpressionStatement, 0, QLatin1String("return ")); return false; } } // namespace QmlRewrite QT_END_NAMESPACE
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmlrewrite_p.h" #include <QtDeclarative/qfxglobal.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(rewriteDump, QML_REWRITE_DUMP); namespace QmlRewrite { QString RewriteBinding::operator()(const QString &code) { Engine engine; NodePool pool(QString(), &engine); Lexer lexer(&engine); Parser parser(&engine); lexer.setCode(code, 0); parser.parseStatement(); return rewrite(code, 0, parser.statement()); } void RewriteBinding::accept(AST::Node *node) { AST::Node::acceptChild(node, this); } QString RewriteBinding::rewrite(QString code, unsigned position, AST::Statement *node) { TextWriter w; _writer = &w; _position = position; accept(node); unsigned startOfStatement = node->firstSourceLocation().begin() - _position; unsigned endOfStatement = node->lastSourceLocation().end() - _position; _writer->replace(startOfStatement, 0, QLatin1String("(function() { ")); _writer->replace(endOfStatement, 0, QLatin1String(" })")); if (rewriteDump()) { qWarning() << "============================================================="; qWarning() << "Rewrote:"; qWarning() << qPrintable(code); } w.write(&code); if (rewriteDump()) { qWarning() << "To:"; qWarning() << qPrintable(code); qWarning() << "============================================================="; } return code; } bool RewriteBinding::visit(AST::Block *ast) { for (AST::StatementList *it = ast->statements; it; it = it->next) { if (! it->next) { // we need to rewrite only the last statement of a block. accept(it->statement); } } return false; } bool RewriteBinding::visit(AST::ExpressionStatement *ast) { unsigned startOfExpressionStatement = ast->firstSourceLocation().begin() - _position; _writer->replace(startOfExpressionStatement, 0, QLatin1String("return ")); return false; } } // namespace QmlRewrite QT_END_NAMESPACE
Add QML_REWRITE_DUMP env flag
Add QML_REWRITE_DUMP env flag
C++
lgpl-2.1
pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt
9ea2c3dfb1321c805007f7f33ed9de897e9c43ff
src/constant_mappings.cpp
src/constant_mappings.cpp
/* * D-Bus AT-SPI, Qt Adaptor * * Copyright 2008, 2009 Nokia. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <QtCore/QHash> #include <QAccessible> #include "constant_mappings.h" #define BITARRAY_SEQ_TERM 0xffffffff #define BITARRAY_SET(p, n) ( (p)[n>>5] |= (1<<(n&31)) ) #define BITARRAY_UNSET(p, n) ( (p)[n>>5] &= ~(1<<(n&31)) ) /*---------------------------------------------------------------------------*/ QHash <QAccessible::Role, QSpiRole> qSpiRoleMapping; static void initialize_role_mapping () { qSpiRoleMapping.insert (QAccessible::NoRole, ROLE_INVALID); qSpiRoleMapping.insert (QAccessible::TitleBar, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::MenuBar, ROLE_MENU_BAR); qSpiRoleMapping.insert (QAccessible::ScrollBar, ROLE_SCROLL_BAR); qSpiRoleMapping.insert (QAccessible::Grip, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Sound, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Cursor, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Caret, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::AlertMessage, ROLE_ALERT); qSpiRoleMapping.insert (QAccessible::Window, ROLE_WINDOW); qSpiRoleMapping.insert (QAccessible::Client, ROLE_FRAME); qSpiRoleMapping.insert (QAccessible::PopupMenu, ROLE_POPUP_MENU); qSpiRoleMapping.insert (QAccessible::MenuItem, ROLE_MENU_ITEM); qSpiRoleMapping.insert (QAccessible::ToolTip, ROLE_TOOL_TIP); qSpiRoleMapping.insert (QAccessible::Application, ROLE_APPLICATION); qSpiRoleMapping.insert (QAccessible::Document, ROLE_DOCUMENT_FRAME); qSpiRoleMapping.insert (QAccessible::Pane, ROLE_FRAME); qSpiRoleMapping.insert (QAccessible::Chart, ROLE_CHART); qSpiRoleMapping.insert (QAccessible::Dialog, ROLE_DIALOG); qSpiRoleMapping.insert (QAccessible::Border, ROLE_FRAME); qSpiRoleMapping.insert (QAccessible::Grouping, ROLE_PANEL); qSpiRoleMapping.insert (QAccessible::Separator, ROLE_SEPARATOR); qSpiRoleMapping.insert (QAccessible::ToolBar, ROLE_TOOL_BAR); qSpiRoleMapping.insert (QAccessible::StatusBar, ROLE_STATUS_BAR); qSpiRoleMapping.insert (QAccessible::Table, ROLE_TABLE); qSpiRoleMapping.insert (QAccessible::ColumnHeader, ROLE_TABLE_COLUMN_HEADER); qSpiRoleMapping.insert (QAccessible::RowHeader, ROLE_TABLE_ROW_HEADER); qSpiRoleMapping.insert (QAccessible::Column, ROLE_TABLE); qSpiRoleMapping.insert (QAccessible::Row, ROLE_TABLE); qSpiRoleMapping.insert (QAccessible::Cell, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Link, ROLE_LINK); qSpiRoleMapping.insert (QAccessible::HelpBalloon, ROLE_DIALOG); qSpiRoleMapping.insert (QAccessible::Assistant, ROLE_DIALOG); qSpiRoleMapping.insert (QAccessible::List, ROLE_LIST); qSpiRoleMapping.insert (QAccessible::ListItem, ROLE_LIST_ITEM); qSpiRoleMapping.insert (QAccessible::Tree, ROLE_TREE); qSpiRoleMapping.insert (QAccessible::TreeItem, ROLE_LIST_ITEM); qSpiRoleMapping.insert (QAccessible::PageTab, ROLE_PAGE_TAB); qSpiRoleMapping.insert (QAccessible::PropertyPage, ROLE_PANEL); qSpiRoleMapping.insert (QAccessible::Indicator, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Graphic, ROLE_IMAGE); qSpiRoleMapping.insert (QAccessible::StaticText, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::EditableText, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::PushButton, ROLE_PUSH_BUTTON); qSpiRoleMapping.insert (QAccessible::CheckBox, ROLE_CHECK_BOX); qSpiRoleMapping.insert (QAccessible::RadioButton, ROLE_RADIO_BUTTON); qSpiRoleMapping.insert (QAccessible::ComboBox, ROLE_COMBO_BOX); qSpiRoleMapping.insert (QAccessible::ProgressBar, ROLE_PROGRESS_BAR); qSpiRoleMapping.insert (QAccessible::Dial, ROLE_DIAL); qSpiRoleMapping.insert (QAccessible::HotkeyField, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::Slider, ROLE_SLIDER); qSpiRoleMapping.insert (QAccessible::SpinBox, ROLE_SPIN_BUTTON); qSpiRoleMapping.insert (QAccessible::Canvas, ROLE_CANVAS); qSpiRoleMapping.insert (QAccessible::Animation, ROLE_ANIMATION); qSpiRoleMapping.insert (QAccessible::Equation, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::ButtonDropDown, ROLE_COMBO_BOX); qSpiRoleMapping.insert (QAccessible::ButtonMenu, ROLE_COMBO_BOX); qSpiRoleMapping.insert (QAccessible::ButtonDropGrid, ROLE_COMBO_BOX); qSpiRoleMapping.insert (QAccessible::Whitespace, ROLE_SEPARATOR); qSpiRoleMapping.insert (QAccessible::PageTabList, ROLE_FRAME); qSpiRoleMapping.insert (QAccessible::Clock, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Splitter, ROLE_SEPARATOR); qSpiRoleMapping.insert (QAccessible::LayeredPane, ROLE_LAYERED_PANE); qSpiRoleMapping.insert (QAccessible::UserRole, ROLE_UNKNOWN); } /*---------------------------------------------------------------------------*/ void qspi_stateset_from_qstate (QAccessible::State state, QSpiIntList &set) { int array[2] = {0, 0}; for (int mask = 1; mask <= int(QAccessible::HasInvokeExtension); mask <<= 1) { /* We may need to take the role of the object into account when * mapping between the state sets */ BITARRAY_SET (array, STATE_EDITABLE); switch (state & mask) { case QAccessible::Normal: { BITARRAY_SET (array, STATE_ENABLED); BITARRAY_SET (array, STATE_SHOWING); BITARRAY_SET (array, STATE_VISIBLE); BITARRAY_SET (array, STATE_SENSITIVE); break; } case QAccessible::Unavailable: { BITARRAY_UNSET (array, STATE_ENABLED); BITARRAY_UNSET (array, STATE_SHOWING); BITARRAY_UNSET (array, STATE_VISIBLE); BITARRAY_UNSET (array, STATE_SENSITIVE); break; } case QAccessible::Selected: { BITARRAY_SET (array, STATE_SELECTED); break; } case QAccessible::Focused: { BITARRAY_SET (array, STATE_FOCUSED); break; } case QAccessible::Pressed: { BITARRAY_SET (array, STATE_PRESSED); break; } case QAccessible::Checked: { BITARRAY_SET (array, STATE_CHECKED); break; } case QAccessible::Mixed: { BITARRAY_SET (array, STATE_INDETERMINATE); break; } case QAccessible::ReadOnly: { BITARRAY_UNSET (array, STATE_EDITABLE); break; } case QAccessible::HotTracked: { break; } case QAccessible::DefaultButton: { BITARRAY_SET (array, STATE_IS_DEFAULT); break; } case QAccessible::Expanded: { BITARRAY_SET (array, STATE_EXPANDED); break; } case QAccessible::Collapsed: { BITARRAY_SET (array, STATE_COLLAPSED); break; } case QAccessible::Busy: { BITARRAY_SET (array, STATE_BUSY); break; } case QAccessible::Marqueed: case QAccessible::Animated: { BITARRAY_SET (array, STATE_ANIMATED); break; } case QAccessible::Invisible: case QAccessible::Offscreen: { BITARRAY_UNSET (array, STATE_VISIBLE); break; } case QAccessible::Sizeable: { BITARRAY_SET (array, STATE_RESIZABLE); break; } case QAccessible::Movable: case QAccessible::SelfVoicing: { break; } case QAccessible::Focusable: { BITARRAY_SET (array, STATE_FOCUSABLE); break; } case QAccessible::Selectable: { BITARRAY_SET (array, STATE_SELECTABLE); break; } case QAccessible::Linked: { break; } case QAccessible::Traversed: { BITARRAY_SET (array, STATE_VISITED); break; } case QAccessible::MultiSelectable: { BITARRAY_SET (array, STATE_MULTISELECTABLE); break; } case QAccessible::ExtSelectable: { BITARRAY_SET (array, STATE_SELECTABLE); break; } case QAccessible::Protected: case QAccessible::HasPopup: { break; } case QAccessible::Modal: { BITARRAY_SET (array, STATE_MODAL); break; } case QAccessible::HasInvokeExtension: { break; } default: { break; } } } set << array[0]; set << array[1]; } /*---------------------------------------------------------------------------*/ void qspi_initialize_constant_mappings () { initialize_role_mapping (); } /*END------------------------------------------------------------------------*/
/* * D-Bus AT-SPI, Qt Adaptor * * Copyright 2008, 2009 Nokia. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <QtCore/QHash> #include <QAccessible> #include "constant_mappings.h" #define BITARRAY_SEQ_TERM 0xffffffff #define BITARRAY_SET(p, n) ( (p)[n>>5] |= (1<<(n&31)) ) #define BITARRAY_UNSET(p, n) ( (p)[n>>5] &= ~(1<<(n&31)) ) /*---------------------------------------------------------------------------*/ QHash <QAccessible::Role, QSpiRole> qSpiRoleMapping; static void initialize_role_mapping () { qSpiRoleMapping.insert (QAccessible::NoRole, ROLE_INVALID); qSpiRoleMapping.insert (QAccessible::TitleBar, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::MenuBar, ROLE_MENU_BAR); qSpiRoleMapping.insert (QAccessible::ScrollBar, ROLE_SCROLL_BAR); qSpiRoleMapping.insert (QAccessible::Grip, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Sound, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Cursor, ROLE_ARROW); qSpiRoleMapping.insert (QAccessible::Caret, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::AlertMessage, ROLE_ALERT); qSpiRoleMapping.insert (QAccessible::Window, ROLE_WINDOW); qSpiRoleMapping.insert (QAccessible::Client, ROLE_FILLER); qSpiRoleMapping.insert (QAccessible::PopupMenu, ROLE_POPUP_MENU); qSpiRoleMapping.insert (QAccessible::MenuItem, ROLE_MENU_ITEM); qSpiRoleMapping.insert (QAccessible::ToolTip, ROLE_TOOL_TIP); qSpiRoleMapping.insert (QAccessible::Application, ROLE_APPLICATION); qSpiRoleMapping.insert (QAccessible::Document, ROLE_DOCUMENT_FRAME); qSpiRoleMapping.insert (QAccessible::Pane, ROLE_PANEL); qSpiRoleMapping.insert (QAccessible::Chart, ROLE_CHART); qSpiRoleMapping.insert (QAccessible::Dialog, ROLE_DIALOG); qSpiRoleMapping.insert (QAccessible::Border, ROLE_FRAME); qSpiRoleMapping.insert (QAccessible::Grouping, ROLE_PANEL); qSpiRoleMapping.insert (QAccessible::Separator, ROLE_SEPARATOR); qSpiRoleMapping.insert (QAccessible::ToolBar, ROLE_TOOL_BAR); qSpiRoleMapping.insert (QAccessible::StatusBar, ROLE_STATUS_BAR); qSpiRoleMapping.insert (QAccessible::Table, ROLE_TABLE); qSpiRoleMapping.insert (QAccessible::ColumnHeader, ROLE_TABLE_COLUMN_HEADER); qSpiRoleMapping.insert (QAccessible::RowHeader, ROLE_TABLE_ROW_HEADER); qSpiRoleMapping.insert (QAccessible::Column, ROLE_TABLE_CELL); qSpiRoleMapping.insert (QAccessible::Row, ROLE_TABLE_CELL); qSpiRoleMapping.insert (QAccessible::Cell, ROLE_TABLE_CELL); qSpiRoleMapping.insert (QAccessible::Link, ROLE_LINK); qSpiRoleMapping.insert (QAccessible::HelpBalloon, ROLE_DIALOG); qSpiRoleMapping.insert (QAccessible::Assistant, ROLE_DIALOG); qSpiRoleMapping.insert (QAccessible::List, ROLE_LIST); qSpiRoleMapping.insert (QAccessible::ListItem, ROLE_LIST_ITEM); qSpiRoleMapping.insert (QAccessible::Tree, ROLE_TREE); qSpiRoleMapping.insert (QAccessible::TreeItem, ROLE_TABLE_CELL); qSpiRoleMapping.insert (QAccessible::PageTab, ROLE_PAGE_TAB); qSpiRoleMapping.insert (QAccessible::PropertyPage, ROLE_PAGE_TAB); qSpiRoleMapping.insert (QAccessible::Indicator, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Graphic, ROLE_IMAGE); qSpiRoleMapping.insert (QAccessible::StaticText, ROLE_LABEL); qSpiRoleMapping.insert (QAccessible::EditableText, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::PushButton, ROLE_PUSH_BUTTON); qSpiRoleMapping.insert (QAccessible::CheckBox, ROLE_CHECK_BOX); qSpiRoleMapping.insert (QAccessible::RadioButton, ROLE_RADIO_BUTTON); qSpiRoleMapping.insert (QAccessible::ComboBox, ROLE_COMBO_BOX); qSpiRoleMapping.insert (QAccessible::ProgressBar, ROLE_PROGRESS_BAR); qSpiRoleMapping.insert (QAccessible::Dial, ROLE_DIAL); qSpiRoleMapping.insert (QAccessible::HotkeyField, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::Slider, ROLE_SLIDER); qSpiRoleMapping.insert (QAccessible::SpinBox, ROLE_SPIN_BUTTON); qSpiRoleMapping.insert (QAccessible::Canvas, ROLE_CANVAS); qSpiRoleMapping.insert (QAccessible::Animation, ROLE_ANIMATION); qSpiRoleMapping.insert (QAccessible::Equation, ROLE_TEXT); qSpiRoleMapping.insert (QAccessible::ButtonDropDown, ROLE_PUSH_BUTTON); qSpiRoleMapping.insert (QAccessible::ButtonMenu, ROLE_PUSH_BUTTON); qSpiRoleMapping.insert (QAccessible::ButtonDropGrid, ROLE_PUSH_BUTTON); qSpiRoleMapping.insert (QAccessible::Whitespace, ROLE_FILLER); qSpiRoleMapping.insert (QAccessible::PageTabList, ROLE_PAGE_TAB_LIST); qSpiRoleMapping.insert (QAccessible::Clock, ROLE_UNKNOWN); qSpiRoleMapping.insert (QAccessible::Splitter, ROLE_SPLIT_PANE); qSpiRoleMapping.insert (QAccessible::LayeredPane, ROLE_LAYERED_PANE); qSpiRoleMapping.insert (QAccessible::UserRole, ROLE_UNKNOWN); } /*---------------------------------------------------------------------------*/ void qspi_stateset_from_qstate (QAccessible::State state, QSpiIntList &set) { int array[2] = {0, 0}; for (int mask = 1; mask <= int(QAccessible::HasInvokeExtension); mask <<= 1) { /* We may need to take the role of the object into account when * mapping between the state sets */ BITARRAY_SET (array, STATE_EDITABLE); switch (state & mask) { case QAccessible::Normal: { BITARRAY_SET (array, STATE_ENABLED); BITARRAY_SET (array, STATE_SHOWING); BITARRAY_SET (array, STATE_VISIBLE); BITARRAY_SET (array, STATE_SENSITIVE); break; } case QAccessible::Unavailable: { BITARRAY_UNSET (array, STATE_ENABLED); BITARRAY_UNSET (array, STATE_SHOWING); BITARRAY_UNSET (array, STATE_VISIBLE); BITARRAY_UNSET (array, STATE_SENSITIVE); break; } case QAccessible::Selected: { BITARRAY_SET (array, STATE_SELECTED); break; } case QAccessible::Focused: { BITARRAY_SET (array, STATE_FOCUSED); break; } case QAccessible::Pressed: { BITARRAY_SET (array, STATE_PRESSED); break; } case QAccessible::Checked: { BITARRAY_SET (array, STATE_CHECKED); break; } case QAccessible::Mixed: { BITARRAY_SET (array, STATE_INDETERMINATE); break; } case QAccessible::ReadOnly: { BITARRAY_UNSET (array, STATE_EDITABLE); break; } case QAccessible::HotTracked: { break; } case QAccessible::DefaultButton: { BITARRAY_SET (array, STATE_IS_DEFAULT); break; } case QAccessible::Expanded: { BITARRAY_SET (array, STATE_EXPANDED); break; } case QAccessible::Collapsed: { BITARRAY_SET (array, STATE_COLLAPSED); break; } case QAccessible::Busy: { BITARRAY_SET (array, STATE_BUSY); break; } case QAccessible::Marqueed: case QAccessible::Animated: { BITARRAY_SET (array, STATE_ANIMATED); break; } case QAccessible::Invisible: case QAccessible::Offscreen: { BITARRAY_UNSET (array, STATE_VISIBLE); break; } case QAccessible::Sizeable: { BITARRAY_SET (array, STATE_RESIZABLE); break; } case QAccessible::Movable: case QAccessible::SelfVoicing: { break; } case QAccessible::Focusable: { BITARRAY_SET (array, STATE_FOCUSABLE); break; } case QAccessible::Selectable: { BITARRAY_SET (array, STATE_SELECTABLE); break; } case QAccessible::Linked: { break; } case QAccessible::Traversed: { BITARRAY_SET (array, STATE_VISITED); break; } case QAccessible::MultiSelectable: { BITARRAY_SET (array, STATE_MULTISELECTABLE); break; } case QAccessible::ExtSelectable: { BITARRAY_SET (array, STATE_SELECTABLE); break; } case QAccessible::Protected: case QAccessible::HasPopup: { break; } case QAccessible::Modal: { BITARRAY_SET (array, STATE_MODAL); break; } case QAccessible::HasInvokeExtension: { break; } default: { break; } } } set << array[0]; set << array[1]; } /*---------------------------------------------------------------------------*/ void qspi_initialize_constant_mappings () { initialize_role_mapping (); } /*END------------------------------------------------------------------------*/
Update role mappings.
Update role mappings.
C++
lgpl-2.1
KDE/qtatspi,KDE/qtatspi,KDE/qtatspi
b9865dbc4a001c39e31e1a76f2be19e85a0fc1c4
test/core/test_read_simulator.cpp
test/core/test_read_simulator.cpp
#define BOOST_TEST_MODULE "test_read_simulator" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <test/util/make_empty_input.hpp> #include <mjolnir/input/read_simulator.hpp> BOOST_AUTO_TEST_CASE(read_newtonian_molecular_dynamics_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "MolecularDynamics" integrator.type = "VelocityVerlet" precision = "double" boundary_type = "Unlimited" delta_t = 0.1 total_step = 100 save_step = 10 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto mdsim = dynamic_cast<mjolnir::MolecularDynamicsSimulator< traits_type, mjolnir::VelocityVerletIntegrator<traits_type>>*>(sim.get()); BOOST_TEST(static_cast<bool>(mdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(mdsim->time() == i * 0.1, boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_langevin_molecular_dynamics_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "MolecularDynamics" integrator.type = "UnderdampedLangevin" integrator.seed = 12345 integrator.parameters = [] precision = "double" boundary_type = "Unlimited" delta_t = 0.1 total_step = 100 save_step = 10 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto mdsim = dynamic_cast<mjolnir::MolecularDynamicsSimulator< traits_type, mjolnir::UnderdampedLangevinIntegrator<traits_type>>*>(sim.get()); BOOST_TEST(static_cast<bool>(mdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(mdsim->time() == i * 0.1, boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_steepest_descent_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "SteepestDescent" precision = "double" boundary_type = "Unlimited" delta = 0.1 step_limit = 100 save_step = 10 threshold = 0.0 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto sdsim = dynamic_cast< mjolnir::SteepestDescentSimulator<traits_type>*>(sim.get()); BOOST_TEST(static_cast<bool>(sdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_simulated_annealing_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "SimulatedAnnealing" integrator.type = "UnderdampedLangevin" integrator.seed = 12345 integrator.parameters = [] precision = "double" boundary_type = "Unlimited" total_step = 100 save_step = 10 each_step = 1 delta_t = 0.1 schedule.type = "linear" schedule.begin = 300.0 schedule.end = 10.0 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto sasim = dynamic_cast<mjolnir::SimulatedAnnealingSimulator< traits_type, mjolnir::UnderdampedLangevinIntegrator<traits_type>, mjolnir::LinearScheduler>*>(sim.get()); BOOST_TEST(static_cast<bool>(sasim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(sasim->system().attribute("temperature") == 300.0 * ((100-i) / 100.0) + 10.0 * (i / 100.0), boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } }
#define BOOST_TEST_MODULE "test_read_simulator" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <test/util/make_empty_input.hpp> #include <mjolnir/input/read_simulator.hpp> BOOST_AUTO_TEST_CASE(read_newtonian_molecular_dynamics_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "MolecularDynamics" integrator.type = "VelocityVerlet" precision = "double" boundary_type = "Unlimited" delta_t = 0.1 total_step = 100 save_step = 10 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto mdsim = dynamic_cast<mjolnir::MolecularDynamicsSimulator< traits_type, mjolnir::VelocityVerletIntegrator<traits_type>>*>(sim.get()); BOOST_TEST(static_cast<bool>(mdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(mdsim->time() == i * 0.1, boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_langevin_molecular_dynamics_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "MolecularDynamics" integrator.type = "UnderdampedLangevin" integrator.seed = 12345 integrator.parameters = [] precision = "double" boundary_type = "Unlimited" delta_t = 0.1 total_step = 100 save_step = 10 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto mdsim = dynamic_cast<mjolnir::MolecularDynamicsSimulator< traits_type, mjolnir::UnderdampedLangevinIntegrator<traits_type>>*>(sim.get()); BOOST_TEST(static_cast<bool>(mdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(mdsim->time() == i * 0.1, boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_BAOAB_langevin_molecular_dynamics_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "MolecularDynamics" integrator.type = "BAOABLangevin" integrator.seed = 12345 integrator.parameters = [] precision = "double" boundary_type = "Unlimited" delta_t = 0.1 total_step = 100 save_step = 10 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto mdsim = dynamic_cast<mjolnir::MolecularDynamicsSimulator< traits_type, mjolnir::BAOABLangevinIntegrator<traits_type>>*>(sim.get()); BOOST_TEST(static_cast<bool>(mdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(mdsim->time() == i * 0.1, boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_steepest_descent_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "SteepestDescent" precision = "double" boundary_type = "Unlimited" delta = 0.1 step_limit = 100 save_step = 10 threshold = 0.0 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto sdsim = dynamic_cast< mjolnir::SteepestDescentSimulator<traits_type>*>(sim.get()); BOOST_TEST(static_cast<bool>(sdsim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_simulated_annealing_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "SimulatedAnnealing" integrator.type = "UnderdampedLangevin" integrator.seed = 12345 integrator.parameters = [] precision = "double" boundary_type = "Unlimited" total_step = 100 save_step = 10 each_step = 1 delta_t = 0.1 schedule.type = "linear" schedule.begin = 300.0 schedule.end = 10.0 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto sasim = dynamic_cast<mjolnir::SimulatedAnnealingSimulator< traits_type, mjolnir::UnderdampedLangevinIntegrator<traits_type>, mjolnir::LinearScheduler>*>(sim.get()); BOOST_TEST(static_cast<bool>(sasim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(sasim->system().attribute("temperature") == 300.0 * ((100-i) / 100.0) + 10.0 * (i / 100.0), boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } } BOOST_AUTO_TEST_CASE(read_BAOAB_Langevin_simulated_annealing_simulator) { mjolnir::LoggerManager::set_default_logger("test_read_simulator.log"); using real_type = double; using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>; constexpr real_type tol = 1e-8; auto root = mjolnir::test::make_empty_input(); { using namespace toml::literals; const auto v = u8R"( type = "SimulatedAnnealing" integrator.type = "BAOABLangevin" integrator.seed = 12345 integrator.parameters = [] precision = "double" boundary_type = "Unlimited" total_step = 100 save_step = 10 each_step = 1 delta_t = 0.1 schedule.type = "linear" schedule.begin = 300.0 schedule.end = 10.0 )"_toml; root["simulator"] = v; const auto sim = mjolnir::read_simulator_from_table<traits_type>(root, v); BOOST_TEST(static_cast<bool>(sim)); const auto sasim = dynamic_cast<mjolnir::SimulatedAnnealingSimulator< traits_type, mjolnir::BAOABLangevinIntegrator<traits_type>, mjolnir::LinearScheduler>*>(sim.get()); BOOST_TEST(static_cast<bool>(sasim)); sim->initialize(); for(std::size_t i=0; i<99; ++i) { BOOST_TEST(sasim->system().attribute("temperature") == 300.0 * ((100-i) / 100.0) + 10.0 * (i / 100.0), boost::test_tools::tolerance(tol)); BOOST_TEST(sim->step()); // check it can step } // at the last (100-th) step, it returns false to stop the simulation. BOOST_TEST(!sim->step()); sim->finalize(); } }
add test for reading simulators with BAOAB
test: add test for reading simulators with BAOAB
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
10dab1950e162ee4df84f71fbd0827a7d24b1b0a
MyBlinkySketch/RandomColorFade.cpp
MyBlinkySketch/RandomColorFade.cpp
#include "RandomColorFade.h" #include "BlinkyTape.h" #include <Arduino.h> RndColFade::RndColFade(CRGB NewRndColFade) : rnd_col_fade(NewRndColFade) { } void RndColFade::draw(CRGB* leds) { if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) { do { C1 = random(1, 3); C2 = random(1, 3); C3 = random(1, 3); } while ((C1 == 2) && (C2 == 2) && (C3 == 2)); } if (((C1 == 1) && (Col1 != 0))) { Col1 = (Col1 - 10); } if (((C2 == 1) && (Col2 != 0))) { Col2 = (Col2 - 10); } if (((C3 == 1) && (Col3 != 0))) { Col3 = (Col3 - 10); } if (((C1 == 2) && (Col1 != 250))) { Col1 = (Col1 + 10); } if (((C2 == 2) && (Col2 != 250))) { Col2 = (Col2 + 10); } if (((C3 == 2) && (Col3 != 250))) { Col3 = (Col3 + 10); } if (((Col1 <= 90) && ((Col2 <= 90) && (Col3 <= 90)))) { //avoid black C1 = 2; C2 = 2; C3 = 2; } for (uint8_t i = 0; i < LED_COUNT; i++) { leds[i] = CRGB(Col1, Col2, Col3); } delay(wait_time); LEDS.show(); }
#include "RandomColorFade.h" #include "BlinkyTape.h" #include <Arduino.h> RndColFade::RndColFade(CRGB NewRndColFade) : rnd_col_fade(NewRndColFade) { } void RndColFade::draw(CRGB* leds) { if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) { do { C1 = random(1, 3); C2 = random(1, 3); C3 = random(1, 3); } while (((((C1 == 1) && (C2 == 1) && (C3 == 1)) || ((C1 == 2) && (C2 == 2) && (C3 == 2))))); } if (((C1 == 1) && (Col1 != 0))) { Col1 = (Col1 - 10); } if (((C2 == 1) && (Col2 != 0))) { Col2 = (Col2 - 10); } if (((C3 == 1) && (Col3 != 0))) { Col3 = (Col3 - 10); } if (((C1 == 2) && (Col1 != 250))) { Col1 = (Col1 + 10); } if (((C2 == 2) && (Col2 != 250))) { Col2 = (Col2 + 10); } if (((C3 == 2) && (Col3 != 250))) { Col3 = (Col3 + 10); } for (uint8_t i = 0; i < LED_COUNT; i++) { leds[i] = CRGB(Col1, Col2, Col3); } delay(wait_time); LEDS.show(); }
Update RandomColorFade.cpp
Update RandomColorFade.cpp First Commit
C++
mit
oddacon/BlinkyTape,oddacon/BlinkyTape
f7f2d999d49e3daeb781b36b548d49f8de5a1f85
ofSketchApp/src/BaseProcessTask.cpp
ofSketchApp/src/BaseProcessTask.cpp
// ============================================================================= // // Copyright (c) 2013 Christopher Baker <http://christopherbaker.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ============================================================================= #include "BaseProcessTask.h" #include "Poco/Buffer.h" #include "Poco/PipeStream.h" #include "Poco/Process.h" #include <iostream> #include "ofLog.h" namespace of { namespace Sketch { BaseProcessTask::BaseProcessTask(const std::string& name, const std::string& command, const std::vector<std::string>& args, std::size_t bufferSize): Poco::Task(name), _command(command), _args(args), _bufferSize(bufferSize) { } BaseProcessTask::~BaseProcessTask() { } void BaseProcessTask::runTask() { Poco::Pipe outAndErrPipe; Poco::ProcessHandle ph = Poco::Process::launch(_command, _args, 0, &outAndErrPipe, &outAndErrPipe); Poco::PipeInputStream istr(outAndErrPipe); Poco::Buffer<char> buffer(_bufferSize); while(istr.good() && !istr.fail()) { if(isCancelled()) { Poco::Process::kill(ph); } istr.getline(buffer.begin(), buffer.size()); if (buffer.begin()) { std::string str(buffer.begin()); if (!str.empty()) { // Progress callbacks and custom data events are the // responsibility of the subclass. processLine(str); } } } int exitCode = ph.wait(); ofLogVerbose("BaseProcessTask::runTask") << "Exit with: " << exitCode; } } } // namespace of::Sketch
// ============================================================================= // // Copyright (c) 2013 Christopher Baker <http://christopherbaker.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ============================================================================= #include "BaseProcessTask.h" #include "Poco/Buffer.h" #include "Poco/PipeStream.h" #include "Poco/Process.h" #include <iostream> #include "ofLog.h" namespace of { namespace Sketch { BaseProcessTask::BaseProcessTask(const std::string& name, const std::string& command, const std::vector<std::string>& args, std::size_t bufferSize): Poco::Task(name), _command(command), _args(args), _bufferSize(bufferSize) { } BaseProcessTask::~BaseProcessTask() { } void BaseProcessTask::runTask() { Poco::Pipe outAndErrPipe; Poco::ProcessHandle ph = Poco::Process::launch(_command, _args, 0, &outAndErrPipe, &outAndErrPipe); Poco::PipeInputStream istr(outAndErrPipe); Poco::Buffer<char> buffer(_bufferSize); while(istr.good() && !istr.fail()) { if(isCancelled()) { Poco::Process::kill(ph); break; } istr.getline(buffer.begin(), buffer.size()); if (buffer.begin()) { std::string str(buffer.begin()); if (!str.empty()) { // Progress callbacks and custom data events are the // responsibility of the subclass. processLine(str); } } } int exitCode = ph.wait(); ofLogVerbose("BaseProcessTask::runTask") << "Exit with: " << exitCode; } } } // namespace of::Sketch
Stop button now works.
Stop button now works.
C++
mit
brannondorsey/ofSketch,brannondorsey/ofSketch,olab-io/ofSketch,olab-io/ofSketch,brannondorsey/ofSketch,olab-io/ofSketch
7c17c8a865fb1523e26397d5819644dc4c045140
ogles_gpgpu/common/proc/pyramid.cpp
ogles_gpgpu/common/proc/pyramid.cpp
// // ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0 // // Author: Markus Konrad <[email protected]>, Winter 2014/2015 // http://www.mkonrad.net // // See LICENSE file in project repository root for the license. // #include "../common_includes.h" #include "pyramid.h" using namespace std; using namespace ogles_gpgpu; static std::vector<Rect2d> pack(const std::vector<Size2d> &src) { std::vector<Rect2d> packed; int x = 0, y = 0; bool half = false; // Decrease going forward: int i = 0; for(; (i < src.size()) && !half; i++) { packed.emplace_back(x, y, src[i].width, src[i].height); x += src[i].width; if(src[i].height*2 < src[0].height) { half = true; } } // Decrease going backward -- now x becomes the right edge int t, l, r, b = src[0].height; for(; i < src.size(); i++) { r = x; l = r - src[i].width; t = b - src[i].height; packed.emplace_back(l, t, src[i].width, src[i].height); x -= src[i].width; } return packed; } static std::vector<Rect2d> reduce(const Size2d &src, int levels) { std::vector<Rect2d> packed; int x = 0, y = 0, w = src.width, h = src.height; for(int i = 0; i < levels; i++) { packed.emplace_back(x, y, w, h); if(i % 2) { y += h; } else { x += w; } w = (w >> 1); h = (h >> 1); } return packed; } PyramidProc::PyramidProc(int levels) : m_levels(levels) { } PyramidProc::PyramidProc(const std::vector<Size2d> &scales) : m_scales(scales) { } void PyramidProc::setOutputSize(float scaleFactor) { // noop } void PyramidProc::setScales(const std::vector<Size2d> &scales) { m_crops = pack(scales); } void PyramidProc::setLevels(int levels) { m_scales.clear(); m_levels = levels; } const std::vector<Rect2d> & PyramidProc::getLevelCrops() const { return m_crops; } void PyramidProc::PyramidProc::render() { OG_LOGINF(getProcName(), "input tex %d, target %d, framebuffer of size %dx%d", texId, texTarget, outFrameW, outFrameH); filterRenderPrepare(); setUniforms(); Tools::checkGLErr(getProcName(), "render prepare"); filterRenderSetCoords(); Tools::checkGLErr(getProcName(), "render set coords"); // Set a constant background color glClear(GL_COLOR_BUFFER_BIT); glClearColor(0,0,0,1); for(auto &c : m_crops) { glViewport(c.x, c.y, c.width, c.height); filterRenderDraw(); } Tools::checkGLErr(getProcName(), "render draw"); filterRenderCleanup(); Tools::checkGLErr(getProcName(), "render cleanup"); } int PyramidProc::init(int inW, int inH, unsigned int order, bool prepareForExternalInput) { int width = 0, height = 0; if(m_scales.size()) { m_crops = pack(m_scales); for(const auto &c : m_crops) { width = std::max(width, c.x + c.width); height = std::max(height, c.y + c.width); } } else { m_crops = reduce({inW, inH}, m_levels); width = inW * 3 / 2; height = inH; } FilterProcBase::setOutputSize(width, height); return FilterProcBase::init(inW, inH, order, prepareForExternalInput); }
// // ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0 // // Author: Markus Konrad <[email protected]>, Winter 2014/2015 // http://www.mkonrad.net // // See LICENSE file in project repository root for the license. // #include "../common_includes.h" #include "pyramid.h" using namespace std; using namespace ogles_gpgpu; static std::vector<Rect2d> pack(const std::vector<Size2d> &src) { std::vector<Rect2d> packed; int x = 0, y = 0; bool half = false; // Decrease going forward: int i = 0; for(; (i < src.size()) && !half; i++) { packed.emplace_back(x, y, src[i].width, src[i].height); x += src[i].width; if(src[i].height*2 < src[0].height) { half = true; } } // Decrease going backward -- now x becomes the right edge int t, l, r, b = src[0].height; for(; i < src.size(); i++) { r = x; l = r - src[i].width; t = b - src[i].height; packed.emplace_back(l, t, src[i].width, src[i].height); x -= src[i].width; } return packed; } static std::vector<Rect2d> reduce(const Size2d &src, int levels) { std::vector<Rect2d> packed; int x = 0, y = 0, w = src.width, h = src.height; for(int i = 0; i < levels; i++) { packed.emplace_back(x, y, w, h); if(i % 2) { y += h; } else { x += w; } w = (w >> 1); h = (h >> 1); } return packed; } PyramidProc::PyramidProc(int levels) : m_levels(levels) { } PyramidProc::PyramidProc(const std::vector<Size2d> &scales) : m_scales(scales) { } void PyramidProc::setOutputSize(float scaleFactor) { // noop } void PyramidProc::setScales(const std::vector<Size2d> &scales) { m_crops = pack(scales); } void PyramidProc::setLevels(int levels) { m_scales.clear(); m_levels = levels; } const std::vector<Rect2d> & PyramidProc::getLevelCrops() const { return m_crops; } void PyramidProc::PyramidProc::render() { OG_LOGINF(getProcName(), "input tex %d, target %d, framebuffer of size %dx%d", texId, texTarget, outFrameW, outFrameH); filterRenderPrepare(); setUniforms(); Tools::checkGLErr(getProcName(), "render prepare"); filterRenderSetCoords(); Tools::checkGLErr(getProcName(), "render set coords"); // Set a constant background color glClear(GL_COLOR_BUFFER_BIT); glClearColor(0,0,0,1); for(auto &c : m_crops) { glViewport(c.x, c.y, c.width, c.height); filterRenderDraw(); } Tools::checkGLErr(getProcName(), "render draw"); filterRenderCleanup(); Tools::checkGLErr(getProcName(), "render cleanup"); } int PyramidProc::init(int inW, int inH, unsigned int order, bool prepareForExternalInput) { int width = 0, height = 0; if(m_scales.size()) { m_crops = pack(m_scales); for(const auto &c : m_crops) { width = std::max(width, c.x + c.width); height = std::max(height, c.y + c.height); } } else { m_crops = reduce({inW, inH}, m_levels); width = inW * 3 / 2; height = inH; } FilterProcBase::setOutputSize(width, height); return FilterProcBase::init(inW, inH, order, prepareForExternalInput); }
Fix max dimension estimation typo (width vs height)
Fix max dimension estimation typo (width vs height)
C++
apache-2.0
headupinclouds/ogles_gpgpu,headupinclouds/ogles_gpgpu,hunter-packages/ogles_gpgpu,hunter-packages/ogles_gpgpu,hunter-packages/ogles_gpgpu,headupinclouds/ogles_gpgpu,hunter-packages/ogles_gpgpu,headupinclouds/ogles_gpgpu
97d9c2e43facab2b405cfdd29ad110f846be2e64
OpenSim/Simulation/Test/testPrescribedForce.cpp
OpenSim/Simulation/Test/testPrescribedForce.cpp
/* -------------------------------------------------------------------------- * * OpenSim: testPrescribedForce.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Peter Eastman, Ajay Seth * * * * 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. * * -------------------------------------------------------------------------- */ //========================================================================================================== // testPrescribedForce tests the application of function specified forces applied to a body // as a force and torque on the body, with the point force application also a function // Tests Include: // 1. No force // 2. Force on the body // 3. Force at a point // 4. Torque on a body // 4. Forces from a file. // Add tests here // //========================================================================================================== #include <iostream> #include <OpenSim/Common/IO.h> #include <OpenSim/Common/Exception.h> #include <OpenSim/Common/PiecewiseLinearFunction.h> #include <OpenSim/Simulation/Model/ForceSet.h> #include <OpenSim/Simulation/Model/AnalysisSet.h> #include <OpenSim/Simulation/Model/BodySet.h> #include <OpenSim/Simulation/Manager/Manager.h> #include <OpenSim/Analyses/Kinematics.h> #include <OpenSim/Analyses/PointKinematics.h> #include <OpenSim/Analyses/Actuation.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/PrescribedForce.h> #include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h> #include <OpenSim/Simulation/SimbodyEngine/FreeJoint.h> #include <OpenSim/Simulation/SimbodyEngine/WeldJoint.h> #include <OpenSim/Simulation/SimbodyEngine/TransformAxis.h> #include <OpenSim/Common/LoadOpenSimLibrary.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include "SimTKsimbody.h" #include "SimTKmath.h" using namespace OpenSim; using namespace std; //========================================================================================================== // Common Parameters for the simulations are just global. const static double integ_accuracy = 1.0e-4; const static double duration = 1.0; const static SimTK::Vec3 gravity_vec = SimTK::Vec3(0, -9.8065, 0); SimTK::MassProperties ballMass = SimTK::MassProperties(8.806, SimTK::Vec3(0), SimTK::Inertia(SimTK::Vec3(0.1268, 0.0332, 0.1337))); //========================================================================================================== static int counter=0; void testNoForce(); void testForceAtOrigin(); void testForceAtPoint(); void testTorque(); int main() { try { testNoForce(); testForceAtOrigin(); testForceAtPoint(); testTorque(); } catch (const Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } //========================================================================================================== // Test Cases //========================================================================================================== void testPrescribedForce(OpenSim::Function* forceX, OpenSim::Function* forceY, OpenSim::Function* forceZ, OpenSim::Function* pointX, OpenSim::Function* pointY, OpenSim::Function* pointZ, OpenSim::Function* torqueX, OpenSim::Function* torqueY, OpenSim::Function* torqueZ, vector<SimTK::Real>& times, vector<SimTK::Vec3>& accelerations, vector<SimTK::Vec3>& angularAccelerations) { using namespace SimTK; //========================================================================================================== // Setup OpenSim model Model *osimModel = new Model; //OpenSim bodies const Ground& ground = osimModel->getGround();; OpenSim::Body ball; ball.setName("ball"); // Add joints FreeJoint free("free", ground, Vec3(0), Vec3(0), ball, Vec3(0), Vec3(0)); // Rename coordinates for a free joint for(int i=0; i<free.numCoordinates(); i++){ std::stringstream coord_name; coord_name << "free_q" << i; free.upd_coordinates(i).setName(coord_name.str()); } osimModel->addBody(&ball); osimModel->addJoint(&free); // Add a PrescribedForce. PrescribedForce force("forceOnBall", ball); if (forceX != NULL) force.setForceFunctions(forceX, forceY, forceZ); if (pointX != NULL) force.setPointFunctions(pointX, pointY, pointZ); if (torqueX != NULL) force.setTorqueFunctions(torqueX, torqueY, torqueZ); counter++; osimModel->updForceSet().append(&force); // BAD: have to set memoryOwner to false or program will crash when this test is complete. osimModel->disownAllComponents(); //Set mass ball.setMass(ballMass.getMass()); ball.setMassCenter(ballMass.getMassCenter()); ball.setInertia(ballMass.getInertia()); osimModel->setGravity(gravity_vec); osimModel->print("TestPrescribedForceModel.osim"); delete osimModel; // Check that serialization/deserialization is working correctly as well osimModel = new Model("TestPrescribedForceModel.osim"); SimTK::State& osim_state = osimModel->initSystem(); osimModel->getMultibodySystem().realize(osim_state, Stage::Position ); //========================================================================================================== // Compute the force and torque at the specified times. const OpenSim::Body& body = osimModel->getBodySet().get("ball"); RungeKuttaMersonIntegrator integrator(osimModel->getMultibodySystem() ); Manager manager(*osimModel, integrator); osim_state.setTime(0.0); for (unsigned int i = 0; i < times.size(); ++i) { manager.integrate(osim_state, times[i]); osimModel->getMultibodySystem().realize(osim_state, Stage::Acceleration); Vec3 accel = body.findStationAccelerationInGround(osim_state, Vec3(0)); Vec3 angularAccel = body.getAccelerationInGround(osim_state)[0]; ASSERT_EQUAL(accelerations[i][0], accel[0], 1e-10); ASSERT_EQUAL(accelerations[i][1], accel[1], 1e-10); ASSERT_EQUAL(accelerations[i][2], accel[2], 1e-10); ASSERT_EQUAL(angularAccelerations[i][0], angularAccel[0], 1e-10); ASSERT_EQUAL(angularAccelerations[i][1], angularAccel[1], 1e-10); ASSERT_EQUAL(angularAccelerations[i][2], angularAccel[2], 1e-10); } } void testNoForce() { using namespace SimTK; vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec); angularAccel.push_back(Vec3(0)); times.push_back(0.5); accel.push_back(gravity_vec); angularAccel.push_back(Vec3(0)); times.push_back(1.0); accel.push_back(gravity_vec); angularAccel.push_back(Vec3(0)); testPrescribedForce(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, times, accel, angularAccel); } void testForceAtOrigin() { using namespace SimTK; vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec+Vec3(1.0/ballMass.getMass(), 0, 0)); angularAccel.push_back(Vec3(0)); times.push_back(0.5); accel.push_back(gravity_vec+Vec3(0.5/ballMass.getMass(), 0.5/ballMass.getMass(), 0)); angularAccel.push_back(Vec3(0)); times.push_back(1.0); accel.push_back(gravity_vec+Vec3(0, 1/ballMass.getMass(), 0)); angularAccel.push_back(Vec3(0)); PiecewiseLinearFunction *forceX = new PiecewiseLinearFunction(), *forceY = new PiecewiseLinearFunction(), *forceZ = new PiecewiseLinearFunction(); forceX->addPoint(0, 1); forceX->addPoint(1, 0); forceY->addPoint(0, 0); forceY->addPoint(1, 1); forceZ->addPoint(0, 0); testPrescribedForce(forceX, forceY, forceZ, NULL, NULL, NULL, NULL, NULL, NULL, times, accel, angularAccel); } void testForceAtPoint() { using namespace SimTK; Mat33 invInertia = ballMass.getInertia().toMat33().invert(); vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec+Vec3(1.0/ballMass.getMass(), 0, 0)); angularAccel.push_back(invInertia*(Vec3(1, -1, 0)%Vec3(1.0, 0, 0))); PiecewiseLinearFunction *forceX = new PiecewiseLinearFunction(), *forceY = new PiecewiseLinearFunction(), *forceZ = new PiecewiseLinearFunction(); forceX->addPoint(0, 1); forceY->addPoint(0, 0); forceZ->addPoint(0, 0); PiecewiseLinearFunction *pointX = new PiecewiseLinearFunction(), *pointY = new PiecewiseLinearFunction(), *pointZ = new PiecewiseLinearFunction(); pointX->addPoint(0, 1); pointY->addPoint(0, -1); pointZ->addPoint(0, 0); testPrescribedForce(forceX, forceY, forceZ, pointX, pointY, pointZ, NULL, NULL, NULL, times, accel, angularAccel); } void testTorque() { using namespace SimTK; Mat33 invInertia = ballMass.getInertia().toMat33().invert(); vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec); angularAccel.push_back(invInertia*Vec3(1, 0.5, 0)); PiecewiseLinearFunction *torqueX = new PiecewiseLinearFunction(), *torqueY = new PiecewiseLinearFunction(), *torqueZ = new PiecewiseLinearFunction(); torqueX->addPoint(0, 1); torqueY->addPoint(0, 0.5); torqueZ->addPoint(0, 0); testPrescribedForce(NULL, NULL, NULL, NULL, NULL, NULL, torqueX, torqueY, torqueZ, times, accel, angularAccel); }
/* -------------------------------------------------------------------------- * * OpenSim: testPrescribedForce.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Peter Eastman, Ajay Seth * * * * 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. * * -------------------------------------------------------------------------- */ //========================================================================================================== // testPrescribedForce tests the application of function specified forces applied to a body // as a force and torque on the body, with the point force application also a function // Tests Include: // 1. No force // 2. Force on the body // 3. Force at a point // 4. Torque on a body // 4. Forces from a file. // Add tests here // //========================================================================================================== #include <iostream> #include <OpenSim/Common/IO.h> #include <OpenSim/Common/Exception.h> #include <OpenSim/Common/PiecewiseLinearFunction.h> #include <OpenSim/Simulation/Model/ForceSet.h> #include <OpenSim/Simulation/Model/AnalysisSet.h> #include <OpenSim/Simulation/Model/BodySet.h> #include <OpenSim/Simulation/Manager/Manager.h> #include <OpenSim/Analyses/Kinematics.h> #include <OpenSim/Analyses/Actuation.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/PrescribedForce.h> #include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h> #include <OpenSim/Simulation/SimbodyEngine/FreeJoint.h> #include <OpenSim/Simulation/SimbodyEngine/WeldJoint.h> #include <OpenSim/Simulation/SimbodyEngine/TransformAxis.h> #include <OpenSim/Common/LoadOpenSimLibrary.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include "SimTKsimbody.h" #include "SimTKmath.h" using namespace OpenSim; using namespace std; //========================================================================================================== // Common Parameters for the simulations are just global. const static double integ_accuracy = 1.0e-4; const static double duration = 1.0; const static SimTK::Vec3 gravity_vec = SimTK::Vec3(0, -9.8065, 0); SimTK::MassProperties ballMass = SimTK::MassProperties(8.806, SimTK::Vec3(0), SimTK::Inertia(SimTK::Vec3(0.1268, 0.0332, 0.1337))); //========================================================================================================== static int counter=0; void testNoForce(); void testForceAtOrigin(); void testForceAtPoint(); void testTorque(); int main() { try { testNoForce(); testForceAtOrigin(); testForceAtPoint(); testTorque(); } catch (const Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } //========================================================================================================== // Test Cases //========================================================================================================== void testPrescribedForce(OpenSim::Function* forceX, OpenSim::Function* forceY, OpenSim::Function* forceZ, OpenSim::Function* pointX, OpenSim::Function* pointY, OpenSim::Function* pointZ, OpenSim::Function* torqueX, OpenSim::Function* torqueY, OpenSim::Function* torqueZ, vector<SimTK::Real>& times, vector<SimTK::Vec3>& accelerations, vector<SimTK::Vec3>& angularAccelerations) { using namespace SimTK; //========================================================================================================== // Setup OpenSim model Model *osimModel = new Model; //OpenSim bodies const Ground& ground = osimModel->getGround();; OpenSim::Body ball; ball.setName("ball"); // Add joints FreeJoint free("free", ground, Vec3(0), Vec3(0), ball, Vec3(0), Vec3(0)); // Rename coordinates for a free joint for(int i=0; i<free.numCoordinates(); i++){ std::stringstream coord_name; coord_name << "free_q" << i; free.upd_coordinates(i).setName(coord_name.str()); } osimModel->addBody(&ball); osimModel->addJoint(&free); // Add a PrescribedForce. PrescribedForce force("forceOnBall", ball); if (forceX != NULL) force.setForceFunctions(forceX, forceY, forceZ); if (pointX != NULL) force.setPointFunctions(pointX, pointY, pointZ); if (torqueX != NULL) force.setTorqueFunctions(torqueX, torqueY, torqueZ); counter++; osimModel->updForceSet().append(&force); // BAD: have to set memoryOwner to false or program will crash when this test is complete. osimModel->disownAllComponents(); //Set mass ball.setMass(ballMass.getMass()); ball.setMassCenter(ballMass.getMassCenter()); ball.setInertia(ballMass.getInertia()); osimModel->setGravity(gravity_vec); osimModel->print("TestPrescribedForceModel.osim"); delete osimModel; // Check that serialization/deserialization is working correctly as well osimModel = new Model("TestPrescribedForceModel.osim"); SimTK::State& osim_state = osimModel->initSystem(); osimModel->getMultibodySystem().realize(osim_state, Stage::Position ); //========================================================================================================== // Compute the force and torque at the specified times. const OpenSim::Body& body = osimModel->getBodySet().get("ball"); RungeKuttaMersonIntegrator integrator(osimModel->getMultibodySystem() ); Manager manager(*osimModel, integrator); osim_state.setTime(0.0); for (unsigned int i = 0; i < times.size(); ++i) { manager.integrate(osim_state, times[i]); osimModel->getMultibodySystem().realize(osim_state, Stage::Acceleration); Vec3 accel = body.findStationAccelerationInGround(osim_state, Vec3(0)); Vec3 angularAccel = body.getAccelerationInGround(osim_state)[0]; ASSERT_EQUAL(accelerations[i][0], accel[0], 1e-10); ASSERT_EQUAL(accelerations[i][1], accel[1], 1e-10); ASSERT_EQUAL(accelerations[i][2], accel[2], 1e-10); ASSERT_EQUAL(angularAccelerations[i][0], angularAccel[0], 1e-10); ASSERT_EQUAL(angularAccelerations[i][1], angularAccel[1], 1e-10); ASSERT_EQUAL(angularAccelerations[i][2], angularAccel[2], 1e-10); } } void testNoForce() { using namespace SimTK; vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec); angularAccel.push_back(Vec3(0)); times.push_back(0.5); accel.push_back(gravity_vec); angularAccel.push_back(Vec3(0)); times.push_back(1.0); accel.push_back(gravity_vec); angularAccel.push_back(Vec3(0)); testPrescribedForce(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, times, accel, angularAccel); } void testForceAtOrigin() { using namespace SimTK; vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec+Vec3(1.0/ballMass.getMass(), 0, 0)); angularAccel.push_back(Vec3(0)); times.push_back(0.5); accel.push_back(gravity_vec+Vec3(0.5/ballMass.getMass(), 0.5/ballMass.getMass(), 0)); angularAccel.push_back(Vec3(0)); times.push_back(1.0); accel.push_back(gravity_vec+Vec3(0, 1/ballMass.getMass(), 0)); angularAccel.push_back(Vec3(0)); PiecewiseLinearFunction *forceX = new PiecewiseLinearFunction(), *forceY = new PiecewiseLinearFunction(), *forceZ = new PiecewiseLinearFunction(); forceX->addPoint(0, 1); forceX->addPoint(1, 0); forceY->addPoint(0, 0); forceY->addPoint(1, 1); forceZ->addPoint(0, 0); testPrescribedForce(forceX, forceY, forceZ, NULL, NULL, NULL, NULL, NULL, NULL, times, accel, angularAccel); } void testForceAtPoint() { using namespace SimTK; Mat33 invInertia = ballMass.getInertia().toMat33().invert(); vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec+Vec3(1.0/ballMass.getMass(), 0, 0)); angularAccel.push_back(invInertia*(Vec3(1, -1, 0)%Vec3(1.0, 0, 0))); PiecewiseLinearFunction *forceX = new PiecewiseLinearFunction(), *forceY = new PiecewiseLinearFunction(), *forceZ = new PiecewiseLinearFunction(); forceX->addPoint(0, 1); forceY->addPoint(0, 0); forceZ->addPoint(0, 0); PiecewiseLinearFunction *pointX = new PiecewiseLinearFunction(), *pointY = new PiecewiseLinearFunction(), *pointZ = new PiecewiseLinearFunction(); pointX->addPoint(0, 1); pointY->addPoint(0, -1); pointZ->addPoint(0, 0); testPrescribedForce(forceX, forceY, forceZ, pointX, pointY, pointZ, NULL, NULL, NULL, times, accel, angularAccel); } void testTorque() { using namespace SimTK; Mat33 invInertia = ballMass.getInertia().toMat33().invert(); vector<Real> times; vector<Vec3> accel; vector<Vec3> angularAccel; times.push_back(0.0); accel.push_back(gravity_vec); angularAccel.push_back(invInertia*Vec3(1, 0.5, 0)); PiecewiseLinearFunction *torqueX = new PiecewiseLinearFunction(), *torqueY = new PiecewiseLinearFunction(), *torqueZ = new PiecewiseLinearFunction(); torqueX->addPoint(0, 1); torqueY->addPoint(0, 0.5); torqueZ->addPoint(0, 0); testPrescribedForce(NULL, NULL, NULL, NULL, NULL, NULL, torqueX, torqueY, torqueZ, times, accel, angularAccel); }
Remove unused include.
Remove unused include.
C++
apache-2.0
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
f0e2b9330b1836e3de22fce0d139959d1ddd2b9d
src/input/psp/joystick.cpp
src/input/psp/joystick.cpp
#ifdef MINPSPW #include "joystick.h" void PSPJoystick::poll(){ sceCtrlPeekBufferPositive(&joystick, 1); } JoystickInput PSPJoystick::readAll(){ JoystickInput input; if(joystick.Buttons != 0){ // WIIMOTE for now, we can add in nunchuck and classic later if(joystick.Buttons & PSP_CTRL_START){ //input.button7 = true; } else if(joystick.Buttons & PSP_CTRL_SELECT){ //input.button8 = true; } else if(joystick.Buttons & PSP_CTRL_SQUARE){ input.button1 = true; } else if(joystick.Buttons & PSP_CTRL_CROSS){ input.button2 = true; } else if(joystick.Buttons & PSP_CTRL_TRIANGLE){ input.button3 = true; } else if(joystick.Buttons & PSP_CTRL_CIRCLE){ input.button4 = true; } else if(joystick.Buttons & PSP_CTRL_RTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LEFT){ input.left = true; } else if(joystick.Buttons & PSP_CTRL_RIGHT){ input.right = true; } else if(joystick.Buttons & PSP_CTRL_DOWN){ input.down = true; } else if(joystick.Buttons & PSP_CTRL_UP){ input.up = true; } } return input; } PSPJoystick::~PSPJoystick(){ // no cleanup required } PSPJoystick::PSPJoystick(){ sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); } #endif
#ifdef MINPSPW #include "joystick.h" void PSPJoystick::poll(){ sceCtrlPeekBufferPositive(&joystick, 1); } JoystickInput PSPJoystick::readAll(){ JoystickInput input; if(joystick.Buttons != 0){ if(joystick.Buttons & PSP_CTRL_START){ //input.button7 = true; } else if(joystick.Buttons & PSP_CTRL_SELECT){ //input.button8 = true; } else if(joystick.Buttons & PSP_CTRL_SQUARE){ input.button1 = true; } else if(joystick.Buttons & PSP_CTRL_CROSS){ input.button2 = true; } else if(joystick.Buttons & PSP_CTRL_TRIANGLE){ input.button3 = true; } else if(joystick.Buttons & PSP_CTRL_CIRCLE){ input.button4 = true; } else if(joystick.Buttons & PSP_CTRL_RTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LEFT){ input.left = true; } else if(joystick.Buttons & PSP_CTRL_RIGHT){ input.right = true; } else if(joystick.Buttons & PSP_CTRL_DOWN){ input.down = true; } else if(joystick.Buttons & PSP_CTRL_UP){ input.up = true; } } return input; } PSPJoystick::~PSPJoystick(){ // no cleanup required } PSPJoystick::PSPJoystick(){ sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); } #endif
Remove comment.
Remove comment. git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@4331 662fdd30-d327-0410-a531-f549c87e1e9e
C++
bsd-3-clause
Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown
cf89978fc0f6b1ff269ed59c14d275cf0fb23c28
src/cpp/code-generator.cc
src/cpp/code-generator.cc
#include <cpp/code-generator.hh> #include <ast/all.hh> namespace cpp { CodeGenerator::CodeGenerator(std::ostream& o) : o_(o) , params_(false) {} CodeGenerator::~CodeGenerator() {} void CodeGenerator::generate_main() { o_ << "int main()" << misc::iendl; o_ << "{" << misc::indentendl; for (auto mod : modules_) o_ << "__" << mod << "__::__init();" << misc::iendl; o_ << misc::dedentendl << "}" << misc::iendl; } void CodeGenerator::operator()(ast::ExprList& ast) { auto beg = ast.list_get().begin(); auto end = ast.list_get().end(); for (auto it = beg; it != end; ++it) { if (it != beg) code_ << ", "; (*it)->accept(*this); } } void CodeGenerator::operator()(ast::StmtList& ast) { auto beg = ast.list_get().begin(); auto end = ast.list_get().end(); for (auto it = beg; it != end; ++it) { if (it != beg) code_ << misc::iendl; (*it)->accept(*this); if (!dynamic_cast<ast::FunctionDec*> (*it)) code_ << ";"; } } void CodeGenerator::operator()(ast::ModuleStmt& ast) { modules_.push_back(ast.name_get()); o_ << "namespace __" << ast.name_get() << "__" << misc::iendl; o_ << "{" << misc::indentendl; code_ << misc::indent; ast.content_get()->accept(*this); o_ << code_.str(); o_ << misc::dedentendl; o_ << "}" << misc::iendl; } void CodeGenerator::operator()(ast::FunctionDec& ast) { // Generating all functions prototypes for (auto proto : ast.to_generate_get()) { ast.type_set(proto); code_ << ast.type_get()->return_type_get()->cpp_type() << " " << ast.name_get() << "("; params_ = true; if (ast.args_get()) ast.args_get()->accept(*this); params_ = false; code_ << ")" << misc::iendl << "{" << misc::indentendl; ast.body_get()->accept(*this); code_ << misc::dedentendl << "}" << misc::iendl; } } void CodeGenerator::operator()(ast::IdVar& ast) { if (params_) code_ << ast.type_get()->cpp_type() << " "; code_ << ast.id_get(); } void CodeGenerator::operator()(ast::AssignExpr& ast) { ast.lvalue_get()->accept(*this); code_ << " = "; ast.rvalue_get()->accept(*this); } void CodeGenerator::operator()(ast::StringExpr& ast) { code_ << "new __repy_string(\"" << ast.str_get() << "\")"; } void CodeGenerator::operator()(ast::NumeralExpr& ast) { code_ << ast.value_get(); } void CodeGenerator::operator()(ast::FunctionVar& ast) { ast.var_get()->accept(*this); code_ << "("; if (ast.params_get()) ast.params_get()->accept(*this); code_ << ")"; } } // namespace cpp
#include <cpp/code-generator.hh> #include <ast/all.hh> namespace cpp { CodeGenerator::CodeGenerator(std::ostream& o) : o_(o) , params_(false) {} CodeGenerator::~CodeGenerator() {} void CodeGenerator::generate_main() { o_ << "int main()" << misc::iendl; o_ << "{" << misc::indentendl; for (auto mod : modules_) o_ << "__" << mod << "__::__init();" << misc::iendl; o_ << misc::dedentendl << "}" << misc::iendl; } void CodeGenerator::operator()(ast::ExprList& ast) { auto beg = ast.list_get().begin(); auto end = ast.list_get().end(); for (auto it = beg; it != end; ++it) { if (it != beg) code_ << ", "; (*it)->accept(*this); } } void CodeGenerator::operator()(ast::StmtList& ast) { auto beg = ast.list_get().begin(); auto end = ast.list_get().end(); for (auto it = beg; it != end; ++it) { if (it != beg) code_ << misc::iendl; (*it)->accept(*this); if (!dynamic_cast<ast::FunctionDec*> (*it)) code_ << ";"; } } void CodeGenerator::operator()(ast::ModuleStmt& ast) { modules_.push_back(ast.name_get()); o_ << "namespace __" << ast.name_get() << "__" << misc::iendl; o_ << "{" << misc::indentendl; code_ << misc::indent; ast.content_get()->accept(*this); o_ << code_.str(); o_ << misc::dedentendl; o_ << "}" << misc::iendl; } void CodeGenerator::operator()(ast::FunctionDec& ast) { // Generating all functions prototypes for (auto proto : ast.to_generate_get()) { ast.type_set(proto); code_ << ast.type_get()->return_type_get()->cpp_type() << " " << ast.name_get() << "("; params_ = true; if (ast.args_get()) ast.args_get()->accept(*this); params_ = false; code_ << ")" << misc::iendl << "{" << misc::indentendl; ast.body_get()->accept(*this); code_ << misc::dedentendl << "}" << misc::iendl; } } void CodeGenerator::operator()(ast::IdVar& ast) { if (params_) code_ << ast.type_get()->cpp_type() << " "; code_ << ast.id_get(); } void CodeGenerator::operator()(ast::AssignExpr& ast) { if (!ast.def_get()) { params_ = true; ast.lvalue_get()->accept(*this); params_ = false; } else ast.lvalue_get()->accept(*this); code_ << " = "; ast.rvalue_get()->accept(*this); } void CodeGenerator::operator()(ast::StringExpr& ast) { code_ << "new __repy_string(\"" << ast.str_get() << "\")"; } void CodeGenerator::operator()(ast::NumeralExpr& ast) { code_ << ast.value_get(); } void CodeGenerator::operator()(ast::FunctionVar& ast) { ast.var_get()->accept(*this); code_ << "("; if (ast.params_get()) ast.params_get()->accept(*this); code_ << ")"; } } // namespace cpp
Add variable type on the first declaration
[CGENERATOR] Add variable type on the first declaration
C++
mit
Nakrez/RePy,Nakrez/RePy
a28f2386902505ba1b45c173d13bb060012eaf47
chrome/test/startup/startup_test.cc
chrome/test/startup/startup_test.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/string_util.h" #include "base/test_file_util.h" #include "base/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" using base::TimeDelta; using base::TimeTicks; namespace { class StartupTest : public UITest { public: StartupTest() { show_window_ = true; pages_ = "about:blank"; } void SetUp() {} void TearDown() {} void RunStartupTest(const char* graph, const char* trace, bool test_cold, bool important, int profile_type) { const int kNumCyclesMax = 20; int numCycles = kNumCyclesMax; // It's ok for unit test code to use getenv(), isn't it? #if defined(OS_WIN) #pragma warning( disable : 4996 ) #endif const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES"); if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles)) LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, " << "so setting numCycles to " << numCycles; TimeDelta timings[kNumCyclesMax]; for (int i = 0; i < numCycles; ++i) { if (test_cold) { FilePath dir_app; ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app)); FilePath chrome_exe(dir_app.Append( FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath))); ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe)); #if defined(OS_WIN) // chrome.dll is windows specific. FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll"))); ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll)); #endif #if defined(OS_WIN) // TODO(port): Re-enable once gears is working on mac/linux. FilePath gears_dll; ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll)); ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll)); #else NOTIMPLEMENTED() << "gears not enabled yet"; #endif } // Sets the profile data for the run. For now, this is only used for // the complex theme test. if (profile_type == UITest::COMPLEX_THEME) set_template_user_data(UITest::ComputeTypicalUserDataSource( profile_type).ToWStringHack()); UITest::SetUp(); TimeTicks end_time = TimeTicks::Now(); timings[i] = end_time - browser_launch_time_; // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we // do, we crash. PlatformThread::Sleep(50); UITest::TearDown(); if (i == 0) { // Re-use the profile data after first run so that the noise from // creating databases doesn't impact all the runs. clear_profile_ = false; } } std::string times; for (int i = 0; i < numCycles; ++i) StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); PrintResultList(graph, "", trace, times, "ms", important); } protected: std::string pages_; }; class StartupReferenceTest : public StartupTest { public: // override the browser directory that is used by UITest::SetUp to cause it // to use the reference build instead. void SetUp() { FilePath dir; PathService::Get(chrome::DIR_TEST_TOOLS, &dir); dir = dir.AppendASCII("reference_build"); #if defined(OS_WIN) dir = dir.AppendASCII("chrome"); #elif defined(OS_LINUX) dir = dir.AppendASCII("chrome_linux"); #elif defined(OS_MACOSX) dir = dir.AppendASCII("chrome_mac"); #endif browser_directory_ = dir; } }; class StartupFileTest : public StartupTest { public: // Load a file on startup rather than about:blank. This tests a longer // startup path, including resource loading and the loading of gears.dll. void SetUp() { FilePath file_url; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url)); file_url = file_url.AppendASCII("empty.html"); ASSERT_TRUE(file_util::PathExists(file_url)); launch_arguments_.AppendLooseValue(file_url.ToWStringHack()); pages_ = WideToUTF8(file_url.ToWStringHack()); } }; TEST_F(StartupTest, Perf) { RunStartupTest("warm", "t", false /* not cold */, true /* important */, UITest::DEFAULT_THEME); } // TODO(port): We need a mac reference build checked in for this. TEST_F(StartupReferenceTest, Perf) { RunStartupTest("warm", "t_ref", false /* not cold */, true /* important */, UITest::DEFAULT_THEME); } // TODO(mpcomplete): Should we have reference timings for all these? TEST_F(StartupTest, PerfCold) { RunStartupTest("cold", "t", true /* cold */, false /* not important */, UITest::DEFAULT_THEME); } #if defined(OS_WIN) // TODO(port): Enable gears tests on linux/mac once gears is working. TEST_F(StartupFileTest, PerfGears) { RunStartupTest("warm", "gears", false /* not cold */, false /* not important */, UITest::DEFAULT_THEME); } TEST_F(StartupFileTest, PerfColdGears) { RunStartupTest("cold", "gears", true /* cold */, false /* not important */, UITest::DEFAULT_THEME); } #endif //TEST_F(StartupTest, PerfColdComplexTheme) { // RunStartupTest("warm", "t-theme", false /* warm */, // false /* not important */, UITest::COMPLEX_THEME); } } // namespace
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/string_util.h" #include "base/test_file_util.h" #include "base/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" using base::TimeDelta; using base::TimeTicks; namespace { class StartupTest : public UITest { public: StartupTest() { show_window_ = true; pages_ = "about:blank"; } void SetUp() {} void TearDown() {} void RunStartupTest(const char* graph, const char* trace, bool test_cold, bool important, int profile_type) { const int kNumCyclesMax = 20; int numCycles = kNumCyclesMax; // It's ok for unit test code to use getenv(), isn't it? #if defined(OS_WIN) #pragma warning( disable : 4996 ) #endif const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES"); if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles)) LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, " << "so setting numCycles to " << numCycles; TimeDelta timings[kNumCyclesMax]; for (int i = 0; i < numCycles; ++i) { if (test_cold) { FilePath dir_app; ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app)); FilePath chrome_exe(dir_app.Append( FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath))); ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe)); #if defined(OS_WIN) // chrome.dll is windows specific. FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll"))); ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll)); #endif #if defined(OS_WIN) // TODO(port): Re-enable once gears is working on mac/linux. FilePath gears_dll; ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll)); ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll)); #else NOTIMPLEMENTED() << "gears not enabled yet"; #endif } // Sets the profile data for the run. For now, this is only used for // the complex theme test. if (profile_type == UITest::COMPLEX_THEME) set_template_user_data(UITest::ComputeTypicalUserDataSource( profile_type).ToWStringHack()); UITest::SetUp(); TimeTicks end_time = TimeTicks::Now(); timings[i] = end_time - browser_launch_time_; // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we // do, we crash. PlatformThread::Sleep(50); UITest::TearDown(); if (i == 0) { // Re-use the profile data after first run so that the noise from // creating databases doesn't impact all the runs. clear_profile_ = false; } } std::string times; for (int i = 0; i < numCycles; ++i) StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); PrintResultList(graph, "", trace, times, "ms", important); } protected: std::string pages_; }; class StartupReferenceTest : public StartupTest { public: // override the browser directory that is used by UITest::SetUp to cause it // to use the reference build instead. void SetUp() { FilePath dir; PathService::Get(chrome::DIR_TEST_TOOLS, &dir); dir = dir.AppendASCII("reference_build"); #if defined(OS_WIN) dir = dir.AppendASCII("chrome"); #elif defined(OS_LINUX) dir = dir.AppendASCII("chrome_linux"); #elif defined(OS_MACOSX) dir = dir.AppendASCII("chrome_mac"); #endif browser_directory_ = dir; } }; class StartupFileTest : public StartupTest { public: // Load a file on startup rather than about:blank. This tests a longer // startup path, including resource loading and the loading of gears.dll. void SetUp() { FilePath file_url; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url)); file_url = file_url.AppendASCII("empty.html"); ASSERT_TRUE(file_util::PathExists(file_url)); launch_arguments_.AppendLooseValue(file_url.ToWStringHack()); pages_ = WideToUTF8(file_url.ToWStringHack()); } }; TEST_F(StartupTest, Perf) { RunStartupTest("warm", "t", false /* not cold */, true /* important */, UITest::DEFAULT_THEME); } // TODO(port): We need a mac reference build checked in for this. TEST_F(StartupReferenceTest, Perf) { RunStartupTest("warm", "t_ref", false /* not cold */, true /* important */, UITest::DEFAULT_THEME); } // TODO(mpcomplete): Should we have reference timings for all these? TEST_F(StartupTest, PerfCold) { RunStartupTest("cold", "t", true /* cold */, false /* not important */, UITest::DEFAULT_THEME); } #if defined(OS_WIN) // TODO(port): Enable gears tests on linux/mac once gears is working. TEST_F(StartupFileTest, PerfGears) { RunStartupTest("warm", "gears", false /* not cold */, false /* not important */, UITest::DEFAULT_THEME); } TEST_F(StartupFileTest, PerfColdGears) { RunStartupTest("cold", "gears", true /* cold */, false /* not important */, UITest::DEFAULT_THEME); } #endif //TEST_F(StartupTest, PerfColdComplexTheme) { // RunStartupTest("warm", "t-theme", false /* warm */, // false /* not important */, UITest::COMPLEX_THEME); //} } // namespace
Fix startup test error for now.
Fix startup test error for now. Review URL: http://codereview.chromium.org/164267 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@22937 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
3b155821bb1487ceece6bac9fb32cb4fb357fd97
test/integration/overload_integration_test.cc
test/integration/overload_integration_test.cc
#include <unordered_map> #include "envoy/config/bootstrap/v3/bootstrap.pb.h" #include "envoy/config/overload/v3/overload.pb.h" #include "envoy/server/resource_monitor.h" #include "envoy/server/resource_monitor_config.h" #include "test/common/config/dummy_config.pb.h" #include "test/integration/http_protocol_integration.h" #include "test/test_common/registry.h" #include "absl/strings/str_cat.h" namespace Envoy { class FakeResourceMonitorFactory; class FakeResourceMonitor : public Server::ResourceMonitor { public: FakeResourceMonitor(Event::Dispatcher& dispatcher, FakeResourceMonitorFactory& factory) : dispatcher_(dispatcher), factory_(factory), pressure_(0.0) {} ~FakeResourceMonitor() override; void updateResourceUsage(Callbacks& callbacks) override; void setResourcePressure(double pressure) { dispatcher_.post([this, pressure] { pressure_ = pressure; }); } private: Event::Dispatcher& dispatcher_; FakeResourceMonitorFactory& factory_; double pressure_; }; class FakeResourceMonitorFactory : public Server::Configuration::ResourceMonitorFactory { public: FakeResourceMonitor* monitor() const { return monitor_; } Server::ResourceMonitorPtr createResourceMonitor(const Protobuf::Message& config, Server::Configuration::ResourceMonitorFactoryContext& context) override; ProtobufTypes::MessagePtr createEmptyConfigProto() override { return std::make_unique<test::common::config::DummyConfig>(); } std::string name() const override { return "envoy.resource_monitors.testonly.fake_resource_monitor"; } void onMonitorDestroyed(FakeResourceMonitor* monitor); private: FakeResourceMonitor* monitor_{nullptr}; }; FakeResourceMonitor::~FakeResourceMonitor() { factory_.onMonitorDestroyed(this); } void FakeResourceMonitor::updateResourceUsage(Callbacks& callbacks) { Server::ResourceUsage usage; usage.resource_pressure_ = pressure_; callbacks.onSuccess(usage); } void FakeResourceMonitorFactory::onMonitorDestroyed(FakeResourceMonitor* monitor) { ASSERT(monitor_ == monitor); monitor_ = nullptr; } Server::ResourceMonitorPtr FakeResourceMonitorFactory::createResourceMonitor( const Protobuf::Message&, Server::Configuration::ResourceMonitorFactoryContext& context) { auto monitor = std::make_unique<FakeResourceMonitor>(context.dispatcher(), *this); monitor_ = monitor.get(); return monitor; } class OverloadIntegrationTest : public HttpProtocolIntegrationTest { protected: void initializeOverloadManager(const envoy::config::overload::v3::OverloadAction& overload_action) { const std::string overload_config = R"EOF( refresh_interval: seconds: 0 nanos: 1000000 resource_monitors: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" typed_config: "@type": type.googleapis.com/google.protobuf.Empty )EOF"; envoy::config::overload::v3::OverloadManager overload_manager_config = TestUtility::parseYaml<envoy::config::overload::v3::OverloadManager>(overload_config); *overload_manager_config.add_actions() = overload_action; config_helper_.addConfigModifier( [overload_manager_config](envoy::config::bootstrap::v3::Bootstrap& bootstrap) { *bootstrap.mutable_overload_manager() = overload_manager_config; }); initialize(); updateResource(0); } void updateResource(double pressure) { auto* monitor = fake_resource_monitor_factory_.monitor(); ASSERT(monitor != nullptr); monitor->setResourcePressure(pressure); } FakeResourceMonitorFactory fake_resource_monitor_factory_; Registry::InjectFactory<Server::Configuration::ResourceMonitorFactory> inject_factory_{ fake_resource_monitor_factory_}; }; INSTANTIATE_TEST_SUITE_P(Protocols, OverloadIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(OverloadIntegrationTest, CloseStreamsWhenOverloaded) { initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.stop_accepting_requests" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" threshold: value: 0.9 )EOF")); // Put envoy in overloaded state and check that it drops new requests. // Test both header-only and header+body requests since the code paths are slightly different. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_requests.active", 1); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); auto response = codec_client_->makeRequestWithBody(request_headers, 10); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("503", response->headers().getStatusValue()); EXPECT_EQ("envoy overloaded", response->body()); codec_client_->close(); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); response = codec_client_->makeHeaderOnlyRequest(request_headers); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("503", response->headers().getStatusValue()); EXPECT_EQ("envoy overloaded", response->body()); codec_client_->close(); // Deactivate overload state and check that new requests are accepted. updateResource(0.8); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_requests.active", 0); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0); EXPECT_TRUE(upstream_request_->complete()); EXPECT_EQ(0U, upstream_request_->bodyLength()); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ(0U, response->body().size()); } TEST_P(OverloadIntegrationTest, DisableKeepaliveWhenOverloaded) { if (downstreamProtocol() != Http::CodecClient::Type::HTTP1) { return; // only relevant for downstream HTTP1.x connections } initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.disable_http_keepalive" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" threshold: value: 0.8 )EOF")); // Put envoy in overloaded state and check that it disables keepalive updateResource(0.8); test_server_->waitForGaugeEq("overload.envoy.overload_actions.disable_http_keepalive.active", 1); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; auto response = sendRequestAndWaitForResponse(request_headers, 1, default_response_headers_, 1); ASSERT_TRUE(codec_client_->waitForDisconnect()); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ("close", response->headers().getConnectionValue()); // Deactivate overload state and check that keepalive is not disabled updateResource(0.7); test_server_->waitForGaugeEq("overload.envoy.overload_actions.disable_http_keepalive.active", 0); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); response = sendRequestAndWaitForResponse(request_headers, 1, default_response_headers_, 1); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ(nullptr, response->headers().Connection()); } TEST_P(OverloadIntegrationTest, StopAcceptingConnectionsWhenOverloaded) { initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.stop_accepting_connections" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" threshold: value: 0.95 )EOF")); // Put envoy in overloaded state and check that it doesn't accept the new client connection. updateResource(0.95); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_connections.active", 1); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; auto response = codec_client_->makeRequestWithBody(request_headers, 10); EXPECT_FALSE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_, std::chrono::milliseconds(1000))); // Reduce load a little to allow the connection to be accepted. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_connections.active", 0); EXPECT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); EXPECT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForHeadersComplete()); ASSERT_TRUE(upstream_request_->waitForData(*dispatcher_, 10)); upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "202"}}, true); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("202", response->headers().getStatusValue()); codec_client_->close(); } class OverloadScaledTimerIntegrationTest : public OverloadIntegrationTest { protected: void initializeOverloadManager( const envoy::config::overload::v3::ScaleTimersOverloadActionConfig& config) { envoy::config::overload::v3::OverloadAction overload_action = TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.reduce_timeouts" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" scaled: scaling_threshold: 0.5 saturation_threshold: 0.9 )EOF"); overload_action.mutable_typed_config()->PackFrom(config); OverloadIntegrationTest::initializeOverloadManager(overload_action); } }; INSTANTIATE_TEST_SUITE_P(Protocols, OverloadScaledTimerIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(OverloadScaledTimerIntegrationTest, CloseIdleHttpConnections) { initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::ScaleTimersOverloadActionConfig>(R"EOF( timer_scale_factors: - timer: HTTP_DOWNSTREAM_CONNECTION_IDLE min_timeout: 5s )EOF")); const Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; // Create an HTTP connection and complete a request. FakeStreamPtr http_stream; codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); auto response = codec_client_->makeRequestWithBody(request_headers, 10); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, http_stream)); ASSERT_TRUE(http_stream->waitForHeadersComplete()); ASSERT_TRUE(http_stream->waitForData(*dispatcher_, 10)); http_stream->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true); response->waitForEndStream(); // At this point, the connection should be idle but still open. ASSERT_TRUE(codec_client_->connected()); // Set the load so the timer is reduced but not to the minimum value. updateResource(0.8); test_server_->waitForGaugeGe("overload.envoy.overload_actions.reduce_timeouts.scale_percent", 50); // Advancing past the minimum time shouldn't close the connection. timeSystem().advanceTimeWait(std::chrono::seconds(5)); // Increase load so that the minimum time has now elapsed. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.reduce_timeouts.scale_percent", 100); // Wait for the proxy to notice and take action for the overload. test_server_->waitForCounterGe("http.config_test.downstream_cx_idle_timeout", 1); dispatcher_->run(Event::Dispatcher::RunType::NonBlock); if (GetParam().downstream_protocol == Http::CodecClient::Type::HTTP1) { // For HTTP1, Envoy will start draining but will wait to close the // connection. If a new stream comes in, it will set the connection header // to "close" on the response and close the connection after. auto response = codec_client_->makeRequestWithBody(request_headers, 10); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, http_stream)); ASSERT_TRUE(http_stream->waitForHeadersComplete()); ASSERT_TRUE(http_stream->waitForData(*dispatcher_, 10)); response->waitForEndStream(); EXPECT_EQ(response->headers().getConnectionValue(), "close"); } else { EXPECT_TRUE(codec_client_->sawGoAway()); } http_stream.reset(); codec_client_->close(); } } // namespace Envoy
#include <unordered_map> #include "envoy/config/bootstrap/v3/bootstrap.pb.h" #include "envoy/config/overload/v3/overload.pb.h" #include "envoy/server/resource_monitor.h" #include "envoy/server/resource_monitor_config.h" #include "test/common/config/dummy_config.pb.h" #include "test/integration/http_protocol_integration.h" #include "test/test_common/registry.h" #include "absl/strings/str_cat.h" namespace Envoy { class FakeResourceMonitorFactory; class FakeResourceMonitor : public Server::ResourceMonitor { public: FakeResourceMonitor(Event::Dispatcher& dispatcher, FakeResourceMonitorFactory& factory) : dispatcher_(dispatcher), factory_(factory), pressure_(0.0) {} ~FakeResourceMonitor() override; void updateResourceUsage(Callbacks& callbacks) override; void setResourcePressure(double pressure) { dispatcher_.post([this, pressure] { pressure_ = pressure; }); } private: Event::Dispatcher& dispatcher_; FakeResourceMonitorFactory& factory_; double pressure_; }; class FakeResourceMonitorFactory : public Server::Configuration::ResourceMonitorFactory { public: FakeResourceMonitor* monitor() const { return monitor_; } Server::ResourceMonitorPtr createResourceMonitor(const Protobuf::Message& config, Server::Configuration::ResourceMonitorFactoryContext& context) override; ProtobufTypes::MessagePtr createEmptyConfigProto() override { return std::make_unique<test::common::config::DummyConfig>(); } std::string name() const override { return "envoy.resource_monitors.testonly.fake_resource_monitor"; } void onMonitorDestroyed(FakeResourceMonitor* monitor); private: FakeResourceMonitor* monitor_{nullptr}; }; FakeResourceMonitor::~FakeResourceMonitor() { factory_.onMonitorDestroyed(this); } void FakeResourceMonitor::updateResourceUsage(Callbacks& callbacks) { Server::ResourceUsage usage; usage.resource_pressure_ = pressure_; callbacks.onSuccess(usage); } void FakeResourceMonitorFactory::onMonitorDestroyed(FakeResourceMonitor* monitor) { ASSERT(monitor_ == monitor); monitor_ = nullptr; } Server::ResourceMonitorPtr FakeResourceMonitorFactory::createResourceMonitor( const Protobuf::Message&, Server::Configuration::ResourceMonitorFactoryContext& context) { auto monitor = std::make_unique<FakeResourceMonitor>(context.dispatcher(), *this); monitor_ = monitor.get(); return monitor; } class OverloadIntegrationTest : public HttpProtocolIntegrationTest { protected: void initializeOverloadManager(const envoy::config::overload::v3::OverloadAction& overload_action) { const std::string overload_config = R"EOF( refresh_interval: seconds: 0 nanos: 1000000 resource_monitors: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" typed_config: "@type": type.googleapis.com/google.protobuf.Empty )EOF"; envoy::config::overload::v3::OverloadManager overload_manager_config = TestUtility::parseYaml<envoy::config::overload::v3::OverloadManager>(overload_config); *overload_manager_config.add_actions() = overload_action; config_helper_.addConfigModifier( [overload_manager_config](envoy::config::bootstrap::v3::Bootstrap& bootstrap) { *bootstrap.mutable_overload_manager() = overload_manager_config; }); initialize(); updateResource(0); } void updateResource(double pressure) { auto* monitor = fake_resource_monitor_factory_.monitor(); ASSERT(monitor != nullptr); monitor->setResourcePressure(pressure); } FakeResourceMonitorFactory fake_resource_monitor_factory_; Registry::InjectFactory<Server::Configuration::ResourceMonitorFactory> inject_factory_{ fake_resource_monitor_factory_}; }; INSTANTIATE_TEST_SUITE_P(Protocols, OverloadIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(OverloadIntegrationTest, CloseStreamsWhenOverloaded) { initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.stop_accepting_requests" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" threshold: value: 0.9 )EOF")); // Put envoy in overloaded state and check that it drops new requests. // Test both header-only and header+body requests since the code paths are slightly different. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_requests.active", 1); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); auto response = codec_client_->makeRequestWithBody(request_headers, 10); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("503", response->headers().getStatusValue()); EXPECT_EQ("envoy overloaded", response->body()); codec_client_->close(); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); response = codec_client_->makeHeaderOnlyRequest(request_headers); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("503", response->headers().getStatusValue()); EXPECT_EQ("envoy overloaded", response->body()); codec_client_->close(); // Deactivate overload state and check that new requests are accepted. updateResource(0.8); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_requests.active", 0); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0); EXPECT_TRUE(upstream_request_->complete()); EXPECT_EQ(0U, upstream_request_->bodyLength()); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ(0U, response->body().size()); } TEST_P(OverloadIntegrationTest, DisableKeepaliveWhenOverloaded) { if (downstreamProtocol() != Http::CodecClient::Type::HTTP1) { return; // only relevant for downstream HTTP1.x connections } initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.disable_http_keepalive" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" threshold: value: 0.8 )EOF")); // Put envoy in overloaded state and check that it disables keepalive updateResource(0.8); test_server_->waitForGaugeEq("overload.envoy.overload_actions.disable_http_keepalive.active", 1); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; auto response = sendRequestAndWaitForResponse(request_headers, 1, default_response_headers_, 1); ASSERT_TRUE(codec_client_->waitForDisconnect()); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ("close", response->headers().getConnectionValue()); // Deactivate overload state and check that keepalive is not disabled updateResource(0.7); test_server_->waitForGaugeEq("overload.envoy.overload_actions.disable_http_keepalive.active", 0); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); response = sendRequestAndWaitForResponse(request_headers, 1, default_response_headers_, 1); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ(nullptr, response->headers().Connection()); } TEST_P(OverloadIntegrationTest, StopAcceptingConnectionsWhenOverloaded) { initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.stop_accepting_connections" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" threshold: value: 0.95 )EOF")); // Put envoy in overloaded state and check that it doesn't accept the new client connection. updateResource(0.95); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_connections.active", 1); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; auto response = codec_client_->makeRequestWithBody(request_headers, 10); EXPECT_FALSE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_, std::chrono::milliseconds(1000))); // Reduce load a little to allow the connection to be accepted. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_connections.active", 0); EXPECT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); EXPECT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForHeadersComplete()); ASSERT_TRUE(upstream_request_->waitForData(*dispatcher_, 10)); upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "202"}}, true); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("202", response->headers().getStatusValue()); codec_client_->close(); } class OverloadScaledTimerIntegrationTest : public OverloadIntegrationTest { protected: void initializeOverloadManager( const envoy::config::overload::v3::ScaleTimersOverloadActionConfig& config) { envoy::config::overload::v3::OverloadAction overload_action = TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF( name: "envoy.overload_actions.reduce_timeouts" triggers: - name: "envoy.resource_monitors.testonly.fake_resource_monitor" scaled: scaling_threshold: 0.5 saturation_threshold: 0.9 )EOF"); overload_action.mutable_typed_config()->PackFrom(config); OverloadIntegrationTest::initializeOverloadManager(overload_action); } }; INSTANTIATE_TEST_SUITE_P(Protocols, OverloadScaledTimerIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(OverloadScaledTimerIntegrationTest, CloseIdleHttpConnections) { initializeOverloadManager( TestUtility::parseYaml<envoy::config::overload::v3::ScaleTimersOverloadActionConfig>(R"EOF( timer_scale_factors: - timer: HTTP_DOWNSTREAM_CONNECTION_IDLE min_timeout: 5s )EOF")); const Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}; // Create an HTTP connection and complete a request. codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); auto response = codec_client_->makeRequestWithBody(request_headers, 10); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForHeadersComplete()); ASSERT_TRUE(upstream_request_->waitForData(*dispatcher_, 10)); upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true); response->waitForEndStream(); // At this point, the connection should be idle but still open. ASSERT_TRUE(codec_client_->connected()); // Set the load so the timer is reduced but not to the minimum value. updateResource(0.8); test_server_->waitForGaugeGe("overload.envoy.overload_actions.reduce_timeouts.scale_percent", 50); // Advancing past the minimum time shouldn't close the connection. timeSystem().advanceTimeWait(std::chrono::seconds(5)); // Increase load so that the minimum time has now elapsed. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.reduce_timeouts.scale_percent", 100); // Wait for the proxy to notice and take action for the overload. test_server_->waitForCounterGe("http.config_test.downstream_cx_idle_timeout", 1); dispatcher_->run(Event::Dispatcher::RunType::NonBlock); if (GetParam().downstream_protocol == Http::CodecClient::Type::HTTP1) { // For HTTP1, Envoy will start draining but will wait to close the // connection. If a new stream comes in, it will set the connection header // to "close" on the response and close the connection after. auto response = codec_client_->makeRequestWithBody(request_headers, 10); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForHeadersComplete()); ASSERT_TRUE(upstream_request_->waitForData(*dispatcher_, 10)); response->waitForEndStream(); EXPECT_EQ(response->headers().getConnectionValue(), "close"); } else { EXPECT_TRUE(codec_client_->sawGoAway()); } codec_client_->close(); } } // namespace Envoy
Fix TSAN bug in integration test (#14327)
Fix TSAN bug in integration test (#14327) Don't delete the HTTP stream prematurely. Signed-off-by: Alex Konradi <[email protected]>
C++
apache-2.0
lyft/envoy,envoyproxy/envoy,lyft/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy
a11caa7aa9e6241b0a78b06114b068ac47a04903
src/ultracomm.cpp
src/ultracomm.cpp
#include "StdAfx.h" #define BUFFERSIZE (2 * 1024 * 1024) char gBuffer[BUFFERSIZE]; #define PROBE_ID 19 // TODO: remove hard-coding of probe id /* Construct Ultracomm object, connect to server, and set/check parameters. */ Ultracomm::Ultracomm(const UltracommOptions& myuopt) : uopt(myuopt), address(myuopt.opt["address"].as<string>()), datatype(myuopt.opt["datatype"].as<int>()) { connect(); ult.setDataToAcquire(datatype); set_int_imaging_params(); check_int_imaging_params(); } /* Connect to the Ultrasonix. */ void Ultracomm::connect() { if (!ult.connect(address.c_str())) { throw ConnectionError(); } /* TODO: throw different errors depending on problem. Note that FD_CONNECT error is when server address is bad (e.g. 123), and SOCKET_ERROR is when we couldn't connect (address good but not in research mode). Should also test when address is good but ultrasound machine not running): C:\build\ultracomm\bin\Debug>ultracomm --address 123 --output asdf monitorConnection(): FD_CONNECT had ERROR Could not connect to Ultrasonix. C:\build\ultracomm\bin\Debug>ultracomm --address 192.168.1.200 --output asdf monitorConnection(): WSAEnumNetworkEvents() ret SOCKET_ERROR (10093) CmonitorConnection(): CONNECTION_COMM lost ould not connect to Ultrasonix. */ } /* Disconnect from Ultrasonix. */ void Ultracomm::disconnect() { if (ult.isConnected()) { ult.disconnect(); } } /* Put Ultrasonix into freeze state and wait for confirmation. */ void Ultracomm::wait_for_freeze() { // 1 = FROZEN; 0 = IMAGING if (ult.getFreezeState() != 1) { ult.toggleFreeze(); } // Wait for server to acknowledge it has frozen. // TODO: this would be safer with a timeout. while (ult.getFreezeState() != 1) {} if (ult.getFreezeState() != 1) { // TODO: throw correct error throw ConnectionError(); } ult.setCompressionStatus(1); } /* Put ultrasonix into imaging state. */ void Ultracomm::wait_for_unfreeze() { // 1 = FROZEN; 0 = IMAGING if (ult.getFreezeState() != 0) { ult.toggleFreeze(); } // Wait for server to acknowledge it has switched to imaging. // TODO: this would be safer with a timeout. while (ult.getFreezeState() != 0) {} if (ult.getFreezeState() != 0) { // TODO: throw correct error throw ConnectionError(); } } /* Set all integer-type Ultrasonix imaging parameters, as specified on the command line or in the parameter file. */ void Ultracomm::set_int_imaging_params() { po::variables_map params = uopt.opt; po::options_description iopts = uopt.int_params; for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter) { /* Ultracomm program options do not contain spaces. Some of the parameters used by the ulterius setParamValue() call do contain spaces, and none appear to use underscore. The convention is that ultracomm program options containing underscore correspond to ulterius parameters that have the same name, but with the underscores replaced with spaces (' '). optname: the name as used in ultracomm program options (underscores) ultname: the name as used by ulterius setParamValue() (spaces) */ string optname = (*iter)->long_name(); if (params.count(optname)) { int val = params[optname].as<int>(); string ultname = boost::replace_all_copy(optname, "_", " "); ult.setParamValue(ultname.c_str(), val); } } } /* Verify that integer-type Ultrasonix imaging parameters have value as specified by user. */ void Ultracomm::check_int_imaging_params() { po::variables_map params = uopt.opt; if (params.count("b-depth")) { int val; ult.getParamValue("b-depth", val); if (val != params["b-depth"].as<int>()) { throw ParameterMismatchError(); } } } /* Get data from Ultrasonix and save to file. */ void Ultracomm::save_data() { po::variables_map params = uopt.opt; const string outname = params["output"].as<string>(); int num_frames = ult.getCineDataCount((uData)datatype); uDataDesc desc; if (! ult.getDataDescriptor((uData)datatype, desc)) { throw DataDescriptorError(); } if (! ult.isDataAvailable((uData)datatype)) { throw DataError(); } ofstream outfile (outname, ios::out | ios::binary); write_header(outfile, desc, num_frames); // TODO: figure out why buffer and sz makes program crash //const int sz = 2 * 1024 * 1024; //char buffer[BUFFERSIZE]; // TODO: determine appropriate sizes on the fly // int num_frames = ult.getCineDataCount((uData)datatype); // TODO: framesize assumes desc.ss is always a multiple of 8, and that might not be safe. int framesize = (desc.ss / 8) * desc.w * desc.h; for (int idx = 0; idx < num_frames; idx++) { ult.getCineData((uData)datatype, idx, false, (char**)&gBuffer, BUFFERSIZE); outfile.write(gBuffer, framesize); } outfile.close(); } /* TODO: header information is probably correct for .bpr files but probably not for other datatypes. */ void Ultracomm::write_header(ofstream& outfile, const uDataDesc& desc, const int& num_frames) { int isize = sizeof(__int32); outfile.write(reinterpret_cast<const char *>(&(__int32)datatype), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)num_frames), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.w), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.h), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.ss), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.ulx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.uly), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.urx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.ury), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.brx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.bry), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.blx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.bly), isize); int probe_id = PROBE_ID; outfile.write(reinterpret_cast<const char *>(&(__int32)probe_id), isize); int txf; ult.getParamValue("b-freq", txf); outfile.write(reinterpret_cast<const char *>(&(__int32)txf), isize); int sf; ult.getParamValue("vec-freq", sf); // TODO: this gives 4000000 instead of 8000000 sf = 8000000; outfile.write(reinterpret_cast<const char *>(&(__int32)sf), isize); int dr; ult.getParamValue("frame rate", dr); outfile.write(reinterpret_cast<const char *>(&(__int32)dr), isize); int ld; ult.getParamValue("b-ldensity", ld); outfile.write(reinterpret_cast<const char *>(&(__int32)ld), isize); int extra; //ult.getParamValue("color-ensemble", extra); extra = 0; // TODO: figure out what goes here outfile.write(reinterpret_cast<const char *>(&(__int32)extra), isize); }
#include "StdAfx.h" #define BUFFERSIZE (2 * 1024 * 1024) char gBuffer[BUFFERSIZE]; #define PROBE_ID 19 // TODO: remove hard-coding of probe id /* Construct Ultracomm object, connect to server, and set/check parameters. */ Ultracomm::Ultracomm(const UltracommOptions& myuopt) : uopt(myuopt), address(myuopt.opt["address"].as<string>()), datatype(myuopt.opt["datatype"].as<int>()) { connect(); ult.setDataToAcquire(datatype); set_int_imaging_params(); check_int_imaging_params(); } /* Connect to the Ultrasonix. */ void Ultracomm::connect() { if (!ult.connect(address.c_str())) { throw ConnectionError(); } /* TODO: throw different errors depending on problem. Note that FD_CONNECT error is when server address is bad (e.g. 123), and SOCKET_ERROR is when we couldn't connect (address good but not in research mode). Should also test when address is good but ultrasound machine not running): C:\build\ultracomm\bin\Debug>ultracomm --address 123 --output asdf monitorConnection(): FD_CONNECT had ERROR Could not connect to Ultrasonix. C:\build\ultracomm\bin\Debug>ultracomm --address 192.168.1.200 --output asdf monitorConnection(): WSAEnumNetworkEvents() ret SOCKET_ERROR (10093) CmonitorConnection(): CONNECTION_COMM lost ould not connect to Ultrasonix. */ } /* Disconnect from Ultrasonix. */ void Ultracomm::disconnect() { if (ult.isConnected()) { ult.disconnect(); } } /* Put Ultrasonix into freeze state and wait for confirmation. */ void Ultracomm::wait_for_freeze() { // 1 = FROZEN; 0 = IMAGING if (ult.getFreezeState() != 1) { ult.toggleFreeze(); } // Wait for server to acknowledge it has frozen. // TODO: this would be safer with a timeout. while (ult.getFreezeState() != 1) {} ult.setCompressionStatus(1); } /* Put ultrasonix into imaging state. */ void Ultracomm::wait_for_unfreeze() { // 1 = FROZEN; 0 = IMAGING if (ult.getFreezeState() != 0) { ult.toggleFreeze(); } // Wait for server to acknowledge it has switched to imaging. // TODO: this would be safer with a timeout. while (ult.getFreezeState() != 0) {} } /* Set all integer-type Ultrasonix imaging parameters, as specified on the command line or in the parameter file. */ void Ultracomm::set_int_imaging_params() { po::variables_map params = uopt.opt; po::options_description iopts = uopt.int_params; for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter) { /* Ultracomm program options do not contain spaces. Some of the parameters used by the ulterius setParamValue() call do contain spaces, and none appear to use underscore. The convention is that ultracomm program options containing underscore correspond to ulterius parameters that have the same name, but with the underscores replaced with spaces (' '). optname: the name as used in ultracomm program options (underscores) ultname: the name as used by ulterius setParamValue() (spaces) */ string optname = (*iter)->long_name(); if (params.count(optname)) { int val = params[optname].as<int>(); string ultname = boost::replace_all_copy(optname, "_", " "); ult.setParamValue(ultname.c_str(), val); } } } /* Verify that integer-type Ultrasonix imaging parameters have value as specified by user. */ void Ultracomm::check_int_imaging_params() { po::variables_map params = uopt.opt; if (params.count("b-depth")) { int val; ult.getParamValue("b-depth", val); if (val != params["b-depth"].as<int>()) { throw ParameterMismatchError(); } } } /* Get data from Ultrasonix and save to file. */ void Ultracomm::save_data() { po::variables_map params = uopt.opt; const string outname = params["output"].as<string>(); int num_frames = ult.getCineDataCount((uData)datatype); uDataDesc desc; if (! ult.getDataDescriptor((uData)datatype, desc)) { throw DataDescriptorError(); } if (! ult.isDataAvailable((uData)datatype)) { throw DataError(); } ofstream outfile (outname, ios::out | ios::binary); write_header(outfile, desc, num_frames); // TODO: figure out why buffer and sz makes program crash //const int sz = 2 * 1024 * 1024; //char buffer[BUFFERSIZE]; // TODO: determine appropriate sizes on the fly // int num_frames = ult.getCineDataCount((uData)datatype); // TODO: framesize assumes desc.ss is always a multiple of 8, and that might not be safe. int framesize = (desc.ss / 8) * desc.w * desc.h; for (int idx = 0; idx < num_frames; idx++) { ult.getCineData((uData)datatype, idx, false, (char**)&gBuffer, BUFFERSIZE); outfile.write(gBuffer, framesize); } outfile.close(); } /* TODO: header information is probably correct for .bpr files but probably not for other datatypes. */ void Ultracomm::write_header(ofstream& outfile, const uDataDesc& desc, const int& num_frames) { int isize = sizeof(__int32); outfile.write(reinterpret_cast<const char *>(&(__int32)datatype), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)num_frames), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.w), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.h), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.ss), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.ulx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.uly), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.urx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.ury), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.brx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.bry), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.blx), isize); outfile.write(reinterpret_cast<const char *>(&(__int32)desc.roi.bly), isize); int probe_id = PROBE_ID; outfile.write(reinterpret_cast<const char *>(&(__int32)probe_id), isize); int txf; ult.getParamValue("b-freq", txf); outfile.write(reinterpret_cast<const char *>(&(__int32)txf), isize); int sf; ult.getParamValue("vec-freq", sf); // TODO: this gives 4000000 instead of 8000000 sf = 8000000; outfile.write(reinterpret_cast<const char *>(&(__int32)sf), isize); int dr; ult.getParamValue("frame rate", dr); outfile.write(reinterpret_cast<const char *>(&(__int32)dr), isize); int ld; ult.getParamValue("b-ldensity", ld); outfile.write(reinterpret_cast<const char *>(&(__int32)ld), isize); int extra; //ult.getParamValue("color-ensemble", extra); extra = 0; // TODO: figure out what goes here outfile.write(reinterpret_cast<const char *>(&(__int32)extra), isize); }
Remove unnecessary checks.
Remove unnecessary checks.
C++
bsd-3-clause
rsprouse/ultracomm,rsprouse/ultracomm,rsprouse/ultracomm
97b0f8600e5052792207b26ac24cba7ef0ba8f1a
src/utilities.cpp
src/utilities.cpp
/* * Copyright (c) 2015-2016 Alex Spataru <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "utilities.h" #include <QTimer> #include <QDebug> #include <QScreen> #include <QSettings> #include <QClipboard> #include <QApplication> //------------------------------------------------------------------------------ // Windows hacks //------------------------------------------------------------------------------ #if defined Q_OS_WIN #include <pdh.h> #include <tchar.h> #include <windows.h> #include <windowsx.h> static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; static SYSTEM_POWER_STATUS power; #endif //------------------------------------------------------------------------------ // Mac OS hacks //------------------------------------------------------------------------------ #if defined Q_OS_MAC static const QString CPU_CMD = "bash -c \"ps -A -o %cpu | " "awk '{s+=$1} END {print s}'\""; static const QString BTY_CMD = "pmset -g batt"; static const QString PWR_CMD = "pmset -g batt"; #endif //------------------------------------------------------------------------------ // Linux hacks //------------------------------------------------------------------------------ #if defined Q_OS_LINUX #include <QFile> #include <QRegExp> static const QString BTY_CMD = "bash -c \"upower -i " "$(upower -e | grep 'BAT') | " "grep -E 'state|to\\ full|percentage'\""; static const QString PWR_CMD = "bash -c \"upower -i " "$(upower -e | grep 'BAT') | " "grep -E 'state|to\\ full|percentage'\""; #endif //------------------------------------------------------------------------------ // Ensure that application compiles even if OS is not supported //------------------------------------------------------------------------------ #if !defined Q_OS_WIN && !defined Q_OS_MAC && !defined Q_OS_LINUX static const QString CPU_CMD = ""; static const QString BTY_CMD = ""; static const QString PWR_CMD = ""; #endif //------------------------------------------------------------------------------ // Start class code //------------------------------------------------------------------------------ /** * Configures the class and nitializes the CPU querying process under Windows. */ Utilities::Utilities() { m_ratio = 0; m_cpuUsage = 0; m_batteryLevel = 0; m_connectedToAC = 0; m_settings = new QSettings (qApp->organizationName(), qApp->applicationName()); /* Read process data when they finish */ connect (&m_cpuProcess, SIGNAL (finished (int)), this, SLOT (readCpuUsageProcess (int))); connect (&m_batteryLevelProcess, SIGNAL (finished (int)), this, SLOT (readBatteryLevelProcess (int))); connect (&m_connectedToACProcess, SIGNAL (finished (int)), this, SLOT (readConnectedToACProcess (int))); /* Kill the probing processes when application quits */ connect (qApp, SIGNAL (aboutToQuit()), &m_cpuProcess, SLOT (kill())); connect (qApp, SIGNAL (aboutToQuit()), &m_batteryLevelProcess, SLOT (kill())); connect (qApp, SIGNAL (aboutToQuit()), &m_connectedToACProcess, SLOT (kill())); /* Configure Windows */ #if defined Q_OS_WIN PdhOpenQuery (0, 0, &cpuQuery); PdhAddCounter (cpuQuery, L"\\Processor(_Total)\\% Processor Time", 0, &cpuTotal); PdhCollectQueryData (cpuQuery); #endif /* Start loop */ updateCpuUsage(); updateBatteryLevel(); updateConnectedToAC(); } /** * Returns the auto-calculates scale ratio */ qreal Utilities::scaleRatio() { if (m_ratio < 1) calculateScaleRatio(); return m_ratio; } /** * Returns the current CPU usage (from 0 to 100) */ int Utilities::cpuUsage() { m_cpuUsage = abs (m_cpuUsage); if (m_cpuUsage <= 100) return m_cpuUsage; return 0; } /** * Returns the current battery level (from 0 to 100) */ int Utilities::batteryLevel() { m_batteryLevel = abs (m_batteryLevel); if (m_batteryLevel <= 100) return m_batteryLevel; return 0; } /** * Returns \c true if the computer is connected to a power source or the * battery is not discharging. */ bool Utilities::isConnectedToAC() { return m_connectedToAC; } /** * Copies the given \a data to the system clipboard */ void Utilities::copy (const QVariant& data) { qApp->clipboard()->setText (data.toString(), QClipboard::Clipboard); } /** * Enables or disables the autoscale feature. * \note The application must be restarted for changes to take effect */ void Utilities::setAutoScaleEnabled (const bool enabled) { m_settings->setValue ("AutoScale", enabled); } /** * Queries for the current CPU usage */ void Utilities::updateCpuUsage() { #if defined Q_OS_WIN PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData (cpuQuery); PdhGetFormattedCounterValue (cpuTotal, PDH_FMT_DOUBLE, 0, &counterVal); m_cpuUsage = static_cast<int> (counterVal.doubleValue); emit cpuUsageChanged(); #elif defined Q_OS_MAC m_cpuProcess.terminate(); m_cpuProcess.start (CPU_CMD, QIODevice::ReadOnly); #elif defined Q_OS_LINUX auto cpuJiffies = getCpuJiffies(); m_cpuUsage = (cpuJiffies.first - m_pastCpuJiffies.first) * 100 / (cpuJiffies.second - m_pastCpuJiffies.second); m_pastCpuJiffies = cpuJiffies; #endif QTimer::singleShot (1000, Qt::PreciseTimer, this, SLOT (updateCpuUsage())); } /** * Queries for the current battery level */ void Utilities::updateBatteryLevel() { #if defined Q_OS_WIN GetSystemPowerStatus (&power); m_batteryLevel = static_cast<int> (power.BatteryLifePercent); emit batteryLevelChanged(); #else m_batteryLevelProcess.terminate(); m_batteryLevelProcess.start (BTY_CMD, QIODevice::ReadOnly); #endif QTimer::singleShot (1000, Qt::PreciseTimer, this, SLOT (updateBatteryLevel())); } /** * Queries for the current AC power source status */ void Utilities::updateConnectedToAC() { #if defined Q_OS_WIN GetSystemPowerStatus (&power); m_connectedToAC = (power.ACLineStatus != 0); emit connectedToACChanged(); #else m_connectedToACProcess.terminate(); m_connectedToACProcess.start (PWR_CMD, QIODevice::ReadOnly); #endif QTimer::singleShot (1000, Qt::PreciseTimer, this, SLOT (updateConnectedToAC())); } /** * Calculates the scale factor to apply to the UI. * \note This function uses different procedures depending on the OS */ void Utilities::calculateScaleRatio() { bool enabled = m_settings->value ("AutoScale", true).toBool(); /* Get scale factor using OS-specific code */ #if defined Q_OS_WIN HDC screen = GetDC (Q_NULLPTR); m_ratio = (qreal) GetDeviceCaps (screen, LOGPIXELSX) / 96; ReleaseDC (Q_NULLPTR, screen); #elif defined Q_OS_LINUX m_ratio = qApp->primaryScreen()->physicalDotsPerInch() / 100; #endif /* Ensure that values between x.40 and x.65 round down to x.40 */ qreal decimals = m_ratio - (int) m_ratio; if (decimals >= 0.40 && decimals <= 0.65) m_ratio -= (decimals - 0.40); /* Ratio is too small to be useful to us */ if (!enabled || m_ratio < 1.2) m_ratio = 1; /* Brag about the obtained result */ qDebug() << "Scale factor set to:" << m_ratio; } /** * Reads the output of the process launched to get the CPU usage */ void Utilities::readCpuUsageProcess (int exit_code) { if (exit_code == EXIT_FAILURE) return; #if defined Q_OS_MAC m_cpuUsage = 0; m_cpuProcess.terminate(); QByteArray data = m_cpuProcess.readAll(); if (!data.isEmpty() && data.length() >= 2) { /* Parse the digits of the percentage */ int t = data.at (0) - '0'; // Tens int u = data.at (1) - '0'; // Units /* Check if process data is invalid */ if (t < 0) t = 0; if (u < 0) u = 0; /* Update information */ m_cpuUsage = (t * 10) + u; emit cpuUsageChanged(); } #endif } /** * Reads the output of the process launched to get the battery level */ void Utilities::readBatteryLevelProcess (int exit_code) { if (exit_code == EXIT_FAILURE) return; #if defined Q_OS_MAC || defined Q_OS_LINUX m_batteryLevel = 0; m_batteryLevelProcess.terminate(); QByteArray data = m_batteryLevelProcess.readAll(); if (!data.isEmpty()) { /* Parse the digits of the percentage */ int h = data.at (data.indexOf ("%") - 3) - '0'; // Hundreds int t = data.at (data.indexOf ("%") - 2) - '0'; // Tens int u = data.at (data.indexOf ("%") - 1) - '0'; // Units /* Check if process data is invalid */ if (h < 0) h = 0; if (t < 0) t = 0; if (u < 0) u = 0; /* Update information */ m_batteryLevel = (h * 100) + (t * 10) + u; emit batteryLevelChanged(); } #endif } /** * Reads the output of the process launched to get the AC power source status */ void Utilities::readConnectedToACProcess (int exit_code) { if (exit_code == EXIT_FAILURE) return; #if defined Q_OS_MAC || defined Q_OS_LINUX m_connectedToAC = false; m_connectedToACProcess.terminate(); QByteArray data = m_connectedToACProcess.readAll(); if (!data.isEmpty()) { m_connectedToAC = !data.contains ("discharging"); emit connectedToACChanged(); } #endif } #if defined Q_OS_LINUX /** * Reads the current count of CPU jiffies from /proc/stat and return a pair * consisting of non-idle jiffies and total jiffies */ QPair<quint64, quint64> Utilities::getCpuJiffies() { quint64 totalJiffies = 0; quint64 nonIdleJiffies = 0; QFile file ("/proc/stat"); if (file.open (QFile::ReadOnly)) { QString line = file.readLine(); QStringList jiffies = line.replace ("cpu ", "").split (" "); if (jiffies.count() > 3) { nonIdleJiffies = jiffies.at (0).toInt() + jiffies.at (2).toInt(); totalJiffies = nonIdleJiffies + jiffies.at (3).toInt(); } file.close(); } return qMakePair (nonIdleJiffies, totalJiffies); } #endif
/* * Copyright (c) 2015-2016 Alex Spataru <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "utilities.h" #include <QTimer> #include <QDebug> #include <QScreen> #include <QSettings> #include <QClipboard> #include <QApplication> //------------------------------------------------------------------------------ // Windows hacks //------------------------------------------------------------------------------ #if defined Q_OS_WIN #include <pdh.h> #include <tchar.h> #include <windows.h> #include <windowsx.h> static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; static SYSTEM_POWER_STATUS power; #endif //------------------------------------------------------------------------------ // Mac OS hacks //------------------------------------------------------------------------------ #if defined Q_OS_MAC static const QString CPU_CMD = "bash -c \"ps -A -o %cpu | " "awk '{s+=$1} END {print s}'\""; static const QString BTY_CMD = "pmset -g batt"; static const QString PWR_CMD = "pmset -g batt"; #endif //------------------------------------------------------------------------------ // Linux hacks //------------------------------------------------------------------------------ #if defined Q_OS_LINUX #include <QFile> #include <QRegExp> static const QString BTY_CMD = "bash -c \"upower -i " "$(upower -e | grep 'BAT') | " "grep -E 'state|to\\ full|percentage'\""; static const QString PWR_CMD = "bash -c \"upower -i " "$(upower -e | grep 'BAT') | " "grep -E 'state|to\\ full|percentage'\""; #endif //------------------------------------------------------------------------------ // Ensure that application compiles even if OS is not supported //------------------------------------------------------------------------------ #if !defined Q_OS_WIN && !defined Q_OS_MAC && !defined Q_OS_LINUX static const QString CPU_CMD = ""; static const QString BTY_CMD = ""; static const QString PWR_CMD = ""; #endif //------------------------------------------------------------------------------ // Start class code //------------------------------------------------------------------------------ /** * Configures the class and nitializes the CPU querying process under Windows. */ Utilities::Utilities() { m_ratio = 0; m_cpuUsage = 0; m_batteryLevel = 0; m_connectedToAC = 0; m_settings = new QSettings (qApp->organizationName(), qApp->applicationName()); /* Read process data when they finish */ connect (&m_cpuProcess, SIGNAL (finished (int)), this, SLOT (readCpuUsageProcess (int))); connect (&m_batteryLevelProcess, SIGNAL (finished (int)), this, SLOT (readBatteryLevelProcess (int))); connect (&m_connectedToACProcess, SIGNAL (finished (int)), this, SLOT (readConnectedToACProcess (int))); /* Kill the probing processes when application quits */ connect (qApp, SIGNAL (aboutToQuit()), &m_cpuProcess, SLOT (kill())); connect (qApp, SIGNAL (aboutToQuit()), &m_batteryLevelProcess, SLOT (kill())); connect (qApp, SIGNAL (aboutToQuit()), &m_connectedToACProcess, SLOT (kill())); /* Configure Windows */ #if defined Q_OS_WIN PdhOpenQuery (0, 0, &cpuQuery); PdhAddCounter (cpuQuery, L"\\Processor(_Total)\\% Processor Time", 0, &cpuTotal); PdhCollectQueryData (cpuQuery); #endif /* Start loop */ updateCpuUsage(); updateBatteryLevel(); updateConnectedToAC(); } /** * Returns the auto-calculates scale ratio */ qreal Utilities::scaleRatio() { if (m_ratio < 1) calculateScaleRatio(); return m_ratio; } /** * Returns the current CPU usage (from 0 to 100) */ int Utilities::cpuUsage() { m_cpuUsage = abs (m_cpuUsage); if (m_cpuUsage <= 100) return m_cpuUsage; return 0; } /** * Returns the current battery level (from 0 to 100) */ int Utilities::batteryLevel() { m_batteryLevel = abs (m_batteryLevel); if (m_batteryLevel <= 100) return m_batteryLevel; return 0; } /** * Returns \c true if the computer is connected to a power source or the * battery is not discharging. */ bool Utilities::isConnectedToAC() { return m_connectedToAC; } /** * Copies the given \a data to the system clipboard */ void Utilities::copy (const QVariant& data) { qApp->clipboard()->setText (data.toString(), QClipboard::Clipboard); } /** * Enables or disables the autoscale feature. * \note The application must be restarted for changes to take effect */ void Utilities::setAutoScaleEnabled (const bool enabled) { m_settings->setValue ("AutoScale", enabled); } /** * Queries for the current CPU usage */ void Utilities::updateCpuUsage() { #if defined Q_OS_WIN PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData (cpuQuery); PdhGetFormattedCounterValue (cpuTotal, PDH_FMT_DOUBLE, 0, &counterVal); m_cpuUsage = static_cast<int> (counterVal.doubleValue); emit cpuUsageChanged(); #elif defined Q_OS_MAC m_cpuProcess.terminate(); m_cpuProcess.start (CPU_CMD, QIODevice::ReadOnly); #elif defined Q_OS_LINUX auto cpuJiffies = getCpuJiffies(); m_cpuUsage = (cpuJiffies.first - m_pastCpuJiffies.first) * 100 / (cpuJiffies.second - m_pastCpuJiffies.second); m_pastCpuJiffies = cpuJiffies; #endif QTimer::singleShot (1000, Qt::PreciseTimer, this, SLOT (updateCpuUsage())); } /** * Queries for the current battery level */ void Utilities::updateBatteryLevel() { #if defined Q_OS_WIN GetSystemPowerStatus (&power); m_batteryLevel = static_cast<int> (power.BatteryLifePercent); emit batteryLevelChanged(); #else m_batteryLevelProcess.terminate(); m_batteryLevelProcess.start (BTY_CMD, QIODevice::ReadOnly); #endif QTimer::singleShot (1000, Qt::PreciseTimer, this, SLOT (updateBatteryLevel())); } /** * Queries for the current AC power source status */ void Utilities::updateConnectedToAC() { #if defined Q_OS_WIN GetSystemPowerStatus (&power); m_connectedToAC = (power.ACLineStatus != 0); emit connectedToACChanged(); #else m_connectedToACProcess.terminate(); m_connectedToACProcess.start (PWR_CMD, QIODevice::ReadOnly); #endif QTimer::singleShot (1000, Qt::PreciseTimer, this, SLOT (updateConnectedToAC())); } /** * Calculates the scale factor to apply to the UI. * \note This function uses different procedures depending on the OS */ void Utilities::calculateScaleRatio() { bool enabled = m_settings->value ("AutoScale", true).toBool(); /* Get scale factor using OS-specific code */ #if defined Q_OS_WIN HDC screen = GetDC (Q_NULLPTR); m_ratio = (qreal) GetDeviceCaps (screen, LOGPIXELSX) / 96; ReleaseDC (Q_NULLPTR, screen); #elif defined Q_OS_LINUX m_ratio = qApp->primaryScreen()->physicalDotsPerInch() / 120; #endif /* Ensure that values between x.40 and x.65 round down to x.40 */ qreal decimals = m_ratio - (int) m_ratio; if (decimals >= 0.40 && decimals <= 0.65) m_ratio -= (decimals - 0.40); /* Ratio is too small to be useful to us */ if (!enabled || m_ratio < 1.2) m_ratio = 1; /* Brag about the obtained result */ qDebug() << "Scale factor set to:" << m_ratio; } /** * Reads the output of the process launched to get the CPU usage */ void Utilities::readCpuUsageProcess (int exit_code) { if (exit_code == EXIT_FAILURE) return; #if defined Q_OS_MAC m_cpuUsage = 0; m_cpuProcess.terminate(); QByteArray data = m_cpuProcess.readAll(); if (!data.isEmpty() && data.length() >= 2) { /* Parse the digits of the percentage */ int t = data.at (0) - '0'; // Tens int u = data.at (1) - '0'; // Units /* Check if process data is invalid */ if (t < 0) t = 0; if (u < 0) u = 0; /* Update information */ m_cpuUsage = (t * 10) + u; emit cpuUsageChanged(); } #endif } /** * Reads the output of the process launched to get the battery level */ void Utilities::readBatteryLevelProcess (int exit_code) { if (exit_code == EXIT_FAILURE) return; #if defined Q_OS_MAC || defined Q_OS_LINUX m_batteryLevel = 0; m_batteryLevelProcess.terminate(); QByteArray data = m_batteryLevelProcess.readAll(); if (!data.isEmpty()) { /* Parse the digits of the percentage */ int h = data.at (data.indexOf ("%") - 3) - '0'; // Hundreds int t = data.at (data.indexOf ("%") - 2) - '0'; // Tens int u = data.at (data.indexOf ("%") - 1) - '0'; // Units /* Check if process data is invalid */ if (h < 0) h = 0; if (t < 0) t = 0; if (u < 0) u = 0; /* Update information */ m_batteryLevel = (h * 100) + (t * 10) + u; emit batteryLevelChanged(); } #endif } /** * Reads the output of the process launched to get the AC power source status */ void Utilities::readConnectedToACProcess (int exit_code) { if (exit_code == EXIT_FAILURE) return; #if defined Q_OS_MAC || defined Q_OS_LINUX m_connectedToAC = false; m_connectedToACProcess.terminate(); QByteArray data = m_connectedToACProcess.readAll(); if (!data.isEmpty()) { m_connectedToAC = !data.contains ("discharging"); emit connectedToACChanged(); } #endif } #if defined Q_OS_LINUX /** * Reads the current count of CPU jiffies from /proc/stat and return a pair * consisting of non-idle jiffies and total jiffies */ QPair<quint64, quint64> Utilities::getCpuJiffies() { quint64 totalJiffies = 0; quint64 nonIdleJiffies = 0; QFile file ("/proc/stat"); if (file.open (QFile::ReadOnly)) { QString line = file.readLine(); QStringList jiffies = line.replace ("cpu ", "").split (" "); if (jiffies.count() > 3) { nonIdleJiffies = jiffies.at (0).toInt() + jiffies.at (2).toInt(); totalJiffies = nonIdleJiffies + jiffies.at (3).toInt(); } file.close(); } return qMakePair (nonIdleJiffies, totalJiffies); } #endif
Fix autoscale factor on GNU/Linux
Fix autoscale factor on GNU/Linux
C++
mit
FRC-Utilities/QDriverStation,FRC-Utilities/QDriverStation,FRC-Utilities/QDriverStation
399dc2d251300d891d1f698128df19d327a90a98
os/net/testsuite/testUrgReceive.cpp
os/net/testsuite/testUrgReceive.cpp
/* * Copyright 2009 Google 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 <string.h> #include "arp.h" #include "conduit.h" #include "dix.h" #include "inet.h" #include "inet4.h" #include "inet4address.h" #include "tcp.h" extern int esInit(Object** nameSpace); extern void esRegisterInternetProtocol(es::Context* context); Handle<es::Resolver> resolver; int main() { Object* root = NULL; esInit(&root); Handle<es::Context> context(root); esRegisterInternetProtocol(context); // Create resolver object resolver = context->lookup("network/resolver"); // Create internet config object Handle<es::InternetConfig> config = context->lookup("network/config"); // Setup DIX interface Handle<es::NetworkInterface> nic = context->lookup("device/ethernet"); nic->start(); int dixID = config->addInterface(nic);// add Interface esReport("dixID: %d\n", dixID); ASSERT(config->getScopeID(nic) == dixID); // 192.168.2.40 Register host address InAddr addr = { htonl(192 << 24 | 168 << 16 | 2 << 8 | 20) }; Handle<es::InternetAddress> host = resolver->getHostByAddress(&addr.addr, sizeof addr, dixID); config->addAddress(host, 16); esSleep(90000000); // Wait for the host address to be settled. Handle<es::Socket> serverSocket = host->socket(AF_INET, es::Socket::Stream, 9); serverSocket->listen(5); es::Socket* Server; while (true) { while ((Server = serverSocket->accept()) == 0) { } esReport("accepted\n"); char data[9]; int length; memset (data, 0, 9); while (true) { // server checks whether the socket has entered urgent mode at every read if (Server->isUrgent()) { esReport("Urgent Mode\n\n"); } else { esReport("Not in urgent Mode\n\n"); } // Tells whether the next read delivers an urgent byte if (Server->sockAtMark()) { esReport("An urgent byte will be read now\n"); } length = Server->read(data,3); esReport("Received data and length.......... ............ %s %d\n", data, length); memset (data, 0 ,3); if (length == 0) { break; } } Server->close(); Server->release(); } config->removeAddress(host); nic->stop(); esReport("done.\n"); }
/* * Copyright 2009 Google 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 <string.h> #include "arp.h" #include "conduit.h" #include "dix.h" #include "inet.h" #include "inet4.h" #include "inet4address.h" #include "tcp.h" extern int esInit(Object** nameSpace); extern void esRegisterInternetProtocol(es::Context* context); Handle<es::Resolver> resolver; int main() { Object* root = NULL; esInit(&root); Handle<es::Context> context(root); esRegisterInternetProtocol(context); // Create resolver object resolver = context->lookup("network/resolver"); // Create internet config object Handle<es::InternetConfig> config = context->lookup("network/config"); // Setup DIX interface Handle<es::NetworkInterface> nic = context->lookup("device/ethernet"); nic->start(); int dixID = config->addInterface(nic);// add Interface esReport("dixID: %d\n", dixID); ASSERT(config->getScopeID(nic) == dixID); // 192.168.2.40 Register host address InAddr addr = { htonl(192 << 24 | 168 << 16 | 2 << 8 | 20) }; Handle<es::InternetAddress> host = resolver->getHostByAddress(&addr.addr, sizeof addr, dixID); config->addAddress(host, 16); esSleep(90000000); // Wait for the host address to be settled. Handle<es::Socket> serverSocket = host->socket(AF_INET, es::Socket::Stream, 9); serverSocket->listen(5); es::Socket* Server; while (true) { while ((Server = serverSocket->accept()) == 0) { } esReport("accepted\n"); char data[9]; int length; memset (data, 0, 9); while (true) { // server checks whether the socket has entered urgent mode at every read if (Server->isUrgent()) { esReport("Urgent Mode\n\n"); } else { esReport("Not in urgent Mode\n\n"); } // Tells whether the next read delivers an urgent byte if (Server->sockAtMark()) { esReport("An urgent byte will be read now\n"); } length = Server->read(data, 3); esReport("Received data and length.......... ............ %s %d\n", data, length); memset (data, 0, 3); if (length == 0) { break; } } Server->close(); Server->release(); } config->removeAddress(host); nic->stop(); esReport("done.\n"); }
clean up
clean up
C++
apache-2.0
mattl/es-operating-system,mattl/es-operating-system,mattl/es-operating-system,mattl/es-operating-system,mattl/es-operating-system,mattl/es-operating-system,mattl/es-operating-system
31dec0ea07593074cb7660a907b3865881a2fd3d
unit-tests/internal/internal-tests-linux.cpp
unit-tests/internal/internal-tests-linux.cpp
#include "catch/catch.hpp" #include <thread> #include <string> #include <linux/backend-v4l2.h> #include <sys/types.h> #include <sys/wait.h> #include <semaphore.h> using namespace librealsense::platform; TEST_CASE("named_mutex_threads", "[code]") { class locker_test { std::mutex _m0, _m1; bool _go_0, _go_1; std::condition_variable _cv0, _cv1; bool _actual_test; std::string _device_path; public: locker_test(const std::string& device_path, bool actual_test): _go_0(false), _go_1(false), _actual_test(actual_test), _device_path(device_path) { }; void func_0() { { std::unique_lock<std::mutex> lk(_m0); _cv0.wait(lk, [this]{return _go_0;}); } named_mutex mutex0(_device_path, 0); if (_actual_test) { mutex0.lock(); } { std::unique_lock<std::mutex> lk(_m0); _go_0 = false; } } void func_1() { { std::unique_lock<std::mutex> lk(_m1); _cv1.wait(lk, [this]{return _go_1;}); } named_mutex mutex1(_device_path, 0); mutex1.lock(); { std::lock_guard<std::mutex> lk_gm(_m1); _go_1 = false; } _cv1.notify_all(); { std::unique_lock<std::mutex> lk(_m1); _cv1.wait(lk, [this]{return _go_1;}); } } void run_test() { bool test_ok(false); std::thread t0 = std::thread([this](){func_0();}); std::thread t1 = std::thread([this](){func_1();}); // Tell Thread 1 to lock named_mutex. { std::lock_guard<std::mutex> lk_gm(_m1); _go_1 = true; } _cv1.notify_all(); // Wait for Thread 1 to acknowledge lock. { std::unique_lock<std::mutex> lk(_m1); _cv1.wait(lk, [this]{return !_go_1;}); } // Tell Thread 0 to lock named_mutex. { std::lock_guard<std::mutex> lk_gm(_m0); _go_0 = true; } _cv0.notify_all(); // Give Thread 2 seconds opportunity to lock. std::this_thread::sleep_for(std::chrono::milliseconds(2000)); { std::lock_guard<std::mutex> lk_gm(_m0); // test_ok if thread 0 didn't manage to change value of _go_0. test_ok = (_go_0 == _actual_test); } // Tell thread 1 to finish and release named_mutex. { std::lock_guard<std::mutex> lk_gm(_m1); _go_1 = true; } _cv1.notify_all(); t1.join(); t0.join(); REQUIRE(test_ok); } }; std::string device_path("./named_mutex_test"); int fid(-1); if( access( device_path.c_str(), F_OK ) == -1 ) { fid = open(device_path.c_str(), O_CREAT | O_RDWR, 0666); close(fid); } bool actual_test; SECTION("self-validation") { actual_test = false; } SECTION("actual-test") { actual_test = true; } locker_test _test(device_path, actual_test); _test.run_test(); } TEST_CASE("named_mutex_processes", "[code]") { std::string device_path("./named_mutex_test"); int fid(-1); if( access( device_path.c_str(), F_OK ) == -1 ) { fid = open(device_path.c_str(), O_CREAT | O_RDWR, 0666); close(fid); } sem_unlink("test_semaphore1"); sem_t *sem1 = sem_open("test_semaphore1", O_CREAT|O_EXCL, S_IRWXU, 0); CHECK_FALSE(sem1 == SEM_FAILED); sem_unlink("test_semaphore2"); sem_t *sem2 = sem_open("test_semaphore2", O_CREAT|O_EXCL, S_IRWXU, 0); CHECK_FALSE(sem2 == SEM_FAILED); pid_t pid_0 = getpid(); pid_t pid = fork(); bool actual_test; SECTION("self-validation") { actual_test = false; } SECTION("actual-test") { actual_test = true; } if (pid == 0) // child { signal(SIGTERM, [](int signum) { exit(1); }); sem_wait(sem1); sem_post(sem2); named_mutex mutex1(device_path, 0); if (actual_test) mutex1.lock(); exit(0); } else { named_mutex mutex1(device_path, 0); mutex1.lock(); CHECK_FALSE(sem_post(sem1) < 0); sem_wait(sem2); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); int status; pid_t w = waitpid(pid, &status, WNOHANG); CHECK_FALSE(w == -1); bool child_alive(w == 0); if (child_alive) { int res = kill(pid,SIGTERM); pid_t w = waitpid(pid, &status, 0); } if (fid > 0) { remove(device_path.c_str()); } sem_unlink("test_semaphore1"); sem_close(sem1); sem_unlink("test_semaphore2"); sem_close(sem2); REQUIRE(child_alive == actual_test); } }
#include "catch/catch.hpp" #include <thread> #include <string> #include <linux/backend-v4l2.h> #include <sys/types.h> #include <sys/wait.h> #include <semaphore.h> using namespace librealsense::platform; TEST_CASE("named_mutex_threads", "[code]") { class locker_test { std::mutex _m0, _m1; bool _go_0, _go_1; std::condition_variable _cv0, _cv1; bool _actual_test; std::string _device_path; public: locker_test(const std::string& device_path, bool actual_test): _go_0(false), _go_1(false), _actual_test(actual_test), _device_path(device_path) { }; void func_0() { { std::unique_lock<std::mutex> lk(_m0); _cv0.wait(lk, [this]{return _go_0;}); } named_mutex mutex0(_device_path, 0); if (_actual_test) { mutex0.lock(); } { std::unique_lock<std::mutex> lk(_m0); _go_0 = false; } } void func_1() { { std::unique_lock<std::mutex> lk(_m1); _cv1.wait(lk, [this]{return _go_1;}); } named_mutex mutex1(_device_path, 0); mutex1.lock(); { std::lock_guard<std::mutex> lk_gm(_m1); _go_1 = false; } _cv1.notify_all(); { std::unique_lock<std::mutex> lk(_m1); _cv1.wait(lk, [this]{return _go_1;}); } } void run_test() { bool test_ok(false); std::thread t0 = std::thread([this](){func_0();}); std::thread t1 = std::thread([this](){func_1();}); // Tell Thread 1 to lock named_mutex. { std::lock_guard<std::mutex> lk_gm(_m1); _go_1 = true; } _cv1.notify_all(); // Wait for Thread 1 to acknowledge lock. { std::unique_lock<std::mutex> lk(_m1); _cv1.wait(lk, [this]{return !_go_1;}); } // Tell Thread 0 to lock named_mutex. { std::lock_guard<std::mutex> lk_gm(_m0); _go_0 = true; } _cv0.notify_all(); // Give Thread 2 seconds opportunity to lock. std::this_thread::sleep_for(std::chrono::milliseconds(2000)); { std::lock_guard<std::mutex> lk_gm(_m0); // test_ok if thread 0 didn't manage to change value of _go_0. test_ok = (_go_0 == _actual_test); } // Tell thread 1 to finish and release named_mutex. { std::lock_guard<std::mutex> lk_gm(_m1); _go_1 = true; } _cv1.notify_all(); t1.join(); t0.join(); REQUIRE(test_ok); } }; std::string device_path("./named_mutex_test"); int fid(-1); if( access( device_path.c_str(), F_OK ) == -1 ) { fid = open(device_path.c_str(), O_CREAT | O_RDWR, 0666); close(fid); } bool actual_test; SECTION("self-validation") { actual_test = false; } SECTION("actual-test") { actual_test = true; } locker_test _test(device_path, actual_test); _test.run_test(); } TEST_CASE("named_mutex_processes", "[code]") { std::string device_path("./named_mutex_test"); int fid(-1); if( access( device_path.c_str(), F_OK ) == -1 ) { fid = open(device_path.c_str(), O_CREAT | O_RDWR, 0666); close(fid); } sem_unlink("test_semaphore1"); sem_t *sem1 = sem_open("test_semaphore1", O_CREAT|O_EXCL, S_IRWXU, 0); CHECK_FALSE(sem1 == SEM_FAILED); sem_unlink("test_semaphore2"); sem_t *sem2 = sem_open("test_semaphore2", O_CREAT|O_EXCL, S_IRWXU, 0); CHECK_FALSE(sem2 == SEM_FAILED); pid_t pid_0 = getpid(); pid_t pid = fork(); bool actual_test; SECTION("self-validation") { actual_test = false; } SECTION("actual-test") { actual_test = true; } if (pid == 0) // child { signal(SIGTERM, [](int signum) { exit(1); }); sem_wait(sem1); sem_post(sem2); named_mutex mutex1(device_path, 0); if (actual_test) mutex1.lock(); exit(0); } else { named_mutex mutex1(device_path, 0); mutex1.lock(); CHECK_FALSE(sem_post(sem1) < 0); sem_wait(sem2); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); int status; pid_t w = waitpid(pid, &status, WNOHANG); CHECK_FALSE(w == -1); bool child_alive(w == 0); if (child_alive) { int res = kill(pid,SIGTERM); pid_t w = waitpid(pid, &status, 0); } if (fid > 0) { remove(device_path.c_str()); } sem_unlink("test_semaphore1"); sem_close(sem1); sem_unlink("test_semaphore2"); sem_close(sem2); REQUIRE(child_alive == actual_test); } }
Drop trailing white spaces
Drop trailing white spaces
C++
apache-2.0
IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense
c5253c84a4236a566d09aac82fc3a60edb85fd36
tests/amnoid-clang-tutorial/src/inputargs.cpp
tests/amnoid-clang-tutorial/src/inputargs.cpp
//! Libs: -lclangFrontendTool -lLLVM-3.1svn -lclangARCMigrate -lclangStaticAnalyzerFrontend -lclangStaticAnalyzerCheckers -lclangStaticAnalyzerCore -lclangIndex -lclangRewrite -lclangCodeGen -lclangFrontend -lclangParse -lclangDriver -lclangSerialization -lclangSema -lclangEdit -lclangAnalysis -lclangAST -lclangLex -lclangBasic #include <iostream> using namespace std; #include <llvm/Config/config.h> #include <llvm/Support/Host.h> #include <clang/Basic/FileManager.h> #include <clang/Driver/ArgList.h> #include <clang/Driver/Arg.h> #include <clang/Driver/Driver.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Action.h> #include <clang/Driver/Job.h> #include <clang/Driver/Tool.h> #include <clang/Driver/ToolChain.h> #include <clang/Lex/Preprocessor.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/Utils.h> #include <clang/FrontendTool/Utils.h> #include <clang/Frontend/FrontendDiagnostic.h> using namespace clang; using llvm::dyn_cast; using clang::driver::Arg; using clang::driver::InputArgList; using clang::driver::DerivedArgList; using clang::CompilerInstance; using llvm::sys::getDefaultTargetTriple; using llvm::sys::Path; using llvm::ArrayRef; using clang::driver::Driver; using clang::driver::Compilation; using clang::driver::Command; using clang::driver::ArgStringList; using clang::driver::ActionList; using clang::driver::Action; using clang::driver::InputAction; using clang::driver::PreprocessJobAction; using clang::driver::Job; using clang::driver::JobAction; using clang::driver::JobList; using clang::driver::Tool; using clang::driver::ToolChain; int parseArgsAndProceed(int argc, const char* argv[]); int parseCC1AndProceed(int argc, const char* argv[]); static void LLVMErrorHandler(void *UserData, const std::string &Message); static llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes); int ExecuteCompilation(const Driver* that, const Compilation &C, const Command *&FailingCommand); int ExecuteCommand(const Compilation* that, const Command &C, const Command *&FailingCommand); int ExecuteJob(const Compilation* that, const Job &J, const Command *&FailingCommand); int main(int argc, const char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " [clang-options] source.cpp" << endl; cerr << "Any clang option is usable, source files may be listed among in no particular order." << endl; return EXIT_FAILURE; } return parseArgsAndProceed(argc, argv); } int parseArgsAndProceed(int argc, const char* argv[]) { if (argc >= 1 && !strcmp("-cc1", argv[0])) { return parseCC1AndProceed(argc, argv); } CompilerInstance ci; ci.createDiagnostics(argc, argv); Path path = GetExecutablePath(argv[0], true); Driver driver (path.str(), getDefaultTargetTriple(), "a.out", true, ci.getDiagnostics()); driver.CCCIsCPP = true; // only preprocess OwningPtr<Compilation> compil (driver.BuildCompilation(llvm::ArrayRef<const char*>(argv, argc))); if (!compil) { cerr << "Cannot build the compilation." << endl; return EXIT_FAILURE; } if (driver.getDiags().hasErrorOccurred()) { cerr << "Error occurred building the compilation." << endl; // We must provide a Command that failed to use Driver::generateCompilationDiagnostics() // That Command will only be used as follows: ``if (FailingCommand->getCreator().isLinkJob()) return;'' // Hence we'll have to create a fake command with a tool that will answer no to isLinkJob(), // As we only have PreprocessorJobActions, the first generated action will do. JobAction& fakeAction = *dyn_cast<JobAction>(*compil->getActions().begin()); Tool& fakeCreator = compil->getDefaultToolChain().SelectTool(*compil, fakeAction, fakeAction.getInputs()); Command fakeCommand (fakeAction, fakeCreator, /*Executable*/NULL, ArgStringList()); cerr << "DIAGNOSTIC:" << endl; driver.generateCompilationDiagnostics(*compil, &fakeCommand); cerr << "END OF DIAGNOSTIC" << endl; return EXIT_FAILURE; } driver.PrintActions(*compil); { const ActionList& actions = compil->getActions(); cout << "Actions: (" << actions.size() << ")" << endl; for (ActionList::const_iterator it = actions.begin(), end = actions.end() ; it != end ; ++it) { const Action& a = *(*it); cout << " - " << a.getClassName() << " inputs(" << a.getInputs().size() << ") -> " << clang::driver::types::getTypeName(a.getType()) << endl; for (ActionList::const_iterator it2 = a.begin(), end2 = a.end() ; it2 != end2 ; ++it2) { const Action& a2 = *(*it2); const InputAction* ia = dyn_cast<const InputAction>(&a2); if (ia) { cout << " - " << a2.getClassName() << " {"; const Arg& inputs = ia->getInputArg(); for (unsigned i = 0, n = inputs.getNumValues() ; i < n ; ++i) { cout << "\"" << inputs.getValue(compil->getArgs(), i) << "\""; if (i+1 < n) cout << ", "; } cout << "} -> " << clang::driver::types::getTypeName(a2.getType()) << endl; } else cout << " - " << a2.getClassName() << " inputs(" << a2.getInputs().size() << ") -> " << clang::driver::types::getTypeName(a2.getType()) << endl; } } } cout << endl; //!\\ The following doesn't quite work //!\\ Tip: Use -### to print commands instead of executing them. //!\\ ExecuteCompilation exec()s the this same program, with extra arguments. //!\\ We should take advantage of the parsing done, and do the preprocess ourselves. int Res = 0; const Command *FailingCommand = 0; Res = ExecuteCompilation(&driver, *compil, FailingCommand); // If result status is < 0, then the driver command signalled an error. // In this case, generate additional diagnostic information if possible. if (Res < 0) driver.generateCompilationDiagnostics(*compil, FailingCommand); return EXIT_SUCCESS; } /// Simplified from tools/clang/tools/driver/cc1_main.cpp. /// Parses -cc1 arguments and performs the required action. int parseCC1AndProceed(int argc, const char* argv[]) { CompilerInstance ci; ci.createDiagnostics(argc, argv); if (!CompilerInvocation::CreateFromArgs(ci.getInvocation(), argv, argv+argc, ci.getDiagnostics())) return 1; llvm::install_fatal_error_handler(LLVMErrorHandler, static_cast<void*>(&ci.getDiagnostics())); int Res = 0; Res = ExecuteCompilerInvocation(&ci) ? 1 : 0; llvm::remove_fatal_error_handler(); return Res; } static void LLVMErrorHandler(void *UserData, const std::string &Message) { DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); Diags.Report(diag::err_fe_error_backend) << Message; // We cannot recover from llvm errors. exit(1); } /// Copied from tools/driver/driver.cpp, where it was a static (local) function. /// Turns argv[0] into the executable path. llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) { if (!CanonicalPrefixes) return llvm::sys::Path(Argv0); // symbol just needs to be some symbol in the binary void *symbol = (void*) (intptr_t) GetExecutablePath; // can't take ::main() address, use the current function instead return llvm::sys::Path::GetMainExecutable(Argv0, symbol); } // Some necessary includes for the following 3 functions #include <clang/Driver/Options.h> #include <clang/Driver/DriverDiagnostic.h> #include <llvm/Support/Program.h> /// Copied from Driver::ExecuteCompilation(). /// Modified to call the modified ExecuteJob(). int ExecuteCompilation(const Driver* that, const Compilation &C, const Command *&FailingCommand) { // Just print if -### was present. if (C.getArgs().hasArg(clang::driver::options::OPT__HASH_HASH_HASH)) { C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); return 0; } // If there were errors building the compilation, quit now. if (that->getDiags().hasErrorOccurred()) return 1; int Res = ExecuteJob(&C, C.getJobs(), FailingCommand); // If the command succeeded, we are done. if (Res == 0) return Res; // Print extra information about abnormal failures, if possible. // // This is ad-hoc, but we don't want to be excessively noisy. If the result // status was 1, assume the command failed normally. In particular, if it was // the compiler then assume it gave a reasonable error code. Failures in other // tools are less common, and they generally have worse diagnostics, so always // print the diagnostic there. const Tool &FailingTool = FailingCommand->getCreator(); if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { // FIXME: See FIXME above regarding result code interpretation. if (Res < 0) that->Diag(clang::diag::err_drv_command_signalled) << FailingTool.getShortName(); else that->Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName() << Res; } return Res; } /// Copied from Compilation::ExecuteCommand(). /// Changed to print command options, and not execute anything. int ExecuteCommand(const Compilation* that, const Command &C, const Command *&FailingCommand) { if ((that->getDriver().CCCEcho || that->getDriver().CCPrintOptions || that->getArgs().hasArg(clang::driver::options::OPT_v)) && !that->getDriver().CCGenDiagnostics) { raw_ostream *OS = &llvm::errs(); // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the // output stream. if (that->getDriver().CCPrintOptions && that->getDriver().CCPrintOptionsFilename) { std::string Error; OS = new llvm::raw_fd_ostream(that->getDriver().CCPrintOptionsFilename, Error, llvm::raw_fd_ostream::F_Append); if (!Error.empty()) { that->getDriver().Diag(clang::diag::err_drv_cc_print_options_failure) << Error; FailingCommand = &C; delete OS; return 1; } } if (that->getDriver().CCPrintOptions) *OS << "[Logging clang options]"; that->PrintJob(*OS, C, "\n", /*Quote=*/that->getDriver().CCPrintOptions); if (OS != &llvm::errs()) delete OS; } int argc = C.getArguments().size(); const char* *argv = new const char* [argc+1]; argv[0] = C.getExecutable(); std::copy(C.getArguments().begin(), C.getArguments().end(), argv+1); int Res = 0; Res = parseArgsAndProceed(argc, argv); if (Res) FailingCommand = &C; return Res; } /// Copied from Compilation::ExecuteJob(). /// changed in order to call the modified ExecuteCommand(). int ExecuteJob(const Compilation* that, const Job &J, const Command *&FailingCommand) { if (const Command *C = dyn_cast<Command>(&J)) { return ExecuteCommand(that, *C, FailingCommand); } else { const JobList *Jobs = cast<JobList>(&J); for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) { if (int Res = ExecuteJob(that, **it, FailingCommand)) return Res; } return 0; } }
//! Libs: -lLLVM-3.1svn -lclangARCMigrate -lclangStaticAnalyzerFrontend -lclangStaticAnalyzerCheckers -lclangStaticAnalyzerCore -lclangIndex -lclangCodeGen -lclangRewrite -lclangFrontend -lclangParse -lclangDriver -lclangSerialization -lclangSema -lclangEdit -lclangAnalysis -lclangAST -lclangLex -lclangBasic -lclangFrontendTool #include <iostream> using namespace std; #include <llvm/Config/config.h> #include <llvm/Support/Host.h> #include <clang/Basic/FileManager.h> #include <clang/Driver/ArgList.h> #include <clang/Driver/Arg.h> #include <clang/Driver/Driver.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Action.h> #include <clang/Driver/Job.h> #include <clang/Driver/Tool.h> #include <clang/Driver/ToolChain.h> #include <clang/Lex/Preprocessor.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/Utils.h> #include <clang/FrontendTool/Utils.h> #include <clang/Frontend/FrontendDiagnostic.h> using namespace clang; using llvm::dyn_cast; using clang::driver::Arg; using clang::driver::InputArgList; using clang::driver::DerivedArgList; using clang::CompilerInstance; using llvm::sys::getDefaultTargetTriple; using llvm::sys::Path; using llvm::ArrayRef; using clang::driver::Driver; using clang::driver::Compilation; using clang::driver::Command; using clang::driver::ArgStringList; using clang::driver::ActionList; using clang::driver::Action; using clang::driver::InputAction; using clang::driver::PreprocessJobAction; using clang::driver::Job; using clang::driver::JobAction; using clang::driver::JobList; using clang::driver::Tool; using clang::driver::ToolChain; int parseArgsAndProceed(int argc, const char* argv[]); int parseCC1AndProceed(int argc, const char* argv[]); static void LLVMErrorHandler(void *UserData, const std::string &Message); static llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes); int ExecuteCompilation(const Driver* that, const Compilation &C, const Command *&FailingCommand); int ExecuteCommand(const Compilation* that, const Command &C, const Command *&FailingCommand); int ExecuteJob(const Compilation* that, const Job &J, const Command *&FailingCommand); int main(int argc, const char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " [clang-options] source.cpp" << endl; cerr << "Any clang option is usable, source files may be listed among in no particular order." << endl; return EXIT_FAILURE; } return parseArgsAndProceed(argc, argv); } int parseArgsAndProceed(int argc, const char* argv[]) { if (argc >= 1 && !strcmp("-cc1", argv[0])) { return parseCC1AndProceed(argc, argv); } CompilerInstance ci; ci.createDiagnostics(argc, argv); Path path = GetExecutablePath(argv[0], true); Driver driver (path.str(), getDefaultTargetTriple(), "a.out", true, ci.getDiagnostics()); driver.CCCIsCPP = true; // only preprocess OwningPtr<Compilation> compil (driver.BuildCompilation(llvm::ArrayRef<const char*>(argv, argc))); if (!compil) { cerr << "Cannot build the compilation." << endl; return EXIT_FAILURE; } if (driver.getDiags().hasErrorOccurred()) { cerr << "Error occurred building the compilation." << endl; // We must provide a Command that failed to use Driver::generateCompilationDiagnostics() // That Command will only be used as follows: ``if (FailingCommand->getCreator().isLinkJob()) return;'' // Hence we'll have to create a fake command with a tool that will answer no to isLinkJob(), // As we only have PreprocessorJobActions, the first generated action will do. JobAction& fakeAction = *dyn_cast<JobAction>(*compil->getActions().begin()); Tool& fakeCreator = compil->getDefaultToolChain().SelectTool(*compil, fakeAction, fakeAction.getInputs()); Command fakeCommand (fakeAction, fakeCreator, /*Executable*/NULL, ArgStringList()); cerr << "DIAGNOSTIC:" << endl; driver.generateCompilationDiagnostics(*compil, &fakeCommand); cerr << "END OF DIAGNOSTIC" << endl; return EXIT_FAILURE; } driver.PrintActions(*compil); { const ActionList& actions = compil->getActions(); cout << "Actions: (" << actions.size() << ")" << endl; for (ActionList::const_iterator it = actions.begin(), end = actions.end() ; it != end ; ++it) { const Action& a = *(*it); cout << " - " << a.getClassName() << " inputs(" << a.getInputs().size() << ") -> " << clang::driver::types::getTypeName(a.getType()) << endl; for (ActionList::const_iterator it2 = a.begin(), end2 = a.end() ; it2 != end2 ; ++it2) { const Action& a2 = *(*it2); const InputAction* ia = dyn_cast<const InputAction>(&a2); if (ia) { cout << " - " << a2.getClassName() << " {"; const Arg& inputs = ia->getInputArg(); for (unsigned i = 0, n = inputs.getNumValues() ; i < n ; ++i) { cout << "\"" << inputs.getValue(compil->getArgs(), i) << "\""; if (i+1 < n) cout << ", "; } cout << "} -> " << clang::driver::types::getTypeName(a2.getType()) << endl; } else cout << " - " << a2.getClassName() << " inputs(" << a2.getInputs().size() << ") -> " << clang::driver::types::getTypeName(a2.getType()) << endl; } } } cout << endl; //!\\ The following doesn't quite work //!\\ Tip: Use -### to print commands instead of executing them. //!\\ ExecuteCompilation exec()s the this same program, with extra arguments. //!\\ We should take advantage of the parsing done, and do the preprocess ourselves. int Res = 0; const Command *FailingCommand = 0; Res = ExecuteCompilation(&driver, *compil, FailingCommand); // If result status is < 0, then the driver command signalled an error. // In this case, generate additional diagnostic information if possible. if (Res < 0) driver.generateCompilationDiagnostics(*compil, FailingCommand); return EXIT_SUCCESS; } /// Simplified from tools/clang/tools/driver/cc1_main.cpp. /// Parses -cc1 arguments and performs the required action. int parseCC1AndProceed(int argc, const char* argv[]) { CompilerInstance ci; ci.createDiagnostics(argc, argv); if (!CompilerInvocation::CreateFromArgs(ci.getInvocation(), argv, argv+argc, ci.getDiagnostics())) return 1; llvm::install_fatal_error_handler(LLVMErrorHandler, static_cast<void*>(&ci.getDiagnostics())); int Res = 0; Res = ExecuteCompilerInvocation(&ci) ? 1 : 0; llvm::remove_fatal_error_handler(); return Res; } static void LLVMErrorHandler(void *UserData, const std::string &Message) { DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); Diags.Report(diag::err_fe_error_backend) << Message; // We cannot recover from llvm errors. exit(1); } /// Copied from tools/driver/driver.cpp, where it was a static (local) function. /// Turns argv[0] into the executable path. llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) { if (!CanonicalPrefixes) return llvm::sys::Path(Argv0); // symbol just needs to be some symbol in the binary void *symbol = (void*) (intptr_t) GetExecutablePath; // can't take ::main() address, use the current function instead return llvm::sys::Path::GetMainExecutable(Argv0, symbol); } // Some necessary includes for the following 3 functions #include <clang/Driver/Options.h> #include <clang/Driver/DriverDiagnostic.h> #include <llvm/Support/Program.h> /// Copied from Driver::ExecuteCompilation(). /// Modified to call the modified ExecuteJob(). int ExecuteCompilation(const Driver* that, const Compilation &C, const Command *&FailingCommand) { // Just print if -### was present. if (C.getArgs().hasArg(clang::driver::options::OPT__HASH_HASH_HASH)) { C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); return 0; } // If there were errors building the compilation, quit now. if (that->getDiags().hasErrorOccurred()) return 1; int Res = ExecuteJob(&C, C.getJobs(), FailingCommand); // If the command succeeded, we are done. if (Res == 0) return Res; // Print extra information about abnormal failures, if possible. // // This is ad-hoc, but we don't want to be excessively noisy. If the result // status was 1, assume the command failed normally. In particular, if it was // the compiler then assume it gave a reasonable error code. Failures in other // tools are less common, and they generally have worse diagnostics, so always // print the diagnostic there. const Tool &FailingTool = FailingCommand->getCreator(); if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { // FIXME: See FIXME above regarding result code interpretation. if (Res < 0) that->Diag(clang::diag::err_drv_command_signalled) << FailingTool.getShortName(); else that->Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName() << Res; } return Res; } /// Copied from Compilation::ExecuteCommand(). /// Changed to print command options, and not execute anything. int ExecuteCommand(const Compilation* that, const Command &C, const Command *&FailingCommand) { if ((that->getDriver().CCCEcho || that->getDriver().CCPrintOptions || that->getArgs().hasArg(clang::driver::options::OPT_v)) && !that->getDriver().CCGenDiagnostics) { raw_ostream *OS = &llvm::errs(); // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the // output stream. if (that->getDriver().CCPrintOptions && that->getDriver().CCPrintOptionsFilename) { std::string Error; OS = new llvm::raw_fd_ostream(that->getDriver().CCPrintOptionsFilename, Error, llvm::raw_fd_ostream::F_Append); if (!Error.empty()) { that->getDriver().Diag(clang::diag::err_drv_cc_print_options_failure) << Error; FailingCommand = &C; delete OS; return 1; } } if (that->getDriver().CCPrintOptions) *OS << "[Logging clang options]"; that->PrintJob(*OS, C, "\n", /*Quote=*/that->getDriver().CCPrintOptions); if (OS != &llvm::errs()) delete OS; } int argc = C.getArguments().size(); const char* *argv = new const char* [argc+1]; argv[0] = C.getExecutable(); std::copy(C.getArguments().begin(), C.getArguments().end(), argv+1); int Res = 0; Res = parseArgsAndProceed(argc, argv); if (Res) FailingCommand = &C; return Res; } /// Copied from Compilation::ExecuteJob(). /// changed in order to call the modified ExecuteCommand(). int ExecuteJob(const Compilation* that, const Job &J, const Command *&FailingCommand) { if (const Command *C = dyn_cast<Command>(&J)) { return ExecuteCommand(that, *C, FailingCommand); } else { const JobList *Jobs = cast<JobList>(&J); for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) { if (int Res = ExecuteJob(that, **it, FailingCommand)) return Res; } return 0; } }
Update libs with shared libs ordering
Update libs with shared libs ordering Only src/inputargs.cpp needs an update. Compilation is faster with shared libs, hurray!
C++
bsd-3-clause
ofavre/TwistIDE,ofavre/TwistIDE,ofavre/TwistIDE
656e6c378104cd72d0db569600e502113dd108bc
tests/bogus-dynamic-cast/main.cpp
tests/bogus-dynamic-cast/main.cpp
struct A { }; struct B : public A { }; void test() { A *a = new A(); B *b = new B(); dynamic_cast<A*>(b); // warning: Casting to base dynamic_cast<A*>(a); // warning: Casting to itself dynamic_cast<B*>(a); // OK dynamic_cast<B*>(b); // warning: Casting to itself }
struct A { virtual void foo() { } }; struct B : public A { }; void test() { A *a = new A(); B *b = new B(); dynamic_cast<A*>(b); // warning: Casting to base dynamic_cast<A*>(a); // warning: Casting to itself dynamic_cast<B*>(a); // OK dynamic_cast<B*>(b); // warning: Casting to itself }
Fix unit-test build
bogus-dynamic-cast: Fix unit-test build
C++
lgpl-2.1
nyalldawson/clazy,nyalldawson/clazy,nyalldawson/clazy,nyalldawson/clazy
74dca8d642bc1fd7df7f4d694094530ebb1271ae
src/liboslexec/opcolor.cpp
src/liboslexec/opcolor.cpp
/* Copyright (c) 2009 Sony Pictures Imageworks, et al. 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 Sony Pictures Imageworks 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. */ ///////////////////////////////////////////////////////////////////////// /// \file /// /// Shader interpreter implementation of color operations. /// ///////////////////////////////////////////////////////////////////////// #include <iostream> #include "oslexec_pvt.h" #include "oslops.h" #include "OpenImageIO/varyingref.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { extern DECLOP (triple_ctr); // definition is elsewhere namespace { static Color3 hsv_to_rgb (float h, float s, float v) { // Reference for this technique: Foley & van Dam if (s < 0.0001f) { return Color3 (v, v, v); } else { h = 6.0f * (h - floorf(h)); // expand to [0..6) int hi = (int) h; float f = h - hi; float p = v * (1.0f-s); float q = v * (1.0f-s*f); float t = v * (1.0f-s*(1.0f-f)); switch (hi) { case 0 : return Color3 (v, t, p); case 1 : return Color3 (q, v, p); case 2 : return Color3 (p, v, t); case 3 : return Color3 (p, q, v); case 4 : return Color3 (t, p, v); default: return Color3 (v, p, q); } } } static Color3 hsl_to_rgb (float h, float s, float l) { // Easiest to convert hsl -> hsv, then hsv -> RGB (per Foley & van Dam) float v = (l <= 0.5) ? (l * (1.0f + s)) : (l * (1.0f - s) + s); if (v <= 0.0f) { return Color3 (0.0f, 0.0f, 0.0f); } else { float min = 2.0f * l - v; s = (v - min) / v; return hsv_to_rgb (h, s, v); } } static Color3 YIQ_to_rgb (float Y, float I, float Q) { return Color3 (Y + 0.9557f * I + 0.6199f * Q, Y - 0.2716f * I - 0.6469f * Q, Y - 1.1082f * I + 1.7051f * Q); } static Color3 xyz_to_rgb (float x, float y, float z) { return Color3 ( 3.240479f * x + -1.537150f * y + -0.498535f * z, -0.969256f * x + 1.875991f * y + 0.041556f * z, 0.055648f * x + -0.204043f * y + 1.057311f * z); } static Color3 to_rgb (ustring fromspace, float a, float b, float c, ShadingExecution *exec) { if (fromspace == Strings::RGB || fromspace == Strings::rgb) return Color3 (a, b, c); if (fromspace == Strings::hsv) return hsv_to_rgb (a, b, c); if (fromspace == Strings::hsl) return hsl_to_rgb (a, b, c); if (fromspace == Strings::YIQ) return YIQ_to_rgb (a, b, c); if (fromspace == Strings::xyz) return xyz_to_rgb (a, b, c); exec->error ("Unknown color space \"%s\"", fromspace.c_str()); return Color3 (a, b, c); } class Luminance { public: Luminance (ShadingExecution *) { } inline float operator() (const Color3 &c) { return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; } }; /// Implementation of the constructor "color (string, float, float, float)". /// DECLOP (color_ctr_transform) { bool using_space = (nargs == 5); Symbol &Result (exec->sym (args[0])); Symbol &Space (exec->sym (args[1])); Symbol &X (exec->sym (args[2])); Symbol &Y (exec->sym (args[3])); Symbol &Z (exec->sym (args[4])); // Adjust the result's uniform/varying status bool vary = (Space.is_varying() | X.is_varying() | Y.is_varying() | Z.is_varying() ); exec->adjust_varying (Result, vary, false /* can't alias */); VaryingRef<Color3> result ((Color3 *)Result.data(), Result.step()); VaryingRef<ustring> space ((ustring *)Space.data(), Space.step()); VaryingRef<float> x ((float *)X.data(), X.step()); VaryingRef<float> y ((float *)Y.data(), Y.step()); VaryingRef<float> z ((float *)Z.data(), Z.step()); Matrix44 M; if (result.is_uniform()) { // Everything is uniform *result = to_rgb (*space, *x, *y, *z, exec); } else if (! vary) { // Result is varying, but everything else is uniform Color3 r = to_rgb (*space, *x, *y, *z, exec); for (int i = beginpoint; i < endpoint; ++i) if (runflags[i]) result[i] = r; } else { // Fully varying case for (int i = beginpoint; i < endpoint; ++i) if (runflags[i]) result[i] = to_rgb (space[i], x[i], y[i], z[i], exec); } } }; // End anonymous namespace DECLOP (OP_color) { ASSERT (nargs == 4 || nargs == 5); Symbol &Result (exec->sym (args[0])); bool using_space = (nargs == 5); Symbol &Space (exec->sym (args[1])); Symbol &X (exec->sym (args[1+using_space])); Symbol &Y (exec->sym (args[2+using_space])); Symbol &Z (exec->sym (args[3+using_space])); ASSERT (! Result.typespec().is_closure() && ! X.typespec().is_closure() && ! Y.typespec().is_closure() && ! Z.typespec().is_closure() && ! Space.typespec().is_closure()); // We allow two flavors: point = point(float,float,float) and // point = point(string,float,float,float) if (Result.typespec().is_triple() && X.typespec().is_float() && Y.typespec().is_float() && Z.typespec().is_float() && (using_space == false || Space.typespec().is_string())) { OpImpl impl = NULL; if (using_space) impl = color_ctr_transform; // special case: colors different else impl = triple_ctr; impl (exec, nargs, args, runflags, beginpoint, endpoint); // Use the specialized one for next time! Never have to check the // types or do the other sanity checks again. // FIXME -- is this thread-safe? exec->op().implementation (impl); } else { std::cerr << "Don't know how compute " << Result.typespec().string() << " = " << exec->op().opname() << "(" << (using_space ? Space.typespec().string() : std::string()) << (using_space ? ", " : "") << X.typespec().string() << ", " << Y.typespec().string() << ", " << Z.typespec().string() << ")\n"; ASSERT (0 && "Function arg type can't be handled"); } } DECLOP (OP_luminance) { DASSERT (nargs == 2); Symbol &Result (exec->sym (args[0])); Symbol &C (exec->sym (args[1])); DASSERT (! Result.typespec().is_closure() && ! X.typespec().is_closure()); DASSERT (Result.typespec().is_float() && X.typespec().is_triple()); unary_op_guts<Float, Color3, Luminance> (Result, C, exec, runflags, beginpoint, endpoint); } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif
/* Copyright (c) 2009 Sony Pictures Imageworks, et al. 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 Sony Pictures Imageworks 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. */ ///////////////////////////////////////////////////////////////////////// /// \file /// /// Shader interpreter implementation of color operations. /// ///////////////////////////////////////////////////////////////////////// #include <iostream> #include "oslexec_pvt.h" #include "oslops.h" #include "OpenImageIO/varyingref.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { extern DECLOP (triple_ctr); // definition is elsewhere namespace { static Color3 hsv_to_rgb (float h, float s, float v) { // Reference for this technique: Foley & van Dam if (s < 0.0001f) { return Color3 (v, v, v); } else { h = 6.0f * (h - floorf(h)); // expand to [0..6) int hi = (int) h; float f = h - hi; float p = v * (1.0f-s); float q = v * (1.0f-s*f); float t = v * (1.0f-s*(1.0f-f)); switch (hi) { case 0 : return Color3 (v, t, p); case 1 : return Color3 (q, v, p); case 2 : return Color3 (p, v, t); case 3 : return Color3 (p, q, v); case 4 : return Color3 (t, p, v); default: return Color3 (v, p, q); } } } static Color3 hsl_to_rgb (float h, float s, float l) { // Easiest to convert hsl -> hsv, then hsv -> RGB (per Foley & van Dam) float v = (l <= 0.5) ? (l * (1.0f + s)) : (l * (1.0f - s) + s); if (v <= 0.0f) { return Color3 (0.0f, 0.0f, 0.0f); } else { float min = 2.0f * l - v; s = (v - min) / v; return hsv_to_rgb (h, s, v); } } static Color3 YIQ_to_rgb (float Y, float I, float Q) { return Color3 (Y + 0.9557f * I + 0.6199f * Q, Y - 0.2716f * I - 0.6469f * Q, Y - 1.1082f * I + 1.7051f * Q); } static Color3 xyz_to_rgb (float x, float y, float z) { return Color3 ( 3.240479f * x + -1.537150f * y + -0.498535f * z, -0.969256f * x + 1.875991f * y + 0.041556f * z, 0.055648f * x + -0.204043f * y + 1.057311f * z); } static Color3 to_rgb (ustring fromspace, float a, float b, float c, ShadingExecution *exec) { if (fromspace == Strings::RGB || fromspace == Strings::rgb) return Color3 (a, b, c); if (fromspace == Strings::hsv) return hsv_to_rgb (a, b, c); if (fromspace == Strings::hsl) return hsl_to_rgb (a, b, c); if (fromspace == Strings::YIQ) return YIQ_to_rgb (a, b, c); if (fromspace == Strings::xyz) return xyz_to_rgb (a, b, c); exec->error ("Unknown color space \"%s\"", fromspace.c_str()); return Color3 (a, b, c); } class Luminance { public: Luminance (ShadingExecution *) { } inline float operator() (const Color3 &c) { return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; } }; /// Implementation of the constructor "color (string, float, float, float)". /// DECLOP (color_ctr_transform) { bool using_space = (nargs == 5); Symbol &Result (exec->sym (args[0])); Symbol &Space (exec->sym (args[1])); Symbol &X (exec->sym (args[2])); Symbol &Y (exec->sym (args[3])); Symbol &Z (exec->sym (args[4])); // Adjust the result's uniform/varying status bool vary = (Space.is_varying() | X.is_varying() | Y.is_varying() | Z.is_varying() ); exec->adjust_varying (Result, vary, false /* can't alias */); VaryingRef<Color3> result ((Color3 *)Result.data(), Result.step()); VaryingRef<ustring> space ((ustring *)Space.data(), Space.step()); VaryingRef<float> x ((float *)X.data(), X.step()); VaryingRef<float> y ((float *)Y.data(), Y.step()); VaryingRef<float> z ((float *)Z.data(), Z.step()); Matrix44 M; if (result.is_uniform()) { // Everything is uniform *result = to_rgb (*space, *x, *y, *z, exec); } else if (! vary) { // Result is varying, but everything else is uniform Color3 r = to_rgb (*space, *x, *y, *z, exec); for (int i = beginpoint; i < endpoint; ++i) if (runflags[i]) result[i] = r; } else { // Fully varying case for (int i = beginpoint; i < endpoint; ++i) if (runflags[i]) result[i] = to_rgb (space[i], x[i], y[i], z[i], exec); } } }; // End anonymous namespace DECLOP (OP_color) { ASSERT (nargs == 4 || nargs == 5); Symbol &Result (exec->sym (args[0])); bool using_space = (nargs == 5); Symbol &Space (exec->sym (args[1])); Symbol &X (exec->sym (args[1+using_space])); Symbol &Y (exec->sym (args[2+using_space])); Symbol &Z (exec->sym (args[3+using_space])); ASSERT (! Result.typespec().is_closure() && ! X.typespec().is_closure() && ! Y.typespec().is_closure() && ! Z.typespec().is_closure() && ! Space.typespec().is_closure()); // We allow two flavors: point = point(float,float,float) and // point = point(string,float,float,float) if (Result.typespec().is_triple() && X.typespec().is_float() && Y.typespec().is_float() && Z.typespec().is_float() && (using_space == false || Space.typespec().is_string())) { OpImpl impl = NULL; if (using_space) impl = color_ctr_transform; // special case: colors different else impl = triple_ctr; impl (exec, nargs, args, runflags, beginpoint, endpoint); // Use the specialized one for next time! Never have to check the // types or do the other sanity checks again. // FIXME -- is this thread-safe? exec->op().implementation (impl); } else { std::cerr << "Don't know how compute " << Result.typespec().string() << " = " << exec->op().opname() << "(" << (using_space ? Space.typespec().string() : std::string()) << (using_space ? ", " : "") << X.typespec().string() << ", " << Y.typespec().string() << ", " << Z.typespec().string() << ")\n"; ASSERT (0 && "Function arg type can't be handled"); } } DECLOP (OP_luminance) { DASSERT (nargs == 2); Symbol &Result (exec->sym (args[0])); Symbol &C (exec->sym (args[1])); DASSERT (! Result.typespec().is_closure() && ! C.typespec().is_closure()); DASSERT (Result.typespec().is_float() && C.typespec().is_triple()); unary_op_guts<Float, Color3, Luminance> (Result, C, exec, runflags, beginpoint, endpoint); } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif
Fix typo in DASSERT for luminance
Fix typo in DASSERT for luminance git-svn-id: 93cebb81a0f5cc00f31a7ad40d16024532691b70@173 a3683778-fedd-11de-87c3-653bb6514e15
C++
bsd-3-clause
yaroslav-tarasov/OpenShadingLanguage,Anteru/OpenShadingLanguage,brechtvl/OpenShadingLanguage,fpsunflower/OpenShadingLanguage,lgritz/OpenShadingLanguage,fpsunflower/OpenShadingLanguage,yaroslav-tarasov/OpenShadingLanguage,aconty/OpenShadingLanguage,svenstaro/OpenShadingLanguage,lgritz/OpenShadingLanguage,juvenal/OpenShadingLanguage,brechtvl/OpenShadingLanguage,amartinez-cg/OpenShadingLanguage,rlmh/OpenShadingLanguage,brechtvl/OpenShadingLanguage,amartinez-cg/OpenShadingLanguage,juvenal/OpenShadingLanguage,gzorin/OpenShadingLanguage,amartinez-cg/OpenShadingLanguage,gzorin/OpenShadingLanguage,imageworks/OpenShadingLanguage,brechtvl/OpenShadingLanguage,mcanthony/OpenShadingLanguage,imageworks/OpenShadingLanguage,amartinez-cg/OpenShadingLanguage,Anteru/OpenShadingLanguage,mcanthony/OpenShadingLanguage,svenstaro/OpenShadingLanguage,yaroslav-tarasov/OpenShadingLanguage,lgritz/OpenShadingLanguage,sjparker/OpenShadingLanguage,Anteru/OpenShadingLanguage,lgritz/OpenShadingLanguage,gzorin/OpenShadingLanguage,brechtvl/OpenShadingLanguage,rlmh/OpenShadingLanguage,gzorin/OpenShadingLanguage,aconty/OpenShadingLanguage,gzorin/OpenShadingLanguage,fpsunflower/OpenShadingLanguage,juvenal/OpenShadingLanguage,johnhaddon/OpenShadingLanguage,yaroslav-tarasov/OpenShadingLanguage,imageworks/OpenShadingLanguage,johnhaddon/OpenShadingLanguage,mcanthony/OpenShadingLanguage,svenstaro/OpenShadingLanguage,amartinez-cg/OpenShadingLanguage,mcanthony/OpenShadingLanguage,aconty/OpenShadingLanguage,sjparker/OpenShadingLanguage,rlmh/OpenShadingLanguage,Anteru/OpenShadingLanguage,aconty/OpenShadingLanguage,aconty/OpenShadingLanguage,lgritz/OpenShadingLanguage,sjparker/OpenShadingLanguage,johnhaddon/OpenShadingLanguage,sjparker/OpenShadingLanguage,juvenal/OpenShadingLanguage,imageworks/OpenShadingLanguage,imageworks/OpenShadingLanguage,johnhaddon/OpenShadingLanguage,rlmh/OpenShadingLanguage,svenstaro/OpenShadingLanguage,fpsunflower/OpenShadingLanguage
88508d5166370b144433c27f8dc60ea60d6ff78b
shell/browser/extensions/api/resources_private/resources_private_api.cc
shell/browser/extensions/api/resources_private/resources_private_api.cc
// Copyright 2015 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 "shell/browser/extensions/api/resources_private/resources_private_api.h" #include <memory> #include <string> #include <utility> #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/common/extensions/api/resources_private.h" #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_strings.h" #include "components/zoom/page_zoom_constants.h" #include "pdf/buildflags.h" #include "printing/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #if BUILDFLAG(ENABLE_PDF) #include "pdf/pdf_features.h" #endif // BUILDFLAG(ENABLE_PDF) // To add a new component to this API, simply: // 1. Add your component to the Component enum in // chrome/common/extensions/api/resources_private.idl // 2. Create an AddStringsForMyComponent(base::DictionaryValue * dict) method. // 3. Tie in that method to the switch statement in Run() namespace extensions { namespace { void AddStringsForPdf(base::DictionaryValue* dict) { #if BUILDFLAG(ENABLE_PDF) static constexpr webui::LocalizedString kPdfResources[] = { {"passwordDialogTitle", IDS_PDF_PASSWORD_DIALOG_TITLE}, {"passwordPrompt", IDS_PDF_NEED_PASSWORD}, {"passwordSubmit", IDS_PDF_PASSWORD_SUBMIT}, {"passwordInvalid", IDS_PDF_PASSWORD_INVALID}, {"pageLoading", IDS_PDF_PAGE_LOADING}, {"pageLoadFailed", IDS_PDF_PAGE_LOAD_FAILED}, {"errorDialogTitle", IDS_PDF_ERROR_DIALOG_TITLE}, {"pageReload", IDS_PDF_PAGE_RELOAD_BUTTON}, {"bookmarks", IDS_PDF_BOOKMARKS}, {"labelPageNumber", IDS_PDF_LABEL_PAGE_NUMBER}, {"tooltipRotateCW", IDS_PDF_TOOLTIP_ROTATE_CW}, {"tooltipDownload", IDS_PDF_TOOLTIP_DOWNLOAD}, {"tooltipPrint", IDS_PDF_TOOLTIP_PRINT}, {"tooltipFitToPage", IDS_PDF_TOOLTIP_FIT_PAGE}, {"tooltipFitToWidth", IDS_PDF_TOOLTIP_FIT_WIDTH}, {"tooltipZoomIn", IDS_PDF_TOOLTIP_ZOOM_IN}, {"tooltipZoomOut", IDS_PDF_TOOLTIP_ZOOM_OUT}, }; for (const auto& resource : kPdfResources) dict->SetString(resource.name, l10n_util::GetStringUTF16(resource.id)); dict->SetString("presetZoomFactors", zoom::GetPresetZoomFactorsAsJSON()); #endif // BUILDFLAG(ENABLE_PDF) } void AddAdditionalDataForPdf(base::DictionaryValue* dict) { #if BUILDFLAG(ENABLE_PDF) dict->SetKey("pdfFormSaveEnabled", base::Value(base::FeatureList::IsEnabled( chrome_pdf::features::kSaveEditedPDFForm))); dict->SetKey("pdfAnnotationsEnabled", base::Value(false)); dict->SetKey("printingEnabled", base::Value(true)); #endif // BUILDFLAG(ENABLE_PDF) } } // namespace namespace get_strings = api::resources_private::GetStrings; ResourcesPrivateGetStringsFunction::ResourcesPrivateGetStringsFunction() {} ResourcesPrivateGetStringsFunction::~ResourcesPrivateGetStringsFunction() {} ExtensionFunction::ResponseAction ResourcesPrivateGetStringsFunction::Run() { std::unique_ptr<get_strings::Params> params( get_strings::Params::Create(*args_)); auto dict = std::make_unique<base::DictionaryValue>(); api::resources_private::Component component = params->component; switch (component) { case api::resources_private::COMPONENT_PDF: AddStringsForPdf(dict.get()); AddAdditionalDataForPdf(dict.get()); break; case api::resources_private::COMPONENT_IDENTITY: NOTREACHED(); break; case api::resources_private::COMPONENT_NONE: NOTREACHED(); break; } const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, dict.get()); return RespondNow(OneArgument(std::move(dict))); } } // namespace extensions
// Copyright 2015 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 "shell/browser/extensions/api/resources_private/resources_private_api.h" #include <memory> #include <string> #include <utility> #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/common/extensions/api/resources_private.h" #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_strings.h" #include "components/zoom/page_zoom_constants.h" #include "pdf/buildflags.h" #include "printing/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #if BUILDFLAG(ENABLE_PDF) #include "pdf/pdf_features.h" #endif // BUILDFLAG(ENABLE_PDF) // To add a new component to this API, simply: // 1. Add your component to the Component enum in // chrome/common/extensions/api/resources_private.idl // 2. Create an AddStringsForMyComponent(base::DictionaryValue * dict) method. // 3. Tie in that method to the switch statement in Run() namespace extensions { namespace { void AddStringsForPdf(base::DictionaryValue* dict) { #if BUILDFLAG(ENABLE_PDF) static constexpr webui::LocalizedString kPdfResources[] = { {"passwordDialogTitle", IDS_PDF_PASSWORD_DIALOG_TITLE}, {"passwordPrompt", IDS_PDF_NEED_PASSWORD}, {"passwordSubmit", IDS_PDF_PASSWORD_SUBMIT}, {"passwordInvalid", IDS_PDF_PASSWORD_INVALID}, {"pageLoading", IDS_PDF_PAGE_LOADING}, {"pageLoadFailed", IDS_PDF_PAGE_LOAD_FAILED}, {"errorDialogTitle", IDS_PDF_ERROR_DIALOG_TITLE}, {"pageReload", IDS_PDF_PAGE_RELOAD_BUTTON}, {"bookmarks", IDS_PDF_BOOKMARKS}, {"labelPageNumber", IDS_PDF_LABEL_PAGE_NUMBER}, {"tooltipRotateCW", IDS_PDF_TOOLTIP_ROTATE_CW}, {"tooltipDownload", IDS_PDF_TOOLTIP_DOWNLOAD}, {"tooltipPrint", IDS_PDF_TOOLTIP_PRINT}, {"tooltipFitToPage", IDS_PDF_TOOLTIP_FIT_PAGE}, {"tooltipFitToWidth", IDS_PDF_TOOLTIP_FIT_WIDTH}, {"tooltipZoomIn", IDS_PDF_TOOLTIP_ZOOM_IN}, {"tooltipZoomOut", IDS_PDF_TOOLTIP_ZOOM_OUT}, }; for (const auto& resource : kPdfResources) dict->SetString(resource.name, l10n_util::GetStringUTF16(resource.id)); dict->SetString("presetZoomFactors", zoom::GetPresetZoomFactorsAsJSON()); #endif // BUILDFLAG(ENABLE_PDF) } void AddAdditionalDataForPdf(base::DictionaryValue* dict) { #if BUILDFLAG(ENABLE_PDF) dict->SetStringKey( "pdfViewerUpdateEnabledAttribute", base::FeatureList::IsEnabled(chrome_pdf::features::kPDFViewerUpdate) ? "pdf-viewer-update-enabled" : ""); dict->SetKey("pdfFormSaveEnabled", base::Value(base::FeatureList::IsEnabled( chrome_pdf::features::kSaveEditedPDFForm))); dict->SetKey("pdfAnnotationsEnabled", base::Value(false)); dict->SetKey("printingEnabled", base::Value(true)); #endif // BUILDFLAG(ENABLE_PDF) } } // namespace namespace get_strings = api::resources_private::GetStrings; ResourcesPrivateGetStringsFunction::ResourcesPrivateGetStringsFunction() {} ResourcesPrivateGetStringsFunction::~ResourcesPrivateGetStringsFunction() {} ExtensionFunction::ResponseAction ResourcesPrivateGetStringsFunction::Run() { std::unique_ptr<get_strings::Params> params( get_strings::Params::Create(*args_)); auto dict = std::make_unique<base::DictionaryValue>(); api::resources_private::Component component = params->component; switch (component) { case api::resources_private::COMPONENT_PDF: AddStringsForPdf(dict.get()); AddAdditionalDataForPdf(dict.get()); break; case api::resources_private::COMPONENT_IDENTITY: NOTREACHED(); break; case api::resources_private::COMPONENT_NONE: NOTREACHED(); break; } const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, dict.get()); return RespondNow(OneArgument(std::move(dict))); } } // namespace extensions
support new PDF viewer update (#26010)
fix: support new PDF viewer update (#26010)
C++
mit
seanchas116/electron,electron/electron,seanchas116/electron,bpasero/electron,bpasero/electron,bpasero/electron,seanchas116/electron,electron/electron,bpasero/electron,seanchas116/electron,seanchas116/electron,electron/electron,gerhardberger/electron,gerhardberger/electron,bpasero/electron,electron/electron,bpasero/electron,gerhardberger/electron,electron/electron,electron/electron,gerhardberger/electron,gerhardberger/electron,seanchas116/electron,gerhardberger/electron,electron/electron,gerhardberger/electron,bpasero/electron
acf68582702c52552052658c4a7c8b77fbb0dc92
src/wall_grid.cpp
src/wall_grid.cpp
#include "wall_grid.hpp" namespace Quoridor { enum NodeOccupiedSide { kBottom = 1, kLeft = 2, kRight = 4, kUp = 8, kVertical = kBottom | kUp, kHorizontal = kLeft | kRight, kAll = 15 }; static const NodeOccupiedSide horiz_occ_sides_[] = { NodeOccupiedSide::kRight, NodeOccupiedSide::kHorizontal, NodeOccupiedSide::kLeft, }; static const NodeOccupiedSide vert_occ_sides_[] = { NodeOccupiedSide::kUp, NodeOccupiedSide::kVertical, NodeOccupiedSide::kBottom, }; WallGrid::WallGrid(int size) : occupied_nodes_(), tmp_occupied_nodes_(), size_(size) { } WallGrid::~WallGrid() { } int WallGrid::add_wall(const Wall &wall) { if (add_tmp_wall(wall) == 0) { apply_tmp_wall(); return 0; } return -1; } int WallGrid::add_tmp_wall(const Wall &wall) { int rc = 0; // check if wall is set on the border if ((wall.orientation() == Wall::kHorizontal) && ((wall.row() == 0) || (wall.row() == size_ - 1))) { return -1; } else if ((wall.orientation() == Wall::kVertical) && ((wall.col() == 0) || (wall.col() == size_ - 1))) { return -1; } Node inc_node(0, 0); const NodeOccupiedSide *occ_sides; switch (wall.orientation()) { case Wall::kHorizontal: inc_node.set_col(1); occ_sides = horiz_occ_sides_; break; case Wall::kVertical: inc_node.set_row(1); occ_sides = vert_occ_sides_; break; case Wall::kInvalid: default: return -1; } tmp_occupied_nodes_.clear(); Node node(wall.row(), wall.col()); NodeOccupiedSide occ_side; for (int i = 0; i <= wall.cnt(); ++i) { // wall extends outside the board if ((node.row() > size_) || (node.col() > size_)) { rc = -1; break; } if (i == 0) { occ_side = occ_sides[0]; } else if (i < wall.cnt()) { occ_side = occ_sides[1]; } else { occ_side = occ_sides[2]; } // new wall intersects with earlier added wall if ((occupied_nodes_.count(node) != 0) && (((occupied_nodes_[node] & occ_side) != 0) || ((occupied_nodes_[node] | occ_side) == NodeOccupiedSide::kAll))) { rc = -1; break; } else { tmp_occupied_nodes_[node] = occ_side; } node += inc_node; } return rc; } void WallGrid::apply_tmp_wall() { for (auto it : tmp_occupied_nodes_) { occupied_nodes_[it.first] |= it.second; } tmp_occupied_nodes_.clear(); } } // namespace Quoridor
#include "wall_grid.hpp" namespace Quoridor { enum NodeOccupiedSide { kBottom = 1, kLeft = 2, kRight = 4, kUp = 8, kVertical = kBottom | kUp, kHorizontal = kLeft | kRight, kAll = 15 }; static const NodeOccupiedSide horiz_occ_sides_[] = { NodeOccupiedSide::kRight, NodeOccupiedSide::kHorizontal, NodeOccupiedSide::kLeft, }; static const NodeOccupiedSide vert_occ_sides_[] = { NodeOccupiedSide::kUp, NodeOccupiedSide::kVertical, NodeOccupiedSide::kBottom, }; WallGrid::WallGrid(int size) : occupied_nodes_(), tmp_occupied_nodes_(), size_(size) { } WallGrid::~WallGrid() { } int WallGrid::add_wall(const Wall &wall) { if (add_tmp_wall(wall) == 0) { apply_tmp_wall(); return 0; } return -1; } int WallGrid::add_tmp_wall(const Wall &wall) { int rc = 0; if ((wall.row() < 0) || (wall.row() >= size_) || (wall.col() < 0) || (wall.col() >= size_)) { return -1; } else if ((wall.orientation() == Wall::kHorizontal) && ((wall.row() == 0) || (wall.row() == size_ - 1) || (wall.col() + wall.cnt() >= size_))) { return -1; } else if ((wall.orientation() == Wall::kVertical) && ((wall.col() == 0) || (wall.col() == size_ - 1) || (wall.row() + wall.cnt() >= size_))) { return -1; } Node inc_node(0, 0); const NodeOccupiedSide *occ_sides; switch (wall.orientation()) { case Wall::kHorizontal: inc_node.set_col(1); occ_sides = horiz_occ_sides_; break; case Wall::kVertical: inc_node.set_row(1); occ_sides = vert_occ_sides_; break; case Wall::kInvalid: default: return -1; } tmp_occupied_nodes_.clear(); Node node(wall.row(), wall.col()); NodeOccupiedSide occ_side; for (int i = 0; i <= wall.cnt(); ++i) { if (i == 0) { occ_side = occ_sides[0]; } else if (i < wall.cnt()) { occ_side = occ_sides[1]; } else { occ_side = occ_sides[2]; } // new wall intersects with earlier added wall if ((occupied_nodes_.count(node) != 0) && (((occupied_nodes_[node] & occ_side) != 0) || ((occupied_nodes_[node] | occ_side) == NodeOccupiedSide::kAll))) { rc = -1; break; } else { tmp_occupied_nodes_[node] = occ_side; } node += inc_node; } return rc; } void WallGrid::apply_tmp_wall() { for (auto it : tmp_occupied_nodes_) { occupied_nodes_[it.first] |= it.second; } tmp_occupied_nodes_.clear(); } } // namespace Quoridor
Fix placing wall at WallGrid
Fix placing wall at WallGrid
C++
mit
sfod/quoridor
15a7e16b124ac5d9330a651febb389216b9fb183
src/libutil/filesystem.cpp
src/libutil/filesystem.cpp
/* Copyright 2008 Larry Gritz and the other authors and 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. * Neither the name of the software's owners 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. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #ifdef _WIN32 #include <windows.h> #include <shellapi.h> #endif #include "dassert.h" #include "ustring.h" #include "filesystem.h" OIIO_NAMESPACE_ENTER { std::string Filesystem::filename (const std::string &filepath) { // To simplify dealing with platform-specific separators and whatnot, // just use the Boost routines: #if BOOST_FILESYSTEM_VERSION == 3 return boost::filesystem::path(filepath).filename().string(); #else return boost::filesystem::path(filepath).filename(); #endif } std::string Filesystem::extension (const std::string &filepath, bool include_dot) { std::string s; #if BOOST_FILESYSTEM_VERSION == 3 s = boost::filesystem::path(filepath).extension().string(); #else s = boost::filesystem::path(filepath).extension(); #endif if (! include_dot && !s.empty() && s[0] == '.') s.erase (0, 1); // erase the first character return s; } std::string Filesystem::parent_path (const std::string &filepath) { return boost::filesystem::path(filepath).parent_path().string(); } std::string Filesystem::replace_extension (const std::string &filepath, const std::string &new_extension) { return boost::filesystem::path(filepath).replace_extension(new_extension).string(); } void Filesystem::searchpath_split (const std::string &searchpath, std::vector<std::string> &dirs, bool validonly) { dirs.clear(); std::string path_copy = searchpath; std::string last_token; typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep(":;"); tokenizer tokens (searchpath, sep); for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); last_token = *tok_iter, ++tok_iter) { std::string path = *tok_iter; #ifdef _WIN32 // On Windows, we might see something like "a:foo" and any human // would know that it means drive/directory 'a:foo', NOT // separate directories 'a' and 'foo'. Implement the obvious // heuristic here. Note that this means that we simply don't // correctly support searching in *relative* directories that // consist of a single letter. if (last_token.length() == 1 && last_token[0] != '.') { // If the last token was a single letter, try prepending it path = last_token + ":" + (*tok_iter); } else #endif path = *tok_iter; // Kill trailing slashes (but not simple "/") size_t len = path.length(); while (len > 1 && (path[len-1] == '/' || path[len-1] == '\\')) path.erase (--len); // If it's a valid directory, or if validonly is false, add it // to the list if (!validonly || Filesystem::is_directory (path)) dirs.push_back (path); } #if 0 std::cerr << "Searchpath = '" << searchpath << "'\n"; BOOST_FOREACH (std::string &d, dirs) std::cerr << "\tPath = '" << d << "'\n"; std::cerr << "\n"; #endif } std::string Filesystem::searchpath_find (const std::string &filename, const std::vector<std::string> &dirs, bool testcwd, bool recursive) { bool abs = Filesystem::path_is_absolute (filename); // If it's an absolute filename, or if we want to check "." first, // then start by checking filename outright. if (testcwd || abs) { if (Filesystem::is_regular (filename)) return filename; } // Relative filename, not yet found -- try each directory in turn BOOST_FOREACH (const std::string &d, dirs) { // std::cerr << "\tPath = '" << d << "'\n"; boost::filesystem::path f = d; f /= filename; // std::cerr << "\tTesting '" << f << "'\n"; if (Filesystem::is_regular (f.string())) { // std::cerr << "Found '" << f << "'\n"; return f.string(); } if (recursive && Filesystem::is_directory (d)) { std::vector<std::string> subdirs; for (boost::filesystem::directory_iterator s(d); s != boost::filesystem::directory_iterator(); ++s) if (Filesystem::is_directory(s->path().string())) subdirs.push_back (s->path().string()); std::string found = searchpath_find (filename, subdirs, false, true); if (found.size()) return found; } } return std::string(); } bool Filesystem::get_directory_entries (const std::string &dirname, std::vector<std::string> &filenames, bool recursive, const std::string &filter_regex) { filenames.clear (); if (dirname.size() && ! is_directory(dirname)) return false; boost::filesystem::path dirpath (dirname.size() ? dirname : std::string(".")); boost::regex re (filter_regex); if (recursive) { for (boost::filesystem::recursive_directory_iterator s (dirpath); s != boost::filesystem::recursive_directory_iterator(); ++s) { std::string file = s->path().string(); if (!filter_regex.size() || boost::regex_search (file, re)) filenames.push_back (file); } } else { for (boost::filesystem::directory_iterator s (dirpath); s != boost::filesystem::directory_iterator(); ++s) { std::string file = s->path().string(); if (!filter_regex.size() || boost::regex_search (file, re)) filenames.push_back (file); } } return true; } bool Filesystem::path_is_absolute (const std::string &path, bool dot_is_absolute) { // "./foo" is considered absolute if dot_is_absolute is true. // Don't get confused by ".foo", which is not absolute! size_t len = path.length(); if (!len) return false; return (path[0] == '/') || (dot_is_absolute && path[0] == '.' && path[1] == '/') || (dot_is_absolute && path[0] == '.' && path[1] == '.' && path[2] == '/') #ifdef _WIN32 || path[0] == '\\' || (dot_is_absolute && path[0] == '.' && path[1] == '\\') || (dot_is_absolute && path[0] == '.' && path[1] == '.' && path[2] == '\\') || (isalpha(path[0]) && path[1] == ':') #endif ; } bool Filesystem::exists (const std::string &path) { bool r = false; try { r = boost::filesystem::exists (path); } catch (const std::exception &e) { r = false; } return r; } bool Filesystem::is_directory (const std::string &path) { bool r = false; try { r = boost::filesystem::is_directory (path); } catch (const std::exception &e) { r = false; } return r; } bool Filesystem::is_regular (const std::string &path) { bool r = false; try { r = boost::filesystem::is_regular_file (path); } catch (const std::exception &e) { r = false; } return r; } FILE* Filesystem::fopen (const std::string &path, const std::string &mode) { #ifdef _WIN32 // on Windows fopen does not accept UTF-8 paths, so we convert to wide char std::wstring wpath = Strutil::utf8_to_utf16 (path); std::wstring wmode = Strutil::utf8_to_utf16 (mode); return ::_wfopen (wpath.c_str(), wmode.c_str()); #else // on Unix platforms passing in UTF-8 works return ::fopen (path.c_str(), mode.c_str()); #endif } void Filesystem::open (std::ifstream &stream, const std::string &path, std::ios_base::openmode mode) { #ifdef _WIN32 // Windows std::ifstream accepts non-standard wchar_t* std::wstring wpath = Strutil::utf8_to_utf16(path); stream.open (wpath.c_str(), mode); #else stream.open (path.c_str(), mode); #endif } void Filesystem::open (std::ofstream &stream, const std::string &path, std::ios_base::openmode mode) { #ifdef _WIN32 // Windows std::ofstream accepts non-standard wchar_t* std::wstring wpath = Strutil::utf8_to_utf16 (path); stream.open (wpath.c_str(), mode); #else stream.open (path.c_str(), mode); #endif } std::time_t Filesystem::last_write_time (const std::string& path) { #ifdef _WIN32 std::wstring wpath = Strutil::utf8_to_utf16 (path); return boost::filesystem::last_write_time (wpath); #else return boost::filesystem::last_write_time (path); #endif } void Filesystem::last_write_time (const std::string& path, std::time_t time) { #ifdef _WIN32 std::wstring wpath = Strutil::utf8_to_utf16 (path); boost::filesystem::last_write_time (wpath, time); #else boost::filesystem::last_write_time (path, time); #endif } void Filesystem::convert_native_arguments (int argc, const char *argv[]) { #ifdef _WIN32 // Windows only, standard main() entry point does not accept unicode file // paths, here we retrieve wide char arguments and convert them to utf8 if (argc == 0) return; int native_argc; wchar_t **native_argv = CommandLineToArgvW (GetCommandLineW (), &native_argc); if (!native_argv || native_argc != argc) return; for (int i = 0; i < argc; i++) { std::string utf8_arg = Strutil::utf16_to_utf8 (native_argv[i]); argv[i] = ustring (utf8_arg).c_str(); } #endif } } OIIO_NAMESPACE_EXIT
/* Copyright 2008 Larry Gritz and the other authors and 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. * Neither the name of the software's owners 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. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #ifdef _WIN32 #include <windows.h> #include <shellapi.h> #endif #include "dassert.h" #include "ustring.h" #include "filesystem.h" OIIO_NAMESPACE_ENTER { std::string Filesystem::filename (const std::string &filepath) { // To simplify dealing with platform-specific separators and whatnot, // just use the Boost routines: #if BOOST_FILESYSTEM_VERSION == 3 return boost::filesystem::path(filepath).filename().string(); #else return boost::filesystem::path(filepath).filename(); #endif } std::string Filesystem::extension (const std::string &filepath, bool include_dot) { std::string s; #if BOOST_FILESYSTEM_VERSION == 3 s = boost::filesystem::path(filepath).extension().string(); #else s = boost::filesystem::path(filepath).extension(); #endif if (! include_dot && !s.empty() && s[0] == '.') s.erase (0, 1); // erase the first character return s; } std::string Filesystem::parent_path (const std::string &filepath) { return boost::filesystem::path(filepath).parent_path().string(); } std::string Filesystem::replace_extension (const std::string &filepath, const std::string &new_extension) { return boost::filesystem::path(filepath).replace_extension(new_extension).string(); } void Filesystem::searchpath_split (const std::string &searchpath, std::vector<std::string> &dirs, bool validonly) { dirs.clear(); std::string path_copy = searchpath; std::string last_token; typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep(":;"); tokenizer tokens (searchpath, sep); for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); last_token = *tok_iter, ++tok_iter) { std::string path = *tok_iter; #ifdef _WIN32 // On Windows, we might see something like "a:foo" and any human // would know that it means drive/directory 'a:foo', NOT // separate directories 'a' and 'foo'. Implement the obvious // heuristic here. Note that this means that we simply don't // correctly support searching in *relative* directories that // consist of a single letter. if (last_token.length() == 1 && last_token[0] != '.') { // If the last token was a single letter, try prepending it path = last_token + ":" + (*tok_iter); } else #endif path = *tok_iter; // Kill trailing slashes (but not simple "/") size_t len = path.length(); while (len > 1 && (path[len-1] == '/' || path[len-1] == '\\')) path.erase (--len); // If it's a valid directory, or if validonly is false, add it // to the list if (!validonly || Filesystem::is_directory (path)) dirs.push_back (path); } #if 0 std::cerr << "Searchpath = '" << searchpath << "'\n"; BOOST_FOREACH (std::string &d, dirs) std::cerr << "\tPath = '" << d << "'\n"; std::cerr << "\n"; #endif } std::string Filesystem::searchpath_find (const std::string &filename, const std::vector<std::string> &dirs, bool testcwd, bool recursive) { bool abs = Filesystem::path_is_absolute (filename); // If it's an absolute filename, or if we want to check "." first, // then start by checking filename outright. if (testcwd || abs) { if (Filesystem::is_regular (filename)) return filename; } // Relative filename, not yet found -- try each directory in turn BOOST_FOREACH (const std::string &d, dirs) { // std::cerr << "\tPath = '" << d << "'\n"; boost::filesystem::path f = d; f /= filename; // std::cerr << "\tTesting '" << f << "'\n"; if (Filesystem::is_regular (f.string())) { // std::cerr << "Found '" << f << "'\n"; return f.string(); } if (recursive && Filesystem::is_directory (d)) { std::vector<std::string> subdirs; for (boost::filesystem::directory_iterator s(d); s != boost::filesystem::directory_iterator(); ++s) if (Filesystem::is_directory(s->path().string())) subdirs.push_back (s->path().string()); std::string found = searchpath_find (filename, subdirs, false, true); if (found.size()) return found; } } return std::string(); } bool Filesystem::get_directory_entries (const std::string &dirname, std::vector<std::string> &filenames, bool recursive, const std::string &filter_regex) { filenames.clear (); if (dirname.size() && ! is_directory(dirname)) return false; boost::filesystem::path dirpath (dirname.size() ? dirname : std::string(".")); boost::regex re (filter_regex); if (recursive) { for (boost::filesystem::recursive_directory_iterator s (dirpath); s != boost::filesystem::recursive_directory_iterator(); ++s) { std::string file = s->path().string(); if (!filter_regex.size() || boost::regex_search (file, re)) filenames.push_back (file); } } else { for (boost::filesystem::directory_iterator s (dirpath); s != boost::filesystem::directory_iterator(); ++s) { std::string file = s->path().string(); if (!filter_regex.size() || boost::regex_search (file, re)) filenames.push_back (file); } } return true; } bool Filesystem::path_is_absolute (const std::string &path, bool dot_is_absolute) { // "./foo" is considered absolute if dot_is_absolute is true. // Don't get confused by ".foo", which is not absolute! size_t len = path.length(); if (!len) return false; return (path[0] == '/') || (dot_is_absolute && path[0] == '.' && path[1] == '/') || (dot_is_absolute && path[0] == '.' && path[1] == '.' && path[2] == '/') #ifdef _WIN32 || path[0] == '\\' || (dot_is_absolute && path[0] == '.' && path[1] == '\\') || (dot_is_absolute && path[0] == '.' && path[1] == '.' && path[2] == '\\') || (isalpha(path[0]) && path[1] == ':') #endif ; } bool Filesystem::exists (const std::string &path) { bool r = false; try { r = boost::filesystem::exists (path); } catch (const std::exception &) { r = false; } return r; } bool Filesystem::is_directory (const std::string &path) { bool r = false; try { r = boost::filesystem::is_directory (path); } catch (const std::exception &) { r = false; } return r; } bool Filesystem::is_regular (const std::string &path) { bool r = false; try { r = boost::filesystem::is_regular_file (path); } catch (const std::exception &) { r = false; } return r; } FILE* Filesystem::fopen (const std::string &path, const std::string &mode) { #ifdef _WIN32 // on Windows fopen does not accept UTF-8 paths, so we convert to wide char std::wstring wpath = Strutil::utf8_to_utf16 (path); std::wstring wmode = Strutil::utf8_to_utf16 (mode); return ::_wfopen (wpath.c_str(), wmode.c_str()); #else // on Unix platforms passing in UTF-8 works return ::fopen (path.c_str(), mode.c_str()); #endif } void Filesystem::open (std::ifstream &stream, const std::string &path, std::ios_base::openmode mode) { #ifdef _WIN32 // Windows std::ifstream accepts non-standard wchar_t* std::wstring wpath = Strutil::utf8_to_utf16(path); stream.open (wpath.c_str(), mode); #else stream.open (path.c_str(), mode); #endif } void Filesystem::open (std::ofstream &stream, const std::string &path, std::ios_base::openmode mode) { #ifdef _WIN32 // Windows std::ofstream accepts non-standard wchar_t* std::wstring wpath = Strutil::utf8_to_utf16 (path); stream.open (wpath.c_str(), mode); #else stream.open (path.c_str(), mode); #endif } std::time_t Filesystem::last_write_time (const std::string& path) { #ifdef _WIN32 std::wstring wpath = Strutil::utf8_to_utf16 (path); return boost::filesystem::last_write_time (wpath); #else return boost::filesystem::last_write_time (path); #endif } void Filesystem::last_write_time (const std::string& path, std::time_t time) { #ifdef _WIN32 std::wstring wpath = Strutil::utf8_to_utf16 (path); boost::filesystem::last_write_time (wpath, time); #else boost::filesystem::last_write_time (path, time); #endif } void Filesystem::convert_native_arguments (int argc, const char *argv[]) { #ifdef _WIN32 // Windows only, standard main() entry point does not accept unicode file // paths, here we retrieve wide char arguments and convert them to utf8 if (argc == 0) return; int native_argc; wchar_t **native_argv = CommandLineToArgvW (GetCommandLineW (), &native_argc); if (!native_argv || native_argc != argc) return; for (int i = 0; i < argc; i++) { std::string utf8_arg = Strutil::utf16_to_utf8 (native_argv[i]); argv[i] = ustring (utf8_arg).c_str(); } #endif } } OIIO_NAMESPACE_EXIT
Fix unused variable warnings.
Fix unused variable warnings.
C++
bsd-3-clause
lgritz/oiio,OpenImageIO/oiio,cwilling/oiio,bdeluca/oiio,bdeluca/oiio,mcanthony/oiio,micler/oiio,OpenImageIO/oiio,OpenImageIO/oiio,mcanthony/oiio,YangYangTL/oiio,scott-wilson/oiio,sambler/oiio,sambler/oiio,YangYangTL/oiio,lgritz/oiio,micler/oiio,scott-wilson/oiio,lgritz/oiio,YangYangTL/oiio,cwilling/oiio,scott-wilson/oiio,bdeluca/oiio,scott-wilson/oiio,bdeluca/oiio,YangYangTL/oiio,micler/oiio,micler/oiio,lgritz/oiio,mcanthony/oiio,sambler/oiio,mcanthony/oiio,cwilling/oiio,sambler/oiio,cwilling/oiio,OpenImageIO/oiio
f6f005ebb6d7b5b9e25d9e74564ad155f92d7f7d
Tests/OgreMain/src/ZipArchiveTests.cpp
Tests/OgreMain/src/ZipArchiveTests.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "ZipArchiveTests.h" #include "OgreZip.h" #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #include "macUtils.h" #endif using namespace Ogre; // Register the suite CPPUNIT_TEST_SUITE_REGISTRATION( ZipArchiveTests ); void ZipArchiveTests::setUp() { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE testPath = macBundlePath() + "/Contents/Resources/Media/misc/ArchiveTest.zip"; #elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 testPath = "./Tests/OgreMain/misc/ArchiveTest.zip"; #else testPath = "../Tests/OgreMain/misc/ArchiveTest.zip"; #endif } void ZipArchiveTests::tearDown() { } void ZipArchiveTests::testListNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.list(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testListRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.list(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file4.material"), vec->at(3)); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(4)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(5)); } void ZipArchiveTests::testListFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.listFileInfo(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.basename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.basename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testListFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.listFileInfo(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.basename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.basename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.basename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.basename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); FileInfo& fi1 = vec->at(4); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.basename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(5); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.basename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.find("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testFindRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.find("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file4.material"), vec->at(3)); } void ZipArchiveTests::testFindFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.findFileInfo("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.basename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.basename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.findFileInfo("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.basename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.basename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.basename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.basename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); } void ZipArchiveTests::testFileRead() { ZipArchive arch(testPath, "Zip"); arch.load(); DataStreamPtr stream = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream->getLine()); CPPUNIT_ASSERT(stream->eof()); } void ZipArchiveTests::testReadInterleave() { // Test overlapping reads from same archive ZipArchive arch(testPath, "Zip"); arch.load(); // File 1 DataStreamPtr stream1 = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream1->getLine()); // File 2 DataStreamPtr stream2 = arch.open("rootfile2.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 2"), stream2->getLine()); // File 1 CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream1->getLine()); CPPUNIT_ASSERT(stream1->eof()); // File 2 CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 6 in file 2"), stream2->getLine()); CPPUNIT_ASSERT(stream2->eof()); }
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "ZipArchiveTests.h" #include "OgreZip.h" #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #include "macUtils.h" #endif using namespace Ogre; // Register the suite CPPUNIT_TEST_SUITE_REGISTRATION( ZipArchiveTests ); void ZipArchiveTests::setUp() { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE testPath = macBundlePath() + "/Contents/Resources/Media/misc/ArchiveTest.zip"; #elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 testPath = "./Tests/OgreMain/misc/ArchiveTest.zip"; #else testPath = "../Tests/OgreMain/misc/ArchiveTest.zip"; #endif } void ZipArchiveTests::tearDown() { } void ZipArchiveTests::testListNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.list(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testListRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.list(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3)); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(4)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(5)); } void ZipArchiveTests::testListFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.listFileInfo(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testListFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.listFileInfo(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); FileInfo& fi1 = vec->at(4); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(5); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.find("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testFindRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.find("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3)); } void ZipArchiveTests::testFindFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.findFileInfo("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.findFileInfo("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); } void ZipArchiveTests::testFileRead() { ZipArchive arch(testPath, "Zip"); arch.load(); DataStreamPtr stream = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream->getLine()); CPPUNIT_ASSERT(stream->eof()); } void ZipArchiveTests::testReadInterleave() { // Test overlapping reads from same archive ZipArchive arch(testPath, "Zip"); arch.load(); // File 1 DataStreamPtr stream1 = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream1->getLine()); // File 2 DataStreamPtr stream2 = arch.open("rootfile2.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 2"), stream2->getLine()); // File 1 CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream1->getLine()); CPPUNIT_ASSERT(stream1->eof()); // File 2 CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 6 in file 2"), stream2->getLine()); CPPUNIT_ASSERT(stream2->eof()); }
Update Zip unit tests
Update Zip unit tests --HG-- branch : v1-9
C++
mit
digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre
1735ba114e444f914fab50488f09545d48cd6e06
src/location/qlandmark.cpp
src/location/qlandmark.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qlandmark.h" #include "qlandmark_p.h" #include "qlandmarkcategory_p.h" #include "qlandmarkcategoryid.h" #include "qlandmarkid.h" #include "qlandmarkid_p.h" #include "qgeoaddress.h" #include "qgeocoordinate.h" #include "qgeoplace.h" #include "qgeoplace_p.h" #include <QVariant> #include <QStringList> QTM_USE_NAMESPACE // ----- QLandmarkPrivate ----- QLandmarkPrivate::QLandmarkPrivate() : QGeoPlacePrivate() { type = QGeoPlace::LandmarkType; radius = -1.0; } QLandmarkPrivate::QLandmarkPrivate(const QGeoPlacePrivate &other) : QGeoPlacePrivate(other) { type = QGeoPlace::LandmarkType; radius = -1.0; } QLandmarkPrivate::QLandmarkPrivate(const QLandmarkPrivate &other) : QGeoPlacePrivate(other), name(other.name), categoryIds(other.categoryIds), description(other.description), iconUrl(other.iconUrl), radius(other.radius), attributes(other.attributes), phone(other.phone), url(other.url), id(other.id) { } QLandmarkPrivate::~QLandmarkPrivate() {} QLandmarkPrivate& QLandmarkPrivate::operator= (const QLandmarkPrivate & other) { QGeoPlacePrivate::operator =(other); name = other.name; description = other.description; iconUrl = other.iconUrl; radius = other.radius; phone = other.phone; url = other.url; categoryIds = other.categoryIds; attributes = other.attributes; id = other.id; return *this; } bool QLandmarkPrivate::operator== (const QLandmarkPrivate &other) const { return (QGeoPlacePrivate::operator== (other) && (name == other.name) && (description == other.description) && (iconUrl == other.iconUrl) && (radius == other.radius) && (phone == other.phone) && (url == other.url) && (categoryIds == other.categoryIds) && (attributes == other.attributes) && (id == other.id)); } /*! \class QLandmark \ingroup landmarks-main \brief The QLandmark class represents a location or point of interest of some significance. Each landmark consists of a number of properties such as name, coordinates, descriptoin etc. Landmarks may also be assigned a set of generic attributes which may be accessed and modified by using the attribute() and setAttribute() functions. Each QLandmark may be associated with zero or more categories. A category defines a type of landmark such as restaurant or cinema. To set the category that a landmark belongs to, use the setCategoryId() or addCategoryId() functions. A landmark may be removed from a category by using the removeCategoryId() function. Some landmarks may be designated as read-only, e.g. a publically accessible landmark server may not want some of its content to be editable. Localization is only possible for landmarks that are read-only. If the landmark store supports localization, the locale may be set through a QLandmarkManager's parameters and whenever landmarks are retrieved, the translated names are used. The \c {QLandmarkManager::isReadOnly(const QLandmarkyId &)} function may be used to determine if a category is read-only. Each QLandmark is an in memory representation of a landmark; it does not reflect the actual landmark state in persistent storage until the appropriate synchronization method is called on the QLandmarkManager(e.g. \l {QLandmarkManager::saveLandmark()} {saveLandmark()}, \l {QLandmarkManager::removeLandmark()} {removeLandmark()}). */ /*! Constructs an new landmark. A new landmark will be assigned with invalid QLandmarkId. */ QLandmark::QLandmark() : QGeoPlace(new QLandmarkPrivate) { } /*! Constructs a new landmark from \a other. If other is a QLandmark instance this is equivalent to QLandmark(const QLandmark &other). If other::type() is QGeoPlace instance this will initialize just the coordinate and address of this landmark. Otherwise this is equivalent to QLandmark(). */ QLandmark::QLandmark(const QGeoPlace &other) : QGeoPlace(other) { switch (other.type()) { case QGeoPlace::GeoPlaceType: // The QGeoPlace copy construct will increase the reference count // of other.d_ptr by 1. // Deleting our copy of d_ptr will reverse this, allowing us // to create a new d_ptr of a different type without breaking other delete d_ptr; d_ptr = new QLandmarkPrivate(*(other.d_ptr.constData())); break; case QGeoPlace::LandmarkType: // nothing extra to do here break; default: // The QGeoPlace copy construct will increase the reference count // of other.d_ptr by 1. // Deleting our copy of d_ptr will reverse this, allowing us // to create a new d_ptr of a different type without breaking other delete d_ptr; d_ptr = new QLandmarkPrivate(); break; } } /*! Constructs a copy of \a other. */ QLandmark::QLandmark(const QLandmark &other) : QGeoPlace(other) { } /*! Destroys the landmark. */ QLandmark::~QLandmark() { } /*! Assigns \a other to this landmark and returns a reference to this landmark. */ QLandmark &QLandmark::operator= (const QLandmark & other) { d_ptr = other.d_ptr; return *this; } inline QLandmarkPrivate* QLandmark::d_func() { return reinterpret_cast<QLandmarkPrivate*>(d_ptr.data()); } inline const QLandmarkPrivate* QLandmark::d_func() const { return reinterpret_cast<const QLandmarkPrivate*>(d_ptr.constData()); } /*! Returns true if this landmark is equal to \a other, otherwise returns false. Two landmarks are considered equal if both the landmark details and identifiers are equal. \sa operator!=() */ bool QLandmark::operator== (const QLandmark &other) const { Q_D(const QLandmark); return *d == *(other.d_func()); } /*! \fn bool QLandmark::operator!= (const QLandmark &other) const Returns true if this landmark not is equal to \a other, otherwise returns false. \sa operator==() */ /*! Returns the name of the landmark. */ QString QLandmark::name() const { Q_D(const QLandmark); return d->name; } /*! Sets the \a name of the landmark. */ void QLandmark::setName(const QString &name) { Q_D(QLandmark); d->name = name; } /*! Returns a of list identifiers of categories that this landmark belongs to. \sa setCategoryIds() */ QList<QLandmarkCategoryId> QLandmark::categoryIds() const { Q_D(const QLandmark); return d->categoryIds; } /*! Sets the categories that this landmark belongs to via a list of \a categoryIds. \sa addCategoryId(), removeCategoryId() */ void QLandmark::setCategoryIds(const QList<QLandmarkCategoryId> &categoryIds) { Q_D(QLandmark); d->categoryIds.clear(); // remove duplicates for (int i = 0; i < categoryIds.size(); ++i) { if (!d->categoryIds.contains(categoryIds.at(i))) d->categoryIds.append(categoryIds.at(i)); } } /*! Adds another category that this landmark will be associated with via its \a categoryId. \sa setCategoryIds(), removeCategoryId() */ void QLandmark::addCategoryId(const QLandmarkCategoryId &categoryId) { Q_D(QLandmark); if (!d->categoryIds.contains(categoryId)) d->categoryIds.append(categoryId); } /*! Removes a category from a landmark, by using its \a categoryId. \sa addCategoryId(), categoryIds() */ void QLandmark::removeCategoryId(const QLandmarkCategoryId &categoryId) { Q_D(QLandmark); d->categoryIds.removeAll(categoryId); } /*! Returns a description of the landmark. */ QString QLandmark::description() const { Q_D(const QLandmark); return d->description; } /*! Sets the \a description of the landmark. */ void QLandmark::setDescription(const QString &description) { Q_D(QLandmark); d->description = description; } /*! Returns the url of the landmark's icon. */ QUrl QLandmark::iconUrl() const { Q_D(const QLandmark); return d->iconUrl; } /*! Sets the \a url of the landmark's icon. */ void QLandmark::setIconUrl(const QUrl &url) { Q_D(QLandmark); d->iconUrl = url; } /*! Returns the coverage radius of the landmark. The coverage radius is relevant for large landmarks such as cities. Note that landmark searches over a given area do not factor in the coverage radius. */ double QLandmark::radius() const { Q_D(const QLandmark); return d->radius; } /*! Sets the coverage \a radius of the landmark. */ void QLandmark::setRadius(double radius) { Q_D(QLandmark); d->radius = radius; } /*! Returns the value of the attribute corresponding to \a key. If the attribute doest exist, returns \a defaultValue. If no default value is specified, a default QVariant is returned. */ QVariant QLandmark::attribute(const QString &key, const QVariant &defaultValue) const { Q_D(const QLandmark); return d->attributes.value(key, defaultValue); } /*! Sets the \a value of the attribute corresponding to \a key. */ void QLandmark::setAttribute(const QString &key, const QVariant &value) { Q_D(QLandmark); d->attributes[key] = value; } /*! Returns a list of attribute keys. \sa attribute(), setAttribute() */ QStringList QLandmark::attributeKeys() const { Q_D(const QLandmark); return d->attributes.keys(); } /*! Returns the phone number of the landmark. */ QString QLandmark::phone() const { Q_D(const QLandmark); return d->phone; } /*! Sets the \a phone number of the landmark. */ void QLandmark::setPhone(const QString &phone) { Q_D(QLandmark); d->phone = phone; } /*! Returns the url of the landmark. */ QUrl QLandmark::url() const { Q_D(const QLandmark); return d->url; } /*! Sets the \a url of the landmark. */ void QLandmark::setUrl(const QUrl &url) { Q_D(QLandmark); d->url = url; } /*! Returns the identifier of the landmark. */ QLandmarkId QLandmark::landmarkId() const { Q_D(const QLandmark); return d->id; } /*! Sets the \a id of the landmark. Note that saving a new landmark using a QLandmarkManager will automatically assign the landmark a valid identifier. */ void QLandmark::setLandmarkId(const QLandmarkId &id) { Q_D(QLandmark); d->id = id; }
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qlandmark.h" #include "qlandmark_p.h" #include "qlandmarkcategory_p.h" #include "qlandmarkcategoryid.h" #include "qlandmarkid.h" #include "qlandmarkid_p.h" #include "qgeoaddress.h" #include "qgeocoordinate.h" #include "qgeoplace.h" #include "qgeoplace_p.h" #include <QVariant> #include <QStringList> QTM_USE_NAMESPACE // ----- QLandmarkPrivate ----- QLandmarkPrivate::QLandmarkPrivate() : QGeoPlacePrivate() { type = QGeoPlace::LandmarkType; radius = -1.0; } QLandmarkPrivate::QLandmarkPrivate(const QGeoPlacePrivate &other) : QGeoPlacePrivate(other) { type = QGeoPlace::LandmarkType; radius = -1.0; } QLandmarkPrivate::QLandmarkPrivate(const QLandmarkPrivate &other) : QGeoPlacePrivate(other), name(other.name), categoryIds(other.categoryIds), description(other.description), iconUrl(other.iconUrl), radius(other.radius), attributes(other.attributes), phone(other.phone), url(other.url), id(other.id) { } QLandmarkPrivate::~QLandmarkPrivate() {} QLandmarkPrivate& QLandmarkPrivate::operator= (const QLandmarkPrivate & other) { QGeoPlacePrivate::operator =(other); name = other.name; description = other.description; iconUrl = other.iconUrl; radius = other.radius; phone = other.phone; url = other.url; categoryIds = other.categoryIds; attributes = other.attributes; id = other.id; return *this; } bool QLandmarkPrivate::operator== (const QLandmarkPrivate &other) const { return (QGeoPlacePrivate::operator== (other) && (name == other.name) && (description == other.description) && (iconUrl == other.iconUrl) && (radius == other.radius) && (phone == other.phone) && (url == other.url) && (categoryIds == other.categoryIds) && (attributes == other.attributes) && (id == other.id)); } /*! \class QLandmark \ingroup landmarks-main \brief The QLandmark class represents a location or point of interest of some significance. Each landmark consists of a number of properties such as name, coordinates, descriptoin etc. Landmarks may also be assigned a set of generic attributes which may be accessed and modified by using the attribute() and setAttribute() functions. Each QLandmark may be associated with zero or more categories. A category defines a type of landmark such as restaurant or cinema. To set the category that a landmark belongs to, use the setCategoryId() or addCategoryId() functions. A landmark may be removed from a category by using the removeCategoryId() function. Some landmarks may be designated as read-only, e.g. a publically accessible landmark server may not want some of its content to be editable. Localization is only possible for landmarks that are read-only. If the landmark store supports localization, the locale may be set through a QLandmarkManager's parameters and whenever landmarks are retrieved, the translated names are used. The \c {QLandmarkManager::isReadOnly(const QLandmarkyId &)} function may be used to determine if a category is read-only. Each QLandmark is an in memory representation of a landmark; it does not reflect the actual landmark state in persistent storage until the appropriate synchronization method is called on the QLandmarkManager(e.g. \l {QLandmarkManager::saveLandmark()} {saveLandmark()}, \l {QLandmarkManager::removeLandmark()} {removeLandmark()}). */ /*! Constructs an new landmark. A new landmark will be assigned with invalid QLandmarkId. */ QLandmark::QLandmark() : QGeoPlace(new QLandmarkPrivate) { } /*! Constructs a new landmark from \a other. If other is a QLandmark instance this is equivalent to QLandmark(const QLandmark &other). If other::type() is QGeoPlace instance this will initialize just the coordinate and address of this landmark. Otherwise this is equivalent to QLandmark(). */ QLandmark::QLandmark(const QGeoPlace &other) : QGeoPlace(other) { switch (other.type()) { case QGeoPlace::GeoPlaceType: d_ptr = new QLandmarkPrivate(*(other.d_ptr.constData())); break; case QGeoPlace::LandmarkType: // nothing extra to do here break; default: d_ptr = new QLandmarkPrivate(); break; } } /*! Constructs a copy of \a other. */ QLandmark::QLandmark(const QLandmark &other) : QGeoPlace(other) { } /*! Destroys the landmark. */ QLandmark::~QLandmark() { } /*! Assigns \a other to this landmark and returns a reference to this landmark. */ QLandmark &QLandmark::operator= (const QLandmark & other) { d_ptr = other.d_ptr; return *this; } inline QLandmarkPrivate* QLandmark::d_func() { return reinterpret_cast<QLandmarkPrivate*>(d_ptr.data()); } inline const QLandmarkPrivate* QLandmark::d_func() const { return reinterpret_cast<const QLandmarkPrivate*>(d_ptr.constData()); } /*! Returns true if this landmark is equal to \a other, otherwise returns false. Two landmarks are considered equal if both the landmark details and identifiers are equal. \sa operator!=() */ bool QLandmark::operator== (const QLandmark &other) const { Q_D(const QLandmark); return *d == *(other.d_func()); } /*! \fn bool QLandmark::operator!= (const QLandmark &other) const Returns true if this landmark not is equal to \a other, otherwise returns false. \sa operator==() */ /*! Returns the name of the landmark. */ QString QLandmark::name() const { Q_D(const QLandmark); return d->name; } /*! Sets the \a name of the landmark. */ void QLandmark::setName(const QString &name) { Q_D(QLandmark); d->name = name; } /*! Returns a of list identifiers of categories that this landmark belongs to. \sa setCategoryIds() */ QList<QLandmarkCategoryId> QLandmark::categoryIds() const { Q_D(const QLandmark); return d->categoryIds; } /*! Sets the categories that this landmark belongs to via a list of \a categoryIds. \sa addCategoryId(), removeCategoryId() */ void QLandmark::setCategoryIds(const QList<QLandmarkCategoryId> &categoryIds) { Q_D(QLandmark); d->categoryIds.clear(); // remove duplicates for (int i = 0; i < categoryIds.size(); ++i) { if (!d->categoryIds.contains(categoryIds.at(i))) d->categoryIds.append(categoryIds.at(i)); } } /*! Adds another category that this landmark will be associated with via its \a categoryId. \sa setCategoryIds(), removeCategoryId() */ void QLandmark::addCategoryId(const QLandmarkCategoryId &categoryId) { Q_D(QLandmark); if (!d->categoryIds.contains(categoryId)) d->categoryIds.append(categoryId); } /*! Removes a category from a landmark, by using its \a categoryId. \sa addCategoryId(), categoryIds() */ void QLandmark::removeCategoryId(const QLandmarkCategoryId &categoryId) { Q_D(QLandmark); d->categoryIds.removeAll(categoryId); } /*! Returns a description of the landmark. */ QString QLandmark::description() const { Q_D(const QLandmark); return d->description; } /*! Sets the \a description of the landmark. */ void QLandmark::setDescription(const QString &description) { Q_D(QLandmark); d->description = description; } /*! Returns the url of the landmark's icon. */ QUrl QLandmark::iconUrl() const { Q_D(const QLandmark); return d->iconUrl; } /*! Sets the \a url of the landmark's icon. */ void QLandmark::setIconUrl(const QUrl &url) { Q_D(QLandmark); d->iconUrl = url; } /*! Returns the coverage radius of the landmark. The coverage radius is relevant for large landmarks such as cities. Note that landmark searches over a given area do not factor in the coverage radius. */ double QLandmark::radius() const { Q_D(const QLandmark); return d->radius; } /*! Sets the coverage \a radius of the landmark. */ void QLandmark::setRadius(double radius) { Q_D(QLandmark); d->radius = radius; } /*! Returns the value of the attribute corresponding to \a key. If the attribute doest exist, returns \a defaultValue. If no default value is specified, a default QVariant is returned. */ QVariant QLandmark::attribute(const QString &key, const QVariant &defaultValue) const { Q_D(const QLandmark); return d->attributes.value(key, defaultValue); } /*! Sets the \a value of the attribute corresponding to \a key. */ void QLandmark::setAttribute(const QString &key, const QVariant &value) { Q_D(QLandmark); d->attributes[key] = value; } /*! Returns a list of attribute keys. \sa attribute(), setAttribute() */ QStringList QLandmark::attributeKeys() const { Q_D(const QLandmark); return d->attributes.keys(); } /*! Returns the phone number of the landmark. */ QString QLandmark::phone() const { Q_D(const QLandmark); return d->phone; } /*! Sets the \a phone number of the landmark. */ void QLandmark::setPhone(const QString &phone) { Q_D(QLandmark); d->phone = phone; } /*! Returns the url of the landmark. */ QUrl QLandmark::url() const { Q_D(const QLandmark); return d->url; } /*! Sets the \a url of the landmark. */ void QLandmark::setUrl(const QUrl &url) { Q_D(QLandmark); d->url = url; } /*! Returns the identifier of the landmark. */ QLandmarkId QLandmark::landmarkId() const { Q_D(const QLandmark); return d->id; } /*! Sets the \a id of the landmark. Note that saving a new landmark using a QLandmarkManager will automatically assign the landmark a valid identifier. */ void QLandmark::setLandmarkId(const QLandmarkId &id) { Q_D(QLandmark); d->id = id; }
Fix compile error / remove unecessary deletes.
Fix compile error / remove unecessary deletes.
C++
lgpl-2.1
qtproject/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,enthought/qt-mobility
3334689c2140fb6ccbb47a625ff4eab9d2847190
sqlite-kvstore.hh
sqlite-kvstore.hh
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef SQLITE_BASE_H #define SQLITE_BASE_H 1 #include <sqlite3.h> #include "kvstore.hh" /** * A sqlite prepared statement. */ class PreparedStatement { public: /** * Construct a prepared statement. * * @param d the DB where the prepared statement will execute * @param query the query to prepare */ PreparedStatement(sqlite3 *d, const char *query); /** * Clean up. */ ~PreparedStatement(); /** * Bind a null-terminated string parameter to a binding in * this statement. * * @param pos the binding position (starting at 1) * @param s the value to bind */ void bind(int pos, const char *s); /** * Bind a string parameter to a binding in this statement. * * @param pos the binding position (starting at 1) * @param s the value to bind * @param nbytes number of bytes in the string. */ void bind(int pos, const char *s, size_t nbytes); /** * Execute a prepared statement that does not return results. * * @return how many rows were affected */ int execute(); /** * Execute a prepared statement that does return results * and/or return the next row. * * @return true if there are more rows after this one */ bool fetch(); /** * Reset the bindings. * * Call this before reusing a prepared statement. */ void reset(); /** * Get the value at a given column in the current row. * * Use this along with fetch. * * @param x the column number (starting at 1) * @return the value */ const char *column(int x); private: sqlite3 *db; sqlite3_stmt *st; }; /** * The sqlite driver. */ class BaseSqlite3 : public KVStore { public: /** * Construct an instance of sqlite with the given database name. */ BaseSqlite3(const char *fn); /** * Cleanup. */ ~BaseSqlite3(); /** * Reset database to a clean state. */ void reset(); /** * Begin a transaction (if not already in one). */ void begin(); /** * Commit a transaction (unless not currently in one). */ void commit(); /** * Rollback a transaction (unless not currently in one). */ void rollback(); protected: /** * Shortcut to execute a simple query. * * @param query a simple query with no bindings to execute directly */ void execute(const char *query); /** * After setting up the DB, this is called to initialize our * prepared statements. */ virtual void initStatements() {} /** * When tearing down, tear down the statements set up by * initStatements. */ virtual void destroyStatements() {} /** * Set up the tables. */ virtual void initTables() {} /** * Clean up the tables. */ virtual void destroyTables() {} protected: /** * Direct access to the DB. */ sqlite3 *db; void open(); void close(); private: const char *filename; bool intransaction; }; class Sqlite3 : public BaseSqlite3 { public: Sqlite3(const char *path, bool is_auditable=false) : BaseSqlite3(path), ins_stmt(NULL), sel_stmt(NULL), del_stmt(NULL), auditable(is_auditable) { open(); initTables(); initStatements(); } /** * Overrides set() to call the char* variant. */ void set(std::string &key, std::string &val, Callback<bool> &cb); /** * Overrides set(). */ void set(std::string &key, const char *val, size_t nbytes, Callback<bool> &cb); /** * Overrides get(). */ void get(std::string &key, Callback<GetValue> &cb); /** * Overrides del(). */ void del(std::string &key, Callback<bool> &cb); /** * Overrides dump */ virtual void dump(Callback<KVPair> &cb); protected: void initStatements(); void destroyStatements(); void initTables(); void destroyTables(); private: bool auditable; PreparedStatement *ins_stmt; PreparedStatement *sel_stmt; PreparedStatement *del_stmt; }; #endif /* SQLITE_BASE_H */
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef SQLITE_BASE_H #define SQLITE_BASE_H 1 #include <sqlite3.h> #include "kvstore.hh" /** * A sqlite prepared statement. */ class PreparedStatement { public: /** * Construct a prepared statement. * * @param d the DB where the prepared statement will execute * @param query the query to prepare */ PreparedStatement(sqlite3 *d, const char *query); /** * Clean up. */ ~PreparedStatement(); /** * Bind a null-terminated string parameter to a binding in * this statement. * * @param pos the binding position (starting at 1) * @param s the value to bind */ void bind(int pos, const char *s); /** * Bind a string parameter to a binding in this statement. * * @param pos the binding position (starting at 1) * @param s the value to bind * @param nbytes number of bytes in the string. */ void bind(int pos, const char *s, size_t nbytes); /** * Execute a prepared statement that does not return results. * * @return how many rows were affected */ int execute(); /** * Execute a prepared statement that does return results * and/or return the next row. * * @return true if there are more rows after this one */ bool fetch(); /** * Reset the bindings. * * Call this before reusing a prepared statement. */ void reset(); /** * Get the value at a given column in the current row. * * Use this along with fetch. * * @param x the column number (starting at 1) * @return the value */ const char *column(int x); private: sqlite3 *db; sqlite3_stmt *st; }; /** * The sqlite driver. */ class BaseSqlite3 : public KVStore { public: /** * Construct an instance of sqlite with the given database name. */ BaseSqlite3(const char *fn); /** * Cleanup. */ ~BaseSqlite3(); /** * Reset database to a clean state. */ void reset(); /** * Begin a transaction (if not already in one). */ void begin(); /** * Commit a transaction (unless not currently in one). */ void commit(); /** * Rollback a transaction (unless not currently in one). */ void rollback(); protected: /** * Shortcut to execute a simple query. * * @param query a simple query with no bindings to execute directly */ void execute(const char *query); /** * After setting up the DB, this is called to initialize our * prepared statements. */ virtual void initStatements() {} /** * When tearing down, tear down the statements set up by * initStatements. */ virtual void destroyStatements() {} /** * Set up the tables. */ virtual void initTables() {} /** * Clean up the tables. */ virtual void destroyTables() {} protected: /** * Direct access to the DB. */ sqlite3 *db; void open(); void close(); private: const char *filename; bool intransaction; }; class Sqlite3 : public BaseSqlite3 { public: Sqlite3(const char *path, bool is_auditable=false) : BaseSqlite3(path), auditable(is_auditable), ins_stmt(NULL), sel_stmt(NULL), del_stmt(NULL) { open(); initTables(); initStatements(); } /** * Overrides set() to call the char* variant. */ void set(std::string &key, std::string &val, Callback<bool> &cb); /** * Overrides set(). */ void set(std::string &key, const char *val, size_t nbytes, Callback<bool> &cb); /** * Overrides get(). */ void get(std::string &key, Callback<GetValue> &cb); /** * Overrides del(). */ void del(std::string &key, Callback<bool> &cb); /** * Overrides dump */ virtual void dump(Callback<KVPair> &cb); protected: void initStatements(); void destroyStatements(); void initTables(); void destroyTables(); private: bool auditable; PreparedStatement *ins_stmt; PreparedStatement *sel_stmt; PreparedStatement *del_stmt; }; #endif /* SQLITE_BASE_H */
Reorder the initialization sequence
Reorder the initialization sequence
C++
apache-2.0
jimwwalker/ep-engine,hisundar/ep-engine,teligent-ru/ep-engine,daverigby/ep-engine,jimwwalker/ep-engine,teligent-ru/ep-engine,sriganes/ep-engine,sriganes/ep-engine,membase/ep-engine,abhinavdangeti/ep-engine,abhinavdangeti/ep-engine,zbase/ep-engine,couchbaselabs/ep-engine,daverigby/ep-engine,membase/ep-engine,abhinavdangeti/ep-engine,abhinavdangeti/ep-engine,jimwwalker/ep-engine,daverigby/kv_engine,daverigby/kv_engine,zbase/ep-engine,couchbase/ep-engine,daverigby/kv_engine,teligent-ru/ep-engine,owendCB/ep-engine,abhinavdangeti/ep-engine,zbase/ep-engine,couchbaselabs/ep-engine,membase/ep-engine,couchbase/ep-engine,hisundar/ep-engine,zbase/ep-engine,daverigby/kv_engine,jimwwalker/ep-engine,teligent-ru/ep-engine,hisundar/ep-engine,owendCB/ep-engine,sriganes/ep-engine,couchbase/ep-engine,couchbaselabs/ep-engine,owendCB/ep-engine,membase/ep-engine,zbase/ep-engine,couchbase/ep-engine,couchbaselabs/ep-engine,owendCB/ep-engine,hisundar/ep-engine,couchbaselabs/ep-engine,daverigby/ep-engine,daverigby/ep-engine,sriganes/ep-engine
7c3af41deff2acd754329aa358a9414a0cf8793f
src/ArgParser.cpp
src/ArgParser.cpp
#include "ArgParser.h" #include <string.h> #include <tclap/CmdLine.h> #include <sstream> #include "ArgParseOutput.h" #include "Version.h" #include "Log.h" #include "PlatformSpecifics.h" #undef module_name #define module_name "ARGPARSER" ArgParser::ArgParser(int argc, char * * argv) { outDefault = "stdout"; noneDefault = "none"; ParseArguments(argc, (char const * *) argv); } ArgParser::~ArgParser() { } char * ArgParser::fromString(std::string str) { char * cstr = 0; if(str.size() > 0 && str != outDefault && str != noneDefault) { cstr = new char[str.size() + 1]; strcpy(cstr, str.c_str()); } return cstr; } template<typename T> void printParameter(std::stringstream & usage, TCLAP::ValueArg<T> & arg) { usage << " " << arg.longID() << std::endl; usage << " " << arg.getDescription(); if(!arg.isRequired()) { usage << " [" << arg.getValue() << "]"; } usage << std::endl; } void printParameter(std::stringstream & usage, TCLAP::SwitchArg & arg) { usage << " " << arg.longID() << std::endl; usage << " " << arg.getDescription(); if(!arg.isRequired()) { usage << " [" << (arg.getValue() ? "true" : "false") << "]"; } usage << std::endl; } void ArgParser::ParseArguments(int argc, char const * argv[]) { argv[0] = "ngmlr"; TCLAP::CmdLine cmd("", ' ', "", true); TCLAP::ValueArg<std::string> queryArg("q", "query", "Path to the read file (FASTA/Q, SAM/BAM)", true, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> refArg("r", "reference", "Path to the reference genome (FASTA/Q, can be gzipped)", true, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> outArg("o", "output", "Path to output file", false, outDefault, "file", cmd); TCLAP::ValueArg<std::string> vcfArg("", "vcf", "SNPs will be taken into account when building reference index", false, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> bedfilterArg("", "bed-filter", "Only reads in the regions specified by the BED file are read from the input file (requires BAM input)", false, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> presetArgs("x", "presets", "Parameter presets for different sequencing technologies", false, "pacbio", "pacbio, ont", cmd); TCLAP::ValueArg<float> minIdentityArg("i", "min-identity", "Alignments with an identity lower than this threshold will be discarded", false, minIdentity, "0-1", cmd); TCLAP::ValueArg<float> minResiduesArg("R", "min-residues", "Alignments containing less than <int> or (<float> * read length) residues will be discarded", false, minResidues, "int/float", cmd); TCLAP::ValueArg<float> sensitivityArg("s", "sensitivity", "", false, sensitivity, "0-1", cmd); TCLAP::ValueArg<int> threadsArg("t", "threads", "Number of threads", false, 1, "int", cmd); TCLAP::ValueArg<int> binSizeArg("", "bin-size", "Sets the size of the grid used during candidate search", false, binSize, "int", cmd); TCLAP::ValueArg<int> kmerLengthArg("k", "kmer-length", "K-mer length in bases", false, kmerLength, "10-15", cmd); TCLAP::ValueArg<int> kmerSkipArg("", "kmer-skip", "Number of k-mers to skip when building the lookup table from the reference", false, kmerSkip, "int", cmd); TCLAP::ValueArg<int> scoreMatchArg("", "match", "Match score", false, scoreMatch, "int", cmd); TCLAP::ValueArg<int> scoreMismatchArg("", "mismatch", "Mismatch score", false, scoreMismatch, "int", cmd); TCLAP::ValueArg<int> scoreGapOpenArg("", "gap-open", "Gap open score", false, scoreGapOpen, "int", cmd); TCLAP::ValueArg<int> scoreGapExtendArg("", "gap-extend", "Gap open extend", false, scoreGapExtend, "int", cmd); TCLAP::ValueArg<int> stdoutArg("", "stdout", "Debug mode", false, stdoutMode, "0-7", cmd); TCLAP::ValueArg<int> readpartLengthArg("", "subread-length", "Length of fragments reads are split into", false, readPartLength, "int", cmd); TCLAP::ValueArg<int> readpartCorridorArg("", "subread-corridor", "Length of corridor sub-reads are aligned with", false, readPartCorridor, "int", cmd); //csSearchTableLength = 0; //logLevel = 0; //16383, 255 //minKmerHits = 0; //maxCMRs = INT_MAX; TCLAP::SwitchArg noprogressArg("", "no-progress", "Don't print progress info while mapping", cmd, false); TCLAP::SwitchArg verboseArg("", "verbose", "Debug output", cmd, false); //bam = false; TCLAP::SwitchArg colorArg("", "color", "Colored command line output", cmd, false); //hardClip = false; //log = false; TCLAP::SwitchArg nolowqualitysplitArg("", "no-lowqualitysplit", "Don't split alignments with poor quality", cmd, false); TCLAP::SwitchArg nosmallInversionArg("", "no-smallinv", "Don't detect small inversions", cmd, false); TCLAP::SwitchArg printAllAlignmentsArg("", "print-all", "Print all alignments. Disable filtering. (debug)", cmd, false); //skipSave = false; //updateCheck = false; //writeUnmapped = true; TCLAP::SwitchArg fastArg("", "fast", "Debug switch (don't use if you don't know what you do)", cmd, false); std::stringstream usage; usage << "" << std::endl; usage << "Usage: ngmlr [options] -r <reference> -q <reads> [-o <output>]" << std::endl; usage << "" << std::endl; usage << "Input/Output:" << std::endl; printParameter<std::string>(usage, refArg); printParameter<std::string>(usage, queryArg); printParameter<std::string>(usage, outArg); usage << "" << std::endl; usage << "General:" << std::endl; printParameter<int>(usage, threadsArg); printParameter<std::string>(usage, presetArgs); printParameter<float>(usage, minIdentityArg); printParameter<float>(usage, minResiduesArg); printParameter(usage, nosmallInversionArg); printParameter(usage, nolowqualitysplitArg); printParameter(usage, verboseArg); printParameter(usage, noprogressArg); usage << "" << std::endl; usage << "Advanced:" << std::endl; printParameter<int>(usage, scoreMatchArg); printParameter<int>(usage, scoreMismatchArg); printParameter<int>(usage, scoreGapOpenArg); printParameter<int>(usage, scoreGapExtendArg); printParameter<int>(usage, kmerLengthArg); printParameter<int>(usage, kmerSkipArg); printParameter<int>(usage, binSizeArg); printParameter<int>(usage, readpartLengthArg); printParameter<int>(usage, readpartCorridorArg); printParameter<std::string>(usage, vcfArg); printParameter<std::string>(usage, bedfilterArg); cmd.setOutput(new ArgParseOutput(usage.str(), "")); cmd.parse(argc, argv); queryFile = fromString(queryArg.getValue()); referenceFile = fromString(refArg.getValue()); outputFile = fromString(outArg.getValue()); if(outputFile == outDefault) { outputFile = 0; } vcfFile = fromString(vcfArg.getValue()); bedFile = fromString(bedfilterArg.getValue()); minIdentity = minIdentityArg.getValue(); minResidues = minResiduesArg.getValue(); binSize = binSizeArg.getValue(); kmerLength = kmerLengthArg.getValue(); threads = threadsArg.getValue(); kmerSkip = kmerSkipArg.getValue(); scoreMatch = scoreMatchArg.getValue(); scoreMismatch = scoreMismatchArg.getValue(); scoreGapOpen = scoreGapOpenArg.getValue(); scoreGapExtend = scoreGapExtendArg.getValue(); stdoutMode = stdoutArg.getValue(); readPartCorridor = readpartCorridorArg.getValue(); readPartLength = readpartLengthArg.getValue(); progress = !noprogressArg.getValue(); color = colorArg.getValue(); verbose = verboseArg.getValue(); lowQualitySplit = !nolowqualitysplitArg.getValue(); smallInversionDetection = !nosmallInversionArg.getValue(); printAllAlignments = printAllAlignmentsArg.getValue(); fast = fastArg.getValue(); if (presetArgs.getValue() == "pacbio") { //Do nothing. Defaults are for Pacbio } else if (presetArgs.getValue() == "ont") { lowQualitySplit = (nolowqualitysplitArg.isSet()) ? lowQualitySplit : true; scoreMatch = (scoreMatchArg.isSet()) ? scoreMatch : 1; scoreMismatch = (scoreMatchArg.isSet()) ? scoreMismatch : -1; scoreGapOpen = (scoreGapOpenArg.isSet()) ? scoreGapOpen : -1; scoreGapExtend = (scoreGapExtendArg.isSet()) ? scoreGapExtend : -1; } else { std::cerr << "Preset " << presetArgs.getValue() << " not found" << std::endl; } std::stringstream fullCmd; fullCmd << std::string(argv[0]); for(int i = 1; i < argc; ++i) { fullCmd << " " << std::string(argv[i]); } fullCommandLineCall = fromString(fullCmd.str()); if(!FileExists(queryFile)) { Log.Error("Query file (%s) does not exist.", queryFile); } if(!FileExists(referenceFile)) { Log.Error("Reference file (%s) does not exist.", referenceFile); } if(bedFile != 0 && !FileExists(bedFile)) { Log.Error("BED filter file (%s) does not exist.", bedFile); } if(vcfFile != 0 && !FileExists(vcfFile)) { Log.Error("SNP file (%s) does not exist.", vcfFile); } }
#include "ArgParser.h" #include <string.h> #include <tclap/CmdLine.h> #include <sstream> #include "ArgParseOutput.h" #include "Version.h" #include "Log.h" #include "PlatformSpecifics.h" #undef module_name #define module_name "ARGPARSER" ArgParser::ArgParser(int argc, char * * argv) { outDefault = "stdout"; noneDefault = "none"; ParseArguments(argc, (char const * *) argv); } ArgParser::~ArgParser() { } char * ArgParser::fromString(std::string str) { char * cstr = 0; if(str.size() > 0 && str != outDefault && str != noneDefault) { cstr = new char[str.size() + 1]; strcpy(cstr, str.c_str()); } return cstr; } template<typename T> void printParameter(std::stringstream & usage, TCLAP::ValueArg<T> & arg) { usage << " " << arg.longID() << std::endl; usage << " " << arg.getDescription(); if(!arg.isRequired()) { usage << " [" << arg.getValue() << "]"; } usage << std::endl; } void printParameter(std::stringstream & usage, TCLAP::SwitchArg & arg) { usage << " " << arg.longID() << std::endl; usage << " " << arg.getDescription(); if(!arg.isRequired()) { usage << " [" << (arg.getValue() ? "true" : "false") << "]"; } usage << std::endl; } void ArgParser::ParseArguments(int argc, char const * argv[]) { argv[0] = "ngmlr"; TCLAP::CmdLine cmd("", ' ', "", true); TCLAP::ValueArg<std::string> queryArg("q", "query", "Path to the read file (FASTA/Q, SAM/BAM)", true, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> refArg("r", "reference", "Path to the reference genome (FASTA/Q, can be gzipped)", true, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> outArg("o", "output", "Path to output file", false, outDefault, "file", cmd); TCLAP::ValueArg<std::string> vcfArg("", "vcf", "SNPs will be taken into account when building reference index", false, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> bedfilterArg("", "bed-filter", "Only reads in the regions specified by the BED file are read from the input file (requires BAM input)", false, noneDefault, "file", cmd); TCLAP::ValueArg<std::string> presetArgs("x", "presets", "Parameter presets for different sequencing technologies", false, "pacbio", "pacbio, ont", cmd); TCLAP::ValueArg<float> minIdentityArg("i", "min-identity", "Alignments with an identity lower than this threshold will be discarded", false, minIdentity, "0-1", cmd); TCLAP::ValueArg<float> minResiduesArg("R", "min-residues", "Alignments containing less than <int> or (<float> * read length) residues will be discarded", false, minResidues, "int/float", cmd); TCLAP::ValueArg<float> sensitivityArg("s", "sensitivity", "", false, sensitivity, "0-1", cmd); TCLAP::ValueArg<int> threadsArg("t", "threads", "Number of threads", false, 1, "int", cmd); TCLAP::ValueArg<int> binSizeArg("", "bin-size", "Sets the size of the grid used during candidate search", false, binSize, "int", cmd); TCLAP::ValueArg<int> kmerLengthArg("k", "kmer-length", "K-mer length in bases", false, kmerLength, "10-15", cmd); TCLAP::ValueArg<int> kmerSkipArg("", "kmer-skip", "Number of k-mers to skip when building the lookup table from the reference", false, kmerSkip, "int", cmd); TCLAP::ValueArg<int> scoreMatchArg("", "match", "Match score", false, scoreMatch, "int", cmd); TCLAP::ValueArg<int> scoreMismatchArg("", "mismatch", "Mismatch score", false, scoreMismatch, "int", cmd); TCLAP::ValueArg<int> scoreGapOpenArg("", "gap-open", "Gap open score", false, scoreGapOpen, "int", cmd); TCLAP::ValueArg<int> scoreGapExtendArg("", "gap-extend", "Gap open extend", false, scoreGapExtend, "int", cmd); TCLAP::ValueArg<int> stdoutArg("", "stdout", "Debug mode", false, stdoutMode, "0-7", cmd); TCLAP::ValueArg<int> readpartLengthArg("", "subread-length", "Length of fragments reads are split into", false, readPartLength, "int", cmd); TCLAP::ValueArg<int> readpartCorridorArg("", "subread-corridor", "Length of corridor sub-reads are aligned with", false, readPartCorridor, "int", cmd); //csSearchTableLength = 0; //logLevel = 0; //16383, 255 //minKmerHits = 0; //maxCMRs = INT_MAX; TCLAP::SwitchArg noprogressArg("", "no-progress", "Don't print progress info while mapping", cmd, false); TCLAP::SwitchArg verboseArg("", "verbose", "Debug output", cmd, false); //bam = false; TCLAP::SwitchArg colorArg("", "color", "Colored command line output", cmd, false); //hardClip = false; //log = false; TCLAP::SwitchArg nolowqualitysplitArg("", "no-lowqualitysplit", "Don't split alignments with poor quality", cmd, false); TCLAP::SwitchArg nosmallInversionArg("", "no-smallinv", "Don't detect small inversions", cmd, false); TCLAP::SwitchArg printAllAlignmentsArg("", "print-all", "Print all alignments. Disable filtering. (debug)", cmd, false); //skipSave = false; //updateCheck = false; //writeUnmapped = true; TCLAP::SwitchArg fastArg("", "fast", "Debug switch (don't use if you don't know what you do)", cmd, false); std::stringstream usage; usage << "" << std::endl; usage << "Usage: ngmlr [options] -r <reference> -q <reads> [-o <output>]" << std::endl; usage << "" << std::endl; usage << "Input/Output:" << std::endl; printParameter<std::string>(usage, refArg); printParameter<std::string>(usage, queryArg); printParameter<std::string>(usage, outArg); usage << "" << std::endl; usage << "General:" << std::endl; printParameter<int>(usage, threadsArg); printParameter<std::string>(usage, presetArgs); printParameter<float>(usage, minIdentityArg); printParameter<float>(usage, minResiduesArg); printParameter(usage, nosmallInversionArg); printParameter(usage, nolowqualitysplitArg); printParameter(usage, verboseArg); printParameter(usage, noprogressArg); usage << "" << std::endl; usage << "Advanced:" << std::endl; printParameter<int>(usage, scoreMatchArg); printParameter<int>(usage, scoreMismatchArg); printParameter<int>(usage, scoreGapOpenArg); printParameter<int>(usage, scoreGapExtendArg); printParameter<int>(usage, kmerLengthArg); printParameter<int>(usage, kmerSkipArg); printParameter<int>(usage, binSizeArg); printParameter<int>(usage, readpartLengthArg); printParameter<int>(usage, readpartCorridorArg); printParameter<std::string>(usage, vcfArg); printParameter<std::string>(usage, bedfilterArg); cmd.setOutput(new ArgParseOutput(usage.str(), "")); cmd.parse(argc, argv); queryFile = fromString(queryArg.getValue()); referenceFile = fromString(refArg.getValue()); outputFile = fromString(outArg.getValue()); vcfFile = fromString(vcfArg.getValue()); bedFile = fromString(bedfilterArg.getValue()); minIdentity = minIdentityArg.getValue(); minResidues = minResiduesArg.getValue(); binSize = binSizeArg.getValue(); kmerLength = kmerLengthArg.getValue(); threads = threadsArg.getValue(); kmerSkip = kmerSkipArg.getValue(); scoreMatch = scoreMatchArg.getValue(); scoreMismatch = scoreMismatchArg.getValue(); scoreGapOpen = scoreGapOpenArg.getValue(); scoreGapExtend = scoreGapExtendArg.getValue(); stdoutMode = stdoutArg.getValue(); readPartCorridor = readpartCorridorArg.getValue(); readPartLength = readpartLengthArg.getValue(); progress = !noprogressArg.getValue(); color = colorArg.getValue(); verbose = verboseArg.getValue(); lowQualitySplit = !nolowqualitysplitArg.getValue(); smallInversionDetection = !nosmallInversionArg.getValue(); printAllAlignments = printAllAlignmentsArg.getValue(); fast = fastArg.getValue(); if (presetArgs.getValue() == "pacbio") { //Do nothing. Defaults are for Pacbio } else if (presetArgs.getValue() == "ont") { lowQualitySplit = (nolowqualitysplitArg.isSet()) ? lowQualitySplit : true; scoreMatch = (scoreMatchArg.isSet()) ? scoreMatch : 1; scoreMismatch = (scoreMatchArg.isSet()) ? scoreMismatch : -1; scoreGapOpen = (scoreGapOpenArg.isSet()) ? scoreGapOpen : -1; scoreGapExtend = (scoreGapExtendArg.isSet()) ? scoreGapExtend : -1; } else { std::cerr << "Preset " << presetArgs.getValue() << " not found" << std::endl; } std::stringstream fullCmd; fullCmd << std::string(argv[0]); for(int i = 1; i < argc; ++i) { fullCmd << " " << std::string(argv[i]); } fullCommandLineCall = fromString(fullCmd.str()); if(!FileExists(queryFile)) { Log.Error("Query file (%s) does not exist.", queryFile); } if(!FileExists(referenceFile)) { Log.Error("Reference file (%s) does not exist.", referenceFile); } if(bedFile != 0 && !FileExists(bedFile)) { Log.Error("BED filter file (%s) does not exist.", bedFile); } if(vcfFile != 0 && !FileExists(vcfFile)) { Log.Error("SNP file (%s) does not exist.", vcfFile); } }
Fix for -o/--output
Fix for -o/--output
C++
mit
philres/ngmlr,philres/ngmlr,philres/ngmlr,philres/ngmlr
090d2866f18ec9f25fd98a5846d4b3736d77f2df
Realm/ObjectStore/shared_realm.cpp
Realm/ObjectStore/shared_realm.cpp
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "shared_realm.hpp" #include "external_commit_helper.hpp" #include "realm_delegate.hpp" #include "schema.hpp" #include "transact_log_handler.hpp" #include <realm/commit_log.hpp> #include <realm/group_shared.hpp> #include <mutex> using namespace realm; RealmCache Realm::s_global_cache; Realm::Config::Config(const Config& c) : path(c.path) , read_only(c.read_only) , in_memory(c.in_memory) , cache(c.cache) , encryption_key(c.encryption_key) , schema_version(c.schema_version) , migration_function(c.migration_function) { if (c.schema) { schema = std::make_unique<Schema>(*c.schema); } } Realm::Config::~Config() = default; Realm::Config& Realm::Config::operator=(realm::Realm::Config const& c) { if (&c != this) { *this = Config(c); } return *this; } Realm::Realm(Config config) : m_config(std::move(config)) { try { if (m_config.read_only) { m_read_only_group = std::make_unique<Group>(m_config.path, m_config.encryption_key.data(), Group::mode_ReadOnly); m_group = m_read_only_group.get(); } else { m_history = realm::make_client_history(m_config.path, m_config.encryption_key.data()); SharedGroup::DurabilityLevel durability = m_config.in_memory ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full; m_shared_group = std::make_unique<SharedGroup>(*m_history, durability, m_config.encryption_key.data()); } } catch (util::File::PermissionDenied const& ex) { throw RealmFileException(RealmFileException::Kind::PermissionDenied, "Unable to open a realm at path '" + m_config.path + "'. Please use a path where your app has " + (m_config.read_only ? "read" : "read-write") + " permissions."); } catch (util::File::Exists const& ex) { throw RealmFileException(RealmFileException::Kind::Exists, "Unable to open a realm at path '" + m_config.path + "'"); } catch (util::File::AccessError const& ex) { throw RealmFileException(RealmFileException::Kind::AccessError, "Unable to open a realm at path '" + m_config.path + "'"); } catch (IncompatibleLockFile const&) { throw RealmFileException(RealmFileException::Kind::IncompatibleLockFile, "Realm file is currently open in another process " "which cannot share access with this process. All processes sharing a single file must be the same architecture."); } } Realm::~Realm() { if (m_notifier) { // might not exist yet if an error occurred during init m_notifier->remove_realm(this); } } Group *Realm::read_group() { if (!m_group) { m_group = &const_cast<Group&>(m_shared_group->begin_read()); } return m_group; } SharedRealm Realm::get_shared_realm(Config config) { if (config.cache) { if (SharedRealm realm = s_global_cache.get_realm(config.path)) { if (realm->config().read_only != config.read_only) { throw MismatchedConfigException("Realm at path already opened with different read permissions."); } if (realm->config().in_memory != config.in_memory) { throw MismatchedConfigException("Realm at path already opened with different inMemory settings."); } if (realm->config().encryption_key != config.encryption_key) { throw MismatchedConfigException("Realm at path already opened with a different encryption key."); } if (realm->config().schema_version != config.schema_version && config.schema_version != ObjectStore::NotVersioned) { throw MismatchedConfigException("Realm at path already opened with different schema version."); } // FIXME - enable schma comparison /*if (realm->config().schema != config.schema) { throw MismatchedConfigException("Realm at path already opened with different schema"); }*/ realm->m_config.migration_function = config.migration_function; return realm; } } SharedRealm realm(new Realm(std::move(config))); auto target_schema = std::move(realm->m_config.schema); auto target_schema_version = realm->m_config.schema_version; realm->m_config.schema_version = ObjectStore::get_schema_version(realm->read_group()); // we want to ensure we are only initializing a single realm at a time static std::mutex s_init_mutex; std::lock_guard<std::mutex> lock(s_init_mutex); if (auto existing = s_global_cache.get_any_realm(realm->config().path)) { // if there is an existing realm at the current path steal its schema/column mapping // FIXME - need to validate that schemas match realm->m_config.schema = std::make_unique<Schema>(*existing->m_config.schema); realm->m_notifier = existing->m_notifier; realm->m_notifier->add_realm(realm.get()); } else { realm->m_notifier = std::make_shared<ExternalCommitHelper>(realm.get()); // otherwise get the schema from the group realm->m_config.schema = std::make_unique<Schema>(ObjectStore::schema_from_group(realm->read_group())); // if a target schema is supplied, verify that it matches or migrate to // it, as neeeded if (target_schema) { if (realm->m_config.read_only) { if (realm->m_config.schema_version == ObjectStore::NotVersioned) { throw UnitializedRealmException("Can't open an un-initialized Realm without a Schema"); } target_schema->validate(); ObjectStore::verify_schema(*realm->m_config.schema, *target_schema, true); realm->m_config.schema = std::move(target_schema); } else { realm->update_schema(std::move(target_schema), target_schema_version); } } } if (config.cache) { s_global_cache.cache_realm(realm, realm->m_thread_id); } return realm; } bool Realm::update_schema(std::unique_ptr<Schema> schema, uint64_t version) { schema->validate(); bool needs_update = !m_config.read_only && (m_config.schema_version != version || ObjectStore::needs_update(*m_config.schema, *schema)); if (!needs_update) { ObjectStore::verify_schema(*m_config.schema, *schema, m_config.read_only); m_config.schema = std::move(schema); m_config.schema_version = version; return false; } // Store the old config/schema for the migration function, and update // our schema to the new one auto old_schema = std::move(m_config.schema); Config old_config(m_config); old_config.read_only = true; old_config.schema = std::move(old_schema); m_config.schema = std::move(schema); m_config.schema_version = version; auto migration_function = [&](Group*, Schema&) { SharedRealm old_realm(new Realm(old_config)); auto updated_realm = shared_from_this(); m_config.migration_function(old_realm, updated_realm); }; try { // update and migrate begin_transaction(); bool changed = ObjectStore::update_realm_with_schema(read_group(), *old_config.schema, version, *m_config.schema, migration_function); commit_transaction(); return changed; } catch (...) { if (is_in_transaction()) { cancel_transaction(); } m_config.schema_version = old_config.schema_version; m_config.schema = std::move(m_config.schema); throw; } } static void check_read_write(Realm *realm) { if (realm->config().read_only) { throw InvalidTransactionException("Can't perform transactions on read-only Realms."); } } void Realm::verify_thread() const { if (m_thread_id != std::this_thread::get_id()) { throw IncorrectThreadException("Realm accessed from incorrect thread."); } } void Realm::begin_transaction() { check_read_write(this); verify_thread(); if (m_in_transaction) { throw InvalidTransactionException("The Realm is already in a write transaction"); } // make sure we have a read transaction read_group(); transaction::begin(*m_shared_group, *m_history, m_delegate.get()); m_in_transaction = true; } void Realm::commit_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't commit a non-existing write transaction"); } m_in_transaction = false; transaction::commit(*m_shared_group, *m_history, m_delegate.get()); m_notifier->notify_others(); } void Realm::cancel_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't cancel a non-existing write transaction"); } m_in_transaction = false; transaction::cancel(*m_shared_group, *m_history, m_delegate.get()); } void Realm::invalidate() { verify_thread(); check_read_write(this); if (m_in_transaction) { cancel_transaction(); } if (!m_group) { return; } m_shared_group->end_read(); m_group = nullptr; } bool Realm::compact() { verify_thread(); if (m_config.read_only) { throw InvalidTransactionException("Can't compact a read-only Realm"); } if (m_in_transaction) { throw InvalidTransactionException("Can't compact a Realm within a write transaction"); } Group* group = read_group(); for (auto &object_schema : *m_config.schema) { ObjectStore::table_for_object_type(group, object_schema.name)->optimize(); } m_shared_group->end_read(); m_group = nullptr; return m_shared_group->compact(); } void Realm::notify() { verify_thread(); if (m_shared_group->has_changed()) { // Throws if (m_auto_refresh) { if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else if (m_delegate) { m_delegate->did_change({}, {}); } } else if (m_delegate) { m_delegate->changes_available(); } } } bool Realm::refresh() { verify_thread(); check_read_write(this); // can't be any new changes if we're in a write transaction if (m_in_transaction) { return false; } // advance transaction if database has changed if (!m_shared_group->has_changed()) { // Throws return false; } if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else { // Create the read transaction read_group(); } return true; } uint64_t Realm::get_schema_version(const realm::Realm::Config &config) { if (auto existing_realm = s_global_cache.get_any_realm(config.path)) { return existing_realm->config().schema_version; } return ObjectStore::get_schema_version(Realm(config).read_group()); } SharedRealm RealmCache::get_realm(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter == path_iter->second.end()) { return SharedRealm(); } return thread_iter->second.lock(); } SharedRealm RealmCache::get_any_realm(const std::string &path) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.begin(); while (thread_iter != path_iter->second.end()) { if (auto realm = thread_iter->second.lock()) { return realm; } path_iter->second.erase(thread_iter++); } return SharedRealm(); } void RealmCache::remove(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return; } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter != path_iter->second.end()) { path_iter->second.erase(thread_iter); } if (path_iter->second.size() == 0) { m_cache.erase(path_iter); } } void RealmCache::cache_realm(SharedRealm &realm, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(realm->config().path); if (path_iter == m_cache.end()) { m_cache.emplace(realm->config().path, std::map<std::thread::id, WeakRealm>{{thread_id, realm}}); } else { path_iter->second.emplace(thread_id, realm); } } void RealmCache::clear() { std::lock_guard<std::mutex> lock(m_mutex); m_cache.clear(); }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "shared_realm.hpp" #include "external_commit_helper.hpp" #include "realm_delegate.hpp" #include "schema.hpp" #include "transact_log_handler.hpp" #include <realm/commit_log.hpp> #include <realm/group_shared.hpp> #include <mutex> using namespace realm; RealmCache Realm::s_global_cache; Realm::Config::Config(const Config& c) : path(c.path) , read_only(c.read_only) , in_memory(c.in_memory) , cache(c.cache) , encryption_key(c.encryption_key) , schema_version(c.schema_version) , migration_function(c.migration_function) { if (c.schema) { schema = std::make_unique<Schema>(*c.schema); } } Realm::Config::~Config() = default; Realm::Config& Realm::Config::operator=(realm::Realm::Config const& c) { if (&c != this) { *this = Config(c); } return *this; } Realm::Realm(Config config) : m_config(std::move(config)) { try { if (m_config.read_only) { m_read_only_group = std::make_unique<Group>(m_config.path, m_config.encryption_key.data(), Group::mode_ReadOnly); m_group = m_read_only_group.get(); } else { m_history = realm::make_client_history(m_config.path, m_config.encryption_key.data()); SharedGroup::DurabilityLevel durability = m_config.in_memory ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full; m_shared_group = std::make_unique<SharedGroup>(*m_history, durability, m_config.encryption_key.data()); } } catch (util::File::PermissionDenied const& ex) { throw RealmFileException(RealmFileException::Kind::PermissionDenied, "Unable to open a realm at path '" + m_config.path + "'. Please use a path where your app has " + (m_config.read_only ? "read" : "read-write") + " permissions."); } catch (util::File::Exists const& ex) { throw RealmFileException(RealmFileException::Kind::Exists, "Unable to open a realm at path '" + m_config.path + "'"); } catch (util::File::AccessError const& ex) { throw RealmFileException(RealmFileException::Kind::AccessError, "Unable to open a realm at path '" + m_config.path + "'"); } catch (IncompatibleLockFile const&) { throw RealmFileException(RealmFileException::Kind::IncompatibleLockFile, "Realm file is currently open in another process " "which cannot share access with this process. All processes sharing a single file must be the same architecture."); } } Realm::~Realm() { if (m_notifier) { // might not exist yet if an error occurred during init m_notifier->remove_realm(this); } } Group *Realm::read_group() { if (!m_group) { m_group = &const_cast<Group&>(m_shared_group->begin_read()); } return m_group; } SharedRealm Realm::get_shared_realm(Config config) { if (config.cache) { if (SharedRealm realm = s_global_cache.get_realm(config.path)) { if (realm->config().read_only != config.read_only) { throw MismatchedConfigException("Realm at path already opened with different read permissions."); } if (realm->config().in_memory != config.in_memory) { throw MismatchedConfigException("Realm at path already opened with different inMemory settings."); } if (realm->config().encryption_key != config.encryption_key) { throw MismatchedConfigException("Realm at path already opened with a different encryption key."); } if (realm->config().schema_version != config.schema_version && config.schema_version != ObjectStore::NotVersioned) { throw MismatchedConfigException("Realm at path already opened with different schema version."); } // FIXME - enable schma comparison /*if (realm->config().schema != config.schema) { throw MismatchedConfigException("Realm at path already opened with different schema"); }*/ realm->m_config.migration_function = config.migration_function; return realm; } } SharedRealm realm(new Realm(std::move(config))); auto target_schema = std::move(realm->m_config.schema); auto target_schema_version = realm->m_config.schema_version; realm->m_config.schema_version = ObjectStore::get_schema_version(realm->read_group()); // we want to ensure we are only initializing a single realm at a time static std::mutex s_init_mutex; std::lock_guard<std::mutex> lock(s_init_mutex); if (auto existing = s_global_cache.get_any_realm(realm->config().path)) { // if there is an existing realm at the current path steal its schema/column mapping // FIXME - need to validate that schemas match realm->m_config.schema = std::make_unique<Schema>(*existing->m_config.schema); realm->m_notifier = existing->m_notifier; realm->m_notifier->add_realm(realm.get()); } else { realm->m_notifier = std::make_shared<ExternalCommitHelper>(realm.get()); // otherwise get the schema from the group realm->m_config.schema = std::make_unique<Schema>(ObjectStore::schema_from_group(realm->read_group())); // if a target schema is supplied, verify that it matches or migrate to // it, as neeeded if (target_schema) { if (realm->m_config.read_only) { if (realm->m_config.schema_version == ObjectStore::NotVersioned) { throw UnitializedRealmException("Can't open an un-initialized Realm without a Schema"); } target_schema->validate(); ObjectStore::verify_schema(*realm->m_config.schema, *target_schema, true); realm->m_config.schema = std::move(target_schema); } else { realm->update_schema(std::move(target_schema), target_schema_version); } } } if (config.cache) { s_global_cache.cache_realm(realm, realm->m_thread_id); } return realm; } bool Realm::update_schema(std::unique_ptr<Schema> schema, uint64_t version) { schema->validate(); bool needs_update = !m_config.read_only && (m_config.schema_version != version || ObjectStore::needs_update(*m_config.schema, *schema)); if (!needs_update) { ObjectStore::verify_schema(*m_config.schema, *schema, m_config.read_only); m_config.schema = std::move(schema); m_config.schema_version = version; return false; } // Store the old config/schema for the migration function, and update // our schema to the new one auto old_schema = std::move(m_config.schema); Config old_config(m_config); old_config.read_only = true; old_config.schema = std::move(old_schema); m_config.schema = std::move(schema); m_config.schema_version = version; auto migration_function = [&](Group*, Schema&) { SharedRealm old_realm(new Realm(old_config)); auto updated_realm = shared_from_this(); m_config.migration_function(old_realm, updated_realm); }; try { // update and migrate begin_transaction(); bool changed = ObjectStore::update_realm_with_schema(read_group(), *old_config.schema, version, *m_config.schema, migration_function); commit_transaction(); return changed; } catch (...) { if (is_in_transaction()) { cancel_transaction(); } m_config.schema_version = old_config.schema_version; m_config.schema = std::move(old_config.schema); throw; } } static void check_read_write(Realm *realm) { if (realm->config().read_only) { throw InvalidTransactionException("Can't perform transactions on read-only Realms."); } } void Realm::verify_thread() const { if (m_thread_id != std::this_thread::get_id()) { throw IncorrectThreadException("Realm accessed from incorrect thread."); } } void Realm::begin_transaction() { check_read_write(this); verify_thread(); if (m_in_transaction) { throw InvalidTransactionException("The Realm is already in a write transaction"); } // make sure we have a read transaction read_group(); transaction::begin(*m_shared_group, *m_history, m_delegate.get()); m_in_transaction = true; } void Realm::commit_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't commit a non-existing write transaction"); } m_in_transaction = false; transaction::commit(*m_shared_group, *m_history, m_delegate.get()); m_notifier->notify_others(); } void Realm::cancel_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't cancel a non-existing write transaction"); } m_in_transaction = false; transaction::cancel(*m_shared_group, *m_history, m_delegate.get()); } void Realm::invalidate() { verify_thread(); check_read_write(this); if (m_in_transaction) { cancel_transaction(); } if (!m_group) { return; } m_shared_group->end_read(); m_group = nullptr; } bool Realm::compact() { verify_thread(); if (m_config.read_only) { throw InvalidTransactionException("Can't compact a read-only Realm"); } if (m_in_transaction) { throw InvalidTransactionException("Can't compact a Realm within a write transaction"); } Group* group = read_group(); for (auto &object_schema : *m_config.schema) { ObjectStore::table_for_object_type(group, object_schema.name)->optimize(); } m_shared_group->end_read(); m_group = nullptr; return m_shared_group->compact(); } void Realm::notify() { verify_thread(); if (m_shared_group->has_changed()) { // Throws if (m_auto_refresh) { if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else if (m_delegate) { m_delegate->did_change({}, {}); } } else if (m_delegate) { m_delegate->changes_available(); } } } bool Realm::refresh() { verify_thread(); check_read_write(this); // can't be any new changes if we're in a write transaction if (m_in_transaction) { return false; } // advance transaction if database has changed if (!m_shared_group->has_changed()) { // Throws return false; } if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else { // Create the read transaction read_group(); } return true; } uint64_t Realm::get_schema_version(const realm::Realm::Config &config) { if (auto existing_realm = s_global_cache.get_any_realm(config.path)) { return existing_realm->config().schema_version; } return ObjectStore::get_schema_version(Realm(config).read_group()); } SharedRealm RealmCache::get_realm(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter == path_iter->second.end()) { return SharedRealm(); } return thread_iter->second.lock(); } SharedRealm RealmCache::get_any_realm(const std::string &path) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.begin(); while (thread_iter != path_iter->second.end()) { if (auto realm = thread_iter->second.lock()) { return realm; } path_iter->second.erase(thread_iter++); } return SharedRealm(); } void RealmCache::remove(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return; } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter != path_iter->second.end()) { path_iter->second.erase(thread_iter); } if (path_iter->second.size() == 0) { m_cache.erase(path_iter); } } void RealmCache::cache_realm(SharedRealm &realm, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(realm->config().path); if (path_iter == m_cache.end()) { m_cache.emplace(realm->config().path, std::map<std::thread::id, WeakRealm>{{thread_id, realm}}); } else { path_iter->second.emplace(thread_id, realm); } } void RealmCache::clear() { std::lock_guard<std::mutex> lock(m_mutex); m_cache.clear(); }
Fix error in cleanup after an error during a migration
Fix error in cleanup after an error during a migration
C++
apache-2.0
ul7290/realm-cocoa,ul7290/realm-cocoa,tenebreux/realm-cocoa,tenebreux/realm-cocoa,ul7290/realm-cocoa,tenebreux/realm-cocoa,ul7290/realm-cocoa,tenebreux/realm-cocoa,ul7290/realm-cocoa,tenebreux/realm-cocoa
595d3884b88d4c764f951869a95ca635d6ae97d0
Models/IndependentMvnModel.hpp
Models/IndependentMvnModel.hpp
// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2012 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef BOOM_INDEPENDENT_MVN_MODEL_HPP #define BOOM_INDEPENDENT_MVN_MODEL_HPP #include "Models/EmMixtureComponent.hpp" #include "Models/GaussianModelBase.hpp" #include "Models/MvnBase.hpp" #include "Models/Policies/ParamPolicy_1.hpp" #include "Models/Policies/ParamPolicy_2.hpp" #include "Models/Policies/PriorPolicy.hpp" #include "Models/Policies/SufstatDataPolicy.hpp" #include "LinAlg/DiagonalMatrix.hpp" namespace BOOM { class IndependentMvnSuf : public SufstatDetails<VectorData> { public: explicit IndependentMvnSuf(int dim); IndependentMvnSuf *clone() const override; void clear() override; void resize(int dim); void Update(const VectorData &) override; void update_raw(const Vector &y); void update_single_dimension(double y, int position); void add_mixture_data(const Vector &v, double prob); // Increment the sample size, sum, and sum_of_squares by specified amounts. void update_expected_value(double sample_size, const Vector &expected_sum, const Vector &expected_sum_of_squares); // The sum of observations for the variable in position i. double sum(int i) const; // The sum of squares of observations for the variable in position i. double sumsq(int i) const; // uncentered sum of squares // The centered sum of squared observations for the variable in position i. double centered_sumsq(int i, double mu) const; // The number of observations in position i. double n(int i = 0) const; // The sample mean of variable in position i. double ybar(int i) const; // The sample variance of the variable in position i. double sample_var(int i) const; IndependentMvnSuf *abstract_combine(Sufstat *s) override; void combine(const Ptr<IndependentMvnSuf> &); void combine(const IndependentMvnSuf &); Vector vectorize(bool minimal = true) const override; Vector::const_iterator unvectorize(Vector::const_iterator &v, bool minimal = true) override; Vector::const_iterator unvectorize(const Vector &v, bool minimal = true) override; std::ostream &print(std::ostream &out) const override; private: std::vector<GaussianSuf> suf_; }; //=========================================================================== // A base class containing code shared by IndependentMvnModel and // ZeroMeanIndependentMvnModel. class IndependentMvnBase : public MvnBase, public SufstatDataPolicy<VectorData, IndependentMvnSuf>, virtual public EmMixtureComponent { public: IndependentMvnBase(int dim); IndependentMvnBase * clone() const override = 0; void add_mixture_data(const Ptr<Data> &dp, double weight) override; double Logp(const Vector &x, Vector &g, Matrix &h, uint nderivs) const override; // mu() is inherited from mvnbase const Vector &mu() const override = 0; virtual double mu(int i) const {return mu()[i];} virtual const Vector &sigsq() const = 0; virtual double sigsq(int i) const {return sigsq()[i];} virtual double sigma(int i) const {return sqrt(sigsq(i));} const SpdMatrix &Sigma() const override; const SpdMatrix &siginv() const override; DiagonalMatrix diagonal_variance() const; double ldsi() const override; Vector sim(RNG &rng = GlobalRng::rng) const override; double pdf(const Data *dp, bool logscale) const override; int number_of_observations() const override { return dat().size(); } private: // Scratch space for computing variance and precision matrices. mutable SpdMatrix sigma_scratch_; // Scratch space for computing gradients and hessians. mutable Vector g_; mutable Matrix h_; }; //=========================================================================== class IndependentMvnModel : public IndependentMvnBase, public ParamPolicy_2<VectorParams, VectorParams>, public PriorPolicy { public: explicit IndependentMvnModel(int dim); IndependentMvnModel(const Vector &mean, const Vector &variance); IndependentMvnModel(const IndependentMvnModel &rhs); IndependentMvnModel *clone() const override; void mle() override; // Several virtual functions from MvnBase are re-implemented here // for efficiency. Ptr<VectorParams> Mu_prm() {return prm1();} const Ptr<VectorParams> Mu_prm() const {return prm1();} const VectorParams &Mu_ref() const {return prm1_ref();} const Vector &mu() const override {return Mu_ref().value();} void set_mu(const Vector &mu); void set_mu_element(double value, int position); Ptr<VectorParams> Sigsq_prm() {return prm2();} const Ptr<VectorParams> Sigsq_prm() const {return prm2();} const VectorParams &Sigsq_ref() const {return prm2_ref();} const Vector &sigsq() const override {return Sigsq_ref().value();} void set_sigsq(const Vector &sigsq); void set_sigsq_element(double sigsq, int position); }; //=========================================================================== class ZeroMeanIndependentMvnModel : public IndependentMvnBase, public ParamPolicy_1<VectorParams>, public PriorPolicy { public: explicit ZeroMeanIndependentMvnModel(int dim); ZeroMeanIndependentMvnModel(const Vector &variance); ZeroMeanIndependentMvnModel(const ZeroMeanIndependentMvnModel &rhs); ZeroMeanIndependentMvnModel *clone() const override; void mle() override; const Vector &mu() const override {return zero_;} Ptr<VectorParams> Sigsq_prm() {return prm();} const Ptr<VectorParams> Sigsq_prm() const {return prm();} const VectorParams &Sigsq_ref() const {return prm_ref();} const Vector &sigsq() const override {return Sigsq_ref().value();} void set_sigsq(const Vector &sigsq) {Sigsq_prm()->set(sigsq);} void set_sigsq_element(double sigsq, int position) { Sigsq_prm()->set_element(sigsq, position); } private: Vector zero_; mutable SpdMatrix sigma_scratch_; mutable Vector g_; mutable Matrix h_; }; } // namespace BOOM #endif // BOOM_INDEPENDENT_MVN_MODEL_HPP
// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2012 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef BOOM_INDEPENDENT_MVN_MODEL_HPP #define BOOM_INDEPENDENT_MVN_MODEL_HPP #include "Models/EmMixtureComponent.hpp" #include "Models/GaussianModelBase.hpp" #include "Models/MvnBase.hpp" #include "Models/Policies/ParamPolicy_1.hpp" #include "Models/Policies/ParamPolicy_2.hpp" #include "Models/Policies/PriorPolicy.hpp" #include "Models/Policies/SufstatDataPolicy.hpp" #include "LinAlg/DiagonalMatrix.hpp" #include "stats/moments.hpp" namespace BOOM { class IndependentMvnSuf : public SufstatDetails<VectorData> { public: explicit IndependentMvnSuf(int dim); IndependentMvnSuf *clone() const override; void clear() override; void resize(int dim); void Update(const VectorData &) override; void update_raw(const Vector &y); void update_single_dimension(double y, int position); void add_mixture_data(const Vector &v, double prob); // Increment the sample size, sum, and sum_of_squares by specified amounts. void update_expected_value(double sample_size, const Vector &expected_sum, const Vector &expected_sum_of_squares); // The sum of observations for the variable in position i. double sum(int i) const; // The sum of squares of observations for the variable in position i. double sumsq(int i) const; // uncentered sum of squares // The centered sum of squared observations for the variable in position i. double centered_sumsq(int i, double mu) const; // The number of observations in position i. double n(int i = 0) const; // The sample mean of variable in position i. double ybar(int i) const; // The sample variance of the variable in position i. double sample_var(int i) const; IndependentMvnSuf *abstract_combine(Sufstat *s) override; void combine(const Ptr<IndependentMvnSuf> &); void combine(const IndependentMvnSuf &); Vector vectorize(bool minimal = true) const override; Vector::const_iterator unvectorize(Vector::const_iterator &v, bool minimal = true) override; Vector::const_iterator unvectorize(const Vector &v, bool minimal = true) override; std::ostream &print(std::ostream &out) const override; private: std::vector<GaussianSuf> suf_; }; //=========================================================================== // A base class containing code shared by IndependentMvnModel and // ZeroMeanIndependentMvnModel. class IndependentMvnBase : public MvnBase, public SufstatDataPolicy<VectorData, IndependentMvnSuf>, virtual public EmMixtureComponent { public: IndependentMvnBase(int dim); IndependentMvnBase * clone() const override = 0; void add_mixture_data(const Ptr<Data> &dp, double weight) override; double Logp(const Vector &x, Vector &g, Matrix &h, uint nderivs) const override; // mu() is inherited from mvnbase const Vector &mu() const override = 0; virtual double mu(int i) const {return mu()[i];} virtual const Vector &sigsq() const = 0; virtual double sigsq(int i) const {return sigsq()[i];} virtual double sigma(int i) const {return sqrt(sigsq(i));} const SpdMatrix &Sigma() const override; const SpdMatrix &siginv() const override; DiagonalMatrix diagonal_variance() const; double ldsi() const override; Vector sim(RNG &rng = GlobalRng::rng) const override; double pdf(const Data *dp, bool logscale) const override; int number_of_observations() const override { return dat().size(); } private: // Scratch space for computing variance and precision matrices. mutable SpdMatrix sigma_scratch_; // Scratch space for computing gradients and hessians. mutable Vector g_; mutable Matrix h_; }; //=========================================================================== class IndependentMvnModel : public IndependentMvnBase, public ParamPolicy_2<VectorParams, VectorParams>, public PriorPolicy { public: explicit IndependentMvnModel(int dim); IndependentMvnModel(const Vector &mean, const Vector &variance); IndependentMvnModel(const IndependentMvnModel &rhs); IndependentMvnModel *clone() const override; void mle() override; // Several virtual functions from MvnBase are re-implemented here // for efficiency. Ptr<VectorParams> Mu_prm() {return prm1();} const Ptr<VectorParams> Mu_prm() const {return prm1();} const VectorParams &Mu_ref() const {return prm1_ref();} const Vector &mu() const override {return Mu_ref().value();} void set_mu(const Vector &mu); void set_mu_element(double value, int position); Ptr<VectorParams> Sigsq_prm() {return prm2();} const Ptr<VectorParams> Sigsq_prm() const {return prm2();} const VectorParams &Sigsq_ref() const {return prm2_ref();} const Vector &sigsq() const override {return Sigsq_ref().value();} double sigsq(int i) const override {return sigsq()[i];} void set_sigsq(const Vector &sigsq); void set_sigsq_element(double sigsq, int position); }; //=========================================================================== class ZeroMeanIndependentMvnModel : public IndependentMvnBase, public ParamPolicy_1<VectorParams>, public PriorPolicy { public: explicit ZeroMeanIndependentMvnModel(int dim); ZeroMeanIndependentMvnModel(const Vector &variance); ZeroMeanIndependentMvnModel(const ZeroMeanIndependentMvnModel &rhs); ZeroMeanIndependentMvnModel *clone() const override; void mle() override; const Vector &mu() const override {return zero_;} Ptr<VectorParams> Sigsq_prm() {return prm();} const Ptr<VectorParams> Sigsq_prm() const {return prm();} const VectorParams &Sigsq_ref() const {return prm_ref();} const Vector &sigsq() const override {return Sigsq_ref().value();} double sigsq(int i) const override {return sigsq()[i];} void set_sigsq(const Vector &sigsq) {Sigsq_prm()->set(sigsq);} void set_sigsq_element(double sigsq, int position) { Sigsq_prm()->set_element(sigsq, position); } private: Vector zero_; mutable SpdMatrix sigma_scratch_; mutable Vector g_; mutable Matrix h_; }; } // namespace BOOM #endif // BOOM_INDEPENDENT_MVN_MODEL_HPP
append to previous commit
append to previous commit
C++
lgpl-2.1
steve-the-bayesian/BOOM,steve-the-bayesian/BOOM,steve-the-bayesian/BOOM,steve-the-bayesian/BOOM,steve-the-bayesian/BOOM
17fc49563c38499262caf901ecf69281dcd1fc02
source/gloperate/include/gloperate/painter/AbstractOutputCapability.hpp
source/gloperate/include/gloperate/painter/AbstractOutputCapability.hpp
#pragma once #include <gloperate/base/collection.hpp> #include <gloperate/pipeline/Data.h> namespace gloperate { template <typename T> gloperate::Data<T> * AbstractOutputCapability::getOutput(const std::string & name) const { for (AbstractData* output : findOutputs(name)) { auto = dynamic_cast<Data<T>*>(output); if (data) { return data; } } return nullptr; } template <typename T> gloperate::Data<T> * AbstractOutputCapability::getOutput() const { return dynamic_cast<Data<T>*>(collection::detect(allOutputs(), [](AbstractData * data) { return dynamic_cast<Data<T>*>(data) != nullptr; }, nullptr)); } } // namespace gloperate
#pragma once #include <gloperate/base/collection.hpp> #include <gloperate/pipeline/Data.h> namespace gloperate { template <typename T> gloperate::Data<T> * AbstractOutputCapability::getOutput(const std::string & name) const { for (AbstractData* output : findOutputs(name)) { auto data = dynamic_cast<Data<T>*>(output); if (data) { return data; } } return nullptr; } template <typename T> gloperate::Data<T> * AbstractOutputCapability::getOutput() const { return dynamic_cast<Data<T>*>(collection::detect(allOutputs(), [](AbstractData * data) { return dynamic_cast<Data<T>*>(data) != nullptr; }, nullptr)); } } // namespace gloperate
Use auto correctly
Use auto correctly
C++
mit
hpi-r2d2/gloperate,lanice/gloperate,hpicgs/gloperate,lanice/gloperate,lanice/gloperate,Beta-Alf/gloperate,p-otto/gloperate,j-o/gloperate,p-otto/gloperate,lanice/gloperate,cginternals/gloperate,p-otto/gloperate,Beta-Alf/gloperate,Beta-Alf/gloperate,hpicgs/gloperate,j-o/gloperate,p-otto/gloperate,hpicgs/gloperate,cginternals/gloperate,lanice/gloperate,hpicgs/gloperate,p-otto/gloperate,hpi-r2d2/gloperate,cginternals/gloperate,j-o/gloperate,hpicgs/gloperate,Beta-Alf/gloperate,cginternals/gloperate,Beta-Alf/gloperate,j-o/gloperate
0069d2a9c38928cfe5bd756432a5f355fcbefce9
include/cmoh/attribute.hpp
include/cmoh/attribute.hpp
/* * The MIT License (MIT) * * Copyright (c) 2016 Julian Ganz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef CMOH_ATTRIBUTE_HPP__ #define CMOH_ATTRIBUTE_HPP__ // std includes #include <type_traits> #include <utility> namespace cmoh { /** * Attribute declaration utility * * Using this template, a programmer may declare attributes she wants to make * accessible to the cmoh system. Use like: * * using foo = cmoh::attribute<int>; * * Note that using `typedef` instead of `using` may produce unintended results, * since the cmoh system relies on each attribute declaration being another * type. * * The attributes themselves are not bound to a C++ type. Attributes do, * however, provide the `accessor()` static method for creating appropriate * types of accessors for accessing attributes in objects of a specific C++ * type. These accessors provide a method for getting the attribute's value and * may provide a method for setting the attribute: * * type get(object_type const& obj) const; * void set(object_type& obj, type&& value); * * Attributes may be grouped together in namespaces or stucts, each representing * an interface. */ template < typename Attr ///< type of the attribute itself > struct attribute { typedef typename std::remove_cv<Attr>::type type; static constexpr bool is_const = std::is_const<Attr>::value; /** * Attribute accessor using methods * * This accessor provides access to the attribute via methods of the target * C++ struct/class. It is constructed from an appropriate getter and, * optionally, a setter. * * Users are discouraged from constructing method accessors directly. Use * one of the `accessor()` overloads provided by the attribute instead. */ template < typename ObjType, ///< type of the class or struct with the attribute typename SetterArg ///< effective type of the setter argument > struct method_accessor { typedef attribute attr; ///< attribute being accessed typedef ObjType object_type; ///< object being accessed typedef type(object_type::* getter)() const; typedef void(object_type::* setter)(SetterArg); method_accessor(getter getter, setter setter = nullptr) : _getter(getter), _setter(setter) {}; method_accessor(method_accessor const&) = default; method_accessor(method_accessor&&) = default; /** * Get the attribute from an object * * \returns the attribute's value */ type get( object_type const& obj ///< object from which to get the value ) const { return (obj.*_getter)(); } /** * Set the attribute on an object */ void set( object_type& obj, ///< object on which to set the attribute type&& value ///< value to set ) const { (obj.*_setter)(std::forward<type>(value)); } private: getter _getter; setter _setter; }; // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if<is_const, method_accessor<ObjType, type>>::type accessor( typename method_accessor<ObjType,type>::getter getter ) { return method_accessor<ObjType,type>(getter, nullptr); } // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if<!is_const, method_accessor<ObjType, type>>::type accessor( typename method_accessor<ObjType,type>::getter getter, typename method_accessor<ObjType,type>::setter setter ) { return method_accessor<ObjType,type>(getter, setter); } // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if< !is_const, method_accessor<ObjType, type const&> >::type accessor( typename method_accessor<ObjType,type const&>::getter getter, typename method_accessor<ObjType,type const&>::setter setter ) { return method_accessor<ObjType,type const&>(getter, setter); } // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if<!is_const, method_accessor<ObjType, type&&>>::type accessor( typename method_accessor<ObjType,type&&>::getter getter, typename method_accessor<ObjType,type&&>::setter setter ) { return method_accessor<ObjType,type&&>(getter, setter); } }; } #endif
/* * The MIT License (MIT) * * Copyright (c) 2016 Julian Ganz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef CMOH_ATTRIBUTE_HPP__ #define CMOH_ATTRIBUTE_HPP__ // std includes #include <type_traits> #include <utility> namespace cmoh { /** * Attribute declaration utility * * Using this template, a programmer may declare attributes she wants to make * accessible to the cmoh system. Use like: * * using foo = cmoh::attribute<int>; * * Note that using `typedef` instead of `using` may produce unintended results, * since the cmoh system relies on each attribute declaration being another * type. * * The attributes themselves are not bound to a C++ type. Attributes do, * however, provide the `accessor()` static method for creating appropriate * types of accessors for accessing attributes in objects of a specific C++ * type. These accessors provide a method for getting the attribute's value and * may provide a method for setting the attribute: * * type get(object_type const& obj) const; * void set(object_type& obj, type&& value); * * Attributes may be grouped together in namespaces or stucts, each representing * an interface. */ template < typename Attr ///< type of the attribute itself > struct attribute { typedef typename std::remove_cv<Attr>::type type; static constexpr bool is_const = std::is_const<Attr>::value; /** * Attribute accessor using methods * * This accessor provides access to the attribute via methods of the target * C++ struct/class. It is constructed from an appropriate getter and, * optionally, a setter. * * Users are discouraged from constructing method accessors directly. Use * one of the `accessor()` overloads provided by the attribute instead. */ template < typename ObjType, ///< type of the class or struct with the attribute typename SetterArg ///< effective type of the setter argument > struct method_accessor { typedef attribute attr; ///< attribute being accessed typedef ObjType object_type; ///< object being accessed typedef type(object_type::* getter)() const; typedef void(object_type::* setter)(SetterArg); method_accessor(getter getter, setter setter = nullptr) : _getter(getter), _setter(setter) {}; method_accessor(method_accessor const&) = default; method_accessor(method_accessor&&) = default; /** * Get the attribute from an object * * \returns the attribute's value */ type get( object_type const& obj ///< object from which to get the value ) const { return (obj.*_getter)(); } /** * Set the attribute on an object */ void set( object_type& obj, ///< object on which to set the attribute type&& value ///< value to set ) const { (obj.*_setter)(std::forward<type>(value)); } private: getter _getter; setter _setter; }; // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if<is_const, method_accessor<ObjType, type>>::type accessor( typename method_accessor<ObjType,type>::getter getter ) { return method_accessor<ObjType,type>(getter, nullptr); } // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if<!is_const, method_accessor<ObjType, type>>::type accessor( typename method_accessor<ObjType,type>::getter getter, typename method_accessor<ObjType,type>::setter setter ) { return method_accessor<ObjType,type>(getter, setter); } // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if< !is_const, method_accessor<ObjType, type const&> >::type accessor( typename method_accessor<ObjType,type const&>::getter getter, typename method_accessor<ObjType,type const&>::setter setter ) { return method_accessor<ObjType,type const&>(getter, setter); } // overload for creating a method accessor template < typename ObjType ///< type of the class or struct with the attribute > static constexpr typename std::enable_if<!is_const, method_accessor<ObjType, type&&>>::type accessor( typename method_accessor<ObjType,type&&>::getter getter, typename method_accessor<ObjType,type&&>::setter setter ) { return method_accessor<ObjType,type&&>(getter, setter); } /** * From a number of values, select the value for the current attribute * * Using this static method, one can select the value for a specific * attribute from a sequence of parameters passed to a function or * method. * * Like `std::forward()`, `select()` is designed to be used within a method * or function call, e.g.: * * foo(attr1::select<attr1, attr2, attr3>('x', "bar", 42)) * */ template < typename Attribute, typename ...Attributes > static constexpr type&& select( typename Attribute::type const& arg0, typename std::conditional< std::is_same<Attributes, attribute>::value, typename Attributes::type&&, typename Attributes::type const& >::type... args ) { return std::forward(select(std::forward(args)...)); } // overload for the current attribute template < typename ...Attributes > static constexpr type&& select( type&& arg0, typename Attributes::type const&... args ) { return std::forward<type>(arg0); } }; } #endif
Add static utility method for selecting an attribute value
Add static utility method for selecting an attribute value
C++
mit
neithernut/cmoh,neithernut/cmoh
896c101c32f53accb904bf3ae83efa3f64126464
include/command_router.hpp
include/command_router.hpp
/* * Copyright 2014 Matthew Harvey */ #ifndef GUARD_command_router_hpp_6901861572126794 #define GUARD_command_router_hpp_6901861572126794 #include "command_processor.hpp" #include "time_log.hpp" #include <memory> #include <ostream> #include <string> #include <map> #include <utility> #include <vector> namespace swx { class CommandRouter { // nested types private: typedef std::shared_ptr<CommandProcessor> CommandProcessorPtr; typedef std::map<std::string, CommandProcessorPtr> CommandProcessorMap; // special member functions public: explicit CommandRouter(TimeLog& p_time_log); CommandRouter(CommandRouter const& rhs) = delete; CommandRouter(CommandRouter&& rhs) = delete; CommandRouter& operator=(CommandRouter const& rhs) = delete; CommandRouter& operator=(CommandRouter&& rhs) = delete; ~CommandRouter() = default; // ordinary and static member functions private: void populate_command_processor_map(); public: int process_command ( std::string const& p_command, std::vector<std::string> const& p_args ) const; /** * @throws std::runtime_error if p_command is not a registered * command word. */ std::string help_information(std::string const& p_command) const; /** * In each element \e e of the returned vector, \e e.first is * the main command word, and \e e.second is a vector of aliases * for that command word. */ std::vector<std::pair<std::string, std::vector<std::string>>> available_commands() const; static std::string directions_to_get_help(); static std::string error_message_for_unrecognized_command ( std::string const& p_command ); private: int process_unrecognized_command(std::string const& p_command) const; public: std::ostream& ordinary_ostream() const; std::ostream& error_ostream() const; void create_command(CommandProcessorPtr const& p_cpp); void register_command_word ( std::string const& p_word, CommandProcessorPtr const& p_cpp ); // member variables private: TimeLog& m_time_log; CommandProcessorMap m_command_processor_map; }; // class CommandRouter } // namespace swx #endif // GUARD_command_router_hpp_6901861572126794
/* * Copyright 2014 Matthew Harvey */ #ifndef GUARD_command_router_hpp_6901861572126794 #define GUARD_command_router_hpp_6901861572126794 #include "command_processor.hpp" #include "time_log.hpp" #include <memory> #include <ostream> #include <string> #include <map> #include <utility> #include <vector> namespace swx { class CommandRouter { // nested types private: typedef std::shared_ptr<CommandProcessor> CommandProcessorPtr; typedef std::map<std::string, CommandProcessorPtr> CommandProcessorMap; // special member functions public: explicit CommandRouter(TimeLog& p_time_log); CommandRouter(CommandRouter const& rhs) = delete; CommandRouter(CommandRouter&& rhs) = delete; CommandRouter& operator=(CommandRouter const& rhs) = delete; CommandRouter& operator=(CommandRouter&& rhs) = delete; ~CommandRouter() = default; // ordinary and static member functions private: void populate_command_processor_map(); public: int process_command ( std::string const& p_command, std::vector<std::string> const& p_args ) const; /** * @throws std::runtime_error if p_command is not a registered * command word. */ std::string help_information(std::string const& p_command) const; /** * In each element \e e of the returned vector, \e e.first is * the main command word, and \e e.second is a vector of aliases * for that command word. */ std::vector<std::pair<std::string, std::vector<std::string>>> available_commands() const; static std::string directions_to_get_help(); static std::string error_message_for_unrecognized_command ( std::string const& p_command ); private: int process_unrecognized_command(std::string const& p_command) const; std::ostream& ordinary_ostream() const; std::ostream& error_ostream() const; void create_command(CommandProcessorPtr const& p_cpp); void register_command_word ( std::string const& p_word, CommandProcessorPtr const& p_cpp ); // member variables private: TimeLog& m_time_log; CommandProcessorMap m_command_processor_map; }; // class CommandRouter } // namespace swx #endif // GUARD_command_router_hpp_6901861572126794
Fix access level for some member functions of CommandRouter.
Fix access level for some member functions of CommandRouter.
C++
apache-2.0
matt-harvey/swx,skybaboon/swx
67a95b1f5e8d21b6ca61d100cc15a35f074a44fd
include/dll/rbm_traits.hpp
include/dll/rbm_traits.hpp
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_RBM_TRAITS_HPP #define DLL_RBM_TRAITS_HPP #include "tmp.hpp" #include "decay_type.hpp" #include "sparsity_method.hpp" namespace dll { template<typename Desc> struct dyn_rbm; template<typename Desc> struct conv_rbm; template<typename Desc> struct conv_rbm_mp; /*! * \brief Type Traits to get information on RBM type */ template<typename RBM> struct rbm_traits { using rbm_t = RBM; HAS_STATIC_FIELD(BatchSize, has_batch_size_field) HAS_STATIC_FIELD(Sparsity, has_sparsity_field) HAS_STATIC_FIELD(Decay, has_decay_field) HAS_STATIC_FIELD(Init, has_init_field) HAS_STATIC_FIELD(Momentum, has_momentum_field) HAS_STATIC_FIELD(Bias, has_bias_field) /*! * \brief Indicates if the RBM is convolutional */ static constexpr bool is_convolutional(){ return cpp::is_specialization_of<conv_rbm, rbm_t>::value || cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value; } /*! * \brief Indicates if the RBM is dynamic */ static constexpr bool is_dynamic(){ return cpp::is_specialization_of<dyn_rbm, rbm_t>::value; } /*! * \brief Indicates if the RBM is convolutional and has probabilistic max * pooling */ static constexpr bool has_probabilistic_max_pooling(){ return cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value; } static constexpr std::size_t input_size(){ return rbm_t::input_size(); } static constexpr std::size_t output_size(){ return rbm_t::output_size(); } template<typename R = RBM, cpp::enable_if_u<has_batch_size_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr std::size_t batch_size(){ return rbm_t::desc::BatchSize; } template<typename R = RBM, cpp::disable_if_u<has_batch_size_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr std::size_t batch_size(){ return 1; } template<typename R = RBM, cpp::enable_if_u<has_momentum_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return rbm_t::desc::Momentum; } template<typename R = RBM, cpp::disable_if_u<has_momentum_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return false; } template<typename R = RBM, cpp::enable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_sparsity(){ return rbm_t::desc::Sparsity != dll::sparsity_method::NONE; } template<typename R = RBM, cpp::disable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_sparsity(){ return false; } template<typename R = RBM, cpp::enable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum sparsity_method sparsity_method(){ return rbm_t::desc::Sparsity; } template<typename R = RBM, cpp::disable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum sparsity_method sparsity_method(){ return dll::sparsity_method::NONE; } template<typename R = RBM, cpp::enable_if_u<has_bias_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum bias_mode bias_mode(){ return rbm_t::desc::Bias; } template<typename R = RBM, cpp::disable_if_u<has_bias_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum bias_mode bias_mode(){ return dll::bias_mode::SIMPLE; } template<typename R = RBM, cpp::enable_if_u<has_decay_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return rbm_t::desc::Decay; } template<typename R = RBM, cpp::disable_if_u<has_decay_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return dll::decay_type::NONE; } template<typename R = RBM, cpp::enable_if_u<has_init_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool init_weights(){ return rbm_t::desc::Init; } template<typename R = RBM, cpp::disable_if_u<has_init_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool init_weights(){ return false; } }; template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t get_batch_size(const RBM& rbm){ return rbm.batch_size; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t get_batch_size(const RBM&){ return rbm_traits<RBM>::batch_size(); } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t num_visible(const RBM& rbm){ return rbm.num_visible; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t num_visible(const RBM&){ return RBM::desc::num_visible; } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t num_hidden(const RBM& rbm){ return rbm.num_hidden; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t num_hidden(const RBM&){ return RBM::desc::num_hidden; } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t output_size(const RBM& rbm){ return rbm.num_hidden; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t output_size(const RBM&){ return rbm_traits<RBM>::output_size(); } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t input_size(const RBM& rbm){ return rbm.num_visible; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t input_size(const RBM&){ return rbm_traits<RBM>::input_size(); } } //end of dbn namespace #endif
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_RBM_TRAITS_HPP #define DLL_RBM_TRAITS_HPP #include "tmp.hpp" #include "decay_type.hpp" #include "sparsity_method.hpp" namespace dll { template<typename Desc> struct dyn_rbm; template<typename Desc> struct conv_rbm; template<typename Desc> struct conv_rbm_mp; /*! * \brief Type Traits to get information on RBM type */ template<typename RBM> struct rbm_traits { using rbm_t = RBM; HAS_STATIC_FIELD(BatchSize, has_batch_size_field) HAS_STATIC_FIELD(Sparsity, has_sparsity_field) HAS_STATIC_FIELD(Decay, has_decay_field) HAS_STATIC_FIELD(Init, has_init_field) HAS_STATIC_FIELD(Momentum, has_momentum_field) HAS_STATIC_FIELD(Bias, has_bias_field) HAS_STATIC_FIELD(Shuffle, has_shuffle_field) /*! * \brief Indicates if the RBM is convolutional */ static constexpr bool is_convolutional(){ return cpp::is_specialization_of<conv_rbm, rbm_t>::value || cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value; } /*! * \brief Indicates if the RBM is dynamic */ static constexpr bool is_dynamic(){ return cpp::is_specialization_of<dyn_rbm, rbm_t>::value; } /*! * \brief Indicates if the RBM is convolutional and has probabilistic max * pooling */ static constexpr bool has_probabilistic_max_pooling(){ return cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value; } static constexpr std::size_t input_size(){ return rbm_t::input_size(); } static constexpr std::size_t output_size(){ return rbm_t::output_size(); } template<typename R = RBM, cpp::enable_if_u<has_batch_size_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr std::size_t batch_size(){ return rbm_t::desc::BatchSize; } template<typename R = RBM, cpp::disable_if_u<has_batch_size_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr std::size_t batch_size(){ return 1; } template<typename R = RBM, cpp::enable_if_u<has_momentum_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return rbm_t::desc::Momentum; } template<typename R = RBM, cpp::disable_if_u<has_momentum_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return false; } template<typename R = RBM, cpp::enable_if_u<has_shuffle_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_shuffle(){ return rbm_t::desc::Shuffle; } template<typename R = RBM, cpp::disable_if_u<has_shuffle_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_shuffle(){ return false; } template<typename R = RBM, cpp::enable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_sparsity(){ return rbm_t::desc::Sparsity != dll::sparsity_method::NONE; } template<typename R = RBM, cpp::disable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool has_sparsity(){ return false; } template<typename R = RBM, cpp::enable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum sparsity_method sparsity_method(){ return rbm_t::desc::Sparsity; } template<typename R = RBM, cpp::disable_if_u<has_sparsity_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum sparsity_method sparsity_method(){ return dll::sparsity_method::NONE; } template<typename R = RBM, cpp::enable_if_u<has_bias_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum bias_mode bias_mode(){ return rbm_t::desc::Bias; } template<typename R = RBM, cpp::disable_if_u<has_bias_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr enum bias_mode bias_mode(){ return dll::bias_mode::SIMPLE; } template<typename R = RBM, cpp::enable_if_u<has_decay_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return rbm_t::desc::Decay; } template<typename R = RBM, cpp::disable_if_u<has_decay_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return dll::decay_type::NONE; } template<typename R = RBM, cpp::enable_if_u<has_init_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool init_weights(){ return rbm_t::desc::Init; } template<typename R = RBM, cpp::disable_if_u<has_init_field<typename R::desc>::value> = cpp::detail::dummy> static constexpr bool init_weights(){ return false; } }; template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t get_batch_size(const RBM& rbm){ return rbm.batch_size; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t get_batch_size(const RBM&){ return rbm_traits<RBM>::batch_size(); } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t num_visible(const RBM& rbm){ return rbm.num_visible; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t num_visible(const RBM&){ return RBM::desc::num_visible; } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t num_hidden(const RBM& rbm){ return rbm.num_hidden; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t num_hidden(const RBM&){ return RBM::desc::num_hidden; } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t output_size(const RBM& rbm){ return rbm.num_hidden; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t output_size(const RBM&){ return rbm_traits<RBM>::output_size(); } template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> std::size_t input_size(const RBM& rbm){ return rbm.num_visible; } template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::is_dynamic()> = cpp::detail::dummy> constexpr std::size_t input_size(const RBM&){ return rbm_traits<RBM>::input_size(); } } //end of dbn namespace #endif
Add traits function for shuffle
Add traits function for shuffle
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
4ee27c124c8ebb218719a3510236d06c63ab8d42
NatNetReceiver/src/listner.cpp
NatNetReceiver/src/listner.cpp
// // Created by andrea on 15/03/16. // #include <lcm/lcm-cpp.hpp> #include "NatNetReceiver.h" #include <QApplication> #include "lcm_messages/geometry/pose.hpp" #include <iostream> #include "common/common.h" void setPositionMsg(NatNetReceiver &nat, geometry::pose &msg); bool isPoseValid(geometry::pose &state, const geometry::pose prev_state); int count = 0; int main(int argc, char** argv){ lcm::LCM handler; if (!handler.good()) return 1; QApplication a(argc, argv); NatNetReceiver nat; geometry::pose pose_msg; geometry::pose prev_pose_msg; while(true) { if(nat._isReady){ setPositionMsg(nat, pose_msg); // Quick estimate for velocities int64_t dt = pose_msg.timestamp - prev_pose_msg.timestamp; pose_msg.velocity[0] = (pose_msg.position[0] - prev_pose_msg.position[0])/((double)dt * MILLI2SECS); pose_msg.velocity[1] = (pose_msg.position[1] - prev_pose_msg.position[1])/((double)dt * MILLI2SECS); pose_msg.velocity[2] = (pose_msg.position[2] - prev_pose_msg.position[2])/((double)dt * MILLI2SECS); // Check for position validity if(isPoseValid(pose_msg, prev_pose_msg)) std::cout << "Untracked object" << std::endl; //Publish pose estimate handler.publish("local_position_sp",&pose_msg); // Reset nat._isReady = false; prev_pose_msg.position[0] = pose_msg.position[0]; prev_pose_msg.position[1] = pose_msg.position[1]; prev_pose_msg.position[2] = pose_msg.position[2]; prev_pose_msg.timestamp = pose_msg.timestamp; } a.processEvents(); } return 0; } void setPositionMsg(NatNetReceiver &nat, geometry::pose &msg){ msg.position[0] = nat.get_position()[0]; //x msg.position[1] = nat.get_position()[1]; //y msg.position[2] = nat.get_position()[2]; //z msg.orientation[0] = nat.get_orientation()[0]; //w msg.orientation[1] = nat.get_orientation()[1]; //x msg.orientation[2] = nat.get_orientation()[2]; //y msg.orientation[3] = nat.get_orientation()[3]; //z msg.timestamp = getTimeMilliSecond(); } bool isPoseValid(geometry::pose &state, const geometry::pose prev_state){ if (prev_state.position[0] == state.position[0] && prev_state.position[1] == state.position[1] && prev_state.position[2] == state.position[2]){ count++; if(count >= 5) state.isValid = 0; return false; } else{ count = 0; state.isValid = 1; return true; } }
// // Created by andrea on 15/03/16. // #include <lcm/lcm-cpp.hpp> #include "NatNetReceiver.h" #include <QApplication> #include "lcm_messages/geometry/pose.hpp" #include <iostream> #include "common/common.h" void setPositionMsg(NatNetReceiver &nat, geometry::pose &msg); bool isPoseValid(geometry::pose &state, const geometry::pose prev_state); int count = 0; int main(int argc, char** argv){ lcm::LCM handler; if (!handler.good()) return 1; QApplication a(argc, argv); NatNetReceiver nat; geometry::pose pose_msg; geometry::pose prev_pose_msg; while(true) { if(nat._isReady){ setPositionMsg(nat, pose_msg); // Quick estimate for velocities int64_t dt = pose_msg.timestamp - prev_pose_msg.timestamp; pose_msg.velocity[0] = (pose_msg.position[0] - prev_pose_msg.position[0])/((double)dt * MILLI2SECS); pose_msg.velocity[1] = (pose_msg.position[1] - prev_pose_msg.position[1])/((double)dt * MILLI2SECS); pose_msg.velocity[2] = (pose_msg.position[2] - prev_pose_msg.position[2])/((double)dt * MILLI2SECS); // Check for position validity if(!isPoseValid(pose_msg, prev_pose_msg)) std::cout << "Untracked object" << std::endl; //Publish pose estimate handler.publish("vision_position_estimate",&pose_msg); // Reset nat._isReady = false; prev_pose_msg.position[0] = pose_msg.position[0]; prev_pose_msg.position[1] = pose_msg.position[1]; prev_pose_msg.position[2] = pose_msg.position[2]; prev_pose_msg.timestamp = pose_msg.timestamp; } a.processEvents(); } return 0; } void setPositionMsg(NatNetReceiver &nat, geometry::pose &msg){ msg.position[0] = nat.get_position()[0]; //x msg.position[1] = nat.get_position()[1]; //y msg.position[2] = nat.get_position()[2]; //z msg.orientation[0] = nat.get_orientation()[0]; //w msg.orientation[1] = nat.get_orientation()[1]; //x msg.orientation[2] = nat.get_orientation()[2]; //y msg.orientation[3] = nat.get_orientation()[3]; //z msg.timestamp = getTimeMilliSecond(); } bool isPoseValid(geometry::pose &state, const geometry::pose prev_state){ if (prev_state.position[0] == state.position[0] && prev_state.position[1] == state.position[1] && prev_state.position[2] == state.position[2]){ count++; if(count >= 5) state.isValid = 0; return false; } else{ count = 0; state.isValid = 1; return true; } }
fix broken master
fix broken master
C++
mit
EmaroLab/mocap2mav,EmaroLab/mocap2mav
d1af621a872ef9bd931ff7c686982c536723f1ad
src/libs/plugins/pokey/drivers/PokeyMAX7219Manager/PokeyMAX7219Manager.cpp
src/libs/plugins/pokey/drivers/PokeyMAX7219Manager/PokeyMAX7219Manager.cpp
#include <string.h> #include <thread> #include <iostream> #include "PokeyMAX7219Manager.h" using namespace std::chrono_literals; PokeyMAX7219Manager::PokeyMAX7219Manager(sPoKeysDevice *pokey, uint8_t chipSelect) { _chipSelect = chipSelect; _pokey = pokey; _driver = std::make_shared<MAX7219>(); _stateMatrix = {{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}}; PK_SPIConfigure(_pokey, MAX7219_PRESCALER, MAX7219_FRAMEFORMAT); uint16_t packet = 0; packet = driver()->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_HIGH); deliverDisplayPacket(packet); } PokeyMAX7219Manager::~PokeyMAX7219Manager(void) {} std::shared_ptr<MAX7219> PokeyMAX7219Manager::driver(void) { return _driver; } void PokeyMAX7219Manager::setAllPinStates(bool enabled) { for (uint8_t col = 1; col < 9; col++) { for (uint8_t row = 1; row < 9; row++) { setPinState(col, row, enabled); } } } #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c\n" #define BYTE_TO_BINARY(byte) \ (byte & 0x80 ? '1' : '0'), \ (byte & 0x40 ? '1' : '0'), \ (byte & 0x20 ? '1' : '0'), \ (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), \ (byte & 0x04 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \ (byte & 0x01 ? '1' : '0') void PokeyMAX7219Manager::setPinState(uint8_t col, uint8_t row, bool enabled) { assert(col >= 1 && col <= 8 && row >=1 && row <= 8); // this function allows for eight states per column, // so get the row mask value with a shift by row // (see MODE_ROW_1 -> MODE_ROW_8) _stateMatrix[col - 1][row - 1] = enabled; // explicitly set the entire row of values to match stored state uint8_t rowMask = 0; uint8_t colRegister = REG_COL_1 + col - 1; uint16_t packet = driver()->encodeOutputPacket(colRegister, rowMask); // build up the mask for the entire col to which the row belongs for (uint8_t idx = 0; idx < 8; idx++) { if (_stateMatrix[col - 1][idx]) { rowMask |= (1 << idx); } } // PRINTF("---> COL REG BITS: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY((&packet)[0])); // printf("---> COL ROW MASK BITS: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(((uint8_t*)&packet)[1])); if (deliverDisplayPacket(packet) != PK_OK) { throw std::runtime_error("failed to set MAX7219 pin state"); } } /** * send MAX7219 packet to device via SPI interface */ uint32_t PokeyMAX7219Manager::deliverDisplayPacket(uint16_t packet) { assert(_pokey); return PK_SPIWrite(_pokey, (uint8_t *)&packet, sizeof(packet), _chipSelect); } bool PokeyMAX7219Manager::RunTests(sPoKeysDevice *pokey, uint8_t chipSelect) { bool retVal = true; try { std::shared_ptr<PokeyMAX7219Manager> matrixManager = std::make_shared<PokeyMAX7219Manager>(pokey, chipSelect); matrixManager->setAllPinStates(true); std::this_thread::sleep_for(500ms); matrixManager->setAllPinStates(false); std::this_thread::sleep_for(500ms); for (uint8_t col = 1; col < 9; col++) { for (uint8_t row = 1; row < 9; row++) { matrixManager->setPinState(col, row, true); std::this_thread::sleep_for(250ms); } } matrixManager->setAllPinStates(false); } catch (std::runtime_error &err) { std::cout << "ERROR: " << err.what() << std::endl; retVal = false; } /* std::shared_ptr<MAX7219> output = matrixManager->driver(); uint16_t packet = 0; packet = output->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF); matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL); matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF); matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF); matrixManager->deliverDisplayPacket(packet); packet = 0; matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_LOW); matrixManager->deliverDisplayPacket(packet); // more for show than for go, so to speak... for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) { packet = output->encodeOutputPacket(col, 0); matrixManager->deliverDisplayPacket(packet); std::this_thread::sleep_for(200ms); } for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) { for (uint8_t row = MODE_ROW_1; row <= MODE_ROW_8; row++) { packet = output->encodeOutputPacket(col, row); matrixManager->deliverDisplayPacket(packet); std::this_thread::sleep_for(10ms); } } */ return retVal; }
#include <string.h> #include <thread> #include <iostream> #include "PokeyMAX7219Manager.h" using namespace std::chrono_literals; PokeyMAX7219Manager::PokeyMAX7219Manager(sPoKeysDevice *pokey, uint8_t chipSelect) { _chipSelect = chipSelect; _pokey = pokey; _driver = std::make_shared<MAX7219>(); _stateMatrix = {{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}}; PK_SPIConfigure(_pokey, MAX7219_PRESCALER, MAX7219_FRAMEFORMAT); uint16_t packet = 0; packet = driver()->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF); deliverDisplayPacket(packet); packet = driver()->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_HIGH); deliverDisplayPacket(packet); } PokeyMAX7219Manager::~PokeyMAX7219Manager(void) {} std::shared_ptr<MAX7219> PokeyMAX7219Manager::driver(void) { return _driver; } void PokeyMAX7219Manager::setAllPinStates(bool enabled) { for (uint8_t col = 1; col < 9; col++) { for (uint8_t row = 1; row < 9; row++) { setPinState(col, row, enabled); } } } #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c\n" #define BYTE_TO_BINARY(byte) \ (byte & 0x80 ? '1' : '0'), \ (byte & 0x40 ? '1' : '0'), \ (byte & 0x20 ? '1' : '0'), \ (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), \ (byte & 0x04 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \ (byte & 0x01 ? '1' : '0') void PokeyMAX7219Manager::setPinState(uint8_t col, uint8_t row, bool enabled) { assert(col >= 1 && col <= 8 && row >=1 && row <= 8); // this function allows for eight states per column, // so get the row mask value with a shift by row // (see MODE_ROW_1 -> MODE_ROW_8) _stateMatrix[col - 1][row - 1] = enabled; // explicitly set the entire row of values to match stored state uint8_t rowMask = 0; uint8_t colRegister = REG_COL_1 + col - 1; uint16_t packet = driver()->encodeOutputPacket(colRegister, rowMask); // build up the mask for the entire col to which the row belongs for (uint8_t idx = 0; idx < 8; idx++) { if (_stateMatrix[col - 1][idx]) { rowMask |= (1 << idx); } } // PRINTF("---> COL REG BITS: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY((&packet)[0])); // printf("---> COL ROW MASK BITS: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(((uint8_t*)&packet)[1])); if (deliverDisplayPacket(packet) != PK_OK) { throw std::runtime_error("failed to set MAX7219 pin state"); } } /** * send MAX7219 packet to device via SPI interface */ uint32_t PokeyMAX7219Manager::deliverDisplayPacket(uint16_t packet) { assert(_pokey); return PK_SPIWrite(_pokey, (uint8_t *)&packet, sizeof(packet), _chipSelect); } bool PokeyMAX7219Manager::RunTests(sPoKeysDevice *pokey, uint8_t chipSelect) { bool retVal = true; try { std::shared_ptr<PokeyMAX7219Manager> matrixManager = std::make_shared<PokeyMAX7219Manager>(pokey, chipSelect); //matrixManager->setAllPinStates(true); std::this_thread::sleep_for(500ms); matrixManager->setAllPinStates(false); std::this_thread::sleep_for(500ms); for (uint8_t col = 1; col < 9; col++) { for (uint8_t row = 1; row < 9; row++) { matrixManager->setPinState(col, row, true); std::this_thread::sleep_for(250ms); } } matrixManager->setAllPinStates(false); } catch (std::runtime_error &err) { std::cout << "ERROR: " << err.what() << std::endl; retVal = false; } /* std::shared_ptr<MAX7219> output = matrixManager->driver(); uint16_t packet = 0; packet = output->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF); matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL); matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF); matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF); matrixManager->deliverDisplayPacket(packet); packet = 0; matrixManager->deliverDisplayPacket(packet); packet = output->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_LOW); matrixManager->deliverDisplayPacket(packet); // more for show than for go, so to speak... for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) { packet = output->encodeOutputPacket(col, 0); matrixManager->deliverDisplayPacket(packet); std::this_thread::sleep_for(200ms); } for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) { for (uint8_t row = MODE_ROW_1; row <= MODE_ROW_8; row++) { packet = output->encodeOutputPacket(col, row); matrixManager->deliverDisplayPacket(packet); std::this_thread::sleep_for(10ms); } } */ return retVal; }
Fix indentation
Fix indentation
C++
mit
mteichtahl/simhub,mteichtahl/simhub,mteichtahl/simhub,mteichtahl/simhub
5db5eb96ed82418e2d5d73753ff4c192925e04ca
include/pandora/Charon.hpp
include/pandora/Charon.hpp
#ifndef PANDORA_CHARON_H #define PANDORA_CHARON_H #include <H5Cpp.h> #include <boost/multi_array.hpp> #include <pandora/PSize.hpp> namespace pandora { namespace hades { /* ********** */ template<typename T> struct TypeSpec { static const bool is_valid = false; const H5::DataType fileType; const H5::DataType memType; }; // template<> struct TypeSpec<char> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I8LE; const H5::DataType memType = H5::PredType::NATIVE_CHAR; }; template<> struct TypeSpec<int16_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I16LE; const H5::DataType memType = H5::PredType::NATIVE_INT16; }; template<> struct TypeSpec<uint16_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_U16LE; const H5::DataType memType = H5::PredType::NATIVE_UINT16; }; template<> struct TypeSpec<int32_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I32LE; const H5::DataType memType = H5::PredType::NATIVE_INT32; }; template<> struct TypeSpec<uint32_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_U32LE; const H5::DataType memType = H5::PredType::NATIVE_UINT32; }; template<> struct TypeSpec<int64_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I64LE; const H5::DataType memType = H5::PredType::NATIVE_INT64; }; template<> struct TypeSpec<uint64_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_U64LE; const H5::DataType memType = H5::PredType::NATIVE_UINT64; }; template<> struct TypeSpec<float> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::IEEE_F32LE; const H5::DataType memType = H5::PredType::NATIVE_FLOAT; }; template<> struct TypeSpec<double> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::IEEE_F64LE; const H5::DataType memType = H5::PredType::NATIVE_DOUBLE; }; template<> struct TypeSpec<std::string> { static const bool is_valid = true; const H5::DataType fileType = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE); const H5::DataType memType = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE); }; /* ********** */ class InvalidRankException : public std::runtime_error { public: InvalidRankException(const std::string &message) : std::runtime_error(message) { } }; /* ** */ template<typename T> class TypeInfo { public: typedef T element_type; static PSize shape(const T &value) { return PSize(); } static size_t num_elements(const T &value) { return 1; } static const element_type* getData(const T &value) { return &value; } static element_type* getData(T &value) { return &value; } static void resize(T &value, const PSize &dims) { if (dims.size() != 0) { throw InvalidRankException("Cannot resize scalar"); } } }; template<typename T> class TypeInfo<std::vector<T>> { public: typedef T element_type; typedef std::vector<T> vector_type; static PSize shape(const vector_type &value) { PSize hsize(1); hsize[0] = value.size(); return hsize; } static size_t num_elements(const vector_type &value) { return value.size(); } static const element_type* getData(const vector_type &value) { return &value[0]; } static element_type* getData(vector_type &value) { return &value[0]; } static void resize(vector_type &value, const PSize &dims) { if (dims.size() != 1) { throw InvalidRankException("Cannot change rank of vector"); //FIXME } if (dims[0] == value.size()) return; value.resize(dims[0]); } }; template<typename T, size_t N> class TypeInfo<boost::multi_array<T, N>> { public: typedef boost::multi_array<T, N> array_type; typedef typename array_type::element element_type; static PSize shape(const array_type &value) { PSize hsize(N); const size_t *shape = value.shape(); std::copy(shape, shape + N, &hsize[0]); return hsize; } static size_t num_elements(const array_type &value) { return value.num_elements(); } static const element_type* getData(const array_type &value) { return value.data(); } static element_type* getData(array_type &value) { return value.data(); } static void resize(array_type &value, const PSize &dims) { if (dims.size() != N) { throw InvalidRankException("Cannot change rank of multiarray"); } value.resize(dims); } }; template<typename T, size_t N> class TypeInfo<T[N]> { public: typedef T element_type; typedef T array_type[N]; static PSize shape(const array_type &value) { PSize hsize(1); hsize[0] = N; return hsize; } static size_t num_elements(const array_type&value) { return N; } static const element_type* getData(const array_type &value) { return value; } static element_type* getData(array_type &value) { return value; } static void resize(array_type &value, const PSize &dims) { if (dims.size() != 1 && dims[0] != N) { throw InvalidRankException("Cannot resize native arrays"); } //NOOP } }; template<typename T, size_t N, size_t M> class TypeInfo<T[M][N]> { public: typedef T element_type; typedef T array_type[M][N]; static PSize shape(const array_type &value) { PSize hsize(2); hsize[0] = M; hsize[1] = N; return hsize; } static size_t num_elements(const array_type &value) { return M*N; } static const element_type* getData(const array_type &value) { return value[0]; } static element_type* getData(array_type &value) { return value[0]; } static void resize(array_type &value, const PSize &dims) { if (dims.size() != 2 && dims[0] != M && dims[1] != N) { throw InvalidRankException("Cannot resize native arrays"); } //NOOP } }; template<typename T> class ValueBox : private TypeInfo<T>, public TypeSpec<typename TypeInfo<T>::element_type> { public: typedef TypeInfo<T> info_type; typedef T value_type; typedef T &value_ref; typedef typename info_type::element_type element; typedef element *element_ptr; ValueBox(value_ref val) : value(val) {} element_ptr get_data() { return info_type::getData(value); } value_ref get() { return value; } PSize shape() const { return info_type::shape(value); } size_t size() { return this->num_elements(value); } void resize(const PSize &size) {info_type::resize (value, size);} private: value_ref value; }; template<typename T> class ValueBox<const T> : private TypeInfo<T>, public TypeSpec<typename TypeInfo<T>::element_type> { public: typedef TypeInfo<T> info_type; typedef const T value_type; typedef const T &value_ref; typedef typename info_type::element_type element; typedef typename info_type::element_type element_type; typedef const element *element_ptr; ValueBox(value_ref val) : value(val) {} element_ptr get_data() const { return info_type::getData(value); } value_ref get() const { return value; } PSize shape() const { return info_type::shape(value); } size_t size() { return this->num_elements(value); } private: value_ref value; }; /* *** */ template< typename T, template <typename> class ValueBox, typename ElementType > class DataBox { public: typedef ValueBox<T> &vbox_ref; typedef ElementType data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) {} data_ptr operator *() { return get(); } data_ptr get() { return value.get_data(); } void finish(const H5::DataSpace *space = nullptr) { } private: vbox_ref value; }; template< typename T, template <typename> class ValueBox, typename ElementType > class DataBox<const T, ValueBox, ElementType> { public: typedef ValueBox<const T> &vbox_ref; typedef const ElementType data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) {} data_ptr operator *() { return get(); } data_ptr get() const { return value.get_data(); } void finish(const H5::DataSpace *space = nullptr) { } private: vbox_ref value; }; template< typename T, template <typename> class ValueBox > class DataBox<T, ValueBox, std::string> { public: typedef ValueBox<T> &vbox_ref; typedef char *data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) { size_t nelms = value.size(); data = new data_type[nelms]; } data_ptr operator *() { return get(); } data_ptr get() { return data; } void finish(const H5::DataSpace *space = nullptr) { size_t nelms = value.size(); auto vptr = value.get_data(); for (size_t i = 0; i < nelms; i++) { vptr[i] = data[i]; } if (space) { H5::DataSet::vlenReclaim(data, value.memType, *space); } } ~DataBox() { delete[] data; } private: data_ptr data; vbox_ref value; }; template< typename T, template <typename> class ValueBox > class DataBox<const T, ValueBox, std::string> { public: typedef ValueBox<const T> &vbox_ref; typedef char const *data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) { size_t nelms = value.size(); data = new data_type[nelms]; auto vptr = value.get_data(); for (auto i = 0; i < nelms; i++) { data[i] = vptr[i].c_str(); } } data_ptr operator *() { return get(); } data_ptr get() const { return data; } void finish(const H5::DataSpace *space = nullptr) { } ~DataBox() { delete[] data; } private: data_ptr data; vbox_ref value; }; } //namespace hades /**/ template<typename T> class Charon { public: typedef hades::ValueBox<T> vbox_type; typedef typename vbox_type::element element_type; typedef typename vbox_type::value_ref value_ref; typedef hades::DataBox<T, hades::ValueBox, element_type> dbox_type; typedef typename dbox_type::data_ptr data_ptr; Charon(value_ref val) : value(val) { static_assert(vbox_type::is_valid, "No valid type spec"); } const H5::DataType& getFileType() const { return value.fileType; } const H5::DataType& getMemType() const { return value.memType; } H5::DataSpace createDataSpace(bool maxdimsUnlimited) const { PSize shape = value.shape(); H5::DataSpace space; if (shape.size() == 0) { space = H5::DataSpace(); return space; //no need to delete shape } int rank = (int) shape.size(); if (maxdimsUnlimited) { PSize maxdims(shape.size()); std::fill_n(&maxdims[0], rank, H5S_UNLIMITED); space = H5::DataSpace(rank, &shape[0], &maxdims[0]); } else { space = H5::DataSpace(rank, &shape[0]); } return space; } PSize shape() const { return value.shape(); } dbox_type get_data() { dbox_type data(value); return data; } void resize(const PSize &size) { value.resize(size); } private: vbox_type value; }; #endif //PANDORA_CHARON_H } //namespace pandora
#ifndef PANDORA_CHARON_H #define PANDORA_CHARON_H #include <H5Cpp.h> #include <boost/multi_array.hpp> #include <pandora/PSize.hpp> #include <pandora/DataType.hpp> namespace pandora { namespace hades { /* ********** */ template<typename T> struct TypeSpec { static const bool is_valid = false; const H5::DataType fileType; const H5::DataType memType; }; // template<> struct TypeSpec<char> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I8LE; const H5::DataType memType = H5::PredType::NATIVE_CHAR; }; template<> struct TypeSpec<int16_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I16LE; const H5::DataType memType = H5::PredType::NATIVE_INT16; }; template<> struct TypeSpec<uint16_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_U16LE; const H5::DataType memType = H5::PredType::NATIVE_UINT16; }; template<> struct TypeSpec<int32_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I32LE; const H5::DataType memType = H5::PredType::NATIVE_INT32; }; template<> struct TypeSpec<uint32_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_U32LE; const H5::DataType memType = H5::PredType::NATIVE_UINT32; }; template<> struct TypeSpec<int64_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_I64LE; const H5::DataType memType = H5::PredType::NATIVE_INT64; }; template<> struct TypeSpec<uint64_t> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::STD_U64LE; const H5::DataType memType = H5::PredType::NATIVE_UINT64; }; template<> struct TypeSpec<float> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::IEEE_F32LE; const H5::DataType memType = H5::PredType::NATIVE_FLOAT; }; template<> struct TypeSpec<double> { static const bool is_valid = true; const H5::DataType fileType = H5::PredType::IEEE_F64LE; const H5::DataType memType = H5::PredType::NATIVE_DOUBLE; }; template<> struct TypeSpec<std::string> { static const bool is_valid = true; const H5::DataType fileType = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE); const H5::DataType memType = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE); }; template<> struct TypeSpec<DataType> { static const bool is_valid = true; TypeSpec(DataType type) : fileType(data_type_to_h5_filetype(type)), memType(data_type_to_h5_memtype(type)) { } const H5::DataType fileType; const H5::DataType memType; }; /* ********** */ class InvalidRankException : public std::runtime_error { public: InvalidRankException(const std::string &message) : std::runtime_error(message) { } }; /* ** */ template<typename T> class TypeInfo { public: typedef T element_type; static PSize shape(const T &value) { return PSize(); } static size_t num_elements(const T &value) { return 1; } static const element_type* getData(const T &value) { return &value; } static element_type* getData(T &value) { return &value; } static void resize(T &value, const PSize &dims) { if (dims.size() != 0) { throw InvalidRankException("Cannot resize scalar"); } } }; template<typename T> class TypeInfo<std::vector<T>> { public: typedef T element_type; typedef std::vector<T> vector_type; static PSize shape(const vector_type &value) { PSize hsize(1); hsize[0] = value.size(); return hsize; } static size_t num_elements(const vector_type &value) { return value.size(); } static const element_type* getData(const vector_type &value) { return &value[0]; } static element_type* getData(vector_type &value) { return &value[0]; } static void resize(vector_type &value, const PSize &dims) { if (dims.size() != 1) { throw InvalidRankException("Cannot change rank of vector"); //FIXME } if (dims[0] == value.size()) return; value.resize(dims[0]); } }; template<typename T, size_t N> class TypeInfo<boost::multi_array<T, N>> { public: typedef boost::multi_array<T, N> array_type; typedef typename array_type::element element_type; static PSize shape(const array_type &value) { PSize hsize(N); const size_t *shape = value.shape(); std::copy(shape, shape + N, &hsize[0]); return hsize; } static size_t num_elements(const array_type &value) { return value.num_elements(); } static const element_type* getData(const array_type &value) { return value.data(); } static element_type* getData(array_type &value) { return value.data(); } static void resize(array_type &value, const PSize &dims) { if (dims.size() != N) { throw InvalidRankException("Cannot change rank of multiarray"); } value.resize(dims); } }; template<typename T, size_t N> class TypeInfo<T[N]> { public: typedef T element_type; typedef T array_type[N]; static PSize shape(const array_type &value) { PSize hsize(1); hsize[0] = N; return hsize; } static size_t num_elements(const array_type&value) { return N; } static const element_type* getData(const array_type &value) { return value; } static element_type* getData(array_type &value) { return value; } static void resize(array_type &value, const PSize &dims) { if (dims.size() != 1 && dims[0] != N) { throw InvalidRankException("Cannot resize native arrays"); } //NOOP } }; template<typename T, size_t N, size_t M> class TypeInfo<T[M][N]> { public: typedef T element_type; typedef T array_type[M][N]; static PSize shape(const array_type &value) { PSize hsize(2); hsize[0] = M; hsize[1] = N; return hsize; } static size_t num_elements(const array_type &value) { return M*N; } static const element_type* getData(const array_type &value) { return value[0]; } static element_type* getData(array_type &value) { return value[0]; } static void resize(array_type &value, const PSize &dims) { if (dims.size() != 2 && dims[0] != M && dims[1] != N) { throw InvalidRankException("Cannot resize native arrays"); } //NOOP } }; template<typename T> class ValueBox : private TypeInfo<T>, public TypeSpec<typename TypeInfo<T>::element_type> { public: typedef TypeInfo<T> info_type; typedef T value_type; typedef T &value_ref; typedef typename info_type::element_type element; typedef element *element_ptr; ValueBox(value_ref val) : value(val) {} element_ptr get_data() { return info_type::getData(value); } value_ref get() { return value; } PSize shape() const { return info_type::shape(value); } size_t size() { return this->num_elements(value); } void resize(const PSize &size) {info_type::resize (value, size);} private: value_ref value; }; template<typename T> class ValueBox<const T> : private TypeInfo<T>, public TypeSpec<typename TypeInfo<T>::element_type> { public: typedef TypeInfo<T> info_type; typedef const T value_type; typedef const T &value_ref; typedef typename info_type::element_type element; typedef typename info_type::element_type element_type; typedef const element *element_ptr; ValueBox(value_ref val) : value(val) {} element_ptr get_data() const { return info_type::getData(value); } value_ref get() const { return value; } PSize shape() const { return info_type::shape(value); } size_t size() { return this->num_elements(value); } private: value_ref value; }; /* *** */ template< typename T, template <typename> class ValueBox, typename ElementType > class DataBox { public: typedef ValueBox<T> &vbox_ref; typedef ElementType data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) {} data_ptr operator *() { return get(); } data_ptr get() { return value.get_data(); } void finish(const H5::DataSpace *space = nullptr) { } private: vbox_ref value; }; template< typename T, template <typename> class ValueBox, typename ElementType > class DataBox<const T, ValueBox, ElementType> { public: typedef ValueBox<const T> &vbox_ref; typedef const ElementType data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) {} data_ptr operator *() { return get(); } data_ptr get() const { return value.get_data(); } void finish(const H5::DataSpace *space = nullptr) { } private: vbox_ref value; }; template< typename T, template <typename> class ValueBox > class DataBox<T, ValueBox, std::string> { public: typedef ValueBox<T> &vbox_ref; typedef char *data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) { size_t nelms = value.size(); data = new data_type[nelms]; } data_ptr operator *() { return get(); } data_ptr get() { return data; } void finish(const H5::DataSpace *space = nullptr) { size_t nelms = value.size(); auto vptr = value.get_data(); for (size_t i = 0; i < nelms; i++) { vptr[i] = data[i]; } if (space) { H5::DataSet::vlenReclaim(data, value.memType, *space); } } ~DataBox() { delete[] data; } private: data_ptr data; vbox_ref value; }; template< typename T, template <typename> class ValueBox > class DataBox<const T, ValueBox, std::string> { public: typedef ValueBox<const T> &vbox_ref; typedef char const *data_type; typedef data_type *data_ptr; DataBox(vbox_ref val) : value(val) { size_t nelms = value.size(); data = new data_type[nelms]; auto vptr = value.get_data(); for (auto i = 0; i < nelms; i++) { data[i] = vptr[i].c_str(); } } data_ptr operator *() { return get(); } data_ptr get() const { return data; } void finish(const H5::DataSpace *space = nullptr) { } ~DataBox() { delete[] data; } private: data_ptr data; vbox_ref value; }; } //namespace hades /**/ template<typename T> class Charon { public: typedef hades::ValueBox<T> vbox_type; typedef typename vbox_type::element element_type; typedef typename vbox_type::value_ref value_ref; typedef hades::DataBox<T, hades::ValueBox, element_type> dbox_type; typedef typename dbox_type::data_ptr data_ptr; Charon(value_ref val) : value(val) { static_assert(vbox_type::is_valid, "No valid type spec"); } const H5::DataType& getFileType() const { return value.fileType; } const H5::DataType& getMemType() const { return value.memType; } H5::DataSpace createDataSpace(bool maxdimsUnlimited) const { PSize shape = value.shape(); H5::DataSpace space; if (shape.size() == 0) { space = H5::DataSpace(); return space; //no need to delete shape } int rank = (int) shape.size(); if (maxdimsUnlimited) { PSize maxdims(shape.size()); std::fill_n(&maxdims[0], rank, H5S_UNLIMITED); space = H5::DataSpace(rank, &shape[0], &maxdims[0]); } else { space = H5::DataSpace(rank, &shape[0]); } return space; } PSize shape() const { return value.shape(); } dbox_type get_data() { dbox_type data(value); return data; } void resize(const PSize &size) { value.resize(size); } private: vbox_type value; }; #endif //PANDORA_CHARON_H } //namespace pandora
Implement TypeSpec for DataType
Charon: Implement TypeSpec for DataType
C++
bsd-3-clause
stoewer/nix
57edafa76e6b3d295c822246f45cece084301154
include/tao/seq/config.hpp
include/tao/seq/config.hpp
// Copyright (c) 2015-2017 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #define TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #if __cplusplus >= 201402L #define TAOCPP_USE_STD_INTEGER_SEQUENCE #endif #if( __cplusplus >= 201402L ) && defined( _LIBCPP_VERSION ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #endif #if defined( __cpp_fold_expressions ) #define TAOCPP_FOLD_EXPRESSIONS #endif #endif // TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP
// Copyright (c) 2015-2017 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #define TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #if __cplusplus >= 201402L #define TAOCPP_USE_STD_INTEGER_SEQUENCE #endif #if defined( _LIBCPP_VERSION ) && ( __cplusplus >= 201402L ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #endif #if defined( _MSC_VER ) && ( _MSC_VER >= 190023918 ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #endif #if defined( __cpp_fold_expressions ) #define TAOCPP_FOLD_EXPRESSIONS #endif #endif // TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP
Use MSVC's integer_sequence/make_integer_sequence
Use MSVC's integer_sequence/make_integer_sequence
C++
mit
taocpp/sequences,taocpp/sequences
a3611010dbb621fdc442692e90a380a3301140a9
include/tudocomp/Range.hpp
include/tudocomp/Range.hpp
#ifndef _INCLUDED_RANGE_HPP #define _INCLUDED_RANGE_HPP #include <tudocomp/def.hpp> #include <limits> namespace tdc { class Range { private: size_t m_min, m_max; public: inline Range(size_t max) : m_min(0), m_max(max) {} inline Range(size_t min, size_t max) : m_min(min), m_max(max) {} inline size_t min() const { return m_min; } inline size_t max() const { return m_max; } }; template<typename T> class TypeRange : public Range { public: TypeRange() : Range(0, std::numeric_limits<T>::max()) {} }; template<size_t t_min, size_t t_max> class FixedRange : public Range { public: FixedRange() : Range(t_min, t_max) {} }; class LiteralRange : public TypeRange<uliteral_t> {}; class LengthRange : public TypeRange<len_t> {}; using BitRange = FixedRange<0, 1>; const TypeRange<size_t> size_r; const BitRange bit_r; const LiteralRange literal_r; const LengthRange len_r; } #endif
#ifndef _INCLUDED_RANGE_HPP #define _INCLUDED_RANGE_HPP #include <tudocomp/def.hpp> #include <limits> namespace tdc { class Range { private: size_t m_min, m_max; public: inline Range(size_t max) : m_min(0), m_max(max) {} inline Range(size_t min, size_t max) : m_min(min), m_max(max) {} inline size_t min() const { return m_min; } inline size_t max() const { return m_max; } inline size_t delta() const { return m_max - m_min; } }; class MinDistributedRange : public Range { public: inline MinDistributedRange(size_t max) : Range(0, max) {} inline MinDistributedRange(size_t min, size_t max) : Range(min, max) {} }; template<typename T> class TypeRange : public Range { public: TypeRange() : Range(0, std::numeric_limits<T>::max()) {} }; template<size_t t_min, size_t t_max> class FixedRange : public Range { public: FixedRange() : Range(t_min, t_max) {} }; class LiteralRange : public TypeRange<uliteral_t> {}; class LengthRange : public TypeRange<len_t> {}; using BitRange = FixedRange<0, 1>; const TypeRange<size_t> size_r; const BitRange bit_r; const LiteralRange literal_r; const LengthRange len_r; } #endif
Introduce class for ranges that are distributed towards their minimum
Introduce class for ranges that are distributed towards their minimum
C++
apache-2.0
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
af6d12715464e9d301565bde8923b544331fd388
include/vtkCameraDevice.hh
include/vtkCameraDevice.hh
/*========================================================================= Program: Visualization Toolkit Module: vtkCameraDevice.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkCameraDevice - abstract definition of a hardware dependent camera // .SECTION Description // vtkCamereaDevice is the superclass of the hardware dependent cameras // such as vtkOglrCamera and vtkSbrCamera. This object is typically created // automatically by a vtkCamera object when it renders. The user should // never see this class. // .SECTION see also // vtkCamera #ifndef __vtkCameraDevice_hh #define __vtkCameraDevice_hh #include "vtkObject.hh" class vtkRenderer; class vtkCamera; class vtkCameraDevice : public vtkObject { public: char *GetClassName() {return "vtkCameraDevice";}; // Description: // This is the only method that the subclasses must supply. virtual void Render(vtkCamera *cam, vtkRenderer *ren) = 0; }; #endif
/*========================================================================= Program: Visualization Toolkit Module: vtkCameraDevice.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkCameraDevice - abstract definition of a hardware dependent camera // .SECTION Description // vtkCamereaDevice is the superclass of the hardware dependent cameras // such as vtkOglrCamera and vtkSbrCamera. This object is typically created // automatically by a vtkCamera object when it renders. The user should // never see this class. // .SECTION see also // vtkCamera #ifndef __vtkCameraDevice_hh #define __vtkCameraDevice_hh #include "vtkObject.hh" class vtkRenderer; class vtkCamera; class vtkCameraDevice : public vtkObject { public: char *GetClassName() {return "vtkCameraDevice";}; // Description: // This is the only method that the subclasses must supply. virtual void Render(vtkCamera *cam, vtkRenderer *ren) = 0; }; #endif
comment update
comment update
C++
bsd-3-clause
collects/VTK,hendradarwin/VTK,sumedhasingla/VTK,sankhesh/VTK,candy7393/VTK,sankhesh/VTK,ashray/VTK-EVM,jmerkow/VTK,daviddoria/PointGraphsPhase1,mspark93/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,hendradarwin/VTK,arnaudgelas/VTK,naucoin/VTKSlicerWidgets,collects/VTK,SimVascular/VTK,aashish24/VTK-old,daviddoria/PointGraphsPhase1,biddisco/VTK,ashray/VTK-EVM,biddisco/VTK,sgh/vtk,johnkit/vtk-dev,msmolens/VTK,demarle/VTK,SimVascular/VTK,demarle/VTK,Wuteyan/VTK,cjh1/VTK,jeffbaumes/jeffbaumes-vtk,keithroe/vtkoptix,arnaudgelas/VTK,keithroe/vtkoptix,aashish24/VTK-old,demarle/VTK,daviddoria/PointGraphsPhase1,sumedhasingla/VTK,spthaolt/VTK,biddisco/VTK,sgh/vtk,aashish24/VTK-old,Wuteyan/VTK,ashray/VTK-EVM,ashray/VTK-EVM,ashray/VTK-EVM,ashray/VTK-EVM,jmerkow/VTK,Wuteyan/VTK,cjh1/VTK,keithroe/vtkoptix,collects/VTK,spthaolt/VTK,msmolens/VTK,collects/VTK,msmolens/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,johnkit/vtk-dev,berendkleinhaneveld/VTK,sumedhasingla/VTK,arnaudgelas/VTK,arnaudgelas/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,gram526/VTK,sgh/vtk,daviddoria/PointGraphsPhase1,keithroe/vtkoptix,sumedhasingla/VTK,sumedhasingla/VTK,sgh/vtk,cjh1/VTK,msmolens/VTK,candy7393/VTK,ashray/VTK-EVM,gram526/VTK,aashish24/VTK-old,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,spthaolt/VTK,msmolens/VTK,SimVascular/VTK,jmerkow/VTK,cjh1/VTK,johnkit/vtk-dev,biddisco/VTK,gram526/VTK,sankhesh/VTK,jmerkow/VTK,aashish24/VTK-old,sgh/vtk,ashray/VTK-EVM,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,candy7393/VTK,candy7393/VTK,mspark93/VTK,demarle/VTK,msmolens/VTK,sankhesh/VTK,sgh/vtk,johnkit/vtk-dev,msmolens/VTK,keithroe/vtkoptix,Wuteyan/VTK,candy7393/VTK,gram526/VTK,demarle/VTK,jmerkow/VTK,biddisco/VTK,sankhesh/VTK,candy7393/VTK,hendradarwin/VTK,keithroe/vtkoptix,berendkleinhaneveld/VTK,naucoin/VTKSlicerWidgets,sankhesh/VTK,Wuteyan/VTK,berendkleinhaneveld/VTK,daviddoria/PointGraphsPhase1,biddisco/VTK,biddisco/VTK,collects/VTK,demarle/VTK,keithroe/vtkoptix,hendradarwin/VTK,gram526/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,sankhesh/VTK,jmerkow/VTK,hendradarwin/VTK,msmolens/VTK,mspark93/VTK,hendradarwin/VTK,cjh1/VTK,sumedhasingla/VTK,cjh1/VTK,Wuteyan/VTK,spthaolt/VTK,SimVascular/VTK,sumedhasingla/VTK,candy7393/VTK,sankhesh/VTK,mspark93/VTK,johnkit/vtk-dev,hendradarwin/VTK,spthaolt/VTK,naucoin/VTKSlicerWidgets,arnaudgelas/VTK,johnkit/vtk-dev,gram526/VTK,gram526/VTK,demarle/VTK,mspark93/VTK,keithroe/vtkoptix,spthaolt/VTK,mspark93/VTK,spthaolt/VTK,Wuteyan/VTK,collects/VTK,berendkleinhaneveld/VTK,candy7393/VTK,aashish24/VTK-old,gram526/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,mspark93/VTK,SimVascular/VTK,daviddoria/PointGraphsPhase1,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,mspark93/VTK,sumedhasingla/VTK,arnaudgelas/VTK
fdf1fbd12b694a3f233a455ac7341dc1beff32e3
parser/parser.cpp
parser/parser.cpp
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "parser.hpp" #include <iostream> #include <pegtl.hh> #include <pegtl/analyze.hh> #include <pegtl/trace.hh> using namespace pegtl; namespace realm { namespace parser { // strings struct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\' > > {}; struct escaped_char : one< '"', '\'', '\\', '/', 'b', 'f', 'n', 'r', 't', '0' > {}; struct escaped : sor< escaped_char, unicode > {}; struct unescaped : utf8::range< 0x20, 0x10FFFF > {}; struct chars : if_then_else< one< '\\' >, must< escaped >, unescaped > {}; struct dq_string_content : until< at< one< '"' > >, must< chars > > {}; struct dq_string : seq< one< '"' >, must< dq_string_content >, any > {}; struct sq_string_content : until< at< one< '\'' > >, must< chars > > {}; struct sq_string : seq< one< '\'' >, must< sq_string_content >, any > {}; // numbers struct minus : opt< one< '-' > > {}; struct dot : one< '.' > {}; struct float_num : sor< seq< plus< digit >, dot, star< digit > >, seq< star< digit >, dot, plus< digit > > > {}; struct hex_num : seq< one< '0' >, one< 'x', 'X' >, plus< xdigit > > {}; struct int_num : plus< digit > {}; struct number : seq< minus, sor< float_num, hex_num, int_num > > {}; struct true_value : pegtl_istring_t("true") {}; struct false_value : pegtl_istring_t("false") {}; // key paths struct key_path : list< seq< sor< alpha, one< '_' > >, star< sor< alnum, one< '_', '-' > > > >, one< '.' > > {}; // argument struct argument_index : plus< digit > {}; struct argument : seq< one< '$' >, must< argument_index > > {}; // expressions and operators struct expr : sor< dq_string, sq_string, number, argument, true_value, false_value, key_path > {}; struct eq : sor< two< '=' >, one< '=' > > {}; struct noteq : pegtl::string< '!', '=' > {}; struct lteq : pegtl::string< '<', '=' > {}; struct lt : one< '<' > {}; struct gteq : pegtl::string< '>', '=' > {}; struct gt : one< '>' > {}; struct contains : pegtl_istring_t("contains") {}; struct begins : pegtl_istring_t("beginswith") {}; struct ends : pegtl_istring_t("endswith") {}; template<typename A, typename B> struct pad_plus : seq< plus< B >, A, plus< B > > {}; struct padded_oper : pad_plus< sor< contains, begins, ends >, blank > {}; struct symbolic_oper : pad< sor< eq, noteq, lteq, lt, gteq, gt >, blank > {}; // predicates struct comparison_pred : seq< expr, sor< padded_oper, symbolic_oper >, expr > {}; struct pred; struct group_pred : if_must< one< '(' >, pad< pred, blank >, one< ')' > > {}; struct true_pred : pegtl_istring_t("truepredicate") {}; struct false_pred : pegtl_istring_t("falsepredicate") {}; struct not_pre : seq< sor< one< '!' >, seq< pegtl_istring_t("not") >, star< blank > > > {}; struct atom_pred : seq< opt< not_pre >, pad< sor< group_pred, true_pred, false_pred, comparison_pred >, blank > > {}; struct and_op : pad< sor< two< '&' >, pegtl_istring_t("and") >, blank > {}; struct or_op : pad< sor< two< '|' >, pegtl_istring_t("or") >, blank > {}; struct or_ext : if_must< or_op, pred > {}; struct and_ext : if_must< and_op, pred > {}; struct and_pred : seq< atom_pred, star< and_ext > > {}; struct pred : seq< and_pred, star< or_ext > > {}; // state struct ParserState { std::vector<Predicate *> predicate_stack; Predicate &current() { return *predicate_stack.back(); } bool negate_next = false; void addExpression(Expression && exp) { if (current().type == Predicate::Type::Comparison) { current().cmpr.expr[1] = std::move(exp); predicate_stack.pop_back(); } else { Predicate p(Predicate::Type::Comparison); p.cmpr.expr[0] = std::move(exp); if (negate_next) { p.negate = true; negate_next = false; } current().cpnd.sub_predicates.emplace_back(std::move(p)); predicate_stack.push_back(&current().cpnd.sub_predicates.back()); } } }; // rules template< typename Rule > struct action : nothing< Rule > {}; #ifdef REALM_PARSER_PRINT_TOKENS #define DEBUG_PRINT_TOKEN(string) std::cout << string << std::endl #else #define DEBUG_PRINT_TOKEN(string) #endif template<> struct action< and_ext > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<and>"); // if we were put into an OR group we need to rearrange auto &current = state.current(); if (current.type == Predicate::Type::Or) { auto &sub_preds = state.current().cpnd.sub_predicates; auto &second_last = sub_preds[sub_preds.size()-2]; if (second_last.type == Predicate::Type::And) { // if we are in an OR group and second to last predicate group is // an AND group then move the last predicate inside second_last.cpnd.sub_predicates.push_back(std::move(sub_preds.back())); sub_preds.pop_back(); } else { // otherwise combine last two into a new AND group Predicate pred(Predicate::Type::And); pred.cpnd.sub_predicates.emplace_back(std::move(second_last)); pred.cpnd.sub_predicates.emplace_back(std::move(sub_preds.back())); sub_preds.pop_back(); sub_preds.pop_back(); sub_preds.push_back(std::move(pred)); } } } }; template<> struct action< or_ext > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<or>"); // if already an OR group do nothing auto &current = state.current(); if (current.type == Predicate::Type::Or) { return; } // if only two predicates in the group, then convert to OR auto &sub_preds = state.current().cpnd.sub_predicates; if (sub_preds.size()) { current.type = Predicate::Type::Or; return; } // split the current group into to groups which are ORed together Predicate pred1(Predicate::Type::And), pred2(Predicate::Type::And); pred1.cpnd.sub_predicates.insert(sub_preds.begin(), sub_preds.back()); pred2.cpnd.sub_predicates.push_back(std::move(sub_preds.back())); current.type = Predicate::Type::Or; sub_preds.clear(); sub_preds.emplace_back(std::move(pred1)); sub_preds.emplace_back(std::move(pred2)); } }; #define EXPRESSION_ACTION(rule, type) \ template<> struct action< rule > { \ static void apply( const input & in, ParserState & state ) { \ DEBUG_PRINT_TOKEN(in.string()); \ state.addExpression(Expression(type, in.string())); }}; EXPRESSION_ACTION(dq_string_content, Expression::Type::String) EXPRESSION_ACTION(sq_string_content, Expression::Type::String) EXPRESSION_ACTION(key_path, Expression::Type::KeyPath) EXPRESSION_ACTION(number, Expression::Type::Number) EXPRESSION_ACTION(true_value, Expression::Type::True) EXPRESSION_ACTION(false_value, Expression::Type::False) EXPRESSION_ACTION(argument_index, Expression::Type::Argument) template<> struct action< true_pred > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN(in.string()); state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::True); } }; template<> struct action< false_pred > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN(in.string()); state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::False); } }; #define OPERATOR_ACTION(rule, oper) \ template<> struct action< rule > { \ static void apply( const input & in, ParserState & state ) { \ DEBUG_PRINT_TOKEN(in.string()); \ state.current().cmpr.op = oper; }}; OPERATOR_ACTION(eq, Predicate::Operator::Equal) OPERATOR_ACTION(noteq, Predicate::Operator::NotEqual) OPERATOR_ACTION(gteq, Predicate::Operator::GreaterThanOrEqual) OPERATOR_ACTION(gt, Predicate::Operator::GreaterThan) OPERATOR_ACTION(lteq, Predicate::Operator::LessThanOrEqual) OPERATOR_ACTION(lt, Predicate::Operator::LessThan) OPERATOR_ACTION(begins, Predicate::Operator::BeginsWith) OPERATOR_ACTION(ends, Predicate::Operator::EndsWith) OPERATOR_ACTION(contains, Predicate::Operator::Contains) template<> struct action< one< '(' > > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<begin_group>"); Predicate group(Predicate::Type::And); if (state.negate_next) { group.negate = true; state.negate_next = false; } state.current().cpnd.sub_predicates.emplace_back(std::move(group)); state.predicate_stack.push_back(&state.current().cpnd.sub_predicates.back()); } }; template<> struct action< group_pred > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<end_group>"); state.predicate_stack.pop_back(); } }; template<> struct action< not_pre > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<not>"); state.negate_next = true; } }; Predicate parse(const std::string &query) { analyze< pred >(); const std::string source = "user query"; Predicate out_predicate(Predicate::Type::And); ParserState state; state.predicate_stack.push_back(&out_predicate); pegtl::parse< must< pred, eof >, action >(query, source, state); if (out_predicate.type == Predicate::Type::And && out_predicate.cpnd.sub_predicates.size() == 1) { return std::move(out_predicate.cpnd.sub_predicates.back()); } return std::move(out_predicate); } }}
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "parser.hpp" #include <iostream> #include <pegtl.hh> #include <pegtl/analyze.hh> #include <pegtl/trace.hh> using namespace pegtl; namespace realm { namespace parser { // strings struct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\' > > {}; struct escaped_char : one< '"', '\'', '\\', '/', 'b', 'f', 'n', 'r', 't', '0' > {}; struct escaped : sor< escaped_char, unicode > {}; struct unescaped : utf8::range< 0x20, 0x10FFFF > {}; struct chars : if_then_else< one< '\\' >, must< escaped >, unescaped > {}; struct dq_string_content : until< at< one< '"' > >, must< chars > > {}; struct dq_string : seq< one< '"' >, must< dq_string_content >, any > {}; struct sq_string_content : until< at< one< '\'' > >, must< chars > > {}; struct sq_string : seq< one< '\'' >, must< sq_string_content >, any > {}; // numbers struct minus : opt< one< '-' > > {}; struct dot : one< '.' > {}; struct float_num : sor< seq< plus< digit >, dot, star< digit > >, seq< star< digit >, dot, plus< digit > > > {}; struct hex_num : seq< one< '0' >, one< 'x', 'X' >, plus< xdigit > > {}; struct int_num : plus< digit > {}; struct number : seq< minus, sor< float_num, hex_num, int_num > > {}; struct true_value : pegtl_istring_t("true") {}; struct false_value : pegtl_istring_t("false") {}; // key paths struct key_path : list< seq< sor< alpha, one< '_' > >, star< sor< alnum, one< '_', '-' > > > >, one< '.' > > {}; // argument struct argument_index : plus< digit > {}; struct argument : seq< one< '$' >, must< argument_index > > {}; // expressions and operators struct expr : sor< dq_string, sq_string, number, argument, true_value, false_value, key_path > {}; struct eq : sor< two< '=' >, one< '=' > > {}; struct noteq : pegtl::string< '!', '=' > {}; struct lteq : pegtl::string< '<', '=' > {}; struct lt : one< '<' > {}; struct gteq : pegtl::string< '>', '=' > {}; struct gt : one< '>' > {}; struct contains : pegtl_istring_t("contains") {}; struct begins : pegtl_istring_t("beginswith") {}; struct ends : pegtl_istring_t("endswith") {}; template<typename A, typename B> struct pad_plus : seq< plus< B >, A, plus< B > > {}; struct padded_oper : pad_plus< sor< contains, begins, ends >, blank > {}; struct symbolic_oper : pad< sor< eq, noteq, lteq, lt, gteq, gt >, blank > {}; // predicates struct comparison_pred : seq< expr, sor< padded_oper, symbolic_oper >, expr > {}; struct pred; struct group_pred : if_must< one< '(' >, pad< pred, blank >, one< ')' > > {}; struct true_pred : pegtl_istring_t("truepredicate") {}; struct false_pred : pegtl_istring_t("falsepredicate") {}; struct not_pre : seq< sor< one< '!' >, pegtl_istring_t("not") > > {}; struct atom_pred : seq< opt< not_pre >, pad< sor< group_pred, true_pred, false_pred, comparison_pred >, blank > > {}; struct and_op : pad< sor< two< '&' >, pegtl_istring_t("and") >, blank > {}; struct or_op : pad< sor< two< '|' >, pegtl_istring_t("or") >, blank > {}; struct or_ext : if_must< or_op, pred > {}; struct and_ext : if_must< and_op, pred > {}; struct and_pred : seq< atom_pred, star< and_ext > > {}; struct pred : seq< and_pred, star< or_ext > > {}; // state struct ParserState { std::vector<Predicate *> predicate_stack; Predicate &current() { return *predicate_stack.back(); } bool negate_next = false; void addExpression(Expression && exp) { if (current().type == Predicate::Type::Comparison) { current().cmpr.expr[1] = std::move(exp); predicate_stack.pop_back(); } else { Predicate p(Predicate::Type::Comparison); p.cmpr.expr[0] = std::move(exp); if (negate_next) { p.negate = true; negate_next = false; } current().cpnd.sub_predicates.emplace_back(std::move(p)); predicate_stack.push_back(&current().cpnd.sub_predicates.back()); } } }; // rules template< typename Rule > struct action : nothing< Rule > {}; #ifdef REALM_PARSER_PRINT_TOKENS #define DEBUG_PRINT_TOKEN(string) std::cout << string << std::endl #else #define DEBUG_PRINT_TOKEN(string) #endif template<> struct action< and_ext > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<and>"); // if we were put into an OR group we need to rearrange auto &current = state.current(); if (current.type == Predicate::Type::Or) { auto &sub_preds = state.current().cpnd.sub_predicates; auto &second_last = sub_preds[sub_preds.size()-2]; if (second_last.type == Predicate::Type::And) { // if we are in an OR group and second to last predicate group is // an AND group then move the last predicate inside second_last.cpnd.sub_predicates.push_back(std::move(sub_preds.back())); sub_preds.pop_back(); } else { // otherwise combine last two into a new AND group Predicate pred(Predicate::Type::And); pred.cpnd.sub_predicates.emplace_back(std::move(second_last)); pred.cpnd.sub_predicates.emplace_back(std::move(sub_preds.back())); sub_preds.pop_back(); sub_preds.pop_back(); sub_preds.push_back(std::move(pred)); } } } }; template<> struct action< or_ext > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<or>"); // if already an OR group do nothing auto &current = state.current(); if (current.type == Predicate::Type::Or) { return; } // if only two predicates in the group, then convert to OR auto &sub_preds = state.current().cpnd.sub_predicates; if (sub_preds.size()) { current.type = Predicate::Type::Or; return; } // split the current group into to groups which are ORed together Predicate pred1(Predicate::Type::And), pred2(Predicate::Type::And); pred1.cpnd.sub_predicates.insert(sub_preds.begin(), sub_preds.back()); pred2.cpnd.sub_predicates.push_back(std::move(sub_preds.back())); current.type = Predicate::Type::Or; sub_preds.clear(); sub_preds.emplace_back(std::move(pred1)); sub_preds.emplace_back(std::move(pred2)); } }; #define EXPRESSION_ACTION(rule, type) \ template<> struct action< rule > { \ static void apply( const input & in, ParserState & state ) { \ DEBUG_PRINT_TOKEN(in.string()); \ state.addExpression(Expression(type, in.string())); }}; EXPRESSION_ACTION(dq_string_content, Expression::Type::String) EXPRESSION_ACTION(sq_string_content, Expression::Type::String) EXPRESSION_ACTION(key_path, Expression::Type::KeyPath) EXPRESSION_ACTION(number, Expression::Type::Number) EXPRESSION_ACTION(true_value, Expression::Type::True) EXPRESSION_ACTION(false_value, Expression::Type::False) EXPRESSION_ACTION(argument_index, Expression::Type::Argument) template<> struct action< true_pred > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN(in.string()); state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::True); } }; template<> struct action< false_pred > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN(in.string()); state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::False); } }; #define OPERATOR_ACTION(rule, oper) \ template<> struct action< rule > { \ static void apply( const input & in, ParserState & state ) { \ DEBUG_PRINT_TOKEN(in.string()); \ state.current().cmpr.op = oper; }}; OPERATOR_ACTION(eq, Predicate::Operator::Equal) OPERATOR_ACTION(noteq, Predicate::Operator::NotEqual) OPERATOR_ACTION(gteq, Predicate::Operator::GreaterThanOrEqual) OPERATOR_ACTION(gt, Predicate::Operator::GreaterThan) OPERATOR_ACTION(lteq, Predicate::Operator::LessThanOrEqual) OPERATOR_ACTION(lt, Predicate::Operator::LessThan) OPERATOR_ACTION(begins, Predicate::Operator::BeginsWith) OPERATOR_ACTION(ends, Predicate::Operator::EndsWith) OPERATOR_ACTION(contains, Predicate::Operator::Contains) template<> struct action< one< '(' > > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<begin_group>"); Predicate group(Predicate::Type::And); if (state.negate_next) { group.negate = true; state.negate_next = false; } state.current().cpnd.sub_predicates.emplace_back(std::move(group)); state.predicate_stack.push_back(&state.current().cpnd.sub_predicates.back()); } }; template<> struct action< group_pred > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<end_group>"); state.predicate_stack.pop_back(); } }; template<> struct action< not_pre > { static void apply( const input & in, ParserState & state ) { DEBUG_PRINT_TOKEN("<not>"); state.negate_next = true; } }; Predicate parse(const std::string &query) { analyze< pred >(); const std::string source = "user query"; Predicate out_predicate(Predicate::Type::And); ParserState state; state.predicate_stack.push_back(&out_predicate); pegtl::parse< must< pred, eof >, action >(query, source, state); if (out_predicate.type == Predicate::Type::And && out_predicate.cpnd.sub_predicates.size() == 1) { return std::move(out_predicate.cpnd.sub_predicates.back()); } return std::move(out_predicate); } }}
fix for not predicate
fix for not predicate
C++
apache-2.0
realm/realm-core,realm/realm-js,realm/realm-core,Shaddix/realm-dotnet,realm/realm-object-store,Shaddix/realm-dotnet,realm/realm-core,realm/realm-core,realm/realm-js,realm/realm-js,realm/realm-core,realm/realm-dotnet,realm/realm-dotnet,realm/realm-core,realm/realm-core,realm/realm-js,realm/realm-object-store,realm/realm-js,realm/realm-js,realm/realm-object-store,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-js,realm/realm-js,realm/realm-js
c6f220e795631d81d130a9b69700ecab034158fa
parser/parser.cpp
parser/parser.cpp
/* * Copyright (C) 2008-2009 Daniel Prevost <[email protected]> * * This file may be distributed and/or modified under the terms of the * MIT License as described by the Open Source Initiative * (http://opensource.org/licenses/mit-license.php) and appearing in * the file COPYING included in the packaging of this software. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY, to the extent permitted by law; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- // Microsoft specific. Must be defined before including system header // files (this will avoid a warning if we ever use a C library function // declared by Microsoft as deprecated. #define _CRT_SECURE_NO_DEPRECATE #include <string> #include <fstream> #include <iostream> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlstring.h> #include <string.h> // memcmp #include "parser.h" #include "AbstractHandler.h" using namespace std; bool handleOptions( vector<AbstractHandler *> & handlers, string & xmlFileName, string & xmlOptionName, string & language ); // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void usage( char * progName ) { cerr << "Usage:" << endl << endl; cerr << progName << "-o|--options options_xml_file input_xml_file" << endl; cerr << " or" << endl; cerr << progName << " -h|-?|--help" << endl; cerr << " or" << endl; cerr << progName << " -v|--version" << endl << endl; cerr << "Options:" << endl << endl; cerr << " -o,--options the name of the xml file defining the options that will be" << endl; cerr << " used to generate the code." << endl; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void addGroup( string & language, xmlNode * group, bool lastGroup, vector<AbstractHandler *> & handlers ) { xmlNode * node = NULL, * errorNode = NULL; vector<AbstractHandler *>::iterator it; node = group->children; // Go to the first element while ( node->type != XML_ELEMENT_NODE ) { node = node->next; } /* * The error-group identifier is optional. But if present, there might be * multiple versions of it (each with a different xml:lang attribute). */ if ( xmlStrcmp( node->name, BAD_CAST "errgroup_ident") == 0 ) { // node is passed by reference - it will be set correctly (to the // next item to process in the xml tree) when this constructor ends. GroupIdent ident( language, node ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addGroupIdent(ident); } } // This one is a bit special - we have to know if it's the last error // or not (for enums, the last error of the last group is special - it's // the only one not terminated by a comma). // // So addError() is always adding the error of the previous iteration! while ( node != NULL ) { if ( node->type == XML_ELEMENT_NODE ) { if ( errorNode != NULL ) { ErrorXML error( language, errorNode ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addError( error, false ); } } errorNode = node; } node = node->next; } // The last one of this group. If it is the last group, then it is the // the last error, evidently { ErrorXML error( language, errorNode ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addError( error, lastGroup ); } } } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void doTopOfFile( string & xmlFileName, xmlChar * version, xmlNode * copyNode, vector<AbstractHandler *> & handlers ) { char timeBuf[30]; time_t t; struct tm * formattedTime; xmlNode * node; vector<AbstractHandler *>::iterator it; memset( timeBuf, '\0', 30 ); t = time(NULL); formattedTime = localtime( &t ); strftime( timeBuf, 30, "%a %b %d %H:%M:%S %Y", formattedTime ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addTop( xmlFileName, timeBuf, (const char *)version ); } if ( copyNode != NULL ) { // We extract the copyright element to be able to print them. node = copyNode->children; while ( node != NULL ) { if ( node->type == XML_ELEMENT_NODE ) { Copyright copy(node); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addCopyright(copy); } } node = node->next; } } for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addEndTop(); } } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void navigate( string & xmlFileName, string & language, xmlNode * root, vector<AbstractHandler *> & handlers ) { xmlNode * node = NULL, * group = NULL; xmlChar * version; vector<AbstractHandler *>::iterator it; version = xmlGetProp( root, BAD_CAST "version" ); node = root->children; // Go to the first element while ( node->type != XML_ELEMENT_NODE ) { node = node->next; } // Copyrigth information is optional if ( xmlStrcmp( node->name, BAD_CAST "copyright_group") == 0 ) { doTopOfFile( xmlFileName, version, node, handlers ); node = node->next; } else { // Do NOT advance the node (node = node->next). The node was not // the copyright group so it is the next element and we must // process it later on. doTopOfFile( xmlFileName, version, NULL, handlers ); } if ( version != NULL ) xmlFree(version); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->startHeaderGuard(); (*it)->addTopCode(); } // This one is a bit special - we have to know if it's the last group // or not (for enums, the last error of the last group is special - it's // the only one not terminated by a comma). // // So addGroup() is always adding the group of the previous iteration! while ( node != NULL ) { if ( node->type == XML_ELEMENT_NODE ) { if ( group != NULL ) addGroup( language, group, false, handlers ); group = node; } node = node->next; } addGroup( language, group, true, handlers ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addBottomCode(); (*it)->stopHeaderGuard(); } } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- int main( int argc, char * argv[] ) { xmlParserCtxtPtr context = NULL; xmlNode * root = NULL; bool rc; vector<AbstractHandler *> handlers; string xmlFileName, xmlOptionName; string language; xmlDoc * document = NULL; vector<AbstractHandler *>::iterator it; // This macro initializes the libxml library and check potential ABI // mismatches between the version it was compiled for and the actual // shared library used. LIBXML_TEST_VERSION if ( argc == 2 ) { if ( strcmp("--help",argv[1]) == 0 || strcmp("-h",argv[1]) == 0 || strcmp("-?",argv[1]) == 0 ) { usage( argv[0] ); return 0; } if ( strcmp("--version",argv[1]) == 0 || strcmp("-v",argv[1]) == 0 ) { cerr << VERSION << endl; return 0; } } if ( argc != 4 ) { usage( argv[0] ); return 1; } if ( strcmp("--options",argv[1]) != 0 && strcmp("-o",argv[1]) != 0 ) { usage( argv[0] ); return 1; } xmlFileName = argv[3]; xmlOptionName = argv[2]; try { rc = handleOptions( handlers, xmlFileName, xmlOptionName, language ); } catch (exception& e) { return 1; } if ( ! rc ) return 1; context = xmlNewParserCtxt(); if ( context == NULL ) { cerr << "Error allocating the parser context" << endl; return 1; } // We create the document and validate in one go document = xmlCtxtReadFile( context, xmlFileName.c_str(), NULL, XML_PARSE_DTDVALID ); if ( document == NULL ) { cerr << "Error while parsing the input file: " << xmlFileName << endl; return 1; } if ( context->valid == 0 ) { cerr << "Error: document validation failed" << endl; return 1; } root = xmlDocGetRootElement( document ); try { navigate( xmlFileName, language, root, handlers ); } catch (exception& e) { cerr << "Exception caught - most likely an error while writing to one of the output files" << endl; return 1; } xmlFreeDoc( document ); xmlFreeParserCtxt( context ); xmlCleanupParser(); for ( it = handlers.begin(); it < handlers.end(); it++ ) { delete (*it); } return 0; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
/* * Copyright (C) 2008-2009 Daniel Prevost <[email protected]> * * This file may be distributed and/or modified under the terms of the * MIT License as described by the Open Source Initiative * (http://opensource.org/licenses/mit-license.php) and appearing in * the file COPYING included in the packaging of this software. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY, to the extent permitted by law; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- // Microsoft specific. Must be defined before including system header // files (this will avoid a warning if we ever use a C library function // declared by Microsoft as deprecated. #define _CRT_SECURE_NO_DEPRECATE #include <string> #include <fstream> #include <iostream> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlstring.h> #include <string.h> // memcmp #include "parser.h" #include "AbstractHandler.h" using namespace std; bool handleOptions( vector<AbstractHandler *> & handlers, string & xmlFileName, string & xmlOptionName, string & language ); // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void usage( char * progName ) { cerr << "Usage:" << endl << endl; cerr << progName << "-o|--options options_xml_file input_xml_file" << endl; cerr << " or" << endl; cerr << progName << " -h|-?|--help" << endl; cerr << " or" << endl; cerr << progName << " -v|--version" << endl << endl; cerr << "Options:" << endl << endl; cerr << " -o,--options the name of the xml file defining the options that will be" << endl; cerr << " used to generate the code." << endl; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void addGroup( string & language, xmlNode * group, bool lastGroup, vector<AbstractHandler *> & handlers ) { xmlNode * node = NULL, * errorNode = NULL; vector<AbstractHandler *>::iterator it; node = group->children; // Go to the first element while ( node->type != XML_ELEMENT_NODE ) { node = node->next; } /* * The error-group identifier is optional. But if present, there might be * multiple versions of it (each with a different xml:lang attribute). */ if ( xmlStrcmp( node->name, BAD_CAST "errgroup_ident") == 0 ) { // node is passed by reference - it will be set correctly (to the // next item to process in the xml tree) when this constructor ends. GroupIdent ident( language, node ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addGroupIdent(ident); } } // This one is a bit special - we have to know if it's the last error // or not (for enums, the last error of the last group is special - it's // the only one not terminated by a comma). // // So addError() is always adding the error of the previous iteration! while ( node != NULL ) { if ( node->type == XML_ELEMENT_NODE ) { if ( errorNode != NULL ) { ErrorXML error( language, errorNode ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addError( error, false ); } } errorNode = node; } node = node->next; } // The last one of this group. If it is the last group, then it is the // the last error, evidently { ErrorXML error( language, errorNode ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addError( error, lastGroup ); } } } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void doTopOfFile( string & xmlFileName, xmlChar * version, xmlNode * copyNode, vector<AbstractHandler *> & handlers ) { char timeBuf[30]; time_t t; struct tm * formattedTime; xmlNode * node; vector<AbstractHandler *>::iterator it; memset( timeBuf, '\0', 30 ); t = time(NULL); formattedTime = localtime( &t ); strftime( timeBuf, 30, "%a %b %d %H:%M:%S %Y", formattedTime ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addTop( xmlFileName, timeBuf, (const char *)version ); } if ( copyNode != NULL ) { // We extract the copyright element to be able to print them. node = copyNode->children; while ( node != NULL ) { if ( node->type == XML_ELEMENT_NODE ) { Copyright copy(node); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addCopyright(copy); } } node = node->next; } } for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addEndTop(); } } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- void navigate( string & xmlFileName, string & language, xmlNode * root, vector<AbstractHandler *> & handlers ) { xmlNode * node = NULL, * group = NULL; xmlChar * version; vector<AbstractHandler *>::iterator it; version = xmlGetProp( root, BAD_CAST "version" ); node = root->children; // Go to the first element while ( node->type != XML_ELEMENT_NODE ) { node = node->next; } // Copyrigth information is optional if ( xmlStrcmp( node->name, BAD_CAST "copyright_group") == 0 ) { doTopOfFile( xmlFileName, version, node, handlers ); node = node->next; } else { // Do NOT advance the node (node = node->next). The node was not // the copyright group so it is the next element and we must // process it later on. doTopOfFile( xmlFileName, version, NULL, handlers ); } if ( version != NULL ) xmlFree(version); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->startHeaderGuard(); (*it)->addTopCode(); } // This one is a bit special - we have to know if it's the last group // or not (for enums, the last error of the last group is special - it's // the only one not terminated by a comma). // // So addGroup() is always adding the group of the previous iteration! while ( node != NULL ) { if ( node->type == XML_ELEMENT_NODE ) { if ( group != NULL ) addGroup( language, group, false, handlers ); group = node; } node = node->next; } addGroup( language, group, true, handlers ); for ( it = handlers.begin(); it < handlers.end(); it++ ) { (*it)->addBottomCode(); (*it)->stopHeaderGuard(); } } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- int main( int argc, char * argv[] ) { xmlParserCtxtPtr context = NULL; xmlNode * root = NULL; bool rc; vector<AbstractHandler *> handlers; string xmlFileName, xmlOptionName; string language; xmlDoc * document = NULL; vector<AbstractHandler *>::iterator it; // This macro initializes the libxml library and check potential ABI // mismatches between the version it was compiled for and the actual // shared library used. LIBXML_TEST_VERSION if ( argc == 2 ) { if ( strcmp("--help",argv[1]) == 0 || strcmp("-h",argv[1]) == 0 || strcmp("-?",argv[1]) == 0 ) { usage( argv[0] ); return 0; } if ( strcmp("--version",argv[1]) == 0 || strcmp("-v",argv[1]) == 0 ) { cerr << VERSION << endl; return 0; } } if ( argc != 4 ) { usage( argv[0] ); return 1; } if ( strcmp("--options",argv[1]) != 0 && strcmp("-o",argv[1]) != 0 ) { usage( argv[0] ); return 1; } xmlFileName = argv[3]; xmlOptionName = argv[2]; try { rc = handleOptions( handlers, xmlFileName, xmlOptionName, language ); } catch (...) { return 1; } if ( ! rc ) return 1; context = xmlNewParserCtxt(); if ( context == NULL ) { cerr << "Error allocating the parser context" << endl; return 1; } // We create the document and validate in one go document = xmlCtxtReadFile( context, xmlFileName.c_str(), NULL, XML_PARSE_DTDVALID ); if ( document == NULL ) { cerr << "Error while parsing the input file: " << xmlFileName << endl; return 1; } if ( context->valid == 0 ) { cerr << "Error: document validation failed" << endl; return 1; } root = xmlDocGetRootElement( document ); try { navigate( xmlFileName, language, root, handlers ); } catch (...) { cerr << "Exception caught - most likely an error while writing to one of the output files" << endl; return 1; } xmlFreeDoc( document ); xmlFreeParserCtxt( context ); xmlCleanupParser(); for ( it = handlers.begin(); it < handlers.end(); it++ ) { delete (*it); } return 0; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
Fix warnings on win32.
Fix warnings on win32. git-svn-id: cc07906f5311cb692740222662fcae95cc55c60b@172 bdce659d-a14a-0410-ae70-83a44b484ef0
C++
mit
dprevost/errorparser,dprevost/errorparser,dprevost/errorparser,dprevost/errorparser,dprevost/errorparser,dprevost/errorparser
183c606066b1b260acb189e46a40cb71e63b44aa
src/glsl/link_interface_blocks.cpp
src/glsl/link_interface_blocks.cpp
/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file link_interface_blocks.cpp * Linker support for GLSL's interface blocks. */ #include "ir.h" #include "glsl_symbol_table.h" #include "linker.h" #include "main/macros.h" #include "program/hash_table.h" namespace { /** * Information about a single interface block definition that we need to keep * track of in order to check linkage rules. * * Note: this class is expected to be short lived, so it doesn't make copies * of the strings it references; it simply borrows the pointers from the * ir_variable class. */ struct interface_block_definition { /** * Extract an interface block definition from an ir_variable that * represents either the interface instance (for named interfaces), or a * member of the interface (for unnamed interfaces). */ explicit interface_block_definition(ir_variable *var) : var(var), type(var->get_interface_type()), instance_name(NULL) { if (var->is_interface_instance()) { instance_name = var->name; } explicitly_declared = (var->data.how_declared != ir_var_declared_implicitly); } /** * Interface block ir_variable */ ir_variable *var; /** * Interface block type */ const glsl_type *type; /** * For a named interface block, the instance name. Otherwise NULL. */ const char *instance_name; /** * True if this interface block was explicitly declared in the shader; * false if it was an implicitly declared built-in interface block. */ bool explicitly_declared; }; /** * Check if two interfaces match, according to intrastage interface matching * rules. If they do, and the first interface uses an unsized array, it will * be updated to reflect the array size declared in the second interface. */ bool intrastage_match(interface_block_definition *a, const interface_block_definition *b, ir_variable_mode mode, struct gl_shader_program *prog) { /* Types must match. */ if (a->type != b->type) { /* Exception: if both the interface blocks are implicitly declared, * don't force their types to match. They might mismatch due to the two * shaders using different GLSL versions, and that's ok. */ if (a->explicitly_declared || b->explicitly_declared) return false; } /* Presence/absence of interface names must match. */ if ((a->instance_name == NULL) != (b->instance_name == NULL)) return false; /* For uniforms, instance names need not match. For shader ins/outs, * it's not clear from the spec whether they need to match, but * Mesa's implementation relies on them matching. */ if (a->instance_name != NULL && mode != ir_var_uniform && mode != ir_var_shader_storage && strcmp(a->instance_name, b->instance_name) != 0) { return false; } /* If a block is an array then it must match across the shader. * Unsized arrays are also processed and matched agaist sized arrays. */ if (b->var->type != a->var->type && (b->instance_name != NULL || a->instance_name != NULL) && !validate_intrastage_arrays(prog, b->var, a->var)) return false; return true; } /** * Check if two interfaces match, according to interstage (in/out) interface * matching rules. * * If \c extra_array_level is true, the consumer interface is required to be * an array and the producer interface is required to be a non-array. * This is used for tessellation control and geometry shader consumers. */ bool interstage_match(const interface_block_definition *producer, const interface_block_definition *consumer, bool extra_array_level) { /* Unsized arrays should not occur during interstage linking. They * should have all been assigned a size by link_intrastage_shaders. */ assert(!consumer->var->type->is_unsized_array()); assert(!producer->var->type->is_unsized_array()); /* Types must match. */ if (consumer->type != producer->type) { /* Exception: if both the interface blocks are implicitly declared, * don't force their types to match. They might mismatch due to the two * shaders using different GLSL versions, and that's ok. */ if (consumer->explicitly_declared || producer->explicitly_declared) return false; } /* Ignore outermost array if geom shader */ const glsl_type *consumer_instance_type; if (extra_array_level) { consumer_instance_type = consumer->var->type->fields.array; } else { consumer_instance_type = consumer->var->type; } /* If a block is an array then it must match across shaders. * Since unsized arrays have been ruled out, we can check this by just * making sure the types are equal. */ if ((consumer->instance_name != NULL && consumer_instance_type->is_array()) || (producer->instance_name != NULL && producer->var->type->is_array())) { if (consumer_instance_type != producer->var->type) return false; } return true; } /** * This class keeps track of a mapping from an interface block name to the * necessary information about that interface block to determine whether to * generate a link error. * * Note: this class is expected to be short lived, so it doesn't make copies * of the strings it references; it simply borrows the pointers from the * ir_variable class. */ class interface_block_definitions { public: interface_block_definitions() : mem_ctx(ralloc_context(NULL)), ht(hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare)) { } ~interface_block_definitions() { hash_table_dtor(ht); ralloc_free(mem_ctx); } /** * Lookup the interface definition having the given block name. Return * NULL if none is found. */ interface_block_definition *lookup(const char *block_name) { return (interface_block_definition *) hash_table_find(ht, block_name); } /** * Add a new interface definition. */ void store(const interface_block_definition &def) { interface_block_definition *hash_entry = rzalloc(mem_ctx, interface_block_definition); *hash_entry = def; hash_table_insert(ht, hash_entry, def.type->name); } private: /** * Ralloc context for data structures allocated by this class. */ void *mem_ctx; /** * Hash table mapping interface block name to an \c * interface_block_definition struct. interface_block_definition structs * are allocated using \c mem_ctx. */ hash_table *ht; }; }; /* anonymous namespace */ void validate_intrastage_interface_blocks(struct gl_shader_program *prog, const gl_shader **shader_list, unsigned num_shaders) { interface_block_definitions in_interfaces; interface_block_definitions out_interfaces; interface_block_definitions uniform_interfaces; interface_block_definitions buffer_interfaces; for (unsigned int i = 0; i < num_shaders; i++) { if (shader_list[i] == NULL) continue; foreach_in_list(ir_instruction, node, shader_list[i]->ir) { ir_variable *var = node->as_variable(); if (!var) continue; const glsl_type *iface_type = var->get_interface_type(); if (iface_type == NULL) continue; interface_block_definitions *definitions; switch (var->data.mode) { case ir_var_shader_in: definitions = &in_interfaces; break; case ir_var_shader_out: definitions = &out_interfaces; break; case ir_var_uniform: definitions = &uniform_interfaces; break; case ir_var_shader_storage: definitions = &buffer_interfaces; break; default: /* Only in, out, and uniform interfaces are legal, so we should * never get here. */ assert(!"illegal interface type"); continue; } const interface_block_definition def(var); interface_block_definition *prev_def = definitions->lookup(iface_type->name); if (prev_def == NULL) { /* This is the first time we've seen the interface, so save * it into the appropriate data structure. */ definitions->store(def); } else if (!intrastage_match(prev_def, &def, (ir_variable_mode) var->data.mode, prog)) { linker_error(prog, "definitions of interface block `%s' do not" " match\n", iface_type->name); return; } } } } void validate_interstage_inout_blocks(struct gl_shader_program *prog, const gl_shader *producer, const gl_shader *consumer) { interface_block_definitions definitions; /* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */ const bool extra_array_level = (producer->Stage == MESA_SHADER_VERTEX && consumer->Stage != MESA_SHADER_FRAGMENT) || consumer->Stage == MESA_SHADER_GEOMETRY; /* Add input interfaces from the consumer to the symbol table. */ foreach_in_list(ir_instruction, node, consumer->ir) { ir_variable *var = node->as_variable(); if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_in) continue; definitions.store(interface_block_definition(var)); } /* Verify that the producer's output interfaces match. */ foreach_in_list(ir_instruction, node, producer->ir) { ir_variable *var = node->as_variable(); if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_out) continue; interface_block_definition *consumer_def = definitions.lookup(var->get_interface_type()->name); /* The consumer doesn't use this output block. Ignore it. */ if (consumer_def == NULL) continue; const interface_block_definition producer_def(var); if (!interstage_match(&producer_def, consumer_def, extra_array_level)) { linker_error(prog, "definitions of interface block `%s' do not " "match\n", var->get_interface_type()->name); return; } } } void validate_interstage_uniform_blocks(struct gl_shader_program *prog, gl_shader **stages, int num_stages) { interface_block_definitions definitions; for (int i = 0; i < num_stages; i++) { if (stages[i] == NULL) continue; const gl_shader *stage = stages[i]; foreach_in_list(ir_instruction, node, stage->ir) { ir_variable *var = node->as_variable(); if (!var || !var->get_interface_type() || (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage)) continue; interface_block_definition *old_def = definitions.lookup(var->get_interface_type()->name); const interface_block_definition new_def(var); if (old_def == NULL) { definitions.store(new_def); } else { /* Interstage uniform matching rules are the same as intrastage * uniform matchin rules (for uniforms, it is as though all * shaders are in the same shader stage). */ if (!intrastage_match(old_def, &new_def, (ir_variable_mode) var->data.mode, prog)) { linker_error(prog, "definitions of interface block `%s' do not " "match\n", var->get_interface_type()->name); return; } } } } }
/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file link_interface_blocks.cpp * Linker support for GLSL's interface blocks. */ #include "ir.h" #include "glsl_symbol_table.h" #include "linker.h" #include "main/macros.h" #include "util/hash_table.h" namespace { /** * Check if two interfaces match, according to intrastage interface matching * rules. If they do, and the first interface uses an unsized array, it will * be updated to reflect the array size declared in the second interface. */ bool intrastage_match(ir_variable *a, ir_variable *b, struct gl_shader_program *prog) { /* Types must match. */ if (a->get_interface_type() != b->get_interface_type()) { /* Exception: if both the interface blocks are implicitly declared, * don't force their types to match. They might mismatch due to the two * shaders using different GLSL versions, and that's ok. */ if (a->data.how_declared != ir_var_declared_implicitly || b->data.how_declared != ir_var_declared_implicitly) return false; } /* Presence/absence of interface names must match. */ if (a->is_interface_instance() != b->is_interface_instance()) return false; /* For uniforms, instance names need not match. For shader ins/outs, * it's not clear from the spec whether they need to match, but * Mesa's implementation relies on them matching. */ if (a->is_interface_instance() && b->data.mode != ir_var_uniform && b->data.mode != ir_var_shader_storage && strcmp(a->name, b->name) != 0) { return false; } /* If a block is an array then it must match across the shader. * Unsized arrays are also processed and matched agaist sized arrays. */ if (b->type != a->type && (b->is_interface_instance() || a->is_interface_instance()) && !validate_intrastage_arrays(prog, b, a)) return false; return true; } /** * Check if two interfaces match, according to interstage (in/out) interface * matching rules. * * If \c extra_array_level is true, the consumer interface is required to be * an array and the producer interface is required to be a non-array. * This is used for tessellation control and geometry shader consumers. */ bool interstage_match(ir_variable *producer, ir_variable *consumer, bool extra_array_level) { /* Unsized arrays should not occur during interstage linking. They * should have all been assigned a size by link_intrastage_shaders. */ assert(!consumer->type->is_unsized_array()); assert(!producer->type->is_unsized_array()); /* Types must match. */ if (consumer->get_interface_type() != producer->get_interface_type()) { /* Exception: if both the interface blocks are implicitly declared, * don't force their types to match. They might mismatch due to the two * shaders using different GLSL versions, and that's ok. */ if (consumer->data.how_declared != ir_var_declared_implicitly || producer->data.how_declared != ir_var_declared_implicitly) return false; } /* Ignore outermost array if geom shader */ const glsl_type *consumer_instance_type; if (extra_array_level) { consumer_instance_type = consumer->type->fields.array; } else { consumer_instance_type = consumer->type; } /* If a block is an array then it must match across shaders. * Since unsized arrays have been ruled out, we can check this by just * making sure the types are equal. */ if ((consumer->is_interface_instance() && consumer_instance_type->is_array()) || (producer->is_interface_instance() && producer->type->is_array())) { if (consumer_instance_type != producer->type) return false; } return true; } /** * This class keeps track of a mapping from an interface block name to the * necessary information about that interface block to determine whether to * generate a link error. * * Note: this class is expected to be short lived, so it doesn't make copies * of the strings it references; it simply borrows the pointers from the * ir_variable class. */ class interface_block_definitions { public: interface_block_definitions() : mem_ctx(ralloc_context(NULL)), ht(_mesa_hash_table_create(NULL, _mesa_key_hash_string, _mesa_key_string_equal)) { } ~interface_block_definitions() { ralloc_free(mem_ctx); _mesa_hash_table_destroy(ht, NULL); } /** * Lookup the interface definition. Return NULL if none is found. */ ir_variable *lookup(ir_variable *var) { const struct hash_entry *entry = _mesa_hash_table_search(ht, var->get_interface_type()->name); return entry ? (ir_variable *) entry->data : NULL; } /** * Add a new interface definition. */ void store(ir_variable *var) { _mesa_hash_table_insert(ht, var->get_interface_type()->name, var); } private: /** * Ralloc context for data structures allocated by this class. */ void *mem_ctx; /** * Hash table mapping interface block name to an \c * ir_variable. */ hash_table *ht; }; }; /* anonymous namespace */ void validate_intrastage_interface_blocks(struct gl_shader_program *prog, const gl_shader **shader_list, unsigned num_shaders) { interface_block_definitions in_interfaces; interface_block_definitions out_interfaces; interface_block_definitions uniform_interfaces; interface_block_definitions buffer_interfaces; for (unsigned int i = 0; i < num_shaders; i++) { if (shader_list[i] == NULL) continue; foreach_in_list(ir_instruction, node, shader_list[i]->ir) { ir_variable *var = node->as_variable(); if (!var) continue; const glsl_type *iface_type = var->get_interface_type(); if (iface_type == NULL) continue; interface_block_definitions *definitions; switch (var->data.mode) { case ir_var_shader_in: definitions = &in_interfaces; break; case ir_var_shader_out: definitions = &out_interfaces; break; case ir_var_uniform: definitions = &uniform_interfaces; break; case ir_var_shader_storage: definitions = &buffer_interfaces; break; default: /* Only in, out, and uniform interfaces are legal, so we should * never get here. */ assert(!"illegal interface type"); continue; } ir_variable *prev_def = definitions->lookup(var); if (prev_def == NULL) { /* This is the first time we've seen the interface, so save * it into the appropriate data structure. */ definitions->store(var); } else if (!intrastage_match(prev_def, var, prog)) { linker_error(prog, "definitions of interface block `%s' do not" " match\n", iface_type->name); return; } } } } void validate_interstage_inout_blocks(struct gl_shader_program *prog, const gl_shader *producer, const gl_shader *consumer) { interface_block_definitions definitions; /* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */ const bool extra_array_level = (producer->Stage == MESA_SHADER_VERTEX && consumer->Stage != MESA_SHADER_FRAGMENT) || consumer->Stage == MESA_SHADER_GEOMETRY; /* Add input interfaces from the consumer to the symbol table. */ foreach_in_list(ir_instruction, node, consumer->ir) { ir_variable *var = node->as_variable(); if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_in) continue; definitions.store(var); } /* Verify that the producer's output interfaces match. */ foreach_in_list(ir_instruction, node, producer->ir) { ir_variable *var = node->as_variable(); if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_out) continue; ir_variable *consumer_def = definitions.lookup(var); /* The consumer doesn't use this output block. Ignore it. */ if (consumer_def == NULL) continue; if (!interstage_match(var, consumer_def, extra_array_level)) { linker_error(prog, "definitions of interface block `%s' do not " "match\n", var->get_interface_type()->name); return; } } } void validate_interstage_uniform_blocks(struct gl_shader_program *prog, gl_shader **stages, int num_stages) { interface_block_definitions definitions; for (int i = 0; i < num_stages; i++) { if (stages[i] == NULL) continue; const gl_shader *stage = stages[i]; foreach_in_list(ir_instruction, node, stage->ir) { ir_variable *var = node->as_variable(); if (!var || !var->get_interface_type() || (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage)) continue; ir_variable *old_def = definitions.lookup(var); if (old_def == NULL) { definitions.store(var); } else { /* Interstage uniform matching rules are the same as intrastage * uniform matchin rules (for uniforms, it is as though all * shaders are in the same shader stage). */ if (!intrastage_match(old_def, var, prog)) { linker_error(prog, "definitions of interface block `%s' do not " "match\n", var->get_interface_type()->name); return; } } } } }
simplify interface matching
glsl: simplify interface matching This makes the code easier to follow, should be more efficient and will makes it easier to add matching via explicit locations in the following patch. This patch also replaces the hash table with the newer resizable hash table this should be more suitable as the table is likely to only contain a small number of entries. Reviewed-by: Edward O'Callaghan <[email protected]>
C++
mit
metora/MesaGLSLCompiler,metora/MesaGLSLCompiler,metora/MesaGLSLCompiler
5eded6f7e8c34cf0bcdaf7c68bb4d70ff1cb3ec5
src/elements/versions.cpp
src/elements/versions.cpp
/* MusicXML Library Copyright (C) Grame 2006-2013 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/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France [email protected] */ #include "versions.h" namespace MusicXML2 { //______________________________________________________________________________ float versions::libVersion() { return 3.17f; } const char* versions::libVersionStr() { return "3.17"; } float versions::xml2guidoVersion() { return 2.3f; } const char* versions::xml2guidoVersionStr() { return "3.0"; } float versions::xml2lilypondVersion() { return 0.9f; } const char* versions::xml2lilypondVersionStr() { return "0.91"; } float versions::xml2brailleVersion() { return 0.01f; } const char* versions::xml2brailleVersionStr() { return "0.02"; } }
/* MusicXML Library Copyright (C) Grame 2006-2013 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/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France [email protected] */ #include "versions.h" namespace MusicXML2 { //______________________________________________________________________________ float versions::libVersion() { return 3.17f; } const char* versions::libVersionStr() { return "3.17"; } float versions::xml2guidoVersion() { return 3.0f; } const char* versions::xml2guidoVersionStr() { return "3.0"; } float versions::xml2lilypondVersion() { return 0.9f; } const char* versions::xml2lilypondVersionStr() { return "0.91"; } float versions::xml2brailleVersion() { return 0.01f; } const char* versions::xml2brailleVersionStr() { return "0.02"; } }
Update xml2guido version
Update xml2guido version
C++
mpl-2.0
grame-cncm/libmusicxml,dfober/libmusicxml,dfober/libmusicxml,dfober/libmusicxml,grame-cncm/libmusicxml,grame-cncm/libmusicxml,arshiacont/libmusicxml,grame-cncm/libmusicxml,arshiacont/libmusicxml,arshiacont/libmusicxml,grame-cncm/libmusicxml,arshiacont/libmusicxml,grame-cncm/libmusicxml,arshiacont/libmusicxml,dfober/libmusicxml