text
stringlengths
54
60.6k
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once struct Options { // Debug mode bool debug = false; // Print messages to standard output bool print = false; // Use subband dedispersion bool subbandDedispersion = false; // Avoid merging batches of dispersed data into contiguous memory bool splitBatchesDedispersion = false; // Compact the triggered events in time and DM dimensions bool compactResults = false; // Threshold for triggering float threshold = 0.0f; // SNR mode SNRMode snrMode; // Step size for median of medians (MOMAD mode) unsigned int medianStepSize = 5; }; struct DeviceOptions { // OpenCL synchronized operations bool synchronized = false; // OpenCL platform ID unsigned int platformID = 0; // OpenCL device ID unsigned int deviceID = 0; // OpenCL device name std::string deviceName{}; // Padding of OpenCL devices AstroData::paddingConf padding{}; }; struct DataOptions { // Use LOFAR file as input bool dataLOFAR = false; // Use SIGPROC file as input bool dataSIGPROC = false; // Use PSRDADA buffer as input bool dataPSRDADA = false; // SIGPROC streaming mode bool streamingMode = false; // Size (in bytes) of the SIGPROC file header unsigned int headerSizeSIGPROC = 0; // Name of the input file std::string dataFile{}; // Basename for the output files std::string outputFile{}; // Name of the file containing the zapped channels std::string channelsFile{}; // Name of the file containing the integration steps std::string integrationFile{}; #ifdef HAVE_HDF5 // Limit the number of batches processed from a LOFAR file bool limit = false; // Name of the LOFAR header file std::string headerFile{}; #endif // HAVE_HDF5 #ifdef HAVE_PSRDADA // PSRDADA buffer key key_t dadaKey = 0; #endif // HAVE_PSRDADA }; struct GeneratorOptions { // Use random numbers in generated data bool random = false; // Width of random generated pulse unsigned int width = 0; // DM of random generated pulse float DM = 0.0f; }; struct HostMemory { // Input data when reading a whole input file std::vector<std::vector<std::vector<inputDataType> *> *> input; // Input data when in streaming mode std::vector<std::vector<inputDataType> *> inputStream; // Zapped channels std::vector<unsigned int> zappedChannels; // Integration steps std::set<unsigned int> integrationSteps; // Map to create synthesized beams std::vector<unsigned int> beamMapping; // Dispersed data std::vector<inputDataType> dispersedData; // Subbanded data std::vector<outputDataType> subbandedData; // Dedispersed data std::vector<outputDataType> dedispersedData; // Integrated data std::vector<outputDataType> integratedData; // SNR data (SNR mode) std::vector<float> snrData; // Index of the sample with highest SNR value (SNR mode) std::vector<unsigned int> snrSamples; // Value of max sample (MOMAD mode) std::vector<outputDataType> maxValues; // Index of max sample (MOMAD MODE) std::vector<unsigned int> maxIndices; // Medians of medians (MOMAD mode) std::vector<outputDataType> mediansOfMedians; // Medians of medians absolute deviation (MOMAD mode) std::vector<outputDataType> medianOfMediansAbsoluteDeviation; // Shifts single step dedispersion std::vector<float> *shiftsSingleStep = nullptr; // Shifts step one subbanding dedispersion std::vector<float> *shiftsStepOne = nullptr; // Shifts step two subbanding dedispersion std::vector<float> *shiftsStepTwo = nullptr; #ifdef HAVE_PSRDADA // PSRDADA ring buffer dada_hdu_t *ringBuffer = nullptr; #endif // HAVE_PSRDADA }; struct DeviceMemory { // Shifts single step dedispersion cl::Buffer shiftsSingleStep; // Shifts step one subbanding dedispersion cl::Buffer shiftsStepOne; // Shifts step two subbanding dedispersion cl::Buffer shiftsStepTwo; // Zapped channels cl::Buffer zappedChannels; // Map to create synthesized beams cl::Buffer beamMapping; // Dispersed dada cl::Buffer dispersedData; // Subbanded data cl::Buffer subbandedData; // Dedispersed data cl::Buffer dedispersedData; // Integrated data cl::Buffer integratedData; // SNR data (SNR mode) cl::Buffer snrData; // Index of the sample with highest SNR value (SNR mode) cl::Buffer snrSamples; // Value of max sample (MOMAD mode) cl::Buffer maxValues; // Index of max sample (MOMAD mode) cl::Buffer maxIndices; // Median of medians first step (MOMAD mode) cl::Buffer medianOfMediansStepOne; // Median of medians second step (MOMAD mode) cl::Buffer medianOfMediansStepTwo; }; struct KernelConfigurations { // Configuration of single step dedispersion kernel Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters; // Configuration of subband dedispersion kernel, step one Dedispersion::tunedDedispersionConf dedispersionStepOneParameters; // Configuration of subband dedispersion kernel, step two Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters; // Configuration of integration kernel Integration::tunedIntegrationConf integrationParameters; // Configuration of SNR kernel (SNR mode) SNR::tunedSNRConf snrParameters; // Configuration of max kernel (MOMAD mode) SNR::tunedSNRConf maxParameters; // Configuration of median of medians first step (MOMAD mode) SNR::tunedSNRConf medianOfMediansStepOneParameters; // Configuration of median of medians second step (MOMAD mode) SNR::tunedSNRConf medianOfMediansStepTwoParameters; // Configuration of median of medians absolute deviation (MOMAD mode) SNR::tunedSNRConf medianOfMediansAbsoluteDeviationParameters; }; struct Kernels { // Single step dedispersion kernel cl::Kernel *dedispersionSingleStep = nullptr; // Step one subbanding dedispersion kernel cl::Kernel *dedispersionStepOne = nullptr; // Step two subbanding dedispersion kernel cl::Kernel *dedispersionStepTwo = nullptr; // Integration kernels, one for each integration step std::vector<cl::Kernel *> integration; // SNR kernels, one for the original data and one for each integration step (SNR mode) std::vector<cl::Kernel *> snr; // Max kernels, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> max; // Median of medians first step, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> medianOfMediansStepOne; // Median of medians second step, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> medianOfMediansStepTwo; // Median of medians absolute deviation, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> medianOfMediansAbsoluteDeviation; }; struct KernelRunTimeConfigurations { // Global NDrange for single step dedispersion cl::NDRange dedispersionSingleStepGlobal; // Local NDRange for single step dedispersion cl::NDRange dedispersionSingleStepLocal; // Global NDRange for subbanding dedispersion step one cl::NDRange dedispersionStepOneGlobal; // Local NDRange for subbanding dedispersion step one cl::NDRange dedispersionStepOneLocal; // Global NDRange for subbanding dedispersion step two cl::NDRange dedispersionStepTwoGlobal; // Local NDRange for subbanding dedispersion step two cl::NDRange dedispersionStepTwoLocal; // Global NDRange for integration std::vector<cl::NDRange> integrationGlobal; // Local NDRange for integration std::vector<cl::NDRange> integrationLocal; // Global NDRange for SNR (SNR mode) std::vector<cl::NDRange> snrGlobal; // Local NDRange for SNR (SNR mode) std::vector<cl::NDRange> snrLocal; // Global NDRange for max (MOMAD mode) std::vector<cl::NDRange> maxGlobal; // Local NDRange for max (MOMAD mode) std::vector<cl::NDRange> maxLocal; // Global NDRange for median of medians first step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepOneGlobal; // Local NDRange for median of medians first step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepOneLocal; // Global NDRange for median of medians second step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepTwoGlobal; // Local NDRange for median of medians second step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepTwoLocal; // Global NDRange for median of medians absolute deviation (MOMAD mode) std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationGlobal; // Local NDRange for median of medians absolute deviation (MOMAD mode) std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationLocal; }; struct Timers { isa::utils::Timer inputLoad; isa::utils::Timer search; isa::utils::Timer inputHandling; isa::utils::Timer inputCopy; isa::utils::Timer dedispersionSingleStep; isa::utils::Timer dedispersionStepOne; isa::utils::Timer dedispersionStepTwo; isa::utils::Timer integration; isa::utils::Timer snr; isa::utils::Timer max; isa::utils::Timer medianOfMediansStepOne; isa::utils::Timer medianOfMediansStepTwo; isa::utils::Timer medianOfMediansAbsoluteDeviationStepOne; isa::utils::Timer medianOfMediansAbsoluteDeviationStepTwo; isa::utils::Timer outputCopy; isa::utils::Timer trigger; }; struct TriggeredEvent { unsigned int beam = 0; unsigned int sample = 0; unsigned int integration = 0; float DM = 0.0f; float SNR = 0.0f; }; struct CompactedEvent : TriggeredEvent { unsigned int compactedIntegration = 1; unsigned int compactedDMs = 1; }; using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>; using CompactedEvents = std::vector<std::vector<CompactedEvent>>; struct OpenCLRunTime { cl::Context *context = nullptr; std::vector<cl::Platform> *platforms = nullptr; std::vector<cl::Device> *devices = nullptr; std::vector<std::vector<cl::CommandQueue>> *queues = nullptr; }; typedef enum { Standard, Momad } SNRMode; <commit_msg>Moving scope.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once typedef enum { Standard, Momad } SNRMode; struct Options { // Debug mode bool debug = false; // Print messages to standard output bool print = false; // Use subband dedispersion bool subbandDedispersion = false; // Avoid merging batches of dispersed data into contiguous memory bool splitBatchesDedispersion = false; // Compact the triggered events in time and DM dimensions bool compactResults = false; // Threshold for triggering float threshold = 0.0f; // SNR mode SNRMode snrMode; // Step size for median of medians (MOMAD mode) unsigned int medianStepSize = 5; }; struct DeviceOptions { // OpenCL synchronized operations bool synchronized = false; // OpenCL platform ID unsigned int platformID = 0; // OpenCL device ID unsigned int deviceID = 0; // OpenCL device name std::string deviceName{}; // Padding of OpenCL devices AstroData::paddingConf padding{}; }; struct DataOptions { // Use LOFAR file as input bool dataLOFAR = false; // Use SIGPROC file as input bool dataSIGPROC = false; // Use PSRDADA buffer as input bool dataPSRDADA = false; // SIGPROC streaming mode bool streamingMode = false; // Size (in bytes) of the SIGPROC file header unsigned int headerSizeSIGPROC = 0; // Name of the input file std::string dataFile{}; // Basename for the output files std::string outputFile{}; // Name of the file containing the zapped channels std::string channelsFile{}; // Name of the file containing the integration steps std::string integrationFile{}; #ifdef HAVE_HDF5 // Limit the number of batches processed from a LOFAR file bool limit = false; // Name of the LOFAR header file std::string headerFile{}; #endif // HAVE_HDF5 #ifdef HAVE_PSRDADA // PSRDADA buffer key key_t dadaKey = 0; #endif // HAVE_PSRDADA }; struct GeneratorOptions { // Use random numbers in generated data bool random = false; // Width of random generated pulse unsigned int width = 0; // DM of random generated pulse float DM = 0.0f; }; struct HostMemory { // Input data when reading a whole input file std::vector<std::vector<std::vector<inputDataType> *> *> input; // Input data when in streaming mode std::vector<std::vector<inputDataType> *> inputStream; // Zapped channels std::vector<unsigned int> zappedChannels; // Integration steps std::set<unsigned int> integrationSteps; // Map to create synthesized beams std::vector<unsigned int> beamMapping; // Dispersed data std::vector<inputDataType> dispersedData; // Subbanded data std::vector<outputDataType> subbandedData; // Dedispersed data std::vector<outputDataType> dedispersedData; // Integrated data std::vector<outputDataType> integratedData; // SNR data (SNR mode) std::vector<float> snrData; // Index of the sample with highest SNR value (SNR mode) std::vector<unsigned int> snrSamples; // Value of max sample (MOMAD mode) std::vector<outputDataType> maxValues; // Index of max sample (MOMAD MODE) std::vector<unsigned int> maxIndices; // Medians of medians (MOMAD mode) std::vector<outputDataType> mediansOfMedians; // Medians of medians absolute deviation (MOMAD mode) std::vector<outputDataType> medianOfMediansAbsoluteDeviation; // Shifts single step dedispersion std::vector<float> *shiftsSingleStep = nullptr; // Shifts step one subbanding dedispersion std::vector<float> *shiftsStepOne = nullptr; // Shifts step two subbanding dedispersion std::vector<float> *shiftsStepTwo = nullptr; #ifdef HAVE_PSRDADA // PSRDADA ring buffer dada_hdu_t *ringBuffer = nullptr; #endif // HAVE_PSRDADA }; struct DeviceMemory { // Shifts single step dedispersion cl::Buffer shiftsSingleStep; // Shifts step one subbanding dedispersion cl::Buffer shiftsStepOne; // Shifts step two subbanding dedispersion cl::Buffer shiftsStepTwo; // Zapped channels cl::Buffer zappedChannels; // Map to create synthesized beams cl::Buffer beamMapping; // Dispersed dada cl::Buffer dispersedData; // Subbanded data cl::Buffer subbandedData; // Dedispersed data cl::Buffer dedispersedData; // Integrated data cl::Buffer integratedData; // SNR data (SNR mode) cl::Buffer snrData; // Index of the sample with highest SNR value (SNR mode) cl::Buffer snrSamples; // Value of max sample (MOMAD mode) cl::Buffer maxValues; // Index of max sample (MOMAD mode) cl::Buffer maxIndices; // Median of medians first step (MOMAD mode) cl::Buffer medianOfMediansStepOne; // Median of medians second step (MOMAD mode) cl::Buffer medianOfMediansStepTwo; }; struct KernelConfigurations { // Configuration of single step dedispersion kernel Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters; // Configuration of subband dedispersion kernel, step one Dedispersion::tunedDedispersionConf dedispersionStepOneParameters; // Configuration of subband dedispersion kernel, step two Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters; // Configuration of integration kernel Integration::tunedIntegrationConf integrationParameters; // Configuration of SNR kernel (SNR mode) SNR::tunedSNRConf snrParameters; // Configuration of max kernel (MOMAD mode) SNR::tunedSNRConf maxParameters; // Configuration of median of medians first step (MOMAD mode) SNR::tunedSNRConf medianOfMediansStepOneParameters; // Configuration of median of medians second step (MOMAD mode) SNR::tunedSNRConf medianOfMediansStepTwoParameters; // Configuration of median of medians absolute deviation (MOMAD mode) SNR::tunedSNRConf medianOfMediansAbsoluteDeviationParameters; }; struct Kernels { // Single step dedispersion kernel cl::Kernel *dedispersionSingleStep = nullptr; // Step one subbanding dedispersion kernel cl::Kernel *dedispersionStepOne = nullptr; // Step two subbanding dedispersion kernel cl::Kernel *dedispersionStepTwo = nullptr; // Integration kernels, one for each integration step std::vector<cl::Kernel *> integration; // SNR kernels, one for the original data and one for each integration step (SNR mode) std::vector<cl::Kernel *> snr; // Max kernels, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> max; // Median of medians first step, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> medianOfMediansStepOne; // Median of medians second step, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> medianOfMediansStepTwo; // Median of medians absolute deviation, one for the original data and one for each integration step (MOMAD mode) std::vector<cl::Kernel *> medianOfMediansAbsoluteDeviation; }; struct KernelRunTimeConfigurations { // Global NDrange for single step dedispersion cl::NDRange dedispersionSingleStepGlobal; // Local NDRange for single step dedispersion cl::NDRange dedispersionSingleStepLocal; // Global NDRange for subbanding dedispersion step one cl::NDRange dedispersionStepOneGlobal; // Local NDRange for subbanding dedispersion step one cl::NDRange dedispersionStepOneLocal; // Global NDRange for subbanding dedispersion step two cl::NDRange dedispersionStepTwoGlobal; // Local NDRange for subbanding dedispersion step two cl::NDRange dedispersionStepTwoLocal; // Global NDRange for integration std::vector<cl::NDRange> integrationGlobal; // Local NDRange for integration std::vector<cl::NDRange> integrationLocal; // Global NDRange for SNR (SNR mode) std::vector<cl::NDRange> snrGlobal; // Local NDRange for SNR (SNR mode) std::vector<cl::NDRange> snrLocal; // Global NDRange for max (MOMAD mode) std::vector<cl::NDRange> maxGlobal; // Local NDRange for max (MOMAD mode) std::vector<cl::NDRange> maxLocal; // Global NDRange for median of medians first step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepOneGlobal; // Local NDRange for median of medians first step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepOneLocal; // Global NDRange for median of medians second step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepTwoGlobal; // Local NDRange for median of medians second step (MOMAD mode) std::vector<cl::NDRange> medianOfMediansStepTwoLocal; // Global NDRange for median of medians absolute deviation (MOMAD mode) std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationGlobal; // Local NDRange for median of medians absolute deviation (MOMAD mode) std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationLocal; }; struct Timers { isa::utils::Timer inputLoad; isa::utils::Timer search; isa::utils::Timer inputHandling; isa::utils::Timer inputCopy; isa::utils::Timer dedispersionSingleStep; isa::utils::Timer dedispersionStepOne; isa::utils::Timer dedispersionStepTwo; isa::utils::Timer integration; isa::utils::Timer snr; isa::utils::Timer max; isa::utils::Timer medianOfMediansStepOne; isa::utils::Timer medianOfMediansStepTwo; isa::utils::Timer medianOfMediansAbsoluteDeviationStepOne; isa::utils::Timer medianOfMediansAbsoluteDeviationStepTwo; isa::utils::Timer outputCopy; isa::utils::Timer trigger; }; struct TriggeredEvent { unsigned int beam = 0; unsigned int sample = 0; unsigned int integration = 0; float DM = 0.0f; float SNR = 0.0f; }; struct CompactedEvent : TriggeredEvent { unsigned int compactedIntegration = 1; unsigned int compactedDMs = 1; }; using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>; using CompactedEvents = std::vector<std::vector<CompactedEvent>>; struct OpenCLRunTime { cl::Context *context = nullptr; std::vector<cl::Platform> *platforms = nullptr; std::vector<cl::Device> *devices = nullptr; std::vector<std::vector<cl::CommandQueue>> *queues = nullptr; }; <|endoftext|>
<commit_before>// 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 "chrome/browser/ui/views/file_manager_dialog.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/threading/platform_thread.h" #include "base/utf_string_conversions.h" // ASCIIToUTF16 #include "build/build_config.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/shell_dialogs.h" // SelectFileDialog #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/common/content_notification_types.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_mount_point_provider.h" #include "webkit/fileapi/file_system_path_manager.h" // Mock listener used by test below. class MockSelectFileDialogListener : public SelectFileDialog::Listener { public: MockSelectFileDialogListener() : file_selected_(false), canceled_(false), params_(NULL) { } bool file_selected() const { return file_selected_; } bool canceled() const { return canceled_; } FilePath path() const { return path_; } void* params() const { return params_; } // SelectFileDialog::Listener implementation. virtual void FileSelected(const FilePath& path, int index, void* params) { file_selected_ = true; path_ = path; params_ = params; } virtual void MultiFilesSelected( const std::vector<FilePath>& files, void* params) {} virtual void FileSelectionCanceled(void* params) { canceled_ = true; params_ = params; } private: bool file_selected_; bool canceled_; FilePath path_; void* params_; DISALLOW_COPY_AND_ASSIGN(MockSelectFileDialogListener); }; class FileManagerDialogTest : public ExtensionBrowserTest { public: void SetUp() { // Create the dialog wrapper object, but don't show it yet. listener_.reset(new MockSelectFileDialogListener()); dialog_ = new FileManagerDialog(listener_.get()); // Must run after our setup because it actually runs the test. ExtensionBrowserTest::SetUp(); } void TearDown() { ExtensionBrowserTest::TearDown(); // Release the dialog first, as it holds a pointer to the listener. dialog_.release(); listener_.reset(); } // Creates a file system mount point for a directory. void AddMountPoint(const FilePath& path) { fileapi::FileSystemPathManager* path_manager = browser()->profile()->GetFileSystemContext()->path_manager(); fileapi::ExternalFileSystemMountPointProvider* provider = path_manager->external_provider(); provider->AddMountPoint(path); } scoped_ptr<MockSelectFileDialogListener> listener_; scoped_refptr<FileManagerDialog> dialog_; }; IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerCreateAndDestroy) { // Browser window must be up for us to test dialog window parent. gfx::NativeWindow native_window = browser()->window()->GetNativeHandle(); ASSERT_TRUE(native_window != NULL); // Before we call SelectFile, dialog is not running/visible. ASSERT_FALSE(dialog_->IsRunning(native_window)); } IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerDestroyListener) { // Some users of SelectFileDialog destroy their listener before cleaning // up the dialog. Make sure we don't crash. dialog_->ListenerDestroyed(); listener_.reset(); } // Flaky: http://crbug.com/89733 IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FLAKY_SelectFileAndCancel) { // Add tmp mount point even though this test won't use it directly. // We need this to make sure that at least one top-level directory exists // in the file browser. FilePath tmp_dir("/tmp"); AddMountPoint(tmp_dir); // Spawn a dialog to open a file. The dialog will signal that it is done // loading via chrome.test.sendMessage('ready') in the extension JavaScript. ExtensionTestMessageListener msg_listener("ready", false /* will_reply */); gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle(); dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE, string16() /* title */, FilePath() /* default_path */, NULL /* file_types */, 0 /* file_type_index */, FILE_PATH_LITERAL("") /* default_extension */, NULL /* source_contents */, owning_window, this /* params */); LOG(INFO) << "Waiting for JavaScript ready message."; ASSERT_TRUE(msg_listener.WaitUntilSatisfied()); // Dialog should be running now. ASSERT_TRUE(dialog_->IsRunning(owning_window)); // Inject JavaScript to click the cancel button and wait for notification // that the window has closed. ui_test_utils::WindowedNotificationObserver host_destroyed( content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); RenderViewHost* host = dialog_->GetRenderViewHost(); string16 main_frame; string16 script = ASCIIToUTF16( "console.log(\'Test JavaScript injected.\');" "document.querySelector(\'.cancel\').click();"); // The file selection handler closes the dialog and does not return control // to JavaScript, so do not wait for return values. host->ExecuteJavascriptInWebFrame(main_frame, script); LOG(INFO) << "Waiting for window close notification."; host_destroyed.Wait(); // Dialog no longer believes it is running. ASSERT_FALSE(dialog_->IsRunning(owning_window)); // Listener should have been informed of the cancellation. ASSERT_FALSE(listener_->file_selected()); ASSERT_TRUE(listener_->canceled()); ASSERT_EQ(this, listener_->params()); } IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, SelectFileAndOpen) { // Allow the tmp directory to be mounted. We explicitly use /tmp because // it it whitelisted for file system access on Chrome OS. FilePath tmp_dir("/tmp"); AddMountPoint(tmp_dir); // Create a directory with a single file in it. ScopedTempDir will delete // itself and our temp file when it goes out of scope. ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir)); FilePath temp_dir = scoped_temp_dir.path(); FilePath test_file = temp_dir.AppendASCII("file_manager_test.html"); // Create an empty file to give us something to select. FILE* fp = file_util::OpenFile(test_file, "w"); ASSERT_TRUE(fp != NULL); ASSERT_TRUE(file_util::CloseFile(fp)); // Spawn a dialog to open a file. Provide the path to the file so the dialog // will automatically select it. Ensure that the OK button is enabled by // waiting for chrome.test.sendMessage('selection-change-complete'). ExtensionTestMessageListener msg_listener("selection-change-complete", false /* will_reply */); gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle(); dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE, string16() /* title */, test_file, NULL /* file_types */, 0 /* file_type_index */, FILE_PATH_LITERAL("") /* default_extension */, NULL /* source_contents */, owning_window, this /* params */); LOG(INFO) << "Waiting for JavaScript selection-change-complete message."; ASSERT_TRUE(msg_listener.WaitUntilSatisfied()); // Dialog should be running now. ASSERT_TRUE(dialog_->IsRunning(owning_window)); // Inject JavaScript to click the open button and wait for notification // that the window has closed. ui_test_utils::WindowedNotificationObserver host_destroyed( content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); RenderViewHost* host = dialog_->GetRenderViewHost(); string16 main_frame; string16 script = ASCIIToUTF16( "console.log(\'Test JavaScript injected.\');" "document.querySelector('.ok').click();"); // The file selection handler closes the dialog and does not return control // to JavaScript, so do not wait for return values. host->ExecuteJavascriptInWebFrame(main_frame, script); LOG(INFO) << "Waiting for window close notification."; host_destroyed.Wait(); // Dialog no longer believes it is running. ASSERT_FALSE(dialog_->IsRunning(owning_window)); // Listener should have been informed that the file was opened. ASSERT_TRUE(listener_->file_selected()); ASSERT_FALSE(listener_->canceled()); ASSERT_EQ(test_file, listener_->path()); ASSERT_EQ(this, listener_->params()); } // Flaky: http://crbug.com/89733 IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FLAKY_SelectFileAndSave) { // Allow the tmp directory to be mounted. We explicitly use /tmp because // it it whitelisted for file system access on Chrome OS. FilePath tmp_dir("/tmp"); AddMountPoint(tmp_dir); // Create a directory with a single file in it. ScopedTempDir will delete // itself and our temp file when it goes out of scope. ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir)); FilePath temp_dir = scoped_temp_dir.path(); FilePath test_file = temp_dir.AppendASCII("file_manager_test.html"); // Spawn a dialog to save a file, providing a suggested path. // Ensure "Save" button is enabled by waiting for notification from // chrome.test.sendMessage(). ExtensionTestMessageListener msg_listener("directory-change-complete", false /* will_reply */); gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle(); dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE, string16() /* title */, test_file, NULL /* file_types */, 0 /* file_type_index */, FILE_PATH_LITERAL("") /* default_extension */, NULL /* source_contents */, owning_window, this /* params */); LOG(INFO) << "Waiting for JavaScript message."; ASSERT_TRUE(msg_listener.WaitUntilSatisfied()); // Dialog should be running now. ASSERT_TRUE(dialog_->IsRunning(owning_window)); // Inject JavaScript to click the save button and wait for notification // that the window has closed. ui_test_utils::WindowedNotificationObserver host_destroyed( content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); RenderViewHost* host = dialog_->GetRenderViewHost(); string16 main_frame; string16 script = ASCIIToUTF16( "console.log(\'Test JavaScript injected.\');" "document.querySelector('.ok').click();"); // The file selection handler closes the dialog and does not return control // to JavaScript, so do not wait for return values. host->ExecuteJavascriptInWebFrame(main_frame, script); LOG(INFO) << "Waiting for window close notification."; host_destroyed.Wait(); // Dialog no longer believes it is running. ASSERT_FALSE(dialog_->IsRunning(owning_window)); // Listener should have been informed that the file was selected. ASSERT_TRUE(listener_->file_selected()); ASSERT_FALSE(listener_->canceled()); ASSERT_EQ(test_file, listener_->path()); ASSERT_EQ(this, listener_->params()); } <commit_msg>Mark SelectFileAndSave as DISABLED.<commit_after>// 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 "chrome/browser/ui/views/file_manager_dialog.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/threading/platform_thread.h" #include "base/utf_string_conversions.h" // ASCIIToUTF16 #include "build/build_config.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/shell_dialogs.h" // SelectFileDialog #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/common/content_notification_types.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_mount_point_provider.h" #include "webkit/fileapi/file_system_path_manager.h" // Mock listener used by test below. class MockSelectFileDialogListener : public SelectFileDialog::Listener { public: MockSelectFileDialogListener() : file_selected_(false), canceled_(false), params_(NULL) { } bool file_selected() const { return file_selected_; } bool canceled() const { return canceled_; } FilePath path() const { return path_; } void* params() const { return params_; } // SelectFileDialog::Listener implementation. virtual void FileSelected(const FilePath& path, int index, void* params) { file_selected_ = true; path_ = path; params_ = params; } virtual void MultiFilesSelected( const std::vector<FilePath>& files, void* params) {} virtual void FileSelectionCanceled(void* params) { canceled_ = true; params_ = params; } private: bool file_selected_; bool canceled_; FilePath path_; void* params_; DISALLOW_COPY_AND_ASSIGN(MockSelectFileDialogListener); }; class FileManagerDialogTest : public ExtensionBrowserTest { public: void SetUp() { // Create the dialog wrapper object, but don't show it yet. listener_.reset(new MockSelectFileDialogListener()); dialog_ = new FileManagerDialog(listener_.get()); // Must run after our setup because it actually runs the test. ExtensionBrowserTest::SetUp(); } void TearDown() { ExtensionBrowserTest::TearDown(); // Release the dialog first, as it holds a pointer to the listener. dialog_.release(); listener_.reset(); } // Creates a file system mount point for a directory. void AddMountPoint(const FilePath& path) { fileapi::FileSystemPathManager* path_manager = browser()->profile()->GetFileSystemContext()->path_manager(); fileapi::ExternalFileSystemMountPointProvider* provider = path_manager->external_provider(); provider->AddMountPoint(path); } scoped_ptr<MockSelectFileDialogListener> listener_; scoped_refptr<FileManagerDialog> dialog_; }; IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerCreateAndDestroy) { // Browser window must be up for us to test dialog window parent. gfx::NativeWindow native_window = browser()->window()->GetNativeHandle(); ASSERT_TRUE(native_window != NULL); // Before we call SelectFile, dialog is not running/visible. ASSERT_FALSE(dialog_->IsRunning(native_window)); } IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerDestroyListener) { // Some users of SelectFileDialog destroy their listener before cleaning // up the dialog. Make sure we don't crash. dialog_->ListenerDestroyed(); listener_.reset(); } // Flaky: http://crbug.com/89733 IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FLAKY_SelectFileAndCancel) { // Add tmp mount point even though this test won't use it directly. // We need this to make sure that at least one top-level directory exists // in the file browser. FilePath tmp_dir("/tmp"); AddMountPoint(tmp_dir); // Spawn a dialog to open a file. The dialog will signal that it is done // loading via chrome.test.sendMessage('ready') in the extension JavaScript. ExtensionTestMessageListener msg_listener("ready", false /* will_reply */); gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle(); dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE, string16() /* title */, FilePath() /* default_path */, NULL /* file_types */, 0 /* file_type_index */, FILE_PATH_LITERAL("") /* default_extension */, NULL /* source_contents */, owning_window, this /* params */); LOG(INFO) << "Waiting for JavaScript ready message."; ASSERT_TRUE(msg_listener.WaitUntilSatisfied()); // Dialog should be running now. ASSERT_TRUE(dialog_->IsRunning(owning_window)); // Inject JavaScript to click the cancel button and wait for notification // that the window has closed. ui_test_utils::WindowedNotificationObserver host_destroyed( content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); RenderViewHost* host = dialog_->GetRenderViewHost(); string16 main_frame; string16 script = ASCIIToUTF16( "console.log(\'Test JavaScript injected.\');" "document.querySelector(\'.cancel\').click();"); // The file selection handler closes the dialog and does not return control // to JavaScript, so do not wait for return values. host->ExecuteJavascriptInWebFrame(main_frame, script); LOG(INFO) << "Waiting for window close notification."; host_destroyed.Wait(); // Dialog no longer believes it is running. ASSERT_FALSE(dialog_->IsRunning(owning_window)); // Listener should have been informed of the cancellation. ASSERT_FALSE(listener_->file_selected()); ASSERT_TRUE(listener_->canceled()); ASSERT_EQ(this, listener_->params()); } IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, SelectFileAndOpen) { // Allow the tmp directory to be mounted. We explicitly use /tmp because // it it whitelisted for file system access on Chrome OS. FilePath tmp_dir("/tmp"); AddMountPoint(tmp_dir); // Create a directory with a single file in it. ScopedTempDir will delete // itself and our temp file when it goes out of scope. ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir)); FilePath temp_dir = scoped_temp_dir.path(); FilePath test_file = temp_dir.AppendASCII("file_manager_test.html"); // Create an empty file to give us something to select. FILE* fp = file_util::OpenFile(test_file, "w"); ASSERT_TRUE(fp != NULL); ASSERT_TRUE(file_util::CloseFile(fp)); // Spawn a dialog to open a file. Provide the path to the file so the dialog // will automatically select it. Ensure that the OK button is enabled by // waiting for chrome.test.sendMessage('selection-change-complete'). ExtensionTestMessageListener msg_listener("selection-change-complete", false /* will_reply */); gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle(); dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE, string16() /* title */, test_file, NULL /* file_types */, 0 /* file_type_index */, FILE_PATH_LITERAL("") /* default_extension */, NULL /* source_contents */, owning_window, this /* params */); LOG(INFO) << "Waiting for JavaScript selection-change-complete message."; ASSERT_TRUE(msg_listener.WaitUntilSatisfied()); // Dialog should be running now. ASSERT_TRUE(dialog_->IsRunning(owning_window)); // Inject JavaScript to click the open button and wait for notification // that the window has closed. ui_test_utils::WindowedNotificationObserver host_destroyed( content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); RenderViewHost* host = dialog_->GetRenderViewHost(); string16 main_frame; string16 script = ASCIIToUTF16( "console.log(\'Test JavaScript injected.\');" "document.querySelector('.ok').click();"); // The file selection handler closes the dialog and does not return control // to JavaScript, so do not wait for return values. host->ExecuteJavascriptInWebFrame(main_frame, script); LOG(INFO) << "Waiting for window close notification."; host_destroyed.Wait(); // Dialog no longer believes it is running. ASSERT_FALSE(dialog_->IsRunning(owning_window)); // Listener should have been informed that the file was opened. ASSERT_TRUE(listener_->file_selected()); ASSERT_FALSE(listener_->canceled()); ASSERT_EQ(test_file, listener_->path()); ASSERT_EQ(this, listener_->params()); } // Flaky: http://crbug.com/89733 IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, DISABLED_SelectFileAndSave) { // Allow the tmp directory to be mounted. We explicitly use /tmp because // it it whitelisted for file system access on Chrome OS. FilePath tmp_dir("/tmp"); AddMountPoint(tmp_dir); // Create a directory with a single file in it. ScopedTempDir will delete // itself and our temp file when it goes out of scope. ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir)); FilePath temp_dir = scoped_temp_dir.path(); FilePath test_file = temp_dir.AppendASCII("file_manager_test.html"); // Spawn a dialog to save a file, providing a suggested path. // Ensure "Save" button is enabled by waiting for notification from // chrome.test.sendMessage(). ExtensionTestMessageListener msg_listener("directory-change-complete", false /* will_reply */); gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle(); dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE, string16() /* title */, test_file, NULL /* file_types */, 0 /* file_type_index */, FILE_PATH_LITERAL("") /* default_extension */, NULL /* source_contents */, owning_window, this /* params */); LOG(INFO) << "Waiting for JavaScript message."; ASSERT_TRUE(msg_listener.WaitUntilSatisfied()); // Dialog should be running now. ASSERT_TRUE(dialog_->IsRunning(owning_window)); // Inject JavaScript to click the save button and wait for notification // that the window has closed. ui_test_utils::WindowedNotificationObserver host_destroyed( content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); RenderViewHost* host = dialog_->GetRenderViewHost(); string16 main_frame; string16 script = ASCIIToUTF16( "console.log(\'Test JavaScript injected.\');" "document.querySelector('.ok').click();"); // The file selection handler closes the dialog and does not return control // to JavaScript, so do not wait for return values. host->ExecuteJavascriptInWebFrame(main_frame, script); LOG(INFO) << "Waiting for window close notification."; host_destroyed.Wait(); // Dialog no longer believes it is running. ASSERT_FALSE(dialog_->IsRunning(owning_window)); // Listener should have been informed that the file was selected. ASSERT_TRUE(listener_->file_selected()); ASSERT_FALSE(listener_->canceled()); ASSERT_EQ(test_file, listener_->path()); ASSERT_EQ(this, listener_->params()); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbOGRDataSourceWrapper.h" #include "otbOGRFeatureWrapper.h" #include "itkVariableLengthVector.h" #include "otbStatisticsXMLFileReader.h" #include "itkListSample.h" #include "otbShiftScaleSampleListFilter.h" #include "otbMachineLearningModelFactory.h" #include "otbMachineLearningModel.h" #include <time.h> namespace otb { namespace Wrapper { /** Utility function to negate std::isalnum */ bool IsNotAlphaNum(char c) { return !std::isalnum(c); } class VectorClassifier : public Application { public: /** Standard class typedefs. */ typedef VectorClassifier Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Self, Application) /** Filters typedef */ typedef double ValueType; typedef unsigned int LabelType; typedef itk::FixedArray<LabelType,1> LabelSampleType; typedef itk::Statistics::ListSample<LabelSampleType> LabelListSampleType; typedef otb::MachineLearningModel<ValueType,LabelType> MachineLearningModelType; typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType; typedef MachineLearningModelType::Pointer ModelPointerType; typedef MachineLearningModelType::ConfidenceListSampleType ConfidenceListSampleType; /** Statistics Filters typedef */ typedef itk::VariableLengthVector<ValueType> MeasurementType; typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; typedef itk::VariableLengthVector<ValueType> InputSampleType; typedef itk::Statistics::ListSample<InputSampleType> ListSampleType; typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType, ListSampleType> ShiftScaleFilterType; ~VectorClassifier() ITK_OVERRIDE { MachineLearningModelFactoryType::CleanFactories(); } private: void DoInit() ITK_OVERRIDE { SetName("VectorClassifier"); SetDescription("Performs a classification of the input vector data according to a model file." "Features of the vector data output will contain the class labels decided by the classifier (maximal class label = 65535)."); SetDocName("Vector Classification"); SetDocAuthors("OTB-Team"); SetDocLongDescription("This application performs a vector data classification based on a model file produced by the TrainVectorClassifier application."); SetDocLimitations("Shapefiles are supported. But the SQLite format is only supported in update mode."); SetDocSeeAlso("TrainVectorClassifier"); AddDocTag(Tags::Learning); AddParameter(ParameterType_InputVectorData, "in", "Name of the input vector data"); SetParameterDescription("in","The input vector data to classify."); AddParameter(ParameterType_InputFilename, "instat", "Statistics file"); SetParameterDescription("instat", "A XML file containing mean and standard deviation to center" "and reduce samples before classification (produced by ComputeImagesStatistics application)."); MandatoryOff("instat"); AddParameter(ParameterType_InputFilename, "model", "Model file"); SetParameterDescription("model", "A model file (produced by TrainVectorClassifier application," "maximal class label = 65535)."); AddParameter(ParameterType_String,"cfield","Field containing the predicted class"); SetParameterDescription("cfield","Field containing the predicted class." "Only geometries with this field available will be taken into account."); SetParameterString("cfield","predicted", false); AddParameter(ParameterType_ListView, "feat", "Field names to be calculated."); // SetParameterDescription("feat","List of field names in the input vector data used as features for training."); // AddParameter(ParameterType_Empty, "confmap", "Confidence map"); SetParameterDescription( "confmap", "Confidence map of the produced classification. The confidence index depends on the model : \n" " - LibSVM : difference between the two highest probabilities (needs a model with probability estimates, so that classes probabilities can be computed for each sample)\n" " - OpenCV\n" " * Boost : sum of votes\n" " * DecisionTree : (not supported)\n" " * GradientBoostedTree : (not supported)\n" " * KNearestNeighbors : number of neighbors with the same label\n" " * NeuralNetwork : difference between the two highest responses\n" " * NormalBayes : (not supported)\n" " * RandomForest : Confidence (proportion of votes for the majority class). Margin (normalized difference of the votes of the 2 majority classes) is not available for now.\n" " * SVM : distance to margin (only works for 2-class models)\n"); MandatoryOff("confmap"); AddParameter(ParameterType_OutputFilename, "out", "Output vector data file containing class labels"); SetParameterDescription("out","Output vector data file storing sample values (OGR format)." "If not given, the input vector data file is updated."); MandatoryOff("out"); // Doc example parameter settings SetDocExampleParameterValue("in", "vectorData.shp"); SetDocExampleParameterValue("instat", "meanVar.xml"); SetDocExampleParameterValue("model", "svmModel.svm"); SetDocExampleParameterValue("out", "svmModel.svm"); SetDocExampleParameterValue("feat", "perimeter area width"); SetDocExampleParameterValue("cfield", "predicted"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { if ( HasValue("in") ) { std::string shapefile = GetParameterString("in"); otb::ogr::DataSource::Pointer ogrDS; OGRSpatialReference oSRS(""); std::vector<std::string> options; ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read); otb::ogr::Layer layer = ogrDS->GetLayer(0); OGRFeatureDefn &layerDefn = layer.GetLayerDefn(); ClearChoices("feat"); for(int iField=0; iField< layerDefn.GetFieldCount(); iField++) { std::string item = layerDefn.GetFieldDefn(iField)->GetNameRef(); std::string key(item); key.erase( std::remove_if(key.begin(),key.end(),IsNotAlphaNum), key.end()); std::transform(key.begin(), key.end(), key.begin(), tolower); OGRFieldType fieldType = layerDefn.GetFieldDefn(iField)->GetType(); if(fieldType == OFTInteger || ogr::version_proxy::IsOFTInteger64(fieldType) || fieldType == OFTReal) { std::string tmpKey="feat."+key; AddChoice(tmpKey,item); } } } } void DoExecute() ITK_OVERRIDE { clock_t tic = clock(); std::string shapefile = GetParameterString("in"); otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read); otb::ogr::Layer layer = source->GetLayer(0); ListSampleType::Pointer input = ListSampleType::New(); const int nbFeatures = GetSelectedItems("feat").size(); input->SetMeasurementVectorSize(nbFeatures); otb::ogr::Layer::const_iterator it = layer.cbegin(); otb::ogr::Layer::const_iterator itEnd = layer.cend(); for( ; it!=itEnd ; ++it) { MeasurementType mv; mv.SetSize(nbFeatures); for(int idx=0; idx < nbFeatures; ++idx) { mv[idx] = (*it)[GetSelectedItems("feat")[idx]].GetValue<double>(); } input->PushBack(mv); } // Statistics for shift/scale MeasurementType meanMeasurementVector; MeasurementType stddevMeasurementVector; if (HasValue("instat") && IsParameterEnabled("instat")) { StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); std::string XMLfile = GetParameterString("instat"); statisticsReader->SetFileName(XMLfile); meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); } else { meanMeasurementVector.SetSize(nbFeatures); meanMeasurementVector.Fill(0.); stddevMeasurementVector.SetSize(nbFeatures); stddevMeasurementVector.Fill(1.); } ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New(); trainingShiftScaleFilter->SetInput(input); trainingShiftScaleFilter->SetShifts(meanMeasurementVector); trainingShiftScaleFilter->SetScales(stddevMeasurementVector); trainingShiftScaleFilter->Update(); otbAppLogINFO("mean used: " << meanMeasurementVector); otbAppLogINFO("standard deviation used: " << stddevMeasurementVector); otbAppLogINFO("Loading model"); m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"), MachineLearningModelFactoryType::ReadMode); if (m_Model.IsNull()) { otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type"); } m_Model->Load(GetParameterString("model")); otbAppLogINFO("Model loaded"); ListSampleType::Pointer listSample = trainingShiftScaleFilter->GetOutput(); ConfidenceListSampleType::Pointer quality; bool computeConfidenceMap(IsParameterEnabled("confmap") && m_Model->HasConfidenceIndex() && !m_Model->GetRegressionMode()); if (!m_Model->HasConfidenceIndex() && IsParameterEnabled("confmap")) { otbAppLogWARNING("Confidence map requested but the classifier doesn't support it!"); } LabelListSampleType::Pointer target; if (computeConfidenceMap) { quality = ConfidenceListSampleType::New(); target = m_Model->PredictBatch(listSample, quality); } else { target = m_Model->PredictBatch(listSample); } ogr::DataSource::Pointer output; ogr::DataSource::Pointer buffer = ogr::DataSource::New(); bool updateMode = false; if (IsParameterEnabled("out") && HasValue("out")) { // Create new OGRDataSource output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Overwrite); otb::ogr::Layer newLayer = output->CreateLayer( GetParameterString("out"), const_cast<OGRSpatialReference*>(layer.GetSpatialRef()), layer.GetGeomType()); // Copy existing fields OGRFeatureDefn &inLayerDefn = layer.GetLayerDefn(); for (int k=0 ; k<inLayerDefn.GetFieldCount() ; k++) { OGRFieldDefn fieldDefn(inLayerDefn.GetFieldDefn(k)); newLayer.CreateField(fieldDefn); } } else { // Update mode updateMode = true; otbAppLogINFO("Update input vector data."); // fill temporary buffer for the transfer otb::ogr::Layer inputLayer = layer; layer = buffer->CopyLayer(inputLayer, std::string("Buffer")); // close input data source source->Clear(); // Re-open input data source in update mode output = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Update_LayerUpdate); } otb::ogr::Layer outLayer = output->GetLayer(0); OGRErr errStart = outLayer.ogr().StartTransaction(); if (errStart != OGRERR_NONE) { itkExceptionMacro(<< "Unable to start transaction for OGR layer " << outLayer.ogr().GetName() << "."); } // Add the field of prediction in the output layer if field not exist OGRFeatureDefn &layerDefn = layer.GetLayerDefn(); int idx = layerDefn.GetFieldIndex(GetParameterString("cfield").c_str()); if (idx >= 0) { if (layerDefn.GetFieldDefn(idx)->GetType() != OFTInteger) itkExceptionMacro("Field name "<< GetParameterString("cfield") << " already exists with a different type!"); } else { OGRFieldDefn predictedField(GetParameterString("cfield").c_str(), OFTInteger); ogr::FieldDefn predictedFieldDef(predictedField); outLayer.CreateField(predictedFieldDef); } // Add confidence field in the output layer std::string confFieldName("confidence"); if (computeConfidenceMap) { idx = layerDefn.GetFieldIndex(confFieldName.c_str()); if (idx >= 0) { if (layerDefn.GetFieldDefn(idx)->GetType() != OFTReal) itkExceptionMacro("Field name "<< confFieldName << " already exists with a different type!"); } else { OGRFieldDefn confidenceField(confFieldName.c_str(), OFTReal); confidenceField.SetWidth(confidenceField.GetWidth()); confidenceField.SetPrecision(confidenceField.GetPrecision()); ogr::FieldDefn confFieldDefn(confidenceField); outLayer.CreateField(confFieldDefn); } } // Fill output layer unsigned int count=0; std::string classfieldname = GetParameterString("cfield"); it = layer.cbegin(); itEnd = layer.cend(); for( ; it!=itEnd ; ++it, ++count) { ogr::Feature dstFeature(outLayer.GetLayerDefn()); dstFeature.SetFrom( *it , TRUE); dstFeature.SetFID(it->GetFID()); dstFeature[classfieldname].SetValue<int>(target->GetMeasurementVector(count)[0]); if (computeConfidenceMap) dstFeature[confFieldName].SetValue<double>(quality->GetMeasurementVector(count)[0]); if (updateMode) { outLayer.SetFeature(dstFeature); } else { outLayer.CreateFeature(dstFeature); } } if(outLayer.ogr().TestCapability("Transactions")) { const OGRErr errCommitX = outLayer.ogr().CommitTransaction(); if (errCommitX != OGRERR_NONE) { itkExceptionMacro(<< "Unable to commit transaction for OGR layer " << outLayer.ogr().GetName() << "."); } } output->SyncToDisk(); clock_t toc = clock(); otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds."); } ModelPointerType m_Model; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::VectorClassifier) <commit_msg>DOC: enhance VectorClassifier application<commit_after>/* * Copyright (C) 2005-2017 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbOGRDataSourceWrapper.h" #include "otbOGRFeatureWrapper.h" #include "itkVariableLengthVector.h" #include "otbStatisticsXMLFileReader.h" #include "itkListSample.h" #include "otbShiftScaleSampleListFilter.h" #include "otbMachineLearningModelFactory.h" #include "otbMachineLearningModel.h" #include <time.h> namespace otb { namespace Wrapper { /** Utility function to negate std::isalnum */ bool IsNotAlphaNum(char c) { return !std::isalnum(c); } class VectorClassifier : public Application { public: /** Standard class typedefs. */ typedef VectorClassifier Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Self, Application) /** Filters typedef */ typedef double ValueType; typedef unsigned int LabelType; typedef itk::FixedArray<LabelType,1> LabelSampleType; typedef itk::Statistics::ListSample<LabelSampleType> LabelListSampleType; typedef otb::MachineLearningModel<ValueType,LabelType> MachineLearningModelType; typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType; typedef MachineLearningModelType::Pointer ModelPointerType; typedef MachineLearningModelType::ConfidenceListSampleType ConfidenceListSampleType; /** Statistics Filters typedef */ typedef itk::VariableLengthVector<ValueType> MeasurementType; typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; typedef itk::VariableLengthVector<ValueType> InputSampleType; typedef itk::Statistics::ListSample<InputSampleType> ListSampleType; typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType, ListSampleType> ShiftScaleFilterType; ~VectorClassifier() ITK_OVERRIDE { MachineLearningModelFactoryType::CleanFactories(); } private: void DoInit() ITK_OVERRIDE { SetName("VectorClassifier"); SetDescription("Performs a classification of the input vector data according to a model file."); SetDocName("Vector Classification"); SetDocAuthors("OTB-Team"); SetDocLongDescription("This application performs a vector data classification " "based on a model file produced by the TrainVectorClassifier application." "Features of the vector data output will contain the class labels decided by the classifier " "(maximal class label = 65535). \n" "There are two modes: \n" "1) Update mode: add of the 'cfield' field containing the predicted class in the input file. \n" "2) Write mode: copies the existing fields of the input file in the output file " " and add the 'cfield' field containing the predicted class. \n" "If you have declared the output file, the write mode applies. " "Otherwise, the input file update mode will be applied."); SetDocLimitations("Shapefiles are supported. But the SQLite format is only supported in update mode."); SetDocSeeAlso("TrainVectorClassifier"); AddDocTag(Tags::Learning); AddParameter(ParameterType_InputVectorData, "in", "Name of the input vector data"); SetParameterDescription("in","The input vector data file to classify."); AddParameter(ParameterType_InputFilename, "instat", "Statistics file"); SetParameterDescription("instat", "A XML file containing mean and standard deviation to center" "and reduce samples before classification, produced by ComputeImagesStatistics application."); MandatoryOff("instat"); AddParameter(ParameterType_InputFilename, "model", "Model file"); SetParameterDescription("model", "Model file produced by TrainVectorClassifier application."); AddParameter(ParameterType_String,"cfield","Field class"); SetParameterDescription("cfield","Field containing the predicted class." "Only geometries with this field available will be taken into account.\n" "The field is added either in the input file (if 'out' off) or in the output file.\n" "Caution, the 'cfield' must not exist in the input file if you are updating the file."); SetParameterString("cfield","predicted", false); AddParameter(ParameterType_ListView, "feat", "Field names to be calculated."); SetParameterDescription("feat","List of field names in the input vector data used as features for training. " "Put the same field names as the TrainVectorClassifier application."); AddParameter(ParameterType_Empty, "confmap", "Confidence map"); SetParameterDescription( "confmap", "Confidence map of the produced classification. " "The confidence index depends on the model : \n" " - LibSVM : difference between the two highest probabilities " "(needs a model with probability estimates, so that classes probabilities can be computed for each sample)\n" " - OpenCV\n" " * Boost : sum of votes\n" " * DecisionTree : (not supported)\n" " * GradientBoostedTree : (not supported)\n" " * KNearestNeighbors : number of neighbors with the same label\n" " * NeuralNetwork : difference between the two highest responses\n" " * NormalBayes : (not supported)\n" " * RandomForest : Confidence (proportion of votes for the majority class). " "Margin (normalized difference of the votes of the 2 majority classes) is not available for now.\n" " * SVM : distance to margin (only works for 2-class models).\n"); MandatoryOff("confmap"); AddParameter(ParameterType_OutputFilename, "out", "Output vector data file containing class labels"); SetParameterDescription("out","Output vector data file storing sample values (OGR format)." "If not given, the input vector data file is updated."); MandatoryOff("out"); // Doc example parameter settings SetDocExampleParameterValue("in", "vectorData.shp"); SetDocExampleParameterValue("instat", "meanVar.xml"); SetDocExampleParameterValue("model", "svmModel.svm"); SetDocExampleParameterValue("out", "vectorDataLabeledVector.shp"); SetDocExampleParameterValue("feat", "perimeter area width"); SetDocExampleParameterValue("cfield", "predicted"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { if ( HasValue("in") ) { std::string shapefile = GetParameterString("in"); otb::ogr::DataSource::Pointer ogrDS; OGRSpatialReference oSRS(""); std::vector<std::string> options; ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read); otb::ogr::Layer layer = ogrDS->GetLayer(0); OGRFeatureDefn &layerDefn = layer.GetLayerDefn(); ClearChoices("feat"); for(int iField=0; iField< layerDefn.GetFieldCount(); iField++) { std::string item = layerDefn.GetFieldDefn(iField)->GetNameRef(); std::string key(item); key.erase( std::remove_if(key.begin(),key.end(),IsNotAlphaNum), key.end()); std::transform(key.begin(), key.end(), key.begin(), tolower); OGRFieldType fieldType = layerDefn.GetFieldDefn(iField)->GetType(); if(fieldType == OFTInteger || ogr::version_proxy::IsOFTInteger64(fieldType) || fieldType == OFTReal) { std::string tmpKey="feat."+key; AddChoice(tmpKey,item); } } } } void DoExecute() ITK_OVERRIDE { clock_t tic = clock(); std::string shapefile = GetParameterString("in"); otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read); otb::ogr::Layer layer = source->GetLayer(0); ListSampleType::Pointer input = ListSampleType::New(); const int nbFeatures = GetSelectedItems("feat").size(); input->SetMeasurementVectorSize(nbFeatures); otb::ogr::Layer::const_iterator it = layer.cbegin(); otb::ogr::Layer::const_iterator itEnd = layer.cend(); for( ; it!=itEnd ; ++it) { MeasurementType mv; mv.SetSize(nbFeatures); for(int idx=0; idx < nbFeatures; ++idx) { mv[idx] = (*it)[GetSelectedItems("feat")[idx]].GetValue<double>(); } input->PushBack(mv); } // Statistics for shift/scale MeasurementType meanMeasurementVector; MeasurementType stddevMeasurementVector; if (HasValue("instat") && IsParameterEnabled("instat")) { StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); std::string XMLfile = GetParameterString("instat"); statisticsReader->SetFileName(XMLfile); meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); } else { meanMeasurementVector.SetSize(nbFeatures); meanMeasurementVector.Fill(0.); stddevMeasurementVector.SetSize(nbFeatures); stddevMeasurementVector.Fill(1.); } ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New(); trainingShiftScaleFilter->SetInput(input); trainingShiftScaleFilter->SetShifts(meanMeasurementVector); trainingShiftScaleFilter->SetScales(stddevMeasurementVector); trainingShiftScaleFilter->Update(); otbAppLogINFO("mean used: " << meanMeasurementVector); otbAppLogINFO("standard deviation used: " << stddevMeasurementVector); otbAppLogINFO("Loading model"); m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"), MachineLearningModelFactoryType::ReadMode); if (m_Model.IsNull()) { otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type"); } m_Model->Load(GetParameterString("model")); otbAppLogINFO("Model loaded"); ListSampleType::Pointer listSample = trainingShiftScaleFilter->GetOutput(); ConfidenceListSampleType::Pointer quality; bool computeConfidenceMap(IsParameterEnabled("confmap") && m_Model->HasConfidenceIndex() && !m_Model->GetRegressionMode()); if (!m_Model->HasConfidenceIndex() && IsParameterEnabled("confmap")) { otbAppLogWARNING("Confidence map requested but the classifier doesn't support it!"); } LabelListSampleType::Pointer target; if (computeConfidenceMap) { quality = ConfidenceListSampleType::New(); target = m_Model->PredictBatch(listSample, quality); } else { target = m_Model->PredictBatch(listSample); } ogr::DataSource::Pointer output; ogr::DataSource::Pointer buffer = ogr::DataSource::New(); bool updateMode = false; if (IsParameterEnabled("out") && HasValue("out")) { // Create new OGRDataSource output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Overwrite); otb::ogr::Layer newLayer = output->CreateLayer( GetParameterString("out"), const_cast<OGRSpatialReference*>(layer.GetSpatialRef()), layer.GetGeomType()); // Copy existing fields OGRFeatureDefn &inLayerDefn = layer.GetLayerDefn(); for (int k=0 ; k<inLayerDefn.GetFieldCount() ; k++) { OGRFieldDefn fieldDefn(inLayerDefn.GetFieldDefn(k)); newLayer.CreateField(fieldDefn); } } else { // Update mode updateMode = true; otbAppLogINFO("Update input vector data."); // fill temporary buffer for the transfer otb::ogr::Layer inputLayer = layer; layer = buffer->CopyLayer(inputLayer, std::string("Buffer")); // close input data source source->Clear(); // Re-open input data source in update mode output = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Update_LayerUpdate); } otb::ogr::Layer outLayer = output->GetLayer(0); OGRErr errStart = outLayer.ogr().StartTransaction(); if (errStart != OGRERR_NONE) { itkExceptionMacro(<< "Unable to start transaction for OGR layer " << outLayer.ogr().GetName() << "."); } // Add the field of prediction in the output layer if field not exist OGRFeatureDefn &layerDefn = layer.GetLayerDefn(); int idx = layerDefn.GetFieldIndex(GetParameterString("cfield").c_str()); if (idx >= 0) { if (layerDefn.GetFieldDefn(idx)->GetType() != OFTInteger) itkExceptionMacro("Field name "<< GetParameterString("cfield") << " already exists with a different type!"); } else { OGRFieldDefn predictedField(GetParameterString("cfield").c_str(), OFTInteger); ogr::FieldDefn predictedFieldDef(predictedField); outLayer.CreateField(predictedFieldDef); } // Add confidence field in the output layer std::string confFieldName("confidence"); if (computeConfidenceMap) { idx = layerDefn.GetFieldIndex(confFieldName.c_str()); if (idx >= 0) { if (layerDefn.GetFieldDefn(idx)->GetType() != OFTReal) itkExceptionMacro("Field name "<< confFieldName << " already exists with a different type!"); } else { OGRFieldDefn confidenceField(confFieldName.c_str(), OFTReal); confidenceField.SetWidth(confidenceField.GetWidth()); confidenceField.SetPrecision(confidenceField.GetPrecision()); ogr::FieldDefn confFieldDefn(confidenceField); outLayer.CreateField(confFieldDefn); } } // Fill output layer unsigned int count=0; std::string classfieldname = GetParameterString("cfield"); it = layer.cbegin(); itEnd = layer.cend(); for( ; it!=itEnd ; ++it, ++count) { ogr::Feature dstFeature(outLayer.GetLayerDefn()); dstFeature.SetFrom( *it , TRUE); dstFeature.SetFID(it->GetFID()); dstFeature[classfieldname].SetValue<int>(target->GetMeasurementVector(count)[0]); if (computeConfidenceMap) dstFeature[confFieldName].SetValue<double>(quality->GetMeasurementVector(count)[0]); if (updateMode) { outLayer.SetFeature(dstFeature); } else { outLayer.CreateFeature(dstFeature); } } if(outLayer.ogr().TestCapability("Transactions")) { const OGRErr errCommitX = outLayer.ogr().CommitTransaction(); if (errCommitX != OGRERR_NONE) { itkExceptionMacro(<< "Unable to commit transaction for OGR layer " << outLayer.ogr().GetName() << "."); } } output->SyncToDisk(); clock_t toc = clock(); otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds."); } ModelPointerType m_Model; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::VectorClassifier) <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/tab_contents/tab_contents_drag_win.h" #include <windows.h> #include <string> #include "base/file_path.h" #include "base/message_loop.h" #include "base/task.h" #include "base/thread.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_drag_data.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/download/download_util.h" #include "chrome/browser/download/drag_download_file.h" #include "chrome/browser/download/drag_download_util.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/web_drag_source_win.h" #include "chrome/browser/tab_contents/web_drag_utils_win.h" #include "chrome/browser/tab_contents/web_drop_target_win.h" #include "chrome/browser/views/tab_contents/tab_contents_view_win.h" #include "chrome/common/url_constants.h" #include "net/base/net_util.h" #include "views/drag_utils.h" #include "webkit/glue/webdropdata.h" using WebKit::WebDragOperationsMask; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationLink; using WebKit::WebDragOperationMove; namespace { HHOOK msg_hook = NULL; DWORD drag_out_thread_id = 0; bool mouse_up_received = false; LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) { if (code == base::MessagePumpForUI::kMessageFilterCode && !mouse_up_received) { MSG* msg = reinterpret_cast<MSG*>(lparam); // We do not care about WM_SYSKEYDOWN and WM_SYSKEYUP because when ALT key // is pressed down on drag-and-drop, it means to create a link. if (msg->message == WM_MOUSEMOVE || msg->message == WM_LBUTTONUP || msg->message == WM_KEYDOWN || msg->message == WM_KEYUP) { // Forward the message from the UI thread to the drag-and-drop thread. PostThreadMessage(drag_out_thread_id, msg->message, msg->wParam, msg->lParam); // If the left button is up, we do not need to forward the message any // more. if (msg->message == WM_LBUTTONUP || !(GetKeyState(VK_LBUTTON) & 0x8000)) mouse_up_received = true; return TRUE; } } return CallNextHookEx(msg_hook, code, wparam, lparam); } } // namespace class DragDropThread : public base::Thread { public: explicit DragDropThread(TabContentsDragWin* drag_handler) : base::Thread("Chrome_DragDropThread"), drag_handler_(drag_handler) { } virtual ~DragDropThread() { Thread::Stop(); } protected: // base::Thread implementations: virtual void Init() { int ole_result = OleInitialize(NULL); DCHECK(ole_result == S_OK); } virtual void CleanUp() { OleUninitialize(); } private: // Hold a reference count to TabContentsDragWin to make sure that it is always // alive in the thread lifetime. scoped_refptr<TabContentsDragWin> drag_handler_; DISALLOW_COPY_AND_ASSIGN(DragDropThread); }; TabContentsDragWin::TabContentsDragWin(TabContentsViewWin* view) : drag_drop_thread_id_(0), view_(view), drag_ended_(false), old_drop_target_suspended_state_(false) { } TabContentsDragWin::~TabContentsDragWin() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!drag_drop_thread_.get()); } void TabContentsDragWin::StartDragging(const WebDropData& drop_data, WebDragOperationsMask ops, const SkBitmap& image, const gfx::Point& image_offset) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); drag_source_ = new WebDragSource(view_->GetNativeView(), view_->tab_contents()); const GURL& page_url = view_->tab_contents()->GetURL(); const std::string& page_encoding = view_->tab_contents()->encoding(); // If it is not drag-out, do the drag-and-drop in the current UI thread. if (drop_data.download_metadata.empty()) { DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset); EndDragging(false); return; } // We do not want to drag and drop the download to itself. old_drop_target_suspended_state_ = view_->drop_target()->suspended(); view_->drop_target()->set_suspended(true); // Start a background thread to do the drag-and-drop. DCHECK(!drag_drop_thread_.get()); drag_drop_thread_.reset(new DragDropThread(this)); base::Thread::Options options; options.message_loop_type = MessageLoop::TYPE_UI; if (drag_drop_thread_->StartWithOptions(options)) { drag_drop_thread_->message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::StartBackgroundDragging, drop_data, ops, page_url, page_encoding, image, image_offset)); } // Install a hook procedure to monitor the messages so that we can forward // the appropriate ones to the background thread. drag_out_thread_id = drag_drop_thread_->thread_id(); mouse_up_received = false; DCHECK(!msg_hook); msg_hook = SetWindowsHookEx(WH_MSGFILTER, MsgFilterProc, NULL, GetCurrentThreadId()); // Attach the input state of the background thread to the UI thread so that // SetCursor can work from the background thread. AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), TRUE); } void TabContentsDragWin::StartBackgroundDragging( const WebDropData& drop_data, WebDragOperationsMask ops, const GURL& page_url, const std::string& page_encoding, const SkBitmap& image, const gfx::Point& image_offset) { drag_drop_thread_id_ = PlatformThread::CurrentId(); DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true)); } void TabContentsDragWin::PrepareDragForDownload( const WebDropData& drop_data, OSExchangeData* data, const GURL& page_url, const std::string& page_encoding) { // Parse the download metadata. string16 mime_type; FilePath file_name; GURL download_url; if (!drag_download_util::ParseDownloadMetadata(drop_data.download_metadata, &mime_type, &file_name, &download_url)) return; // Generate the download filename. std::string content_disposition = "attachment; filename=" + UTF16ToUTF8(file_name.value()); FilePath generated_file_name; download_util::GenerateFileName(download_url, content_disposition, std::string(), UTF16ToUTF8(mime_type), &generated_file_name); // Provide the data as file (CF_HDROP). A temporary download file with the // Zone.Identifier ADS (Alternate Data Stream) attached will be created. linked_ptr<net::FileStream> empty_file_stream; scoped_refptr<DragDownloadFile> download_file = new DragDownloadFile(generated_file_name, empty_file_stream, download_url, page_url, page_encoding, view_->tab_contents()); OSExchangeData::DownloadFileInfo file_download(FilePath(), download_file.get()); data->SetDownloadFileInfo(file_download); // Enable asynchronous operation. OSExchangeDataProviderWin::GetIAsyncOperation(*data)->SetAsyncMode(TRUE); } void TabContentsDragWin::PrepareDragForFileContents( const WebDropData& drop_data, OSExchangeData* data) { // Images without ALT text will only have a file extension so we need to // synthesize one from the provided extension and URL. FilePath file_name(drop_data.file_description_filename); file_name = file_name.BaseName().RemoveExtension(); if (file_name.value().empty()) { // Retrieve the name from the URL. file_name = net::GetSuggestedFilename(drop_data.url, "", "", FilePath()); if (file_name.value().size() + drop_data.file_extension.size() + 1 > MAX_PATH) { file_name = FilePath(file_name.value().substr( 0, MAX_PATH - drop_data.file_extension.size() - 2)); } } file_name = file_name.ReplaceExtension(drop_data.file_extension); data->SetFileContents(file_name.value(), drop_data.file_contents); } void TabContentsDragWin::PrepareDragForUrl(const WebDropData& drop_data, OSExchangeData* data) { if (drop_data.url.SchemeIs(chrome::kJavaScriptScheme)) { // We don't want to allow javascript URLs to be dragged to the desktop, // but we do want to allow them to be added to the bookmarks bar // (bookmarklets). So we create a fake bookmark entry (BookmarkDragData // object) which explorer.exe cannot handle, and write the entry to data. BookmarkDragData::Element bm_elt; bm_elt.is_url = true; bm_elt.url = drop_data.url; bm_elt.title = drop_data.url_title; BookmarkDragData bm_drag_data; bm_drag_data.elements.push_back(bm_elt); // Pass in NULL as the profile so that the bookmark always adds the url // rather than trying to move an existing url. bm_drag_data.Write(NULL, data); } else { data->SetURL(drop_data.url, drop_data.url_title); } } void TabContentsDragWin::DoDragging(const WebDropData& drop_data, WebDragOperationsMask ops, const GURL& page_url, const std::string& page_encoding, const SkBitmap& image, const gfx::Point& image_offset) { OSExchangeData data; if (!drop_data.download_metadata.empty()) { PrepareDragForDownload(drop_data, &data, page_url, page_encoding); // Set the observer. OSExchangeDataProviderWin::GetDataObjectImpl(data)->set_observer(this); } else { // We set the file contents before the URL because the URL also sets file // contents (to a .URL shortcut). We want to prefer file content data over // a shortcut so we add it first. if (!drop_data.file_contents.empty()) PrepareDragForFileContents(drop_data, &data); if (!drop_data.text_html.empty()) data.SetHtml(drop_data.text_html, drop_data.html_base_url); if (drop_data.url.is_valid()) PrepareDragForUrl(drop_data, &data); if (!drop_data.plain_text.empty()) data.SetString(drop_data.plain_text); } // Set drag image. if (!image.isNull()) { drag_utils::SetDragImageOnDataObject( image, gfx::Size(image.width(), image.height()), image_offset, &data); } // We need to enable recursive tasks on the message loop so we can get // updates while in the system DoDragDrop loop. bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); DWORD effect; DoDragDrop(OSExchangeDataProviderWin::GetIDataObject(data), drag_source_, web_drag_utils_win::WebDragOpMaskToWinDragOpMask(ops), &effect); MessageLoop::current()->SetNestableTasksAllowed(old_state); // This works because WebDragSource::OnDragSourceDrop uses PostTask to // dispatch the actual event. drag_source_->set_effect(effect); } void TabContentsDragWin::EndDragging(bool restore_suspended_state) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (drag_ended_) return; drag_ended_ = true; if (restore_suspended_state) view_->drop_target()->set_suspended(old_drop_target_suspended_state_); if (msg_hook) { AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), FALSE); UnhookWindowsHookEx(msg_hook); msg_hook = NULL; } view_->EndDragging(); } void TabContentsDragWin::CancelDrag() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); drag_source_->CancelDrag(); } void TabContentsDragWin::CloseThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); drag_drop_thread_.reset(); } void TabContentsDragWin::OnWaitForData() { DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId()); // When the left button is release and we start to wait for the data, end // the dragging before DoDragDrop returns. This makes the page leave the drag // mode so that it can start to process the normal input events. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true)); } void TabContentsDragWin::OnDataObjectDisposed() { DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId()); // The drag-and-drop thread is only closed after OLE is done with // DataObjectImpl. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::CloseThread)); } <commit_msg>Fix drag data population on Windows so URL data doesn't take precedence over text.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/tab_contents/tab_contents_drag_win.h" #include <windows.h> #include <string> #include "base/file_path.h" #include "base/message_loop.h" #include "base/task.h" #include "base/thread.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_drag_data.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/download/download_util.h" #include "chrome/browser/download/drag_download_file.h" #include "chrome/browser/download/drag_download_util.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/web_drag_source_win.h" #include "chrome/browser/tab_contents/web_drag_utils_win.h" #include "chrome/browser/tab_contents/web_drop_target_win.h" #include "chrome/browser/views/tab_contents/tab_contents_view_win.h" #include "chrome/common/url_constants.h" #include "net/base/net_util.h" #include "views/drag_utils.h" #include "webkit/glue/webdropdata.h" using WebKit::WebDragOperationsMask; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationLink; using WebKit::WebDragOperationMove; namespace { HHOOK msg_hook = NULL; DWORD drag_out_thread_id = 0; bool mouse_up_received = false; LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) { if (code == base::MessagePumpForUI::kMessageFilterCode && !mouse_up_received) { MSG* msg = reinterpret_cast<MSG*>(lparam); // We do not care about WM_SYSKEYDOWN and WM_SYSKEYUP because when ALT key // is pressed down on drag-and-drop, it means to create a link. if (msg->message == WM_MOUSEMOVE || msg->message == WM_LBUTTONUP || msg->message == WM_KEYDOWN || msg->message == WM_KEYUP) { // Forward the message from the UI thread to the drag-and-drop thread. PostThreadMessage(drag_out_thread_id, msg->message, msg->wParam, msg->lParam); // If the left button is up, we do not need to forward the message any // more. if (msg->message == WM_LBUTTONUP || !(GetKeyState(VK_LBUTTON) & 0x8000)) mouse_up_received = true; return TRUE; } } return CallNextHookEx(msg_hook, code, wparam, lparam); } } // namespace class DragDropThread : public base::Thread { public: explicit DragDropThread(TabContentsDragWin* drag_handler) : base::Thread("Chrome_DragDropThread"), drag_handler_(drag_handler) { } virtual ~DragDropThread() { Thread::Stop(); } protected: // base::Thread implementations: virtual void Init() { int ole_result = OleInitialize(NULL); DCHECK(ole_result == S_OK); } virtual void CleanUp() { OleUninitialize(); } private: // Hold a reference count to TabContentsDragWin to make sure that it is always // alive in the thread lifetime. scoped_refptr<TabContentsDragWin> drag_handler_; DISALLOW_COPY_AND_ASSIGN(DragDropThread); }; TabContentsDragWin::TabContentsDragWin(TabContentsViewWin* view) : drag_drop_thread_id_(0), view_(view), drag_ended_(false), old_drop_target_suspended_state_(false) { } TabContentsDragWin::~TabContentsDragWin() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!drag_drop_thread_.get()); } void TabContentsDragWin::StartDragging(const WebDropData& drop_data, WebDragOperationsMask ops, const SkBitmap& image, const gfx::Point& image_offset) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); drag_source_ = new WebDragSource(view_->GetNativeView(), view_->tab_contents()); const GURL& page_url = view_->tab_contents()->GetURL(); const std::string& page_encoding = view_->tab_contents()->encoding(); // If it is not drag-out, do the drag-and-drop in the current UI thread. if (drop_data.download_metadata.empty()) { DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset); EndDragging(false); return; } // We do not want to drag and drop the download to itself. old_drop_target_suspended_state_ = view_->drop_target()->suspended(); view_->drop_target()->set_suspended(true); // Start a background thread to do the drag-and-drop. DCHECK(!drag_drop_thread_.get()); drag_drop_thread_.reset(new DragDropThread(this)); base::Thread::Options options; options.message_loop_type = MessageLoop::TYPE_UI; if (drag_drop_thread_->StartWithOptions(options)) { drag_drop_thread_->message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::StartBackgroundDragging, drop_data, ops, page_url, page_encoding, image, image_offset)); } // Install a hook procedure to monitor the messages so that we can forward // the appropriate ones to the background thread. drag_out_thread_id = drag_drop_thread_->thread_id(); mouse_up_received = false; DCHECK(!msg_hook); msg_hook = SetWindowsHookEx(WH_MSGFILTER, MsgFilterProc, NULL, GetCurrentThreadId()); // Attach the input state of the background thread to the UI thread so that // SetCursor can work from the background thread. AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), TRUE); } void TabContentsDragWin::StartBackgroundDragging( const WebDropData& drop_data, WebDragOperationsMask ops, const GURL& page_url, const std::string& page_encoding, const SkBitmap& image, const gfx::Point& image_offset) { drag_drop_thread_id_ = PlatformThread::CurrentId(); DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true)); } void TabContentsDragWin::PrepareDragForDownload( const WebDropData& drop_data, OSExchangeData* data, const GURL& page_url, const std::string& page_encoding) { // Parse the download metadata. string16 mime_type; FilePath file_name; GURL download_url; if (!drag_download_util::ParseDownloadMetadata(drop_data.download_metadata, &mime_type, &file_name, &download_url)) return; // Generate the download filename. std::string content_disposition = "attachment; filename=" + UTF16ToUTF8(file_name.value()); FilePath generated_file_name; download_util::GenerateFileName(download_url, content_disposition, std::string(), UTF16ToUTF8(mime_type), &generated_file_name); // Provide the data as file (CF_HDROP). A temporary download file with the // Zone.Identifier ADS (Alternate Data Stream) attached will be created. linked_ptr<net::FileStream> empty_file_stream; scoped_refptr<DragDownloadFile> download_file = new DragDownloadFile(generated_file_name, empty_file_stream, download_url, page_url, page_encoding, view_->tab_contents()); OSExchangeData::DownloadFileInfo file_download(FilePath(), download_file.get()); data->SetDownloadFileInfo(file_download); // Enable asynchronous operation. OSExchangeDataProviderWin::GetIAsyncOperation(*data)->SetAsyncMode(TRUE); } void TabContentsDragWin::PrepareDragForFileContents( const WebDropData& drop_data, OSExchangeData* data) { // Images without ALT text will only have a file extension so we need to // synthesize one from the provided extension and URL. FilePath file_name(drop_data.file_description_filename); file_name = file_name.BaseName().RemoveExtension(); if (file_name.value().empty()) { // Retrieve the name from the URL. file_name = net::GetSuggestedFilename(drop_data.url, "", "", FilePath()); if (file_name.value().size() + drop_data.file_extension.size() + 1 > MAX_PATH) { file_name = FilePath(file_name.value().substr( 0, MAX_PATH - drop_data.file_extension.size() - 2)); } } file_name = file_name.ReplaceExtension(drop_data.file_extension); data->SetFileContents(file_name.value(), drop_data.file_contents); } void TabContentsDragWin::PrepareDragForUrl(const WebDropData& drop_data, OSExchangeData* data) { if (drop_data.url.SchemeIs(chrome::kJavaScriptScheme)) { // We don't want to allow javascript URLs to be dragged to the desktop, // but we do want to allow them to be added to the bookmarks bar // (bookmarklets). So we create a fake bookmark entry (BookmarkDragData // object) which explorer.exe cannot handle, and write the entry to data. BookmarkDragData::Element bm_elt; bm_elt.is_url = true; bm_elt.url = drop_data.url; bm_elt.title = drop_data.url_title; BookmarkDragData bm_drag_data; bm_drag_data.elements.push_back(bm_elt); // Pass in NULL as the profile so that the bookmark always adds the url // rather than trying to move an existing url. bm_drag_data.Write(NULL, data); } else { data->SetURL(drop_data.url, drop_data.url_title); } } void TabContentsDragWin::DoDragging(const WebDropData& drop_data, WebDragOperationsMask ops, const GURL& page_url, const std::string& page_encoding, const SkBitmap& image, const gfx::Point& image_offset) { OSExchangeData data; if (!drop_data.download_metadata.empty()) { PrepareDragForDownload(drop_data, &data, page_url, page_encoding); // Set the observer. OSExchangeDataProviderWin::GetDataObjectImpl(data)->set_observer(this); } else { // We set the file contents before the URL because the URL also sets file // contents (to a .URL shortcut). We want to prefer file content data over // a shortcut so we add it first. if (!drop_data.file_contents.empty()) PrepareDragForFileContents(drop_data, &data); if (!drop_data.text_html.empty()) data.SetHtml(drop_data.text_html, drop_data.html_base_url); // We set the text contents before the URL because the URL also sets text // content. if (!drop_data.plain_text.empty()) data.SetString(drop_data.plain_text); if (drop_data.url.is_valid()) PrepareDragForUrl(drop_data, &data); } // Set drag image. if (!image.isNull()) { drag_utils::SetDragImageOnDataObject( image, gfx::Size(image.width(), image.height()), image_offset, &data); } // We need to enable recursive tasks on the message loop so we can get // updates while in the system DoDragDrop loop. bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); DWORD effect; DoDragDrop(OSExchangeDataProviderWin::GetIDataObject(data), drag_source_, web_drag_utils_win::WebDragOpMaskToWinDragOpMask(ops), &effect); MessageLoop::current()->SetNestableTasksAllowed(old_state); // This works because WebDragSource::OnDragSourceDrop uses PostTask to // dispatch the actual event. drag_source_->set_effect(effect); } void TabContentsDragWin::EndDragging(bool restore_suspended_state) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (drag_ended_) return; drag_ended_ = true; if (restore_suspended_state) view_->drop_target()->set_suspended(old_drop_target_suspended_state_); if (msg_hook) { AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), FALSE); UnhookWindowsHookEx(msg_hook); msg_hook = NULL; } view_->EndDragging(); } void TabContentsDragWin::CancelDrag() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); drag_source_->CancelDrag(); } void TabContentsDragWin::CloseThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); drag_drop_thread_.reset(); } void TabContentsDragWin::OnWaitForData() { DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId()); // When the left button is release and we start to wait for the data, end // the dragging before DoDragDrop returns. This makes the page leave the drag // mode so that it can start to process the normal input events. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true)); } void TabContentsDragWin::OnDataObjectDisposed() { DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId()); // The drag-and-drop thread is only closed after OLE is done with // DataObjectImpl. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &TabContentsDragWin::CloseThread)); } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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 <iostream> # include "gtest/gtest.h" # include "test_utils.h" # include <dsn/tool/simulator.h> # include <dsn/tool/nativerun.h> # include <dsn/tool/fastrun.h> # include <dsn/toollet/tracer.h> # include <dsn/toollet/profiler.h> # include <dsn/toollet/fault_injector.h> # include <dsn/tool/providers.common.h> # include <dsn/tool/providers.hpc.h> # include <dsn/tool/nfs_node_simple.h> void module_init() { // register all providers dsn::tools::register_common_providers(); dsn::tools::register_hpc_providers(); dsn::tools::register_component_provider<::dsn::service::nfs_node_simple>("dsn::service::nfs_node_simple"); //dsn::tools::register_component_provider<dsn::thrift_binary_message_parser>("thrift"); // register all possible tools and toollets dsn::tools::register_tool<dsn::tools::nativerun>("nativerun"); dsn::tools::register_tool<dsn::tools::fastrun>("fastrun"); dsn::tools::register_tool<dsn::tools::simulator>("simulator"); dsn::tools::register_toollet<dsn::tools::tracer>("tracer"); dsn::tools::register_toollet<dsn::tools::profiler>("profiler"); dsn::tools::register_toollet<dsn::tools::fault_injector>("fault_injector"); } int g_test_count = 0; dsn_app_t g_app = nullptr; GTEST_API_ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); // register all tools module_init(); // register all possible services dsn::register_app<test_client>("test"); // specify what services and tools will run in config file, then run dsn_run(argc, argv, false); // run in-rDSN tests while (g_test_count == 0) { std::this_thread::sleep_for(std::chrono::seconds(1)); } // run out-rDSN tests std::cout << "=========================================================== " << std::endl; std::cout << "================== run in non-rDSN threads ================ " << std::endl; std::cout << "=========================================================== " << std::endl; // set host app for the non-in-rDSN-thread api calls g_app = dsn_query_app("client", 1); exec_tests(); // exit without any destruction dsn_terminate(); return 0; } <commit_msg>add test case for invoking service API from non-rDSN threads<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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 <iostream> # include "gtest/gtest.h" # include "test_utils.h" # include <dsn/tool/simulator.h> # include <dsn/tool/nativerun.h> # include <dsn/tool/fastrun.h> # include <dsn/toollet/tracer.h> # include <dsn/toollet/profiler.h> # include <dsn/toollet/fault_injector.h> # include <dsn/tool/providers.common.h> # include <dsn/tool/providers.hpc.h> # include <dsn/tool/nfs_node_simple.h> void module_init() { // register all providers dsn::tools::register_common_providers(); dsn::tools::register_hpc_providers(); dsn::tools::register_component_provider<::dsn::service::nfs_node_simple>("dsn::service::nfs_node_simple"); //dsn::tools::register_component_provider<dsn::thrift_binary_message_parser>("thrift"); // register all possible tools and toollets dsn::tools::register_tool<dsn::tools::nativerun>("nativerun"); dsn::tools::register_tool<dsn::tools::fastrun>("fastrun"); dsn::tools::register_tool<dsn::tools::simulator>("simulator"); dsn::tools::register_toollet<dsn::tools::tracer>("tracer"); dsn::tools::register_toollet<dsn::tools::profiler>("profiler"); dsn::tools::register_toollet<dsn::tools::fault_injector>("fault_injector"); } int g_test_count = 0; dsn_app_t g_app = nullptr; GTEST_API_ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); // register all tools module_init(); // register all possible services dsn::register_app<test_client>("test"); // specify what services and tools will run in config file, then run dsn_run(argc, argv, false); // run in-rDSN tests while (g_test_count == 0) { std::this_thread::sleep_for(std::chrono::seconds(1)); } // set host app for the non-in-rDSN-thread api calls g_app = dsn_query_app("client", 1); // run out-rDSN tests in Main thread std::cout << "=========================================================== " << std::endl; std::cout << "================== run in Main thread ===================== " << std::endl; std::cout << "=========================================================== " << std::endl; exec_tests(); // run out-rDSN tests in other threads std::cout << "=========================================================== " << std::endl; std::cout << "================== run in non-rDSN threads ================ " << std::endl; std::cout << "=========================================================== " << std::endl; std::thread t([](){ exec_tests(); }); t.join(); // exit without any destruction dsn_terminate(); return 0; } <|endoftext|>
<commit_before>// 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 "content/browser/download/save_file_resource_handler.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_number_conversions.h" #include "content/browser/browser_thread.h" #include "content/browser/download/save_file_manager.h" #include "net/base/io_buffer.h" #include "net/url_request/url_request_status.h" SaveFileResourceHandler::SaveFileResourceHandler(int render_process_host_id, int render_view_id, const GURL& url, SaveFileManager* manager) : save_id_(-1), render_process_id_(render_process_host_id), render_view_id_(render_view_id), url_(url), content_length_(0), save_manager_(manager) { } bool SaveFileResourceHandler::OnUploadProgress(int request_id, uint64 position, uint64 size) { return true; } bool SaveFileResourceHandler::OnRequestRedirected(int request_id, const GURL& url, ResourceResponse* response, bool* defer) { final_url_ = url; return true; } bool SaveFileResourceHandler::OnResponseStarted(int request_id, ResourceResponse* response) { save_id_ = save_manager_->GetNextId(); // |save_manager_| consumes (deletes): SaveFileCreateInfo* info = new SaveFileCreateInfo; info->url = url_; info->final_url = final_url_; info->total_bytes = content_length_; info->save_id = save_id_; info->render_process_id = render_process_id_; info->render_view_id = render_view_id_; info->request_id = request_id; info->content_disposition = content_disposition_; info->save_source = SaveFileCreateInfo::SAVE_FILE_FROM_NET; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(save_manager_, &SaveFileManager::StartSave, info)); return true; } bool SaveFileResourceHandler::OnWillStart(int request_id, const GURL& url, bool* defer) { return true; } bool SaveFileResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, int min_size) { DCHECK(buf && buf_size); if (!read_buffer_) { *buf_size = min_size < 0 ? kReadBufSize : min_size; read_buffer_ = new net::IOBuffer(*buf_size); } *buf = read_buffer_.get(); return true; } bool SaveFileResourceHandler::OnReadCompleted(int request_id, int* bytes_read) { DCHECK(read_buffer_); // We are passing ownership of this buffer to the save file manager. scoped_refptr<net::IOBuffer> buffer; read_buffer_.swap(buffer); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(save_manager_, &SaveFileManager::UpdateSaveProgress, save_id_, buffer, *bytes_read)); return true; } bool SaveFileResourceHandler::OnResponseCompleted( int request_id, const net::URLRequestStatus& status, const std::string& security_info) { BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(save_manager_, &SaveFileManager::SaveFinished, save_id_, url_, render_process_id_, status.is_success() && !status.is_io_pending())); read_buffer_ = NULL; return true; } void SaveFileResourceHandler::OnRequestClosed() { } void SaveFileResourceHandler::set_content_length( const std::string& content_length) { base::StringToInt64(content_length, &content_length_); } SaveFileResourceHandler::~SaveFileResourceHandler() {} <commit_msg>Replace NewRunnableFunction with Callback in SaveFileResourceHandler.<commit_after>// 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 "content/browser/download/save_file_resource_handler.h" #include "base/bind.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_number_conversions.h" #include "content/browser/browser_thread.h" #include "content/browser/download/save_file_manager.h" #include "net/base/io_buffer.h" #include "net/url_request/url_request_status.h" SaveFileResourceHandler::SaveFileResourceHandler(int render_process_host_id, int render_view_id, const GURL& url, SaveFileManager* manager) : save_id_(-1), render_process_id_(render_process_host_id), render_view_id_(render_view_id), url_(url), content_length_(0), save_manager_(manager) { } bool SaveFileResourceHandler::OnUploadProgress(int request_id, uint64 position, uint64 size) { return true; } bool SaveFileResourceHandler::OnRequestRedirected(int request_id, const GURL& url, ResourceResponse* response, bool* defer) { final_url_ = url; return true; } bool SaveFileResourceHandler::OnResponseStarted(int request_id, ResourceResponse* response) { save_id_ = save_manager_->GetNextId(); // |save_manager_| consumes (deletes): SaveFileCreateInfo* info = new SaveFileCreateInfo; info->url = url_; info->final_url = final_url_; info->total_bytes = content_length_; info->save_id = save_id_; info->render_process_id = render_process_id_; info->render_view_id = render_view_id_; info->request_id = request_id; info->content_disposition = content_disposition_; info->save_source = SaveFileCreateInfo::SAVE_FILE_FROM_NET; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&SaveFileManager::StartSave, save_manager_, info)); return true; } bool SaveFileResourceHandler::OnWillStart(int request_id, const GURL& url, bool* defer) { return true; } bool SaveFileResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, int min_size) { DCHECK(buf && buf_size); if (!read_buffer_) { *buf_size = min_size < 0 ? kReadBufSize : min_size; read_buffer_ = new net::IOBuffer(*buf_size); } *buf = read_buffer_.get(); return true; } bool SaveFileResourceHandler::OnReadCompleted(int request_id, int* bytes_read) { DCHECK(read_buffer_); // We are passing ownership of this buffer to the save file manager. scoped_refptr<net::IOBuffer> buffer; read_buffer_.swap(buffer); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&SaveFileManager::UpdateSaveProgress, save_manager_, save_id_, buffer, *bytes_read)); return true; } bool SaveFileResourceHandler::OnResponseCompleted( int request_id, const net::URLRequestStatus& status, const std::string& security_info) { BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&SaveFileManager::SaveFinished, save_manager_, save_id_, url_, render_process_id_, status.is_success() && !status.is_io_pending())); read_buffer_ = NULL; return true; } void SaveFileResourceHandler::OnRequestClosed() { } void SaveFileResourceHandler::set_content_length( const std::string& content_length) { base::StringToInt64(content_length, &content_length_); } SaveFileResourceHandler::~SaveFileResourceHandler() {} <|endoftext|>
<commit_before>#ifndef constants_hpp #define constants_hpp #include <string> using namespace std; const string REGEX_LHS_LEQ_RHS = "(.*)\\s*<=\\s*(.*)"; const string REGEX_LHS_GEQ_RHS = "(.*)\\s*>=\\s*(.*)"; const string REGEX_INIT_FUNCTIONS = "void init_(.*)\\(\\);"; const string REGEX_TRIANGLE_VAR = "(?!sqrt\\b|long_d\\b|t\\b|sum\\b|prod\\b|pow\\b|" "sin\\b|cos\\b|pi\\b)\\b[a-zA-Z]+([0-9]?)+[A-Z]?"; const string REGEX_REMARKABLE_DIST = "[FGHINOK]{2}"; const string REGEX_CYCLIC_SUM = "\\[sum (?!sum)([^\\[\\]]*)\\]"; const string REGEX_CYCLIC_PROD = "\\[prod (?!prod)([^\\[\\]]*)\\]"; const string INDENT = string(12, ' '); const string MEMBER_FUNC_PTR_KEY = "__POINTERS_TO_MEMBER_FUNCTIONS__"; const string TRIANGLE_ELEM_MAP_KEY = "__MAP_OF_TRIANGLE_ELEMENTS_TO_POINTERS__"; const char DELIMITER = '_'; #endif /* constants_hpp */ <commit_msg>Added support for min and max functions.<commit_after>#ifndef constants_hpp #define constants_hpp #include <string> using namespace std; const string REGEX_LHS_LEQ_RHS = "(.*)\\s*<=\\s*(.*)"; const string REGEX_LHS_GEQ_RHS = "(.*)\\s*>=\\s*(.*)"; const string REGEX_INIT_FUNCTIONS = "void init_(.*)\\(\\);"; const string REGEX_TRIANGLE_VAR = "(?!sqrt\\b|long_d\\b|t\\b|" "sum\\b|prod\\b|pow\\b|max\\b|min\\b|" "sin\\b|cos\\b|asin\\b|acos\\b|pi\\b)\\b" "[a-zA-Z]+([0-9]?)+[A-Z]?"; const string REGEX_REMARKABLE_DIST = "[FGHINOK]{2}"; const string REGEX_CYCLIC_SUM = "\\[sum (?!sum)([^\\[\\]]*)\\]"; const string REGEX_CYCLIC_PROD = "\\[prod (?!prod)([^\\[\\]]*)\\]"; const string INDENT = string(12, ' '); const string MEMBER_FUNC_PTR_KEY = "__POINTERS_TO_MEMBER_FUNCTIONS__"; const string TRIANGLE_ELEM_MAP_KEY = "__MAP_OF_TRIANGLE_ELEMENTS_TO_POINTERS__"; const char DELIMITER = '_'; #endif /* constants_hpp */ <|endoftext|>
<commit_before>#ifndef _COTL_TYPE_HPP #define _COTL_TYPE_HPP namespace cotl { class Val { private: long _type; protected: inline Val(long type): _type(type) {}; inline Val(const Val &) = delete; inline void setType(long type) { _type = type; } public: inline long getType() { return _type; } virtual void repl(std::ostream &stream, long level) const; }; template <class T> class NativeVal: public Val { private: T _data; protected: inline NativeVal(long type, T data): Val(type), _data(data) {}; inline void set(T data) { _data = data; } public: inline T get() { return _data; } }; class Atom: public Val { }; class Int: public NativeVal<long> { }; class Str: public NativeVal<std::string> { }; class Arr: public NativeVal<std::map<long, Val *>> { }; class Ptr: public NativeVal<Val *> { }; class Pair: public NativeVal<std::pair<Val *, Val *>> { }; } #endif <commit_msg>add const protection<commit_after>#ifndef _COTL_TYPE_HPP #define _COTL_TYPE_HPP namespace cotl { class Val { private: long _type; protected: inline Val(long type): _type(type) {}; inline Val(const Val &) = delete; inline void setType(long type) { _type = type; } public: inline long getType() const { return _type; } virtual void repl(std::ostream &stream, long level) const; }; template <class T> class NativeVal: public Val { private: T _data; protected: inline NativeVal(long type, T data): Val(type), _data(data) {}; inline void set(T data) { _data = data; } public: inline T get() { return _data; } inline const T getConst() const { return _data; } }; class Atom: public Val { }; class Int: public NativeVal<long> { }; class Str: public NativeVal<std::string> { }; class Arr: public NativeVal<std::map<long, Val *>> { }; class Ptr: public NativeVal<Val *> { }; class Pair: public NativeVal<std::pair<Val *, Val *>> { }; } #endif <|endoftext|>
<commit_before>//======================================================================= // 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 DBN_LAYER_HPP #define DBN_LAYER_HPP namespace dbn { template<typename C, std::size_t visibles, std::size_t hiddens> struct layer { static constexpr const std::size_t num_visible = visibles; static constexpr const std::size_t num_hidden = hiddens; typedef C Conf; }; } //end of dbn namespace #endif<commit_msg>Add assertions<commit_after>//======================================================================= // 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 DBN_LAYER_HPP #define DBN_LAYER_HPP namespace dbn { template<typename C, std::size_t visibles, std::size_t hiddens> struct layer { static constexpr const std::size_t num_visible = visibles; static constexpr const std::size_t num_hidden = hiddens; static_assert(num_visible > 0, "There must be at least 1 visible unit"); static_assert(num_hidden > 0, "There must be at least 1 hidden unit"); typedef C Conf; }; } //end of dbn namespace #endif<|endoftext|>
<commit_before>/* * Copyright © 2014 Mozilla Foundation * * This program is made available under an ISC-style license. See the * accompanying file LICENSE for details. */ #ifndef NOMINMAX #define NOMINMAX #endif // NOMINMAX #include <algorithm> #include <cmath> #include <cassert> #include <cstring> #include <cstddef> #include <cstdio> #include "cubeb_resampler.h" #include "cubeb-speex-resampler.h" #include "cubeb_resampler_internal.h" #include "cubeb_utils.h" int to_speex_quality(cubeb_resampler_quality q) { switch(q) { case CUBEB_RESAMPLER_QUALITY_VOIP: return SPEEX_RESAMPLER_QUALITY_VOIP; case CUBEB_RESAMPLER_QUALITY_DEFAULT: return SPEEX_RESAMPLER_QUALITY_DEFAULT; case CUBEB_RESAMPLER_QUALITY_DESKTOP: return SPEEX_RESAMPLER_QUALITY_DESKTOP; default: assert(false); return 0XFFFFFFFF; } } uint32_t min_buffered_audio_frame(uint32_t sample_rate) { return sample_rate / 20; } template<typename T> passthrough_resampler<T>::passthrough_resampler(cubeb_stream * s, cubeb_data_callback cb, void * ptr, uint32_t input_channels, uint32_t sample_rate) : processor(input_channels) , stream(s) , data_callback(cb) , user_ptr(ptr) , sample_rate(sample_rate) { } template<typename T> long passthrough_resampler<T>::fill(void * input_buffer, long * input_frames_count, void * output_buffer, long output_frames) { if (input_buffer) { assert(input_frames_count); } assert((input_buffer && output_buffer && *input_frames_count + static_cast<int>(samples_to_frames(internal_input_buffer.length())) >= output_frames) || (output_buffer && !input_buffer && (!input_frames_count || *input_frames_count == 0)) || (input_buffer && !output_buffer && output_frames == 0)); if (input_buffer) { if (!output_buffer) { output_frames = *input_frames_count; } internal_input_buffer.push(static_cast<T*>(input_buffer), frames_to_samples(*input_frames_count)); } long rv = data_callback(stream, user_ptr, internal_input_buffer.data(), output_buffer, output_frames); if (input_buffer) { internal_input_buffer.pop(nullptr, frames_to_samples(output_frames)); *input_frames_count = output_frames; drop_audio_if_needed(); } return rv; } template<typename T, typename InputProcessor, typename OutputProcessor> cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::cubeb_resampler_speex(InputProcessor * input_processor, OutputProcessor * output_processor, cubeb_stream * s, cubeb_data_callback cb, void * ptr) : input_processor(input_processor) , output_processor(output_processor) , stream(s) , data_callback(cb) , user_ptr(ptr) { if (input_processor && output_processor) { // Add some delay on the processor that has the lowest delay so that the // streams are synchronized. uint32_t in_latency = input_processor->latency(); uint32_t out_latency = output_processor->latency(); if (in_latency > out_latency) { uint32_t latency_diff = in_latency - out_latency; output_processor->add_latency(latency_diff); } else if (in_latency < out_latency) { uint32_t latency_diff = out_latency - in_latency; input_processor->add_latency(latency_diff); } fill_internal = &cubeb_resampler_speex::fill_internal_duplex; } else if (input_processor) { fill_internal = &cubeb_resampler_speex::fill_internal_input; } else if (output_processor) { fill_internal = &cubeb_resampler_speex::fill_internal_output; } } template<typename T, typename InputProcessor, typename OutputProcessor> cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::~cubeb_resampler_speex() { } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill(void * input_buffer, long * input_frames_count, void * output_buffer, long output_frames_needed) { /* Input and output buffers, typed */ T * in_buffer = reinterpret_cast<T*>(input_buffer); T * out_buffer = reinterpret_cast<T*>(output_buffer); return (this->*fill_internal)(in_buffer, input_frames_count, out_buffer, output_frames_needed); } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill_internal_output(T * input_buffer, long * input_frames_count, T * output_buffer, long output_frames_needed) { assert(!input_buffer && (!input_frames_count || *input_frames_count == 0) && output_buffer && output_frames_needed); if (!draining) { long got = 0; T * out_unprocessed = nullptr; long output_frames_before_processing = 0; /* fill directly the input buffer of the output processor to save a copy */ output_frames_before_processing = output_processor->input_needed_for_output(output_frames_needed); out_unprocessed = output_processor->input_buffer(output_frames_before_processing); got = data_callback(stream, user_ptr, nullptr, out_unprocessed, output_frames_before_processing); if (got < output_frames_before_processing) { draining = true; if (got < 0) { return got; } } output_processor->written(got); } /* Process the output. If not enough frames have been returned from the * callback, drain the processors. */ return output_processor->output(output_buffer, output_frames_needed); } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill_internal_input(T * input_buffer, long * input_frames_count, T * output_buffer, long /*output_frames_needed*/) { assert(input_buffer && input_frames_count && *input_frames_count && !output_buffer); /* The input data, after eventual resampling. This is passed to the callback. */ T * resampled_input = nullptr; uint32_t resampled_frame_count = input_processor->output_for_input(*input_frames_count); /* process the input, and present exactly `output_frames_needed` in the * callback. */ input_processor->input(input_buffer, *input_frames_count); resampled_input = input_processor->output(resampled_frame_count, (size_t*)input_frames_count); long got = data_callback(stream, user_ptr, resampled_input, nullptr, resampled_frame_count); /* Return the number of initial input frames or part of it. * Since output_frames_needed == 0 in input scenario, the only * available number outside resampler is the initial number of frames. */ return (*input_frames_count) * (got / resampled_frame_count); } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill_internal_duplex(T * in_buffer, long * input_frames_count, T * out_buffer, long output_frames_needed) { if (draining) { // discard input and drain any signal remaining in the resampler. return output_processor->output(out_buffer, output_frames_needed); } /* The input data, after eventual resampling. This is passed to the callback. */ T * resampled_input = nullptr; /* The output buffer passed down in the callback, that might be resampled. */ T * out_unprocessed = nullptr; long output_frames_before_processing = 0; /* The number of frames returned from the callback. */ long got = 0; /* We need to determine how much frames to present to the consumer. * - If we have a two way stream, but we're only resampling input, we resample * the input to the number of output frames. * - If we have a two way stream, but we're only resampling the output, we * resize the input buffer of the output resampler to the number of input * frames, and we resample it afterwards. * - If we resample both ways, we resample the input to the number of frames * we would need to pass down to the consumer (before resampling the output), * get the output data, and resample it to the number of frames needed by the * caller. */ output_frames_before_processing = output_processor->input_needed_for_output(output_frames_needed); /* fill directly the input buffer of the output processor to save a copy */ out_unprocessed = output_processor->input_buffer(output_frames_before_processing); if (in_buffer) { /* process the input, and present exactly `output_frames_needed` in the * callback. */ input_processor->input(in_buffer, *input_frames_count); resampled_input = input_processor->output(output_frames_before_processing, (size_t*)input_frames_count); } else { resampled_input = nullptr; } got = data_callback(stream, user_ptr, resampled_input, out_unprocessed, output_frames_before_processing); if (got < output_frames_before_processing) { draining = true; if (got < 0) { return got; } } output_processor->written(got); input_processor->drop_audio_if_needed(); /* Process the output. If not enough frames have been returned from the * callback, drain the processors. */ got = output_processor->output(out_buffer, output_frames_needed); output_processor->drop_audio_if_needed(); return got; } /* Resampler C API */ cubeb_resampler * cubeb_resampler_create(cubeb_stream * stream, cubeb_stream_params * input_params, cubeb_stream_params * output_params, unsigned int target_rate, cubeb_data_callback callback, void * user_ptr, cubeb_resampler_quality quality) { cubeb_sample_format format; assert(input_params || output_params); if (input_params) { format = input_params->format; } else { format = output_params->format; } switch(format) { case CUBEB_SAMPLE_S16NE: return cubeb_resampler_create_internal<short>(stream, input_params, output_params, target_rate, callback, user_ptr, quality); case CUBEB_SAMPLE_FLOAT32NE: return cubeb_resampler_create_internal<float>(stream, input_params, output_params, target_rate, callback, user_ptr, quality); default: assert(false); return nullptr; } } long cubeb_resampler_fill(cubeb_resampler * resampler, void * input_buffer, long * input_frames_count, void * output_buffer, long output_frames_needed) { return resampler->fill(input_buffer, input_frames_count, output_buffer, output_frames_needed); } void cubeb_resampler_destroy(cubeb_resampler * resampler) { delete resampler; } long cubeb_resampler_latency(cubeb_resampler * resampler) { return resampler->latency(); } <commit_msg>Remove c-style cast in cubeb_resampler.cpp (#454)<commit_after>/* * Copyright © 2014 Mozilla Foundation * * This program is made available under an ISC-style license. See the * accompanying file LICENSE for details. */ #ifndef NOMINMAX #define NOMINMAX #endif // NOMINMAX #include <algorithm> #include <cmath> #include <cassert> #include <cstring> #include <cstddef> #include <cstdio> #include "cubeb_resampler.h" #include "cubeb-speex-resampler.h" #include "cubeb_resampler_internal.h" #include "cubeb_utils.h" int to_speex_quality(cubeb_resampler_quality q) { switch(q) { case CUBEB_RESAMPLER_QUALITY_VOIP: return SPEEX_RESAMPLER_QUALITY_VOIP; case CUBEB_RESAMPLER_QUALITY_DEFAULT: return SPEEX_RESAMPLER_QUALITY_DEFAULT; case CUBEB_RESAMPLER_QUALITY_DESKTOP: return SPEEX_RESAMPLER_QUALITY_DESKTOP; default: assert(false); return 0XFFFFFFFF; } } uint32_t min_buffered_audio_frame(uint32_t sample_rate) { return sample_rate / 20; } template<typename T> passthrough_resampler<T>::passthrough_resampler(cubeb_stream * s, cubeb_data_callback cb, void * ptr, uint32_t input_channels, uint32_t sample_rate) : processor(input_channels) , stream(s) , data_callback(cb) , user_ptr(ptr) , sample_rate(sample_rate) { } template<typename T> long passthrough_resampler<T>::fill(void * input_buffer, long * input_frames_count, void * output_buffer, long output_frames) { if (input_buffer) { assert(input_frames_count); } assert((input_buffer && output_buffer && *input_frames_count + static_cast<int>(samples_to_frames(internal_input_buffer.length())) >= output_frames) || (output_buffer && !input_buffer && (!input_frames_count || *input_frames_count == 0)) || (input_buffer && !output_buffer && output_frames == 0)); if (input_buffer) { if (!output_buffer) { output_frames = *input_frames_count; } internal_input_buffer.push(static_cast<T*>(input_buffer), frames_to_samples(*input_frames_count)); } long rv = data_callback(stream, user_ptr, internal_input_buffer.data(), output_buffer, output_frames); if (input_buffer) { internal_input_buffer.pop(nullptr, frames_to_samples(output_frames)); *input_frames_count = output_frames; drop_audio_if_needed(); } return rv; } template<typename T, typename InputProcessor, typename OutputProcessor> cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::cubeb_resampler_speex(InputProcessor * input_processor, OutputProcessor * output_processor, cubeb_stream * s, cubeb_data_callback cb, void * ptr) : input_processor(input_processor) , output_processor(output_processor) , stream(s) , data_callback(cb) , user_ptr(ptr) { if (input_processor && output_processor) { // Add some delay on the processor that has the lowest delay so that the // streams are synchronized. uint32_t in_latency = input_processor->latency(); uint32_t out_latency = output_processor->latency(); if (in_latency > out_latency) { uint32_t latency_diff = in_latency - out_latency; output_processor->add_latency(latency_diff); } else if (in_latency < out_latency) { uint32_t latency_diff = out_latency - in_latency; input_processor->add_latency(latency_diff); } fill_internal = &cubeb_resampler_speex::fill_internal_duplex; } else if (input_processor) { fill_internal = &cubeb_resampler_speex::fill_internal_input; } else if (output_processor) { fill_internal = &cubeb_resampler_speex::fill_internal_output; } } template<typename T, typename InputProcessor, typename OutputProcessor> cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::~cubeb_resampler_speex() { } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill(void * input_buffer, long * input_frames_count, void * output_buffer, long output_frames_needed) { /* Input and output buffers, typed */ T * in_buffer = reinterpret_cast<T*>(input_buffer); T * out_buffer = reinterpret_cast<T*>(output_buffer); return (this->*fill_internal)(in_buffer, input_frames_count, out_buffer, output_frames_needed); } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill_internal_output(T * input_buffer, long * input_frames_count, T * output_buffer, long output_frames_needed) { assert(!input_buffer && (!input_frames_count || *input_frames_count == 0) && output_buffer && output_frames_needed); if (!draining) { long got = 0; T * out_unprocessed = nullptr; long output_frames_before_processing = 0; /* fill directly the input buffer of the output processor to save a copy */ output_frames_before_processing = output_processor->input_needed_for_output(output_frames_needed); out_unprocessed = output_processor->input_buffer(output_frames_before_processing); got = data_callback(stream, user_ptr, nullptr, out_unprocessed, output_frames_before_processing); if (got < output_frames_before_processing) { draining = true; if (got < 0) { return got; } } output_processor->written(got); } /* Process the output. If not enough frames have been returned from the * callback, drain the processors. */ return output_processor->output(output_buffer, output_frames_needed); } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill_internal_input(T * input_buffer, long * input_frames_count, T * output_buffer, long /*output_frames_needed*/) { assert(input_buffer && input_frames_count && *input_frames_count && !output_buffer); /* The input data, after eventual resampling. This is passed to the callback. */ T * resampled_input = nullptr; uint32_t resampled_frame_count = input_processor->output_for_input(*input_frames_count); /* process the input, and present exactly `output_frames_needed` in the * callback. */ input_processor->input(input_buffer, *input_frames_count); size_t frames_resampled = 0; resampled_input = input_processor->output(resampled_frame_count, &frames_resampled); *input_frames_count = frames_resampled; long got = data_callback(stream, user_ptr, resampled_input, nullptr, resampled_frame_count); /* Return the number of initial input frames or part of it. * Since output_frames_needed == 0 in input scenario, the only * available number outside resampler is the initial number of frames. */ return (*input_frames_count) * (got / resampled_frame_count); } template<typename T, typename InputProcessor, typename OutputProcessor> long cubeb_resampler_speex<T, InputProcessor, OutputProcessor> ::fill_internal_duplex(T * in_buffer, long * input_frames_count, T * out_buffer, long output_frames_needed) { if (draining) { // discard input and drain any signal remaining in the resampler. return output_processor->output(out_buffer, output_frames_needed); } /* The input data, after eventual resampling. This is passed to the callback. */ T * resampled_input = nullptr; /* The output buffer passed down in the callback, that might be resampled. */ T * out_unprocessed = nullptr; long output_frames_before_processing = 0; /* The number of frames returned from the callback. */ long got = 0; /* We need to determine how much frames to present to the consumer. * - If we have a two way stream, but we're only resampling input, we resample * the input to the number of output frames. * - If we have a two way stream, but we're only resampling the output, we * resize the input buffer of the output resampler to the number of input * frames, and we resample it afterwards. * - If we resample both ways, we resample the input to the number of frames * we would need to pass down to the consumer (before resampling the output), * get the output data, and resample it to the number of frames needed by the * caller. */ output_frames_before_processing = output_processor->input_needed_for_output(output_frames_needed); /* fill directly the input buffer of the output processor to save a copy */ out_unprocessed = output_processor->input_buffer(output_frames_before_processing); if (in_buffer) { /* process the input, and present exactly `output_frames_needed` in the * callback. */ input_processor->input(in_buffer, *input_frames_count); size_t frames_resampled = 0; resampled_input = input_processor->output(output_frames_before_processing, &frames_resampled); *input_frames_count = frames_resampled; } else { resampled_input = nullptr; } got = data_callback(stream, user_ptr, resampled_input, out_unprocessed, output_frames_before_processing); if (got < output_frames_before_processing) { draining = true; if (got < 0) { return got; } } output_processor->written(got); input_processor->drop_audio_if_needed(); /* Process the output. If not enough frames have been returned from the * callback, drain the processors. */ got = output_processor->output(out_buffer, output_frames_needed); output_processor->drop_audio_if_needed(); return got; } /* Resampler C API */ cubeb_resampler * cubeb_resampler_create(cubeb_stream * stream, cubeb_stream_params * input_params, cubeb_stream_params * output_params, unsigned int target_rate, cubeb_data_callback callback, void * user_ptr, cubeb_resampler_quality quality) { cubeb_sample_format format; assert(input_params || output_params); if (input_params) { format = input_params->format; } else { format = output_params->format; } switch(format) { case CUBEB_SAMPLE_S16NE: return cubeb_resampler_create_internal<short>(stream, input_params, output_params, target_rate, callback, user_ptr, quality); case CUBEB_SAMPLE_FLOAT32NE: return cubeb_resampler_create_internal<float>(stream, input_params, output_params, target_rate, callback, user_ptr, quality); default: assert(false); return nullptr; } } long cubeb_resampler_fill(cubeb_resampler * resampler, void * input_buffer, long * input_frames_count, void * output_buffer, long output_frames_needed) { return resampler->fill(input_buffer, input_frames_count, output_buffer, output_frames_needed); } void cubeb_resampler_destroy(cubeb_resampler * resampler) { delete resampler; } long cubeb_resampler_latency(cubeb_resampler * resampler) { return resampler->latency(); } <|endoftext|>
<commit_before>/* * This file is part of libgpiod. * * Copyright (C) 2017-2018 Bartosz Golaszewski <[email protected]> * * This program 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. */ #include <gpiod.hpp> #include <system_error> #include <map> namespace gpiod { namespace { const ::std::map<int, int> reqtype_mapping = { { line_request::DIRECTION_AS_IS, GPIOD_LINE_REQUEST_DIRECTION_AS_IS, }, { line_request::DIRECTION_INPUT, GPIOD_LINE_REQUEST_DIRECTION_INPUT, }, { line_request::DIRECTION_OUTPUT, GPIOD_LINE_REQUEST_DIRECTION_OUTPUT, }, { line_request::EVENT_FALLING_EDGE, GPIOD_LINE_REQUEST_EVENT_FALLING_EDGE, }, { line_request::EVENT_RISING_EDGE, GPIOD_LINE_REQUEST_EVENT_RISING_EDGE, }, { line_request::EVENT_BOTH_EDGES, GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES, }, }; struct bitset_cmp { bool operator()(const ::std::bitset<32>& lhs, const ::std::bitset<32>& rhs) { return lhs.to_ulong() < rhs.to_ulong(); } }; const ::std::map<::std::bitset<32>, int, bitset_cmp> reqflag_mapping = { { line_request::FLAG_ACTIVE_LOW, GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW, }, { line_request::FLAG_OPEN_DRAIN, GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN, }, { line_request::FLAG_OPEN_SOURCE, GPIOD_LINE_REQUEST_FLAG_OPEN_SOURCE, }, }; } /* namespace */ const ::std::bitset<32> line_request::FLAG_ACTIVE_LOW("001"); const ::std::bitset<32> line_request::FLAG_OPEN_SOURCE("010"); const ::std::bitset<32> line_request::FLAG_OPEN_DRAIN("100"); const unsigned int line_bulk::MAX_LINES = GPIOD_LINE_BULK_MAX_LINES; line_bulk::line_bulk(const ::std::vector<line>& lines) : _m_bulk() { this->_m_bulk.reserve(lines.size()); for (auto& it: lines) this->add(it); } void line_bulk::add(const line& new_line) { if (!new_line) throw ::std::logic_error("line_bulk cannot hold empty line objects"); if (this->_m_bulk.size() >= MAX_LINES) throw ::std::logic_error("maximum number of lines reached"); if (this->_m_bulk.size() >= 1 && this->_m_bulk.begin()->get_chip() != new_line.get_chip()) throw std::logic_error("line_bulk cannot hold GPIO lines from different chips"); this->_m_bulk.push_back(new_line); } line& line_bulk::get(unsigned int offset) { return this->_m_bulk.at(offset); } line& line_bulk::operator[](unsigned int offset) { return this->_m_bulk[offset]; } unsigned int line_bulk::size(void) const noexcept { return this->_m_bulk.size(); } bool line_bulk::empty(void) const noexcept { return this->_m_bulk.empty(); } void line_bulk::clear(void) { this->_m_bulk.clear(); } void line_bulk::request(const line_request& config, const std::vector<int> default_vals) const { this->throw_if_empty(); if (!default_vals.empty() && this->size() != default_vals.size()) throw ::std::invalid_argument("the number of default values must correspond with the number of lines"); ::gpiod_line_request_config conf; ::gpiod_line_bulk bulk; int rv; this->to_line_bulk(::std::addressof(bulk)); conf.consumer = config.consumer.c_str(); conf.request_type = reqtype_mapping.at(config.request_type); conf.flags = 0; for (auto& it: reqflag_mapping) { if ((it.first & config.flags).to_ulong()) conf.flags |= it.second; } rv = ::gpiod_line_request_bulk(::std::addressof(bulk), ::std::addressof(conf), default_vals.data()); if (rv) throw ::std::system_error(errno, ::std::system_category(), "error requesting GPIO lines"); } ::std::vector<int> line_bulk::get_values(void) const { this->throw_if_empty(); ::std::vector<int> values; ::gpiod_line_bulk bulk; int rv; this->to_line_bulk(::std::addressof(bulk)); values.resize(this->_m_bulk.size()); rv = ::gpiod_line_get_value_bulk(::std::addressof(bulk), values.data()); if (rv) throw ::std::system_error(errno, ::std::system_category(), "error reading GPIO line values"); return ::std::move(values); } void line_bulk::set_values(const ::std::vector<int>& values) const { this->throw_if_empty(); if (values.size() != this->_m_bulk.size()) throw ::std::invalid_argument("the size of values array must correspond with the number of lines"); ::gpiod_line_bulk bulk; int rv; this->to_line_bulk(::std::addressof(bulk)); rv = ::gpiod_line_set_value_bulk(::std::addressof(bulk), values.data()); if (rv) throw ::std::system_error(errno, ::std::system_category(), "error setting GPIO line values"); } line_bulk line_bulk::event_wait(const ::std::chrono::nanoseconds& timeout) const { this->throw_if_empty(); ::gpiod_line_bulk bulk, event_bulk; ::timespec ts; line_bulk ret; int rv; this->to_line_bulk(::std::addressof(bulk)); ::gpiod_line_bulk_init(::std::addressof(event_bulk)); ts.tv_sec = timeout.count() / 1000000000ULL; ts.tv_nsec = timeout.count() % 1000000000ULL; rv = ::gpiod_line_event_wait_bulk(::std::addressof(bulk), ::std::addressof(ts), ::std::addressof(event_bulk)); if (rv < 0) { throw ::std::system_error(errno, ::std::system_category(), "error polling for events"); } else if (rv > 0) { for (unsigned int i = 0; i < event_bulk.num_lines; i++) ret.add(line(event_bulk.lines[i], this->_m_bulk[i].get_chip())); } return ::std::move(ret); } line_bulk::operator bool(void) const noexcept { return !this->_m_bulk.empty(); } bool line_bulk::operator!(void) const noexcept { return this->_m_bulk.empty(); } line_bulk::iterator::iterator(const ::std::vector<line>::iterator& it) : _m_iter(it) { } line_bulk::iterator& line_bulk::iterator::operator++(void) { this->_m_iter++; return *this; } const line& line_bulk::iterator::operator*(void) const { return *this->_m_iter; } const line* line_bulk::iterator::operator->(void) const { return this->_m_iter.operator->(); } bool line_bulk::iterator::operator==(const iterator& rhs) const noexcept { return this->_m_iter == rhs._m_iter; } bool line_bulk::iterator::operator!=(const iterator& rhs) const noexcept { return this->_m_iter != rhs._m_iter; } line_bulk::iterator line_bulk::begin(void) noexcept { return ::std::move(line_bulk::iterator(this->_m_bulk.begin())); } line_bulk::iterator line_bulk::end(void) noexcept { return ::std::move(line_bulk::iterator(this->_m_bulk.end())); } void line_bulk::throw_if_empty(void) const { if (this->_m_bulk.empty()) throw std::logic_error("line_bulk not holding any GPIO lines"); } void line_bulk::to_line_bulk(::gpiod_line_bulk *bulk) const { ::gpiod_line_bulk_init(bulk); for (auto& it: this->_m_bulk) ::gpiod_line_bulk_add(bulk, it._m_line); } } /* namespace gpiod */ <commit_msg>bindings: cxx: require default values for output requests<commit_after>/* * This file is part of libgpiod. * * Copyright (C) 2017-2018 Bartosz Golaszewski <[email protected]> * * This program 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. */ #include <gpiod.hpp> #include <system_error> #include <map> namespace gpiod { namespace { const ::std::map<int, int> reqtype_mapping = { { line_request::DIRECTION_AS_IS, GPIOD_LINE_REQUEST_DIRECTION_AS_IS, }, { line_request::DIRECTION_INPUT, GPIOD_LINE_REQUEST_DIRECTION_INPUT, }, { line_request::DIRECTION_OUTPUT, GPIOD_LINE_REQUEST_DIRECTION_OUTPUT, }, { line_request::EVENT_FALLING_EDGE, GPIOD_LINE_REQUEST_EVENT_FALLING_EDGE, }, { line_request::EVENT_RISING_EDGE, GPIOD_LINE_REQUEST_EVENT_RISING_EDGE, }, { line_request::EVENT_BOTH_EDGES, GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES, }, }; struct bitset_cmp { bool operator()(const ::std::bitset<32>& lhs, const ::std::bitset<32>& rhs) { return lhs.to_ulong() < rhs.to_ulong(); } }; const ::std::map<::std::bitset<32>, int, bitset_cmp> reqflag_mapping = { { line_request::FLAG_ACTIVE_LOW, GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW, }, { line_request::FLAG_OPEN_DRAIN, GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN, }, { line_request::FLAG_OPEN_SOURCE, GPIOD_LINE_REQUEST_FLAG_OPEN_SOURCE, }, }; } /* namespace */ const ::std::bitset<32> line_request::FLAG_ACTIVE_LOW("001"); const ::std::bitset<32> line_request::FLAG_OPEN_SOURCE("010"); const ::std::bitset<32> line_request::FLAG_OPEN_DRAIN("100"); const unsigned int line_bulk::MAX_LINES = GPIOD_LINE_BULK_MAX_LINES; line_bulk::line_bulk(const ::std::vector<line>& lines) : _m_bulk() { this->_m_bulk.reserve(lines.size()); for (auto& it: lines) this->add(it); } void line_bulk::add(const line& new_line) { if (!new_line) throw ::std::logic_error("line_bulk cannot hold empty line objects"); if (this->_m_bulk.size() >= MAX_LINES) throw ::std::logic_error("maximum number of lines reached"); if (this->_m_bulk.size() >= 1 && this->_m_bulk.begin()->get_chip() != new_line.get_chip()) throw std::logic_error("line_bulk cannot hold GPIO lines from different chips"); this->_m_bulk.push_back(new_line); } line& line_bulk::get(unsigned int offset) { return this->_m_bulk.at(offset); } line& line_bulk::operator[](unsigned int offset) { return this->_m_bulk[offset]; } unsigned int line_bulk::size(void) const noexcept { return this->_m_bulk.size(); } bool line_bulk::empty(void) const noexcept { return this->_m_bulk.empty(); } void line_bulk::clear(void) { this->_m_bulk.clear(); } void line_bulk::request(const line_request& config, const std::vector<int> default_vals) const { this->throw_if_empty(); if (!default_vals.empty() && this->size() != default_vals.size()) throw ::std::invalid_argument("the number of default values must correspond with the number of lines"); if (config.request_type == line_request::DIRECTION_OUTPUT && default_vals.empty()) throw ::std::invalid_argument("default values are required for output mode"); ::gpiod_line_request_config conf; ::gpiod_line_bulk bulk; int rv; this->to_line_bulk(::std::addressof(bulk)); conf.consumer = config.consumer.c_str(); conf.request_type = reqtype_mapping.at(config.request_type); conf.flags = 0; for (auto& it: reqflag_mapping) { if ((it.first & config.flags).to_ulong()) conf.flags |= it.second; } rv = ::gpiod_line_request_bulk(::std::addressof(bulk), ::std::addressof(conf), default_vals.data()); if (rv) throw ::std::system_error(errno, ::std::system_category(), "error requesting GPIO lines"); } ::std::vector<int> line_bulk::get_values(void) const { this->throw_if_empty(); ::std::vector<int> values; ::gpiod_line_bulk bulk; int rv; this->to_line_bulk(::std::addressof(bulk)); values.resize(this->_m_bulk.size()); rv = ::gpiod_line_get_value_bulk(::std::addressof(bulk), values.data()); if (rv) throw ::std::system_error(errno, ::std::system_category(), "error reading GPIO line values"); return ::std::move(values); } void line_bulk::set_values(const ::std::vector<int>& values) const { this->throw_if_empty(); if (values.size() != this->_m_bulk.size()) throw ::std::invalid_argument("the size of values array must correspond with the number of lines"); ::gpiod_line_bulk bulk; int rv; this->to_line_bulk(::std::addressof(bulk)); rv = ::gpiod_line_set_value_bulk(::std::addressof(bulk), values.data()); if (rv) throw ::std::system_error(errno, ::std::system_category(), "error setting GPIO line values"); } line_bulk line_bulk::event_wait(const ::std::chrono::nanoseconds& timeout) const { this->throw_if_empty(); ::gpiod_line_bulk bulk, event_bulk; ::timespec ts; line_bulk ret; int rv; this->to_line_bulk(::std::addressof(bulk)); ::gpiod_line_bulk_init(::std::addressof(event_bulk)); ts.tv_sec = timeout.count() / 1000000000ULL; ts.tv_nsec = timeout.count() % 1000000000ULL; rv = ::gpiod_line_event_wait_bulk(::std::addressof(bulk), ::std::addressof(ts), ::std::addressof(event_bulk)); if (rv < 0) { throw ::std::system_error(errno, ::std::system_category(), "error polling for events"); } else if (rv > 0) { for (unsigned int i = 0; i < event_bulk.num_lines; i++) ret.add(line(event_bulk.lines[i], this->_m_bulk[i].get_chip())); } return ::std::move(ret); } line_bulk::operator bool(void) const noexcept { return !this->_m_bulk.empty(); } bool line_bulk::operator!(void) const noexcept { return this->_m_bulk.empty(); } line_bulk::iterator::iterator(const ::std::vector<line>::iterator& it) : _m_iter(it) { } line_bulk::iterator& line_bulk::iterator::operator++(void) { this->_m_iter++; return *this; } const line& line_bulk::iterator::operator*(void) const { return *this->_m_iter; } const line* line_bulk::iterator::operator->(void) const { return this->_m_iter.operator->(); } bool line_bulk::iterator::operator==(const iterator& rhs) const noexcept { return this->_m_iter == rhs._m_iter; } bool line_bulk::iterator::operator!=(const iterator& rhs) const noexcept { return this->_m_iter != rhs._m_iter; } line_bulk::iterator line_bulk::begin(void) noexcept { return ::std::move(line_bulk::iterator(this->_m_bulk.begin())); } line_bulk::iterator line_bulk::end(void) noexcept { return ::std::move(line_bulk::iterator(this->_m_bulk.end())); } void line_bulk::throw_if_empty(void) const { if (this->_m_bulk.empty()) throw std::logic_error("line_bulk not holding any GPIO lines"); } void line_bulk::to_line_bulk(::gpiod_line_bulk *bulk) const { ::gpiod_line_bulk_init(bulk); for (auto& it: this->_m_bulk) ::gpiod_line_bulk_add(bulk, it._m_line); } } /* namespace gpiod */ <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Jana Kiesel <[email protected]> * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date Mai, 2015 * * @section LICENSE * * Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of reading BEM data * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <mne/mne.h> #include <utils/ioutils.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QCommandLineParser> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("Read BEM Example"); parser.addHelpOption(); QCommandLineOption sampleBEMFileOption("f", "Path to BEM <file>.", "file", "./MNE-sample-data/subjects/sample/bem/sample-head.fif"); // "./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif" // "./MNE-sample-data/subjects/sample/bem/sample-all-src.fif" // "./MNE-sample-data/subjects/sample/bem/sample-5120-bem-sol.fif" // "./MNE-sample-data/subjects/sample/bem/sample-5120-bem.fif" parser.addOption(sampleBEMFileOption); parser.process(app); //######################################################################################## // Read the BEM QFile t_fileBem(parser.value(sampleBEMFileOption)); MNEBem t_Bem(t_fileBem); if( t_Bem.size() > 0 ) { qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(0,0) << t_Bem[0].tri_nn(0,1) << t_Bem[0].tri_nn(0,2); qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(2,0) << t_Bem[0].tri_nn(2,1) << t_Bem[0].tri_nn(2,2); qDebug() << "t_Bem[0].rr:" << t_Bem[0].rr(2,0) << t_Bem[0].rr(2,1) << t_Bem[0].rr(2,2); } //Read and write Iso2Mesh Bem QString folder = "C:/Users/Jana/Documents/MATLAB/AVG4-0Years_segmented_BEM3/"; MatrixXd help; MNEBem t_BemIso2Mesh; MNEBemSurface p_Brain; p_Brain.id = FIFFV_BEM_SURF_ID_BRAIN; QString path=folder; IOUtils::read_eigen_matrix(help, path.append("brain_vert.txt")); p_Brain.rr= help.cast<float>(); path=folder; IOUtils::read_eigen_matrix(help, path.append("brain_tri.txt")); p_Brain.tris = help.cast<int>(); p_Brain.np = p_Brain.rr.rows(); p_Brain.ntri = p_Brain.tris.rows(); p_Brain.addTriangleData(); p_Brain.addVertexNormals(); t_BemIso2Mesh<<p_Brain; MNEBemSurface p_Skull; p_Skull.id = FIFFV_BEM_SURF_ID_SKULL; path=folder; IOUtils::read_eigen_matrix(help,path.append("skull_vert.txt")); p_Skull.rr = help.cast<float>(); path=folder; IOUtils::read_eigen_matrix(help,path.append("skull_tri.txt")); p_Skull.tris = help.cast<int>(); p_Skull.np = p_Skull.rr.rows(); p_Skull.ntri = p_Skull.tris.rows(); p_Skull.addTriangleData(); p_Skull.addVertexNormals(); t_BemIso2Mesh<<p_Skull; MNEBemSurface p_Head; p_Head.id = FIFFV_BEM_SURF_ID_HEAD; path=folder; IOUtils::read_eigen_matrix(help,path.append("head_vert.txt")); p_Head.rr = help.cast<float>(); path=folder; IOUtils::read_eigen_matrix(help,path.append("head_tri.txt")); p_Head.tris = help.cast<int>(); p_Head.np = p_Head.rr.rows(); p_Head.ntri = p_Head.tris.rows(); p_Head.addTriangleData(); p_Head.addVertexNormals(); t_BemIso2Mesh<<p_Head; QFile t_fileIso2MeshBem("./Iso2MeshBem/AVG4-0Years_segmented_BEM3.fiff"); t_BemIso2Mesh.write(t_fileIso2MeshBem); t_fileIso2MeshBem.close(); // Write the BEM QFile t_fileBemTest("./MNE-sample-data/subjects/sample/bem/sample-head-test.fif"); t_Bem.write(t_fileBemTest); t_fileBemTest.close(); MNEBem t_BemTest (t_fileBemTest) ; if( t_BemTest.size() > 0 ) { qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(0,0) << t_BemTest[0].tri_nn(0,1) << t_BemTest[0].tri_nn(0,2); qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(2,0) << t_BemTest[0].tri_nn(2,1) << t_BemTest[0].tri_nn(2,2); } qDebug() << "Put your stuff your interest in here"; return app.exec(); } <commit_msg>[LIB-110] changed name of files that need to be read.<commit_after>//============================================================================================================= /** * @file main.cpp * @author Jana Kiesel <[email protected]> * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date Mai, 2015 * * @section LICENSE * * Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of reading BEM data * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <mne/mne.h> #include <utils/ioutils.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QCommandLineParser> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("Read BEM Example"); parser.addHelpOption(); QCommandLineOption sampleBEMFileOption("f", "Path to BEM <file>.", "file", "./MNE-sample-data/subjects/sample/bem/sample-head.fif"); // "./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif" // "./MNE-sample-data/subjects/sample/bem/sample-all-src.fif" // "./MNE-sample-data/subjects/sample/bem/sample-5120-bem-sol.fif" // "./MNE-sample-data/subjects/sample/bem/sample-5120-bem.fif" parser.addOption(sampleBEMFileOption); parser.process(app); //######################################################################################## // Read the BEM QFile t_fileBem(parser.value(sampleBEMFileOption)); MNEBem t_Bem(t_fileBem); if( t_Bem.size() > 0 ) { qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(0,0) << t_Bem[0].tri_nn(0,1) << t_Bem[0].tri_nn(0,2); qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(2,0) << t_Bem[0].tri_nn(2,1) << t_Bem[0].tri_nn(2,2); qDebug() << "t_Bem[0].rr:" << t_Bem[0].rr(2,0) << t_Bem[0].rr(2,1) << t_Bem[0].rr(2,2); } //Read and write Iso2Mesh Bem QString folder = "./MNE-sample-data/warping/AVG4-0Years_segmented_BEM3/bem/"; MatrixXd help; MNEBem t_BemIso2Mesh; MNEBemSurface p_Brain; p_Brain.id = FIFFV_BEM_SURF_ID_BRAIN; QString path=folder; IOUtils::read_eigen_matrix(help, path.append("inner_skull_vert.txt")); p_Brain.rr= help.cast<float>(); path=folder; IOUtils::read_eigen_matrix(help, path.append("inner_skull_tri.txt")); p_Brain.tris = help.cast<int>(); p_Brain.np = p_Brain.rr.rows(); p_Brain.ntri = p_Brain.tris.rows(); p_Brain.addTriangleData(); p_Brain.addVertexNormals(); t_BemIso2Mesh<<p_Brain; MNEBemSurface p_Skull; p_Skull.id = FIFFV_BEM_SURF_ID_SKULL; path=folder; IOUtils::read_eigen_matrix(help,path.append("outer_skull_vert.txt")); p_Skull.rr = help.cast<float>(); path=folder; IOUtils::read_eigen_matrix(help,path.append("outer_skull_tri.txt")); p_Skull.tris = help.cast<int>(); p_Skull.np = p_Skull.rr.rows(); p_Skull.ntri = p_Skull.tris.rows(); p_Skull.addTriangleData(); p_Skull.addVertexNormals(); t_BemIso2Mesh<<p_Skull; MNEBemSurface p_Head; p_Head.id = FIFFV_BEM_SURF_ID_HEAD; path=folder; IOUtils::read_eigen_matrix(help,path.append("skin_vert.txt")); p_Head.rr = help.cast<float>(); path=folder; IOUtils::read_eigen_matrix(help,path.append("skin_tri.txt")); p_Head.tris = help.cast<int>(); p_Head.np = p_Head.rr.rows(); p_Head.ntri = p_Head.tris.rows(); p_Head.addTriangleData(); p_Head.addVertexNormals(); t_BemIso2Mesh<<p_Head; QFile t_fileIso2MeshBem("./Iso2MeshBem/AVG4-0Years_segmented_BEM3.fiff"); t_BemIso2Mesh.write(t_fileIso2MeshBem); t_fileIso2MeshBem.close(); // Write the BEM QFile t_fileBemTest("./MNE-sample-data/subjects/sample/bem/sample-head-test.fif"); t_Bem.write(t_fileBemTest); t_fileBemTest.close(); MNEBem t_BemTest (t_fileBemTest) ; if( t_BemTest.size() > 0 ) { qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(0,0) << t_BemTest[0].tri_nn(0,1) << t_BemTest[0].tri_nn(0,2); qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(2,0) << t_BemTest[0].tri_nn(2,1) << t_BemTest[0].tri_nn(2,2); } qDebug() << "Put your stuff your interest in here"; return app.exec(); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_Characters_Format_inl_ #define _Stroika_Foundation_Characters_Format_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Containers/Common.h" #include "../Memory/SmallStackBuffer.h" namespace Stroika { namespace Foundation { namespace Characters { namespace Private_ { long long int String2Int_ (const string& s); long long int String2Int_ (const String& s); long long int String2Int_ (const char* s); long long int String2Int_ (const wchar_t* s); long long int String2Int_ (const wstring& s); unsigned long long int String2UInt_ (const string& s); unsigned long long int String2UInt_ (const String& s); unsigned long long int String2UInt_ (const char* s); unsigned long long int String2UInt_ (const wchar_t* s); unsigned long long int String2UInt_ (const wstring& s); inline long long int String2Int_ (const char* s) { return String2Int_ (string (s)); } inline long long int String2Int (const wchar_t* s) { return String2Int_ (String (s)); } inline long long int String2Int (const wstring& s) { return String2Int_ (String (s)); } inline unsigned long long int String2UInt (const char* s) { return String2UInt_ (string (s)); } inline unsigned long long int String2UInt (const wchar_t* s) { return String2UInt_ (String (s)); } inline unsigned long long int String2UInt (const wstring& s) { return String2UInt_ (String (s)); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER #pragma warning (push) #pragma warning (4 : 4018) #endif template <typename T, typename STRING_ARG> T String2IntOrUInt_ (STRING_ARG s) { using std::numeric_limits; if (numeric_limits<T>::is_signed) { long long int l = String2Int_ (s); if (l <= numeric_limits<T>::min ()) { return numeric_limits<T>::min (); } if (l >= numeric_limits<T>::max ()) { return numeric_limits<T>::max (); } return static_cast<T> (l); } else { unsigned long long int l = String2UInt_ (s); if (l >= numeric_limits<T>::max ()) { return numeric_limits<T>::max (); } return static_cast<T> (l); } } } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER #pragma warning (push) #endif template <typename TCHAR> basic_string<TCHAR> LTrim (const basic_string<TCHAR>& text) { std::locale loc1; // default locale const ctype<TCHAR>& ct = use_facet<ctype<TCHAR>>(loc1); typename basic_string<TCHAR>::const_iterator i = text.begin (); for (; i != text.end () and ct.is (ctype<TCHAR>::space, *i); ++i) ; return basic_string<TCHAR> (i, text.end ()); } template <typename TCHAR> basic_string<TCHAR> RTrim (const basic_string<TCHAR>& text) { std::locale loc1; // default locale const ctype<TCHAR>& ct = use_facet<ctype<TCHAR>>(loc1); typename basic_string<TCHAR>::const_iterator i = text.end (); for (; i != text.begin () and ct.is (ctype<TCHAR>::space, *(i - 1)); --i) ; return basic_string<TCHAR> (text.begin (), i); } template <typename TCHAR> inline basic_string<TCHAR> Trim (const basic_string<TCHAR>& text) { return LTrim (RTrim (text)); } template <typename T> inline T String2Int (const string& s) { return Private_::String2IntOrUInt_<T, const string&> (s); } template <typename T> inline T String2Int (const wchar_t* s) { return Private_::String2IntOrUInt_<T, const wchar_t*> (s); } template <typename T> inline T String2Int (const wstring& s) { return Private_::String2IntOrUInt_<T, const wstring&> (s); } template <typename T> inline T String2Int (const String& s) { return Private_::String2IntOrUInt_<T, const String&> (s); } } } } #endif /*_Stroika_Foundation_Characters_Format_inl_*/ <commit_msg>fix small bug with String2Int changes<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_Characters_Format_inl_ #define _Stroika_Foundation_Characters_Format_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Containers/Common.h" #include "../Memory/SmallStackBuffer.h" namespace Stroika { namespace Foundation { namespace Characters { namespace Private_ { long long int String2Int_ (const string& s); long long int String2Int_ (const String& s); long long int String2Int_ (const char* s); long long int String2Int_ (const wchar_t* s); long long int String2Int_ (const wstring& s); unsigned long long int String2UInt_ (const string& s); unsigned long long int String2UInt_ (const String& s); unsigned long long int String2UInt_ (const char* s); unsigned long long int String2UInt_ (const wchar_t* s); unsigned long long int String2UInt_ (const wstring& s); inline long long int String2Int_ (const char* s) { return String2Int_ (string (s)); } inline long long int String2Int_ (const wchar_t* s) { return String2Int_ (String (s)); } inline long long int String2Int_ (const wstring& s) { return String2Int_ (String (s)); } inline unsigned long long int String2UInt_ (const char* s) { return String2UInt_ (string (s)); } inline unsigned long long int String2UInt_ (const wchar_t* s) { return String2UInt_ (String (s)); } inline unsigned long long int String2UInt_ (const wstring& s) { return String2UInt_ (String (s)); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER #pragma warning (push) #pragma warning (4 : 4018) #endif template <typename T, typename STRING_ARG> T String2IntOrUInt_ (STRING_ARG s) { using std::numeric_limits; if (numeric_limits<T>::is_signed) { long long int l = String2Int_ (s); if (l <= numeric_limits<T>::min ()) { return numeric_limits<T>::min (); } if (l >= numeric_limits<T>::max ()) { return numeric_limits<T>::max (); } return static_cast<T> (l); } else { unsigned long long int l = String2UInt_ (s); if (l >= numeric_limits<T>::max ()) { return numeric_limits<T>::max (); } return static_cast<T> (l); } } } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER #pragma warning (push) #endif template <typename TCHAR> basic_string<TCHAR> LTrim (const basic_string<TCHAR>& text) { std::locale loc1; // default locale const ctype<TCHAR>& ct = use_facet<ctype<TCHAR>>(loc1); typename basic_string<TCHAR>::const_iterator i = text.begin (); for (; i != text.end () and ct.is (ctype<TCHAR>::space, *i); ++i) ; return basic_string<TCHAR> (i, text.end ()); } template <typename TCHAR> basic_string<TCHAR> RTrim (const basic_string<TCHAR>& text) { std::locale loc1; // default locale const ctype<TCHAR>& ct = use_facet<ctype<TCHAR>>(loc1); typename basic_string<TCHAR>::const_iterator i = text.end (); for (; i != text.begin () and ct.is (ctype<TCHAR>::space, *(i - 1)); --i) ; return basic_string<TCHAR> (text.begin (), i); } template <typename TCHAR> inline basic_string<TCHAR> Trim (const basic_string<TCHAR>& text) { return LTrim (RTrim (text)); } template <typename T> inline T String2Int (const string& s) { return Private_::String2IntOrUInt_<T, const string&> (s); } template <typename T> inline T String2Int (const wchar_t* s) { return Private_::String2IntOrUInt_<T, const wchar_t*> (s); } template <typename T> inline T String2Int (const wstring& s) { return Private_::String2IntOrUInt_<T, const wstring&> (s); } template <typename T> inline T String2Int (const String& s) { return Private_::String2IntOrUInt_<T, const String&> (s); } } } } #endif /*_Stroika_Foundation_Characters_Format_inl_*/ <|endoftext|>
<commit_before>// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include "mp/MpInputDeviceManager.h" #include "mp/MprFromInputDevice.h" #include "mp/MpOutputDeviceManager.h" #include "mp/MprToOutputDevice.h" #include "mp/MpFlowGraphBase.h" #include "mp/MpMisc.h" #include "mp/MpMediaTask.h" #include "os/OsTask.h" #ifdef RTL_ENABLED # include <rtl_macro.h> #else # define RTL_BLOCK(x) # define RTL_EVENT(x,y) #endif #include <os/OsFS.h> #define TEST_TIME_MS 10000 ///< Time to runs test (in milliseconds) #define AUDIO_BUFS_NUM 500 ///< Number of buffers in buffer pool we'll use. #define BUFFERS_TO_BUFFER_ON_INPUT 3 ///< Number of buffers to buffer in input manager. #define BUFFERS_TO_BUFFER_ON_OUTPUT 0 ///< Number of buffers to buffer in output manager. #define TEST_SAMPLES_PER_FRAME 80 ///< in samples #define TEST_SAMPLES_PER_SECOND 8000 ///< in samples/sec (Hz) #define BUFFER_ON_OUTPUT_MS (BUFFERS_TO_BUFFER_ON_OUTPUT*TEST_SAMPLES_PER_FRAME*1000/TEST_SAMPLES_PER_SECOND) ///< Buffer size in output manager in milliseconds. //#define USE_TEST_INPUT_DRIVER //#define USE_TEST_OUTPUT_DRIVER #ifdef USE_TEST_INPUT_DRIVER // USE_TEST_DRIVER [ #include <mp/MpSineWaveGeneratorDeviceDriver.h> #define INPUT_DRIVER MpSineWaveGeneratorDeviceDriver #define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) "SineGenerator", (manager), 32000, 3, 0 #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #include <mp/MpInputDeviceDriverWnt.h> #define INPUT_DRIVER MpInputDeviceDriverWnt #define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) "SoundMAX HD Audio", (manager) #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpidOSS.h> #define INPUT_DRIVER MpidOSS #define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) "/dev/dsp", (manager) #else // __pingtel_on_possix__ ] #error Unknown platform! #endif #ifdef USE_TEST_OUTPUT_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_TIME_MS #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #error No output driver for Windows exist! #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOSS.h> #define OUTPUT_DRIVER MpodOSS #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_possix__ ] #error Unknown platform! #endif /// Unit test for MprSplitter class MpInputOutputFrameworkTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpInputOutputFrameworkTest); CPPUNIT_TEST(testShortCircuit); CPPUNIT_TEST_SUITE_END(); protected: MpFlowGraphBase* mpFlowGraph; ///< Flowgraph for our fromInputDevice and ///< toOutputDevice resources. public: void setUp() { // Setup media task CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpStartUp(TEST_SAMPLES_PER_SECOND, TEST_SAMPLES_PER_FRAME, 6*10, 0)); mpFlowGraph = new MpFlowGraphBase( TEST_SAMPLES_PER_FRAME , TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT(mpFlowGraph != NULL); // Call getMediaTask() which causes the task to get instantiated CPPUNIT_ASSERT(MpMediaTask::getMediaTask(10) != NULL); } void tearDown() { // This should normally be done by haltFramework, but if we aborted due // to an assertion the flowgraph will need to be shutdown here if (mpFlowGraph && mpFlowGraph->isStarted()) { osPrintf("WARNING: flowgraph found still running, shutting down\n"); // ignore the result and keep going mpFlowGraph->stop(); // Request processing of another frame so that the STOP_FLOWGRAPH // message gets handled mpFlowGraph->processNextFrame(); } // Free flowgraph resources delete mpFlowGraph; mpFlowGraph = NULL; // Clear all Media Tasks data CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpShutdown()); } void testShortCircuit() { enableConsoleOutput(1); #ifdef RTL_ENABLED RTL_START(1000000); #endif // Get media processing task. MpMediaTask *pMediaTask = MpMediaTask::getMediaTask(10); // Create input and output device managers MpInputDeviceManager inputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFERS_TO_BUFFER_ON_INPUT, *MpMisc.RawAudioPool); MpOutputDeviceManager outputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFER_ON_OUTPUT_MS); // Create source (input) device and add it to manager. INPUT_DRIVER sourceDevice(INPUT_DRIVER_CONSTRUCTOR_PARAMS(inputDeviceManager)); MpInputDeviceHandle sourceDeviceId = inputDeviceManager.addDevice(sourceDevice); CPPUNIT_ASSERT(sourceDeviceId > 0); CPPUNIT_ASSERT(!inputDeviceManager.isDeviceEnabled(sourceDeviceId)); // Create sink (output) device and add it to manager. OUTPUT_DRIVER sinkDevice(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); MpOutputDeviceHandle sinkDeviceId = outputDeviceManager.addDevice(&sinkDevice); CPPUNIT_ASSERT(sinkDeviceId > 0); CPPUNIT_ASSERT(!outputDeviceManager.isDeviceEnabled(sinkDeviceId)); // Create source (input) and sink (output) resources. MprFromInputDevice pSource("MprFromInputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, &inputDeviceManager, sourceDeviceId); MprToOutputDevice pSink("MprToOutputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, &outputDeviceManager, sinkDeviceId); // Add source and sink resources to flowgraph and link them together. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSink)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addLink(pSource, 0, pSink, 0)); // Enable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, inputDeviceManager.enableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.enableDevice(sinkDeviceId)); // Set flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.setFlowgraphTickerSource(sinkDeviceId)); // Enable resources CPPUNIT_ASSERT(pSource.enable()); CPPUNIT_ASSERT(pSink.enable()); // Manage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->manageFlowGraph(*mpFlowGraph)); // Start flowgraph CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->startFlowGraph(*mpFlowGraph)); // Run test! OsTask::delay(TEST_TIME_MS); /* for (int i=0; i<TEST_TIME_MS*(TEST_SAMPLES_PER_SECOND/TEST_SAMPLES_PER_FRAME)/1000; i++) { RTL_BLOCK("test loop body"); printf("==> i=%d\n",i); OsTask::delay(TEST_SAMPLES_PER_FRAME*1000/TEST_SAMPLES_PER_SECOND-2); RTL_EVENT("test loop body", 2); MpMediaTask::signalFrameStart(); } */ // Stop flowgraph CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->stopFlowGraph(*mpFlowGraph)); OsTask::delay(20); // Unmanage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->unmanageFlowGraph(*mpFlowGraph)); // Disable resources CPPUNIT_ASSERT(pSource.disable()); CPPUNIT_ASSERT(pSink.disable()); mpFlowGraph->processNextFrame(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->stop()); mpFlowGraph->processNextFrame(); #ifdef USE_TEST_OUTPUT_DRIVER // [ OsFile::openAndWrite("capture.raw", (const char*)sinkDevice.getBufferData(), sinkDevice.getBufferLength()*sizeof(MpAudioSample)); #endif // USE_TEST_OUTPUT_DRIVER ] // Disable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, inputDeviceManager.disableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.disableDevice(sinkDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSink)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSource)); mpFlowGraph->processNextFrame(); OsTask::delay(10); #ifdef RTL_ENABLED RTL_WRITE("testShortCircuit.rtl"); #endif } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpInputOutputFrameworkTest); <commit_msg>MpInputOutputFrameworkTest: Make this test more resilent to CPPUnit assert exception, better cleanup, some more checks.<commit_after>// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include "mp/MpInputDeviceManager.h" #include "mp/MprFromInputDevice.h" #include "mp/MpOutputDeviceManager.h" #include "mp/MprToOutputDevice.h" #include "mp/MpFlowGraphBase.h" #include "mp/MpMisc.h" #include "mp/MpMediaTask.h" #include "os/OsTask.h" #ifdef RTL_ENABLED # include <rtl_macro.h> #else # define RTL_BLOCK(x) # define RTL_EVENT(x,y) #endif #include <os/OsFS.h> #define TEST_TIME_MS 10000 ///< Time to runs test (in milliseconds) #define AUDIO_BUFS_NUM 500 ///< Number of buffers in buffer pool we'll use. #define BUFFERS_TO_BUFFER_ON_INPUT 3 ///< Number of buffers to buffer in input manager. #define BUFFERS_TO_BUFFER_ON_OUTPUT 0 ///< Number of buffers to buffer in output manager. #define TEST_SAMPLES_PER_FRAME 80 ///< in samples #define TEST_SAMPLES_PER_SECOND 8000 ///< in samples/sec (Hz) #define BUFFER_ON_OUTPUT_MS (BUFFERS_TO_BUFFER_ON_OUTPUT*TEST_SAMPLES_PER_FRAME*1000/TEST_SAMPLES_PER_SECOND) ///< Buffer size in output manager in milliseconds. //#define USE_TEST_INPUT_DRIVER //#define USE_TEST_OUTPUT_DRIVER #ifdef USE_TEST_INPUT_DRIVER // USE_TEST_DRIVER [ #include <mp/MpSineWaveGeneratorDeviceDriver.h> #define INPUT_DRIVER MpSineWaveGeneratorDeviceDriver #define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) "SineGenerator", (manager), 32000, 3, 0 #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #include <mp/MpInputDeviceDriverWnt.h> #define INPUT_DRIVER MpInputDeviceDriverWnt #define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) "SoundMAX HD Audio", (manager) #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpidOSS.h> #define INPUT_DRIVER MpidOSS #define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) "/dev/dsp", (manager) #else // __pingtel_on_possix__ ] #error Unknown platform! #endif #ifdef USE_TEST_OUTPUT_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_TIME_MS #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #error No output driver for Windows exist! #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOSS.h> #define OUTPUT_DRIVER MpodOSS #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_possix__ ] #error Unknown platform! #endif /// Unit test for MprSplitter class MpInputOutputFrameworkTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpInputOutputFrameworkTest); CPPUNIT_TEST(testShortCircuit); CPPUNIT_TEST_SUITE_END(); protected: MpFlowGraphBase* mpFlowGraph; ///< Flowgraph for our fromInputDevice and ///< toOutputDevice resources. public: void setUp() { // Setup media task CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpStartUp(TEST_SAMPLES_PER_SECOND, TEST_SAMPLES_PER_FRAME, 6*10, 0)); mpFlowGraph = new MpFlowGraphBase( TEST_SAMPLES_PER_FRAME , TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT(mpFlowGraph != NULL); // Call getMediaTask() which causes the task to get instantiated CPPUNIT_ASSERT(MpMediaTask::getMediaTask(10) != NULL); } void tearDown() { // This should normally be done by haltFramework, but if we aborted due // to an assertion the flowgraph will need to be shutdown here if (mpFlowGraph && mpFlowGraph->isStarted()) { osPrintf("WARNING: flowgraph found still running, shutting down\n"); // ignore the result and keep going mpFlowGraph->stop(); // Request processing of another frame so that the STOP_FLOWGRAPH // message gets handled mpFlowGraph->processNextFrame(); } // Free flowgraph resources delete mpFlowGraph; mpFlowGraph = NULL; // Clear all Media Tasks data CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpShutdown()); } void testShortCircuit() { enableConsoleOutput(1); #ifdef RTL_ENABLED RTL_START(10000000); #endif // Get media processing task. MpMediaTask *pMediaTask = MpMediaTask::getMediaTask(10); CPPUNIT_ASSERT(pMediaTask != NULL); // Create input and output device managers MpInputDeviceManager inputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFERS_TO_BUFFER_ON_INPUT, *MpMisc.RawAudioPool); MpOutputDeviceManager outputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFER_ON_OUTPUT_MS); // Create source (input) device and add it to manager. INPUT_DRIVER sourceDevice(INPUT_DRIVER_CONSTRUCTOR_PARAMS(inputDeviceManager)); MpInputDeviceHandle sourceDeviceId = inputDeviceManager.addDevice(sourceDevice); CPPUNIT_ASSERT(sourceDeviceId > 0); CPPUNIT_ASSERT(!inputDeviceManager.isDeviceEnabled(sourceDeviceId)); // Create sink (output) device and add it to manager. OUTPUT_DRIVER sinkDevice(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); MpOutputDeviceHandle sinkDeviceId = outputDeviceManager.addDevice(&sinkDevice); CPPUNIT_ASSERT(sinkDeviceId > 0); CPPUNIT_ASSERT(!outputDeviceManager.isDeviceEnabled(sinkDeviceId)); // Create source (input) and sink (output) resources. MprFromInputDevice pSource("MprFromInputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, &inputDeviceManager, sourceDeviceId); MprToOutputDevice pSink("MprToOutputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, &outputDeviceManager, sinkDeviceId); // Add source and sink resources to flowgraph and link them together. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSink)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addLink(pSource, 0, pSink, 0)); try { // Set flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.setFlowgraphTickerSource(sinkDeviceId)); // Enable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, inputDeviceManager.enableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.enableDevice(sinkDeviceId)); // Enable resources CPPUNIT_ASSERT(pSource.enable()); CPPUNIT_ASSERT(pSink.enable()); // Manage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->manageFlowGraph(*mpFlowGraph)); // Start flowgraph CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->startFlowGraph(*mpFlowGraph)); // Run test! OsTask::delay(TEST_TIME_MS); /* for (int i=0; i<TEST_TIME_MS*(TEST_SAMPLES_PER_SECOND/TEST_SAMPLES_PER_FRAME)/1000; i++) { RTL_BLOCK("test loop body"); osPrintf("==> i=%d\n",i); OsTask::delay(TEST_SAMPLES_PER_FRAME*1000/TEST_SAMPLES_PER_SECOND-2); RTL_EVENT("test loop body", 2); MpMediaTask::signalFrameStart(); } */ // Clear flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.setFlowgraphTickerSource(MP_INVALID_OUTPUT_DEVICE_HANDLE)); // OsTask::delay(50); // Disable resources CPPUNIT_ASSERT(pSource.disable()); CPPUNIT_ASSERT(pSink.disable()); MpMediaTask::signalFrameStart(); // Unmanage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->unmanageFlowGraph(*mpFlowGraph)); MpMediaTask::signalFrameStart(); #ifdef USE_TEST_OUTPUT_DRIVER // [ OsFile::openAndWrite("capture.raw", (const char*)sinkDevice.getBufferData(), sinkDevice.getBufferLength()*sizeof(MpAudioSample)); #endif // USE_TEST_OUTPUT_DRIVER ] // Disable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, inputDeviceManager.disableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, outputDeviceManager.disableDevice(sinkDeviceId)); // Remove resources from flowgraph. We sohuld remove them explicitly // here, because they are stored on the stack and will be destroyed. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSink)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSource)); mpFlowGraph->processNextFrame(); } catch (CppUnit::Exception& e) { // Remove resources from flowgraph. We sohuld remove them explicitly // here, because they are stored on the stack and will be destroyed. // If we will not catch this assert we'll have this resources destroyed // while still referenced in flowgraph, causing crash. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSink)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSource)); mpFlowGraph->processNextFrame(); // Rethrow exception. throw(e); } // Remove devices from managers. CPPUNIT_ASSERT_EQUAL((MpInputDeviceDriver*)&sourceDevice, inputDeviceManager.removeDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL((MpOutputDeviceDriver*)&sinkDevice, outputDeviceManager.removeDevice(sinkDeviceId)); #ifdef RTL_ENABLED RTL_WRITE("testShortCircuit.rtl"); #endif } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpInputOutputFrameworkTest); <|endoftext|>
<commit_before>// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #ifdef TEST #include <assert.h> #include "utl/UtlMemCheck.h" #endif //TEST #ifdef __pingtel_on_posix__ #include <stdlib.h> #endif // APPLICATION INCLUDES #include <siptest/CommandMsgProcessor.h> #include <net/SipUserAgent.h> #include <os/OsServerTask.h> #include <os/OsTask.h> // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor CommandMsgProcessor::CommandMsgProcessor(SipUserAgent* sipUserAgent) { #ifdef TEST if (!sIsTested) { sIsTested = true; test(); } #endif //TEST userAgent = sipUserAgent; numRespondToMessages = 0; userAgent->addMessageConsumer(this); mpResponseMessage = NULL; mpLastResponseMessage = NULL; } // Copy constructor CommandMsgProcessor::CommandMsgProcessor(const CommandMsgProcessor& rCommandMsgProcessor) { } // Destructor CommandMsgProcessor::~CommandMsgProcessor() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator CommandMsgProcessor& CommandMsgProcessor::operator=(const CommandMsgProcessor& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean CommandMsgProcessor::handleMessage(OsMsg& eventMessage) { int msgType = eventMessage.getMsgType(); // int msgSubType = eventMessage.getMsgSubType(); if(msgType == OsMsg::PHONE_APP) // && msgSubType == CP_SIP_MESSAGE) { osPrintf("CommandMsgProcessor::handleMessage Got a message\n"); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); const SipMessage* sipMsg = ((SipMessageEvent&)eventMessage).getMessage(); UtlString callId; if(sipMsg) { osPrintf("numRespondToMessages: %d isResponse: %d messageType: %d TransErro: %d\n", numRespondToMessages, sipMsg->isResponse(), messageType, SipMessageEvent::TRANSPORT_ERROR); if((numRespondToMessages == -1 || numRespondToMessages > 0) && !sipMsg->isResponse() && messageType != SipMessageEvent::TRANSPORT_ERROR) { osPrintf("valid message\n"); if(numRespondToMessages > 0) { numRespondToMessages--; } SipMessage response; if(mpResponseMessage) { response = *mpResponseMessage; } response.setResponseData(sipMsg, responseStatusCode, responseStatusText.data()); UtlString address; int port; UtlString protocol; UtlString tag; sipMsg->getToAddress(&address, &port, &protocol, NULL, NULL, &tag) ; if( tag.isNull()) { int tagNum = rand(); char tag[100]; sprintf(tag, "%d", tagNum); UtlString tagWithDot(tag); tagWithDot.append(".34756498567498567"); response.setToFieldTag(tagWithDot); } UtlString msgBytes; int msgLen; response.getBytes(&msgBytes, &msgLen); osPrintf("%s",msgBytes.data()); if(mpLastResponseMessage) { delete mpLastResponseMessage; mpLastResponseMessage = NULL; } // Keep a copy of the last response sent mpLastResponseMessage = new SipMessage(response); if(userAgent->send(response)) { osPrintf("Sent response\n"); } else { osPrintf("Send failed\n"); } } } } return(TRUE); } /* ============================ ACCESSORS ================================= */ void CommandMsgProcessor::stopResponding() { numRespondToMessages = 0; } void CommandMsgProcessor::startResponding(int responseCode, const char* responseText, int numMessagesToRespondTo) { numRespondToMessages = numMessagesToRespondTo; responseStatusCode = responseCode; responseStatusText.remove(0); if(responseText) { responseStatusText.append(responseText); } if(mpResponseMessage) delete mpResponseMessage; mpResponseMessage = NULL; } void CommandMsgProcessor::startResponding(const char* filename, int numMessagesToRespondTo ) { UtlString messageBuffer; char buffer[1025]; int bufferSize = 1024; int charsRead; UtlString file = filename; numRespondToMessages = numMessagesToRespondTo; if (!file.isNull()) { //get header parameters from files FILE* sipMessageFile = fopen(filename, "r"); if(sipMessageFile) { //printf("opened file: \"%s\"\n", argv[1]); do { charsRead = fread(buffer, 1, bufferSize, sipMessageFile); if(charsRead > 0) { messageBuffer.append(buffer, charsRead); } } while(charsRead); fclose(sipMessageFile); //messageBuffer.strip(UtlString::trailing, '\n'); //messageBuffer.strip(UtlString::trailing, '\r'); // Make sure there is a NULL at the end messageBuffer.append("\0"); if(mpResponseMessage) delete mpResponseMessage; mpResponseMessage = new SipMessage(messageBuffer); responseStatusCode = mpResponseMessage->getResponseStatusCode(); mpResponseMessage->getResponseStatusText(&responseStatusText); } } //responseStatusText.append(messageBuffer); } void CommandMsgProcessor::resendLastResponse() { if(mpLastResponseMessage) { if(userAgent->send(*mpLastResponseMessage)) { osPrintf("Sent response\n"); } else { osPrintf("Send failed\n"); } } else { osPrintf("No previous response\n"); } } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ TESTING =================================== */ #ifdef TEST // Set to true after the tests have been executed once bool CommandMsgProcessor::sIsTested = false; // Test this class by running all of its assertion tests void CommandMsgProcessor::test() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check testCreators(); testManipulators(); testAccessors(); testInquiry(); assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the creators (and destructor) methods for the class void CommandMsgProcessor::testCreators() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // test the default constructor (if implemented) // test the copy constructor (if implemented) // test other constructors (if implemented) // if a constructor parameter is used to set information in an ancestor // class, then verify it gets set correctly (i.e., via ancestor // class accessor method. // test the destructor // if the class contains member pointer variables, verify that the // pointers are getting scrubbed. assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the manipulator methods void CommandMsgProcessor::testManipulators() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // test the assignment method (if implemented) // test the other manipulator methods for the class assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the accessor methods for the class void CommandMsgProcessor::testAccessors() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // body of the test goes here assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the inquiry methods for the class void CommandMsgProcessor::testInquiry() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // body of the test goes here assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } #endif //TEST /* ============================ FUNCTIONS ================================= */ <commit_msg>Copy Record-Route fields from INVITEs in siptest simulator. Also fixed indentation<commit_after>// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #ifdef TEST #include <assert.h> #include "utl/UtlMemCheck.h" #endif //TEST #ifdef __pingtel_on_posix__ #include <stdlib.h> #endif // APPLICATION INCLUDES #include <siptest/CommandMsgProcessor.h> #include <net/SipUserAgent.h> #include <os/OsServerTask.h> #include <os/OsTask.h> // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor CommandMsgProcessor::CommandMsgProcessor(SipUserAgent* sipUserAgent) { #ifdef TEST if (!sIsTested) { sIsTested = true; test(); } #endif //TEST userAgent = sipUserAgent; numRespondToMessages = 0; userAgent->addMessageConsumer(this); mpResponseMessage = NULL; mpLastResponseMessage = NULL; } // Copy constructor CommandMsgProcessor::CommandMsgProcessor(const CommandMsgProcessor& rCommandMsgProcessor) { } // Destructor CommandMsgProcessor::~CommandMsgProcessor() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator CommandMsgProcessor& CommandMsgProcessor::operator=(const CommandMsgProcessor& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean CommandMsgProcessor::handleMessage(OsMsg& eventMessage) { int msgType = eventMessage.getMsgType(); // int msgSubType = eventMessage.getMsgSubType(); if(msgType == OsMsg::PHONE_APP) // && msgSubType == CP_SIP_MESSAGE) { osPrintf("CommandMsgProcessor::handleMessage Got a message\n"); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); const SipMessage* sipMsg = ((SipMessageEvent&)eventMessage).getMessage(); UtlString callId; if(sipMsg) { osPrintf("numRespondToMessages: %d isResponse: %d messageType: %d TransErro: %d\n", numRespondToMessages, sipMsg->isResponse(), messageType, SipMessageEvent::TRANSPORT_ERROR); if((numRespondToMessages == -1 || numRespondToMessages > 0) && !sipMsg->isResponse() && messageType != SipMessageEvent::TRANSPORT_ERROR) { osPrintf("valid message\n"); if(numRespondToMessages > 0) { numRespondToMessages--; } SipMessage response; if(mpResponseMessage) { response = *mpResponseMessage; } // Copy To, From, CallId, Via(s), CSeq from request response.setResponseData(sipMsg, responseStatusCode, responseStatusText.data()); // If this is an INVITE 200 response, we need to set the Route headers UtlString method; sipMsg->getRequestMethod(&method); if(method.compareTo(SIP_INVITE_METHOD) == 0 && responseStatusCode >= 200 && responseStatusCode < 300) { response.setInviteOkRoutes(*sipMsg); } UtlString address; int port; UtlString protocol; UtlString tag; sipMsg->getToAddress(&address, &port, &protocol, NULL, NULL, &tag); if( tag.isNull()) { int tagNum = rand(); char tag[100]; sprintf(tag, "%d", tagNum); UtlString tagWithDot(tag); tagWithDot.append(".34756498567498567"); response.setToFieldTag(tagWithDot); } UtlString msgBytes; int msgLen; response.getBytes(&msgBytes, &msgLen); osPrintf("%s",msgBytes.data()); if(mpLastResponseMessage) { delete mpLastResponseMessage; mpLastResponseMessage = NULL; } // Keep a copy of the last response sent mpLastResponseMessage = new SipMessage(response); if(userAgent->send(response)) { osPrintf("Sent response\n"); } else { osPrintf("Send failed\n"); } } } } return(TRUE); } /* ============================ ACCESSORS ================================= */ void CommandMsgProcessor::stopResponding() { numRespondToMessages = 0; } void CommandMsgProcessor::startResponding(int responseCode, const char* responseText, int numMessagesToRespondTo) { numRespondToMessages = numMessagesToRespondTo; responseStatusCode = responseCode; responseStatusText.remove(0); if(responseText) { responseStatusText.append(responseText); } if(mpResponseMessage) delete mpResponseMessage; mpResponseMessage = NULL; } void CommandMsgProcessor::startResponding(const char* filename, int numMessagesToRespondTo ) { UtlString messageBuffer; char buffer[1025]; int bufferSize = 1024; int charsRead; UtlString file = filename; numRespondToMessages = numMessagesToRespondTo; if (!file.isNull()) { //get header parameters from files FILE* sipMessageFile = fopen(filename, "r"); if(sipMessageFile) { //printf("opened file: \"%s\"\n", argv[1]); do { charsRead = fread(buffer, 1, bufferSize, sipMessageFile); if(charsRead > 0) { messageBuffer.append(buffer, charsRead); } } while(charsRead); fclose(sipMessageFile); //messageBuffer.strip(UtlString::trailing, '\n'); //messageBuffer.strip(UtlString::trailing, '\r'); // Make sure there is a NULL at the end messageBuffer.append("\0"); if(mpResponseMessage) delete mpResponseMessage; mpResponseMessage = new SipMessage(messageBuffer); responseStatusCode = mpResponseMessage->getResponseStatusCode(); mpResponseMessage->getResponseStatusText(&responseStatusText); } } //responseStatusText.append(messageBuffer); } void CommandMsgProcessor::resendLastResponse() { if(mpLastResponseMessage) { if(userAgent->send(*mpLastResponseMessage)) { osPrintf("Sent response\n"); } else { osPrintf("Send failed\n"); } } else { osPrintf("No previous response\n"); } } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ TESTING =================================== */ #ifdef TEST // Set to true after the tests have been executed once bool CommandMsgProcessor::sIsTested = false; // Test this class by running all of its assertion tests void CommandMsgProcessor::test() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check testCreators(); testManipulators(); testAccessors(); testInquiry(); assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the creators (and destructor) methods for the class void CommandMsgProcessor::testCreators() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // test the default constructor (if implemented) // test the copy constructor (if implemented) // test other constructors (if implemented) // if a constructor parameter is used to set information in an ancestor // class, then verify it gets set correctly (i.e., via ancestor // class accessor method. // test the destructor // if the class contains member pointer variables, verify that the // pointers are getting scrubbed. assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the manipulator methods void CommandMsgProcessor::testManipulators() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // test the assignment method (if implemented) // test the other manipulator methods for the class assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the accessor methods for the class void CommandMsgProcessor::testAccessors() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // body of the test goes here assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } // Test the inquiry methods for the class void CommandMsgProcessor::testInquiry() { UtlMemCheck* pUtlMemCheck = 0; pUtlMemCheck = new UtlMemCheck(); // checkpoint for memory leak check // body of the test goes here assert(pUtlMemCheck->delta() == 0); // check for memory leak delete pUtlMemCheck; } #endif //TEST /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <pcl/pcl_config.h> #ifdef HAVE_QHULL #ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_ #define PCL_SURFACE_IMPL_CONVEX_HULL_H_ #include "pcl/surface/convex_hull.h" #include "pcl/common/common.h" #include "pcl/registration/transforms.h" #include "pcl/kdtree/kdtree.h" #include <stdio.h> #include <stdlib.h> extern "C" { #ifdef HAVE_QHULL_2011 # include "libqhull/libqhull.h" # include "libqhull/mem.h" # include "libqhull/qset.h" # include "libqhull/geom.h" # include "libqhull/merge.h" # include "libqhull/poly.h" # include "libqhull/io.h" # include "libqhull/stat.h" #else # include "qhull/qhull.h" # include "qhull/mem.h" # include "qhull/qset.h" # include "qhull/geom.h" # include "qhull/merge.h" # include "qhull/poly.h" # include "qhull/io.h" # include "qhull/stat.h" #endif } ////////////////////////////////////////////////////////////////////////// template <typename PointInT> void pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons, bool fill_polygon_data) { // FInd the principal directions EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix; Eigen::Vector4f xyz_centroid; compute3DCentroid (*input_, *indices_, xyz_centroid); computeCovarianceMatrix (*input_, *indices_, xyz_centroid, covariance_matrix); EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors; pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); Eigen::Affine3f transform1; transform1.setIdentity (); int dim = 3; if (eigen_values[0] / eigen_values[2] < 1.0e-5) { // We have points laying on a plane, using 2d convex hull // Compute transformation bring eigen_vectors.col(i) to z-axis eigen_vectors.col (2) = eigen_vectors.col (0).cross (eigen_vectors.col (1)); eigen_vectors.col (1) = eigen_vectors.col (2).cross (eigen_vectors.col (0)); transform1 (0, 2) = eigen_vectors (0, 0); transform1 (1, 2) = eigen_vectors (1, 0); transform1 (2, 2) = eigen_vectors (2, 0); transform1 (0, 1) = eigen_vectors (0, 1); transform1 (1, 1) = eigen_vectors (1, 1); transform1 (2, 1) = eigen_vectors (2, 1); transform1 (0, 0) = eigen_vectors (0, 2); transform1 (1, 0) = eigen_vectors (1, 2); transform1 (2, 0) = eigen_vectors (2, 2); transform1 = transform1.inverse (); dim = 2; } else transform1.setIdentity (); PointCloud cloud_transformed; pcl::demeanPointCloud (*input_, *indices_, xyz_centroid, cloud_transformed); pcl::transformPointCloud (cloud_transformed, cloud_transformed, transform1); // True if qhull should free points in qh_freeqhull() or reallocation boolT ismalloc = True; // option flags for qhull, see qh_opt.htm char flags[] = "qhull Tc"; // output from qh_produce_output(), use NULL to skip qh_produce_output() FILE *outfile = NULL; // error messages from qhull code FILE *errfile = stderr; // 0 if no error from qhull int exitcode; // Array of coordinates for each point coordT *points = (coordT *)calloc (cloud_transformed.points.size () * dim, sizeof(coordT)); for (size_t i = 0; i < cloud_transformed.points.size (); ++i) { points[i * dim + 0] = (coordT)cloud_transformed.points[i].x; points[i * dim + 1] = (coordT)cloud_transformed.points[i].y; if (dim > 2) points[i * dim + 2] = (coordT)cloud_transformed.points[i].z; } // Compute convex hull exitcode = qh_new_qhull (dim, cloud_transformed.points.size (), points, ismalloc, flags, outfile, errfile); if (exitcode != 0) { PCL_ERROR ("ERROR: qhull was unable to compute a convex hull for the given point cloud\n"); //check if it fails because of NaN values... if (!cloud_transformed.is_dense) { PCL_WARN ("Checking for Nans"); bool NaNvalues = false; for (size_t i = 0; i < cloud_transformed.size (); ++i) { if (!pcl_isfinite (cloud_transformed.points[i].x) || !pcl_isfinite (cloud_transformed.points[i].y) || !pcl_isfinite (cloud_transformed.points[i].z)) { NaNvalues = true; break; } } if (NaNvalues) PCL_ERROR ("ERROR: point cloud contains NaN values, consider running pcl::PassThrough filter first to remove NaNs.\n"); } hull.points.resize (0); hull.width = hull.height = 0; polygons.resize (0); qh_freeqhull (!qh_ALL); int curlong, totlong; qh_memfreeshort (&curlong, &totlong); return; } qh_triangulate (); int num_facets = qh num_facets; int num_vertices = qh num_vertices; hull.points.resize (num_vertices); vertexT * vertex; int i = 0; // Max vertex id int max_vertex_id = -1; FORALLvertices { if ((int)vertex->id > max_vertex_id) max_vertex_id = vertex->id; } ++max_vertex_id; std::vector<int> qhid_to_pcidx (max_vertex_id); FORALLvertices { // Add vertices to hull point_cloud hull.points[i].x = vertex->point[0]; hull.points[i].y = vertex->point[1]; if (dim>2) hull.points[i].z = vertex->point[2]; else hull.points[i].z = 0; qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index ++i; } if (fill_polygon_data) { if (dim == 3) { polygons.resize (num_facets); int dd = 0; facetT * facet; FORALLfacets { polygons[dd].vertices.resize (3); // Needed by FOREACHvertex_i_ int vertex_n, vertex_i; FOREACHvertex_i_((*facet).vertices) //facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]); polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id]; ++dd; } } else { // dim=2, we want to return just a polygon with all vertices sorted // so that they form a non-intersecting polygon... // this can be moved to the upper loop probably and here just // the sorting + populate Eigen::Vector4f centroid; pcl::compute3DCentroid (hull, centroid); centroid[3] = 0; polygons.resize (1); int num_vertices = qh num_vertices, dd = 0; // Copy all vertices std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices); FORALLvertices { idx_points[dd].first = qhid_to_pcidx[vertex->id]; idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid; ++dd; } // Sort idx_points std::sort (idx_points.begin (), idx_points.end (), comparePoints2D); polygons[0].vertices.resize (idx_points.size () + 1); //Sort also points... PointCloud hull_sorted; hull_sorted.points.resize (hull.points.size ()); for (size_t j = 0; j < idx_points.size (); ++j) hull_sorted.points[j] = hull.points[idx_points[j].first]; hull.points = hull_sorted.points; // Populate points for (size_t j = 0; j < idx_points.size (); ++j) polygons[0].vertices[j] = j; polygons[0].vertices[idx_points.size ()] = 0; } } else { if (dim == 2) { // We want to sort the points Eigen::Vector4f centroid; pcl::compute3DCentroid (hull, centroid); centroid[3] = 0; polygons.resize (1); int num_vertices = qh num_vertices, dd = 0; // Copy all vertices std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices); FORALLvertices { idx_points[dd].first = qhid_to_pcidx[vertex->id]; idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid; ++dd; } // Sort idx_points std::sort (idx_points.begin (), idx_points.end (), comparePoints2D); //Sort also points... PointCloud hull_sorted; hull_sorted.points.resize (hull.points.size ()); for (size_t j = 0; j < idx_points.size (); ++j) hull_sorted.points[j] = hull.points[idx_points[j].first]; hull.points = hull_sorted.points; } } // Deallocates memory (also the points) qh_freeqhull(!qh_ALL); int curlong, totlong; qh_memfreeshort (&curlong, &totlong); // Rotate the hull point cloud by transform's inverse // If the input point cloud has been rotated if (dim == 2) { Eigen::Affine3f transInverse = transform1.inverse (); pcl::transformPointCloud (hull, hull, transInverse); } xyz_centroid[0] = -xyz_centroid[0]; xyz_centroid[1] = -xyz_centroid[1]; xyz_centroid[2] = -xyz_centroid[2]; pcl::demeanPointCloud (hull, xyz_centroid, hull); //if keep_information_ if (keep_information_) { PCL_INFO ("[ConvexHull] Keep information is true, points in hull created from the original input cloud\n"); //build a tree with the original points pcl::KdTreeFLANN<PointInT> tree (true); tree.setInputCloud (input_, indices_); std::vector<int> neighbor; std::vector<float> distances; neighbor.resize (1); distances.resize (1); //for each point in the convex hull, search for the nearest neighbor std::vector<int> indices; indices.resize (hull.points.size ()); for (size_t i = 0; i < hull.points.size (); i++) { tree.nearestKSearch (hull.points[i], 1, neighbor, distances); indices[i] = (*indices_)[neighbor[0]]; } //replace point with the closest neighbor in the original point cloud pcl::copyPointCloud (*input_, indices, hull); } hull.width = hull.points.size (); hull.height = 1; hull.is_dense = false; } ////////////////////////////////////////////////////////////////////////// template <typename PointInT> void pcl::ConvexHull<PointInT>::reconstruct (PointCloud &output) { output.header = input_->header; if (!initCompute ()) { output.points.clear (); return; } // Perform the actual surface reconstruction std::vector<pcl::Vertices> polygons; performReconstruction (output, polygons, false); output.width = output.points.size (); output.height = 1; output.is_dense = true; deinitCompute (); } ////////////////////////////////////////////////////////////////////////// template <typename PointInT> void pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons) { points.header = input_->header; if (!initCompute ()) { points.points.clear (); return; } // Perform the actual surface reconstruction performReconstruction (points, polygons, true); points.width = points.points.size (); points.height = 1; points.is_dense = true; deinitCompute (); } #define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>; #endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_ #endif <commit_msg>tiny convex hull output adjustments<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <pcl/pcl_config.h> #ifdef HAVE_QHULL #ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_ #define PCL_SURFACE_IMPL_CONVEX_HULL_H_ #include "pcl/surface/convex_hull.h" #include "pcl/common/common.h" #include "pcl/registration/transforms.h" #include "pcl/kdtree/kdtree.h" #include <stdio.h> #include <stdlib.h> extern "C" { #ifdef HAVE_QHULL_2011 # include "libqhull/libqhull.h" # include "libqhull/mem.h" # include "libqhull/qset.h" # include "libqhull/geom.h" # include "libqhull/merge.h" # include "libqhull/poly.h" # include "libqhull/io.h" # include "libqhull/stat.h" #else # include "qhull/qhull.h" # include "qhull/mem.h" # include "qhull/qset.h" # include "qhull/geom.h" # include "qhull/merge.h" # include "qhull/poly.h" # include "qhull/io.h" # include "qhull/stat.h" #endif } ////////////////////////////////////////////////////////////////////////// template <typename PointInT> void pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons, bool fill_polygon_data) { // FInd the principal directions EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix; Eigen::Vector4f xyz_centroid; compute3DCentroid (*input_, *indices_, xyz_centroid); computeCovarianceMatrix (*input_, *indices_, xyz_centroid, covariance_matrix); EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors; pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); Eigen::Affine3f transform1; transform1.setIdentity (); int dim = 3; if (eigen_values[0] / eigen_values[2] < 1.0e-5) { // We have points laying on a plane, using 2d convex hull // Compute transformation bring eigen_vectors.col(i) to z-axis eigen_vectors.col (2) = eigen_vectors.col (0).cross (eigen_vectors.col (1)); eigen_vectors.col (1) = eigen_vectors.col (2).cross (eigen_vectors.col (0)); transform1 (0, 2) = eigen_vectors (0, 0); transform1 (1, 2) = eigen_vectors (1, 0); transform1 (2, 2) = eigen_vectors (2, 0); transform1 (0, 1) = eigen_vectors (0, 1); transform1 (1, 1) = eigen_vectors (1, 1); transform1 (2, 1) = eigen_vectors (2, 1); transform1 (0, 0) = eigen_vectors (0, 2); transform1 (1, 0) = eigen_vectors (1, 2); transform1 (2, 0) = eigen_vectors (2, 2); transform1 = transform1.inverse (); dim = 2; } else transform1.setIdentity (); PointCloud cloud_transformed; pcl::demeanPointCloud (*input_, *indices_, xyz_centroid, cloud_transformed); pcl::transformPointCloud (cloud_transformed, cloud_transformed, transform1); // True if qhull should free points in qh_freeqhull() or reallocation boolT ismalloc = True; // option flags for qhull, see qh_opt.htm char flags[] = "qhull Tc"; // output from qh_produce_output(), use NULL to skip qh_produce_output() FILE *outfile = NULL; // error messages from qhull code FILE *errfile = stderr; // 0 if no error from qhull int exitcode; // Array of coordinates for each point coordT *points = (coordT *)calloc (cloud_transformed.points.size () * dim, sizeof(coordT)); for (size_t i = 0; i < cloud_transformed.points.size (); ++i) { points[i * dim + 0] = (coordT)cloud_transformed.points[i].x; points[i * dim + 1] = (coordT)cloud_transformed.points[i].y; if (dim > 2) points[i * dim + 2] = (coordT)cloud_transformed.points[i].z; } // Compute convex hull exitcode = qh_new_qhull (dim, cloud_transformed.points.size (), points, ismalloc, flags, outfile, errfile); if (exitcode != 0) { PCL_ERROR ("[pcl::%s::performReconstrution] ERROR: qhull was unable to compute a convex hull for the given point cloud (%zu)!\n", getClassName ().c_str (), input_->points.size ()); //check if it fails because of NaN values... if (!cloud_transformed.is_dense) { bool NaNvalues = false; for (size_t i = 0; i < cloud_transformed.size (); ++i) { if (!pcl_isfinite (cloud_transformed.points[i].x) || !pcl_isfinite (cloud_transformed.points[i].y) || !pcl_isfinite (cloud_transformed.points[i].z)) { NaNvalues = true; break; } } if (NaNvalues) PCL_ERROR ("[pcl::%s::performReconstruction] ERROR: point cloud contains NaN values, consider running pcl::PassThrough filter first to remove NaNs!\n", getClassName ().c_str ()); } hull.points.resize (0); hull.width = hull.height = 0; polygons.resize (0); qh_freeqhull (!qh_ALL); int curlong, totlong; qh_memfreeshort (&curlong, &totlong); return; } qh_triangulate (); int num_facets = qh num_facets; int num_vertices = qh num_vertices; hull.points.resize (num_vertices); vertexT * vertex; int i = 0; // Max vertex id int max_vertex_id = -1; FORALLvertices { if ((int)vertex->id > max_vertex_id) max_vertex_id = vertex->id; } ++max_vertex_id; std::vector<int> qhid_to_pcidx (max_vertex_id); FORALLvertices { // Add vertices to hull point_cloud hull.points[i].x = vertex->point[0]; hull.points[i].y = vertex->point[1]; if (dim>2) hull.points[i].z = vertex->point[2]; else hull.points[i].z = 0; qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index ++i; } if (fill_polygon_data) { if (dim == 3) { polygons.resize (num_facets); int dd = 0; facetT * facet; FORALLfacets { polygons[dd].vertices.resize (3); // Needed by FOREACHvertex_i_ int vertex_n, vertex_i; FOREACHvertex_i_((*facet).vertices) //facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]); polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id]; ++dd; } } else { // dim=2, we want to return just a polygon with all vertices sorted // so that they form a non-intersecting polygon... // this can be moved to the upper loop probably and here just // the sorting + populate Eigen::Vector4f centroid; pcl::compute3DCentroid (hull, centroid); centroid[3] = 0; polygons.resize (1); int num_vertices = qh num_vertices, dd = 0; // Copy all vertices std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices); FORALLvertices { idx_points[dd].first = qhid_to_pcidx[vertex->id]; idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid; ++dd; } // Sort idx_points std::sort (idx_points.begin (), idx_points.end (), comparePoints2D); polygons[0].vertices.resize (idx_points.size () + 1); //Sort also points... PointCloud hull_sorted; hull_sorted.points.resize (hull.points.size ()); for (size_t j = 0; j < idx_points.size (); ++j) hull_sorted.points[j] = hull.points[idx_points[j].first]; hull.points = hull_sorted.points; // Populate points for (size_t j = 0; j < idx_points.size (); ++j) polygons[0].vertices[j] = j; polygons[0].vertices[idx_points.size ()] = 0; } } else { if (dim == 2) { // We want to sort the points Eigen::Vector4f centroid; pcl::compute3DCentroid (hull, centroid); centroid[3] = 0; polygons.resize (1); int num_vertices = qh num_vertices, dd = 0; // Copy all vertices std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices); FORALLvertices { idx_points[dd].first = qhid_to_pcidx[vertex->id]; idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid; ++dd; } // Sort idx_points std::sort (idx_points.begin (), idx_points.end (), comparePoints2D); //Sort also points... PointCloud hull_sorted; hull_sorted.points.resize (hull.points.size ()); for (size_t j = 0; j < idx_points.size (); ++j) hull_sorted.points[j] = hull.points[idx_points[j].first]; hull.points = hull_sorted.points; } } // Deallocates memory (also the points) qh_freeqhull(!qh_ALL); int curlong, totlong; qh_memfreeshort (&curlong, &totlong); // Rotate the hull point cloud by transform's inverse // If the input point cloud has been rotated if (dim == 2) { Eigen::Affine3f transInverse = transform1.inverse (); pcl::transformPointCloud (hull, hull, transInverse); } xyz_centroid[0] = -xyz_centroid[0]; xyz_centroid[1] = -xyz_centroid[1]; xyz_centroid[2] = -xyz_centroid[2]; pcl::demeanPointCloud (hull, xyz_centroid, hull); //if keep_information_ if (keep_information_) { //build a tree with the original points pcl::KdTreeFLANN<PointInT> tree (true); tree.setInputCloud (input_, indices_); std::vector<int> neighbor; std::vector<float> distances; neighbor.resize (1); distances.resize (1); //for each point in the convex hull, search for the nearest neighbor std::vector<int> indices; indices.resize (hull.points.size ()); for (size_t i = 0; i < hull.points.size (); i++) { tree.nearestKSearch (hull.points[i], 1, neighbor, distances); indices[i] = (*indices_)[neighbor[0]]; } //replace point with the closest neighbor in the original point cloud pcl::copyPointCloud (*input_, indices, hull); } hull.width = hull.points.size (); hull.height = 1; hull.is_dense = false; } ////////////////////////////////////////////////////////////////////////// template <typename PointInT> void pcl::ConvexHull<PointInT>::reconstruct (PointCloud &output) { output.header = input_->header; if (!initCompute ()) { output.points.clear (); return; } // Perform the actual surface reconstruction std::vector<pcl::Vertices> polygons; performReconstruction (output, polygons, false); output.width = output.points.size (); output.height = 1; output.is_dense = true; deinitCompute (); } ////////////////////////////////////////////////////////////////////////// template <typename PointInT> void pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons) { points.header = input_->header; if (!initCompute ()) { points.points.clear (); return; } // Perform the actual surface reconstruction performReconstruction (points, polygons, true); points.width = points.points.size (); points.height = 1; points.is_dense = true; deinitCompute (); } #define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>; #endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_ #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include <QDebug> #include <QApplication> #include <QStringList> #ifdef QT_SIMULATOR #include <private/qsimulatorconnection_p.h> #endif #include <qt4nodeinstanceclientproxy.h> #ifdef ENABLE_QT_BREAKPAD #include <qtsystemexceptionhandler.h> #endif #ifdef Q_OS_WIN #include <windows.h> #endif int main(int argc, char *argv[]) { #ifdef QT_SIMULATOR QtSimulatorPrivate::SimulatorConnection::createStubInstance(); #endif #ifdef Q_OS_MAC //This keeps qml2puppet from stealing focus qputenv("QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM", "true"); #endif QApplication application(argc, argv); QCoreApplication::setOrganizationName("QtProject"); QCoreApplication::setOrganizationDomain("qt-project.org"); QCoreApplication::setApplicationName("QmlPuppet"); QCoreApplication::setApplicationVersion("1.1.0"); if (application.arguments().count() == 2 && application.arguments().at(1) == "--version") { qDebug() << QCoreApplication::applicationVersion(); return 0; } if (application.arguments().count() < 4) return -1; #ifdef ENABLE_QT_BREAKPAD QtSystemExceptionHandler systemExceptionHandler; #endif new QmlDesigner::Qt4NodeInstanceClientProxy(&application); #if defined(Q_OS_WIN) && defined(QT_NO_DEBUG) && !defined(ENABLE_QT_BREAKPAD) SetErrorMode(SEM_NOGPFAULTERRORBOX); //We do not want to see any message boxes #endif return application.exec(); } <commit_msg>QmlDesigner: Change version for Qml1Puppet to 2<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include <QDebug> #include <QApplication> #include <QStringList> #ifdef QT_SIMULATOR #include <private/qsimulatorconnection_p.h> #endif #include <iostream> #include <qt4nodeinstanceclientproxy.h> #ifdef ENABLE_QT_BREAKPAD #include <qtsystemexceptionhandler.h> #endif #ifdef Q_OS_WIN #include <windows.h> #endif int main(int argc, char *argv[]) { #ifdef QT_SIMULATOR QtSimulatorPrivate::SimulatorConnection::createStubInstance(); #endif #ifdef Q_OS_MAC //This keeps qml2puppet from stealing focus qputenv("QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM", "true"); #endif QApplication application(argc, argv); QCoreApplication::setOrganizationName("QtProject"); QCoreApplication::setOrganizationDomain("qt-project.org"); QCoreApplication::setApplicationName("QmlPuppet"); QCoreApplication::setApplicationVersion("2.0.0"); if (application.arguments().count() == 2 && application.arguments().at(1) == "--version") { std::cout << 2; return 0; } if (application.arguments().count() < 4) return -1; #ifdef ENABLE_QT_BREAKPAD QtSystemExceptionHandler systemExceptionHandler; #endif new QmlDesigner::Qt4NodeInstanceClientProxy(&application); #if defined(Q_OS_WIN) && defined(QT_NO_DEBUG) && !defined(ENABLE_QT_BREAKPAD) SetErrorMode(SEM_NOGPFAULTERRORBOX); //We do not want to see any message boxes #endif return application.exec(); } <|endoftext|>
<commit_before>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #include "DatabaseGenerator.h" #include "CodeGenerator.h" #include "ArticyDatabase.h" #include "ArticyImportData.h" #include "CodeFileGenerator.h" #include "ExpressoScriptsGenerator.h" #include "ArticyImporterHelpers.h" void DatabaseGenerator::GenerateCode(const UArticyImportData* Data) { if(!ensure(Data)) return; const auto filename = CodeGenerator::GetDatabaseClassname(Data, true); CodeFileGenerator(filename + ".h", true, [&](CodeFileGenerator* header) { header->Line("#include \"ArticyRuntime/Public/ArticyDatabase.h\""); header->Line("#include \"" + ExpressoScriptsGenerator::GetFilename(Data) + "\""); header->Line("#include \"" + filename + ".generated.h\""); header->Line(); const auto className = CodeGenerator::GetDatabaseClassname(Data); header->Class(className + " : public UArticyDatabase", "", true, [&] { const auto expressoClass = CodeGenerator::GetExpressoScriptsClassname(Data, false); header->AccessModifier("public"); header->Method("", className, "", [&] { header->Line(FString::Printf(TEXT("SetExpressoScriptsClass(%s::StaticClass());"), *expressoClass)); }); { header->Line(); header->Method("static " + className + "*", "Get", "const UObject* WorldContext", [&] { header->Line(FString::Printf(TEXT("returns static_cast<%s*>(Super::Get(WorldContext));"), *className)); }, "Get the instace (copy of the asset) of the database.", true, "BlueprintPure, Category = \"articy:draft\", meta=(HidePin=\"WorldContext\", DefaultToSelf=\"WorldContext\", DisplayName=\"GetArticyDB\", keywords=\"database\")"); header->Line(); const auto globalVarsClass = CodeGenerator::GetGlobalVarsClassname(Data); header->Method(globalVarsClass + "*", "GetGVs", "", [&] { header->Line(FString::Printf(TEXT("return static_cast<%s*>(Super::GetGVs());"), *globalVarsClass)); }, "Get the global variables.", true, "BlueprintPure, Category = \"articy:draft\", meta=(keywords=\"global variables\")", "const override"); } }); }); } UArticyDatabase* DatabaseGenerator::GenerateAsset(const UArticyImportData* Data) { const auto className = CodeGenerator::GetDatabaseClassname(Data, true); return ArticyImporterHelpers::GenerateAsset<UArticyDatabase>(*className, TEXT("ArticyGenerated"), "", "", RF_ArchetypeObject); } <commit_msg>Fixed debug code generation<commit_after>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #include "DatabaseGenerator.h" #include "CodeGenerator.h" #include "ArticyDatabase.h" #include "ArticyImportData.h" #include "CodeFileGenerator.h" #include "ExpressoScriptsGenerator.h" #include "ArticyImporterHelpers.h" void DatabaseGenerator::GenerateCode(const UArticyImportData* Data) { if(!ensure(Data)) return; const auto filename = CodeGenerator::GetDatabaseClassname(Data, true); CodeFileGenerator(filename + ".h", true, [&](CodeFileGenerator* header) { header->Line("#include \"ArticyRuntime/Public/ArticyDatabase.h\""); header->Line("#include \"" + ExpressoScriptsGenerator::GetFilename(Data) + "\""); header->Line("#include \"" + filename + ".generated.h\""); header->Line(); const auto className = CodeGenerator::GetDatabaseClassname(Data); header->Class(className + " : public UArticyDatabase", "", true, [&] { const auto expressoClass = CodeGenerator::GetExpressoScriptsClassname(Data, false); header->AccessModifier("public"); header->Method("", className, "", [&] { header->Line(FString::Printf(TEXT("SetExpressoScriptsClass(%s::StaticClass());"), *expressoClass)); }); { header->Line(); header->Method("static " + className + "*", "Get", "const UObject* WorldContext", [&] { header->Line(FString::Printf(TEXT("return static_cast<%s*>(Super::Get(WorldContext));"), *className)); }, "Get the instace (copy of the asset) of the database.", true, "BlueprintPure, Category = \"articy:draft\", meta=(HidePin=\"WorldContext\", DefaultToSelf=\"WorldContext\", DisplayName=\"GetArticyDB\", keywords=\"database\")"); header->Line(); const auto globalVarsClass = CodeGenerator::GetGlobalVarsClassname(Data); header->Method(globalVarsClass + "*", "GetGVs", "", [&] { header->Line(FString::Printf(TEXT("return static_cast<%s*>(Super::GetGVs());"), *globalVarsClass)); }, "Get the global variables.", true, "BlueprintPure, Category = \"articy:draft\", meta=(keywords=\"global variables\")", "const override"); } }); }); } UArticyDatabase* DatabaseGenerator::GenerateAsset(const UArticyImportData* Data) { const auto className = CodeGenerator::GetDatabaseClassname(Data, true); return ArticyImporterHelpers::GenerateAsset<UArticyDatabase>(*className, TEXT("ArticyGenerated"), "", "", RF_ArchetypeObject); } <|endoftext|>
<commit_before>/********************************************************************************* * * Copyright (c) 2017 Josef Adamsson, Denise Härnström * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/crystalvisualization/processors/structuremesh.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> #include <inviwo/core/interaction/events/pickingevent.h> #include <inviwo/core/interaction/events/mouseevent.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <inviwo/core/datastructures/buffer/buffer.h> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo StructureMesh::processorInfo_{ "envision.StructureMesh", // Class identifier "Structure Mesh", // Display name "Crystal", // Category CodeState::Experimental, // Code state Tags::None, // Tags }; const ProcessorInfo StructureMesh::getProcessorInfo() const { return processorInfo_; } StructureMesh::StructureMesh() : Processor() , structure_("coordinates") , mesh_("mesh") , scalingFactor_("scalingFactor", "Scaling factor", 1.f) , basis_("basis", "Basis", glm::mat3x3()) , fullMesh_("fullMesh", "Full mesh", false) , animation_("animation", "Animation", false) , timestep_("timestep", "Time step", false) , enablePicking_("enablePicking", "Enable Picking", false) , spherePicking_(this, 0, [&](PickingEvent* p) { handlePicking(p); }) , inds_("inds", "Picked atoms") { addPort(structure_); addPort(mesh_); addProperty(scalingFactor_); addProperty(basis_); addProperty(fullMesh_); addProperty(animation_); addProperty(timestep_); addProperty(enablePicking_); addProperty(inds_); structure_.onChange([&](){ const auto data = structure_.getVectorData(); for(int i = colors_.size(); i < data.size(); ++i) { colors_.push_back(std::make_unique<FloatVec4Property>("color" + toString(i), "Color " + toString(i), vec4(1.0f, 1.0f, 1.0f, 1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput, PropertySemantics::Color)); addProperty(colors_.back().get(), false); radii_.push_back(std::make_unique<FloatProperty>("radius"+ toString(i), "Atom Radius"+ toString(i), 1.0f)); addProperty(radii_.back().get(), false); num_.push_back(std::make_unique<IntProperty>("atoms" + toString(i), "Atoms" + toString(i), 0)); addProperty(num_.back().get(), false); } int numSpheres = 0; for (const auto &strucs : structure_) numSpheres += strucs->size(); spherePicking_.resize(numSpheres); }); } void StructureMesh::process() { if (fullMesh_.get()) { auto mesh = std::make_shared<BasicMesh>(); mesh_.setData(mesh); size_t ind = 0; for (const auto &strucs : structure_) { for (long long j = 0; j < static_cast<long long>(strucs->size()); ++j) { auto center = scalingFactor_.get() * basis_.get() * strucs->at(j) - 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]); BasicMesh::sphere(center, radii_[ind]->get(), colors_[ind]->get(), mesh); } ++ind; } } else { if (structure_.isChanged() || animation_.isModified() || std::any_of(num_.begin(), num_.end(), [](const std::unique_ptr<IntProperty>& property) { return property->isModified(); }) || enablePicking_.isModified()) { int numSpheres = 0; size_t pInd = 0; for (const auto &strucs : structure_) { if (animation_.get()) { numSpheres += num_[pInd]->get(); ++pInd; } else { numSpheres += strucs->size(); } } vertexRAM_ = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres); colorRAM_ = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres); radiiRAM_ = std::make_shared<BufferRAMPrecision<float>>(numSpheres); auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None); mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib), std::make_shared<Buffer<vec3>>(vertexRAM_)); mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib), std::make_shared<Buffer<vec4>>(colorRAM_)); mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 5), std::make_shared<Buffer<float>>(radiiRAM_)); mesh_.setData(mesh); if (enablePicking_.get()) { auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres); auto& data = pickingRAM->getDataContainer(); // fill in picking IDs std::iota(data.begin(), data.end(), static_cast<uint32_t>(spherePicking_.getPickingId(0))); mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 4), std::make_shared<Buffer<uint32_t>>(pickingRAM)); } } auto& vertices = vertexRAM_->getDataContainer(); auto& colors = colorRAM_->getDataContainer(); auto& radii = radiiRAM_->getDataContainer(); size_t portInd = 0; size_t sphereInd = 0; for (const auto &strucs : structure_) { long long j_start, j_stop; j_start = 0; j_stop = static_cast<long long>(strucs->size()); if (animation_.get()) { j_start = num_[portInd]->get() * timestep_.get(); j_stop = num_[portInd]->get() * (timestep_.get() + 1); } for (long long j = j_start; j < j_stop ; ++j) { auto center = scalingFactor_.get() * basis_.get() * strucs->at(j); //- 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]); vertices[sphereInd] = center; colors[sphereInd] = colors_[portInd]->get(); radii[sphereInd] = radii_[portInd]->get(); ++sphereInd; } ++portInd; } if (enablePicking_.get()) { //Set alpha-layer of picked atoms if (!inds_.get().empty()) { for (const auto &ind : inds_.get()) { if (ind < sphereInd) { colors[ind].w = 0.5; } } } } colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get()); vertexRAM_->getOwner()->invalidateAllOther(vertexRAM_.get()); radiiRAM_->getOwner()->invalidateAllOther(radiiRAM_.get()); invalidate(InvalidationLevel::InvalidOutput); } } void StructureMesh::handlePicking(PickingEvent* p) { if (enablePicking_.get()) { if (p->getState() == PickingState::Updated && p->getEvent()->hash() == MouseEvent::chash()) { auto me = p->getEventAs<MouseEvent>(); if ((me->buttonState() & MouseButton::Left) && me->state() != MouseState::Move) { auto& color = colorRAM_->getDataContainer(); std::vector<int> temp = inds_.get(); auto picked = p->getPickedId(); if( std::none_of(temp.begin(), temp.end(), [&](unsigned int i){return i == picked;}) ) { temp.push_back(picked); color[picked].w = 0.5; } else { temp.erase(std::remove(temp.begin(), temp.end(), picked), temp.end()); color[picked].w = 1; } inds_.set(temp); colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get()); invalidate(InvalidationLevel::InvalidOutput); p->markAsUsed(); } } } } } // namespace <commit_msg>Update of the BSD2 license.<commit_after>/********************************************************************************* * * Copyright (c) 2017 Josef Adamsson, Denise Härnström, Anders Rehult * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/crystalvisualization/processors/structuremesh.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> #include <inviwo/core/interaction/events/pickingevent.h> #include <inviwo/core/interaction/events/mouseevent.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <inviwo/core/datastructures/buffer/buffer.h> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo StructureMesh::processorInfo_{ "envision.StructureMesh", // Class identifier "Structure Mesh", // Display name "Crystal", // Category CodeState::Experimental, // Code state Tags::None, // Tags }; const ProcessorInfo StructureMesh::getProcessorInfo() const { return processorInfo_; } StructureMesh::StructureMesh() : Processor() , structure_("coordinates") , mesh_("mesh") , scalingFactor_("scalingFactor", "Scaling factor", 1.f) , basis_("basis", "Basis", glm::mat3x3()) , fullMesh_("fullMesh", "Full mesh", false) , animation_("animation", "Animation", false) , timestep_("timestep", "Time step", false) , enablePicking_("enablePicking", "Enable Picking", false) , spherePicking_(this, 0, [&](PickingEvent* p) { handlePicking(p); }) , inds_("inds", "Picked atoms") { addPort(structure_); addPort(mesh_); addProperty(scalingFactor_); addProperty(basis_); addProperty(fullMesh_); addProperty(animation_); addProperty(timestep_); addProperty(enablePicking_); addProperty(inds_); structure_.onChange([&](){ const auto data = structure_.getVectorData(); for(int i = colors_.size(); i < data.size(); ++i) { colors_.push_back(std::make_unique<FloatVec4Property>("color" + toString(i), "Color " + toString(i), vec4(1.0f, 1.0f, 1.0f, 1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput, PropertySemantics::Color)); addProperty(colors_.back().get(), false); radii_.push_back(std::make_unique<FloatProperty>("radius"+ toString(i), "Atom Radius"+ toString(i), 1.0f)); addProperty(radii_.back().get(), false); num_.push_back(std::make_unique<IntProperty>("atoms" + toString(i), "Atoms" + toString(i), 0)); addProperty(num_.back().get(), false); } int numSpheres = 0; for (const auto &strucs : structure_) numSpheres += strucs->size(); spherePicking_.resize(numSpheres); }); } void StructureMesh::process() { if (fullMesh_.get()) { auto mesh = std::make_shared<BasicMesh>(); mesh_.setData(mesh); size_t ind = 0; for (const auto &strucs : structure_) { for (long long j = 0; j < static_cast<long long>(strucs->size()); ++j) { auto center = scalingFactor_.get() * basis_.get() * strucs->at(j) - 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]); BasicMesh::sphere(center, radii_[ind]->get(), colors_[ind]->get(), mesh); } ++ind; } } else { if (structure_.isChanged() || animation_.isModified() || std::any_of(num_.begin(), num_.end(), [](const std::unique_ptr<IntProperty>& property) { return property->isModified(); }) || enablePicking_.isModified()) { int numSpheres = 0; size_t pInd = 0; for (const auto &strucs : structure_) { if (animation_.get()) { numSpheres += num_[pInd]->get(); ++pInd; } else { numSpheres += strucs->size(); } } vertexRAM_ = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres); colorRAM_ = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres); radiiRAM_ = std::make_shared<BufferRAMPrecision<float>>(numSpheres); auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None); mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib), std::make_shared<Buffer<vec3>>(vertexRAM_)); mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib), std::make_shared<Buffer<vec4>>(colorRAM_)); mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 5), std::make_shared<Buffer<float>>(radiiRAM_)); mesh_.setData(mesh); if (enablePicking_.get()) { auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres); auto& data = pickingRAM->getDataContainer(); // fill in picking IDs std::iota(data.begin(), data.end(), static_cast<uint32_t>(spherePicking_.getPickingId(0))); mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 4), std::make_shared<Buffer<uint32_t>>(pickingRAM)); } } auto& vertices = vertexRAM_->getDataContainer(); auto& colors = colorRAM_->getDataContainer(); auto& radii = radiiRAM_->getDataContainer(); size_t portInd = 0; size_t sphereInd = 0; for (const auto &strucs : structure_) { long long j_start, j_stop; j_start = 0; j_stop = static_cast<long long>(strucs->size()); if (animation_.get()) { j_start = num_[portInd]->get() * timestep_.get(); j_stop = num_[portInd]->get() * (timestep_.get() + 1); } for (long long j = j_start; j < j_stop ; ++j) { auto center = scalingFactor_.get() * basis_.get() * strucs->at(j); //- 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]); vertices[sphereInd] = center; colors[sphereInd] = colors_[portInd]->get(); radii[sphereInd] = radii_[portInd]->get(); ++sphereInd; } ++portInd; } if (enablePicking_.get()) { //Set alpha-layer of picked atoms if (!inds_.get().empty()) { for (const auto &ind : inds_.get()) { if (ind < sphereInd) { colors[ind].w = 0.5; } } } } colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get()); vertexRAM_->getOwner()->invalidateAllOther(vertexRAM_.get()); radiiRAM_->getOwner()->invalidateAllOther(radiiRAM_.get()); invalidate(InvalidationLevel::InvalidOutput); } } void StructureMesh::handlePicking(PickingEvent* p) { if (enablePicking_.get()) { if (p->getState() == PickingState::Updated && p->getEvent()->hash() == MouseEvent::chash()) { auto me = p->getEventAs<MouseEvent>(); if ((me->buttonState() & MouseButton::Left) && me->state() != MouseState::Move) { auto& color = colorRAM_->getDataContainer(); std::vector<int> temp = inds_.get(); auto picked = p->getPickedId(); if( std::none_of(temp.begin(), temp.end(), [&](unsigned int i){return i == picked;}) ) { temp.push_back(picked); color[picked].w = 0.5; } else { temp.erase(std::remove(temp.begin(), temp.end(), picked), temp.end()); color[picked].w = 1; } inds_.set(temp); colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get()); invalidate(InvalidationLevel::InvalidOutput); p->markAsUsed(); } } } } } // namespace <|endoftext|>
<commit_before>/*************************************************************************/ /* test_astar.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "test_astar.h" #include "core/math/a_star.h" #include "core/os/os.h" #include <stdio.h> namespace TestAStar { class ABCX : public AStar { public: enum { A, B, C, X }; ABCX() { add_point(A, Vector3(0, 0, 0)); add_point(B, Vector3(1, 0, 0)); add_point(C, Vector3(0, 1, 0)); add_point(X, Vector3(0, 0, 1)); connect_points(A, B); connect_points(A, C); connect_points(B, C); connect_points(X, A); } // Disable heuristic completely float _compute_cost(int p_from, int p_to) { if (p_from == A && p_to == C) { return 1000; } return 100; } }; bool test_abc() { ABCX abcx; PoolVector<int> path = abcx.get_id_path(ABCX::A, ABCX::C); bool ok = path.size() == 3; int i = 0; ok = ok && path[i++] == ABCX::A; ok = ok && path[i++] == ABCX::B; ok = ok && path[i++] == ABCX::C; return ok; } bool test_abcx() { ABCX abcx; PoolVector<int> path = abcx.get_id_path(ABCX::X, ABCX::C); bool ok = path.size() == 4; int i = 0; ok = ok && path[i++] == ABCX::X; ok = ok && path[i++] == ABCX::A; ok = ok && path[i++] == ABCX::B; ok = ok && path[i++] == ABCX::C; return ok; } bool test_add_remove() { AStar a; bool ok = true; // Manual tests a.add_point(1, Vector3(0, 0, 0)); a.add_point(2, Vector3(0, 1, 0)); a.add_point(3, Vector3(1, 1, 0)); a.add_point(4, Vector3(2, 0, 0)); a.connect_points(1, 2, true); a.connect_points(1, 3, true); a.connect_points(1, 4, false); ok = ok && (a.are_points_connected(2, 1) == true); ok = ok && (a.are_points_connected(4, 1) == true); ok = ok && (a.are_points_connected(2, 1, false) == true); ok = ok && (a.are_points_connected(4, 1, false) == false); a.disconnect_points(1, 2, true); ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4 ok = ok && (a.get_point_connections(2).size() == 0); a.disconnect_points(4, 1, false); ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4 ok = ok && (a.get_point_connections(4).size() == 0); a.disconnect_points(4, 1, true); ok = ok && (a.get_point_connections(1).size() == 1); // 3 ok = ok && (a.get_point_connections(4).size() == 0); a.connect_points(2, 3, false); ok = ok && (a.get_point_connections(2).size() == 1); // 3 ok = ok && (a.get_point_connections(3).size() == 1); // 1 a.connect_points(2, 3, true); ok = ok && (a.get_point_connections(2).size() == 1); // 3 ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 a.disconnect_points(2, 3, false); ok = ok && (a.get_point_connections(2).size() == 0); ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 a.connect_points(4, 3, true); ok = ok && (a.get_point_connections(3).size() == 3); // 1, 2, 4 ok = ok && (a.get_point_connections(4).size() == 1); // 3 a.disconnect_points(3, 4, false); ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 ok = ok && (a.get_point_connections(4).size() == 1); // 3 a.remove_point(3); ok = ok && (a.get_point_connections(1).size() == 0); ok = ok && (a.get_point_connections(2).size() == 0); ok = ok && (a.get_point_connections(4).size() == 0); a.add_point(0, Vector3(0, -1, 0)); a.add_point(3, Vector3(2, 1, 0)); // 0: (0, -1) // 1: (0, 0) // 2: (0, 1) // 3: (2, 1) // 4: (2, 0) // Tests for get_closest_position_in_segment a.connect_points(2, 3); ok = ok && (a.get_closest_position_in_segment(Vector3(0.5, 0.5, 0)) == Vector3(0.5, 1, 0)); a.connect_points(3, 4); a.connect_points(0, 3); a.connect_points(1, 4); a.disconnect_points(1, 4, false); a.disconnect_points(4, 3, false); a.disconnect_points(3, 4, false); // Remaining edges: <2, 3>, <0, 3>, <1, 4> (directed) ok = ok && (a.get_closest_position_in_segment(Vector3(2, 0.5, 0)) == Vector3(1.75, 0.75, 0)); ok = ok && (a.get_closest_position_in_segment(Vector3(-1, 0.2, 0)) == Vector3(0, 0, 0)); ok = ok && (a.get_closest_position_in_segment(Vector3(3, 2, 0)) == Vector3(2, 1, 0)); int seed = 0; // Random tests for connectivity checks for (int i = 0; i < 20000; i++) { seed = (seed * 1103515245 + 12345) & 0x7fffffff; int u = (seed / 5) % 5; int v = seed % 5; if (u == v) { i--; continue; } if (seed % 2 == 1) { // Add a (possibly existing) directed edge and confirm connectivity a.connect_points(u, v, false); ok = ok && (a.are_points_connected(u, v, false) == true); } else { // Remove a (possibly nonexistent) directed edge and confirm disconnectivity a.disconnect_points(u, v, false); ok = ok && (a.are_points_connected(u, v, false) == false); } } // Random tests for point removal for (int i = 0; i < 20000; i++) { a.clear(); for (int j = 0; j < 5; j++) a.add_point(j, Vector3(0, 0, 0)); // Add or remove random edges for (int j = 0; j < 10; j++) { seed = (seed * 1103515245 + 12345) & 0x7fffffff; int u = (seed / 5) % 5; int v = seed % 5; if (u == v) { j--; continue; } if (seed % 2 == 1) a.connect_points(u, v, false); else a.disconnect_points(u, v, false); } // Remove point 0 a.remove_point(0); // White box: this will check all edges remaining in the segments set for (int j = 1; j < 5; j++) { ok = ok && (a.are_points_connected(0, j, true) == false); } } // It's been great work, cheers \(^ ^)/ return ok; } typedef bool (*TestFunc)(void); TestFunc test_funcs[] = { test_abc, test_abcx, test_add_remove, NULL }; MainLoop *test() { int count = 0; int passed = 0; while (true) { if (!test_funcs[count]) break; bool pass = test_funcs[count](); if (pass) passed++; OS::get_singleton()->print("\t%s\n", pass ? "PASS" : "FAILED"); count++; } OS::get_singleton()->print("\n"); OS::get_singleton()->print("Passed %i of %i tests\n", passed, count); return NULL; } } // namespace TestAStar <commit_msg>Add stress test between A* and Floyd-Warshall<commit_after>/*************************************************************************/ /* test_astar.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "test_astar.h" #include "core/math/a_star.h" #include "core/math/math_funcs.h" #include "core/os/os.h" #include <math.h> #include <stdio.h> namespace TestAStar { class ABCX : public AStar { public: enum { A, B, C, X }; ABCX() { add_point(A, Vector3(0, 0, 0)); add_point(B, Vector3(1, 0, 0)); add_point(C, Vector3(0, 1, 0)); add_point(X, Vector3(0, 0, 1)); connect_points(A, B); connect_points(A, C); connect_points(B, C); connect_points(X, A); } // Disable heuristic completely float _compute_cost(int p_from, int p_to) { if (p_from == A && p_to == C) { return 1000; } return 100; } }; bool test_abc() { ABCX abcx; PoolVector<int> path = abcx.get_id_path(ABCX::A, ABCX::C); bool ok = path.size() == 3; int i = 0; ok = ok && path[i++] == ABCX::A; ok = ok && path[i++] == ABCX::B; ok = ok && path[i++] == ABCX::C; return ok; } bool test_abcx() { ABCX abcx; PoolVector<int> path = abcx.get_id_path(ABCX::X, ABCX::C); bool ok = path.size() == 4; int i = 0; ok = ok && path[i++] == ABCX::X; ok = ok && path[i++] == ABCX::A; ok = ok && path[i++] == ABCX::B; ok = ok && path[i++] == ABCX::C; return ok; } bool test_add_remove() { AStar a; bool ok = true; // Manual tests a.add_point(1, Vector3(0, 0, 0)); a.add_point(2, Vector3(0, 1, 0)); a.add_point(3, Vector3(1, 1, 0)); a.add_point(4, Vector3(2, 0, 0)); a.connect_points(1, 2, true); a.connect_points(1, 3, true); a.connect_points(1, 4, false); ok = ok && (a.are_points_connected(2, 1) == true); ok = ok && (a.are_points_connected(4, 1) == true); ok = ok && (a.are_points_connected(2, 1, false) == true); ok = ok && (a.are_points_connected(4, 1, false) == false); a.disconnect_points(1, 2, true); ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4 ok = ok && (a.get_point_connections(2).size() == 0); a.disconnect_points(4, 1, false); ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4 ok = ok && (a.get_point_connections(4).size() == 0); a.disconnect_points(4, 1, true); ok = ok && (a.get_point_connections(1).size() == 1); // 3 ok = ok && (a.get_point_connections(4).size() == 0); a.connect_points(2, 3, false); ok = ok && (a.get_point_connections(2).size() == 1); // 3 ok = ok && (a.get_point_connections(3).size() == 1); // 1 a.connect_points(2, 3, true); ok = ok && (a.get_point_connections(2).size() == 1); // 3 ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 a.disconnect_points(2, 3, false); ok = ok && (a.get_point_connections(2).size() == 0); ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 a.connect_points(4, 3, true); ok = ok && (a.get_point_connections(3).size() == 3); // 1, 2, 4 ok = ok && (a.get_point_connections(4).size() == 1); // 3 a.disconnect_points(3, 4, false); ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 ok = ok && (a.get_point_connections(4).size() == 1); // 3 a.remove_point(3); ok = ok && (a.get_point_connections(1).size() == 0); ok = ok && (a.get_point_connections(2).size() == 0); ok = ok && (a.get_point_connections(4).size() == 0); a.add_point(0, Vector3(0, -1, 0)); a.add_point(3, Vector3(2, 1, 0)); // 0: (0, -1) // 1: (0, 0) // 2: (0, 1) // 3: (2, 1) // 4: (2, 0) // Tests for get_closest_position_in_segment a.connect_points(2, 3); ok = ok && (a.get_closest_position_in_segment(Vector3(0.5, 0.5, 0)) == Vector3(0.5, 1, 0)); a.connect_points(3, 4); a.connect_points(0, 3); a.connect_points(1, 4); a.disconnect_points(1, 4, false); a.disconnect_points(4, 3, false); a.disconnect_points(3, 4, false); // Remaining edges: <2, 3>, <0, 3>, <1, 4> (directed) ok = ok && (a.get_closest_position_in_segment(Vector3(2, 0.5, 0)) == Vector3(1.75, 0.75, 0)); ok = ok && (a.get_closest_position_in_segment(Vector3(-1, 0.2, 0)) == Vector3(0, 0, 0)); ok = ok && (a.get_closest_position_in_segment(Vector3(3, 2, 0)) == Vector3(2, 1, 0)); Math::seed(0); // Random tests for connectivity checks for (int i = 0; i < 20000; i++) { int u = Math::rand() % 5; int v = Math::rand() % 4; if (u == v) v = 4; if (Math::rand() % 2 == 1) { // Add a (possibly existing) directed edge and confirm connectivity a.connect_points(u, v, false); ok = ok && (a.are_points_connected(u, v, false) == true); } else { // Remove a (possibly nonexistent) directed edge and confirm disconnectivity a.disconnect_points(u, v, false); ok = ok && (a.are_points_connected(u, v, false) == false); } } // Random tests for point removal for (int i = 0; i < 20000; i++) { a.clear(); for (int j = 0; j < 5; j++) a.add_point(j, Vector3(0, 0, 0)); // Add or remove random edges for (int j = 0; j < 10; j++) { int u = Math::rand() % 5; int v = Math::rand() % 4; if (u == v) v = 4; if (Math::rand() % 2 == 1) a.connect_points(u, v, false); else a.disconnect_points(u, v, false); } // Remove point 0 a.remove_point(0); // White box: this will check all edges remaining in the segments set for (int j = 1; j < 5; j++) { ok = ok && (a.are_points_connected(0, j, true) == false); } } // It's been great work, cheers \(^ ^)/ return ok; } bool test_solutions() { // Random stress tests with Floyd-Warshall const int N = 30; Math::seed(0); for (int test = 0; test < 1000; test++) { AStar a; Vector3 p[N]; bool adj[N][N] = { { false } }; // Assign initial coordinates for (int u = 0; u < N; u++) { p[u].x = Math::rand() % 100; p[u].y = Math::rand() % 100; p[u].z = Math::rand() % 100; a.add_point(u, p[u]); } // Generate a random sequence of operations for (int i = 0; i < 1000; i++) { // Pick two different vertices int u, v; u = Math::rand() % N; v = Math::rand() % (N - 1); if (u == v) v = N - 1; // Pick a random operation int op = Math::rand(); switch (op % 9) { case 0: case 1: case 2: case 3: case 4: case 5: // Add edge (u, v); possibly bidirectional a.connect_points(u, v, op % 2); adj[u][v] = true; if (op % 2) adj[v][u] = true; break; case 6: case 7: // Remove edge (u, v); possibly bidirectional a.disconnect_points(u, v, op % 2); adj[u][v] = false; if (op % 2) adj[v][u] = false; break; case 8: // Remove point u and add it back; clears adjacent edges and changes coordinates a.remove_point(u); p[u].x = Math::rand() % 100; p[u].y = Math::rand() % 100; p[u].z = Math::rand() % 100; a.add_point(u, p[u]); for (v = 0; v < N; v++) adj[u][v] = adj[v][u] = false; break; } } // Floyd-Warshall float d[N][N]; for (int u = 0; u < N; u++) for (int v = 0; v < N; v++) d[u][v] = (u == v || adj[u][v]) ? p[u].distance_to(p[v]) : INFINITY; for (int w = 0; w < N; w++) for (int u = 0; u < N; u++) for (int v = 0; v < N; v++) if (d[u][v] > d[u][w] + d[w][v]) d[u][v] = d[u][w] + d[w][v]; // Display statistics int count = 0; for (int u = 0; u < N; u++) for (int v = 0; v < N; v++) if (adj[u][v]) count++; printf("Test #%4d: %3d edges, ", test + 1, count); count = 0; for (int u = 0; u < N; u++) for (int v = 0; v < N; v++) if (!Math::is_inf(d[u][v])) count++; printf("%3d/%d pairs of reachable points\n", count - N, N * (N - 1)); // Check A*'s output bool match = true; for (int u = 0; u < N; u++) for (int v = 0; v < N; v++) if (u != v) { PoolVector<int> route = a.get_id_path(u, v); if (!Math::is_inf(d[u][v])) { // Reachable if (route.size() == 0) { printf("From %d to %d: A* did not find a path\n", u, v); match = false; goto exit; } float astar_dist = 0; for (int i = 1; i < route.size(); i++) { if (!adj[route[i - 1]][route[i]]) { printf("From %d to %d: edge (%d, %d) does not exist\n", u, v, route[i - 1], route[i]); match = false; goto exit; } astar_dist += p[route[i - 1]].distance_to(p[route[i]]); } if (!Math::is_equal_approx(astar_dist, d[u][v])) { printf("From %d to %d: Floyd-Warshall gives %.6f, A* gives %.6f\n", u, v, d[u][v], astar_dist); match = false; goto exit; } } else { // Unreachable if (route.size() > 0) { printf("From %d to %d: A* somehow found a nonexistent path\n", u, v); match = false; goto exit; } } } exit: if (!match) return false; } return true; } typedef bool (*TestFunc)(void); TestFunc test_funcs[] = { test_abc, test_abcx, test_add_remove, test_solutions, NULL }; MainLoop *test() { int count = 0; int passed = 0; while (true) { if (!test_funcs[count]) break; bool pass = test_funcs[count](); if (pass) passed++; OS::get_singleton()->print("\t%s\n", pass ? "PASS" : "FAILED"); count++; } OS::get_singleton()->print("\n"); OS::get_singleton()->print("Passed %i of %i tests\n", passed, count); return NULL; } } // namespace TestAStar <|endoftext|>
<commit_before>/* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. * * author: Max Kellermann <[email protected]> */ #include "Client.hxx" #include "Handler.hxx" #include "Protocol.hxx" #include "async.hxx" #include "please.hxx" #include "fd_util.h" #include "pevent.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Cast.hxx" #include "util/Macros.hxx" #include <assert.h> #include <string.h> #include <sys/socket.h> struct DelegateClient { struct lease_ref lease_ref; const int fd; struct event event; struct pool *const pool; const struct delegate_handler *const handler; void *handler_ctx; struct async_operation operation; DelegateClient(int _fd, const struct lease &lease, void *lease_ctx, struct pool &_pool, const struct delegate_handler &_handler, void *_handler_ctx) :fd(_fd), pool(&_pool), handler(&_handler), handler_ctx(_handler_ctx) { p_lease_ref_set(lease_ref, lease, lease_ctx, _pool, "delegate_client_lease"); } ~DelegateClient() { pool_unref(pool); } void Destroy() { this->~DelegateClient(); } }; static void delegate_release_socket(DelegateClient *d, bool reuse) { assert(d != nullptr); assert(d->fd >= 0); p_lease_release(d->lease_ref, reuse, *d->pool); } static void delegate_handle_fd(DelegateClient *d, const struct msghdr *msg, size_t length) { if (length != 0) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); d->handler->error(error, d->handler_ctx); d->Destroy(); return; } struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); if (cmsg == nullptr) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "No fd passed"); d->handler->error(error, d->handler_ctx); d->Destroy(); return; } if (cmsg->cmsg_type != SCM_RIGHTS) { delegate_release_socket(d, false); GError *error = g_error_new(delegate_client_quark(), 0, "got control message of unknown type %d", cmsg->cmsg_type); d->handler->error(error, d->handler_ctx); d->Destroy(); return; } delegate_release_socket(d, true); const void *data = CMSG_DATA(cmsg); const int *fd_p = (const int *)data; int fd = *fd_p; d->handler->success(fd, d->handler_ctx); d->Destroy(); } static void delegate_handle_errno(DelegateClient *d, size_t length) { int e; if (length != sizeof(e)) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); d->handler->error(error, d->handler_ctx); d->Destroy(); return; } ssize_t nbytes = recv(d->fd, &e, sizeof(e), 0); GError *error; if (nbytes == sizeof(e)) { delegate_release_socket(d, true); error = new_error_errno2(e); } else { delegate_release_socket(d, false); error = g_error_new_literal(delegate_client_quark(), 0, "Failed to receive errno"); } d->handler->error(error, d->handler_ctx); d->Destroy(); } static void delegate_handle_msghdr(DelegateClient *d, const struct msghdr *msg, DelegateResponseCommand command, size_t length) { switch (command) { case DelegateResponseCommand::FD: delegate_handle_fd(d, msg, length); return; case DelegateResponseCommand::ERRNO: /* i/o error */ delegate_handle_errno(d, length); return; } delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid delegate response"); d->handler->error(error, d->handler_ctx); d->Destroy(); } static void delegate_try_read(DelegateClient *d) { d->operation.Finished(); struct iovec iov; int fd; char ccmsg[CMSG_SPACE(sizeof(fd))]; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ccmsg, .msg_controllen = sizeof(ccmsg), }; DelegateResponseHeader header; ssize_t nbytes; iov.iov_base = &header; iov.iov_len = sizeof(header); nbytes = recvmsg_cloexec(d->fd, &msg, 0); if (nbytes < 0) { fd = -errno; delegate_release_socket(d, false); GError *error = new_error_errno_msg("recvmsg() failed"); d->handler->error(error, d->handler_ctx); d->Destroy(); return; } if ((size_t)nbytes != sizeof(header)) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "short recvmsg()"); d->handler->error(error, d->handler_ctx); d->Destroy(); return; } delegate_handle_msghdr(d, &msg, header.command, header.length); } static void delegate_read_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { DelegateClient *d = (DelegateClient *)ctx; p_event_consumed(&d->event, d->pool); assert(d->fd == fd); delegate_try_read(d); } /* * async operation * */ static void delegate_connection_abort(struct async_operation *ao) { DelegateClient &d = ContainerCast2(*ao, &DelegateClient::operation); p_event_del(&d.event, d.pool); delegate_release_socket(&d, false); d.Destroy(); } static const struct async_operation_class delegate_operation = { .abort = delegate_connection_abort, }; /* * constructor * */ static bool SendDelegatePacket(int fd, DelegateRequestCommand cmd, const void *payload, size_t length, GError **error_r) { const DelegateRequestHeader header = { .length = (uint16_t)length, .command = cmd, }; struct iovec v[] = { { const_cast<void *>((const void *)&header), sizeof(header) }, { const_cast<void *>(payload), length }, }; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = v, .msg_iovlen = ARRAY_SIZE(v), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; auto nbytes = sendmsg(fd, &msg, MSG_DONTWAIT); if (nbytes < 0) { set_error_errno_msg(error_r, "Failed to send to delegate"); return false; } if (size_t(nbytes) != sizeof(header) + length) { g_set_error_literal(error_r, delegate_client_quark(), 0, "Short send to delegate"); return false; } return true; } void delegate_open(int fd, const struct lease *lease, void *lease_ctx, struct pool *pool, const char *path, const struct delegate_handler *handler, void *ctx, struct async_operation_ref *async_ref) { GError *error = nullptr; if (!SendDelegatePacket(fd, DelegateRequestCommand::OPEN, path, strlen(path), &error)) { lease->Release(lease_ctx, false); handler->error(error, ctx); return; } auto d = NewFromPool<DelegateClient>(*pool, fd, *lease, lease_ctx, *pool, *handler, ctx); pool_ref(pool); d->operation.Init(delegate_operation); async_ref->Set(d->operation); event_set(&d->event, d->fd, EV_READ, delegate_read_event_callback, d); p_event_add(&d->event, nullptr, pool, "delegate_client_event"); } <commit_msg>delegate/Client: convert pointers to references<commit_after>/* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. * * author: Max Kellermann <[email protected]> */ #include "Client.hxx" #include "Handler.hxx" #include "Protocol.hxx" #include "async.hxx" #include "please.hxx" #include "fd_util.h" #include "pevent.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Cast.hxx" #include "util/Macros.hxx" #include <assert.h> #include <string.h> #include <sys/socket.h> struct DelegateClient { struct lease_ref lease_ref; const int fd; struct event event; struct pool &pool; const struct delegate_handler &handler; void *handler_ctx; struct async_operation operation; DelegateClient(int _fd, const struct lease &lease, void *lease_ctx, struct pool &_pool, const struct delegate_handler &_handler, void *_handler_ctx) :fd(_fd), pool(_pool), handler(_handler), handler_ctx(_handler_ctx) { p_lease_ref_set(lease_ref, lease, lease_ctx, _pool, "delegate_client_lease"); } ~DelegateClient() { pool_unref(&pool); } void Destroy() { this->~DelegateClient(); } }; static void delegate_release_socket(DelegateClient *d, bool reuse) { assert(d != nullptr); assert(d->fd >= 0); p_lease_release(d->lease_ref, reuse, d->pool); } static void delegate_handle_fd(DelegateClient *d, const struct msghdr *msg, size_t length) { if (length != 0) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); d->handler.error(error, d->handler_ctx); d->Destroy(); return; } struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); if (cmsg == nullptr) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "No fd passed"); d->handler.error(error, d->handler_ctx); d->Destroy(); return; } if (cmsg->cmsg_type != SCM_RIGHTS) { delegate_release_socket(d, false); GError *error = g_error_new(delegate_client_quark(), 0, "got control message of unknown type %d", cmsg->cmsg_type); d->handler.error(error, d->handler_ctx); d->Destroy(); return; } delegate_release_socket(d, true); const void *data = CMSG_DATA(cmsg); const int *fd_p = (const int *)data; int fd = *fd_p; d->handler.success(fd, d->handler_ctx); d->Destroy(); } static void delegate_handle_errno(DelegateClient *d, size_t length) { int e; if (length != sizeof(e)) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); d->handler.error(error, d->handler_ctx); d->Destroy(); return; } ssize_t nbytes = recv(d->fd, &e, sizeof(e), 0); GError *error; if (nbytes == sizeof(e)) { delegate_release_socket(d, true); error = new_error_errno2(e); } else { delegate_release_socket(d, false); error = g_error_new_literal(delegate_client_quark(), 0, "Failed to receive errno"); } d->handler.error(error, d->handler_ctx); d->Destroy(); } static void delegate_handle_msghdr(DelegateClient *d, const struct msghdr *msg, DelegateResponseCommand command, size_t length) { switch (command) { case DelegateResponseCommand::FD: delegate_handle_fd(d, msg, length); return; case DelegateResponseCommand::ERRNO: /* i/o error */ delegate_handle_errno(d, length); return; } delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid delegate response"); d->handler.error(error, d->handler_ctx); d->Destroy(); } static void delegate_try_read(DelegateClient *d) { d->operation.Finished(); struct iovec iov; int fd; char ccmsg[CMSG_SPACE(sizeof(fd))]; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ccmsg, .msg_controllen = sizeof(ccmsg), }; DelegateResponseHeader header; ssize_t nbytes; iov.iov_base = &header; iov.iov_len = sizeof(header); nbytes = recvmsg_cloexec(d->fd, &msg, 0); if (nbytes < 0) { fd = -errno; delegate_release_socket(d, false); GError *error = new_error_errno_msg("recvmsg() failed"); d->handler.error(error, d->handler_ctx); d->Destroy(); return; } if ((size_t)nbytes != sizeof(header)) { delegate_release_socket(d, false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "short recvmsg()"); d->handler.error(error, d->handler_ctx); d->Destroy(); return; } delegate_handle_msghdr(d, &msg, header.command, header.length); } static void delegate_read_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { DelegateClient *d = (DelegateClient *)ctx; p_event_consumed(&d->event, &d->pool); assert(d->fd == fd); delegate_try_read(d); } /* * async operation * */ static void delegate_connection_abort(struct async_operation *ao) { DelegateClient &d = ContainerCast2(*ao, &DelegateClient::operation); p_event_del(&d.event, &d.pool); delegate_release_socket(&d, false); d.Destroy(); } static const struct async_operation_class delegate_operation = { .abort = delegate_connection_abort, }; /* * constructor * */ static bool SendDelegatePacket(int fd, DelegateRequestCommand cmd, const void *payload, size_t length, GError **error_r) { const DelegateRequestHeader header = { .length = (uint16_t)length, .command = cmd, }; struct iovec v[] = { { const_cast<void *>((const void *)&header), sizeof(header) }, { const_cast<void *>(payload), length }, }; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = v, .msg_iovlen = ARRAY_SIZE(v), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; auto nbytes = sendmsg(fd, &msg, MSG_DONTWAIT); if (nbytes < 0) { set_error_errno_msg(error_r, "Failed to send to delegate"); return false; } if (size_t(nbytes) != sizeof(header) + length) { g_set_error_literal(error_r, delegate_client_quark(), 0, "Short send to delegate"); return false; } return true; } void delegate_open(int fd, const struct lease *lease, void *lease_ctx, struct pool *pool, const char *path, const struct delegate_handler *handler, void *ctx, struct async_operation_ref *async_ref) { GError *error = nullptr; if (!SendDelegatePacket(fd, DelegateRequestCommand::OPEN, path, strlen(path), &error)) { lease->Release(lease_ctx, false); handler->error(error, ctx); return; } auto d = NewFromPool<DelegateClient>(*pool, fd, *lease, lease_ctx, *pool, *handler, ctx); pool_ref(pool); d->operation.Init(delegate_operation); async_ref->Set(d->operation); event_set(&d->event, d->fd, EV_READ, delegate_read_event_callback, d); p_event_add(&d->event, nullptr, pool, "delegate_client_event"); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_PRINT_HPP #define ETL_PRINT_HPP #include<string> #include "cpp_utils/tmp.hpp" #include "traits.hpp" namespace etl { template<typename T, cpp_enable_if((etl_traits<T>::dimensions() > 1))> std::string to_string(const T& m){ std::string v = "["; for(std::size_t i = 0; i < etl::dim<0>(m); ++i){ v += to_string(sub(m, i)); if(i < etl::dim<0>(m) - 1){ v += "\n"; } } v += "]"; return v; } template<typename T, cpp_enable_if(etl_traits<T>::dimensions() == 1)> std::string to_string(const T& m){ return to_octave(m); } template<bool Sub = false, typename T, cpp_enable_if((etl_traits<T>::dimensions() > 1))> std::string to_octave(const T& m){ std::string v; if(!Sub){ v = "["; } for(std::size_t i = 0; i < etl::dim<0>(m); ++i){ v += to_octave<true>(sub(m, i)); if(i < etl::dim<0>(m) - 1){ v += ";"; } } if(!Sub){ v += "]"; } return v; } template<bool Sub = false, typename T, cpp_enable_if(etl_traits<T>::dimensions() == 1)> std::string to_octave(const T& m){ std::string v; if(!Sub){ v = "["; } std::string comma = ""; for(std::size_t j = 0; j < etl::dim<0>(m); ++j){ v += comma + std::to_string(m(j)); comma = ","; } if(!Sub){ v += "]"; } return v; } } //end of namespace etl #endif <commit_msg>Include only traits_lite<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_PRINT_HPP #define ETL_PRINT_HPP #include<string> #include "cpp_utils/tmp.hpp" #include "traits_lite.hpp" namespace etl { template<typename T, cpp_enable_if((etl_traits<T>::dimensions() > 1))> std::string to_string(const T& m){ std::string v = "["; for(std::size_t i = 0; i < etl::dim<0>(m); ++i){ v += to_string(sub(m, i)); if(i < etl::dim<0>(m) - 1){ v += "\n"; } } v += "]"; return v; } template<typename T, cpp_enable_if(etl_traits<T>::dimensions() == 1)> std::string to_string(const T& m){ return to_octave(m); } template<bool Sub = false, typename T, cpp_enable_if((etl_traits<T>::dimensions() > 1))> std::string to_octave(const T& m){ std::string v; if(!Sub){ v = "["; } for(std::size_t i = 0; i < etl::dim<0>(m); ++i){ v += to_octave<true>(sub(m, i)); if(i < etl::dim<0>(m) - 1){ v += ";"; } } if(!Sub){ v += "]"; } return v; } template<bool Sub = false, typename T, cpp_enable_if(etl_traits<T>::dimensions() == 1)> std::string to_octave(const T& m){ std::string v; if(!Sub){ v = "["; } std::string comma = ""; for(std::size_t j = 0; j < etl::dim<0>(m); ++j){ v += comma + std::to_string(m(j)); comma = ","; } if(!Sub){ v += "]"; } return v; } } //end of namespace etl #endif <|endoftext|>
<commit_before>/* * 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. */ #ifndef otbGenericRSTransform_hxx #define otbGenericRSTransform_hxx #include "otbGenericRSTransform.h" #include "otbMacro.h" #include "otbMetaDataKey.h" #include "otbRPCForwardTransform.h" #include "otbRPCInverseTransform.h" #include "otbSpatialReference.h" #include "ogr_spatialref.h" namespace otb { template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GenericRSTransform() : Superclass(0) { m_InputProjectionRef.clear(); m_OutputProjectionRef.clear(); m_InputSpacing.Fill(1); m_InputOrigin.Fill(0); m_OutputSpacing.Fill(1); m_OutputOrigin.Fill(0); m_InputImd = nullptr; m_OutputImd = nullptr; m_Transform = nullptr; m_InputTransform = nullptr; m_OutputTransform = nullptr; m_TransformUpToDate = false; m_TransformAccuracy = Projection::UNKNOWN; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> const typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::TransformType* GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GetTransform() const { itkDebugMacro("returning MapProjection address " << this->m_Transform); if ((!m_TransformUpToDate) || (m_Transform.IsNull())) { itkExceptionMacro(<< "m_Transform not up-to-date, call InstantiateTransform() first"); } return this->m_Transform; } /** * Instantiate the transformation according to information */ template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> void GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::InstantiateTransform(void) { m_Transform = TransformType::New(); otbMsgDevMacro(<< "Information to instantiate transform: "); otbMsgDevMacro(<< " * Input Origin: " << m_InputOrigin); otbMsgDevMacro(<< " * Input Spacing: " << m_InputSpacing); otbMsgDevMacro(<< " * Input metadata: " << ((m_InputImd == nullptr) ? "Empty" : "Full")); otbMsgDevMacro(<< " * Input projection: " << m_InputProjectionRef); otbMsgDevMacro(<< " * Output metadata: " << ((m_OutputImd == nullptr) ? "Empty" : "Full")); otbMsgDevMacro(<< " * Output projection: " << m_OutputProjectionRef); otbMsgDevMacro(<< " * Output Origin: " << m_OutputOrigin); otbMsgDevMacro(<< " * Output Spacing: " << m_OutputSpacing); // Make sure that the state is clean: m_InputTransform = nullptr; m_OutputTransform = nullptr; bool inputTransformIsSensor = false; bool inputTransformIsMap = false; bool outputTransformIsSensor = false; bool outputTransformIsMap = false; //***************************** // Set the input transformation //***************************** // First, try to make a geo transform if (!m_InputProjectionRef.empty()) // map projection { typedef otb::GenericMapProjection<TransformDirection::INVERSE, ScalarType, InputSpaceDimension, InputSpaceDimension> InverseMapProjectionType; typename InverseMapProjectionType::Pointer mapTransform = InverseMapProjectionType::New(); mapTransform->SetWkt(m_InputProjectionRef); if (mapTransform->IsProjectionDefined()) { m_InputTransform = mapTransform.GetPointer(); inputTransformIsMap = true; otbMsgDevMacro(<< "Input projection set to map transform: " << m_InputTransform); } } // If not, try to make a RPC sensor model if ((m_InputTransform.IsNull()) && (m_InputImd->Has(MDGeom::RPC))) { typedef otb::RPCForwardTransform<double, InputSpaceDimension, OutputSpaceDimension> RPCForwardTransformType; typename RPCForwardTransformType::Pointer sensorModel = RPCForwardTransformType::New(); sensorModel->SetMetadataModel((*m_InputImd)[MDGeom::RPC]); if (sensorModel->IsValidSensorModel()) { //TODO: m_InputTransform = sensorModel.GetPointer(); inputTransformIsSensor = true; otbMsgDevMacro(<< "Input projection set to sensor model."); } } //***************************** // Set the output transformation //***************************** if (!m_OutputProjectionRef.empty()) // map projection { typedef otb::GenericMapProjection<TransformDirection::FORWARD, ScalarType, InputSpaceDimension, OutputSpaceDimension> ForwardMapProjectionType; typename ForwardMapProjectionType::Pointer mapTransform = ForwardMapProjectionType::New(); mapTransform->SetWkt(m_OutputProjectionRef); if (mapTransform->IsProjectionDefined()) { m_OutputTransform = mapTransform.GetPointer(); outputTransformIsMap = true; otbMsgDevMacro(<< "Output projection set to map transform: " << m_OutputTransform); } } // If not, try to make a RPC sensor model if ((m_OutputTransform.IsNull()) && (m_OutputImd->Has(MDGeom::RPC))) { typedef otb::RPCInverseTransform<double, InputSpaceDimension, OutputSpaceDimension> RPCInverseTransformType; typename RPCInverseTransformType::Pointer sensorModel = RPCInverseTransformType::New(); sensorModel->SetMetadataModel((*m_OutputImd)[MDGeom::RPC]); if (sensorModel->IsValidSensorModel()) { //TODO: m_OutputTransform = sensorModel.GetPointer(); outputTransformIsSensor = true; otbMsgDevMacro(<< "Output projection set to sensor model"); } } if (m_InputTransform.IsNull()) // default if we didn't manage to instantiate it before { // In this case, if output transform is set, we set // inputProjectionRef to wgs84 to ensure consistency if (outputTransformIsSensor || outputTransformIsMap) { m_InputProjectionRef = SpatialReference::FromWGS84().ToWkt(); } m_InputTransform = itk::IdentityTransform<double, NInputDimensions>::New(); } if (m_OutputTransform.IsNull()) // default if we didn't manage to instantiate it before { // In this case, if input transform is set, we set // outputProjectionRef to wgs84 to ensure consistency if (inputTransformIsSensor || inputTransformIsMap) { m_OutputProjectionRef = SpatialReference::FromWGS84().ToWkt(); } m_OutputTransform = itk::IdentityTransform<double, NOutputDimensions>::New(); otbMsgDevMacro(<< "Output projection set to identity"); } m_Transform->SetFirstTransform(m_InputTransform); m_Transform->SetSecondTransform(m_OutputTransform); m_TransformUpToDate = true; // The accuracy information is a simplistic model for now and should be refined if ((inputTransformIsSensor || outputTransformIsSensor)) { // Sensor model m_TransformAccuracy = Projection::ESTIMATE; } else if (!outputTransformIsSensor && !outputTransformIsMap) { // The original image was in lon/lat and we did not change anything m_TransformAccuracy = Projection::PRECISE; } else if (!inputTransformIsSensor && !outputTransformIsSensor && !inputTransformIsMap && !outputTransformIsMap) { // no transform m_TransformAccuracy = Projection::UNKNOWN; } else { m_TransformAccuracy = Projection::PRECISE; } } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::TransformPoint(const InputPointType& point) const { InputPointType inputPoint = point; // Apply input origin/spacing inputPoint[0] = inputPoint[0] * m_InputSpacing[0] + m_InputOrigin[0]; inputPoint[1] = inputPoint[1] * m_InputSpacing[1] + m_InputOrigin[1]; // Transform point OutputPointType outputPoint; outputPoint = this->GetTransform()->TransformPoint(inputPoint); // Apply output origin/spacing outputPoint[0] = (outputPoint[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; outputPoint[1] = (outputPoint[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; // otbMsgDevMacro("GenericRSTransform: " << point << " -> " << outputPoint); return outputPoint; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> bool GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GetInverse(Self* inverseTransform) const { // Test the inverseTransform pointer if (inverseTransform == nullptr) { return false; } // Swich projection refs inverseTransform->SetInputProjectionRef(m_OutputProjectionRef); inverseTransform->SetOutputProjectionRef(m_InputProjectionRef); // Switch ImageMetadatas inverseTransform->SetInputImageMetadata(m_OutputImd); inverseTransform->SetOutputImageMetadata(m_InputImd); // Switch spacings inverseTransform->SetInputSpacing(m_OutputSpacing); inverseTransform->SetOutputSpacing(m_InputSpacing); // Switch origins inverseTransform->SetInputOrigin(m_OutputOrigin); inverseTransform->SetOutputOrigin(m_InputOrigin); // Instantiate transform inverseTransform->InstantiateTransform(); return true; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::InverseTransformBasePointer GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GetInverseTransform() const { Self* inverseTransform = Self::New(); bool success = this->GetInverse(inverseTransform); if (!success) { itkExceptionMacro(<< "Failed to create inverse transform"); } return inverseTransform; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> void GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Up to date: " << m_TransformUpToDate << std::endl; if (m_TransformUpToDate) { os << indent << "Input transform: " << std::endl; m_InputTransform->Print(os, indent.GetNextIndent()); os << indent << "Output transform: " << std::endl; m_OutputTransform->Print(os, indent.GetNextIndent()); } else { os << indent << "Input transform: NULL" << std::endl; os << indent << "Output transform: NULL" << std::endl; } os << indent << "Accuracy: " << (m_TransformAccuracy == Projection::PRECISE ? "PRECISE" : (m_TransformAccuracy == Projection::ESTIMATE ? "ESTIMATE" : "UNKNOWN")) << std::endl; } } // namespace otb #endif <commit_msg>BUG: remove solved TODOs<commit_after>/* * 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. */ #ifndef otbGenericRSTransform_hxx #define otbGenericRSTransform_hxx #include "otbGenericRSTransform.h" #include "otbMacro.h" #include "otbMetaDataKey.h" #include "otbRPCForwardTransform.h" #include "otbRPCInverseTransform.h" #include "otbSpatialReference.h" #include "ogr_spatialref.h" namespace otb { template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GenericRSTransform() : Superclass(0) { m_InputProjectionRef.clear(); m_OutputProjectionRef.clear(); m_InputSpacing.Fill(1); m_InputOrigin.Fill(0); m_OutputSpacing.Fill(1); m_OutputOrigin.Fill(0); m_InputImd = nullptr; m_OutputImd = nullptr; m_Transform = nullptr; m_InputTransform = nullptr; m_OutputTransform = nullptr; m_TransformUpToDate = false; m_TransformAccuracy = Projection::UNKNOWN; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> const typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::TransformType* GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GetTransform() const { itkDebugMacro("returning MapProjection address " << this->m_Transform); if ((!m_TransformUpToDate) || (m_Transform.IsNull())) { itkExceptionMacro(<< "m_Transform not up-to-date, call InstantiateTransform() first"); } return this->m_Transform; } /** * Instantiate the transformation according to information */ template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> void GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::InstantiateTransform(void) { m_Transform = TransformType::New(); otbMsgDevMacro(<< "Information to instantiate transform: "); otbMsgDevMacro(<< " * Input Origin: " << m_InputOrigin); otbMsgDevMacro(<< " * Input Spacing: " << m_InputSpacing); otbMsgDevMacro(<< " * Input metadata: " << ((m_InputImd == nullptr) ? "Empty" : "Full")); otbMsgDevMacro(<< " * Input projection: " << m_InputProjectionRef); otbMsgDevMacro(<< " * Output metadata: " << ((m_OutputImd == nullptr) ? "Empty" : "Full")); otbMsgDevMacro(<< " * Output projection: " << m_OutputProjectionRef); otbMsgDevMacro(<< " * Output Origin: " << m_OutputOrigin); otbMsgDevMacro(<< " * Output Spacing: " << m_OutputSpacing); // Make sure that the state is clean: m_InputTransform = nullptr; m_OutputTransform = nullptr; bool inputTransformIsSensor = false; bool inputTransformIsMap = false; bool outputTransformIsSensor = false; bool outputTransformIsMap = false; //***************************** // Set the input transformation //***************************** // First, try to make a geo transform if (!m_InputProjectionRef.empty()) // map projection { typedef otb::GenericMapProjection<TransformDirection::INVERSE, ScalarType, InputSpaceDimension, InputSpaceDimension> InverseMapProjectionType; typename InverseMapProjectionType::Pointer mapTransform = InverseMapProjectionType::New(); mapTransform->SetWkt(m_InputProjectionRef); if (mapTransform->IsProjectionDefined()) { m_InputTransform = mapTransform.GetPointer(); inputTransformIsMap = true; otbMsgDevMacro(<< "Input projection set to map transform: " << m_InputTransform); } } // If not, try to make a RPC sensor model if ((m_InputTransform.IsNull()) && (m_InputImd->Has(MDGeom::RPC))) { typedef otb::RPCForwardTransform<double, InputSpaceDimension, OutputSpaceDimension> RPCForwardTransformType; typename RPCForwardTransformType::Pointer sensorModel = RPCForwardTransformType::New(); sensorModel->SetMetadataModel((*m_InputImd)[MDGeom::RPC]); if (sensorModel->IsValidSensorModel()) { m_InputTransform = sensorModel.GetPointer(); inputTransformIsSensor = true; otbMsgDevMacro(<< "Input projection set to sensor model."); } } //***************************** // Set the output transformation //***************************** if (!m_OutputProjectionRef.empty()) // map projection { typedef otb::GenericMapProjection<TransformDirection::FORWARD, ScalarType, InputSpaceDimension, OutputSpaceDimension> ForwardMapProjectionType; typename ForwardMapProjectionType::Pointer mapTransform = ForwardMapProjectionType::New(); mapTransform->SetWkt(m_OutputProjectionRef); if (mapTransform->IsProjectionDefined()) { m_OutputTransform = mapTransform.GetPointer(); outputTransformIsMap = true; otbMsgDevMacro(<< "Output projection set to map transform: " << m_OutputTransform); } } // If not, try to make a RPC sensor model if ((m_OutputTransform.IsNull()) && (m_OutputImd->Has(MDGeom::RPC))) { typedef otb::RPCInverseTransform<double, InputSpaceDimension, OutputSpaceDimension> RPCInverseTransformType; typename RPCInverseTransformType::Pointer sensorModel = RPCInverseTransformType::New(); sensorModel->SetMetadataModel((*m_OutputImd)[MDGeom::RPC]); if (sensorModel->IsValidSensorModel()) { m_OutputTransform = sensorModel.GetPointer(); outputTransformIsSensor = true; otbMsgDevMacro(<< "Output projection set to sensor model"); } } if (m_InputTransform.IsNull()) // default if we didn't manage to instantiate it before { // In this case, if output transform is set, we set // inputProjectionRef to wgs84 to ensure consistency if (outputTransformIsSensor || outputTransformIsMap) { m_InputProjectionRef = SpatialReference::FromWGS84().ToWkt(); } m_InputTransform = itk::IdentityTransform<double, NInputDimensions>::New(); } if (m_OutputTransform.IsNull()) // default if we didn't manage to instantiate it before { // In this case, if input transform is set, we set // outputProjectionRef to wgs84 to ensure consistency if (inputTransformIsSensor || inputTransformIsMap) { m_OutputProjectionRef = SpatialReference::FromWGS84().ToWkt(); } m_OutputTransform = itk::IdentityTransform<double, NOutputDimensions>::New(); otbMsgDevMacro(<< "Output projection set to identity"); } m_Transform->SetFirstTransform(m_InputTransform); m_Transform->SetSecondTransform(m_OutputTransform); m_TransformUpToDate = true; // The accuracy information is a simplistic model for now and should be refined if ((inputTransformIsSensor || outputTransformIsSensor)) { // Sensor model m_TransformAccuracy = Projection::ESTIMATE; } else if (!outputTransformIsSensor && !outputTransformIsMap) { // The original image was in lon/lat and we did not change anything m_TransformAccuracy = Projection::PRECISE; } else if (!inputTransformIsSensor && !outputTransformIsSensor && !inputTransformIsMap && !outputTransformIsMap) { // no transform m_TransformAccuracy = Projection::UNKNOWN; } else { m_TransformAccuracy = Projection::PRECISE; } } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::TransformPoint(const InputPointType& point) const { InputPointType inputPoint = point; // Apply input origin/spacing inputPoint[0] = inputPoint[0] * m_InputSpacing[0] + m_InputOrigin[0]; inputPoint[1] = inputPoint[1] * m_InputSpacing[1] + m_InputOrigin[1]; // Transform point OutputPointType outputPoint; outputPoint = this->GetTransform()->TransformPoint(inputPoint); // Apply output origin/spacing outputPoint[0] = (outputPoint[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; outputPoint[1] = (outputPoint[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; // otbMsgDevMacro("GenericRSTransform: " << point << " -> " << outputPoint); return outputPoint; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> bool GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GetInverse(Self* inverseTransform) const { // Test the inverseTransform pointer if (inverseTransform == nullptr) { return false; } // Swich projection refs inverseTransform->SetInputProjectionRef(m_OutputProjectionRef); inverseTransform->SetOutputProjectionRef(m_InputProjectionRef); // Switch ImageMetadatas inverseTransform->SetInputImageMetadata(m_OutputImd); inverseTransform->SetOutputImageMetadata(m_InputImd); // Switch spacings inverseTransform->SetInputSpacing(m_OutputSpacing); inverseTransform->SetOutputSpacing(m_InputSpacing); // Switch origins inverseTransform->SetInputOrigin(m_OutputOrigin); inverseTransform->SetOutputOrigin(m_InputOrigin); // Instantiate transform inverseTransform->InstantiateTransform(); return true; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::InverseTransformBasePointer GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::GetInverseTransform() const { Self* inverseTransform = Self::New(); bool success = this->GetInverse(inverseTransform); if (!success) { itkExceptionMacro(<< "Failed to create inverse transform"); } return inverseTransform; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> void GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Up to date: " << m_TransformUpToDate << std::endl; if (m_TransformUpToDate) { os << indent << "Input transform: " << std::endl; m_InputTransform->Print(os, indent.GetNextIndent()); os << indent << "Output transform: " << std::endl; m_OutputTransform->Print(os, indent.GetNextIndent()); } else { os << indent << "Input transform: NULL" << std::endl; os << indent << "Output transform: NULL" << std::endl; } os << indent << "Accuracy: " << (m_TransformAccuracy == Projection::PRECISE ? "PRECISE" : (m_TransformAccuracy == Projection::ESTIMATE ? "ESTIMATE" : "UNKNOWN")) << std::endl; } } // namespace otb #endif <|endoftext|>
<commit_before><commit_msg>delegate/Client: use class Event<commit_after><|endoftext|>
<commit_before>#include "generator.h" #include <fstream> #include <sstream> #include <string> #include <assert.h> #include <arpa/inet.h> #include <string> #include <map> using namespace std; int main (void) { int ad_id, isd_id, isCore, registerPath, as1, as2, rel, nbrType1, port = 33000, nbrType2, ifId1, ifId2, nbrTd1, nbrTd2, nbrAd1, nbrAd2, numTDs; string line, ip_address = "127.0.0.1", tmp_ip_address = "127.0.0.1"; ifstream asRel, asInfo; ofstream runNet, netIPs; map<int, SCIONScriptGen*> asList; //Write the SCION run script runNet.open("run.sh"); runNet << "#!/bin/bash\n\n"; runNet.close(); asInfo.open("ADToISD"); while (getline(asInfo, line)) { istringstream iss(line); iss >> ad_id >> isd_id >> isCore; registerPath = (isCore==2 || isCore==0) ? 1 : 0; isCore = (isCore==0) ? 1 : 0; asList[ad_id-1] = new SCIONScriptGen(ad_id, isCore, isd_id, 1234567890, 1919191919, ip_address, registerPath); asList[ad_id-1]->GenerateAllConf (ip_address); } asInfo.close(); asRel.open("ADRelationships"); while (getline(asRel, line)) { istringstream iss(line); iss >> as1 >> as2 >> rel; ifId1 = 1; ifId2 = 1; nbrTd1 = 0; nbrTd2 = 0; nbrAd1 = as2; nbrAd2 = as1; if (rel == 0) { nbrType1 = PEER; nbrType2 = PEER; } else if (rel == -1) { nbrType1 = CHILD; nbrType2 = PARENT; } else if (rel == 1) { nbrType1 = ROUTING; nbrType2 = ROUTING; nbrTd1 = asList[as2-1]->GetISDId (); nbrTd2 = asList[as1-1]->GetISDId (); } Router rtr1(IPV4, ifId1, nbrTd1, nbrAd1, nbrType1, IPV4, (const char*)(asList[as1-1]->GetIpAddress()).c_str(), (const char*)(asList[as2-1]->GetIpAddress()).c_str(), port, port); asList[as1-1]->AddRouter(&rtr1, ip_address); Router rtr2(IPV4, ifId2, nbrTd2, nbrAd2, nbrType2, IPV4, (const char*)(asList[as2-1]->GetIpAddress()).c_str(), (const char*)(asList[as1-1]->GetIpAddress()).c_str(), port, port); asList[as2-1]->AddRouter(&rtr2, ip_address); port++; } asRel.close(); for(map<int, SCIONScriptGen*>::iterator it = asList.begin(); it != asList.end(); it++) { delete it->second; } //Write the SCION setup script netIPs.open("setup.sh"); netIPs << "#!/bin/bash\n\n"; while (tmp_ip_address != ip_address) { netIPs << "ip addr add " << tmp_ip_address << "/8 " << "dev lo\n"; tmp_ip_address = increment_address((const char*)tmp_ip_address.c_str()); } netIPs.close(); return 0; } <commit_msg>changed edge routers port range<commit_after>#include "generator.h" #include <fstream> #include <sstream> #include <string> #include <assert.h> #include <arpa/inet.h> #include <string> #include <map> using namespace std; int main (void) { int ad_id, isd_id, isCore, registerPath, as1, as2, rel, nbrType1, port = 50000, nbrType2, ifId1, ifId2, nbrTd1, nbrTd2, nbrAd1, nbrAd2, numTDs; string line, ip_address = "127.0.0.1", tmp_ip_address = "127.0.0.1"; ifstream asRel, asInfo; ofstream runNet, netIPs; map<int, SCIONScriptGen*> asList; //Write the SCION run script runNet.open("run.sh"); runNet << "#!/bin/bash\n\n"; runNet.close(); asInfo.open("ADToISD"); while (getline(asInfo, line)) { istringstream iss(line); iss >> ad_id >> isd_id >> isCore; registerPath = (isCore==2 || isCore==0) ? 1 : 0; isCore = (isCore==0) ? 1 : 0; asList[ad_id-1] = new SCIONScriptGen(ad_id, isCore, isd_id, 1234567890, 1919191919, ip_address, registerPath); asList[ad_id-1]->GenerateAllConf (ip_address); } asInfo.close(); asRel.open("ADRelationships"); while (getline(asRel, line)) { istringstream iss(line); iss >> as1 >> as2 >> rel; ifId1 = 1; ifId2 = 1; nbrTd1 = 0; nbrTd2 = 0; nbrAd1 = as2; nbrAd2 = as1; if (rel == 0) { nbrType1 = PEER; nbrType2 = PEER; } else if (rel == -1) { nbrType1 = CHILD; nbrType2 = PARENT; } else if (rel == 1) { nbrType1 = ROUTING; nbrType2 = ROUTING; nbrTd1 = asList[as2-1]->GetISDId (); nbrTd2 = asList[as1-1]->GetISDId (); } Router rtr1(IPV4, ifId1, nbrTd1, nbrAd1, nbrType1, IPV4, (const char*)(asList[as1-1]->GetIpAddress()).c_str(), (const char*)(asList[as2-1]->GetIpAddress()).c_str(), port, port); asList[as1-1]->AddRouter(&rtr1, ip_address); Router rtr2(IPV4, ifId2, nbrTd2, nbrAd2, nbrType2, IPV4, (const char*)(asList[as2-1]->GetIpAddress()).c_str(), (const char*)(asList[as1-1]->GetIpAddress()).c_str(), port, port); asList[as2-1]->AddRouter(&rtr2, ip_address); port++; } asRel.close(); for(map<int, SCIONScriptGen*>::iterator it = asList.begin(); it != asList.end(); it++) { delete it->second; } //Write the SCION setup script netIPs.open("setup.sh"); netIPs << "#!/bin/bash\n\n"; while (tmp_ip_address != ip_address) { netIPs << "ip addr add " << tmp_ip_address << "/8 " << "dev lo\n"; tmp_ip_address = increment_address((const char*)tmp_ip_address.c_str()); } netIPs.close(); return 0; } <|endoftext|>
<commit_before>#include <ROOT/TDataFrame.hxx> #include <ROOT/TTrivialDS.hxx> #include <ROOT/TSeq.hxx> #include "gtest/gtest.h" using namespace ROOT::Experimental; using namespace ROOT::Experimental::TDF; TEST(TTrivialDS, ColTypeNames) { TTrivialDS tds(32); tds.SetNSlots(1); auto colName = tds.GetColumnNames()[0]; // We know it's one. EXPECT_STREQ("col0", colName.c_str()); EXPECT_STREQ("ULong64_t", tds.GetTypeName("col0").c_str()); EXPECT_TRUE(tds.HasColumn("col0")); EXPECT_FALSE(tds.HasColumn("col1")); } TEST(TTrivialDS, EntryRanges) { TTrivialDS tds(32); const auto nSlots = 4U; tds.SetNSlots(nSlots); tds.Initialise(); auto ranges = tds.GetEntryRanges(); EXPECT_EQ(4U, ranges.size()); EXPECT_EQ(0U, ranges[0].first); EXPECT_EQ(8U, ranges[0].second); EXPECT_EQ(8U, ranges[1].first); EXPECT_EQ(16U, ranges[1].second); EXPECT_EQ(16U, ranges[2].first); EXPECT_EQ(24U, ranges[2].second); EXPECT_EQ(24U, ranges[3].first); EXPECT_EQ(32U, ranges[3].second); } TEST(TTrivialDS, ColumnReaders) { TTrivialDS tds(32); const auto nSlots = 4U; tds.SetNSlots(nSlots); auto vals = tds.GetColumnReaders<ULong64_t>("col0"); tds.Initialise(); auto ranges = tds.GetEntryRanges(); auto slot = 0U; for (auto &&range : ranges) { for (auto i : ROOT::TSeq<ULong64_t>(range.first, range.second)) { tds.SetEntry(slot, i); auto val = **vals[slot]; EXPECT_EQ(i, val); } slot++; } } TEST(TTrivialDS, ColumnReadersWrongType) { TTrivialDS tds(32); const auto nSlots = 4U; tds.SetNSlots(nSlots); int res = 1; try { auto vals = tds.GetColumnReaders<float>("col0"); } catch (const std::runtime_error &e) { EXPECT_STREQ("The type specified for the column col0 is not ULong64_t.", e.what()); res = 0; } EXPECT_EQ(0, res); } #ifndef NDEBUG TEST(TTrivialDS, SetNSlotsTwice) { auto theTest = []() { TTrivialDS tds(1); tds.SetNSlots(1); tds.SetNSlots(1); }; ASSERT_DEATH(theTest(), "Setting the number of slots even if the number of slots is different from zero."); } #endif TEST(TTrivialDS, FromATDF) { std::unique_ptr<TDataSource> tds(new TTrivialDS(32)); TDataFrame tdf(std::move(tds)); auto max = tdf.Max<ULong64_t>("col0"); auto min = tdf.Min<ULong64_t>("col0"); auto c = tdf.Count(); auto max2 = tdf.Filter([](ULong64_t col0) { return col0 < 10; }, {"col0"}).Max<ULong64_t>("col0"); auto min2 = tdf.Filter([](ULong64_t col0) { return col0 > 10; }, {"col0"}) .Define("j", [](ULong64_t col0) { return col0 * 2; }, {"col0"}) .Min<ULong64_t>("j"); EXPECT_EQ(32U, *c); EXPECT_DOUBLE_EQ(31., *max); EXPECT_DOUBLE_EQ(0., *min); EXPECT_DOUBLE_EQ(9., *max2); EXPECT_DOUBLE_EQ(22., *min2); } #ifdef R__B64 TEST(TTrivialDS, FromATDFWithJitting) { std::unique_ptr<TDataSource> tds(new TTrivialDS(32)); TDataFrame tdf(std::move(tds)); auto max = tdf.Filter("col0 < 10").Max("col0"); auto min = tdf.Filter("col0 > 10").Define("j", "col0*2").Min("j"); EXPECT_DOUBLE_EQ(9., *max); EXPECT_DOUBLE_EQ(22., *min); } // NOW MT!------------- #ifdef R__USE_IMT TEST(TTrivialDS, DefineSlotCheckMT) { const auto nSlots = 4U; ROOT::EnableImplicitMT(nSlots); std::vector<unsigned int> ids(nSlots, 0u); std::unique_ptr<TDataSource> tds(new TTrivialDS(nSlots)); TDataFrame d(std::move(tds)); auto m = d.DefineSlot("x", [&](unsigned int slot) { ids[slot] = 1u; return 1; }).Max("x"); EXPECT_EQ(1, *m); // just in case const auto nUsedSlots = std::accumulate(ids.begin(), ids.end(), 0u); EXPECT_GT(nUsedSlots, 0u); EXPECT_LE(nUsedSlots, nSlots); ROOT::DisableImplicitMT(); } TEST(TTrivialDS, FromATDFMT) { std::unique_ptr<TDataSource> tds(new TTrivialDS(320)); TDataFrame tdf(std::move(tds)); auto max = tdf.Max<ULong64_t>("col0"); auto min = tdf.Min<ULong64_t>("col0"); auto c = tdf.Count(); auto max2 = tdf.Filter([](ULong64_t col0) { return col0 < 10; }, {"col0"}).Max<ULong64_t>("col0"); auto min2 = tdf.Filter([](ULong64_t col0) { return col0 > 10; }, {"col0"}) .Define("j", [](ULong64_t col0) { return col0 * 2; }, {"col0"}) .Min<ULong64_t>("j"); EXPECT_EQ(320U, *c); EXPECT_DOUBLE_EQ(319., *max); EXPECT_DOUBLE_EQ(0., *min); EXPECT_DOUBLE_EQ(9., *max2); EXPECT_DOUBLE_EQ(22., *min2); } TEST(TTrivialDS, FromATDFWithJittingMT) { std::unique_ptr<TDataSource> tds(new TTrivialDS(320)); TDataFrame tdf(std::move(tds)); auto max = tdf.Filter("col0 < 10").Max("col0"); auto min = tdf.Filter("col0 > 10").Define("j", "col0*2").Min("j"); EXPECT_DOUBLE_EQ(9., *max); EXPECT_DOUBLE_EQ(22., *min); } TEST(TTrivialDS, Snapshot) { std::unique_ptr<TDataSource> tds(new TTrivialDS(10)); TDataFrame tdf(std::move(tds)); auto tdf2 = tdf.Snapshot("t", "f.root", "col0"); auto c = tdf2.Take<ULong64_t>("col0"); auto i = 0u; for (auto e : c) { EXPECT_EQ(e, i); ++i; } } TEST(TTrivialDS, Cache) { std::unique_ptr<TDataSource> tds(new TTrivialDS(10)); TDataFrame tdf(std::move(tds)); auto tdfCached = tdf.Cache("col0"); auto c = tdfCached.Take<ULong64_t>("col0"); auto i = 0u; for (auto e : c) { EXPECT_EQ(e, i); ++i; } } #endif // R__USE_IMT #endif // R__B64 <commit_msg>[TDF] Adjust reference in the test<commit_after>#include <ROOT/TDataFrame.hxx> #include <ROOT/TTrivialDS.hxx> #include <ROOT/TSeq.hxx> #include "gtest/gtest.h" using namespace ROOT::Experimental; using namespace ROOT::Experimental::TDF; TEST(TTrivialDS, ColTypeNames) { TTrivialDS tds(32); tds.SetNSlots(1); auto colName = tds.GetColumnNames()[0]; // We know it's one. EXPECT_STREQ("col0", colName.c_str()); EXPECT_STREQ("ULong64_t", tds.GetTypeName("col0").c_str()); EXPECT_TRUE(tds.HasColumn("col0")); EXPECT_FALSE(tds.HasColumn("col1")); } TEST(TTrivialDS, EntryRanges) { TTrivialDS tds(32); const auto nSlots = 4U; tds.SetNSlots(nSlots); tds.Initialise(); auto ranges = tds.GetEntryRanges(); EXPECT_EQ(4U, ranges.size()); EXPECT_EQ(0U, ranges[0].first); EXPECT_EQ(8U, ranges[0].second); EXPECT_EQ(8U, ranges[1].first); EXPECT_EQ(16U, ranges[1].second); EXPECT_EQ(16U, ranges[2].first); EXPECT_EQ(24U, ranges[2].second); EXPECT_EQ(24U, ranges[3].first); EXPECT_EQ(32U, ranges[3].second); } TEST(TTrivialDS, ColumnReaders) { TTrivialDS tds(32); const auto nSlots = 4U; tds.SetNSlots(nSlots); auto vals = tds.GetColumnReaders<ULong64_t>("col0"); tds.Initialise(); auto ranges = tds.GetEntryRanges(); auto slot = 0U; for (auto &&range : ranges) { for (auto i : ROOT::TSeq<ULong64_t>(range.first, range.second)) { tds.SetEntry(slot, i); auto val = **vals[slot]; EXPECT_EQ(i, val); } slot++; } } TEST(TTrivialDS, ColumnReadersWrongType) { TTrivialDS tds(32); const auto nSlots = 4U; tds.SetNSlots(nSlots); int res = 1; try { auto vals = tds.GetColumnReaders<float>("col0"); } catch (const std::runtime_error &e) { EXPECT_STREQ("The type specified for the column \"col0\" is not ULong64_t.", e.what()); res = 0; } EXPECT_EQ(0, res); } #ifndef NDEBUG TEST(TTrivialDS, SetNSlotsTwice) { auto theTest = []() { TTrivialDS tds(1); tds.SetNSlots(1); tds.SetNSlots(1); }; ASSERT_DEATH(theTest(), "Setting the number of slots even if the number of slots is different from zero."); } #endif TEST(TTrivialDS, FromATDF) { std::unique_ptr<TDataSource> tds(new TTrivialDS(32)); TDataFrame tdf(std::move(tds)); auto max = tdf.Max<ULong64_t>("col0"); auto min = tdf.Min<ULong64_t>("col0"); auto c = tdf.Count(); auto max2 = tdf.Filter([](ULong64_t col0) { return col0 < 10; }, {"col0"}).Max<ULong64_t>("col0"); auto min2 = tdf.Filter([](ULong64_t col0) { return col0 > 10; }, {"col0"}) .Define("j", [](ULong64_t col0) { return col0 * 2; }, {"col0"}) .Min<ULong64_t>("j"); EXPECT_EQ(32U, *c); EXPECT_DOUBLE_EQ(31., *max); EXPECT_DOUBLE_EQ(0., *min); EXPECT_DOUBLE_EQ(9., *max2); EXPECT_DOUBLE_EQ(22., *min2); } #ifdef R__B64 TEST(TTrivialDS, FromATDFWithJitting) { std::unique_ptr<TDataSource> tds(new TTrivialDS(32)); TDataFrame tdf(std::move(tds)); auto max = tdf.Filter("col0 < 10").Max("col0"); auto min = tdf.Filter("col0 > 10").Define("j", "col0*2").Min("j"); EXPECT_DOUBLE_EQ(9., *max); EXPECT_DOUBLE_EQ(22., *min); } // NOW MT!------------- #ifdef R__USE_IMT TEST(TTrivialDS, DefineSlotCheckMT) { const auto nSlots = 4U; ROOT::EnableImplicitMT(nSlots); std::vector<unsigned int> ids(nSlots, 0u); std::unique_ptr<TDataSource> tds(new TTrivialDS(nSlots)); TDataFrame d(std::move(tds)); auto m = d.DefineSlot("x", [&](unsigned int slot) { ids[slot] = 1u; return 1; }).Max("x"); EXPECT_EQ(1, *m); // just in case const auto nUsedSlots = std::accumulate(ids.begin(), ids.end(), 0u); EXPECT_GT(nUsedSlots, 0u); EXPECT_LE(nUsedSlots, nSlots); ROOT::DisableImplicitMT(); } TEST(TTrivialDS, FromATDFMT) { std::unique_ptr<TDataSource> tds(new TTrivialDS(320)); TDataFrame tdf(std::move(tds)); auto max = tdf.Max<ULong64_t>("col0"); auto min = tdf.Min<ULong64_t>("col0"); auto c = tdf.Count(); auto max2 = tdf.Filter([](ULong64_t col0) { return col0 < 10; }, {"col0"}).Max<ULong64_t>("col0"); auto min2 = tdf.Filter([](ULong64_t col0) { return col0 > 10; }, {"col0"}) .Define("j", [](ULong64_t col0) { return col0 * 2; }, {"col0"}) .Min<ULong64_t>("j"); EXPECT_EQ(320U, *c); EXPECT_DOUBLE_EQ(319., *max); EXPECT_DOUBLE_EQ(0., *min); EXPECT_DOUBLE_EQ(9., *max2); EXPECT_DOUBLE_EQ(22., *min2); } TEST(TTrivialDS, FromATDFWithJittingMT) { std::unique_ptr<TDataSource> tds(new TTrivialDS(320)); TDataFrame tdf(std::move(tds)); auto max = tdf.Filter("col0 < 10").Max("col0"); auto min = tdf.Filter("col0 > 10").Define("j", "col0*2").Min("j"); EXPECT_DOUBLE_EQ(9., *max); EXPECT_DOUBLE_EQ(22., *min); } TEST(TTrivialDS, Snapshot) { std::unique_ptr<TDataSource> tds(new TTrivialDS(10)); TDataFrame tdf(std::move(tds)); auto tdf2 = tdf.Snapshot("t", "f.root", "col0"); auto c = tdf2.Take<ULong64_t>("col0"); auto i = 0u; for (auto e : c) { EXPECT_EQ(e, i); ++i; } } TEST(TTrivialDS, Cache) { std::unique_ptr<TDataSource> tds(new TTrivialDS(10)); TDataFrame tdf(std::move(tds)); auto tdfCached = tdf.Cache("col0"); auto c = tdfCached.Take<ULong64_t>("col0"); auto i = 0u; for (auto e : c) { EXPECT_EQ(e, i); ++i; } } #endif // R__USE_IMT #endif // R__B64 <|endoftext|>
<commit_before>// Deadfrog includes #include "df_bmp.h" #include "df_font.h" #include "df_time.h" #include "df_window.h" #include "fonts/df_mono.h" // Standard includes #include <math.h> void StretchBlitMain() { CreateWin(1024, 768, WT_WINDOWED, "Stretch Blit Example"); g_defaultFont = LoadFontFromMemory(deadfrog_mono_7x13, sizeof(deadfrog_mono_7x13)); DfBitmap *dogBmp = LoadBmp("marlieses_dog.bmp"); if (!dogBmp) { dogBmp = LoadBmp("../../marlieses_dog.bmp"); } ReleaseAssert(dogBmp, "Couldn't load marlieses_dog.bmp"); // Animate the stretch blit. while (!g_input.keyDowns[KEY_SPACE]) { InputPoll(); if (g_window->windowClosed || g_input.keys[KEY_ESC]) return; BitmapClear(g_window->bmp, g_colourBlack); double time = GetRealTime(); float scale = 0.1f + fabs(sin(time * 1.9) * 1.2); int targetWidth = dogBmp->width * scale; int targetHeight = dogBmp->width * scale; int x = g_window->bmp->width * (0.5f + 0.2 * sin(time * 1.5)) - targetHeight / 2.0f; int y = g_window->bmp->height * (0.5f + 0.2 * sin(time * 1.3)) - targetWidth / 2.0f; StretchBlit(g_window->bmp, x, y, targetWidth, targetHeight, dogBmp); UpdateWin(); WaitVsync(); } // Benchmark the stretch blit. while (!g_window->windowClosed && !g_input.keys[KEY_ESC]) { InputPoll(); BitmapClear(g_window->bmp, g_colourBlack); double time1 = GetRealTime(); int targetWidth = dogBmp->width * 0.1; int targetHeight = dogBmp->width * 0.1; StretchBlit(g_window->bmp, 10, 15, targetWidth, targetHeight, dogBmp); double time2 = GetRealTime(); targetWidth = dogBmp->width * 0.7; targetHeight = dogBmp->width * 0.7; StretchBlit(g_window->bmp, 100, 15, targetWidth, targetHeight, dogBmp); double time3 = GetRealTime(); targetWidth = dogBmp->width * 2.0; targetHeight = dogBmp->width * 2.0; StretchBlit(g_window->bmp, 400, 15, targetWidth, targetHeight, dogBmp); double time4 = GetRealTime(); DrawTextLeft(g_defaultFont, g_colourWhite, g_window->bmp, 10, 0, "%.2fms", (time2 - time1) * 1000.0f); DrawTextLeft(g_defaultFont, g_colourWhite, g_window->bmp, 100, 0, "%.2fms", (time3 - time2) * 1000.0f); DrawTextLeft(g_defaultFont, g_colourWhite, g_window->bmp, 400, 0, "%.2fms", (time4 - time3) * 1000.0f); UpdateWin(); WaitVsync(); } } <commit_msg>Made the StretchBlit example exercise the clipping.<commit_after>// Deadfrog includes #include "df_bmp.h" #include "df_font.h" #include "df_time.h" #include "df_window.h" #include "fonts/df_mono.h" // Standard includes #include <math.h> void StretchBlitMain() { CreateWin(1024, 768, WT_WINDOWED, "Stretch Blit Example"); g_defaultFont = LoadFontFromMemory(deadfrog_mono_7x13, sizeof(deadfrog_mono_7x13)); DfBitmap *dogBmp = LoadBmp("marlieses_dog.bmp"); if (!dogBmp) { dogBmp = LoadBmp("../../marlieses_dog.bmp"); } ReleaseAssert(dogBmp, "Couldn't load marlieses_dog.bmp"); // Animate the stretch blit. while (!g_input.keyDowns[KEY_SPACE]) { InputPoll(); if (g_window->windowClosed || g_input.keys[KEY_ESC]) return; BitmapClear(g_window->bmp, g_colourBlack); double time = GetRealTime(); float scale = 0.2f + powf(fabs(sin(time * 1.9) * 1.2), 2.0); int targetWidth = dogBmp->width * scale; int targetHeight = dogBmp->width * scale; int x = g_window->bmp->width * (0.5f + 0.7 * sin(time * 2.5)) - targetHeight / 2.0f; int y = g_window->bmp->height * (0.5f + 0.7 * sin(time * 1.3)) - targetWidth / 2.0f; StretchBlit(g_window->bmp, x, y, targetWidth, targetHeight, dogBmp); UpdateWin(); WaitVsync(); } // Benchmark the stretch blit. while (!g_window->windowClosed && !g_input.keys[KEY_ESC]) { InputPoll(); BitmapClear(g_window->bmp, g_colourBlack); double time1 = GetRealTime(); int targetWidth = dogBmp->width * 0.1; int targetHeight = dogBmp->width * 0.1; StretchBlit(g_window->bmp, 10, 15, targetWidth, targetHeight, dogBmp); double time2 = GetRealTime(); targetWidth = dogBmp->width * 0.7; targetHeight = dogBmp->width * 0.7; StretchBlit(g_window->bmp, 100, 15, targetWidth, targetHeight, dogBmp); double time3 = GetRealTime(); targetWidth = dogBmp->width * 2.0; targetHeight = dogBmp->width * 2.0; StretchBlit(g_window->bmp, 400, 15, targetWidth, targetHeight, dogBmp); double time4 = GetRealTime(); DrawTextLeft(g_defaultFont, g_colourWhite, g_window->bmp, 10, 0, "%.2fms", (time2 - time1) * 1000.0f); DrawTextLeft(g_defaultFont, g_colourWhite, g_window->bmp, 100, 0, "%.2fms", (time3 - time2) * 1000.0f); DrawTextLeft(g_defaultFont, g_colourWhite, g_window->bmp, 400, 0, "%.2fms", (time4 - time3) * 1000.0f); UpdateWin(); WaitVsync(); } } <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "../basic/TConfig.h" #if defined(TYR_WINDOWS) # include <WinSock2.h> # include <Windows.h> #else # include <sys/socket.h> # include <fcntl.h> # include <unistd.h> #endif #include <errno.h> #include <stdio.h> #include "../basic/TLogging.h" #include "unexposed/TSocketSupportUnexposed.h" #include "TSocketSupport.h" namespace tyr { namespace net { namespace SocketSupport { int kern_socket(int family) { int sockfd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (sockfd < 0) TL_SYSFATAL << "SocketSupport::kern_socket failed"; unexposed::kern_set_nonblock(sockfd); return sockfd; } int kern_bind(int sockfd, const struct sockaddr* addr) { socklen_t addrlen = static_cast<socklen_t>(sizeof(struct sockaddr_in6)); int rc = bind(sockfd, addr, addrlen); if (rc < 0) TL_SYSFATAL << "SocketSupport::kern_bind failed"; return 0; } int kern_listen(int sockfd) { int rc = listen(sockfd, SOMAXCONN); if (rc < 0) TL_SYSFATAL << "SocketSupport::kern_listen failed"; return 0; } int kern_accept(int sockfd, struct sockaddr_in6* addr) { socklen_t addrlen = static_cast<socklen_t>(sizeof(*addr)); int connfd = accept(sockfd, kern_sockaddr_cast(addr), &addrlen); unexposed::kern_set_nonblock(connfd); if (connfd < 0) { int saved_errno = errno; TL_SYSERR << "SocketSupport::kern_accept failed"; switch (saved_errno) { } } return connfd; } int kern_connect(int sockfd, const struct sockaddr* addr) { return connect(sockfd, addr, static_cast<socklen_t>(sizeof(struct sockaddr_in6))); } // int kern_shutdown(int sockfd); // int kern_close(int sockfd); // // void kern_to_ip_port(char* buf, size_t len, const struct sockaddr* addr); // void kern_to_ip(char* buf, size_t len, const struct sockaddr* addr); // void kern_from_ip_port(const char* ip, uint16_t port, struct sockaddr_in* addr); // void kern_from_ip_port(const char* ip, uint16_t port, struct sockaddr_in6* addr); // // int kern_socket_error(int fd); const struct sockaddr* kern_sockaddr_cast(const struct sockaddr_in* addr) { return static_cast<const struct sockaddr*>(tyr::basic::implicit_cast<const void*>(addr)); } const struct sockaddr* kern_sockaddr_cast(const struct sockaddr_in6* addr) { return static_cast<const struct sockaddr*>(tyr::basic::implicit_cast<const void*>(addr)); } struct sockaddr* kern_sockaddr_cast(struct sockaddr_in6* addr) { return static_cast<struct sockaddr*>(tyr::basic::implicit_cast<void*>(addr)); } const struct sockaddr_in* kern_sockaddr_in_cast(const struct sockaddr* addr) { return static_cast<const struct sockaddr_in*>(tyr::basic::implicit_cast<const void*>(addr)); } const struct sockaddr_in6* kern_sockaddr_in6_cast(const struct sockaddr* addr) { return static_cast<const struct sockaddr_in6*>(tyr::basic::implicit_cast<const void*>(addr)); } // struct sockaddr_in6 kern_localaddr(int fd); // struct sockaddr_in6 kern_peekaddr(int fd); // bool kern_is_self_connect(int fd); } }} <commit_msg>chore(tyr.net): updated the socket supporting implementation<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "../basic/TConfig.h" #if defined(TYR_WINDOWS) # include <WinSock2.h> # include <Windows.h> #else # include <sys/socket.h> # include <fcntl.h> # include <unistd.h> #endif #include <errno.h> #include <stdio.h> #include "../basic/TLogging.h" #include "TEndian.h" #include "unexposed/TSocketSupportUnexposed.h" #include "TSocketSupport.h" namespace tyr { namespace net { namespace SocketSupport { int kern_socket(int family) { int sockfd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (sockfd < 0) TL_SYSFATAL << "SocketSupport::kern_socket failed"; unexposed::kern_set_nonblock(sockfd); return sockfd; } int kern_bind(int sockfd, const struct sockaddr* addr) { socklen_t addrlen = static_cast<socklen_t>(sizeof(struct sockaddr_in6)); int rc = bind(sockfd, addr, addrlen); if (rc < 0) TL_SYSFATAL << "SocketSupport::kern_bind failed"; return 0; } int kern_listen(int sockfd) { int rc = listen(sockfd, SOMAXCONN); if (rc < 0) TL_SYSFATAL << "SocketSupport::kern_listen failed"; return 0; } int kern_accept(int sockfd, struct sockaddr_in6* addr) { socklen_t addrlen = static_cast<socklen_t>(sizeof(*addr)); int connfd = accept(sockfd, kern_sockaddr_cast(addr), &addrlen); unexposed::kern_set_nonblock(connfd); if (connfd < 0) { int saved_errno = errno; TL_SYSERR << "SocketSupport::kern_accept failed"; switch (saved_errno) { } } return connfd; } int kern_connect(int sockfd, const struct sockaddr* addr) { return connect(sockfd, addr, static_cast<socklen_t>(sizeof(struct sockaddr_in6))); } void kern_to_ip_port(char* buf, size_t len, const struct sockaddr* addr) { kern_to_ip(buf, len, addr); size_t end = strlen(buf); const struct sockaddr_in* addr4 = kern_sockaddr_in_cast(addr); uint16_t port = net_to_host16(addr4->sin_port); snprintf(buf + end, len - end, ":%u", port); } int kern_socket_error(int sockfd) { char optval; socklen_t optlen = static_cast<socklen_t>(sizeof(optval)); if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0) return errno; else return optval; } const struct sockaddr* kern_sockaddr_cast(const struct sockaddr_in* addr) { return static_cast<const struct sockaddr*>(tyr::basic::implicit_cast<const void*>(addr)); } const struct sockaddr* kern_sockaddr_cast(const struct sockaddr_in6* addr) { return static_cast<const struct sockaddr*>(tyr::basic::implicit_cast<const void*>(addr)); } struct sockaddr* kern_sockaddr_cast(struct sockaddr_in6* addr) { return static_cast<struct sockaddr*>(tyr::basic::implicit_cast<void*>(addr)); } const struct sockaddr_in* kern_sockaddr_in_cast(const struct sockaddr* addr) { return static_cast<const struct sockaddr_in*>(tyr::basic::implicit_cast<const void*>(addr)); } const struct sockaddr_in6* kern_sockaddr_in6_cast(const struct sockaddr* addr) { return static_cast<const struct sockaddr_in6*>(tyr::basic::implicit_cast<const void*>(addr)); } struct sockaddr_in6 kern_localaddr(int sockfd) { struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); socklen_t addrlen = static_cast<socklen_t>(sizeof(addr)); if (getsockname(sockfd, kern_sockaddr_cast(&addr), &addrlen) < 0) TL_SYSERR << "SocketSupport::kern_localaddr failed"; return addr; } struct sockaddr_in6 kern_peekaddr(int sockfd) { struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); socklen_t addrlen = static_cast<socklen_t>(sizeof(addr)); if (getpeername(sockfd, kern_sockaddr_cast(&addr), &addrlen) < 0) TL_SYSERR << "SocketSupport::kern_peekaddr failed"; return addr; } // bool kern_is_self_connect(int fd); } }} <|endoftext|>
<commit_before>// // key-chain-manager.cpp // // Created by Peter Gusev on 02 September 2016. // Copyright 2013-2016 Regents of the University of California // #include "key-chain-manager.hpp" #include <algorithm> #include <ndn-cpp/security/key-chain.hpp> #include <ndn-cpp/security/certificate/identity-certificate.hpp> #include <ndn-cpp/security/identity/memory-identity-storage.hpp> #include <ndn-cpp/security/identity/memory-private-key-storage.hpp> #include <ndn-cpp/security/policy/config-policy-manager.hpp> #include <ndn-cpp/security/policy/self-verify-policy-manager.hpp> #include <ndn-cpp/security/v2/certificate-cache-v2.hpp> #include <ndn-cpp/security/pib/pib-memory.hpp> #include <ndn-cpp/security/tpm/tpm-back-end-memory.hpp> #include <ndn-cpp/security/signing-info.hpp> #include <ndn-cpp/face.hpp> #include <ndnrtc/simple-log.hpp> #include <boost/chrono.hpp> using namespace boost::chrono; using namespace ndn; KeyChainManager::KeyChainManager(boost::shared_ptr<Face> face, const std::string& identityNameStr, const std::string& instanceNameStr, const std::string& configPolicy, unsigned int runTime): face_(face), signingIdentity_(identityNameStr), instanceName_(instanceNameStr), configPolicy_(configPolicy), runTime_(runTime) { checkExists(configPolicy); setupDefaultKeyChain(); setupConfigPolicyManager(); setupInstanceKeyChain(); } void KeyChainManager::setupDefaultKeyChain() { defaultKeyChain_ = boost::make_shared<ndn::KeyChain>(); } void KeyChainManager::setupInstanceKeyChain() { Name signingIdentity(signingIdentity_); std::vector<Name> identities; if (defaultKeyChain_->getIsSecurityV1()) { defaultKeyChain_->getIdentityManager()->getAllIdentities(identities, false); defaultKeyChain_->getIdentityManager()->getAllIdentities(identities, true); } else defaultKeyChain_->getPib().getAllIdentityNames(identities); if (std::find(identities.begin(), identities.end(), signingIdentity) == identities.end()) { // create signing identity in default keychain LogInfo("") << "Signing identity not found. Creating..." << std::endl; createSigningIdentity(); } createMemoryKeychain(); if (defaultKeyChain_->getIsSecurityV1()) createInstanceIdentity(); else createInstanceIdentityV2(); } void KeyChainManager::setupConfigPolicyManager() { identityStorage_ = boost::make_shared<MemoryIdentityStorage>(); privateKeyStorage_ = boost::make_shared<MemoryPrivateKeyStorage>(); if (defaultKeyChain_->getIsSecurityV1()) configPolicyManager_ = boost::make_shared<ConfigPolicyManager>(configPolicy_); else configPolicyManager_ = boost::make_shared<ConfigPolicyManager> (configPolicy_, boost::make_shared<CertificateCacheV2>()); } void KeyChainManager::createSigningIdentity() { // create self-signed certificate Name cert = defaultKeyChain_->createIdentityAndCertificate(Name(signingIdentity_)); LogWarn("") << "Generated identity " << signingIdentity_ << " (certificate name " << cert << ")" << std::endl; LogWarn("") << "Check policy config file for correct trust anchor (run `ndnsec-dump-certificate -i " << signingIdentity_ << " > signing.cert` if needed)" << std::endl; } void KeyChainManager::createMemoryKeychain() { if (defaultKeyChain_->getIsSecurityV1()) instanceKeyChain_ = boost::make_shared<KeyChain> (boost::make_shared<IdentityManager>(identityStorage_, privateKeyStorage_), configPolicyManager_); else instanceKeyChain_ = boost::make_shared<KeyChain> (boost::make_shared<PibMemory>(), boost::make_shared<TpmBackEndMemory>(), configPolicyManager_); instanceKeyChain_->setFace(face_.get()); } void KeyChainManager::createInstanceIdentity() { auto now = system_clock::now().time_since_epoch(); duration<double> sec = now; Name instanceIdentity(signingIdentity_); instanceIdentity.append(instanceName_); instanceIdentity_ = instanceIdentity.toUri(); LogInfo("") << "Instance identity " << instanceIdentity << std::endl; Name instanceKeyName = instanceKeyChain_->generateRSAKeyPairAsDefault(instanceIdentity, true); Name signingCert = defaultKeyChain_->getIdentityManager()->getDefaultCertificateNameForIdentity(Name(signingIdentity_)); LogDebug("") << "Instance key " << instanceKeyName << std::endl; LogDebug("") << "Signing certificate " << signingCert << std::endl; std::vector<CertificateSubjectDescription> subjectDescriptions; instanceCert_ = instanceKeyChain_->getIdentityManager()->prepareUnsignedIdentityCertificate(instanceKeyName, Name(signingIdentity_), sec.count()*1000, (sec+duration<double>(runTime_)).count()*1000, subjectDescriptions, &instanceIdentity); assert(instanceCert_.get()); defaultKeyChain_->sign(*instanceCert_, signingCert); instanceKeyChain_->installIdentityCertificate(*instanceCert_); instanceKeyChain_->setDefaultCertificateForKey(*instanceCert_); instanceKeyChain_->getIdentityManager()->setDefaultIdentity(instanceIdentity); LogInfo("") << "Instance certificate " << instanceKeyChain_->getIdentityManager()->getDefaultCertificateNameForIdentity(Name(instanceIdentity)) << std::endl; } void KeyChainManager::createInstanceIdentityV2() { auto now = system_clock::now().time_since_epoch(); duration<double> sec = now; Name instanceIdentity(signingIdentity_); instanceIdentity.append(instanceName_); instanceIdentity_ = instanceIdentity.toUri(); LogInfo("") << "Instance identity " << instanceIdentity << std::endl; boost::shared_ptr<PibIdentity> instancePibIdentity = instanceKeyChain_->createIdentityV2(instanceIdentity); std::cout << "Debug instancePibIdentity " << instancePibIdentity->getName() << std::endl; boost::shared_ptr<PibKey> instancePibKey = instancePibIdentity->getDefaultKey(); Name signingCert = defaultKeyChain_->getPib() .getIdentity(Name(signingIdentity_))->getDefaultKey() ->getDefaultCertificate()->getName(); LogDebug("") << "Instance key " << instancePibKey->getName() << std::endl; LogDebug("") << "Signing certificate " << signingCert << std::endl; // Prepare the instance certificate. boost::shared_ptr<CertificateV2> instanceCertificate(new CertificateV2()); Name certificateName = instancePibKey->getName(); certificateName.append("issuer").appendVersion((uint64_t)(sec.count()*1000)); instanceCertificate->setName(certificateName); instanceCertificate->getMetaInfo().setType(ndn_ContentType_KEY); instanceCertificate->getMetaInfo().setFreshnessPeriod(3600 * 1000.0); instanceCertificate->setContent(instancePibKey->getPublicKey()); SigningInfo signingParams (defaultKeyChain_->getPib().getIdentity(Name(signingIdentity_))); signingParams.setValidityPeriod (ValidityPeriod(sec.count() * 1000, (sec + duration<double>(runTime_)).count() * 1000)); defaultKeyChain_->sign(*instanceCertificate, signingParams); instanceKeyChain_->addCertificate(*instancePibKey, *instanceCertificate); instanceKeyChain_->setDefaultCertificate(*instancePibKey, *instanceCertificate); instanceKeyChain_->setDefaultIdentity(*instancePibIdentity); instanceCert_ = instanceCertificate; LogInfo("") << "Instance certificate " << instanceKeyChain_->getPib().getIdentity(Name(instanceIdentity_)) ->getDefaultKey()->getDefaultCertificate()->getName() << std::endl; } void KeyChainManager::checkExists(const std::string& file) { std::ifstream stream(file.c_str()); bool result = (bool)stream; stream.close(); if (!result) { std::stringstream ss; ss << "Can't find file " << file << std::endl; throw std::runtime_error(ss.str()); } } <commit_msg>KeyChainManager: In createInstanceIdentityV2, in the certificate name, use the issuer's public key digest.<commit_after>// // key-chain-manager.cpp // // Created by Peter Gusev on 02 September 2016. // Copyright 2013-2016 Regents of the University of California // #include "key-chain-manager.hpp" #include <algorithm> #include <ndn-cpp/security/key-chain.hpp> #include <ndn-cpp/security/certificate/identity-certificate.hpp> #include <ndn-cpp/security/identity/memory-identity-storage.hpp> #include <ndn-cpp/security/identity/memory-private-key-storage.hpp> #include <ndn-cpp/security/policy/config-policy-manager.hpp> #include <ndn-cpp/security/policy/self-verify-policy-manager.hpp> #include <ndn-cpp/security/v2/certificate-cache-v2.hpp> #include <ndn-cpp/security/pib/pib-memory.hpp> #include <ndn-cpp/security/tpm/tpm-back-end-memory.hpp> #include <ndn-cpp/security/signing-info.hpp> #include <ndn-cpp/face.hpp> #include <ndnrtc/simple-log.hpp> #include <boost/chrono.hpp> using namespace boost::chrono; using namespace ndn; KeyChainManager::KeyChainManager(boost::shared_ptr<Face> face, const std::string& identityNameStr, const std::string& instanceNameStr, const std::string& configPolicy, unsigned int runTime): face_(face), signingIdentity_(identityNameStr), instanceName_(instanceNameStr), configPolicy_(configPolicy), runTime_(runTime) { checkExists(configPolicy); setupDefaultKeyChain(); setupConfigPolicyManager(); setupInstanceKeyChain(); } void KeyChainManager::setupDefaultKeyChain() { defaultKeyChain_ = boost::make_shared<ndn::KeyChain>(); } void KeyChainManager::setupInstanceKeyChain() { Name signingIdentity(signingIdentity_); std::vector<Name> identities; if (defaultKeyChain_->getIsSecurityV1()) { defaultKeyChain_->getIdentityManager()->getAllIdentities(identities, false); defaultKeyChain_->getIdentityManager()->getAllIdentities(identities, true); } else defaultKeyChain_->getPib().getAllIdentityNames(identities); if (std::find(identities.begin(), identities.end(), signingIdentity) == identities.end()) { // create signing identity in default keychain LogInfo("") << "Signing identity not found. Creating..." << std::endl; createSigningIdentity(); } createMemoryKeychain(); if (defaultKeyChain_->getIsSecurityV1()) createInstanceIdentity(); else createInstanceIdentityV2(); } void KeyChainManager::setupConfigPolicyManager() { identityStorage_ = boost::make_shared<MemoryIdentityStorage>(); privateKeyStorage_ = boost::make_shared<MemoryPrivateKeyStorage>(); if (defaultKeyChain_->getIsSecurityV1()) configPolicyManager_ = boost::make_shared<ConfigPolicyManager>(configPolicy_); else configPolicyManager_ = boost::make_shared<ConfigPolicyManager> (configPolicy_, boost::make_shared<CertificateCacheV2>()); } void KeyChainManager::createSigningIdentity() { // create self-signed certificate Name cert = defaultKeyChain_->createIdentityAndCertificate(Name(signingIdentity_)); LogWarn("") << "Generated identity " << signingIdentity_ << " (certificate name " << cert << ")" << std::endl; LogWarn("") << "Check policy config file for correct trust anchor (run `ndnsec-dump-certificate -i " << signingIdentity_ << " > signing.cert` if needed)" << std::endl; } void KeyChainManager::createMemoryKeychain() { if (defaultKeyChain_->getIsSecurityV1()) instanceKeyChain_ = boost::make_shared<KeyChain> (boost::make_shared<IdentityManager>(identityStorage_, privateKeyStorage_), configPolicyManager_); else instanceKeyChain_ = boost::make_shared<KeyChain> (boost::make_shared<PibMemory>(), boost::make_shared<TpmBackEndMemory>(), configPolicyManager_); instanceKeyChain_->setFace(face_.get()); } void KeyChainManager::createInstanceIdentity() { auto now = system_clock::now().time_since_epoch(); duration<double> sec = now; Name instanceIdentity(signingIdentity_); instanceIdentity.append(instanceName_); instanceIdentity_ = instanceIdentity.toUri(); LogInfo("") << "Instance identity " << instanceIdentity << std::endl; Name instanceKeyName = instanceKeyChain_->generateRSAKeyPairAsDefault(instanceIdentity, true); Name signingCert = defaultKeyChain_->getIdentityManager()->getDefaultCertificateNameForIdentity(Name(signingIdentity_)); LogDebug("") << "Instance key " << instanceKeyName << std::endl; LogDebug("") << "Signing certificate " << signingCert << std::endl; std::vector<CertificateSubjectDescription> subjectDescriptions; instanceCert_ = instanceKeyChain_->getIdentityManager()->prepareUnsignedIdentityCertificate(instanceKeyName, Name(signingIdentity_), sec.count()*1000, (sec+duration<double>(runTime_)).count()*1000, subjectDescriptions, &instanceIdentity); assert(instanceCert_.get()); defaultKeyChain_->sign(*instanceCert_, signingCert); instanceKeyChain_->installIdentityCertificate(*instanceCert_); instanceKeyChain_->setDefaultCertificateForKey(*instanceCert_); instanceKeyChain_->getIdentityManager()->setDefaultIdentity(instanceIdentity); LogInfo("") << "Instance certificate " << instanceKeyChain_->getIdentityManager()->getDefaultCertificateNameForIdentity(Name(instanceIdentity)) << std::endl; } void KeyChainManager::createInstanceIdentityV2() { auto now = system_clock::now().time_since_epoch(); duration<double> sec = now; Name instanceIdentity(signingIdentity_); instanceIdentity.append(instanceName_); instanceIdentity_ = instanceIdentity.toUri(); LogInfo("") << "Instance identity " << instanceIdentity << std::endl; boost::shared_ptr<PibIdentity> instancePibIdentity = instanceKeyChain_->createIdentityV2(instanceIdentity); std::cout << "Debug instancePibIdentity " << instancePibIdentity->getName() << std::endl; boost::shared_ptr<PibKey> instancePibKey = instancePibIdentity->getDefaultKey(); boost::shared_ptr<PibKey> signingPibKey = defaultKeyChain_->getPib() .getIdentity(Name(signingIdentity_))->getDefaultKey(); Name signingCert = signingPibKey->getDefaultCertificate()->getName(); LogDebug("") << "Instance key " << instancePibKey->getName() << std::endl; LogDebug("") << "Signing certificate " << signingCert << std::endl; // Prepare the instance certificate. boost::shared_ptr<CertificateV2> instanceCertificate(new CertificateV2()); Name certificateName = instancePibKey->getName(); // Use the issuer's public key digest. certificateName.append(PublicKey(signingPibKey->getPublicKey()).getDigest()); certificateName.appendVersion((uint64_t)(sec.count()*1000)); instanceCertificate->setName(certificateName); instanceCertificate->getMetaInfo().setType(ndn_ContentType_KEY); instanceCertificate->getMetaInfo().setFreshnessPeriod(3600 * 1000.0); instanceCertificate->setContent(instancePibKey->getPublicKey()); SigningInfo signingParams(signingPibKey); signingParams.setValidityPeriod (ValidityPeriod(sec.count() * 1000, (sec + duration<double>(runTime_)).count() * 1000)); defaultKeyChain_->sign(*instanceCertificate, signingParams); instanceKeyChain_->addCertificate(*instancePibKey, *instanceCertificate); instanceKeyChain_->setDefaultCertificate(*instancePibKey, *instanceCertificate); instanceKeyChain_->setDefaultIdentity(*instancePibIdentity); instanceCert_ = instanceCertificate; LogInfo("") << "Instance certificate " << instanceKeyChain_->getPib().getIdentity(Name(instanceIdentity_)) ->getDefaultKey()->getDefaultCertificate()->getName() << std::endl; } void KeyChainManager::checkExists(const std::string& file) { std::ifstream stream(file.c_str()); bool result = (bool)stream; stream.close(); if (!result) { std::stringstream ss; ss << "Can't find file " << file << std::endl; throw std::runtime_error(ss.str()); } } <|endoftext|>
<commit_before>// // key-chain-manager.h // // Created by Peter Gusev on 02 September 2016. // Copyright 2013-2016 Regents of the University of California // #ifndef __key_chain_manager_h__ #define __key_chain_manager_h__ #include <boost/shared_ptr.hpp> namespace ndn { class KeyChain; class Face; class IdentityCertificate; class ConfigPolicyManager; class IdentityStorage; class PrivateKeyStorage; } class KeyChainManager { public: KeyChainManager(boost::shared_ptr<ndn::Face> face, const std::string& identityName, const std::string& instanceName, const std::string& configPolicy, unsigned int runTime); boost::shared_ptr<ndn::KeyChain> defaultKeyChain() { return defaultKeyChain_; } boost::shared_ptr<ndn::KeyChain> instanceKeyChain() { return instanceKeyChain_; } std::string instancePrefix() const { return instanceIdentity_; } const boost::shared_ptr<ndn::IdentityCertificate> instanceCertificate() const { return instanceCert_; } private: boost::shared_ptr<ndn::Face> face_; std::string signingIdentity_, instanceName_, configPolicy_, instanceIdentity_; unsigned int runTime_; boost::shared_ptr<ndn::ConfigPolicyManager> configPolicyManager_; boost::shared_ptr<ndn::KeyChain> defaultKeyChain_, instanceKeyChain_; boost::shared_ptr<ndn::IdentityCertificate> instanceCert_; boost::shared_ptr<ndn::IdentityStorage> identityStorage_; boost::shared_ptr<ndn::PrivateKeyStorage> privateKeyStorage_; void setupDefaultKeyChain(); void setupInstanceKeyChain(); void setupConfigPolicyManager(); void createSigningIdentity(); void createMemoryKeychain(); void createInstanceIdentity(); void checkExists(const std::string&); }; #endif <commit_msg>In KeyChainManager, change instanceCert_ to the more general Data.<commit_after>// // key-chain-manager.h // // Created by Peter Gusev on 02 September 2016. // Copyright 2013-2016 Regents of the University of California // #ifndef __key_chain_manager_h__ #define __key_chain_manager_h__ #include <boost/shared_ptr.hpp> namespace ndn { class KeyChain; class Face; class Data; class ConfigPolicyManager; class IdentityStorage; class PrivateKeyStorage; } class KeyChainManager { public: KeyChainManager(boost::shared_ptr<ndn::Face> face, const std::string& identityName, const std::string& instanceName, const std::string& configPolicy, unsigned int runTime); boost::shared_ptr<ndn::KeyChain> defaultKeyChain() { return defaultKeyChain_; } boost::shared_ptr<ndn::KeyChain> instanceKeyChain() { return instanceKeyChain_; } std::string instancePrefix() const { return instanceIdentity_; } const boost::shared_ptr<ndn::Data> instanceCertificate() const { return instanceCert_; } private: boost::shared_ptr<ndn::Face> face_; std::string signingIdentity_, instanceName_, configPolicy_, instanceIdentity_; unsigned int runTime_; boost::shared_ptr<ndn::ConfigPolicyManager> configPolicyManager_; boost::shared_ptr<ndn::KeyChain> defaultKeyChain_, instanceKeyChain_; // instanceCert_ is a certificate subclass of Data. boost::shared_ptr<ndn::Data> instanceCert_; boost::shared_ptr<ndn::IdentityStorage> identityStorage_; boost::shared_ptr<ndn::PrivateKeyStorage> privateKeyStorage_; void setupDefaultKeyChain(); void setupInstanceKeyChain(); void setupConfigPolicyManager(); void createSigningIdentity(); void createMemoryKeychain(); void createInstanceIdentity(); void checkExists(const std::string&); }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2012 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "common/test_environment.h" #include "common/test_rpc_server_dir.h" #include "common/test_rpc_server_mrc.h" #include "common/test_rpc_server_osd.h" #include "libxtreemfs/client.h" using namespace xtreemfs::rpc; namespace xtreemfs { TestEnvironment::TestEnvironment() : options(), user_credentials() { user_credentials.set_username("ClientTest"); user_credentials.add_groups("ClientTest"); dir.reset(new TestRPCServerDIR()); mrc.reset(new TestRPCServerMRC()); osds.push_back(new TestRPCServerOSD()); volume_name_ = "test"; } TestEnvironment::~TestEnvironment() { for (size_t i = 0; i < osds.size(); i++) { delete osds[i]; } } void TestEnvironment::AddOSDs(int num_of_osds) { for (int i = 1; i < num_of_osds; i++) { osds.push_back(new TestRPCServerOSD()); } } bool TestEnvironment::Start() { if (!dir->Start()) { return false; } if (!mrc->Start()) { return false; } dir->RegisterVolume(volume_name_, mrc->GetAddress()); for (size_t i = 0; i < osds.size(); i++) { if (!osds[i]->Start()) { return false; } mrc->RegisterOSD(osds[i]->GetAddress()); } // TODO(mberlin): Register OSDs at MRC. // If the DIR server address was not explicitly overridden, set it to the // started test DIR server. if (options.service_addresses.empty()) { options.service_addresses.push_back(dir->GetAddress()); } client.reset(Client::CreateClient( options.service_addresses, user_credentials, NULL, // No SSL options. options)); // Start the client (a connection to the DIR service will be setup). client->Start(); return true; } void TestEnvironment::Stop() { if (client.get()) { client->Shutdown(); } if (dir.get()) { dir->Stop(); } if (mrc.get()) { mrc->Stop(); } for (size_t i = 0; i < osds.size(); i++) { osds[i]->Stop(); } } } // namespace xtreemfs <commit_msg>client: log test server ports so that they can be correlated with rpc error messages.<commit_after>/* * Copyright (c) 2012 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "common/test_environment.h" #include "common/test_rpc_server_dir.h" #include "common/test_rpc_server_mrc.h" #include "common/test_rpc_server_osd.h" #include "libxtreemfs/client.h" #include "util/logging.h" using namespace xtreemfs::rpc; using xtreemfs::util::Logging; namespace xtreemfs { TestEnvironment::TestEnvironment() : options(), user_credentials() { user_credentials.set_username("ClientTest"); user_credentials.add_groups("ClientTest"); dir.reset(new TestRPCServerDIR()); mrc.reset(new TestRPCServerMRC()); osds.push_back(new TestRPCServerOSD()); volume_name_ = "test"; } TestEnvironment::~TestEnvironment() { for (size_t i = 0; i < osds.size(); i++) { delete osds[i]; } } void TestEnvironment::AddOSDs(int num_of_osds) { for (int i = 1; i < num_of_osds; i++) { osds.push_back(new TestRPCServerOSD()); } } bool TestEnvironment::Start() { if (!dir->Start()) { return false; } Logging::log->getLog(xtreemfs::util::LEVEL_INFO) << "DIR running at: " << dir->GetAddress() << std::endl; if (!mrc->Start()) { return false; } Logging::log->getLog(xtreemfs::util::LEVEL_INFO) << "MRC running at: " << mrc->GetAddress() << std::endl; dir->RegisterVolume(volume_name_, mrc->GetAddress()); for (size_t i = 0; i < osds.size(); i++) { if (!osds[i]->Start()) { return false; } Logging::log->getLog(xtreemfs::util::LEVEL_INFO) << "OSD running at: " << osds[i]->GetAddress() << std::endl; mrc->RegisterOSD(osds[i]->GetAddress()); } // TODO(mberlin): Register OSDs at MRC. // If the DIR server address was not explicitly overridden, set it to the // started test DIR server. if (options.service_addresses.empty()) { options.service_addresses.push_back(dir->GetAddress()); } client.reset(Client::CreateClient( options.service_addresses, user_credentials, NULL, // No SSL options. options)); // Start the client (a connection to the DIR service will be setup). client->Start(); return true; } void TestEnvironment::Stop() { if (client.get()) { client->Shutdown(); } if (dir.get()) { dir->Stop(); } if (mrc.get()) { mrc->Stop(); } for (size_t i = 0; i < osds.size(); i++) { osds[i]->Stop(); } } } // namespace xtreemfs <|endoftext|>
<commit_before>/* Various utility definitions for libpqxx. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/util instead. * * Copyright (c) 2000-2020, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this * mistake, or contact the author. */ #ifndef PQXX_H_UTIL #define PQXX_H_UTIL #include "pqxx/compiler-public.hxx" #include "pqxx/internal/compiler-internal-pre.hxx" #include <cctype> #include <cstdio> #include <iterator> #include <limits> #include <memory> #include <stdexcept> #include <string> #include <string_view> #include <type_traits> #include <typeinfo> #include <vector> #include "pqxx/except.hxx" #include "pqxx/types.hxx" #include "pqxx/version.hxx" /// The home of all libpqxx classes, functions, templates, etc. namespace pqxx {} #include <pqxx/internal/libpq-forward.hxx> namespace pqxx { /// Suppress compiler warning about an unused item. template<typename... T> inline void ignore_unused(T &&...) {} /// Cast a numeric value to another type, or throw if it underflows/overflows. /** Both types must be arithmetic types, and they must either be both integral * or both floating-point types. */ template<typename TO, typename FROM> inline TO check_cast(FROM value, char const description[]) { static_assert(std::is_arithmetic_v<FROM>); static_assert(std::is_arithmetic_v<TO>); static_assert(std::is_integral_v<FROM> == std::is_integral_v<TO>); // The rest of this code won't quite work for bool, but bool is trivially // convertible to other arithmetic types as far as I can see. if constexpr (std::is_same_v<FROM, bool>) return static_cast<TO>(value); // Depending on our "if constexpr" conditions, this parameter may not be // needed. Some compilers will warn. ignore_unused(description); using from_limits = std::numeric_limits<decltype(value)>; using to_limits = std::numeric_limits<TO>; if constexpr (std::is_signed_v<FROM>) { if constexpr (std::is_signed_v<TO>) { if (value < (to_limits::min)()) throw range_error(std::string{"Cast underflow: "} + description); } else { // FROM is signed, but TO is not. Treat this as a special case, because // there may not be a good broader type in which the compiler can even // perform our check. if (value < 0) throw range_error( std::string{"Casting negative value to unsigned type: "} + description); } } else { // No need to check: the value is unsigned so can't fall below the range // of the TO type. } if constexpr (std::is_integral_v<FROM>) { using unsigned_from = std::make_unsigned_t<FROM>; using unsigned_to = std::make_unsigned_t<TO>; constexpr auto from_max{static_cast<unsigned_from>((from_limits::max)())}; constexpr auto to_max{static_cast<unsigned_to>((to_limits::max)())}; if constexpr (from_max > to_max) { if (static_cast<unsigned_from>(value) > to_max) throw range_error(std::string{"Cast overflow: "} + description); } } else if constexpr ((from_limits::max)() > (to_limits::max)()) { if (value > (to_limits::max)()) throw range_error(std::string{"Cast overflow: "} + description); } return static_cast<TO>(value); } /// Remove any constness, volatile, and reference-ness from a type. template<typename TYPE> using strip_t = std::remove_cv_t<std::remove_reference_t<TYPE>>; /** Check library version at link time. * * Ensures a failure when linking an application against a radically * different libpqxx version than the one against which it was compiled. * * Sometimes application builds fail in unclear ways because they compile * using headers from libpqxx version X, but then link against libpqxx * binary version Y. A typical scenario would be one where you're building * against a libpqxx which you have built yourself, but a different version * is installed on the system. * * The check_library_version template is declared for any library version, * but only actually defined for the version of the libpqxx binary against * which the code is linked. * * If the library binary is a different version than the one declared in * these headers, then this call will fail to link: there will be no * definition for the function with these exact template parameter values. * There will be a definition, but the version in the parameter values will * be different. */ inline PQXX_PRIVATE void check_version() { // There is no particular reason to do this here in @c connection, except // to ensure that every meaningful libpqxx client will execute it. The call // must be in the execution path somewhere or the compiler won't try to link // it. We can't use it to initialise a global or class-static variable, // because a smart compiler might resolve it at compile time. // // On the other hand, we don't want to make a useless function call too // often for performance reasons. A local static variable is initialised // only on the definition's first execution. Compilers will be well // optimised for this behaviour, so there's a minimal one-time cost. static auto const version_ok{internal::PQXX_VERSION_CHECK()}; ignore_unused(version_ok); } /// Descriptor of library's thread-safety model. /** This describes what the library knows about various risks to thread-safety. */ struct PQXX_LIBEXPORT thread_safety_model { /// Is the underlying libpq build thread-safe? bool safe_libpq = false; /// Is Kerberos thread-safe? /** @warning Is currently always @c false. * * If your application uses Kerberos, all accesses to libpqxx or Kerberos * must be serialized. Confine their use to a single thread, or protect it * with a global lock. */ bool safe_kerberos = false; /// A human-readable description of any thread-safety issues. std::string description; }; /// Describe thread safety available in this build. [[nodiscard]] PQXX_LIBEXPORT thread_safety_model describe_thread_safety(); /// The "null" oid. constexpr oid oid_none{0}; } // namespace pqxx /// Private namespace for libpqxx's internal use; do not access. /** This namespace hides definitions internal to libpqxx. These are not * supposed to be used by client programs, and they may change at any time * without notice. * * Conversely, if you find something in this namespace tremendously useful, by * all means do lodge a request for its publication. * * @warning Here be dragons! */ namespace pqxx::internal { /// Helper base class: object descriptions for error messages and such. /** * Classes derived from namedclass have a class name (such as "transaction"), * an optional object name (such as "delete-old-logs"), and a description * generated from the two names (such as "transaction delete-old-logs"). * * The class name is dynamic here, in order to support inheritance hierarchies * where the exact class name may not be known statically. * * In inheritance hierarchies, make namedclass a virtual base class so that * each class in the hierarchy can specify its own class name in its * constructors. */ class PQXX_LIBEXPORT namedclass { public: explicit namedclass(std::string_view classname) : m_classname{classname} {} namedclass(std::string_view classname, std::string_view name) : m_classname{classname}, m_name{name} {} namedclass(std::string_view classname, char const name[]) : m_classname{classname}, m_name{name} {} namedclass(std::string_view classname, std::string &&name) : m_classname{classname}, m_name{std::move(name)} {} /// Object name, or the empty string if no name was given. std::string const &name() const noexcept { return m_name; } /// Class name. std::string const &classname() const noexcept { return m_classname; } /// Combination of class name and object name; or just class name. std::string description() const; private: std::string m_classname, m_name; }; PQXX_PRIVATE void check_unique_registration( namedclass const *new_ptr, namedclass const *old_ptr); PQXX_PRIVATE void check_unique_unregistration( namedclass const *new_ptr, namedclass const *old_ptr); /// Ensure proper opening/closing of GUEST objects related to a "host" object /** Only a single GUEST may exist for a single host at any given time. GUEST * must be derived from namedclass. */ template<typename GUEST> class unique { public: constexpr unique() = default; constexpr unique(unique const &) = delete; constexpr unique(unique &&rhs) : m_guest(rhs.m_guest) { rhs.m_guest = nullptr; } constexpr unique &operator=(unique const &) = delete; constexpr unique &operator=(unique &&rhs) { m_guest = rhs.m_guest; rhs.m_guest = nullptr; return *this; } constexpr GUEST *get() const noexcept { return m_guest; } constexpr void register_guest(GUEST *G) { check_unique_registration(G, m_guest); m_guest = G; } constexpr void unregister_guest(GUEST *G) { check_unique_unregistration(G, m_guest); m_guest = nullptr; } private: GUEST *m_guest = nullptr; }; } // namespace pqxx::internal #include "pqxx/internal/compiler-internal-post.hxx" #endif <commit_msg>Deprecate `strip_t`.<commit_after>/* Various utility definitions for libpqxx. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/util instead. * * Copyright (c) 2000-2020, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this * mistake, or contact the author. */ #ifndef PQXX_H_UTIL #define PQXX_H_UTIL #include "pqxx/compiler-public.hxx" #include "pqxx/internal/compiler-internal-pre.hxx" #include <cctype> #include <cstdio> #include <iterator> #include <limits> #include <memory> #include <stdexcept> #include <string> #include <string_view> #include <type_traits> #include <typeinfo> #include <vector> #include "pqxx/except.hxx" #include "pqxx/types.hxx" #include "pqxx/version.hxx" /// The home of all libpqxx classes, functions, templates, etc. namespace pqxx {} #include <pqxx/internal/libpq-forward.hxx> namespace pqxx { /// Suppress compiler warning about an unused item. template<typename... T> inline void ignore_unused(T &&...) {} /// Cast a numeric value to another type, or throw if it underflows/overflows. /** Both types must be arithmetic types, and they must either be both integral * or both floating-point types. */ template<typename TO, typename FROM> inline TO check_cast(FROM value, char const description[]) { static_assert(std::is_arithmetic_v<FROM>); static_assert(std::is_arithmetic_v<TO>); static_assert(std::is_integral_v<FROM> == std::is_integral_v<TO>); // The rest of this code won't quite work for bool, but bool is trivially // convertible to other arithmetic types as far as I can see. if constexpr (std::is_same_v<FROM, bool>) return static_cast<TO>(value); // Depending on our "if constexpr" conditions, this parameter may not be // needed. Some compilers will warn. ignore_unused(description); using from_limits = std::numeric_limits<decltype(value)>; using to_limits = std::numeric_limits<TO>; if constexpr (std::is_signed_v<FROM>) { if constexpr (std::is_signed_v<TO>) { if (value < (to_limits::min)()) throw range_error(std::string{"Cast underflow: "} + description); } else { // FROM is signed, but TO is not. Treat this as a special case, because // there may not be a good broader type in which the compiler can even // perform our check. if (value < 0) throw range_error( std::string{"Casting negative value to unsigned type: "} + description); } } else { // No need to check: the value is unsigned so can't fall below the range // of the TO type. } if constexpr (std::is_integral_v<FROM>) { using unsigned_from = std::make_unsigned_t<FROM>; using unsigned_to = std::make_unsigned_t<TO>; constexpr auto from_max{static_cast<unsigned_from>((from_limits::max)())}; constexpr auto to_max{static_cast<unsigned_to>((to_limits::max)())}; if constexpr (from_max > to_max) { if (static_cast<unsigned_from>(value) > to_max) throw range_error(std::string{"Cast overflow: "} + description); } } else if constexpr ((from_limits::max)() > (to_limits::max)()) { if (value > (to_limits::max)()) throw range_error(std::string{"Cast overflow: "} + description); } return static_cast<TO>(value); } /// Remove any constness, volatile, and reference-ness from a type. /** @deprecated In C++20 we'll replace this with std::remove_cvref. */ template<typename TYPE> using strip_t = std::remove_cv_t<std::remove_reference_t<TYPE>>; /** Check library version at link time. * * Ensures a failure when linking an application against a radically * different libpqxx version than the one against which it was compiled. * * Sometimes application builds fail in unclear ways because they compile * using headers from libpqxx version X, but then link against libpqxx * binary version Y. A typical scenario would be one where you're building * against a libpqxx which you have built yourself, but a different version * is installed on the system. * * The check_library_version template is declared for any library version, * but only actually defined for the version of the libpqxx binary against * which the code is linked. * * If the library binary is a different version than the one declared in * these headers, then this call will fail to link: there will be no * definition for the function with these exact template parameter values. * There will be a definition, but the version in the parameter values will * be different. */ inline PQXX_PRIVATE void check_version() { // There is no particular reason to do this here in @c connection, except // to ensure that every meaningful libpqxx client will execute it. The call // must be in the execution path somewhere or the compiler won't try to link // it. We can't use it to initialise a global or class-static variable, // because a smart compiler might resolve it at compile time. // // On the other hand, we don't want to make a useless function call too // often for performance reasons. A local static variable is initialised // only on the definition's first execution. Compilers will be well // optimised for this behaviour, so there's a minimal one-time cost. static auto const version_ok{internal::PQXX_VERSION_CHECK()}; ignore_unused(version_ok); } /// Descriptor of library's thread-safety model. /** This describes what the library knows about various risks to thread-safety. */ struct PQXX_LIBEXPORT thread_safety_model { /// Is the underlying libpq build thread-safe? bool safe_libpq = false; /// Is Kerberos thread-safe? /** @warning Is currently always @c false. * * If your application uses Kerberos, all accesses to libpqxx or Kerberos * must be serialized. Confine their use to a single thread, or protect it * with a global lock. */ bool safe_kerberos = false; /// A human-readable description of any thread-safety issues. std::string description; }; /// Describe thread safety available in this build. [[nodiscard]] PQXX_LIBEXPORT thread_safety_model describe_thread_safety(); /// The "null" oid. constexpr oid oid_none{0}; } // namespace pqxx /// Private namespace for libpqxx's internal use; do not access. /** This namespace hides definitions internal to libpqxx. These are not * supposed to be used by client programs, and they may change at any time * without notice. * * Conversely, if you find something in this namespace tremendously useful, by * all means do lodge a request for its publication. * * @warning Here be dragons! */ namespace pqxx::internal { /// Helper base class: object descriptions for error messages and such. /** * Classes derived from namedclass have a class name (such as "transaction"), * an optional object name (such as "delete-old-logs"), and a description * generated from the two names (such as "transaction delete-old-logs"). * * The class name is dynamic here, in order to support inheritance hierarchies * where the exact class name may not be known statically. * * In inheritance hierarchies, make namedclass a virtual base class so that * each class in the hierarchy can specify its own class name in its * constructors. */ class PQXX_LIBEXPORT namedclass { public: explicit namedclass(std::string_view classname) : m_classname{classname} {} namedclass(std::string_view classname, std::string_view name) : m_classname{classname}, m_name{name} {} namedclass(std::string_view classname, char const name[]) : m_classname{classname}, m_name{name} {} namedclass(std::string_view classname, std::string &&name) : m_classname{classname}, m_name{std::move(name)} {} /// Object name, or the empty string if no name was given. std::string const &name() const noexcept { return m_name; } /// Class name. std::string const &classname() const noexcept { return m_classname; } /// Combination of class name and object name; or just class name. std::string description() const; private: std::string m_classname, m_name; }; PQXX_PRIVATE void check_unique_registration( namedclass const *new_ptr, namedclass const *old_ptr); PQXX_PRIVATE void check_unique_unregistration( namedclass const *new_ptr, namedclass const *old_ptr); /// Ensure proper opening/closing of GUEST objects related to a "host" object /** Only a single GUEST may exist for a single host at any given time. GUEST * must be derived from namedclass. */ template<typename GUEST> class unique { public: constexpr unique() = default; constexpr unique(unique const &) = delete; constexpr unique(unique &&rhs) : m_guest(rhs.m_guest) { rhs.m_guest = nullptr; } constexpr unique &operator=(unique const &) = delete; constexpr unique &operator=(unique &&rhs) { m_guest = rhs.m_guest; rhs.m_guest = nullptr; return *this; } constexpr GUEST *get() const noexcept { return m_guest; } constexpr void register_guest(GUEST *G) { check_unique_registration(G, m_guest); m_guest = G; } constexpr void unregister_guest(GUEST *G) { check_unique_unregistration(G, m_guest); m_guest = nullptr; } private: GUEST *m_guest = nullptr; }; } // namespace pqxx::internal #include "pqxx/internal/compiler-internal-post.hxx" #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2009-2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file sched/job.hxx ** \brief Inline implementation of Job. */ #ifndef SCHED_JOB_HXX # define SCHED_JOB_HXX # include <libport/bind.hh> # include <libport/cassert> # include <libport/debug.hh> # include <sched/scheduler.hh> # include <sched/coroutine.hh> GD_ADD_CATEGORY(sched); namespace sched { /*------------. | job_state. | `------------*/ inline const char* name(job_state state) { #define CASE(State) case State: return #State; switch (state) { CASE(to_start) CASE(running) CASE(sleeping) CASE(waiting) CASE(joining) CASE(zombie) } #undef CASE return "<unknown state>"; } inline std::ostream& operator<<(std::ostream& o, job_state s) { return o << name(s); } /*------. | Job. | `------*/ inline void Job::init_common(const libport::Symbol& name) { state_ = to_start; frozen_since_ = 0; time_shift_ = 0; name_ = name; coro_ = coroutine_new(); non_interruptible_ = false; side_effect_free_ = false; check_stack_space_ = true; alive_jobs_++; } inline Job::Job(Scheduler& scheduler, const libport::Symbol& name) : RefCounted() , scheduler_(scheduler) { init_common(name); } inline Job::Job(const Job& model, const libport::Symbol& name) : RefCounted() , scheduler_(model.scheduler_) { init_common(name); time_shift_ = model.time_shift_; } inline Job::~Job() { passert(children_, children_.empty()); coroutine_free(coro_); alive_jobs_--; } inline Scheduler& Job::scheduler_get() const { return scheduler_; } inline bool Job::terminated() const { return state_ == zombie; } inline void Job::yield() { // The only case where we yield while being non-interruptible // is when we get frozen. This is used to suspend a task // and resume it in non-interruptible contexts. if (non_interruptible_ && !frozen()) return; state_ = running; scheduler_.resume_scheduler(this); } inline void Job::yield_until(libport::utime_t deadline) { if (non_interruptible_) scheduling_error("attempt to sleep in non-interruptible code"); state_ = sleeping; deadline_ = deadline; scheduler_.resume_scheduler(this); } inline Coro* Job::coro_get() const { aver(coro_); return coro_; } inline void Job::start_job() { aver(state_ == to_start); scheduler_.add_job(this); } inline void Job::side_effect_free_set(bool s) { side_effect_free_ = s; } inline bool Job::side_effect_free_get() const { return side_effect_free_; } inline const libport::Symbol& Job::name_get() const { return name_; } inline bool Job::non_interruptible_get() const { return non_interruptible_; } inline void Job::non_interruptible_set(bool ni) { non_interruptible_ = ni; } inline void Job::check_stack_space() { if (check_stack_space_ && coroutine_stack_space_almost_gone(coro_)) { FINALLY(((bool&, check_stack_space_)), check_stack_space_ = false); GD_CATEGORY(sched); GD_ERROR("Stack space exhausted"); scheduling_error("stack space exhausted"); } } inline job_state Job::state_get() const { return state_; } inline void Job::state_set(job_state state) { state_ = state; } inline libport::utime_t Job::deadline_get() const { return deadline_; } inline void Job::notice_frozen(libport::utime_t current_time) { if (!frozen_since_) frozen_since_ = current_time; } inline void Job::notice_not_frozen(libport::utime_t current_time) { if (frozen_since_) { libport::utime_t time_spent_frozen = current_time - frozen_since_; time_shift_ += time_spent_frozen; if (state_ == sleeping) deadline_ += time_spent_frozen; } frozen_since_ = 0; } inline libport::utime_t Job::frozen_since_get() const { return frozen_since_; } inline libport::utime_t Job::time_shift_get() const { return time_shift_; } inline void Job::time_shift_set(libport::utime_t ts) { time_shift_ = ts; } inline bool Job::has_pending_exception() const { return pending_exception_.get(); } inline bool Job::child_job() const { return parent_; } inline bool Job::ancester_of(const rJob& that) const { for (const Job* j = that.get(); j; j = j->parent_.get()) if (j == this) return true; return false; } inline std::ostream& operator<< (std::ostream& o, const Job& j) { return j.dump(o); } /*-----------------. | ChildException. | `-----------------*/ inline ChildException::ChildException(exception_ptr exc) : child_exception_(exc) { } inline ChildException::ChildException(const ChildException& exc) : SchedulerException(exc) , child_exception_(exc.child_exception_) { } inline exception_ptr ChildException::clone() const { return exception_ptr(new ChildException(child_exception_)); } inline void ChildException::rethrow_() const { throw *this; } inline void ChildException::rethrow_child_exception() const { child_exception_->rethrow(); } /*------------. | Collector. | `------------*/ ATTRIBUTE_ALWAYS_INLINE Job::Collector::Collector(rJob parent, size_t) : super_type() , parent_(parent) { } } // namespace sched #endif // !SCHED_JOB_HXX <commit_msg>msvc: don't use FINALLY in hxx.<commit_after>/* * Copyright (C) 2009-2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file sched/job.hxx ** \brief Inline implementation of Job. */ #ifndef SCHED_JOB_HXX # define SCHED_JOB_HXX # include <libport/bind.hh> # include <libport/cassert> # include <libport/debug.hh> # include <sched/scheduler.hh> # include <sched/coroutine.hh> GD_ADD_CATEGORY(sched); namespace sched { /*------------. | job_state. | `------------*/ inline const char* name(job_state state) { #define CASE(State) case State: return #State; switch (state) { CASE(to_start) CASE(running) CASE(sleeping) CASE(waiting) CASE(joining) CASE(zombie) } #undef CASE return "<unknown state>"; } inline std::ostream& operator<<(std::ostream& o, job_state s) { return o << name(s); } /*------. | Job. | `------*/ inline void Job::init_common(const libport::Symbol& name) { state_ = to_start; frozen_since_ = 0; time_shift_ = 0; name_ = name; coro_ = coroutine_new(); non_interruptible_ = false; side_effect_free_ = false; check_stack_space_ = true; alive_jobs_++; } inline Job::Job(Scheduler& scheduler, const libport::Symbol& name) : RefCounted() , scheduler_(scheduler) { init_common(name); } inline Job::Job(const Job& model, const libport::Symbol& name) : RefCounted() , scheduler_(model.scheduler_) { init_common(name); time_shift_ = model.time_shift_; } inline Job::~Job() { passert(children_, children_.empty()); coroutine_free(coro_); alive_jobs_--; } inline Scheduler& Job::scheduler_get() const { return scheduler_; } inline bool Job::terminated() const { return state_ == zombie; } inline void Job::yield() { // The only case where we yield while being non-interruptible // is when we get frozen. This is used to suspend a task // and resume it in non-interruptible contexts. if (non_interruptible_ && !frozen()) return; state_ = running; scheduler_.resume_scheduler(this); } inline void Job::yield_until(libport::utime_t deadline) { if (non_interruptible_) scheduling_error("attempt to sleep in non-interruptible code"); state_ = sleeping; deadline_ = deadline; scheduler_.resume_scheduler(this); } inline Coro* Job::coro_get() const { aver(coro_); return coro_; } inline void Job::start_job() { aver(state_ == to_start); scheduler_.add_job(this); } inline void Job::side_effect_free_set(bool s) { side_effect_free_ = s; } inline bool Job::side_effect_free_get() const { return side_effect_free_; } inline const libport::Symbol& Job::name_get() const { return name_; } inline bool Job::non_interruptible_get() const { return non_interruptible_; } inline void Job::non_interruptible_set(bool ni) { non_interruptible_ = ni; } inline void Job::check_stack_space() { if (check_stack_space_ && coroutine_stack_space_almost_gone(coro_)) { // Cannot be nicely converted to using FINALLY because of // MSVC2005. See finally.hh. libport::Finally finally(libport::scoped_set(check_stack_space_, false)); GD_CATEGORY(sched); GD_ERROR("Stack space exhausted"); scheduling_error("stack space exhausted"); } } inline job_state Job::state_get() const { return state_; } inline void Job::state_set(job_state state) { state_ = state; } inline libport::utime_t Job::deadline_get() const { return deadline_; } inline void Job::notice_frozen(libport::utime_t current_time) { if (!frozen_since_) frozen_since_ = current_time; } inline void Job::notice_not_frozen(libport::utime_t current_time) { if (frozen_since_) { libport::utime_t time_spent_frozen = current_time - frozen_since_; time_shift_ += time_spent_frozen; if (state_ == sleeping) deadline_ += time_spent_frozen; } frozen_since_ = 0; } inline libport::utime_t Job::frozen_since_get() const { return frozen_since_; } inline libport::utime_t Job::time_shift_get() const { return time_shift_; } inline void Job::time_shift_set(libport::utime_t ts) { time_shift_ = ts; } inline bool Job::has_pending_exception() const { return pending_exception_.get(); } inline bool Job::child_job() const { return parent_; } inline bool Job::ancester_of(const rJob& that) const { for (const Job* j = that.get(); j; j = j->parent_.get()) if (j == this) return true; return false; } inline std::ostream& operator<< (std::ostream& o, const Job& j) { return j.dump(o); } /*-----------------. | ChildException. | `-----------------*/ inline ChildException::ChildException(exception_ptr exc) : child_exception_(exc) { } inline ChildException::ChildException(const ChildException& exc) : SchedulerException(exc) , child_exception_(exc.child_exception_) { } inline exception_ptr ChildException::clone() const { return exception_ptr(new ChildException(child_exception_)); } inline void ChildException::rethrow_() const { throw *this; } inline void ChildException::rethrow_child_exception() const { child_exception_->rethrow(); } /*------------. | Collector. | `------------*/ ATTRIBUTE_ALWAYS_INLINE Job::Collector::Collector(rJob parent, size_t) : super_type() , parent_(parent) { } } // namespace sched #endif // !SCHED_JOB_HXX <|endoftext|>
<commit_before>#include <rleahylib/rleahylib.hpp> #include <mod.hpp> #include <server.hpp> #include <multi_scope_guard.hpp> #include <atomic> #include <functional> #include <limits> #include <utility> #include <type_traits> namespace MCPP { /** * Contains all possible phases of * the moon. */ enum class LunarPhase { Full=0, WaningGibbous=1, LastQuarter=2, WaningCrescent=3, New=4, WaxingCrescent=5, FirstQuarter=6, WaxingGibbous=7 }; /** * Specifies the different times of * day. */ enum class TimeOfDay { Day, Dusk, Night, Dawn }; /** * Keeps track of the time of day. */ class TimeModule : public Module { template <typename T> class bind_wrapper { public: T callback; inline void operator () () const noexcept(noexcept(callback())) { callback(); } }; private: mutable Mutex lock; // Time since last tick Timer timer; // Number of ticks std::atomic<Word> ticks; // Time spent ticking std::atomic<UInt64> tick_time; // Time spent executing ticks std::atomic<UInt64> executing; // Age of the world UInt64 age; // Time of day UInt64 time; // Time since last save UInt64 since; // If true time stops when // no one is logged in bool offline_freeze; // Ticks between saves UInt64 between_saves; // Number if milliseconds per // tick Word tick_length; // Threshold above which a tick // is considered "too long" Word threshold; // The percentage which is used // to derive the threshold Word threshold_percentage; // Tasks to be executed every // tick Vector< Tuple< // Callback std::function<void (MultiScopeGuard)>, // Whether the next tick should // wait for this task to finish bool > > callbacks; // Tasks to be executed at a certain // point in time Vector< Tuple< // Tick on which this task should // be executed Word, // Callback std::function<void (MultiScopeGuard)>, // Whether the next tick should // wait for this task to finish bool > > scheduled_callbacks; void tick (); void save (UInt64, UInt64) const; LunarPhase get_lunar_phase () const noexcept; UInt64 get_time (bool) const noexcept; TimeOfDay get_time_of_day () const noexcept; template <typename T, typename... Args> auto binder (T && callback, Args &&... args) -> decltype( std::bind( std::forward<T>(callback), std::forward<Args>(args)... ) ) { return std::bind( std::forward<T>(callback), std::forward<Args>(args)... ); } template <typename T> bind_wrapper<T> inner_wrapper (T && bound) { return bind_wrapper<T>{std::forward<T>(bound)}; } template <typename T> static void callback (MultiScopeGuard, T callback) { callback(); } template <typename T> auto outer_wrapper (T && wrapped) -> decltype( std::bind( callback<typename std::decay<T>::type>, std::placeholders::_1, std::move(wrapped) ) ) { return std::bind( callback<typename std::decay<T>::type>, std::placeholders::_1, std::move(wrapped) ); } template <typename T, typename... Args> auto wrap (T && callback, Args &&... args) -> decltype( outer_wrapper( inner_wrapper( binder( std::forward<T>(callback), std::forward<Args>(args)... ) ) ) ) { return outer_wrapper( inner_wrapper( binder( std::forward<T>(callback), std::forward<Args>(args)... ) ) ); } public: /** * Retrieves a string which describes * a phase of the moon. * * \param [in] phase * A phase of the moon. * * \return * A string which describes \em phase. */ static const String & GetLunarPhase (LunarPhase phase) noexcept; /** * Retrieves a string which describes * a time of day. * * \param [in] time_of_day * A time of day. * * \return * A string which describes \em time_of_day. */ static const String & GetTimeOfDay (TimeOfDay time_of_day) noexcept; TimeModule () noexcept; virtual const String & Name () const noexcept override; virtual Word Priority () const noexcept override; virtual void Install () override; /** * Determines the phase the moon is * currently in. * * \return * The current phase of the moon. */ LunarPhase GetLunarPhase () const noexcept; /** * Retrieves the current time. * * \param [in] total * If \em true the number of ticks * by which in game time has been * displaced from the start of this * world. If \em false the number * of ticks since midnight. Defaults * to \em false. * * \return * The current time. */ UInt64 GetTime (bool total=false) const noexcept; /** * Retrieves the current time of day. * * \return * The current time of day. */ TimeOfDay GetTimeOfDay () const noexcept; /** * Retrieves the age of the world. * * \return * The number of ticks that have * passed since this world began. */ UInt64 GetAge () const noexcept; /** * Gets all time-related information * atomically. * * \return * A tuple containing the current time, * the number of ticks since it was * last midnight, the current lunar phase, * the current time of day, and the current * world's age, respectively. */ Tuple<UInt64,UInt64,LunarPhase,TimeOfDay,UInt64> Get () const noexcept; /** * Adds a certain number of ticks to the * current time. * * The age of the world is unaffected. * * \param [in] ticks * The number of ticks to add to * the current time. */ void Add (UInt64 ticks) noexcept; /** * Subtracts a certain number of ticks * from the current time. * * If the current time would underflow * as a result of this subtraction, the * time is set to the smallest value which * causes the time to have the same displacement * from midnight as the subtraction would * have caused. * * The age of the world is unaffected. * * \param [in] ticks * The number of ticks to subtract from * the current time. */ void Subtract (UInt64 ticks) noexcept; /** * Sets the time to a certain value. * * \param [in] time * The time to set. * \param [in] total * If \em true the time will be set * to exactly \em time, otherwise * the time shall be adjusted so that * the difference between midinght * and the current time is the same * as the difference between midnight * and \em time. Defaults to \em false. */ void Set (UInt64 time, bool total=false) noexcept; /** * Causes the age of the world and * time of day to immediately be * saved to the backing store. */ void Save () const; template <typename T, typename... Args> void Enqueue (bool wait, T && callback, Args &&... args) { auto wrapped=wrap( std::forward<T>(callback), std::forward<Args>(args)... ); lock.Execute([&] () { callbacks.EmplaceBack( std::move(wrapped), wait ); }); } template <typename T, typename... Args> void Enqueue (Word milliseconds, bool wait, T && callback, Args &&... args) { auto wrapped=wrap( std::forward<T>(callback), std::forward<Args>(args)... ); lock.Execute([&] () { // Deduce execution time Word when=milliseconds+ticks; // Find insertion point Word i=0; for (;i<scheduled_callbacks.Count();++i) if (when<scheduled_callbacks[i].Item<0>()) break; // Insert scheduled_callbacks.Emplace( when, std::move(wrapped), wait ); }); } }; /** * The single valid instance of TimeModule. */ extern Nullable<TimeModule> Time; } <commit_msg>Time Documentation<commit_after>#include <rleahylib/rleahylib.hpp> #include <mod.hpp> #include <server.hpp> #include <multi_scope_guard.hpp> #include <atomic> #include <functional> #include <limits> #include <utility> #include <type_traits> namespace MCPP { /** * Contains all possible phases of * the moon. */ enum class LunarPhase { Full=0, WaningGibbous=1, LastQuarter=2, WaningCrescent=3, New=4, WaxingCrescent=5, FirstQuarter=6, WaxingGibbous=7 }; /** * Specifies the different times of * day. */ enum class TimeOfDay { Day, Dusk, Night, Dawn }; /** * Keeps track of the time of day. */ class TimeModule : public Module { template <typename T> class bind_wrapper { public: T callback; inline void operator () () const noexcept(noexcept(callback())) { callback(); } }; private: mutable Mutex lock; // Time since last tick Timer timer; // Number of ticks std::atomic<Word> ticks; // Time spent ticking std::atomic<UInt64> tick_time; // Time spent executing ticks std::atomic<UInt64> executing; // Age of the world UInt64 age; // Time of day UInt64 time; // Time since last save UInt64 since; // If true time stops when // no one is logged in bool offline_freeze; // Ticks between saves UInt64 between_saves; // Number if milliseconds per // tick Word tick_length; // Threshold above which a tick // is considered "too long" Word threshold; // The percentage which is used // to derive the threshold Word threshold_percentage; // Tasks to be executed every // tick Vector< Tuple< // Callback std::function<void (MultiScopeGuard)>, // Whether the next tick should // wait for this task to finish bool > > callbacks; // Tasks to be executed at a certain // point in time Vector< Tuple< // Tick on which this task should // be executed Word, // Callback std::function<void (MultiScopeGuard)>, // Whether the next tick should // wait for this task to finish bool > > scheduled_callbacks; void tick (); void save (UInt64, UInt64) const; LunarPhase get_lunar_phase () const noexcept; UInt64 get_time (bool) const noexcept; TimeOfDay get_time_of_day () const noexcept; template <typename T, typename... Args> auto binder (T && callback, Args &&... args) -> decltype( std::bind( std::forward<T>(callback), std::forward<Args>(args)... ) ) { return std::bind( std::forward<T>(callback), std::forward<Args>(args)... ); } template <typename T> bind_wrapper<T> inner_wrapper (T && bound) { return bind_wrapper<T>{std::forward<T>(bound)}; } template <typename T> static void callback (MultiScopeGuard, T callback) { callback(); } template <typename T> auto outer_wrapper (T && wrapped) -> decltype( std::bind( callback<typename std::decay<T>::type>, std::placeholders::_1, std::move(wrapped) ) ) { return std::bind( callback<typename std::decay<T>::type>, std::placeholders::_1, std::move(wrapped) ); } template <typename T, typename... Args> auto wrap (T && callback, Args &&... args) -> decltype( outer_wrapper( inner_wrapper( binder( std::forward<T>(callback), std::forward<Args>(args)... ) ) ) ) { return outer_wrapper( inner_wrapper( binder( std::forward<T>(callback), std::forward<Args>(args)... ) ) ); } public: /** * Retrieves a string which describes * a phase of the moon. * * \param [in] phase * A phase of the moon. * * \return * A string which describes \em phase. */ static const String & GetLunarPhase (LunarPhase phase) noexcept; /** * Retrieves a string which describes * a time of day. * * \param [in] time_of_day * A time of day. * * \return * A string which describes \em time_of_day. */ static const String & GetTimeOfDay (TimeOfDay time_of_day) noexcept; TimeModule () noexcept; virtual const String & Name () const noexcept override; virtual Word Priority () const noexcept override; virtual void Install () override; /** * Determines the phase the moon is * currently in. * * \return * The current phase of the moon. */ LunarPhase GetLunarPhase () const noexcept; /** * Retrieves the current time. * * \param [in] total * If \em true the number of ticks * by which in game time has been * displaced from the start of this * world. If \em false the number * of ticks since midnight. Defaults * to \em false. * * \return * The current time. */ UInt64 GetTime (bool total=false) const noexcept; /** * Retrieves the current time of day. * * \return * The current time of day. */ TimeOfDay GetTimeOfDay () const noexcept; /** * Retrieves the age of the world. * * \return * The number of ticks that have * passed since this world began. */ UInt64 GetAge () const noexcept; /** * Gets all time-related information * atomically. * * \return * A tuple containing the current time, * the number of ticks since it was * last midnight, the current lunar phase, * the current time of day, and the current * world's age, respectively. */ Tuple<UInt64,UInt64,LunarPhase,TimeOfDay,UInt64> Get () const noexcept; /** * Adds a certain number of ticks to the * current time. * * The age of the world is unaffected. * * \param [in] ticks * The number of ticks to add to * the current time. */ void Add (UInt64 ticks) noexcept; /** * Subtracts a certain number of ticks * from the current time. * * If the current time would underflow * as a result of this subtraction, the * time is set to the smallest value which * causes the time to have the same displacement * from midnight as the subtraction would * have caused. * * The age of the world is unaffected. * * \param [in] ticks * The number of ticks to subtract from * the current time. */ void Subtract (UInt64 ticks) noexcept; /** * Sets the time to a certain value. * * \param [in] time * The time to set. * \param [in] total * If \em true the time will be set * to exactly \em time, otherwise * the time shall be adjusted so that * the difference between midinght * and the current time is the same * as the difference between midnight * and \em time. Defaults to \em false. */ void Set (UInt64 time, bool total=false) noexcept; /** * Causes the age of the world and * time of day to immediately be * saved to the backing store. */ void Save () const; /** * Enqueues a task to be asynchronously * invoked each tick. * * \tparam T * The type of callback which shall be * invoked each tick. * \tparam Args * The types of the arguments which shall * be passed through to the callback of * type \em T. * * \param [in] wait * If \em true each tick shall be * delayed until this task completes. * \param [in] callback * The callback which shall be invoked * each tick. * \param [in] args * The arguments which shall be forwarded * through to \em callback. */ template <typename T, typename... Args> void Enqueue (bool wait, T && callback, Args &&... args) { auto wrapped=wrap( std::forward<T>(callback), std::forward<Args>(args)... ); lock.Execute([&] () { callbacks.EmplaceBack( std::move(wrapped), wait ); }); } /** * Enqueues a task to be asynchronously invoked * after a certain number of ticks have passed. * * \tparam T * The type of callback which shall be * invoked. * \tparam Args * The types of the arguments which shall be * passed through to the callback of type * \em T. * * \param [in] ticks * The number of ticks after which \em callback * shall be invoked. * \param [in] wait * If \em true the tick after this task is * executed shall wait until the task completes. * \param [in] callback * The callback that shall be invoked after \em ticks * ticks. * \param [in] args * The arguments that shall be forwarded through to * \em callback. */ template <typename T, typename... Args> void Enqueue (Word ticks, bool wait, T && callback, Args &&... args) { auto wrapped=wrap( std::forward<T>(callback), std::forward<Args>(args)... ); lock.Execute([&] () { // Deduce execution time Word when=ticks+this->ticks; // Find insertion point Word i=0; for (;i<scheduled_callbacks.Count();++i) if (when<scheduled_callbacks[i].Item<0>()) break; // Insert scheduled_callbacks.Emplace( when, std::move(wrapped), wait ); }); } }; /** * The single valid instance of TimeModule. */ extern Nullable<TimeModule> Time; } <|endoftext|>
<commit_before>/* Copyright 2022 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <stdexcept> #include <string> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "cpp/array_record_reader.h" #include "cpp/array_record_writer.h" #include "cpp/thread_pool.h" #include "pybind11/gil.h" #include "pybind11/pybind11.h" #include "pybind11/pytypes.h" #include "pybind11/stl.h" #include "riegeli/bytes/fd_reader.h" #include "riegeli/bytes/fd_writer.h" namespace py = pybind11; PYBIND11_MODULE(array_record_module, m) { using ArrayRecordWriter = array_record::ArrayRecordWriter<std::unique_ptr<riegeli::Writer>>; using ArrayRecordReader = array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>; py::class_<ArrayRecordWriter>(m, "ArrayRecordWriter") .def(py::init([](const std::string& path, const std::string& options) { auto status_or_option = array_record::ArrayRecordWriterBase::Options::FromString( options); if (!status_or_option.ok()) { throw py::value_error( std::string(status_or_option.status().message())); } auto file_writer = std::make_unique<riegeli::FdWriter<>>(path); if (!file_writer->ok()) { throw std::runtime_error( std::string(file_writer->status().message())); } return array_record::ArrayRecordWriter< std::unique_ptr<riegeli::Writer>>(std::move(file_writer), status_or_option.value()); }), py::arg("path"), py::arg("options") = "") .def("ok", &ArrayRecordWriter::ok) .def("close", [](ArrayRecordWriter& writer) { if (!writer.Close()) { throw std::runtime_error(std::string(writer.status().message())); } }) .def("is_open", &ArrayRecordWriter::is_open) // We accept only py::bytes (and not unicode strings) since we expect // most users to store binary data (e.g. serialized protocol buffers). // We cannot know if a users wants to write+read unicode and forcing users // to encode() their unicode strings avoids accidential convertions. .def("write", [](ArrayRecordWriter& writer, py::bytes record) { if (!writer.WriteRecord(record)) { throw std::runtime_error(std::string(writer.status().message())); } }); py::class_<array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>>( m, "ArrayRecordReader") .def(py::init([](const std::string& path, const std::string& options) { auto status_or_option = array_record::ArrayRecordReaderBase::Options::FromString( options); if (!status_or_option.ok()) { throw py::value_error( std::string(status_or_option.status().message())); } auto file_reader = std::make_unique<riegeli::FdReader<>>(path); if (!file_reader->ok()) { throw std::runtime_error( std::string(file_reader->status().message())); } return array_record::ArrayRecordReader< std::unique_ptr<riegeli::Reader>>( std::move(file_reader), status_or_option.value(), array_record::ArrayRecordGlobalPool()); }), py::arg("path"), py::arg("options") = "") .def("ok", &ArrayRecordReader::ok) .def("close", [](ArrayRecordReader& reader) { if (!reader.Close()) { throw std::runtime_error(std::string(reader.status().message())); } }) .def("is_open", &ArrayRecordReader::is_open) .def("num_records", &ArrayRecordReader::NumRecords) .def("record_index", &ArrayRecordReader::RecordIndex) .def("writer_options_string", &ArrayRecordReader::WriterOptionsString) .def("seek", [](ArrayRecordReader& reader, int64_t record_index) { if (!reader.SeekRecord(record_index)) { throw std::runtime_error(std::string(reader.status().message())); } }) // See write() for why this returns py::bytes. .def("read", [](ArrayRecordReader& reader) { absl::string_view string_view; if (!reader.ReadRecord(&string_view)) { if (reader.ok()) { throw std::out_of_range(absl::StrFormat( "Out of range of num_records: %d", reader.NumRecords())); } throw std::runtime_error(std::string(reader.status().message())); } return py::bytes(string_view); }) .def("read", [](ArrayRecordReader& reader, std::vector<uint64_t> indices) { std::vector<std::string> staging(indices.size()); py::list output(indices.size()); { py::gil_scoped_release scoped_release; auto status = reader.ParallelReadRecordsWithIndices( indices, [&](uint64_t indices_index, absl::string_view record_data) -> absl::Status { staging[indices_index] = record_data; return absl::OkStatus(); }); if (!status.ok()) { throw std::runtime_error(std::string(status.message())); } } ssize_t index = 0; for (const auto& record : staging) { auto py_record = py::bytes(record); PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr()); } return output; }) .def("read", [](ArrayRecordReader& reader, int32_t begin, int32_t end) { int32_t range_begin = begin, range_end = end; if (range_begin < 0) { range_begin = reader.NumRecords() + range_begin; } if (range_end < 0) { range_end = reader.NumRecords() + range_end; } if (range_begin > reader.NumRecords() || range_begin < 0 || range_end > reader.NumRecords() || range_end < 0 || range_end <= range_begin) { throw std::out_of_range( absl::StrFormat("[%d, %d) is of range of [0, %d)", begin, end, reader.NumRecords())); } int32_t num_to_read = range_end - range_begin; std::vector<std::string> staging(num_to_read); py::list output(num_to_read); { py::gil_scoped_release scoped_release; auto status = reader.ParallelReadRecordsInRange( range_begin, range_end, [&](uint64_t index, absl::string_view record_data) -> absl::Status { staging[index - range_begin] = record_data; return absl::OkStatus(); }); if (!status.ok()) { throw std::runtime_error(std::string(status.message())); } } ssize_t index = 0; for (const auto& record : staging) { auto py_record = py::bytes(record); PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr()); } return output; }) .def("read_all", [](ArrayRecordReader& reader) { std::vector<std::string> staging(reader.NumRecords()); py::list output(reader.NumRecords()); { py::gil_scoped_release scoped_release; auto status = reader.ParallelReadRecords( [&](uint64_t index, absl::string_view record_data) -> absl::Status { staging[index] = record_data; return absl::OkStatus(); }); if (!status.ok()) { throw std::runtime_error(std::string(status.message())); } } ssize_t index = 0; for (const auto& record : staging) { auto py_record = py::bytes(record); PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr()); } return output; }); } <commit_msg>No-op: Unify the way array_record::ArrayRecord{Writer,Reader} are referenced<commit_after>/* Copyright 2022 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <stdexcept> #include <string> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "cpp/array_record_reader.h" #include "cpp/array_record_writer.h" #include "cpp/thread_pool.h" #include "pybind11/gil.h" #include "pybind11/pybind11.h" #include "pybind11/pytypes.h" #include "pybind11/stl.h" #include "riegeli/bytes/fd_reader.h" #include "riegeli/bytes/fd_writer.h" namespace py = pybind11; PYBIND11_MODULE(array_record_module, m) { using ArrayRecordWriter = array_record::ArrayRecordWriter<std::unique_ptr<riegeli::Writer>>; using ArrayRecordReader = array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>; py::class_<ArrayRecordWriter>(m, "ArrayRecordWriter") .def(py::init([](const std::string& path, const std::string& options) { auto status_or_option = array_record::ArrayRecordWriterBase::Options::FromString( options); if (!status_or_option.ok()) { throw py::value_error( std::string(status_or_option.status().message())); } auto file_writer = std::make_unique<riegeli::FdWriter<>>(path); if (!file_writer->ok()) { throw std::runtime_error( std::string(file_writer->status().message())); } return ArrayRecordWriter(std::move(file_writer), status_or_option.value()); }), py::arg("path"), py::arg("options") = "") .def("ok", &ArrayRecordWriter::ok) .def("close", [](ArrayRecordWriter& writer) { if (!writer.Close()) { throw std::runtime_error(std::string(writer.status().message())); } }) .def("is_open", &ArrayRecordWriter::is_open) // We accept only py::bytes (and not unicode strings) since we expect // most users to store binary data (e.g. serialized protocol buffers). // We cannot know if a users wants to write+read unicode and forcing users // to encode() their unicode strings avoids accidential convertions. .def("write", [](ArrayRecordWriter& writer, py::bytes record) { if (!writer.WriteRecord(record)) { throw std::runtime_error(std::string(writer.status().message())); } }); py::class_<ArrayRecordReader>(m, "ArrayRecordReader") .def(py::init([](const std::string& path, const std::string& options) { auto status_or_option = array_record::ArrayRecordReaderBase::Options::FromString( options); if (!status_or_option.ok()) { throw py::value_error( std::string(status_or_option.status().message())); } auto file_reader = std::make_unique<riegeli::FdReader<>>(path); if (!file_reader->ok()) { throw std::runtime_error( std::string(file_reader->status().message())); } return ArrayRecordReader(std::move(file_reader), status_or_option.value(), array_record::ArrayRecordGlobalPool()); }), py::arg("path"), py::arg("options") = "") .def("ok", &ArrayRecordReader::ok) .def("close", [](ArrayRecordReader& reader) { if (!reader.Close()) { throw std::runtime_error(std::string(reader.status().message())); } }) .def("is_open", &ArrayRecordReader::is_open) .def("num_records", &ArrayRecordReader::NumRecords) .def("record_index", &ArrayRecordReader::RecordIndex) .def("writer_options_string", &ArrayRecordReader::WriterOptionsString) .def("seek", [](ArrayRecordReader& reader, int64_t record_index) { if (!reader.SeekRecord(record_index)) { throw std::runtime_error(std::string(reader.status().message())); } }) // See write() for why this returns py::bytes. .def("read", [](ArrayRecordReader& reader) { absl::string_view string_view; if (!reader.ReadRecord(&string_view)) { if (reader.ok()) { throw std::out_of_range(absl::StrFormat( "Out of range of num_records: %d", reader.NumRecords())); } throw std::runtime_error(std::string(reader.status().message())); } return py::bytes(string_view); }) .def("read", [](ArrayRecordReader& reader, std::vector<uint64_t> indices) { std::vector<std::string> staging(indices.size()); py::list output(indices.size()); { py::gil_scoped_release scoped_release; auto status = reader.ParallelReadRecordsWithIndices( indices, [&](uint64_t indices_index, absl::string_view record_data) -> absl::Status { staging[indices_index] = record_data; return absl::OkStatus(); }); if (!status.ok()) { throw std::runtime_error(std::string(status.message())); } } ssize_t index = 0; for (const auto& record : staging) { auto py_record = py::bytes(record); PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr()); } return output; }) .def("read", [](ArrayRecordReader& reader, int32_t begin, int32_t end) { int32_t range_begin = begin, range_end = end; if (range_begin < 0) { range_begin = reader.NumRecords() + range_begin; } if (range_end < 0) { range_end = reader.NumRecords() + range_end; } if (range_begin > reader.NumRecords() || range_begin < 0 || range_end > reader.NumRecords() || range_end < 0 || range_end <= range_begin) { throw std::out_of_range( absl::StrFormat("[%d, %d) is of range of [0, %d)", begin, end, reader.NumRecords())); } int32_t num_to_read = range_end - range_begin; std::vector<std::string> staging(num_to_read); py::list output(num_to_read); { py::gil_scoped_release scoped_release; auto status = reader.ParallelReadRecordsInRange( range_begin, range_end, [&](uint64_t index, absl::string_view record_data) -> absl::Status { staging[index - range_begin] = record_data; return absl::OkStatus(); }); if (!status.ok()) { throw std::runtime_error(std::string(status.message())); } } ssize_t index = 0; for (const auto& record : staging) { auto py_record = py::bytes(record); PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr()); } return output; }) .def("read_all", [](ArrayRecordReader& reader) { std::vector<std::string> staging(reader.NumRecords()); py::list output(reader.NumRecords()); { py::gil_scoped_release scoped_release; auto status = reader.ParallelReadRecords( [&](uint64_t index, absl::string_view record_data) -> absl::Status { staging[index] = record_data; return absl::OkStatus(); }); if (!status.ok()) { throw std::runtime_error(std::string(status.message())); } } ssize_t index = 0; for (const auto& record : staging) { auto py_record = py::bytes(record); PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr()); } return output; }); } <|endoftext|>
<commit_before>#include "simdjson/jsonparser.h" #include <unistd.h> #include "benchmark.h" // #define RAPIDJSON_SSE2 // bad for performance // #define RAPIDJSON_SSE42 // bad for performance #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "sajson.h" #ifdef ALLPARSER #include "fastjson.cpp" #include "fastjson_dom.cpp" #include "gason.cpp" #include "json11.cpp" extern "C" { #include "ujdecode.h" #include "ultrajsondec.c" } #endif using namespace rapidjson; using namespace std; #ifdef ALLPARSER // fastjson has a tricky interface void on_json_error(void *, const fastjson::ErrorContext &ec) { // std::cerr<<"ERROR: "<<ec.mesg<<std::endl; } bool fastjson_parse(const char *input) { fastjson::Token token; fastjson::dom::Chunk chunk; return fastjson::dom::parse_string(input, &token, &chunk, 0, &on_json_error, NULL); } // end of fastjson stuff #endif int main(int argc, char *argv[]) { bool verbose = false; bool justdata = false; int c; while ((c = getopt(argc, argv, "vt")) != -1) switch (c) { case 't': justdata = true; break; case 'v': verbose = true; break; default: abort(); } if (optind >= argc) { cerr << "Usage: " << argv[0] << " <jsonfile>\n"; cerr << "Or " << argv[0] << " -v <jsonfile>\n"; cerr << "To enable parsers that are not standard compliant, use the -a " "flag\n"; exit(1); } const char *filename = argv[optind]; if (optind + 1 < argc) { cerr << "warning: ignoring everything after " << argv[optind + 1] << endl; } std::string_view p; try { p = get_corpus(filename); } catch (const std::exception &e) { // caught by reference to base std::cout << "Could not load the file " << filename << std::endl; return EXIT_FAILURE; } if (verbose) { std::cout << "Input has "; if (p.size() > 1024 * 1024) std::cout << p.size() / (1024 * 1024) << " MB "; else if (p.size() > 1024) std::cout << p.size() / 1024 << " KB "; else std::cout << p.size() << " B "; std::cout << std::endl; } ParsedJson pj; bool allocok = pj.allocateCapacity(p.size(), 1024); if (!allocok) { std::cerr << "can't allocate memory" << std::endl; return EXIT_FAILURE; } int repeat = 50; int volume = p.size(); if(justdata) { printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n"); } if(!justdata) BEST_TIME("simdjson (dynamic mem) ", build_parsed_json(p).isValid(), true, , repeat, volume, !justdata); // (static alloc) BEST_TIME("simdjson ", json_parse(p, pj), true, , repeat, volume, !justdata); rapidjson::Document d; char *buffer = (char *)malloc(p.size() + 1); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; if(!justdata) BEST_TIME( "RapidJSON (doc reused) ", d.Parse<kParseValidateEncodingFlag>((const char *)buffer).HasParseError(), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); BEST_TIME("RapidJSON", d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError(), false, memcpy(buffer, p.data(), p.size()) && (buffer[p.size()] = '\0'), repeat, volume, !justdata); if(!justdata) BEST_TIME("sajson (dynamic mem, insitu)", sajson::parse(sajson::dynamic_allocation(), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); size_t astbuffersize = p.size(); size_t *ast_buffer = (size_t *)malloc(astbuffersize * sizeof(size_t)); // (static alloc, insitu) BEST_TIME("sajson", sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); #ifdef ALLPARSER std::string json11err; if (all) BEST_TIME("dropbox (json11) ", ((json11::Json::parse(buffer, json11err).is_null()) || (!json11err.empty())), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); if (all) BEST_TIME("fastjson ", fastjson_parse(buffer), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); JsonValue value; JsonAllocator allocator; char *endptr; if (all) BEST_TIME("gason ", jsonParse(buffer, &endptr, &value, allocator), JSON_OK, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); void *state; if (all) BEST_TIME("ultrajson ", (UJDecode(buffer, p.size(), NULL, &state) == NULL), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); #endif if(!justdata) BEST_TIME("memcpy ", (memcpy(buffer, p.data(), p.size()) == buffer), true, , repeat, volume, !justdata); aligned_free((void *)p.data()); free(ast_buffer); free(buffer); } <commit_msg>More details.<commit_after>#include "simdjson/jsonparser.h" #ifndef _MSC_VER #include <unistd.h> #include "linux-perf-events.h" #ifdef __linux__ #include <libgen.h> #endif //__linux__ #endif // _MSC_VER #include "benchmark.h" // #define RAPIDJSON_SSE2 // bad for performance // #define RAPIDJSON_SSE42 // bad for performance #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "sajson.h" #ifdef ALLPARSER #include "fastjson.cpp" #include "fastjson_dom.cpp" #include "gason.cpp" #include "json11.cpp" extern "C" { #include "ujdecode.h" #include "ultrajsondec.c" } #endif using namespace rapidjson; using namespace std; #ifdef ALLPARSER // fastjson has a tricky interface void on_json_error(void *, const fastjson::ErrorContext &ec) { // std::cerr<<"ERROR: "<<ec.mesg<<std::endl; } bool fastjson_parse(const char *input) { fastjson::Token token; fastjson::dom::Chunk chunk; return fastjson::dom::parse_string(input, &token, &chunk, 0, &on_json_error, NULL); } // end of fastjson stuff #endif int main(int argc, char *argv[]) { bool verbose = false; bool justdata = false; int c; while ((c = getopt(argc, argv, "vt")) != -1) switch (c) { case 't': justdata = true; break; case 'v': verbose = true; break; default: abort(); } if (optind >= argc) { cerr << "Usage: " << argv[0] << " <jsonfile>\n"; cerr << "Or " << argv[0] << " -v <jsonfile>\n"; cerr << "To enable parsers that are not standard compliant, use the -a " "flag\n"; exit(1); } const char *filename = argv[optind]; if (optind + 1 < argc) { cerr << "warning: ignoring everything after " << argv[optind + 1] << endl; } std::string_view p; try { p = get_corpus(filename); } catch (const std::exception &e) { // caught by reference to base std::cout << "Could not load the file " << filename << std::endl; return EXIT_FAILURE; } if (verbose) { std::cout << "Input has "; if (p.size() > 1024 * 1024) std::cout << p.size() / (1024 * 1024) << " MB "; else if (p.size() > 1024) std::cout << p.size() / 1024 << " KB "; else std::cout << p.size() << " B "; std::cout << std::endl; } ParsedJson pj; bool allocok = pj.allocateCapacity(p.size(), 1024); if (!allocok) { std::cerr << "can't allocate memory" << std::endl; return EXIT_FAILURE; } int repeat = 50; int volume = p.size(); if(justdata) { printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n"); } if(!justdata) BEST_TIME("simdjson (dynamic mem) ", build_parsed_json(p).isValid(), true, , repeat, volume, !justdata); // (static alloc) BEST_TIME("simdjson ", json_parse(p, pj), true, , repeat, volume, !justdata); rapidjson::Document d; char *buffer = (char *)malloc(p.size() + 1); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; if(!justdata) BEST_TIME( "RapidJSON (doc reused) ", d.Parse<kParseValidateEncodingFlag>((const char *)buffer).HasParseError(), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); BEST_TIME("RapidJSON", d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError(), false, memcpy(buffer, p.data(), p.size()) && (buffer[p.size()] = '\0'), repeat, volume, !justdata); if(!justdata) BEST_TIME("sajson (dynamic mem, insitu)", sajson::parse(sajson::dynamic_allocation(), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); size_t astbuffersize = p.size(); size_t *ast_buffer = (size_t *)malloc(astbuffersize * sizeof(size_t)); // (static alloc, insitu) BEST_TIME("sajson", sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid(), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); #ifdef __linux__ if(!justdata) { vector<int> evts; evts.push_back(PERF_COUNT_HW_CPU_CYCLES); evts.push_back(PERF_COUNT_HW_INSTRUCTIONS); evts.push_back(PERF_COUNT_HW_BRANCH_MISSES); evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES); evts.push_back(PERF_COUNT_HW_CACHE_MISSES); LinuxEvents<PERF_TYPE_HARDWARE> unified(evts); vector<unsigned long long> results; vector<unsigned long long> stats; results.resize(evts.size()); stats.resize(evts.size()); std::fill(stats.begin(), stats.end(), 0);// unnecessary for(size_t i = 0; i < repeat; i++) { unified.start(); if(json_parse(p, pj) != true) printf("bug\n"); unified.end(results); std::transform (stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("simdjson: cycles %f instructions %f branchmisses %f cacheref %f cachemisses %f \n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat ); std::fill(stats.begin(), stats.end(), 0); for(size_t i = 0; i < repeat; i++) { memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; unified.start(); if(d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError() != false) printf("bug\n"); unified.end(results); std::transform (stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("RapidJSON: cycles %f instructions %f branchmisses %f cacheref %f cachemisses %f \n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat ); std::fill(stats.begin(), stats.end(), 0);// unnecessary for(size_t i = 0; i < repeat; i++) { memcpy(buffer, p.data(), p.size()); unified.start(); if(sajson::parse(sajson::bounded_allocation(ast_buffer, astbuffersize), sajson::mutable_string_view(p.size(), buffer)) .is_valid() != true) printf("bug\n"); unified.end(results); std::transform (stats.begin(), stats.end(), results.begin(), stats.begin(), std::plus<unsigned long long>()); } printf("sajson: cycles %f instructions %f branchmisses %f cacheref %f cachemisses %f \n", stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat, stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat, stats[4] * 1.0 / repeat ); } #endif// __linux__ #ifdef ALLPARSER std::string json11err; if (all) BEST_TIME("dropbox (json11) ", ((json11::Json::parse(buffer, json11err).is_null()) || (!json11err.empty())), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); if (all) BEST_TIME("fastjson ", fastjson_parse(buffer), true, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); JsonValue value; JsonAllocator allocator; char *endptr; if (all) BEST_TIME("gason ", jsonParse(buffer, &endptr, &value, allocator), JSON_OK, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); void *state; if (all) BEST_TIME("ultrajson ", (UJDecode(buffer, p.size(), NULL, &state) == NULL), false, memcpy(buffer, p.data(), p.size()), repeat, volume, !justdata); #endif if(!justdata) BEST_TIME("memcpy ", (memcpy(buffer, p.data(), p.size()) == buffer), true, , repeat, volume, !justdata); aligned_free((void *)p.data()); free(ast_buffer); free(buffer); } <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan [email protected] Contact: Nokia Corporation [email protected] Contact: Nokia Corporation [email protected] You may use this file under the terms of the BSD license as follows: 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 Nokia Corporation and its Subsidiary(-ies) 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 "trackpad.h" #include <QtGui> Trackpad::Trackpad(QObject *p) : QObject(p), parent(p) { } Trackpad::~Trackpad() { } void Trackpad::setRecipient(QObject *recipient) { #ifndef QT5 QDeclarativeView *potentialDeclarativeView = qobject_cast<QDeclarativeView*>(recipient); if (potentialDeclarativeView) { m_recipientContext = QWeakPointer<QDeclarativeContext>(potentialDeclarativeView->rootContext()); m_recipient = QWeakPointer<QWidget>(potentialDeclarativeView->viewport()); } #endif } void Trackpad::setEnabled(bool e) { #ifndef QT5 if(m_recipientContext.isNull()) { qWarning("Trying to use Declarative specific functionality outside of Declarative"); return; } QDeclarativeExpression expression(m_recipientContext.data(), 0, QString("runtime.cursor.enableCursor(%1)").arg(e)); expression.evaluate(); if (expression.hasError()) qWarning() << "Failed to enable/disable cursor"; #endif } void Trackpad::moveBy(qlonglong x, qlonglong y) { #ifndef QT5 if(m_recipientContext.isNull()) { qWarning("Trying to use Declarative specific functionality outside of Declarative"); return; } QDeclarativeExpression expression(m_recipientContext.data(), 0, QString("runtime.cursor.moveBy(%1,%2)").arg(x).arg(y)); expression.evaluate(); if (expression.hasError()) qWarning() << "Failed to enable/disable cursor"; #endif } void Trackpad::click() { #ifndef QT5 if(m_recipient.isNull()) { qFatal("No recipient has been specified for mouse events"); return; } QPoint globalPos = QCursor::pos(); QPoint localPos = m_recipient.data()->mapFromGlobal(globalPos); QMouseEvent mousePress(QEvent::MouseButtonPress, localPos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); qApp->sendEvent(m_recipient.data(), &mousePress); QMouseEvent mouseRelease(QEvent::MouseButtonRelease, localPos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); qApp->sendEvent(m_recipient.data(), &mouseRelease); #endif } <commit_msg>follow-up commit for dc4e5ee3f1<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan [email protected] Contact: Nokia Corporation [email protected] Contact: Nokia Corporation [email protected] You may use this file under the terms of the BSD license as follows: 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 Nokia Corporation and its Subsidiary(-ies) 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 "trackpad.h" #include <QtGui> #ifndef QT5 #include <QtDeclarative> #endif Trackpad::Trackpad(QObject *p) : QObject(p), parent(p) { } Trackpad::~Trackpad() { } void Trackpad::setRecipient(QObject *recipient) { #ifndef QT5 QDeclarativeView *potentialDeclarativeView = qobject_cast<QDeclarativeView*>(recipient); if (potentialDeclarativeView) { m_recipientContext = QWeakPointer<QDeclarativeContext>(potentialDeclarativeView->rootContext()); m_recipient = QWeakPointer<QWidget>(potentialDeclarativeView->viewport()); } #endif } void Trackpad::setEnabled(bool e) { #ifndef QT5 if(m_recipientContext.isNull()) { qWarning("Trying to use Declarative specific functionality outside of Declarative"); return; } QDeclarativeExpression expression(m_recipientContext.data(), 0, QString("runtime.cursor.enableCursor(%1)").arg(e)); expression.evaluate(); if (expression.hasError()) qWarning() << "Failed to enable/disable cursor"; #endif } void Trackpad::moveBy(qlonglong x, qlonglong y) { #ifndef QT5 if(m_recipientContext.isNull()) { qWarning("Trying to use Declarative specific functionality outside of Declarative"); return; } QDeclarativeExpression expression(m_recipientContext.data(), 0, QString("runtime.cursor.moveBy(%1,%2)").arg(x).arg(y)); expression.evaluate(); if (expression.hasError()) qWarning() << "Failed to enable/disable cursor"; #endif } void Trackpad::click() { #ifndef QT5 if(m_recipient.isNull()) { qFatal("No recipient has been specified for mouse events"); return; } QPoint globalPos = QCursor::pos(); QPoint localPos = m_recipient.data()->mapFromGlobal(globalPos); QMouseEvent mousePress(QEvent::MouseButtonPress, localPos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); qApp->sendEvent(m_recipient.data(), &mousePress); QMouseEvent mouseRelease(QEvent::MouseButtonRelease, localPos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); qApp->sendEvent(m_recipient.data(), &mouseRelease); #endif } <|endoftext|>
<commit_before>/* * trakstar.cpp * * Created on: Nov 05, 2013 * Author: Bjorn Blissing */ #include "trakstar.h" #include <iostream> TrakStar::TrakStar() : m_sensor(0), m_transmitter(0), m_initialized(false), m_numberOfSensors(0), m_numberOfTransmitters(0) { initialize(); } TrakStar::~TrakStar() { shutdownTransmittor(); delete[] m_transmitter; delete[] m_sensor; }; int TrakStar::shutdownTransmittor() { int id = -1; return SetSystemParameter(SELECT_TRANSMITTER, &id, sizeof(id)); } int TrakStar::initialize() { int errorCode = 0; // Try to Initialize BIRD System errorCode = InitializeBIRDSystem(); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to initialize BIRD System." << std::endl; return errorCode; } // Get system configuration errorCode = GetBIRDSystemConfiguration(&m_system); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get system configuration of BIRD System." << std::endl; return errorCode; } // Get number of sensors and try to get sensor information m_numberOfSensors = static_cast<unsigned short>(m_system.numberSensors); m_sensor = new SENSOR_CONFIGURATION[m_numberOfSensors]; for (USHORT i = 0; i < m_system.numberSensors; ++i) { errorCode = GetSensorConfiguration(i, (m_sensor+i)); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get sensor configuration for sensor id: " << i << std::endl; return errorCode; } } // Get transmitter configuration m_numberOfTransmitters = static_cast<unsigned short>(m_system.numberTransmitters); m_transmitter = new TRANSMITTER_CONFIGURATION[m_numberOfTransmitters]; for (USHORT i = 0; i < m_system.numberTransmitters; ++i) { errorCode = GetTransmitterConfiguration(i, (m_transmitter+i)); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get transmitter configuration for transmitter id: " << i << std::endl; return errorCode; } } // Search for first active transmitter and turn it on for (USHORT id = 0; id < m_system.numberTransmitters; ++id) { if ((m_transmitter+id)->attached) { // Transmitter selection is a system function. // Using the SELECT_TRANSMITTER parameter we send the id of the // transmitter that we want to run with the SetSystemParameter() call errorCode = SetSystemParameter(SELECT_TRANSMITTER, &id, sizeof(id)); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable turn on transmitter id: " << id << std::endl; return errorCode; } break; } } m_initialized = true; return 0; } void TrakStar::getPosition(unsigned short sensorId, double& x, double& y, double& z) { DOUBLE_POSITION_ANGLES_RECORD record; int errorCode = GetAsynchronousRecord(sensorId, &record, sizeof(record)); if (errorCode != BIRD_ERROR_SUCCESS) { x = 0; y = 0; z = 0; } else { x = record.x; y = record.y; z = record.z; } } void TrakStar::getOrientation(unsigned short sensorId, double& azimuth, double& elevation, double& roll) { DOUBLE_POSITION_ANGLES_RECORD record; int errorCode = GetAsynchronousRecord(sensorId, &record, sizeof(record)); if (errorCode != BIRD_ERROR_SUCCESS) { azimuth = 0; elevation = 0; roll = 0; } else { azimuth = record.a; elevation = record.e; roll = record.r; } } <commit_msg>Change to 50 Hz power line frequency and metric measurments.<commit_after>/* * trakstar.cpp * * Created on: Nov 05, 2013 * Author: Bjorn Blissing */ #include "trakstar.h" #include <iostream> TrakStar::TrakStar() : m_sensor(0), m_transmitter(0), m_initialized(false), m_numberOfSensors(0), m_numberOfTransmitters(0) { initialize(); } TrakStar::~TrakStar() { shutdownTransmittor(); delete[] m_transmitter; delete[] m_sensor; }; int TrakStar::shutdownTransmittor() { int id = -1; return SetSystemParameter(SELECT_TRANSMITTER, &id, sizeof(id)); } int TrakStar::initialize() { int errorCode = 0; // Try to Initialize BIRD System errorCode = InitializeBIRDSystem(); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to initialize BIRD System." << std::endl; return errorCode; } // Get system configuration errorCode = GetBIRDSystemConfiguration(&m_system); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get system configuration of BIRD System." << std::endl; return errorCode; } // Get number of sensors and try to get sensor information m_numberOfSensors = static_cast<unsigned short>(m_system.numberSensors); m_sensor = new SENSOR_CONFIGURATION[m_numberOfSensors]; for (USHORT i = 0; i < m_system.numberSensors; ++i) { errorCode = GetSensorConfiguration(i, (m_sensor+i)); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get sensor configuration for sensor id: " << i << std::endl; return errorCode; } } // Set system settings double pl = 50.0; // 50 Hz power line errorCode = SetSystemParameter(POWER_LINE_FREQUENCY, &pl, sizeof(pl)); if(errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get set system configuration: Power Line." << std::endl; return errorCode; } BOOL metric = true; // metric reporting enabled errorCode = SetSystemParameter(METRIC, &metric, sizeof(metric)); if(errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get set system configuration: Metric mode." << std::endl; return errorCode; } // Get transmitter configuration m_numberOfTransmitters = static_cast<unsigned short>(m_system.numberTransmitters); m_transmitter = new TRANSMITTER_CONFIGURATION[m_numberOfTransmitters]; for (USHORT i = 0; i < m_system.numberTransmitters; ++i) { errorCode = GetTransmitterConfiguration(i, (m_transmitter+i)); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable to get transmitter configuration for transmitter id: " << i << std::endl; return errorCode; } } // Search for first active transmitter and turn it on for (USHORT id = 0; id < m_system.numberTransmitters; ++id) { if ((m_transmitter+id)->attached) { // Transmitter selection is a system function. // Using the SELECT_TRANSMITTER parameter we send the id of the // transmitter that we want to run with the SetSystemParameter() call errorCode = SetSystemParameter(SELECT_TRANSMITTER, &id, sizeof(id)); if (errorCode != BIRD_ERROR_SUCCESS) { std::cerr << "Error: Unable turn on transmitter id: " << id << std::endl; return errorCode; } break; } } m_initialized = true; return 0; } void TrakStar::getPosition(unsigned short sensorId, double& x, double& y, double& z) { DOUBLE_POSITION_ANGLES_RECORD record; int errorCode = GetAsynchronousRecord(sensorId, &record, sizeof(record)); if (errorCode != BIRD_ERROR_SUCCESS) { x = 0; y = 0; z = 0; } else { x = record.x; y = record.y; z = record.z; } } void TrakStar::getOrientation(unsigned short sensorId, double& azimuth, double& elevation, double& roll) { DOUBLE_POSITION_ANGLES_RECORD record; int errorCode = GetAsynchronousRecord(sensorId, &record, sizeof(record)); if (errorCode != BIRD_ERROR_SUCCESS) { azimuth = 0; elevation = 0; roll = 0; } else { azimuth = record.a; elevation = record.e; roll = record.r; } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ //______________________________________________________________________________ // Analysis task for providing various flow informations // author: D.J. Kim([email protected]) // ALICE Group University of Jyvaskyla // Finland // // Fill the analysis containers for ESD or AOD // Note: Adapted for AliAnalysisTaskSE ////////////////////////////////////////////////////////////////////////////// #include <AliAnalysisManager.h> #include <AliQnCorrectionsManager.h> #include <AliJBaseTrack.h> #include "AliJFlowBaseTask.h" static double decAcc[AliJFlowBaseTask::D_COUNT][2] = { {-0.8,0.8}, {-1.5,-0.8}, {0.8,1.5}, {2.8,5.1}, // V0A {-3.7,-1.7}, // V0C {2.8,5.1}, // V0P+ need to do it manually {2.5,5.1} // Virtual dector +- }; //______________________________________________________________________________ AliJFlowBaseTask::AliJFlowBaseTask() : AliAnalysisTaskSE("JFlowBaseTask"), fJCatalystTask(NULL), fJCatalystTaskName("JCatalystTask"), fFlowVectorTask(NULL), fIsMC(kTRUE), fhistos(NULL), fCBin(-1), fOutput(NULL) { } //______________________________________________________________________________ AliJFlowBaseTask::AliJFlowBaseTask(const char *name, TString inputformat): AliAnalysisTaskSE(name), fJCatalystTask(NULL), fJCatalystTaskName("JCatalystTask"), fFlowVectorTask(NULL), fIsMC(kTRUE), fhistos(NULL), fCBin(-1), fOutput(NULL) { // Constructor AliInfo("---- AliJFlowBaseTask Constructor ----"); for(uint i=0;i<D_COUNT;i++) { for(uint j=0;j<2;j++) fEventPlaneALICE[i][j] =-999; } DefineOutput (1, TDirectory::Class()); } //____________________________________________________________________________ AliJFlowBaseTask::AliJFlowBaseTask(const AliJFlowBaseTask& ap) : AliAnalysisTaskSE(ap.GetName()), fJCatalystTask(ap.fJCatalystTask), fJCatalystTaskName(ap.fJCatalystTaskName), fFlowVectorTask(ap.fFlowVectorTask), fIsMC(ap.fIsMC), fhistos(ap.fhistos), fCBin(ap.fCBin), fOutput( ap.fOutput ) { AliInfo("----DEBUG AliJFlowBaseTask COPY ----"); } //_____________________________________________________________________________ AliJFlowBaseTask& AliJFlowBaseTask::operator = (const AliJFlowBaseTask& ap) { // assignment operator AliInfo("----DEBUG AliJFlowBaseTask operator= ----"); this->~AliJFlowBaseTask(); new(this) AliJFlowBaseTask(ap); return *this; } //______________________________________________________________________________ AliJFlowBaseTask::~AliJFlowBaseTask() { // destructor delete fOutput; delete fhistos; } //________________________________________________________________________ void AliJFlowBaseTask::UserCreateOutputObjects() { //=== create the jcorran outputs objects if(fDebug > 1) printf("AliJFlowBaseTask::UserCreateOutPutData() \n"); //=== Get AnalysisManager AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager(); fJCatalystTask = (AliJCatalystTask*)(man->GetTask( fJCatalystTaskName )); if(!fIsMC) fFlowVectorTask = (AliAnalysisTaskFlowVectorCorrections*)(man->GetTask("FlowQnVectorCorrections")); OpenFile(1); fOutput = gDirectory; fOutput->cd(); fhistos = new AliJFlowHistos(); fhistos->CreateEventTrackHistos(); fhistos->fHMG->Print(); PostData(1, fOutput); } //______________________________________________________________________________ void AliJFlowBaseTask::UserExec(Option_t* /*option*/) { // Processing of one event if(fDebug > 5) cout << "------- AliJFlowBaseTask Exec-------"<<endl; if(!((Entry()-1)%100)) AliInfo(Form(" Processing event # %lld", Entry())); if( fJCatalystTask->GetJCatalystEntry() != fEntry ) return; fCBin = AliJFlowHistos::GetCentralityClass(fJCatalystTask->GetCentrality()); if(fCBin == -1) return; if(fIsMC) { TClonesArray *fInputList = (TClonesArray*)fJCatalystTask->GetInputList(); CalculateEventPlane(fInputList); } else { AliQnCorrectionsManager *fFlowVectorMgr = fFlowVectorTask->GetAliQnCorrectionsManager(); for(int iH=2;iH<=3;iH++) { fEventPlaneALICE[D_TPC][iH-2] = fFlowVectorMgr->GetDetectorQnVector("TPC")->EventPlane(iH); fEventPlaneALICE[D_V0P][iH-2] = fFlowVectorMgr->GetDetectorQnVector("VZERO")->EventPlane(iH); fEventPlaneALICE[D_V0A][iH-2] = fFlowVectorMgr->GetDetectorQnVector("VZEROA")->EventPlane(iH); fEventPlaneALICE[D_V0C][iH-2] = fFlowVectorMgr->GetDetectorQnVector("VZEROC")->EventPlane(iH); } for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ if (is != D_TPC && is != D_V0A && is != D_V0C) continue; for(int iH=2;iH<=3;iH++) { double EPref = fEventPlaneALICE[D_V0A][iH-2]; double EP = fEventPlaneALICE[is][iH-2]; fhistos->fhEPCorrInHar[fCBin][is][iH-2]->Fill( EP-EPref ); fhistos->fhEPCorr2D[fCBin][is][iH-2]->Fill(EP,EPref); } } } } //______________________________________________________________________________ void AliJFlowBaseTask::Init() { // Intialisation of parameters AliInfo("Doing initialization") ; } //______________________________________________________________________________ void AliJFlowBaseTask::Terminate(Option_t *) { // Processing when the event loop is ended cout<<"AliJFlowBaseTask Analysis DONE !!"<<endl; } //______________________________________________________________________________ void AliJFlowBaseTask::CalculateEventPlane(TClonesArray *inList) { int NtracksDEC[AliJFlowBaseTask::D_COUNT]; // Num of particle in each dector int noTracks = inList->GetEntries(); for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++) { NtracksDEC[is] = 0; for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] = TComplex(0,0); } } for(int itrack=0;itrack<noTracks; itrack++){ AliJBaseTrack *trk = (AliJBaseTrack*)inList->At(itrack); double phi = trk->Phi(); double eta = trk->Eta(); for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ if(is == AliJFlowBaseTask::D_VIRT) { if(decAcc[is][0]<eta && decAcc[is][1]>eta) { for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] += TComplex(TMath::Cos(iH*phi),TMath::Sin(iH*phi));} NtracksDEC[is]++; fhistos->fh_eta[fCBin][is]->Fill(eta); fhistos->fh_phi[fCBin][is]->Fill(phi); fhistos->fh_pt[fCBin][is]->Fill(trk->Pt()); } } else if(is == AliJFlowBaseTask::D_V0P) { if((decAcc[AliJFlowBaseTask::D_V0A][0]<eta && decAcc[AliJFlowBaseTask::D_V0A][1]>eta) || (decAcc[AliJFlowBaseTask::D_V0C][0]<eta && decAcc[AliJFlowBaseTask::D_V0C][1]>eta) ) { for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] += TComplex(TMath::Cos(iH*phi),TMath::Sin(iH*phi));} NtracksDEC[is]++; fhistos->fh_eta[fCBin][is]->Fill(eta); fhistos->fh_phi[fCBin][is]->Fill(phi); fhistos->fh_pt[fCBin][is]->Fill(trk->Pt()); } } else { if(decAcc[is][0]<eta && decAcc[is][1]>eta) { for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] += TComplex(TMath::Cos(iH*phi),TMath::Sin(iH*phi));} NtracksDEC[is]++; fhistos->fh_eta[fCBin][is]->Fill(eta); fhistos->fh_phi[fCBin][is]->Fill(phi); fhistos->fh_pt[fCBin][is]->Fill(trk->Pt()); } } } } for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] /= (double)NtracksDEC[is]; QvectorsEP[is][iH-2] = QvectorsEP[is][iH-2]/TComplex::Abs(QvectorsEP[is][iH-2]); fhistos->fh_EP[fCBin][is][iH-2]->Fill(QvectorsEP[is][iH-2].Theta()/double(iH)); } } // Calculation resolution for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ for(int iH=2;iH<=3;iH++) { double EPref = QvectorsEP[D_V0A][iH-2].Theta()/double(iH); double EP = QvectorsEP[is][iH-2].Theta()/double(iH); fhistos->fhEPCorrInHar[fCBin][is][iH-2]->Fill( EP-EPref ); fhistos->fhEPCorr2D[fCBin][is][iH-2]->Fill(EPref,EP); } } } <commit_msg>only for calibration EP<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ //______________________________________________________________________________ // Analysis task for providing various flow informations // author: D.J. Kim([email protected]) // ALICE Group University of Jyvaskyla // Finland // // Fill the analysis containers for ESD or AOD // Note: Adapted for AliAnalysisTaskSE ////////////////////////////////////////////////////////////////////////////// #include <AliAnalysisManager.h> #include <AliQnCorrectionsManager.h> #include <AliJBaseTrack.h> #include "AliJFlowBaseTask.h" static double decAcc[AliJFlowBaseTask::D_COUNT][2] = { {-0.8,0.8}, {-1.5,-0.8}, {0.8,1.5}, {2.8,5.1}, // V0A {-3.7,-1.7}, // V0C {2.8,5.1}, // V0P+ need to do it manually {2.5,5.1} // Virtual dector +- }; //______________________________________________________________________________ AliJFlowBaseTask::AliJFlowBaseTask() : AliAnalysisTaskSE("JFlowBaseTask"), fJCatalystTask(NULL), fJCatalystTaskName("JCatalystTask"), fFlowVectorTask(NULL), fIsMC(kTRUE), fhistos(NULL), fCBin(-1), fOutput(NULL) { } //______________________________________________________________________________ AliJFlowBaseTask::AliJFlowBaseTask(const char *name, TString inputformat): AliAnalysisTaskSE(name), fJCatalystTask(NULL), fJCatalystTaskName("JCatalystTask"), fFlowVectorTask(NULL), fIsMC(kTRUE), fhistos(NULL), fCBin(-1), fOutput(NULL) { // Constructor AliInfo("---- AliJFlowBaseTask Constructor ----"); for(uint i=0;i<D_COUNT;i++) { for(uint j=0;j<2;j++) fEventPlaneALICE[i][j] =-999; } DefineOutput (1, TDirectory::Class()); } //____________________________________________________________________________ AliJFlowBaseTask::AliJFlowBaseTask(const AliJFlowBaseTask& ap) : AliAnalysisTaskSE(ap.GetName()), fJCatalystTask(ap.fJCatalystTask), fJCatalystTaskName(ap.fJCatalystTaskName), fFlowVectorTask(ap.fFlowVectorTask), fIsMC(ap.fIsMC), fhistos(ap.fhistos), fCBin(ap.fCBin), fOutput( ap.fOutput ) { AliInfo("----DEBUG AliJFlowBaseTask COPY ----"); } //_____________________________________________________________________________ AliJFlowBaseTask& AliJFlowBaseTask::operator = (const AliJFlowBaseTask& ap) { // assignment operator AliInfo("----DEBUG AliJFlowBaseTask operator= ----"); this->~AliJFlowBaseTask(); new(this) AliJFlowBaseTask(ap); return *this; } //______________________________________________________________________________ AliJFlowBaseTask::~AliJFlowBaseTask() { // destructor delete fOutput; delete fhistos; } //________________________________________________________________________ void AliJFlowBaseTask::UserCreateOutputObjects() { //=== create the jcorran outputs objects if(fDebug > 1) printf("AliJFlowBaseTask::UserCreateOutPutData() \n"); //=== Get AnalysisManager AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager(); fJCatalystTask = (AliJCatalystTask*)(man->GetTask( fJCatalystTaskName )); if(!fIsMC) fFlowVectorTask = (AliAnalysisTaskFlowVectorCorrections*)(man->GetTask("FlowQnVectorCorrections")); OpenFile(1); fOutput = gDirectory; fOutput->cd(); fhistos = new AliJFlowHistos(); fhistos->CreateEventTrackHistos(); fhistos->fHMG->Print(); PostData(1, fOutput); } //______________________________________________________________________________ void AliJFlowBaseTask::UserExec(Option_t* /*option*/) { // Processing of one event if(fDebug > 5) cout << "------- AliJFlowBaseTask Exec-------"<<endl; if(!((Entry()-1)%100)) AliInfo(Form(" Processing event # %lld", Entry())); if( fJCatalystTask->GetJCatalystEntry() != fEntry ) return; fCBin = AliJFlowHistos::GetCentralityClass(fJCatalystTask->GetCentrality()); if(fCBin == -1) return; if(fIsMC) { TClonesArray *fInputList = (TClonesArray*)fJCatalystTask->GetInputList(); CalculateEventPlane(fInputList); } else { static const char *pdetn[] = {"TPC","VZERO","VZEROA","VZEROC"}; static int newDetID[] = {D_TPC,D_V0P,D_V0A,D_V0C}; AliQnCorrectionsManager *fFlowVectorMgr = fFlowVectorTask->GetAliQnCorrectionsManager(); const AliQnCorrectionsQnVector *fQnVector; for(UInt_t di = 0; di < sizeof(pdetn)/sizeof(pdetn[0]); ++di) { for(int iH=2;iH<=3;iH++) { fQnVector = fFlowVectorMgr->GetDetectorQnVector(pdetn[di]); if(fQnVector) fEventPlaneALICE[newDetID[di]][iH-2] = fQnVector->EventPlane(iH); } } for(UInt_t di = 0; di < sizeof(pdetn)/sizeof(pdetn[0]); ++di) { for(int iH=2;iH<=3;iH++) { double EPref = fEventPlaneALICE[newDetID[di]][iH-2]; double EP = fEventPlaneALICE[newDetID[di]][iH-2]; fhistos->fhEPCorrInHar[fCBin][newDetID[di]][iH-2]->Fill( EP-EPref ); fhistos->fhEPCorr2D[fCBin][newDetID[di]][iH-2]->Fill(EP,EPref); } } } } //______________________________________________________________________________ void AliJFlowBaseTask::Init() { // Intialisation of parameters AliInfo("Doing initialization") ; } //______________________________________________________________________________ void AliJFlowBaseTask::Terminate(Option_t *) { // Processing when the event loop is ended cout<<"AliJFlowBaseTask Analysis DONE !!"<<endl; } //______________________________________________________________________________ void AliJFlowBaseTask::CalculateEventPlane(TClonesArray *inList) { int NtracksDEC[AliJFlowBaseTask::D_COUNT]; // Num of particle in each dector int noTracks = inList->GetEntries(); for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++) { NtracksDEC[is] = 0; for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] = TComplex(0,0); } } for(int itrack=0;itrack<noTracks; itrack++){ AliJBaseTrack *trk = (AliJBaseTrack*)inList->At(itrack); double phi = trk->Phi(); double eta = trk->Eta(); for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ if(is == AliJFlowBaseTask::D_VIRT) { if(decAcc[is][0]<eta && decAcc[is][1]>eta) { for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] += TComplex(TMath::Cos(iH*phi),TMath::Sin(iH*phi));} NtracksDEC[is]++; fhistos->fh_eta[fCBin][is]->Fill(eta); fhistos->fh_phi[fCBin][is]->Fill(phi); fhistos->fh_pt[fCBin][is]->Fill(trk->Pt()); } } else if(is == AliJFlowBaseTask::D_V0P) { if((decAcc[AliJFlowBaseTask::D_V0A][0]<eta && decAcc[AliJFlowBaseTask::D_V0A][1]>eta) || (decAcc[AliJFlowBaseTask::D_V0C][0]<eta && decAcc[AliJFlowBaseTask::D_V0C][1]>eta) ) { for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] += TComplex(TMath::Cos(iH*phi),TMath::Sin(iH*phi));} NtracksDEC[is]++; fhistos->fh_eta[fCBin][is]->Fill(eta); fhistos->fh_phi[fCBin][is]->Fill(phi); fhistos->fh_pt[fCBin][is]->Fill(trk->Pt()); } } else { if(decAcc[is][0]<eta && decAcc[is][1]>eta) { for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] += TComplex(TMath::Cos(iH*phi),TMath::Sin(iH*phi));} NtracksDEC[is]++; fhistos->fh_eta[fCBin][is]->Fill(eta); fhistos->fh_phi[fCBin][is]->Fill(phi); fhistos->fh_pt[fCBin][is]->Fill(trk->Pt()); } } } } for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ for(int iH=2;iH<=3;iH++) { QvectorsEP[is][iH-2] /= (double)NtracksDEC[is]; QvectorsEP[is][iH-2] = QvectorsEP[is][iH-2]/TComplex::Abs(QvectorsEP[is][iH-2]); fhistos->fh_EP[fCBin][is][iH-2]->Fill(QvectorsEP[is][iH-2].Theta()/double(iH)); } } // Calculation resolution for(int is = 0; is < AliJFlowBaseTask::D_COUNT; is++){ for(int iH=2;iH<=3;iH++) { double EPref = QvectorsEP[D_V0A][iH-2].Theta()/double(iH); double EP = QvectorsEP[is][iH-2].Theta()/double(iH); fhistos->fhEPCorrInHar[fCBin][is][iH-2]->Fill( EP-EPref ); fhistos->fhEPCorr2D[fCBin][is][iH-2]->Fill(EPref,EP); } } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/software/license/ * * 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 <cstdlib> #include <iostream> #include <cmath> #include "Gaussian2DModel.h" #include "RegularStepGradientDescentSampler.h" #include "Trace.h" int main(int argc, char *argv[]) { madai::Gaussian2DModel *model = new madai::Gaussian2DModel(); model->LoadConfigurationFile( "file.txt" ); // TODO - does nothing madai::RegularStepGradientDescentSampler *sampler = new madai::RegularStepGradientDescentSampler(); sampler->SetModel( model ); sampler->MinimizeOff(); // We want to maximize this function //madai::Trace *trace = new madai::Trace(); madai::Trace trace; // Set the step size. double stepSize = 20.0; sampler->SetStepSize( stepSize ); // // Pick which output scalar to optimize. // sampler->SetOutputScalarToOptimize( "Value " ); // Set initial parameter values. sampler->SetParameterValue( "X", 21.0 ); sampler->SetParameterValue( "Y", -13.5 ); std::vector< double > currentParameters; for (unsigned int i = 0; i < 50; i++) { currentParameters = sampler->GetCurrentParameters(); madai::Sample sample = sampler->NextSample(); trace.Add( sample ); } double modelMeanX; double modelMeanY; model->GetMeans( modelMeanX, modelMeanY ); if ( std::abs( modelMeanX - currentParameters[0] ) > 1.0e-3 || std::abs( modelMeanY - currentParameters[1] ) > 1.0e-3 ) { std::cerr << "RegularStepGradientDescentSampler failed to converge " << "on the expected solution." << std::endl; std::cerr << "Expected currentParameters to be (" << modelMeanX << ", " << modelMeanY << "), got (" << currentParameters[0] << ", " << currentParameters[1] << ") instead." << std::endl; return EXIT_FAILURE; } //delete trace; return EXIT_SUCCESS; } <commit_msg>Need to minimize on the log likelihood?<commit_after>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/software/license/ * * 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 <cstdlib> #include <iostream> #include <cmath> #include "Gaussian2DModel.h" #include "RegularStepGradientDescentSampler.h" #include "Trace.h" int main(int argc, char *argv[]) { madai::Gaussian2DModel *model = new madai::Gaussian2DModel(); model->LoadConfigurationFile( "file.txt" ); // TODO - does nothing madai::RegularStepGradientDescentSampler *sampler = new madai::RegularStepGradientDescentSampler(); sampler->SetModel( model ); sampler->MinimizeOn(); // We want to minimize this function //madai::Trace *trace = new madai::Trace(); madai::Trace trace; // Set the step size. double stepSize = 20.0; sampler->SetStepSize( stepSize ); // // Pick which output scalar to optimize. // sampler->SetOutputScalarToOptimize( "Value " ); // Set initial parameter values. sampler->SetParameterValue( "X", 21.0 ); sampler->SetParameterValue( "Y", -13.5 ); std::vector< double > currentParameters; for (unsigned int i = 0; i < 50; i++) { currentParameters = sampler->GetCurrentParameters(); madai::Sample sample = sampler->NextSample(); trace.Add( sample ); } double modelMeanX; double modelMeanY; model->GetMeans( modelMeanX, modelMeanY ); if ( std::abs( modelMeanX - currentParameters[0] ) > 1.0e-3 || std::abs( modelMeanY - currentParameters[1] ) > 1.0e-3 ) { std::cerr << "RegularStepGradientDescentSampler failed to converge " << "on the expected solution." << std::endl; std::cerr << "Expected currentParameters to be (" << modelMeanX << ", " << modelMeanY << "), got (" << currentParameters[0] << ", " << currentParameters[1] << ") instead." << std::endl; return EXIT_FAILURE; } //delete trace; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <cmath> #include <ctime> #include <iostream> #include <iomanip> #include <random> #include <set> #include <vector> #include <unordered_map> namespace { inline size_t GenerateMaskWithRightOnes(size_t onesCount) { return (1ull << onesCount) - 1ull; } class TCacheSet { public: TCacheSet(size_t waysCount) : TicksTimer(0) , CacheWays(waysCount) , CacheHits(0) {} bool Touch(size_t cacheLineNum) { ++TicksTimer; // CacheLine2LastTouch[cacheLineNum] = TicksTimer; TCacheLine* minTickLine = nullptr; size_t minTickTime = TicksTimer; for (auto& activeLine : CacheWays) { if (activeLine.LineNum != cacheLineNum) { if (activeLine.LineNum == -1) { activeLine.TouchTick = TicksTimer; activeLine.LineNum = cacheLineNum; return false; } if (activeLine.TouchTick < minTickTime) { minTickTime = activeLine.TouchTick; minTickLine = &activeLine; } } else { activeLine.TouchTick = TicksTimer; ++CacheHits; return true; } } minTickLine->LineNum = cacheLineNum; minTickLine->TouchTick = TicksTimer; return false; } size_t GetCacheHits() const { return CacheHits; } size_t GetTicks() const { return TicksTimer; } size_t GetCacheMisses() const { return TicksTimer - CacheHits; } double GetCacheMissRate() const { return GetCacheMisses() / (TicksTimer * 1.0); } private: struct TCacheLine { size_t LineNum = -1; size_t TouchTick = 0; }; private: size_t TicksTimer; std::vector<TCacheLine> CacheWays; // Contains LineNum == -1 if free // std::unordered_map<size_t, size_t> CacheLine2LastTouch; size_t CacheHits; }; class TCache { public: TCache(size_t cacheSize, size_t cacheLineSize, size_t waysCount) : CacheSize(cacheSize) , CacheLineSize(cacheLineSize) , WaysCount(waysCount) , BlocksCount(CacheSize / cacheLineSize) , SetsCount(BlocksCount / WaysCount) , BlockOffsetSize(static_cast<size_t>(log2(CacheLineSize))) , ShiftedIndexMask(GenerateMaskWithRightOnes(static_cast<size_t>(log2(SetsCount)))) , InvBlockMask(~GenerateMaskWithRightOnes(BlockOffsetSize)) , CacheSets(SetsCount, {WaysCount}) { std::cout << "Params: " << std::endl << "\tCacheSize:\t" << CacheSize << ' ' << std::endl << "\tCacheLineSize:\t" << CacheLineSize << ' ' << std::endl << "\tWaysCount:\t" << WaysCount << ' ' << std::endl << "\tBlocksCount:\t" << BlocksCount << ' ' << std::endl << "\tSetsCount:\t" << SetsCount << ' ' << std::endl << "\tBlockOffsetSize:\t" << BlockOffsetSize << ' ' << std::endl << "\tShiftedIndexMask:\t" << ShiftedIndexMask << ' ' << std::endl << "\tInvBlockMask:\t" << InvBlockMask << ' ' << std::endl; } /// @return true if needed cache line is in cache bool Touch(const void* ptr) { return CacheSets[GetIndexFromPtr(ptr)].Touch(GetCacheLineNumFromPtr(ptr)); } void PrintStats() const { size_t cacheSetIdx = 0; double mean = 0.0; double meanSq = 0.0; size_t totalTicks = 0; for (const auto& cacheSet : CacheSets) { std::cout << cacheSetIdx << ")\t" << cacheSet.GetCacheMisses() << "\t" << cacheSet.GetTicks() << "\t= " << std::setprecision(3) << cacheSet.GetCacheMissRate() * 100.0 << '%' << std::endl; ++cacheSetIdx; totalTicks += cacheSet.GetTicks(); double misses = cacheSet.GetCacheMisses() * 1.0; mean += misses / CacheSets.size(); meanSq += misses * misses / CacheSets.size(); } std::cout << std::fixed << std::setprecision(3) << "Misses: mean=" << mean << " " "var=" << (meanSq - mean * mean) << " " "rate=" << (mean * CacheSets.size() / totalTicks) * 100 << '%' << std::endl; } private: size_t GetIndexFromPtr(const void* ptr) { return ((size_t)ptr >> BlockOffsetSize) & ShiftedIndexMask; } size_t GetCacheLineNumFromPtr(const void* ptr) { return (size_t)ptr & InvBlockMask; } private: const size_t CacheSize; const size_t CacheLineSize; const size_t WaysCount; const size_t BlocksCount; const size_t SetsCount; const size_t BlockOffsetSize; const size_t ShiftedIndexMask; const size_t InvBlockMask; std::vector<TCacheSet> CacheSets; }; void MultSimpleTooled(TCache& cache, const float* __restrict a, const float* __restrict b, float* __restrict c, int n) { for (int i = 0; i < n; ++i) { if (i == 0) { //>-- i = 0 cache.Touch(&i); //<-- i = 0 //>-- i < n cache.Touch(&i); cache.Touch(&n); //<-- i < n } for (int j = 0; j < n; ++j) { if (j == 0) { //>-- j = 0 cache.Touch(&j); //<-- j = 0 //>-- j < n cache.Touch(&j); cache.Touch(&n); //<-- j < n } //>-- c[i * n + j] cache.Touch(&i); cache.Touch(&j); cache.Touch(&n); cache.Touch(&c); cache.Touch(&c[i * n + j]); //<-- c[i * n + j] c[i * n + j] = 0.f; for (int k = 0; k < n; ++k) { if (k == 0) { //>-- k = 0 cache.Touch(&k); //<-- k = 0 //>-- k < n cache.Touch(&k); cache.Touch(&n); //<-- k < n } cache.Touch(&i); cache.Touch(&j); cache.Touch(&k); cache.Touch(&n); cache.Touch(&a); cache.Touch(&b); cache.Touch(&c); cache.Touch(&a[i * n + k]); cache.Touch(&b[k * n + j]); cache.Touch(&c[i * n + j]); c[i * n + j] += a[i * n + k] * b[k * n + j]; //>-- ++k cache.Touch(&k); //<-- ++k //>-- k < n cache.Touch(&k); cache.Touch(&n); //<-- k < n } //>-- ++j cache.Touch(&j); //<-- ++j //>-- j < n cache.Touch(&j); cache.Touch(&n); //<-- j < n } //>-- ++i cache.Touch(&i); //<-- ++i //>-- i < n cache.Touch(&i); cache.Touch(&n); //<-- i < n } } void MultSimple(const float* __restrict a, const float* __restrict b, float* __restrict c, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { c[i * n + j] = 0.f; for (int k = 0; k < n; ++k) { c[i * n + j] += a[i * n + k] * b[k * n + j]; } } } } void FillRandom(float* a, int n) { std::default_random_engine eng; std::uniform_real_distribution<float> dist; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i * n + j] = dist(eng); } } } } int main(int argc, char* argv[]) { if (argc < 5) { std::cerr << "Usage: " << argv[0] << " MATRIX_SIZE CACHE_SIZE_KB CACHE_LINE_SIZE_B WAYS_COUNT" << std::endl; return 1; } const int n = atoi(argv[1]); const size_t cacheSizeKB = atoi(argv[2]); const size_t cacheLineSizeB = atoi(argv[3]); const size_t waysCount = atoi(argv[4]); std::cout << "n = " << n << std::endl; std::cout << "Cache: " << cacheSizeKB << "KB, " << waysCount << " ways with " << cacheLineSizeB << "b cache line." << std::endl; float* a = new float[n * n]; float* b = new float[n * n]; float* c = new float[n * n]; FillRandom(a, n); FillRandom(b, n); TCache cache(cacheSizeKB * 1024 /* kb */, cacheLineSizeB /* b */, waysCount /* ways */); { const auto startTime = std::clock(); MultSimpleTooled(cache, a, b, c, n); const auto endTime = std::clock(); std::cout << "timeSimple: " << double(endTime - startTime) / CLOCKS_PER_SEC << '\n'; } cache.PrintStats(); delete[] a; delete[] b; delete[] c; } <commit_msg>Do not track register vars.<commit_after>#include <cmath> #include <ctime> #include <iostream> #include <iomanip> #include <random> #include <set> #include <vector> #include <unordered_map> namespace { inline size_t GenerateMaskWithRightOnes(size_t onesCount) { return (1ull << onesCount) - 1ull; } class TCacheSet { public: TCacheSet(size_t waysCount) : TicksTimer(0) , CacheWays(waysCount) , CacheHits(0) {} bool Touch(size_t cacheLineNum) { ++TicksTimer; // CacheLine2LastTouch[cacheLineNum] = TicksTimer; TCacheLine* minTickLine = nullptr; size_t minTickTime = TicksTimer; for (auto& activeLine : CacheWays) { if (activeLine.LineNum != cacheLineNum) { if (activeLine.LineNum == -1) { activeLine.TouchTick = TicksTimer; activeLine.LineNum = cacheLineNum; return false; } if (activeLine.TouchTick < minTickTime) { minTickTime = activeLine.TouchTick; minTickLine = &activeLine; } } else { activeLine.TouchTick = TicksTimer; ++CacheHits; return true; } } minTickLine->LineNum = cacheLineNum; minTickLine->TouchTick = TicksTimer; return false; } size_t GetCacheHits() const { return CacheHits; } size_t GetTicks() const { return TicksTimer; } size_t GetCacheMisses() const { return TicksTimer - CacheHits; } double GetCacheMissRate() const { return GetCacheMisses() / (TicksTimer * 1.0); } private: struct TCacheLine { size_t LineNum = -1; size_t TouchTick = 0; }; private: size_t TicksTimer; std::vector<TCacheLine> CacheWays; // Contains LineNum == -1 if free // std::unordered_map<size_t, size_t> CacheLine2LastTouch; size_t CacheHits; }; class TCache { public: TCache(size_t cacheSize, size_t cacheLineSize, size_t waysCount) : CacheSize(cacheSize) , CacheLineSize(cacheLineSize) , WaysCount(waysCount) , BlocksCount(CacheSize / cacheLineSize) , SetsCount(BlocksCount / WaysCount) , BlockOffsetSize(static_cast<size_t>(log2(CacheLineSize))) , ShiftedIndexMask(GenerateMaskWithRightOnes(static_cast<size_t>(log2(SetsCount)))) , InvBlockMask(~GenerateMaskWithRightOnes(BlockOffsetSize)) , CacheSets(SetsCount, {WaysCount}) { std::cout << "Params: " << std::endl << "\tCacheSize:\t" << CacheSize << ' ' << std::endl << "\tCacheLineSize:\t" << CacheLineSize << ' ' << std::endl << "\tWaysCount:\t" << WaysCount << ' ' << std::endl << "\tBlocksCount:\t" << BlocksCount << ' ' << std::endl << "\tSetsCount:\t" << SetsCount << ' ' << std::endl << "\tBlockOffsetSize:\t" << BlockOffsetSize << ' ' << std::endl << "\tShiftedIndexMask:\t" << ShiftedIndexMask << ' ' << std::endl << "\tInvBlockMask:\t" << InvBlockMask << ' ' << std::endl; } /// @return true if needed cache line is in cache bool Touch(const void* ptr) { return CacheSets[GetIndexFromPtr(ptr)].Touch(GetCacheLineNumFromPtr(ptr)); } void PrintStats() const { size_t cacheSetIdx = 0; double mean = 0.0; double meanSq = 0.0; size_t totalTicks = 0; for (const auto& cacheSet : CacheSets) { std::cout << cacheSetIdx << ")\t" << cacheSet.GetCacheMisses() << "\t" << cacheSet.GetTicks() << "\t= " << std::setprecision(3) << cacheSet.GetCacheMissRate() * 100.0 << '%' << std::endl; ++cacheSetIdx; totalTicks += cacheSet.GetTicks(); double misses = cacheSet.GetCacheMisses() * 1.0; mean += misses / CacheSets.size(); meanSq += misses * misses / CacheSets.size(); } std::cout << std::fixed << std::setprecision(3) << "Misses: mean=" << mean << " " "var=" << (meanSq - mean * mean) << " " "rate=" << (mean * CacheSets.size() / totalTicks) * 100 << '%' << std::endl; } private: size_t GetIndexFromPtr(const void* ptr) { return ((size_t)ptr >> BlockOffsetSize) & ShiftedIndexMask; } size_t GetCacheLineNumFromPtr(const void* ptr) { return (size_t)ptr & InvBlockMask; } private: const size_t CacheSize; const size_t CacheLineSize; const size_t WaysCount; const size_t BlocksCount; const size_t SetsCount; const size_t BlockOffsetSize; const size_t ShiftedIndexMask; const size_t InvBlockMask; std::vector<TCacheSet> CacheSets; }; void MultSimpleTooled(TCache& cache, const float* __restrict a, const float* __restrict b, float* __restrict c, int n) { /// We suppose that i j k, as iteration vars, would be placed to registers /// So cache will work with n, a, b, c and corresponding arrays cache.Touch(&n); // for next loop start for (int i = 0; i < n; ++i) { cache.Touch(&n); // for next loop start for (int j = 0; j < n; ++j) { //>-- c[i * n + j] // cache.Touch(&i); // cache.Touch(&j); cache.Touch(&n); cache.Touch(&c); cache.Touch(&c[i * n + j]); //<-- c[i * n + j] c[i * n + j] = 0.f; cache.Touch(&n); // for next loop start for (int k = 0; k < n; ++k) { // cache.Touch(&i); // cache.Touch(&j); // cache.Touch(&k); cache.Touch(&n); cache.Touch(&a); cache.Touch(&b); cache.Touch(&c); cache.Touch(&a[i * n + k]); cache.Touch(&b[k * n + j]); cache.Touch(&c[i * n + j]); c[i * n + j] += a[i * n + k] * b[k * n + j]; //>-- k < n // cache.Touch(&k); cache.Touch(&n); //<-- k < n } //>-- j < n // cache.Touch(&j); cache.Touch(&n); //<-- j < n } //>-- i < n // cache.Touch(&i); cache.Touch(&n); //<-- i < n } } void MultSimple(const float* __restrict a, const float* __restrict b, float* __restrict c, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { c[i * n + j] = 0.f; for (int k = 0; k < n; ++k) { c[i * n + j] += a[i * n + k] * b[k * n + j]; } } } } void FillRandom(float* a, int n) { std::default_random_engine eng; std::uniform_real_distribution<float> dist; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i * n + j] = dist(eng); } } } } int main(int argc, char* argv[]) { if (argc < 5) { std::cerr << "Usage: " << argv[0] << " MATRIX_SIZE CACHE_SIZE_KB CACHE_LINE_SIZE_B WAYS_COUNT" << std::endl; return 1; } const int n = atoi(argv[1]); const size_t cacheSizeKB = atoi(argv[2]); const size_t cacheLineSizeB = atoi(argv[3]); const size_t waysCount = atoi(argv[4]); std::cout << "n = " << n << std::endl; std::cout << "Cache: " << cacheSizeKB << "KB, " << waysCount << " ways with " << cacheLineSizeB << "b cache line." << std::endl; float* a = new float[n * n]; float* b = new float[n * n]; float* c = new float[n * n]; FillRandom(a, n); FillRandom(b, n); TCache cache(cacheSizeKB * 1024 /* kb */, cacheLineSizeB /* b */, waysCount /* ways */); { const auto startTime = std::clock(); MultSimpleTooled(cache, a, b, c, n); const auto endTime = std::clock(); std::cout << "timeSimple: " << double(endTime - startTime) / CLOCKS_PER_SEC << '\n'; } cache.PrintStats(); delete[] a; delete[] b; delete[] c; } <|endoftext|>
<commit_before>/* * * Copyright 2018 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 <benchmark/benchmark.h> #include <string> #include <thread> // NOLINT #include "absl/base/call_once.h" #include "absl/strings/str_cat.h" #include "include/grpc++/grpc++.h" #include "include/grpcpp/opencensus.h" #include "opencensus/stats/stats.h" #include "src/cpp/ext/filters/census/grpc_plugin.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" #include "test/cpp/microbenchmarks/helpers.h" using ::grpc::RegisterOpenCensusPlugin; using ::grpc::RegisterOpenCensusViewsForExport; absl::once_flag once; void RegisterOnce() { absl::call_once(once, RegisterOpenCensusPlugin); } class EchoServer final : public grpc::testing::EchoTestService::Service { grpc::Status Echo(grpc::ServerContext* context, const grpc::testing::EchoRequest* request, grpc::testing::EchoResponse* response) override { if (request->param().expected_error().code() == 0) { response->set_message(request->message()); return grpc::Status::OK; } else { return grpc::Status(static_cast<grpc::StatusCode>( request->param().expected_error().code()), ""); } } }; // An EchoServerThread object creates an EchoServer on a separate thread and // shuts down the server and thread when it goes out of scope. class EchoServerThread final { public: EchoServerThread() { grpc::ServerBuilder builder; int port; builder.AddListeningPort("[::]:0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); if (server_ == nullptr || port == 0) { std::abort(); } server_address_ = absl::StrCat("[::]:", port); server_thread_ = std::thread(&EchoServerThread::RunServerLoop, this); } ~EchoServerThread() { server_->Shutdown(); server_thread_.join(); } const std::string& address() { return server_address_; } private: void RunServerLoop() { server_->Wait(); } std::string server_address_; EchoServer service_; std::unique_ptr<grpc::Server> server_; std::thread server_thread_; }; static void BM_E2eLatencyCensusDisabled(benchmark::State& state) { EchoServerThread server; std::unique_ptr<grpc::testing::EchoTestService::Stub> stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannel( server.address(), grpc::InsecureChannelCredentials())); grpc::testing::EchoResponse response; for (auto _ : state) { grpc::testing::EchoRequest request; grpc::ClientContext context; grpc::Status status = stub->Echo(&context, request, &response); } } BENCHMARK(BM_E2eLatencyCensusDisabled); static void BM_E2eLatencyCensusEnabled(benchmark::State& state) { RegisterOnce(); // This we can safely repeat, and doing so clears accumulated data to avoid // initialization costs varying between runs. RegisterOpenCensusViewsForExport(); EchoServerThread server; std::unique_ptr<grpc::testing::EchoTestService::Stub> stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannel( server.address(), grpc::InsecureChannelCredentials())); grpc::testing::EchoResponse response; for (auto _ : state) { grpc::testing::EchoRequest request; grpc::ClientContext context; grpc::Status status = stub->Echo(&context, request, &response); } } BENCHMARK(BM_E2eLatencyCensusEnabled); BENCHMARK_MAIN(); <commit_msg>Fix errors from clang_format_code.sh<commit_after>/* * * Copyright 2018 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 <benchmark/benchmark.h> #include <string> #include <thread> // NOLINT #include "absl/base/call_once.h" #include "absl/strings/str_cat.h" #include "include/grpc++/grpc++.h" #include "include/grpcpp/opencensus.h" #include "opencensus/stats/stats.h" #include "src/cpp/ext/filters/census/grpc_plugin.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" #include "test/cpp/microbenchmarks/helpers.h" using ::grpc::RegisterOpenCensusPlugin; using ::grpc::RegisterOpenCensusViewsForExport; absl::once_flag once; void RegisterOnce() { absl::call_once(once, RegisterOpenCensusPlugin); } class EchoServer final : public grpc::testing::EchoTestService::Service { grpc::Status Echo(grpc::ServerContext* context, const grpc::testing::EchoRequest* request, grpc::testing::EchoResponse* response) override { if (request->param().expected_error().code() == 0) { response->set_message(request->message()); return grpc::Status::OK; } else { return grpc::Status(static_cast<grpc::StatusCode>( request->param().expected_error().code()), ""); } } }; // An EchoServerThread object creates an EchoServer on a separate thread and // shuts down the server and thread when it goes out of scope. class EchoServerThread final { public: EchoServerThread() { grpc::ServerBuilder builder; int port; builder.AddListeningPort("[::]:0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); if (server_ == nullptr || port == 0) { std::abort(); } server_address_ = absl::StrCat("[::]:", port); server_thread_ = std::thread(&EchoServerThread::RunServerLoop, this); } ~EchoServerThread() { server_->Shutdown(); server_thread_.join(); } const std::string& address() { return server_address_; } private: void RunServerLoop() { server_->Wait(); } std::string server_address_; EchoServer service_; std::unique_ptr<grpc::Server> server_; std::thread server_thread_; }; static void BM_E2eLatencyCensusDisabled(benchmark::State& state) { EchoServerThread server; std::unique_ptr<grpc::testing::EchoTestService::Stub> stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannel( server.address(), grpc::InsecureChannelCredentials())); grpc::testing::EchoResponse response; for (auto _ : state) { grpc::testing::EchoRequest request; grpc::ClientContext context; grpc::Status status = stub->Echo(&context, request, &response); } } BENCHMARK(BM_E2eLatencyCensusDisabled); static void BM_E2eLatencyCensusEnabled(benchmark::State& state) { RegisterOnce(); // This we can safely repeat, and doing so clears accumulated data to avoid // initialization costs varying between runs. RegisterOpenCensusViewsForExport(); EchoServerThread server; std::unique_ptr<grpc::testing::EchoTestService::Stub> stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannel( server.address(), grpc::InsecureChannelCredentials())); grpc::testing::EchoResponse response; for (auto _ : state) { grpc::testing::EchoRequest request; grpc::ClientContext context; grpc::Status status = stub->Echo(&context, request, &response); } } BENCHMARK(BM_E2eLatencyCensusEnabled); BENCHMARK_MAIN(); <|endoftext|>
<commit_before>#include <iostream> #include <opencv2/opencv.hpp> #include <cmath> #include <set> #include <vector> using namespace cv; using namespace std; Mat frame, filtered, binary; void on_mouse(int evt, int c, int r, int flags, void* param) { if(evt==CV_EVENT_LBUTTONDOWN) { uchar* row = filtered.ptr<uchar>(r); int blue = row[c*3]; int green = row[c*3+1]; int red = row[c*3+2]; std::cout << red << " " << green << " " << blue << std::endl; } } void normalizeRGB(Mat mat) { uchar* p; for(int i = 0; i < mat.rows; i++) { p = mat.ptr<uchar>(i); for(int j = 0; j < mat.cols*mat.channels(); j += 3) { uchar blue = p[j]; uchar green = p[j+1]; uchar red = p[j+2]; double sum = red+ green + blue; if(sum > 0) { p[j] = blue / sum * 255; p[j+1] = green / sum * 255; p[j+2] = red / sum * 255; } } } } int main() { int trackVal = 215; cvNamedWindow("Binary"); cvCreateTrackbar("trackbar", "Binary", &trackVal, 255); while(true) { frame = imread("/home/matt/Pictures/2005IGVCcoursePics 154.jpg", 1); resize(frame, frame, Size(640,480)); imshow("Raw", frame); frame.copyTo(filtered); // boxFilter(filtered, filtered, 0, Size(9,9)); cvtColor(filtered, filtered, CV_BGR2HSV); { vector<Mat> channels; split(filtered, channels); Mat H = channels[0]; equalizeHist(H, H); imshow("Hue", H); Mat S = channels[1]; S.at } imshow("Filtered", filtered); /* { // Increase contrast of color image // http://stackoverflow.com/questions/15007304/histogram-equalization-not-working-on-color-image-opencv Mat ycrcb; cvtColor(filtered, ycrcb, CV_BGR2YCrCb); vector<Mat> channels; split(ycrcb, channels); equalizeHist(channels[0], channels[0]); merge(channels, ycrcb); cvtColor(ycrcb, filtered, CV_YCrCb2BGR); } imshow("Filtered", filtered); binary = Mat(filtered.rows, filtered.cols, CV_8UC3); filtered.copyTo(binary); uchar* p; for(int r = 0; r < binary.rows; r++) { p = binary.ptr<uchar>(r); for(int c = 0; c < binary.cols*binary.channels(); c+=3) { uchar blue = p[c]; uchar green = p[c+1]; uchar red = p[c+2]; p[c] = 0; p[c+1] = 0; p[c+2] = 0; // if(abs(blue - 85) < 10 && abs(green - 85) < 10 && abs(red - 85) < 10) //White if(blue > trackVal && green > trackVal && red > trackVal) { p[c] = 255; p[c+1] = 255; p[c+2] = 255; } } } cvtColor(binary, binary, CV_BGR2GRAY); imshow("Binary", binary);*/ if(waitKey(10) > 0) break; } return 0; } <commit_msg>Successful isolation of lane markers from orange/white striped obstacles in TestLaneDetection<commit_after>#include <iostream> #include <opencv2/opencv.hpp> #include <cmath> #include <set> #include <vector> using namespace cv; using namespace std; Mat frame, filtered, binary; void on_mouse(int evt, int c, int r, int flags, void* param) { if(evt==CV_EVENT_LBUTTONDOWN) { uchar* row = filtered.ptr<uchar>(r); int blue = row[c*3]; int green = row[c*3+1]; int red = row[c*3+2]; std::cout << red << " " << green << " " << blue << std::endl; } } void normalizeRGB(Mat mat) { uchar* p; for(int i = 0; i < mat.rows; i++) { p = mat.ptr<uchar>(i); for(int j = 0; j < mat.cols*mat.channels(); j += 3) { uchar blue = p[j]; uchar green = p[j+1]; uchar red = p[j+2]; double sum = red+ green + blue; if(sum > 0) { p[j] = blue / sum * 255; p[j+1] = green / sum * 255; p[j+2] = red / sum * 255; } } } } int main() { int trackVal = 215; //cvNamedWindow("Binary"); //cvCreateTrackbar("trackbar", "Binary", &trackVal, 255); while(true) { frame = imread("/home/matt/Pictures/2005IGVCcoursePics 154.jpg", 1); resize(frame, frame, Size(640,480)); { // ROI int startrow = frame.rows / 4; frame = frame(Rect(0,startrow,frame.cols,frame.rows - startrow)); } imshow("Raw", frame); frame.copyTo(filtered); boxFilter(filtered, filtered, 0, Size(9,9)); { // Filter Orange hues to Black Mat HSV; cvtColor(filtered, HSV, CV_BGR2HSV); vector<Mat> channels; split(HSV, channels); Mat H = channels[0]; Mat V = channels[2]; uchar* pH; uchar* pV; for(int r = 0; r < H.rows; r++) { pH = H.ptr<uchar>(r); pV = V.ptr<uchar>(r); for(int c = 0; c < H.cols; c++) { uchar hVal = pH[c]; if(abs(hVal - 170) < 10 || abs(hVal - 0) < 10) { pV[c] = 0; } } } //imshow("H", channels[0]); merge(channels, filtered); cvtColor(filtered, filtered, CV_HSV2BGR); } { // Remove White segments of columns between Orange segments Mat transposed; transpose(filtered, transposed); uchar* p; bool seenBlack, seenWhite; int startInd = 0; for(int c = 0; c < transposed.rows; c++) { p = transposed.ptr<uchar>(c); seenBlack = false; seenWhite = false; for(int r = 0; r < transposed.cols*transposed.channels(); r+=3) { uchar blue = p[r], green = p[r+1], red = p[r+2]; if( red == 0 && green == 0 && blue == 0) { if(seenBlack && seenWhite) { for(int i = startInd; i <= r; i++) { p[i] = 0; p[i+1] = 0; p[i+2] = 0; } } else if(!seenBlack) { seenBlack = true; startInd = r; } } else if(abs(red-green) < 5 && abs(green-blue) < 30)//if(red > 150 && green > 150 && blue > 150) { if(seenBlack && !seenWhite) { seenWhite = true; } } } } //imshow("Transposed", transposed); transpose(transposed, filtered); } imshow("Filtered", filtered); //cvSetMouseCallback("Raw", on_mouse, 0); cvtColor(filtered, filtered, CV_BGR2GRAY); threshold(filtered, filtered, 0, 1, THRESH_BINARY); cvtColor(filtered, filtered, CV_GRAY2BGR); Mat masked; multiply(filtered, frame, masked); { // Increase contrast of color image // http://stackoverflow.com/questions/15007304/histogram-equalization-not-working-on-color-image-opencv Mat ycrcb; cvtColor(masked, ycrcb, CV_BGR2YCrCb); vector<Mat> channels; split(ycrcb, channels); equalizeHist(channels[0], channels[0]); merge(channels, ycrcb); cvtColor(ycrcb, masked, CV_YCrCb2BGR); } imshow("Masked", masked); binary = Mat(masked.rows, masked.cols, CV_8UC3); masked.copyTo(binary); { // Threshold for White uchar threshold = 240; uchar* p; for(int r = 0; r < binary.rows; r++) { p = binary.ptr<uchar>(r); for(int c = 0; c < binary.cols*binary.channels(); c+=3) { uchar blue = p[c]; uchar green = p[c+1]; uchar red = p[c+2]; p[c] = 0; p[c+1] = 0; p[c+2] = 0; if(blue > threshold && green > threshold && red > threshold) { p[c] = 255; p[c+1] = 255; p[c+2] = 255; } } } cvtColor(binary, binary, CV_BGR2GRAY); } int erosion_size =2; cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1), cv::Point(erosion_size, erosion_size) ); erode(binary, binary, element); dilate(binary, binary, element); imshow("Binary", binary); if(waitKey(10) > 0) break; } return 0; } <|endoftext|>
<commit_before>#include "fnv_param.hpp" #include "fnv_algo.hpp" #include "constraint.hpp" #include "fnv_solver.hpp" #include <vector> #include <iostream> #include <boost/foreach.hpp> int main(int argc, char** argv) { const std::vector<FNVParam> fnvParams = FNVParam::getAll(); const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll(); const std::vector<Constraint> constraints = Constraint::getAll(); BOOST_FOREACH(const FNVParam& fnvParam, fnvParams) { std::cout << "Problem size: " << fnvParam.getWidth() << std::endl; BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos) { std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl; const Constraint nullConstraint = Constraint::getNull(); std::cout << "Constraint: " << nullConstraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, nullConstraint); solver.solve(); const int solutionLength = solver.getSolutionLength(); BOOST_FOREACH(const Constraint& constraint, constraints) { std::cout << "Constraint: " << constraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength); solver.solve(); } } } } <commit_msg>Add slightly more spacing in output.<commit_after>#include "fnv_param.hpp" #include "fnv_algo.hpp" #include "constraint.hpp" #include "fnv_solver.hpp" #include <vector> #include <iostream> #include <boost/foreach.hpp> int main(int argc, char** argv) { const std::vector<FNVParam> fnvParams = FNVParam::getAll(); const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll(); const std::vector<Constraint> constraints = Constraint::getAll(); BOOST_FOREACH(const FNVParam& fnvParam, fnvParams) { std::cout << "Problem size: " << fnvParam.getWidth() << std::endl; BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos) { std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl; const Constraint nullConstraint = Constraint::getNull(); std::cout << "Constraint: " << nullConstraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, nullConstraint); solver.solve(); const int solutionLength = solver.getSolutionLength(); BOOST_FOREACH(const Constraint& constraint, constraints) { std::cout << "Constraint: " << constraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength); solver.solve(); } } std::cout << std::endl; } } <|endoftext|>
<commit_before>#include "Executioner.h" // Moose includes #include "Moose.h" #include "MooseSystem.h" #include "Kernel.h" #include "ComputeJacobian.h" #include "ComputeResidual.h" #include "ComputeInitialConditions.h" // C++ includes #include <vector> #include <limits> // libMesh includes #include "nonlinear_implicit_system.h" #include "transient_system.h" #include "kelly_error_estimator.h" #include "mesh_refinement.h" #include "numeric_vector.h" template<> InputParameters validParams<Executioner>() { InputParameters params = validParams<MooseObject>(); return params; } Executioner::Executioner(std::string name, MooseSystem & moose_system, InputParameters parameters) : MooseObject(name, moose_system, parameters), FunctionInterface(moose_system._functions[_tid], parameters), _initial_residual_norm(std::numeric_limits<Real>::max()), _old_initial_residual_norm(std::numeric_limits<Real>::max()) { } Executioner::~Executioner() { } void Executioner::setup() { Moose::setSolverDefaults(_moose_system); _moose_system.getNonlinearSystem()->update(); // Update backward time solution vectors. *_moose_system._system->older_local_solution = *_moose_system._system->current_local_solution; *_moose_system._system->old_local_solution = *_moose_system._system->current_local_solution; *_moose_system._aux_system->older_local_solution = *_moose_system._aux_system->current_local_solution; *_moose_system._aux_system->old_local_solution = *_moose_system._aux_system->current_local_solution; unsigned int initial_adaptivity = _moose_system.getInitialAdaptivityStepCount(); //Initial adaptivity for(unsigned int i=0; i<initial_adaptivity; i++) { _moose_system.doAdaptivityStep(); // Tell MOOSE that the mesh has changed // this performs a lot of functions including projecting // the solution onto the new grid. _moose_system.meshChanged(); //reproject the initial condition _moose_system.project_solution(Moose::initial_value, NULL); } if(_moose_system._output_initial) { std::cout<<"Outputting Initial Condition"<<std::endl; _moose_system.output_system(0, 0.0); } // Check for Kernel, BC, and Material coverage on the Mesh _moose_system.checkSystemsIntegrity(); _moose_system.getNonlinearSystem()->update(); // Compute the initial value of postprocessors _moose_system.compute_postprocessors(*(_moose_system.getNonlinearSystem()->current_local_solution)); } void Executioner::adaptMesh() { _moose_system.adaptMesh(); } void Executioner::setScaling() { std::vector<Real> one_scaling; // Reset the scaling to all 1's so we can compute the true residual for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++) one_scaling.push_back(1.0); _moose_system.setVarScaling(one_scaling); _moose_system.compute_residual(*_moose_system.getNonlinearSystem()->current_local_solution, *_moose_system.getNonlinearSystem()->rhs); _old_initial_residual_norm = _initial_residual_norm; _initial_residual_norm = _moose_system.getNonlinearSystem()->rhs->l2_norm(); std::cout<<" True Initial Nonlinear Residual: "<<_initial_residual_norm<<std::endl; // Set the scaling to manual scaling _moose_system.setVarScaling(_moose_system._manual_scaling); if (_moose_system._auto_scaling) { std::vector<Real> scaling; // Compute the new scaling for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++) { Real norm = _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2); if(norm != 0) scaling.push_back(1.0/norm); else scaling.push_back(1.0); } _moose_system.setVarScaling(scaling); } } <commit_msg>fix initial adaptivity with C1 elements<commit_after>#include "Executioner.h" // Moose includes #include "Moose.h" #include "MooseSystem.h" #include "Kernel.h" #include "ComputeJacobian.h" #include "ComputeResidual.h" #include "ComputeInitialConditions.h" // C++ includes #include <vector> #include <limits> // libMesh includes #include "nonlinear_implicit_system.h" #include "transient_system.h" #include "kelly_error_estimator.h" #include "mesh_refinement.h" #include "numeric_vector.h" template<> InputParameters validParams<Executioner>() { InputParameters params = validParams<MooseObject>(); return params; } Executioner::Executioner(std::string name, MooseSystem & moose_system, InputParameters parameters) : MooseObject(name, moose_system, parameters), FunctionInterface(moose_system._functions[_tid], parameters), _initial_residual_norm(std::numeric_limits<Real>::max()), _old_initial_residual_norm(std::numeric_limits<Real>::max()) { } Executioner::~Executioner() { } void Executioner::setup() { Moose::setSolverDefaults(_moose_system); _moose_system.getNonlinearSystem()->update(); // Update backward time solution vectors. *_moose_system._system->older_local_solution = *_moose_system._system->current_local_solution; *_moose_system._system->old_local_solution = *_moose_system._system->current_local_solution; *_moose_system._aux_system->older_local_solution = *_moose_system._aux_system->current_local_solution; *_moose_system._aux_system->old_local_solution = *_moose_system._aux_system->current_local_solution; unsigned int initial_adaptivity = _moose_system.getInitialAdaptivityStepCount(); //Initial adaptivity for(unsigned int i=0; i<initial_adaptivity; i++) { _moose_system.doAdaptivityStep(); // Tell MOOSE that the mesh has changed // this performs a lot of functions including projecting // the solution onto the new grid. _moose_system.meshChanged(); //reproject the initial condition _moose_system.project_solution(Moose::initial_value, Moose::initial_gradient); } if(_moose_system._output_initial) { std::cout<<"Outputting Initial Condition"<<std::endl; _moose_system.output_system(0, 0.0); } // Check for Kernel, BC, and Material coverage on the Mesh _moose_system.checkSystemsIntegrity(); _moose_system.getNonlinearSystem()->update(); // Compute the initial value of postprocessors _moose_system.compute_postprocessors(*(_moose_system.getNonlinearSystem()->current_local_solution)); } void Executioner::adaptMesh() { _moose_system.adaptMesh(); } void Executioner::setScaling() { std::vector<Real> one_scaling; // Reset the scaling to all 1's so we can compute the true residual for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++) one_scaling.push_back(1.0); _moose_system.setVarScaling(one_scaling); _moose_system.compute_residual(*_moose_system.getNonlinearSystem()->current_local_solution, *_moose_system.getNonlinearSystem()->rhs); _old_initial_residual_norm = _initial_residual_norm; _initial_residual_norm = _moose_system.getNonlinearSystem()->rhs->l2_norm(); std::cout<<" True Initial Nonlinear Residual: "<<_initial_residual_norm<<std::endl; // Set the scaling to manual scaling _moose_system.setVarScaling(_moose_system._manual_scaling); if (_moose_system._auto_scaling) { std::vector<Real> scaling; // Compute the new scaling for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++) { Real norm = _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2); if(norm != 0) scaling.push_back(1.0/norm); else scaling.push_back(1.0); } _moose_system.setVarScaling(scaling); } } <|endoftext|>
<commit_before>#include <string> #include <gtest/gtest.h> #include "prefix_function.hpp" namespace gt = testing; namespace pk { namespace testing { struct prefix_function_tester : public gt::Test { static const int MAX_TEXT_SIZE = 100; // tested class: prefix_function<MAX_TEXT_SIZE> pf; }; TEST_F(prefix_function_tester, tests_abcd) { // given const std::string text = "abcd"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(0, prefix_suffix_table[1]); EXPECT_EQ(0, prefix_suffix_table[2]); EXPECT_EQ(0, prefix_suffix_table[3]); } TEST_F(prefix_function_tester, tests_aaaa) { // given const std::string text = "aaaa"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(1, prefix_suffix_table[1]); EXPECT_EQ(2, prefix_suffix_table[2]); EXPECT_EQ(3, prefix_suffix_table[3]); } TEST_F(prefix_function_tester, tests_abcabcabc) { // given const std::string text = "abcabcabc"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(0, prefix_suffix_table[1]); EXPECT_EQ(0, prefix_suffix_table[2]); EXPECT_EQ(1, prefix_suffix_table[3]); EXPECT_EQ(2, prefix_suffix_table[4]); EXPECT_EQ(3, prefix_suffix_table[5]); EXPECT_EQ(4, prefix_suffix_table[6]); EXPECT_EQ(5, prefix_suffix_table[7]); EXPECT_EQ(6, prefix_suffix_table[8]); } TEST_F(prefix_function_tester, tests_abcdabcaba) { // given const std::string text = "abcdabcaba"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(0, prefix_suffix_table[1]); EXPECT_EQ(0, prefix_suffix_table[2]); EXPECT_EQ(0, prefix_suffix_table[3]); EXPECT_EQ(1, prefix_suffix_table[4]); EXPECT_EQ(2, prefix_suffix_table[5]); EXPECT_EQ(3, prefix_suffix_table[6]); EXPECT_EQ(1, prefix_suffix_table[7]); EXPECT_EQ(2, prefix_suffix_table[8]); EXPECT_EQ(1, prefix_suffix_table[9]); } TEST_F(prefix_function_tester, tests_pattern_searching_in_text) { // given const std::string pattern = "abca"; const std::string text = "abaabcdabcabdabcabcad"; // pattern ends at: ^ ^ ^ // when std::string s = pattern + "#" + text; pf.run(s.c_str(), s.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(3, std::count(prefix_suffix_table, prefix_suffix_table + s.size(), pattern.size())); const int first_occurance = pattern.size() + 1 + 10; EXPECT_EQ(pattern.size(), prefix_suffix_table[first_occurance]); const int second_occurance = pattern.size() + 1 + 16; EXPECT_EQ(pattern.size(), prefix_suffix_table[second_occurance]); const int third_occurance = pattern.size() + 1 + 19; EXPECT_EQ(pattern.size(), prefix_suffix_table[third_occurance]); } } // namespace testing } // namespace pk <commit_msg>Missing include added<commit_after>#include <algorithm> #include <string> #include <gtest/gtest.h> #include "prefix_function.hpp" namespace gt = testing; namespace pk { namespace testing { struct prefix_function_tester : public gt::Test { static const int MAX_TEXT_SIZE = 100; // tested class: prefix_function<MAX_TEXT_SIZE> pf; }; TEST_F(prefix_function_tester, tests_abcd) { // given const std::string text = "abcd"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(0, prefix_suffix_table[1]); EXPECT_EQ(0, prefix_suffix_table[2]); EXPECT_EQ(0, prefix_suffix_table[3]); } TEST_F(prefix_function_tester, tests_aaaa) { // given const std::string text = "aaaa"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(1, prefix_suffix_table[1]); EXPECT_EQ(2, prefix_suffix_table[2]); EXPECT_EQ(3, prefix_suffix_table[3]); } TEST_F(prefix_function_tester, tests_abcabcabc) { // given const std::string text = "abcabcabc"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(0, prefix_suffix_table[1]); EXPECT_EQ(0, prefix_suffix_table[2]); EXPECT_EQ(1, prefix_suffix_table[3]); EXPECT_EQ(2, prefix_suffix_table[4]); EXPECT_EQ(3, prefix_suffix_table[5]); EXPECT_EQ(4, prefix_suffix_table[6]); EXPECT_EQ(5, prefix_suffix_table[7]); EXPECT_EQ(6, prefix_suffix_table[8]); } TEST_F(prefix_function_tester, tests_abcdabcaba) { // given const std::string text = "abcdabcaba"; // when pf.run(text.c_str(), text.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(0, prefix_suffix_table[0]); EXPECT_EQ(0, prefix_suffix_table[1]); EXPECT_EQ(0, prefix_suffix_table[2]); EXPECT_EQ(0, prefix_suffix_table[3]); EXPECT_EQ(1, prefix_suffix_table[4]); EXPECT_EQ(2, prefix_suffix_table[5]); EXPECT_EQ(3, prefix_suffix_table[6]); EXPECT_EQ(1, prefix_suffix_table[7]); EXPECT_EQ(2, prefix_suffix_table[8]); EXPECT_EQ(1, prefix_suffix_table[9]); } TEST_F(prefix_function_tester, tests_pattern_searching_in_text) { // given const std::string pattern = "abca"; const std::string text = "abaabcdabcabdabcabcad"; // pattern ends at: ^ ^ ^ // when std::string s = pattern + "#" + text; pf.run(s.c_str(), s.size()); // then const int* prefix_suffix_table = pf.get_prefix_suffix_table(); EXPECT_EQ(3u, std::count(prefix_suffix_table, prefix_suffix_table + s.size(), pattern.size())); const int first_occurance = pattern.size() + 1 + 10; EXPECT_EQ(pattern.size(), prefix_suffix_table[first_occurance]); const int second_occurance = pattern.size() + 1 + 16; EXPECT_EQ(pattern.size(), prefix_suffix_table[second_occurance]); const int third_occurance = pattern.size() + 1 + 19; EXPECT_EQ(pattern.size(), prefix_suffix_table[third_occurance]); } } // namespace testing } // namespace pk <|endoftext|>
<commit_before><commit_msg>fix NetDaemon example build<commit_after><|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2016-2020 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #if defined(MBED_CONF_RTOS_PRESENT) #include "rtos.h" #endif using namespace utest::v1; #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/sha256.h" #include "mbedtls/sha512.h" #include "mbedtls/entropy.h" #include "mbedtls/entropy_poll.h" #include <string.h> #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif #define MBEDTLS_SELF_TEST_TEST_CASE(self_test_function) \ void self_test_function ## _test_case() { \ int ret = self_test_function(0); \ TEST_ASSERT_EQUAL(ret, 0); \ } #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SHA256_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_sha256_self_test) #endif #if defined(MBEDTLS_SHA512_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_sha512_self_test) #endif #if defined(MBEDTLS_ENTROPY_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_entropy_self_test) #endif #else #warning "MBEDTLS_SELF_TEST not enabled" #endif /* MBEDTLS_SELF_TEST */ Case cases[] = { #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SHA256_C) Case("mbedtls_sha256_self_test", mbedtls_sha256_self_test_test_case), #endif #if defined(MBEDTLS_SHA512_C) Case("mbedtls_sha512_self_test", mbedtls_sha512_self_test_test_case), #endif #if defined(MBEDTLS_ENTROPY_C) Case("mbedtls_entropy_self_test", mbedtls_entropy_self_test_test_case), #endif #endif /* MBEDTLS_SELF_TEST */ }; utest::v1::status_t test_setup(const size_t num_cases) { GREENTEA_SETUP(120, "default_auto"); return verbose_test_setup_handler(num_cases); } Specification specification(test_setup, cases); int main() { int ret = 0; #if defined(MBEDTLS_PLATFORM_C) if ((ret = mbedtls_platform_setup(NULL)) != 0) { mbedtls_printf("Mbed TLS selftest failed! mbedtls_platform_setup returned %d\n", ret); return 1; } #endif ret = (Harness::run(specification) ? 0 : 1); #if defined(MBEDTLS_PLATFORM_C) mbedtls_platform_teardown(NULL); #endif return ret; } <commit_msg>mbedtls: Run mbedtls_timing_self_test if MBEDTLS_TIMING_C<commit_after>/* mbed Microcontroller Library * Copyright (c) 2016-2020 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #if defined(MBED_CONF_RTOS_PRESENT) #include "rtos.h" #endif using namespace utest::v1; #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/sha256.h" #include "mbedtls/sha512.h" #include "mbedtls/entropy.h" #include "mbedtls/entropy_poll.h" #include "mbedtls/timing.h" #include <string.h> #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif #define MBEDTLS_SELF_TEST_TEST_CASE(self_test_function) \ void self_test_function ## _test_case() { \ int ret = self_test_function(0); \ TEST_ASSERT_EQUAL(ret, 0); \ } #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SHA256_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_sha256_self_test) #endif #if defined(MBEDTLS_SHA512_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_sha512_self_test) #endif #if defined(MBEDTLS_ENTROPY_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_entropy_self_test) #endif #if defined(MBEDTLS_TIMING_C) MBEDTLS_SELF_TEST_TEST_CASE(mbedtls_timing_self_test) #endif #else #warning "MBEDTLS_SELF_TEST not enabled" #endif /* MBEDTLS_SELF_TEST */ Case cases[] = { #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SHA256_C) Case("mbedtls_sha256_self_test", mbedtls_sha256_self_test_test_case), #endif #if defined(MBEDTLS_SHA512_C) Case("mbedtls_sha512_self_test", mbedtls_sha512_self_test_test_case), #endif #if defined(MBEDTLS_ENTROPY_C) Case("mbedtls_entropy_self_test", mbedtls_entropy_self_test_test_case), #endif #if defined(MBEDTLS_TIMING_C) Case("mbedtls_timing_self_test", mbedtls_timing_self_test_test_case), #endif #endif /* MBEDTLS_SELF_TEST */ }; utest::v1::status_t test_setup(const size_t num_cases) { GREENTEA_SETUP(120, "default_auto"); return verbose_test_setup_handler(num_cases); } Specification specification(test_setup, cases); int main() { int ret = 0; #if defined(MBEDTLS_PLATFORM_C) if ((ret = mbedtls_platform_setup(NULL)) != 0) { mbedtls_printf("Mbed TLS selftest failed! mbedtls_platform_setup returned %d\n", ret); return 1; } #endif ret = (Harness::run(specification) ? 0 : 1); #if defined(MBEDTLS_PLATFORM_C) mbedtls_platform_teardown(NULL); #endif return ret; } <|endoftext|>
<commit_before>// 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 "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop_proxy.h" #include "base/values.h" #include "content/child/indexed_db/indexed_db_dispatcher.h" #include "content/child/indexed_db/webidbcursor_impl.h" #include "content/child/thread_safe_sender.h" #include "content/common/indexed_db/indexed_db_key.h" #include "content/common/indexed_db/indexed_db_key_range.h" #include "content/common/indexed_db/indexed_db_messages.h" #include "ipc/ipc_sync_message_filter.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebBlobInfo.h" #include "third_party/WebKit/public/platform/WebData.h" #include "third_party/WebKit/public/platform/WebIDBCallbacks.h" using blink::WebBlobInfo; using blink::WebData; using blink::WebIDBCallbacks; using blink::WebIDBCursor; using blink::WebIDBDatabase; using blink::WebIDBDatabaseError; using blink::WebIDBKey; using blink::WebVector; namespace content { namespace { class MockCallbacks : public WebIDBCallbacks { public: MockCallbacks() : error_seen_(false) {} virtual void onError(const WebIDBDatabaseError&) { error_seen_ = true; } bool error_seen() const { return error_seen_; } private: bool error_seen_; DISALLOW_COPY_AND_ASSIGN(MockCallbacks); }; class MockDispatcher : public IndexedDBDispatcher { public: explicit MockDispatcher(ThreadSafeSender* sender) : IndexedDBDispatcher(sender) {} virtual bool Send(IPC::Message* msg) OVERRIDE { delete msg; return true; } private: DISALLOW_COPY_AND_ASSIGN(MockDispatcher); }; } // namespace class IndexedDBDispatcherTest : public testing::Test { public: IndexedDBDispatcherTest() : message_loop_proxy_(base::MessageLoopProxy::current()), sync_message_filter_(new IPC::SyncMessageFilter(NULL)), thread_safe_sender_(new ThreadSafeSender(message_loop_proxy_.get(), sync_message_filter_.get())) {} protected: scoped_refptr<base::MessageLoopProxy> message_loop_proxy_; scoped_refptr<IPC::SyncMessageFilter> sync_message_filter_; scoped_refptr<ThreadSafeSender> thread_safe_sender_; private: DISALLOW_COPY_AND_ASSIGN(IndexedDBDispatcherTest); }; TEST_F(IndexedDBDispatcherTest, ValueSizeTest) { const std::vector<char> data(kMaxIDBValueSizeInBytes + 1); const WebData value(&data.front(), data.size()); const WebVector<WebBlobInfo> web_blob_info; const int32 ipc_dummy_id = -1; const int64 transaction_id = 1; const int64 object_store_id = 2; MockCallbacks callbacks; IndexedDBDispatcher dispatcher(thread_safe_sender_.get()); IndexedDBKey key(0, blink::WebIDBKeyTypeNumber); dispatcher.RequestIDBDatabasePut(ipc_dummy_id, transaction_id, object_store_id, value, web_blob_info, key, blink::WebIDBPutModeAddOrUpdate, &callbacks, WebVector<long long>(), WebVector<WebVector<WebIDBKey> >()); EXPECT_TRUE(callbacks.error_seen()); } TEST_F(IndexedDBDispatcherTest, KeyAndValueSizeTest) { const size_t kKeySize = 1024 * 1024; const std::vector<char> data(kMaxIDBValueSizeInBytes - kKeySize); const WebData value(&data.front(), data.size()); const WebVector<WebBlobInfo> web_blob_info; const IndexedDBKey key( base::string16(kKeySize / sizeof(base::string16::value_type), 'x')); const int32 ipc_dummy_id = -1; const int64 transaction_id = 1; const int64 object_store_id = 2; MockCallbacks callbacks; IndexedDBDispatcher dispatcher(thread_safe_sender_.get()); dispatcher.RequestIDBDatabasePut(ipc_dummy_id, transaction_id, object_store_id, value, web_blob_info, key, blink::WebIDBPutModeAddOrUpdate, &callbacks, WebVector<long long>(), WebVector<WebVector<WebIDBKey> >()); EXPECT_TRUE(callbacks.error_seen()); } namespace { class CursorCallbacks : public WebIDBCallbacks { public: explicit CursorCallbacks(scoped_ptr<WebIDBCursor>* cursor) : cursor_(cursor) {} virtual void onSuccess(const WebData&, const WebVector<WebBlobInfo>&) OVERRIDE {} virtual void onSuccess(WebIDBCursor* cursor, const WebIDBKey& key, const WebIDBKey& primaryKey, const WebData& value, const WebVector<WebBlobInfo>&) OVERRIDE { cursor_->reset(cursor); } private: scoped_ptr<WebIDBCursor>* cursor_; DISALLOW_COPY_AND_ASSIGN(CursorCallbacks); }; } // namespace TEST_F(IndexedDBDispatcherTest, CursorTransactionId) { const int32 ipc_database_id = -1; const int64 transaction_id = 1234; const int64 object_store_id = 2; const int32 index_id = 3; const blink::WebIDBCursorDirection direction = blink::WebIDBCursorDirectionNext; const bool key_only = false; MockDispatcher dispatcher(thread_safe_sender_.get()); // First case: successful cursor open. { scoped_ptr<WebIDBCursor> cursor; EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); // Make a cursor request. This should record the transaction id. dispatcher.RequestIDBDatabaseOpenCursor(ipc_database_id, transaction_id, object_store_id, index_id, IndexedDBKeyRange(), direction, key_only, blink::WebIDBTaskTypeNormal, new CursorCallbacks(&cursor)); // Verify that the transaction id was captured. EXPECT_EQ(1UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_FALSE(cursor.get()); int32 ipc_callbacks_id = dispatcher.cursor_transaction_ids_.begin()->first; IndexedDBMsg_CallbacksSuccessIDBCursor_Params params; params.ipc_thread_id = dispatcher.CurrentWorkerId(); params.ipc_callbacks_id = ipc_callbacks_id; // Now simululate the cursor response. params.ipc_cursor_id = WebIDBCursorImpl::kInvalidCursorId; dispatcher.OnSuccessOpenCursor(params); EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_TRUE(cursor.get()); WebIDBCursorImpl* impl = static_cast<WebIDBCursorImpl*>(cursor.get()); // This is the primary expectation of this test: the transaction id was // applied to the cursor. EXPECT_EQ(transaction_id, impl->transaction_id()); } // Second case: null cursor (no data in range) { scoped_ptr<WebIDBCursor> cursor; EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); // Make a cursor request. This should record the transaction id. dispatcher.RequestIDBDatabaseOpenCursor(ipc_database_id, transaction_id, object_store_id, index_id, IndexedDBKeyRange(), direction, key_only, blink::WebIDBTaskTypeNormal, new CursorCallbacks(&cursor)); // Verify that the transaction id was captured. EXPECT_EQ(1UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_FALSE(cursor.get()); int32 ipc_callbacks_id = dispatcher.cursor_transaction_ids_.begin()->first; // Now simululate a "null cursor" response. IndexedDBMsg_CallbacksSuccessValue_Params params; params.ipc_thread_id = dispatcher.CurrentWorkerId(); params.ipc_callbacks_id = ipc_callbacks_id; dispatcher.OnSuccessValue(params); // Ensure the map result was deleted. EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_FALSE(cursor.get()); } } namespace { class MockCursor : public WebIDBCursorImpl { public: MockCursor(int32 ipc_cursor_id, int64 transaction_id, ThreadSafeSender* thread_safe_sender) : WebIDBCursorImpl(ipc_cursor_id, transaction_id, thread_safe_sender), reset_count_(0) {} // This method is virtual so it can be overridden in unit tests. virtual void ResetPrefetchCache() OVERRIDE { ++reset_count_; } int reset_count() const { return reset_count_; } private: int reset_count_; DISALLOW_COPY_AND_ASSIGN(MockCursor); }; } // namespace TEST_F(IndexedDBDispatcherTest, CursorReset) { scoped_ptr<WebIDBCursor> cursor; MockDispatcher dispatcher(thread_safe_sender_.get()); const int32 ipc_database_id = 0; const int32 object_store_id = 0; const int32 index_id = 0; const bool key_only = false; const int cursor1_ipc_id = 1; const int cursor2_ipc_id = 2; const int other_cursor_ipc_id = 2; const int cursor1_transaction_id = 1; const int cursor2_transaction_id = 2; const int other_transaction_id = 3; scoped_ptr<MockCursor> cursor1( new MockCursor(WebIDBCursorImpl::kInvalidCursorId, cursor1_transaction_id, thread_safe_sender_.get())); scoped_ptr<MockCursor> cursor2( new MockCursor(WebIDBCursorImpl::kInvalidCursorId, cursor2_transaction_id, thread_safe_sender_.get())); dispatcher.cursors_[cursor1_ipc_id] = cursor1.get(); dispatcher.cursors_[cursor2_ipc_id] = cursor2.get(); EXPECT_EQ(0, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Other transaction: dispatcher.RequestIDBDatabaseGet(ipc_database_id, other_transaction_id, object_store_id, index_id, IndexedDBKeyRange(), key_only, new MockCallbacks()); EXPECT_EQ(0, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Same transaction: dispatcher.RequestIDBDatabaseGet(ipc_database_id, cursor1_transaction_id, object_store_id, index_id, IndexedDBKeyRange(), key_only, new MockCallbacks()); EXPECT_EQ(1, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Same transaction and same cursor: dispatcher.RequestIDBCursorContinue(IndexedDBKey(), IndexedDBKey(), new MockCallbacks(), cursor1_ipc_id, cursor1_transaction_id); EXPECT_EQ(1, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Same transaction and different cursor: dispatcher.RequestIDBCursorContinue(IndexedDBKey(), IndexedDBKey(), new MockCallbacks(), other_cursor_ipc_id, cursor1_transaction_id); EXPECT_EQ(2, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); cursor1.reset(); cursor2.reset(); } } // namespace content <commit_msg>Fix unit test memory leaks following blink r183043<commit_after>// 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 "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop_proxy.h" #include "base/values.h" #include "content/child/indexed_db/indexed_db_dispatcher.h" #include "content/child/indexed_db/webidbcursor_impl.h" #include "content/child/thread_safe_sender.h" #include "content/common/indexed_db/indexed_db_key.h" #include "content/common/indexed_db/indexed_db_key_range.h" #include "content/common/indexed_db/indexed_db_messages.h" #include "ipc/ipc_sync_message_filter.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebBlobInfo.h" #include "third_party/WebKit/public/platform/WebData.h" #include "third_party/WebKit/public/platform/WebIDBCallbacks.h" #include "third_party/WebKit/public/web/WebHeap.h" using blink::WebBlobInfo; using blink::WebData; using blink::WebIDBCallbacks; using blink::WebIDBCursor; using blink::WebIDBDatabase; using blink::WebIDBDatabaseError; using blink::WebIDBKey; using blink::WebVector; namespace content { namespace { class MockCallbacks : public WebIDBCallbacks { public: MockCallbacks() : error_seen_(false) {} virtual void onError(const WebIDBDatabaseError&) { error_seen_ = true; } bool error_seen() const { return error_seen_; } private: bool error_seen_; DISALLOW_COPY_AND_ASSIGN(MockCallbacks); }; class MockDispatcher : public IndexedDBDispatcher { public: explicit MockDispatcher(ThreadSafeSender* sender) : IndexedDBDispatcher(sender) {} virtual bool Send(IPC::Message* msg) OVERRIDE { delete msg; return true; } private: DISALLOW_COPY_AND_ASSIGN(MockDispatcher); }; } // namespace class IndexedDBDispatcherTest : public testing::Test { public: IndexedDBDispatcherTest() : message_loop_proxy_(base::MessageLoopProxy::current()), sync_message_filter_(new IPC::SyncMessageFilter(NULL)), thread_safe_sender_(new ThreadSafeSender(message_loop_proxy_.get(), sync_message_filter_.get())) {} virtual void TearDown() override { blink::WebHeap::collectAllGarbageForTesting(); } protected: scoped_refptr<base::MessageLoopProxy> message_loop_proxy_; scoped_refptr<IPC::SyncMessageFilter> sync_message_filter_; scoped_refptr<ThreadSafeSender> thread_safe_sender_; private: DISALLOW_COPY_AND_ASSIGN(IndexedDBDispatcherTest); }; TEST_F(IndexedDBDispatcherTest, ValueSizeTest) { const std::vector<char> data(kMaxIDBValueSizeInBytes + 1); const WebData value(&data.front(), data.size()); const WebVector<WebBlobInfo> web_blob_info; const int32 ipc_dummy_id = -1; const int64 transaction_id = 1; const int64 object_store_id = 2; MockCallbacks callbacks; IndexedDBDispatcher dispatcher(thread_safe_sender_.get()); IndexedDBKey key(0, blink::WebIDBKeyTypeNumber); dispatcher.RequestIDBDatabasePut(ipc_dummy_id, transaction_id, object_store_id, value, web_blob_info, key, blink::WebIDBPutModeAddOrUpdate, &callbacks, WebVector<long long>(), WebVector<WebVector<WebIDBKey> >()); EXPECT_TRUE(callbacks.error_seen()); } TEST_F(IndexedDBDispatcherTest, KeyAndValueSizeTest) { const size_t kKeySize = 1024 * 1024; const std::vector<char> data(kMaxIDBValueSizeInBytes - kKeySize); const WebData value(&data.front(), data.size()); const WebVector<WebBlobInfo> web_blob_info; const IndexedDBKey key( base::string16(kKeySize / sizeof(base::string16::value_type), 'x')); const int32 ipc_dummy_id = -1; const int64 transaction_id = 1; const int64 object_store_id = 2; MockCallbacks callbacks; IndexedDBDispatcher dispatcher(thread_safe_sender_.get()); dispatcher.RequestIDBDatabasePut(ipc_dummy_id, transaction_id, object_store_id, value, web_blob_info, key, blink::WebIDBPutModeAddOrUpdate, &callbacks, WebVector<long long>(), WebVector<WebVector<WebIDBKey> >()); EXPECT_TRUE(callbacks.error_seen()); } namespace { class CursorCallbacks : public WebIDBCallbacks { public: explicit CursorCallbacks(scoped_ptr<WebIDBCursor>* cursor) : cursor_(cursor) {} virtual void onSuccess(const WebData&, const WebVector<WebBlobInfo>&) OVERRIDE {} virtual void onSuccess(WebIDBCursor* cursor, const WebIDBKey& key, const WebIDBKey& primaryKey, const WebData& value, const WebVector<WebBlobInfo>&) OVERRIDE { cursor_->reset(cursor); } private: scoped_ptr<WebIDBCursor>* cursor_; DISALLOW_COPY_AND_ASSIGN(CursorCallbacks); }; } // namespace TEST_F(IndexedDBDispatcherTest, CursorTransactionId) { const int32 ipc_database_id = -1; const int64 transaction_id = 1234; const int64 object_store_id = 2; const int32 index_id = 3; const blink::WebIDBCursorDirection direction = blink::WebIDBCursorDirectionNext; const bool key_only = false; MockDispatcher dispatcher(thread_safe_sender_.get()); // First case: successful cursor open. { scoped_ptr<WebIDBCursor> cursor; EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); // Make a cursor request. This should record the transaction id. dispatcher.RequestIDBDatabaseOpenCursor(ipc_database_id, transaction_id, object_store_id, index_id, IndexedDBKeyRange(), direction, key_only, blink::WebIDBTaskTypeNormal, new CursorCallbacks(&cursor)); // Verify that the transaction id was captured. EXPECT_EQ(1UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_FALSE(cursor.get()); int32 ipc_callbacks_id = dispatcher.cursor_transaction_ids_.begin()->first; IndexedDBMsg_CallbacksSuccessIDBCursor_Params params; params.ipc_thread_id = dispatcher.CurrentWorkerId(); params.ipc_callbacks_id = ipc_callbacks_id; // Now simululate the cursor response. params.ipc_cursor_id = WebIDBCursorImpl::kInvalidCursorId; dispatcher.OnSuccessOpenCursor(params); EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_TRUE(cursor.get()); WebIDBCursorImpl* impl = static_cast<WebIDBCursorImpl*>(cursor.get()); // This is the primary expectation of this test: the transaction id was // applied to the cursor. EXPECT_EQ(transaction_id, impl->transaction_id()); } // Second case: null cursor (no data in range) { scoped_ptr<WebIDBCursor> cursor; EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); // Make a cursor request. This should record the transaction id. dispatcher.RequestIDBDatabaseOpenCursor(ipc_database_id, transaction_id, object_store_id, index_id, IndexedDBKeyRange(), direction, key_only, blink::WebIDBTaskTypeNormal, new CursorCallbacks(&cursor)); // Verify that the transaction id was captured. EXPECT_EQ(1UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_FALSE(cursor.get()); int32 ipc_callbacks_id = dispatcher.cursor_transaction_ids_.begin()->first; // Now simululate a "null cursor" response. IndexedDBMsg_CallbacksSuccessValue_Params params; params.ipc_thread_id = dispatcher.CurrentWorkerId(); params.ipc_callbacks_id = ipc_callbacks_id; dispatcher.OnSuccessValue(params); // Ensure the map result was deleted. EXPECT_EQ(0UL, dispatcher.cursor_transaction_ids_.size()); EXPECT_FALSE(cursor.get()); } } namespace { class MockCursor : public WebIDBCursorImpl { public: MockCursor(int32 ipc_cursor_id, int64 transaction_id, ThreadSafeSender* thread_safe_sender) : WebIDBCursorImpl(ipc_cursor_id, transaction_id, thread_safe_sender), reset_count_(0) {} // This method is virtual so it can be overridden in unit tests. virtual void ResetPrefetchCache() OVERRIDE { ++reset_count_; } int reset_count() const { return reset_count_; } private: int reset_count_; DISALLOW_COPY_AND_ASSIGN(MockCursor); }; } // namespace TEST_F(IndexedDBDispatcherTest, CursorReset) { scoped_ptr<WebIDBCursor> cursor; MockDispatcher dispatcher(thread_safe_sender_.get()); const int32 ipc_database_id = 0; const int32 object_store_id = 0; const int32 index_id = 0; const bool key_only = false; const int cursor1_ipc_id = 1; const int cursor2_ipc_id = 2; const int other_cursor_ipc_id = 2; const int cursor1_transaction_id = 1; const int cursor2_transaction_id = 2; const int other_transaction_id = 3; scoped_ptr<MockCursor> cursor1( new MockCursor(WebIDBCursorImpl::kInvalidCursorId, cursor1_transaction_id, thread_safe_sender_.get())); scoped_ptr<MockCursor> cursor2( new MockCursor(WebIDBCursorImpl::kInvalidCursorId, cursor2_transaction_id, thread_safe_sender_.get())); dispatcher.cursors_[cursor1_ipc_id] = cursor1.get(); dispatcher.cursors_[cursor2_ipc_id] = cursor2.get(); EXPECT_EQ(0, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Other transaction: dispatcher.RequestIDBDatabaseGet(ipc_database_id, other_transaction_id, object_store_id, index_id, IndexedDBKeyRange(), key_only, new MockCallbacks()); EXPECT_EQ(0, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Same transaction: dispatcher.RequestIDBDatabaseGet(ipc_database_id, cursor1_transaction_id, object_store_id, index_id, IndexedDBKeyRange(), key_only, new MockCallbacks()); EXPECT_EQ(1, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Same transaction and same cursor: dispatcher.RequestIDBCursorContinue(IndexedDBKey(), IndexedDBKey(), new MockCallbacks(), cursor1_ipc_id, cursor1_transaction_id); EXPECT_EQ(1, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); // Same transaction and different cursor: dispatcher.RequestIDBCursorContinue(IndexedDBKey(), IndexedDBKey(), new MockCallbacks(), other_cursor_ipc_id, cursor1_transaction_id); EXPECT_EQ(2, cursor1->reset_count()); EXPECT_EQ(0, cursor2->reset_count()); cursor1.reset(); cursor2.reset(); } } // namespace content <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #define DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include "config.h" #endif #include <dune/common/static_assert.hh> #include <dune/common/exceptions.hh> #include <dune/localfunctions/raviartthomas.hh> #include <dune/fem/space/common/allgeomtypes.hh> #include <dune/fem_localfunctions/localfunctions/transformations.hh> #include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh> #include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh> #include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh> #include <dune/stuff/common/color.hh> #include "../../mapper/fem.hh" #include "../../basefunctionset/fem-localfunctions.hh" #include "../constraints.hh" #include "../interface.hh" namespace Dune { namespace GDT { namespace RaviartThomasSpace { // forward, to be used in the traits and to allow for specialization template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class FemLocalfunctionsWrapper; // forward, to allow for specialization template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class FemLocalfunctionsWrapperTraits; template< class GridPartImp, int polynomialOrder, class RangeFieldImp > class FemLocalfunctionsWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > { dune_static_assert((GridPartImp::dimension == 2), "ERROR: only implemented for dimDomain = 2!"); dune_static_assert((polynomialOrder >= 0), "ERROR: wrong polOrder given!"); public: typedef GridPartImp GridPartType; static const int polOrder = polynomialOrder; private: typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; public: typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = 2; static const unsigned int dimRangeCols = 1; typedef FemLocalfunctionsWrapper< GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols > derived_type; private: typedef Dune::RaviartThomasLocalFiniteElement< dimDomain, DomainFieldType, RangeFieldType > FiniteElementType; typedef Dune::FemLocalFunctions::BaseFunctionSetMap< GridPartType, FiniteElementType, Dune::FemLocalFunctions::PiolaTransformation, Dune::FemLocalFunctions::SimpleStorage, polOrder, polOrder, true > BaseFunctionSetMapType; public: typedef Dune::FemLocalFunctions::DiscreteFunctionSpace< BaseFunctionSetMapType > BackendType; typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType; typedef BaseFunctionSet::FemLocalfunctionsWrapper< BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType; typedef typename BaseFunctionSetType::EntityType EntityType; private: template< class G, int p, class R, int r, int rC > friend class FemLocalfunctionsWrapper; }; // class FemLocalfunctionsWrapperTraits< ..., 1, 1 > template< class GridPartImp, int polynomialOrder, class RangeFieldImp > class FemLocalfunctionsWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > : public SpaceInterface< FemLocalfunctionsWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > > { public: typedef FemLocalfunctionsWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > Traits; typedef typename Traits::GridPartType GridPartType; typedef typename GridPartType::ctype DomainFieldType; static const int polOrder = Traits::polOrder; static const unsigned int dimDomain = GridPartType::dimension; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; private: typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType; public: FemLocalfunctionsWrapper(const GridPartType& gridP) : gridPart_(assertGridPart(gridP)) , baseFunctionSetMap_(gridPart_) , backend_(const_cast< GridPartType& >(gridPart_), baseFunctionSetMap_) , mapper_(backend_.mapper()) {} const GridPartType& gridPart() const { return gridPart_; } const BackendType& backend() const { return backend_; } bool continuous() const { return true; } const MapperType& mapper() const { return mapper_; } BaseFunctionSetType baseFunctionSet(const EntityType& entity) const { return BaseFunctionSetType(baseFunctionSetMap_, entity); } template< class R > void localConstraints(const EntityType& /*entity*/, Constraints::LocalDefault< R >& /*ret*/) const { dune_static_assert(Dune::AlwaysFalse< R >::value, "ERROR: not implemented for arbitrary constraints!"); } private: static const GridPartType& assertGridPart(const GridPartType& gP) { // check typedef typename Dune::Fem::AllGeomTypes< typename GridPartType::IndexSetType, typename GridPartType::GridType > AllGeometryTypes; const AllGeometryTypes allGeometryTypes(gP.indexSet()); const std::vector< Dune::GeometryType >& geometryTypes = allGeometryTypes.geomTypes(0); if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex())) DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " this space is only implemented for simplicial grids!"); return gP; } // ... assertGridPart(...) const GridPartType& gridPart_; BaseFunctionSetMapType baseFunctionSetMap_; const BackendType backend_; const MapperType mapper_; }; // class FemLocalfunctionsWrapper< ..., 1, 1 > } // namespace RaviartThomasSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH <commit_msg>[space.raviartthomas...] is not continuous<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #define DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include "config.h" #endif #include <dune/common/static_assert.hh> #include <dune/common/exceptions.hh> #include <dune/localfunctions/raviartthomas.hh> #include <dune/fem/space/common/allgeomtypes.hh> #include <dune/fem_localfunctions/localfunctions/transformations.hh> #include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh> #include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh> #include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh> #include <dune/stuff/common/color.hh> #include "../../mapper/fem.hh" #include "../../basefunctionset/fem-localfunctions.hh" #include "../constraints.hh" #include "../interface.hh" namespace Dune { namespace GDT { namespace RaviartThomasSpace { // forward, to be used in the traits and to allow for specialization template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class FemLocalfunctionsWrapper; // forward, to allow for specialization template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class FemLocalfunctionsWrapperTraits; template< class GridPartImp, int polynomialOrder, class RangeFieldImp > class FemLocalfunctionsWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > { dune_static_assert((GridPartImp::dimension == 2), "ERROR: only implemented for dimDomain = 2!"); dune_static_assert((polynomialOrder >= 0), "ERROR: wrong polOrder given!"); public: typedef GridPartImp GridPartType; static const int polOrder = polynomialOrder; private: typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; public: typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = 2; static const unsigned int dimRangeCols = 1; typedef FemLocalfunctionsWrapper< GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols > derived_type; private: typedef Dune::RaviartThomasLocalFiniteElement< dimDomain, DomainFieldType, RangeFieldType > FiniteElementType; typedef Dune::FemLocalFunctions::BaseFunctionSetMap< GridPartType, FiniteElementType, Dune::FemLocalFunctions::PiolaTransformation, Dune::FemLocalFunctions::SimpleStorage, polOrder, polOrder, true > BaseFunctionSetMapType; public: typedef Dune::FemLocalFunctions::DiscreteFunctionSpace< BaseFunctionSetMapType > BackendType; typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType; typedef BaseFunctionSet::FemLocalfunctionsWrapper< BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType; typedef typename BaseFunctionSetType::EntityType EntityType; private: template< class G, int p, class R, int r, int rC > friend class FemLocalfunctionsWrapper; }; // class FemLocalfunctionsWrapperTraits< ..., 1, 1 > template< class GridPartImp, int polynomialOrder, class RangeFieldImp > class FemLocalfunctionsWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > : public SpaceInterface< FemLocalfunctionsWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > > { public: typedef FemLocalfunctionsWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 2, 1 > Traits; typedef typename Traits::GridPartType GridPartType; typedef typename GridPartType::ctype DomainFieldType; static const int polOrder = Traits::polOrder; static const unsigned int dimDomain = GridPartType::dimension; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; private: typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType; public: FemLocalfunctionsWrapper(const GridPartType& gridP) : gridPart_(assertGridPart(gridP)) , baseFunctionSetMap_(gridPart_) , backend_(const_cast< GridPartType& >(gridPart_), baseFunctionSetMap_) , mapper_(backend_.mapper()) {} const GridPartType& gridPart() const { return gridPart_; } const BackendType& backend() const { return backend_; } bool continuous() const { return false; } const MapperType& mapper() const { return mapper_; } BaseFunctionSetType baseFunctionSet(const EntityType& entity) const { return BaseFunctionSetType(baseFunctionSetMap_, entity); } template< class R > void localConstraints(const EntityType& /*entity*/, Constraints::LocalDefault< R >& /*ret*/) const { dune_static_assert(Dune::AlwaysFalse< R >::value, "ERROR: not implemented for arbitrary constraints!"); } private: static const GridPartType& assertGridPart(const GridPartType& gP) { // check typedef typename Dune::Fem::AllGeomTypes< typename GridPartType::IndexSetType, typename GridPartType::GridType > AllGeometryTypes; const AllGeometryTypes allGeometryTypes(gP.indexSet()); const std::vector< Dune::GeometryType >& geometryTypes = allGeometryTypes.geomTypes(0); if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex())) DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " this space is only implemented for simplicial grids!"); return gP; } // ... assertGridPart(...) const GridPartType& gridPart_; BaseFunctionSetMapType baseFunctionSetMap_; const BackendType backend_; const MapperType mapper_; }; // class FemLocalfunctionsWrapper< ..., 1, 1 > } // namespace RaviartThomasSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH <|endoftext|>
<commit_before>/** * Copyright (c) 2013, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_util.cc * * Dumping ground for useful functions with no other home. */ #include "config.h" #include <stdio.h> #include <fcntl.h> #include <ctype.h> #include <sqlite3.h> #include "auto_fd.hh" #include "lnav_util.hh" std::string hash_string(const std::string &str) { byte_array<SHA_DIGEST_LENGTH> hash; SHA_CTX context; SHA_Init(&context); SHA_Update(&context, str.c_str(), str.length()); SHA_Final(hash.out(), &context); return hash.to_string(); } std::string time_ago(time_t last_time) { time_t delta, current_time = time(NULL); const char *fmt; char buffer[64]; int amount; delta = current_time - last_time; if (delta < 0) { return "in the future"; } else if (delta < 60) { return "just now"; } else if (delta < (60 * 2)) { return "one minute ago"; } else if (delta < (60 * 60)) { fmt = "%d minutes ago"; amount = delta / 60; } else if (delta < (2 * 60 * 60)) { return "one hour ago"; } else if (delta < (24 * 60 * 60)) { fmt = "%d hours ago"; amount = delta / (60 * 60); } else if (delta < (2 * 24 * 60 * 60)) { return "one day ago"; } else if (delta < (365 * 24 * 60 * 60)) { fmt = "%d days ago"; amount = delta / (24 * 60 * 60); } else { return "over a year ago"; } snprintf(buffer, sizeof(buffer), fmt, amount); return std::string(buffer); } /* XXX figure out how to do this with the template */ void sqlite_close_wrapper(void *mem) { sqlite3_close((sqlite3 *)mem); } std::string get_current_dir(void) { char cwd[FILENAME_MAX]; std::string retval = "."; if (getcwd(cwd, sizeof(cwd)) == NULL) { perror("getcwd"); } else { retval = std::string(cwd); } if (retval != "/") { retval += "/"; } return retval; } bool change_to_parent_dir(void) { bool retval = false; char cwd[3] = ""; if (getcwd(cwd, sizeof(cwd)) == NULL) { /* perror("getcwd"); */ } if (strcmp(cwd, "/") != 0) { if (chdir("..") == -1) { perror("chdir('..')"); } else { retval = true; } } return retval; } file_format_t detect_file_format(const std::string &filename) { file_format_t retval = FF_UNKNOWN; auto_fd fd; if ((fd = open(filename.c_str(), O_RDONLY)) != -1) { char buffer[32]; int rc; if ((rc = read(fd, buffer, sizeof(buffer))) > 0) { if (rc > 16 && strncmp(buffer, "SQLite format 3", 16) == 0) { retval = FF_SQLITE_DB; } } } return retval; } static time_t BAD_DATE = -1; time_t tm2sec(const struct tm *t) { int year; time_t days; const int dayoffset[12] = { 306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275 }; year = t->tm_year; if (year < 70 || ((sizeof(time_t) <= 4) && (year >= 138))) { return BAD_DATE; } /* shift new year to 1st March in order to make leap year calc easy */ if (t->tm_mon < 2) { year--; } /* Find number of days since 1st March 1900 (in the Gregorian calendar). */ days = year * 365 + year / 4 - year / 100 + (year / 100 + 3) / 4; days += dayoffset[t->tm_mon] + t->tm_mday - 1; days -= 25508; /* 1 jan 1970 is 25508 days since 1 mar 1900 */ days = ((days * 24 + t->tm_hour) * 60 + t->tm_min) * 60 + t->tm_sec; if (days < 0) { return BAD_DATE; } /* must have overflowed */ else { #ifdef HAVE_STRUCT_TM_TM_ZONE if (t->tm_zone) { days -= t->tm_gmtoff; } #endif return days; } /* must be a valid time */ } bool next_format(const char *fmt[], int &index, int &locked_index) { bool retval = true; if (locked_index == -1) { index += 1; if (fmt[index] == NULL) { retval = false; } } else if (index == locked_index) { retval = false; } else { index = locked_index; } return retval; } static const char *time_fmt_with_zone = "%a %b %d %H:%M:%S "; const char *std_time_fmt[] = { "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%SZ", "%Y/%m/%d %H:%M:%S", "%Y/%m/%d %H:%M", "%a %b %d %H:%M:%S %Y", "%a %b %d %H:%M:%S %Z %Y", time_fmt_with_zone, "%d/%b/%Y:%H:%M:%S +0000", "%d/%b/%Y:%H:%M:%S %z", "%b %d %H:%M:%S", "%m/%d/%y %H:%M:%S", "%m%d %H:%M:%S", "+%s", NULL, }; const char *date_time_scanner::scan(const char *time_dest, const char *time_fmt[], struct tm *tm_out, struct timeval &tv_out) { int curr_time_fmt = -1; bool found = false; const char *retval = NULL; if (!time_fmt) { time_fmt = std_time_fmt; } while (next_format(time_fmt, curr_time_fmt, this->dts_fmt_lock)) { *tm_out = this->dts_base_tm; if (time_fmt[curr_time_fmt][0] == '+') { int gmt_int, off; retval = NULL; if (sscanf(time_dest, "+%d%n", &gmt_int, &off) == 1) { time_t gmt = gmt_int; if (this->dts_local_time) { localtime_r(&gmt, tm_out); #ifdef HAVE_STRUCT_TM_TM_ZONE tm_out->tm_zone = NULL; #endif tm_out->tm_isdst = 0; gmt = tm2sec(tm_out); } tv_out.tv_sec = gmt; this->dts_fmt_lock = curr_time_fmt; this->dts_fmt_len = off; retval = time_dest + off; found = true; break; } } else if ((retval = strptime(time_dest, time_fmt[curr_time_fmt], tm_out)) != NULL) { if (time_fmt[curr_time_fmt] == time_fmt_with_zone) { int lpc; for (lpc = 0; retval[lpc] && retval[lpc] != ' '; lpc++) { } if (retval[lpc] == ' ' && sscanf(&retval[lpc], "%d", &tm_out->tm_year) == 1) { lpc += 1; for (; retval[lpc] && isdigit(retval[lpc]); lpc++) { } retval = &retval[lpc]; } } if (tm_out->tm_year < 70) { tm_out->tm_year = 80; } if (this->dts_local_time) { time_t gmt = tm2sec(tm_out); localtime_r(&gmt, tm_out); #ifdef HAVE_STRUCT_TM_TM_ZONE tm_out->tm_zone = NULL; #endif tm_out->tm_isdst = 0; } tv_out.tv_sec = tm2sec(tm_out); tv_out.tv_usec = 0; this->dts_fmt_lock = curr_time_fmt; this->dts_fmt_len = retval - time_dest; found = true; break; } } if (!found) { retval = NULL; } if (retval != NULL) { /* Try to pull out the milli/micro-second value. */ if (retval[0] == '.' || retval[0] == ',') { int sub_seconds = 0, sub_len = 0; if (sscanf(retval + 1, "%d%n", &sub_seconds, &sub_len) == 1) { switch (sub_len) { case 3: tv_out.tv_usec = sub_seconds * 1000; this->dts_fmt_len += 1 + sub_len; break; case 6: tv_out.tv_usec = sub_seconds; this->dts_fmt_len += 1 + sub_len; break; } } } } return retval; } template<typename T> size_t strtonum(T &num_out, const char *string, size_t len) { size_t retval = 0; T sign = 1; num_out = 0; for (; retval < len && isspace(string[retval]); retval++); for (; retval < len && string[retval] == '-'; retval++) { sign *= -1; } for (; retval < len && string[retval] == '+'; retval++); for (; retval < len && isdigit(string[retval]); retval++) { num_out *= 10; num_out += string[retval] - '0'; } return retval; } template size_t strtonum<long long>(long long &num_out, const char *string, size_t len); <commit_msg>instantiate templates for other number types<commit_after>/** * Copyright (c) 2013, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_util.cc * * Dumping ground for useful functions with no other home. */ #include "config.h" #include <stdio.h> #include <fcntl.h> #include <ctype.h> #include <sqlite3.h> #include "auto_fd.hh" #include "lnav_util.hh" std::string hash_string(const std::string &str) { byte_array<SHA_DIGEST_LENGTH> hash; SHA_CTX context; SHA_Init(&context); SHA_Update(&context, str.c_str(), str.length()); SHA_Final(hash.out(), &context); return hash.to_string(); } std::string time_ago(time_t last_time) { time_t delta, current_time = time(NULL); const char *fmt; char buffer[64]; int amount; delta = current_time - last_time; if (delta < 0) { return "in the future"; } else if (delta < 60) { return "just now"; } else if (delta < (60 * 2)) { return "one minute ago"; } else if (delta < (60 * 60)) { fmt = "%d minutes ago"; amount = delta / 60; } else if (delta < (2 * 60 * 60)) { return "one hour ago"; } else if (delta < (24 * 60 * 60)) { fmt = "%d hours ago"; amount = delta / (60 * 60); } else if (delta < (2 * 24 * 60 * 60)) { return "one day ago"; } else if (delta < (365 * 24 * 60 * 60)) { fmt = "%d days ago"; amount = delta / (24 * 60 * 60); } else { return "over a year ago"; } snprintf(buffer, sizeof(buffer), fmt, amount); return std::string(buffer); } /* XXX figure out how to do this with the template */ void sqlite_close_wrapper(void *mem) { sqlite3_close((sqlite3 *)mem); } std::string get_current_dir(void) { char cwd[FILENAME_MAX]; std::string retval = "."; if (getcwd(cwd, sizeof(cwd)) == NULL) { perror("getcwd"); } else { retval = std::string(cwd); } if (retval != "/") { retval += "/"; } return retval; } bool change_to_parent_dir(void) { bool retval = false; char cwd[3] = ""; if (getcwd(cwd, sizeof(cwd)) == NULL) { /* perror("getcwd"); */ } if (strcmp(cwd, "/") != 0) { if (chdir("..") == -1) { perror("chdir('..')"); } else { retval = true; } } return retval; } file_format_t detect_file_format(const std::string &filename) { file_format_t retval = FF_UNKNOWN; auto_fd fd; if ((fd = open(filename.c_str(), O_RDONLY)) != -1) { char buffer[32]; int rc; if ((rc = read(fd, buffer, sizeof(buffer))) > 0) { if (rc > 16 && strncmp(buffer, "SQLite format 3", 16) == 0) { retval = FF_SQLITE_DB; } } } return retval; } static time_t BAD_DATE = -1; time_t tm2sec(const struct tm *t) { int year; time_t days; const int dayoffset[12] = { 306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275 }; year = t->tm_year; if (year < 70 || ((sizeof(time_t) <= 4) && (year >= 138))) { return BAD_DATE; } /* shift new year to 1st March in order to make leap year calc easy */ if (t->tm_mon < 2) { year--; } /* Find number of days since 1st March 1900 (in the Gregorian calendar). */ days = year * 365 + year / 4 - year / 100 + (year / 100 + 3) / 4; days += dayoffset[t->tm_mon] + t->tm_mday - 1; days -= 25508; /* 1 jan 1970 is 25508 days since 1 mar 1900 */ days = ((days * 24 + t->tm_hour) * 60 + t->tm_min) * 60 + t->tm_sec; if (days < 0) { return BAD_DATE; } /* must have overflowed */ else { #ifdef HAVE_STRUCT_TM_TM_ZONE if (t->tm_zone) { days -= t->tm_gmtoff; } #endif return days; } /* must be a valid time */ } bool next_format(const char *fmt[], int &index, int &locked_index) { bool retval = true; if (locked_index == -1) { index += 1; if (fmt[index] == NULL) { retval = false; } } else if (index == locked_index) { retval = false; } else { index = locked_index; } return retval; } static const char *time_fmt_with_zone = "%a %b %d %H:%M:%S "; const char *std_time_fmt[] = { "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%SZ", "%Y/%m/%d %H:%M:%S", "%Y/%m/%d %H:%M", "%a %b %d %H:%M:%S %Y", "%a %b %d %H:%M:%S %Z %Y", time_fmt_with_zone, "%d/%b/%Y:%H:%M:%S +0000", "%d/%b/%Y:%H:%M:%S %z", "%b %d %H:%M:%S", "%m/%d/%y %H:%M:%S", "%m%d %H:%M:%S", "+%s", NULL, }; const char *date_time_scanner::scan(const char *time_dest, const char *time_fmt[], struct tm *tm_out, struct timeval &tv_out) { int curr_time_fmt = -1; bool found = false; const char *retval = NULL; if (!time_fmt) { time_fmt = std_time_fmt; } while (next_format(time_fmt, curr_time_fmt, this->dts_fmt_lock)) { *tm_out = this->dts_base_tm; if (time_fmt[curr_time_fmt][0] == '+') { int gmt_int, off; retval = NULL; if (sscanf(time_dest, "+%d%n", &gmt_int, &off) == 1) { time_t gmt = gmt_int; if (this->dts_local_time) { localtime_r(&gmt, tm_out); #ifdef HAVE_STRUCT_TM_TM_ZONE tm_out->tm_zone = NULL; #endif tm_out->tm_isdst = 0; gmt = tm2sec(tm_out); } tv_out.tv_sec = gmt; this->dts_fmt_lock = curr_time_fmt; this->dts_fmt_len = off; retval = time_dest + off; found = true; break; } } else if ((retval = strptime(time_dest, time_fmt[curr_time_fmt], tm_out)) != NULL) { if (time_fmt[curr_time_fmt] == time_fmt_with_zone) { int lpc; for (lpc = 0; retval[lpc] && retval[lpc] != ' '; lpc++) { } if (retval[lpc] == ' ' && sscanf(&retval[lpc], "%d", &tm_out->tm_year) == 1) { lpc += 1; for (; retval[lpc] && isdigit(retval[lpc]); lpc++) { } retval = &retval[lpc]; } } if (tm_out->tm_year < 70) { tm_out->tm_year = 80; } if (this->dts_local_time) { time_t gmt = tm2sec(tm_out); localtime_r(&gmt, tm_out); #ifdef HAVE_STRUCT_TM_TM_ZONE tm_out->tm_zone = NULL; #endif tm_out->tm_isdst = 0; } tv_out.tv_sec = tm2sec(tm_out); tv_out.tv_usec = 0; this->dts_fmt_lock = curr_time_fmt; this->dts_fmt_len = retval - time_dest; found = true; break; } } if (!found) { retval = NULL; } if (retval != NULL) { /* Try to pull out the milli/micro-second value. */ if (retval[0] == '.' || retval[0] == ',') { int sub_seconds = 0, sub_len = 0; if (sscanf(retval + 1, "%d%n", &sub_seconds, &sub_len) == 1) { switch (sub_len) { case 3: tv_out.tv_usec = sub_seconds * 1000; this->dts_fmt_len += 1 + sub_len; break; case 6: tv_out.tv_usec = sub_seconds; this->dts_fmt_len += 1 + sub_len; break; } } } } return retval; } template<typename T> size_t strtonum(T &num_out, const char *string, size_t len) { size_t retval = 0; T sign = 1; num_out = 0; for (; retval < len && isspace(string[retval]); retval++); for (; retval < len && string[retval] == '-'; retval++) { sign *= -1; } for (; retval < len && string[retval] == '+'; retval++); for (; retval < len && isdigit(string[retval]); retval++) { num_out *= 10; num_out += string[retval] - '0'; } return retval; } template size_t strtonum<long long>(long long &num_out, const char *string, size_t len); template size_t strtonum<long>(long &num_out, const char *string, size_t len); template size_t strtonum<int>(int &num_out, const char *string, size_t len); <|endoftext|>
<commit_before>// ProtectMySelf.cpp : α׷ մϴ. // #include "stdafx.h" #include "ProtectMySelf.h" #define MAX_LOADSTRING 100 // : HINSTANCE hInst; // νϽԴϴ. TCHAR szTitle[MAX_LOADSTRING]; // ǥ ؽƮԴϴ. TCHAR szWindowClass[MAX_LOADSTRING]; // ⺻ â Ŭ ̸Դϴ. // ڵ ⿡ ִ Լ Դϴ. ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: ⿡ ڵ带 Էմϴ. MSG msg; HACCEL hAccelTable; // ڿ ʱȭմϴ. LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_PROTECTMYSELF, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // α׷ ʱȭ մϴ. if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PROTECTMYSELF)); // ⺻ ޽ Դϴ. while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // Լ: MyRegisterClass() // // : â Ŭ մϴ. // // : // // Windows 95 ߰ 'RegisterClassEx' Լ // ش ڵ尡 Win32 ý۰ ȣȯǵ // Ϸ 쿡 Լ մϴ. Լ ȣؾ // ش α׷ // 'ùٸ ' ֽϴ. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PROTECTMYSELF)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_PROTECTMYSELF); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // Լ: InitInstance(HINSTANCE, int) // // : νϽ ڵ ϰ â ϴ. // // : // // Լ νϽ ڵ ϰ // α׷ â ǥմϴ. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // νϽ ڵ մϴ. hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // Լ: WndProc(HWND, UINT, WPARAM, LPARAM) // // : â ޽ óմϴ. // // WM_COMMAND - α׷ ޴ óմϴ. // WM_PAINT - â ׸ϴ. // WM_DESTROY - ޽ Խϰ ȯմϴ. // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // ޴ мմϴ. switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: ⿡ ׸ ڵ带 ߰մϴ. EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // ȭ ޽ óԴϴ. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } <commit_msg>Timer & WTS<commit_after>// ProtectMySelf.cpp : α׷ մϴ. // #include "stdafx.h" #include "ProtectMySelf.h" #include <WtsApi32.h> #pragma comment(lib,"wtsapi32.lib") #define MAX_LOADSTRING 100 #define IDC_TIMER 999 // : HINSTANCE hInst; // νϽԴϴ. TCHAR szTitle[MAX_LOADSTRING]; // ǥ ؽƮԴϴ. TCHAR szWindowClass[MAX_LOADSTRING]; // ⺻ â Ŭ ̸Դϴ. BOOL fBlocked; // ڵ ⿡ ִ Լ Դϴ. ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: ⿡ ڵ带 Էմϴ. MSG msg; HACCEL hAccelTable; // ڿ ʱȭմϴ. LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_PROTECTMYSELF, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // α׷ ʱȭ մϴ. if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PROTECTMYSELF)); // ⺻ ޽ Դϴ. while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // Լ: MyRegisterClass() // // : â Ŭ մϴ. // // : // // Windows 95 ߰ 'RegisterClassEx' Լ // ش ڵ尡 Win32 ý۰ ȣȯǵ // Ϸ 쿡 Լ մϴ. Լ ȣؾ // ش α׷ // 'ùٸ ' ֽϴ. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PROTECTMYSELF)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_PROTECTMYSELF); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // Լ: InitInstance(HINSTANCE, int) // // : νϽ ڵ ϰ â ϴ. // // : // // Լ νϽ ڵ ϰ // α׷ â ǥմϴ. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // νϽ ڵ մϴ. hWnd = CreateWindow(szWindowClass, szTitle, WS_EX_TOOLWINDOW | WS_SYSMENU | WS_CAPTION, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } RECT rc = {0}; if (::SystemParametersInfoW(SPI_GETWORKAREA, 0, &rc, 0)) { rc.left = rc.right; rc.top = rc.bottom; } ::SetWindowPos(hWnd, NULL, rc.left, rc.top, 0, 0, SWP_HIDEWINDOW); fBlocked = FALSE; ::SetTimer(hWnd, IDC_TIMER, 50*60*1000, 0); ::WTSRegisterSessionNotification(hWnd, NOTIFY_FOR_ALL_SESSIONS); // ShowWindow(hWnd, nCmdShow); // UpdateWindow(hWnd); return TRUE; } // // Լ: WndProc(HWND, UINT, WPARAM, LPARAM) // // : â ޽ óմϴ. // // WM_COMMAND - α׷ ޴ óմϴ. // WM_PAINT - â ׸ϴ. // WM_DESTROY - ޽ Խϰ ȯմϴ. // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // ޴ мմϴ. switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: ⿡ ׸ ڵ带 ߰մϴ. EndPaint(hWnd, &ps); break; case WM_DESTROY: KillTimer(hWnd, IDC_TIMER); PostQuitMessage(0); break; case WM_TIMER: if(IDC_TIMER == wParam && FALSE == fBlocked) { BlockInput(TRUE); LockWorkStation(); } break; case WM_WTSSESSION_CHANGE: if(WTS_SESSION_LOCK == wParam) { fBlocked = TRUE; KillTimer(hWnd, IDC_TIMER); } else if(WTS_SESSION_UNLOCK == wParam) { fBlocked = FALSE; SetTimer(hWnd, IDC_TIMER, 50*60*1000, 0); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // ȭ ޽ óԴϴ. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } <|endoftext|>
<commit_before>// Copyright © 2017-2018 Dmitriy Khaustov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.08.16 // Sink.cpp #include <stdexcept> #include "Sink.hpp" #include <sstream> Sink::Sink(const Setting& setting) { std::ostringstream cfgline("/P7.Pool=32768"); if (!setting.lookupValue("name", _name)) { throw std::runtime_error("Not found name for one of sinks"); } std::string type; if (!setting.lookupValue("type", type)) { throw std::runtime_error("Undefined type for sink '" + _name + "'"); } if (type == "console") { cfgline << " /P7.Sink=Console"; } else if (type == "file") { cfgline << " /P7.Sink=FileTxt"; } else if (type == "syslog") { cfgline << " /P7.Sink=Syslog"; } else { throw std::runtime_error("Unknown type ('" + type + "') for sink '" + _name + "'"); } std::string format; if (!setting.lookupValue("format", format)) { format = "%tm\t%tn\t%mn\t%lv\t%ms"; } cfgline << " /P7.Format=" << format; if (type == "file") { std::string directory; if (!setting.lookupValue("directory", directory)) { throw std::runtime_error("Undefined directory for sink '" + _name + "'"); } cfgline << " /P7.Dir=" << directory; std::string rolling; if (!setting.lookupValue("rolling", rolling)) { throw std::runtime_error("Undefined setting of rolling for sink '" + _name + "'"); } cfgline << " /P7.Roll=" << rolling; uint32_t maxcount; if (!setting.lookupValue("maxcount", maxcount)) { throw std::runtime_error("Undefined maxcount of rolling for sink '" + _name + "'"); } cfgline << " /P7.Files=" << maxcount; } _p7client = P7_Create_Client(cfgline.str().c_str()); if (_p7client == nullptr) { throw std::runtime_error("Can't create p7-client for sink '" + _name + "'"); } _p7trace = P7_Create_Trace(_p7client, "TraceChannel"); if (_p7trace == nullptr) { throw std::runtime_error("Can't create p7-channel for sink '" + _name + "'"); } _p7trace->Share("TraceChannel"); } Sink::Sink() { _p7client = P7_Create_Client("/P7.Pool=32768 /P7.Sink=Console /P7.Format=%tm\t%tn\t%mn\t%lv\t%ms"); if (_p7client == nullptr) { throw std::runtime_error("Can't create p7-client for default sink"); } _p7trace = P7_Create_Trace(_p7client, "TraceChannel"); if (_p7trace == nullptr) { throw std::runtime_error("Can't create p7-channel for default sink"); } _p7trace->Share("TraceChannel"); } Sink::~Sink() { _p7trace->Release(); _p7client->Release(); } <commit_msg>Fix logger sink<commit_after>// Copyright © 2017-2018 Dmitriy Khaustov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.08.16 // Sink.cpp #include <stdexcept> #include "Sink.hpp" #include <sstream> Sink::Sink(const Setting& setting) { std::string cfgline = "/P7.Pool=32768"; if (!setting.lookupValue("name", _name)) { throw std::runtime_error("Not found name for one of sinks"); } std::string type; if (!setting.lookupValue("type", type)) { throw std::runtime_error("Undefined type for sink '" + _name + "'"); } if (type == "console") { cfgline += " /P7.Sink=Console"; } else if (type == "file") { cfgline += " /P7.Sink=FileTxt"; } else if (type == "syslog") { cfgline += " /P7.Sink=Syslog"; } else { throw std::runtime_error("Unknown type ('" + type + "') for sink '" + _name + "'"); } std::string format; if (!setting.lookupValue("format", format)) { format = "%tm\t%tn\t%mn\t%lv\t%ms"; } cfgline += " /P7.Format=" + format; if (type == "file") { std::string directory; if (!setting.lookupValue("directory", directory)) { throw std::runtime_error("Undefined directory for sink '" + _name + "'"); } cfgline += " /P7.Dir=" + directory; std::string rolling; if (!setting.lookupValue("rolling", rolling)) { throw std::runtime_error("Undefined setting of rolling for sink '" + _name + "'"); } cfgline += " /P7.Roll=" + rolling; uint32_t maxcount; if (!setting.lookupValue("maxcount", maxcount)) { throw std::runtime_error("Undefined maxcount of rolling for sink '" + _name + "'"); } cfgline += " /P7.Files=" + maxcount; } _p7client = P7_Create_Client(cfgline.c_str()); if (_p7client == nullptr) { throw std::runtime_error("Can't create p7-client for sink '" + _name + "'"); } _p7trace = P7_Create_Trace(_p7client, "TraceChannel"); if (_p7trace == nullptr) { throw std::runtime_error("Can't create p7-channel for sink '" + _name + "'"); } _p7trace->Share("TraceChannel"); } Sink::Sink() { _p7client = P7_Create_Client("/P7.Pool=32768 /P7.Sink=Console /P7.Format=%tm\t%tn\t%mn\t%lv\t%ms"); if (_p7client == nullptr) { throw std::runtime_error("Can't create p7-client for default sink"); } _p7trace = P7_Create_Trace(_p7client, "TraceChannel"); if (_p7trace == nullptr) { throw std::runtime_error("Can't create p7-channel for default sink"); } _p7trace->Share("TraceChannel"); } Sink::~Sink() { _p7trace->Release(); _p7client->Release(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ 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 <QmitkFunctionalityTesting.h> #include <QmitkFctMediator.h> #include <qapplication.h> #include <qtimer.h> #include <qwidgetlist.h> #include <qobjectlist.h> #include <qmessagebox.h> #include <stdlib.h> #include <iostream> #include <mitkTestingConfig.h> QmitkFunctionalityTesting::QmitkFunctionalityTesting( QmitkFctMediator* qfm, QObject * parent, const char * name ) : QObject(parent, name), m_QmitkFctMediator(qfm) { QObject::connect( &m_ActivateTimer, SIGNAL(timeout()), this, SLOT(ActivateNextFunctionality()) ); QObject::connect( &m_CloseMessagesTimer, SIGNAL(timeout()), this, SLOT(CloseFirstMessageBox()) ); } QmitkFunctionalityTesting::~QmitkFunctionalityTesting() { } void QmitkFunctionalityTesting::CloseFirstMessageBox() { bool boxClosed = false; QWidgetList* topWidgets = QApplication::topLevelWidgets(); QWidgetListIt topWidgetsIt(*topWidgets); QWidget* widget; while ( ( widget = topWidgetsIt.current()) != 0 ) { ++topWidgetsIt; if (widget->isA("QMessageBox")) { std::cout << "Found a toplevel message box! Give it a parent! Closing it ..." << std::endl; ((QMessageBox*)widget)->close(); boxClosed=true; break; } QObjectList *l = widget->queryList( "QMessageBox" ); QObjectListIt it( *l ); QObject *obj; while ( (obj = it.current()) != 0 ) { ++it; std::cout << "Found a message box! Closing it ..." << std::endl; ((QMessageBox*)obj)->close(); boxClosed = true; break; } delete l; // delete the list, not the objects if (boxClosed) { break; } } delete topWidgets; if (boxClosed) { // let everything redraw and call self m_CloseMessagesTimer.start(5000,true); } else { std::cout << "No message box closed" << std::endl; } } void QmitkFunctionalityTesting::ActivateNextFunctionality() { // last one passed std::cout<<"[PASSED]"<<std::endl; #ifdef BUILD_TESTING std::cout << "GUI test for \"" << m_QmitkFctMediator->GetActiveFunctionality()->className() <<"\": "<< std::flush; QmitkFunctionality* activeFunctionality = m_QmitkFctMediator->GetActiveFunctionality(); if (activeFunctionality) { if ( activeFunctionality->TestYourself() ) { std::cout<<"[PASSED]"<<std::endl; } else { std::cout<<"[FAILED]"<<std::endl; ++m_NumberOfFunctionalitiesFailed; m_NamesOfFailedFunctionalities.push_back( activeFunctionality->className() ); } } #endif // activate next functionality int nextId = m_QmitkFctMediator->GetActiveFunctionalityId()+1; QmitkFunctionality * nextFunctionality = m_QmitkFctMediator->GetFunctionalityById(nextId); if(nextFunctionality != NULL) { std::cout << "Activating \"" << nextFunctionality->className() <<"\" "<< std::flush; m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return m_QmitkFctMediator->RaiseFunctionality(nextId); m_CloseMessagesTimer.stop(); m_ActivateTimer.start(2000,true); // after redraw activate next } else { qApp->quit(); } } int StartQmitkFunctionalityTesting(QmitkFctMediator* qfm) { QmitkFunctionalityTesting *testing = new QmitkFunctionalityTesting(qfm); testing->m_NumberOfFunctionalitiesFailed = 0; QTimer::singleShot(2000,testing,SLOT(ActivateNextFunctionality())); // 2 seconds single-shot timer testing->m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return std::cout << "Starting QmitkFunctionalityTesting ... " << std::endl; if (qfm->GetActiveFunctionality()) { std::cout << "Activating \"" << qfm->GetActiveFunctionality()->className() <<"\": "<< std::flush; } else { std::cout << "No active functionality yet ..." << std::endl << std::flush; } qApp->exec(); if (testing->m_NumberOfFunctionalitiesFailed > 0) { std::cout<<"No crashes, but " << testing->m_NumberOfFunctionalitiesFailed << " functionalities failed during testing themselves:" <<std::endl; for ( std::list<std::string>::iterator iter = testing->m_NamesOfFailedFunctionalities.begin(); iter != testing->m_NamesOfFailedFunctionalities.end(); ++iter ) { std::cout << *iter << std::endl; } std::cout<<"Test done [FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"Test done [PASSED]"<<std::endl; return EXIT_SUCCESS; } } <commit_msg>FIX (#1007) Test for QmitkSliceBasedSegmentation fails The "message box closer" timer was not stopped before starting testing of the first functionality. It unintendedly(?) closed an important dialog in the wrong way in one test case.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ 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 <QmitkFunctionalityTesting.h> #include <QmitkFctMediator.h> #include <qapplication.h> #include <qtimer.h> #include <qwidgetlist.h> #include <qobjectlist.h> #include <qmessagebox.h> #include <stdlib.h> #include <iostream> #include <mitkTestingConfig.h> QmitkFunctionalityTesting::QmitkFunctionalityTesting( QmitkFctMediator* qfm, QObject * parent, const char * name ) : QObject(parent, name), m_QmitkFctMediator(qfm) { QObject::connect( &m_ActivateTimer, SIGNAL(timeout()), this, SLOT(ActivateNextFunctionality()) ); QObject::connect( &m_CloseMessagesTimer, SIGNAL(timeout()), this, SLOT(CloseFirstMessageBox()) ); } QmitkFunctionalityTesting::~QmitkFunctionalityTesting() { } void QmitkFunctionalityTesting::CloseFirstMessageBox() { bool boxClosed = false; QWidgetList* topWidgets = QApplication::topLevelWidgets(); QWidgetListIt topWidgetsIt(*topWidgets); QWidget* widget; while ( ( widget = topWidgetsIt.current()) != 0 ) { ++topWidgetsIt; if (widget->isA("QMessageBox")) { std::cout << "Found a toplevel message box! Give it a parent! Closing it ..." << std::endl; ((QMessageBox*)widget)->close(); boxClosed=true; break; } QObjectList *l = widget->queryList( "QMessageBox" ); QObjectListIt it( *l ); QObject *obj; while ( (obj = it.current()) != 0 ) { ++it; std::cout << "Found a message box! Closing it ..." << std::endl; ((QMessageBox*)obj)->close(); boxClosed = true; break; } delete l; // delete the list, not the objects if (boxClosed) { break; } } delete topWidgets; if (boxClosed) { // let everything redraw and call self m_CloseMessagesTimer.start(5000,true); } else { std::cout << "No message box closed" << std::endl; } } void QmitkFunctionalityTesting::ActivateNextFunctionality() { // last one passed std::cout<<"[PASSED]"<<std::endl; #ifdef BUILD_TESTING std::cout << "GUI test for \"" << m_QmitkFctMediator->GetActiveFunctionality()->className() <<"\": "<< std::flush; m_CloseMessagesTimer.stop(); QmitkFunctionality* activeFunctionality = m_QmitkFctMediator->GetActiveFunctionality(); if (activeFunctionality) { if ( activeFunctionality->TestYourself() ) { std::cout<<"[PASSED]"<<std::endl; } else { std::cout<<"[FAILED]"<<std::endl; ++m_NumberOfFunctionalitiesFailed; m_NamesOfFailedFunctionalities.push_back( activeFunctionality->className() ); } } #endif // activate next functionality int nextId = m_QmitkFctMediator->GetActiveFunctionalityId()+1; QmitkFunctionality * nextFunctionality = m_QmitkFctMediator->GetFunctionalityById(nextId); if(nextFunctionality != NULL) { std::cout << "Activating \"" << nextFunctionality->className() <<"\" "<< std::flush; m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return m_QmitkFctMediator->RaiseFunctionality(nextId); m_CloseMessagesTimer.stop(); m_ActivateTimer.start(2000,true); // after redraw activate next } else { qApp->quit(); } } int StartQmitkFunctionalityTesting(QmitkFctMediator* qfm) { QmitkFunctionalityTesting *testing = new QmitkFunctionalityTesting(qfm); testing->m_NumberOfFunctionalitiesFailed = 0; QTimer::singleShot(2000,testing,SLOT(ActivateNextFunctionality())); // 2 seconds single-shot timer testing->m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return std::cout << "Starting QmitkFunctionalityTesting ... " << std::endl; if (qfm->GetActiveFunctionality()) { std::cout << "Activating \"" << qfm->GetActiveFunctionality()->className() <<"\": "<< std::flush; } else { std::cout << "No active functionality yet ..." << std::endl << std::flush; } qApp->exec(); if (testing->m_NumberOfFunctionalitiesFailed > 0) { std::cout<<"No crashes, but " << testing->m_NumberOfFunctionalitiesFailed << " functionalities failed during testing themselves:" <<std::endl; for ( std::list<std::string>::iterator iter = testing->m_NamesOfFailedFunctionalities.begin(); iter != testing->m_NamesOfFailedFunctionalities.end(); ++iter ) { std::cout << *iter << std::endl; } std::cout<<"Test done [FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"Test done [PASSED]"<<std::endl; return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>#include "mwm_url.hpp" #include "render/scales_processor.hpp" #include "indexer/mercator.hpp" #include "indexer/scales.hpp" #include "coding/uri.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "std/algorithm.hpp" #include "std/bind.hpp" namespace url_scheme { namespace { static int const INVALID_LAT_VALUE = -1000; bool IsInvalidApiPoint(ApiPoint const & p) { return p.m_lat == INVALID_LAT_VALUE; } } // unnames namespace ParsedMapApi::ParsedMapApi() : m_controller(NULL) , m_version(0) , m_zoomLevel(0.0) , m_goBackOnBalloonClick(false) { } void ParsedMapApi::SetController(UserMarkContainer::Controller * controller) { m_controller = controller; } bool ParsedMapApi::SetUriAndParse(string const & url) { Reset(); return Parse(url_scheme::Uri(url)); } bool ParsedMapApi::IsValid() const { ASSERT(m_controller != NULL, ()); return m_controller->GetUserMarkCount() > 0; } bool ParsedMapApi::Parse(Uri const & uri) { ASSERT(m_controller != NULL, ()); string const & scheme = uri.GetScheme(); if ((scheme != "mapswithme" && scheme != "mwm") || uri.GetPath() != "map") return false; vector<ApiPoint> points; uri.ForEachKeyValue(bind(&ParsedMapApi::AddKeyValue, this, _1, _2, ref(points))); points.erase(remove_if(points.begin(), points.end(), &IsInvalidApiPoint), points.end()); for (size_t i = 0; i < points.size(); ++i) { ApiPoint const & p = points[i]; m2::PointD glPoint(MercatorBounds::FromLatLon(p.m_lat, p.m_lon)); ApiMarkPoint * mark = static_cast<ApiMarkPoint *>(m_controller->CreateUserMark(glPoint)); mark->SetName(p.m_name); mark->SetID(p.m_id); } return true; } void ParsedMapApi::AddKeyValue(string key, string const & value, vector<ApiPoint> & points) { strings::AsciiToLower(key); if (key == "ll") { points.push_back(ApiPoint()); points.back().m_lat = INVALID_LAT_VALUE; size_t const firstComma = value.find(','); if (firstComma == string::npos) { LOG(LWARNING, ("Map API: no comma between lat and lon for 'll' key", key, value)); return; } if (value.find(',', firstComma + 1) != string::npos) { LOG(LWARNING, ("Map API: more than one comma in a value for 'll' key", key, value)); return; } double lat, lon; if (!strings::to_double(value.substr(0, firstComma), lat) || !strings::to_double(value.substr(firstComma + 1), lon)) { LOG(LWARNING, ("Map API: can't parse lat,lon for 'll' key", key, value)); return; } if (!MercatorBounds::ValidLat(lat) || !MercatorBounds::ValidLon(lon)) { LOG(LWARNING, ("Map API: incorrect value for lat and/or lon", key, value, lat, lon)); return; } points.back().m_lat = lat; points.back().m_lon = lon; } else if (key == "z") { if (!strings::to_double(value, m_zoomLevel)) m_zoomLevel = 0.0; } else if (key == "n") { if (!points.empty()) points.back().m_name = value; else LOG(LWARNING, ("Map API: Point name with no point. 'll' should come first!")); } else if (key == "id") { if (!points.empty()) points.back().m_id = value; else LOG(LWARNING, ("Map API: Point url with no point. 'll' should come first!")); } else if (key == "backurl") { // Fix missing :// in back url, it's important for iOS if (value.find("://") == string::npos) m_globalBackUrl = value + "://"; else m_globalBackUrl = value; } else if (key == "v") { if (!strings::to_int(value, m_version)) m_version = 0; } else if (key == "appname") { m_appTitle = value; } else if (key == "balloonaction") { m_goBackOnBalloonClick = true; } } void ParsedMapApi::Reset() { m_globalBackUrl.clear(); m_appTitle.clear(); m_version = 0; m_zoomLevel = 0.0; m_goBackOnBalloonClick = false; } bool ParsedMapApi::GetViewportRect(ScalesProcessor const & scales, m2::RectD & rect) const { ASSERT(m_controller != NULL, ()); size_t markCount = m_controller->GetUserMarkCount(); if (markCount == 1 && m_zoomLevel >= 1) { double zoom = min(static_cast<double>(scales::GetUpperComfortScale()), m_zoomLevel); rect = scales.GetRectForDrawScale(zoom, m_controller->GetUserMark(0)->GetOrg()); return true; } else { m2::RectD result; for (size_t i = 0; i < m_controller->GetUserMarkCount(); ++i) result.Add(m_controller->GetUserMark(i)->GetOrg()); if (result.IsValid()) { rect = result; return true; } return false; } } UserMark const * ParsedMapApi::GetSinglePoint() const { ASSERT(m_controller != NULL, ()); if (m_controller->GetUserMarkCount() != 1) return 0; return m_controller->GetUserMark(0); } } <commit_msg>Fix warning<commit_after>#include "mwm_url.hpp" #include "render/scales_processor.hpp" #include "indexer/mercator.hpp" #include "indexer/scales.hpp" #include "coding/uri.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "std/algorithm.hpp" #include "std/bind.hpp" namespace url_scheme { namespace { static int const INVALID_LAT_VALUE = -1000; bool IsInvalidApiPoint(ApiPoint const & p) { return p.m_lat == INVALID_LAT_VALUE; } } // unnames namespace ParsedMapApi::ParsedMapApi() : m_controller(NULL) , m_version(0) , m_zoomLevel(0.0) , m_goBackOnBalloonClick(false) { } void ParsedMapApi::SetController(UserMarkContainer::Controller * controller) { m_controller = controller; } bool ParsedMapApi::SetUriAndParse(string const & url) { Reset(); return Parse(url_scheme::Uri(url)); } bool ParsedMapApi::IsValid() const { ASSERT(m_controller != NULL, ()); return m_controller->GetUserMarkCount() > 0; } bool ParsedMapApi::Parse(Uri const & uri) { ASSERT(m_controller != NULL, ()); string const & scheme = uri.GetScheme(); if ((scheme != "mapswithme" && scheme != "mwm") || uri.GetPath() != "map") return false; vector<ApiPoint> points; uri.ForEachKeyValue(bind(&ParsedMapApi::AddKeyValue, this, _1, _2, ref(points))); points.erase(remove_if(points.begin(), points.end(), &IsInvalidApiPoint), points.end()); for (size_t i = 0; i < points.size(); ++i) { ApiPoint const & p = points[i]; m2::PointD glPoint(MercatorBounds::FromLatLon(p.m_lat, p.m_lon)); ApiMarkPoint * mark = static_cast<ApiMarkPoint *>(m_controller->CreateUserMark(glPoint)); mark->SetName(p.m_name); mark->SetID(p.m_id); } return true; } void ParsedMapApi::AddKeyValue(string key, string const & value, vector<ApiPoint> & points) { strings::AsciiToLower(key); if (key == "ll") { points.push_back(ApiPoint()); points.back().m_lat = INVALID_LAT_VALUE; size_t const firstComma = value.find(','); if (firstComma == string::npos) { LOG(LWARNING, ("Map API: no comma between lat and lon for 'll' key", key, value)); return; } if (value.find(',', firstComma + 1) != string::npos) { LOG(LWARNING, ("Map API: more than one comma in a value for 'll' key", key, value)); return; } double lat = 0.0; double lon = 0.0; if (!strings::to_double(value.substr(0, firstComma), lat) || !strings::to_double(value.substr(firstComma + 1), lon)) { LOG(LWARNING, ("Map API: can't parse lat,lon for 'll' key", key, value)); return; } if (!MercatorBounds::ValidLat(lat) || !MercatorBounds::ValidLon(lon)) { LOG(LWARNING, ("Map API: incorrect value for lat and/or lon", key, value, lat, lon)); return; } points.back().m_lat = lat; points.back().m_lon = lon; } else if (key == "z") { if (!strings::to_double(value, m_zoomLevel)) m_zoomLevel = 0.0; } else if (key == "n") { if (!points.empty()) points.back().m_name = value; else LOG(LWARNING, ("Map API: Point name with no point. 'll' should come first!")); } else if (key == "id") { if (!points.empty()) points.back().m_id = value; else LOG(LWARNING, ("Map API: Point url with no point. 'll' should come first!")); } else if (key == "backurl") { // Fix missing :// in back url, it's important for iOS if (value.find("://") == string::npos) m_globalBackUrl = value + "://"; else m_globalBackUrl = value; } else if (key == "v") { if (!strings::to_int(value, m_version)) m_version = 0; } else if (key == "appname") { m_appTitle = value; } else if (key == "balloonaction") { m_goBackOnBalloonClick = true; } } void ParsedMapApi::Reset() { m_globalBackUrl.clear(); m_appTitle.clear(); m_version = 0; m_zoomLevel = 0.0; m_goBackOnBalloonClick = false; } bool ParsedMapApi::GetViewportRect(ScalesProcessor const & scales, m2::RectD & rect) const { ASSERT(m_controller != NULL, ()); size_t markCount = m_controller->GetUserMarkCount(); if (markCount == 1 && m_zoomLevel >= 1) { double zoom = min(static_cast<double>(scales::GetUpperComfortScale()), m_zoomLevel); rect = scales.GetRectForDrawScale(zoom, m_controller->GetUserMark(0)->GetOrg()); return true; } else { m2::RectD result; for (size_t i = 0; i < m_controller->GetUserMarkCount(); ++i) result.Add(m_controller->GetUserMark(i)->GetOrg()); if (result.IsValid()) { rect = result; return true; } return false; } } UserMark const * ParsedMapApi::GetSinglePoint() const { ASSERT(m_controller != NULL, ()); if (m_controller->GetUserMarkCount() != 1) return 0; return m_controller->GetUserMark(0); } } <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_kf_test.cpp * \date Febuary 2015 * \author Jan Issac ([email protected]) */ #include <gtest/gtest.h> #include "../typecast.hpp" #include <Eigen/Dense> #include "gaussian_filter_test_suite.hpp" /** * Customize the GaussianFilterTest fixture by defining the Kalman filter */ template <typename TestType> class KalmanFilterTest : public GaussianFilterTest<TestType> { public: typedef GaussianFilterTest<TestType> Base; typedef typename Base::LinearStateTransition LinearStateTransition; typedef typename Base::LinearObservation LinearObservation; typedef fl::GaussianFilter<LinearStateTransition, LinearObservation> Filter; static Filter create_kalman_filter() { auto filter = Filter( LinearStateTransition(Base::StateDim, Base::InputDim), LinearObservation(Base::ObsrvDim, Base::StateDim)); return filter; } }; typedef ::testing::Types< fl::StaticTest<>, fl::DynamicTest<> > TestTypes; TYPED_TEST_CASE(KalmanFilterTest, TestTypes); TYPED_TEST(KalmanFilterTest, init_predict) { auto filter = TestFixture::create_kalman_filter(); predict(filter); } TYPED_TEST(KalmanFilterTest, predict_then_update) { auto filter = TestFixture::create_kalman_filter(); predict_update(filter); } TYPED_TEST(KalmanFilterTest, predict_and_update) { auto filter = TestFixture::create_kalman_filter(); predict_and_update(filter); } TYPED_TEST(KalmanFilterTest, predict_loop) { auto filter = TestFixture::create_kalman_filter(); predict_loop(filter); } TYPED_TEST(KalmanFilterTest, predict_multiple_function_loop) { auto filter = TestFixture::create_kalman_filter(); predict_multiple_function_loop(filter); } TYPED_TEST(KalmanFilterTest, predict_multiple) { auto filter = TestFixture::create_kalman_filter(); predict_multiple(filter); } TYPED_TEST(KalmanFilterTest, predict_loop_vs_predict_multiple) { auto filter = TestFixture::create_kalman_filter(); predict_loop_vs_predict_multiple(filter); } <commit_msg>Created KalmanFilterTest instance using GaussianFilterTest<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_kf_test.cpp * \date Febuary 2015 * \author Jan Issac ([email protected]) */ #include <gtest/gtest.h> #include "../typecast.hpp" #include <Eigen/Dense> #include "gaussian_filter_test_suite.hpp" #include <fl/filter/gaussian/gaussian_filter_kf.hpp> template <int StateDimension, int InputDimension, int ObsrvDimension> struct KalmanFilterTestConfiguration { enum: signed int { StateDim = StateDimension, InputDim = InputDimension, ObsrvDim = ObsrvDimension }; template <typename StateTransitionModel, typename ObservationModel> struct FilterDefinition { typedef fl::GaussianFilter< StateTransitionModel, ObservationModel > Type; }; template <typename F, typename H> static typename FilterDefinition<F, H>::Type create_filter(F&& f, H&& h) { return typename FilterDefinition<F, H>::Type(f, h); } }; typedef ::testing::Types< fl::StaticTest<KalmanFilterTestConfiguration<3, 1, 2>>, fl::StaticTest<KalmanFilterTestConfiguration<3, 3, 10>>, fl::StaticTest<KalmanFilterTestConfiguration<10, 10, 20>>, fl::DynamicTest<KalmanFilterTestConfiguration<3, 1, 2>>, fl::DynamicTest<KalmanFilterTestConfiguration<3, 3, 10>>, fl::DynamicTest<KalmanFilterTestConfiguration<10, 10, 20>> > TestTypes; INSTANTIATE_TYPED_TEST_CASE_P(KalmanFilterTest, GaussianFilterTest, TestTypes); <|endoftext|>
<commit_before>//====================================================================== //----------------------------------------------------------------------- /** * @file env_var_tests.cpp * @brief 環境変数対応テスト * * @author t.shirayanagi * @par copyright * Copyright (C) 2012-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #if defined(USE_GTEST_PREFIX) || defined(IUTEST_USE_GTEST) # define ENV_PREFIX "GTEST_" #else # define ENV_PREFIX "IUTEST_" #endif int SetUpEnvironment(void) { if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "SHUFFLE=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "RANDOM_SEED=200") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "ALSO_RUN_DISABLED_TESTS=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "BREAK_ON_FAILURE=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "THROW_ON_FAILURE=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "CATCH_EXCEPTIONS=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "PRINT_TIME=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "REPEAT=2") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "FILTER=Flag*") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "OUTPUT=test") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv("IUTEST_DEFAULT_PACKAGE_NAME=env_var") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv("IUTEST_FILE_LOCATION=vs") == -1 ) return -1; return 0; } static volatile int g_setup_environment = SetUpEnvironment(); IUTEST(FlagTest, Check) { IUTEST_ASSUME_EQ(0, g_setup_environment); // putenv に失敗した場合はテストしない IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(also_run_disabled_tests) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(break_on_failure) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(throw_on_failure) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(catch_exceptions) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(print_time) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(shuffle) ); #if !defined(IUTEST_USE_GTEST) IUTEST_EXPECT_STREQ( "env_var", ::iutest::IUTEST_FLAG(default_package_name).c_str() ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(file_location_style_msvc) ); #endif IUTEST_EXPECT_EQ( 200u, ::iutest::IUTEST_FLAG(random_seed) ); IUTEST_EXPECT_EQ( 2 , ::iutest::IUTEST_FLAG(repeat) ); IUTEST_EXPECT_STREQ( "Flag*", ::iutest::IUTEST_FLAG(filter).c_str() ); IUTEST_EXPECT_STREQ( "test", ::iutest::IUTEST_FLAG(output).c_str() ); } #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { (void)argc; (void)argv; #ifdef UNICODE wchat_t a[] = ""; wchar_t* targv[] = { a }; #else char a[] = ""; char* targv[] = { a }; #endif int targc = 1; IUTEST_INIT(&targc, targv); return IUTEST_RUN_ALL_TESTS(); } <commit_msg>append errno message<commit_after>//====================================================================== //----------------------------------------------------------------------- /** * @file env_var_tests.cpp * @brief 環境変数対応テスト * * @author t.shirayanagi * @par copyright * Copyright (C) 2012-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #include <errno.h> #if defined(USE_GTEST_PREFIX) || defined(IUTEST_USE_GTEST) # define ENV_PREFIX "GTEST_" #else # define ENV_PREFIX "IUTEST_" #endif int SetUpEnvironmentImpl(void) { if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "SHUFFLE=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "RANDOM_SEED=200") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "ALSO_RUN_DISABLED_TESTS=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "BREAK_ON_FAILURE=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "THROW_ON_FAILURE=1") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "CATCH_EXCEPTIONS=0") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "PRINT_TIME=0") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "REPEAT=2") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "FILTER=Flag*") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "OUTPUT=test") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv("IUTEST_DEFAULT_PACKAGE_NAME=env_var") == -1 ) return -1; if( ::iutest::internal::posix::PutEnv("IUTEST_FILE_LOCATION=vs") == -1 ) return -1; return 0; } static int lasterror = 0; int SetUpEnvironment(void) { if( SetUpEnvironmentImpl() == 0 ) return 0; lasterror = errno; return -1; } static volatile int g_setup_environment = SetUpEnvironment(); IUTEST(FlagTest, Check) { IUTEST_ASSUME_EQ(0, g_setup_environment) << lasterror << ": " << strerror(lasterror); // putenv に失敗した場合はテストしない IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(also_run_disabled_tests) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(break_on_failure) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(throw_on_failure) ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(shuffle) ); IUTEST_EXPECT_FALSE( ::iutest::IUTEST_FLAG(catch_exceptions) ); IUTEST_EXPECT_FALSE( ::iutest::IUTEST_FLAG(print_time) ); #if !defined(IUTEST_USE_GTEST) IUTEST_EXPECT_STREQ( "env_var", ::iutest::IUTEST_FLAG(default_package_name).c_str() ); IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(file_location_style_msvc) ); #endif IUTEST_EXPECT_EQ( 200u, ::iutest::IUTEST_FLAG(random_seed) ); IUTEST_EXPECT_EQ( 2 , ::iutest::IUTEST_FLAG(repeat) ); IUTEST_EXPECT_STREQ( "Flag*", ::iutest::IUTEST_FLAG(filter).c_str() ); IUTEST_EXPECT_STREQ( "test", ::iutest::IUTEST_FLAG(output).c_str() ); } #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { (void)argc; (void)argv; #ifdef UNICODE wchat_t a[] = ""; wchar_t* targv[] = { a }; #else char a[] = ""; char* targv[] = { a }; #endif int targc = 1; IUTEST_INIT(&targc, targv); return IUTEST_RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright 2016, Dawid Kurek, [email protected] #include <type_traits> #include "../src/executor.hpp" #include "gtest/gtest.h" class executor_test : public ::testing::Test { protected: void SetUp() override { memset(memory.Raw, 0, sizeof (memory.Raw)); for (int i = 0; i < 16; ++i) { memory.V[i] = i; } } void execute(Word const word) { do_execute(Opcode{word}, memory); } Executor do_execute; Memory memory; }; TEST_F(executor_test, 0_CLS_clear_the_display) { memory.Display[0] = 0x12; execute(0x00E0); ASSERT_EQ(0x00, memory.Display[0]); } TEST_F(executor_test, 0_RET_return_from_subroutine) { memory.SP = 1; memory.Stack[1] = 0x54; execute(0x00EE); ASSERT_EQ(0, memory.SP); ASSERT_EQ(0x54, memory.PC); } TEST_F(executor_test, 1_JP_kump_to_location_nnn) { memory.PC = 0x01; execute(0x1234); ASSERT_EQ(0x0234, memory.PC); } TEST_F(executor_test, 2_CALL_call_subroutine_at_nnn) { memory.PC = 0x5678; execute(0x2345); ASSERT_EQ(1, memory.SP); ASSERT_EQ(0x5678, memory.Stack[memory.SP]); ASSERT_EQ(0x0345, memory.PC); } TEST_F(executor_test, 3_SE_skip_next_instruction_if_Vx_eq_kk_true) { memory.PC = 1; execute(0x3404); ASSERT_EQ(3, memory.PC); } TEST_F(executor_test, 3_SE_skip_next_instruction_if_Vx_eq_kk_false) { memory.PC = 1; execute(0x3456); ASSERT_EQ(1, memory.PC); } TEST_F(executor_test, 4_SNE_skip_next_instruction_if_Vx_neq_kk_true) { memory.PC = 1; execute(0x4456); ASSERT_EQ(3, memory.PC); } TEST_F(executor_test, 4_SNE_skip_next_instruction_if_Vx_neq_kk_false) { memory.PC = 1; execute(0x4505); ASSERT_EQ(1, memory.PC); } TEST_F(executor_test, 5_SE_skip_next_instruction_if_Vx_eq_Vy_true) { memory.PC = 1; memory.V[4] = 0x5; execute(0x5450); ASSERT_EQ(3, memory.PC); } TEST_F(executor_test, 5_SE_skip_next_instruction_if_Vx_eq_Vy_false) { memory.PC = 1; execute(0x5450); ASSERT_EQ(1, memory.PC); } TEST_F(executor_test, 6_LD_set_Vx_to_kk) { execute(0x6323); ASSERT_EQ(0x23, memory.V[3]); } TEST_F(executor_test, 7_ADD_set_Vx_to_Vx_plus_kk) { execute(0x7723); ASSERT_EQ(0x2A, memory.V[7]); } TEST_F(executor_test, 8_LD_set_Vx_to_Vy) { execute(0x8670); ASSERT_EQ(0x7, memory.V[6]); } TEST_F(executor_test, 8_OR_set_Vx_to_Vx_or_Vy) { execute(0x8141); ASSERT_EQ(0x5, memory.V[1]); } TEST_F(executor_test, 8_AND_set_Vx_to_Vx_and_Vy) { execute(0x8542); ASSERT_EQ(0x4, memory.V[5]); } TEST_F(executor_test, 8_XOR_set_Vx_to_Vx_xor_Vy) { execute(0x8543); ASSERT_EQ(0x1, memory.V[5]); } TEST_F(executor_test, 8_ADD_set_Vx_to_Vx_plus_Vy_set_VF_to_carry_0) { execute(0x8AB4); ASSERT_EQ(0x15, memory.V[0xA]); ASSERT_EQ(0x0, memory.VF); } TEST_F(executor_test, 8_ADD_set_Vx_to_Vx_plus_Vy_set_VF_to_carry_1) { memory.V[0xA] = 0xFF; execute(0x8AB4); ASSERT_EQ(0xA, memory.V[0xA]); ASSERT_EQ(0x1, memory.VF); } TEST_F(executor_test, 8_SUB_set_Vx_to_Vx_minux_Vy_set_VF_to_carry_1) { execute(0x8545); ASSERT_EQ(0x1, memory.V[5]); ASSERT_EQ(0x1, memory.VF); } TEST_F(executor_test, 8_SUB_set_Vx_to_Vx_minux_Vy_set_VF_to_carry_0) { execute(0x8455); ASSERT_EQ(0xFF, memory.V[4]); ASSERT_EQ(0x0, memory.VF); } TEST_F(executor_test, 8_SHR_set_Vx_to_Vx_SHR_1_and_VF_0) { execute(0x8456); ASSERT_EQ(2, memory.V[4]); ASSERT_EQ(0, memory.VF); } TEST_F(executor_test, 8_SHR_set_Vx_to_Vx_SHR_1_and_VF_1) { execute(0x8356); ASSERT_EQ(1, memory.V[3]); ASSERT_EQ(1, memory.VF); } TEST_F(executor_test, 8_SUBN_set_Vx_to_Vy_minus_Vx_set_VF_Not_bottow_0) { execute(0x8547); ASSERT_EQ(0x1, memory.V[5]); ASSERT_EQ(0, memory.VF); } TEST_F(executor_test, 8_SUBN_set_Vx_to_Vy_minus_Vx_set_VF_Not_bottow_1) { execute(0x8457); ASSERT_EQ(0xFF, memory.V[4]); ASSERT_EQ(1, memory.VF); } TEST_F(executor_test, 8_SHL_set_Vx_to_Vx_SHL_1_0) { execute(0x887E); ASSERT_EQ(0x10, memory.V[8]); ASSERT_EQ(0, memory.VF); } TEST_F(executor_test, 8_SHL_set_Vx_to_Vx_SHL_1_1) { memory.V[8] = 0xF0; execute(0x887E); ASSERT_EQ(0xE0, memory.V[8]); ASSERT_EQ(1, memory.VF); } TEST_F(executor_test, 9_SNE_skip_next_instruction_if_Vx_neq_Vy_true) { execute(0x9450); ASSERT_EQ(0x2, memory.PC); } TEST_F(executor_test, 9_SNE_skip_next_instruction_if_Vx_neq_Vy_false) { execute(0x9440); ASSERT_EQ(0x0, memory.PC); } TEST_F(executor_test, A_LD_set_I_to_nnn) { execute(0xA123); ASSERT_EQ(0x123, memory.I); } TEST_F(executor_test, B_JP_jump_to_location_nnn_plus_V0) { memory.V[0] = 5; execute(0xB123); ASSERT_EQ(0x128, memory.PC); } TEST_F(executor_test, C_RND_set_Vx_to_random_byte_AND_kk) { execute(0xC500); ASSERT_EQ(0x0, memory.V[5]); } TEST_F(executor_test, D_DRW_display_n_byte_sprite_TODO) { EXPECT_TRUE(false); } TEST_F(executor_test, E_SKP_skip_next_instruction_if_key_with_value_f_Vx_is_pressed_false) { execute(0xE59E); EXPECT_EQ(0, memory.PC); } TEST_F(executor_test, E_SKP_skip_next_instruction_if_key_with_value_f_Vx_is_pressed_true) { memory.Keypad[5] = 1; execute(0xE59E); EXPECT_EQ(2, memory.PC); } TEST_F(executor_test, E_SKNP_skip_next_instruction_if_key_with_value_f_Vx_is_not_pressed_false) { memory.Keypad[5] = 1; execute(0xE5A1); EXPECT_EQ(0, memory.PC); } TEST_F(executor_test, E_SKNP_skip_next_instruction_if_key_with_value_f_Vx_is_not_pressed_true) { execute(0xE5A1); EXPECT_EQ(2, memory.PC); } TEST_F(executor_test, F_LD_set_Vx_to_delay_timer_value) { memory.DT = 0xA; execute(0xFE07); EXPECT_EQ(0xA, memory.V[0xE]); } TEST_F(executor_test, F_LD_wait_for_a_key_press_store_the_value_of_the_key_in_Vx) { EXPECT_TRUE(false); } TEST_F(executor_test, F_LD_set_delay_timer_to_Vx) { memory.V[7] = 0xB; execute(0xF715); EXPECT_EQ(0xB, memory.DT); } TEST_F(executor_test, F_LD_set_sound_timer_to_Vx) { memory.V[7] = 0xB; execute(0xF718); EXPECT_EQ(0xB, memory.ST); } TEST_F(executor_test, F_ADD_set_I_to_I_add_Vx) { memory.I = 2; memory.V[3] = 5; execute(0xF31E); EXPECT_EQ(7, memory.I); } <commit_msg>Add more tests<commit_after>// Copyright 2016, Dawid Kurek, [email protected] #include <type_traits> #include "../src/executor.hpp" #include "gtest/gtest.h" class executor_test : public ::testing::Test { protected: void SetUp() override { memset(memory.Raw, 0, sizeof (memory.Raw)); for (int i = 0; i < 16; ++i) { memory.V[i] = i; } } void execute(Word const word) { do_execute(Opcode{word}, memory); } Executor do_execute; Memory memory; }; TEST_F(executor_test, 0_CLS_clear_the_display) { memory.Display[0] = 0x12; execute(0x00E0); ASSERT_EQ(0x00, memory.Display[0]); } TEST_F(executor_test, 0_RET_return_from_subroutine) { memory.SP = 1; memory.Stack[1] = 0x54; execute(0x00EE); ASSERT_EQ(0, memory.SP); ASSERT_EQ(0x54, memory.PC); } TEST_F(executor_test, 1_JP_kump_to_location_nnn) { memory.PC = 0x01; execute(0x1234); ASSERT_EQ(0x0234, memory.PC); } TEST_F(executor_test, 2_CALL_call_subroutine_at_nnn) { memory.PC = 0x5678; execute(0x2345); ASSERT_EQ(1, memory.SP); ASSERT_EQ(0x5678, memory.Stack[memory.SP]); ASSERT_EQ(0x0345, memory.PC); } TEST_F(executor_test, 3_SE_skip_next_instruction_if_Vx_eq_kk_true) { memory.PC = 1; execute(0x3404); ASSERT_EQ(3, memory.PC); } TEST_F(executor_test, 3_SE_skip_next_instruction_if_Vx_eq_kk_false) { memory.PC = 1; execute(0x3456); ASSERT_EQ(1, memory.PC); } TEST_F(executor_test, 4_SNE_skip_next_instruction_if_Vx_neq_kk_true) { memory.PC = 1; execute(0x4456); ASSERT_EQ(3, memory.PC); } TEST_F(executor_test, 4_SNE_skip_next_instruction_if_Vx_neq_kk_false) { memory.PC = 1; execute(0x4505); ASSERT_EQ(1, memory.PC); } TEST_F(executor_test, 5_SE_skip_next_instruction_if_Vx_eq_Vy_true) { memory.PC = 1; memory.V[4] = 0x5; execute(0x5450); ASSERT_EQ(3, memory.PC); } TEST_F(executor_test, 5_SE_skip_next_instruction_if_Vx_eq_Vy_false) { memory.PC = 1; execute(0x5450); ASSERT_EQ(1, memory.PC); } TEST_F(executor_test, 6_LD_set_Vx_to_kk) { execute(0x6323); ASSERT_EQ(0x23, memory.V[3]); } TEST_F(executor_test, 7_ADD_set_Vx_to_Vx_plus_kk) { execute(0x7723); ASSERT_EQ(0x2A, memory.V[7]); } TEST_F(executor_test, 8_LD_set_Vx_to_Vy) { execute(0x8670); ASSERT_EQ(0x7, memory.V[6]); } TEST_F(executor_test, 8_OR_set_Vx_to_Vx_or_Vy) { execute(0x8141); ASSERT_EQ(0x5, memory.V[1]); } TEST_F(executor_test, 8_AND_set_Vx_to_Vx_and_Vy) { execute(0x8542); ASSERT_EQ(0x4, memory.V[5]); } TEST_F(executor_test, 8_XOR_set_Vx_to_Vx_xor_Vy) { execute(0x8543); ASSERT_EQ(0x1, memory.V[5]); } TEST_F(executor_test, 8_ADD_set_Vx_to_Vx_plus_Vy_set_VF_to_carry_0) { execute(0x8AB4); ASSERT_EQ(0x15, memory.V[0xA]); ASSERT_EQ(0x0, memory.VF); } TEST_F(executor_test, 8_ADD_set_Vx_to_Vx_plus_Vy_set_VF_to_carry_1) { memory.V[0xA] = 0xFF; execute(0x8AB4); ASSERT_EQ(0xA, memory.V[0xA]); ASSERT_EQ(0x1, memory.VF); } TEST_F(executor_test, 8_SUB_set_Vx_to_Vx_minux_Vy_set_VF_to_carry_1) { execute(0x8545); ASSERT_EQ(0x1, memory.V[5]); ASSERT_EQ(0x1, memory.VF); } TEST_F(executor_test, 8_SUB_set_Vx_to_Vx_minux_Vy_set_VF_to_carry_0) { execute(0x8455); ASSERT_EQ(0xFF, memory.V[4]); ASSERT_EQ(0x0, memory.VF); } TEST_F(executor_test, 8_SHR_set_Vx_to_Vx_SHR_1_and_VF_0) { execute(0x8456); ASSERT_EQ(2, memory.V[4]); ASSERT_EQ(0, memory.VF); } TEST_F(executor_test, 8_SHR_set_Vx_to_Vx_SHR_1_and_VF_1) { execute(0x8356); ASSERT_EQ(1, memory.V[3]); ASSERT_EQ(1, memory.VF); } TEST_F(executor_test, 8_SUBN_set_Vx_to_Vy_minus_Vx_set_VF_Not_bottow_0) { execute(0x8547); ASSERT_EQ(0x1, memory.V[5]); ASSERT_EQ(0, memory.VF); } TEST_F(executor_test, 8_SUBN_set_Vx_to_Vy_minus_Vx_set_VF_Not_bottow_1) { execute(0x8457); ASSERT_EQ(0xFF, memory.V[4]); ASSERT_EQ(1, memory.VF); } TEST_F(executor_test, 8_SHL_set_Vx_to_Vx_SHL_1_0) { execute(0x887E); ASSERT_EQ(0x10, memory.V[8]); ASSERT_EQ(0, memory.VF); } TEST_F(executor_test, 8_SHL_set_Vx_to_Vx_SHL_1_1) { memory.V[8] = 0xF0; execute(0x887E); ASSERT_EQ(0xE0, memory.V[8]); ASSERT_EQ(1, memory.VF); } TEST_F(executor_test, 9_SNE_skip_next_instruction_if_Vx_neq_Vy_true) { execute(0x9450); ASSERT_EQ(0x2, memory.PC); } TEST_F(executor_test, 9_SNE_skip_next_instruction_if_Vx_neq_Vy_false) { execute(0x9440); ASSERT_EQ(0x0, memory.PC); } TEST_F(executor_test, A_LD_set_I_to_nnn) { execute(0xA123); ASSERT_EQ(0x123, memory.I); } TEST_F(executor_test, B_JP_jump_to_location_nnn_plus_V0) { memory.V[0] = 5; execute(0xB123); ASSERT_EQ(0x128, memory.PC); } TEST_F(executor_test, C_RND_set_Vx_to_random_byte_AND_kk) { execute(0xC500); ASSERT_EQ(0x0, memory.V[5]); } TEST_F(executor_test, D_DRW_display_n_byte_sprite_TODO) { execute(0xD58A); EXPECT_TRUE(false); } TEST_F(executor_test, E_SKP_skip_next_instruction_if_key_with_value_f_Vx_is_pressed_false) { execute(0xE59E); EXPECT_EQ(0, memory.PC); } TEST_F(executor_test, E_SKP_skip_next_instruction_if_key_with_value_f_Vx_is_pressed_true) { memory.Keypad[5] = 1; execute(0xE59E); EXPECT_EQ(2, memory.PC); } TEST_F(executor_test, E_SKNP_skip_next_instruction_if_key_with_value_f_Vx_is_not_pressed_false) { memory.Keypad[5] = 1; execute(0xE5A1); EXPECT_EQ(0, memory.PC); } TEST_F(executor_test, E_SKNP_skip_next_instruction_if_key_with_value_f_Vx_is_not_pressed_true) { execute(0xE5A1); EXPECT_EQ(2, memory.PC); } TEST_F(executor_test, F_LD_set_Vx_to_delay_timer_value) { memory.DT = 0xA; execute(0xFE07); EXPECT_EQ(0xA, memory.V[0xE]); } TEST_F(executor_test, F_LD_wait_for_a_key_press_store_the_value_of_the_key_in_Vx) { execute(0xF20A); EXPECT_TRUE(false); } TEST_F(executor_test, F_LD_set_delay_timer_to_Vx) { memory.V[7] = 0xB; execute(0xF715); EXPECT_EQ(0xB, memory.DT); } TEST_F(executor_test, F_LD_set_sound_timer_to_Vx) { memory.V[7] = 0xB; execute(0xF718); EXPECT_EQ(0xB, memory.ST); } TEST_F(executor_test, F_ADD_set_I_to_I_add_Vx) { memory.I = 2; memory.V[3] = 5; execute(0xF31E); EXPECT_EQ(7, memory.I); } TEST_F(executor_test, F_LD_set_I_to_location_of_sprite_for_digit_Vx) { execute(0xFB29); EXPECT_TRUE(false); } TEST_F(executor_test, F_LD_store_BCD_representation_of_Vx_in_memory_location_I) { execute(0xF933); EXPECT_TRUE(false); } TEST_F(executor_test, F_LD_store_registers_V0_through_Vx_in_memory_starting_at_location_I) { execute(0xFB55); EXPECT_TRUE(false); } TEST_F(executor_test, F_LD_read_registers_Vo_throu_Vx_from_memory_starting_at_location_I) { execute(0xFE65); EXPECT_TRUE(false); } <|endoftext|>
<commit_before>/* * Copyright 2019 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 "cluster.h" #include "bucket.h" #include "node.h" #include <platform/dirutils.h> #include <protocol/connection/client_mcbp_commands.h> #include <iostream> #include <vector> namespace cb { namespace test { Cluster::~Cluster() = default; class ClusterImpl : public Cluster { public: ClusterImpl() = delete; ClusterImpl(const ClusterImpl&) = delete; ClusterImpl(std::vector<std::unique_ptr<Node>>& nodes, std::string dir) : nodes(std::move(nodes)), directory(std::move(dir)) { } ~ClusterImpl() override; std::shared_ptr<Bucket> createBucket( const std::string& name, const nlohmann::json& attributes, DcpPacketFilter packet_filter) override; void deleteBucket(const std::string& name) override; std::shared_ptr<Bucket> getBucket(const std::string& name) const override { for (auto& bucket : buckets) { if (bucket->getName() == name) { return bucket; } } return std::shared_ptr<Bucket>(); } std::unique_ptr<MemcachedConnection> getConnection( size_t node) const override { if (node < nodes.size()) { return nodes[node]->getConnection(); } throw std::invalid_argument( "ClusterImpl::getConnection: Invalid node number"); } size_t size() const override; protected: std::vector<std::unique_ptr<Node>> nodes; std::vector<std::shared_ptr<Bucket>> buckets; const std::string directory; }; std::shared_ptr<Bucket> ClusterImpl::createBucket( const std::string& name, const nlohmann::json& attributes, DcpPacketFilter packet_filter) { size_t vbuckets = 1024; size_t replicas = std::min<size_t>(nodes.size() - 1, 3); nlohmann::json json = {{"max_size", 67108864}, {"backend", "couchdb"}, {"couch_bucket", name}, {"max_vbuckets", vbuckets}, {"data_traffic_enabled", false}, {"max_num_workers", 3}, {"conflict_resolution_type", "seqno"}, {"bucket_type", "persistent"}, {"item_eviction_policy", "value_only"}, {"max_ttl", 0}, {"ht_locks", 47}, {"compression_mode", "off"}, {"failpartialwarmup", false}}; json.update(attributes); auto iter = json.find("max_vbuckets"); if (iter != json.end()) { vbuckets = iter->get<size_t>(); } iter = json.find("replicas"); if (iter != json.end()) { replicas = iter->get<size_t>(); // The underlying bucket don't know about replicas json.erase(iter); if (replicas > nodes.size() - 1) { throw std::invalid_argument( "ClusterImpl::createBucket: Not enough nodes in the " "cluster for " + std::to_string(replicas) + " replicas"); } } auto bucket = std::make_shared<Bucket>( *this, name, vbuckets, replicas, packet_filter); const auto& vbucketmap = bucket->getVbucketMap(); json["uuid"] = bucket->getUuid(); try { // @todo I need at least the number of nodes to set active + n replicas for (std::size_t node_idx = 0; node_idx < nodes.size(); ++node_idx) { auto connection = nodes[node_idx]->getConnection(); connection->connect(); connection->authenticate("@admin", "password", "plain"); connection->setFeatures("cluster_testapp", {{cb::mcbp::Feature::MUTATION_SEQNO, cb::mcbp::Feature::XATTR, cb::mcbp::Feature::XERROR, cb::mcbp::Feature::SELECT_BUCKET, cb::mcbp::Feature::JSON, cb::mcbp::Feature::SNAPPY}}); std::string fname = nodes[node_idx]->directory + "/" + name; cb::io::sanitizePath(fname); json["dbname"] = fname; fname = json["dbname"].get<std::string>() + "/access.log"; cb::io::sanitizePath(fname); json["alog_path"] = fname; std::string config; for (auto it = json.begin(); it != json.end(); ++it) { if (it.value().is_string()) { config += it.key() + "=" + it.value().get<std::string>() + ";"; } else { config += it.key() + "=" + it.value().dump() + ";"; } } connection->createBucket(name, config, BucketType::Couchbase); connection->selectBucket(name); // iterate over all of the vbuckets and find that node number and // define the vbuckets for (std::size_t vbucket = 0; vbucket < vbucketmap.size(); ++vbucket) { std::vector<std::string> chain; for (int ii : vbucketmap[vbucket]) { chain.emplace_back("n_" + std::to_string(ii)); } nlohmann::json topology = { {"topology", nlohmann::json::array({chain})}}; for (std::size_t ii = 0; ii < vbucketmap[vbucket].size(); ++ii) { if (vbucketmap[vbucket][ii] == int(node_idx)) { // This is me if (ii == 0) { connection->setVbucket(Vbid{uint16_t(vbucket)}, vbucket_state_active, topology); } else { connection->setVbucket(Vbid{uint16_t(vbucket)}, vbucket_state_replica, {}); } } } } // Call enable traffic const auto rsp = connection->execute(BinprotGenericCommand{ cb::mcbp::ClientOpcode::EnableTraffic}); if (!rsp.isSuccess()) { throw ConnectionError("Failed to enable traffic", rsp.getStatus()); } } bucket->setupReplication(); buckets.push_back(bucket); return bucket; } catch (const ConnectionError& e) { std::cerr << "ERROR: " << e.what() << std::endl; for (auto& b : nodes) { auto connection = b->getConnection(); connection->connect(); connection->authenticate("@admin", "password", "plain"); try { connection->deleteBucket(name); } catch (const std::exception&) { } } } return {}; } void ClusterImpl::deleteBucket(const std::string& name) { for (auto iter = buckets.begin(); iter != buckets.end(); ++iter) { if ((*iter)->getName() == name) { // The DCP replicators throws an exception if they get a // read error (in the case of others holding a reference // to the bucket class)... (*iter)->shutdownReplication(); buckets.erase(iter); break; } } // I should wait for the bucket being closed on all nodes.. for (auto& n : nodes) { auto connection = n->getConnection(); connection->connect(); connection->authenticate("@admin", "password", "plain"); connection->deleteBucket(name); } } size_t ClusterImpl::size() const { return nodes.size(); } ClusterImpl::~ClusterImpl() { buckets.clear(); bool cleanup = true; for (auto& n : nodes) { std::string minidump_dir = n->directory + "/crash"; cb::io::sanitizePath(minidump_dir); if (cb::io::isDirectory(minidump_dir)) { auto files = cb::io::findFilesWithPrefix(minidump_dir, ""); cleanup &= files.empty(); } } nodes.clear(); // @todo I should make this configurable? if (cleanup && cb::io::isDirectory(directory)) { cb::io::rmrf(directory); } } std::unique_ptr<Cluster> Cluster::create(size_t num_nodes) { auto pattern = cb::io::getcwd() + "/cluster_"; cb::io::sanitizePath(pattern); auto clusterdir = cb::io::mkdtemp(pattern); std::vector<std::unique_ptr<Node>> nodes; for (size_t n = 0; n < num_nodes; ++n) { const std::string id = "n_" + std::to_string(n); std::string nodedir = clusterdir + "/" + id; cb::io::sanitizePath(nodedir); cb::io::mkdirp(nodedir); nodes.emplace_back(Node::create(nodedir, id)); } return std::make_unique<ClusterImpl>(nodes, clusterdir); } } // namespace test } // namespace cb <commit_msg>Use '/' as directory separator for Create Bucket<commit_after>/* * Copyright 2019 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 "cluster.h" #include "bucket.h" #include "node.h" #include <platform/dirutils.h> #include <protocol/connection/client_mcbp_commands.h> #include <iostream> #include <vector> namespace cb { namespace test { Cluster::~Cluster() = default; class ClusterImpl : public Cluster { public: ClusterImpl() = delete; ClusterImpl(const ClusterImpl&) = delete; ClusterImpl(std::vector<std::unique_ptr<Node>>& nodes, std::string dir) : nodes(std::move(nodes)), directory(std::move(dir)) { } ~ClusterImpl() override; std::shared_ptr<Bucket> createBucket( const std::string& name, const nlohmann::json& attributes, DcpPacketFilter packet_filter) override; void deleteBucket(const std::string& name) override; std::shared_ptr<Bucket> getBucket(const std::string& name) const override { for (auto& bucket : buckets) { if (bucket->getName() == name) { return bucket; } } return std::shared_ptr<Bucket>(); } std::unique_ptr<MemcachedConnection> getConnection( size_t node) const override { if (node < nodes.size()) { return nodes[node]->getConnection(); } throw std::invalid_argument( "ClusterImpl::getConnection: Invalid node number"); } size_t size() const override; protected: std::vector<std::unique_ptr<Node>> nodes; std::vector<std::shared_ptr<Bucket>> buckets; const std::string directory; }; std::shared_ptr<Bucket> ClusterImpl::createBucket( const std::string& name, const nlohmann::json& attributes, DcpPacketFilter packet_filter) { size_t vbuckets = 1024; size_t replicas = std::min<size_t>(nodes.size() - 1, 3); nlohmann::json json = {{"max_size", 67108864}, {"backend", "couchdb"}, {"couch_bucket", name}, {"max_vbuckets", vbuckets}, {"data_traffic_enabled", false}, {"max_num_workers", 3}, {"conflict_resolution_type", "seqno"}, {"bucket_type", "persistent"}, {"item_eviction_policy", "value_only"}, {"max_ttl", 0}, {"ht_locks", 47}, {"compression_mode", "off"}, {"failpartialwarmup", false}}; json.update(attributes); auto iter = json.find("max_vbuckets"); if (iter != json.end()) { vbuckets = iter->get<size_t>(); } iter = json.find("replicas"); if (iter != json.end()) { replicas = iter->get<size_t>(); // The underlying bucket don't know about replicas json.erase(iter); if (replicas > nodes.size() - 1) { throw std::invalid_argument( "ClusterImpl::createBucket: Not enough nodes in the " "cluster for " + std::to_string(replicas) + " replicas"); } } auto bucket = std::make_shared<Bucket>( *this, name, vbuckets, replicas, packet_filter); const auto& vbucketmap = bucket->getVbucketMap(); json["uuid"] = bucket->getUuid(); try { // @todo I need at least the number of nodes to set active + n replicas for (std::size_t node_idx = 0; node_idx < nodes.size(); ++node_idx) { auto connection = nodes[node_idx]->getConnection(); connection->connect(); connection->authenticate("@admin", "password", "plain"); connection->setFeatures("cluster_testapp", {{cb::mcbp::Feature::MUTATION_SEQNO, cb::mcbp::Feature::XATTR, cb::mcbp::Feature::XERROR, cb::mcbp::Feature::SELECT_BUCKET, cb::mcbp::Feature::JSON, cb::mcbp::Feature::SNAPPY}}); std::string fname = nodes[node_idx]->directory + "/" + name; std::replace(fname.begin(), fname.end(), '\\', '/'); json["dbname"] = fname; fname = json["dbname"].get<std::string>() + "/access.log"; std::replace(fname.begin(), fname.end(), '\\', '/'); json["alog_path"] = fname; std::string config; for (auto it = json.begin(); it != json.end(); ++it) { if (it.value().is_string()) { config += it.key() + "=" + it.value().get<std::string>() + ";"; } else { config += it.key() + "=" + it.value().dump() + ";"; } } connection->createBucket(name, config, BucketType::Couchbase); connection->selectBucket(name); // iterate over all of the vbuckets and find that node number and // define the vbuckets for (std::size_t vbucket = 0; vbucket < vbucketmap.size(); ++vbucket) { std::vector<std::string> chain; for (int ii : vbucketmap[vbucket]) { chain.emplace_back("n_" + std::to_string(ii)); } nlohmann::json topology = { {"topology", nlohmann::json::array({chain})}}; for (std::size_t ii = 0; ii < vbucketmap[vbucket].size(); ++ii) { if (vbucketmap[vbucket][ii] == int(node_idx)) { // This is me if (ii == 0) { connection->setVbucket(Vbid{uint16_t(vbucket)}, vbucket_state_active, topology); } else { connection->setVbucket(Vbid{uint16_t(vbucket)}, vbucket_state_replica, {}); } } } } // Call enable traffic const auto rsp = connection->execute(BinprotGenericCommand{ cb::mcbp::ClientOpcode::EnableTraffic}); if (!rsp.isSuccess()) { throw ConnectionError("Failed to enable traffic", rsp.getStatus()); } } bucket->setupReplication(); buckets.push_back(bucket); return bucket; } catch (const ConnectionError& e) { std::cerr << "ERROR: " << e.what() << std::endl; for (auto& b : nodes) { auto connection = b->getConnection(); connection->connect(); connection->authenticate("@admin", "password", "plain"); try { connection->deleteBucket(name); } catch (const std::exception&) { } } } return {}; } void ClusterImpl::deleteBucket(const std::string& name) { for (auto iter = buckets.begin(); iter != buckets.end(); ++iter) { if ((*iter)->getName() == name) { // The DCP replicators throws an exception if they get a // read error (in the case of others holding a reference // to the bucket class)... (*iter)->shutdownReplication(); buckets.erase(iter); break; } } // I should wait for the bucket being closed on all nodes.. for (auto& n : nodes) { auto connection = n->getConnection(); connection->connect(); connection->authenticate("@admin", "password", "plain"); connection->deleteBucket(name); } } size_t ClusterImpl::size() const { return nodes.size(); } ClusterImpl::~ClusterImpl() { buckets.clear(); bool cleanup = true; for (auto& n : nodes) { std::string minidump_dir = n->directory + "/crash"; cb::io::sanitizePath(minidump_dir); if (cb::io::isDirectory(minidump_dir)) { auto files = cb::io::findFilesWithPrefix(minidump_dir, ""); cleanup &= files.empty(); } } nodes.clear(); // @todo I should make this configurable? if (cleanup && cb::io::isDirectory(directory)) { cb::io::rmrf(directory); } } std::unique_ptr<Cluster> Cluster::create(size_t num_nodes) { auto pattern = cb::io::getcwd() + "/cluster_"; cb::io::sanitizePath(pattern); auto clusterdir = cb::io::mkdtemp(pattern); std::vector<std::unique_ptr<Node>> nodes; for (size_t n = 0; n < num_nodes; ++n) { const std::string id = "n_" + std::to_string(n); std::string nodedir = clusterdir + "/" + id; cb::io::sanitizePath(nodedir); cb::io::mkdirp(nodedir); nodes.emplace_back(Node::create(nodedir, id)); } return std::make_unique<ClusterImpl>(nodes, clusterdir); } } // namespace test } // namespace cb <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_capture/video_capture_impl.h" #include <stdlib.h> #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/modules/video_capture/video_capture_config.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/ref_count.h" #include "webrtc/system_wrappers/interface/tick_util.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { namespace videocapturemodule { VideoCaptureModule* VideoCaptureImpl::Create( const int32_t id, VideoCaptureExternal*& externalCapture) { RefCountImpl<VideoCaptureImpl>* implementation = new RefCountImpl<VideoCaptureImpl>(id); externalCapture = implementation; return implementation; } const char* VideoCaptureImpl::CurrentDeviceName() const { return _deviceUniqueId; } // static int32_t VideoCaptureImpl::RotationFromDegrees(int degrees, VideoCaptureRotation* rotation) { switch (degrees) { case 0: *rotation = kCameraRotate0; return 0; case 90: *rotation = kCameraRotate90; return 0; case 180: *rotation = kCameraRotate180; return 0; case 270: *rotation = kCameraRotate270; return 0; default: return -1;; } } // static int32_t VideoCaptureImpl::RotationInDegrees(VideoCaptureRotation rotation, int* degrees) { switch (rotation) { case kCameraRotate0: *degrees = 0; return 0; case kCameraRotate90: *degrees = 90; return 0; case kCameraRotate180: *degrees = 180; return 0; case kCameraRotate270: *degrees = 270; return 0; } return -1; } int32_t VideoCaptureImpl::ChangeUniqueId(const int32_t id) { _id = id; return 0; } // returns the number of milliseconds until the module want a worker thread to call Process int32_t VideoCaptureImpl::TimeUntilNextProcess() { CriticalSectionScoped cs(&_callBackCs); int32_t timeToNormalProcess = kProcessInterval - (int32_t)((TickTime::Now() - _lastProcessTime).Milliseconds()); return timeToNormalProcess; } // Process any pending tasks such as timeouts int32_t VideoCaptureImpl::Process() { CriticalSectionScoped cs(&_callBackCs); const TickTime now = TickTime::Now(); _lastProcessTime = TickTime::Now(); // Handle No picture alarm if (_lastProcessFrameCount.Ticks() == _incomingFrameTimes[0].Ticks() && _captureAlarm != Raised) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Raised; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } else if (_lastProcessFrameCount.Ticks() != _incomingFrameTimes[0].Ticks() && _captureAlarm != Cleared) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Cleared; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } // Handle frame rate callback if ((now - _lastFrameRateCallbackTime).Milliseconds() > kFrameRateCallbackInterval) { if (_frameRateCallBack && _captureCallBack) { const uint32_t frameRate = CalculateFrameRate(now); _captureCallBack->OnCaptureFrameRate(_id, frameRate); } _lastFrameRateCallbackTime = now; // Can be set by EnableFrameRateCallback } _lastProcessFrameCount = _incomingFrameTimes[0]; return 0; } VideoCaptureImpl::VideoCaptureImpl(const int32_t id) : _id(id), _deviceUniqueId(NULL), _apiCs(*CriticalSectionWrapper::CreateCriticalSection()), _captureDelay(0), _requestedCapability(), _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()), _lastProcessTime(TickTime::Now()), _lastFrameRateCallbackTime(TickTime::Now()), _frameRateCallBack(false), _noPictureAlarmCallBack(false), _captureAlarm(Cleared), _setCaptureDelay(0), _dataCallBack(NULL), _captureCallBack(NULL), _lastProcessFrameCount(TickTime::Now()), _rotateFrame(kRotateNone), last_capture_time_(0), delta_ntp_internal_ms_( Clock::GetRealTimeClock()->CurrentNtpInMilliseconds() - TickTime::MillisecondTimestamp()) { _requestedCapability.width = kDefaultWidth; _requestedCapability.height = kDefaultHeight; _requestedCapability.maxFPS = 30; _requestedCapability.rawType = kVideoI420; _requestedCapability.codecType = kVideoCodecUnknown; memset(_incomingFrameTimes, 0, sizeof(_incomingFrameTimes)); } VideoCaptureImpl::~VideoCaptureImpl() { DeRegisterCaptureDataCallback(); DeRegisterCaptureCallback(); delete &_callBackCs; delete &_apiCs; if (_deviceUniqueId) delete[] _deviceUniqueId; } void VideoCaptureImpl::RegisterCaptureDataCallback( VideoCaptureDataCallback& dataCallBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = &dataCallBack; } void VideoCaptureImpl::DeRegisterCaptureDataCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = NULL; } void VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = &callBack; } void VideoCaptureImpl::DeRegisterCaptureCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = NULL; } void VideoCaptureImpl::SetCaptureDelay(int32_t delayMS) { CriticalSectionScoped cs(&_apiCs); _captureDelay = delayMS; } int32_t VideoCaptureImpl::CaptureDelay() { CriticalSectionScoped cs(&_apiCs); return _setCaptureDelay; } int32_t VideoCaptureImpl::DeliverCapturedFrame(I420VideoFrame& captureFrame, int64_t capture_time) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.set_render_time_ms(capture_time - delta_ntp_internal_ms_); } else { captureFrame.set_render_time_ms(TickTime::MillisecondTimestamp()); } if (captureFrame.render_time_ms() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.render_time_ms(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame); } return 0; } int32_t VideoCaptureImpl::IncomingFrame( uint8_t* videoFrame, int32_t videoFrameLength, const VideoCaptureCapability& frameInfo, int64_t captureTime/*=0*/) { WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideoCapture, _id, "IncomingFrame width %d, height %d", (int) frameInfo.width, (int) frameInfo.height); TickTime startProcessTime = TickTime::Now(); CriticalSectionScoped cs(&_callBackCs); const int32_t width = frameInfo.width; const int32_t height = frameInfo.height; TRACE_EVENT1("webrtc", "VC::IncomingFrame", "capture_time", captureTime); if (frameInfo.codecType == kVideoCodecUnknown) { // Not encoded, convert to I420. const VideoType commonVideoType = RawVideoTypeToCommonVideoVideoType(frameInfo.rawType); if (frameInfo.rawType != kVideoMJPEG && CalcBufferSize(commonVideoType, width, abs(height)) != videoFrameLength) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Wrong incoming frame length."); return -1; } int stride_y = width; int stride_uv = (width + 1) / 2; int target_width = width; int target_height = height; // Rotating resolution when for 90/270 degree rotations. if (_rotateFrame == kRotate90 || _rotateFrame == kRotate270) { target_width = abs(height); target_height = width; } // TODO(mikhal): Update correct aligned stride values. //Calc16ByteAlignedStride(target_width, &stride_y, &stride_uv); // Setting absolute height (in case it was negative). // In Windows, the image starts bottom left, instead of top left. // Setting a negative source height, inverts the image (within LibYuv). int ret = _captureFrame.CreateEmptyFrame(target_width, abs(target_height), stride_y, stride_uv, stride_uv); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to allocate I420 frame."); return -1; } const int conversionResult = ConvertToI420(commonVideoType, videoFrame, 0, 0, // No cropping width, height, videoFrameLength, _rotateFrame, &_captureFrame); if (conversionResult < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to convert capture frame from type %d to I420", frameInfo.rawType); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); } else // Encoded format { assert(false); return -1; } const uint32_t processTime = (uint32_t)(TickTime::Now() - startProcessTime).Milliseconds(); if (processTime > 10) // If the process time is too long MJPG will not work well. { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCapture, _id, "Too long processing time of Incoming frame: %ums", (unsigned int) processTime); } return 0; } int32_t VideoCaptureImpl::IncomingI420VideoFrame(I420VideoFrame* video_frame, int64_t captureTime) { CriticalSectionScoped cs(&_callBackCs); DeliverCapturedFrame(*video_frame, captureTime); return 0; } int32_t VideoCaptureImpl::SetCaptureRotation(VideoCaptureRotation rotation) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); switch (rotation){ case kCameraRotate0: _rotateFrame = kRotateNone; break; case kCameraRotate90: _rotateFrame = kRotate90; break; case kCameraRotate180: _rotateFrame = kRotate180; break; case kCameraRotate270: _rotateFrame = kRotate270; break; default: return -1; } return 0; } void VideoCaptureImpl::EnableFrameRateCallback(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _frameRateCallBack = enable; if (enable) { _lastFrameRateCallbackTime = TickTime::Now(); } } void VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _noPictureAlarmCallBack = enable; } void VideoCaptureImpl::UpdateFrameCount() { if (_incomingFrameTimes[0].MicrosecondTimestamp() == 0) { // first no shift } else { // shift for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--) { _incomingFrameTimes[i + 1] = _incomingFrameTimes[i]; } } _incomingFrameTimes[0] = TickTime::Now(); } uint32_t VideoCaptureImpl::CalculateFrameRate(const TickTime& now) { int32_t num = 0; int32_t nrOfFrames = 0; for (num = 1; num < (kFrameRateCountHistorySize - 1); num++) { if (_incomingFrameTimes[num].Ticks() <= 0 || (now - _incomingFrameTimes[num]).Milliseconds() > kFrameRateHistoryWindowMs) // don't use data older than 2sec { break; } else { nrOfFrames++; } } if (num > 1) { int64_t diff = (now - _incomingFrameTimes[num - 1]).Milliseconds(); if (diff > 0) { return uint32_t((nrOfFrames * 1000.0f / diff) + 0.5f); } } return nrOfFrames; } } // namespace videocapturemodule } // namespace webrtc <commit_msg>Remove "Too long processing time of Incoming frame" logspam.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_capture/video_capture_impl.h" #include <stdlib.h> #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/modules/video_capture/video_capture_config.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/ref_count.h" #include "webrtc/system_wrappers/interface/tick_util.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { namespace videocapturemodule { VideoCaptureModule* VideoCaptureImpl::Create( const int32_t id, VideoCaptureExternal*& externalCapture) { RefCountImpl<VideoCaptureImpl>* implementation = new RefCountImpl<VideoCaptureImpl>(id); externalCapture = implementation; return implementation; } const char* VideoCaptureImpl::CurrentDeviceName() const { return _deviceUniqueId; } // static int32_t VideoCaptureImpl::RotationFromDegrees(int degrees, VideoCaptureRotation* rotation) { switch (degrees) { case 0: *rotation = kCameraRotate0; return 0; case 90: *rotation = kCameraRotate90; return 0; case 180: *rotation = kCameraRotate180; return 0; case 270: *rotation = kCameraRotate270; return 0; default: return -1;; } } // static int32_t VideoCaptureImpl::RotationInDegrees(VideoCaptureRotation rotation, int* degrees) { switch (rotation) { case kCameraRotate0: *degrees = 0; return 0; case kCameraRotate90: *degrees = 90; return 0; case kCameraRotate180: *degrees = 180; return 0; case kCameraRotate270: *degrees = 270; return 0; } return -1; } int32_t VideoCaptureImpl::ChangeUniqueId(const int32_t id) { _id = id; return 0; } // returns the number of milliseconds until the module want a worker thread to call Process int32_t VideoCaptureImpl::TimeUntilNextProcess() { CriticalSectionScoped cs(&_callBackCs); int32_t timeToNormalProcess = kProcessInterval - (int32_t)((TickTime::Now() - _lastProcessTime).Milliseconds()); return timeToNormalProcess; } // Process any pending tasks such as timeouts int32_t VideoCaptureImpl::Process() { CriticalSectionScoped cs(&_callBackCs); const TickTime now = TickTime::Now(); _lastProcessTime = TickTime::Now(); // Handle No picture alarm if (_lastProcessFrameCount.Ticks() == _incomingFrameTimes[0].Ticks() && _captureAlarm != Raised) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Raised; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } else if (_lastProcessFrameCount.Ticks() != _incomingFrameTimes[0].Ticks() && _captureAlarm != Cleared) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Cleared; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } // Handle frame rate callback if ((now - _lastFrameRateCallbackTime).Milliseconds() > kFrameRateCallbackInterval) { if (_frameRateCallBack && _captureCallBack) { const uint32_t frameRate = CalculateFrameRate(now); _captureCallBack->OnCaptureFrameRate(_id, frameRate); } _lastFrameRateCallbackTime = now; // Can be set by EnableFrameRateCallback } _lastProcessFrameCount = _incomingFrameTimes[0]; return 0; } VideoCaptureImpl::VideoCaptureImpl(const int32_t id) : _id(id), _deviceUniqueId(NULL), _apiCs(*CriticalSectionWrapper::CreateCriticalSection()), _captureDelay(0), _requestedCapability(), _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()), _lastProcessTime(TickTime::Now()), _lastFrameRateCallbackTime(TickTime::Now()), _frameRateCallBack(false), _noPictureAlarmCallBack(false), _captureAlarm(Cleared), _setCaptureDelay(0), _dataCallBack(NULL), _captureCallBack(NULL), _lastProcessFrameCount(TickTime::Now()), _rotateFrame(kRotateNone), last_capture_time_(0), delta_ntp_internal_ms_( Clock::GetRealTimeClock()->CurrentNtpInMilliseconds() - TickTime::MillisecondTimestamp()) { _requestedCapability.width = kDefaultWidth; _requestedCapability.height = kDefaultHeight; _requestedCapability.maxFPS = 30; _requestedCapability.rawType = kVideoI420; _requestedCapability.codecType = kVideoCodecUnknown; memset(_incomingFrameTimes, 0, sizeof(_incomingFrameTimes)); } VideoCaptureImpl::~VideoCaptureImpl() { DeRegisterCaptureDataCallback(); DeRegisterCaptureCallback(); delete &_callBackCs; delete &_apiCs; if (_deviceUniqueId) delete[] _deviceUniqueId; } void VideoCaptureImpl::RegisterCaptureDataCallback( VideoCaptureDataCallback& dataCallBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = &dataCallBack; } void VideoCaptureImpl::DeRegisterCaptureDataCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = NULL; } void VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = &callBack; } void VideoCaptureImpl::DeRegisterCaptureCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = NULL; } void VideoCaptureImpl::SetCaptureDelay(int32_t delayMS) { CriticalSectionScoped cs(&_apiCs); _captureDelay = delayMS; } int32_t VideoCaptureImpl::CaptureDelay() { CriticalSectionScoped cs(&_apiCs); return _setCaptureDelay; } int32_t VideoCaptureImpl::DeliverCapturedFrame(I420VideoFrame& captureFrame, int64_t capture_time) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.set_render_time_ms(capture_time - delta_ntp_internal_ms_); } else { captureFrame.set_render_time_ms(TickTime::MillisecondTimestamp()); } if (captureFrame.render_time_ms() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.render_time_ms(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame); } return 0; } int32_t VideoCaptureImpl::IncomingFrame( uint8_t* videoFrame, int32_t videoFrameLength, const VideoCaptureCapability& frameInfo, int64_t captureTime/*=0*/) { WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideoCapture, _id, "IncomingFrame width %d, height %d", (int) frameInfo.width, (int) frameInfo.height); CriticalSectionScoped cs(&_callBackCs); const int32_t width = frameInfo.width; const int32_t height = frameInfo.height; TRACE_EVENT1("webrtc", "VC::IncomingFrame", "capture_time", captureTime); if (frameInfo.codecType == kVideoCodecUnknown) { // Not encoded, convert to I420. const VideoType commonVideoType = RawVideoTypeToCommonVideoVideoType(frameInfo.rawType); if (frameInfo.rawType != kVideoMJPEG && CalcBufferSize(commonVideoType, width, abs(height)) != videoFrameLength) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Wrong incoming frame length."); return -1; } int stride_y = width; int stride_uv = (width + 1) / 2; int target_width = width; int target_height = height; // Rotating resolution when for 90/270 degree rotations. if (_rotateFrame == kRotate90 || _rotateFrame == kRotate270) { target_width = abs(height); target_height = width; } // TODO(mikhal): Update correct aligned stride values. //Calc16ByteAlignedStride(target_width, &stride_y, &stride_uv); // Setting absolute height (in case it was negative). // In Windows, the image starts bottom left, instead of top left. // Setting a negative source height, inverts the image (within LibYuv). int ret = _captureFrame.CreateEmptyFrame(target_width, abs(target_height), stride_y, stride_uv, stride_uv); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to allocate I420 frame."); return -1; } const int conversionResult = ConvertToI420(commonVideoType, videoFrame, 0, 0, // No cropping width, height, videoFrameLength, _rotateFrame, &_captureFrame); if (conversionResult < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to convert capture frame from type %d to I420", frameInfo.rawType); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); } else // Encoded format { assert(false); return -1; } return 0; } int32_t VideoCaptureImpl::IncomingI420VideoFrame(I420VideoFrame* video_frame, int64_t captureTime) { CriticalSectionScoped cs(&_callBackCs); DeliverCapturedFrame(*video_frame, captureTime); return 0; } int32_t VideoCaptureImpl::SetCaptureRotation(VideoCaptureRotation rotation) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); switch (rotation){ case kCameraRotate0: _rotateFrame = kRotateNone; break; case kCameraRotate90: _rotateFrame = kRotate90; break; case kCameraRotate180: _rotateFrame = kRotate180; break; case kCameraRotate270: _rotateFrame = kRotate270; break; default: return -1; } return 0; } void VideoCaptureImpl::EnableFrameRateCallback(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _frameRateCallBack = enable; if (enable) { _lastFrameRateCallbackTime = TickTime::Now(); } } void VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _noPictureAlarmCallBack = enable; } void VideoCaptureImpl::UpdateFrameCount() { if (_incomingFrameTimes[0].MicrosecondTimestamp() == 0) { // first no shift } else { // shift for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--) { _incomingFrameTimes[i + 1] = _incomingFrameTimes[i]; } } _incomingFrameTimes[0] = TickTime::Now(); } uint32_t VideoCaptureImpl::CalculateFrameRate(const TickTime& now) { int32_t num = 0; int32_t nrOfFrames = 0; for (num = 1; num < (kFrameRateCountHistorySize - 1); num++) { if (_incomingFrameTimes[num].Ticks() <= 0 || (now - _incomingFrameTimes[num]).Milliseconds() > kFrameRateHistoryWindowMs) // don't use data older than 2sec { break; } else { nrOfFrames++; } } if (num > 1) { int64_t diff = (now - _incomingFrameTimes[num - 1]).Milliseconds(); if (diff > 0) { return uint32_t((nrOfFrames * 1000.0f / diff) + 0.5f); } } return nrOfFrames; } } // namespace videocapturemodule } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_capture_impl.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "critical_section_wrapper.h" #include "module_common_types.h" #include "ref_count.h" #include "tick_util.h" #include "trace.h" #include "video_capture_config.h" #include <stdlib.h> namespace webrtc { namespace videocapturemodule { VideoCaptureModule* VideoCaptureImpl::Create( const WebRtc_Word32 id, VideoCaptureExternal*& externalCapture) { RefCountImpl<VideoCaptureImpl>* implementation = new RefCountImpl<VideoCaptureImpl>(id); externalCapture = implementation; return implementation; } const char* VideoCaptureImpl::CurrentDeviceName() const { return _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::ChangeUniqueId(const WebRtc_Word32 id) { _id = id; return 0; } // returns the number of milliseconds until the module want a worker thread to call Process WebRtc_Word32 VideoCaptureImpl::TimeUntilNextProcess() { CriticalSectionScoped cs(&_callBackCs); WebRtc_Word32 timeToNormalProcess = kProcessInterval - (WebRtc_Word32)((TickTime::Now() - _lastProcessTime).Milliseconds()); return timeToNormalProcess; } // Process any pending tasks such as timeouts WebRtc_Word32 VideoCaptureImpl::Process() { CriticalSectionScoped cs(&_callBackCs); const TickTime now = TickTime::Now(); _lastProcessTime = TickTime::Now(); // Handle No picture alarm if (_lastProcessFrameCount.Ticks() == _incomingFrameTimes[0].Ticks() && _captureAlarm != Raised) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Raised; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } else if (_lastProcessFrameCount.Ticks() != _incomingFrameTimes[0].Ticks() && _captureAlarm != Cleared) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Cleared; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } // Handle frame rate callback if ((now - _lastFrameRateCallbackTime).Milliseconds() > kFrameRateCallbackInterval) { if (_frameRateCallBack && _captureCallBack) { const WebRtc_UWord32 frameRate = CalculateFrameRate(now); _captureCallBack->OnCaptureFrameRate(_id, frameRate); } _lastFrameRateCallbackTime = now; // Can be set by EnableFrameRateCallback } _lastProcessFrameCount = _incomingFrameTimes[0]; return 0; } VideoCaptureImpl::VideoCaptureImpl(const WebRtc_Word32 id) : _id(id), _deviceUniqueId(NULL), _apiCs(*CriticalSectionWrapper::CreateCriticalSection()), _captureDelay(0), _requestedCapability(), _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()), _lastProcessTime(TickTime::Now()), _lastFrameRateCallbackTime(TickTime::Now()), _frameRateCallBack(false), _noPictureAlarmCallBack(false), _captureAlarm(Cleared), _setCaptureDelay(0), _dataCallBack(NULL), _captureCallBack(NULL), _lastProcessFrameCount(TickTime::Now()), _rotateFrame(kRotateNone), last_capture_time_(TickTime::MillisecondTimestamp()) { _requestedCapability.width = kDefaultWidth; _requestedCapability.height = kDefaultHeight; _requestedCapability.maxFPS = 30; _requestedCapability.rawType = kVideoI420; _requestedCapability.codecType = kVideoCodecUnknown; memset(_incomingFrameTimes, 0, sizeof(_incomingFrameTimes)); } VideoCaptureImpl::~VideoCaptureImpl() { DeRegisterCaptureDataCallback(); DeRegisterCaptureCallback(); delete &_callBackCs; delete &_apiCs; if (_deviceUniqueId) delete[] _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureDataCallback( VideoCaptureDataCallback& dataCallBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = &dataCallBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureDataCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = &callBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureDelay(WebRtc_Word32 delayMS) { CriticalSectionScoped cs(&_apiCs); _captureDelay = delayMS; return 0; } WebRtc_Word32 VideoCaptureImpl::CaptureDelay() { CriticalSectionScoped cs(&_apiCs); return _setCaptureDelay; } WebRtc_Word32 VideoCaptureImpl::DeliverCapturedFrame(I420VideoFrame& captureFrame, WebRtc_Word64 capture_time) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.set_render_time_ms(capture_time); } else { captureFrame.set_render_time_ms(TickTime::MillisecondTimestamp()); } if (captureFrame.render_time_ms() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.render_time_ms(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame); } return 0; } WebRtc_Word32 VideoCaptureImpl::DeliverEncodedCapturedFrame( VideoFrame& captureFrame, WebRtc_Word64 capture_time, VideoCodecType codecType) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.SetRenderTime(capture_time); } else { captureFrame.SetRenderTime(TickTime::MillisecondTimestamp()); } if (captureFrame.RenderTimeMs() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.RenderTimeMs(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedEncodedFrame(_id, captureFrame, codecType); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrame( WebRtc_UWord8* videoFrame, WebRtc_Word32 videoFrameLength, const VideoCaptureCapability& frameInfo, WebRtc_Word64 captureTime/*=0*/) { WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideoCapture, _id, "IncomingFrame width %d, height %d", (int) frameInfo.width, (int) frameInfo.height); TickTime startProcessTime = TickTime::Now(); CriticalSectionScoped cs(&_callBackCs); const WebRtc_Word32 width = frameInfo.width; const WebRtc_Word32 height = frameInfo.height; if (frameInfo.codecType == kVideoCodecUnknown) { // Not encoded, convert to I420. const VideoType commonVideoType = RawVideoTypeToCommonVideoVideoType(frameInfo.rawType); if (frameInfo.rawType != kVideoMJPEG && CalcBufferSize(commonVideoType, width, abs(height)) != videoFrameLength) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Wrong incoming frame length."); return -1; } int stride_y = 0; int stride_uv = 0; int target_width = width; int target_height = height; // Rotating resolution when for 90/270 degree rotations. if (_rotateFrame == kRotate90 || _rotateFrame == kRotate270) { target_width = abs(height); target_height = width; } Calc16ByteAlignedStride(target_width, &stride_y, &stride_uv); // Setting absolute height (in case it was negative). // In Windows, the image starts bottom left, instead of top left. // Setting a negative source height, inverts the image (within LibYuv). int ret = _captureFrame.CreateEmptyFrame(target_width, abs(target_height), stride_y, stride_uv, stride_uv); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to allocate I420 frame."); return -1; } const int conversionResult = ConvertToI420(commonVideoType, videoFrame, 0, 0, // No cropping width, height, videoFrameLength, _rotateFrame, &_captureFrame); if (conversionResult < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to convert capture frame from type %d to I420", frameInfo.rawType); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); } else // Encoded format { if (_capture_encoded_frame.CopyFrame(videoFrameLength, videoFrame) != 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to copy captured frame of length %d", static_cast<int>(videoFrameLength)); } DeliverEncodedCapturedFrame(_capture_encoded_frame, captureTime, frameInfo.codecType); } const WebRtc_UWord32 processTime = (WebRtc_UWord32)(TickTime::Now() - startProcessTime).Milliseconds(); if (processTime > 10) // If the process time is too long MJPG will not work well. { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCapture, _id, "Too long processing time of Incoming frame: %ums", (unsigned int) processTime); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrameI420( const VideoFrameI420& video_frame, WebRtc_Word64 captureTime) { CriticalSectionScoped cs(&_callBackCs); int size_y = video_frame.height * video_frame.y_pitch; int size_u = video_frame.u_pitch * ((video_frame.height + 1) / 2); int size_v = video_frame.v_pitch * ((video_frame.height + 1) / 2); // TODO(mikhal): Can we use Swap here? This will do a memcpy. int ret = _captureFrame.CreateFrame(size_y, video_frame.y_plane, size_u, video_frame.u_plane, size_v, video_frame.v_plane, video_frame.width, video_frame.height, video_frame.y_pitch, video_frame.u_pitch, video_frame.v_pitch); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to create I420VideoFrame"); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureRotation(VideoCaptureRotation rotation) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); switch (rotation){ case kCameraRotate0: _rotateFrame = kRotateNone; break; case kCameraRotate90: _rotateFrame = kRotate90; break; case kCameraRotate180: _rotateFrame = kRotate180; break; case kCameraRotate270: _rotateFrame = kRotate270; break; } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableFrameRateCallback(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _frameRateCallBack = enable; if (enable) { _lastFrameRateCallbackTime = TickTime::Now(); } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _noPictureAlarmCallBack = enable; return 0; } void VideoCaptureImpl::UpdateFrameCount() { if (_incomingFrameTimes[0].MicrosecondTimestamp() == 0) { // first no shift } else { // shift for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--) { _incomingFrameTimes[i + 1] = _incomingFrameTimes[i]; } } _incomingFrameTimes[0] = TickTime::Now(); } WebRtc_UWord32 VideoCaptureImpl::CalculateFrameRate(const TickTime& now) { WebRtc_Word32 num = 0; WebRtc_Word32 nrOfFrames = 0; for (num = 1; num < (kFrameRateCountHistorySize - 1); num++) { if (_incomingFrameTimes[num].Ticks() <= 0 || (now - _incomingFrameTimes[num]).Milliseconds() > kFrameRateHistoryWindowMs) // don't use data older than 2sec { break; } else { nrOfFrames++; } } if (num > 1) { WebRtc_Word64 diff = (now - _incomingFrameTimes[num - 1]).Milliseconds(); if (diff > 0) { return WebRtc_UWord32((nrOfFrames * 1000.0f / diff) + 0.5f); } } return nrOfFrames; } } // namespace videocapturemodule } // namespace webrtc <commit_msg>Setting capture stride to width<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_capture_impl.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "critical_section_wrapper.h" #include "module_common_types.h" #include "ref_count.h" #include "tick_util.h" #include "trace.h" #include "video_capture_config.h" #include <stdlib.h> namespace webrtc { namespace videocapturemodule { VideoCaptureModule* VideoCaptureImpl::Create( const WebRtc_Word32 id, VideoCaptureExternal*& externalCapture) { RefCountImpl<VideoCaptureImpl>* implementation = new RefCountImpl<VideoCaptureImpl>(id); externalCapture = implementation; return implementation; } const char* VideoCaptureImpl::CurrentDeviceName() const { return _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::ChangeUniqueId(const WebRtc_Word32 id) { _id = id; return 0; } // returns the number of milliseconds until the module want a worker thread to call Process WebRtc_Word32 VideoCaptureImpl::TimeUntilNextProcess() { CriticalSectionScoped cs(&_callBackCs); WebRtc_Word32 timeToNormalProcess = kProcessInterval - (WebRtc_Word32)((TickTime::Now() - _lastProcessTime).Milliseconds()); return timeToNormalProcess; } // Process any pending tasks such as timeouts WebRtc_Word32 VideoCaptureImpl::Process() { CriticalSectionScoped cs(&_callBackCs); const TickTime now = TickTime::Now(); _lastProcessTime = TickTime::Now(); // Handle No picture alarm if (_lastProcessFrameCount.Ticks() == _incomingFrameTimes[0].Ticks() && _captureAlarm != Raised) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Raised; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } else if (_lastProcessFrameCount.Ticks() != _incomingFrameTimes[0].Ticks() && _captureAlarm != Cleared) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Cleared; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } // Handle frame rate callback if ((now - _lastFrameRateCallbackTime).Milliseconds() > kFrameRateCallbackInterval) { if (_frameRateCallBack && _captureCallBack) { const WebRtc_UWord32 frameRate = CalculateFrameRate(now); _captureCallBack->OnCaptureFrameRate(_id, frameRate); } _lastFrameRateCallbackTime = now; // Can be set by EnableFrameRateCallback } _lastProcessFrameCount = _incomingFrameTimes[0]; return 0; } VideoCaptureImpl::VideoCaptureImpl(const WebRtc_Word32 id) : _id(id), _deviceUniqueId(NULL), _apiCs(*CriticalSectionWrapper::CreateCriticalSection()), _captureDelay(0), _requestedCapability(), _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()), _lastProcessTime(TickTime::Now()), _lastFrameRateCallbackTime(TickTime::Now()), _frameRateCallBack(false), _noPictureAlarmCallBack(false), _captureAlarm(Cleared), _setCaptureDelay(0), _dataCallBack(NULL), _captureCallBack(NULL), _lastProcessFrameCount(TickTime::Now()), _rotateFrame(kRotateNone), last_capture_time_(TickTime::MillisecondTimestamp()) { _requestedCapability.width = kDefaultWidth; _requestedCapability.height = kDefaultHeight; _requestedCapability.maxFPS = 30; _requestedCapability.rawType = kVideoI420; _requestedCapability.codecType = kVideoCodecUnknown; memset(_incomingFrameTimes, 0, sizeof(_incomingFrameTimes)); } VideoCaptureImpl::~VideoCaptureImpl() { DeRegisterCaptureDataCallback(); DeRegisterCaptureCallback(); delete &_callBackCs; delete &_apiCs; if (_deviceUniqueId) delete[] _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureDataCallback( VideoCaptureDataCallback& dataCallBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = &dataCallBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureDataCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = &callBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureDelay(WebRtc_Word32 delayMS) { CriticalSectionScoped cs(&_apiCs); _captureDelay = delayMS; return 0; } WebRtc_Word32 VideoCaptureImpl::CaptureDelay() { CriticalSectionScoped cs(&_apiCs); return _setCaptureDelay; } WebRtc_Word32 VideoCaptureImpl::DeliverCapturedFrame(I420VideoFrame& captureFrame, WebRtc_Word64 capture_time) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.set_render_time_ms(capture_time); } else { captureFrame.set_render_time_ms(TickTime::MillisecondTimestamp()); } if (captureFrame.render_time_ms() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.render_time_ms(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame); } return 0; } WebRtc_Word32 VideoCaptureImpl::DeliverEncodedCapturedFrame( VideoFrame& captureFrame, WebRtc_Word64 capture_time, VideoCodecType codecType) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.SetRenderTime(capture_time); } else { captureFrame.SetRenderTime(TickTime::MillisecondTimestamp()); } if (captureFrame.RenderTimeMs() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.RenderTimeMs(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedEncodedFrame(_id, captureFrame, codecType); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrame( WebRtc_UWord8* videoFrame, WebRtc_Word32 videoFrameLength, const VideoCaptureCapability& frameInfo, WebRtc_Word64 captureTime/*=0*/) { WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideoCapture, _id, "IncomingFrame width %d, height %d", (int) frameInfo.width, (int) frameInfo.height); TickTime startProcessTime = TickTime::Now(); CriticalSectionScoped cs(&_callBackCs); const WebRtc_Word32 width = frameInfo.width; const WebRtc_Word32 height = frameInfo.height; if (frameInfo.codecType == kVideoCodecUnknown) { // Not encoded, convert to I420. const VideoType commonVideoType = RawVideoTypeToCommonVideoVideoType(frameInfo.rawType); if (frameInfo.rawType != kVideoMJPEG && CalcBufferSize(commonVideoType, width, abs(height)) != videoFrameLength) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Wrong incoming frame length."); return -1; } int stride_y = width; int stride_uv = (width + 1) / 2; int target_width = width; int target_height = height; // Rotating resolution when for 90/270 degree rotations. if (_rotateFrame == kRotate90 || _rotateFrame == kRotate270) { target_width = abs(height); target_height = width; } // TODO(mikhal): Update correct aligned stride values. //Calc16ByteAlignedStride(target_width, &stride_y, &stride_uv); // Setting absolute height (in case it was negative). // In Windows, the image starts bottom left, instead of top left. // Setting a negative source height, inverts the image (within LibYuv). int ret = _captureFrame.CreateEmptyFrame(target_width, abs(target_height), stride_y, stride_uv, stride_uv); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to allocate I420 frame."); return -1; } const int conversionResult = ConvertToI420(commonVideoType, videoFrame, 0, 0, // No cropping width, height, videoFrameLength, _rotateFrame, &_captureFrame); if (conversionResult < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to convert capture frame from type %d to I420", frameInfo.rawType); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); } else // Encoded format { if (_capture_encoded_frame.CopyFrame(videoFrameLength, videoFrame) != 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to copy captured frame of length %d", static_cast<int>(videoFrameLength)); } DeliverEncodedCapturedFrame(_capture_encoded_frame, captureTime, frameInfo.codecType); } const WebRtc_UWord32 processTime = (WebRtc_UWord32)(TickTime::Now() - startProcessTime).Milliseconds(); if (processTime > 10) // If the process time is too long MJPG will not work well. { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCapture, _id, "Too long processing time of Incoming frame: %ums", (unsigned int) processTime); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrameI420( const VideoFrameI420& video_frame, WebRtc_Word64 captureTime) { CriticalSectionScoped cs(&_callBackCs); int size_y = video_frame.height * video_frame.y_pitch; int size_u = video_frame.u_pitch * ((video_frame.height + 1) / 2); int size_v = video_frame.v_pitch * ((video_frame.height + 1) / 2); // TODO(mikhal): Can we use Swap here? This will do a memcpy. int ret = _captureFrame.CreateFrame(size_y, video_frame.y_plane, size_u, video_frame.u_plane, size_v, video_frame.v_plane, video_frame.width, video_frame.height, video_frame.y_pitch, video_frame.u_pitch, video_frame.v_pitch); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to create I420VideoFrame"); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureRotation(VideoCaptureRotation rotation) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); switch (rotation){ case kCameraRotate0: _rotateFrame = kRotateNone; break; case kCameraRotate90: _rotateFrame = kRotate90; break; case kCameraRotate180: _rotateFrame = kRotate180; break; case kCameraRotate270: _rotateFrame = kRotate270; break; } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableFrameRateCallback(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _frameRateCallBack = enable; if (enable) { _lastFrameRateCallbackTime = TickTime::Now(); } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _noPictureAlarmCallBack = enable; return 0; } void VideoCaptureImpl::UpdateFrameCount() { if (_incomingFrameTimes[0].MicrosecondTimestamp() == 0) { // first no shift } else { // shift for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--) { _incomingFrameTimes[i + 1] = _incomingFrameTimes[i]; } } _incomingFrameTimes[0] = TickTime::Now(); } WebRtc_UWord32 VideoCaptureImpl::CalculateFrameRate(const TickTime& now) { WebRtc_Word32 num = 0; WebRtc_Word32 nrOfFrames = 0; for (num = 1; num < (kFrameRateCountHistorySize - 1); num++) { if (_incomingFrameTimes[num].Ticks() <= 0 || (now - _incomingFrameTimes[num]).Milliseconds() > kFrameRateHistoryWindowMs) // don't use data older than 2sec { break; } else { nrOfFrames++; } } if (num > 1) { WebRtc_Word64 diff = (now - _incomingFrameTimes[num - 1]).Milliseconds(); if (diff > 0) { return WebRtc_UWord32((nrOfFrames * 1000.0f / diff) + 0.5f); } } return nrOfFrames; } } // namespace videocapturemodule } // namespace webrtc <|endoftext|>
<commit_before>/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: [email protected], [email protected], [email protected] * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * 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, version 2. * * * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <stdlib.h> #include <stdio.h> #include <OSGConfig.h> #ifdef OSG_HAS_SSTREAM #include <sstream> #else #include <strstream> #endif #include <OSGImage.h> #include <OSGViewport.h> #include "OSGSimpleStatisticsForeground.h" #include "OSGStatisticsDefaultFont.h" #include "OSGTextLayoutParam.h" #include "OSGTextLayoutResult.h" #include "OSGTextTXFGlyph.h" OSG_USING_NAMESPACE /*! \class OSG::SimpleStatisticsForeground \ingroup GrpSystemWindowForegroundsStatistics SimpleStatisticsForeground displays the Statistics info as simple lines of text. osg::SimpleStatisticsForeground displays the statistics info as simple text lines. They are displayed using a compiled-in font that can use an arbitrary color and that can be arbitrarily resized, with the size per line given in pixel. The format of every element is given by a format string for every element that is directly passed to OSG::StatElem::putToString(), so go there to see the possible options. If no elementIDs are given all elements in the osg::StatCollector are display, using the default format. The format string for the given elements are stored in the _mfFormats Field, the size and color used for all lines in _sfSize and _sfColor. See \ref PageSystemWindowForegroundStatisticsSimple */ /*----------------------- constructors & destructors ----------------------*/ SimpleStatisticsForeground::SimpleStatisticsForeground(void) : Inherited(), _face(0), _texchunk(NullFC), _texenvchunk(NullFC) { _texenvchunk = TextureEnvChunk::create(); addRef(_texenvchunk); _texenvchunk->setEnvMode(GL_MODULATE); } /* */ SimpleStatisticsForeground::SimpleStatisticsForeground( const SimpleStatisticsForeground &source) : Inherited(source), _face(source._face), _texchunk(source._texchunk), _texenvchunk(source._texenvchunk) { if (_face != 0) addRefP(_face); if (_texchunk != NullFC) addRef(_texchunk); if (_texenvchunk != NullFC) addRef(_texenvchunk); } /* */ SimpleStatisticsForeground::~SimpleStatisticsForeground(void) { if (_face != 0) subRefP(_face); if (_texchunk != NullFC) subRef(_texchunk); if (_texenvchunk != NullFC) subRef(_texenvchunk); } /*----------------------------- class specific ----------------------------*/ void SimpleStatisticsForeground::initMethod(InitPhase ePhase) { Inherited::initMethod(ePhase); } /* */ void SimpleStatisticsForeground::changed(ConstFieldMaskArg whichField, UInt32 origin ) { Inherited::changed(whichField, origin); } /* */ void SimpleStatisticsForeground::dump(UInt32, const BitVector) const { SLOG << "Dump SimpleStatisticsForeground NI" << std::endl; } /*! Convenience function to add an element and format. */ void SimpleStatisticsForeground::addElement(StatElemDescBase &desc, const char *format) { editElementIDs().push_back(desc.getID()); editFormats().push_back(format ? format : ""); } /*! Convenience function to add an element and format. */ void SimpleStatisticsForeground::addElement(Int32 id, const char *format) { editElementIDs().push_back(id); editFormats().push_back(format ? format : ""); } /*! Initialize the text used. It is compiled into the library as StatisticsDefaultFontData and used as a TXF font. */ void SimpleStatisticsForeground::initText(const std::string &family, Real32 size) { // Cleanup if (_face != 0) subRefP(_face); if (_texchunk != NullFC) subRef(_texchunk); // Create the font if (family.empty() == false) { TextTXFParam param; param.size = static_cast<UInt32>(size); _face = TextTXFFace::create(family, TextFace::STYLE_PLAIN, param); if (_face != 0) { _texchunk = TextureObjChunk::create(); ImagePtr texture = _face->getTexture(); _texchunk->setImage(texture); _texchunk->setWrapS(GL_CLAMP); _texchunk->setWrapT(GL_CLAMP); _texchunk->setMinFilter(GL_NEAREST); _texchunk->setMagFilter(GL_NEAREST); } } // We failed to create the font - fallback to the default font if (_face == 0) { _face = StatisticsDefaultFont::the()->getFace(); _texchunk = StatisticsDefaultFont::the()->getTexture(); } // Increment reference counters addRefP(_face); addRef(_texchunk); } /*! Draw the statistics lines. */ void SimpleStatisticsForeground::draw(DrawEnv *pEnv, Viewport *pPort) { if (_face == 0) initText(""/*getFamily()*/, getSize()); // TODO Real32 pw = Real32(pPort->getPixelWidth ()); Real32 ph = Real32(pPort->getPixelHeight()); if(pw < 1 || ph < 1) return; GLboolean light = glIsEnabled(GL_LIGHTING); GLint fill[2]; glGetIntegerv(GL_POLYGON_MODE, fill); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); GLboolean depth = glIsEnabled(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST); GLboolean colmat = glIsEnabled(GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); Real32 aspect = pw / ph; Real32 size = getSize(); glOrtho(-0.5, -0.5 + ph / size * aspect, 0.5 - ph / size, 0.5, 0, 1); glAlphaFunc(GL_NOTEQUAL, 0); glEnable(GL_ALPHA_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // draw text std::vector < std::string > stat; StatCollector *col = &(this->editCollector()); StatElem *el; if(getElementIDs().size() != 0) { for(UInt32 i = 0; i < getElementIDs().size(); ++i) { Int32 id(getElementIDs()[i]); el = ((id >= 0) ? col->getElem(id) : 0); stat.resize(stat.size() + 1); std::vector < std::string >::iterator str = stat.end() - 1; const char *format = NULL; if(i < getFormats().size() && getFormats()[i].length()) { format = getFormats()[i].c_str(); } if (el) el->putToString(*str, format); else *str = format; } } else // fallback, show all elements { for(UInt32 i = 0; i < col->getNumOfElems(); ++i) { el = col->getElem(i, false); if(el) { std::string desc(el->getDesc()->getName().str()), eltext; el->putToString(eltext); desc = desc + " : " + eltext; stat.resize(stat.size() + 1); std::vector < std::string >::iterator str = stat.end() - 1; *str = desc; } } } TextLayoutParam layoutParam; layoutParam.majorAlignment = TextLayoutParam::ALIGN_BEGIN; layoutParam.minorAlignment = TextLayoutParam::ALIGN_BEGIN; TextLayoutResult layoutResult; _face->layout(stat, layoutParam, layoutResult); _texchunk ->activate(pEnv); _texenvchunk->activate(pEnv); glColor4fv((GLfloat *) getColor().getValuesRGBA()); glBegin(GL_QUADS); UInt32 i, numGlyphs = layoutResult.getNumGlyphs(); for(i = 0; i < numGlyphs; ++i) { const TextTXFGlyph &glyph = _face->getTXFGlyph(layoutResult.indices[i]); Real32 width = glyph.getWidth(); Real32 height = glyph.getHeight(); // No need to draw invisible glyphs if ((width <= 0.f) || (height <= 0.f)) continue; // Calculate coordinates const Vec2f &pos = layoutResult.positions[i]; Real32 posLeft = pos.x(); Real32 posTop = pos.y(); Real32 posRight = pos.x() + width; Real32 posBottom = pos.y() - height; Real32 texCoordLeft = glyph.getTexCoord(TextTXFGlyph::COORD_LEFT); Real32 texCoordTop = glyph.getTexCoord(TextTXFGlyph::COORD_TOP); Real32 texCoordRight = glyph.getTexCoord(TextTXFGlyph::COORD_RIGHT); Real32 texCoordBottom = glyph.getTexCoord(TextTXFGlyph::COORD_BOTTOM); // lower left corner glTexCoord2f(texCoordLeft, texCoordBottom); glVertex2f(posLeft, posBottom); // lower right corner glTexCoord2f(texCoordRight, texCoordBottom); glVertex2f(posRight, posBottom); // upper right corner glTexCoord2f(texCoordRight, texCoordTop); glVertex2f(posRight, posTop); // upper left corner glTexCoord2f(texCoordLeft, texCoordTop); glVertex2f(posLeft, posTop); } glEnd(); _texchunk ->deactivate(pEnv); _texenvchunk->deactivate(pEnv); glDisable(GL_ALPHA_TEST); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); if(depth == GL_TRUE) glEnable(GL_DEPTH_TEST); if(light == GL_TRUE) glEnable(GL_LIGHTING); if(colmat == GL_TRUE) glEnable(GL_COLOR_MATERIAL); glPolygonMode(GL_FRONT_AND_BACK, fill[0]); } /*-------------------------------------------------------------------------*/ /* cvs id's */ #ifdef __sgi #pragma set woff 1174 #endif #ifdef OSG_LINUX_ICC #pragma warning(disable : 177) #endif namespace { static char cvsid_cpp[] = "@(#)$Id$"; static char cvsid_hpp[] = OSGSIMPLESTATISTICSFOREGROUND_HEADER_CVSID; static char cvsid_inl[] = OSGSIMPLESTATISTICSFOREGROUND_INLINE_CVSID; } <commit_msg>Improved rendering of statistic text (ported from OSG 1.8)<commit_after>/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: [email protected], [email protected], [email protected] * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * 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, version 2. * * * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <stdlib.h> #include <stdio.h> #include <OSGConfig.h> #ifdef OSG_HAS_SSTREAM #include <sstream> #else #include <strstream> #endif #include <OSGImage.h> #include <OSGViewport.h> #include "OSGSimpleStatisticsForeground.h" #include "OSGStatisticsDefaultFont.h" #include "OSGTextLayoutParam.h" #include "OSGTextLayoutResult.h" #include "OSGTextTXFGlyph.h" OSG_USING_NAMESPACE /*! \class OSG::SimpleStatisticsForeground \ingroup GrpSystemWindowForegroundsStatistics SimpleStatisticsForeground displays the Statistics info as simple lines of text. osg::SimpleStatisticsForeground displays the statistics info as simple text lines. They are displayed using a compiled-in font that can use an arbitrary color and that can be arbitrarily resized, with the size per line given in pixel. The format of every element is given by a format string for every element that is directly passed to OSG::StatElem::putToString(), so go there to see the possible options. If no elementIDs are given all elements in the osg::StatCollector are display, using the default format. The format string for the given elements are stored in the _mfFormats Field, the size and color used for all lines in _sfSize and _sfColor. See \ref PageSystemWindowForegroundStatisticsSimple */ /*----------------------- constructors & destructors ----------------------*/ SimpleStatisticsForeground::SimpleStatisticsForeground(void) : Inherited(), _face(0), _texchunk(NullFC), _texenvchunk(NullFC) { _texenvchunk = TextureEnvChunk::create(); addRef(_texenvchunk); _texenvchunk->setEnvMode(GL_MODULATE); } /* */ SimpleStatisticsForeground::SimpleStatisticsForeground( const SimpleStatisticsForeground &source) : Inherited(source), _face(source._face), _texchunk(source._texchunk), _texenvchunk(source._texenvchunk) { if (_face != 0) addRefP(_face); if (_texchunk != NullFC) addRef(_texchunk); if (_texenvchunk != NullFC) addRef(_texenvchunk); } /* */ SimpleStatisticsForeground::~SimpleStatisticsForeground(void) { if (_face != 0) subRefP(_face); if (_texchunk != NullFC) subRef(_texchunk); if (_texenvchunk != NullFC) subRef(_texenvchunk); } /*----------------------------- class specific ----------------------------*/ void SimpleStatisticsForeground::initMethod(InitPhase ePhase) { Inherited::initMethod(ePhase); } /* */ void SimpleStatisticsForeground::changed(ConstFieldMaskArg whichField, UInt32 origin ) { Inherited::changed(whichField, origin); } /* */ void SimpleStatisticsForeground::dump(UInt32, const BitVector) const { SLOG << "Dump SimpleStatisticsForeground NI" << std::endl; } /*! Convenience function to add an element and format. */ void SimpleStatisticsForeground::addElement(StatElemDescBase &desc, const char *format) { editElementIDs().push_back(desc.getID()); editFormats().push_back(format ? format : ""); } /*! Convenience function to add an element and format. */ void SimpleStatisticsForeground::addElement(Int32 id, const char *format) { editElementIDs().push_back(id); editFormats().push_back(format ? format : ""); } /*! Initialize the text used. It is compiled into the library as StatisticsDefaultFontData and used as a TXF font. */ void SimpleStatisticsForeground::initText(const std::string &family, Real32 size) { // Cleanup if (_face != 0) subRefP(_face); if (_texchunk != NullFC) subRef(_texchunk); // Create the font if (family.empty() == false) { TextTXFParam param; param.size = static_cast<UInt32>(size); _face = TextTXFFace::create(family, TextFace::STYLE_PLAIN, param); if (_face != 0) { _texchunk = TextureObjChunk::create(); ImagePtr texture = _face->getTexture(); _texchunk->setImage(texture); _texchunk->setWrapS(GL_CLAMP); _texchunk->setWrapT(GL_CLAMP); _texchunk->setMinFilter(GL_NEAREST); _texchunk->setMagFilter(GL_NEAREST); } } // We failed to create the font - fallback to the default font if (_face == 0) { _face = StatisticsDefaultFont::the()->getFace(); _texchunk = StatisticsDefaultFont::the()->getTexture(); } // Increment reference counters addRefP(_face); addRef(_texchunk); } /*! Draw the statistics lines. */ void SimpleStatisticsForeground::draw(DrawEnv *pEnv, Viewport *pPort) { if (_face == 0) initText(""/*getFamily()*/, getSize()); // TODO if (!getCollector().getNumOfElems() && !getElementIDs().size()) return; // nothing to do Real32 pw = Real32(pPort->getPixelWidth ()); Real32 ph = Real32(pPort->getPixelHeight()); if(pw < 1 || ph < 1) return; glPushAttrib(GL_LIGHTING_BIT | GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_DEPTH_TEST); glDisable(GL_COLOR_MATERIAL); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); // Set viewport. We want to map one unit to one pixel on the // screen. Some sources in the internet say that we should // add an offset of -0.375 to prevent rounding errors. Don't // know if that is true, but it seems to work. glOrtho(0 - 0.375, pw - 0.375, 0 - 0.375, ph - 0.375, 0, 1); // retrieve text std::vector < std::string > stat; StatCollector *col = &(this->editCollector()); StatElem *el; if(getElementIDs().size() != 0) { for(UInt32 i = 0; i < getElementIDs().size(); ++i) { Int32 id(getElementIDs()[i]); el = ((id >= 0) ? col->getElem(id) : 0); stat.resize(stat.size() + 1); std::vector < std::string >::iterator str = stat.end() - 1; const char *format = NULL; if(i < getFormats().size() && getFormats()[i].length()) { format = getFormats()[i].c_str(); } if (el) el->putToString(*str, format); else *str = format; } } else // fallback, show all elements { for(UInt32 i = 0; i < col->getNumOfElems(); ++i) { el = col->getElem(i, false); if(el) { std::string desc(el->getDesc()->getName().str()), eltext; el->putToString(eltext); desc = desc + " : " + eltext; stat.resize(stat.size() + 1); std::vector < std::string >::iterator str = stat.end() - 1; *str = desc; } } } TextLayoutParam layoutParam; layoutParam.spacing = 1.1; layoutParam.majorAlignment = TextLayoutParam::ALIGN_BEGIN; layoutParam.minorAlignment = TextLayoutParam::ALIGN_BEGIN; TextLayoutResult layoutResult; _face->layout(stat, layoutParam, layoutResult); Real32 scale = 1 / _face->getScale(); Real32 size = _face->getParam().size; Real32 textWidth = layoutResult.textBounds.x() * scale + size; Real32 textHeight = layoutResult.textBounds.y() * scale + size; glTranslatef(0.0, ph, 0.0); // draw text glTranslatef(0.5 * size, -0.5 * size, 0.0); _texchunk ->activate(pEnv); _texenvchunk->activate(pEnv); glColor4fv((GLfloat *) getColor().getValuesRGBA()); glScalef(scale, scale, 1); glBegin(GL_QUADS); UInt32 i, numGlyphs = layoutResult.getNumGlyphs(); for(i = 0; i < numGlyphs; ++i) { const TextTXFGlyph &glyph = _face->getTXFGlyph(layoutResult.indices[i]); Real32 width = glyph.getWidth(); Real32 height = glyph.getHeight(); // No need to draw invisible glyphs if ((width <= 0.f) || (height <= 0.f)) continue; // Calculate coordinates const Vec2f &pos = layoutResult.positions[i]; Real32 posLeft = pos.x(); Real32 posTop = pos.y(); Real32 posRight = pos.x() + width; Real32 posBottom = pos.y() - height; Real32 texCoordLeft = glyph.getTexCoord(TextTXFGlyph::COORD_LEFT); Real32 texCoordTop = glyph.getTexCoord(TextTXFGlyph::COORD_TOP); Real32 texCoordRight = glyph.getTexCoord(TextTXFGlyph::COORD_RIGHT); Real32 texCoordBottom = glyph.getTexCoord(TextTXFGlyph::COORD_BOTTOM); // lower left corner glTexCoord2f(texCoordLeft, texCoordBottom); glVertex2f(posLeft, posBottom); // lower right corner glTexCoord2f(texCoordRight, texCoordBottom); glVertex2f(posRight, posBottom); // upper right corner glTexCoord2f(texCoordRight, texCoordTop); glVertex2f(posRight, posTop); // upper left corner glTexCoord2f(texCoordLeft, texCoordTop); glVertex2f(posLeft, posTop); } glEnd(); _texchunk ->deactivate(pEnv); _texenvchunk->deactivate(pEnv); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); } /*-------------------------------------------------------------------------*/ /* cvs id's */ #ifdef __sgi #pragma set woff 1174 #endif #ifdef OSG_LINUX_ICC #pragma warning(disable : 177) #endif namespace { static char cvsid_cpp[] = "@(#)$Id$"; static char cvsid_hpp[] = OSGSIMPLESTATISTICSFOREGROUND_HEADER_CVSID; static char cvsid_inl[] = OSGSIMPLESTATISTICSFOREGROUND_INLINE_CVSID; } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2018 Intel Corporation. All Rights Reserved. #include "frame-validator.h" #define INVALID_PIXELS_THRESHOLD 0.1 namespace librealsense { bool stream_profiles_equal(stream_profile_interface* l, stream_profile_interface* r) { auto vl = dynamic_cast<video_stream_profile_interface*>(l); auto vr = dynamic_cast<video_stream_profile_interface*>(r); if (!vl || !vr) return false; return l->get_framerate() == r->get_framerate() && vl->get_width() == vr->get_width() && vl->get_height() == vr->get_height() && vl->get_stream_type() == vr->get_stream_type(); } void frame_validator::on_frame(rs2_frame * f) { if (!_stopped && propagate((frame_interface*)f) && is_user_requested_frame((frame_interface*)f)) { _user_callback->on_frame(f); } else { // Resource handling ((frame_interface*)f)->release(); } } void frame_validator::release() {} frame_validator::frame_validator(std::shared_ptr<sensor_base> sensor, frame_callback_ptr user_callback, stream_profiles current_requests, stream_profiles validator_requests) : _sensor(sensor), _user_callback(user_callback), _user_requests(current_requests), _validator_requests(validator_requests), _stopped(false), _validated(false) {} frame_validator::~frame_validator() {} bool frame_validator::propagate(frame_interface* frame) { if(_validated) return true; auto vf = dynamic_cast<video_frame*>(frame); if (vf == nullptr) throw std::runtime_error(to_string() << "non video stream arrived to frame_validator"); auto stream = vf->get_stream(); //all streams except ir will be droped untill the validation on ir, //after the validation all streams will be passeded to user callback directly if (stream->get_stream_type() != RS2_STREAM_INFRARED) return false; //start to validate only from the second frame if(_ir_frame_num++ < 2) return false; auto w = vf->get_width(); auto h = vf->get_height(); auto data = static_cast<const void*>(vf->get_frame_data()); auto invalid_pixels = 0; for (int y = 0; y < h*w; y++) { if (((byte*)data)[y] == 0) { invalid_pixels++; } } if ((float)invalid_pixels/(w*h) < INVALID_PIXELS_THRESHOLD) { _validated = true; return true; } else { LOG_ERROR("frame_source received corrupted frame ("<<(float)invalid_pixels/(w*h)<<"% invalid pixels), restarting the sensor..."); _sensor->get_notifications_processor()->raise_notification({ RS2_NOTIFICATION_CATEGORY_FRAME_CORRUPTED , 0, RS2_LOG_SEVERITY_WARN, "L500 Corrupted Frame Detected\n" }); auto s = _sensor; auto vr = _validator_requests; auto uc = _user_callback; _stopped = true; _reset_thread = std::thread([s, vr, uc]() { try { //added delay as WA for stabilities issues std::this_thread::sleep_for(std::chrono::milliseconds(500)); s->stop(); s->close(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); s->open(vr); s->start(uc); } catch (...) { LOG_ERROR("restarting of sensor failed"); } }); _reset_thread.detach(); } return false; } bool frame_validator::is_user_requested_frame(frame_interface* frame) { return std::find_if(_user_requests.begin(), _user_requests.end(), [&](std::shared_ptr<stream_profile_interface> sp) { return stream_profiles_equal(frame->get_stream().get(), sp.get()); }) != _user_requests.end(); } } <commit_msg>disable ignoring of first two IR frames in corrupted frame handling<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2018 Intel Corporation. All Rights Reserved. #include "frame-validator.h" #define INVALID_PIXELS_THRESHOLD 0.1 namespace librealsense { bool stream_profiles_equal(stream_profile_interface* l, stream_profile_interface* r) { auto vl = dynamic_cast<video_stream_profile_interface*>(l); auto vr = dynamic_cast<video_stream_profile_interface*>(r); if (!vl || !vr) return false; return l->get_framerate() == r->get_framerate() && vl->get_width() == vr->get_width() && vl->get_height() == vr->get_height() && vl->get_stream_type() == vr->get_stream_type(); } void frame_validator::on_frame(rs2_frame * f) { if (!_stopped && propagate((frame_interface*)f) && is_user_requested_frame((frame_interface*)f)) { _user_callback->on_frame(f); } else { // Resource handling ((frame_interface*)f)->release(); } } void frame_validator::release() {} frame_validator::frame_validator(std::shared_ptr<sensor_base> sensor, frame_callback_ptr user_callback, stream_profiles current_requests, stream_profiles validator_requests) : _sensor(sensor), _user_callback(user_callback), _user_requests(current_requests), _validator_requests(validator_requests), _stopped(false), _validated(false) {} frame_validator::~frame_validator() {} bool frame_validator::propagate(frame_interface* frame) { if(_validated) return true; auto vf = dynamic_cast<video_frame*>(frame); if (vf == nullptr) throw std::runtime_error(to_string() << "non video stream arrived to frame_validator"); auto stream = vf->get_stream(); //all streams except ir will be droped untill the validation on ir, //after the validation all streams will be passeded to user callback directly if (stream->get_stream_type() != RS2_STREAM_INFRARED) return false; // TODO review the above statement and check with PLM #if 0 // TODO WHY? //start to validate only from the second frame if(_ir_frame_num++ < 2) return false; #endif auto w = vf->get_width(); auto h = vf->get_height(); auto data = static_cast<const void*>(vf->get_frame_data()); auto invalid_pixels = 0; for (int y = 0; y < h*w; y++) { if (((byte*)data)[y] == 0) { invalid_pixels++; } } if ((float)invalid_pixels/(w*h) < INVALID_PIXELS_THRESHOLD) { _validated = true; return true; } else { LOG_ERROR("frame_source received corrupted frame ("<<(float)invalid_pixels/(w*h)<<"% invalid pixels), restarting the sensor..."); _sensor->get_notifications_processor()->raise_notification({ RS2_NOTIFICATION_CATEGORY_FRAME_CORRUPTED , 0, RS2_LOG_SEVERITY_WARN, "L500 Corrupted Frame Detected\n" }); auto s = _sensor; auto vr = _validator_requests; auto uc = _user_callback; _stopped = true; _reset_thread = std::thread([s, vr, uc]() { try { //added delay as WA for stabilities issues std::this_thread::sleep_for(std::chrono::milliseconds(500)); s->stop(); s->close(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); s->open(vr); s->start(uc); } catch (...) { LOG_ERROR("restarting of sensor failed"); } }); _reset_thread.detach(); } return false; } bool frame_validator::is_user_requested_frame(frame_interface* frame) { return std::find_if(_user_requests.begin(), _user_requests.end(), [&](std::shared_ptr<stream_profile_interface> sp) { return stream_profiles_equal(frame->get_stream().get(), sp.get()); }) != _user_requests.end(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGradientAnisotropicDiffusionImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> #include "itkImage.h" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkNullImageToImageFilterDriver.txx" /** * This program tests the FilterImageAnisotropicDiffusion object by driving it * with a null input and output. Returns 0 on success and 1 on failure. */ int main(int argc, char *argv[]) { try { // Set up filter itk::GradientAnisotropicDiffusionImageFilter<float, 4>::Pointer filter = itk::GradientAnisotropicDiffusionImageFilter<float, 4>::New(); filter->SetIterations(1); filter->SetConductanceParameter(3.0f); filter->SetTimeStep(0.125f); // Run Test itk::Size<4> sz; sz[0] = 25;//atoi(argv[1]); sz[1] = 25;//atoi(argv[2]); sz[2] = 10;//atoi(argv[3]); sz[3] = 5;//atoi(argv[4]); itk::NullImageToImageFilterDriver< itk::Image<float, 4>, itk::Image<float, 4> > test1; test1.SetImageSize(sz); test1.SetFilter(filter.GetPointer()); test1.Execute(); } catch(itk::ExceptionObject &err) { (&err)->Print(std::cerr); return 1; } return 0; } <commit_msg>BUG: Fixed reference to missing include file.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGradientAnisotropicDiffusionImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> #include "itkImage.h" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkNullImageToImageFilterDriver.txx" /** * This program tests the FilterImageAnisotropicDiffusion object by driving it * with a null input and output. Returns 0 on success and 1 on failure. */ int main(int argc, char *argv[]) { try { // Set up filter itk::GradientAnisotropicDiffusionImageFilter<float, 4>::Pointer filter = itk::GradientAnisotropicDiffusionImageFilter<float, 4>::New(); filter->SetIterations(1); filter->SetConductanceParameter(3.0f); filter->SetTimeStep(0.125f); // Run Test itk::Size<4> sz; sz[0] = 25; sz[1] = 25; sz[2] = 10; sz[3] = 5; itk::NullImageToImageFilterDriver< itk::Image<float, 4>, itk::Image<float, 4> > test1; test1.SetImageSize(sz); test1.SetFilter(filter.GetPointer()); test1.Execute(); } catch(itk::ExceptionObject &err) { (&err)->Print(std::cerr); return 1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of k-par-means * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "knori.hpp" int main(int argc, char* argv[]) { constexpr size_t nrow = 50; constexpr size_t ncol = 5; constexpr size_t max_iters = 20; constexpr unsigned k = 8; constexpr unsigned nthread = 2; const std::string fn = "../../test-data/matrix_r50_c5_rrw.bin"; // Read from disk std::cout << "Testing read from disk ..\n"; { kpmbase::kmeans_t ret = kpmbase::kmeans( fn, nrow, ncol, k, /*"/data/kmeans/r16_c3145728_k100_cw.dat", 3145728, 16, 100,*/ max_iters, numa_num_task_nodes(), nthread, NULL); ret.print(); } // Data already in-mem FULL std::cout << "Testing data only in-mem ..\n"; { std::vector<double> data(nrow*ncol); kpmbase::bin_rm_reader<double> br(fn); br.read(data); kpmbase::kmeans_t ret = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, NULL, "kmeanspp", -1, "eucl", true); ret.print(); } // Data already in-mem PRUNED std::cout << "Testing PRUNED data only in-mem ..\n"; { std::vector<double> data(nrow*ncol); kpmbase::bin_rm_reader<double> br(fn); br.read(data); kpmbase::kmeans_t ret = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, NULL); ret.print(); } return EXIT_SUCCESS; } <commit_msg>test: Verify numa reorg used works (only on 1 NUMA node)<commit_after>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of k-par-means * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "knori.hpp" int main(int argc, char* argv[]) { constexpr size_t nrow = 50; constexpr size_t ncol = 5; constexpr size_t max_iters = 20; constexpr unsigned k = 8; constexpr unsigned nthread = 2; const std::string fn = "../../test-data/matrix_r50_c5_rrw.bin"; const std::string centroidfn = "../../test-data/init_clusters_k8_c5.bin"; // Read from disk std::cout << "Testing read from disk ..\n"; { kpmbase::kmeans_t ret = kpmbase::kmeans( fn, nrow, ncol, k, /*"/data/kmeans/r16_c3145728_k100_cw.dat", 3145728, 16, 100,*/ max_iters, numa_num_task_nodes(), nthread, NULL); ret.print(); } //Data already in-mem FULL std::cout << "Testing data only in-mem ..\n"; { std::vector<double> data(nrow*ncol); kpmbase::bin_rm_reader<double> br(fn); br.read(data); kpmbase::kmeans_t ret = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, NULL, "kmeanspp", -1, "eucl", true); ret.print(); } // Data already in-mem PRUNED std::cout << "Testing PRUNED data only in-mem ..\n"; { std::vector<double> data(nrow*ncol); kpmbase::bin_rm_reader<double> br(fn); br.read(data); kpmbase::kmeans_t ret = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, NULL); ret.print(); } std::cout << "Testing data + Centroid in-mem ..\n"; { std::vector<double> data(nrow*ncol); kpmbase::bin_rm_reader<double> br(fn); br.read(data); std::vector<double> centroids(k*ncol); kpmbase::bin_rm_reader<double> br2(centroidfn); br2.read(centroids); kpmbase::kmeans_t ret_full = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, &centroids[0], "none", -1, "eucl", true, false); ret_full.print(); //////////////////////////////////*****//////////////////////////// //////////////////////////////////*****//////////////////////////// kpmbase::kmeans_t ret_numa_full = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, &centroids[0], "none", -1, "eucl", true, true); ret_numa_full.print(); BOOST_VERIFY(ret_full == ret_numa_full); std::cout << "SUCCESS FULL. Data + Centroids in-mem (numa_opt)!\n\n"; //////////////////////////////////*****//////////////////////////// //////////////////////////////////*****//////////////////////////// std::cout << "Testing PRUNED. Data + Centroid in-mem ...\n"; kpmbase::kmeans_t ret = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, &centroids[0], "none"); ret.print(); //////////////////////////////////*****//////////////////////////// //////////////////////////////////*****//////////////////////////// std::cout << "Testing PRUNED. Data + Centroid in-mem ...\n"; kpmbase::kmeans_t ret_numa = kpmbase::kmeans( &data[0], nrow, ncol, k, max_iters, numa_num_task_nodes(), nthread, &centroids[0], "none", -1, "eucl", false, true); ret_numa.print(); BOOST_VERIFY(ret == ret_numa); std::cout << "SUCCESS PRUNED. Data + Centroids in-mem (numa_opt)!\n\n"; //////////////////////////////////*****//////////////////////////// //////////////////////////////////*****//////////////////////////// // BOOST_VERIFY(ret_full == ret_numa); // FIXME: Fails but is the same ... // std::cout << "SUCCESS PRUNED v FULL. Data + Centroids in-mem (numa_opt)!\n\n"; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "lua/state.h" #include "lua/term.h" #include "rwte/logging.h" #include "rwte/term.h" /// Term module; `term` is the global terminal object. // @module term #define LOGGER() (logging::get("luaterm")) /// Returns whether a terminal mode is set. // // @function mode // @int mode Mode flag. See values in @{modes} // @usage // is_crlf = term.mode(term.modes.MODE_CRLF) static int luaterm_mode(lua_State *l) { lua::State L(l); auto mode = static_cast<term::term_mode_enum>(L.checkinteger(1)); L.pushbool(term::g_term->mode()[mode]); return 1; } /// Sends a string to the terminal. // // @function send // @string s String to send // @usage // term.send("\025") static int luaterm_send(lua_State *l) { lua::State L(l); size_t len = 0; const char * buffer = L.checklstring(1, &len); term::g_term->send(buffer, len); return 0; } /// Initiates copy of the terminal selection to the system clipboard. // // @function clipcopy // @usage // term.clipcopy() static int luaterm_clipcopy(lua_State *l) { term::g_term->clipcopy(); return 0; } // functions for term library static const luaL_Reg term_funcs[] = { {"mode", luaterm_mode}, {"send", luaterm_send}, {"clipcopy", luaterm_clipcopy}, {nullptr, nullptr} }; static int term_openf(lua_State *l) { lua::State L(l); // make the lib (3 funcs, 1 values) L.newlib(term_funcs, 4); /// Mode flag table; maps mode flags to their integer value. // @class field // @name modes L.newtable(); #define PUSH_ENUM_FIELD(nm)\ L.pushinteger(nm); L.setfield(-2, #nm) PUSH_ENUM_FIELD(term::MODE_WRAP); PUSH_ENUM_FIELD(term::MODE_INSERT); PUSH_ENUM_FIELD(term::MODE_APPKEYPAD); PUSH_ENUM_FIELD(term::MODE_ALTSCREEN); PUSH_ENUM_FIELD(term::MODE_CRLF); PUSH_ENUM_FIELD(term::MODE_MOUSEBTN); PUSH_ENUM_FIELD(term::MODE_MOUSEMOTION); PUSH_ENUM_FIELD(term::MODE_REVERSE); PUSH_ENUM_FIELD(term::MODE_KBDLOCK); PUSH_ENUM_FIELD(term::MODE_HIDE); PUSH_ENUM_FIELD(term::MODE_ECHO); PUSH_ENUM_FIELD(term::MODE_APPCURSOR); PUSH_ENUM_FIELD(term::MODE_MOUSESGR); PUSH_ENUM_FIELD(term::MODE_8BIT); PUSH_ENUM_FIELD(term::MODE_BLINK); PUSH_ENUM_FIELD(term::MODE_FBLINK); PUSH_ENUM_FIELD(term::MODE_FOCUS); PUSH_ENUM_FIELD(term::MODE_MOUSEX10); PUSH_ENUM_FIELD(term::MODE_MOUSEMANY); PUSH_ENUM_FIELD(term::MODE_BRCKTPASTE); PUSH_ENUM_FIELD(term::MODE_PRINT); PUSH_ENUM_FIELD(term::MODE_UTF8); PUSH_ENUM_FIELD(term::MODE_SIXEL); #undef PUSH_ENUM_FIELD L.setfield(-2, "modes"); return 1; } void lua::register_luaterm(lua::State *L) { L->requiref("term", term_openf, true); L->pop(); } <commit_msg>Fixed usage of enum name / namespace in macro<commit_after>#include "lua/state.h" #include "lua/term.h" #include "rwte/logging.h" #include "rwte/term.h" /// Term module; `term` is the global terminal object. // @module term #define LOGGER() (logging::get("luaterm")) /// Returns whether a terminal mode is set. // // @function mode // @int mode Mode flag. See values in @{modes} // @usage // is_crlf = term.mode(term.modes.MODE_CRLF) static int luaterm_mode(lua_State *l) { lua::State L(l); auto mode = static_cast<term::term_mode_enum>(L.checkinteger(1)); L.pushbool(term::g_term->mode()[mode]); return 1; } /// Sends a string to the terminal. // // @function send // @string s String to send // @usage // term.send("\025") static int luaterm_send(lua_State *l) { lua::State L(l); size_t len = 0; const char * buffer = L.checklstring(1, &len); term::g_term->send(buffer, len); return 0; } /// Initiates copy of the terminal selection to the system clipboard. // // @function clipcopy // @usage // term.clipcopy() static int luaterm_clipcopy(lua_State *l) { term::g_term->clipcopy(); return 0; } // functions for term library static const luaL_Reg term_funcs[] = { {"mode", luaterm_mode}, {"send", luaterm_send}, {"clipcopy", luaterm_clipcopy}, {nullptr, nullptr} }; static int term_openf(lua_State *l) { lua::State L(l); // make the lib (3 funcs, 1 values) L.newlib(term_funcs, 4); /// Mode flag table; maps mode flags to their integer value. // @class field // @name modes L.newtable(); #define PUSH_ENUM_FIELD(nm)\ L.pushinteger(term::nm); L.setfield(-2, #nm) PUSH_ENUM_FIELD(MODE_WRAP); PUSH_ENUM_FIELD(MODE_INSERT); PUSH_ENUM_FIELD(MODE_APPKEYPAD); PUSH_ENUM_FIELD(MODE_ALTSCREEN); PUSH_ENUM_FIELD(MODE_CRLF); PUSH_ENUM_FIELD(MODE_MOUSEBTN); PUSH_ENUM_FIELD(MODE_MOUSEMOTION); PUSH_ENUM_FIELD(MODE_REVERSE); PUSH_ENUM_FIELD(MODE_KBDLOCK); PUSH_ENUM_FIELD(MODE_HIDE); PUSH_ENUM_FIELD(MODE_ECHO); PUSH_ENUM_FIELD(MODE_APPCURSOR); PUSH_ENUM_FIELD(MODE_MOUSESGR); PUSH_ENUM_FIELD(MODE_8BIT); PUSH_ENUM_FIELD(MODE_BLINK); PUSH_ENUM_FIELD(MODE_FBLINK); PUSH_ENUM_FIELD(MODE_FOCUS); PUSH_ENUM_FIELD(MODE_MOUSEX10); PUSH_ENUM_FIELD(MODE_MOUSEMANY); PUSH_ENUM_FIELD(MODE_BRCKTPASTE); PUSH_ENUM_FIELD(MODE_PRINT); PUSH_ENUM_FIELD(MODE_UTF8); PUSH_ENUM_FIELD(MODE_SIXEL); #undef PUSH_ENUM_FIELD L.setfield(-2, "modes"); return 1; } void lua::register_luaterm(lua::State *L) { L->requiref("term", term_openf, true); L->pop(); } <|endoftext|>
<commit_before>/// HEADER #include "confusion_matrix_display_adapter.h" /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_node_adapter.h> /// SYSTEM #include <QTableView> #include <QPainter> #include <QGridLayout> #include <QLabel> #include <QApplication> using namespace csapex; CSAPEX_REGISTER_NODE_ADAPTER(ConfusionMatrixDisplayAdapter, csapex::ConfusionMatrixDisplay) ConfusionMatrixTableModel::ConfusionMatrixTableModel() : dim(0) { } void ConfusionMatrixTableModel::update(const ConfusionMatrix& confusion) { int new_dim = confusion_.classes.size(); if(dim != new_dim) { beginInsertRows(QModelIndex(), dim, new_dim - 1); beginInsertColumns(QModelIndex(), dim, new_dim - 1); dim = new_dim; endInsertRows(); endInsertColumns(); } confusion_ = confusion; sum.resize(dim); for(int col = 0; col < dim; ++col) { sum[col] = 0; for(int row = 0; row < dim; ++row) { sum[col] += confusion.histogram.at(std::make_pair(row, col)); } } } int ConfusionMatrixTableModel::rowCount(const QModelIndex &parent) const { return dim; } int ConfusionMatrixTableModel::columnCount(const QModelIndex &parent) const { return dim; } QVariant ConfusionMatrixTableModel::data(const QModelIndex &index, int role) const { if(role != Qt::ForegroundRole && role != Qt::BackgroundColorRole && role != Qt::DisplayRole) { return QVariant(); } auto actual = index.column(); auto prediction = index.row(); int entry = confusion_.histogram.at(std::make_pair(actual, prediction)); if(role == Qt::DisplayRole) { return entry; } double f = entry / double(sum[actual]); static QColor min_color = QColor::fromRgb(255, 255, 255); static QColor max_color = QColor::fromRgb(0, 0, 0); int grey = std::min(255, std::max(0, int(min_color.red() * (1.0-f) + max_color.red() * f))); if (role == Qt::ForegroundRole) { int v = grey < 100 ? 255 : 0; return QVariant::fromValue(QColor::fromRgb(v,v,v)); } else { return QVariant::fromValue(QColor::fromRgb(grey,grey,grey)); } } QVariant ConfusionMatrixTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); return confusion_.classes.at(section); } ConfusionMatrixDisplayAdapter::ConfusionMatrixDisplayAdapter(NodeWorkerWeakPtr worker, std::weak_ptr<ConfusionMatrixDisplay> node, WidgetController* widget_ctrl) : NodeAdapter(worker, widget_ctrl), wrapped_(node) { auto n = wrapped_.lock(); // translate to UI thread via Qt signal trackConnection(n ->display_request.connect(std::bind(&ConfusionMatrixDisplayAdapter::displayRequest, this))); } void ConfusionMatrixDisplayAdapter::setupUi(QBoxLayout* layout) { model_ = new ConfusionMatrixTableModel; table_ = new QTableView; table_->setModel(model_); table_->showGrid(); table_->setMinimumSize(0, 0); table_->viewport()->setMinimumSize(0, 0); table_->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); QGridLayout* grid = new QGridLayout; layout->addLayout(grid); auto actual = new QLabel("actual"); grid->addWidget(actual, 0, 1); grid->addWidget(new QLabel("predicted"), 1, 0); grid->addWidget(table_, 1, 1); connect(this, SIGNAL(displayRequest()), this, SLOT(display())); } void ConfusionMatrixDisplayAdapter::display() { auto node = wrapped_.lock(); if(!node) { return; } assert(QThread::currentThread() == QApplication::instance()->thread()); model_->update(node->getConfusionMatrix()); table_->resizeColumnsToContents(); table_->resizeRowsToContents(); table_->viewport()->update(); } /// MOC #include "moc_confusion_matrix_display_adapter.cpp" <commit_msg>fixed render bug in confusion matrix display<commit_after>/// HEADER #include "confusion_matrix_display_adapter.h" /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_node_adapter.h> /// SYSTEM #include <QTableView> #include <QPainter> #include <QGridLayout> #include <QLabel> #include <QApplication> using namespace csapex; CSAPEX_REGISTER_NODE_ADAPTER(ConfusionMatrixDisplayAdapter, csapex::ConfusionMatrixDisplay) ConfusionMatrixTableModel::ConfusionMatrixTableModel() : dim(0) { } void ConfusionMatrixTableModel::update(const ConfusionMatrix& confusion) { int new_dim = confusion_.classes.size(); if(dim != new_dim) { beginInsertRows(QModelIndex(), dim, new_dim - 1); beginInsertColumns(QModelIndex(), dim, new_dim - 1); dim = new_dim; endInsertRows(); endInsertColumns(); } confusion_ = confusion; sum.resize(dim); for(int col = 0; col < dim; ++col) { sum[col] = 0; for(int row = 0; row < dim; ++row) { sum[col] += confusion.histogram.at(std::make_pair(confusion.classes[row], confusion.classes[col])); } } } int ConfusionMatrixTableModel::rowCount(const QModelIndex &parent) const { return dim; } int ConfusionMatrixTableModel::columnCount(const QModelIndex &parent) const { return dim; } QVariant ConfusionMatrixTableModel::data(const QModelIndex &index, int role) const { if(role != Qt::ForegroundRole && role != Qt::BackgroundColorRole && role != Qt::DisplayRole) { return QVariant(); } auto actual = confusion_.classes[index.column()]; auto prediction = confusion_.classes[index.row()]; int entry = confusion_.histogram.at(std::make_pair(actual, prediction)); if(role == Qt::DisplayRole) { return entry; } double f = entry / double(sum[actual]); static QColor min_color = QColor::fromRgb(255, 255, 255); static QColor max_color = QColor::fromRgb(0, 0, 0); int grey = std::min(255, std::max(0, int(min_color.red() * (1.0-f) + max_color.red() * f))); if (role == Qt::ForegroundRole) { int v = grey < 100 ? 255 : 0; return QVariant::fromValue(QColor::fromRgb(v,v,v)); } else { return QVariant::fromValue(QColor::fromRgb(grey,grey,grey)); } } QVariant ConfusionMatrixTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); return confusion_.classes.at(section); } ConfusionMatrixDisplayAdapter::ConfusionMatrixDisplayAdapter(NodeWorkerWeakPtr worker, std::weak_ptr<ConfusionMatrixDisplay> node, WidgetController* widget_ctrl) : NodeAdapter(worker, widget_ctrl), wrapped_(node) { auto n = wrapped_.lock(); // translate to UI thread via Qt signal trackConnection(n ->display_request.connect(std::bind(&ConfusionMatrixDisplayAdapter::displayRequest, this))); } void ConfusionMatrixDisplayAdapter::setupUi(QBoxLayout* layout) { model_ = new ConfusionMatrixTableModel; table_ = new QTableView; table_->setModel(model_); table_->showGrid(); table_->setMinimumSize(0, 0); table_->viewport()->setMinimumSize(0, 0); table_->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); QGridLayout* grid = new QGridLayout; layout->addLayout(grid); auto actual = new QLabel("actual"); grid->addWidget(actual, 0, 1); grid->addWidget(new QLabel("predicted"), 1, 0); grid->addWidget(table_, 1, 1); connect(this, SIGNAL(displayRequest()), this, SLOT(display())); } void ConfusionMatrixDisplayAdapter::display() { auto node = wrapped_.lock(); if(!node) { return; } assert(QThread::currentThread() == QApplication::instance()->thread()); model_->update(node->getConfusionMatrix()); table_->resizeColumnsToContents(); table_->resizeRowsToContents(); table_->viewport()->update(); } /// MOC #include "moc_confusion_matrix_display_adapter.cpp" <|endoftext|>
<commit_before><commit_msg>document SwPaM::SetMark()<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/serviceworkers/ServiceWorkerContainer.h" #include "bindings/core/v8/CallbackPromiseAdapter.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/SerializedScriptValue.h" #include "core/dom/DOMException.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/dom/MessagePort.h" #include "core/events/MessageEvent.h" #include "core/frame/LocalDOMWindow.h" #include "modules/serviceworkers/ServiceWorker.h" #include "modules/serviceworkers/ServiceWorkerContainerClient.h" #include "modules/serviceworkers/ServiceWorkerError.h" #include "modules/serviceworkers/ServiceWorkerRegistration.h" #include "platform/RuntimeEnabledFeatures.h" #include "public/platform/WebServiceWorker.h" #include "public/platform/WebServiceWorkerProvider.h" #include "public/platform/WebServiceWorkerRegistration.h" #include "public/platform/WebString.h" #include "public/platform/WebURL.h" namespace blink { // This wraps CallbackPromiseAdapter and resolves the promise with undefined // when nullptr is given to onSuccess. class GetRegistrationCallback : public WebServiceWorkerProvider::WebServiceWorkerGetRegistrationCallbacks { public: explicit GetRegistrationCallback(PassRefPtr<ScriptPromiseResolver> resolver) : m_resolver(resolver) , m_adapter(m_resolver) { } virtual ~GetRegistrationCallback() { } virtual void onSuccess(WebServiceWorkerRegistration* registration) override { if (registration) m_adapter.onSuccess(registration); else if (m_resolver->executionContext() && !m_resolver->executionContext()->activeDOMObjectsAreStopped()) m_resolver->resolve(); } virtual void onError(WebServiceWorkerError* error) override { m_adapter.onError(error); } private: RefPtr<ScriptPromiseResolver> m_resolver; CallbackPromiseAdapter<ServiceWorkerRegistration, ServiceWorkerError> m_adapter; WTF_MAKE_NONCOPYABLE(GetRegistrationCallback); }; ServiceWorkerContainer* ServiceWorkerContainer::create(ExecutionContext* executionContext) { return new ServiceWorkerContainer(executionContext); } ServiceWorkerContainer::~ServiceWorkerContainer() { ASSERT(!m_provider); } void ServiceWorkerContainer::willBeDetachedFromFrame() { if (m_provider) { m_provider->setClient(0); m_provider = nullptr; } } void ServiceWorkerContainer::trace(Visitor* visitor) { visitor->trace(m_controller); visitor->trace(m_readyRegistration); visitor->trace(m_ready); } ScriptPromise ServiceWorkerContainer::registerServiceWorker(ScriptState* scriptState, const String& url, const RegistrationOptions& options) { ASSERT(RuntimeEnabledFeatures::serviceWorkerEnabled()); RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); if (!m_provider) { resolver->reject(DOMException::create(InvalidStateError, "No associated provider is available")); return promise; } // FIXME: This should use the container's execution context, not // the callers. ExecutionContext* executionContext = scriptState->executionContext(); RefPtr<SecurityOrigin> documentOrigin = executionContext->securityOrigin(); String errorMessage; if (!documentOrigin->canAccessFeatureRequiringSecureOrigin(errorMessage)) { resolver->reject(DOMException::create(NotSupportedError, errorMessage)); return promise; } KURL pageURL = KURL(KURL(), documentOrigin->toString()); if (!pageURL.protocolIsInHTTPFamily()) { resolver->reject(DOMException::create(SecurityError, "The URL protocol of the current origin is not supported: " + pageURL.protocol())); return promise; } KURL patternURL = executionContext->completeURL(options.scope()); patternURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(patternURL)) { resolver->reject(DOMException::create(SecurityError, "The scope must match the current origin.")); return promise; } KURL scriptURL = executionContext->completeURL(url); scriptURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(scriptURL)) { resolver->reject(DOMException::create(SecurityError, "The origin of the script must match the current origin.")); return promise; } if (!patternURL.string().startsWith(scriptURL.baseAsString())) { resolver->reject(DOMException::create(SecurityError, "The scope must be under the directory of the script URL.")); return promise; } m_provider->registerServiceWorker(patternURL, scriptURL, new CallbackPromiseAdapter<ServiceWorkerRegistration, ServiceWorkerError>(resolver)); return promise; } class BooleanValue { public: typedef bool WebType; static bool take(ScriptPromiseResolver* resolver, WebType* boolean) { return *boolean; } static void dispose(WebType* boolean) { } private: BooleanValue(); }; ScriptPromise ServiceWorkerContainer::getRegistration(ScriptState* scriptState, const String& documentURL) { ASSERT(RuntimeEnabledFeatures::serviceWorkerEnabled()); RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); // FIXME: This should use the container's execution context, not // the callers. ExecutionContext* executionContext = scriptState->executionContext(); RefPtr<SecurityOrigin> documentOrigin = executionContext->securityOrigin(); String errorMessage; if (!documentOrigin->canAccessFeatureRequiringSecureOrigin(errorMessage)) { resolver->reject(DOMException::create(NotSupportedError, errorMessage)); return promise; } KURL pageURL = KURL(KURL(), documentOrigin->toString()); if (!pageURL.protocolIsInHTTPFamily()) { resolver->reject(DOMException::create(SecurityError, "The URL protocol of the current origin is not supported: " + pageURL.protocol())); return promise; } KURL completedURL = executionContext->completeURL(documentURL); completedURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(completedURL)) { resolver->reject(DOMException::create(SecurityError, "The documentURL must match the current origin.")); return promise; } m_provider->getRegistration(completedURL, new GetRegistrationCallback(resolver)); return promise; } ServiceWorkerContainer::ReadyProperty* ServiceWorkerContainer::createReadyProperty() { return new ReadyProperty(executionContext(), this, ReadyProperty::Ready); } ScriptPromise ServiceWorkerContainer::ready(ScriptState* callerState) { if (!executionContext()) return ScriptPromise(); if (!callerState->world().isMainWorld()) { // FIXME: Support .ready from isolated worlds when // ScriptPromiseProperty can vend Promises in isolated worlds. return ScriptPromise::rejectWithDOMException(callerState, DOMException::create(NotSupportedError, "'ready' is only supported in pages.")); } return m_ready->promise(callerState->world()); } // If the WebServiceWorker is up for adoption (does not have a // WebServiceWorkerProxy owner), rejects the adoption by deleting the // WebServiceWorker. static void deleteIfNoExistingOwner(WebServiceWorker* serviceWorker) { if (serviceWorker && !serviceWorker->proxy()) delete serviceWorker; } void ServiceWorkerContainer::setController(WebServiceWorker* serviceWorker) { if (!executionContext()) { deleteIfNoExistingOwner(serviceWorker); return; } m_controller = ServiceWorker::from(executionContext(), serviceWorker); } void ServiceWorkerContainer::setReadyRegistration(WebServiceWorkerRegistration* registration) { if (!executionContext()) { ServiceWorkerRegistration::dispose(registration); return; } ServiceWorkerRegistration* readyRegistration = ServiceWorkerRegistration::from(executionContext(), registration); ASSERT(readyRegistration->active()); if (m_readyRegistration) { ASSERT(m_readyRegistration == readyRegistration); ASSERT(m_ready->state() == ReadyProperty::Resolved); return; } m_readyRegistration = readyRegistration; m_ready->resolve(readyRegistration); } void ServiceWorkerContainer::dispatchMessageEvent(const WebString& message, const WebMessagePortChannelArray& webChannels) { if (!executionContext() || !executionContext()->executingWindow()) return; OwnPtrWillBeRawPtr<MessagePortArray> ports = MessagePort::toMessagePortArray(executionContext(), webChannels); RefPtr<SerializedScriptValue> value = SerializedScriptValue::createFromWire(message); executionContext()->executingWindow()->dispatchEvent(MessageEvent::create(ports.release(), value)); } ServiceWorkerContainer::ServiceWorkerContainer(ExecutionContext* executionContext) : ContextLifecycleObserver(executionContext) , m_provider(0) { if (!executionContext) return; m_ready = createReadyProperty(); if (ServiceWorkerContainerClient* client = ServiceWorkerContainerClient::from(executionContext)) { m_provider = client->provider(); if (m_provider) m_provider->setClient(this); } } } // namespace blink <commit_msg>ServiceWorker: Add null check in ServiceWorkerContainer::getRegistration()<commit_after>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/serviceworkers/ServiceWorkerContainer.h" #include "bindings/core/v8/CallbackPromiseAdapter.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/SerializedScriptValue.h" #include "core/dom/DOMException.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/dom/MessagePort.h" #include "core/events/MessageEvent.h" #include "core/frame/LocalDOMWindow.h" #include "modules/serviceworkers/ServiceWorker.h" #include "modules/serviceworkers/ServiceWorkerContainerClient.h" #include "modules/serviceworkers/ServiceWorkerError.h" #include "modules/serviceworkers/ServiceWorkerRegistration.h" #include "platform/RuntimeEnabledFeatures.h" #include "public/platform/WebServiceWorker.h" #include "public/platform/WebServiceWorkerProvider.h" #include "public/platform/WebServiceWorkerRegistration.h" #include "public/platform/WebString.h" #include "public/platform/WebURL.h" namespace blink { // This wraps CallbackPromiseAdapter and resolves the promise with undefined // when nullptr is given to onSuccess. class GetRegistrationCallback : public WebServiceWorkerProvider::WebServiceWorkerGetRegistrationCallbacks { public: explicit GetRegistrationCallback(PassRefPtr<ScriptPromiseResolver> resolver) : m_resolver(resolver) , m_adapter(m_resolver) { } virtual ~GetRegistrationCallback() { } virtual void onSuccess(WebServiceWorkerRegistration* registration) override { if (registration) m_adapter.onSuccess(registration); else if (m_resolver->executionContext() && !m_resolver->executionContext()->activeDOMObjectsAreStopped()) m_resolver->resolve(); } virtual void onError(WebServiceWorkerError* error) override { m_adapter.onError(error); } private: RefPtr<ScriptPromiseResolver> m_resolver; CallbackPromiseAdapter<ServiceWorkerRegistration, ServiceWorkerError> m_adapter; WTF_MAKE_NONCOPYABLE(GetRegistrationCallback); }; ServiceWorkerContainer* ServiceWorkerContainer::create(ExecutionContext* executionContext) { return new ServiceWorkerContainer(executionContext); } ServiceWorkerContainer::~ServiceWorkerContainer() { ASSERT(!m_provider); } void ServiceWorkerContainer::willBeDetachedFromFrame() { if (m_provider) { m_provider->setClient(0); m_provider = nullptr; } } void ServiceWorkerContainer::trace(Visitor* visitor) { visitor->trace(m_controller); visitor->trace(m_readyRegistration); visitor->trace(m_ready); } ScriptPromise ServiceWorkerContainer::registerServiceWorker(ScriptState* scriptState, const String& url, const RegistrationOptions& options) { ASSERT(RuntimeEnabledFeatures::serviceWorkerEnabled()); RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); if (!m_provider) { resolver->reject(DOMException::create(InvalidStateError, "The document is in an invalid state.")); return promise; } // FIXME: This should use the container's execution context, not // the callers. ExecutionContext* executionContext = scriptState->executionContext(); RefPtr<SecurityOrigin> documentOrigin = executionContext->securityOrigin(); String errorMessage; if (!documentOrigin->canAccessFeatureRequiringSecureOrigin(errorMessage)) { resolver->reject(DOMException::create(NotSupportedError, errorMessage)); return promise; } KURL pageURL = KURL(KURL(), documentOrigin->toString()); if (!pageURL.protocolIsInHTTPFamily()) { resolver->reject(DOMException::create(SecurityError, "The URL protocol of the current origin is not supported: " + pageURL.protocol())); return promise; } KURL patternURL = executionContext->completeURL(options.scope()); patternURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(patternURL)) { resolver->reject(DOMException::create(SecurityError, "The scope must match the current origin.")); return promise; } KURL scriptURL = executionContext->completeURL(url); scriptURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(scriptURL)) { resolver->reject(DOMException::create(SecurityError, "The origin of the script must match the current origin.")); return promise; } if (!patternURL.string().startsWith(scriptURL.baseAsString())) { resolver->reject(DOMException::create(SecurityError, "The scope must be under the directory of the script URL.")); return promise; } m_provider->registerServiceWorker(patternURL, scriptURL, new CallbackPromiseAdapter<ServiceWorkerRegistration, ServiceWorkerError>(resolver)); return promise; } class BooleanValue { public: typedef bool WebType; static bool take(ScriptPromiseResolver* resolver, WebType* boolean) { return *boolean; } static void dispose(WebType* boolean) { } private: BooleanValue(); }; ScriptPromise ServiceWorkerContainer::getRegistration(ScriptState* scriptState, const String& documentURL) { ASSERT(RuntimeEnabledFeatures::serviceWorkerEnabled()); RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); if (!m_provider) { resolver->reject(DOMException::create(InvalidStateError, "The document is in an invalid state.")); return promise; } // FIXME: This should use the container's execution context, not // the callers. ExecutionContext* executionContext = scriptState->executionContext(); RefPtr<SecurityOrigin> documentOrigin = executionContext->securityOrigin(); String errorMessage; if (!documentOrigin->canAccessFeatureRequiringSecureOrigin(errorMessage)) { resolver->reject(DOMException::create(NotSupportedError, errorMessage)); return promise; } KURL pageURL = KURL(KURL(), documentOrigin->toString()); if (!pageURL.protocolIsInHTTPFamily()) { resolver->reject(DOMException::create(SecurityError, "The URL protocol of the current origin is not supported: " + pageURL.protocol())); return promise; } KURL completedURL = executionContext->completeURL(documentURL); completedURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(completedURL)) { resolver->reject(DOMException::create(SecurityError, "The documentURL must match the current origin.")); return promise; } m_provider->getRegistration(completedURL, new GetRegistrationCallback(resolver)); return promise; } ServiceWorkerContainer::ReadyProperty* ServiceWorkerContainer::createReadyProperty() { return new ReadyProperty(executionContext(), this, ReadyProperty::Ready); } ScriptPromise ServiceWorkerContainer::ready(ScriptState* callerState) { if (!executionContext()) return ScriptPromise(); if (!callerState->world().isMainWorld()) { // FIXME: Support .ready from isolated worlds when // ScriptPromiseProperty can vend Promises in isolated worlds. return ScriptPromise::rejectWithDOMException(callerState, DOMException::create(NotSupportedError, "'ready' is only supported in pages.")); } return m_ready->promise(callerState->world()); } // If the WebServiceWorker is up for adoption (does not have a // WebServiceWorkerProxy owner), rejects the adoption by deleting the // WebServiceWorker. static void deleteIfNoExistingOwner(WebServiceWorker* serviceWorker) { if (serviceWorker && !serviceWorker->proxy()) delete serviceWorker; } void ServiceWorkerContainer::setController(WebServiceWorker* serviceWorker) { if (!executionContext()) { deleteIfNoExistingOwner(serviceWorker); return; } m_controller = ServiceWorker::from(executionContext(), serviceWorker); } void ServiceWorkerContainer::setReadyRegistration(WebServiceWorkerRegistration* registration) { if (!executionContext()) { ServiceWorkerRegistration::dispose(registration); return; } ServiceWorkerRegistration* readyRegistration = ServiceWorkerRegistration::from(executionContext(), registration); ASSERT(readyRegistration->active()); if (m_readyRegistration) { ASSERT(m_readyRegistration == readyRegistration); ASSERT(m_ready->state() == ReadyProperty::Resolved); return; } m_readyRegistration = readyRegistration; m_ready->resolve(readyRegistration); } void ServiceWorkerContainer::dispatchMessageEvent(const WebString& message, const WebMessagePortChannelArray& webChannels) { if (!executionContext() || !executionContext()->executingWindow()) return; OwnPtrWillBeRawPtr<MessagePortArray> ports = MessagePort::toMessagePortArray(executionContext(), webChannels); RefPtr<SerializedScriptValue> value = SerializedScriptValue::createFromWire(message); executionContext()->executingWindow()->dispatchEvent(MessageEvent::create(ports.release(), value)); } ServiceWorkerContainer::ServiceWorkerContainer(ExecutionContext* executionContext) : ContextLifecycleObserver(executionContext) , m_provider(0) { if (!executionContext) return; m_ready = createReadyProperty(); if (ServiceWorkerContainerClient* client = ServiceWorkerContainerClient::from(executionContext)) { m_provider = client->provider(); if (m_provider) m_provider->setClient(this); } } } // namespace blink <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Collision/TriangleMeshTriangleMeshDcdContact.h" #include "SurgSim/Collision/CollisionPair.h" #include "SurgSim/Collision/Representation.h" #include "SurgSim/DataStructures/TriangleMesh.h" #include "SurgSim/DataStructures/TriangleMeshBase.h" #include "SurgSim/Math/Geometry.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/RigidTransform.h" using SurgSim::DataStructures::TriangleMesh; using SurgSim::DataStructures::TriangleMeshBase; using SurgSim::Math::MeshShape; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; namespace SurgSim { namespace Collision { TriangleMeshTriangleMeshDcdContact::TriangleMeshTriangleMeshDcdContact() { } std::pair<int,int> TriangleMeshTriangleMeshDcdContact::getShapeTypes() { return std::pair<int,int>(SurgSim::Math::SHAPE_TYPE_MESH, SurgSim::Math::SHAPE_TYPE_MESH); } static void assertIsCoplanar(const Vector3d& triangle0, const Vector3d& triangle1, const Vector3d& triangle2, const Vector3d& point) { SURGSIM_ASSERT(abs((triangle2 - triangle0).dot((triangle1 - triangle0).cross(point - triangle2))) < SurgSim::Math::Geometry::ScalarEpsilon) << "Coplanarity failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", pt " << point.transpose(); } static void assertIsConstrained(const Vector3d& point, const Vector3d& triangle0, const Vector3d& triangle1, const Vector3d& triangle2, const Vector3d& normal) { Vector3d barycentricCoordinate; SurgSim::Math::barycentricCoordinates(point, triangle0, triangle1, triangle2, normal, &barycentricCoordinate); SURGSIM_ASSERT(barycentricCoordinate.x() >= -SurgSim::Math::Geometry::ScalarEpsilon && barycentricCoordinate.x() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon) << "Constrained failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", n " << normal.transpose() << ", pt " << point.transpose(); SURGSIM_ASSERT(barycentricCoordinate.y() >= -SurgSim::Math::Geometry::ScalarEpsilon && barycentricCoordinate.y() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon) << "Constrained failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", n " << normal.transpose() << ", pt " << point.transpose(); SURGSIM_ASSERT(barycentricCoordinate.z() >= -SurgSim::Math::Geometry::ScalarEpsilon && barycentricCoordinate.z() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon) << "Constrained failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", n " << normal.transpose() << ", pt " << point.transpose(); } static void assertIsCorrectNormalAndDepth(const Vector3d& normal, double penetrationDepth, const Vector3d& triangleA0, const Vector3d& triangleA1, const Vector3d& triangleA2, const Vector3d& triangleB0, const Vector3d& triangleB1, const Vector3d& triangleB2) { Vector3d correction = normal * (penetrationDepth + 2 * SurgSim::Math::Geometry::DistanceEpsilon); Vector3d temp1, temp2; double expectedDistance = SurgSim::Math::distanceTriangleTriangle( (Vector3d)(triangleA0 + correction), (Vector3d)(triangleA1 + correction), (Vector3d)(triangleA2 + correction), triangleB0, triangleB1, triangleB2, &temp1, &temp2); SURGSIM_ASSERT(expectedDistance > 0.0) << "Normal and depth failed with: " << "calcD " << expectedDistance << ", n " << normal.transpose() << ", d " << penetrationDepth << ", a0 " << triangleA0.transpose() << ", a1 " << triangleA1.transpose() << ", a2 " << triangleA2.transpose() << ", b0 " << triangleB0.transpose() << ", b1 " << triangleB1.transpose() << ", b2 " << triangleB2.transpose(); SURGSIM_ASSERT(expectedDistance <= 2.1 * SurgSim::Math::Geometry::DistanceEpsilon) << "Normal and depth failed with: " << "calcD " << expectedDistance << ", n " << normal.transpose() << ", d " << penetrationDepth << ", a0 " << triangleA0.transpose() << ", a1 " << triangleA1.transpose() << ", a2 " << triangleA2.transpose() << ", b0 " << triangleB0.transpose() << ", b1 " << triangleB1.transpose() << ", b2 " << triangleB2.transpose(); } void TriangleMeshTriangleMeshDcdContact::doCalculateContact(std::shared_ptr<CollisionPair> pair) { std::shared_ptr<Representation> representationMeshA = pair->getFirst(); std::shared_ptr<Representation> representationMeshB = pair->getSecond(); std::shared_ptr<TriangleMesh> collisionMeshA = std::static_pointer_cast<MeshShape>(representationMeshA->getShape())->getMesh(); std::shared_ptr<TriangleMesh> collisionMeshB = std::static_pointer_cast<MeshShape>(representationMeshB->getShape())->getMesh(); RigidTransform3d globalCoordinatesFromMeshACoordinates = representationMeshA->getPose(); RigidTransform3d globalCoordinatesFromMeshBCoordinates = representationMeshB->getPose(); RigidTransform3d meshBCoordinatesFromGlobalCoordinates = globalCoordinatesFromMeshBCoordinates.inverse(); RigidTransform3d meshBCoordinatesFromMeshACoordinates = meshBCoordinatesFromGlobalCoordinates * globalCoordinatesFromMeshACoordinates; double depth = 0.0; Vector3d normal; Vector3d penetrationPointA, penetrationPointB; for (size_t i = 0; i < collisionMeshA->getNumTriangles(); ++i) { // The triangleA vertices. const Vector3d& triangleA0InLocalB = meshBCoordinatesFromMeshACoordinates * collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[0]); const Vector3d& triangleA1InLocalB = meshBCoordinatesFromMeshACoordinates * collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[1]); const Vector3d& triangleA2InLocalB = meshBCoordinatesFromMeshACoordinates * collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[2]); const Vector3d& normalAInLocalB = meshBCoordinatesFromMeshACoordinates.linear() * collisionMeshA->getNormal(i); if (normalAInLocalB.isZero()) { continue; } for (size_t j = 0; j < collisionMeshB->getNumTriangles(); ++j) { const Vector3d& normalB = collisionMeshB->getNormal(j); if (normalB.isZero()) { continue; } // The triangleB vertices. const Vector3d& triangleB0 = collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[0]); const Vector3d& triangleB1 = collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[1]); const Vector3d& triangleB2 = collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[2]); // Check if the triangles intersect. if (SurgSim::Math::calculateContactTriangleTriangle(triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, triangleB0, triangleB1, triangleB2, normalAInLocalB, normalB, &depth, &penetrationPointA, &penetrationPointB, &normal)) { #ifdef SURGSIM_DEBUG_TRIANGLETRIANGLECONTACT assertIsCoplanar(triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, penetrationPointA); assertIsCoplanar(triangleB0, triangleB1, triangleB2, penetrationPointB); assertIsConstrained( penetrationPointA, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, normalAInLocalB); assertIsConstrained(penetrationPointB, triangleB0, triangleB1, triangleB2, normalB); assertIsCorrectNormalAndDepth(normal, depth, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, triangleB0, triangleB1, triangleB2); #endif // Create the contact. std::pair<Location, Location> penetrationPoints; penetrationPoints.first.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates * penetrationPointA); penetrationPoints.second.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates * penetrationPointB); pair->addContact(std::abs(depth), globalCoordinatesFromMeshBCoordinates.linear() * normal, penetrationPoints); } } } } }; // namespace Collision }; // namespace SurgSim <commit_msg>TriangleMeshTriangleMeshDcdContact, fix GCC unused warning<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Collision/TriangleMeshTriangleMeshDcdContact.h" #include "SurgSim/Collision/CollisionPair.h" #include "SurgSim/Collision/Representation.h" #include "SurgSim/DataStructures/TriangleMesh.h" #include "SurgSim/DataStructures/TriangleMeshBase.h" #include "SurgSim/Math/Geometry.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/RigidTransform.h" using SurgSim::DataStructures::TriangleMesh; using SurgSim::DataStructures::TriangleMeshBase; using SurgSim::Math::MeshShape; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; namespace SurgSim { namespace Collision { TriangleMeshTriangleMeshDcdContact::TriangleMeshTriangleMeshDcdContact() { } std::pair<int,int> TriangleMeshTriangleMeshDcdContact::getShapeTypes() { return std::pair<int,int>(SurgSim::Math::SHAPE_TYPE_MESH, SurgSim::Math::SHAPE_TYPE_MESH); } #ifdef SURGSIM_DEBUG_TRIANGLETRIANGLECONTACT static void assertIsCoplanar(const Vector3d& triangle0, const Vector3d& triangle1, const Vector3d& triangle2, const Vector3d& point) { SURGSIM_ASSERT(abs((triangle2 - triangle0).dot((triangle1 - triangle0).cross(point - triangle2))) < SurgSim::Math::Geometry::ScalarEpsilon) << "Coplanarity failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", pt " << point.transpose(); } static void assertIsConstrained(const Vector3d& point, const Vector3d& triangle0, const Vector3d& triangle1, const Vector3d& triangle2, const Vector3d& normal) { Vector3d barycentricCoordinate; SurgSim::Math::barycentricCoordinates(point, triangle0, triangle1, triangle2, normal, &barycentricCoordinate); SURGSIM_ASSERT(barycentricCoordinate.x() >= -SurgSim::Math::Geometry::ScalarEpsilon && barycentricCoordinate.x() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon) << "Constrained failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", n " << normal.transpose() << ", pt " << point.transpose(); SURGSIM_ASSERT(barycentricCoordinate.y() >= -SurgSim::Math::Geometry::ScalarEpsilon && barycentricCoordinate.y() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon) << "Constrained failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", n " << normal.transpose() << ", pt " << point.transpose(); SURGSIM_ASSERT(barycentricCoordinate.z() >= -SurgSim::Math::Geometry::ScalarEpsilon && barycentricCoordinate.z() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon) << "Constrained failed with: " << "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose() << ", n " << normal.transpose() << ", pt " << point.transpose(); } static void assertIsCorrectNormalAndDepth(const Vector3d& normal, double penetrationDepth, const Vector3d& triangleA0, const Vector3d& triangleA1, const Vector3d& triangleA2, const Vector3d& triangleB0, const Vector3d& triangleB1, const Vector3d& triangleB2) { Vector3d correction = normal * (penetrationDepth + 2 * SurgSim::Math::Geometry::DistanceEpsilon); Vector3d temp1, temp2; double expectedDistance = SurgSim::Math::distanceTriangleTriangle( (Vector3d)(triangleA0 + correction), (Vector3d)(triangleA1 + correction), (Vector3d)(triangleA2 + correction), triangleB0, triangleB1, triangleB2, &temp1, &temp2); SURGSIM_ASSERT(expectedDistance > 0.0) << "Normal and depth failed with: " << "calcD " << expectedDistance << ", n " << normal.transpose() << ", d " << penetrationDepth << ", a0 " << triangleA0.transpose() << ", a1 " << triangleA1.transpose() << ", a2 " << triangleA2.transpose() << ", b0 " << triangleB0.transpose() << ", b1 " << triangleB1.transpose() << ", b2 " << triangleB2.transpose(); SURGSIM_ASSERT(expectedDistance <= 2.1 * SurgSim::Math::Geometry::DistanceEpsilon) << "Normal and depth failed with: " << "calcD " << expectedDistance << ", n " << normal.transpose() << ", d " << penetrationDepth << ", a0 " << triangleA0.transpose() << ", a1 " << triangleA1.transpose() << ", a2 " << triangleA2.transpose() << ", b0 " << triangleB0.transpose() << ", b1 " << triangleB1.transpose() << ", b2 " << triangleB2.transpose(); } #endif // SURGSIM_DEBUG_TRIANGLETRIANGLECONTACT void TriangleMeshTriangleMeshDcdContact::doCalculateContact(std::shared_ptr<CollisionPair> pair) { std::shared_ptr<Representation> representationMeshA = pair->getFirst(); std::shared_ptr<Representation> representationMeshB = pair->getSecond(); std::shared_ptr<TriangleMesh> collisionMeshA = std::static_pointer_cast<MeshShape>(representationMeshA->getShape())->getMesh(); std::shared_ptr<TriangleMesh> collisionMeshB = std::static_pointer_cast<MeshShape>(representationMeshB->getShape())->getMesh(); RigidTransform3d globalCoordinatesFromMeshACoordinates = representationMeshA->getPose(); RigidTransform3d globalCoordinatesFromMeshBCoordinates = representationMeshB->getPose(); RigidTransform3d meshBCoordinatesFromGlobalCoordinates = globalCoordinatesFromMeshBCoordinates.inverse(); RigidTransform3d meshBCoordinatesFromMeshACoordinates = meshBCoordinatesFromGlobalCoordinates * globalCoordinatesFromMeshACoordinates; double depth = 0.0; Vector3d normal; Vector3d penetrationPointA, penetrationPointB; for (size_t i = 0; i < collisionMeshA->getNumTriangles(); ++i) { // The triangleA vertices. const Vector3d& triangleA0InLocalB = meshBCoordinatesFromMeshACoordinates * collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[0]); const Vector3d& triangleA1InLocalB = meshBCoordinatesFromMeshACoordinates * collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[1]); const Vector3d& triangleA2InLocalB = meshBCoordinatesFromMeshACoordinates * collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[2]); const Vector3d& normalAInLocalB = meshBCoordinatesFromMeshACoordinates.linear() * collisionMeshA->getNormal(i); if (normalAInLocalB.isZero()) { continue; } for (size_t j = 0; j < collisionMeshB->getNumTriangles(); ++j) { const Vector3d& normalB = collisionMeshB->getNormal(j); if (normalB.isZero()) { continue; } // The triangleB vertices. const Vector3d& triangleB0 = collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[0]); const Vector3d& triangleB1 = collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[1]); const Vector3d& triangleB2 = collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[2]); // Check if the triangles intersect. if (SurgSim::Math::calculateContactTriangleTriangle(triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, triangleB0, triangleB1, triangleB2, normalAInLocalB, normalB, &depth, &penetrationPointA, &penetrationPointB, &normal)) { #ifdef SURGSIM_DEBUG_TRIANGLETRIANGLECONTACT assertIsCoplanar(triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, penetrationPointA); assertIsCoplanar(triangleB0, triangleB1, triangleB2, penetrationPointB); assertIsConstrained( penetrationPointA, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, normalAInLocalB); assertIsConstrained(penetrationPointB, triangleB0, triangleB1, triangleB2, normalB); assertIsCorrectNormalAndDepth(normal, depth, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, triangleB0, triangleB1, triangleB2); #endif // Create the contact. std::pair<Location, Location> penetrationPoints; penetrationPoints.first.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates * penetrationPointA); penetrationPoints.second.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates * penetrationPointB); pair->addContact(std::abs(depth), globalCoordinatesFromMeshBCoordinates.linear() * normal, penetrationPoints); } } } } }; // namespace Collision }; // namespace SurgSim <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013-2016, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file /// Tests for the CombiningOutputComponent class. #include <boost/chrono.hpp> #include <boost/thread.hpp> #include <gtest/gtest.h> #include <memory> #include <set> #include <string> #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Framework/FrameworkConvert.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/SceneElement.h" #include "SurgSim/Input/CombiningOutputComponent.h" #include "SurgSim/Input/CommonDevice.h" #include "SurgSim/Input/InputManager.h" #include "SurgSim/Input/OutputComponent.h" #include "SurgSim/Math/Vector.h" namespace { const double ERROR_EPSILON = 1e-7; auto DO_NOTHING_FUNCTOR = [](const std::vector<std::shared_ptr<SurgSim::Input::OutputComponent>>&, SurgSim::DataStructures::DataGroup*) {return false; }; /// Device that exposes pullOutput and getOutputData. class MockDevice : public SurgSim::Input::CommonDevice { public: MockDevice(const std::string& name) : SurgSim::Input::CommonDevice(name) { } ~MockDevice() { } using CommonDevice::pullOutput; using CommonDevice::getOutputData; bool initialize() override { return true; } bool isInitialized() const override { return true; } bool finalize() override { return true; } }; }; TEST(CombiningOutputComponentTest, NoOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); EXPECT_FALSE(mockDevice->pullOutput()); } TEST(CombiningOutputComponentTest, DuplicateOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output1 = std::make_shared<SurgSim::Input::OutputComponent>("output1"); auto output2 = std::make_shared<SurgSim::Input::OutputComponent>("output2"); outputs.push_back(output1); outputs.push_back(output2); outputs.push_back(output1); outputs.push_back(output2); outputs.push_back(output2); combiningOutputComponent->setOutputs(outputs); auto storedOutputs = combiningOutputComponent->getOutputs(); ASSERT_EQ(2, storedOutputs.size()); EXPECT_EQ(output1, storedOutputs[0]); EXPECT_EQ(output2, storedOutputs[1]); } TEST(CombiningOutputComponentTest, EmptyOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; outputs.push_back(std::make_shared<SurgSim::Input::OutputComponent>("output1")); outputs.push_back(std::make_shared<SurgSim::Input::OutputComponent>("output2")); combiningOutputComponent->setOutputs(outputs); ASSERT_EQ(outputs, combiningOutputComponent->getOutputs()); EXPECT_FALSE(mockDevice->pullOutput()); } TEST(CombiningOutputComponentTest, OneNonEmptyOutput) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output = std::make_shared<SurgSim::Input::OutputComponent>("output1"); outputs.push_back(output); combiningOutputComponent->setOutputs(outputs); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); builder.addBoolean("extraData"); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); data.booleans().set("extraData", true); output->setData(data); ASSERT_TRUE(mockDevice->pullOutput()); SurgSim::DataStructures::DataGroup actualData = mockDevice->getOutputData(); ASSERT_FALSE(actualData.isEmpty()); SurgSim::Math::Vector3d actualForce; ASSERT_TRUE(actualData.vectors().get(SurgSim::DataStructures::Names::FORCE, &actualForce)); EXPECT_TRUE(actualForce.isApprox(initialForce)); EXPECT_FALSE(actualData.booleans().hasEntry("extraData")); EXPECT_ANY_THROW(combiningOutputComponent->setData(data)); } TEST(CombiningOutputComponentTest, SetCombiner) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); combiningOutputComponent->setCombiner(DO_NOTHING_FUNCTOR); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output1 = std::make_shared<SurgSim::Input::OutputComponent>("output1"); outputs.push_back(output1); auto output2 = std::make_shared<SurgSim::Input::OutputComponent>("output2"); outputs.push_back(output2); auto output3 = std::make_shared<SurgSim::Input::OutputComponent>("output3"); outputs.push_back(output3); combiningOutputComponent->setOutputs(outputs); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); output1->setData(data); output3->setData(data); EXPECT_FALSE(mockDevice->pullOutput()); } TEST(CombiningOutputComponentTest, MultipleOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output1 = std::make_shared<SurgSim::Input::OutputComponent>("output1"); outputs.push_back(output1); auto output2 = std::make_shared<SurgSim::Input::OutputComponent>("output2"); outputs.push_back(output2); auto output3 = std::make_shared<SurgSim::Input::OutputComponent>("output3"); outputs.push_back(output3); combiningOutputComponent->setOutputs(outputs); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); output1->setData(data); output3->setData(data); ASSERT_TRUE(mockDevice->pullOutput()); SurgSim::DataStructures::DataGroup actualData = mockDevice->getOutputData(); ASSERT_FALSE(actualData.isEmpty()); SurgSim::Math::Vector3d actualForce; ASSERT_TRUE(actualData.vectors().get(SurgSim::DataStructures::Names::FORCE, &actualForce)); EXPECT_TRUE(actualForce.isApprox(2.0 * initialForce)); // Check subsequent calls to pullOutput will correctly handle non-asserting DataGroup assignment. EXPECT_NO_THROW(mockDevice->pullOutput()); // Check first OutputComponent going away. outputs.clear(); output1.reset(); EXPECT_TRUE(mockDevice->pullOutput()); EXPECT_EQ(2, combiningOutputComponent->getOutputs().size()); } TEST(CombiningOutputComponentTest, Serialization) { auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt"); auto inputManager = std::make_shared<SurgSim::Input::InputManager>(); runtime->addManager(inputManager); runtime->addSceneElements("CombiningOutputComponent.yaml"); auto element = runtime->getScene()->getSceneElement("element"); ASSERT_NE(element, nullptr); auto outputs = element->getComponents<SurgSim::Input::OutputComponent>(); ASSERT_EQ(outputs.size(), 4); std::shared_ptr<SurgSim::Input::CombiningOutputComponent> combiningOutputComponent; for (size_t i = 0; i < outputs.size(); ++i) { combiningOutputComponent = std::dynamic_pointer_cast<SurgSim::Input::CombiningOutputComponent>(outputs[i]); if (combiningOutputComponent != nullptr) { outputs.erase(outputs.begin() + i); break; } } ASSERT_NE(combiningOutputComponent, nullptr); std::set<std::shared_ptr<SurgSim::Framework::Component>> componentsFromElement; componentsFromElement.insert(outputs.begin(), outputs.end()); std::set<std::shared_ptr<SurgSim::Framework::Component>> componentsFromCombiner; auto actualOutputs = combiningOutputComponent->getOutputs(); componentsFromCombiner.insert(actualOutputs.begin(), actualOutputs.end()); ASSERT_EQ(componentsFromElement, componentsFromCombiner); EXPECT_EQ("output1", actualOutputs[0]->getName()); EXPECT_EQ("output2", actualOutputs[1]->getName()); EXPECT_EQ("output3", actualOutputs[2]->getName()); auto mockDevice = std::make_shared<MockDevice>("device"); inputManager->addDevice(mockDevice); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); std::static_pointer_cast<SurgSim::Input::OutputComponent>(actualOutputs[0])->setData(data); std::static_pointer_cast<SurgSim::Input::OutputComponent>(actualOutputs[2])->setData(data); runtime->start(true); runtime->step(); runtime->step(); runtime->step(); ASSERT_TRUE(mockDevice->pullOutput()); SurgSim::DataStructures::DataGroup actualData = mockDevice->getOutputData(); ASSERT_FALSE(actualData.isEmpty()); SurgSim::Math::Vector3d actualForce; ASSERT_TRUE(actualData.vectors().get(SurgSim::DataStructures::Names::FORCE, &actualForce)); EXPECT_TRUE(actualForce.isApprox(2.0 * initialForce)); YAML::Node node; EXPECT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*combiningOutputComponent)); EXPECT_TRUE(node.IsMap()); std::shared_ptr<SurgSim::Input::CombiningOutputComponent> newComponent; EXPECT_NO_THROW(newComponent = std::dynamic_pointer_cast<SurgSim::Input::CombiningOutputComponent>( node.as<std::shared_ptr<SurgSim::Framework::Component>>())); ASSERT_NE(newComponent, nullptr); auto newOutputs = newComponent->getValue<std::vector<std::shared_ptr<SurgSim::Framework::Component>>>("Outputs"); for (auto newOutput : newOutputs) { EXPECT_NE(std::dynamic_pointer_cast<SurgSim::Input::OutputComponent>(newOutput), nullptr); } } <commit_msg>Add sleep after runtime->step in UnitTest<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013-2016, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file /// Tests for the CombiningOutputComponent class. #include <boost/chrono.hpp> #include <boost/thread.hpp> #include <gtest/gtest.h> #include <memory> #include <set> #include <string> #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Framework/FrameworkConvert.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/SceneElement.h" #include "SurgSim/Input/CombiningOutputComponent.h" #include "SurgSim/Input/CommonDevice.h" #include "SurgSim/Input/InputManager.h" #include "SurgSim/Input/OutputComponent.h" #include "SurgSim/Math/Vector.h" namespace { const double ERROR_EPSILON = 1e-7; auto DO_NOTHING_FUNCTOR = [](const std::vector<std::shared_ptr<SurgSim::Input::OutputComponent>>&, SurgSim::DataStructures::DataGroup*) {return false; }; /// Device that exposes pullOutput and getOutputData. class MockDevice : public SurgSim::Input::CommonDevice { public: MockDevice(const std::string& name) : SurgSim::Input::CommonDevice(name) { } ~MockDevice() { } using CommonDevice::pullOutput; using CommonDevice::getOutputData; bool initialize() override { return true; } bool isInitialized() const override { return true; } bool finalize() override { return true; } }; }; TEST(CombiningOutputComponentTest, NoOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); EXPECT_FALSE(mockDevice->pullOutput()); } TEST(CombiningOutputComponentTest, DuplicateOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output1 = std::make_shared<SurgSim::Input::OutputComponent>("output1"); auto output2 = std::make_shared<SurgSim::Input::OutputComponent>("output2"); outputs.push_back(output1); outputs.push_back(output2); outputs.push_back(output1); outputs.push_back(output2); outputs.push_back(output2); combiningOutputComponent->setOutputs(outputs); auto storedOutputs = combiningOutputComponent->getOutputs(); ASSERT_EQ(2, storedOutputs.size()); EXPECT_EQ(output1, storedOutputs[0]); EXPECT_EQ(output2, storedOutputs[1]); } TEST(CombiningOutputComponentTest, EmptyOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; outputs.push_back(std::make_shared<SurgSim::Input::OutputComponent>("output1")); outputs.push_back(std::make_shared<SurgSim::Input::OutputComponent>("output2")); combiningOutputComponent->setOutputs(outputs); ASSERT_EQ(outputs, combiningOutputComponent->getOutputs()); EXPECT_FALSE(mockDevice->pullOutput()); } TEST(CombiningOutputComponentTest, OneNonEmptyOutput) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output = std::make_shared<SurgSim::Input::OutputComponent>("output1"); outputs.push_back(output); combiningOutputComponent->setOutputs(outputs); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); builder.addBoolean("extraData"); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); data.booleans().set("extraData", true); output->setData(data); ASSERT_TRUE(mockDevice->pullOutput()); SurgSim::DataStructures::DataGroup actualData = mockDevice->getOutputData(); ASSERT_FALSE(actualData.isEmpty()); SurgSim::Math::Vector3d actualForce; ASSERT_TRUE(actualData.vectors().get(SurgSim::DataStructures::Names::FORCE, &actualForce)); EXPECT_TRUE(actualForce.isApprox(initialForce)); EXPECT_FALSE(actualData.booleans().hasEntry("extraData")); EXPECT_ANY_THROW(combiningOutputComponent->setData(data)); } TEST(CombiningOutputComponentTest, SetCombiner) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); combiningOutputComponent->setCombiner(DO_NOTHING_FUNCTOR); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output1 = std::make_shared<SurgSim::Input::OutputComponent>("output1"); outputs.push_back(output1); auto output2 = std::make_shared<SurgSim::Input::OutputComponent>("output2"); outputs.push_back(output2); auto output3 = std::make_shared<SurgSim::Input::OutputComponent>("output3"); outputs.push_back(output3); combiningOutputComponent->setOutputs(outputs); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); output1->setData(data); output3->setData(data); EXPECT_FALSE(mockDevice->pullOutput()); } TEST(CombiningOutputComponentTest, MultipleOutputs) { auto combiningOutputComponent = std::make_shared<SurgSim::Input::CombiningOutputComponent>("combiner"); auto mockDevice = std::make_shared<MockDevice>("device"); mockDevice->setOutputProducer(combiningOutputComponent); std::vector<std::shared_ptr<SurgSim::Framework::Component>> outputs; auto output1 = std::make_shared<SurgSim::Input::OutputComponent>("output1"); outputs.push_back(output1); auto output2 = std::make_shared<SurgSim::Input::OutputComponent>("output2"); outputs.push_back(output2); auto output3 = std::make_shared<SurgSim::Input::OutputComponent>("output3"); outputs.push_back(output3); combiningOutputComponent->setOutputs(outputs); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); output1->setData(data); output3->setData(data); ASSERT_TRUE(mockDevice->pullOutput()); SurgSim::DataStructures::DataGroup actualData = mockDevice->getOutputData(); ASSERT_FALSE(actualData.isEmpty()); SurgSim::Math::Vector3d actualForce; ASSERT_TRUE(actualData.vectors().get(SurgSim::DataStructures::Names::FORCE, &actualForce)); EXPECT_TRUE(actualForce.isApprox(2.0 * initialForce)); // Check subsequent calls to pullOutput will correctly handle non-asserting DataGroup assignment. EXPECT_NO_THROW(mockDevice->pullOutput()); // Check first OutputComponent going away. outputs.clear(); output1.reset(); EXPECT_TRUE(mockDevice->pullOutput()); EXPECT_EQ(2, combiningOutputComponent->getOutputs().size()); } TEST(CombiningOutputComponentTest, Serialization) { auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt"); auto inputManager = std::make_shared<SurgSim::Input::InputManager>(); runtime->addManager(inputManager); runtime->addSceneElements("CombiningOutputComponent.yaml"); auto element = runtime->getScene()->getSceneElement("element"); ASSERT_NE(element, nullptr); auto outputs = element->getComponents<SurgSim::Input::OutputComponent>(); ASSERT_EQ(outputs.size(), 4); std::shared_ptr<SurgSim::Input::CombiningOutputComponent> combiningOutputComponent; for (size_t i = 0; i < outputs.size(); ++i) { combiningOutputComponent = std::dynamic_pointer_cast<SurgSim::Input::CombiningOutputComponent>(outputs[i]); if (combiningOutputComponent != nullptr) { outputs.erase(outputs.begin() + i); break; } } ASSERT_NE(combiningOutputComponent, nullptr); std::set<std::shared_ptr<SurgSim::Framework::Component>> componentsFromElement; componentsFromElement.insert(outputs.begin(), outputs.end()); std::set<std::shared_ptr<SurgSim::Framework::Component>> componentsFromCombiner; auto actualOutputs = combiningOutputComponent->getOutputs(); componentsFromCombiner.insert(actualOutputs.begin(), actualOutputs.end()); ASSERT_EQ(componentsFromElement, componentsFromCombiner); EXPECT_EQ("output1", actualOutputs[0]->getName()); EXPECT_EQ("output2", actualOutputs[1]->getName()); EXPECT_EQ("output3", actualOutputs[2]->getName()); auto mockDevice = std::make_shared<MockDevice>("device"); inputManager->addDevice(mockDevice); SurgSim::DataStructures::DataGroupBuilder builder; builder.addVector(SurgSim::DataStructures::Names::FORCE); SurgSim::DataStructures::DataGroup data = builder.createData(); auto initialForce = SurgSim::Math::Vector3d(0.89, 0.0, -324.67); data.vectors().set(SurgSim::DataStructures::Names::FORCE, initialForce); std::static_pointer_cast<SurgSim::Input::OutputComponent>(actualOutputs[0])->setData(data); std::static_pointer_cast<SurgSim::Input::OutputComponent>(actualOutputs[2])->setData(data); runtime->start(true); runtime->step(); runtime->step(); runtime->step(); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); runtime->stop(); ASSERT_TRUE(mockDevice->pullOutput()); SurgSim::DataStructures::DataGroup actualData = mockDevice->getOutputData(); ASSERT_FALSE(actualData.isEmpty()); SurgSim::Math::Vector3d actualForce; ASSERT_TRUE(actualData.vectors().get(SurgSim::DataStructures::Names::FORCE, &actualForce)); EXPECT_TRUE(actualForce.isApprox(2.0 * initialForce)); YAML::Node node; EXPECT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*combiningOutputComponent)); EXPECT_TRUE(node.IsMap()); std::shared_ptr<SurgSim::Input::CombiningOutputComponent> newComponent; EXPECT_NO_THROW(newComponent = std::dynamic_pointer_cast<SurgSim::Input::CombiningOutputComponent>( node.as<std::shared_ptr<SurgSim::Framework::Component>>())); ASSERT_NE(newComponent, nullptr); auto newOutputs = newComponent->getValue<std::vector<std::shared_ptr<SurgSim::Framework::Component>>>("Outputs"); for (auto newOutput : newOutputs) { EXPECT_NE(std::dynamic_pointer_cast<SurgSim::Input::OutputComponent>(newOutput), nullptr); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkQuadEdgeMeshCountingCellsTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif int itkQuadEdgeMeshCountingCellsTest( int , char *[] ) { return EXIT_SUCCESS; } <commit_msg>ENH: Including itkMacro.h in order to get the EXIT_SUCCESS symbol. Waiting for Alex to commit the real test.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkQuadEdgeMeshCountingCellsTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkMacro.h" int itkQuadEdgeMeshCountingCellsTest( int , char *[] ) { return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkTransformFileReaderWriterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkTransformFileReader.h" #include "itkTransformFileWriter.h" #include "itkTransformIOFactory.h" #include "itkAffineTransform.h" #include "itkTransformFactory.h" #include "itkScaleVersor3DTransform.h" #include "itkBSplineDeformableTransform.h" int itkTransformFileReaderWriterTest( int argc, char *argv[] ) { itk::TransformFactory<itk::ScaleVersor3DTransform<float> >::RegisterDefaultTransforms(); itk::TransformFactory<itk::ScaleVersor3DTransform<float> >::RegisterTransform (); if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputTransformFile "; std::cerr << " outputTransformFile "; std::cerr << std::endl; return EXIT_FAILURE; } itk::TransformIOBase::Pointer transformIO = itk::TransformIOFactory::CreateTransformIO(argv[1],itk::TransformIOFactory::ReadMode); transformIO->Print(std::cout,0); transformIO = itk::TransformIOFactory::CreateTransformIO(argv[1],itk::TransformIOFactory::WriteMode); transformIO->Print(std::cout,0); typedef itk::TransformFileReader TransformReaderType; typedef itk::TransformFileWriter TransformWriterType; typedef itk::AffineTransform<double, 3> AffineTransformType; typedef AffineTransformType::Pointer AffineTransformPointer; TransformReaderType::Pointer transformReader = TransformReaderType::New(); TransformWriterType::Pointer transformWriter = TransformWriterType::New(); std::cout << "Reader class = " << transformReader->GetNameOfClass() << " Writer class = " << transformWriter->GetNameOfClass() << "Reader base = " << dynamic_cast<TransformReaderType::Superclass *>(transformReader.GetPointer())->GetNameOfClass() << dynamic_cast<TransformWriterType::Superclass *>(transformWriter.GetPointer())->GetNameOfClass() << std::endl; std::cout << "Loading Transform: " << argv[1] << std::endl; try { // first try, to trigger exception transformReader->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no filename)" << std::endl << excp << std::endl; } transformReader->SetFileName("transform.garbage"); try { // first try, trigger exception for transformio not found transformReader->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no transformio that can read file)" << excp << std::endl; } //DEBUG std::cout << "Reading " << argv[1] << std::endl; transformReader->SetFileName( argv[1] ); std::cout << "Filename: " << transformReader->GetFileName() << std::endl; transformReader->Update(); typedef TransformReaderType::TransformListType * TransformListType; TransformListType transforms = transformReader->GetTransformList(); TransformReaderType::TransformListType::const_iterator tit = transforms->begin(); AffineTransformPointer affine_transform1 = AffineTransformType::New(); if( !strcmp((*tit)->GetNameOfClass(),"AffineTransform") ) { AffineTransformPointer affine_read = static_cast<AffineTransformType*>((*tit).GetPointer()); affine_transform1 = dynamic_cast< AffineTransformType * >( affine_read.GetPointer() ); if( affine_transform1 ) { std::cout << "Successful Read" << std::endl; } else { std::cerr << "Error reading Affine Transform" << std::endl; return EXIT_FAILURE; } } // // Now Write the transform: // try { // first try, to trigger exception transformWriter->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no filename)" << std::endl << excp << std::endl; } transformWriter->SetFileName("transform.garbage"); try { // first try, trigger exception for transformio not found transformWriter->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no transformio that can write file)" << excp << std::endl; } transformWriter->SetFileName( argv[2] ); std::cout << "Filename: " << transformWriter->GetFileName() << std::endl; unsigned int precision(transformWriter->GetPrecision()); std::cout << "transform writer precision " << precision; transformWriter->SetPrecision(precision); bool appendMode = transformWriter->GetAppendMode(); std::cout << " Append mode " << appendMode; transformWriter->SetAppendOn(); transformWriter->SetAppendOff(); transformWriter->SetAppendMode(appendMode); transformWriter->SetInput( affine_transform1 ); transformWriter->Update(); // // And read it again to compare // TransformReaderType::Pointer transformReader2 = TransformReaderType::New(); std::cout << "Loading Transform back: " << argv[2] << std::endl; transformReader2->SetFileName( argv[2] ); transformReader2->Update(); TransformListType transforms2 = transformReader2->GetTransformList(); TransformReaderType::TransformListType::const_iterator tit2 = transforms2->begin(); AffineTransformPointer affine_transform2; if( !strcmp((*tit2)->GetNameOfClass(),"AffineTransform") ) { typedef AffineTransformType::Pointer AffineTransformPointer; AffineTransformPointer affine_read = static_cast<AffineTransformType*>((*tit).GetPointer()); affine_transform2 = dynamic_cast< AffineTransformType * >( affine_read.GetPointer() ); if( affine_transform2 ) { std::cout << "Successful Read" << std::endl; } else { std::cerr << "Error reading Affine Transform" << std::endl; return EXIT_FAILURE; } } const double tolerance = 1e-6; std::cout << "Testing STANDARD parameters" << std::endl; AffineTransformType::ParametersType parameters1 = affine_transform1->GetParameters(); AffineTransformType::ParametersType parameters2 = affine_transform2->GetParameters(); for( unsigned int k = 0; k < parameters1.Size(); k++ ) { if( vnl_math_abs( parameters1[k] - parameters2[k] ) > tolerance ) { std::cerr << "ERROR: parameter " << k << " differs above tolerace" << std::endl; std::cerr << "Expected parameters = " << parameters1 << std::endl; std::cerr << "but Found parameters = " << parameters2 << std::endl; return EXIT_FAILURE; } } std::cout << "Testing FIXED parameters" << std::endl; AffineTransformType::ParametersType fixedparameters1 = affine_transform1->GetFixedParameters(); AffineTransformType::ParametersType fixedparameters2 = affine_transform2->GetFixedParameters(); for( unsigned int j = 0; j < fixedparameters1.Size(); j++ ) { if( vnl_math_abs( fixedparameters1[j] - fixedparameters2[j] ) > tolerance ) { std::cerr << "ERROR: parameter " << j << " differs above tolerace" << std::endl; std::cerr << "Expected parameters = " << fixedparameters1 << std::endl; std::cerr << "but Found parameters = " << fixedparameters2 << std::endl; return EXIT_FAILURE; } } std::cout << "Test PASSED!" << std::endl; return EXIT_SUCCESS; } <commit_msg>Removed unnecessary static_casts.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkTransformFileReaderWriterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkTransformFileReader.h" #include "itkTransformFileWriter.h" #include "itkTransformIOFactory.h" #include "itkAffineTransform.h" #include "itkTransformFactory.h" #include "itkScaleVersor3DTransform.h" #include "itkBSplineDeformableTransform.h" int itkTransformFileReaderWriterTest( int argc, char *argv[] ) { itk::TransformFactory<itk::ScaleVersor3DTransform<float> >::RegisterDefaultTransforms(); itk::TransformFactory<itk::ScaleVersor3DTransform<float> >::RegisterTransform (); if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputTransformFile "; std::cerr << " outputTransformFile "; std::cerr << std::endl; return EXIT_FAILURE; } itk::TransformIOBase::Pointer transformIO = itk::TransformIOFactory::CreateTransformIO(argv[1],itk::TransformIOFactory::ReadMode); transformIO->Print(std::cout,0); transformIO = itk::TransformIOFactory::CreateTransformIO(argv[1],itk::TransformIOFactory::WriteMode); transformIO->Print(std::cout,0); typedef itk::TransformFileReader TransformReaderType; typedef itk::TransformFileWriter TransformWriterType; typedef itk::AffineTransform<double, 3> AffineTransformType; typedef AffineTransformType::Pointer AffineTransformPointer; TransformReaderType::Pointer transformReader = TransformReaderType::New(); TransformWriterType::Pointer transformWriter = TransformWriterType::New(); std::cout << "Reader class = " << transformReader->GetNameOfClass() << " Writer class = " << transformWriter->GetNameOfClass() << "Reader base = " << dynamic_cast<TransformReaderType::Superclass *>(transformReader.GetPointer())->GetNameOfClass() << dynamic_cast<TransformWriterType::Superclass *>(transformWriter.GetPointer())->GetNameOfClass() << std::endl; std::cout << "Loading Transform: " << argv[1] << std::endl; try { // first try, to trigger exception transformReader->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no filename)" << std::endl << excp << std::endl; } transformReader->SetFileName("transform.garbage"); try { // first try, trigger exception for transformio not found transformReader->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no transformio that can read file)" << excp << std::endl; } //DEBUG std::cout << "Reading " << argv[1] << std::endl; transformReader->SetFileName( argv[1] ); std::cout << "Filename: " << transformReader->GetFileName() << std::endl; transformReader->Update(); typedef TransformReaderType::TransformListType * TransformListType; typedef TransformReaderType::TransformPointer TransformPointer; TransformListType transforms = transformReader->GetTransformList(); TransformReaderType::TransformListType::const_iterator tit = transforms->begin(); AffineTransformPointer affine_transform1 = AffineTransformType::New(); if( !strcmp((*tit)->GetNameOfClass(),"AffineTransform") ) { TransformPointer transform_read = tit->GetPointer(); affine_transform1 = dynamic_cast< AffineTransformType * >( transform_read.GetPointer() ); if( affine_transform1 ) { std::cout << "Successful Read" << std::endl; } else { std::cerr << "Error reading Affine Transform" << std::endl; return EXIT_FAILURE; } } // // Now Write the transform: // try { // first try, to trigger exception transformWriter->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no filename)" << std::endl << excp << std::endl; } transformWriter->SetFileName("transform.garbage"); try { // first try, trigger exception for transformio not found transformWriter->Update(); } catch(itk::ExceptionObject &excp) { std::cerr << "Expected exception (no transformio that can write file)" << excp << std::endl; } transformWriter->SetFileName( argv[2] ); std::cout << "Filename: " << transformWriter->GetFileName() << std::endl; unsigned int precision(transformWriter->GetPrecision()); std::cout << "transform writer precision " << precision; transformWriter->SetPrecision(precision); bool appendMode = transformWriter->GetAppendMode(); std::cout << " Append mode " << appendMode; transformWriter->SetAppendOn(); transformWriter->SetAppendOff(); transformWriter->SetAppendMode(appendMode); transformWriter->SetInput( affine_transform1 ); transformWriter->Update(); // // And read it again to compare // TransformReaderType::Pointer transformReader2 = TransformReaderType::New(); std::cout << "Loading Transform back: " << argv[2] << std::endl; transformReader2->SetFileName( argv[2] ); transformReader2->Update(); TransformListType transforms2 = transformReader2->GetTransformList(); TransformReaderType::TransformListType::const_iterator tit2 = transforms2->begin(); AffineTransformPointer affine_transform2; if( !strcmp((*tit2)->GetNameOfClass(),"AffineTransform") ) { typedef AffineTransformType::Pointer AffineTransformPointer; TransformPointer transform_read = tit->GetPointer(); affine_transform2 = dynamic_cast< AffineTransformType * >( transform_read.GetPointer() ); if( affine_transform2 ) { std::cout << "Successful Read" << std::endl; } else { std::cerr << "Error reading Affine Transform" << std::endl; return EXIT_FAILURE; } } const double tolerance = 1e-6; std::cout << "Testing STANDARD parameters" << std::endl; AffineTransformType::ParametersType parameters1 = affine_transform1->GetParameters(); AffineTransformType::ParametersType parameters2 = affine_transform2->GetParameters(); for( unsigned int k = 0; k < parameters1.Size(); k++ ) { if( vnl_math_abs( parameters1[k] - parameters2[k] ) > tolerance ) { std::cerr << "ERROR: parameter " << k << " differs above tolerace" << std::endl; std::cerr << "Expected parameters = " << parameters1 << std::endl; std::cerr << "but Found parameters = " << parameters2 << std::endl; return EXIT_FAILURE; } } std::cout << "Testing FIXED parameters" << std::endl; AffineTransformType::ParametersType fixedparameters1 = affine_transform1->GetFixedParameters(); AffineTransformType::ParametersType fixedparameters2 = affine_transform2->GetFixedParameters(); for( unsigned int j = 0; j < fixedparameters1.Size(); j++ ) { if( vnl_math_abs( fixedparameters1[j] - fixedparameters2[j] ) > tolerance ) { std::cerr << "ERROR: parameter " << j << " differs above tolerace" << std::endl; std::cerr << "Expected parameters = " << fixedparameters1 << std::endl; std::cerr << "but Found parameters = " << fixedparameters2 << std::endl; return EXIT_FAILURE; } } std::cout << "Test PASSED!" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// 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 "webkit/appcache/appcache_backend_impl.h" #include "base/logging.h" #include "webkit/appcache/web_application_cache_host_impl.h" namespace appcache { AppCacheBackendImpl::~AppCacheBackendImpl() { // TODO(michaeln): if (service_) service_->UnregisterFrontend(frontend_); } void AppCacheBackendImpl::Initialize(AppCacheService* service, AppCacheFrontend* frontend) { DCHECK(!service_ && !frontend_ && frontend); // DCHECK(service) service_ = service; frontend_ = frontend; // TODO(michaeln): service_->RegisterFrontend(frontend_); } void AppCacheBackendImpl::RegisterHost(int host_id) { // TODO(michaeln): plumb to service } void AppCacheBackendImpl::UnregisterHost(int host_id) { // TODO(michaeln): plumb to service } void AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { // TODO(michaeln): plumb to service frontend_->OnCacheSelected(host_id, kNoCacheId, UNCACHED); } void AppCacheBackendImpl::MarkAsForeignEntry( int host_id, const GURL& document_url, int64 cache_document_was_loaded_from) { // TODO(michaeln): plumb to service } Status AppCacheBackendImpl::GetStatus(int host_id) { // TODO(michaeln): plumb to service return UNCACHED; } bool AppCacheBackendImpl::StartUpdate(int host_id) { // TODO(michaeln): plumb to service return false; } bool AppCacheBackendImpl::SwapCache(int host_id) { // TODO(michaeln): plumb to service return false; } } // namespace appcache<commit_msg>Add missing newline at end of file. BUG=none TEST=none<commit_after>// 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 "webkit/appcache/appcache_backend_impl.h" #include "base/logging.h" #include "webkit/appcache/web_application_cache_host_impl.h" namespace appcache { AppCacheBackendImpl::~AppCacheBackendImpl() { // TODO(michaeln): if (service_) service_->UnregisterFrontend(frontend_); } void AppCacheBackendImpl::Initialize(AppCacheService* service, AppCacheFrontend* frontend) { DCHECK(!service_ && !frontend_ && frontend); // DCHECK(service) service_ = service; frontend_ = frontend; // TODO(michaeln): service_->RegisterFrontend(frontend_); } void AppCacheBackendImpl::RegisterHost(int host_id) { // TODO(michaeln): plumb to service } void AppCacheBackendImpl::UnregisterHost(int host_id) { // TODO(michaeln): plumb to service } void AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { // TODO(michaeln): plumb to service frontend_->OnCacheSelected(host_id, kNoCacheId, UNCACHED); } void AppCacheBackendImpl::MarkAsForeignEntry( int host_id, const GURL& document_url, int64 cache_document_was_loaded_from) { // TODO(michaeln): plumb to service } Status AppCacheBackendImpl::GetStatus(int host_id) { // TODO(michaeln): plumb to service return UNCACHED; } bool AppCacheBackendImpl::StartUpdate(int host_id) { // TODO(michaeln): plumb to service return false; } bool AppCacheBackendImpl::SwapCache(int host_id) { // TODO(michaeln): plumb to service return false; } } // namespace appcache <|endoftext|>
<commit_before>#include "ros/ros.h" #include "sensor_msgs/LaserScan.h" #include "nav_msgs/MapMetaData.h" #include "nav_msgs/OccupancyGrid.h" #include <sstream> //Global var of map meta data nav_msgs::MapMetaData mmd; void chatterCallback(const sensor_msgs::LaserScan::ConstPtr& msg) { //Figure out if I need to use another pointer for this msg nav_msgs::OccupancyGrid newGrid = OGridFromLScan(msg, mmd); //remake publisher? or just constantly update a global map that then gets pushed each spin? chatter_pub.publish(newGrid); } //This is where the work gets done nav_msgs::OccupancyGrid OGridFromLScan(sensor_msgs::LaserScan lmsg, nav_msgs::MapMetaData mapmetad) { } int main(int argc, char **argv) { ros::init(argc, argv, "scantomap"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("scan_data", 10, chatterCallback); ros::Publisher chatter_pub = n.advertise<nav_msgs::OccupancyGrid>("map_data", 1, true); ros::spin(); return 0; } <commit_msg>putting it into a class<commit_after>#include "ros/ros.h" #include "sensor_msgs/LaserScan.h" #include "nav_msgs/MapMetaData.h" #include "nav_msgs/OccupancyGrid.h" #include <sstream> //Global var of map meta data nav_msgs::MapMetaData mmd; class oGridMaker { ros::NodeHandle n; void initialize(this) { ros::Publisher chatter_pub = n.advertise<nav_msgs::OccupancyGrid>("map_data", 1, true); ros::Subscriber sub = n.subscribe("scan_data", 10, this.chatterCallback); } //this is where the work gets done nav_msgs::OccupancyGrid OGridFromLScan(const sensor_msgs::LaserScan::ConstPtr& msg, nav_msgs::MapMetaData mapmetad) { } void chatterCallback(const sensor_msgs::LaserScan::ConstPtr& msg) { //Figure out if I need to use another pointer for this msg nav_msgs::OccupancyGrid newGrid = OGridFromLScan(msg, mmd); //remake publisher? or just constantly update a global map that then gets pushed each spin? chatter_pub.publish(newGrid); } } ogmaker; int main(int argc, char **argv) { ros::init(argc, argv, "scantomap"); ogmaker.initialize(); //ros::NodeHandle n; //ros::Publisher chatter_pub = n.advertise<nav_msgs::OccupancyGrid>("map_data", 1, true); //ros::Subscriber sub = n.subscribe("scan_data", 10, chatterCallback); ros::spin(); return 0; } <|endoftext|>
<commit_before>#include "ros/ros.h" #include "std_msgs/Time.h" #include "std_msgs/Float32.h" #include "std_msgs/UInt32.h" #include "geometry_msgs/Quaternion.h" #include "geometry_msgs/Point.h" #include "geometry_msgs/Pose.h" #include "sensor_msgs/LaserScan.h" #include "nav_msgs/MapMetaData.h" #include "nav_msgs/OccupancyGrid.h" #include <sstream> #include "math.h" #include "stdio.h" class oGridMaker { private: ros::NodeHandle n; ros::Publisher mapper_pub; ros::Subscriber sub; nav_msgs::MapMetaData mmd; nav_msgs::OccupancyGrid mapGrid; public: oGridMaker() { ROS_INFO("inside constructor"); mapper_pub = n.advertise<nav_msgs::OccupancyGrid>("map_eric", 10, true); // or scannerCallBack sub = n.subscribe("scan", 10, &oGridMaker::scannerCallBack, this); //make map meta data mmd.map_load_time = ros::Time::now(); mmd.resolution = .10; mmd.width = 100; mmd.height = 50; mmd.origin = createPose(); mapGrid.info = mmd; std::vector<signed char> unkdata (5000,-1); mapGrid.data = unkdata; mapper_pub.publish(mapGrid); ROS_INFO("filling in with unknown"); } geometry_msgs::Pose createPose() { geometry_msgs::Point thisp; thisp.x = -1.0; thisp.y = -5.0; thisp.z = 0.0; geometry_msgs::Quaternion thisq; thisq.x = 0.0; thisq.y = 0.0; thisq.z = 0.0; thisq.w = 0.0; geometry_msgs::Pose thispose; thispose.position = thisp; thispose.orientation = thisq; ROS_INFO("created a pose"); return thispose; } //this is where the work gets done void OGridFromLScan(const sensor_msgs::LaserScan::ConstPtr& msg) { //ROS_INFO("inside gfroms"); //update time mmd.map_load_time = msg->header.stamp; //angle to this scan, with distance, should determine which tiles it hit on as filled //number of for (int i=0; i < msg->ranges.size(); i++) { float thisangle = msg->angle_min + i*msg->angle_increment; ROS_INFO("this angle %f", thisangle); float thisrange = msg->ranges[i]; ROS_INFO("this range %f", thisrange); if (thisrange > msg->range_min && thisrange < msg->range_max) { float x = sin(thisangle)*thisrange; float y = cos(thisangle)*thisrange; x = x + 1.0; y = y + 5.0; int ix = int(x); int iy = int(y); //find the position on the occupancy grid updatePosOccGrid(ix,iy); //downgrade grids between that range and my position //updateNegOccGrid(thisrange,thisangle); } } mapGrid.info = mmd; } void updatePosOccGrid(int x, int y) { ROS_INFO("inside pos"); updateOccGrid(x,y,1, mapGrid.data); } void updateNegOccGrid(float range, float angle) { ROS_INFO("inside neg"); //subtract confidence from grids between that grid and my position //get the new range (subtract one grid length from my range based on the angle) range -= .1; if (range > 0) { ROS_INFO("this is the range %f",range); ROS_INFO("this is the angle %f", angle); float x = sin(angle)*range; float y = cos(angle)*range; int ix = int(x); int iy = int(y); //this grid is between the hit range and my position, so I think it is empty updateOccGrid(ix,iy,-1, mapGrid.data); //recursively call until I get to my position if (ix > 1 && iy > 5) { updateNegOccGrid(range,angle); } } } void updateOccGrid(int x, int y, int change, std::vector<signed char> thisdata) { //add confidence to grid that range hit in int grid = x*100 + y; thisdata[grid]+= change; ROS_INFO("updating map grids %d", grid); ROS_INFO("this is the val %d", thisdata[grid]); if (thisdata[grid] > 100) { thisdata[grid] = 100; } else if (thisdata[grid] < 0) { thisdata[grid] = 0; } mapGrid.data = thisdata; } void scannerCallBack(const sensor_msgs::LaserScan::ConstPtr& msg) { //ROS_INFO("Inside Callback"); OGridFromLScan(msg); mapper_pub.publish(mapGrid); } }; int main(int argc, char **argv) { ros::init(argc, argv, "scantomap"); oGridMaker ogm = oGridMaker(); //ogmaker.initialize(nh); //ros::Publisher chatter_pub = n.advertise<nav_msgs::OccupancyGrid>("map_data", 1, true); //ros::Subscriber sub = n.subscribe("scan_data", 10, chatterCallback); ros::spin(); return 0; } <commit_msg>most recent version<commit_after>#include "ros/ros.h" #include "std_msgs/Time.h" #include "std_msgs/Float32.h" #include "std_msgs/UInt32.h" #include "geometry_msgs/Quaternion.h" #include "geometry_msgs/Point.h" #include "geometry_msgs/Pose.h" #include "sensor_msgs/LaserScan.h" #include "nav_msgs/MapMetaData.h" #include "nav_msgs/OccupancyGrid.h" #include <sstream> #include "math.h" #include "stdio.h" class oGridMaker { private: ros::NodeHandle n; ros::Publisher mapper_pub; ros::Subscriber sub; nav_msgs::MapMetaData mmd; nav_msgs::OccupancyGrid mapGrid; public: oGridMaker() { ROS_INFO("inside constructor"); mapper_pub = n.advertise<nav_msgs::OccupancyGrid>("map_eric", 10, true); // or scannerCallBack sub = n.subscribe("scan", 10, &oGridMaker::scannerCallBack, this); //make map meta data mmd.map_load_time = ros::Time::now(); mmd.resolution = .10; mmd.width = 50; mmd.height = 50; mmd.origin = createPose(); mapGrid.info = mmd; std::vector<signed char> unkdata (2500,-1); mapGrid.data = unkdata; mapper_pub.publish(mapGrid); ROS_INFO("filling in with unknown"); } geometry_msgs::Pose createPose() { geometry_msgs::Point thisp; thisp.x = -2.0; thisp.y = 0.0; thisp.z = 0.0; geometry_msgs::Quaternion thisq; thisq.x = 0.0; thisq.y = 0.0; thisq.z = 0.0; thisq.w = 0.0; geometry_msgs::Pose thispose; thispose.position = thisp; thispose.orientation = thisq; ROS_INFO("created a pose"); return thispose; } //this is where the work gets done void OGridFromLScan(const sensor_msgs::LaserScan::ConstPtr& msg) { //ROS_INFO("inside gfroms"); //update time mmd.map_load_time = msg->header.stamp; //angle to this scan, with distance, should determine which tiles it hit on as filled //number of for (int i=0; i < msg->ranges.size(); i++) { float thisangle = msg->angle_min + i*msg->angle_increment; ROS_INFO("this angle %f", thisangle); float thisrange = msg->ranges[i]; ROS_INFO("this range %f", thisrange); if (thisrange > msg->range_min && thisrange < msg->range_max) { float x = sin(thisangle)*thisrange *1; float y = cos(thisangle)*thisrange * 1; x = x + 10.0; y = y + 20.0; int ix = int(x); int iy = int(y); //find the position on the occupancy grid updatePosOccGrid(ix,iy); //downgrade grids between that range and my position updateNegOccGrid(thisrange,thisangle); } } mapGrid.info = mmd; } void updatePosOccGrid(int x, int y) { ROS_INFO("inside pos"); updateOccGrid(x,y,10, mapGrid.data); } void updateNegOccGrid(float range, float angle) { ROS_INFO("inside neg"); //subtract confidence from grids between that grid and my position //get the new range (subtract one grid length from my range based on the angle) range -= .1; if (range > 0) { ROS_INFO("this is the range %f",range); ROS_INFO("this is the angle %f", angle); float x = sin(angle)*range; float y = cos(angle)*range; int ix = int(x); int iy = int(y); //this grid is between the hit range and my position, so I think it is empty updateOccGrid(ix,iy,-10, mapGrid.data); //recursively call until I get to my position if (ix > 1 && iy > 5) { updateNegOccGrid(range,angle); } } } void updateOccGrid(int x, int y, int change, std::vector<signed char> thisdata) { //add confidence to grid that range hit in int grid = x*100 + y; thisdata[grid]+= change; ROS_INFO("updating map grids %d", grid); ROS_INFO("this is the val %d", thisdata[grid]); if (thisdata[grid] > 100) { thisdata[grid] = 100; } else if (thisdata[grid] < 0) { thisdata[grid] = 0; } mapGrid.data = thisdata; } void scannerCallBack(const sensor_msgs::LaserScan::ConstPtr& msg) { //ROS_INFO("Inside Callback"); OGridFromLScan(msg); mapper_pub.publish(mapGrid); } }; int main(int argc, char **argv) { ros::init(argc, argv, "scantomap"); oGridMaker ogm = oGridMaker(); //ogmaker.initialize(nh); //ros::Publisher chatter_pub = n.advertise<nav_msgs::OccupancyGrid>("map_data", 1, true); //ros::Subscriber sub = n.subscribe("scan_data", 10, chatterCallback); ros::spin(); return 0; } <|endoftext|>
<commit_before><commit_msg>Make GetSelectionMaster virtual<commit_after><|endoftext|>
<commit_before>#ifndef BLUETOE_CHARACTERISTIC_VALUE_HPP #define BLUETOE_CHARACTERISTIC_VALUE_HPP #include <bluetoe/options.hpp> #include <bluetoe/attribute.hpp> namespace bluetoe { namespace details { struct characteristic_value_meta_type {}; struct characteristic_parameter_meta_type {}; struct characteristic_value_declaration_parameter {}; struct client_characteristic_configuration_parameter {}; } /** * @brief if added as option to a characteristic, read access is removed from the characteristic * * Even if read access was the only remaining access type, the characterist will not be readable. * * Example: * @code std::uint32_t simple_value = 0xaabbccdd; bluetoe::characteristic< bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >, bluetoe::bind_characteristic_value< std::uint32_t, &simple_value >, bluetoe::no_read_access > > * @endcode * @sa characteristic */ class no_read_access {}; /** * @brief if added as option to a characteristic, write access is removed from the characteristic * * Even if write access was the only remaining access type, the characterist will not be writeable. * * Example: * @code std::uint32_t simple_value = 0xaabbccdd; bluetoe::characteristic< bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >, bluetoe::bind_characteristic_value< std::uint32_t, &simple_value >, bluetoe::no_write_access > > * @endcode * @sa characteristic */ class no_write_access {}; /** * @brief adds the ability to notify this characteristic. * * When a characteristic gets notified, the current value of the characteristic will be send to all * connected clients that have subscribed for notifications. * @sa server::notify */ struct notify { /** @cond HIDDEN_SYMBOLS */ struct meta_type : details::client_characteristic_configuration_parameter, details::characteristic_parameter_meta_type {}; /** @endcond */ }; /** * @brief a very simple device to bind a characteristic to a global variable to provide access to the characteristic value */ template < typename T, T* Ptr > class bind_characteristic_value { public: /** * @cond HIDDEN_SYMBOLS * use a new type to mixin the options given to characteristic */ template < typename ... Options > class value_impl { public: static constexpr bool has_read_access = !details::has_option< no_read_access, Options... >::value; static constexpr bool has_write_access = !std::is_const< T >::value && !details::has_option< no_write_access, Options... >::value; static constexpr bool has_notifcation = details::has_option< notify, Options... >::value; static details::attribute_access_result characteristic_value_access( details::attribute_access_arguments&, std::uint16_t attribute_handle ); static bool is_this( const void* value ); private: static details::attribute_access_result characteristic_value_read_access( details::attribute_access_arguments&, const std::true_type& ); static details::attribute_access_result characteristic_value_read_access( details::attribute_access_arguments&, const std::false_type& ); static details::attribute_access_result characteristic_value_write_access( details::attribute_access_arguments&, const std::true_type& ); static details::attribute_access_result characteristic_value_write_access( details::attribute_access_arguments&, const std::false_type& ); }; struct meta_type : details::characteristic_value_meta_type, details::characteristic_value_declaration_parameter {}; /** @endcond */ }; // implementation /** @cond HIDDEN_SYMBOLS */ template < typename T, T* Ptr > template < typename ... Options > details::attribute_access_result bind_characteristic_value< T, Ptr >::value_impl< Options... >::characteristic_value_access( details::attribute_access_arguments& args, std::uint16_t attribute_handle ) { if ( args.type == details::attribute_access_type::read ) { return characteristic_value_read_access( args, std::integral_constant< bool, has_read_access >() ); } else if ( args.type == details::attribute_access_type::write ) { return characteristic_value_write_access( args, std::integral_constant< bool, has_write_access >() ); } return details::attribute_access_result::write_not_permitted; } template < typename T, T* Ptr > template < typename ... Options > details::attribute_access_result bind_characteristic_value< T, Ptr >::value_impl< Options... >::characteristic_value_read_access( details::attribute_access_arguments& args, const std::true_type& ) { if ( args.buffer_offset > sizeof( T ) ) return details::attribute_access_result::invalid_offset; args.buffer_size = std::min< std::size_t >( args.buffer_size, sizeof( T ) - args.buffer_offset ); const std::uint8_t* const ptr = static_cast< const std::uint8_t* >( static_cast< const void* >( Ptr ) ) + args.buffer_offset; std::copy( ptr, ptr + args.buffer_size, args.buffer ); return args.buffer_size == sizeof( T ) - args.buffer_offset ? details::attribute_access_result::success : details::attribute_access_result::read_truncated; } template < typename T, T* Ptr > template < typename ... Options > details::attribute_access_result bind_characteristic_value< T, Ptr >::value_impl< Options... >::characteristic_value_read_access( details::attribute_access_arguments&, const std::false_type& ) { return details::attribute_access_result::read_not_permitted; } template < typename T, T* Ptr > template < typename ... Options > details::attribute_access_result bind_characteristic_value< T, Ptr >::value_impl< Options... >::characteristic_value_write_access( details::attribute_access_arguments& args, const std::true_type& ) { if ( args.buffer_offset > sizeof( T ) ) return details::attribute_access_result::invalid_offset; if ( args.buffer_size + args.buffer_offset > sizeof( T ) ) return details::attribute_access_result::write_overflow; args.buffer_size = std::min< std::size_t >( args.buffer_size, sizeof( T ) - args.buffer_offset ); std::uint8_t* const ptr = static_cast< std::uint8_t* >( static_cast< void* >( Ptr ) ); std::copy( args.buffer, args.buffer + args.buffer_size, ptr + args.buffer_offset ); return details::attribute_access_result::success; } template < typename T, T* Ptr > template < typename ... Options > details::attribute_access_result bind_characteristic_value< T, Ptr >::value_impl< Options... >::characteristic_value_write_access( details::attribute_access_arguments&, const std::false_type& ) { return details::attribute_access_result::write_not_permitted; } template < typename T, T* Ptr > template < typename ... Options > bool bind_characteristic_value< T, Ptr >::value_impl< Options... >::is_this( const void* value ) { return value == Ptr; } /** @endcond */ } #endif <commit_msg>workaround for bug in clang<commit_after>#ifndef BLUETOE_CHARACTERISTIC_VALUE_HPP #define BLUETOE_CHARACTERISTIC_VALUE_HPP #include <bluetoe/options.hpp> #include <bluetoe/attribute.hpp> namespace bluetoe { namespace details { struct characteristic_value_meta_type {}; struct characteristic_parameter_meta_type {}; struct characteristic_value_declaration_parameter {}; struct client_characteristic_configuration_parameter {}; } /** * @brief if added as option to a characteristic, read access is removed from the characteristic * * Even if read access was the only remaining access type, the characterist will not be readable. * * Example: * @code std::uint32_t simple_value = 0xaabbccdd; bluetoe::characteristic< bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >, bluetoe::bind_characteristic_value< std::uint32_t, &simple_value >, bluetoe::no_read_access > > * @endcode * @sa characteristic */ class no_read_access {}; /** * @brief if added as option to a characteristic, write access is removed from the characteristic * * Even if write access was the only remaining access type, the characterist will not be writeable. * * Example: * @code std::uint32_t simple_value = 0xaabbccdd; bluetoe::characteristic< bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >, bluetoe::bind_characteristic_value< std::uint32_t, &simple_value >, bluetoe::no_write_access > > * @endcode * @sa characteristic */ class no_write_access {}; /** * @brief adds the ability to notify this characteristic. * * When a characteristic gets notified, the current value of the characteristic will be send to all * connected clients that have subscribed for notifications. * @sa server::notify */ struct notify { /** @cond HIDDEN_SYMBOLS */ struct meta_type : details::client_characteristic_configuration_parameter, details::characteristic_parameter_meta_type {}; /** @endcond */ }; /** * @brief a very simple device to bind a characteristic to a global variable to provide access to the characteristic value */ template < typename T, T* Ptr > class bind_characteristic_value { public: /** * @cond HIDDEN_SYMBOLS * use a new type to mixin the options given to characteristic */ template < typename ... Options > class value_impl { public: static constexpr bool has_read_access = !details::has_option< no_read_access, Options... >::value; static constexpr bool has_write_access = !std::is_const< T >::value && !details::has_option< no_write_access, Options... >::value; static constexpr bool has_notifcation = details::has_option< notify, Options... >::value; static details::attribute_access_result characteristic_value_access( details::attribute_access_arguments& args, std::uint16_t attribute_handle ) { if ( args.type == details::attribute_access_type::read ) { return characteristic_value_read_access( args, std::integral_constant< bool, has_read_access >() ); } else if ( args.type == details::attribute_access_type::write ) { return characteristic_value_write_access( args, std::integral_constant< bool, has_write_access >() ); } return details::attribute_access_result::write_not_permitted; } static bool is_this( const void* value ) { return value == Ptr; } private: static details::attribute_access_result characteristic_value_read_access( details::attribute_access_arguments& args, const std::true_type& ) { if ( args.buffer_offset > sizeof( T ) ) return details::attribute_access_result::invalid_offset; args.buffer_size = std::min< std::size_t >( args.buffer_size, sizeof( T ) - args.buffer_offset ); const std::uint8_t* const ptr = static_cast< const std::uint8_t* >( static_cast< const void* >( Ptr ) ) + args.buffer_offset; std::copy( ptr, ptr + args.buffer_size, args.buffer ); return args.buffer_size == sizeof( T ) - args.buffer_offset ? details::attribute_access_result::success : details::attribute_access_result::read_truncated; } static details::attribute_access_result characteristic_value_read_access( details::attribute_access_arguments&, const std::false_type& ) { return details::attribute_access_result::read_not_permitted; } static details::attribute_access_result characteristic_value_write_access( details::attribute_access_arguments& args, const std::true_type& ) { if ( args.buffer_offset > sizeof( T ) ) return details::attribute_access_result::invalid_offset; if ( args.buffer_size + args.buffer_offset > sizeof( T ) ) return details::attribute_access_result::write_overflow; args.buffer_size = std::min< std::size_t >( args.buffer_size, sizeof( T ) - args.buffer_offset ); std::uint8_t* const ptr = static_cast< std::uint8_t* >( static_cast< void* >( Ptr ) ); std::copy( args.buffer, args.buffer + args.buffer_size, ptr + args.buffer_offset ); return details::attribute_access_result::success; } static details::attribute_access_result characteristic_value_write_access( details::attribute_access_arguments&, const std::false_type& ) { return details::attribute_access_result::write_not_permitted; } }; struct meta_type : details::characteristic_value_meta_type, details::characteristic_value_declaration_parameter {}; /** @endcond */ }; } #endif <|endoftext|>
<commit_before>#include <nanyc/library.h> #include <nanyc/program.h> #include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <yuni/core/string.h> #include <yuni/io/filename-manipulation.h> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> #include <algorithm> #include <memory> #include <random> #include "libnanyc.h" namespace ny { namespace unittests { namespace { struct Entry final { yuni::String module; yuni::String name; }; struct App final { App(); App(App&&) = default; ~App(); void importFilenames(const std::vector<AnyString>&); void fetch(bool nsl); void run(const Entry&); int run(); void statstics(int64_t duration) const; struct final { uint32_t total = 0; uint32_t passing = 0; uint32_t failed = 0; } stats; nycompile_opts_t opts; bool interactive = true; uint32_t loops = 1; bool shuffle = false; std::vector<Entry> unittests; std::vector<yuni::String> filenames; private: void startEntry(const Entry&); void endEntry(const Entry&, bool, int64_t); }; App::App() { memset(&opts, 0x0, sizeof(opts)); opts.userdata = this;; } App::~App() { free(opts.sources.items); } auto now() { return yuni::DateTime::NowMilliSeconds(); } bool operator < (const Entry& a, const Entry& b) { return std::tie(a.module, a.name) < std::tie(b.module, b.name); } const char* plurals(auto count, const char* single, const char* many) { return (count <= 1) ? single : many; } void App::importFilenames(const std::vector<AnyString>& list) { uint32_t count = static_cast<uint32_t>(list.size()); filenames.resize(count); std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String { return std::move(yuni::IO::Canonicalize(item)); }); opts.sources.count = count; opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t)); if (unlikely(!opts.sources.items)) throw std::bad_alloc(); for (uint32_t i = 0; i != count; ++i) { opts.sources.items[i].filename.len = filenames[i].size(); opts.sources.items[i].filename.c_str = filenames[i].c_str(); } } void App::fetch(bool nsl) { unittests.reserve(512); // arbitrary opts.with_nsl_unittests = nsl ? nytrue : nyfalse; opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) { auto& self = *reinterpret_cast<App*>(userdata); self.unittests.emplace_back(); auto& entry = self.unittests.back(); entry.module.assign(mod, mlen); entry.name.assign(name, nlen); }; std::cout << "searching for unittests in all source files...\n"; auto start = now(); nyprogram_compile(&opts); opts.on_unittest = nullptr; std::sort(std::begin(unittests), std::end(unittests)); auto duration = now() - start; std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests"); std::cout << " found (in " << duration << "ms)\n"; } void App::startEntry(const Entry& entry) { if (interactive) { std::cout << " running "; std::cout << entry.module << '/' << entry.name; std::cout << "... " << std::flush; } } void App::endEntry(const Entry& entry, bool success, int64_t duration) { ++stats.total; ++(success ? stats.passing : stats.failed); if (interactive) std::cout << '\r'; // back to begining of the line if (success) { #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif } else { std::cout << " ERR "; } std::cout << entry.module << '/' << entry.name; std::cout << " (" << duration << "ms) "; std::cout << '\n'; } void App::statstics(int64_t duration) const { std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests"); std::cout << ", " << stats.passing << " passing"; if (stats.failed) std::cout << ", " << stats.failed << " failed"; std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; } void App::run(const Entry& entry) { startEntry(entry); auto start = now(); auto* program = nyprogram_compile(&opts); bool success = program != nullptr; if (program) { nyprogram_free(program); } auto duration = now() - start; endEntry(entry, success, duration); } void shuffleDeck(std::vector<Entry>& unittests) { std::cout << "shuffling the tests...\n" << std::flush; auto seed = now(); auto useed = static_cast<uint32_t>(seed); std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed)); } int App::run() { std::cout << '\n'; auto start = now(); for (uint32_t l = 0; l != loops; ++l) { if (unlikely(shuffle)) shuffleDeck(unittests); for (auto& entry: unittests) run(entry); } auto duration = now() - start; statstics(duration); bool success = stats.failed == 0 and stats.total != 0; return success ? EXIT_SUCCESS : EXIT_FAILURE; } int printVersion() { std::cout << libnanyc_version_to_cstr() << '\n'; return EXIT_SUCCESS; } int printBugreport() { uint32_t length; auto* text = libnanyc_get_bugreportdetails(&length); if (text) { std::cout.write(text, length); free(text); } std::cout << '\n'; return EXIT_SUCCESS; } App prepare(int argc, char** argv) { App app; bool version = false; bool bugreport = false; bool nsl = false; bool verbose = false; std::vector<AnyString> filenames; yuni::GetOpt::Parser options; options.addFlag(filenames, 'i', "", "Input nanyc source files"); options.addFlag(nsl, ' ', "nsl", "Import NSL unittests"); options.addParagraph("\nEntropy"); options.addFlag(app.loops, 'l', "loops", "Number of loops (default: 1)"); options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests"); options.addParagraph("\nHelp"); options.addFlag(verbose, 'v', "verbose", "More stuff on the screen"); options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug"); options.addFlag(version, ' ', "version", "Print the version"); options.remainingArguments(filenames); if (not options(argc, argv)) { if (options.errors()) throw std::runtime_error("Abort due to error"); throw EXIT_SUCCESS; } if (unlikely(version)) throw printVersion(); if (unlikely(bugreport)) throw printBugreport(); if (unlikely(verbose)) printBugreport(); app.importFilenames(filenames); app.fetch(nsl); return app; } } // namespace } // namespace unittests } // namespace ny int main(int argc, char** argv) { try { auto app = ny::unittests::prepare(argc, argv); return app.run(); } catch (const std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } catch (int e) { return e; } return EXIT_FAILURE;; } <commit_msg>unittests: add colors for output<commit_after>#include <nanyc/library.h> #include <nanyc/program.h> #include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <yuni/core/string.h> #include <yuni/io/filename-manipulation.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/system/console/console.h> #include <iostream> #include <vector> #include <algorithm> #include <memory> #include <random> #include "libnanyc.h" namespace ny { namespace unittests { namespace { struct Entry final { yuni::String module; yuni::String name; }; struct App final { App(); App(App&&) = default; ~App(); void importFilenames(const std::vector<AnyString>&); void fetch(bool nsl); void run(const Entry&); int run(); void statstics(int64_t duration) const; void setcolor(yuni::System::Console::Color) const; void resetcolor() const; struct final { uint32_t total = 0; uint32_t passing = 0; uint32_t failed = 0; } stats; nycompile_opts_t opts; bool interactive = true; bool colors = true; uint32_t loops = 1; bool shuffle = false; std::vector<Entry> unittests; std::vector<yuni::String> filenames; private: void startEntry(const Entry&); void endEntry(const Entry&, bool, int64_t); }; App::App() { memset(&opts, 0x0, sizeof(opts)); opts.userdata = this;; } App::~App() { free(opts.sources.items); } void App::setcolor(yuni::System::Console::Color c) const { if (colors) yuni::System::Console::SetTextColor(std::cout, c); } void App::resetcolor() const { if (colors) yuni::System::Console::ResetTextColor(std::cout); } auto now() { return yuni::DateTime::NowMilliSeconds(); } bool operator < (const Entry& a, const Entry& b) { return std::tie(a.module, a.name) < std::tie(b.module, b.name); } const char* plurals(auto count, const char* single, const char* many) { return (count <= 1) ? single : many; } void App::importFilenames(const std::vector<AnyString>& list) { uint32_t count = static_cast<uint32_t>(list.size()); filenames.resize(count); std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String { return std::move(yuni::IO::Canonicalize(item)); }); opts.sources.count = count; opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t)); if (unlikely(!opts.sources.items)) throw std::bad_alloc(); for (uint32_t i = 0; i != count; ++i) { opts.sources.items[i].filename.len = filenames[i].size(); opts.sources.items[i].filename.c_str = filenames[i].c_str(); } } void App::fetch(bool nsl) { unittests.reserve(512); // arbitrary opts.with_nsl_unittests = nsl ? nytrue : nyfalse; opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) { auto& self = *reinterpret_cast<App*>(userdata); self.unittests.emplace_back(); auto& entry = self.unittests.back(); entry.module.assign(mod, mlen); entry.name.assign(name, nlen); }; std::cout << "searching for unittests in all source files...\n"; auto start = now(); nyprogram_compile(&opts); opts.on_unittest = nullptr; std::sort(std::begin(unittests), std::end(unittests)); auto duration = now() - start; std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests"); std::cout << " found (in " << duration << "ms)\n"; } void App::startEntry(const Entry& entry) { if (interactive) { setcolor(yuni::System::Console::bold); std::cout << " running "; resetcolor(); std::cout << entry.module << '/' << entry.name; std::cout << "... " << std::flush; } } void App::endEntry(const Entry& entry, bool success, int64_t duration) { ++stats.total; ++(success ? stats.passing : stats.failed); if (interactive) std::cout << '\r'; // back to begining of the line if (success) { setcolor(yuni::System::Console::green); #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif resetcolor(); } else { setcolor(yuni::System::Console::red); std::cout << " ERR "; resetcolor(); } std::cout << entry.module << '/' << entry.name; setcolor(yuni::System::Console::lightblue); std::cout << " (" << duration << "ms)"; resetcolor(); std::cout << " \n"; } void App::statstics(int64_t duration) const { std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests"); if (stats.passing != 0) { std::cout << ", "; setcolor(yuni::System::Console::red); std::cout << stats.passing << " passing"; resetcolor(); } if (stats.failed) { std::cout << ", "; setcolor(yuni::System::Console::red); std::cout << stats.failed << " failed"; resetcolor(); } std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; } void App::run(const Entry& entry) { startEntry(entry); auto start = now(); auto* program = nyprogram_compile(&opts); bool success = program != nullptr; if (program) { nyprogram_free(program); } auto duration = now() - start; endEntry(entry, success, duration); } void shuffleDeck(std::vector<Entry>& unittests) { std::cout << "shuffling the tests...\n" << std::flush; auto seed = now(); auto useed = static_cast<uint32_t>(seed); std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed)); } int App::run() { std::cout << '\n'; auto start = now(); for (uint32_t l = 0; l != loops; ++l) { if (unlikely(shuffle)) shuffleDeck(unittests); for (auto& entry: unittests) run(entry); } auto duration = now() - start; statstics(duration); bool success = stats.failed == 0 and stats.total != 0; return success ? EXIT_SUCCESS : EXIT_FAILURE; } int printVersion() { std::cout << libnanyc_version_to_cstr() << '\n'; return EXIT_SUCCESS; } int printBugreport() { uint32_t length; auto* text = libnanyc_get_bugreportdetails(&length); if (text) { std::cout.write(text, length); free(text); } std::cout << '\n'; return EXIT_SUCCESS; } App prepare(int argc, char** argv) { App app; bool version = false; bool bugreport = false; bool nsl = false; bool verbose = false; std::vector<AnyString> filenames; yuni::GetOpt::Parser options; options.addFlag(filenames, 'i', "", "Input nanyc source files"); options.addFlag(nsl, ' ', "nsl", "Import NSL unittests"); options.addParagraph("\nEntropy"); options.addFlag(app.loops, 'l', "loops", "Number of loops (default: 1)"); options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests"); options.addParagraph("\nHelp"); options.addFlag(verbose, 'v', "verbose", "More stuff on the screen"); options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug"); options.addFlag(version, ' ', "version", "Print the version"); options.remainingArguments(filenames); if (not options(argc, argv)) { if (options.errors()) throw std::runtime_error("Abort due to error"); throw EXIT_SUCCESS; } if (unlikely(version)) throw printVersion(); if (unlikely(bugreport)) throw printBugreport(); if (unlikely(verbose)) printBugreport(); app.colors = yuni::System::Console::IsStdoutTTY(); app.importFilenames(filenames); app.fetch(nsl); return app; } } // namespace } // namespace unittests } // namespace ny int main(int argc, char** argv) { try { auto app = ny::unittests::prepare(argc, argv); return app.run(); } catch (const std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } catch (int e) { return e; } return EXIT_FAILURE;; } <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "devicecrawler.hh" #if __has_include(<filesystem>) // clang++ 6.0.0 #include <filesystem> namespace Fs = std::filesystem; #else // g++ 7.4.0 #include <experimental/filesystem> namespace Fs = std::experimental::filesystem; #endif namespace Bse { static DeviceEntry device_entry (DeviceEntryType type, String label, String identifier, int64 size = -1, bool favorite = false) { DeviceEntry r; r.type = type; r.label = label; r.identifier = identifier; r.size = size; r.favorite = favorite; return r; } static DeviceEntrySeq& crawl_directory (DeviceEntrySeq &eseq, const std::string &dir, const bool force = false) { const String bname = Path::basename (dir); DeviceEntry entry = device_entry (DeviceEntryType::DIRECTORY, bname, dir); for (auto &e : Fs::directory_iterator (dir)) { const auto filepath = e.path(); const auto bname = Path::basename (filepath); if (bname.size() && bname[0] == '.') continue; if (e.is_directory()) crawl_directory (entry.entries, e.path()); if (!e.is_regular_file()) continue; if (string_endswith (string_tolower (filepath), ".sf2")) { const auto identifier = e.path(); entry.entries.push_back (device_entry (DeviceEntryType::DIRECTORY, Path::basename (identifier), identifier, e.file_size())); } } if (force || entry.entries.size()) eseq.push_back (entry); return eseq; } DeviceEntry DeviceCrawlerImpl::list_device_origin (DeviceOrigin origin) { DeviceEntrySeq eseq; switch (origin) { const char *cstr; case DeviceOrigin::USER_DOWNLOADS: cstr = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD); if (cstr) crawl_directory (eseq, cstr, true); break; case DeviceOrigin::STANDARD_LIBRARY: break; case DeviceOrigin::PACKAGE_LIBRARY: break; case DeviceOrigin::SYSTEM_LIBRARY: break; case DeviceOrigin::USER_LIBRARY: break; case DeviceOrigin::FAVORITES: break; case DeviceOrigin::NONE: break; }; return eseq.empty() ? DeviceEntry() : eseq[0]; } DeviceCrawlerImpl::~DeviceCrawlerImpl () {} DeviceCrawlerImplP DeviceCrawlerImpl::instance_p() { static DeviceCrawlerImplP singleton = FriendAllocator<DeviceCrawlerImpl>::make_shared (); return singleton; } } // Bse <commit_msg>BSE: devicecrawler.cc: remove g++ 7.4.0 experimental/filesystem workaround<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "devicecrawler.hh" #include <filesystem> namespace Fs = std::filesystem; namespace Bse { static DeviceEntry device_entry (DeviceEntryType type, String label, String identifier, int64 size = -1, bool favorite = false) { DeviceEntry r; r.type = type; r.label = label; r.identifier = identifier; r.size = size; r.favorite = favorite; return r; } static DeviceEntrySeq& crawl_directory (DeviceEntrySeq &eseq, const std::string &dir, const bool force = false) { const String bname = Path::basename (dir); DeviceEntry entry = device_entry (DeviceEntryType::DIRECTORY, bname, dir); for (auto &e : Fs::directory_iterator (dir)) { const auto filepath = e.path(); const auto bname = Path::basename (filepath); if (bname.size() && bname[0] == '.') continue; if (e.is_directory()) crawl_directory (entry.entries, e.path()); if (!e.is_regular_file()) continue; if (string_endswith (string_tolower (filepath), ".sf2")) { const auto identifier = e.path(); entry.entries.push_back (device_entry (DeviceEntryType::DIRECTORY, Path::basename (identifier), identifier, e.file_size())); } } if (force || entry.entries.size()) eseq.push_back (entry); return eseq; } DeviceEntry DeviceCrawlerImpl::list_device_origin (DeviceOrigin origin) { DeviceEntrySeq eseq; switch (origin) { const char *cstr; case DeviceOrigin::USER_DOWNLOADS: cstr = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD); if (cstr) crawl_directory (eseq, cstr, true); break; case DeviceOrigin::STANDARD_LIBRARY: break; case DeviceOrigin::PACKAGE_LIBRARY: break; case DeviceOrigin::SYSTEM_LIBRARY: break; case DeviceOrigin::USER_LIBRARY: break; case DeviceOrigin::FAVORITES: break; case DeviceOrigin::NONE: break; }; return eseq.empty() ? DeviceEntry() : eseq[0]; } DeviceCrawlerImpl::~DeviceCrawlerImpl () {} DeviceCrawlerImplP DeviceCrawlerImpl::instance_p() { static DeviceCrawlerImplP singleton = FriendAllocator<DeviceCrawlerImpl>::make_shared (); return singleton; } } // Bse <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include "librealsense2\rs.hpp" #include "librealsense2\hpp\rs_internal.hpp" #include <fstream> #include <thread> #include "tclap/CmdLine.h" using namespace std; using namespace TCLAP; using namespace rs2; string char2hex(unsigned char n) { string res; do { res += "0123456789ABCDEF"[n % 16]; n >>= 4; } while (n); reverse(res.begin(), res.end()); if (res.size() == 1) { res.insert(0, "0"); } return res; } string datetime_string() { auto t = time(nullptr); char buffer[20] = {}; const tm* time = localtime(&t); if (nullptr != time) strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", time); return string(buffer); } int main(int argc, char* argv[]) { CmdLine cmd("librealsense rs-fw-logger example tool", ' ', RS2_API_VERSION_STR); ValueArg<string> xml_arg("l", "load", "Full file path of HW Logger Events XML file", false, "", "Load HW Logger Events XML file"); SwitchArg flash_logs_arg("f", "flash", "Flash Logs Request", false); cmd.add(xml_arg); cmd.add(flash_logs_arg); cmd.parse(argc, argv); log_to_file(RS2_LOG_SEVERITY_WARN, "librealsense.log"); auto use_xml_file = false; auto xml_full_file_path = xml_arg.getValue(); bool are_flash_logs_requested = flash_logs_arg.isSet(); context ctx; device_hub hub(ctx); bool should_loop_end = false; while (!should_loop_end) { try { cout << "\nWaiting for RealSense device to connect...\n"; auto dev = hub.wait_for_device(); cout << "RealSense device was connected...\n"; setvbuf(stdout, NULL, _IONBF, 0); // unbuffering stdout auto fw_log_device = dev.as<rs2::firmware_logger>(); bool using_parser = false; if (!xml_full_file_path.empty()) { ifstream f(xml_full_file_path); if (f.good()) { std::string xml_content((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); bool parser_initialized = fw_log_device.init_parser(xml_content); if (parser_initialized) using_parser = true; } } bool are_there_remaining_flash_logs_to_pull = true; while (hub.is_connected(dev)) { if (are_flash_logs_requested && !are_there_remaining_flash_logs_to_pull) { should_loop_end = true; break; } auto log_message = fw_log_device.create_message(); bool result = false; if (are_flash_logs_requested) { result = fw_log_device.get_flash_log(log_message); } else { result = fw_log_device.get_firmware_log(log_message); } if (result) { std::vector<string> fw_log_lines; if (using_parser) { auto parsed_log = fw_log_device.create_parsed_message(); bool parsing_result = fw_log_device.parse_log(log_message, parsed_log); stringstream sstr; sstr << parsed_log.timestamp() << " " << parsed_log.severity() << " " << parsed_log.message() << " " << parsed_log.thread_name() << " " << parsed_log.file_name() << " " << parsed_log.line(); fw_log_lines.push_back(sstr.str()); } else { stringstream sstr; sstr << log_message.get_timestamp(); sstr << " " << log_message.get_severity_str(); sstr << " FW_Log_Data:"; std::vector<uint8_t> msg_data = log_message.data(); for (int i = 0; i < msg_data.size(); ++i) { sstr << char2hex(msg_data[i]) << " "; } fw_log_lines.push_back(sstr.str()); } for (auto& line : fw_log_lines) cout << line << endl; } else { if (are_flash_logs_requested) { are_there_remaining_flash_logs_to_pull = false; } } } } catch (const error & e) { cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << endl; } } return EXIT_SUCCESS; } <commit_msg>correcting slash directions<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include "librealsense2/rs.hpp" #include "librealsense2/hpp/rs_internal.hpp" #include <fstream> #include <thread> #include "tclap/CmdLine.h" using namespace std; using namespace TCLAP; using namespace rs2; string char2hex(unsigned char n) { string res; do { res += "0123456789ABCDEF"[n % 16]; n >>= 4; } while (n); reverse(res.begin(), res.end()); if (res.size() == 1) { res.insert(0, "0"); } return res; } string datetime_string() { auto t = time(nullptr); char buffer[20] = {}; const tm* time = localtime(&t); if (nullptr != time) strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", time); return string(buffer); } int main(int argc, char* argv[]) { CmdLine cmd("librealsense rs-fw-logger example tool", ' ', RS2_API_VERSION_STR); ValueArg<string> xml_arg("l", "load", "Full file path of HW Logger Events XML file", false, "", "Load HW Logger Events XML file"); SwitchArg flash_logs_arg("f", "flash", "Flash Logs Request", false); cmd.add(xml_arg); cmd.add(flash_logs_arg); cmd.parse(argc, argv); log_to_file(RS2_LOG_SEVERITY_WARN, "librealsense.log"); auto use_xml_file = false; auto xml_full_file_path = xml_arg.getValue(); bool are_flash_logs_requested = flash_logs_arg.isSet(); context ctx; device_hub hub(ctx); bool should_loop_end = false; while (!should_loop_end) { try { cout << "\nWaiting for RealSense device to connect...\n"; auto dev = hub.wait_for_device(); cout << "RealSense device was connected...\n"; setvbuf(stdout, NULL, _IONBF, 0); // unbuffering stdout auto fw_log_device = dev.as<rs2::firmware_logger>(); bool using_parser = false; if (!xml_full_file_path.empty()) { ifstream f(xml_full_file_path); if (f.good()) { std::string xml_content((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); bool parser_initialized = fw_log_device.init_parser(xml_content); if (parser_initialized) using_parser = true; } } bool are_there_remaining_flash_logs_to_pull = true; while (hub.is_connected(dev)) { if (are_flash_logs_requested && !are_there_remaining_flash_logs_to_pull) { should_loop_end = true; break; } auto log_message = fw_log_device.create_message(); bool result = false; if (are_flash_logs_requested) { result = fw_log_device.get_flash_log(log_message); } else { result = fw_log_device.get_firmware_log(log_message); } if (result) { std::vector<string> fw_log_lines; if (using_parser) { auto parsed_log = fw_log_device.create_parsed_message(); bool parsing_result = fw_log_device.parse_log(log_message, parsed_log); stringstream sstr; sstr << parsed_log.timestamp() << " " << parsed_log.severity() << " " << parsed_log.message() << " " << parsed_log.thread_name() << " " << parsed_log.file_name() << " " << parsed_log.line(); fw_log_lines.push_back(sstr.str()); } else { stringstream sstr; sstr << log_message.get_timestamp(); sstr << " " << log_message.get_severity_str(); sstr << " FW_Log_Data:"; std::vector<uint8_t> msg_data = log_message.data(); for (int i = 0; i < msg_data.size(); ++i) { sstr << char2hex(msg_data[i]) << " "; } fw_log_lines.push_back(sstr.str()); } for (auto& line : fw_log_lines) cout << line << endl; } else { if (are_flash_logs_requested) { are_there_remaining_flash_logs_to_pull = false; } } } } catch (const error & e) { cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << endl; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// $Id: HINFile_test.C,v 1.7 2001/04/24 22:05:02 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/FORMAT/HINFile.h> #include <BALL/KERNEL/system.h> #include <BALL/KERNEL/PTE.h> /////////////////////////// START_TEST(HINFile, "$Id: HINFile_test.C,v 1.7 2001/04/24 22:05:02 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; HINFile* ptr; CHECK(HINFile::HINFile()) ptr = new HINFile; TEST_NOT_EQUAL(ptr, 0) RESULT CHECK(HINFile::~HINFile()) delete ptr; RESULT HINFile hin; CHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN)) hin = HINFile("data/HINFile_test.hin"); TEST_EQUAL(hin.isValid(), true) RESULT System system; CHECK(HINFile::read(System& system)) hin.read(system); hin.reopen(); Vector3 position(0.59038, -0.410275, -0.860515); TEST_EQUAL(hin.isValid(), true) TEST_EQUAL(system.countAtoms(), 648) TEST_EQUAL(system.countMolecules(), 216) TEST_EQUAL(system.getAtom(0)->getName(), "O") TEST_EQUAL(system.getAtom(0)->getElement(), PTE["O"]) TEST_REAL_EQUAL(system.getAtom(0)->getCharge(), -0.834) TEST_EQUAL(system.getAtom(0)->getPosition(), position) TEST_NOT_EQUAL(system.getAtom(0)->getRadius(), 0) TEST_EQUAL(system.getAtom(0)->countBonds(), 2) RESULT CHECK(HINFile::write(const System& system)) String filename; NEW_TMP_FILE(filename) HINFile hin2(filename, std::ios::out); hin2.write(system); TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false) RESULT CHECK(HINFile::HINFile& operator >> (System& system)) System system2; hin >> system2; TEST_EQUAL(system.countAtoms(), system2.countAtoms()) RESULT CHECK(HINFile::HINFile& operator << (const System& system)) String filename; NEW_TMP_FILE(filename) HINFile hin2(filename, std::ios::out); hin2 << system; TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false) RESULT CHECK(HINFile::hasPeriodicBoundary() const ) TEST_EQUAL(hin.hasPeriodicBoundary(), true) RESULT CHECK(HINFile::getPeriodicBoundary() const ) Box3 box3(-9.35068, -9.35068, -9.35068, 9.35068, 9.35068, 9.35068); TEST_EQUAL(hin.getPeriodicBoundary(), box3) RESULT CHECK(HINFile::getTemperature() const ) //BAUSTELLE RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: floating point number instead of an integer to avoid warnings<commit_after>// $Id: HINFile_test.C,v 1.8 2001/05/06 21:11:13 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/FORMAT/HINFile.h> #include <BALL/KERNEL/system.h> #include <BALL/KERNEL/PTE.h> /////////////////////////// START_TEST(HINFile, "$Id: HINFile_test.C,v 1.8 2001/05/06 21:11:13 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; HINFile* ptr; CHECK(HINFile::HINFile()) ptr = new HINFile; TEST_NOT_EQUAL(ptr, 0) RESULT CHECK(HINFile::~HINFile()) delete ptr; RESULT HINFile hin; CHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN)) hin = HINFile("data/HINFile_test.hin"); TEST_EQUAL(hin.isValid(), true) RESULT System system; CHECK(HINFile::read(System& system)) hin.read(system); hin.reopen(); Vector3 position(0.59038, -0.410275, -0.860515); TEST_EQUAL(hin.isValid(), true) TEST_EQUAL(system.countAtoms(), 648) TEST_EQUAL(system.countMolecules(), 216) TEST_EQUAL(system.getAtom(0)->getName(), "O") TEST_EQUAL(system.getAtom(0)->getElement(), PTE["O"]) TEST_REAL_EQUAL(system.getAtom(0)->getCharge(), -0.834) TEST_EQUAL(system.getAtom(0)->getPosition(), position) TEST_NOT_EQUAL(system.getAtom(0)->getRadius(), 0.0) TEST_EQUAL(system.getAtom(0)->countBonds(), 2) RESULT CHECK(HINFile::write(const System& system)) String filename; NEW_TMP_FILE(filename) HINFile hin2(filename, std::ios::out); hin2.write(system); TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false) RESULT CHECK(HINFile::HINFile& operator >> (System& system)) System system2; hin >> system2; TEST_EQUAL(system.countAtoms(), system2.countAtoms()) RESULT CHECK(HINFile::HINFile& operator << (const System& system)) String filename; NEW_TMP_FILE(filename) HINFile hin2(filename, std::ios::out); hin2 << system; TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false) RESULT CHECK(HINFile::hasPeriodicBoundary() const ) TEST_EQUAL(hin.hasPeriodicBoundary(), true) RESULT CHECK(HINFile::getPeriodicBoundary() const ) Box3 box3(-9.35068, -9.35068, -9.35068, 9.35068, 9.35068, 9.35068); TEST_EQUAL(hin.getPeriodicBoundary(), box3) RESULT CHECK(HINFile::getTemperature() const ) //BAUSTELLE RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>//===-- Language.cpp -------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <functional> #include <map> #include "lldb/Target/Language.h" #include "lldb/Host/Mutex.h" #include "lldb/Core/PluginManager.h" using namespace lldb; using namespace lldb_private; typedef std::unique_ptr<Language> LanguageUP; typedef std::map<lldb::LanguageType, LanguageUP> LanguagesMap; static LanguagesMap& GetLanguagesMap () { static LanguagesMap *g_map = nullptr; static std::once_flag g_initialize; std::call_once(g_initialize, [] { g_map = new LanguagesMap(); // NOTE: INTENTIONAL LEAK due to global destructor chain }); return *g_map; } static Mutex& GetLanguagesMutex () { static Mutex *g_mutex = nullptr; static std::once_flag g_initialize; std::call_once(g_initialize, [] { g_mutex = new Mutex(); // NOTE: INTENTIONAL LEAK due to global destructor chain }); return *g_mutex; } Language* Language::FindPlugin (lldb::LanguageType language) { Mutex::Locker locker(GetLanguagesMutex()); LanguagesMap& map(GetLanguagesMap()); auto iter = map.find(language), end = map.end(); if (iter != end) return iter->second.get(); Language *language_ptr = nullptr; LanguageCreateInstance create_callback; for (uint32_t idx = 0; (create_callback = PluginManager::GetLanguageCreateCallbackAtIndex(idx)) != nullptr; ++idx) { language_ptr = create_callback(language); if (language_ptr) { map[language] = std::unique_ptr<Language>(language_ptr); return language_ptr; } } return nullptr; } void Language::ForEach (std::function<bool(Language*)> callback) { Mutex::Locker locker(GetLanguagesMutex()); LanguagesMap& map(GetLanguagesMap()); for (const auto& entry : map) { if (!callback(entry.second.get())) break; } } //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- Language::Language() { } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- Language::~Language() { } <commit_msg>Include <mutex><commit_after>//===-- Language.cpp -------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <functional> #include <map> #include <mutex> #include "lldb/Target/Language.h" #include "lldb/Host/Mutex.h" #include "lldb/Core/PluginManager.h" using namespace lldb; using namespace lldb_private; typedef std::unique_ptr<Language> LanguageUP; typedef std::map<lldb::LanguageType, LanguageUP> LanguagesMap; static LanguagesMap& GetLanguagesMap () { static LanguagesMap *g_map = nullptr; static std::once_flag g_initialize; std::call_once(g_initialize, [] { g_map = new LanguagesMap(); // NOTE: INTENTIONAL LEAK due to global destructor chain }); return *g_map; } static Mutex& GetLanguagesMutex () { static Mutex *g_mutex = nullptr; static std::once_flag g_initialize; std::call_once(g_initialize, [] { g_mutex = new Mutex(); // NOTE: INTENTIONAL LEAK due to global destructor chain }); return *g_mutex; } Language* Language::FindPlugin (lldb::LanguageType language) { Mutex::Locker locker(GetLanguagesMutex()); LanguagesMap& map(GetLanguagesMap()); auto iter = map.find(language), end = map.end(); if (iter != end) return iter->second.get(); Language *language_ptr = nullptr; LanguageCreateInstance create_callback; for (uint32_t idx = 0; (create_callback = PluginManager::GetLanguageCreateCallbackAtIndex(idx)) != nullptr; ++idx) { language_ptr = create_callback(language); if (language_ptr) { map[language] = std::unique_ptr<Language>(language_ptr); return language_ptr; } } return nullptr; } void Language::ForEach (std::function<bool(Language*)> callback) { Mutex::Locker locker(GetLanguagesMutex()); LanguagesMap& map(GetLanguagesMap()); for (const auto& entry : map) { if (!callback(entry.second.get())) break; } } //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- Language::Language() { } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- Language::~Language() { } <|endoftext|>
<commit_before>#include "codec.h" #include "surface.h" #include "../orz/logger.h" namespace Img { bool AbstractCodec::LoadHeader(IO::FileReader::Ptr reader) { try { if (reader == nullptr) { DO_THROW(Err::InvalidParam, "Reader was null."); } m_file = reader; { std::lock_guard<std::mutex> l(m_state); m_info.SurfaceFormat = Img::Format::Undefined; m_info.Dimensions = Geom::SizeInt(-1, -1); m_fs = reader->Size(); } ImageInfo ii; ii.SurfaceFormat = Format::Undefined; if (PerformLoadHeader(reader, ii)) { // Validate info. Invalid values are treated as codec bugs. if (ii.SurfaceFormat == Img::Format::Undefined) { DO_THROW(Err::CodecError, "Surface format was set to invalid."); } if ((ii.Dimensions.Width <= 0) || (ii.Dimensions.Height <= 0)) { DO_THROW(Err::CodecError, "Dimensions were set to an invalid value."); } std::lock_guard<std::mutex> l(m_state); m_info = ii; return true; } } catch (Err::Exception& ex) { m_file.reset(); Log << "(AbstractCodec::LoadHeader) " << ex.what() << "\n"; return false; } catch (...) { m_file.reset(); Log << "(AbstractCodec::LoadHeader) Unrecognized exception.\n"; return false; } m_file.reset(); return false; } std::shared_ptr<Metadata::Document> AbstractCodec::LoadMetadata() { if (m_file == nullptr) { DO_THROW(Err::InvalidCall, "No file was set"); } if (m_file->IsOpen() == false) { DO_THROW(Err::InvalidCall, "File not open"); } try { return PerformLoadMetadata(); } catch (Err::Exception& e) { Log << "(AbstractCodec::LoadMetadata) " << e.what() << "\n"; return nullptr; } } AbstractCodec::AllocationStatus AbstractCodec::Allocate(const Geom::SizeInt& dimHint) { try { if (dimHint == Geom::SizeInt(0, 0)) { return PerformAllocate(); } return PerformAllocate(dimHint); } catch(std::bad_alloc& e) { // We can't handle infinitely huge images, which is not really a fatal error. Log << "(AbstractCodec::Allocate) " << e.what() << "\n"; return AllocationStatus::Failed; } } size_t AbstractCodec::EstimateMemory() { return PerformEstimateMemory(); } AbstractCodec::LoadStatus AbstractCodec::LoadImageData(bool mayReset) { if (m_file == 0) { DO_THROW(Err::InvalidCall, "No file was set"); } if (m_file->IsOpen() == false) { DO_THROW(Err::InvalidCall, "File not open"); } LoadStatus l; try { l = PerformLoadImageData(m_file); m_isFinished = (l != LoadStatus::Aborted); } catch (Err::Exception& e) { Log << "(AbstractCodec::LoadImageData) " << e.what() << "\n"; l = LoadStatus::Finished; m_isFinished = true; } if (m_isFinished && m_file && mayReset) { m_file->Close(); } return l; } bool AbstractCodec::IsFinished() { return m_isFinished; } Geom::SizeInt AbstractCodec::GetSize() const { std::lock_guard<std::mutex> l(m_state); return m_info.Dimensions; } void AbstractCodec::Terminate() { m_doAbort = true; } AbstractCodec::AbstractCodec(): m_doAbort{ false }, m_fs{ 0 }, m_isFinished{ false } { m_info.Dimensions = Geom::SizeInt(0, 0); m_info.SurfaceFormat = Img::Format::Undefined; } AbstractCodec::~AbstractCodec() {} bool AbstractCodec::DoTerminate() { return m_doAbort; } size_t AbstractCodec::PerformEstimateMemory() { return Area(GetSize()) * EstimatePixelSize(GetFormat()); } Img::Format AbstractCodec::GetFormat() const { std::lock_guard<std::mutex> l(m_state); return m_info.SurfaceFormat; } void AbstractCodec::ResetTerminate() { m_doAbort = false; } std::shared_ptr<Metadata::Document> AbstractCodec::PerformLoadMetadata() { return nullptr; } AbstractCodec::AllocationStatus AbstractCodec::PerformAllocate() { AllocationStatus a = PerformAllocate(GetSize()); if (a == AllocationStatus::NotSupported) { return AllocationStatus::Failed; } return a; } AbstractCodec::AllocationStatus AbstractCodec::PerformAllocate( const Geom::SizeInt& ) { return AllocationStatus::NotSupported; } bool AbstractCodec::CanDetectFormat() const { return true; } } <commit_msg>Handle non-standard exceptions in Allocate<commit_after>#include "codec.h" #include "surface.h" #include "../orz/logger.h" namespace Img { bool AbstractCodec::LoadHeader(IO::FileReader::Ptr reader) { try { if (reader == nullptr) { DO_THROW(Err::InvalidParam, "Reader was null."); } m_file = reader; { std::lock_guard<std::mutex> l(m_state); m_info.SurfaceFormat = Img::Format::Undefined; m_info.Dimensions = Geom::SizeInt(-1, -1); m_fs = reader->Size(); } ImageInfo ii; ii.SurfaceFormat = Format::Undefined; if (PerformLoadHeader(reader, ii)) { // Validate info. Invalid values are treated as codec bugs. if (ii.SurfaceFormat == Img::Format::Undefined) { DO_THROW(Err::CodecError, "Surface format was set to invalid."); } if ((ii.Dimensions.Width <= 0) || (ii.Dimensions.Height <= 0)) { DO_THROW(Err::CodecError, "Dimensions were set to an invalid value."); } std::lock_guard<std::mutex> l(m_state); m_info = ii; return true; } } catch (Err::Exception& ex) { m_file.reset(); Log << "(AbstractCodec::LoadHeader) " << ex.what() << "\n"; return false; } catch (...) { m_file.reset(); Log << "(AbstractCodec::LoadHeader) Unrecognized exception.\n"; return false; } m_file.reset(); return false; } std::shared_ptr<Metadata::Document> AbstractCodec::LoadMetadata() { if (m_file == nullptr) { DO_THROW(Err::InvalidCall, "No file was set"); } if (m_file->IsOpen() == false) { DO_THROW(Err::InvalidCall, "File not open"); } try { return PerformLoadMetadata(); } catch (Err::Exception& e) { Log << "(AbstractCodec::LoadMetadata) " << e.what() << "\n"; return nullptr; } } AbstractCodec::AllocationStatus AbstractCodec::Allocate(const Geom::SizeInt& dimHint) { try { if (dimHint == Geom::SizeInt(0, 0)) { return PerformAllocate(); } return PerformAllocate(dimHint); } catch(std::bad_alloc& e) { // We can't handle infinitely huge images, which is not really a fatal error. Log << "(AbstractCodec::Allocate) " << e.what() << "\n"; return AllocationStatus::Failed; } catch (Err::Exception& e) { Log << "(AbstractCodec::Allocate) " << e.what() << "\n"; return AllocationStatus::Failed; } } size_t AbstractCodec::EstimateMemory() { return PerformEstimateMemory(); } AbstractCodec::LoadStatus AbstractCodec::LoadImageData(bool mayReset) { if (m_file == 0) { DO_THROW(Err::InvalidCall, "No file was set"); } if (m_file->IsOpen() == false) { DO_THROW(Err::InvalidCall, "File not open"); } LoadStatus l; try { l = PerformLoadImageData(m_file); m_isFinished = (l != LoadStatus::Aborted); } catch (Err::Exception& e) { Log << "(AbstractCodec::LoadImageData) " << e.what() << "\n"; l = LoadStatus::Finished; m_isFinished = true; } if (m_isFinished && m_file && mayReset) { m_file->Close(); } return l; } bool AbstractCodec::IsFinished() { return m_isFinished; } Geom::SizeInt AbstractCodec::GetSize() const { std::lock_guard<std::mutex> l(m_state); return m_info.Dimensions; } void AbstractCodec::Terminate() { m_doAbort = true; } AbstractCodec::AbstractCodec(): m_doAbort{ false }, m_fs{ 0 }, m_isFinished{ false } { m_info.Dimensions = Geom::SizeInt(0, 0); m_info.SurfaceFormat = Img::Format::Undefined; } AbstractCodec::~AbstractCodec() {} bool AbstractCodec::DoTerminate() { return m_doAbort; } size_t AbstractCodec::PerformEstimateMemory() { return Area(GetSize()) * EstimatePixelSize(GetFormat()); } Img::Format AbstractCodec::GetFormat() const { std::lock_guard<std::mutex> l(m_state); return m_info.SurfaceFormat; } void AbstractCodec::ResetTerminate() { m_doAbort = false; } std::shared_ptr<Metadata::Document> AbstractCodec::PerformLoadMetadata() { return nullptr; } AbstractCodec::AllocationStatus AbstractCodec::PerformAllocate() { AllocationStatus a = PerformAllocate(GetSize()); if (a == AllocationStatus::NotSupported) { return AllocationStatus::Failed; } return a; } AbstractCodec::AllocationStatus AbstractCodec::PerformAllocate( const Geom::SizeInt& ) { return AllocationStatus::NotSupported; } bool AbstractCodec::CanDetectFormat() const { return true; } } <|endoftext|>
<commit_before>/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ /** * Add each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`. */ #include <stdint.h> #include <nan.h> #include "stdlib/strided_binary.h" /** * Add-on namespace. */ namespace addon_strided_add { using Nan::FunctionCallbackInfo; using Nan::TypedArrayContents; using Nan::ThrowTypeError; using Nan::ThrowError; using v8::Value; /** * Adds two doubles. * * @private * @param x first double * @param y second double * @return sum */ double add( double x, double y ) { return x + y; } /** * Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`. * * When called from JavaScript, the function expects the following arguments: * * * __n__: number of elements. * * __X__: input typed array. * * __sx__: `X` stride length. * * __Y__: input typed array. * * __sy__: `Y` typed array stride length. * * __Z__: destination typed array. * * __sz__: destination typed array stride length. * * @param info arguments */ void node_add( const FunctionCallbackInfo<Value>& info ) { int64_t strides[ 3 ]; int64_t shape[ 1 ]; uint8_t *arrays[ 3 ]; if ( info.Length() != 7 ) { ThrowError( "invalid invocation. Must provide 7 arguments." ); return; } if ( !info[ 0 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. First argument must be a number." ); return; } if ( !info[ 2 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. Third argument must be a number." ); return; } if ( !info[ 4 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. Fifth argument must be a number." ); return; } if ( !info[ 6 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. Seventh argument must be a number." ); return; } // Retrieve the number of elements: shape[ 0 ] = static_cast<int64_t>( info[ 0 ]->IntegerValue() ); // Retrieve the strides: strides[ 0 ] = static_cast<int64_t>( info[ 2 ]->IntegerValue() ); strides[ 1 ] = static_cast<int64_t>( info[ 4 ]->IntegerValue() ); strides[ 2 ] = static_cast<int64_t>( info[ 6 ]->IntegerValue() ); // Convert the strides from units of elements to units of bytes... if ( info[ 1 ]->IsFloat64Array() ) { strides[ 0 ] *= 8; // 8 bytes per double } if ( info[ 3 ]->IsFloat64Array() ) { strides[ 1 ] *= 8; } if ( info[ 5 ]->IsFloat64Array() ) { strides[ 2 ] *= 8; } // Get the underlying byte arrays: TypedArrayContents<uint8_t> X( info[ 1 ] ); TypedArrayContents<uint8_t> Y( info[ 3 ] ); TypedArrayContents<uint8_t> Z( info[ 5 ] ); // Add the arrays to our array of array pointers: arrays[ 0 ] = *X; arrays[ 1 ] = *Y; arrays[ 2 ] = *Z; // Perform addition: stdlib_strided_dd_d( arrays, shape, strides, (void *)add ); } NAN_MODULE_INIT( Init ) { Nan::Export( target, "add", node_add ); } NODE_MODULE( addon, Init ) } // end namespace addon_strided_add <commit_msg>Move declaration<commit_after>/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ /** * Add each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`. */ #include <stdint.h> #include <nan.h> #include "stdlib/strided_binary.h" /** * Add-on namespace. */ namespace addon_strided_add { using Nan::FunctionCallbackInfo; using Nan::TypedArrayContents; using Nan::ThrowTypeError; using Nan::ThrowError; using v8::Value; /** * Adds two doubles. * * @private * @param x first double * @param y second double * @return sum */ double add( double x, double y ) { return x + y; } /** * Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`. * * When called from JavaScript, the function expects the following arguments: * * * __n__: number of elements. * * __X__: input typed array. * * __sx__: `X` stride length. * * __Y__: input typed array. * * __sy__: `Y` typed array stride length. * * __Z__: destination typed array. * * __sz__: destination typed array stride length. * * @param info arguments */ void node_add( const FunctionCallbackInfo<Value>& info ) { uint8_t *arrays[ 3 ]; int64_t strides[ 3 ]; int64_t shape[ 1 ]; if ( info.Length() != 7 ) { ThrowError( "invalid invocation. Must provide 7 arguments." ); return; } if ( !info[ 0 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. First argument must be a number." ); return; } if ( !info[ 2 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. Third argument must be a number." ); return; } if ( !info[ 4 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. Fifth argument must be a number." ); return; } if ( !info[ 6 ]->IsNumber() ) { ThrowTypeError( "invalid input argument. Seventh argument must be a number." ); return; } // Retrieve the number of elements: shape[ 0 ] = static_cast<int64_t>( info[ 0 ]->IntegerValue() ); // Retrieve the strides: strides[ 0 ] = static_cast<int64_t>( info[ 2 ]->IntegerValue() ); strides[ 1 ] = static_cast<int64_t>( info[ 4 ]->IntegerValue() ); strides[ 2 ] = static_cast<int64_t>( info[ 6 ]->IntegerValue() ); // Convert the strides from units of elements to units of bytes... if ( info[ 1 ]->IsFloat64Array() ) { strides[ 0 ] *= 8; // 8 bytes per double } if ( info[ 3 ]->IsFloat64Array() ) { strides[ 1 ] *= 8; } if ( info[ 5 ]->IsFloat64Array() ) { strides[ 2 ] *= 8; } // Get the underlying byte arrays: TypedArrayContents<uint8_t> X( info[ 1 ] ); TypedArrayContents<uint8_t> Y( info[ 3 ] ); TypedArrayContents<uint8_t> Z( info[ 5 ] ); // Add the arrays to our array of array pointers: arrays[ 0 ] = *X; arrays[ 1 ] = *Y; arrays[ 2 ] = *Z; // Perform addition: stdlib_strided_dd_d( arrays, shape, strides, (void *)add ); } NAN_MODULE_INIT( Init ) { Nan::Export( target, "add", node_add ); } NODE_MODULE( addon, Init ) } // end namespace addon_strided_add <|endoftext|>
<commit_before>/******************************************************************************* * c7a/core/stage_builder.hpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_CORE_STAGE_BUILDER_HEADER #define C7A_CORE_STAGE_BUILDER_HEADER #include <c7a/api/collapse.hpp> #include <c7a/api/dia_base.hpp> #include <c7a/common/logger.hpp> #include <algorithm> #include <set> #include <stack> #include <string> #include <utility> #include <vector> namespace c7a { namespace core { using c7a::api::DIABase; class Stage { public: explicit Stage(DIABase* node) : node_(node) { LOG << "CREATING stage" << node_->ToString() << "node" << node_; } void Execute() { LOG << "EXECUTING stage " << node_->ToString() << "node" << node_; node_->StartExecutionTimer(); node_->Execute(); node_->StopExecutionTimer(); node_->PushData(); node_->set_state(api::DIAState::EXECUTED); } void PushData() { LOG << "PUSHING stage " << node_->ToString() << "node" << node_; node_->PushData(); node_->set_state(api::DIAState::EXECUTED); } void Dispose() { LOG << "DISPOSING stage " << node_->ToString() << "node" << node_; node_->Dispose(); node_->set_state(api::DIAState::DISPOSED); } DIABase * node() { return node_; } private: static const bool debug = false; DIABase* node_; }; class StageBuilder { public: void FindStages(DIABase* action, std::vector<Stage>& stages_result) { LOG << "FINDING stages:"; std::set<const DIABase*> stages_found; // Do a reverse DFS and find all stages std::stack<DIABase*> dia_stack; dia_stack.push(action); stages_found.insert(action); stages_result.push_back(Stage(action)); while (!dia_stack.empty()) { DIABase* curr = dia_stack.top(); dia_stack.pop(); const auto parents = curr->parents(); for (size_t i = 0; i < parents.size(); ++i) { // Check if parent was already added auto p = parents[i].get(); if (p && (stages_found.find(p) == stages_found.end())) { // If not add parent to stages found and result stages stages_found.insert(p); stages_result.push_back(Stage(p)); // If parent was not executed push it to the DFS if (p->state() != api::DIAState::EXECUTED || p->type() == api::NodeType::COLLAPSE) { dia_stack.push(p); } } } } // Reverse the execution order std::reverse(stages_result.begin(), stages_result.end()); } void RunScope(DIABase* action) { std::vector<Stage> result; FindStages(action, result); for (auto s : result) { if (s.node()->state() == api::DIAState::EXECUTED) s.PushData(); if (s.node()->state() == api::DIAState::NEW) s.Execute(); s.node()->UnregisterChilds(); } } static const bool debug = false; }; } // namespace core } // namespace c7a #endif // !C7A_CORE_STAGE_BUILDER_HEADER /******************************************************************************/ <commit_msg>Stage builder update.<commit_after>/******************************************************************************* * c7a/core/stage_builder.hpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_CORE_STAGE_BUILDER_HEADER #define C7A_CORE_STAGE_BUILDER_HEADER #include <c7a/api/collapse.hpp> #include <c7a/api/dia_base.hpp> #include <c7a/common/logger.hpp> #include <algorithm> #include <set> #include <stack> #include <string> #include <utility> #include <vector> namespace c7a { namespace core { using c7a::api::DIABase; class Stage { public: explicit Stage(DIABase* node) : node_(node) { LOG << "CREATING stage" << node_->ToString() << "node" << node_; } void Execute() { LOG << "EXECUTING stage " << node_->ToString() << "node" << node_; node_->StartExecutionTimer(); node_->Execute(); node_->StopExecutionTimer(); node_->PushData(); node_->set_state(api::DIAState::EXECUTED); } void PushData() { LOG << "PUSHING stage " << node_->ToString() << "node" << node_; node_->PushData(); node_->set_state(api::DIAState::EXECUTED); } void Dispose() { LOG << "DISPOSING stage " << node_->ToString() << "node" << node_; node_->Dispose(); node_->set_state(api::DIAState::DISPOSED); } DIABase * node() { return node_; } private: static const bool debug = false; DIABase* node_; }; class StageBuilder { public: void FindStages(DIABase* action, std::vector<Stage>& stages_result) { LOG << "FINDING stages:"; std::set<const DIABase*> stages_found; // Do a reverse DFS and find all stages std::stack<DIABase*> dia_stack; dia_stack.push(action); stages_found.insert(action); stages_result.push_back(Stage(action)); while (!dia_stack.empty()) { DIABase* curr = dia_stack.top(); dia_stack.pop(); const auto parents = curr->parents(); for (size_t i = 0; i < parents.size(); ++i) { // Check if parent was already added auto p = parents[i].get(); if (p) { // If not add parent to stages found and result stages stages_found.insert(p); stages_result.push_back(Stage(p)); // If parent was not executed push it to the DFS if (p->state() != api::DIAState::EXECUTED || p->type() == api::NodeType::COLLAPSE) { dia_stack.push(p); } } } } // Reverse the execution order std::reverse(stages_result.begin(), stages_result.end()); } void RunScope(DIABase* action) { std::vector<Stage> result; FindStages(action, result); for (auto s : result) { if (s.node()->state() == api::DIAState::EXECUTED) s.PushData(); if (s.node()->state() == api::DIAState::NEW) s.Execute(); s.node()->UnregisterChilds(); } } static const bool debug = false; }; } // namespace core } // namespace c7a #endif // !C7A_CORE_STAGE_BUILDER_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestUncertaintyTubeFilter.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. =========================================================================*/ // This test creates some polylines with uncertainty values. #include "vtkUncertaintyTubeFilter.h" #include "vtkPolyData.h" #include "vtkDelaunay2D.h" #include "vtkCellArray.h" #include "vtkShrinkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkDoubleArray.h" #include "vtkMath.h" #include "vtkCamera.h" #include "vtkPointData.h" #include "vtkRenderWindowInteractor.h" #include "vtkRegressionTestImage.h" int TestUncertaintyTubeFilter( int argc, char* argv[] ) { vtkPoints *newPts = vtkPoints::New(); newPts->SetNumberOfPoints(10); newPts->SetPoint( 0, 10,10,0); newPts->SetPoint( 1, 10,10,2); newPts->SetPoint( 2, 10,10,4); newPts->SetPoint( 3, 10,10,8); newPts->SetPoint( 4, 10,10,12); newPts->SetPoint( 5, 1,1,2); newPts->SetPoint( 6, 1,2,3); newPts->SetPoint( 7, 1,4,3); newPts->SetPoint( 8, 1,8,4); newPts->SetPoint( 9, 1,16,5); vtkDoubleArray *s = vtkDoubleArray::New(); s->SetNumberOfComponents(1); s->SetNumberOfTuples(10); vtkDoubleArray *v = vtkDoubleArray::New(); v->SetNumberOfComponents(3); v->SetNumberOfTuples(10); for (int i=0; i<10; i++) { s->SetTuple1(i, vtkMath::Random(0,1)); v->SetTuple3(i, vtkMath::Random(0.0,2), vtkMath::Random(0.0,2), vtkMath::Random(0.0,2)); } vtkCellArray *lines = vtkCellArray::New(); lines->EstimateSize(2,5); lines->InsertNextCell(5); lines->InsertCellPoint(0); lines->InsertCellPoint(1); lines->InsertCellPoint(2); lines->InsertCellPoint(3); lines->InsertCellPoint(4); lines->InsertNextCell(5); lines->InsertCellPoint(5); lines->InsertCellPoint(6); lines->InsertCellPoint(7); lines->InsertCellPoint(8); lines->InsertCellPoint(9); vtkPolyData *pd = vtkPolyData::New(); pd->SetPoints(newPts); pd->SetLines(lines); pd->GetPointData()->SetScalars(s); pd->GetPointData()->SetVectors(v); newPts->Delete(); vtkUncertaintyTubeFilter *utf = vtkUncertaintyTubeFilter::New(); utf->SetInput(pd); utf->SetNumberOfSides(8); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInputConnection( utf->GetOutputPort() ); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); vtkRenderer *ren = vtkRenderer::New(); ren->AddActor(actor); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); ren->GetActiveCamera()->SetPosition(1,1,1); ren->GetActiveCamera()->SetFocalPoint(0,0,0); ren->ResetCamera(); iren->Initialize(); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } // Clean up pd->Delete(); utf->Delete(); mapper->Delete(); actor->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); return !retVal; } <commit_msg>BUG: Fix mem leak in test code so test can pass on dashboards with VTK_DEBUG_LEAKS ON.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestUncertaintyTubeFilter.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. =========================================================================*/ // This test creates some polylines with uncertainty values. #include "vtkUncertaintyTubeFilter.h" #include "vtkPolyData.h" #include "vtkDelaunay2D.h" #include "vtkCellArray.h" #include "vtkShrinkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkDoubleArray.h" #include "vtkMath.h" #include "vtkCamera.h" #include "vtkPointData.h" #include "vtkRenderWindowInteractor.h" #include "vtkRegressionTestImage.h" int TestUncertaintyTubeFilter( int argc, char* argv[] ) { vtkPoints *newPts = vtkPoints::New(); newPts->SetNumberOfPoints(10); newPts->SetPoint( 0, 10,10,0); newPts->SetPoint( 1, 10,10,2); newPts->SetPoint( 2, 10,10,4); newPts->SetPoint( 3, 10,10,8); newPts->SetPoint( 4, 10,10,12); newPts->SetPoint( 5, 1,1,2); newPts->SetPoint( 6, 1,2,3); newPts->SetPoint( 7, 1,4,3); newPts->SetPoint( 8, 1,8,4); newPts->SetPoint( 9, 1,16,5); vtkDoubleArray *s = vtkDoubleArray::New(); s->SetNumberOfComponents(1); s->SetNumberOfTuples(10); vtkDoubleArray *v = vtkDoubleArray::New(); v->SetNumberOfComponents(3); v->SetNumberOfTuples(10); for (int i=0; i<10; i++) { s->SetTuple1(i, vtkMath::Random(0,1)); v->SetTuple3(i, vtkMath::Random(0.0,2), vtkMath::Random(0.0,2), vtkMath::Random(0.0,2)); } vtkCellArray *lines = vtkCellArray::New(); lines->EstimateSize(2,5); lines->InsertNextCell(5); lines->InsertCellPoint(0); lines->InsertCellPoint(1); lines->InsertCellPoint(2); lines->InsertCellPoint(3); lines->InsertCellPoint(4); lines->InsertNextCell(5); lines->InsertCellPoint(5); lines->InsertCellPoint(6); lines->InsertCellPoint(7); lines->InsertCellPoint(8); lines->InsertCellPoint(9); vtkPolyData *pd = vtkPolyData::New(); pd->SetPoints(newPts); pd->SetLines(lines); pd->GetPointData()->SetScalars(s); pd->GetPointData()->SetVectors(v); newPts->Delete(); lines->Delete(); s->Delete(); v->Delete(); vtkUncertaintyTubeFilter *utf = vtkUncertaintyTubeFilter::New(); utf->SetInput(pd); utf->SetNumberOfSides(8); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInputConnection( utf->GetOutputPort() ); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); vtkRenderer *ren = vtkRenderer::New(); ren->AddActor(actor); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); ren->GetActiveCamera()->SetPosition(1,1,1); ren->GetActiveCamera()->SetFocalPoint(0,0,0); ren->ResetCamera(); iren->Initialize(); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } // Clean up pd->Delete(); utf->Delete(); mapper->Delete(); actor->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); return !retVal; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_freq.C /// @brief Calculate and save off DIMM frequencies /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Louis Stermole <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include <p9_mss_freq.H> // std lib #include <map> #include <utility> // fapi2 #include <fapi2.H> // mss lib #include <generic/memory/lib/spd/common/ddr4/spd_decoder_ddr4.H> #include <lib/spd/spd_factory.H> #include <lib/freq/cas_latency.H> #include <lib/freq/sync.H> #include <lib/workarounds/freq_workarounds.H> #include <generic/memory/lib/utils/c_str.H> #include <generic/memory/lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <generic/memory/lib/utils/index.H> #include <lib/shared/mss_const.H> using fapi2::TARGET_TYPE_MCS; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; using fapi2::TARGET_TYPE_MCBIST; using fapi2::FAPI2_RC_SUCCESS; extern "C" { /// /// @brief Calculate and save off DIMM frequencies /// @param[in] i_target, the controller (e.g., MCS) /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_freq( const fapi2::Target<TARGET_TYPE_MCS>& i_target ) { // TODO RTC:161701 p9_mss_freq needs to be re-worked to work per-MC as it's hard // (if not impossible) to know the appropriate freq if we don't have information // for both MCS. Setting one to max freq doesn't work in the case of 0 DIMM as // there is no check for other freq's and we end up setting the chosen freq to // the default. // So for now, iterate over all the MCBIST. This isn't great as we do this work // twice for every MC. However, attribute access is cheap so this will suffice for // the time being. const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target); std::vector< std::vector<uint64_t> > l_min_dimm_freq(mss::MCS_PER_MC, std::vector<uint64_t> (mss::PORTS_PER_MCS, 0) ); std::vector<uint32_t> l_supported_freqs; uint64_t l_mss_freq = 0; uint32_t l_nest_freq = 0; // If there are no DIMM, we can just get out. if (mss::count_dimm(l_mcbist) == 0) { FAPI_INF("Seeing no DIMM on %s, no freq to set", mss::c_str(l_mcbist)); return FAPI2_RC_SUCCESS; } // Get supported freqs for this MCBIST FAPI_TRY( mss::supported_freqs(l_mcbist, l_supported_freqs) ); for (const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(l_mcbist)) { const auto l_mcs_index = mss::index(l_mcs); std::vector< std::pair< uint64_t, fapi2::Target<fapi2::TARGET_TYPE_MCA>> > l_desired_cas_latency; for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(l_mcs) ) { const auto l_mca_index = mss::index(l_mca); std::vector< std::shared_ptr<mss::spd::decoder> > l_factory_caches; fapi2::ReturnCode l_rc; // Get cached decoder FAPI_TRY( mss::spd::populate_decoder_caches(l_mca, l_factory_caches), "%s. Failed to populate decoder cache", mss::c_str(l_mca) ); // Instantiation of class that calculates CL algorithm mss::cas_latency l_cas_latency( l_mca, l_factory_caches, l_supported_freqs, l_rc ); FAPI_TRY( l_rc, "%s. Failed to initialize cas_latency ctor", mss::c_str(l_mca) ); if(l_cas_latency.iv_dimm_list_empty) { // Cannot fail out for an empty DIMM configuration, so default values are set FAPI_INF("%s. DIMM list is empty! Setting default values for CAS latency and DIMM speed.", mss::c_str(l_mca) ); } else { // We set this to a non-0 so we avoid divide-by-zero errors in the conversions which // go from clocks to time (and vice versa.) We have other bugs if there was really // no MT/s determined and there really is a DIMM installed, so this is ok. // We pick the maximum frequency supported by the system as the default. uint64_t l_desired_cl = 0; l_min_dimm_freq[l_mcs_index][l_mca_index] = fapi2::ENUM_ATTR_MSS_FREQ_MT2666; uint64_t l_tCKmin = 0; // Find CAS latency using JEDEC algorithm FAPI_TRY( l_cas_latency.find_cl(l_desired_cl, l_tCKmin) ); FAPI_INF("%s. Result from CL algorithm, CL (nck): %d, tCK (ps): %d", mss::c_str(l_mca), l_desired_cl, l_tCKmin); l_desired_cas_latency.push_back(std::make_pair(l_desired_cl, l_mca) ); // Find dimm transfer speed from selected tCK FAPI_TRY( mss::ps_to_freq(l_tCKmin, l_min_dimm_freq[l_mcs_index][l_mca_index]), "%s. Failed ps_to_freq()", mss::c_str(l_mca) ); FAPI_INF("DIMM speed from selected tCK (ps): %d for %s", l_min_dimm_freq[l_mcs_index][l_mca_index], mss::c_str(l_mca)); FAPI_INF("%s. Selected DIMM speed from supported speeds: %d", mss::c_str(l_mca), l_min_dimm_freq[l_mcs_index][l_mca_index]); }// end else } // mca FAPI_TRY(mss::set_CL_attr(l_mcs, l_desired_cas_latency), "%s. Failed set_CL_attr()", mss::c_str(i_target) ); } // close for each mcs FAPI_TRY(mss::set_freq_attrs(l_mcbist, l_min_dimm_freq), "%s. Failed set_freq_attrs()", mss::c_str(i_target) ); // Check MEM/NEST frequency ratio FAPI_TRY( mss::freq_pb_mhz(l_nest_freq) ); FAPI_TRY( mss::freq(l_mcbist, l_mss_freq) ); FAPI_TRY( mss::workarounds::check_dimm_nest_freq_ratio(l_mcbist, l_mss_freq, l_nest_freq) ); fapi_try_exit: return fapi2::current_err; }// p9_mss_freq }// extern C <commit_msg>Moves count_dimm to be in the memory generic folder<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_freq.C /// @brief Calculate and save off DIMM frequencies /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Louis Stermole <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include <p9_mss_freq.H> // std lib #include <map> #include <utility> // fapi2 #include <fapi2.H> // mss lib #include <generic/memory/lib/spd/common/ddr4/spd_decoder_ddr4.H> #include <lib/spd/spd_factory.H> #include <lib/freq/cas_latency.H> #include <lib/freq/sync.H> #include <lib/workarounds/freq_workarounds.H> #include <generic/memory/lib/utils/c_str.H> #include <generic/memory/lib/utils/find.H> #include <generic/memory/lib/utils/count_dimm.H> #include <generic/memory/lib/utils/index.H> #include <lib/shared/mss_const.H> using fapi2::TARGET_TYPE_MCS; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; using fapi2::TARGET_TYPE_MCBIST; using fapi2::FAPI2_RC_SUCCESS; extern "C" { /// /// @brief Calculate and save off DIMM frequencies /// @param[in] i_target, the controller (e.g., MCS) /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_freq( const fapi2::Target<TARGET_TYPE_MCS>& i_target ) { // TODO RTC:161701 p9_mss_freq needs to be re-worked to work per-MC as it's hard // (if not impossible) to know the appropriate freq if we don't have information // for both MCS. Setting one to max freq doesn't work in the case of 0 DIMM as // there is no check for other freq's and we end up setting the chosen freq to // the default. // So for now, iterate over all the MCBIST. This isn't great as we do this work // twice for every MC. However, attribute access is cheap so this will suffice for // the time being. const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target); std::vector< std::vector<uint64_t> > l_min_dimm_freq(mss::MCS_PER_MC, std::vector<uint64_t> (mss::PORTS_PER_MCS, 0) ); std::vector<uint32_t> l_supported_freqs; uint64_t l_mss_freq = 0; uint32_t l_nest_freq = 0; // If there are no DIMM, we can just get out. if (mss::count_dimm(l_mcbist) == 0) { FAPI_INF("Seeing no DIMM on %s, no freq to set", mss::c_str(l_mcbist)); return FAPI2_RC_SUCCESS; } // Get supported freqs for this MCBIST FAPI_TRY( mss::supported_freqs(l_mcbist, l_supported_freqs) ); for (const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(l_mcbist)) { const auto l_mcs_index = mss::index(l_mcs); std::vector< std::pair< uint64_t, fapi2::Target<fapi2::TARGET_TYPE_MCA>> > l_desired_cas_latency; for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(l_mcs) ) { const auto l_mca_index = mss::index(l_mca); std::vector< std::shared_ptr<mss::spd::decoder> > l_factory_caches; fapi2::ReturnCode l_rc; // Get cached decoder FAPI_TRY( mss::spd::populate_decoder_caches(l_mca, l_factory_caches), "%s. Failed to populate decoder cache", mss::c_str(l_mca) ); // Instantiation of class that calculates CL algorithm mss::cas_latency l_cas_latency( l_mca, l_factory_caches, l_supported_freqs, l_rc ); FAPI_TRY( l_rc, "%s. Failed to initialize cas_latency ctor", mss::c_str(l_mca) ); if(l_cas_latency.iv_dimm_list_empty) { // Cannot fail out for an empty DIMM configuration, so default values are set FAPI_INF("%s. DIMM list is empty! Setting default values for CAS latency and DIMM speed.", mss::c_str(l_mca) ); } else { // We set this to a non-0 so we avoid divide-by-zero errors in the conversions which // go from clocks to time (and vice versa.) We have other bugs if there was really // no MT/s determined and there really is a DIMM installed, so this is ok. // We pick the maximum frequency supported by the system as the default. uint64_t l_desired_cl = 0; l_min_dimm_freq[l_mcs_index][l_mca_index] = fapi2::ENUM_ATTR_MSS_FREQ_MT2666; uint64_t l_tCKmin = 0; // Find CAS latency using JEDEC algorithm FAPI_TRY( l_cas_latency.find_cl(l_desired_cl, l_tCKmin) ); FAPI_INF("%s. Result from CL algorithm, CL (nck): %d, tCK (ps): %d", mss::c_str(l_mca), l_desired_cl, l_tCKmin); l_desired_cas_latency.push_back(std::make_pair(l_desired_cl, l_mca) ); // Find dimm transfer speed from selected tCK FAPI_TRY( mss::ps_to_freq(l_tCKmin, l_min_dimm_freq[l_mcs_index][l_mca_index]), "%s. Failed ps_to_freq()", mss::c_str(l_mca) ); FAPI_INF("DIMM speed from selected tCK (ps): %d for %s", l_min_dimm_freq[l_mcs_index][l_mca_index], mss::c_str(l_mca)); FAPI_INF("%s. Selected DIMM speed from supported speeds: %d", mss::c_str(l_mca), l_min_dimm_freq[l_mcs_index][l_mca_index]); }// end else } // mca FAPI_TRY(mss::set_CL_attr(l_mcs, l_desired_cas_latency), "%s. Failed set_CL_attr()", mss::c_str(i_target) ); } // close for each mcs FAPI_TRY(mss::set_freq_attrs(l_mcbist, l_min_dimm_freq), "%s. Failed set_freq_attrs()", mss::c_str(i_target) ); // Check MEM/NEST frequency ratio FAPI_TRY( mss::freq_pb_mhz(l_nest_freq) ); FAPI_TRY( mss::freq(l_mcbist, l_mss_freq) ); FAPI_TRY( mss::workarounds::check_dimm_nest_freq_ratio(l_mcbist, l_mss_freq, l_nest_freq) ); fapi_try_exit: return fapi2::current_err; }// p9_mss_freq }// extern C <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_common.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_sbe_common.H /// /// @brief Common Modules for SBE //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #ifndef _P9_SBE_COMMON_H_ #define _P9_SBE_COMMON_H_ #include <fapi2.H> fapi2::ReturnCode p9_sbe_common_align_chiplets(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplets); fapi2::ReturnCode p9_sbe_common_clock_start_allRegions(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_anychiplet); fapi2::ReturnCode p9_sbe_common_clock_start_stop(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target, const fapi2::buffer<uint8_t> i_clock_cmd, const bool i_startslave, const bool i_startmaster, const fapi2::buffer<uint64_t> i_regions, const fapi2::buffer<uint8_t> i_clock_types); fapi2::ReturnCode p9_sbe_common_set_scan_ratio(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplets); #endif <commit_msg>IPL optimized codes<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_common.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_sbe_common.H /// /// @brief Common Modules for SBE //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #ifndef _P9_SBE_COMMON_H_ #define _P9_SBE_COMMON_H_ #include <fapi2.H> fapi2::ReturnCode p9_sbe_common_align_chiplets(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplets); fapi2::ReturnCode p9_sbe_common_check_status(const fapi2::buffer<uint64_t> i_regions, const fapi2::buffer<uint64_t> i_clock_status, const bool i_reg, const fapi2::buffer<uint8_t> i_clock_cmd, fapi2::buffer<uint64_t>& o_exp_clock_status); fapi2::ReturnCode p9_sbe_common_clock_start_allRegions(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_anychiplet); fapi2::ReturnCode p9_sbe_common_clock_start_stop(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target, const fapi2::buffer<uint8_t> i_clock_cmd, const bool i_startslave, const bool i_startmaster, const fapi2::buffer<uint64_t> i_regions, const fapi2::buffer<uint8_t> i_clock_types); fapi2::ReturnCode p9_sbe_common_set_scan_ratio(const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplets); #endif <|endoftext|>
<commit_before>#pragma once #include <memory> #include <random> #include "agent.hpp" class position; class alphabeta_pv : public agent { const size_t mask_max; const size_t mask_min; std::unique_ptr<uint64_t[]> pv_max; std::unique_ptr<uint64_t[]> pv_min; std::ranlux24 r{std::random_device{}()}; int eval(const position &, unsigned char depth, int alpha, int beta, bool maximize); public: alphabeta_pv(const heuristic &e, int d, char side); position get_move(const position &); }; <commit_msg>Added a handful of comments.<commit_after>#pragma once #include <memory> #include <random> #include "agent.hpp" class position; /** * An agent which performs alpha beta search, guided by principle variation. */ class alphabeta_pv : public agent { const size_t mask_max; const size_t mask_min; std::unique_ptr<uint64_t[]> pv_max; std::unique_ptr<uint64_t[]> pv_min; std::ranlux24 r{std::random_device{}()}; int eval(const position &, unsigned char depth, int alpha, int beta, bool maximize); public: /** * Constructs a new alphabeta_pv agent. * * @param e The herustic to use to prioritize a given postiion. * @param d The depth to search to. Larger values result in better moves, but * take exponentially more time. * @param side WHITE or BLACK: chooses which side the agent is. */ alphabeta_pv(const heuristic &e, int d, char side); /** * Searches for a good move and returns the best move found. * * @param The current position. * @return The position the board will be in after the agent has executed the * move it chooses. * @throws resign If the agent has lost or chooses to resign. */ position get_move(const position &); }; <|endoftext|>
<commit_before><commit_msg>align fixes for color texts<commit_after><|endoftext|>
<commit_before><commit_msg>Refactor timers tests<commit_after><|endoftext|>
<commit_before>#include "bitfield.h" unsigned long getBitField(uint8_t* data, int startBit, int numBits) { unsigned long ret = 0; int startByte = startBit / 8; if (numBits <= 8 ) { // Bit fields are positioned according to big-endian bit layout, but // inside the bit field, values are represented as little-endian. // Therefore, to get the bit field, we just need to convert to big-endian // bit ordering to find the field, and directly use the value we find in // the field. int bitPosition = startBit % 8; ret = data[startByte]; int endBit = bitPosition + numBits; ret = ret >> (8 - endBit); } else { int endByte = (startBit + numBits) / 8; // The lowest byte address contains the most significant bit. for (int i = startByte; i <= endByte; i++) { ret = ret << 8; ret = ret | data[i]; } //Calculates value to shift bitfield of interest to LSB ret = ret >> (8 - ((startBit + numBits) % 8)); } // Mask out any other bits besides those in the bitfield. unsigned long bitmask = (unsigned long)((0x1 << numBits) - 1); return ret & bitmask; } void setBitField(uint8_t* data, float value, int startPos) { // TODO } <commit_msg>Fix indentation (4 spaces).<commit_after>#include "bitfield.h" unsigned long getBitField(uint8_t* data, int startBit, int numBits) { unsigned long ret = 0; int startByte = startBit / 8; if (numBits <= 8 ) { // Bit fields are positioned according to big-endian bit layout, but // inside the bit field, values are represented as little-endian. // Therefore, to get the bit field, we just need to convert to big-endian // bit ordering to find the field, and directly use the value we find in // the field. int bitPosition = startBit % 8; ret = data[startByte]; int endBit = bitPosition + numBits; ret = ret >> (8 - endBit); } else { int endByte = (startBit + numBits) / 8; // The lowest byte address contains the most significant bit. for (int i = startByte; i <= endByte; i++) { ret = ret << 8; ret = ret | data[i]; } //Calculates value to shift bitfield of interest to LSB ret = ret >> (8 - ((startBit + numBits) % 8)); } // Mask out any other bits besides those in the bitfield. unsigned long bitmask = (unsigned long)((0x1 << numBits) - 1); return ret & bitmask; } void setBitField(uint8_t* data, float value, int startPos) { // TODO } <|endoftext|>
<commit_before>#include <stan/math/prim.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> TEST(MathMatrixPrimMat, append_row) { using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::RowVectorXd; using Eigen::VectorXd; using stan::math::append_row; using std::vector; MatrixXd m33(3, 3); m33 << 1, 2, 3, 4, 5, 6, 7, 8, 9; MatrixXd m32(3, 2); m32 << 11, 12, 13, 14, 15, 16; MatrixXd m23(2, 3); m23 << 21, 22, 23, 24, 25, 26; VectorXd v3(3); v3 << 31, 32, 33; VectorXd v3b(3); v3b << 34, 35, 36; RowVectorXd rv3(3); rv3 << 41, 42, 43; RowVectorXd rv3b(3); rv3b << 44, 45, 46; MatrixXd mat; VectorXd cvec; // matrix append_row(matrix, matrix) mat = append_row(m33, m23); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m33(j, i)); for (int j = 3; j < 5; j++) EXPECT_EQ(mat(j, i), m23(j - 3, i)); } mat = append_row(m23, m33); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) EXPECT_EQ(mat(j, i), m23(j, i)); for (int j = 2; j < 5; j++) EXPECT_EQ(mat(j, i), m33(j - 2, i)); } MatrixXd m32b(2, 3); // ensure some different values m32b = m32 * 1.101; mat = append_row(m32, m32b); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m32(j, i)); for (int j = 3; j < 6; j++) EXPECT_EQ(mat(j, i), m32b(j - 3, i)); } mat = append_row(m32b, m32); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m32b(j, i)); for (int j = 3; j < 6; j++) EXPECT_EQ(mat(j, i), m32(j - 3, i)); } // matrix append_row(matrix, row_vector) // matrix append_row(row_vector, matrix) mat = append_row(m33, rv3); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m33(j, i)); EXPECT_EQ(mat(3, i), rv3(i)); } mat = append_row(rv3, m33); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3(i)); for (int j = 1; j < 4; j++) EXPECT_EQ(mat(j, i), m33(j - 1, i)); } mat = append_row(m23, rv3); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) EXPECT_EQ(mat(j, i), m23(j, i)); EXPECT_EQ(mat(2, i), rv3(i)); } mat = append_row(rv3, m23); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3(i)); for (int j = 1; j < 3; j++) EXPECT_EQ(mat(j, i), m23(j - 1, i)); } // matrix append_row(row_vector, row_vector) mat = append_row(rv3, rv3b); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3(i)); EXPECT_EQ(mat(1, i), rv3b(i)); } mat = append_row(rv3b, rv3); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3b(i)); EXPECT_EQ(mat(1, i), rv3(i)); } // matrix append_row(vector, vector) cvec = append_row(v3, v3b); for (int i = 0; i < 3; i++) EXPECT_EQ(cvec(i), v3(i)); for (int i = 3; i < 6; i++) EXPECT_EQ(cvec(i), v3b(i - 3)); cvec = append_row(v3b, v3); for (int i = 0; i < 3; i++) EXPECT_EQ(cvec(i), v3b(i)); for (int i = 3; i < 6; i++) EXPECT_EQ(cvec(i), v3(i - 3)); // matrix append_row(vector, scalar) cvec = append_row(v3, 3.11); for (int i = 0; i < 3; i++) EXPECT_EQ(cvec(i), v3(i)); EXPECT_EQ(cvec(3), 3.11); // matrix append_row(vector, scalar) cvec = append_row(-6.512, v3); EXPECT_EQ(cvec(0), -6.512); for (int i = 1; i < 4; i++) EXPECT_EQ(cvec(i), v3(i - 1)); EXPECT_THROW(append_row(m32, m33), std::invalid_argument); EXPECT_THROW(append_row(m32, m23), std::invalid_argument); EXPECT_THROW(append_row(m32, v3), std::invalid_argument); EXPECT_THROW(append_row(m32, rv3), std::invalid_argument); EXPECT_THROW(append_row(m33, m32), std::invalid_argument); EXPECT_THROW(append_row(m23, m32), std::invalid_argument); EXPECT_THROW(append_row(v3, m32), std::invalid_argument); EXPECT_THROW(append_row(rv3, m32), std::invalid_argument); EXPECT_THROW(append_row(v3, m33), std::invalid_argument); EXPECT_THROW(append_row(v3, m32), std::invalid_argument); EXPECT_THROW(append_row(v3, rv3), std::invalid_argument); EXPECT_THROW(append_row(m33, v3), std::invalid_argument); EXPECT_THROW(append_row(m32, v3), std::invalid_argument); EXPECT_THROW(append_row(rv3, v3), std::invalid_argument); stan::test::correct_type_matrix(append_row(m23, m33)); stan::test::correct_type_matrix(append_row(m33, m23)); stan::test::correct_type_matrix(append_row(m32, m32b)); stan::test::correct_type_matrix(append_row(m32b, m32)); stan::test::correct_type_matrix(append_row(m33, rv3)); stan::test::correct_type_matrix(append_row(rv3, m33)); stan::test::correct_type_matrix(append_row(m23, rv3)); stan::test::correct_type_matrix(append_row(rv3, m23)); stan::test::correct_type_matrix(append_row(rv3, rv3b)); stan::test:: correct_type_matrix(append_row(rv3b, rv3)); stan::test::correct_type_vector(append_row(v3, v3b)); stan::test::correct_type_vector(append_row(v3b, v3)); stan::test::correct_type_vector(append_row(v3, -4.31)); stan::test::correct_type_vector(append_row(5.23, v3)); } TEST(MathMatrixPrimMat, append_row_different_types) { Eigen::MatrixXd m_d(3, 3); Eigen::MatrixXi m_i(3, 3); EXPECT_NO_THROW(stan::math::append_row(m_d, m_i)); } <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#include <stan/math/prim.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> TEST(MathMatrixPrimMat, append_row) { using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::RowVectorXd; using Eigen::VectorXd; using stan::math::append_row; using std::vector; MatrixXd m33(3, 3); m33 << 1, 2, 3, 4, 5, 6, 7, 8, 9; MatrixXd m32(3, 2); m32 << 11, 12, 13, 14, 15, 16; MatrixXd m23(2, 3); m23 << 21, 22, 23, 24, 25, 26; VectorXd v3(3); v3 << 31, 32, 33; VectorXd v3b(3); v3b << 34, 35, 36; RowVectorXd rv3(3); rv3 << 41, 42, 43; RowVectorXd rv3b(3); rv3b << 44, 45, 46; MatrixXd mat; VectorXd cvec; // matrix append_row(matrix, matrix) mat = append_row(m33, m23); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m33(j, i)); for (int j = 3; j < 5; j++) EXPECT_EQ(mat(j, i), m23(j - 3, i)); } mat = append_row(m23, m33); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) EXPECT_EQ(mat(j, i), m23(j, i)); for (int j = 2; j < 5; j++) EXPECT_EQ(mat(j, i), m33(j - 2, i)); } MatrixXd m32b(2, 3); // ensure some different values m32b = m32 * 1.101; mat = append_row(m32, m32b); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m32(j, i)); for (int j = 3; j < 6; j++) EXPECT_EQ(mat(j, i), m32b(j - 3, i)); } mat = append_row(m32b, m32); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m32b(j, i)); for (int j = 3; j < 6; j++) EXPECT_EQ(mat(j, i), m32(j - 3, i)); } // matrix append_row(matrix, row_vector) // matrix append_row(row_vector, matrix) mat = append_row(m33, rv3); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) EXPECT_EQ(mat(j, i), m33(j, i)); EXPECT_EQ(mat(3, i), rv3(i)); } mat = append_row(rv3, m33); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3(i)); for (int j = 1; j < 4; j++) EXPECT_EQ(mat(j, i), m33(j - 1, i)); } mat = append_row(m23, rv3); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) EXPECT_EQ(mat(j, i), m23(j, i)); EXPECT_EQ(mat(2, i), rv3(i)); } mat = append_row(rv3, m23); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3(i)); for (int j = 1; j < 3; j++) EXPECT_EQ(mat(j, i), m23(j - 1, i)); } // matrix append_row(row_vector, row_vector) mat = append_row(rv3, rv3b); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3(i)); EXPECT_EQ(mat(1, i), rv3b(i)); } mat = append_row(rv3b, rv3); for (int i = 0; i < 3; i++) { EXPECT_EQ(mat(0, i), rv3b(i)); EXPECT_EQ(mat(1, i), rv3(i)); } // matrix append_row(vector, vector) cvec = append_row(v3, v3b); for (int i = 0; i < 3; i++) EXPECT_EQ(cvec(i), v3(i)); for (int i = 3; i < 6; i++) EXPECT_EQ(cvec(i), v3b(i - 3)); cvec = append_row(v3b, v3); for (int i = 0; i < 3; i++) EXPECT_EQ(cvec(i), v3b(i)); for (int i = 3; i < 6; i++) EXPECT_EQ(cvec(i), v3(i - 3)); // matrix append_row(vector, scalar) cvec = append_row(v3, 3.11); for (int i = 0; i < 3; i++) EXPECT_EQ(cvec(i), v3(i)); EXPECT_EQ(cvec(3), 3.11); // matrix append_row(vector, scalar) cvec = append_row(-6.512, v3); EXPECT_EQ(cvec(0), -6.512); for (int i = 1; i < 4; i++) EXPECT_EQ(cvec(i), v3(i - 1)); EXPECT_THROW(append_row(m32, m33), std::invalid_argument); EXPECT_THROW(append_row(m32, m23), std::invalid_argument); EXPECT_THROW(append_row(m32, v3), std::invalid_argument); EXPECT_THROW(append_row(m32, rv3), std::invalid_argument); EXPECT_THROW(append_row(m33, m32), std::invalid_argument); EXPECT_THROW(append_row(m23, m32), std::invalid_argument); EXPECT_THROW(append_row(v3, m32), std::invalid_argument); EXPECT_THROW(append_row(rv3, m32), std::invalid_argument); EXPECT_THROW(append_row(v3, m33), std::invalid_argument); EXPECT_THROW(append_row(v3, m32), std::invalid_argument); EXPECT_THROW(append_row(v3, rv3), std::invalid_argument); EXPECT_THROW(append_row(m33, v3), std::invalid_argument); EXPECT_THROW(append_row(m32, v3), std::invalid_argument); EXPECT_THROW(append_row(rv3, v3), std::invalid_argument); stan::test::correct_type_matrix(append_row(m23, m33)); stan::test::correct_type_matrix(append_row(m33, m23)); stan::test::correct_type_matrix(append_row(m32, m32b)); stan::test::correct_type_matrix(append_row(m32b, m32)); stan::test::correct_type_matrix(append_row(m33, rv3)); stan::test::correct_type_matrix(append_row(rv3, m33)); stan::test::correct_type_matrix(append_row(m23, rv3)); stan::test::correct_type_matrix(append_row(rv3, m23)); stan::test::correct_type_matrix(append_row(rv3, rv3b)); stan::test::correct_type_matrix(append_row(rv3b, rv3)); stan::test::correct_type_vector(append_row(v3, v3b)); stan::test::correct_type_vector(append_row(v3b, v3)); stan::test::correct_type_vector(append_row(v3, -4.31)); stan::test::correct_type_vector(append_row(5.23, v3)); } TEST(MathMatrixPrimMat, append_row_different_types) { Eigen::MatrixXd m_d(3, 3); Eigen::MatrixXi m_i(3, 3); EXPECT_NO_THROW(stan::math::append_row(m_d, m_i)); } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006 Tim Beaulen <[email protected]> Copyright (C) 2006-2007 Matthias Kretz <[email protected]> This program 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiooutput.h" #include <QVector> #include <QtCore/QCoreApplication> #include <sys/ioctl.h> #include <iostream> #include <QSet> #include "mediaobject.h" #include "backend.h" #include "events.h" #include "wirecall.h" #include "xineengine.h" #include "xinethread.h" #include "keepreference.h" #include <xine/audio_out.h> #undef assert typedef QPair<QByteArray, QString> PhononDeviceAccess; typedef QList<PhononDeviceAccess> PhononDeviceAccessList; Q_DECLARE_METATYPE(PhononDeviceAccessList) namespace Phonon { namespace Xine { AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(new AudioOutputXT, parent) { } AudioOutput::~AudioOutput() { //debug() << Q_FUNC_INFO ; } AudioOutputXT::~AudioOutputXT() { if (m_audioPort) { xine_close_audio_driver(m_xine, m_audioPort); m_audioPort = 0; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port destroyed"; } } qreal AudioOutput::volume() const { return m_volume; } int AudioOutput::outputDevice() const { return m_device.index(); } void AudioOutput::setVolume(qreal newVolume) { m_volume = newVolume; int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); emit volumeChanged(m_volume); } xine_audio_port_t *AudioOutputXT::audioPort() const { return m_audioPort; } static QByteArray audioDriverFor(const QByteArray &driver) { if (driver == "alsa" || driver == "oss" || driver == "pulseaudio" || driver == "esd" || driver == "arts" || driver == "jack") { return driver; } return QByteArray(); } static bool lookupConfigEntry(xine_t *xine, const char *key, xine_cfg_entry_t *entry, const char *driver) { if(!xine_config_lookup_entry(xine, key, entry)) { // the config key is not registered yet - it is registered when the output // plugin is opened. So we open the plugin and close it again, then we can set the // setting. :( xine_audio_port_t *port = xine_open_audio_driver(xine, driver, 0); if (port) { xine_close_audio_driver(xine, port); // port == 0 does not have to be fatal, since it might be only the default device // that cannot be opened } // now the config key should be registered if(!xine_config_lookup_entry(xine, key, entry)) { qWarning() << "cannot configure the device on Xine's" << driver << "output plugin"; return false; } } return true; } xine_audio_port_t *AudioOutput::createPort(const AudioOutputDevice &deviceDesc) { K_XT(AudioOutput); xine_audio_port_t *port = 0; const QVariant &deviceAccessListVariant = deviceDesc.property("deviceAccessList"); if (deviceAccessListVariant.isValid()) { const PhononDeviceAccessList &deviceAccessList = qvariant_cast<PhononDeviceAccessList>(deviceAccessListVariant); foreach (const PhononDeviceAccess &access, deviceAccessList) { const QByteArray &outputPlugin = audioDriverFor(access.first); if (outputPlugin.isEmpty()) { continue; } const QString &handle = access.second; if (outputPlugin == "alsa") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); const int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_UNUSED(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "pulseaudio") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.pulseaudio_device", &deviceConfig, "pulseaudio")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "pulseaudio", 0); if (port) { debug() << Q_FUNC_INFO << "use PulseAudio: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "oss") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.oss_device_name", &deviceConfig, "oss")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_ENUM); deviceConfig.num_value = 0; xine_config_update_entry(xt->m_xine, &deviceConfig); if(!xine_config_lookup_entry(xt->m_xine, "audio.device.oss_device_number", &deviceConfig)) { qWarning() << "cannot set the OSS device on Xine's OSS output plugin"; return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_NUM); const QByteArray &deviceStr = handle.toUtf8(); char lastChar = deviceStr[deviceStr.length() - 1]; int deviceNumber = -1; if (lastChar >= '0' || lastChar <= '9') { deviceNumber = lastChar - '0'; char lastChar = deviceStr[deviceStr.length() - 2]; if (lastChar >= '0' || lastChar <= '9') { deviceNumber += 10 * (lastChar - '0'); } } deviceConfig.num_value = deviceNumber; xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "oss", 0); if (port) { debug() << Q_FUNC_INFO << "use OSS device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } } } QVariant v = deviceDesc.property("driver"); if (!v.isValid()) { const QByteArray &outputPlugin = Backend::audioDriverFor(deviceDesc.index()); debug() << Q_FUNC_INFO << "use output plugin:" << outputPlugin; port = xine_open_audio_driver(xt->m_xine, outputPlugin.constData(), 0); } else { const QByteArray &outputPlugin = v.toByteArray(); v = deviceDesc.property("deviceIds"); const QStringList &deviceIds = v.toStringList(); if (deviceIds.isEmpty()) { return 0; } //debug() << Q_FUNC_INFO << outputPlugin << alsaDevices; if (outputPlugin == "alsa") { foreach (const QString &device, deviceIds) { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = device.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << device; break; } } } else if (outputPlugin == "oss") { debug() << Q_FUNC_INFO << "use OSS output"; port = xine_open_audio_driver(xt->m_xine, "oss", 0); } } debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } bool AudioOutput::setOutputDevice(int newDevice) { return setOutputDevice(AudioOutputDevice::fromIndex(newDevice)); } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice) { K_XT(AudioOutput); if (!xt->m_xine) { // remeber the choice until we have a xine_t m_device = newDevice; return true; } xine_audio_port_t *port = createPort(newDevice); if (!port) { debug() << Q_FUNC_INFO << "new audio port is invalid"; return false; } KeepReference<> *keep = new KeepReference<>; keep->addObject(xt); keep->ready(); AudioOutputXT *newXt = new AudioOutputXT; newXt->m_audioPort = port; newXt->m_xine = xt->m_xine; m_threadSafeObject = newXt; m_device = newDevice; SourceNode *src = source(); if (src) { QList<WireCall> wireCall; QList<WireCall> unwireCall; wireCall << WireCall(src, this); unwireCall << WireCall(src, QExplicitlySharedDataPointer<SinkNodeXT>(xt)); QCoreApplication::postEvent(XineThread::instance(), new RewireEvent(wireCall, unwireCall)); graphChanged(); } return true; } void AudioOutput::xineEngineChanged() { K_XT(AudioOutput); if (xt->m_xine) { xine_audio_port_t *port = createPort(m_device); if (!port) { debug() << Q_FUNC_INFO << "stored audio port is invalid"; QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); return; } // our XT object is in a wirecall, better not delete it Q_ASSERT(xt->m_audioPort == 0); xt->m_audioPort = port; } } void AudioOutput::aboutToChangeXineEngine() { K_XT(AudioOutput); if (xt->m_audioPort) { AudioOutputXT *xt2 = new AudioOutputXT; xt2->m_xine = xt->m_xine; xt2->m_audioPort = xt->m_audioPort; xt->m_audioPort = 0; KeepReference<> *keep = new KeepReference<>; keep->addObject(xt2); keep->ready(); } } void AudioOutput::downstreamEvent(Event *e) { Q_ASSERT(e); QCoreApplication::sendEvent(this, e); SinkNode::downstreamEvent(e); } void AudioOutputXT::rewireTo(SourceNodeXT *source) { if (!source->audioOutputPort()) { return; } source->assert(); xine_post_wire_audio_port(source->audioOutputPort(), m_audioPort); source->assert(); SinkNodeXT::assert(); } bool AudioOutput::event(QEvent *ev) { switch (ev->type()) { case Event::AudioDeviceFailed: { ev->accept(); // we don't know for sure which AudioPort failed. but the one without any // capabilities must be the guilty one K_XT(AudioOutput); if (!xt->m_audioPort || xt->m_audioPort->get_capabilities(xt->m_audioPort) == AO_CAP_NOCAP) { QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); } } return true; default: return AbstractAudioOutput::event(ev); } } void AudioOutput::graphChanged() { debug() << Q_FUNC_INFO; // we got connected to a new XineStream, it needs to know our m_volume int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); } }} //namespace Phonon::Xine #include "audiooutput.moc" // vim: sw=4 ts=4 <commit_msg>fix audio device failure. If it's only a specific access method that failed (e.g. pulse server quit) the same device will stay in use, just using ALSA dmix now.<commit_after>/* This file is part of the KDE project Copyright (C) 2006 Tim Beaulen <[email protected]> Copyright (C) 2006-2007 Matthias Kretz <[email protected]> This program 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiooutput.h" #include <QVector> #include <QtCore/QCoreApplication> #include <sys/ioctl.h> #include <iostream> #include <QSet> #include "mediaobject.h" #include "backend.h" #include "events.h" #include "wirecall.h" #include "xineengine.h" #include "xinethread.h" #include "keepreference.h" #include <xine/audio_out.h> #undef assert typedef QPair<QByteArray, QString> PhononDeviceAccess; typedef QList<PhononDeviceAccess> PhononDeviceAccessList; Q_DECLARE_METATYPE(PhononDeviceAccessList) namespace Phonon { namespace Xine { AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(new AudioOutputXT, parent) { } AudioOutput::~AudioOutput() { //debug() << Q_FUNC_INFO ; } AudioOutputXT::~AudioOutputXT() { if (m_audioPort) { xine_close_audio_driver(m_xine, m_audioPort); m_audioPort = 0; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port destroyed"; } } qreal AudioOutput::volume() const { return m_volume; } int AudioOutput::outputDevice() const { return m_device.index(); } void AudioOutput::setVolume(qreal newVolume) { m_volume = newVolume; int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); emit volumeChanged(m_volume); } xine_audio_port_t *AudioOutputXT::audioPort() const { return m_audioPort; } static QByteArray audioDriverFor(const QByteArray &driver) { if (driver == "alsa" || driver == "oss" || driver == "pulseaudio" || driver == "esd" || driver == "arts" || driver == "jack") { return driver; } return QByteArray(); } static bool lookupConfigEntry(xine_t *xine, const char *key, xine_cfg_entry_t *entry, const char *driver) { if(!xine_config_lookup_entry(xine, key, entry)) { // the config key is not registered yet - it is registered when the output // plugin is opened. So we open the plugin and close it again, then we can set the // setting. :( xine_audio_port_t *port = xine_open_audio_driver(xine, driver, 0); if (port) { xine_close_audio_driver(xine, port); // port == 0 does not have to be fatal, since it might be only the default device // that cannot be opened } // now the config key should be registered if(!xine_config_lookup_entry(xine, key, entry)) { qWarning() << "cannot configure the device on Xine's" << driver << "output plugin"; return false; } } return true; } xine_audio_port_t *AudioOutput::createPort(const AudioOutputDevice &deviceDesc) { K_XT(AudioOutput); xine_audio_port_t *port = 0; const QVariant &deviceAccessListVariant = deviceDesc.property("deviceAccessList"); if (deviceAccessListVariant.isValid()) { const PhononDeviceAccessList &deviceAccessList = qvariant_cast<PhononDeviceAccessList>(deviceAccessListVariant); foreach (const PhononDeviceAccess &access, deviceAccessList) { const QByteArray &outputPlugin = audioDriverFor(access.first); if (outputPlugin.isEmpty()) { continue; } const QString &handle = access.second; if (outputPlugin == "alsa") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); const int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_UNUSED(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "pulseaudio") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.pulseaudio_device", &deviceConfig, "pulseaudio")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "pulseaudio", 0); if (port) { debug() << Q_FUNC_INFO << "use PulseAudio: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "oss") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.oss_device_name", &deviceConfig, "oss")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_ENUM); deviceConfig.num_value = 0; xine_config_update_entry(xt->m_xine, &deviceConfig); if(!xine_config_lookup_entry(xt->m_xine, "audio.device.oss_device_number", &deviceConfig)) { qWarning() << "cannot set the OSS device on Xine's OSS output plugin"; return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_NUM); const QByteArray &deviceStr = handle.toUtf8(); char lastChar = deviceStr[deviceStr.length() - 1]; int deviceNumber = -1; if (lastChar >= '0' || lastChar <= '9') { deviceNumber = lastChar - '0'; char lastChar = deviceStr[deviceStr.length() - 2]; if (lastChar >= '0' || lastChar <= '9') { deviceNumber += 10 * (lastChar - '0'); } } deviceConfig.num_value = deviceNumber; xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "oss", 0); if (port) { debug() << Q_FUNC_INFO << "use OSS device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } } } QVariant v = deviceDesc.property("driver"); if (!v.isValid()) { const QByteArray &outputPlugin = Backend::audioDriverFor(deviceDesc.index()); debug() << Q_FUNC_INFO << "use output plugin:" << outputPlugin; port = xine_open_audio_driver(xt->m_xine, outputPlugin.constData(), 0); } else { const QByteArray &outputPlugin = v.toByteArray(); v = deviceDesc.property("deviceIds"); const QStringList &deviceIds = v.toStringList(); if (deviceIds.isEmpty()) { return 0; } //debug() << Q_FUNC_INFO << outputPlugin << alsaDevices; if (outputPlugin == "alsa") { foreach (const QString &device, deviceIds) { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = device.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << device; break; } } } else if (outputPlugin == "oss") { debug() << Q_FUNC_INFO << "use OSS output"; port = xine_open_audio_driver(xt->m_xine, "oss", 0); } } debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } bool AudioOutput::setOutputDevice(int newDevice) { return setOutputDevice(AudioOutputDevice::fromIndex(newDevice)); } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice) { K_XT(AudioOutput); if (!xt->m_xine) { // remeber the choice until we have a xine_t m_device = newDevice; return true; } xine_audio_port_t *port = createPort(newDevice); if (!port) { debug() << Q_FUNC_INFO << "new audio port is invalid"; return false; } KeepReference<> *keep = new KeepReference<>; keep->addObject(xt); keep->ready(); AudioOutputXT *newXt = new AudioOutputXT; newXt->m_audioPort = port; newXt->m_xine = xt->m_xine; m_threadSafeObject = newXt; m_device = newDevice; SourceNode *src = source(); if (src) { QList<WireCall> wireCall; QList<WireCall> unwireCall; wireCall << WireCall(src, this); unwireCall << WireCall(src, QExplicitlySharedDataPointer<SinkNodeXT>(xt)); QCoreApplication::postEvent(XineThread::instance(), new RewireEvent(wireCall, unwireCall)); graphChanged(); } return true; } void AudioOutput::xineEngineChanged() { K_XT(AudioOutput); if (xt->m_xine) { xine_audio_port_t *port = createPort(m_device); if (!port) { debug() << Q_FUNC_INFO << "stored audio port is invalid"; QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); return; } // our XT object is in a wirecall, better not delete it Q_ASSERT(xt->m_audioPort == 0); xt->m_audioPort = port; } } void AudioOutput::aboutToChangeXineEngine() { K_XT(AudioOutput); if (xt->m_audioPort) { AudioOutputXT *xt2 = new AudioOutputXT; xt2->m_xine = xt->m_xine; xt2->m_audioPort = xt->m_audioPort; xt->m_audioPort = 0; KeepReference<> *keep = new KeepReference<>; keep->addObject(xt2); keep->ready(); } } void AudioOutput::downstreamEvent(Event *e) { Q_ASSERT(e); QCoreApplication::sendEvent(this, e); SinkNode::downstreamEvent(e); } void AudioOutputXT::rewireTo(SourceNodeXT *source) { if (!source->audioOutputPort()) { return; } source->assert(); xine_post_wire_audio_port(source->audioOutputPort(), m_audioPort); source->assert(); SinkNodeXT::assert(); } bool AudioOutput::event(QEvent *ev) { switch (ev->type()) { case Event::AudioDeviceFailed: { ev->accept(); // we don't know for sure which AudioPort failed. We also can't know from the // information libxine makes available. So we have to just try the old device again if (setOutputDevice(m_device)) { return true; } // we really need a different output device QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); } return true; default: return AbstractAudioOutput::event(ev); } } void AudioOutput::graphChanged() { debug() << Q_FUNC_INFO; // we got connected to a new XineStream, it needs to know our m_volume int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); } }} //namespace Phonon::Xine #include "audiooutput.moc" // vim: sw=4 ts=4 <|endoftext|>
<commit_before>#include <type_traits> #include <utility> #include "../fakeconcepts.h" #include "../tests/testbench.h" #define Action typename //∨ namespace eop { template<typename T> struct domain_type { typedef T type; }; template<typename T> struct domain_type<void(T&)> { typedef T type; }; template<typename A> using Domain = typename domain_type<A>::type; template<typename T> struct distance_type { typedef int type; }; template<typename T> struct distance_type<void(T&)> { typedef int type; }; template<> struct distance_type<long> { typedef long type; }; template<typename A> using DistanceType = typename distance_type<A>::type; // Exercise 2.6 Rewrite all the algorithms in this chapter in terms of actions // /!\ The following did not compile :( // void power_unary(Domain<A>& x, N n, A a) template<Action A, Integral N, typename D = Domain<A>> void power_unary(D& x, N n, A a) { // Precondition: n≥0 ∧(∀i∈N), 0<i≤n ⇒ a^i(x) is defined while (n != N(0)) { --n; a(x); } } template<Action A, typename D = Domain<A>> DistanceType<A> distance(D& x, const D& y, A a) { // Precondition: y is reachable from x under a typedef DistanceType<A> N; N n(0); while (x != y) { a(x); ++n; } return n; } template<Action A, Predicate P, typename D = Domain<A>> void collision_point(D& x, A a, P p) { // Precondition: p(x) ⇔ a(x) is defined if (!p(x)) return; D slow = x; const D& fast = x; a(fast); while (fast != slow) { if (!p(fast)) return; a(fast); if (!p(fast)) return; a(fast); a(slow); } // Postcondition: x is terminal point or collision_point } template<Action A, Predicate P, typename D = Domain<A>> bool terminating(D& x, A a, P p) { // Precondition: p(x) ⇔ a(x) is defined collision_point(x, a, p); return !p(x); } template<Action A, typename D = Domain<A>> void collision_point_nonterminating_orbit(D& x, A a) { if (!p(x)) return; D slow = x; const D& fast = x; a(fast); while (fast != slow) { a(fast); a(fast); a(slow); } // Postcondition: x is terminal point or collision_point } } namespace { void twice(int& i) { i *= 2; } } TESTBENCH() TEST(check_power_unary) { using namespace eop; static_assert(std::is_same<int, Domain<decltype(twice)>>::value, "Wrong domain type"); auto n = 8; power_unary(n, 4, twice); VERIFY_EQ(128, n) } TEST(check_distance) { using namespace eop; static_assert(std::is_same<int, Domain<decltype(twice)>>::value, "Wrong domain type"); auto x = 8; auto n = distance(x, 128, twice); VERIFY_EQ(4, n) } TESTFIXTURE(eop2)<commit_msg>Added circular.<commit_after>#include <type_traits> #include <utility> #include "../fakeconcepts.h" #include "../tests/testbench.h" #define Action typename //∨ namespace eop { template<typename T> struct domain_type { typedef T type; }; template<typename T> struct domain_type<void(T&)> { typedef T type; }; template<typename A> using Domain = typename domain_type<A>::type; template<typename T> struct distance_type { typedef int type; }; template<typename T> struct distance_type<void(T&)> { typedef int type; }; template<> struct distance_type<long> { typedef long type; }; template<typename A> using DistanceType = typename distance_type<A>::type; // Exercise 2.6 Rewrite all the algorithms in this chapter in terms of actions // /!\ The following did not compile :( // void power_unary(Domain<A>& x, N n, A a) template<Action A, Integral N, typename D = Domain<A>> void power_unary(D& x, N n, A a) { // Precondition: n≥0 ∧(∀i∈N), 0<i≤n ⇒ a^i(x) is defined while (n != N(0)) { --n; a(x); } } template<Action A, typename D = Domain<A>> DistanceType<A> distance(D& x, const D& y, A a) { // Precondition: y is reachable from x under a typedef DistanceType<A> N; N n(0); while (x != y) { a(x); ++n; } return n; } template<Action A, Predicate P, typename D = Domain<A>> void collision_point(D& x, A a, P p) { // Precondition: p(x) ⇔ a(x) is defined if (!p(x)) return; D slow = x; const D& fast = x; a(fast); while (fast != slow) { if (!p(fast)) return; a(fast); if (!p(fast)) return; a(fast); a(slow); } // Postcondition: x is terminal point or collision_point } template<Action A, Predicate P, typename D = Domain<A>> bool terminating(D& x, A a, P p) { // Precondition: p(x) ⇔ a(x) is defined collision_point(x, a, p); return !p(x); } template<Action A, typename D = Domain<A>> void collision_point_nonterminating_orbit(D& x, A a) { if (!p(x)) return; D slow = x; const D& fast = x; a(fast); while (fast != slow) { a(fast); a(fast); a(slow); } // Postcondition: x is terminal point or collision_point } template<Action A, typename D = Domain<A>> bool circular_nonterminating_orbit(D& x, A a) { D t = x; a(collision_point_nonterminating_orbit(x, a)); return t == x; } template<Action A, Predicate P, typename D = Domain<A>> bool circular(D& x, A a, P p) { D t = x; collision_point(x, a, p); if (p(x)) { a(x); return t == x; } return false; } } namespace { void twice(int& i) { i *= 2; } } TESTBENCH() TEST(check_power_unary) { using namespace eop; static_assert(std::is_same<int, Domain<decltype(twice)>>::value, "Wrong domain type"); auto n = 8; power_unary(n, 4, twice); VERIFY_EQ(128, n) } TEST(check_distance) { using namespace eop; static_assert(std::is_same<int, Domain<decltype(twice)>>::value, "Wrong domain type"); auto x = 8; auto n = distance(x, 128, twice); VERIFY_EQ(4, n) } TESTFIXTURE(eop2)<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2007 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include "kismet_datasource.hpp" #include "kismet_featureset.hpp" // network #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> // mapnik #include <mapnik/ptree_helpers.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/bind.hpp> #define MAX_TCP_BUFFER 4096 // maximum accepted TCP data block size // If you change this also change the according sscanf line! #define MAX_KISMET_LINE 1024 // maximum length of a kismet command (assumed) using boost::lexical_cast; using boost::bad_lexical_cast; using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(kismet_datasource) using mapnik::Envelope; using mapnik::coord2d; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; using mapnik::datasource_exception; using namespace std; boost::mutex knd_list_mutex; std::list<kismet_network_data> knd_list; const unsigned int queue_size = 20; kismet_datasource::kismet_datasource(parameters const& params) : datasource(params), extent_(), extent_initialized_(false), type_(datasource::Vector), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")) { //cout << "kismet_datasource::kismet_datasource()" << endl; boost::optional<std::string> host = params.get<std::string>("host"); if (!host) throw datasource_exception("missing <host> paramater"); boost::optional<std::string> port = params.get<std::string>("port"); if (!port) throw datasource_exception("missing <port> paramater"); unsigned int portnr = atoi ((*port).c_str () ); kismet_thread.reset (new boost::thread (boost::bind (&kismet_datasource::run, this, *host, portnr))); boost::optional<std::string> ext = params_.get<std::string>("extent"); if (ext) { boost::char_separator<char> sep(","); boost::tokenizer<boost::char_separator<char> > tok(*ext,sep); unsigned i = 0; bool success = false; double d[4]; for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg) { try { d[i] = boost::lexical_cast<double>(*beg); } catch (boost::bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; break; } if (i==3) { success = true; break; } ++i; } if (success) { extent_.init(d[0],d[1],d[2],d[3]); extent_initialized_ = true; } } } kismet_datasource::~kismet_datasource() { } std::string const kismet_datasource::name_="kismet"; std::string kismet_datasource::name() { return name_; } int kismet_datasource::type() const { return type_; } Envelope<double> kismet_datasource::envelope() const { //cout << "kismet_datasource::envelope()" << endl; return extent_; } layer_descriptor kismet_datasource::get_descriptor() const { return desc_; } featureset_ptr kismet_datasource::features(query const& q) const { //cout << "kismet_datasource::features()" << endl; // TODO: use Envelope to filter bbox before adding to featureset_ptr mapnik::Envelope<double> const& e = q.get_bbox(); boost::mutex::scoped_lock lock(knd_list_mutex); return featureset_ptr (new kismet_featureset(knd_list, desc_.get_encoding())); // TODO: if illegal: // return featureset_ptr(); } featureset_ptr kismet_datasource::features_at_point(coord2d const& pt) const { //cout << "kismet_datasource::features_at_point()" << endl; #if 0 if (dataset_ && layer_) { OGRPoint point; point.setX (pt.x); point.setY (pt.y); layer_->SetSpatialFilter (&point); return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding())); } #endif return featureset_ptr(); } void kismet_datasource::run (const std::string &ip_host, const unsigned int port) { //cout << "+run" << endl; int sockfd, n; struct sockaddr_in sock_addr; struct in_addr inadr; struct hostent *host; char buffer[MAX_TCP_BUFFER]; // TCP data send from kismet_server string command; if (inet_aton(ip_host.c_str (), &inadr)) { host = gethostbyaddr((char *) &inadr, sizeof(inadr), AF_INET); } else { host = gethostbyname(ip_host.c_str ()); } if (host == NULL) { herror ("plugins/input/kismet: Error while searching host"); exit (1); } sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons(port); memcpy(&sock_addr.sin_addr, host->h_addr_list[0], sizeof(sock_addr.sin_addr)); if ( (sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { cerr << "plugins/input/kismet: Error while creating socket" << endl; } if (connect(sockfd, (struct sockaddr *) &sock_addr, sizeof(sock_addr))) { cerr << "plugins/input/kismet: Error while connecting" << endl; } command = "!1 ENABLE NETWORK ssid,bssid,wep,bestlat,bestlon\n"; if (write(sockfd, command.c_str (), command.length ()) != (signed) command.length ()) { cerr << "plugins/input/kismet: Error sending command to " << ip_host << endl; close(sockfd); // TODO: what to do now? } char ssid[MAX_KISMET_LINE] = {}; char bssid[MAX_KISMET_LINE] = {}; double bestlat = 0; double bestlon = 0; int crypt = crypt_none; // BUG: if kismet_server is active sending after mapnik was killed and then restarted the // assert is called. Needs to be analyzed! while ( (n = read(sockfd, buffer, sizeof(buffer))) > 0) { assert (n < MAX_TCP_BUFFER); buffer[n] = '\0'; string bufferObj (buffer); // TCP data send from kismet_server as STL string //cout << "BufferObj: " << endl << bufferObj << "[END]" << endl; string::size_type found = 0; string::size_type search_start = 0; string kismet_line; // contains a line from kismet_server do { found = bufferObj.find ('\n', search_start); if (found != string::npos) { kismet_line.assign (bufferObj, search_start, found - search_start); //cout << "Line: " << kismet_line << "[ENDL]" << endl; int param_number = 5; // the number of parameters to parse // Attention: string length specified to the constant! if (sscanf (kismet_line.c_str (), "*NETWORK: \001%1024[^\001]\001 %1024s %d %lf %lf", ssid, bssid, &crypt, &bestlat, &bestlon) == param_number) { //printf ("ssid=%s, bssid=%s, crypt=%d, bestlat=%f, bestlon=%f\n", ssid, bssid, crypt, bestlat, bestlon); kismet_network_data knd (ssid, bssid, bestlat, bestlon, crypt); boost::mutex::scoped_lock lock(knd_list_mutex); // the queue only grows to a max size if (knd_list.size () >= queue_size) { knd_list.pop_front (); } knd_list.push_back (knd); } else { // do nothing if not matched! } search_start = found + 1; } } while (found != string::npos); } if (n < 0) { cerr << "plugins/input/kismet: Error while reading from socket" << endl; } close(sockfd); //cout << "-run" << endl; } <commit_msg>kismet: avoid compiler errors due to unused variable<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2007 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include "kismet_datasource.hpp" #include "kismet_featureset.hpp" // network #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> // mapnik #include <mapnik/ptree_helpers.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/bind.hpp> #define MAX_TCP_BUFFER 4096 // maximum accepted TCP data block size // If you change this also change the according sscanf line! #define MAX_KISMET_LINE 1024 // maximum length of a kismet command (assumed) using boost::lexical_cast; using boost::bad_lexical_cast; using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(kismet_datasource) using mapnik::Envelope; using mapnik::coord2d; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; using mapnik::datasource_exception; using namespace std; boost::mutex knd_list_mutex; std::list<kismet_network_data> knd_list; const unsigned int queue_size = 20; kismet_datasource::kismet_datasource(parameters const& params) : datasource(params), extent_(), extent_initialized_(false), type_(datasource::Vector), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")) { //cout << "kismet_datasource::kismet_datasource()" << endl; boost::optional<std::string> host = params.get<std::string>("host"); if (!host) throw datasource_exception("missing <host> paramater"); boost::optional<std::string> port = params.get<std::string>("port"); if (!port) throw datasource_exception("missing <port> paramater"); unsigned int portnr = atoi ((*port).c_str () ); kismet_thread.reset (new boost::thread (boost::bind (&kismet_datasource::run, this, *host, portnr))); boost::optional<std::string> ext = params_.get<std::string>("extent"); if (ext) { boost::char_separator<char> sep(","); boost::tokenizer<boost::char_separator<char> > tok(*ext,sep); unsigned i = 0; bool success = false; double d[4]; for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg) { try { d[i] = boost::lexical_cast<double>(*beg); } catch (boost::bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; break; } if (i==3) { success = true; break; } ++i; } if (success) { extent_.init(d[0],d[1],d[2],d[3]); extent_initialized_ = true; } } } kismet_datasource::~kismet_datasource() { } std::string const kismet_datasource::name_="kismet"; std::string kismet_datasource::name() { return name_; } int kismet_datasource::type() const { return type_; } Envelope<double> kismet_datasource::envelope() const { //cout << "kismet_datasource::envelope()" << endl; return extent_; } layer_descriptor kismet_datasource::get_descriptor() const { return desc_; } featureset_ptr kismet_datasource::features(query const& q) const { //cout << "kismet_datasource::features()" << endl; // TODO: use Envelope to filter bbox before adding to featureset_ptr //mapnik::Envelope<double> const& e = q.get_bbox(); boost::mutex::scoped_lock lock(knd_list_mutex); return featureset_ptr (new kismet_featureset(knd_list, desc_.get_encoding())); // TODO: if illegal: // return featureset_ptr(); } featureset_ptr kismet_datasource::features_at_point(coord2d const& pt) const { //cout << "kismet_datasource::features_at_point()" << endl; #if 0 if (dataset_ && layer_) { OGRPoint point; point.setX (pt.x); point.setY (pt.y); layer_->SetSpatialFilter (&point); return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding())); } #endif return featureset_ptr(); } void kismet_datasource::run (const std::string &ip_host, const unsigned int port) { //cout << "+run" << endl; int sockfd, n; struct sockaddr_in sock_addr; struct in_addr inadr; struct hostent *host; char buffer[MAX_TCP_BUFFER]; // TCP data send from kismet_server string command; if (inet_aton(ip_host.c_str (), &inadr)) { host = gethostbyaddr((char *) &inadr, sizeof(inadr), AF_INET); } else { host = gethostbyname(ip_host.c_str ()); } if (host == NULL) { herror ("plugins/input/kismet: Error while searching host"); exit (1); } sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons(port); memcpy(&sock_addr.sin_addr, host->h_addr_list[0], sizeof(sock_addr.sin_addr)); if ( (sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { cerr << "plugins/input/kismet: Error while creating socket" << endl; } if (connect(sockfd, (struct sockaddr *) &sock_addr, sizeof(sock_addr))) { cerr << "plugins/input/kismet: Error while connecting" << endl; } command = "!1 ENABLE NETWORK ssid,bssid,wep,bestlat,bestlon\n"; if (write(sockfd, command.c_str (), command.length ()) != (signed) command.length ()) { cerr << "plugins/input/kismet: Error sending command to " << ip_host << endl; close(sockfd); // TODO: what to do now? } char ssid[MAX_KISMET_LINE] = {}; char bssid[MAX_KISMET_LINE] = {}; double bestlat = 0; double bestlon = 0; int crypt = crypt_none; // BUG: if kismet_server is active sending after mapnik was killed and then restarted the // assert is called. Needs to be analyzed! while ( (n = read(sockfd, buffer, sizeof(buffer))) > 0) { assert (n < MAX_TCP_BUFFER); buffer[n] = '\0'; string bufferObj (buffer); // TCP data send from kismet_server as STL string //cout << "BufferObj: " << endl << bufferObj << "[END]" << endl; string::size_type found = 0; string::size_type search_start = 0; string kismet_line; // contains a line from kismet_server do { found = bufferObj.find ('\n', search_start); if (found != string::npos) { kismet_line.assign (bufferObj, search_start, found - search_start); //cout << "Line: " << kismet_line << "[ENDL]" << endl; int param_number = 5; // the number of parameters to parse // Attention: string length specified to the constant! if (sscanf (kismet_line.c_str (), "*NETWORK: \001%1024[^\001]\001 %1024s %d %lf %lf", ssid, bssid, &crypt, &bestlat, &bestlon) == param_number) { //printf ("ssid=%s, bssid=%s, crypt=%d, bestlat=%f, bestlon=%f\n", ssid, bssid, crypt, bestlat, bestlon); kismet_network_data knd (ssid, bssid, bestlat, bestlon, crypt); boost::mutex::scoped_lock lock(knd_list_mutex); // the queue only grows to a max size if (knd_list.size () >= queue_size) { knd_list.pop_front (); } knd_list.push_back (knd); } else { // do nothing if not matched! } search_start = found + 1; } } while (found != string::npos); } if (n < 0) { cerr << "plugins/input/kismet: Error while reading from socket" << endl; } close(sockfd); //cout << "-run" << endl; } <|endoftext|>
<commit_before>#ifndef BAULK_RCWRITER_HPP #define BAULK_RCWRITER_HPP #include <string> #include <string_view> #include <bela/strcat.hpp> /***** //Microsoft Visual C++ generated resource script. // #include "windows.h" ///////////////////////////////////////////////////////////////////////////// //@MANIFEST VS_VERSION_INFO VERSIONINFO FILEVERSION @FileMajorPart, @FileMinorPart, @FileBuildPart, @FilePrivatePart PRODUCTVERSION @FileMajorPart, @FileMinorPart, @FileBuildPart, @FilePrivatePart FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000904b0" BEGIN VALUE "CompanyName", L"@CompanyName" VALUE "FileDescription", L"@FileDescription" VALUE "FileVersion", L"@FileVersion" VALUE "InternalName", L"@InternalName" VALUE "LegalCopyright", L"@LegalCopyright" VALUE "OriginalFilename", L"@OriginalFilename" VALUE "ProductName", L"@ProductName" VALUE "ProductVersion", L"@ProductVersion" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x9, 1200 END END #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ****/ namespace baulk::rc { class Writer { public: Writer() { buffer.reserve(4096); } Writer(const Writer &) = delete; Writer &operator=(const Writer &) = delete; Writer &Prefix() { buffer.assign(L"//Baulk generated resource script.\n#include " L"\"windows.h\"\n\nVS_VERSION_INFO VERSIONINFO\n"); return *this; } Writer &FileVersion(int MajorPart, int MinorPart, int BuildPart, int PrivatePart) { bela::StrAppend(&buffer, L"FILEVERSION ", MajorPart, L", ", MinorPart, L", ", BuildPart, L", ", PrivatePart); return *this; } Writer &ProductVersion(int MajorPart, int MinorPart, int BuildPart, int PrivatePart) { bela::StrAppend(&buffer, L"FILEVERSION ", MajorPart, L", ", MinorPart, L", ", BuildPart, L", ", PrivatePart); return *this; } Writer &PreVersion() { buffer.append( L"FILEFLAGSMASK 0x3fL\nFILEFLAGS 0x0L\nFILEOS 0x40004L\nFILETYPE " L"0x1L\nFILESUBTYPE 0x0L\nBEGIN\nBLOCK " L"\"StringFileInfo\"\nBEGIN\nBLOCK \"000904b0\"\nBEGIN\n"); return *this; } Writer &Version(std::wstring_view name, std::wstring_view value) { bela::StrAppend(&buffer, L"VALUE \"", name, L"\" L\"", value, L"\"\n"); return *this; } Writer &AfterVersion() { buffer.append(L"END\nEND\nBLOCK \"VarFileInfo\"\nBEGIN\nVALUE " L"\"Translation\", 0x9, 1200\nEND\nEND\n\n"); return *this; } bool FlushFile(std::wstring_view file) const { (void)file; return true; } private: std::wstring buffer; }; } // namespace baulk::rc #endif <commit_msg>[baulk] Add MakeVersionPart<commit_after>#ifndef BAULK_RCWRITER_HPP #define BAULK_RCWRITER_HPP #include <string> #include <string_view> #include <bela/strcat.hpp> #include <bela/str_split.hpp> /***** //Microsoft Visual C++ generated resource script. // #include "windows.h" ///////////////////////////////////////////////////////////////////////////// //@MANIFEST VS_VERSION_INFO VERSIONINFO FILEVERSION @FileMajorPart, @FileMinorPart, @FileBuildPart, @FilePrivatePart PRODUCTVERSION @FileMajorPart, @FileMinorPart, @FileBuildPart, @FilePrivatePart FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000904b0" BEGIN VALUE "CompanyName", L"@CompanyName" VALUE "FileDescription", L"@FileDescription" VALUE "FileVersion", L"@FileVersion" VALUE "InternalName", L"@InternalName" VALUE "LegalCopyright", L"@LegalCopyright" VALUE "OriginalFilename", L"@OriginalFilename" VALUE "ProductName", L"@ProductName" VALUE "ProductVersion", L"@ProductVersion" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x9, 1200 END END #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ****/ namespace baulk::rc { struct VersionPart { int MajorPart{0}; int MinorPart{0}; int BuildPart{0}; int PrivatePart{0}; }; inline VersionPart MakeVersionPart(std::wstring_view vs) { VersionPart vp; std::vector<std::wstring_view> vsv = bela::StrSplit(vs, bela::ByChar('.'), bela::SkipEmpty()); if (!vsv.empty()) { bela::SimpleAtoi(vsv[0], &vp.MajorPart); } if (vsv.size() > 1) { bela::SimpleAtoi(vsv[1], &vp.MinorPart); } if (vsv.size() > 2) { bela::SimpleAtoi(vsv[2], &vp.BuildPart); } if (vsv.size() > 3) { bela::SimpleAtoi(vsv[3], &vp.PrivatePart); } return vp; } class Writer { public: Writer() { buffer.reserve(4096); } Writer(const Writer &) = delete; Writer &operator=(const Writer &) = delete; Writer &Prefix() { buffer.assign(L"//Baulk generated resource script.\n#include " L"\"windows.h\"\n\nVS_VERSION_INFO VERSIONINFO\n"); return *this; } Writer &FileVersion(int MajorPart, int MinorPart, int BuildPart, int PrivatePart) { bela::StrAppend(&buffer, L"FILEVERSION ", MajorPart, L", ", MinorPart, L", ", BuildPart, L", ", PrivatePart); return *this; } Writer &ProductVersion(int MajorPart, int MinorPart, int BuildPart, int PrivatePart) { bela::StrAppend(&buffer, L"FILEVERSION ", MajorPart, L", ", MinorPart, L", ", BuildPart, L", ", PrivatePart); return *this; } Writer &PreVersion() { buffer.append( L"FILEFLAGSMASK 0x3fL\nFILEFLAGS 0x0L\nFILEOS 0x40004L\nFILETYPE " L"0x1L\nFILESUBTYPE 0x0L\nBEGIN\nBLOCK " L"\"StringFileInfo\"\nBEGIN\nBLOCK \"000904b0\"\nBEGIN\n"); return *this; } Writer &Version(std::wstring_view name, std::wstring_view value) { bela::StrAppend(&buffer, L"VALUE \"", name, L"\" L\"", value, L"\"\n"); return *this; } Writer &AfterVersion() { buffer.append(L"END\nEND\nBLOCK \"VarFileInfo\"\nBEGIN\nVALUE " L"\"Translation\", 0x9, 1200\nEND\nEND\n\n"); return *this; } bool FlushFile(std::wstring_view file) const { (void)file; return true; } private: std::wstring buffer; }; } // namespace baulk::rc #endif <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <itkImage.h> #include "itkFilterWatcher.h" #include <itkExceptionObject.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkTubeNJetImageFunction.h> int itkTubeNJetImageFunctionTest(int argc, char* argv [] ) { if( argc < 4 ) { std::cerr << "Missing arguments." << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " function inputImage outputImage" << std::endl; return EXIT_FAILURE; } // Define the dimension of the images const unsigned int Dimension = 2; // Define the pixel type typedef float PixelType; // Declare the types of the images typedef itk::Image<PixelType, Dimension> ImageType; // Declare the reader and writer typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; // Declare the type for the Filter typedef itk::tube::NJetImageFunction< ImageType > FunctionType; // Create the reader and writer ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); try { reader->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception caught during read:\n" << e; return EXIT_FAILURE; } ImageType::Pointer inputImage = reader->GetOutput(); typedef itk::tube::NJetImageFunction< ImageType > FunctionType; FunctionType::Pointer func = FunctionType::New(); func->SetInputImage( inputImage ); ImageType::Pointer outputImage = ImageType::New(); outputImage->CopyInformation( inputImage ); outputImage->SetRegions( inputImage->GetLargestPossibleRegion() ); outputImage->Allocate(); bool error = false; func->ComputeStatistics(); func->SetUseProjection( false ); double minI = 0; double maxI = 255; if( func->GetMin() != 0 ) { error = true; std::cerr << "Min = " << func->GetMin() << " != " << minI << std::endl; } if( func->GetMax() != maxI ) { error = true; std::cerr << "Max = " << func->GetMax() << " != " << maxI << std::endl; } double scale = 4.0; FunctionType::VectorType v1, v2, d; v1.Fill( 0 ); v1[0] = 1; v2.Fill( 0 ); v2[1] = 1; double val; double val2; FunctionType::MatrixType h; FunctionType::MatrixType h2; int function = atoi( argv[1] ); itk::ImageRegionIteratorWithIndex< ImageType > outIter( outputImage, outputImage->GetLargestPossibleRegion() ); ImageType::PointType pnt; outIter.GoToBegin(); while( !outIter.IsAtEnd() ) { inputImage->TransformIndexToPhysicalPoint( outIter.GetIndex(), pnt); switch( function ) { case 0: { outIter.Set( func->Evaluate( pnt, scale ) ); break; } case 1: { outIter.Set( func->Evaluate( pnt, v1, scale ) ); break; } case 2: { outIter.Set( func->Evaluate( pnt, v1, v2, scale ) ); break; } case 3: { outIter.Set( func->EvaluateAtIndex( outIter.GetIndex(), scale ) ); break; } case 4: { outIter.Set( func->EvaluateAtIndex( outIter.GetIndex(), v1, scale ) ); break; } case 5: { outIter.Set( func->EvaluateAtIndex( outIter.GetIndex(), v1, v2, scale ) ); break; } case 6: { func->Derivative( pnt, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 7: { func->Derivative( pnt, v1, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 8: { func->Derivative( pnt, v1, v2, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 9: { func->DerivativeAtIndex( outIter.GetIndex(), scale, d ); outIter.Set( d[0]+d[1] ); break; } case 10: { func->DerivativeAtIndex( outIter.GetIndex(), v1, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 11: { func->DerivativeAtIndex( outIter.GetIndex(), v1, v2, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 12: { func->Derivative( pnt, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 13: { func->Derivative(pnt, v1, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 14: { func->Derivative(pnt, v1, v2, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 15: { func->DerivativeAtIndex( outIter.GetIndex(), scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 16: { func->DerivativeAtIndex( outIter.GetIndex(), v1, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 17: { func->DerivativeAtIndex( outIter.GetIndex(), v1, v2, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 18: { val = func->Jet( pnt, d, h, scale ); outIter.Set( val+d[0]+d[1]+(h[0][0]+h[1][1]) ); break; } case 19: { val = func->JetAtIndex( outIter.GetIndex(), d, h, scale ); outIter.Set( val+d[0]+d[1]+(h[0][0]+h[1][1]) ); break; } case 20: { val = func->Ridgeness( pnt, scale ); outIter.Set( val ); break; } case 21: { val = func->Ridgeness( pnt, v1, scale ); outIter.Set( val ); break; } case 22: { val = func->Ridgeness( pnt, v1, v2, scale ); outIter.Set( val ); break; } case 23: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); outIter.Set( val ); break; } case 24: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, scale ); outIter.Set( val ); break; } case 25: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, v2, scale ); outIter.Set( val ); break; } case 26: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, v2, scale ); h = func->GetMostRecentHessian(); outIter.Set( h[0][0] * h[1][1] + h[0][1] * h[1][0] ); break; } case 27: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); val2 = func->GetMostRecentRidgeness(); if( val != val2 ) { error = true; std::cerr << "Ridgeness and recent ridgeness differ at " << outIter.GetIndex() << std::endl; outIter.Set( val-val2 ); } else { outIter.Set( 0 ); } break; } case 28: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); h = func->GetMostRecentHessian(); val2 = func->HessianAtIndex( outIter.GetIndex(), scale, h2 ); val = vnl_math_abs( h[0][0] - h2[0][0] ) + vnl_math_abs( h[0][1] - h2[0][1] ) + vnl_math_abs( h[1][0] - h2[1][0] ) + vnl_math_abs( h[1][1] - h2[1][1] ); if( val > 0.0001 ) { error = true; std::cerr << "Ridgeness Hessian and Hessian differ at " << outIter.GetIndex() << std::endl; outIter.Set( val ); } else { outIter.Set( 0 ); } break; } case 29: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); d = func->GetMostRecentDerivative(); if( d.GetNorm() != 0 ) { d.Normalize(); } else { d.Fill( 0 ); } outIter.Set( val+d[0]+d[1] ); break; } case 30: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, scale ); d = func->GetMostRecentDerivative(); if( d.GetNorm() != 0 ) { d.Normalize(); } else { d.Fill( 0 ); } outIter.Set( val+d[0]+d[1] ); break; } case 31: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, v2, scale ); d = func->GetMostRecentDerivative(); if( d.GetNorm() != 0 ) { d.Normalize(); } else { d.Fill( 0 ); } outIter.Set( val+d[0]+d[1] ); break; } case 32: { func->Hessian( pnt, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 33: { func->Hessian( pnt, v1, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 34: { func->Hessian( pnt, v1, v2, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 35: { func->HessianAtIndex( outIter.GetIndex(), scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 36: { func->HessianAtIndex( outIter.GetIndex(), v1, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 37: { func->HessianAtIndex( outIter.GetIndex(), v1, v2, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } } ++outIter; } WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( outputImage ); writer->SetUseCompression( true ); try { writer->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception caught during write:\n" << e; return EXIT_FAILURE; } // All objects should be automatically destroyed at this point if( !error ) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } <commit_msg>ENH: Modified itkTubeNJetImageFunctionTest for more thorough ridgeness eval<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <itkImage.h> #include "itkFilterWatcher.h" #include <itkExceptionObject.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkTubeNJetImageFunction.h> int itkTubeNJetImageFunctionTest(int argc, char* argv [] ) { if( argc < 4 ) { std::cerr << "Missing arguments." << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " function inputImage outputImage" << std::endl; return EXIT_FAILURE; } // Define the dimension of the images const unsigned int Dimension = 2; // Define the pixel type typedef float PixelType; // Declare the types of the images typedef itk::Image<PixelType, Dimension> ImageType; // Declare the reader and writer typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; // Declare the type for the Filter typedef itk::tube::NJetImageFunction< ImageType > FunctionType; // Create the reader and writer ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); try { reader->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception caught during read:\n" << e; return EXIT_FAILURE; } ImageType::Pointer inputImage = reader->GetOutput(); typedef itk::tube::NJetImageFunction< ImageType > FunctionType; FunctionType::Pointer func = FunctionType::New(); func->SetInputImage( inputImage ); ImageType::Pointer outputImage = ImageType::New(); outputImage->CopyInformation( inputImage ); outputImage->SetRegions( inputImage->GetLargestPossibleRegion() ); outputImage->Allocate(); bool error = false; func->ComputeStatistics(); func->SetUseProjection( false ); double minI = 0; double maxI = 255; if( func->GetMin() != 0 ) { error = true; std::cerr << "Min = " << func->GetMin() << " != " << minI << std::endl; } if( func->GetMax() != maxI ) { error = true; std::cerr << "Max = " << func->GetMax() << " != " << maxI << std::endl; } double scale = 0.5; FunctionType::VectorType v1, v2, d; v1.Fill( 0 ); v1[0] = 1; v2.Fill( 0 ); v2[1] = 1; double val; double val2; FunctionType::MatrixType h; FunctionType::MatrixType h2; int function = atoi( argv[1] ); itk::ImageRegionIteratorWithIndex< ImageType > outIter( outputImage, outputImage->GetLargestPossibleRegion() ); ImageType::PointType pnt; outIter.GoToBegin(); while( !outIter.IsAtEnd() ) { inputImage->TransformIndexToPhysicalPoint( outIter.GetIndex(), pnt); switch( function ) { case 0: { outIter.Set( func->Evaluate( pnt, scale ) ); break; } case 1: { outIter.Set( func->Evaluate( pnt, v1, scale ) ); break; } case 2: { outIter.Set( func->Evaluate( pnt, v1, v2, scale ) ); break; } case 3: { outIter.Set( func->EvaluateAtIndex( outIter.GetIndex(), scale ) ); break; } case 4: { outIter.Set( func->EvaluateAtIndex( outIter.GetIndex(), v1, scale ) ); break; } case 5: { outIter.Set( func->EvaluateAtIndex( outIter.GetIndex(), v1, v2, scale ) ); break; } case 6: { func->Derivative( pnt, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 7: { func->Derivative( pnt, v1, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 8: { func->Derivative( pnt, v1, v2, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 9: { func->DerivativeAtIndex( outIter.GetIndex(), scale, d ); outIter.Set( d[0]+d[1] ); break; } case 10: { func->DerivativeAtIndex( outIter.GetIndex(), v1, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 11: { func->DerivativeAtIndex( outIter.GetIndex(), v1, v2, scale, d ); outIter.Set( d[0]+d[1] ); break; } case 12: { func->Derivative( pnt, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 13: { func->Derivative(pnt, v1, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 14: { func->Derivative(pnt, v1, v2, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 15: { func->DerivativeAtIndex( outIter.GetIndex(), scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 16: { func->DerivativeAtIndex( outIter.GetIndex(), v1, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 17: { func->DerivativeAtIndex( outIter.GetIndex(), v1, v2, scale, d ); val = func->GetMostRecentIntensity(); outIter.Set( val+(d[0]+d[1]) ); break; } case 18: { val = func->Jet( pnt, d, h, scale ); outIter.Set( val+d[0]+d[1]+(h[0][0]+h[1][1]) ); break; } case 19: { val = func->JetAtIndex( outIter.GetIndex(), d, h, scale ); outIter.Set( val+d[0]+d[1]+(h[0][0]+h[1][1]) ); break; } case 20: { val = func->Ridgeness( pnt, scale ); outIter.Set( val ); break; } case 21: { val = func->Ridgeness( pnt, scale ); val = func->GetMostRecentRidgeLevelness(); outIter.Set( val ); break; } case 22: { val = func->Ridgeness( pnt, scale ); val = func->GetMostRecentRidgeRoundness(); outIter.Set( val ); break; } case 23: { val = func->Ridgeness( pnt, scale ); val = func->GetMostRecentRidgeCurvature(); outIter.Set( val ); break; } case 24: { val = func->Ridgeness( pnt, scale ); val *= func->GetMostRecentRidgeLevelness(); val *= func->GetMostRecentRidgeRoundness(); val *= func->GetMostRecentRidgeCurvature(); outIter.Set( val ); break; } case 25: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, v2, scale ); outIter.Set( val ); break; } case 26: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, v2, scale ); h = func->GetMostRecentHessian(); outIter.Set( h[0][0] * h[1][1] + h[0][1] * h[1][0] ); break; } case 27: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); val2 = func->GetMostRecentRidgeness(); if( val != val2 ) { error = true; std::cerr << "Ridgeness and recent ridgeness differ at " << outIter.GetIndex() << std::endl; outIter.Set( val-val2 ); } else { outIter.Set( 0 ); } break; } case 28: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); h = func->GetMostRecentHessian(); val2 = func->HessianAtIndex( outIter.GetIndex(), scale, h2 ); val = vnl_math_abs( h[0][0] - h2[0][0] ) + vnl_math_abs( h[0][1] - h2[0][1] ) + vnl_math_abs( h[1][0] - h2[1][0] ) + vnl_math_abs( h[1][1] - h2[1][1] ); if( val > 0.0001 ) { error = true; std::cerr << "Ridgeness Hessian and Hessian differ at " << outIter.GetIndex() << std::endl; outIter.Set( val ); } else { outIter.Set( 0 ); } break; } case 29: { val = func->RidgenessAtIndex( outIter.GetIndex(), scale ); d = func->GetMostRecentDerivative(); if( d.GetNorm() != 0 ) { d.Normalize(); } else { d.Fill( 0 ); } outIter.Set( val+d[0]+d[1] ); break; } case 30: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, scale ); d = func->GetMostRecentDerivative(); if( d.GetNorm() != 0 ) { d.Normalize(); } else { d.Fill( 0 ); } outIter.Set( val+d[0]+d[1] ); break; } case 31: { val = func->RidgenessAtIndex( outIter.GetIndex(), v1, v2, scale ); d = func->GetMostRecentDerivative(); if( d.GetNorm() != 0 ) { d.Normalize(); } else { d.Fill( 0 ); } outIter.Set( val+d[0]+d[1] ); break; } case 32: { func->Hessian( pnt, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 33: { func->Hessian( pnt, v1, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 34: { func->Hessian( pnt, v1, v2, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 35: { func->HessianAtIndex( outIter.GetIndex(), scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 36: { func->HessianAtIndex( outIter.GetIndex(), v1, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } case 37: { func->HessianAtIndex( outIter.GetIndex(), v1, v2, scale, h ); outIter.Set( h[0][0]+h[1][1] ); break; } } ++outIter; } WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( outputImage ); writer->SetUseCompression( true ); try { writer->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception caught during write:\n" << e; return EXIT_FAILURE; } // All objects should be automatically destroyed at this point if( !error ) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } <|endoftext|>
<commit_before>//===--- Format.cpp -----------------------------------------*- C++-*------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Format.h" #include "Logger.h" #include "clang/Basic/SourceManager.h" #include "clang/Format/Format.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Core/Replacement.h" #include "llvm/Support/Unicode.h" namespace clang { namespace clangd { namespace { /// Append closing brackets )]} to \p Code to make it well-formed. /// Clang-format conservatively refuses to format files with unmatched brackets /// as it isn't sure where the errors are and so can't correct. /// When editing, it's reasonable to assume code before the cursor is complete. void closeBrackets(std::string &Code, const format::FormatStyle &Style) { SourceManagerForFile FileSM("dummy.cpp", Code); auto &SM = FileSM.get(); FileID FID = SM.getMainFileID(); Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style)); Token Tok; std::vector<char> Brackets; while (!Lex.LexFromRawLexer(Tok)) { switch(Tok.getKind()) { case tok::l_paren: Brackets.push_back(')'); break; case tok::l_brace: Brackets.push_back('}'); break; case tok::l_square: Brackets.push_back(']'); break; case tok::r_paren: if (!Brackets.empty() && Brackets.back() == ')') Brackets.pop_back(); break; case tok::r_brace: if (!Brackets.empty() && Brackets.back() == '}') Brackets.pop_back(); break; case tok::r_square: if (!Brackets.empty() && Brackets.back() == ']') Brackets.pop_back(); break; default: continue; } } // Attempt to end any open comments first. Code.append("\n// */\n"); Code.append(Brackets.rbegin(), Brackets.rend()); } static StringRef commentMarker(llvm::StringRef Line) { for (StringRef Marker : {"///", "//"}){ auto I = Line.rfind(Marker); if (I != StringRef::npos) return Line.substr(I, Marker.size()); } return ""; } llvm::StringRef firstLine(llvm::StringRef Code) { return Code.take_until([](char C) { return C == '\n'; }); } llvm::StringRef lastLine(llvm::StringRef Code) { llvm::StringRef Rest = Code; while (!Rest.empty() && Rest.back() != '\n') Rest = Rest.drop_back(); return Code.substr(Rest.size()); } // Filename is needed for tooling::Replacement and some overloads of reformat(). // Its value should not affect the outcome. We use the default from reformat(). llvm::StringRef Filename = "<stdin>"; // tooling::Replacement from overlapping StringRefs: From must be part of Code. tooling::Replacement replacement(llvm::StringRef Code, llvm::StringRef From, llvm::StringRef To) { assert(From.begin() >= Code.begin() && From.end() <= Code.end()); // The filename is required but ignored. return tooling::Replacement(Filename, From.data() - Code.data(), From.size(), To); }; // High-level representation of incremental formatting changes. // The changes are made in two steps. // 1) a (possibly-empty) set of changes synthesized by clangd (e.g. adding // comment markers when splitting a line comment with a newline). // 2) a selective clang-format run: // - the "source code" passed to clang format is the code up to the cursor, // a placeholder for the cursor, and some closing brackets // - the formatting is restricted to the cursor and (possibly) other ranges // (e.g. the old line when inserting a newline). // - changes before the cursor are applied, those after are discarded. struct IncrementalChanges { // Changes that should be applied before running clang-format. tooling::Replacements Changes; // Ranges of the original source code that should be clang-formatted. // The CursorProxyText will also be formatted. std::vector<tooling::Range> FormatRanges; // The source code that should stand in for the cursor when clang-formatting. // e.g. after inserting a newline, a line-comment at the cursor is used to // ensure that the newline is preserved. std::string CursorPlaceholder; }; // After a newline: // - we continue any line-comment that was split // - we format the old line in addition to the cursor // - we represent the cursor with a line comment to preserve the newline IncrementalChanges getIncrementalChangesAfterNewline(llvm::StringRef Code, unsigned Cursor) { IncrementalChanges Result; // Before newline, code looked like: // leading^trailing // After newline, code looks like: // leading // indentation^trailing // Where indentation was added by the editor. StringRef Trailing = firstLine(Code.substr(Cursor)); StringRef Indentation = lastLine(Code.take_front(Cursor)); if (Indentation.data() == Code.data()) { vlog("Typed a newline, but we're still on the first line!"); return Result; } StringRef Leading = lastLine(Code.take_front(Indentation.data() - Code.data() - 1)); StringRef NextLine = firstLine(Code.substr(Cursor + Trailing.size() + 1)); // Strip leading whitespace on trailing line. StringRef TrailingTrim = Trailing.ltrim(); if (unsigned TrailWS = Trailing.size() - TrailingTrim.size()) cantFail(Result.Changes.add( replacement(Code, StringRef(Trailing.begin(), TrailWS), ""))); // If we split a comment, replace indentation with a comment marker. // If the editor made the new line a comment, also respect that. StringRef CommentMarker = commentMarker(Leading); bool NewLineIsComment = !commentMarker(Indentation).empty(); if (!CommentMarker.empty() && (NewLineIsComment || !commentMarker(NextLine).empty() || (!TrailingTrim.empty() && !TrailingTrim.startswith("//")))) { using llvm::sys::unicode::columnWidthUTF8; // We indent the new comment to match the previous one. StringRef PreComment = Leading.take_front(CommentMarker.data() - Leading.data()); std::string IndentAndComment = (std::string(columnWidthUTF8(PreComment), ' ') + CommentMarker + " ") .str(); cantFail( Result.Changes.add(replacement(Code, Indentation, IndentAndComment))); } else { // Remove any indentation and let clang-format re-add it. // This prevents the cursor marker dragging e.g. an aligned comment with it. cantFail(Result.Changes.add(replacement(Code, Indentation, ""))); } // If we put a the newline inside a {} pair, put } on its own line... if (CommentMarker.empty() && Leading.endswith("{") && Trailing.startswith("}")) { cantFail( Result.Changes.add(replacement(Code, Trailing.take_front(1), "\n}"))); // ...and format it. Result.FormatRanges.push_back( tooling::Range(Trailing.data() - Code.data() + 1, 1)); } // Format the whole leading line. Result.FormatRanges.push_back( tooling::Range(Leading.data() - Code.data(), Leading.size())); // We use a comment to represent the cursor, to preserve the newline. // A trailing identifier improves parsing of e.g. for without braces. // Exception: if the previous line has a trailing comment, we can't use one // as the cursor (they will be aligned). But in this case we don't need to. Result.CursorPlaceholder = !CommentMarker.empty() ? "ident" : "//==\nident"; return Result; } IncrementalChanges getIncrementalChanges(llvm::StringRef Code, unsigned Cursor, llvm::StringRef InsertedText) { IncrementalChanges Result; if (InsertedText == "\n") return getIncrementalChangesAfterNewline(Code, Cursor); Result.CursorPlaceholder = " /**/"; return Result; } // Returns equivalent replacements that preserve the correspondence between // OldCursor and NewCursor. If OldCursor lies in a replaced region, that // replacement will be split. std::vector<tooling::Replacement> split(const tooling::Replacements &Replacements, unsigned OldCursor, unsigned NewCursor) { std::vector<tooling::Replacement> Result; int LengthChange = 0; for (const tooling::Replacement &R : Replacements) { if (R.getOffset() + R.getLength() <= OldCursor) { // before cursor Result.push_back(R); LengthChange += R.getReplacementText().size() - R.getLength(); } else if (R.getOffset() < OldCursor) { // overlaps cursor int ReplacementSplit = NewCursor - LengthChange - R.getOffset(); assert(ReplacementSplit >= 0 && ReplacementSplit <= int(R.getReplacementText().size()) && "NewCursor incompatible with OldCursor!"); Result.push_back(tooling::Replacement( R.getFilePath(), R.getOffset(), OldCursor - R.getOffset(), R.getReplacementText().take_front(ReplacementSplit))); Result.push_back(tooling::Replacement( R.getFilePath(), OldCursor, R.getLength() - (OldCursor - R.getOffset()), R.getReplacementText().drop_front(ReplacementSplit))); } else if (R.getOffset() >= OldCursor) { // after cursor Result.push_back(R); } } return Result; } } // namespace // We're simulating the following sequence of changes: // - apply the pre-formatting edits (see getIncrementalChanges) // - insert a placeholder for the cursor // - format some of the resulting code // - remove the cursor placeholder again // The replacements we return are produced by composing these. // // The text we actually pass to clang-format is slightly different from this, // e.g. we have to close brackets. We ensure these differences are *after* // all the regions we want to format, and discard changes in them. std::vector<tooling::Replacement> formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, llvm::StringRef InsertedText, format::FormatStyle Style) { IncrementalChanges Incremental = getIncrementalChanges(OriginalCode, OriginalCursor, InsertedText); // Never *remove* lines in response to pressing enter! This annoys users. if (InsertedText == "\n") { Style.MaxEmptyLinesToKeep = 1000; Style.KeepEmptyLinesAtTheStartOfBlocks = true; } // Compute the code we want to format: // 1) Start with code after the pre-formatting edits. std::string CodeToFormat = cantFail( tooling::applyAllReplacements(OriginalCode, Incremental.Changes)); unsigned Cursor = Incremental.Changes.getShiftedCodePosition(OriginalCursor); // 2) Truncate code after the last interesting range. unsigned FormatLimit = Cursor; for (tooling::Range &R : Incremental.FormatRanges) FormatLimit = std::max(FormatLimit, R.getOffset() + R.getLength()); CodeToFormat.resize(FormatLimit); // 3) Insert a placeholder for the cursor. CodeToFormat.insert(Cursor, Incremental.CursorPlaceholder); // 4) Append brackets after FormatLimit so the code is well-formed. closeBrackets(CodeToFormat, Style); // Determine the ranges to format: std::vector<tooling::Range> RangesToFormat = Incremental.FormatRanges; // Ranges after the cursor need to be adjusted for the placeholder. for (auto &R : RangesToFormat) { if (R.getOffset() > Cursor) R = tooling::Range(R.getOffset() + Incremental.CursorPlaceholder.size(), R.getLength()); } // We also format the cursor. RangesToFormat.push_back( tooling::Range(Cursor, Incremental.CursorPlaceholder.size())); // Also update FormatLimit for the placeholder, we'll use this later. FormatLimit += Incremental.CursorPlaceholder.size(); // Run clang-format, and truncate changes at FormatLimit. tooling::Replacements FormattingChanges; format::FormattingAttemptStatus Status; for (const tooling::Replacement &R : format::reformat( Style, CodeToFormat, RangesToFormat, Filename, &Status)) { if (R.getOffset() + R.getLength() <= FormatLimit) // Before limit. cantFail(FormattingChanges.add(R)); else if(R.getOffset() < FormatLimit) { // Overlaps limit. if (R.getReplacementText().empty()) // Deletions are easy to handle. cantFail(FormattingChanges.add(tooling::Replacement(Filename, R.getOffset(), FormatLimit - R.getOffset(), ""))); else // Hopefully won't happen in practice? elog("Incremental clang-format edit overlapping cursor @ {0}!\n{1}", Cursor, CodeToFormat); } } if (!Status.FormatComplete) vlog("Incremental format incomplete at line {0}", Status.Line); // Now we are ready to compose the changes relative to OriginalCode. // edits -> insert placeholder -> format -> remove placeholder. // We must express insert/remove as Replacements. tooling::Replacements InsertCursorPlaceholder( tooling::Replacement(Filename, Cursor, 0, Incremental.CursorPlaceholder)); unsigned FormattedCursorStart = FormattingChanges.getShiftedCodePosition(Cursor), FormattedCursorEnd = FormattingChanges.getShiftedCodePosition( Cursor + Incremental.CursorPlaceholder.size()); tooling::Replacements RemoveCursorPlaceholder( tooling::Replacement(Filename, FormattedCursorStart, FormattedCursorEnd - FormattedCursorStart, "")); // We can't simply merge() and return: tooling::Replacements will combine // adjacent edits left and right of the cursor. This gives the right source // code, but loses information about where the cursor is! // Fortunately, none of the individual passes lose information, so: // - we use merge() to compute the final Replacements // - we chain getShiftedCodePosition() to compute final cursor position // - we split the final Replacements at the cursor position, so that // each Replacement lies either before or after the cursor. tooling::Replacements Final; unsigned FinalCursor = OriginalCursor; #ifndef NDEBUG std::string FinalCode = OriginalCode; dlog("Initial code: {0}", FinalCode); #endif for (auto Pass : std::vector<std::pair<const char *, const tooling::Replacements *>>{ {"Pre-formatting changes", &Incremental.Changes}, {"Insert placeholder", &InsertCursorPlaceholder}, {"clang-format", &FormattingChanges}, {"Remove placeholder", &RemoveCursorPlaceholder}}) { Final = Final.merge(*Pass.second); FinalCursor = Pass.second->getShiftedCodePosition(FinalCursor); #ifndef NDEBUG FinalCode = cantFail(tooling::applyAllReplacements(FinalCode, *Pass.second)); dlog("After {0}:\n{1}^{2}", Pass.first, StringRef(FinalCode).take_front(FinalCursor), StringRef(FinalCode).drop_front(FinalCursor)); #endif } return split(Final, OriginalCursor, FinalCursor); } unsigned transformCursorPosition(unsigned Offset, const std::vector<tooling::Replacement> &Replacements) { unsigned OriginalOffset = Offset; for (const auto &R : Replacements) { if (R.getOffset() + R.getLength() <= OriginalOffset) { // Replacement is before cursor. Offset += R.getReplacementText().size(); Offset -= R.getLength(); } else if (R.getOffset() < OriginalOffset) { // Replacement overlaps cursor. // Preserve position within replacement text, as far as possible. unsigned PositionWithinReplacement = Offset - R.getOffset(); if (PositionWithinReplacement > R.getReplacementText().size()) { Offset += R.getReplacementText().size(); Offset -= PositionWithinReplacement; } } else { // Replacement after cursor. break; // Replacements are sorted, the rest are also after the cursor. } } return Offset; } } // namespace clangd } // namespace clang <commit_msg>[clangd] Fix gcc warning by removing extra ";"<commit_after>//===--- Format.cpp -----------------------------------------*- C++-*------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Format.h" #include "Logger.h" #include "clang/Basic/SourceManager.h" #include "clang/Format/Format.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Core/Replacement.h" #include "llvm/Support/Unicode.h" namespace clang { namespace clangd { namespace { /// Append closing brackets )]} to \p Code to make it well-formed. /// Clang-format conservatively refuses to format files with unmatched brackets /// as it isn't sure where the errors are and so can't correct. /// When editing, it's reasonable to assume code before the cursor is complete. void closeBrackets(std::string &Code, const format::FormatStyle &Style) { SourceManagerForFile FileSM("dummy.cpp", Code); auto &SM = FileSM.get(); FileID FID = SM.getMainFileID(); Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style)); Token Tok; std::vector<char> Brackets; while (!Lex.LexFromRawLexer(Tok)) { switch(Tok.getKind()) { case tok::l_paren: Brackets.push_back(')'); break; case tok::l_brace: Brackets.push_back('}'); break; case tok::l_square: Brackets.push_back(']'); break; case tok::r_paren: if (!Brackets.empty() && Brackets.back() == ')') Brackets.pop_back(); break; case tok::r_brace: if (!Brackets.empty() && Brackets.back() == '}') Brackets.pop_back(); break; case tok::r_square: if (!Brackets.empty() && Brackets.back() == ']') Brackets.pop_back(); break; default: continue; } } // Attempt to end any open comments first. Code.append("\n// */\n"); Code.append(Brackets.rbegin(), Brackets.rend()); } static StringRef commentMarker(llvm::StringRef Line) { for (StringRef Marker : {"///", "//"}){ auto I = Line.rfind(Marker); if (I != StringRef::npos) return Line.substr(I, Marker.size()); } return ""; } llvm::StringRef firstLine(llvm::StringRef Code) { return Code.take_until([](char C) { return C == '\n'; }); } llvm::StringRef lastLine(llvm::StringRef Code) { llvm::StringRef Rest = Code; while (!Rest.empty() && Rest.back() != '\n') Rest = Rest.drop_back(); return Code.substr(Rest.size()); } // Filename is needed for tooling::Replacement and some overloads of reformat(). // Its value should not affect the outcome. We use the default from reformat(). llvm::StringRef Filename = "<stdin>"; // tooling::Replacement from overlapping StringRefs: From must be part of Code. tooling::Replacement replacement(llvm::StringRef Code, llvm::StringRef From, llvm::StringRef To) { assert(From.begin() >= Code.begin() && From.end() <= Code.end()); // The filename is required but ignored. return tooling::Replacement(Filename, From.data() - Code.data(), From.size(), To); } // High-level representation of incremental formatting changes. // The changes are made in two steps. // 1) a (possibly-empty) set of changes synthesized by clangd (e.g. adding // comment markers when splitting a line comment with a newline). // 2) a selective clang-format run: // - the "source code" passed to clang format is the code up to the cursor, // a placeholder for the cursor, and some closing brackets // - the formatting is restricted to the cursor and (possibly) other ranges // (e.g. the old line when inserting a newline). // - changes before the cursor are applied, those after are discarded. struct IncrementalChanges { // Changes that should be applied before running clang-format. tooling::Replacements Changes; // Ranges of the original source code that should be clang-formatted. // The CursorProxyText will also be formatted. std::vector<tooling::Range> FormatRanges; // The source code that should stand in for the cursor when clang-formatting. // e.g. after inserting a newline, a line-comment at the cursor is used to // ensure that the newline is preserved. std::string CursorPlaceholder; }; // After a newline: // - we continue any line-comment that was split // - we format the old line in addition to the cursor // - we represent the cursor with a line comment to preserve the newline IncrementalChanges getIncrementalChangesAfterNewline(llvm::StringRef Code, unsigned Cursor) { IncrementalChanges Result; // Before newline, code looked like: // leading^trailing // After newline, code looks like: // leading // indentation^trailing // Where indentation was added by the editor. StringRef Trailing = firstLine(Code.substr(Cursor)); StringRef Indentation = lastLine(Code.take_front(Cursor)); if (Indentation.data() == Code.data()) { vlog("Typed a newline, but we're still on the first line!"); return Result; } StringRef Leading = lastLine(Code.take_front(Indentation.data() - Code.data() - 1)); StringRef NextLine = firstLine(Code.substr(Cursor + Trailing.size() + 1)); // Strip leading whitespace on trailing line. StringRef TrailingTrim = Trailing.ltrim(); if (unsigned TrailWS = Trailing.size() - TrailingTrim.size()) cantFail(Result.Changes.add( replacement(Code, StringRef(Trailing.begin(), TrailWS), ""))); // If we split a comment, replace indentation with a comment marker. // If the editor made the new line a comment, also respect that. StringRef CommentMarker = commentMarker(Leading); bool NewLineIsComment = !commentMarker(Indentation).empty(); if (!CommentMarker.empty() && (NewLineIsComment || !commentMarker(NextLine).empty() || (!TrailingTrim.empty() && !TrailingTrim.startswith("//")))) { using llvm::sys::unicode::columnWidthUTF8; // We indent the new comment to match the previous one. StringRef PreComment = Leading.take_front(CommentMarker.data() - Leading.data()); std::string IndentAndComment = (std::string(columnWidthUTF8(PreComment), ' ') + CommentMarker + " ") .str(); cantFail( Result.Changes.add(replacement(Code, Indentation, IndentAndComment))); } else { // Remove any indentation and let clang-format re-add it. // This prevents the cursor marker dragging e.g. an aligned comment with it. cantFail(Result.Changes.add(replacement(Code, Indentation, ""))); } // If we put a the newline inside a {} pair, put } on its own line... if (CommentMarker.empty() && Leading.endswith("{") && Trailing.startswith("}")) { cantFail( Result.Changes.add(replacement(Code, Trailing.take_front(1), "\n}"))); // ...and format it. Result.FormatRanges.push_back( tooling::Range(Trailing.data() - Code.data() + 1, 1)); } // Format the whole leading line. Result.FormatRanges.push_back( tooling::Range(Leading.data() - Code.data(), Leading.size())); // We use a comment to represent the cursor, to preserve the newline. // A trailing identifier improves parsing of e.g. for without braces. // Exception: if the previous line has a trailing comment, we can't use one // as the cursor (they will be aligned). But in this case we don't need to. Result.CursorPlaceholder = !CommentMarker.empty() ? "ident" : "//==\nident"; return Result; } IncrementalChanges getIncrementalChanges(llvm::StringRef Code, unsigned Cursor, llvm::StringRef InsertedText) { IncrementalChanges Result; if (InsertedText == "\n") return getIncrementalChangesAfterNewline(Code, Cursor); Result.CursorPlaceholder = " /**/"; return Result; } // Returns equivalent replacements that preserve the correspondence between // OldCursor and NewCursor. If OldCursor lies in a replaced region, that // replacement will be split. std::vector<tooling::Replacement> split(const tooling::Replacements &Replacements, unsigned OldCursor, unsigned NewCursor) { std::vector<tooling::Replacement> Result; int LengthChange = 0; for (const tooling::Replacement &R : Replacements) { if (R.getOffset() + R.getLength() <= OldCursor) { // before cursor Result.push_back(R); LengthChange += R.getReplacementText().size() - R.getLength(); } else if (R.getOffset() < OldCursor) { // overlaps cursor int ReplacementSplit = NewCursor - LengthChange - R.getOffset(); assert(ReplacementSplit >= 0 && ReplacementSplit <= int(R.getReplacementText().size()) && "NewCursor incompatible with OldCursor!"); Result.push_back(tooling::Replacement( R.getFilePath(), R.getOffset(), OldCursor - R.getOffset(), R.getReplacementText().take_front(ReplacementSplit))); Result.push_back(tooling::Replacement( R.getFilePath(), OldCursor, R.getLength() - (OldCursor - R.getOffset()), R.getReplacementText().drop_front(ReplacementSplit))); } else if (R.getOffset() >= OldCursor) { // after cursor Result.push_back(R); } } return Result; } } // namespace // We're simulating the following sequence of changes: // - apply the pre-formatting edits (see getIncrementalChanges) // - insert a placeholder for the cursor // - format some of the resulting code // - remove the cursor placeholder again // The replacements we return are produced by composing these. // // The text we actually pass to clang-format is slightly different from this, // e.g. we have to close brackets. We ensure these differences are *after* // all the regions we want to format, and discard changes in them. std::vector<tooling::Replacement> formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, llvm::StringRef InsertedText, format::FormatStyle Style) { IncrementalChanges Incremental = getIncrementalChanges(OriginalCode, OriginalCursor, InsertedText); // Never *remove* lines in response to pressing enter! This annoys users. if (InsertedText == "\n") { Style.MaxEmptyLinesToKeep = 1000; Style.KeepEmptyLinesAtTheStartOfBlocks = true; } // Compute the code we want to format: // 1) Start with code after the pre-formatting edits. std::string CodeToFormat = cantFail( tooling::applyAllReplacements(OriginalCode, Incremental.Changes)); unsigned Cursor = Incremental.Changes.getShiftedCodePosition(OriginalCursor); // 2) Truncate code after the last interesting range. unsigned FormatLimit = Cursor; for (tooling::Range &R : Incremental.FormatRanges) FormatLimit = std::max(FormatLimit, R.getOffset() + R.getLength()); CodeToFormat.resize(FormatLimit); // 3) Insert a placeholder for the cursor. CodeToFormat.insert(Cursor, Incremental.CursorPlaceholder); // 4) Append brackets after FormatLimit so the code is well-formed. closeBrackets(CodeToFormat, Style); // Determine the ranges to format: std::vector<tooling::Range> RangesToFormat = Incremental.FormatRanges; // Ranges after the cursor need to be adjusted for the placeholder. for (auto &R : RangesToFormat) { if (R.getOffset() > Cursor) R = tooling::Range(R.getOffset() + Incremental.CursorPlaceholder.size(), R.getLength()); } // We also format the cursor. RangesToFormat.push_back( tooling::Range(Cursor, Incremental.CursorPlaceholder.size())); // Also update FormatLimit for the placeholder, we'll use this later. FormatLimit += Incremental.CursorPlaceholder.size(); // Run clang-format, and truncate changes at FormatLimit. tooling::Replacements FormattingChanges; format::FormattingAttemptStatus Status; for (const tooling::Replacement &R : format::reformat( Style, CodeToFormat, RangesToFormat, Filename, &Status)) { if (R.getOffset() + R.getLength() <= FormatLimit) // Before limit. cantFail(FormattingChanges.add(R)); else if(R.getOffset() < FormatLimit) { // Overlaps limit. if (R.getReplacementText().empty()) // Deletions are easy to handle. cantFail(FormattingChanges.add(tooling::Replacement(Filename, R.getOffset(), FormatLimit - R.getOffset(), ""))); else // Hopefully won't happen in practice? elog("Incremental clang-format edit overlapping cursor @ {0}!\n{1}", Cursor, CodeToFormat); } } if (!Status.FormatComplete) vlog("Incremental format incomplete at line {0}", Status.Line); // Now we are ready to compose the changes relative to OriginalCode. // edits -> insert placeholder -> format -> remove placeholder. // We must express insert/remove as Replacements. tooling::Replacements InsertCursorPlaceholder( tooling::Replacement(Filename, Cursor, 0, Incremental.CursorPlaceholder)); unsigned FormattedCursorStart = FormattingChanges.getShiftedCodePosition(Cursor), FormattedCursorEnd = FormattingChanges.getShiftedCodePosition( Cursor + Incremental.CursorPlaceholder.size()); tooling::Replacements RemoveCursorPlaceholder( tooling::Replacement(Filename, FormattedCursorStart, FormattedCursorEnd - FormattedCursorStart, "")); // We can't simply merge() and return: tooling::Replacements will combine // adjacent edits left and right of the cursor. This gives the right source // code, but loses information about where the cursor is! // Fortunately, none of the individual passes lose information, so: // - we use merge() to compute the final Replacements // - we chain getShiftedCodePosition() to compute final cursor position // - we split the final Replacements at the cursor position, so that // each Replacement lies either before or after the cursor. tooling::Replacements Final; unsigned FinalCursor = OriginalCursor; #ifndef NDEBUG std::string FinalCode = OriginalCode; dlog("Initial code: {0}", FinalCode); #endif for (auto Pass : std::vector<std::pair<const char *, const tooling::Replacements *>>{ {"Pre-formatting changes", &Incremental.Changes}, {"Insert placeholder", &InsertCursorPlaceholder}, {"clang-format", &FormattingChanges}, {"Remove placeholder", &RemoveCursorPlaceholder}}) { Final = Final.merge(*Pass.second); FinalCursor = Pass.second->getShiftedCodePosition(FinalCursor); #ifndef NDEBUG FinalCode = cantFail(tooling::applyAllReplacements(FinalCode, *Pass.second)); dlog("After {0}:\n{1}^{2}", Pass.first, StringRef(FinalCode).take_front(FinalCursor), StringRef(FinalCode).drop_front(FinalCursor)); #endif } return split(Final, OriginalCursor, FinalCursor); } unsigned transformCursorPosition(unsigned Offset, const std::vector<tooling::Replacement> &Replacements) { unsigned OriginalOffset = Offset; for (const auto &R : Replacements) { if (R.getOffset() + R.getLength() <= OriginalOffset) { // Replacement is before cursor. Offset += R.getReplacementText().size(); Offset -= R.getLength(); } else if (R.getOffset() < OriginalOffset) { // Replacement overlaps cursor. // Preserve position within replacement text, as far as possible. unsigned PositionWithinReplacement = Offset - R.getOffset(); if (PositionWithinReplacement > R.getReplacementText().size()) { Offset += R.getReplacementText().size(); Offset -= PositionWithinReplacement; } } else { // Replacement after cursor. break; // Replacements are sorted, the rest are also after the cursor. } } return Offset; } } // namespace clangd } // namespace clang <|endoftext|>