commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
3da1cc25eba2f6ec3d1cfd5687656ca31ae1a4b8
src/backend/gporca/libgpopt/src/xforms/CXformRightOuterJoin2HashJoin.cpp
src/backend/gporca/libgpopt/src/xforms/CXformRightOuterJoin2HashJoin.cpp
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (c) 2020 VMware, Inc. // // @filename: // CXformRightOuterJoin2HashJoin.cpp // // @doc: // Implementation of transform //--------------------------------------------------------------------------- #include "gpopt/xforms/CXformRightOuterJoin2HashJoin.h" #include "gpos/base.h" #include "gpopt/operators/CLogicalRightOuterJoin.h" #include "gpopt/operators/CPatternLeaf.h" #include "gpopt/operators/CPhysicalRightOuterHashJoin.h" #include "gpopt/operators/CPredicateUtils.h" #include "gpopt/xforms/CXformUtils.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CXformRightOuterJoin2HashJoin::CXformRightOuterJoin2HashJoin // // @doc: // ctor // //--------------------------------------------------------------------------- CXformRightOuterJoin2HashJoin::CXformRightOuterJoin2HashJoin(CMemoryPool *mp) : // pattern CXformImplementation(GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CLogicalRightOuterJoin(mp), GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternLeaf(mp)), // left child GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternLeaf(mp)), // right child GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternTree(mp)) // predicate )) { } //--------------------------------------------------------------------------- // @function: // CXformRightOuterJoin2HashJoin::Exfp // // @doc: // Compute xform promise for a given expression handle; // //--------------------------------------------------------------------------- CXform::EXformPromise CXformRightOuterJoin2HashJoin::Exfp(CExpressionHandle &exprhdl) const { return CXformUtils::ExfpLogicalJoin2PhysicalJoin(exprhdl); } //--------------------------------------------------------------------------- // @function: // CXformRightOuterJoin2HashJoin::Transform // // @doc: // actual transformation // //--------------------------------------------------------------------------- void CXformRightOuterJoin2HashJoin::Transform(CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr) const { GPOS_ASSERT(nullptr != pxfctxt); GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr)); GPOS_ASSERT(FCheckPattern(pexpr)); // If the inner row estimate is an arbitary factor larger than the outer, don't generate a ROJ alternative. // Although the ROJ may still be better due to partition selection, which isn't considered below, // we're more cautious so we don't increase optimization time too much and that we account for // poor cardinality estimation. This is admittedly conservative, but mis-estimating the hash side // of a ROJ can cause spilling. CDouble outerRows = (*pexpr)[0]->Pstats()->Rows(); CDouble outerWidth = (*pexpr)[0]->Pstats()->Width(); CDouble innerRows = (*pexpr)[1]->Pstats()->Rows(); CDouble innerWidth = (*pexpr)[1]->Pstats()->Width(); CDouble confidenceFactor = 2 * (*pexpr)[1]->DeriveJoinDepth(); if (innerRows * innerWidth * confidenceFactor > outerRows * outerWidth) { return; } CXformUtils::ImplementHashJoin<CPhysicalRightOuterHashJoin>(pxfctxt, pxfres, pexpr); } // EOF
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (c) 2020 VMware, Inc. // // @filename: // CXformRightOuterJoin2HashJoin.cpp // // @doc: // Implementation of transform //--------------------------------------------------------------------------- #include "gpopt/xforms/CXformRightOuterJoin2HashJoin.h" #include "gpos/base.h" #include "gpopt/operators/CLogicalRightOuterJoin.h" #include "gpopt/operators/CPatternLeaf.h" #include "gpopt/operators/CPhysicalRightOuterHashJoin.h" #include "gpopt/operators/CPredicateUtils.h" #include "gpopt/xforms/CXformUtils.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CXformRightOuterJoin2HashJoin::CXformRightOuterJoin2HashJoin // // @doc: // ctor // //--------------------------------------------------------------------------- CXformRightOuterJoin2HashJoin::CXformRightOuterJoin2HashJoin(CMemoryPool *mp) : // pattern CXformImplementation(GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CLogicalRightOuterJoin(mp), GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternLeaf(mp)), // left child GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternLeaf(mp)), // right child GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternTree(mp)) // predicate )) { } //--------------------------------------------------------------------------- // @function: // CXformRightOuterJoin2HashJoin::Exfp // // @doc: // Compute xform promise for a given expression handle; // //--------------------------------------------------------------------------- CXform::EXformPromise CXformRightOuterJoin2HashJoin::Exfp(CExpressionHandle &exprhdl) const { return CXformUtils::ExfpLogicalJoin2PhysicalJoin(exprhdl); } //--------------------------------------------------------------------------- // @function: // CXformRightOuterJoin2HashJoin::Transform // // @doc: // actual transformation // //--------------------------------------------------------------------------- void CXformRightOuterJoin2HashJoin::Transform(CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr) const { GPOS_ASSERT(nullptr != pxfctxt); GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr)); GPOS_ASSERT(FCheckPattern(pexpr)); const IStatistics *outerStats = (*pexpr)[0]->Pstats(); const IStatistics *innerStats = (*pexpr)[1]->Pstats(); if (nullptr == outerStats || nullptr == innerStats) { return; } // If the inner row estimate is an arbitary factor larger than the outer, don't generate a ROJ alternative. // Although the ROJ may still be better due to partition selection, which isn't considered below, // we're more cautious so we don't increase optimization time too much and that we account for // poor cardinality estimation. This is admittedly conservative, but mis-estimating the hash side // of a ROJ can cause spilling. CDouble outerRows = outerStats->Rows(); CDouble outerWidth = outerStats->Width(); CDouble innerRows = innerStats->Rows(); CDouble innerWidth = innerStats->Width(); CDouble confidenceFactor = 2 * (*pexpr)[1]->DeriveJoinDepth(); if (innerRows * innerWidth * confidenceFactor > outerRows * outerWidth) { return; } CXformUtils::ImplementHashJoin<CPhysicalRightOuterHashJoin>(pxfctxt, pxfres, pexpr); } // EOF
Fix SIGSEGV due to non-derived statistics (#12970)
Fix SIGSEGV due to non-derived statistics (#12970) Similar to dede33b352f when statistics may not be derived yet, we should take care to handle the scenario gracefully. Following demonstrated error using non-assert build: ```sql CREATE TABLE a_table(col text); SELECT a.col FROM ( SELECT col FROM a_table e WHERE exists ( SELECT col FROM a_table ) ) a WHERE exists ( SELECT c.col FROM a_table c INNER JOIN a_table b ON c.col = a.col WHERE exists ( SELECT distinct _a.col FROM ( SELECT distinct col FROM a_table _a ) _a WHERE _a.col = c.col ) ); ```
C++
apache-2.0
lisakowen/gpdb,greenplum-db/gpdb,lisakowen/gpdb,greenplum-db/gpdb,50wu/gpdb,xinzweb/gpdb,lisakowen/gpdb,lisakowen/gpdb,50wu/gpdb,xinzweb/gpdb,50wu/gpdb,50wu/gpdb,greenplum-db/gpdb,50wu/gpdb,greenplum-db/gpdb,xinzweb/gpdb,50wu/gpdb,xinzweb/gpdb,lisakowen/gpdb,xinzweb/gpdb,lisakowen/gpdb,lisakowen/gpdb,greenplum-db/gpdb,50wu/gpdb,greenplum-db/gpdb,xinzweb/gpdb,lisakowen/gpdb,greenplum-db/gpdb,greenplum-db/gpdb,xinzweb/gpdb,50wu/gpdb,xinzweb/gpdb
4bd24710fdfccef668c1553dc48d192209399285
extensions/CuteHMI/GUI.1/src/cutehmi/gui/internal/QMLPlugin.cpp
extensions/CuteHMI/GUI.1/src/cutehmi/gui/internal/QMLPlugin.cpp
#include "QMLPlugin.hpp" #include <cutehmi/gui/CuteApplication.hpp> #include <cutehmi/gui/ColorSet.hpp> #include <cutehmi/gui/Palette.hpp> #include <cutehmi/gui/Fonts.hpp> #include <cutehmi/gui/Units.hpp> #include <cutehmi/gui/Theme.hpp> #include <QtQml> //<Doxygen-3.workaround target="Doxygen" cause="missing"> #ifdef DOXYGEN_WORKAROUND namespace CuteHMI { namespace GUI { /** * Exposes cutehmi::gui::CuteApplication to QML. */ class CuteApplication: public cutehmi::gui::CuteApplication {}; /** * Exposes cutehmi::gui::ColorSet to QML. */ class ColorSet: public cutehmi::gui::ColorSet {}; /** * Exposes cutehmi::gui::Palette to QML. */ class Palette: public cutehmi::gui::Palette {}; /** * Exposes cutehmi::gui::Fonts to QML. */ class Fonts: public cutehmi::gui::Fonts {}; /** * Exposes cutehmi::gui::Units to QML. */ class Units: public cutehmi::gui::Units {}; /** * Exposes cutehmi::gui::Theme to QML. */ class Theme: public cutehmi::gui::Theme {}; } } #endif //</Doxygen-3.workaround> namespace cutehmi { namespace gui { namespace internal { /** * Register QML types. * @param uri URI. */ void QMLPlugin::registerTypes(const char * uri) { Q_ASSERT(uri == QLatin1String("CuteHMI.GUI")); qmlRegisterType<cutehmi::gui::ColorSet>(uri, CUTEHMI_GUI_MAJOR, 0, "ColorSet"); qmlRegisterType<cutehmi::gui::Palette>(uri, CUTEHMI_GUI_MAJOR, 0, "Palette"); qmlRegisterType<cutehmi::gui::Fonts>(uri, CUTEHMI_GUI_MAJOR, 0, "Fonts"); qmlRegisterType<cutehmi::gui::Units>(uri, CUTEHMI_GUI_MAJOR, 0, "Units"); qmlRegisterSingletonType<cutehmi::gui::Theme>(uri, CUTEHMI_GUI_MAJOR, 0, "Theme", ThemeProvider); if (qgetenv("QML_PUPPET_MODE").isNull()) { //<CuteHMI.LockScreen-1.workaround target="Qt" cause="design"> qmlRegisterSingletonType<cutehmi::gui::CuteApplication>(uri, CUTEHMI_GUI_MAJOR, 0, "CuteApplication", CuteApplicationProvider); //</CuteHMI.LockScreen-1.workaround> } } QObject * QMLPlugin::CuteApplicationProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * app = cutehmi::gui::CuteApplication::instance(); engine->setObjectOwnership(app, QQmlEngine::CppOwnership); return app; } QObject * QMLPlugin::ThemeProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * theme = & cutehmi::gui::Theme::Instance(); engine->setObjectOwnership(theme, QQmlEngine::CppOwnership); return theme; } } } } //(c)C: Copyright © 2020, Michał Policht <[email protected]>. All rights reserved. //(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. //(c)C: Additionally, this file is licensed under terms of MIT license as expressed below. //(c)C: 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: //(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //(c)C: 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 "QMLPlugin.hpp" #include <cutehmi/gui/CuteApplication.hpp> #include <cutehmi/gui/ColorSet.hpp> #include <cutehmi/gui/Palette.hpp> #include <cutehmi/gui/Fonts.hpp> #include <cutehmi/gui/Units.hpp> #include <cutehmi/gui/Theme.hpp> #include <QtQml> //<Doxygen-3.workaround target="Doxygen" cause="missing"> #ifdef DOXYGEN_WORKAROUND namespace CuteHMI { namespace GUI { /** * Exposes cutehmi::gui::CuteApplication to QML. */ class CuteApplication: public cutehmi::gui::CuteApplication {}; /** * Exposes cutehmi::gui::ColorSet to QML. */ class ColorSet: public cutehmi::gui::ColorSet {}; /** * Exposes cutehmi::gui::Palette to QML. */ class Palette: public cutehmi::gui::Palette {}; /** * Exposes cutehmi::gui::Fonts to QML. */ class Fonts: public cutehmi::gui::Fonts {}; /** * Exposes cutehmi::gui::Units to QML. */ class Units: public cutehmi::gui::Units {}; /** * Exposes cutehmi::gui::Theme to QML. */ class Theme: public cutehmi::gui::Theme {}; } } #endif //</Doxygen-3.workaround> namespace cutehmi { namespace gui { namespace internal { /** * Register QML types. * @param uri URI. */ void QMLPlugin::registerTypes(const char * uri) { Q_ASSERT(uri == QLatin1String("CuteHMI.GUI")); // @uri CuteHMI.GUI qmlRegisterType<cutehmi::gui::ColorSet>(uri, CUTEHMI_GUI_MAJOR, 0, "ColorSet"); qmlRegisterType<cutehmi::gui::Palette>(uri, CUTEHMI_GUI_MAJOR, 0, "Palette"); qmlRegisterType<cutehmi::gui::Fonts>(uri, CUTEHMI_GUI_MAJOR, 0, "Fonts"); qmlRegisterType<cutehmi::gui::Units>(uri, CUTEHMI_GUI_MAJOR, 0, "Units"); qmlRegisterSingletonType<cutehmi::gui::Theme>(uri, CUTEHMI_GUI_MAJOR, 0, "Theme", ThemeProvider); if (qEnvironmentVariableIsSet("QML_PUPPET_MODE")) { //<CuteHMI.LockScreen-1.workaround target="Qt" cause="design"> // @uri CuteHMI.GUI qmlRegisterSingletonType<cutehmi::gui::CuteApplication>(uri, CUTEHMI_GUI_MAJOR, 0, "CuteApplication", CuteApplicationProvider); //</CuteHMI.LockScreen-1.workaround> } } QObject * QMLPlugin::CuteApplicationProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * app = cutehmi::gui::CuteApplication::instance(); engine->setObjectOwnership(app, QQmlEngine::CppOwnership); return app; } QObject * QMLPlugin::ThemeProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * theme = & cutehmi::gui::Theme::Instance(); engine->setObjectOwnership(theme, QQmlEngine::CppOwnership); return theme; } } } } //(c)C: Copyright © 2020, Michał Policht <[email protected]>. All rights reserved. //(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. //(c)C: Additionally, this file is licensed under terms of MIT license as expressed below. //(c)C: 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: //(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //(c)C: 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.
Use uri annotations and improve check for environmental variable being set
Use uri annotations and improve check for environmental variable being set
C++
mit
michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI
672c58438e1475c597d53cae86e43dc13f7678d6
CodeCompareLib/Memory.cpp
CodeCompareLib/Memory.cpp
#include "Memory.h" #include <malloc.h> #include <atomic> #include <assert.h> namespace Memory { struct Tracker { std::atomic_size_t TotalMemory; // only 100% accurate globals std::atomic_size_t ActiveAllocations; // only 100% accurate globals std::atomic_size_t TotalAllocations; std::atomic_size_t TrackingStart; std::atomic_size_t TrackingMax; void Alloc(size_t bytes) { TotalMemory += bytes; ++ActiveAllocations; ++TotalAllocations; if (TotalMemory > TrackingMax) TrackingMax = TotalMemory._My_val; } void Free(size_t bytes) { assert(TotalMemory >= bytes); assert(ActiveAllocations > 0); TotalMemory -= bytes; --ActiveAllocations; } void ResetTracking() { size_t total = TotalMemory; TrackingStart = total; TrackingMax = total; } }; Tracker Global; Tracker thread_local Thread; Report GetReport(Tracker const& tracker) { return { tracker.TotalMemory, tracker.ActiveAllocations, tracker.TotalAllocations, tracker.TrackingMax - tracker.TrackingStart }; } Report GetGlobalReport() { return GetReport(Global); } Report GetThreadReport() { return GetReport(Thread); } void ResetThreadTracking() { Thread.ResetTracking(); } void Alloc(size_t bytes) { Global.Alloc(bytes); Thread.Alloc(bytes); } void Free(size_t bytes) { Global.Free(bytes); Thread.Free(bytes); } } void * operator new(size_t n) throw() { Memory::Alloc(n); return malloc(n); } void operator delete(void * p) throw() { Memory::Free(_msize(p)); free(p); }
#include "Memory.h" #include <malloc.h> #include <atomic> #include <assert.h> namespace Memory { struct Tracker { std::atomic_size_t TotalMemory; // only 100% accurate globals std::atomic_size_t ActiveAllocations; // only 100% accurate globals std::atomic_size_t TotalAllocations; std::atomic_size_t TrackingStart; std::atomic_size_t TrackingMax; void Alloc(size_t bytes) { TotalMemory += bytes; ++ActiveAllocations; ++TotalAllocations; if (TotalMemory > TrackingMax) TrackingMax = TotalMemory._My_val; } void Free(size_t bytes) { assert(TotalMemory >= bytes); assert(ActiveAllocations > 0); TotalMemory -= bytes; --ActiveAllocations; } void ResetTracking() { size_t total = TotalMemory; TrackingStart = total; TrackingMax = total; } }; Tracker Global; Tracker thread_local Thread; Report GetReport(Tracker const& tracker) { return { tracker.TotalMemory, tracker.ActiveAllocations, tracker.TotalAllocations, tracker.TrackingMax - tracker.TrackingStart }; } Report GetGlobalReport() { return GetReport(Global); } Report GetThreadReport() { return GetReport(Thread); } void ResetThreadTracking() { Thread.ResetTracking(); } void Alloc(size_t bytes) { Global.Alloc(bytes); Thread.Alloc(bytes); } void Free(size_t bytes) { Global.Free(bytes); Thread.Free(bytes); } } void * operator new(size_t n) throw() { Memory::Alloc(n); return malloc(n); } void operator delete(void * p) throw() { if (p) { Memory::Free(_msize(p)); free(p); } }
Fix crash when deleting null
Fix crash when deleting null
C++
unlicense
kudaba/CodeCompare,kudaba/CodeCompare
3068d55cba6006bff20ab3e15cfb108d45e08f87
gapid_tests/command_buffer_tests/vkCmdResolveImage_test/main.cpp
gapid_tests/command_buffer_tests/vkCmdResolveImage_test/main.cpp
/* Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include "support/entry/entry.h" #include "support/log/log.h" #include "vulkan_helpers/helper_functions.h" #include "vulkan_helpers/vulkan_application.h" int main_entry(const entry::EntryData* data) { data->logger()->LogInfo("Application Startup"); vulkan::VulkanApplication application(data->allocator(), data->logger(), data, {}, {}, {0}, 1024*1024, 1024*1024, 1024*1024, 1024*1024); const VkExtent3D sample_image_extent{32, 32, 1}; const VkImageCreateInfo sample_image_create_info{ /* sType = */ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* pNext = */ nullptr, /* flags = */ 0, /* imageType = */ VK_IMAGE_TYPE_2D, /* format = */ VK_FORMAT_R8G8B8A8_UNORM, /* extent = */ sample_image_extent, /* mipLevels = */ 1, /* arrayLayers = */ 1, /* samples = */ VK_SAMPLE_COUNT_1_BIT, /* tiling = */ VK_IMAGE_TILING_OPTIMAL, /* usage = */ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, /* sharingMode = */ VK_SHARING_MODE_EXCLUSIVE, /* queueFamilyIndexCount = */ 0, /* pQueueFamilyIndices = */ nullptr, /* initialLayout = */ VK_IMAGE_LAYOUT_UNDEFINED, }; { // 1. Resolve from a 2D, Optimal tiling, 4x multi-sampled color image, with // only 1 layer, 1 miplevel and 0 offsets in all dimensions. VkImageCreateInfo src_image_create_info = sample_image_create_info; src_image_create_info.samples = VK_SAMPLE_COUNT_4_BIT; // 4x multi-sampled vulkan::ImagePointer src_image = application.CreateAndBindImage(&src_image_create_info); VkImageCreateInfo dst_image_create_info = sample_image_create_info; vulkan::ImagePointer dst_image = application.CreateAndBindImage(&dst_image_create_info); // Data in the multi-sampled source image VkClearColorValue clear_color{ {0.5, 0.5, 0.5, 0.5} // uint32[4] }; // Range used for vkCmdClearColorImage() to fill the multi-sampled image // with data VkImageSubresourceRange clear_color_range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; // Fill the multi-sampled image with data through vkCmdClearColorImage() vulkan::VkCommandBuffer cmd_buf = application.GetCommandBuffer(); ::VkCommandBuffer raw_cmd_buf = cmd_buf.get_command_buffer(); VkCommandBufferBeginInfo cmd_buf_begin_info{ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0, nullptr}; cmd_buf->vkBeginCommandBuffer(cmd_buf, &cmd_buf_begin_info); vulkan::RecordImageLayoutTransition(*src_image, clear_color_range, VK_IMAGE_LAYOUT_UNDEFINED, 0, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, &cmd_buf); cmd_buf->vkCmdClearColorImage(cmd_buf, *src_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clear_color, 1, &clear_color_range); // Switch src image layout from TRANSFER_DST to TRANSFER_SRC vulkan::RecordImageLayoutTransition( *src_image, clear_color_range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, &cmd_buf); vulkan::RecordImageLayoutTransition(*dst_image, clear_color_range, VK_IMAGE_LAYOUT_UNDEFINED, 0, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, &cmd_buf); VkImageResolve image_resolve{ // mip level 0, layerbase 0, layer count 1 {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, {0, 0, 0}, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, {0, 0, 0}, sample_image_extent, }; // Call vkCmdResolveImage cmd_buf->vkCmdResolveImage( cmd_buf, *src_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_resolve); cmd_buf->vkEndCommandBuffer(cmd_buf); VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &raw_cmd_buf, 0, nullptr}; application.render_queue()->vkQueueSubmit( application.render_queue(), 1, &submit_info, static_cast<VkFence>(VK_NULL_HANDLE)); application.render_queue()->vkQueueWaitIdle(application.render_queue()); // Dump the resolved image data containers::vector<uint8_t> dump_data(data->allocator()); application.DumpImageLayersData( dst_image.get(), {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, // subresourceLayer {0, 0, 0}, // offset sample_image_extent, // extent VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // initial layout &dump_data, // data {} // wait_semaphores ); containers::vector<uint8_t> expected_data(32 * 32 * 4, 0.5 * 255, data->allocator()); LOG_ASSERT(==, data->logger(), expected_data.size(), dump_data.size()); LOG_ASSERT(==, data->logger(), true, std::equal(expected_data.begin(), expected_data.end(), dump_data.begin())); } data->logger()->LogInfo("Application Shutdown"); return 0; }
/* Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include "support/entry/entry.h" #include "support/log/log.h" #include "vulkan_helpers/helper_functions.h" #include "vulkan_helpers/vulkan_application.h" int main_entry(const entry::EntryData* data) { data->logger()->LogInfo("Application Startup"); vulkan::VulkanApplication application(data->allocator(), data->logger(), data, {}, {}, {0}, 1024*1024, 1024*1024, 1024*1024, 1024*1024); const VkExtent3D sample_image_extent{32, 32, 1}; const VkImageCreateInfo sample_image_create_info{ /* sType = */ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* pNext = */ nullptr, /* flags = */ 0, /* imageType = */ VK_IMAGE_TYPE_2D, /* format = */ VK_FORMAT_R8G8B8A8_UINT, /* extent = */ sample_image_extent, /* mipLevels = */ 1, /* arrayLayers = */ 1, /* samples = */ VK_SAMPLE_COUNT_1_BIT, /* tiling = */ VK_IMAGE_TILING_OPTIMAL, /* usage = */ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, /* sharingMode = */ VK_SHARING_MODE_EXCLUSIVE, /* queueFamilyIndexCount = */ 0, /* pQueueFamilyIndices = */ nullptr, /* initialLayout = */ VK_IMAGE_LAYOUT_UNDEFINED, }; { // 1. Resolve from a 2D, Optimal tiling, 4x multi-sampled color image, with // only 1 layer, 1 miplevel and 0 offsets in all dimensions. VkImageCreateInfo src_image_create_info = sample_image_create_info; src_image_create_info.samples = VK_SAMPLE_COUNT_4_BIT; // 4x multi-sampled vulkan::ImagePointer src_image = application.CreateAndBindImage(&src_image_create_info); VkImageCreateInfo dst_image_create_info = sample_image_create_info; vulkan::ImagePointer dst_image = application.CreateAndBindImage(&dst_image_create_info); // Data in the multi-sampled source image VkClearColorValue clear_color; clear_color.uint32[0] = 150; clear_color.uint32[1] = 150; clear_color.uint32[2] = 150; clear_color.uint32[3] = 150; // Range used for vkCmdClearColorImage() to fill the multi-sampled image // with data VkImageSubresourceRange clear_color_range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; // Fill the multi-sampled image with data through vkCmdClearColorImage() vulkan::VkCommandBuffer cmd_buf = application.GetCommandBuffer(); ::VkCommandBuffer raw_cmd_buf = cmd_buf.get_command_buffer(); VkCommandBufferBeginInfo cmd_buf_begin_info{ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0, nullptr}; cmd_buf->vkBeginCommandBuffer(cmd_buf, &cmd_buf_begin_info); vulkan::RecordImageLayoutTransition(*src_image, clear_color_range, VK_IMAGE_LAYOUT_UNDEFINED, 0, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, &cmd_buf); cmd_buf->vkCmdClearColorImage(cmd_buf, *src_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clear_color, 1, &clear_color_range); // Switch src image layout from TRANSFER_DST to TRANSFER_SRC vulkan::RecordImageLayoutTransition( *src_image, clear_color_range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, &cmd_buf); vulkan::RecordImageLayoutTransition(*dst_image, clear_color_range, VK_IMAGE_LAYOUT_UNDEFINED, 0, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, &cmd_buf); VkImageResolve image_resolve{ // mip level 0, layerbase 0, layer count 1 {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, {0, 0, 0}, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, {0, 0, 0}, sample_image_extent, }; // Call vkCmdResolveImage cmd_buf->vkCmdResolveImage( cmd_buf, *src_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_resolve); cmd_buf->vkEndCommandBuffer(cmd_buf); VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &raw_cmd_buf, 0, nullptr}; application.render_queue()->vkQueueSubmit( application.render_queue(), 1, &submit_info, static_cast<VkFence>(VK_NULL_HANDLE)); application.render_queue()->vkQueueWaitIdle(application.render_queue()); // Dump the resolved image data containers::vector<uint8_t> dump_data(data->allocator()); application.DumpImageLayersData( dst_image.get(), {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, // subresourceLayer {0, 0, 0}, // offset sample_image_extent, // extent VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // initial layout &dump_data, // data {} // wait_semaphores ); containers::vector<uint8_t> expected_data(32 * 32 * 4, 150, data->allocator()); LOG_ASSERT(==, data->logger(), expected_data.size(), dump_data.size()); LOG_ASSERT(==, data->logger(), true, std::equal(expected_data.begin(), expected_data.end(), dump_data.begin())); } data->logger()->LogInfo("Application Shutdown"); return 0; }
Change the format to UINT to avoid floating point errors
Change the format to UINT to avoid floating point errors
C++
apache-2.0
google/vulkan_test_applications,google/vulkan_test_applications,google/vulkan_test_applications,google/vulkan_test_applications
79605eb9897d694079c0942c12bf365ef8a61b87
include/opengm/functions/learnable/lweightedsum_of_functions.hxx
include/opengm/functions/learnable/lweightedsum_of_functions.hxx
#pragma once #ifndef OPENGM_LEARNABLE_LWEIGHTEDSUM_OF_FUNCTIONS_FUNCTION_HXX #define OPENGM_LEARNABLE_LWEIGHTEDSUM_OF_FUNCTIONS_FUNCTION_HXX #include <algorithm> #include <vector> #include <cmath> #include "opengm/opengm.hxx" #include "opengm/functions/function_registration.hxx" #include "opengm/functions/function_properties_base.hxx" #include "opengm/datastructures/marray/marray.hxx" #include "opengm/graphicalmodel/weights.hxx" namespace opengm { namespace functions { namespace learnable { /// Learnable weighted sum of feature-functions /// /// f(x) = \sum_i w(i) * feat(i)(x) /// - w = parameter vector /// - feat = feature-function vector /// /// /// \ingroup functions template<class T, class I = size_t, class L = size_t> class LWeightedSumOfFunctions : public opengm::FunctionBase<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>, T, I, L> { public: typedef T ValueType; typedef L LabelType; typedef I IndexType; LWeightedSumOfFunctions(); LWeightedSumOfFunctions(const std::vector<L>& shape, const opengm::learning::Weights<T>& weights, const std::vector<size_t>& weightIDs, const std::vector<marray::Marray<T> >& feat ); L shape(const size_t) const; size_t size() const; size_t dimension() const; template<class ITERATOR> T operator()(ITERATOR) const; // parameters void setWeights(const opengm::learning::Weights<T>& weights) const {weights_ = &weights;} size_t numberOfWeights()const {return weightIDs_.size();} I weightIndex(const size_t weightNumber) const {return weightIDs_[weightNumber];} //dummy template<class ITERATOR> T weightGradient(size_t,ITERATOR) const; protected: mutable const opengm::learning::Weights<T>* weights_; std::vector<L> shape_; std::vector<size_t> weightIDs_; std::vector<marray::Marray<T> > feat_; friend class opengm::FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >; }; template <class T, class I, class L> inline LWeightedSumOfFunctions<T, I, L>::LWeightedSumOfFunctions ( const std::vector<L>& shape, const opengm::learning::Weights<T>& weights, const std::vector<size_t>& weightIDs, const std::vector<marray::Marray<T> >& feat ) : shape_(shape), weights_(&weights), weightIDs_(weightIDs),feat_(feat) { OPENGM_ASSERT( weightIDs_.size() == feat_.size() ); for(size_t i=0 i<weightIDs_.size();++1) OPENGM_ASSERT( size() == feat_[i].size() ); } template <class T, class I, class L> inline LWeightedSumOfFunctions<T, I, L>::LWeightedSumOfFunctions() : shape_(std::vector<L>(0)), weightIDs_(std::vector<size_t>(0)), feat_(std::vector<marray::Marray<T> >(0)) { ; } template <class T, class I, class L> template <class ITERATOR> inline T LWeightedSumOfFunctions<T, I, L>::weightGradient ( size_t weightNumber, ITERATOR begin ) const { OPENGM_ASSERT(weightNumber< numberOfWeights()); return feat_[weightNumber](*begin); } template <class T, class I, class L> template <class ITERATOR> inline T LWeightedSumOfFunctions<T, I, L>::operator() ( ITERATOR begin ) const { T val = 0; for(size_t i=0;i<numberOfWeights();++i){ val += weights_->getWeight(weightIDs_[i]) * weightGradient(i,begin); } return val; } template <class T, class I, class L> inline L LWeightedSumOfFunctions<T, I, L>::shape ( const size_t i ) const { return shape_[i]; } template <class T, class I, class L> inline size_t LWeightedSumOfFunctions<T, I, L>::dimension() const { return shape_.size(); } template <class T, class I, class L> inline size_t LWeightedSumOfFunctions<T, I, L>::size() const { size_t s = 1; for(size_t i=0; i<dimension(); ++i) s *=shape_[i]; return s; } } // namespace learnable } // namespace functions /// FunctionSerialization template<class T, class I, class L> class FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> > { public: typedef typename opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>::ValueType ValueType; static size_t indexSequenceSize(const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&); static size_t valueSequenceSize(const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&); template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR> static void serialize(const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR> static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&); }; template<class T, class I, class L> struct FunctionRegistration<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> > { enum ID { Id = opengm::FUNCTION_TYPE_ID_OFFSET + 100 + 67 }; }; template<class T, class I, class L> inline size_t FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::indexSequenceSize ( const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & src ) { return 1+src.shape_.size()+1+src.weightIDs_.size(); } template<class T, class I, class L> inline size_t FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::valueSequenceSize ( const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & src ) { return src.feat_.size()*src.size(); } template<class T, class I, class L> template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR > inline void FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::serialize ( const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator ) { // save shape *indexOutIterator = src.shape_.size(); ++indexOutIterator; for(size_t i=0; i<src.shape_.size();++i){ *indexOutIterator = src.shape_[i]; ++indexOutIterator; } //save parameter ids *indexOutIterator = src.weightIDs_.size(); ++indexOutIterator; for(size_t i=0; i<src.weightIDs_.size();++i){ *indexOutIterator = src.weightIDs_[i]; ++indexOutIterator; } OPENGM_ASSERT_OP(src.weightIDs_.size(), ==, src.feat_.size()); // save features for(size_t i=0; i<src.weightIDs_.size();++i){ for(size_t j=0; j<src.feat_[i].size();++j){ *valueOutIterator = src.feat_[i](j); ++valueOutIterator; } } } template<class T, class I, class L> template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR > inline void FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::deserialize ( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & dst ) { //read shape size_t dim = *indexInIterator; size_t size = 1; ++indexInIterator; std::vector<L> shape(dim); for(size_t i=0; i<dim;++i){ shape[i] = *indexInIterator; size *= *indexInIterator; ++indexInIterator; } //read parameter ids size_t numW =*indexInIterator; ++indexInIterator; std::vector<size_t> parameterIDs(numW); for(size_t i=0; i<numW;++i){ parameterIDs[i] = *indexInIterator; ++indexInIterator; } //read features std::vector<marray::Marray<T> > feat(numW,marray::Marray<T>(shape.begin(),shape.end())); for(size_t i=0; i<numW;++i){ for(size_t j=0; j<size;++j){ feat[i](j)=*valueInIterator; ++valueInIterator; } } } } // namespace opengm #endif //OPENGM_LEARNABLE_LWEIGHTEDSUM_OF_FUNCTIONS_FUNCTION_HXX
#pragma once #ifndef OPENGM_LEARNABLE_LWEIGHTEDSUM_OF_FUNCTIONS_FUNCTION_HXX #define OPENGM_LEARNABLE_LWEIGHTEDSUM_OF_FUNCTIONS_FUNCTION_HXX #include <algorithm> #include <vector> #include <cmath> #include "opengm/opengm.hxx" #include "opengm/functions/function_registration.hxx" #include "opengm/functions/function_properties_base.hxx" #include "opengm/datastructures/marray/marray.hxx" #include "opengm/graphicalmodel/weights.hxx" namespace opengm { namespace functions { namespace learnable { /// Learnable weighted sum of feature-functions /// /// f(x) = \sum_i w(i) * feat(i)(x) /// - w = parameter vector /// - feat = feature-function vector /// /// /// \ingroup functions template<class T, class I = size_t, class L = size_t> class LWeightedSumOfFunctions : public opengm::FunctionBase<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>, T, I, L> { public: typedef T ValueType; typedef L LabelType; typedef I IndexType; LWeightedSumOfFunctions(); LWeightedSumOfFunctions(const std::vector<L>& shape, const opengm::learning::Weights<T>& weights, const std::vector<size_t>& weightIDs, const std::vector<marray::Marray<T> >& feat ); L shape(const size_t) const; size_t size() const; size_t dimension() const; template<class ITERATOR> T operator()(ITERATOR) const; // parameters void setWeights(const opengm::learning::Weights<T>& weights) const {weights_ = &weights;} size_t numberOfWeights()const {return weightIDs_.size();} I weightIndex(const size_t weightNumber) const {return weightIDs_[weightNumber];} //dummy template<class ITERATOR> T weightGradient(size_t,ITERATOR) const; protected: mutable const opengm::learning::Weights<T>* weights_; std::vector<L> shape_; std::vector<size_t> weightIDs_; std::vector<marray::Marray<T> > feat_; friend class opengm::FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >; }; template <class T, class I, class L> inline LWeightedSumOfFunctions<T, I, L>::LWeightedSumOfFunctions ( const std::vector<L>& shape, const opengm::learning::Weights<T>& weights, const std::vector<size_t>& weightIDs, const std::vector<marray::Marray<T> >& feat ) : shape_(shape), weights_(&weights), weightIDs_(weightIDs),feat_(feat) { OPENGM_ASSERT( weightIDs_.size() == feat_.size() ); for(size_t i=0; i<weightIDs_.size(); ++i) OPENGM_ASSERT( size() == feat_[i].size() ); } template <class T, class I, class L> inline LWeightedSumOfFunctions<T, I, L>::LWeightedSumOfFunctions() : shape_(std::vector<L>(0)), weightIDs_(std::vector<size_t>(0)), feat_(std::vector<marray::Marray<T> >(0)) { ; } template <class T, class I, class L> template <class ITERATOR> inline T LWeightedSumOfFunctions<T, I, L>::weightGradient ( size_t weightNumber, ITERATOR begin ) const { OPENGM_ASSERT(weightNumber< numberOfWeights()); return feat_[weightNumber](*begin); } template <class T, class I, class L> template <class ITERATOR> inline T LWeightedSumOfFunctions<T, I, L>::operator() ( ITERATOR begin ) const { T val = 0; for(size_t i=0;i<numberOfWeights();++i){ val += weights_->getWeight(weightIDs_[i]) * weightGradient(i,begin); } return val; } template <class T, class I, class L> inline L LWeightedSumOfFunctions<T, I, L>::shape ( const size_t i ) const { return shape_[i]; } template <class T, class I, class L> inline size_t LWeightedSumOfFunctions<T, I, L>::dimension() const { return shape_.size(); } template <class T, class I, class L> inline size_t LWeightedSumOfFunctions<T, I, L>::size() const { size_t s = 1; for(size_t i=0; i<dimension(); ++i) s *=shape_[i]; return s; } } // namespace learnable } // namespace functions /// FunctionSerialization template<class T, class I, class L> class FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> > { public: typedef typename opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>::ValueType ValueType; static size_t indexSequenceSize(const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&); static size_t valueSequenceSize(const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&); template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR> static void serialize(const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR> static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L>&); }; template<class T, class I, class L> struct FunctionRegistration<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> > { enum ID { Id = opengm::FUNCTION_TYPE_ID_OFFSET + 100 + 67 }; }; template<class T, class I, class L> inline size_t FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::indexSequenceSize ( const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & src ) { return 1+src.shape_.size()+1+src.weightIDs_.size(); } template<class T, class I, class L> inline size_t FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::valueSequenceSize ( const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & src ) { return src.feat_.size()*src.size(); } template<class T, class I, class L> template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR > inline void FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::serialize ( const opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator ) { // save shape *indexOutIterator = src.shape_.size(); ++indexOutIterator; for(size_t i=0; i<src.shape_.size();++i){ *indexOutIterator = src.shape_[i]; ++indexOutIterator; } //save parameter ids *indexOutIterator = src.weightIDs_.size(); ++indexOutIterator; for(size_t i=0; i<src.weightIDs_.size();++i){ *indexOutIterator = src.weightIDs_[i]; ++indexOutIterator; } OPENGM_ASSERT_OP(src.weightIDs_.size(), ==, src.feat_.size()); // save features for(size_t i=0; i<src.weightIDs_.size();++i){ for(size_t j=0; j<src.feat_[i].size();++j){ *valueOutIterator = src.feat_[i](j); ++valueOutIterator; } } } template<class T, class I, class L> template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR > inline void FunctionSerialization<opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> >::deserialize ( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, opengm::functions::learnable::LWeightedSumOfFunctions<T, I, L> & dst ) { //read shape size_t dim = *indexInIterator; size_t size = 1; ++indexInIterator; std::vector<L> shape(dim); for(size_t i=0; i<dim;++i){ shape[i] = *indexInIterator; size *= *indexInIterator; ++indexInIterator; } //read parameter ids size_t numW =*indexInIterator; ++indexInIterator; std::vector<size_t> parameterIDs(numW); for(size_t i=0; i<numW;++i){ parameterIDs[i] = *indexInIterator; ++indexInIterator; } //read features std::vector<marray::Marray<T> > feat(numW,marray::Marray<T>(shape.begin(),shape.end())); for(size_t i=0; i<numW;++i){ for(size_t j=0; j<size;++j){ feat[i](j)=*valueInIterator; ++valueInIterator; } } } } // namespace opengm #endif //OPENGM_LEARNABLE_LWEIGHTEDSUM_OF_FUNCTIONS_FUNCTION_HXX
Update lweightedsum_of_functions.hxx
Update lweightedsum_of_functions.hxx fix typo in assert-loop
C++
mit
chaubold/opengm,joergkappes/opengm,joergkappes/opengm,joergkappes/opengm,chaubold/opengm,chaubold/opengm,chaubold/opengm,DerThorsten/opengm,DerThorsten/opengm,joergkappes/opengm,opengm/opengm,DerThorsten/opengm,joergkappes/opengm,plstcharles/opengm,opengm/opengm,plstcharles/opengm,DerThorsten/opengm,plstcharles/opengm,plstcharles/opengm,chaubold/opengm,opengm/opengm,DerThorsten/opengm,opengm/opengm,opengm/opengm,plstcharles/opengm
0dd9c789302aca305740c848f0f9c486b2d0f3eb
include/tudocomp/compressors/esacomp/decoding/MultiMapBuffer.hpp
include/tudocomp/compressors/esacomp/decoding/MultiMapBuffer.hpp
#pragma once #include <tudocomp/Algorithm.hpp> #include <tudocomp/def.hpp> #include <sdsl/int_vector.hpp> namespace tdc { namespace esacomp { class MultimapBuffer : public Algorithm { public: inline static Meta meta() { Meta m("esadec", "MultimapListBuffer"); m.option("lazy").dynamic("0"); return m; } private: std::vector<uliteral_t> m_buffer; std::unordered_multimap<len_t, len_t> m_fwd; sdsl::bit_vector m_decoded; len_t m_cursor; len_t m_longest_chain; len_t m_current_chain; //storing factors std::vector<len_t> m_target_pos; std::vector<len_t> m_source_pos; std::vector<len_t> m_length; const size_t m_lazy; // number of lazy rounds inline void decode_literal_at(len_t pos, uliteral_t c) { ++m_current_chain; m_longest_chain = std::max(m_longest_chain, m_current_chain); m_buffer[pos] = c; m_decoded[pos] = 1; // { // const auto range = m_fwd.equal_range(pos); // for (auto it = range.first; it != range.second; ++it) { // decode_literal_at(it->second, c); // recursion // } // } // m_fwd.erase(pos); // // // for(auto it = m_fwd.find(pos); it != m_fwd.end(); it = m_fwd.find(pos)) { //TODO: replace with equal_range! decode_literal_at(it->second, c); // recursion m_fwd.erase(it); } // for(auto it = m_fwd.find(pos); it != m_fwd.end(); it = m_fwd.find(pos)) { //TODO: replace with equal_range! // decode_literal_at(it->second, c); // recursion // } // m_fwd.erase(pos); --m_current_chain; } inline void decode_lazy_() { const len_t factors = m_source_pos.size(); for(len_t j = 0; j < factors; ++j) { const len_t& target_position = m_target_pos[j]; const len_t& source_position = m_source_pos[j]; const len_t& factor_length = m_length[j]; for(len_t i = 0; i < factor_length; ++i) { if(m_decoded[source_position+i]) { m_buffer[target_position+i] = m_buffer[source_position+i]; m_decoded[target_position+i] = 1; } } } } public: inline MultimapBuffer(Env&& env, len_t size) : Algorithm(std::move(env)), m_cursor(0), m_longest_chain(0), m_current_chain(0), m_lazy(this->env().option("lazy").as_integer()) { m_fwd.max_load_factor(0.8); m_buffer.resize(size, 0); m_decoded = sdsl::bit_vector(size, 0); } inline void decode_literal(uliteral_t c) { decode_literal_at(m_cursor++, c); } inline void decode_factor(const len_t source_position, const len_t factor_length) { bool factor_stored = false; for(len_t i = 0; i < factor_length; ++i) { const len_t src_pos = source_position+i; if(m_decoded[src_pos]) { m_buffer[m_cursor] = m_buffer[src_pos]; m_decoded[m_cursor] = 1; } else if(factor_stored == false) { factor_stored = true; m_target_pos.push_back(m_cursor); m_source_pos.push_back(src_pos); m_length.push_back(factor_length-i); } ++m_cursor; } } inline void decode_lazy() { size_t lazy = m_lazy; while(lazy > 0) { decode_lazy_(); --lazy; } } tdc_stats(size_t max_size = 0); inline void decode_eagerly() { const len_t factors = m_source_pos.size(); env().log_stat("factors", factors); env().begin_stat_phase("Decoding Factors"); for(len_t j = 0; j < factors; ++j) { const len_t& target_position = m_target_pos[j]; const len_t& source_position = m_source_pos[j]; const len_t& factor_length = m_length[j]; for(len_t i = 0; i < factor_length; ++i) { if(m_decoded[source_position+i]) { decode_literal_at(target_position+i, m_buffer[source_position+i]); } else { m_fwd.emplace(source_position+i, target_position+i); } } tdc_stats(max_size = std::max(max_size, m_fwd.bucket_count())); if(tdc_stats((j+1) % (factors/5) == 0 )) { env().log_stat("hash table size", m_fwd.bucket_count()); env().log_stat("hash table entries", m_fwd.size()); env().end_stat_phase(); env().begin_stat_phase("Decoding Factors at position " + std::to_string(target_position)); } } env().log_stat("hash table max size", max_size); env().end_stat_phase(); } inline len_t longest_chain() const { return m_longest_chain; } inline void write_to(std::ostream& out) { for(auto c : m_buffer) out << c; } }; }}//ns
#pragma once #include <tudocomp/Algorithm.hpp> #include <tudocomp/def.hpp> #include <sdsl/int_vector.hpp> namespace tdc { namespace esacomp { class MultimapBuffer : public Algorithm { public: inline static Meta meta() { Meta m("esadec", "MultimapListBuffer"); m.option("lazy").dynamic("0"); return m; } private: std::vector<uliteral_t> m_buffer; std::unordered_multimap<len_t, len_t> m_fwd; sdsl::bit_vector m_decoded; len_t m_cursor; len_t m_longest_chain; len_t m_current_chain; //storing factors std::vector<len_t> m_target_pos; std::vector<len_t> m_source_pos; std::vector<len_t> m_length; const size_t m_lazy; // number of lazy rounds inline void decode_literal_at(len_t pos, uliteral_t c) { ++m_current_chain; m_longest_chain = std::max(m_longest_chain, m_current_chain); m_buffer[pos] = c; m_decoded[pos] = 1; // { // const auto range = m_fwd.equal_range(pos); // for (auto it = range.first; it != range.second; ++it) { // decode_literal_at(it->second, c); // recursion // } // } // m_fwd.erase(pos); // // // for(auto it = m_fwd.find(pos); it != m_fwd.end(); it = m_fwd.find(pos)) { //TODO: replace with equal_range! decode_literal_at(it->second, c); // recursion m_fwd.erase(it); } // for(auto it = m_fwd.find(pos); it != m_fwd.end(); it = m_fwd.find(pos)) { //TODO: replace with equal_range! // decode_literal_at(it->second, c); // recursion // } // m_fwd.erase(pos); --m_current_chain; } inline void decode_lazy_() { const len_t factors = m_source_pos.size(); for(len_t j = 0; j < factors; ++j) { const len_t& target_position = m_target_pos[j]; const len_t& source_position = m_source_pos[j]; const len_t& factor_length = m_length[j]; for(len_t i = 0; i < factor_length; ++i) { if(m_decoded[source_position+i]) { m_buffer[target_position+i] = m_buffer[source_position+i]; m_decoded[target_position+i] = 1; } } } } public: inline MultimapBuffer(Env&& env, len_t size) : Algorithm(std::move(env)), m_cursor(0), m_longest_chain(0), m_current_chain(0), m_lazy(this->env().option("lazy").as_integer()) { m_fwd.max_load_factor(0.8); m_buffer.resize(size, 0); m_decoded = sdsl::bit_vector(size, 0); } inline void decode_literal(uliteral_t c) { decode_literal_at(m_cursor++, c); } inline void decode_factor(const len_t source_position, const len_t factor_length) { bool factor_stored = false; for(len_t i = 0; i < factor_length; ++i) { const len_t src_pos = source_position+i; if(m_decoded[src_pos]) { m_buffer[m_cursor] = m_buffer[src_pos]; m_decoded[m_cursor] = 1; } else if(factor_stored == false) { factor_stored = true; m_target_pos.push_back(m_cursor); m_source_pos.push_back(src_pos); m_length.push_back(factor_length-i); } ++m_cursor; } } inline void decode_lazy() { size_t lazy = m_lazy; while(lazy > 0) { decode_lazy_(); --lazy; } } tdc_stats(size_t max_size = 0); inline void decode_eagerly() { const len_t factors = m_source_pos.size(); env().log_stat("factors", factors); env().begin_stat_phase("Decoding Factors"); for(len_t j = 0; j < factors; ++j) { const len_t& target_position = m_target_pos[j]; const len_t& source_position = m_source_pos[j]; const len_t& factor_length = m_length[j]; for(len_t i = 0; i < factor_length; ++i) { if(m_decoded[source_position+i]) { decode_literal_at(target_position+i, m_buffer[source_position+i]); } else { m_fwd.emplace(source_position+i, target_position+i); } } tdc_stats(max_size = std::max(max_size, m_fwd.bucket_count())); if(tdc_stats((j+1) % ((factors+5)/5) == 0 )) { env().log_stat("hash table size", m_fwd.bucket_count()); env().log_stat("hash table entries", m_fwd.size()); env().end_stat_phase(); env().begin_stat_phase("Decoding Factors at position " + std::to_string(target_position)); } } env().log_stat("hash table max size", max_size); env().end_stat_phase(); } inline len_t longest_chain() const { return m_longest_chain; } inline void write_to(std::ostream& out) { for(auto c : m_buffer) out << c; } }; }}//ns
Fix MultiMap arithmetic exception
Fix MultiMap arithmetic exception
C++
apache-2.0
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
a7c44b2e9f53f9407837e930f61fafeb3bb86376
src/unit_VEHICLE/models/hmmwv/suspension/HMMWV_DoubleWishboneReduced.cpp
src/unit_VEHICLE/models/hmmwv/suspension/HMMWV_DoubleWishboneReduced.cpp
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Front and Rear HMMWV suspension subsystems (reduced double A-arm). // // These concrete suspension subsystems are defined with respect to right-handed // frames with X pointing towards the front, Y to the left, and Z up (as imposed // by the base class ChDoubleWishboneReduced) and origins at the midpoint // between the lower control arms' connection points to the chassis. // // All point locations are provided for the left half of the supspension. // // ============================================================================= #include "models/hmmwv/suspension/HMMWV_DoubleWishboneReduced.h" using namespace chrono; namespace hmmwv { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- static const double in2m = 0.0254; static const double lb2kg = 0.453592; static const double lbf2N = 4.44822162; static const double lbfpin2Npm = 175.12677; // entire wheel assembly = 195 lbs, includes upright, spindle and tire. // HMMWV tires run ~ 100 lbs, so the spindle and upright should be ~ 95 lbs combined const double HMMWV_DoubleWishboneReducedFront::m_uprightMass = lb2kg * 60.0; const double HMMWV_DoubleWishboneReducedFront::m_spindleMass = lb2kg * 35.0; const double HMMWV_DoubleWishboneReducedFront::m_spindleRadius = 0.15; const double HMMWV_DoubleWishboneReducedFront::m_spindleWidth = 0.06; const double HMMWV_DoubleWishboneReducedFront::m_uprightRadius = 0.02; const ChVector<> HMMWV_DoubleWishboneReducedFront::m_spindleInertia(1, 1, 1); const ChVector<> HMMWV_DoubleWishboneReducedFront::m_uprightInertia(5, 5, 5); const double HMMWV_DoubleWishboneReducedFront::m_axleInertia = 0.4; const double HMMWV_DoubleWishboneReducedFront::m_springCoefficient = lbfpin2Npm * 954; const double HMMWV_DoubleWishboneReducedFront::m_dampingCoefficient = lbfpin2Npm * 128.25; const double HMMWV_DoubleWishboneReducedFront::m_springRestLength = in2m * 13.36; // ----------------------------------------------------------------------------- const double HMMWV_DoubleWishboneReducedRear::m_uprightMass = lb2kg * 60.0; const double HMMWV_DoubleWishboneReducedRear::m_spindleMass = lb2kg * 35.0; const double HMMWV_DoubleWishboneReducedRear::m_spindleRadius = 0.15; const double HMMWV_DoubleWishboneReducedRear::m_spindleWidth = 0.06; const double HMMWV_DoubleWishboneReducedRear::m_uprightRadius = 0.02; const ChVector<> HMMWV_DoubleWishboneReducedRear::m_spindleInertia(1, 1, 1); const ChVector<> HMMWV_DoubleWishboneReducedRear::m_uprightInertia(5, 5, 5); const double HMMWV_DoubleWishboneReducedRear::m_axleInertia = 0.4; const double HMMWV_DoubleWishboneReducedRear::m_springCoefficient = lbfpin2Npm * 2108; const double HMMWV_DoubleWishboneReducedRear::m_dampingCoefficient = lbfpin2Npm * 200.00; const double HMMWV_DoubleWishboneReducedRear::m_springRestLength = in2m * 15.03; // ----------------------------------------------------------------------------- // Constructors // ----------------------------------------------------------------------------- HMMWV_DoubleWishboneReducedFront::HMMWV_DoubleWishboneReducedFront(const std::string& name, bool driven) : ChDoubleWishboneReduced(name, true, driven) { } HMMWV_DoubleWishboneReducedRear::HMMWV_DoubleWishboneReducedRear(const std::string& name, bool driven) : ChDoubleWishboneReduced(name, false, driven) { } // ----------------------------------------------------------------------------- // Implementations of the getLocation() virtual methods. // ----------------------------------------------------------------------------- const ChVector<> HMMWV_DoubleWishboneReducedFront::getLocation(PointId which) { switch (which) { case SPINDLE: return in2m * ChVector<>(-1.59, 35.815, -1.0350); case UPRIGHT: return in2m * ChVector<>(-1.59, 31.81, -1.0350); case UCA_F: return in2m * ChVector<>(-1.89, 17.55, 9.63); case UCA_B: return in2m * ChVector<>(-10.56, 18.81, 7.69); case UCA_U: return in2m * ChVector<>(-2.09, 28.16, 8.48); case LCA_F: return in2m * ChVector<>(8.79, 12.09, 0); case LCA_B: return in2m * ChVector<>(-8.79, 12.09, 0); case LCA_U: return in2m * ChVector<>(-1.40, 30.96, -4.65); case SHOCK_C: return in2m * ChVector<>(4.10, 27.86, 12.72); case SHOCK_U: return in2m * ChVector<>(3.83, 30.96, -1.52); case TIEROD_C: return in2m * ChVector<>(-13.39, 9.8, -1.0350); case TIEROD_U: return in2m * ChVector<>(-6.92, 32.31, -1.0350); default: return ChVector<>(0, 0, 0); } } const ChVector<> HMMWV_DoubleWishboneReducedRear::getLocation(PointId which) { switch (which) { case SPINDLE: return in2m * ChVector<>(1.40, 35.815, -1.035); case UPRIGHT: return in2m * ChVector<>(1.40, 31.81, -1.035); case UCA_F: return in2m * ChVector<>(13.78, 18.19, 8.88); case UCA_B: return in2m * ChVector<>(3.07, 18.19, 8.88); case UCA_U: return in2m * ChVector<>(1.40, 28.16, 8.50); case LCA_F: return in2m * ChVector<>(8.79, 12.09, 0); case LCA_B: return in2m * ChVector<>(-8.79, 12.09, 0); case LCA_U: return in2m * ChVector<>(1.40, 30.96, -4.65); case SHOCK_C: return in2m * ChVector<>(-4.09, 28.19, 12.72); case SHOCK_U: return in2m * ChVector<>(-4.09, 30.96, -1.51); case TIEROD_C: return in2m * ChVector<>(12.70, 16.37, -0.37); case TIEROD_U: return in2m * ChVector<>(6.70, 32.32, -0.37); default: return ChVector<>(0, 0, 0); } } } // end namespace hmmwv
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Front and Rear HMMWV suspension subsystems (reduced double A-arm). // // These concrete suspension subsystems are defined with respect to right-handed // frames with X pointing towards the front, Y to the left, and Z up (as imposed // by the base class ChDoubleWishboneReduced) and origins at the midpoint // between the lower control arms' connection points to the chassis. // // All point locations are provided for the left half of the supspension. // // ============================================================================= #include "models/hmmwv/suspension/HMMWV_DoubleWishboneReduced.h" using namespace chrono; namespace hmmwv { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- static const double in2m = 0.0254; static const double lb2kg = 0.453592; static const double lbf2N = 4.44822162; static const double lbfpin2Npm = 175.12677; // entire wheel assembly = 195 lbs, includes upright, spindle and tire. // HMMWV tires run ~ 100 lbs, so the spindle and upright should be ~ 95 lbs combined const double HMMWV_DoubleWishboneReducedFront::m_uprightMass = lb2kg * 60.0; const double HMMWV_DoubleWishboneReducedFront::m_spindleMass = lb2kg * 35.0; const double HMMWV_DoubleWishboneReducedFront::m_spindleRadius = 0.15; const double HMMWV_DoubleWishboneReducedFront::m_spindleWidth = 0.06; const double HMMWV_DoubleWishboneReducedFront::m_uprightRadius = 0.02; const ChVector<> HMMWV_DoubleWishboneReducedFront::m_spindleInertia(1, 1, 1); const ChVector<> HMMWV_DoubleWishboneReducedFront::m_uprightInertia(5, 5, 5); const double HMMWV_DoubleWishboneReducedFront::m_axleInertia = 0.4; const double HMMWV_DoubleWishboneReducedFront::m_springCoefficient = lbfpin2Npm * 954; const double HMMWV_DoubleWishboneReducedFront::m_dampingCoefficient = lbfpin2Npm * 128.25; const double HMMWV_DoubleWishboneReducedFront::m_springRestLength = in2m * 13.36; // ----------------------------------------------------------------------------- const double HMMWV_DoubleWishboneReducedRear::m_uprightMass = lb2kg * 60.0; const double HMMWV_DoubleWishboneReducedRear::m_spindleMass = lb2kg * 35.0; const double HMMWV_DoubleWishboneReducedRear::m_spindleRadius = 0.15; const double HMMWV_DoubleWishboneReducedRear::m_spindleWidth = 0.06; const double HMMWV_DoubleWishboneReducedRear::m_uprightRadius = 0.02; const ChVector<> HMMWV_DoubleWishboneReducedRear::m_spindleInertia(1, 1, 1); const ChVector<> HMMWV_DoubleWishboneReducedRear::m_uprightInertia(5, 5, 5); const double HMMWV_DoubleWishboneReducedRear::m_axleInertia = 0.4; const double HMMWV_DoubleWishboneReducedRear::m_springCoefficient = lbfpin2Npm * 2108; const double HMMWV_DoubleWishboneReducedRear::m_dampingCoefficient = lbfpin2Npm * 200.00; const double HMMWV_DoubleWishboneReducedRear::m_springRestLength = in2m * 15.03; // ----------------------------------------------------------------------------- // Constructors // ----------------------------------------------------------------------------- HMMWV_DoubleWishboneReducedFront::HMMWV_DoubleWishboneReducedFront(const std::string& name, bool driven) : ChDoubleWishboneReduced(name, true, driven) { } HMMWV_DoubleWishboneReducedRear::HMMWV_DoubleWishboneReducedRear(const std::string& name, bool driven) : ChDoubleWishboneReduced(name, false, driven) { } // ----------------------------------------------------------------------------- // Implementations of the getLocation() virtual methods. // ----------------------------------------------------------------------------- const ChVector<> HMMWV_DoubleWishboneReducedFront::getLocation(PointId which) { switch (which) { case SPINDLE: return in2m * ChVector<>(-1.59, 35.815, -1.0350); case UPRIGHT: return in2m * ChVector<>(-1.59, 31.81, -1.0350); case UCA_F: return in2m * ChVector<>(-1.89, 17.55, 9.63); case UCA_B: return in2m * ChVector<>(-10.56, 18.81, 7.69); case UCA_U: return in2m * ChVector<>(-2.09, 28.16, 8.48); case LCA_F: return in2m * ChVector<>(8.79, 12.09, 0); case LCA_B: return in2m * ChVector<>(-8.79, 12.09, 0); case LCA_U: return in2m * ChVector<>(-1.40, 30.96, -4.65); case SHOCK_C: return in2m * ChVector<>(4.10, 27.86, 12.72); case SHOCK_U: return in2m * ChVector<>(3.83, 30.96, -1.52); case TIEROD_C: return in2m * ChVector<>(-9.855, 17.655, 2.135); case TIEROD_U: return in2m * ChVector<>(-6.922, 32.327, -0.643); default: return ChVector<>(0, 0, 0); } } const ChVector<> HMMWV_DoubleWishboneReducedRear::getLocation(PointId which) { switch (which) { case SPINDLE: return in2m * ChVector<>(1.40, 35.815, -1.035); case UPRIGHT: return in2m * ChVector<>(1.40, 31.81, -1.035); case UCA_F: return in2m * ChVector<>(13.78, 18.19, 8.88); case UCA_B: return in2m * ChVector<>(3.07, 18.19, 8.88); case UCA_U: return in2m * ChVector<>(1.40, 28.16, 8.50); case LCA_F: return in2m * ChVector<>(8.79, 12.09, 0); case LCA_B: return in2m * ChVector<>(-8.79, 12.09, 0); case LCA_U: return in2m * ChVector<>(1.40, 30.96, -4.65); case SHOCK_C: return in2m * ChVector<>(-4.09, 28.19, 12.72); case SHOCK_U: return in2m * ChVector<>(-4.09, 30.96, -1.51); case TIEROD_C: return in2m * ChVector<>(8.790, 16.38, 2.310); case TIEROD_U: return in2m * ChVector<>(6.704, 32.327, -0.365); default: return ChVector<>(0, 0, 0); } } } // end namespace hmmwv
Modify tierod attachment points to match the full double wishbone suspension.
Modify tierod attachment points to match the full double wishbone suspension.
C++
bsd-3-clause
armanpazouki/chrono,amelmquist/chrono,Milad-Rakhsha/chrono,andrewseidl/chrono,projectchrono/chrono,jcmadsen/chrono,jcmadsen/chrono,rserban/chrono,armanpazouki/chrono,jcmadsen/chrono,amelmquist/chrono,armanpazouki/chrono,amelmquist/chrono,Bryan-Peterson/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,Milad-Rakhsha/chrono,projectchrono/chrono,rserban/chrono,tjolsen/chrono,Bryan-Peterson/chrono,Bryan-Peterson/chrono,dariomangoni/chrono,tjolsen/chrono,projectchrono/chrono,rserban/chrono,Bryan-Peterson/chrono,dariomangoni/chrono,amelmquist/chrono,Bryan-Peterson/chrono,armanpazouki/chrono,projectchrono/chrono,armanpazouki/chrono,jcmadsen/chrono,tjolsen/chrono,jcmadsen/chrono,andrewseidl/chrono,rserban/chrono,dariomangoni/chrono,jcmadsen/chrono,rserban/chrono,tjolsen/chrono,amelmquist/chrono,projectchrono/chrono,armanpazouki/chrono,Milad-Rakhsha/chrono,andrewseidl/chrono,Milad-Rakhsha/chrono,projectchrono/chrono,jcmadsen/chrono,rserban/chrono,andrewseidl/chrono,Milad-Rakhsha/chrono,rserban/chrono,andrewseidl/chrono,dariomangoni/chrono,dariomangoni/chrono,tjolsen/chrono,amelmquist/chrono
d7b0636c668b1b72f6ae7d2ab68751397e538470
tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/fusion_utils.cc
tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/fusion_utils.cc
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "mlir-hlo/Dialect/lhlo/transforms/fusion_utils.h" #include <algorithm> #include "mlir/Dialect/Shape/IR/Shape.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/Matchers.h" // This file implements some helper functions and classes used to do fusion // & code generation. namespace mlir { namespace lmhlo { // Returns true if the op is an elementwise unary lmhlo op. // TODO(disc): use fusibility interface // TODO(disc): Unify with disc_supported_list.h and Elementwise Trait bool isElementWiseUnary(Operation* op) { // clang-format off return isa< lmhlo::AbsOp, lmhlo::CeilOp, lmhlo::ConvertOp, lmhlo::CopyOp, lmhlo::CosOp, lmhlo::ExpOp, lmhlo::FloorOp, lmhlo::IsFiniteOp, lmhlo::LogOp, lmhlo::NegOp, lmhlo::NotOp, lmhlo::RsqrtOp, lmhlo::SignOp, lmhlo::SqrtOp, lmhlo::TanhOp >(op); // clang-format on } // Returns true if the op is an elementwise binary lmhlo op. // TODO(disc): use fusibility interface bool isElementWiseBinary(Operation* op) { // clang-format off return isa< lmhlo::AddOp, lmhlo::AndOp, lmhlo::CompareOp, lmhlo::DivOp, lmhlo::MaxOp, lmhlo::MinOp, lmhlo::MulOp, lmhlo::OrOp, lmhlo::PowOp, lmhlo::SubOp >(op); // clang-format on } // Returns true if the op is an elementwise lmhlo op. // TODO(disc): use fusibility interface bool isElementWise(Operation* op) { return isElementWiseUnary(op) || isElementWiseBinary(op); } // Returns true if this op is a rank-2 row reduction. bool isRank2RowReduction(Operation* op) { auto reduce_op = dyn_cast<lmhlo::ReduceOp>(op); if (!reduce_op || reduce_op.dimensions().getNumElements() != 1) return false; int rank = op->getOperand(0).getType().cast<MemRefType>().getRank(); auto dimensions = reduce_op.dimensions().getValues<int64_t>(); return ((*dimensions.begin() == 1) && (rank == 2)); } // Returns true if this op is a rank-2 column reduction. bool isRank2ColReduction(Operation* op) { auto reduce_op = dyn_cast<lmhlo::ReduceOp>(op); if (!reduce_op || reduce_op.dimensions().getNumElements() != 1) return false; int rank = op->getOperand(0).getType().cast<MemRefType>().getRank(); auto dimensions = reduce_op.dimensions().getValues<int64_t>(); return ((*dimensions.begin() == 0) && (rank == 2)); } // Returns true if the op is supported by the downstreaming fusion codegen // engine. bool isFusible(Operation* op) { // Only scalar const are supported by the fusion codegen engine a.t.m. if (dyn_cast<lmhlo::ConstOp>(op)) { MemRefType type = op->getOperand(0).getType().cast<MemRefType>(); return (type.getRank() == 0); } // All element ops are supported by the fusion codegen engine. if (isElementWise(op)) return true; // Only rank-2 tensor -> rank-1 tensor reduction are supported now. if (isRank2RowReduction(op) || isRank2ColReduction(op)) return true; // clang-format off return isa< lmhlo::BroadcastInDimOp, lmhlo::BroadcastOp, lmhlo::ConcatenateOp, lmhlo::DynamicBroadcastInDimOp, lmhlo::DynamicGatherOp, lmhlo::DynamicIotaOp, lmhlo::DynamicPadOp, lmhlo::DynamicReshapeOp, lmhlo::GatherOp, lmhlo::RealDynamicSliceOp, lmhlo::ReshapeOp, lmhlo::SelectOp, lmhlo::SliceOp, lmhlo::TransposeOp >(op); // clang-format on } // Returns the number of operands that are supposed to be written. // For some ops (e.g. lmhlo ops), some operands are the output memrefs // Thus these operands are supposed to be updated. int getNumResultOperands(Operation* op) { if (!isa<LmhloOp>(op)) { return 0; } auto isWritable = [&](Value operand) -> bool { llvm::SmallVector<mlir::MemoryEffects::EffectInstance, 2> effects; MemoryEffectOpInterface interface = dyn_cast<MemoryEffectOpInterface>(op); // Suppose that operands of op without `MemoryEffectOpInterface` are // readonly. if (!interface) return false; interface.getEffectsOnValue(operand, effects); return llvm::any_of( effects, [](const mlir::MemoryEffects::EffectInstance& instance) { return mlir::isa<mlir::MemoryEffects::Write>(instance.getEffect()); }); }; return llvm::count_if(op->getOperands(), [&](Value v) { return isWritable(v); }); } // Returns data users of the value and its aliases (e.g. memref.cast). // Here non-data users means DimOp, DeallocOp and ShapeOfOp. SmallVector<Operation*, 4> getValueUsers(Value v) { SmallVector<Operation*, 4> users; SmallVector<Value, 4> worklist; worklist.push_back(v); while (!worklist.empty()) { Value curr = worklist.back(); worklist.pop_back(); for (Operation* user : curr.getUsers()) { // Skip non-data users if (isa<memref::DimOp, memref::DeallocOp, shape::ShapeOfOp>(user)) { continue; } // alias value if (isa<memref::CastOp>(user)) { worklist.push_back(user->getResult(0)); } else { users.push_back(user); } } } return users; } // Create a new fusion pattern from a single op. FusionPattern::FusionPattern(Operation* op) { op_list_.push_back(op); if (isRank2RowReduction(op)) { fusion_type_ = FusionType::kRowReduction; } else if (isRank2ColReduction(op)) { fusion_type_ = FusionType::kColReduction; } else if (mlir::lmhlo::isFusible(op)) { fusion_type_ = FusionType::kLoop; } else { fusion_type_ = FusionType::kNone; } dominant_op_ = op; calculateOperandsAndResults(); } // Create a new fusion pattern from the ops inside the lmhlo fusion op. FusionPattern::FusionPattern(lmhlo::FusionOp fusion_op) { for (Operation& op : fusion_op.region().getBlocks().front()) { op_list_.push_back(&op); } // Figure out fusion type and dominant op for the fusion pattern. for (Operation* op : op_list_) { if (isRank2RowReduction(op)) { fusion_type_ = FusionType::kRowReduction; dominant_op_ = op; } else if (isRank2ColReduction(op)) { if (fusion_type_ != FusionType::kRowReduction) { fusion_type_ = FusionType::kColReduction; dominant_op_ = op; } } else if (lmhlo::isFusible(op)) { // Ignore if already a kRowReduction or kColReduction, otherwise update // the fusion type to kLoop and dominant op to current op. This supposes // that the last op inside the block is a valid candidate dominant op if // the fusion pattern is a kLoop. if (fusion_type_ == FusionType::kNone || fusion_type_ == FusionType::kLoop) { fusion_type_ = FusionType::kLoop; dominant_op_ = op; } } else if (!isa<lmhlo::TerminatorOp>(op)) { // Not a supported fusionOp, early stop. fusion_type_ = FusionType::kNone; dominant_op_ = nullptr; break; } } if (isFusible()) calculateOperandsAndResults(); } // Create a new fusion pattern from a valid fusion op list. FusionPattern::FusionPattern(SmallVectorImpl<Operation*>& op_list) : op_list_(op_list.begin(), op_list.end()) { calculateOperandsAndResults(); } // Returns true if two fusion patterns can be merged into one bigger fusion // pattern. bool FusionPattern::isMergeable(FusionPattern& other) { if (!this->isFusible() || !other.isFusible()) return false; return true; } // Merges two fusion patterns and returns the merged pattern. The original // pattern remains unmodified. FusionPattern FusionPattern::merge(FusionPattern& other) { assert(isMergeable(other)); FusionOpList new_op_list = op_list_; new_op_list.insert(new_op_list.end(), other.getOpList().begin(), other.getOpList().end()); FusionPattern new_fusion_pattern{new_op_list}; FusionType newType = FusionType::kLoop; Operation* newDominant = getDominantOp(); // kRowReduction + (kRowReduction | kColReduction | kLoop) = kRowReduction // kColReduction + (kColReduction | kLoop) = kColReduction // kLoop + kLoop = kLoop if (getFusionType() == FusionType::kRowReduction || other.getFusionType() == FusionType::kRowReduction) { newType = FusionType::kRowReduction; if (getFusionType() != FusionType::kRowReduction) newDominant = other.getDominantOp(); } else if (getFusionType() == FusionType::kColReduction || other.getFusionType() == FusionType::kColReduction) { newType = FusionType::kColReduction; if (getFusionType() != FusionType::kColReduction) newDominant = other.getDominantOp(); } new_fusion_pattern.setDominantOp(newDominant); new_fusion_pattern.setFusionType(newType); return new_fusion_pattern; } // Merges two fusion patterns and returns the merged pattern. Replaces the // original pattern with new merged pattern. FusionPattern& FusionPattern::mergeInplace(FusionPattern& other) { *this = merge(other); return *this; } // Returns the effective size (e.g. not counting const ops) of the ops this // fusion pattern contains. int FusionPattern::effectiveSize() { return llvm::count_if( op_list_, [](Operation* op) { return !matchPattern(op, m_Constant()); }); } // Sorts the ops inside the fusion pattern according to the keys provided. void FusionPattern::sortFusionOpListBy(DenseMap<Operation*, int>& op_to_idx) { std::sort(op_list_.begin(), op_list_.end(), [&](Operation* lhs, Operation* rhs) { return op_to_idx[lhs] < op_to_idx[rhs]; }); } // Calculates the inputs and outputs of the fusion pattern. void FusionPattern::calculateOperandsAndResults() { DenseSet<Value> input_set; DenseSet<Value> result_set; DenseSet<Value> internal_result_set; DenseSet<Operation*> op_set(op_list_.begin(), op_list_.end()); DenseMap<Value, Operation*> last_writer; for (Operation* op : op_list_) { int num_input_operand = op->getNumOperands() - getNumResultOperands(op); for (Value v : op->getOperands().drop_front(num_input_operand)) { bool inserted = last_writer.try_emplace(v, op).second; (void)inserted; assert(inserted); bool has_external_user = false; for (Operation* user : getValueUsers(v)) { if (!op_set.contains(user)) { has_external_user = true; break; } } if (has_external_user) { results_.push_back(v); root_ops_.push_back(op); } else { internal_results_.push_back(v); } } } for (Operation* op : op_list_) { int num_input_operand = op->getNumOperands() - getNumResultOperands(op); for (Value value : op->getOperands().take_front(num_input_operand)) { if (last_writer.find(value) != last_writer.end()) { // skip if defining op is in the pattern continue; } input_set.insert(value); } } for (Value v : input_set) operands_.push_back(v); } // Supports using EquivalenceClasses for Value bool operator<(const ValueWrapper& lhs, const ValueWrapper& rhs) { auto* lhs_value = lhs.getValue().getAsOpaquePointer(); auto* rhs_value = rhs.getValue().getAsOpaquePointer(); return lhs_value < rhs_value; } // shape equality propagation based on the shape constrains of // elementwise ops. void ShapeConstraintAnalysis::PropagateEquality( const SmallVectorImpl<Operation*>& op_list) { bool converged = true; do { converged = true; auto update = [&](Value lhs, Value rhs, EquivalenceClasses<ValueWrapper>& impl) { if (!impl.isEquivalent(ValueWrapper(lhs), ValueWrapper(rhs))) { converged = false; impl.unionSets(ValueWrapper(lhs), ValueWrapper(rhs)); } }; for (Operation* op : op_list) { int num_operand = op->getNumOperands(); // Propagates same num_elements equality, and shape equality if (isElementWise(op)) { Value lhs = op->getOperand(0); for (Value rhs : op->getOperands().drop_front()) { update(lhs, rhs, same_num_elements_impl_); update(lhs, rhs, same_shape_impl_); } } // Propagates same num_elements equality, not shape equality if (isa<lmhlo::DynamicReshapeOp, lmhlo::ReshapeOp, lmhlo::TransposeOp>( op)) { Value input = op->getOperand(0); // The last operand is the output memref by design Value output = op->getOperand(num_operand - 1); update(input, output, same_num_elements_impl_); } } } while (!converged); } } // namespace lmhlo } // namespace mlir
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "mlir-hlo/Dialect/lhlo/transforms/fusion_utils.h" #include <algorithm> #include "mlir/Dialect/Shape/IR/Shape.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/Matchers.h" // This file implements some helper functions and classes used to do fusion // & code generation. namespace mlir { namespace lmhlo { // Returns true if the op is an elementwise unary lmhlo op. // TODO(disc): use fusibility interface // TODO(disc): Unify with disc_supported_list.h and Elementwise Trait bool isElementWiseUnary(Operation* op) { // clang-format off return isa< lmhlo::AbsOp, lmhlo::CeilOp, lmhlo::ConvertOp, lmhlo::CopyOp, lmhlo::CosOp, lmhlo::ExpOp, lmhlo::FloorOp, lmhlo::IsFiniteOp, lmhlo::LogOp, lmhlo::NegOp, lmhlo::NotOp, lmhlo::RsqrtOp, lmhlo::SignOp, lmhlo::SqrtOp, lmhlo::TanhOp >(op); // clang-format on } // Returns true if the op is an elementwise binary lmhlo op. // TODO(disc): use fusibility interface bool isElementWiseBinary(Operation* op) { // clang-format off return isa< lmhlo::AddOp, lmhlo::AndOp, lmhlo::CompareOp, lmhlo::DivOp, lmhlo::MaxOp, lmhlo::MinOp, lmhlo::MulOp, lmhlo::OrOp, lmhlo::PowOp, lmhlo::SubOp >(op); // clang-format on } // Returns true if the op is an elementwise lmhlo op. // TODO(disc): use fusibility interface bool isElementWise(Operation* op) { return isElementWiseUnary(op) || isElementWiseBinary(op); } // Returns true if this op is a rank-2 row reduction. bool isRank2RowReduction(Operation* op) { auto reduce_op = dyn_cast<lmhlo::ReduceOp>(op); if (!reduce_op || reduce_op.dimensions().getNumElements() != 1) return false; int rank = op->getOperand(0).getType().cast<MemRefType>().getRank(); auto dimensions = reduce_op.dimensions().getValues<int64_t>(); return ((*dimensions.begin() == 1) && (rank == 2)); } // Returns true if this op is a rank-2 column reduction. bool isRank2ColReduction(Operation* op) { auto reduce_op = dyn_cast<lmhlo::ReduceOp>(op); if (!reduce_op || reduce_op.dimensions().getNumElements() != 1) return false; int rank = op->getOperand(0).getType().cast<MemRefType>().getRank(); auto dimensions = reduce_op.dimensions().getValues<int64_t>(); return ((*dimensions.begin() == 0) && (rank == 2)); } // Returns true if the op is supported by the downstreaming fusion codegen // engine. bool isFusible(Operation* op) { // Only scalar const are supported by the fusion codegen engine a.t.m. if (dyn_cast<lmhlo::ConstOp>(op)) { MemRefType type = op->getOperand(0).getType().cast<MemRefType>(); return (type.getRank() == 0); } // All element ops are supported by the fusion codegen engine. if (isElementWise(op)) return true; // Only rank-2 tensor -> rank-1 tensor reduction are supported now. if (isRank2RowReduction(op) || isRank2ColReduction(op)) return true; // clang-format off return isa< lmhlo::BroadcastInDimOp, lmhlo::BroadcastOp, lmhlo::ConcatenateOp, lmhlo::DynamicBroadcastInDimOp, lmhlo::DynamicGatherOp, lmhlo::DynamicIotaOp, lmhlo::DynamicPadOp, lmhlo::DynamicReshapeOp, lmhlo::GatherOp, lmhlo::RealDynamicSliceOp, lmhlo::ReshapeOp, lmhlo::SelectOp, lmhlo::SliceOp, lmhlo::TransposeOp >(op); // clang-format on } // Returns the number of operands that are supposed to be written. // For some ops (e.g. lmhlo ops), some operands are the output memrefs // Thus these operands are supposed to be updated. int getNumResultOperands(Operation* op) { if (!isa<LmhloOp>(op)) { return 0; } auto isWritable = [&](Value operand) -> bool { llvm::SmallVector<mlir::MemoryEffects::EffectInstance, 2> effects; MemoryEffectOpInterface interface = dyn_cast<MemoryEffectOpInterface>(op); // Suppose that operands of op without `MemoryEffectOpInterface` are // readonly. if (!interface) return false; interface.getEffectsOnValue(operand, effects); return llvm::any_of( effects, [](const mlir::MemoryEffects::EffectInstance& instance) { return mlir::isa<mlir::MemoryEffects::Write>(instance.getEffect()); }); }; return llvm::count_if(op->getOperands(), [&](Value v) { return isWritable(v); }); } // Returns data users of the value and its aliases (e.g. memref.cast). // Here non-data users means DimOp, DeallocOp and ShapeOfOp. SmallVector<Operation*, 4> getValueUsers(Value v) { SmallVector<Operation*, 4> users; SmallVector<Value, 4> worklist; worklist.push_back(v); while (!worklist.empty()) { Value curr = worklist.back(); worklist.pop_back(); for (Operation* user : curr.getUsers()) { // Skip non-data users if (isa<memref::DimOp, memref::DeallocOp, shape::ShapeOfOp>(user)) { continue; } // alias value if (isa<memref::CastOp>(user)) { worklist.push_back(user->getResult(0)); } else { users.push_back(user); } } } return users; } // Create a new fusion pattern from a single op. FusionPattern::FusionPattern(Operation* op) { op_list_.push_back(op); if (isRank2RowReduction(op)) { fusion_type_ = FusionType::kRowReduction; } else if (isRank2ColReduction(op)) { fusion_type_ = FusionType::kColReduction; } else if (mlir::lmhlo::isFusible(op)) { fusion_type_ = FusionType::kLoop; } else { fusion_type_ = FusionType::kNone; } dominant_op_ = op; calculateOperandsAndResults(); } // Create a new fusion pattern from the ops inside the lmhlo fusion op. FusionPattern::FusionPattern(lmhlo::FusionOp fusion_op) { for (Operation& op : fusion_op.region().getBlocks().front()) { op_list_.push_back(&op); } // Figure out fusion type and dominant op for the fusion pattern. for (Operation* op : op_list_) { if (isRank2RowReduction(op)) { fusion_type_ = FusionType::kRowReduction; dominant_op_ = op; } else if (isRank2ColReduction(op)) { if (fusion_type_ != FusionType::kRowReduction) { fusion_type_ = FusionType::kColReduction; dominant_op_ = op; } } else if (lmhlo::isFusible(op)) { // Ignore if already a kRowReduction or kColReduction, otherwise update // the fusion type to kLoop and dominant op to current op. This supposes // that the last op inside the block is a valid candidate dominant op if // the fusion pattern is a kLoop. if (fusion_type_ == FusionType::kNone || fusion_type_ == FusionType::kLoop) { fusion_type_ = FusionType::kLoop; dominant_op_ = op; } } else if (!isa<lmhlo::TerminatorOp>(op)) { // Not a supported fusionOp, early stop. fusion_type_ = FusionType::kNone; dominant_op_ = nullptr; break; } } if (isFusible()) calculateOperandsAndResults(); } // Create a new fusion pattern from a valid fusion op list. FusionPattern::FusionPattern(SmallVectorImpl<Operation*>& op_list) : op_list_(op_list.begin(), op_list.end()) { calculateOperandsAndResults(); } // Returns true if two fusion patterns can be merged into one bigger fusion // pattern. bool FusionPattern::isMergeable(FusionPattern& other) { return this->isFusible() && other.isFusible(); } // Merges two fusion patterns and returns the merged pattern. The original // pattern remains unmodified. FusionPattern FusionPattern::merge(FusionPattern& other) { assert(isMergeable(other)); FusionOpList new_op_list = op_list_; new_op_list.insert(new_op_list.end(), other.getOpList().begin(), other.getOpList().end()); FusionPattern new_fusion_pattern{new_op_list}; FusionType newType = FusionType::kLoop; Operation* newDominant = getDominantOp(); // kRowReduction + (kRowReduction | kColReduction | kLoop) = kRowReduction // kColReduction + (kColReduction | kLoop) = kColReduction // kLoop + kLoop = kLoop if (getFusionType() == FusionType::kRowReduction || other.getFusionType() == FusionType::kRowReduction) { newType = FusionType::kRowReduction; if (getFusionType() != FusionType::kRowReduction) newDominant = other.getDominantOp(); } else if (getFusionType() == FusionType::kColReduction || other.getFusionType() == FusionType::kColReduction) { newType = FusionType::kColReduction; if (getFusionType() != FusionType::kColReduction) newDominant = other.getDominantOp(); } new_fusion_pattern.setDominantOp(newDominant); new_fusion_pattern.setFusionType(newType); return new_fusion_pattern; } // Merges two fusion patterns and returns the merged pattern. Replaces the // original pattern with new merged pattern. FusionPattern& FusionPattern::mergeInplace(FusionPattern& other) { *this = merge(other); return *this; } // Returns the effective size (e.g. not counting const ops) of the ops this // fusion pattern contains. int FusionPattern::effectiveSize() { return llvm::count_if( op_list_, [](Operation* op) { return !matchPattern(op, m_Constant()); }); } // Sorts the ops inside the fusion pattern according to the keys provided. void FusionPattern::sortFusionOpListBy(DenseMap<Operation*, int>& op_to_idx) { std::sort(op_list_.begin(), op_list_.end(), [&](Operation* lhs, Operation* rhs) { return op_to_idx[lhs] < op_to_idx[rhs]; }); } // Calculates the inputs and outputs of the fusion pattern. void FusionPattern::calculateOperandsAndResults() { DenseSet<Value> input_set; DenseSet<Value> result_set; DenseSet<Value> internal_result_set; DenseSet<Operation*> op_set(op_list_.begin(), op_list_.end()); DenseMap<Value, Operation*> last_writer; for (Operation* op : op_list_) { int num_input_operand = op->getNumOperands() - getNumResultOperands(op); for (Value v : op->getOperands().drop_front(num_input_operand)) { bool inserted = last_writer.try_emplace(v, op).second; (void)inserted; assert(inserted); bool has_external_user = false; for (Operation* user : getValueUsers(v)) { if (!op_set.contains(user)) { has_external_user = true; break; } } if (has_external_user) { results_.push_back(v); root_ops_.push_back(op); } else { internal_results_.push_back(v); } } } for (Operation* op : op_list_) { int num_input_operand = op->getNumOperands() - getNumResultOperands(op); for (Value value : op->getOperands().take_front(num_input_operand)) { if (last_writer.find(value) != last_writer.end()) { // skip if defining op is in the pattern continue; } input_set.insert(value); } } for (Value v : input_set) operands_.push_back(v); } // Supports using EquivalenceClasses for Value bool operator<(const ValueWrapper& lhs, const ValueWrapper& rhs) { auto* lhs_value = lhs.getValue().getAsOpaquePointer(); auto* rhs_value = rhs.getValue().getAsOpaquePointer(); return lhs_value < rhs_value; } // shape equality propagation based on the shape constrains of // elementwise ops. void ShapeConstraintAnalysis::PropagateEquality( const SmallVectorImpl<Operation*>& op_list) { bool converged = true; do { converged = true; auto update = [&](Value lhs, Value rhs, EquivalenceClasses<ValueWrapper>& impl) { if (!impl.isEquivalent(ValueWrapper(lhs), ValueWrapper(rhs))) { converged = false; impl.unionSets(ValueWrapper(lhs), ValueWrapper(rhs)); } }; for (Operation* op : op_list) { int num_operand = op->getNumOperands(); // Propagates same num_elements equality, and shape equality if (isElementWise(op)) { Value lhs = op->getOperand(0); for (Value rhs : op->getOperands().drop_front()) { update(lhs, rhs, same_num_elements_impl_); update(lhs, rhs, same_shape_impl_); } } // Propagates same num_elements equality, not shape equality if (isa<lmhlo::DynamicReshapeOp, lmhlo::ReshapeOp, lmhlo::TransposeOp>( op)) { Value input = op->getOperand(0); // The last operand is the output memref by design Value output = op->getOperand(num_operand - 1); update(input, output, same_num_elements_impl_); } } } while (!converged); } } // namespace lmhlo } // namespace mlir
Apply clang-tidy fixes for readability-simplify-boolean-expr in fusion_utils.cc (NFC)
Apply clang-tidy fixes for readability-simplify-boolean-expr in fusion_utils.cc (NFC) PiperOrigin-RevId: 418588961 Change-Id: I175b164ff3f6daecf00b4d0820a1de575d27e320
C++
apache-2.0
Intel-Corporation/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,yongtang/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer
c8533d8a93fa9eed822683616ba43fa734cffdb3
src/system/WatchableEventManagerSelect.cpp
src/system/WatchableEventManagerSelect.cpp
/* * * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2014-2017 Nest Labs, 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 * This file implements WatchableEventManager using select(). */ #include <platform/LockTracker.h> #include <support/CodeUtils.h> #include <system/SystemFaultInjection.h> #include <system/SystemLayer.h> #include <system/WatchableEventManager.h> #include <system/WatchableSocket.h> #include <errno.h> #define DEFAULT_MIN_SLEEP_PERIOD (60 * 60 * 24 * 30) // Month [sec] // Choose an approximation of PTHREAD_NULL if pthread.h doesn't define one. #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING && !defined(PTHREAD_NULL) #define PTHREAD_NULL 0 #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING && !defined(PTHREAD_NULL) #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ namespace chip { namespace Mdns { void GetMdnsTimeout(timeval & timeout); void HandleMdnsTimeout(); } // namespace Mdns } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ namespace chip { namespace System { CHIP_ERROR WatchableEventManager::Init(Layer & systemLayer) { RegisterPOSIXErrorFormatter(); mSystemLayer = &systemLayer; mMaxFd = -1; FD_ZERO(&mRequest.mReadSet); FD_ZERO(&mRequest.mWriteSet); FD_ZERO(&mRequest.mErrorSet); ReturnErrorOnFailure(mTimerList.Init()); #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING mHandleSelectThread = PTHREAD_NULL; #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING // Create an event to allow an arbitrary thread to wake the thread in the select loop. return mWakeEvent.Open(*this); } CHIP_ERROR WatchableEventManager::Shutdown() { Timer * timer; while ((timer = mTimerList.PopEarliest()) != nullptr) { timer->Clear(); timer->Release(); } mWakeEvent.Close(); mSystemLayer = nullptr; return CHIP_NO_ERROR; } void WatchableEventManager::Signal() { /* * Wake up the I/O thread by writing a single byte to the wake pipe. * * If this is being called from within an I/O event callback, then writing to the wake pipe can be skipped, * since the I/O thread is already awake. * * Furthermore, we don't care if this write fails as the only reasonably likely failure is that the pipe is full, in which * case the select calling thread is going to wake up anyway. */ #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING if (pthread_equal(mHandleSelectThread, pthread_self())) { return; } #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING // Send notification to wake up the select call. CHIP_ERROR status = mWakeEvent.Notify(); if (status != CHIP_NO_ERROR) { ChipLogError(chipSystemLayer, "System wake event notify failed: %" CHIP_ERROR_FORMAT, status.Format()); } } CHIP_ERROR WatchableEventManager::StartTimer(uint32_t delayMilliseconds, Timers::OnCompleteFunct onComplete, void * appState) { CHIP_SYSTEM_FAULT_INJECT(FaultInjection::kFault_TimeoutImmediate, delayMilliseconds = 0); CancelTimer(onComplete, appState); Timer * timer = Timer::New(*mSystemLayer, delayMilliseconds, onComplete, appState); VerifyOrReturnError(timer != nullptr, CHIP_ERROR_NO_MEMORY); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH dispatch_queue_t dispatchQueue = GetDispatchQueue(); if (dispatchQueue) { (void) mTimerList.Add(timer); dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatchQueue); if (timerSource == nullptr) { chipDie(); } timer->mTimerSource = timerSource; dispatch_source_set_timer(timerSource, dispatch_walltime(NULL, delayMilliseconds * NSEC_PER_MSEC), 0, 100 * NSEC_PER_MSEC); dispatch_source_set_event_handler(timerSource, ^{ dispatch_source_cancel(timerSource); dispatch_release(timerSource); this->HandleTimerComplete(timer); }); dispatch_resume(timerSource); return CHIP_NO_ERROR; } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH if (mTimerList.Add(timer) == timer) { // The new timer is the earliest, so the time until the next event has probably changed. Signal(); } return CHIP_NO_ERROR; } void WatchableEventManager::CancelTimer(Timers::OnCompleteFunct onComplete, void * appState) { Timer * timer = mTimerList.Remove(onComplete, appState); VerifyOrReturn(timer != nullptr); timer->Clear(); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH if (timer->mTimerSource != nullptr) { dispatch_source_cancel(timer->mTimerSource); dispatch_release(timer->mTimerSource); } #endif timer->Release(); Signal(); } CHIP_ERROR WatchableEventManager::ScheduleWork(Timers::OnCompleteFunct onComplete, void * appState) { CancelTimer(onComplete, appState); Timer * timer = Timer::New(*mSystemLayer, 0, onComplete, appState); VerifyOrReturnError(timer != nullptr, CHIP_ERROR_NO_MEMORY); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH dispatch_queue_t dispatchQueue = GetDispatchQueue(); if (dispatchQueue) { (void) mTimerList.Add(timer); dispatch_async(dispatchQueue, ^{ this->HandleTimerComplete(timer); }); return CHIP_NO_ERROR; } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH if (mTimerList.Add(timer) == timer) { // The new timer is the earliest, so the time until the next event has probably changed. Signal(); } return CHIP_NO_ERROR; } /** * Set the read, write or exception bit flags for the specified socket based on its status in * the corresponding file descriptor sets. * * @param[in] socket The file descriptor for which the bit flags are being set. * * @param[in] readfds A pointer to the set of readable file descriptors. * * @param[in] writefds A pointer to the set of writable file descriptors. * * @param[in] exceptfds A pointer to the set of file descriptors with errors. */ SocketEvents WatchableEventManager::SocketEventsFromFDs(int socket, const fd_set & readfds, const fd_set & writefds, const fd_set & exceptfds) { SocketEvents res; if (socket >= 0) { // POSIX does not define the fd_set parameter of FD_ISSET() as const, even though it isn't modified. if (FD_ISSET(socket, const_cast<fd_set *>(&readfds))) res.Set(SocketEventFlags::kRead); if (FD_ISSET(socket, const_cast<fd_set *>(&writefds))) res.Set(SocketEventFlags::kWrite); if (FD_ISSET(socket, const_cast<fd_set *>(&exceptfds))) res.Set(SocketEventFlags::kExcept); } return res; } bool WatchableEventManager::HasAnyRequest(int fd) { return FD_ISSET(fd, &mRequest.mReadSet) || FD_ISSET(fd, &mRequest.mWriteSet) || FD_ISSET(fd, &mRequest.mErrorSet); } CHIP_ERROR WatchableEventManager::SetRequest(int fd, fd_set * fds) { FD_SET(fd, fds); if (fd > mMaxFd) { mMaxFd = fd; } // Wake the thread calling select so that it starts selecting on the new socket. Signal(); return CHIP_NO_ERROR; } CHIP_ERROR WatchableEventManager::ClearRequest(int fd, fd_set * fds) { FD_CLR(fd, fds); if (fd == mMaxFd) { MaybeLowerMaxFd(); } // Wake the thread calling select so that it starts selecting on the new socket. Signal(); return CHIP_NO_ERROR; } void WatchableEventManager::ResetRequests(int fd) { FD_CLR(fd, &mRequest.mReadSet); FD_CLR(fd, &mRequest.mWriteSet); FD_CLR(fd, &mRequest.mErrorSet); if (fd == mMaxFd) { MaybeLowerMaxFd(); } } void WatchableEventManager::MaybeLowerMaxFd() { int fd; for (fd = mMaxFd; fd >= 0; --fd) { if (HasAnyRequest(fd)) { break; } } mMaxFd = fd; } void WatchableEventManager::PrepareEvents() { assertChipStackLockedByCurrentThread(); // Max out this duration and let CHIP set it appropriately. mNextTimeout.tv_sec = DEFAULT_MIN_SLEEP_PERIOD; mNextTimeout.tv_usec = 0; PrepareEventsWithTimeout(mNextTimeout); } void WatchableEventManager::PrepareEventsWithTimeout(struct timeval & nextTimeout) { const Clock::MonotonicMilliseconds currentTime = Clock::GetMonotonicMilliseconds(); Clock::MonotonicMilliseconds awakenTime = currentTime + TimevalToMilliseconds(nextTimeout); Timer * timer = mTimerList.Earliest(); if (timer && Clock::IsEarlier(timer->mAwakenTime, awakenTime)) { awakenTime = timer->mAwakenTime; } const Clock::MonotonicMilliseconds sleepTime = (awakenTime > currentTime) ? (awakenTime - currentTime) : 0; MillisecondsToTimeval(sleepTime, nextTimeout); #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ && !__MBED__ chip::Mdns::GetMdnsTimeout(nextTimeout); #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ mSelected = mRequest; } void WatchableEventManager::WaitForEvents() { mSelectResult = select(mMaxFd + 1, &mSelected.mReadSet, &mSelected.mWriteSet, &mSelected.mErrorSet, &mNextTimeout); } void WatchableEventManager::HandleEvents() { assertChipStackLockedByCurrentThread(); if (mSelectResult < 0) { ChipLogError(DeviceLayer, "select failed: %s\n", ErrorStr(System::MapErrorPOSIX(errno))); return; } VerifyOrDie(mSystemLayer != nullptr); #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING mHandleSelectThread = pthread_self(); #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING // Obtain the list of currently expired timers. Any new timers added by timer callback are NOT handled on this pass, // since that could result in infinite handling of new timers blocking any other progress. Timer::List expiredTimers(mTimerList.ExtractEarlier(1 + Clock::GetMonotonicMilliseconds())); Timer * timer = nullptr; while ((timer = expiredTimers.PopEarliest()) != nullptr) { timer->HandleComplete(); } for (WatchableSocket * watchable = mAttachedSockets; watchable != nullptr; watchable = watchable->mAttachedNext) { watchable->SetPendingIO( SocketEventsFromFDs(watchable->GetFD(), mSelected.mReadSet, mSelected.mWriteSet, mSelected.mErrorSet)); } for (WatchableSocket * watchable = mAttachedSockets; watchable != nullptr; watchable = watchable->mAttachedNext) { if (watchable->mPendingIO.HasAny()) { watchable->InvokeCallback(); } } #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ && !__MBED__ chip::Mdns::HandleMdnsTimeout(); #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING mHandleSelectThread = PTHREAD_NULL; #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING } #if CHIP_SYSTEM_CONFIG_USE_DISPATCH void WatchableEventManager::HandleTimerComplete(Timer * timer) { mTimerList.Remove(timer); timer->HandleComplete(); } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH } // namespace System } // namespace chip
/* * * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2014-2017 Nest Labs, 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 * This file implements WatchableEventManager using select(). */ #include <platform/LockTracker.h> #include <support/CodeUtils.h> #include <system/SystemFaultInjection.h> #include <system/SystemLayer.h> #include <system/WatchableEventManager.h> #include <system/WatchableSocket.h> #include <errno.h> #define DEFAULT_MIN_SLEEP_PERIOD (60 * 60 * 24 * 30) // Month [sec] // Choose an approximation of PTHREAD_NULL if pthread.h doesn't define one. #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING && !defined(PTHREAD_NULL) #define PTHREAD_NULL 0 #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING && !defined(PTHREAD_NULL) #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ namespace chip { namespace Mdns { void GetMdnsTimeout(timeval & timeout); void HandleMdnsTimeout(); } // namespace Mdns } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ namespace chip { namespace System { CHIP_ERROR WatchableEventManager::Init(Layer & systemLayer) { RegisterPOSIXErrorFormatter(); mSystemLayer = &systemLayer; mMaxFd = -1; FD_ZERO(&mRequest.mReadSet); FD_ZERO(&mRequest.mWriteSet); FD_ZERO(&mRequest.mErrorSet); ReturnErrorOnFailure(mTimerList.Init()); #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING mHandleSelectThread = PTHREAD_NULL; #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING // Create an event to allow an arbitrary thread to wake the thread in the select loop. return mWakeEvent.Open(*this); } CHIP_ERROR WatchableEventManager::Shutdown() { Timer * timer; while ((timer = mTimerList.PopEarliest()) != nullptr) { timer->Clear(); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH if (timer->mTimerSource != nullptr) { dispatch_source_cancel(timer->mTimerSource); dispatch_release(timer->mTimerSource); } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH timer->Release(); } mWakeEvent.Close(); mSystemLayer = nullptr; return CHIP_NO_ERROR; } void WatchableEventManager::Signal() { /* * Wake up the I/O thread by writing a single byte to the wake pipe. * * If this is being called from within an I/O event callback, then writing to the wake pipe can be skipped, * since the I/O thread is already awake. * * Furthermore, we don't care if this write fails as the only reasonably likely failure is that the pipe is full, in which * case the select calling thread is going to wake up anyway. */ #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING if (pthread_equal(mHandleSelectThread, pthread_self())) { return; } #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING // Send notification to wake up the select call. CHIP_ERROR status = mWakeEvent.Notify(); if (status != CHIP_NO_ERROR) { ChipLogError(chipSystemLayer, "System wake event notify failed: %" CHIP_ERROR_FORMAT, status.Format()); } } CHIP_ERROR WatchableEventManager::StartTimer(uint32_t delayMilliseconds, Timers::OnCompleteFunct onComplete, void * appState) { CHIP_SYSTEM_FAULT_INJECT(FaultInjection::kFault_TimeoutImmediate, delayMilliseconds = 0); CancelTimer(onComplete, appState); Timer * timer = Timer::New(*mSystemLayer, delayMilliseconds, onComplete, appState); VerifyOrReturnError(timer != nullptr, CHIP_ERROR_NO_MEMORY); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH dispatch_queue_t dispatchQueue = GetDispatchQueue(); if (dispatchQueue) { (void) mTimerList.Add(timer); dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatchQueue); if (timerSource == nullptr) { chipDie(); } timer->mTimerSource = timerSource; dispatch_source_set_timer(timerSource, dispatch_walltime(NULL, delayMilliseconds * NSEC_PER_MSEC), 0, 100 * NSEC_PER_MSEC); dispatch_source_set_event_handler(timerSource, ^{ dispatch_source_cancel(timerSource); dispatch_release(timerSource); this->HandleTimerComplete(timer); }); dispatch_resume(timerSource); return CHIP_NO_ERROR; } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH if (mTimerList.Add(timer) == timer) { // The new timer is the earliest, so the time until the next event has probably changed. Signal(); } return CHIP_NO_ERROR; } void WatchableEventManager::CancelTimer(Timers::OnCompleteFunct onComplete, void * appState) { Timer * timer = mTimerList.Remove(onComplete, appState); VerifyOrReturn(timer != nullptr); timer->Clear(); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH if (timer->mTimerSource != nullptr) { dispatch_source_cancel(timer->mTimerSource); dispatch_release(timer->mTimerSource); } #endif timer->Release(); Signal(); } CHIP_ERROR WatchableEventManager::ScheduleWork(Timers::OnCompleteFunct onComplete, void * appState) { CancelTimer(onComplete, appState); Timer * timer = Timer::New(*mSystemLayer, 0, onComplete, appState); VerifyOrReturnError(timer != nullptr, CHIP_ERROR_NO_MEMORY); #if CHIP_SYSTEM_CONFIG_USE_DISPATCH dispatch_queue_t dispatchQueue = GetDispatchQueue(); if (dispatchQueue) { (void) mTimerList.Add(timer); dispatch_async(dispatchQueue, ^{ this->HandleTimerComplete(timer); }); return CHIP_NO_ERROR; } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH if (mTimerList.Add(timer) == timer) { // The new timer is the earliest, so the time until the next event has probably changed. Signal(); } return CHIP_NO_ERROR; } /** * Set the read, write or exception bit flags for the specified socket based on its status in * the corresponding file descriptor sets. * * @param[in] socket The file descriptor for which the bit flags are being set. * * @param[in] readfds A pointer to the set of readable file descriptors. * * @param[in] writefds A pointer to the set of writable file descriptors. * * @param[in] exceptfds A pointer to the set of file descriptors with errors. */ SocketEvents WatchableEventManager::SocketEventsFromFDs(int socket, const fd_set & readfds, const fd_set & writefds, const fd_set & exceptfds) { SocketEvents res; if (socket >= 0) { // POSIX does not define the fd_set parameter of FD_ISSET() as const, even though it isn't modified. if (FD_ISSET(socket, const_cast<fd_set *>(&readfds))) res.Set(SocketEventFlags::kRead); if (FD_ISSET(socket, const_cast<fd_set *>(&writefds))) res.Set(SocketEventFlags::kWrite); if (FD_ISSET(socket, const_cast<fd_set *>(&exceptfds))) res.Set(SocketEventFlags::kExcept); } return res; } bool WatchableEventManager::HasAnyRequest(int fd) { return FD_ISSET(fd, &mRequest.mReadSet) || FD_ISSET(fd, &mRequest.mWriteSet) || FD_ISSET(fd, &mRequest.mErrorSet); } CHIP_ERROR WatchableEventManager::SetRequest(int fd, fd_set * fds) { FD_SET(fd, fds); if (fd > mMaxFd) { mMaxFd = fd; } // Wake the thread calling select so that it starts selecting on the new socket. Signal(); return CHIP_NO_ERROR; } CHIP_ERROR WatchableEventManager::ClearRequest(int fd, fd_set * fds) { FD_CLR(fd, fds); if (fd == mMaxFd) { MaybeLowerMaxFd(); } // Wake the thread calling select so that it starts selecting on the new socket. Signal(); return CHIP_NO_ERROR; } void WatchableEventManager::ResetRequests(int fd) { FD_CLR(fd, &mRequest.mReadSet); FD_CLR(fd, &mRequest.mWriteSet); FD_CLR(fd, &mRequest.mErrorSet); if (fd == mMaxFd) { MaybeLowerMaxFd(); } } void WatchableEventManager::MaybeLowerMaxFd() { int fd; for (fd = mMaxFd; fd >= 0; --fd) { if (HasAnyRequest(fd)) { break; } } mMaxFd = fd; } void WatchableEventManager::PrepareEvents() { assertChipStackLockedByCurrentThread(); // Max out this duration and let CHIP set it appropriately. mNextTimeout.tv_sec = DEFAULT_MIN_SLEEP_PERIOD; mNextTimeout.tv_usec = 0; PrepareEventsWithTimeout(mNextTimeout); } void WatchableEventManager::PrepareEventsWithTimeout(struct timeval & nextTimeout) { const Clock::MonotonicMilliseconds currentTime = Clock::GetMonotonicMilliseconds(); Clock::MonotonicMilliseconds awakenTime = currentTime + TimevalToMilliseconds(nextTimeout); Timer * timer = mTimerList.Earliest(); if (timer && Clock::IsEarlier(timer->mAwakenTime, awakenTime)) { awakenTime = timer->mAwakenTime; } const Clock::MonotonicMilliseconds sleepTime = (awakenTime > currentTime) ? (awakenTime - currentTime) : 0; MillisecondsToTimeval(sleepTime, nextTimeout); #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ && !__MBED__ chip::Mdns::GetMdnsTimeout(nextTimeout); #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ mSelected = mRequest; } void WatchableEventManager::WaitForEvents() { mSelectResult = select(mMaxFd + 1, &mSelected.mReadSet, &mSelected.mWriteSet, &mSelected.mErrorSet, &mNextTimeout); } void WatchableEventManager::HandleEvents() { assertChipStackLockedByCurrentThread(); if (mSelectResult < 0) { ChipLogError(DeviceLayer, "select failed: %s\n", ErrorStr(System::MapErrorPOSIX(errno))); return; } VerifyOrDie(mSystemLayer != nullptr); #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING mHandleSelectThread = pthread_self(); #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING // Obtain the list of currently expired timers. Any new timers added by timer callback are NOT handled on this pass, // since that could result in infinite handling of new timers blocking any other progress. Timer::List expiredTimers(mTimerList.ExtractEarlier(1 + Clock::GetMonotonicMilliseconds())); Timer * timer = nullptr; while ((timer = expiredTimers.PopEarliest()) != nullptr) { timer->HandleComplete(); } for (WatchableSocket * watchable = mAttachedSockets; watchable != nullptr; watchable = watchable->mAttachedNext) { watchable->SetPendingIO( SocketEventsFromFDs(watchable->GetFD(), mSelected.mReadSet, mSelected.mWriteSet, mSelected.mErrorSet)); } for (WatchableSocket * watchable = mAttachedSockets; watchable != nullptr; watchable = watchable->mAttachedNext) { if (watchable->mPendingIO.HasAny()) { watchable->InvokeCallback(); } } #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ && !__MBED__ chip::Mdns::HandleMdnsTimeout(); #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS && !__ZEPHYR__ #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING mHandleSelectThread = PTHREAD_NULL; #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING } #if CHIP_SYSTEM_CONFIG_USE_DISPATCH void WatchableEventManager::HandleTimerComplete(Timer * timer) { mTimerList.Remove(timer); timer->HandleComplete(); } #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH } // namespace System } // namespace chip
Fix Watchable Event Manager Select crash on shutdown (#8985)
Fix Watchable Event Manager Select crash on shutdown (#8985)
C++
apache-2.0
project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip
cd1c78f30089d0486811923405c6d29df02b1bed
chrome/browser/ui/views/file_manager_dialog_browsertest.cc
chrome/browser/ui/views/file_manager_dialog_browsertest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "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/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()); } IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, 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()); }
// 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/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()); }
Mark SelectFileAndSave test as FLAKY.
Mark SelectFileAndSave test as FLAKY. BUG=89733 TEST=None [email protected] Review URL: http://codereview.chromium.org/7465071 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@94306 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk,robclark/chromium,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,patrickm/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,dushu1203/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,keishi/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,anirudhSK/chromium,bright-sparks/chromium-spacewalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,robclark/chromium,rogerwang/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,M4sse/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,jaruba/chromium.src,keishi/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,robclark/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,robclark/chromium,axinging/chromium-crosswalk,robclark/chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,ondra-novak/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,hujiajie/pa-chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,keishi/chromium,Fireblend/chromium-crosswalk,ltilve/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,ondra-novak/chromium.src,robclark/chromium,littlstar/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,rogerwang/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,keishi/chromium,dednal/chromium.src,zcbenz/cefode-chromium,ltilve/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,anirudhSK/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,keishi/chromium,keishi/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,patrickm/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,Chilledheart/chromium,ltilve/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,dednal/chromium.src,robclark/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,rogerwang/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,littlstar/chromium.src,Chilledheart/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk
5b6a698a794bc01dd3acdb617881998fe55b6f48
copasi/UI/CQMathMatrixWidget.cpp
copasi/UI/CQMathMatrixWidget.cpp
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CQMathMatrixWidget.h" #include "copasi.h" #include "qtUtilities.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "model/CModel.h" #include "function/CExpression.h" //activate display of test of symbolic derivatives //#define _DERIV_TEST_ /** * Constructs a CQMathMatrixWidget which is a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent) : CopasiWidget(parent) { setupUi(this); CColorScaleSimple * tcs = new CColorScaleSimple(); mpArrayWidget1->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget1->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget2->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget2->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget3->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget3->setColorScalingAutomatic(false); #ifdef _DERIV_TEST_ connect(mpDerivButton, SIGNAL(clicked()), this, SLOT(slotDerivButtonPressed())); #else if (mpTabWidget->count()) mpTabWidget->removeTab(mpTabWidget->count() - 1); #endif } /* * Destroys the object and frees any allocated resources */ CQMathMatrixWidget::~CQMathMatrixWidget() {} void CQMathMatrixWidget::loadMatrices() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); mpArrayWidget1->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))); mpArrayWidget2->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"))); mpArrayWidget3->setArrayAnnotation(tmp); } void CQMathMatrixWidget::clearArrays() { mpArrayWidget1->setArrayAnnotation(NULL); mpArrayWidget2->setArrayAnnotation(NULL); mpArrayWidget3->setArrayAnnotation(NULL); } //************************************* bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { clearArrays(); return true; } bool CQMathMatrixWidget::leave() { return true; } bool CQMathMatrixWidget::enterProtected() { loadMatrices(); return true; } #include <qtablewidget.h> void CQMathMatrixWidget::slotDerivButtonPressed() { #ifdef _DERIV_TEST_ std::cout << "Deriv" << std::endl; CModel* pModel = &CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[0], pModel->getMetabolites()[0], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(pModel->getReactions()[0], pModel->getMetabolites()[0], true); //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); mpMML->setBaseFontPointSize(qApp->font().pointSize()); mpMML->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML->setContent(tmpstring.c_str()); mpMML2->setBaseFontPointSize(qApp->font().pointSize()); mpMML2->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML2->setContent(tmpstring2.c_str()); QTableWidget * pTable = new QTableWidget(pModel->getReactions().size(), pModel->getMetabolites().size()); pTable->show(); int i, imax = pModel->getMetabolites().size(); int j, jmax = pModel->getReactions().size(); for (i = 0; i < imax; ++i) for (j = 0; j < jmax; ++j) { //CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[j], // pModel->getMetabolites()[i], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(pModel->getReactions()[j], pModel->getMetabolites()[i], true); //evaluate CExpression * tmpExp = new CExpression("tmp expr", pModel); tmpExp->setRoot(tmpnode2); tmpExp->compile(); std::cout << tmpExp->calcValue() << std::endl; //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; //std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); QtMmlWidget* tmpmml = new QtMmlWidget(); tmpmml->setBaseFontPointSize(qApp->font().pointSize() - 2); tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); tmpmml->setContent(tmpstring2.c_str()); pTable->setCellWidget(j, i, tmpmml); //tmpmml = new QtMmlWidget(); //tmpmml->setBaseFontPointSize(qApp->font().pointSize()-2); //tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); //tmpmml->setContent(tmpstring.c_str()); //pTable->setCellWidget(i, 1, tmpmml); } pTable->resizeColumnsToContents(); pTable->resizeRowsToContents(); #endif }
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CQMathMatrixWidget.h" #include "copasi.h" #include "qtUtilities.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "model/CModel.h" #include "function/CExpression.h" //activate display of test of symbolic derivatives //#define _DERIV_TEST_ /** * Constructs a CQMathMatrixWidget which is a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent) : CopasiWidget(parent) { setupUi(this); CColorScaleSimple * tcs = new CColorScaleSimple(); mpArrayWidget1->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget1->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget2->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget2->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget3->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget3->setColorScalingAutomatic(false); #ifdef _DERIV_TEST_ connect(mpDerivButton, SIGNAL(clicked()), this, SLOT(slotDerivButtonPressed())); #else if (mpTabWidget->count()) mpTabWidget->removeTab(mpTabWidget->count() - 1); #endif } /* * Destroys the object and frees any allocated resources */ CQMathMatrixWidget::~CQMathMatrixWidget() {} void CQMathMatrixWidget::loadMatrices() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); mpArrayWidget1->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))); mpArrayWidget2->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"))); mpArrayWidget3->setArrayAnnotation(tmp); } void CQMathMatrixWidget::clearArrays() { mpArrayWidget1->setArrayAnnotation(NULL); mpArrayWidget2->setArrayAnnotation(NULL); mpArrayWidget3->setArrayAnnotation(NULL); } //************************************* bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { clearArrays(); return true; } bool CQMathMatrixWidget::leave() { return true; } bool CQMathMatrixWidget::enterProtected() { loadMatrices(); return true; } #include <qtablewidget.h> void CQMathMatrixWidget::slotDerivButtonPressed() { #ifdef _DERIV_TEST_ std::cout << "Deriv" << std::endl; CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); CEvaluationNode* tmpnode = pModel->prepareElasticity(&pModel->getReactions()[0], &pModel->getMetabolites()[0], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(&pModel->getReactions()[0], &pModel->getMetabolites()[0], true); //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); mpMML->setBaseFontPointSize(qApp->font().pointSize()); mpMML->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML->setContent(tmpstring.c_str()); mpMML2->setBaseFontPointSize(qApp->font().pointSize()); mpMML2->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML2->setContent(tmpstring2.c_str()); QTableWidget * pTable = new QTableWidget(pModel->getReactions().size(), pModel->getMetabolites().size()); pTable->show(); int i, imax = pModel->getMetabolites().size(); int j, jmax = pModel->getReactions().size(); for (i = 0; i < imax; ++i) for (j = 0; j < jmax; ++j) { //CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[j], // pModel->getMetabolites()[i], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(&pModel->getReactions()[j], &pModel->getMetabolites()[i], true); //evaluate CExpression * tmpExp = new CExpression("tmp expr", pModel); tmpExp->setRoot(tmpnode2); tmpExp->compile(); std::cout << tmpExp->calcValue() << std::endl; //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; //std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); QtMmlWidget* tmpmml = new QtMmlWidget(); tmpmml->setBaseFontPointSize(qApp->font().pointSize() - 2); tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); tmpmml->setContent(tmpstring2.c_str()); pTable->setCellWidget(j, i, tmpmml); //tmpmml = new QtMmlWidget(); //tmpmml->setBaseFontPointSize(qApp->font().pointSize()-2); //tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); //tmpmml->setContent(tmpstring.c_str()); //pTable->setCellWidget(i, 1, tmpmml); } pTable->resizeColumnsToContents(); pTable->resizeRowsToContents(); #endif }
make the test code for derivatives compile again
make the test code for derivatives compile again
C++
artistic-2.0
copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI
66210ad965efffddf5c9415e9f40a8492a6f55cb
getRegionAroundSampledColumn.cpp
getRegionAroundSampledColumn.cpp
// Samples a column and extracts a FASTA of the region surrounding // every column entry. #include <time.h> #include "hal.h" #include "sonLib.h" #include "bioioC.h" using namespace std; using namespace hal; static CLParserPtr initParser() { CLParserPtr optionsParser = hdf5CLParserInstance(true); optionsParser->addArgument("halFile", "target hal file"); optionsParser->addArgument("genome", "reference genome"); optionsParser->addOption("refSequence", "reference sequence name (by default, a random column will be sampled)", ""); optionsParser->addOption("refPos", "position (only valid if also using --sequence)", -1); optionsParser->addOption("width", "width of the region around the sampled column to extract, default = 500", 500); return optionsParser; } // Adapted from the hal2maf block-tree building code. // Could put this general version into the column iterator interface. // Builds a "gene"-tree node and labels it properly. static stTree *getTreeNode(SegmentIteratorConstPtr segIt) { // Make sure the segment is sliced to only 1 base. assert(segIt->getStartPosition() == segIt->getEndPosition()); stTree *ret = stTree_construct(); const Genome *genome = segIt->getGenome(); const Sequence *seq = genome->getSequenceBySite(segIt->getStartPosition()); // make the sequence name safe for newick parsers (':'->'_') string seqName = seq->getName(); hal_size_t i; while ((i = seqName.find(":")) != string::npos) { seqName[i] = '_'; } stringstream ss; ss << segIt->getGenome()->getName() << "." << seqName << "|" << segIt->getStartPosition() - seq->getStartPosition(); stTree_setLabel(ret, stString_copy(ss.str().c_str())); return ret; } // Recursive part of buildTree // tree parameter represents node corresponding to the genome with // bottom segment botIt static void buildTreeR(BottomSegmentIteratorConstPtr botIt, stTree *tree) { const Genome *genome = botIt->getGenome(); // attach a node and recurse for each of this segment's children // (and paralogous segments) for (hal_size_t i = 0; i < botIt->getNumChildren(); i++) { if (botIt->hasChild(i)) { const Genome *child = genome->getChild(i); TopSegmentIteratorConstPtr topIt = child->getTopSegmentIterator(); topIt->toChild(botIt, i); stTree *canonicalParalog = getTreeNode(topIt); stTree_setParent(canonicalParalog, tree); if (topIt->hasParseDown()) { BottomSegmentIteratorConstPtr childBotIt = child->getBottomSegmentIterator(); childBotIt->toParseDown(topIt); buildTreeR(childBotIt, canonicalParalog); } // Traverse the paralogous segments cycle and add those segments as well if (topIt->hasNextParalogy()) { topIt->toNextParalogy(); while(!topIt->isCanonicalParalog()) { stTree *paralog = getTreeNode(topIt); stTree_setParent(paralog, tree); if(topIt->hasParseDown()) { BottomSegmentIteratorConstPtr childBotIt = child->getBottomSegmentIterator(); childBotIt->toParseDown(topIt); buildTreeR(childBotIt, paralog); } topIt->toNextParalogy(); } } } } if (genome->getNumChildren() != 0 && stTree_getChildNumber(tree) == 0) { // Ancestral insertion. Ignore it. stTree_setParent(tree, NULL); stTree_destruct(tree); } } // Build a gene-tree from a column iterator. static stTree *buildTree(ColumnIteratorConstPtr colIt) { // Get any base from the column to begin building the tree const ColumnIterator::ColumnMap *colMap = colIt->getColumnMap(); ColumnIterator::ColumnMap::const_iterator colMapIt = colMap->begin(); const Sequence *sequence = NULL; hal_index_t index = NULL_INDEX; while (colMapIt != colMap->end()) { if (!colMapIt->second->empty()) { // Found a non-empty column map entry, just take the index and // sequence of the first base found sequence = colMapIt->first; index = colMapIt->second->at(0)->getArrayIndex(); break; } colMapIt++; } assert(sequence != NULL && index != NULL_INDEX); const Genome *genome = sequence->getGenome(); // Get the bottom segment that is the common ancestor of all entries TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); BottomSegmentIteratorConstPtr botIt; if (genome->getNumTopSegments() == 0) { // The reference is the root genome. botIt = genome->getBottomSegmentIterator(); botIt->toSite(index); } else { // Keep heading up the tree until we hit the root segment. topIt->toSite(index); while (topIt->hasParent()) { const Genome *parent = topIt->getGenome()->getParent(); botIt = parent->getBottomSegmentIterator(); botIt->toParent(topIt); if(parent->getParent() == NULL || !botIt->hasParseUp()) { // Reached root genome break; } topIt = parent->getTopSegmentIterator(); topIt->toParseUp(botIt); } } stTree *tree = NULL; if(topIt->hasParent() == false && topIt->getGenome() == genome && genome->getNumBottomSegments() == 0) { // Handle insertions in leaves. botIt doesn't point anywhere since // there are no bottom segments. tree = getTreeNode(topIt); } else { tree = getTreeNode(botIt); buildTreeR(botIt, tree); } assert(tree != NULL); return tree; } int main(int argc, char *argv[]) { CLParserPtr optParser = initParser(); string halPath, genomeName, refSequenceName; hal_index_t refPos = -1; hal_index_t width = 1000; try { optParser->parseOptions(argc, argv); halPath = optParser->getArgument<string>("halFile"); genomeName = optParser->getArgument<string>("genome"); refSequenceName = optParser->getOption<string>("refSequence"); refPos = optParser->getOption<hal_index_t>("refPos"); width = optParser->getOption<hal_index_t>("width"); } catch (exception &e) { cerr << e.what() << endl; optParser->printUsage(cerr); return 1; } st_randomSeed(time(NULL)); AlignmentConstPtr alignment = openHalAlignment(halPath, optParser); const Genome *genome = alignment->openGenome(genomeName); if (genome == NULL) { throw hal_exception("Genome " + genome->getName() + " not found in alignment"); } const Sequence *refSequence = NULL; if (refSequenceName.empty()) { // Sample a position from the entire genome. hal_size_t genomeLen = genome->getSequenceLength(); refPos = st_randomInt64(0, genomeLen - 1); refSequence = genome->getSequenceBySite(refPos); } else if (refPos == -1) { refSequence = genome->getSequence(refSequenceName); hal_size_t sequenceLen = refSequence->getSequenceLength(); refPos = st_randomInt64(0, sequenceLen - 1); refPos += refSequence->getStartPosition(); } else { refSequence = genome->getSequence(refSequenceName); refPos += refSequence->getStartPosition(); } char *outputSeq = (char *) malloc((width*2 + 2) * sizeof(char)); ColumnIteratorConstPtr colIt = genome->getColumnIterator(NULL, 0, refPos, NULL_INDEX, false, true); // Print out the tree underlying this column as a FASTA comment. cout << "#" << stTree_getNewickTreeString(buildTree(colIt)) << endl; const ColumnIterator::ColumnMap *cols = colIt->getColumnMap(); ColumnIterator::ColumnMap::const_iterator colMapIt; for (colMapIt = cols->begin(); colMapIt != cols->end(); colMapIt++) { if (colMapIt->second->empty()) { // The column map can contain empty entries. continue; } const Sequence *seq = colMapIt->first; hal_index_t seqStart = seq->getStartPosition(); hal_index_t seqEnd = seqStart + seq->getSequenceLength(); // exclusive. for (ColumnIterator::DNASet::const_iterator dnaIt = colMapIt->second->begin(); dnaIt != colMapIt->second->end(); dnaIt++) { DNAIteratorConstPtr dna = *dnaIt; hal_index_t midpoint = dna->getArrayIndex(); hal_index_t startPos = (dna->getReversed()) ? midpoint + width : midpoint - width; if (startPos < seqStart) { startPos = seqStart; } else if (startPos >= seqEnd) { startPos = seqEnd - 1; } hal_index_t size = width * 2 + 1; if ((hal_size_t) size >= seq->getSequenceLength()) { size = seqEnd - seqStart; } if (dna->getReversed() == false && startPos + size >= seqEnd) { size = seqEnd - startPos - 1; } else if(dna->getReversed() == true && startPos - size < seqStart) { size = startPos - seqStart - 1; } // Be paranoid about the iterator still being reversed properly after we reposition it. bool reversed = dna->getReversed(); dna->jumpTo(startPos); dna->setReversed(reversed); for(int64_t i = 0; i < (int64_t) size; i++, dna->toRight()) { outputSeq[i] = dna->getChar(); } outputSeq[size] = '\0'; // make the sequence name safe for newick parsers (':'->'_') string seqName = seq->getName(); hal_size_t i; while ((i = seqName.find(":")) != string::npos) { seqName[i] = '_'; } stringstream header; header << seq->getGenome()->getName() << "." << seqName << "|" << midpoint - seqStart; fastaWrite(outputSeq, (char *) header.str().c_str(), stdout); } } // Intentionally not dealing with memory leaks for this very // short-lived process. }
// Samples a column and extracts a FASTA of the region surrounding // every column entry. #include <time.h> #include "hal.h" #include "sonLib.h" #include "bioioC.h" using namespace std; using namespace hal; static CLParserPtr initParser() { CLParserPtr optionsParser = hdf5CLParserInstance(true); optionsParser->addArgument("halFile", "target hal file"); optionsParser->addArgument("genome", "reference genome"); optionsParser->addOption("refSequence", "reference sequence name (by default, a random column will be sampled)", ""); optionsParser->addOption("refPos", "position (only valid if also using --sequence)", -1); optionsParser->addOption("width", "width of the region around the sampled column to extract, default = 500", 500); return optionsParser; } // Adapted from the hal2maf block-tree building code. // Could put this general version into the column iterator interface. // Builds a "gene"-tree node and labels it properly. static stTree *getTreeNode(SegmentIteratorConstPtr segIt) { // Make sure the segment is sliced to only 1 base. assert(segIt->getStartPosition() == segIt->getEndPosition()); stTree *ret = stTree_construct(); const Genome *genome = segIt->getGenome(); const Sequence *seq = genome->getSequenceBySite(segIt->getStartPosition()); // make the sequence name safe for newick parsers (':'->'_') string seqName = seq->getName(); hal_size_t i; while ((i = seqName.find(":")) != string::npos) { seqName[i] = '_'; } stringstream ss; ss << segIt->getGenome()->getName() << "." << seqName << "|" << segIt->getStartPosition() - seq->getStartPosition(); stTree_setLabel(ret, stString_copy(ss.str().c_str())); return ret; } // Recursive part of buildTree // tree parameter represents node corresponding to the genome with // bottom segment botIt static void buildTreeR(BottomSegmentIteratorConstPtr botIt, stTree *tree) { const Genome *genome = botIt->getGenome(); // attach a node and recurse for each of this segment's children // (and paralogous segments) for (hal_size_t i = 0; i < botIt->getNumChildren(); i++) { if (botIt->hasChild(i)) { const Genome *child = genome->getChild(i); TopSegmentIteratorConstPtr topIt = child->getTopSegmentIterator(); topIt->toChild(botIt, i); stTree *canonicalParalog = getTreeNode(topIt); stTree_setParent(canonicalParalog, tree); if (topIt->hasParseDown()) { BottomSegmentIteratorConstPtr childBotIt = child->getBottomSegmentIterator(); childBotIt->toParseDown(topIt); buildTreeR(childBotIt, canonicalParalog); } // Traverse the paralogous segments cycle and add those segments as well if (topIt->hasNextParalogy()) { topIt->toNextParalogy(); while(!topIt->isCanonicalParalog()) { stTree *paralog = getTreeNode(topIt); stTree_setParent(paralog, tree); if(topIt->hasParseDown()) { BottomSegmentIteratorConstPtr childBotIt = child->getBottomSegmentIterator(); childBotIt->toParseDown(topIt); buildTreeR(childBotIt, paralog); } topIt->toNextParalogy(); } } } } if (genome->getNumChildren() != 0 && stTree_getChildNumber(tree) == 0) { // Ancestral insertion. Ignore it. stTree_setParent(tree, NULL); stTree_destruct(tree); } } // Build a gene-tree from a column iterator. static stTree *buildTree(ColumnIteratorConstPtr colIt) { // Get any base from the column to begin building the tree const ColumnIterator::ColumnMap *colMap = colIt->getColumnMap(); ColumnIterator::ColumnMap::const_iterator colMapIt = colMap->begin(); const Sequence *sequence = NULL; hal_index_t index = NULL_INDEX; while (colMapIt != colMap->end()) { if (!colMapIt->second->empty()) { // Found a non-empty column map entry, just take the index and // sequence of the first base found sequence = colMapIt->first; index = colMapIt->second->at(0)->getArrayIndex(); break; } colMapIt++; } assert(sequence != NULL && index != NULL_INDEX); const Genome *genome = sequence->getGenome(); // Get the bottom segment that is the common ancestor of all entries TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); BottomSegmentIteratorConstPtr botIt; if (genome->getNumTopSegments() == 0) { // The reference is the root genome. botIt = genome->getBottomSegmentIterator(); botIt->toSite(index); } else { // Keep heading up the tree until we hit the root segment. topIt->toSite(index); while (topIt->hasParent()) { const Genome *parent = topIt->getGenome()->getParent(); botIt = parent->getBottomSegmentIterator(); botIt->toParent(topIt); if(parent->getParent() == NULL || !botIt->hasParseUp()) { // Reached root genome break; } topIt = parent->getTopSegmentIterator(); topIt->toParseUp(botIt); } } stTree *tree = NULL; if(topIt->hasParent() == false && topIt->getGenome() == genome && genome->getNumBottomSegments() == 0) { // Handle insertions in leaves. botIt doesn't point anywhere since // there are no bottom segments. tree = getTreeNode(topIt); } else { tree = getTreeNode(botIt); buildTreeR(botIt, tree); } assert(tree != NULL); return tree; } int main(int argc, char *argv[]) { CLParserPtr optParser = initParser(); string halPath, genomeName, refSequenceName; hal_index_t refPos = -1; hal_index_t width = 1000; try { optParser->parseOptions(argc, argv); halPath = optParser->getArgument<string>("halFile"); genomeName = optParser->getArgument<string>("genome"); refSequenceName = optParser->getOption<string>("refSequence"); refPos = optParser->getOption<hal_index_t>("refPos"); width = optParser->getOption<hal_index_t>("width"); } catch (exception &e) { cerr << e.what() << endl; optParser->printUsage(cerr); return 1; } st_randomSeed(time(NULL)); AlignmentConstPtr alignment = openHalAlignment(halPath, optParser); const Genome *genome = alignment->openGenome(genomeName); if (genome == NULL) { throw hal_exception("Genome " + genomeName + " not found in alignment"); } const Sequence *refSequence = NULL; if (refSequenceName.empty()) { // Sample a position from the entire genome. hal_size_t genomeLen = genome->getSequenceLength(); refPos = st_randomInt64(0, genomeLen - 1); refSequence = genome->getSequenceBySite(refPos); } else if (refPos == -1) { refSequence = genome->getSequence(refSequenceName); hal_size_t sequenceLen = refSequence->getSequenceLength(); refPos = st_randomInt64(0, sequenceLen - 1); refPos += refSequence->getStartPosition(); } else { refSequence = genome->getSequence(refSequenceName); refPos += refSequence->getStartPosition(); } char *outputSeq = (char *) malloc((width*2 + 2) * sizeof(char)); ColumnIteratorConstPtr colIt = genome->getColumnIterator(NULL, 0, refPos, NULL_INDEX, false, true); // Print out the tree underlying this column as a FASTA comment. cout << "#" << stTree_getNewickTreeString(buildTree(colIt)) << endl; const ColumnIterator::ColumnMap *cols = colIt->getColumnMap(); ColumnIterator::ColumnMap::const_iterator colMapIt; for (colMapIt = cols->begin(); colMapIt != cols->end(); colMapIt++) { if (colMapIt->second->empty()) { // The column map can contain empty entries. continue; } const Sequence *seq = colMapIt->first; hal_index_t seqStart = seq->getStartPosition(); hal_index_t seqEnd = seqStart + seq->getSequenceLength(); // exclusive. for (ColumnIterator::DNASet::const_iterator dnaIt = colMapIt->second->begin(); dnaIt != colMapIt->second->end(); dnaIt++) { DNAIteratorConstPtr dna = *dnaIt; hal_index_t midpoint = dna->getArrayIndex(); hal_index_t startPos = (dna->getReversed()) ? midpoint + width : midpoint - width; if (startPos < seqStart) { startPos = seqStart; } else if (startPos >= seqEnd) { startPos = seqEnd - 1; } hal_index_t size = width * 2 + 1; if ((hal_size_t) size >= seq->getSequenceLength()) { size = seqEnd - seqStart; } if (dna->getReversed() == false && startPos + size >= seqEnd) { size = seqEnd - startPos - 1; } else if(dna->getReversed() == true && startPos - size < seqStart) { size = startPos - seqStart - 1; } // Be paranoid about the iterator still being reversed properly after we reposition it. bool reversed = dna->getReversed(); dna->jumpTo(startPos); dna->setReversed(reversed); for(int64_t i = 0; i < (int64_t) size; i++, dna->toRight()) { outputSeq[i] = dna->getChar(); } outputSeq[size] = '\0'; // make the sequence name safe for newick parsers (':'->'_') string seqName = seq->getName(); hal_size_t i; while ((i = seqName.find(":")) != string::npos) { seqName[i] = '_'; } stringstream header; header << seq->getGenome()->getName() << "." << seqName << "|" << midpoint - seqStart; fastaWrite(outputSeq, (char *) header.str().c_str(), stdout); } } // Intentionally not dealing with memory leaks for this very // short-lived process. }
Fix segfault on missing reference genome.
Fix segfault on missing reference genome.
C++
mit
joelarmstrong/treeBuildingEvaluation,joelarmstrong/treeBuildingEvaluation,joelarmstrong/treeBuildingEvaluation,joelarmstrong/treeBuildingEvaluation,joelarmstrong/treeBuildingEvaluation
7924abcf9b7ee0eb2c4284b2430afc14e213f3bb
chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc
chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h" #include <string> #include "ash/session_state_delegate.h" #include "ash/shell.h" #include "base/bind.h" #include "base/prefs/pref_change_registrar.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/sys_info.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/proxy_cros_settings_parser.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h" #include "chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h" #include "chrome/common/pref_names.h" #include "content/public/browser/user_metrics.h" #include "content/public/browser/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { namespace options { namespace { // List of settings that should be changeable by all users. const char* kNonOwnerSettings[] = { kSystemTimezone }; // Returns true if |pref| should be only available to the owner. bool IsSettingOwnerOnly(const std::string& pref) { const char** end = kNonOwnerSettings + arraysize(kNonOwnerSettings); return std::find(kNonOwnerSettings, end, pref) == end; } // Creates a user info dictionary to be stored in the |ListValue| that is // passed to Javascript for the |kAccountsPrefUsers| preference. base::DictionaryValue* CreateUserInfo(const std::string& username, const std::string& display_email, const std::string& display_name) { base::DictionaryValue* user_dict = new base::DictionaryValue; user_dict->SetString("username", username); user_dict->SetString("name", display_email); user_dict->SetString("email", display_name); bool is_owner = UserManager::Get()->GetOwnerEmail() == username; user_dict->SetBoolean("owner", is_owner); return user_dict; } // This function decorates the bare list of emails with some more information // needed by the UI to properly display the Accounts page. base::Value* CreateUsersWhitelist(const base::Value *pref_value) { const base::ListValue* list_value = static_cast<const base::ListValue*>(pref_value); base::ListValue* user_list = new base::ListValue(); UserManager* user_manager = UserManager::Get(); for (base::ListValue::const_iterator i = list_value->begin(); i != list_value->end(); ++i) { std::string email; if ((*i)->GetAsString(&email)) { // Translate email to the display email. std::string display_email = user_manager->GetUserDisplayEmail(email); // TODO(ivankr): fetch display name for existing users. user_list->Append(CreateUserInfo(email, display_email, std::string())); } } return user_list; } const char kSelectNetworkMessage[] = "selectNetwork"; } // namespace CoreChromeOSOptionsHandler::CoreChromeOSOptionsHandler() { } CoreChromeOSOptionsHandler::~CoreChromeOSOptionsHandler() { } void CoreChromeOSOptionsHandler::RegisterMessages() { CoreOptionsHandler::RegisterMessages(); web_ui()->RegisterMessageCallback( kSelectNetworkMessage, base::Bind(&CoreChromeOSOptionsHandler::SelectNetworkCallback, base::Unretained(this))); } void CoreChromeOSOptionsHandler::InitializeHandler() { // This function is both called on the initial page load and on each reload. // For the latter case, forget the last selected network. proxy_config_service_.SetCurrentNetwork(std::string()); // And clear the cached configuration. proxy_config_service_.UpdateFromPrefs(); CoreOptionsHandler::InitializeHandler(); PrefService* profile_prefs = NULL; Profile* profile = Profile::FromWebUI(web_ui()); if (!ProfileHelper::IsSigninProfile(profile)) { profile_prefs = profile->GetPrefs(); ObservePref(prefs::kOpenNetworkConfiguration); } ObservePref(prefs::kProxy); ObservePref(prefs::kDeviceOpenNetworkConfiguration); proxy_config_service_.SetPrefs(profile_prefs, g_browser_process->local_state()); } base::Value* CoreChromeOSOptionsHandler::FetchPref( const std::string& pref_name) { if (proxy_cros_settings_parser::IsProxyPref(pref_name)) { base::Value *value = NULL; proxy_cros_settings_parser::GetProxyPrefValue( proxy_config_service_, pref_name, &value); if (!value) return base::Value::CreateNullValue(); return value; } if (!CrosSettings::IsCrosSettings(pref_name)) { std::string controlling_pref = pref_name == prefs::kUseSharedProxies ? prefs::kProxy : std::string(); return CreateValueForPref(pref_name, controlling_pref); } const base::Value* pref_value = CrosSettings::Get()->GetPref(pref_name); if (!pref_value) return base::Value::CreateNullValue(); // Decorate pref value as CoreOptionsHandler::CreateValueForPref() does. // TODO(estade): seems that this should replicate CreateValueForPref less. base::DictionaryValue* dict = new base::DictionaryValue; if (pref_name == kAccountsPrefUsers) dict->Set("value", CreateUsersWhitelist(pref_value)); else dict->Set("value", pref_value->DeepCopy()); policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); if (connector->IsEnterpriseManaged()) { dict->SetBoolean("disabled", true); dict->SetString("controlledBy", "policy"); } else { bool controlled_by_owner = IsSettingOwnerOnly(pref_name) && !ProfileHelper::IsOwnerProfile(Profile::FromWebUI(web_ui())); dict->SetBoolean("disabled", controlled_by_owner); if (controlled_by_owner) dict->SetString("controlledBy", "owner"); } return dict; } void CoreChromeOSOptionsHandler::ObservePref(const std::string& pref_name) { if (proxy_cros_settings_parser::IsProxyPref(pref_name)) { // We observe those all the time. return; } if (!CrosSettings::IsCrosSettings(pref_name)) return ::options::CoreOptionsHandler::ObservePref(pref_name); linked_ptr<CrosSettings::ObserverSubscription> subscription( CrosSettings::Get()->AddSettingsObserver( pref_name.c_str(), base::Bind(&CoreChromeOSOptionsHandler::NotifySettingsChanged, base::Unretained(this), pref_name)).release()); pref_subscription_map_.insert(make_pair(pref_name, subscription)); } void CoreChromeOSOptionsHandler::SetPref(const std::string& pref_name, const base::Value* value, const std::string& metric) { if (proxy_cros_settings_parser::IsProxyPref(pref_name)) { proxy_cros_settings_parser::SetProxyPrefValue( pref_name, value, &proxy_config_service_); base::StringValue proxy_type(pref_name); web_ui()->CallJavascriptFunction( "options.internet.DetailsInternetPage.updateProxySettings", proxy_type); ProcessUserMetric(value, metric); return; } if (!CrosSettings::IsCrosSettings(pref_name)) return ::options::CoreOptionsHandler::SetPref(pref_name, value, metric); CrosSettings::Get()->Set(pref_name, *value); ProcessUserMetric(value, metric); } void CoreChromeOSOptionsHandler::StopObservingPref(const std::string& path) { if (proxy_cros_settings_parser::IsProxyPref(path)) return; // We unregister those in the destructor. // Unregister this instance from observing prefs of chrome os settings. if (CrosSettings::IsCrosSettings(path)) pref_subscription_map_.erase(path); else // Call base class to handle regular preferences. ::options::CoreOptionsHandler::StopObservingPref(path); } base::Value* CoreChromeOSOptionsHandler::CreateValueForPref( const std::string& pref_name, const std::string& controlling_pref_name) { // The screen lock setting is shared if multiple users are logged in and at // least one has chosen to require passwords. if (pref_name == prefs::kEnableAutoScreenLock && UserManager::Get()->GetLoggedInUsers().size() > 1 && controlling_pref_name.empty()) { PrefService* user_prefs = Profile::FromWebUI(web_ui())->GetPrefs(); const PrefService::Preference* pref = user_prefs->FindPreference(prefs::kEnableAutoScreenLock); ash::SessionStateDelegate* delegate = ash::Shell::GetInstance()->session_state_delegate(); if (pref && pref->IsUserModifiable() && delegate->ShouldLockScreenBeforeSuspending()) { bool screen_lock = false; bool success = pref->GetValue()->GetAsBoolean(&screen_lock); DCHECK(success); if (!screen_lock) { // Screen lock is enabled for the session, but not in the user's // preferences. Show the user's value in the checkbox, but indicate // that the password requirement is enabled by some other user. base::DictionaryValue* dict = new base::DictionaryValue; dict->Set("value", pref->GetValue()->DeepCopy()); dict->SetString("controlledBy", "shared"); return dict; } } } return CoreOptionsHandler::CreateValueForPref(pref_name, controlling_pref_name); } void CoreChromeOSOptionsHandler::GetLocalizedValues( base::DictionaryValue* localized_strings) { DCHECK(localized_strings); CoreOptionsHandler::GetLocalizedValues(localized_strings); Profile* profile = Profile::FromWebUI(web_ui()); AddAccountUITweaksLocalizedValues(localized_strings, profile); UserManager* user_manager = UserManager::Get(); // Check at load time whether this is a secondary user in a multi-profile // session. User* user = user_manager->GetUserByProfile(profile); if (user && user->email() != user_manager->GetPrimaryUser()->email()) { const std::string& primary_email = user_manager->GetPrimaryUser()->email(); // Set secondaryUser to show the shared icon by the network section header. localized_strings->SetBoolean("secondaryUser", true); localized_strings->SetString("secondaryUserBannerText", l10n_util::GetStringFUTF16( IDS_OPTIONS_SETTINGS_SECONDARY_USER_BANNER, base::ASCIIToUTF16(primary_email))); localized_strings->SetString("controlledSettingShared", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTING_SHARED, base::ASCIIToUTF16(primary_email))); localized_strings->SetString("controlledSettingsShared", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTINGS_SHARED, base::ASCIIToUTF16(primary_email))); } else { localized_strings->SetBoolean("secondaryUser", false); localized_strings->SetString("secondaryUserBannerText", base::string16()); localized_strings->SetString("controlledSettingShared", base::string16()); localized_strings->SetString("controlledSettingsShared", base::string16()); } // Screen lock icon can show up as primary or secondary user. localized_strings->SetString("screenLockShared", l10n_util::GetStringUTF16( IDS_OPTIONS_CONTROLLED_SETTING_SHARED_SCREEN_LOCK)); policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); if (connector->IsEnterpriseManaged()) { // Managed machines have no "owner". localized_strings->SetString("controlledSettingOwner", base::string16()); } else { localized_strings->SetString("controlledSettingOwner", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTING_OWNER, base::ASCIIToUTF16(user_manager->GetOwnerEmail()))); } } void CoreChromeOSOptionsHandler::SelectNetworkCallback( const base::ListValue* args) { std::string service_path; if (args->GetSize() != 1 || !args->GetString(0, &service_path)) { NOTREACHED(); return; } proxy_config_service_.SetCurrentNetwork(service_path); NotifyProxyPrefsChanged(); } void CoreChromeOSOptionsHandler::OnPreferenceChanged( PrefService* service, const std::string& pref_name) { // Redetermine the current proxy settings and notify the UI if any of these // preferences change. if (pref_name == prefs::kOpenNetworkConfiguration || pref_name == prefs::kDeviceOpenNetworkConfiguration || pref_name == prefs::kProxy) { NotifyProxyPrefsChanged(); return; } if (pref_name == prefs::kUseSharedProxies) { // kProxy controls kUseSharedProxies and decides if it's managed by // policy/extension. NotifyPrefChanged(prefs::kUseSharedProxies, prefs::kProxy); return; } ::options::CoreOptionsHandler::OnPreferenceChanged(service, pref_name); } void CoreChromeOSOptionsHandler::NotifySettingsChanged( const std::string& setting_name) { DCHECK(CrosSettings::Get()->IsCrosSettings(setting_name)); scoped_ptr<base::Value> value(FetchPref(setting_name)); if (!value.get()) NOTREACHED(); DispatchPrefChangeNotification(setting_name, value.Pass()); } void CoreChromeOSOptionsHandler::NotifyProxyPrefsChanged() { proxy_config_service_.UpdateFromPrefs(); for (size_t i = 0; i < kProxySettingsCount; ++i) { base::Value* value = NULL; proxy_cros_settings_parser::GetProxyPrefValue( proxy_config_service_, kProxySettings[i], &value); DCHECK(value); scoped_ptr<base::Value> ptr(value); DispatchPrefChangeNotification(kProxySettings[i], ptr.Pass()); } } } // namespace options } // namespace chromeos
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h" #include <string> #include "ash/session_state_delegate.h" #include "ash/shell.h" #include "base/bind.h" #include "base/prefs/pref_change_registrar.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/sys_info.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/proxy_cros_settings_parser.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h" #include "chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h" #include "chrome/common/pref_names.h" #include "content/public/browser/user_metrics.h" #include "content/public/browser/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { namespace options { namespace { // List of settings that should be changeable by all users. const char* kNonPrivilegedSettings[] = { kSystemTimezone }; // Returns true if |pref| can be controlled (e.g. by policy or owner). bool IsSettingPrivileged(const std::string& pref) { const char** end = kNonPrivilegedSettings + arraysize(kNonPrivilegedSettings); return std::find(kNonPrivilegedSettings, end, pref) == end; } // Creates a user info dictionary to be stored in the |ListValue| that is // passed to Javascript for the |kAccountsPrefUsers| preference. base::DictionaryValue* CreateUserInfo(const std::string& username, const std::string& display_email, const std::string& display_name) { base::DictionaryValue* user_dict = new base::DictionaryValue; user_dict->SetString("username", username); user_dict->SetString("name", display_email); user_dict->SetString("email", display_name); bool is_owner = UserManager::Get()->GetOwnerEmail() == username; user_dict->SetBoolean("owner", is_owner); return user_dict; } // This function decorates the bare list of emails with some more information // needed by the UI to properly display the Accounts page. base::Value* CreateUsersWhitelist(const base::Value *pref_value) { const base::ListValue* list_value = static_cast<const base::ListValue*>(pref_value); base::ListValue* user_list = new base::ListValue(); UserManager* user_manager = UserManager::Get(); for (base::ListValue::const_iterator i = list_value->begin(); i != list_value->end(); ++i) { std::string email; if ((*i)->GetAsString(&email)) { // Translate email to the display email. std::string display_email = user_manager->GetUserDisplayEmail(email); // TODO(ivankr): fetch display name for existing users. user_list->Append(CreateUserInfo(email, display_email, std::string())); } } return user_list; } const char kSelectNetworkMessage[] = "selectNetwork"; } // namespace CoreChromeOSOptionsHandler::CoreChromeOSOptionsHandler() { } CoreChromeOSOptionsHandler::~CoreChromeOSOptionsHandler() { } void CoreChromeOSOptionsHandler::RegisterMessages() { CoreOptionsHandler::RegisterMessages(); web_ui()->RegisterMessageCallback( kSelectNetworkMessage, base::Bind(&CoreChromeOSOptionsHandler::SelectNetworkCallback, base::Unretained(this))); } void CoreChromeOSOptionsHandler::InitializeHandler() { // This function is both called on the initial page load and on each reload. // For the latter case, forget the last selected network. proxy_config_service_.SetCurrentNetwork(std::string()); // And clear the cached configuration. proxy_config_service_.UpdateFromPrefs(); CoreOptionsHandler::InitializeHandler(); PrefService* profile_prefs = NULL; Profile* profile = Profile::FromWebUI(web_ui()); if (!ProfileHelper::IsSigninProfile(profile)) { profile_prefs = profile->GetPrefs(); ObservePref(prefs::kOpenNetworkConfiguration); } ObservePref(prefs::kProxy); ObservePref(prefs::kDeviceOpenNetworkConfiguration); proxy_config_service_.SetPrefs(profile_prefs, g_browser_process->local_state()); } base::Value* CoreChromeOSOptionsHandler::FetchPref( const std::string& pref_name) { if (proxy_cros_settings_parser::IsProxyPref(pref_name)) { base::Value *value = NULL; proxy_cros_settings_parser::GetProxyPrefValue( proxy_config_service_, pref_name, &value); if (!value) return base::Value::CreateNullValue(); return value; } if (!CrosSettings::IsCrosSettings(pref_name)) { std::string controlling_pref = pref_name == prefs::kUseSharedProxies ? prefs::kProxy : std::string(); return CreateValueForPref(pref_name, controlling_pref); } const base::Value* pref_value = CrosSettings::Get()->GetPref(pref_name); if (!pref_value) return base::Value::CreateNullValue(); // Decorate pref value as CoreOptionsHandler::CreateValueForPref() does. // TODO(estade): seems that this should replicate CreateValueForPref less. base::DictionaryValue* dict = new base::DictionaryValue; if (pref_name == kAccountsPrefUsers) dict->Set("value", CreateUsersWhitelist(pref_value)); else dict->Set("value", pref_value->DeepCopy()); std::string controlled_by; if (IsSettingPrivileged(pref_name)) { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); if (connector->IsEnterpriseManaged()) controlled_by = "policy"; else if (!ProfileHelper::IsOwnerProfile(Profile::FromWebUI(web_ui()))) controlled_by = "owner"; } dict->SetBoolean("disabled", !controlled_by.empty()); if (!controlled_by.empty()) dict->SetString("controlledBy", controlled_by); return dict; } void CoreChromeOSOptionsHandler::ObservePref(const std::string& pref_name) { if (proxy_cros_settings_parser::IsProxyPref(pref_name)) { // We observe those all the time. return; } if (!CrosSettings::IsCrosSettings(pref_name)) return ::options::CoreOptionsHandler::ObservePref(pref_name); linked_ptr<CrosSettings::ObserverSubscription> subscription( CrosSettings::Get()->AddSettingsObserver( pref_name.c_str(), base::Bind(&CoreChromeOSOptionsHandler::NotifySettingsChanged, base::Unretained(this), pref_name)).release()); pref_subscription_map_.insert(make_pair(pref_name, subscription)); } void CoreChromeOSOptionsHandler::SetPref(const std::string& pref_name, const base::Value* value, const std::string& metric) { if (proxy_cros_settings_parser::IsProxyPref(pref_name)) { proxy_cros_settings_parser::SetProxyPrefValue( pref_name, value, &proxy_config_service_); base::StringValue proxy_type(pref_name); web_ui()->CallJavascriptFunction( "options.internet.DetailsInternetPage.updateProxySettings", proxy_type); ProcessUserMetric(value, metric); return; } if (!CrosSettings::IsCrosSettings(pref_name)) return ::options::CoreOptionsHandler::SetPref(pref_name, value, metric); CrosSettings::Get()->Set(pref_name, *value); ProcessUserMetric(value, metric); } void CoreChromeOSOptionsHandler::StopObservingPref(const std::string& path) { if (proxy_cros_settings_parser::IsProxyPref(path)) return; // We unregister those in the destructor. // Unregister this instance from observing prefs of chrome os settings. if (CrosSettings::IsCrosSettings(path)) pref_subscription_map_.erase(path); else // Call base class to handle regular preferences. ::options::CoreOptionsHandler::StopObservingPref(path); } base::Value* CoreChromeOSOptionsHandler::CreateValueForPref( const std::string& pref_name, const std::string& controlling_pref_name) { // The screen lock setting is shared if multiple users are logged in and at // least one has chosen to require passwords. if (pref_name == prefs::kEnableAutoScreenLock && UserManager::Get()->GetLoggedInUsers().size() > 1 && controlling_pref_name.empty()) { PrefService* user_prefs = Profile::FromWebUI(web_ui())->GetPrefs(); const PrefService::Preference* pref = user_prefs->FindPreference(prefs::kEnableAutoScreenLock); ash::SessionStateDelegate* delegate = ash::Shell::GetInstance()->session_state_delegate(); if (pref && pref->IsUserModifiable() && delegate->ShouldLockScreenBeforeSuspending()) { bool screen_lock = false; bool success = pref->GetValue()->GetAsBoolean(&screen_lock); DCHECK(success); if (!screen_lock) { // Screen lock is enabled for the session, but not in the user's // preferences. Show the user's value in the checkbox, but indicate // that the password requirement is enabled by some other user. base::DictionaryValue* dict = new base::DictionaryValue; dict->Set("value", pref->GetValue()->DeepCopy()); dict->SetString("controlledBy", "shared"); return dict; } } } return CoreOptionsHandler::CreateValueForPref(pref_name, controlling_pref_name); } void CoreChromeOSOptionsHandler::GetLocalizedValues( base::DictionaryValue* localized_strings) { DCHECK(localized_strings); CoreOptionsHandler::GetLocalizedValues(localized_strings); Profile* profile = Profile::FromWebUI(web_ui()); AddAccountUITweaksLocalizedValues(localized_strings, profile); UserManager* user_manager = UserManager::Get(); // Check at load time whether this is a secondary user in a multi-profile // session. User* user = user_manager->GetUserByProfile(profile); if (user && user->email() != user_manager->GetPrimaryUser()->email()) { const std::string& primary_email = user_manager->GetPrimaryUser()->email(); // Set secondaryUser to show the shared icon by the network section header. localized_strings->SetBoolean("secondaryUser", true); localized_strings->SetString("secondaryUserBannerText", l10n_util::GetStringFUTF16( IDS_OPTIONS_SETTINGS_SECONDARY_USER_BANNER, base::ASCIIToUTF16(primary_email))); localized_strings->SetString("controlledSettingShared", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTING_SHARED, base::ASCIIToUTF16(primary_email))); localized_strings->SetString("controlledSettingsShared", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTINGS_SHARED, base::ASCIIToUTF16(primary_email))); } else { localized_strings->SetBoolean("secondaryUser", false); localized_strings->SetString("secondaryUserBannerText", base::string16()); localized_strings->SetString("controlledSettingShared", base::string16()); localized_strings->SetString("controlledSettingsShared", base::string16()); } // Screen lock icon can show up as primary or secondary user. localized_strings->SetString("screenLockShared", l10n_util::GetStringUTF16( IDS_OPTIONS_CONTROLLED_SETTING_SHARED_SCREEN_LOCK)); policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); if (connector->IsEnterpriseManaged()) { // Managed machines have no "owner". localized_strings->SetString("controlledSettingOwner", base::string16()); } else { localized_strings->SetString("controlledSettingOwner", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTING_OWNER, base::ASCIIToUTF16(user_manager->GetOwnerEmail()))); } } void CoreChromeOSOptionsHandler::SelectNetworkCallback( const base::ListValue* args) { std::string service_path; if (args->GetSize() != 1 || !args->GetString(0, &service_path)) { NOTREACHED(); return; } proxy_config_service_.SetCurrentNetwork(service_path); NotifyProxyPrefsChanged(); } void CoreChromeOSOptionsHandler::OnPreferenceChanged( PrefService* service, const std::string& pref_name) { // Redetermine the current proxy settings and notify the UI if any of these // preferences change. if (pref_name == prefs::kOpenNetworkConfiguration || pref_name == prefs::kDeviceOpenNetworkConfiguration || pref_name == prefs::kProxy) { NotifyProxyPrefsChanged(); return; } if (pref_name == prefs::kUseSharedProxies) { // kProxy controls kUseSharedProxies and decides if it's managed by // policy/extension. NotifyPrefChanged(prefs::kUseSharedProxies, prefs::kProxy); return; } ::options::CoreOptionsHandler::OnPreferenceChanged(service, pref_name); } void CoreChromeOSOptionsHandler::NotifySettingsChanged( const std::string& setting_name) { DCHECK(CrosSettings::Get()->IsCrosSettings(setting_name)); scoped_ptr<base::Value> value(FetchPref(setting_name)); if (!value.get()) NOTREACHED(); DispatchPrefChangeNotification(setting_name, value.Pass()); } void CoreChromeOSOptionsHandler::NotifyProxyPrefsChanged() { proxy_config_service_.UpdateFromPrefs(); for (size_t i = 0; i < kProxySettingsCount; ++i) { base::Value* value = NULL; proxy_cros_settings_parser::GetProxyPrefValue( proxy_config_service_, kProxySettings[i], &value); DCHECK(value); scoped_ptr<base::Value> ptr(value); DispatchPrefChangeNotification(kProxySettings[i], ptr.Pass()); } } } // namespace options } // namespace chromeos
Make timezone editable
Make timezone editable Fixes regression where timezone setting is disabled on enterprise devices. BUG=347071 [email protected] NOTRY=true Review URL: https://codereview.chromium.org/181813004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@253661 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
markYoungH/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,anirudhSK/chromium,ltilve/chromium,dednal/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,littlstar/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Chilledheart/chromium,patrickm/chromium.src,anirudhSK/chromium,jaruba/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,littlstar/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Chilledheart/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,patrickm/chromium.src,dednal/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,jaruba/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,dushu1203/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,patrickm/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,Jonekee/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src
f95477e944d5c8feeed5ebe13fcdadc2f096ef9f
src/socket_tls.cc
src/socket_tls.cc
// // tls_socket.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstring> #include <memory> #include <sstream> #include <string> #include <vector> #include "log.h" #include "io.h" #include "socket.h" #include "socket_tls.h" /* tls_connected_socket */ tls_connected_socket::tls_connected_socket() : connected_socket(-1), ssl(nullptr),lingering_close(0), nopush(0), nodelay(0) {} tls_connected_socket::tls_connected_socket(int fd) : connected_socket(fd), ssl(nullptr), lingering_close(0), nopush(0), nodelay(0) { if (fd < 0) return; if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { log_error("fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s", fd, strerror(errno)); } if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { log_error("fcntl(%d, F_SETFL, O_NONBLOCK) failed: %s", fd, strerror(errno)); } } tls_connected_socket::~tls_connected_socket() { if (ssl) { SSL_free(ssl); ssl = nullptr; } } void tls_connected_socket::set_context(void *context) { ctx = (SSL_CTX*)context; } socket_mode tls_connected_socket::get_mode() { return socket_mode_tls; } int tls_connected_socket::do_handshake() { int ret = SSL_do_handshake(ssl); return ret < 0 ? SSL_get_error(ssl, ret) : 0; } bool tls_connected_socket::start_listening(socket_addr addr, int backlog) { int fd = socket(addr.saddr.sa_family, SOCK_STREAM, 0); if (fd < 0) { log_error("socket failed: %s", strerror(errno)); return false; } set_fd(fd); this->addr = addr; this->backlog = backlog; if (addr.saddr.sa_family == AF_INET6) { int ipv6only = 1; if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, sizeof(ipv6only)) < 0) { log_error("setsockopt(IPPROTO_IPV6, IPV6_V6ONLY) failed: %s", strerror(errno)); return false; } } int reuse = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) { log_error("setsockopt(SOL_SOCKET, SO_REUSEADDR) failed: %s", strerror(errno)); return false; } if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { log_error("fcntl(F_SETFD, FD_CLOEXEC) failed: %s", strerror(errno)); return false; } if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { log_error("fcntl(F_SETFL, O_NONBLOCK) failed: %s", strerror(errno)); return false; } socklen_t addr_size = 0; if (addr.saddr.sa_family == AF_INET) addr_size = sizeof(addr.ip4addr); if (addr.saddr.sa_family == AF_INET6) addr_size = sizeof(addr.ip6addr); if (bind(fd, (struct sockaddr *) &addr.storage, addr_size) < 0) { log_error("bind failed: %s: %s", to_string().c_str(), strerror(errno)); return false; } if (listen(fd, (int)backlog) < 0) { log_error("listen failed: %s", strerror(errno)); return false; } return true; } socket_addr tls_connected_socket::get_addr() { return addr; } std::string tls_connected_socket::to_string() { return socket_addr::addr_to_string(addr); } void tls_connected_socket::close_connection() { if (ssl) { SSL_shutdown(ssl); } generic_socket::close_connection(); } void tls_connected_socket::accept(int fd) { set_fd(fd); if (!ssl) { ssl = SSL_new((SSL_CTX*)ctx); } SSL_clear(ssl); SSL_set_fd(ssl, fd); SSL_set_accept_state(ssl); } bool tls_connected_socket::connect_to_host( socket_addr addr) { int fd = socket(addr.saddr.sa_family, SOCK_STREAM, 0); if (fd < 0) { log_error("socket failed: %s", strerror(errno)); return false; } set_fd(-1); if (!ssl) { ssl = SSL_new((SSL_CTX*)ctx); } SSL_clear(ssl); SSL_set_fd(ssl, fd); SSL_set_connect_state(ssl); if (addr.saddr.sa_family == AF_INET6) { int ipv6only = 1; if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, sizeof(ipv6only)) < 0) { log_error("setsockopt(IPPROTO_IPV6, IPV6_V6ONLY) failed: %s", strerror(errno)); } } int reuse = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) { log_error("setsockopt(SOL_SOCKET, SO_REUSEADDR) failed: %s", strerror(errno)); } if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { log_error("fcntl(F_SETFD, FD_CLOEXEC) failed: %s", strerror(errno)); } if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { log_error("fcntl(F_SETFL, O_NONBLOCK) failed: %s", strerror(errno)); } int ret = connect(fd, (struct sockaddr *) &addr.storage, socket_addr::len(addr)); if (ret < 0 && errno != EINPROGRESS) { log_error("connect failed: %s", strerror(errno)); return false; } assert(ssl != nullptr); SSL_clear(ssl); SSL_set_fd(ssl, fd); SSL_set_connect_state(ssl); return true; } bool tls_connected_socket::set_nopush(bool nopush) { unsigned int val = nopush ? 1 : 0; if (this->nopush == val) return true; if (setsockopt(fd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val)) < 0) { log_error("setsockopt(TCP_NOPUSH) failed: %s", strerror(errno)); return false; } else { this->nopush = val; return true; } } bool tls_connected_socket::set_nodelay(bool nodelay) { unsigned int val = nodelay ? 1 : 0; if (this->nodelay == val) return true; if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) < 0) { log_error("setsockopt(TCP_NODELAY) failed: %s", strerror(errno)); return false; } else { this->nodelay = val; return true; } } bool tls_connected_socket::start_lingering_close() { /* called in the case of a server initiated close (half-close). * i.e. timeouts of keepalive connections and aborts */ if (lingering_close) return true; if (shutdown(fd, SHUT_WR) < 0) { log_debug("shutdown failed: %s", strerror(errno)); close(fd); return false; } else { lingering_close = true; return true; } } io_result tls_connected_socket::read(void *buf, size_t len) { assert(ssl != nullptr); int ret = SSL_read(ssl, buf, (int)len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); } io_result tls_connected_socket::readv(const struct iovec *iov, int iovcnt) { assert(iovcnt > 0); assert(ssl != nullptr); int ret = SSL_read(ssl, iov[0].iov_base, (int)iov[0].iov_len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); } io_result tls_connected_socket::write(void *buf, size_t len) { assert(ssl != nullptr); int ret = SSL_write(ssl, buf, (int)len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); } io_result tls_connected_socket::writev(const struct iovec *iov, int iovcnt) { assert(iovcnt > 0); assert(ssl != nullptr); int ret = SSL_write(ssl, iov[0].iov_base, (int)iov[0].iov_len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); }
// // tls_socket.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstring> #include <memory> #include <sstream> #include <string> #include <vector> #include "log.h" #include "io.h" #include "socket.h" #include "socket_tls.h" /* tls_connected_socket */ tls_connected_socket::tls_connected_socket() : connected_socket(-1), ssl(nullptr),lingering_close(0), nopush(0), nodelay(0) {} tls_connected_socket::tls_connected_socket(int fd) : connected_socket(fd), ssl(nullptr), lingering_close(0), nopush(0), nodelay(0) { if (fd < 0) return; if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { log_error("fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s", fd, strerror(errno)); } if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { log_error("fcntl(%d, F_SETFL, O_NONBLOCK) failed: %s", fd, strerror(errno)); } } tls_connected_socket::~tls_connected_socket() { if (ssl) { SSL_free(ssl); ssl = nullptr; } } void tls_connected_socket::set_context(void *context) { ctx = (SSL_CTX*)context; } socket_mode tls_connected_socket::get_mode() { return socket_mode_tls; } int tls_connected_socket::do_handshake() { int ret = SSL_do_handshake(ssl); return ret < 0 ? SSL_get_error(ssl, ret) : 0; } bool tls_connected_socket::start_listening(socket_addr addr, int backlog) { int fd = socket(addr.saddr.sa_family, SOCK_STREAM, 0); if (fd < 0) { log_error("socket failed: %s", strerror(errno)); return false; } set_fd(fd); this->addr = addr; this->backlog = backlog; if (addr.saddr.sa_family == AF_INET6) { int ipv6only = 1; if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, sizeof(ipv6only)) < 0) { log_error("setsockopt(IPPROTO_IPV6, IPV6_V6ONLY) failed: %s", strerror(errno)); return false; } } int reuse = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) { log_error("setsockopt(SOL_SOCKET, SO_REUSEADDR) failed: %s", strerror(errno)); return false; } if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { log_error("fcntl(F_SETFD, FD_CLOEXEC) failed: %s", strerror(errno)); return false; } if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { log_error("fcntl(F_SETFL, O_NONBLOCK) failed: %s", strerror(errno)); return false; } socklen_t addr_size = 0; if (addr.saddr.sa_family == AF_INET) addr_size = sizeof(addr.ip4addr); if (addr.saddr.sa_family == AF_INET6) addr_size = sizeof(addr.ip6addr); if (bind(fd, (struct sockaddr *) &addr.storage, addr_size) < 0) { log_error("bind failed: %s: %s", to_string().c_str(), strerror(errno)); return false; } if (listen(fd, (int)backlog) < 0) { log_error("listen failed: %s", strerror(errno)); return false; } return true; } socket_addr tls_connected_socket::get_addr() { return addr; } std::string tls_connected_socket::to_string() { return socket_addr::addr_to_string(addr); } void tls_connected_socket::close_connection() { if (ssl) { SSL_shutdown(ssl); } generic_socket::close_connection(); } void tls_connected_socket::accept(int fd) { set_fd(fd); if (!ssl) { ssl = SSL_new((SSL_CTX*)ctx); } SSL_clear(ssl); SSL_set_fd(ssl, fd); SSL_set_accept_state(ssl); } bool tls_connected_socket::connect_to_host( socket_addr addr) { int fd = socket(addr.saddr.sa_family, SOCK_STREAM, 0); if (fd < 0) { log_error("socket failed: %s", strerror(errno)); return false; } set_fd(fd); if (!ssl) { ssl = SSL_new((SSL_CTX*)ctx); } SSL_clear(ssl); SSL_set_fd(ssl, fd); SSL_set_connect_state(ssl); if (addr.saddr.sa_family == AF_INET6) { int ipv6only = 1; if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, sizeof(ipv6only)) < 0) { log_error("setsockopt(IPPROTO_IPV6, IPV6_V6ONLY) failed: %s", strerror(errno)); } } int reuse = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) { log_error("setsockopt(SOL_SOCKET, SO_REUSEADDR) failed: %s", strerror(errno)); } if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { log_error("fcntl(F_SETFD, FD_CLOEXEC) failed: %s", strerror(errno)); } if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { log_error("fcntl(F_SETFL, O_NONBLOCK) failed: %s", strerror(errno)); } int ret = connect(fd, (struct sockaddr *) &addr.storage, socket_addr::len(addr)); if (ret < 0 && errno != EINPROGRESS) { log_error("connect failed: %s", strerror(errno)); return false; } assert(ssl != nullptr); SSL_clear(ssl); SSL_set_fd(ssl, fd); SSL_set_connect_state(ssl); return true; } bool tls_connected_socket::set_nopush(bool nopush) { unsigned int val = nopush ? 1 : 0; if (this->nopush == val) return true; if (setsockopt(fd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val)) < 0) { log_error("setsockopt(TCP_NOPUSH) failed: %s", strerror(errno)); return false; } else { this->nopush = val; return true; } } bool tls_connected_socket::set_nodelay(bool nodelay) { unsigned int val = nodelay ? 1 : 0; if (this->nodelay == val) return true; if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) < 0) { log_error("setsockopt(TCP_NODELAY) failed: %s", strerror(errno)); return false; } else { this->nodelay = val; return true; } } bool tls_connected_socket::start_lingering_close() { /* called in the case of a server initiated close (half-close). * i.e. timeouts of keepalive connections and aborts */ if (lingering_close) return true; if (shutdown(fd, SHUT_WR) < 0) { log_debug("shutdown failed: %s", strerror(errno)); close(fd); return false; } else { lingering_close = true; return true; } } io_result tls_connected_socket::read(void *buf, size_t len) { assert(ssl != nullptr); int ret = SSL_read(ssl, buf, (int)len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); } io_result tls_connected_socket::readv(const struct iovec *iov, int iovcnt) { assert(iovcnt > 0); assert(ssl != nullptr); int ret = SSL_read(ssl, iov[0].iov_base, (int)iov[0].iov_len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); } io_result tls_connected_socket::write(void *buf, size_t len) { assert(ssl != nullptr); int ret = SSL_write(ssl, buf, (int)len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); } io_result tls_connected_socket::writev(const struct iovec *iov, int iovcnt) { assert(iovcnt > 0); assert(ssl != nullptr); int ret = SSL_write(ssl, iov[0].iov_base, (int)iov[0].iov_len); return ret < 0 ? io_result(io_error(SSL_get_error(ssl, ret))) : io_result(ret); }
Fix typo in tls_connected_socket
Fix typo in tls_connected_socket
C++
isc
metaparadigm/latypus,metaparadigm/latypus,metaparadigm/latypus,metaparadigm/latypus
2325650d59511ad1e19e0102cf920b48cca0bfc5
tensorflow/lite/kernels/internal/reference/portable_tensor_utils.cc
tensorflow/lite/kernels/internal/reference/portable_tensor_utils.cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdlib.h> #include <string.h> #include <algorithm> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/activation_functor.h" #include "tensorflow/lite/kernels/internal/round.h" #include "tensorflow/lite/kernels/op_macros.h" #if defined(_MSC_VER) #define __restrict__ __restrict #endif namespace tflite { namespace tensor_utils { float PortableClip(float f, float abs_limit) { float result = (abs_limit < f) ? abs_limit : f; result = (-abs_limit > result) ? -abs_limit : result; return result; } bool PortableIsZeroVector(const float* vector, int v_size) { for (int i = 0; i < v_size; ++i) { if (*vector++ != 0.0f) return false; } return true; } void PortableSymmetricQuantizeFloats(const float* values, const int size, int8_t* quantized_values, float* min_value, float* max_value, float* scaling_factor) { auto minmax = std::minmax_element(values, values + size); *min_value = *minmax.first; *max_value = *minmax.second; const int kScale = 127; const float range = std::max(std::abs(*min_value), std::abs(*max_value)); if (range == 0) { memset(quantized_values, 0, size * sizeof(int8_t)); *scaling_factor = 1; return; } *scaling_factor = range / kScale; const float scaling_factor_inv = kScale / range; for (int i = 0; i < size; ++i) { const int32_t quantized_value = static_cast<int32_t>(TfLiteRound(values[i] * scaling_factor_inv)); // Clamp: just in case some odd numeric offset. quantized_values[i] = std::min(kScale, std::max(-kScale, quantized_value)); } } void PortableMatrixBatchVectorMultiplyAccumulate(const float* matrix, int m_rows, int m_cols, const float* vector, int n_batch, float* result, int result_stride) { float* result_in_batch = result; for (int b = 0; b < n_batch; b++) { const float* matrix_ptr = matrix; for (int r = 0; r < m_rows; r++) { float dot_prod = 0.0f; const float* vector_in_batch = vector + b * m_cols; for (int c = 0; c < m_cols; c++) { dot_prod += *matrix_ptr++ * *vector_in_batch++; } *result_in_batch += dot_prod; result_in_batch += result_stride; } } } void PortableMatrixBatchVectorMultiplyAccumulate( const int8_t* __restrict__ matrix, const int m_rows, const int m_cols, const int8_t* __restrict__ vectors, const float* scaling_factors, int n_batch, float* __restrict__ result, int result_stride) { int batch, row, col; for (batch = 0; batch < n_batch; ++batch, vectors += m_cols) { const float batch_scaling_factor = scaling_factors[batch]; // Get the address of the first row. const int8_t* row_ptr = matrix; for (row = 0; row < m_rows; ++row, result += result_stride) { // Initialize the dot product sum for the row to 0. int32_t dotprod = 0; #if defined(__GNUC__) // Prefetch the row to cache. __builtin_prefetch(row_ptr, 0 /* prefetch for read */, 3 /* temporal locality */); #endif // For every block of 16 8-bit elements (128-bit register) from each row. for (col = 0; col < m_cols; ++col, ++row_ptr) { dotprod += (*row_ptr) * (vectors[col]); } // for col *result += (dotprod * batch_scaling_factor); } // for row } // for batch } void PortableVectorVectorCwiseProduct(const float* vector1, const float* vector2, int v_size, float* result) { for (int v = 0; v < v_size; v++) { *result++ = *vector1++ * *vector2++; } } float PortableVectorVectorDotProduct(const float* vector1, const float* vector2, int v_size) { float result = 0.0; for (int v = 0; v < v_size; v++) { result += *vector1++ * *vector2++; } return result; } void PortableBatchVectorBatchVectorDotProduct(const float* vector1, const float* vector2, int v_size, int n_batch, float* result, int result_stride) { float* result_ptr = result; const float* vector1_ptr = vector1; const float* vector2_ptr = vector2; for (int b = 0; b < n_batch; b++) { *result_ptr = PortableVectorVectorDotProduct(vector1_ptr, vector2_ptr, v_size); vector1_ptr += v_size; vector2_ptr += v_size; result_ptr += result_stride; } } void PortableVectorVectorCwiseProductAccumulate(const float* vector1, const float* vector2, int v_size, float* result) { for (int v = 0; v < v_size; v++) { *result++ += *vector1++ * *vector2++; } } void PortableVectorBatchVectorCwiseProduct(const float* vector, int v_size, const float* batch_vector, int n_batch, float* result) { for (int b = 0; b < n_batch; b++) { for (int v = 0; v < v_size; v++) { *result++ = vector[v] * *batch_vector++; } } } void PortableVectorBatchVectorCwiseProductAccumulate(const float* vector, int v_size, const float* batch_vector, int n_batch, float* result) { for (int b = 0; b < n_batch; b++) { for (int v = 0; v < v_size; v++) { *result++ += vector[v] * *batch_vector++; } } } void PortableVectorBatchVectorAdd(const float* vector, int v_size, int n_batch, float* batch_vector) { for (int b = 0; b < n_batch; b++) { for (int i = 0; i < v_size; ++i) { batch_vector[i] += vector[i]; } batch_vector += v_size; } } void PortableVectorBatchVectorAssign(const float* vector, int v_size, int n_batch, float* batch_vector) { for (int b = 0; b < n_batch; b++) { memcpy(batch_vector + b * v_size, vector, v_size * sizeof(float)); } } void PortableApplySigmoidToVector(const float* vector, int v_size, float* result) { auto sigmoid_func = ActivationFunctor(kTfLiteActSigmoid); for (int v = 0; v < v_size; v++) { *result++ = (sigmoid_func)(*vector++); } } void PortableApplyActivationToVector(const float* vector, int v_size, TfLiteFusedActivation activation, float* result) { auto activation_func = ActivationFunctor(activation); for (int v = 0; v < v_size; v++) { *result++ = (activation_func)(*vector++); } } void PortableCopyVector(const float* vector, int v_size, float* result) { memcpy(result, vector, v_size * sizeof(float)); } void PortableSub1Vector(const float* vector, int v_size, float* result) { for (int v = 0; v < v_size; v++) { *result++ = 1.0f - *vector++; } } void PortableZeroVector(float* vector, int v_size) { memset(vector, 0, v_size * sizeof(float)); } void PortableVectorScalarMultiply(const int8_t* vector, const int v_size, const float scale, float* result) { for (int v = 0; v < v_size; ++v) { *result++ = scale * *vector++; } } void PortableClipVector(const float* vector, int v_size, float abs_limit, float* result) { for (int v = 0; v < v_size; v++) { *result++ = PortableClip(*vector++, abs_limit); } } void PortableVectorShiftLeft(float* vector, int v_size, float shift_value) { TF_LITE_ASSERT(v_size > 0); for (int i = 0; i < v_size - 1; i++) { vector[i] = vector[i + 1]; } vector[v_size - 1] = shift_value; } void PortableReductionSumVector(const float* input_vector, float* output_vector, int output_size, int reduction_size) { const float* input_vector_ptr = input_vector; for (int o = 0; o < output_size; o++) { for (int r = 0; r < reduction_size; r++) { output_vector[o] += *input_vector_ptr++; } } } void PortableMeanStddevNormalization(const float* input_vector, float* output_vector, int v_size, int n_batch, float normalization_epsilon) { for (int batch = 0; batch < n_batch; ++batch) { float sum = 0.0f; float sum_sq = 0.0f; for (int i = 0; i < v_size; ++i) { sum += input_vector[i]; sum_sq += input_vector[i] * input_vector[i]; } const float mean = sum / v_size; float stddev_inv = 0.0f; const float variance = sum_sq / v_size - mean * mean; if (variance == 0) { stddev_inv = 1.0f / sqrt(normalization_epsilon); } else { stddev_inv = 1.0f / sqrt(variance); } for (int i = 0; i < v_size; ++i) { output_vector[i] = (input_vector[i] - mean) * stddev_inv; } input_vector += v_size; output_vector += v_size; } } } // namespace tensor_utils } // namespace tflite
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdlib.h> #include <string.h> #include <algorithm> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/activation_functor.h" #include "tensorflow/lite/kernels/internal/round.h" #include "tensorflow/lite/kernels/op_macros.h" #if defined(_MSC_VER) #define __restrict__ __restrict #endif namespace tflite { namespace tensor_utils { float PortableClip(float f, float abs_limit) { float result = (abs_limit < f) ? abs_limit : f; result = (-abs_limit > result) ? -abs_limit : result; return result; } bool PortableIsZeroVector(const float* vector, int v_size) { for (int i = 0; i < v_size; ++i) { if (*vector++ != 0.0f) return false; } return true; } void PortableSymmetricQuantizeFloats(const float* values, const int size, int8_t* quantized_values, float* min_value, float* max_value, float* scaling_factor) { auto minmax = std::minmax_element(values, values + size); *min_value = *minmax.first; *max_value = *minmax.second; const int kScale = 127; const float range = std::max(std::abs(*min_value), std::abs(*max_value)); if (range == 0) { memset(quantized_values, 0, size * sizeof(int8_t)); *scaling_factor = 1; return; } *scaling_factor = range / kScale; const float scaling_factor_inv = kScale / range; for (int i = 0; i < size; ++i) { const int32_t quantized_value = static_cast<int32_t>(TfLiteRound(values[i] * scaling_factor_inv)); // Clamp: just in case some odd numeric offset. quantized_values[i] = std::min(kScale, std::max(-kScale, quantized_value)); } } void PortableMatrixBatchVectorMultiplyAccumulate(const float* matrix, int m_rows, int m_cols, const float* vector, int n_batch, float* result, int result_stride) { float* result_in_batch = result; for (int b = 0; b < n_batch; b++) { const float* matrix_ptr = matrix; for (int r = 0; r < m_rows; r++) { float dot_prod = 0.0f; const float* vector_in_batch = vector + b * m_cols; for (int c = 0; c < m_cols; c++) { dot_prod += *matrix_ptr++ * *vector_in_batch++; } *result_in_batch += dot_prod; result_in_batch += result_stride; } } } void PortableMatrixBatchVectorMultiplyAccumulate( const int8_t* __restrict__ matrix, const int m_rows, const int m_cols, const int8_t* __restrict__ vectors, const float* scaling_factors, int n_batch, float* __restrict__ result, int result_stride) { int batch, row, col; for (batch = 0; batch < n_batch; ++batch, vectors += m_cols) { const float batch_scaling_factor = scaling_factors[batch]; // Get the address of the first row. const int8_t* row_ptr = matrix; for (row = 0; row < m_rows; ++row, result += result_stride) { // Initialize the dot product sum for the row to 0. int32_t dotprod = 0; #if defined(__GNUC__) // Prefetch the row to cache. __builtin_prefetch(row_ptr, 0 /* prefetch for read */, 3 /* temporal locality */); #endif for (col = 0; col < m_cols; ++col, ++row_ptr) { dotprod += (*row_ptr) * (vectors[col]); } // for col *result += (dotprod * batch_scaling_factor); } // for row } // for batch } void PortableVectorVectorCwiseProduct(const float* vector1, const float* vector2, int v_size, float* result) { for (int v = 0; v < v_size; v++) { *result++ = *vector1++ * *vector2++; } } float PortableVectorVectorDotProduct(const float* vector1, const float* vector2, int v_size) { float result = 0.0; for (int v = 0; v < v_size; v++) { result += *vector1++ * *vector2++; } return result; } void PortableBatchVectorBatchVectorDotProduct(const float* vector1, const float* vector2, int v_size, int n_batch, float* result, int result_stride) { float* result_ptr = result; const float* vector1_ptr = vector1; const float* vector2_ptr = vector2; for (int b = 0; b < n_batch; b++) { *result_ptr = PortableVectorVectorDotProduct(vector1_ptr, vector2_ptr, v_size); vector1_ptr += v_size; vector2_ptr += v_size; result_ptr += result_stride; } } void PortableVectorVectorCwiseProductAccumulate(const float* vector1, const float* vector2, int v_size, float* result) { for (int v = 0; v < v_size; v++) { *result++ += *vector1++ * *vector2++; } } void PortableVectorBatchVectorCwiseProduct(const float* vector, int v_size, const float* batch_vector, int n_batch, float* result) { for (int b = 0; b < n_batch; b++) { for (int v = 0; v < v_size; v++) { *result++ = vector[v] * *batch_vector++; } } } void PortableVectorBatchVectorCwiseProductAccumulate(const float* vector, int v_size, const float* batch_vector, int n_batch, float* result) { for (int b = 0; b < n_batch; b++) { for (int v = 0; v < v_size; v++) { *result++ += vector[v] * *batch_vector++; } } } void PortableVectorBatchVectorAdd(const float* vector, int v_size, int n_batch, float* batch_vector) { for (int b = 0; b < n_batch; b++) { for (int i = 0; i < v_size; ++i) { batch_vector[i] += vector[i]; } batch_vector += v_size; } } void PortableVectorBatchVectorAssign(const float* vector, int v_size, int n_batch, float* batch_vector) { for (int b = 0; b < n_batch; b++) { memcpy(batch_vector + b * v_size, vector, v_size * sizeof(float)); } } void PortableApplySigmoidToVector(const float* vector, int v_size, float* result) { auto sigmoid_func = ActivationFunctor(kTfLiteActSigmoid); for (int v = 0; v < v_size; v++) { *result++ = (sigmoid_func)(*vector++); } } void PortableApplyActivationToVector(const float* vector, int v_size, TfLiteFusedActivation activation, float* result) { auto activation_func = ActivationFunctor(activation); for (int v = 0; v < v_size; v++) { *result++ = (activation_func)(*vector++); } } void PortableCopyVector(const float* vector, int v_size, float* result) { memcpy(result, vector, v_size * sizeof(float)); } void PortableSub1Vector(const float* vector, int v_size, float* result) { for (int v = 0; v < v_size; v++) { *result++ = 1.0f - *vector++; } } void PortableZeroVector(float* vector, int v_size) { memset(vector, 0, v_size * sizeof(float)); } void PortableVectorScalarMultiply(const int8_t* vector, const int v_size, const float scale, float* result) { for (int v = 0; v < v_size; ++v) { *result++ = scale * *vector++; } } void PortableClipVector(const float* vector, int v_size, float abs_limit, float* result) { for (int v = 0; v < v_size; v++) { *result++ = PortableClip(*vector++, abs_limit); } } void PortableVectorShiftLeft(float* vector, int v_size, float shift_value) { TF_LITE_ASSERT(v_size > 0); for (int i = 0; i < v_size - 1; i++) { vector[i] = vector[i + 1]; } vector[v_size - 1] = shift_value; } void PortableReductionSumVector(const float* input_vector, float* output_vector, int output_size, int reduction_size) { const float* input_vector_ptr = input_vector; for (int o = 0; o < output_size; o++) { for (int r = 0; r < reduction_size; r++) { output_vector[o] += *input_vector_ptr++; } } } void PortableMeanStddevNormalization(const float* input_vector, float* output_vector, int v_size, int n_batch, float normalization_epsilon) { for (int batch = 0; batch < n_batch; ++batch) { float sum = 0.0f; float sum_sq = 0.0f; for (int i = 0; i < v_size; ++i) { sum += input_vector[i]; sum_sq += input_vector[i] * input_vector[i]; } const float mean = sum / v_size; float stddev_inv = 0.0f; const float variance = sum_sq / v_size - mean * mean; if (variance == 0) { stddev_inv = 1.0f / sqrt(normalization_epsilon); } else { stddev_inv = 1.0f / sqrt(variance); } for (int i = 0; i < v_size; ++i) { output_vector[i] = (input_vector[i] - mean) * stddev_inv; } input_vector += v_size; output_vector += v_size; } } } // namespace tensor_utils } // namespace tflite
Remove false comments in portable kernel.
Remove false comments in portable kernel. PiperOrigin-RevId: 228203258
C++
apache-2.0
apark263/tensorflow,paolodedios/tensorflow,jbedorf/tensorflow,arborh/tensorflow,ageron/tensorflow,arborh/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,jbedorf/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ageron/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,chemelnucfin/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ageron/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,arborh/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jbedorf/tensorflow,aam-at/tensorflow,apark263/tensorflow,alsrgv/tensorflow,gunan/tensorflow,ghchinoy/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,apark263/tensorflow,karllessard/tensorflow,jendap/tensorflow,annarev/tensorflow,ageron/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,theflofly/tensorflow,theflofly/tensorflow,xzturn/tensorflow,xzturn/tensorflow,jbedorf/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,Intel-Corporation/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow,gautam1858/tensorflow,gunan/tensorflow,adit-chandra/tensorflow,ghchinoy/tensorflow,davidzchen/tensorflow,chemelnucfin/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,apark263/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,theflofly/tensorflow,xzturn/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,theflofly/tensorflow,jendap/tensorflow,jendap/tensorflow,adit-chandra/tensorflow,alsrgv/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,annarev/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,theflofly/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-pywrap_saved_model,arborh/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,arborh/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,aam-at/tensorflow,yongtang/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,Intel-tensorflow/tensorflow,theflofly/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,kevin-coder/tensorflow-fork,petewarden/tensorflow,theflofly/tensorflow,aam-at/tensorflow,theflofly/tensorflow,ghchinoy/tensorflow,petewarden/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,aldian/tensorflow,gunan/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,yongtang/tensorflow,arborh/tensorflow,kevin-coder/tensorflow-fork,freedomtan/tensorflow,freedomtan/tensorflow,annarev/tensorflow,jendap/tensorflow,annarev/tensorflow,xzturn/tensorflow,renyi533/tensorflow,chemelnucfin/tensorflow,gunan/tensorflow,adit-chandra/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jendap/tensorflow,davidzchen/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,theflofly/tensorflow,ghchinoy/tensorflow,ppwwyyxx/tensorflow,ghchinoy/tensorflow,sarvex/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,ageron/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,davidzchen/tensorflow,alsrgv/tensorflow,ghchinoy/tensorflow,yongtang/tensorflow,gunan/tensorflow,alsrgv/tensorflow,xzturn/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,aldian/tensorflow,renyi533/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,ageron/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,ppwwyyxx/tensorflow,kevin-coder/tensorflow-fork,alsrgv/tensorflow,apark263/tensorflow,cxxgtxy/tensorflow,theflofly/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,theflofly/tensorflow,jhseu/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,Intel-tensorflow/tensorflow,sarvex/tensorflow,yongtang/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,apark263/tensorflow,jendap/tensorflow,aldian/tensorflow,petewarden/tensorflow,arborh/tensorflow,annarev/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,jbedorf/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,ppwwyyxx/tensorflow,davidzchen/tensorflow,DavidNorman/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,cxxgtxy/tensorflow,annarev/tensorflow,jhseu/tensorflow,alsrgv/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,annarev/tensorflow,renyi533/tensorflow,cxxgtxy/tensorflow,apark263/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,DavidNorman/tensorflow,jbedorf/tensorflow,aam-at/tensorflow,adit-chandra/tensorflow,jbedorf/tensorflow,xzturn/tensorflow,karllessard/tensorflow,gunan/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,DavidNorman/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow,alsrgv/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,jhseu/tensorflow,Intel-tensorflow/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,xzturn/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,aam-at/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,chemelnucfin/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,karllessard/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,ghchinoy/tensorflow,jendap/tensorflow,adit-chandra/tensorflow,jendap/tensorflow,gunan/tensorflow,karllessard/tensorflow,ghchinoy/tensorflow,ppwwyyxx/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,alsrgv/tensorflow,gautam1858/tensorflow,arborh/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,chemelnucfin/tensorflow,tensorflow/tensorflow,apark263/tensorflow,DavidNorman/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,gautam1858/tensorflow,gunan/tensorflow,davidzchen/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,ageron/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,jbedorf/tensorflow,frreiss/tensorflow-fred,alsrgv/tensorflow,paolodedios/tensorflow,arborh/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aldian/tensorflow,sarvex/tensorflow,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,kevin-coder/tensorflow-fork,renyi533/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,aldian/tensorflow,chemelnucfin/tensorflow,alsrgv/tensorflow,apark263/tensorflow,kevin-coder/tensorflow-fork,jbedorf/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,DavidNorman/tensorflow,DavidNorman/tensorflow,ppwwyyxx/tensorflow,apark263/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,jbedorf/tensorflow,adit-chandra/tensorflow,arborh/tensorflow,apark263/tensorflow,jbedorf/tensorflow,davidzchen/tensorflow,ghchinoy/tensorflow,alsrgv/tensorflow,jhseu/tensorflow,ghchinoy/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,jendap/tensorflow,yongtang/tensorflow,theflofly/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,frreiss/tensorflow-fred,jbedorf/tensorflow,davidzchen/tensorflow,jendap/tensorflow,sarvex/tensorflow,aam-at/tensorflow,yongtang/tensorflow,annarev/tensorflow,ageron/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,DavidNorman/tensorflow,jendap/tensorflow,arborh/tensorflow,ageron/tensorflow,ghchinoy/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,renyi533/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,davidzchen/tensorflow,gunan/tensorflow,sarvex/tensorflow,aldian/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,alsrgv/tensorflow,jhseu/tensorflow,xzturn/tensorflow,Intel-tensorflow/tensorflow,ageron/tensorflow,ageron/tensorflow
3e9dbd3977feec13660eb11fdd2be11e396a9e42
core/source/datastore/labels.cpp
core/source/datastore/labels.cpp
/** * FILE : datastore/labels.hpp * * Implements a set of labels identifying nodes, elements, field components. * Used to index a dimension of a datastore map. */ /* OpenCMISS-Zinc Library * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "zinc/status.h" #include "datastore/labels.hpp" #include "general/message.h" DsLabels::DsLabels() : cmzn::RefCounted(), contiguous(true), firstFreeIdentifier(1), firstIdentifier(DS_LABEL_IDENTIFIER_INVALID), lastIdentifier(DS_LABEL_IDENTIFIER_INVALID), labelsCount(0), indexSize(0), activeIterators(0), inactiveIterators(0) { }; DsLabels::~DsLabels() { DsLabelIterator *iterator; while (inactiveIterators) { iterator = inactiveIterators->next; delete inactiveIterators; inactiveIterators = iterator; } // can't free externally held objects, hence just invalidate for safety iterator = activeIterators; while (iterator) { iterator->invalidate(); iterator = iterator->next; } } /** restore to initial empty, contiguous state. Keeps current name, if any */ void DsLabels::clear() { // can't free externally held objects, hence just invalidate for safety DsLabelIterator *iterator = this->activeIterators; while (iterator) { iterator->invalidate(); iterator = iterator->next; } this->contiguous = true; this->firstFreeIdentifier = 1; this->firstIdentifier = DS_LABEL_IDENTIFIER_INVALID; this->lastIdentifier = DS_LABEL_IDENTIFIER_INVALID; this->identifiers.clear(); this->identifierToIndexMap.clear(); this->labelsCount = 0; this->indexSize = 0; } /** * Get the next unused identifier of at least startIdentifier, * or 1 if startIdentifier is not positive. */ DsLabelIdentifier DsLabels::getFirstFreeIdentifier(DsLabelIdentifier startIdentifier) { DsLabelIdentifier identifier = (startIdentifier <= this->firstFreeIdentifier) ? this->firstFreeIdentifier : startIdentifier; if (identifier < (this->lastIdentifier + 1)) { // this can be optimised using an iterator: while (DS_LABEL_INDEX_INVALID != findLabelByIdentifier(identifier)) ++identifier; } if (startIdentifier <= this->firstFreeIdentifier) this->firstFreeIdentifier = identifier; return identifier; } int DsLabels::setNotContiguous() { if (this->contiguous) { // this can be optimised: DsLabelIdentifier identifier = this->firstIdentifier; for (DsLabelIndex index = 0; index < this->indexSize; ++index) { if (!(this->identifiers.setValue(index, identifier) && this->identifierToIndexMap.insert(*this, index))) { display_message(ERROR_MESSAGE, "DsLabels::setNotContiguous. Failed"); return CMZN_ERROR_MEMORY; } ++identifier; } this->contiguous = false; return CMZN_OK; } return CMZN_ERROR_ARGUMENT; } /** private: caller must have checked identifier is not in use! */ DsLabelIndex DsLabels::createLabelPrivate(DsLabelIdentifier identifier) { if (identifier < 0) return DS_LABEL_INDEX_INVALID; DsLabelIndex index = DS_LABEL_INDEX_INVALID; if (this->contiguous) { if (0 == this->labelsCount) { this->firstIdentifier = identifier; } else if ((identifier < this->firstIdentifier) || (identifier > (this->lastIdentifier + 1))) { if (CMZN_OK != this->setNotContiguous()) return index; } if (this->contiguous) { index = this->indexSize; this->lastIdentifier = identifier; this->firstFreeIdentifier = this->lastIdentifier + 1; ++this->labelsCount; ++this->indexSize; return index; } } // Future memory optimisation: reclaim unused indexes for new labels. // Note for reclaim to work would have to clear indexes into maps // as labels are deleted [for maps indexed by these labels]. if (this->identifiers.setValue(this->indexSize, identifier)) { index = this->indexSize; // must increase these now to allow identifiers to be queried by map ++this->labelsCount; ++this->indexSize; if (!this->identifierToIndexMap.insert(*this, index)) { display_message(ERROR_MESSAGE, "DsLabels::createLabelPrivate. Failed to insert index into map"); --this->labelsCount; --this->indexSize; return DS_LABEL_INDEX_INVALID; } if (identifier > this->lastIdentifier) this->lastIdentifier = identifier; if (identifier == this->firstFreeIdentifier) ++this->firstFreeIdentifier; } else display_message(ERROR_MESSAGE, "DsLabels::createLabelPrivate. Failed to set identifier"); return index; } /** create with auto-generated unique identifier */ DsLabelIndex DsLabels::createLabel() { return createLabelPrivate(this->getFirstFreeIdentifier()); } /** fails if identifier already in use */ DsLabelIndex DsLabels::createLabel(DsLabelIdentifier identifier) { DsLabelIndex index = findLabelByIdentifier(identifier); if (index >= 0) return DS_LABEL_INDEX_INVALID; return createLabelPrivate(identifier); } /** finds existing entry with identifier, or creates new one if none */ DsLabelIndex DsLabels::findOrCreateLabel(DsLabelIdentifier identifier) { DsLabelIndex index = findLabelByIdentifier(identifier); if (index >= 0) return index; return createLabelPrivate(identifier); } int DsLabels::addLabelsRange(DsLabelIdentifier min, DsLabelIdentifier max, DsLabelIdentifier stride) { if ((max < min) || (stride < 1)) return CMZN_ERROR_ARGUMENT; if (this->contiguous && (stride == 1) && (0 == this->labelsCount)) { // fast case this->firstIdentifier = min; this->lastIdentifier = max; this->firstFreeIdentifier = max + 1; this->labelsCount = max - min + 1; this->indexSize = max - min + 1; } else { for (DsLabelIdentifier identifier = min; identifier <= max; identifier += stride) { DsLabelIndex index = this->findOrCreateLabel(identifier); if (index < 0) return CMZN_ERROR_GENERAL; } } return CMZN_OK; } int DsLabels::removeLabel(DsLabelIndex index) { if ((index < 0) || (index >= this->indexSize)) return 0; if (this->contiguous) setNotContiguous(); DsLabelIdentifier identifier; if (this->identifiers.getValue(index, identifier)) { if (identifier >= 0) { this->identifierToIndexMap.erase(*this, index); this->identifiers.setValue(index, DS_LABEL_IDENTIFIER_INVALID); if (identifier < this->firstFreeIdentifier) this->firstFreeIdentifier = identifier; --this->labelsCount; if (identifier == this->lastIdentifier) { if (0 == this->labelsCount) this->clear(); else { DsLabelIndex lastIndex = this->identifierToIndexMap.get_last_object(); this->lastIdentifier = this->getIdentifier(lastIndex); } } return 1; } } return 0; } int DsLabels::removeLabelWithIdentifier(DsLabelIdentifier identifier) { DsLabelIndex index = findLabelByIdentifier(identifier); if (index >= 0) return removeLabel(index); return 0; } /** * Safely changes the identifier at index to identifier, by removing index from * the identifier-to-index map and any other related maps, then changing the * identifier and re-inserting it where it was removed. * @return CMZN_OK on success, any other error code if failed. */ int DsLabels::setIdentifier(DsLabelIndex index, DsLabelIdentifier identifier) { if ((index < 0) || (index >= this->indexSize)) return CMZN_ERROR_ARGUMENT; DsLabelIdentifier oldIdentifier = this->getIdentifier(index); if (oldIdentifier < 0) return CMZN_ERROR_ARGUMENT; DsLabelIndex existingIndex = this->findLabelByIdentifier(identifier); if (existingIndex != DS_LABEL_INDEX_INVALID) { if (existingIndex == index) return CMZN_OK; return CMZN_ERROR_ALREADY_EXISTS; } if (this->contiguous) { int result = this->setNotContiguous(); if (CMZN_OK != result) return result; } int return_code = CMZN_OK; if (this->identifierToIndexMap.begin_identifier_change(*this, index)) { if (this->identifiers.setValue(index, identifier)) { if (oldIdentifier < this->firstFreeIdentifier) this->firstFreeIdentifier = oldIdentifier; } else return_code = CMZN_ERROR_GENERAL; this->identifierToIndexMap.end_identifier_change(*this); } else return_code = CMZN_ERROR_GENERAL; return return_code; } DsLabelIndex DsLabels::getFirstIndex() { if (0 == this->labelsCount) return DS_LABEL_INDEX_INVALID; if (this->contiguous) return 0; return this->identifierToIndexMap.get_first_object(); } DsLabelIterator *DsLabels::createLabelIterator() { DsLabelIterator *iterator = 0; if (this->inactiveIterators) { iterator = this->inactiveIterators; iterator->access(); this->inactiveIterators = iterator->next; if (this->inactiveIterators) this->inactiveIterators->previous = 0; } else iterator = new DsLabelIterator(); if (iterator) { iterator->labels = this; iterator->iter = (this->contiguous) ? 0 : new DsLabelIdentifierToIndexMapIterator(&this->identifierToIndexMap); iterator->index = DS_LABEL_INDEX_INVALID; iterator->next = this->activeIterators; iterator->previous = 0; if (this->activeIterators) this->activeIterators->previous = iterator; this->activeIterators = iterator; } return iterator; } void DsLabels::destroyLabelIterator(DsLabelIterator *&iterator) { if (iterator) { if (iterator->labels) { // reclaim to inactiveIterators if (iterator->previous) iterator->previous->next = iterator->next; if (iterator->next) iterator->next->previous = iterator->previous; if (iterator == iterator->labels->activeIterators) iterator->labels->activeIterators = iterator->next; iterator->previous = 0; iterator->next = iterator->labels->inactiveIterators; if (iterator->next) iterator->next->previous = iterator; iterator->labels->inactiveIterators = iterator; iterator->invalidate(); } else { delete iterator; } iterator = 0; } } int DsLabels::getIdentifierRanges(DsLabelIdentifierRanges& ranges) { ranges.clear(); DsLabelIterator *iterator = this->createLabelIterator(); if (!iterator) return CMZN_ERROR_MEMORY; if (iterator->nextIndex() != DS_LABEL_INDEX_INVALID) { DsLabelIdentifier identifier = iterator->getIdentifier(); DsLabelIdentifierRange range = { identifier, identifier }; while (iterator->nextIndex() != DS_LABEL_INDEX_INVALID) { identifier = iterator->getIdentifier(); if (identifier != (range.last + 1)) { ranges.push_back(range); range.first = identifier; } range.last = identifier; } ranges.push_back(range); } cmzn::Deaccess(iterator); return CMZN_OK; } DsLabelIterator::DsLabelIterator() : cmzn::RefCounted(), labels(0), iter(0), index(DS_LABEL_INDEX_INVALID), next(0), previous(0) { } DsLabelIterator::~DsLabelIterator() { delete this->iter; } void DsLabelIterator::invalidate() { if (this->labels) { delete this->iter; this->iter = 0; this->labels = 0; } }
/** * FILE : datastore/labels.hpp * * Implements a set of labels identifying nodes, elements, field components. * Used to index a dimension of a datastore map. */ /* OpenCMISS-Zinc Library * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "zinc/status.h" #include "datastore/labels.hpp" #include "general/message.h" DsLabels::DsLabels() : cmzn::RefCounted(), contiguous(true), firstFreeIdentifier(1), firstIdentifier(DS_LABEL_IDENTIFIER_INVALID), lastIdentifier(DS_LABEL_IDENTIFIER_INVALID), labelsCount(0), indexSize(0), activeIterators(0), inactiveIterators(0) { }; DsLabels::~DsLabels() { DsLabelIterator *iterator; while (inactiveIterators) { iterator = inactiveIterators->next; delete inactiveIterators; inactiveIterators = iterator; } // can't free externally held objects, hence just invalidate for safety iterator = activeIterators; while (iterator) { iterator->invalidate(); iterator = iterator->next; } } /** restore to initial empty, contiguous state. Keeps current name, if any */ void DsLabels::clear() { // can't free externally held objects, hence just invalidate for safety DsLabelIterator *iterator = this->activeIterators; while (iterator) { iterator->invalidate(); iterator = iterator->next; } this->contiguous = true; this->firstFreeIdentifier = 1; this->firstIdentifier = DS_LABEL_IDENTIFIER_INVALID; this->lastIdentifier = DS_LABEL_IDENTIFIER_INVALID; this->identifiers.clear(); this->identifierToIndexMap.clear(); this->labelsCount = 0; this->indexSize = 0; } /** * Get the next unused identifier of at least startIdentifier, * or 1 if startIdentifier is not positive. */ DsLabelIdentifier DsLabels::getFirstFreeIdentifier(DsLabelIdentifier startIdentifier) { DsLabelIdentifier identifier = (startIdentifier <= this->firstFreeIdentifier) ? this->firstFreeIdentifier : startIdentifier; if (identifier <= this->lastIdentifier) { // this can be optimised using an iterator: while (DS_LABEL_INDEX_INVALID != findLabelByIdentifier(identifier)) ++identifier; } if (startIdentifier <= this->firstFreeIdentifier) this->firstFreeIdentifier = identifier; return identifier; } int DsLabels::setNotContiguous() { if (this->contiguous) { // this can be optimised: DsLabelIdentifier identifier = this->firstIdentifier; for (DsLabelIndex index = 0; index < this->indexSize; ++index) { if (!(this->identifiers.setValue(index, identifier) && this->identifierToIndexMap.insert(*this, index))) { display_message(ERROR_MESSAGE, "DsLabels::setNotContiguous. Failed"); return CMZN_ERROR_MEMORY; } ++identifier; } this->contiguous = false; return CMZN_OK; } return CMZN_ERROR_ARGUMENT; } /** private: caller must have checked identifier is not in use! */ DsLabelIndex DsLabels::createLabelPrivate(DsLabelIdentifier identifier) { if (identifier < 0) return DS_LABEL_INDEX_INVALID; DsLabelIndex index = DS_LABEL_INDEX_INVALID; if (this->contiguous) { if (0 == this->labelsCount) { this->firstIdentifier = identifier; } else if ((identifier < this->firstIdentifier) || (identifier > (this->lastIdentifier + 1))) { if (CMZN_OK != this->setNotContiguous()) return index; } if (this->contiguous) { index = this->indexSize; this->lastIdentifier = identifier; if (identifier == this->firstFreeIdentifier) ++this->firstFreeIdentifier; ++this->labelsCount; ++this->indexSize; return index; } } // Future memory optimisation: reclaim unused indexes for new labels. // Note for reclaim to work would have to clear indexes into maps // as labels are deleted [for maps indexed by these labels]. if (this->identifiers.setValue(this->indexSize, identifier)) { index = this->indexSize; // must increase these now to allow identifiers to be queried by map ++this->labelsCount; ++this->indexSize; if (!this->identifierToIndexMap.insert(*this, index)) { display_message(ERROR_MESSAGE, "DsLabels::createLabelPrivate. Failed to insert index into map"); --this->labelsCount; --this->indexSize; return DS_LABEL_INDEX_INVALID; } if (identifier > this->lastIdentifier) this->lastIdentifier = identifier; if (identifier == this->firstFreeIdentifier) ++this->firstFreeIdentifier; } else display_message(ERROR_MESSAGE, "DsLabels::createLabelPrivate. Failed to set identifier"); return index; } /** create with auto-generated unique identifier */ DsLabelIndex DsLabels::createLabel() { return createLabelPrivate(this->getFirstFreeIdentifier()); } /** fails if identifier already in use */ DsLabelIndex DsLabels::createLabel(DsLabelIdentifier identifier) { DsLabelIndex index = findLabelByIdentifier(identifier); if (index >= 0) return DS_LABEL_INDEX_INVALID; return createLabelPrivate(identifier); } /** finds existing entry with identifier, or creates new one if none */ DsLabelIndex DsLabels::findOrCreateLabel(DsLabelIdentifier identifier) { DsLabelIndex index = findLabelByIdentifier(identifier); if (index >= 0) return index; return createLabelPrivate(identifier); } int DsLabels::addLabelsRange(DsLabelIdentifier min, DsLabelIdentifier max, DsLabelIdentifier stride) { if ((max < min) || (stride < 1)) return CMZN_ERROR_ARGUMENT; if (this->contiguous && (stride == 1) && (0 == this->labelsCount)) { // fast case this->firstIdentifier = min; this->lastIdentifier = max; this->firstFreeIdentifier = max + 1; this->labelsCount = max - min + 1; this->indexSize = max - min + 1; } else { for (DsLabelIdentifier identifier = min; identifier <= max; identifier += stride) { DsLabelIndex index = this->findOrCreateLabel(identifier); if (index < 0) return CMZN_ERROR_GENERAL; } } return CMZN_OK; } int DsLabels::removeLabel(DsLabelIndex index) { if ((index < 0) || (index >= this->indexSize)) return 0; if (this->contiguous) setNotContiguous(); DsLabelIdentifier identifier; if (this->identifiers.getValue(index, identifier)) { if (identifier >= 0) { this->identifierToIndexMap.erase(*this, index); this->identifiers.setValue(index, DS_LABEL_IDENTIFIER_INVALID); if (identifier < this->firstFreeIdentifier) this->firstFreeIdentifier = identifier; --this->labelsCount; if (identifier == this->lastIdentifier) { if (0 == this->labelsCount) this->clear(); else { DsLabelIndex lastIndex = this->identifierToIndexMap.get_last_object(); this->lastIdentifier = this->getIdentifier(lastIndex); } } return 1; } } return 0; } int DsLabels::removeLabelWithIdentifier(DsLabelIdentifier identifier) { DsLabelIndex index = findLabelByIdentifier(identifier); if (index >= 0) return removeLabel(index); return 0; } /** * Safely changes the identifier at index to identifier, by removing index from * the identifier-to-index map and any other related maps, then changing the * identifier and re-inserting it where it was removed. * @return CMZN_OK on success, any other error code if failed. */ int DsLabels::setIdentifier(DsLabelIndex index, DsLabelIdentifier identifier) { if ((index < 0) || (index >= this->indexSize)) return CMZN_ERROR_ARGUMENT; DsLabelIdentifier oldIdentifier = this->getIdentifier(index); if (oldIdentifier < 0) return CMZN_ERROR_ARGUMENT; DsLabelIndex existingIndex = this->findLabelByIdentifier(identifier); if (existingIndex != DS_LABEL_INDEX_INVALID) { if (existingIndex == index) return CMZN_OK; return CMZN_ERROR_ALREADY_EXISTS; } if (this->contiguous) { int result = this->setNotContiguous(); if (CMZN_OK != result) return result; } int return_code = CMZN_OK; if (this->identifierToIndexMap.begin_identifier_change(*this, index)) { if (this->identifiers.setValue(index, identifier)) { if (oldIdentifier < this->firstFreeIdentifier) this->firstFreeIdentifier = oldIdentifier; } else return_code = CMZN_ERROR_GENERAL; this->identifierToIndexMap.end_identifier_change(*this); } else return_code = CMZN_ERROR_GENERAL; return return_code; } DsLabelIndex DsLabels::getFirstIndex() { if (0 == this->labelsCount) return DS_LABEL_INDEX_INVALID; if (this->contiguous) return 0; return this->identifierToIndexMap.get_first_object(); } DsLabelIterator *DsLabels::createLabelIterator() { DsLabelIterator *iterator = 0; if (this->inactiveIterators) { iterator = this->inactiveIterators; iterator->access(); this->inactiveIterators = iterator->next; if (this->inactiveIterators) this->inactiveIterators->previous = 0; } else iterator = new DsLabelIterator(); if (iterator) { iterator->labels = this; iterator->iter = (this->contiguous) ? 0 : new DsLabelIdentifierToIndexMapIterator(&this->identifierToIndexMap); iterator->index = DS_LABEL_INDEX_INVALID; iterator->next = this->activeIterators; iterator->previous = 0; if (this->activeIterators) this->activeIterators->previous = iterator; this->activeIterators = iterator; } return iterator; } void DsLabels::destroyLabelIterator(DsLabelIterator *&iterator) { if (iterator) { if (iterator->labels) { // reclaim to inactiveIterators if (iterator->previous) iterator->previous->next = iterator->next; if (iterator->next) iterator->next->previous = iterator->previous; if (iterator == iterator->labels->activeIterators) iterator->labels->activeIterators = iterator->next; iterator->previous = 0; iterator->next = iterator->labels->inactiveIterators; if (iterator->next) iterator->next->previous = iterator; iterator->labels->inactiveIterators = iterator; iterator->invalidate(); } else { delete iterator; } iterator = 0; } } int DsLabels::getIdentifierRanges(DsLabelIdentifierRanges& ranges) { ranges.clear(); DsLabelIterator *iterator = this->createLabelIterator(); if (!iterator) return CMZN_ERROR_MEMORY; if (iterator->nextIndex() != DS_LABEL_INDEX_INVALID) { DsLabelIdentifier identifier = iterator->getIdentifier(); DsLabelIdentifierRange range = { identifier, identifier }; while (iterator->nextIndex() != DS_LABEL_INDEX_INVALID) { identifier = iterator->getIdentifier(); if (identifier != (range.last + 1)) { ranges.push_back(range); range.first = identifier; } range.last = identifier; } ranges.push_back(range); } cmzn::Deaccess(iterator); return CMZN_OK; } DsLabelIterator::DsLabelIterator() : cmzn::RefCounted(), labels(0), iter(0), index(DS_LABEL_INDEX_INVALID), next(0), previous(0) { } DsLabelIterator::~DsLabelIterator() { delete this->iter; } void DsLabelIterator::invalidate() { if (this->labels) { delete this->iter; this->iter = 0; this->labels = 0; } }
Fix bug where contiguous labels always returned the last identifier + 1 as the next free identifier, rather than starting at 1. This broke Cmgui example a/element_types. https://tracker.physiomeproject.org/show_bug.cgi?id=1496
Fix bug where contiguous labels always returned the last identifier + 1 as the next free identifier, rather than starting at 1. This broke Cmgui example a/element_types. https://tracker.physiomeproject.org/show_bug.cgi?id=1496
C++
mpl-2.0
hsorby/zinc,OpenCMISS/zinc,OpenCMISS/zinc,hsorby/zinc,hsorby/zinc,hsorby/zinc,OpenCMISS/zinc,OpenCMISS/zinc
6b221ff1c648b3850c57ce17008eb8fe457d35af
libdariadb/storage/chunk.cpp
libdariadb/storage/chunk.cpp
#include "chunk.h" #include "bloom_filter.h" #include <algorithm> #include <cassert> using namespace dariadb; using namespace dariadb::utils; using namespace dariadb::storage; using namespace dariadb::compression; std::unique_ptr<ChunkPool> ChunkPool::_instance=nullptr; ChunkPool::ChunkPool(){ _max_size = ChunkPool_default_max_size; } ChunkPool::~ChunkPool(){ for(auto p:_ptrs){ :: operator delete(p); } } void ChunkPool::start(size_t max_size){ if (max_size != 0) { ChunkPool::instance()->_max_size = max_size; } } void ChunkPool::stop(){ ChunkPool::_instance=nullptr; } ChunkPool*ChunkPool::instance(){ if(_instance==nullptr){ _instance=std::unique_ptr<ChunkPool>{new ChunkPool}; } return _instance.get(); } size_t ChunkPool::polled(){ return _ptrs.size(); } void* ChunkPool::alloc(std::size_t sz){ std::lock_guard<std::mutex> lg(_mutex); if(this->_ptrs.size()!=0){ auto result= this->_ptrs.back(); this->_ptrs.pop_back(); return result; } return ::operator new(sz); } void ChunkPool::free(void* ptr, std::size_t){ std::lock_guard<std::mutex> lg(_mutex); if (_ptrs.size() < _max_size) { _ptrs.push_front(ptr); } else { ::operator delete(ptr); } } void* Chunk::operator new(std::size_t sz){ return ChunkPool::instance()->alloc(sz); } void Chunk::operator delete(void* ptr, std::size_t sz){ ChunkPool::instance()->free(ptr,sz); } Chunk::Chunk(const ChunkIndexInfo&index, const uint8_t* buffer, const size_t buffer_length) : _buffer_t(buffer_length), _mutex{} { count = index.count; first = index.first; flag_bloom = index.flag_bloom; last = index.last; maxTime = index.maxTime; minTime = index.minTime; bw_pos = index.bw_pos; bw_bit_num = index.bw_bit_num; is_readonly = index.is_readonly; for (size_t i = 0; i < buffer_length; i++) { _buffer_t[i] = buffer[i]; } range = Range{ _buffer_t.data(),_buffer_t.data() + buffer_length - 1 }; bw = std::make_shared<BinaryBuffer>(range); bw->set_bitnum(bw_bit_num); bw->set_pos(bw_pos); c_writer = compression::CopmressedWriter(bw); c_writer.restore_position(index.writer_position); minTime = std::min(minTime, first.time); maxTime = std::max(maxTime, first.time); } Chunk::Chunk(size_t size, Meas first_m) : _buffer_t(size), _mutex() { is_readonly = false; count = 0; first = first_m; last = first_m; minTime = std::numeric_limits<Time>::max(); maxTime = std::numeric_limits<Time>::min(); std::fill(_buffer_t.begin(), _buffer_t.end(), 0); using compression::BinaryBuffer; range = Range{ _buffer_t.data(),_buffer_t.data() + size - 1 }; bw = std::make_shared<BinaryBuffer>(range); c_writer = compression::CopmressedWriter(bw); c_writer.append(first); minTime = std::min(minTime, first_m.time); maxTime = std::max(maxTime, first_m.time); flag_bloom = dariadb::storage::bloom_empty<dariadb::Flag>(); } Chunk::~Chunk() { } bool Chunk::append(const Meas&m) { assert(!is_readonly); std::lock_guard<std::mutex> lg(_mutex); auto t_f = this->c_writer.append(m); bw_pos = uint32_t(bw->pos()); bw_bit_num= bw->bitnum(); writer_position=c_writer.get_position(); if (!t_f) { is_readonly = true; assert(c_writer.is_full()); return false; } else { count++; minTime = std::min(minTime, m.time); maxTime = std::max(maxTime, m.time); flag_bloom = dariadb::storage::bloom_add(flag_bloom, m.flag); last = m; return true; } } bool Chunk::check_flag(const Flag& f) { if (f != 0) { if (!dariadb::storage::bloom_check(flag_bloom, f)) { return false; } } return true; }
#include "chunk.h" #include "bloom_filter.h" #include <algorithm> #include <cassert> #include <cstring> using namespace dariadb; using namespace dariadb::utils; using namespace dariadb::storage; using namespace dariadb::compression; std::unique_ptr<ChunkPool> ChunkPool::_instance=nullptr; ChunkPool::ChunkPool(){ _max_size = ChunkPool_default_max_size; } ChunkPool::~ChunkPool(){ for(auto p:_ptrs){ :: operator delete(p); } } void ChunkPool::start(size_t max_size){ if (max_size != 0) { ChunkPool::instance()->_max_size = max_size; } } void ChunkPool::stop(){ ChunkPool::_instance=nullptr; } ChunkPool*ChunkPool::instance(){ if(_instance==nullptr){ _instance=std::unique_ptr<ChunkPool>{new ChunkPool}; } return _instance.get(); } size_t ChunkPool::polled(){ return _ptrs.size(); } void* ChunkPool::alloc(std::size_t sz){ std::lock_guard<std::mutex> lg(_mutex); void*result=nullptr; if(this->_ptrs.size()!=0){ result= this->_ptrs.back(); this->_ptrs.pop_back(); }else{ result=::operator new(sz); } memset(result,0,sz); return result; } void ChunkPool::free(void* ptr, std::size_t){ std::lock_guard<std::mutex> lg(_mutex); if (_ptrs.size() < _max_size) { _ptrs.push_front(ptr); } else { ::operator delete(ptr); } } void* Chunk::operator new(std::size_t sz){ return ChunkPool::instance()->alloc(sz); } void Chunk::operator delete(void* ptr, std::size_t sz){ ChunkPool::instance()->free(ptr,sz); } Chunk::Chunk(const ChunkIndexInfo&index, const uint8_t* buffer, const size_t buffer_length) : _buffer_t(buffer_length), _mutex{} { count = index.count; first = index.first; flag_bloom = index.flag_bloom; last = index.last; maxTime = index.maxTime; minTime = index.minTime; bw_pos = index.bw_pos; bw_bit_num = index.bw_bit_num; is_readonly = index.is_readonly; for (size_t i = 0; i < buffer_length; i++) { _buffer_t[i] = buffer[i]; } range = Range{ _buffer_t.data(),_buffer_t.data() + buffer_length - 1 }; bw = std::make_shared<BinaryBuffer>(range); bw->set_bitnum(bw_bit_num); bw->set_pos(bw_pos); c_writer = compression::CopmressedWriter(bw); c_writer.restore_position(index.writer_position); minTime = std::min(minTime, first.time); maxTime = std::max(maxTime, first.time); } Chunk::Chunk(size_t size, Meas first_m) : _buffer_t(size), _mutex() { is_readonly = false; count = 0; first = first_m; last = first_m; minTime = std::numeric_limits<Time>::max(); maxTime = std::numeric_limits<Time>::min(); std::fill(_buffer_t.begin(), _buffer_t.end(), 0); using compression::BinaryBuffer; range = Range{ _buffer_t.data(),_buffer_t.data() + size - 1 }; bw = std::make_shared<BinaryBuffer>(range); c_writer = compression::CopmressedWriter(bw); c_writer.append(first); minTime = std::min(minTime, first_m.time); maxTime = std::max(maxTime, first_m.time); flag_bloom = dariadb::storage::bloom_empty<dariadb::Flag>(); } Chunk::~Chunk() { } bool Chunk::append(const Meas&m) { assert(!is_readonly); std::lock_guard<std::mutex> lg(_mutex); auto t_f = this->c_writer.append(m); bw_pos = uint32_t(bw->pos()); bw_bit_num= bw->bitnum(); writer_position=c_writer.get_position(); if (!t_f) { is_readonly = true; assert(c_writer.is_full()); return false; } else { count++; minTime = std::min(minTime, m.time); maxTime = std::max(maxTime, m.time); flag_bloom = dariadb::storage::bloom_add(flag_bloom, m.flag); last = m; return true; } } bool Chunk::check_flag(const Flag& f) { if (f != 0) { if (!dariadb::storage::bloom_check(flag_bloom, f)) { return false; } } return true; }
clean allocated memories.
clean allocated memories.
C++
apache-2.0
dariadb/dariadb,dariadb/dariadb,lysevi/dariadb,lysevi/dariadb,lysevi/dariadb
313663bfdf532d03d44994be4ab2a0fb3a3c59f9
core/src/datamatrix/DMReader.cpp
core/src/datamatrix/DMReader.cpp
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing 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 "DMReader.h" #include "DMDecoder.h" #include "DMDetector.h" #include "Result.h" #include "BitMatrix.h" #include "BinaryBitmap.h" #include "DecodeHints.h" #include "DecoderResult.h" #include "DetectorResult.h" #include <utility> #include <vector> namespace ZXing { namespace DataMatrix { static int GetModuleSize(int x, int y, const BitMatrix& image) { int oldX = x; int width = image.width(); while (x < width && image.get(x, y)) { x++; } if (x == width) { return 0; } return x - oldX; } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. * * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) */ static BitMatrix ExtractPureBits(const BitMatrix& image) { int left, top, right, bottom; if (!image.getTopLeftOnBit(left, top) || !image.getBottomRightOnBit(right, bottom)) { return {}; } int moduleSize = GetModuleSize(left, top, image); int matrixWidth = (right - left + 1) / moduleSize; int matrixHeight = (bottom - top + 1) / moduleSize; if (matrixWidth <= 0 || matrixHeight <= 0) { return {}; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = moduleSize / 2; top += nudge; left += nudge; // Now just read off the bits (this is a crop + subsample) return Deflate(image, matrixWidth, matrixHeight, top, left, moduleSize); } Reader::Reader(const DecodeHints& hints) : _tryRotate(hints.tryRotate()), _tryHarder(hints.tryHarder()), _isPure(hints.isPure()) { } /** * Locates and decodes a Data Matrix code in an image. * * @return a string representing the content encoded by the Data Matrix code * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded * @throws ChecksumException if error correction fails */ Result Reader::decode(const BinaryBitmap& image) const { auto binImg = image.getBlackMatrix(); if (binImg == nullptr) { return Result(DecodeStatus::NotFound); } DecoderResult decoderResult; std::vector<ResultPoint> points; if (_isPure) { BitMatrix bits = ExtractPureBits(*binImg); if (bits.empty()) return Result(DecodeStatus::NotFound); decoderResult = Decoder::Decode(bits); } else { DetectorResult detectorResult = Detector::Detect(*binImg, _tryHarder, _tryRotate); if (!detectorResult.isValid()) return Result(DecodeStatus::NotFound); decoderResult = Decoder::Decode(detectorResult.bits()); points = detectorResult.points(); } return Result(std::move(decoderResult), std::move(points), BarcodeFormat::DATA_MATRIX); } } // DataMatrix } // ZXing
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing 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 "DMReader.h" #include "DMDecoder.h" #include "DMDetector.h" #include "Result.h" #include "BitMatrix.h" #include "BinaryBitmap.h" #include "DecodeHints.h" #include "DecoderResult.h" #include "DetectorResult.h" #include <utility> #include <vector> namespace ZXing { namespace DataMatrix { static int GetModuleSize(int x, int y, const BitMatrix& image) { int oldX = x; while (x < image.width() && image.get(x, y)) { x++; } return x - oldX; } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. * * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) */ static BitMatrix ExtractPureBits(const BitMatrix& image) { const int MIN_SIZE = 8; // datamatrix codes are at least 8x8 modules int left, top, right, bottom; if (!image.getTopLeftOnBit(left, top) || !image.getBottomRightOnBit(right, bottom) || right - left < MIN_SIZE || bottom - top < MIN_SIZE) { return {}; } int moduleSize = GetModuleSize(left, top, image); int matrixWidth = (right - left + 1) / moduleSize; int matrixHeight = (bottom - top + 1) / moduleSize; if (matrixWidth < MIN_SIZE || matrixHeight < MIN_SIZE) { return {}; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = moduleSize / 2; top += nudge; left += nudge; // Now just read off the bits (this is a crop + subsample) return Deflate(image, matrixWidth, matrixHeight, top, left, moduleSize); } Reader::Reader(const DecodeHints& hints) : _tryRotate(hints.tryRotate()), _tryHarder(hints.tryHarder()), _isPure(hints.isPure()) { } /** * Locates and decodes a Data Matrix code in an image. * * @return a string representing the content encoded by the Data Matrix code * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded * @throws ChecksumException if error correction fails */ Result Reader::decode(const BinaryBitmap& image) const { auto binImg = image.getBlackMatrix(); if (binImg == nullptr) { return Result(DecodeStatus::NotFound); } DecoderResult decoderResult; std::vector<ResultPoint> points; if (_isPure) { BitMatrix bits = ExtractPureBits(*binImg); if (bits.empty()) return Result(DecodeStatus::NotFound); decoderResult = Decoder::Decode(bits); } else { DetectorResult detectorResult = Detector::Detect(*binImg, _tryHarder, _tryRotate); if (!detectorResult.isValid()) return Result(DecodeStatus::NotFound); decoderResult = Decoder::Decode(detectorResult.bits()); points = detectorResult.points(); } return Result(std::move(decoderResult), std::move(points), BarcodeFormat::DATA_MATRIX); } } // DataMatrix } // ZXing
fix div-by-0 crash in isPure-code path
DataMatrix: fix div-by-0 crash in isPure-code path Also, widen some size based bail-out-early checks.
C++
apache-2.0
nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp
08273c7f08e2800a5923a384627ccbd1f1c1f4fe
src/src/config.cc
src/src/config.cc
#include "config.h" #include <cstdlib> #include <iostream> #include <string> #include <fstream> #include <sstream> #include <cstring> using namespace std; //// parameters // for bam file and reads int min_flank_length = 5; int32_t min_bundle_gap = 50; int min_num_hits_in_bundle = 20; uint32_t min_mapping_quality = 1; int32_t min_splice_boundary_hits = 1; // for identifying subgraphs double max_indel_ratio = 0.2; int32_t min_subregion_gap = 3; int32_t min_subregion_length = 15; double min_subregion_overlap = 2; int min_subregion_ladders = 0; // for splice graph double min_inner_vertex_weight = 10.0; double min_inner_boundary_weight = 5.0; double min_splice_edge_weight = 3.5; double max_split_error_ratio = 0.15; double min_transcript_coverage = 10.0; double min_splice_graph_coverage = 20.0; double smallest_edge_ratio_scalor1 = 0.2; double smallest_edge_ratio_scalor2 = 1.0; // for identifying new boundaries bool identify_extra_boundary = false; int min_boundary_length = 80; int min_boundary_score = 100; double min_boundary_ave_ratio = 3.0; double min_boundary_sigma = 5.0; // for subsetsum and router int max_dp_table_size = 10000; int min_router_count = 1; // for simulation int simulation_num_vertices = 0; int simulation_num_edges = 0; int simulation_max_edge_weight = 0; // input and output string algo = "scallop"; string input_file; string ref_file; string ref_file1; string ref_file2; string output_file; // for controling int max_num_bundles = -1; int32_t average_read_length = 100; bool strand_reverse = false; bool output_tex_files = false; string fixed_gene_name = ""; int min_gtf_transcripts_num = 0; bool fast_mode = true; int print_parameters() { printf("parameters:\n"); // for bam file and reads printf("min_flank_length = %d\n", min_flank_length); printf("min_bundle_gap = %d\n", min_bundle_gap); printf("min_num_hits_in_bundle = %d\n", min_num_hits_in_bundle); printf("min_mapping_quality = %d\n", min_mapping_quality); printf("min_splice_boundary_hits = %d\n", min_splice_boundary_hits); // for identifying subgraphs printf("max_indel_ratio = %.2lf\n", max_indel_ratio); printf("min_subregion_gap = %d\n", min_subregion_gap); printf("min_subregion_length = %d\n", min_subregion_length); printf("min_subregion_overlap = %.2lf\n", min_subregion_overlap); printf("min_subregion_ladders = %d\n", min_subregion_ladders); // for splice graph printf("min_splice_edge_weight = %.2lf\n", min_splice_edge_weight); printf("min_inner_vertex_weight = %.2lf\n", min_inner_vertex_weight); printf("min_inner_boundary_weight = %.2lf\n", min_inner_boundary_weight); printf("min_transcript_coverage = %.2lf\n", min_transcript_coverage); printf("min_splice_graph_coverage = %.2lf\n", min_splice_graph_coverage); printf("max_split_error_ratio = %.2lf\n", max_split_error_ratio); printf("smallest_edge_ratio_scalor1 = %.2lf\n", smallest_edge_ratio_scalor1); printf("smallest_edge_ratio_scalor2 = %.2lf\n", smallest_edge_ratio_scalor2); // for identifying new boundaries printf("identify_extra_boundary = %c\n", identify_extra_boundary ? 'T' : 'F'); printf("min_boundary_length = %d\n", min_boundary_length); printf("min_boundary_score = %d\n", min_boundary_score); printf("min_boundary_ave_ratio = %.2lf\n", min_boundary_ave_ratio); printf("min_boundary_signma = %.2lf\n", min_boundary_sigma); // for subsetsum and router printf("max_dp_table_size = %d\n", max_dp_table_size); printf("min_router_count = %d\n", min_router_count); // for simulation printf("simulation_num_vertices = %d\n", simulation_num_vertices); printf("simulation_num_edges = %d\n", simulation_num_edges); printf("simulation_max_edge_weight = %d\n", simulation_max_edge_weight); // for input and output printf("algo = %s\n", algo.c_str()); printf("input_file = %s\n", input_file.c_str()); printf("ref_file = %s\n", ref_file.c_str()); printf("ref_file1 = %s\n", ref_file1.c_str()); printf("ref_file2 = %s\n", ref_file2.c_str()); printf("output_file = %s\n", output_file.c_str()); // for controling printf("max_num_bundles = %d\n", max_num_bundles); printf("average_read_length = %d\n", average_read_length); printf("strand_reverse = %c\n", strand_reverse ? 'T' : 'F'); printf("output_tex_files = %c\n", output_tex_files ? 'T' : 'F'); printf("fixed_gene_name = %s\n", fixed_gene_name.c_str()); printf("min_gtf_transcripts_num = %d\n", min_gtf_transcripts_num); printf("fast_mode = %c\n", fast_mode ? 'T' : 'F'); printf("\n"); return 0; } int print_command_line(int argc, const char ** argv) { printf("command line: "); for(int i = 0; i < argc; i++) { printf("%s ", argv[i]); } printf("\n"); return 0; } int parse_arguments(int argc, const char ** argv) { for(int i = 1; i < argc; i++) { // necessary ones if(string(argv[i]) == "-i") { input_file = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-o") { output_file = string(argv[i + 1]); i++; } // internal use else if(string(argv[i]) == "-a") { algo = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-r") { ref_file = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-r1") { ref_file1 = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-r2") { ref_file2 = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-g") { fixed_gene_name = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-t") { output_tex_files = true; } // user specified else if(string(argv[i]) == "--min_flank_length") { min_flank_length = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_bundle_gap") { min_bundle_gap = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_num_hits_in_bundle") { min_num_hits_in_bundle = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_mapping_quality") { min_mapping_quality = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_splice_boundary_hits") { min_splice_boundary_hits = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--max_indel_ratio") { max_indel_ratio = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_subregion_gap") { min_subregion_gap = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_subregion_length") { min_subregion_length = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_subregion_overlap") { min_subregion_overlap = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--identify_extra_boundary") { string s(argv[i + 1]); if(s == "true") identify_extra_boundary = true; else identify_extra_boundary = false; i++; } else if(string(argv[i]) == "--min_subregion_ladders") { min_subregion_ladders = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_splice_edge_weight") { min_splice_edge_weight = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_inner_vertex_weight") { min_inner_vertex_weight = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_inner_boundary_weight") { min_inner_boundary_weight = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_transcript_coverage") { min_transcript_coverage = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_splice_graph_coverage") { min_splice_graph_coverage = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--max_split_error_ratio") { max_split_error_ratio = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--smallest_edge_ratio_scalor1") { smallest_edge_ratio_scalor1 = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--smallest_edge_ratio_scalor2") { smallest_edge_ratio_scalor2 = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_length") { min_boundary_length = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_score") { min_boundary_score = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_ave_ratio") { min_boundary_ave_ratio = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_sigma") { min_boundary_sigma = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--max_dp_table_size") { max_dp_table_size = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_router_count") { min_router_count = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--strand_reverse") { string s(argv[i + 1]); if(s == "true") strand_reverse = true; else strand_reverse = false; i++; } } return 0; }
#include "config.h" #include <cstdlib> #include <iostream> #include <string> #include <fstream> #include <sstream> #include <cstring> using namespace std; //// parameters // for bam file and reads int min_flank_length = 5; int32_t min_bundle_gap = 50; int min_num_hits_in_bundle = 20; uint32_t min_mapping_quality = 1; int32_t min_splice_boundary_hits = 1; // for identifying subgraphs double max_indel_ratio = 0.2; int32_t min_subregion_gap = 3; int32_t min_subregion_length = 15; double min_subregion_overlap = 2; int min_subregion_ladders = 0; // for splice graph double min_inner_vertex_weight = 10.0; double min_inner_boundary_weight = 4.0; double min_splice_edge_weight = 3.5; double max_split_error_ratio = 0.15; double min_transcript_coverage = 10.0; double min_splice_graph_coverage = 20.0; double smallest_edge_ratio_scalor1 = 0.2; double smallest_edge_ratio_scalor2 = 1.0; // for identifying new boundaries bool identify_extra_boundary = false; int min_boundary_length = 80; int min_boundary_score = 100; double min_boundary_ave_ratio = 3.0; double min_boundary_sigma = 5.0; // for subsetsum and router int max_dp_table_size = 10000; int min_router_count = 1; // for simulation int simulation_num_vertices = 0; int simulation_num_edges = 0; int simulation_max_edge_weight = 0; // input and output string algo = "scallop"; string input_file; string ref_file; string ref_file1; string ref_file2; string output_file; // for controling int max_num_bundles = -1; int32_t average_read_length = 100; bool strand_reverse = false; bool output_tex_files = false; string fixed_gene_name = ""; int min_gtf_transcripts_num = 0; bool fast_mode = true; int print_parameters() { printf("parameters:\n"); // for bam file and reads printf("min_flank_length = %d\n", min_flank_length); printf("min_bundle_gap = %d\n", min_bundle_gap); printf("min_num_hits_in_bundle = %d\n", min_num_hits_in_bundle); printf("min_mapping_quality = %d\n", min_mapping_quality); printf("min_splice_boundary_hits = %d\n", min_splice_boundary_hits); // for identifying subgraphs printf("max_indel_ratio = %.2lf\n", max_indel_ratio); printf("min_subregion_gap = %d\n", min_subregion_gap); printf("min_subregion_length = %d\n", min_subregion_length); printf("min_subregion_overlap = %.2lf\n", min_subregion_overlap); printf("min_subregion_ladders = %d\n", min_subregion_ladders); // for splice graph printf("min_splice_edge_weight = %.2lf\n", min_splice_edge_weight); printf("min_inner_vertex_weight = %.2lf\n", min_inner_vertex_weight); printf("min_inner_boundary_weight = %.2lf\n", min_inner_boundary_weight); printf("min_transcript_coverage = %.2lf\n", min_transcript_coverage); printf("min_splice_graph_coverage = %.2lf\n", min_splice_graph_coverage); printf("max_split_error_ratio = %.2lf\n", max_split_error_ratio); printf("smallest_edge_ratio_scalor1 = %.2lf\n", smallest_edge_ratio_scalor1); printf("smallest_edge_ratio_scalor2 = %.2lf\n", smallest_edge_ratio_scalor2); // for identifying new boundaries printf("identify_extra_boundary = %c\n", identify_extra_boundary ? 'T' : 'F'); printf("min_boundary_length = %d\n", min_boundary_length); printf("min_boundary_score = %d\n", min_boundary_score); printf("min_boundary_ave_ratio = %.2lf\n", min_boundary_ave_ratio); printf("min_boundary_signma = %.2lf\n", min_boundary_sigma); // for subsetsum and router printf("max_dp_table_size = %d\n", max_dp_table_size); printf("min_router_count = %d\n", min_router_count); // for simulation printf("simulation_num_vertices = %d\n", simulation_num_vertices); printf("simulation_num_edges = %d\n", simulation_num_edges); printf("simulation_max_edge_weight = %d\n", simulation_max_edge_weight); // for input and output printf("algo = %s\n", algo.c_str()); printf("input_file = %s\n", input_file.c_str()); printf("ref_file = %s\n", ref_file.c_str()); printf("ref_file1 = %s\n", ref_file1.c_str()); printf("ref_file2 = %s\n", ref_file2.c_str()); printf("output_file = %s\n", output_file.c_str()); // for controling printf("max_num_bundles = %d\n", max_num_bundles); printf("average_read_length = %d\n", average_read_length); printf("strand_reverse = %c\n", strand_reverse ? 'T' : 'F'); printf("output_tex_files = %c\n", output_tex_files ? 'T' : 'F'); printf("fixed_gene_name = %s\n", fixed_gene_name.c_str()); printf("min_gtf_transcripts_num = %d\n", min_gtf_transcripts_num); printf("fast_mode = %c\n", fast_mode ? 'T' : 'F'); printf("\n"); return 0; } int print_command_line(int argc, const char ** argv) { printf("command line: "); for(int i = 0; i < argc; i++) { printf("%s ", argv[i]); } printf("\n"); return 0; } int parse_arguments(int argc, const char ** argv) { for(int i = 1; i < argc; i++) { // necessary ones if(string(argv[i]) == "-i") { input_file = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-o") { output_file = string(argv[i + 1]); i++; } // internal use else if(string(argv[i]) == "-a") { algo = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-r") { ref_file = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-r1") { ref_file1 = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-r2") { ref_file2 = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-g") { fixed_gene_name = string(argv[i + 1]); i++; } else if(string(argv[i]) == "-t") { output_tex_files = true; } // user specified else if(string(argv[i]) == "--min_flank_length") { min_flank_length = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_bundle_gap") { min_bundle_gap = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_num_hits_in_bundle") { min_num_hits_in_bundle = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_mapping_quality") { min_mapping_quality = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_splice_boundary_hits") { min_splice_boundary_hits = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--max_indel_ratio") { max_indel_ratio = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_subregion_gap") { min_subregion_gap = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_subregion_length") { min_subregion_length = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_subregion_overlap") { min_subregion_overlap = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--identify_extra_boundary") { string s(argv[i + 1]); if(s == "true") identify_extra_boundary = true; else identify_extra_boundary = false; i++; } else if(string(argv[i]) == "--min_subregion_ladders") { min_subregion_ladders = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_splice_edge_weight") { min_splice_edge_weight = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_inner_vertex_weight") { min_inner_vertex_weight = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_inner_boundary_weight") { min_inner_boundary_weight = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_transcript_coverage") { min_transcript_coverage = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_splice_graph_coverage") { min_splice_graph_coverage = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--max_split_error_ratio") { max_split_error_ratio = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--smallest_edge_ratio_scalor1") { smallest_edge_ratio_scalor1 = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--smallest_edge_ratio_scalor2") { smallest_edge_ratio_scalor2 = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_length") { min_boundary_length = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_score") { min_boundary_score = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_ave_ratio") { min_boundary_ave_ratio = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_boundary_sigma") { min_boundary_sigma = atof(argv[i + 1]); i++; } else if(string(argv[i]) == "--max_dp_table_size") { max_dp_table_size = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--min_router_count") { min_router_count = atoi(argv[i + 1]); i++; } else if(string(argv[i]) == "--strand_reverse") { string s(argv[i + 1]); if(s == "true") strand_reverse = true; else strand_reverse = false; i++; } } return 0; }
change default min_inner_boundary_weight to 4.0
change default min_inner_boundary_weight to 4.0
C++
bsd-3-clause
Kingsford-Group/scallop
1d512690de35cad13531c72b04fe0870c890bb56
core/src/mapcss/TextureAtlas.hpp
core/src/mapcss/TextureAtlas.hpp
#ifndef MAPCSS_TEXTUREATLAS_HPP_INCLUDED #define MAPCSS_TEXTUREATLAS_HPP_INCLUDED #include "meshing/MeshTypes.hpp" #include <cstdint> #include <string> #include <vector> #include <unordered_map> namespace utymap { namespace mapcss { /// Represents a single texture region inside texture atlas. struct TextureRegion final { TextureRegion(std::uint16_t atlasWidth, std::uint16_t atlasHeight, std::uint16_t x, std::uint16_t y, std::uint16_t width, std::uint16_t height) : atlasWidth_(atlasWidth), atlasHeight_(atlasHeight), x_(x), y_(y), width_(width), height_(height) { } /// Maps relative uv coordinate to absolute one in texture atlas. utymap::meshing::Vector2 map(const utymap::meshing::Vector2& uv) const { return utymap::meshing::Vector2( (x_ + width_ * uv.x) / atlasWidth_, (y_ + height_ * uv.y) / atlasHeight_); } bool isEmpty() const { return atlasWidth_ == 0 || atlasHeight_ == 0; } private: std::uint16_t atlasWidth_, atlasHeight_, x_, y_, width_, height_; }; /// Holds list of textures which represent the same material. struct TextureGroup final { /// Adds specific region to the group. void add(std::uint16_t width, std::uint16_t height, utymap::meshing::Rectangle rect) { regions_.emplace_back(width, height, rect.xMin, rect.yMin, rect.width(), rect.height()); } /// Returns pseudo random region. TextureRegion random(std::uint32_t seed) const { return regions_[seed % regions_.size()]; } private: std::vector<TextureRegion> regions_; }; struct TextureAtlas final { using Groups = std::unordered_map<std::string, TextureGroup>; TextureAtlas() : TextureAtlas(Groups()) { } TextureAtlas(const Groups& textureGroups) : textureGroups_(std::move(textureGroups)), emptyGroup_() { emptyGroup_.add(0, 0, utymap::meshing::Rectangle()); } /// Returns a reference to texture group. /// Note: returns raw reference from map. const TextureGroup& get(const std::string& key) const { auto group = textureGroups_.find(key); if (group == textureGroups_.end()) { return emptyGroup_; } return group->second; } private: Groups textureGroups_; TextureGroup emptyGroup_; }; }} #endif // MAPCSS_TEXTUREATLAS_HPP_INCLUDED
#ifndef MAPCSS_TEXTUREATLAS_HPP_INCLUDED #define MAPCSS_TEXTUREATLAS_HPP_INCLUDED #include "meshing/MeshTypes.hpp" #include <cstdint> #include <string> #include <vector> #include <unordered_map> namespace utymap { namespace mapcss { /// Represents a single texture region inside texture atlas. struct TextureRegion final { TextureRegion(std::uint16_t atlasWidth, std::uint16_t atlasHeight, std::uint16_t x, std::uint16_t y, std::uint16_t width, std::uint16_t height) : atlasWidth_(atlasWidth), atlasHeight_(atlasHeight), x_(x), y_(y), width_(width), height_(height) { } /// Maps relative uv coordinate to absolute one in texture atlas. utymap::meshing::Vector2 map(const utymap::meshing::Vector2& uv) const { return utymap::meshing::Vector2( (x_ + width_ * uv.x) / atlasWidth_, (y_ + height_ * uv.y) / atlasHeight_); } bool isEmpty() const { return atlasWidth_ == 0 || atlasHeight_ == 0; } private: std::uint16_t atlasWidth_, atlasHeight_, x_, y_, width_, height_; }; /// Holds list of textures which represent the same material. struct TextureGroup final { /// Adds specific region to the group. void add(std::uint16_t width, std::uint16_t height, utymap::meshing::Rectangle rect) { regions_.emplace_back( width, height, static_cast<std::uint16_t>(rect.xMin), static_cast<std::uint16_t>(rect.yMin), static_cast<std::uint16_t>(rect.width()), static_cast<std::uint16_t>(rect.height())); } /// Returns pseudo random region. TextureRegion random(std::uint32_t seed) const { return regions_[seed % regions_.size()]; } private: std::vector<TextureRegion> regions_; }; struct TextureAtlas final { using Groups = std::unordered_map<std::string, TextureGroup>; TextureAtlas() : TextureAtlas(Groups()) { } TextureAtlas(const Groups& textureGroups) : textureGroups_(std::move(textureGroups)), emptyGroup_() { emptyGroup_.add(0, 0, utymap::meshing::Rectangle()); } /// Returns a reference to texture group. /// Note: returns raw reference from map. const TextureGroup& get(const std::string& key) const { auto group = textureGroups_.find(key); if (group == textureGroups_.end()) { return emptyGroup_; } return group->second; } private: Groups textureGroups_; TextureGroup emptyGroup_; }; }} #endif // MAPCSS_TEXTUREATLAS_HPP_INCLUDED
fix compiler warning
core: fix compiler warning
C++
apache-2.0
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
14596855ff50bcc4140c4aadb5872e724c69ad67
src/stopwatch.hxx
src/stopwatch.hxx
/* * Copyright 2007-2019 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "util/Compiler.h" #include <utility> class AllocatorPtr; class Stopwatch; class SocketAddress; class SocketDescriptor; #ifdef ENABLE_STOPWATCH class StopwatchPtr { protected: Stopwatch *stopwatch = nullptr; public: StopwatchPtr() = default; StopwatchPtr(std::nullptr_t) noexcept {} protected: StopwatchPtr(AllocatorPtr alloc, const char *name, const char *suffix=nullptr) noexcept; StopwatchPtr(AllocatorPtr alloc, SocketAddress address, const char *suffix=nullptr) noexcept; StopwatchPtr(AllocatorPtr alloc, SocketDescriptor fd, const char *suffix=nullptr) noexcept; public: StopwatchPtr(Stopwatch *parent, const char *name, const char *suffix=nullptr) noexcept; StopwatchPtr(const StopwatchPtr &parent, const char *name, const char *suffix=nullptr) noexcept :StopwatchPtr(parent.stopwatch, name, suffix) {} StopwatchPtr(StopwatchPtr &&src) noexcept :stopwatch(std::exchange(src.stopwatch, nullptr)) {} operator bool() const noexcept { return stopwatch != nullptr; } AllocatorPtr GetAllocator() const noexcept; void RecordEvent(const char *name) const noexcept; }; class RootStopwatchPtr : public StopwatchPtr { public: template<typename A, typename N> RootStopwatchPtr(A &&alloc, N &&name, const char *suffix=nullptr) noexcept :StopwatchPtr(std::forward<A>(alloc), std::forward<N>(name), suffix) {} RootStopwatchPtr(RootStopwatchPtr &&) = default; ~RootStopwatchPtr() noexcept { if (stopwatch != nullptr) Destruct(*stopwatch); } private: static void Destruct(Stopwatch &stopwatch) noexcept; }; void stopwatch_enable() noexcept; gcc_const bool stopwatch_is_enabled() noexcept; #else #include "AllocatorPtr.hxx" #include "net/SocketAddress.hxx" #include "net/SocketDescriptor.hxx" class StopwatchPtr { public: StopwatchPtr() = default; StopwatchPtr(std::nullptr_t) noexcept {} template<typename N> StopwatchPtr(AllocatorPtr, N &&, const char * =nullptr) noexcept {} template<typename N> StopwatchPtr(const StopwatchPtr &, N &&, const char * =nullptr) noexcept {} operator bool() const noexcept { return false; } void RecordEvent(const char *) const noexcept {} }; static inline void stopwatch_enable() noexcept { } static inline bool stopwatch_is_enabled() noexcept { return false; } #endif
/* * Copyright 2007-2019 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "util/Compiler.h" #include <utility> class AllocatorPtr; class Stopwatch; class SocketAddress; class SocketDescriptor; #ifdef ENABLE_STOPWATCH class StopwatchPtr { protected: Stopwatch *stopwatch = nullptr; public: StopwatchPtr() = default; StopwatchPtr(std::nullptr_t) noexcept {} protected: StopwatchPtr(AllocatorPtr alloc, const char *name, const char *suffix=nullptr) noexcept; StopwatchPtr(AllocatorPtr alloc, SocketAddress address, const char *suffix=nullptr) noexcept; StopwatchPtr(AllocatorPtr alloc, SocketDescriptor fd, const char *suffix=nullptr) noexcept; public: StopwatchPtr(Stopwatch *parent, const char *name, const char *suffix=nullptr) noexcept; StopwatchPtr(const StopwatchPtr &parent, const char *name, const char *suffix=nullptr) noexcept :StopwatchPtr(parent.stopwatch, name, suffix) {} StopwatchPtr(StopwatchPtr &&src) noexcept :stopwatch(std::exchange(src.stopwatch, nullptr)) {} operator bool() const noexcept { return stopwatch != nullptr; } AllocatorPtr GetAllocator() const noexcept; void RecordEvent(const char *name) const noexcept; }; class RootStopwatchPtr : public StopwatchPtr { public: template<typename A, typename N> RootStopwatchPtr(A &&alloc, N &&name, const char *suffix=nullptr) noexcept :StopwatchPtr(std::forward<A>(alloc), std::forward<N>(name), suffix) {} RootStopwatchPtr(RootStopwatchPtr &&) = default; ~RootStopwatchPtr() noexcept { if (stopwatch != nullptr) Destruct(*stopwatch); } private: static void Destruct(Stopwatch &stopwatch) noexcept; }; void stopwatch_enable() noexcept; gcc_const bool stopwatch_is_enabled() noexcept; #else #include "AllocatorPtr.hxx" #include "net/SocketAddress.hxx" #include "net/SocketDescriptor.hxx" class StopwatchPtr { public: StopwatchPtr() = default; StopwatchPtr(std::nullptr_t) noexcept {} template<typename N> StopwatchPtr(AllocatorPtr, N &&, const char * =nullptr) noexcept {} template<typename N> StopwatchPtr(const StopwatchPtr &, N &&, const char * =nullptr) noexcept {} operator bool() const noexcept { return false; } void RecordEvent(const char *) const noexcept {} }; using RootStopwatchPtr = StopwatchPtr; static inline void stopwatch_enable() noexcept { } static inline bool stopwatch_is_enabled() noexcept { return false; } #endif
fix the NDEBUG build
stopwatch: fix the NDEBUG build
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
923df29441fca21747f01856d99d614dff355f16
src/import/chips/ocmb/odyssey/procedures/hwp/memory/ody_check_for_ready.C
src/import/chips/ocmb/odyssey/procedures/hwp/memory/ody_check_for_ready.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/odyssey/procedures/hwp/memory/ody_check_for_ready.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2021,2022 */ /* [+] 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 ody_check_for_ready.C /// @brief FW polls I2C slave interface to determine when it is ready /// /// *HWP HWP Owner: Thi Tran [email protected] /// *HWP HWP Backup: <none> /// *HWP Team: VBU /// *HWP Level: 2 /// *HWP Consumed by: Hostboot / Cronus #include <fapi2.H> #include <ody_scom_ody.H> #include <ody_check_for_ready.H> #include <generic/memory/lib/utils/c_str.H> extern "C" { SCOMT_ODY_USE_T_CFAM_FSI_W_FSI2PIB_STATUS; // Constant definitions const uint8_t MAX_I2C_ACTIVE_POLL = 2; // Max # of polls waiting for I2C active const uint64_t SIM_CYC_DELAY = 0; const uint64_t MICRO_SEC_DELAY = 1000; /// /// @brief Checks if the Odyssey I2C is ready to receive commands /// @param[in] i_target the controller /// @return FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode ody_check_for_ready(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target) { FAPI_DBG("ody_check_for_ready: Entering..."); // scomt definitions using namespace scomt; using namespace scomt::ody; T_CFAM_FSI_W_FSI2PIB_STATUS_t FSI2PIB_STATUS; fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS; fapi2::ATTR_IS_SIMULATION_Type l_sim_env; fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; // Skip delay polls if running on sim FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, FAPI_SYSTEM, l_sim_env), "Error from FAPI_ATTR_GET (ATTR_IS_SIMULATION)"); if (l_sim_env) { FAPI_INF("Sim environment, skipping ody_check_for_ready %s", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } else { // Polling until CFAM logic is active uint8_t l_poll = 0; while (l_poll < MAX_I2C_ACTIVE_POLL) { FAPI_DBG("Loop count: %d", l_poll); FAPI_TRY(fapi2::delay(MICRO_SEC_DELAY, SIM_CYC_DELAY), "fapiDelay error."); l_rc = FSI2PIB_STATUS.getCfam(i_target); if (l_rc == fapi2::FAPI2_RC_SUCCESS) { FAPI_INF("OCMB %s is active.", mss::c_str(i_target)); break; } l_poll++; } FAPI_ASSERT(!l_rc, fapi2::ODYSSEY_I2C_ERROR() .set_OCMB_TARGET(i_target), "Odyssey I2C is not active for target %s.", mss::c_str(i_target)); } fapi_try_exit: FAPI_DBG("ody_check_for_ready: Exiting."); return fapi2::current_err; } }// extern C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/odyssey/procedures/hwp/memory/ody_check_for_ready.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2021,2022 */ /* [+] 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 ody_check_for_ready.C /// @brief FW polls I2C slave interface to determine when it is ready /// /// *HWP HWP Owner: Thi Tran [email protected] /// *HWP HWP Backup: <none> /// *HWP Team: VBU /// *HWP Level: 2 /// *HWP Consumed by: Hostboot / Cronus #include <fapi2.H> #include <ody_scom_ody.H> #include <ody_check_for_ready.H> #include <generic/memory/lib/utils/c_str.H> extern "C" { SCOMT_ODY_USE_T_CFAM_FSI_W_FSI2PIB_STATUS; // Constant definitions const uint8_t MAX_I2C_ACTIVE_POLL = 2; // Max # of polls waiting for I2C active const uint64_t SIM_CYC_DELAY = 0; const uint64_t MICRO_SEC_DELAY = 1000; /// /// @brief Checks if the Odyssey I2C is ready to receive commands /// @param[in] i_target the controller /// @return FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode ody_check_for_ready(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target) { FAPI_DBG("ody_check_for_ready: Entering..."); // scomt definitions using namespace scomt; using namespace scomt::ody; T_CFAM_FSI_W_FSI2PIB_STATUS_t FSI2PIB_STATUS; fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS; fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; // Polling until CFAM logic is active uint8_t l_poll = 0; while (l_poll < MAX_I2C_ACTIVE_POLL) { FAPI_DBG("Loop count: %d", l_poll); FAPI_TRY(fapi2::delay(MICRO_SEC_DELAY, SIM_CYC_DELAY), "fapiDelay error."); l_rc = FSI2PIB_STATUS.getCfam(i_target); if (l_rc == fapi2::FAPI2_RC_SUCCESS) { FAPI_INF("OCMB %s is active.", mss::c_str(i_target)); break; } l_poll++; } FAPI_ASSERT(!l_rc, fapi2::ODYSSEY_I2C_ERROR() .set_OCMB_TARGET(i_target), "Odyssey I2C is not active for target %s.", mss::c_str(i_target)); fapi_try_exit: FAPI_DBG("ody_check_for_ready: Exiting."); return fapi2::current_err; } }// extern C
Remove no-op when running on simulation.
Remove no-op when running on simulation. Change-Id: I99d590984f26ac44852cc9cddf3f16917b5ef2a1 Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/134729 Tested-by: Jenkins Server <[email protected]> Tested-by: FSP CI Jenkins <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: Joseph J McGill <[email protected]> Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/134973 Tested-by: Jenkins OP Build CI <[email protected]> Tested-by: Jenkins Combined Simics CI <[email protected]> Tested-by: Jenkins OP HW <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Daniel M Crowell <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
59d33e3dd43e92b560899b823c6c11dd2bdd50af
stan/math/prim/mat/fun/singular_values.hpp
stan/math/prim/mat/fun/singular_values.hpp
#ifndef STAN_MATH_PRIM_MAT_FUN_SINGULAR_VALUES_HPP #define STAN_MATH_PRIM_MAT_FUN_SINGULAR_VALUES_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> namespace stan { namespace math { /** * Return the vector of the singular values of the specified matrix * in decreasing order of magnitude. * <p>See the documentation for <code>svd()</code> for * information on the singular values. * @param m Specified matrix. * @return Singular values of the matrix. */ template <typename T> Eigen::Matrix<T, Eigen::Dynamic, 1> singular_values( const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m) { if (m.rows() == 0 || m.cols() == 0) return Eigen::Matrix<T, 0, 1>(); return Eigen::JacobiSVD<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >(m) .singularValues(); } } // namespace math } // namespace stan #endif
#ifndef STAN_MATH_PRIM_MAT_FUN_SINGULAR_VALUES_HPP #define STAN_MATH_PRIM_MAT_FUN_SINGULAR_VALUES_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> namespace stan { namespace math { /** * Return the vector of the singular values of the specified matrix * in decreasing order of magnitude. * <p>See the documentation for <code>svd()</code> for * information on the singular values. * @param m Specified matrix. * @return Singular values of the matrix. */ template <typename T> Eigen::Matrix<T, Eigen::Dynamic, 1> singular_values( const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m) { if (m.size() == 0) return Eigen::Matrix<T, 0, 1>(); return Eigen::JacobiSVD<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >(m) .singularValues(); } } // namespace math } // namespace stan #endif
Use m.size() instead of m.rows() and m.cols()
Use m.size() instead of m.rows() and m.cols()
C++
bsd-3-clause
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
8cc30a687da43e327c1a726cfe6a68ed1242e818
Firmware/communication/communication.cpp
Firmware/communication/communication.cpp
/* Includes ------------------------------------------------------------------*/ #include "communication.h" #include "interface_usb.h" #include "interface_uart.h" #include "interface_can.hpp" #include "interface_i2c.h" #include "odrive_main.h" #include "freertos_vars.h" #include "utils.h" #include "../build/version.h" // autogenerated based on Git state #include <cmsis_os.h> #include <memory> //#include <usbd_cdc_if.h> //#include <usb_device.h> //#include <usart.h> #include <gpio.h> #include <type_traits> /* Private defines -----------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Global constant data ------------------------------------------------------*/ /* Global variables ----------------------------------------------------------*/ uint64_t serial_number; char serial_number_str[13]; // 12 digits + null termination /* Private constant data -----------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ #if HW_VERSION_MAJOR == 3 // Determine start address of the OTP struct: // The OTP is organized into 16-byte blocks. // If the first block starts with "0xfe" we use the first block. // If the first block starts with "0x00" and the second block starts with "0xfe", // we use the second block. This gives the user the chance to screw up once. // If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL). const uint8_t* otp_ptr = (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE : (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL : (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL : (uint8_t*)(FLASH_OTP_BASE + 0x10); // Read hardware version from OTP if available, otherwise fall back // to software defined version. const uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR; const uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR; const uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE; #else #error "not implemented" #endif // the corresponding macros are defined in the autogenerated version.h const uint8_t fw_version_major = FW_VERSION_MAJOR; const uint8_t fw_version_minor = FW_VERSION_MINOR; const uint8_t fw_version_revision = FW_VERSION_REVISION; const uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; // 0 for official releases, 1 otherwise osThreadId comm_thread; volatile bool endpoint_list_valid = false; static uint32_t test_property = 0; /* Private function prototypes -----------------------------------------------*/ auto make_protocol_definitions(PWMMapping_t& mapping) { return make_protocol_member_list( make_protocol_property("endpoint", &mapping.endpoint), make_protocol_property("min", &mapping.min), make_protocol_property("max", &mapping.max) ); } /* Function implementations --------------------------------------------------*/ void init_communication(void) { printf("hi!\r\n"); // Start command handling thread osThreadDef(task_cmd_parse, communication_task, osPriorityNormal, 0, 8000 /* in 32-bit words */); // TODO: fix stack issues comm_thread = osThreadCreate(osThread(task_cmd_parse), NULL); while (!endpoint_list_valid) osDelay(1); } float oscilloscope[OSCILLOSCOPE_SIZE] = {0}; size_t oscilloscope_pos = 0; static CAN_context can1_ctx; // Helper class because the protocol library doesn't yet // support non-member functions // TODO: make this go away class StaticFunctions { public: void save_configuration_helper() { save_configuration(); } void erase_configuration_helper() { erase_configuration(); } void NVIC_SystemReset_helper() { NVIC_SystemReset(); } void enter_dfu_mode_helper() { enter_dfu_mode(); } float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; } float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); } int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; } } static_functions; // When adding new functions/variables to the protocol, be careful not to // blow the communication stack. You can check comm_stack_info to see // how much headroom you have. static inline auto make_obj_tree() { return make_protocol_member_list( make_protocol_ro_property("vbus_voltage", &vbus_voltage), make_protocol_ro_property("serial_number", &serial_number), make_protocol_ro_property("hw_version_major", &hw_version_major), make_protocol_ro_property("hw_version_minor", &hw_version_minor), make_protocol_ro_property("hw_version_variant", &hw_version_variant), make_protocol_ro_property("fw_version_major", &fw_version_major), make_protocol_ro_property("fw_version_minor", &fw_version_minor), make_protocol_ro_property("fw_version_revision", &fw_version_revision), make_protocol_ro_property("fw_version_unreleased", &fw_version_unreleased), make_protocol_ro_property("user_config_loaded", const_cast<const bool *>(&user_config_loaded_)), make_protocol_ro_property("brake_resistor_armed", &brake_resistor_armed), make_protocol_object("system_stats", make_protocol_ro_property("uptime", &system_stats_.uptime), make_protocol_ro_property("min_heap_space", &system_stats_.min_heap_space), make_protocol_ro_property("min_stack_space_axis0", &system_stats_.min_stack_space_axis0), make_protocol_ro_property("min_stack_space_axis1", &system_stats_.min_stack_space_axis1), make_protocol_ro_property("min_stack_space_comms", &system_stats_.min_stack_space_comms), make_protocol_ro_property("min_stack_space_usb", &system_stats_.min_stack_space_usb), make_protocol_ro_property("min_stack_space_uart", &system_stats_.min_stack_space_uart), make_protocol_ro_property("min_stack_space_usb_irq", &system_stats_.min_stack_space_usb_irq), make_protocol_ro_property("min_stack_space_startup", &system_stats_.min_stack_space_startup), make_protocol_object("usb", make_protocol_ro_property("rx_cnt", &usb_stats_.rx_cnt), make_protocol_ro_property("tx_cnt", &usb_stats_.tx_cnt), make_protocol_ro_property("tx_overrun_cnt", &usb_stats_.tx_overrun_cnt) ), make_protocol_object("i2c", make_protocol_ro_property("addr", &i2c_stats_.addr), make_protocol_ro_property("addr_match_cnt", &i2c_stats_.addr_match_cnt), make_protocol_ro_property("rx_cnt", &i2c_stats_.rx_cnt), make_protocol_ro_property("error_cnt", &i2c_stats_.error_cnt) ) ), make_protocol_object("config", make_protocol_property("brake_resistance", &board_config.brake_resistance), // TODO: changing this currently requires a reboot - fix this make_protocol_property("enable_uart", &board_config.enable_uart), make_protocol_property("enable_i2c_instead_of_can" , &board_config.enable_i2c_instead_of_can), // requires a reboot make_protocol_property("enable_ascii_protocol_on_usb", &board_config.enable_ascii_protocol_on_usb), make_protocol_property("dc_bus_undervoltage_trip_level", &board_config.dc_bus_undervoltage_trip_level), make_protocol_property("dc_bus_overvoltage_trip_level", &board_config.dc_bus_overvoltage_trip_level), #if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3 make_protocol_object("gpio1_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[0])), make_protocol_object("gpio2_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[1])), make_protocol_object("gpio3_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[2])), #endif make_protocol_object("gpio4_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[3])), make_protocol_object("gpio3_analog_mapping", make_protocol_definitions(board_config.analog_mappings[2])), make_protocol_object("gpio4_analog_mapping", make_protocol_definitions(board_config.analog_mappings[3])) ), make_protocol_object("axis0", axes[0]->make_protocol_definitions()), make_protocol_object("axis1", axes[1]->make_protocol_definitions()), make_protocol_object("can", can1_ctx.make_protocol_definitions()), make_protocol_property("test_property", &test_property), make_protocol_function("test_function", static_functions, &StaticFunctions::test_function, "delta"), make_protocol_function("get_oscilloscope_val", static_functions, &StaticFunctions::get_oscilloscope_val, "index"), make_protocol_function("get_adc_voltage", static_functions, &StaticFunctions::get_adc_voltage_, "gpio"), make_protocol_function("save_configuration", static_functions, &StaticFunctions::save_configuration_helper), make_protocol_function("erase_configuration", static_functions, &StaticFunctions::erase_configuration_helper), make_protocol_function("reboot", static_functions, &StaticFunctions::NVIC_SystemReset_helper), make_protocol_function("enter_dfu_mode", static_functions, &StaticFunctions::enter_dfu_mode_helper) ); } using tree_type = decltype(make_obj_tree()); uint8_t tree_buffer[sizeof(tree_type)]; // Thread to handle deffered processing of USB interrupt, and // read commands out of the UART DMA circular buffer void communication_task(void * ctx) { (void) ctx; // unused parameter // TODO: this is supposed to use the move constructor, but currently // the compiler uses the copy-constructor instead. Thus the make_obj_tree // ends up with a stupid stack size of around 8000 bytes. Fix this. auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree()); fibre_publish(*tree_ptr); // Allow main init to continue endpoint_list_valid = true; start_uart_server(); start_usb_server(); if (board_config.enable_i2c_instead_of_can) { start_i2c_server(); } else { // TODO: finish implementing CAN // start_can_server(can1_ctx, CAN1, serial_number); } for (;;) { osDelay(1000); // nothing to do } } extern "C" { int _write(int file, const char* data, int len); } // @brief This is what printf calls internally int _write(int file, const char* data, int len) { #ifdef USB_PROTOCOL_STDOUT usb_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr); #endif #ifdef UART_PROTOCOL_STDOUT uart4_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr); #endif return len; }
/* Includes ------------------------------------------------------------------*/ #include "communication.h" #include "interface_usb.h" #include "interface_uart.h" #include "interface_can.hpp" #include "interface_i2c.h" #include "odrive_main.h" #include "freertos_vars.h" #include "utils.h" #include "../build/version.h" // autogenerated based on Git state #include <cmsis_os.h> #include <memory> //#include <usbd_cdc_if.h> //#include <usb_device.h> //#include <usart.h> #include <gpio.h> #include <type_traits> /* Private defines -----------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Global constant data ------------------------------------------------------*/ /* Global variables ----------------------------------------------------------*/ uint64_t serial_number; char serial_number_str[13]; // 12 digits + null termination /* Private constant data -----------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ #if HW_VERSION_MAJOR == 3 // Determine start address of the OTP struct: // The OTP is organized into 16-byte blocks. // If the first block starts with "0xfe" we use the first block. // If the first block starts with "0x00" and the second block starts with "0xfe", // we use the second block. This gives the user the chance to screw up once. // If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL). const uint8_t* otp_ptr = (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE : (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL : (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL : (uint8_t*)(FLASH_OTP_BASE + 0x10); // Read hardware version from OTP if available, otherwise fall back // to software defined version. const uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR; const uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR; const uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE; #else #error "not implemented" #endif // the corresponding macros are defined in the autogenerated version.h const uint8_t fw_version_major = FW_VERSION_MAJOR; const uint8_t fw_version_minor = FW_VERSION_MINOR; const uint8_t fw_version_revision = FW_VERSION_REVISION; const uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; // 0 for official releases, 1 otherwise osThreadId comm_thread; volatile bool endpoint_list_valid = false; static uint32_t test_property = 0; /* Private function prototypes -----------------------------------------------*/ auto make_protocol_definitions(PWMMapping_t& mapping) { return make_protocol_member_list( make_protocol_property("endpoint", &mapping.endpoint), make_protocol_property("min", &mapping.min), make_protocol_property("max", &mapping.max) ); } /* Function implementations --------------------------------------------------*/ void init_communication(void) { printf("hi!\r\n"); // Start command handling thread osThreadDef(task_cmd_parse, communication_task, osPriorityNormal, 0, 8000 /* in 32-bit words */); // TODO: fix stack issues comm_thread = osThreadCreate(osThread(task_cmd_parse), NULL); while (!endpoint_list_valid) osDelay(1); } float oscilloscope[OSCILLOSCOPE_SIZE] = {0}; size_t oscilloscope_pos = 0; static CAN_context can1_ctx; // Helper class because the protocol library doesn't yet // support non-member functions // TODO: make this go away class StaticFunctions { public: void save_configuration_helper() { save_configuration(); } void erase_configuration_helper() { erase_configuration(); } void NVIC_SystemReset_helper() { NVIC_SystemReset(); } void enter_dfu_mode_helper() { enter_dfu_mode(); } float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; } float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); } int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; } } static_functions; // When adding new functions/variables to the protocol, be careful not to // blow the communication stack. You can check comm_stack_info to see // how much headroom you have. static inline auto make_obj_tree() { return make_protocol_member_list( make_protocol_ro_property("vbus_voltage", &vbus_voltage), make_protocol_ro_property("serial_number", &serial_number), make_protocol_ro_property("hw_version_major", &hw_version_major), make_protocol_ro_property("hw_version_minor", &hw_version_minor), make_protocol_ro_property("hw_version_variant", &hw_version_variant), make_protocol_ro_property("fw_version_major", &fw_version_major), make_protocol_ro_property("fw_version_minor", &fw_version_minor), make_protocol_ro_property("fw_version_revision", &fw_version_revision), make_protocol_ro_property("fw_version_unreleased", &fw_version_unreleased), make_protocol_ro_property("user_config_loaded", const_cast<const bool *>(&user_config_loaded_)), make_protocol_ro_property("brake_resistor_armed", &brake_resistor_armed), make_protocol_object("system_stats", make_protocol_ro_property("uptime", &system_stats_.uptime), make_protocol_ro_property("min_heap_space", &system_stats_.min_heap_space), make_protocol_ro_property("min_stack_space_axis0", &system_stats_.min_stack_space_axis0), make_protocol_ro_property("min_stack_space_axis1", &system_stats_.min_stack_space_axis1), make_protocol_ro_property("min_stack_space_comms", &system_stats_.min_stack_space_comms), make_protocol_ro_property("min_stack_space_usb", &system_stats_.min_stack_space_usb), make_protocol_ro_property("min_stack_space_uart", &system_stats_.min_stack_space_uart), make_protocol_ro_property("min_stack_space_usb_irq", &system_stats_.min_stack_space_usb_irq), make_protocol_ro_property("min_stack_space_startup", &system_stats_.min_stack_space_startup), make_protocol_object("usb", make_protocol_ro_property("rx_cnt", &usb_stats_.rx_cnt), make_protocol_ro_property("tx_cnt", &usb_stats_.tx_cnt), make_protocol_ro_property("tx_overrun_cnt", &usb_stats_.tx_overrun_cnt) ), make_protocol_object("i2c", make_protocol_ro_property("addr", &i2c_stats_.addr), make_protocol_ro_property("addr_match_cnt", &i2c_stats_.addr_match_cnt), make_protocol_ro_property("rx_cnt", &i2c_stats_.rx_cnt), make_protocol_ro_property("error_cnt", &i2c_stats_.error_cnt) ) ), make_protocol_object("config", make_protocol_property("brake_resistance", &board_config.brake_resistance), make_protocol_property("max_regen_current", &board_config.max_regen_current), // TODO: changing this currently requires a reboot - fix this make_protocol_property("enable_uart", &board_config.enable_uart), make_protocol_property("enable_i2c_instead_of_can" , &board_config.enable_i2c_instead_of_can), // requires a reboot make_protocol_property("enable_ascii_protocol_on_usb", &board_config.enable_ascii_protocol_on_usb), make_protocol_property("dc_bus_undervoltage_trip_level", &board_config.dc_bus_undervoltage_trip_level), make_protocol_property("dc_bus_overvoltage_trip_level", &board_config.dc_bus_overvoltage_trip_level), #if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3 make_protocol_object("gpio1_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[0])), make_protocol_object("gpio2_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[1])), make_protocol_object("gpio3_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[2])), #endif make_protocol_object("gpio4_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[3])), make_protocol_object("gpio3_analog_mapping", make_protocol_definitions(board_config.analog_mappings[2])), make_protocol_object("gpio4_analog_mapping", make_protocol_definitions(board_config.analog_mappings[3])) ), make_protocol_object("axis0", axes[0]->make_protocol_definitions()), make_protocol_object("axis1", axes[1]->make_protocol_definitions()), make_protocol_object("can", can1_ctx.make_protocol_definitions()), make_protocol_property("test_property", &test_property), make_protocol_function("test_function", static_functions, &StaticFunctions::test_function, "delta"), make_protocol_function("get_oscilloscope_val", static_functions, &StaticFunctions::get_oscilloscope_val, "index"), make_protocol_function("get_adc_voltage", static_functions, &StaticFunctions::get_adc_voltage_, "gpio"), make_protocol_function("save_configuration", static_functions, &StaticFunctions::save_configuration_helper), make_protocol_function("erase_configuration", static_functions, &StaticFunctions::erase_configuration_helper), make_protocol_function("reboot", static_functions, &StaticFunctions::NVIC_SystemReset_helper), make_protocol_function("enter_dfu_mode", static_functions, &StaticFunctions::enter_dfu_mode_helper) ); } using tree_type = decltype(make_obj_tree()); uint8_t tree_buffer[sizeof(tree_type)]; // Thread to handle deffered processing of USB interrupt, and // read commands out of the UART DMA circular buffer void communication_task(void * ctx) { (void) ctx; // unused parameter // TODO: this is supposed to use the move constructor, but currently // the compiler uses the copy-constructor instead. Thus the make_obj_tree // ends up with a stupid stack size of around 8000 bytes. Fix this. auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree()); fibre_publish(*tree_ptr); // Allow main init to continue endpoint_list_valid = true; start_uart_server(); start_usb_server(); if (board_config.enable_i2c_instead_of_can) { start_i2c_server(); } else { // TODO: finish implementing CAN // start_can_server(can1_ctx, CAN1, serial_number); } for (;;) { osDelay(1000); // nothing to do } } extern "C" { int _write(int file, const char* data, int len); } // @brief This is what printf calls internally int _write(int file, const char* data, int len) { #ifdef USB_PROTOCOL_STDOUT usb_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr); #endif #ifdef UART_PROTOCOL_STDOUT uart4_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr); #endif return len; }
Add max_regen_current to protocol
Add max_regen_current to protocol
C++
mit
madcowswe/ODriveFirmware,madcowswe/ODriveFirmware,madcowswe/ODriveFirmware,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODriveFirmware
f00f8f59a5f06c9aa5e4fc76835c7f9ddb999ab9
eval/src/tests/instruction/dense_single_reduce_function/dense_single_reduce_function_test.cpp
eval/src/tests/instruction/dense_single_reduce_function/dense_single_reduce_function_test.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/operation.h> #include <vespa/eval/instruction/dense_single_reduce_function.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add_dense({{"a", 2}, {"b", 3}, {"c", 4}, {"d", 5}}) .add_dense({{"a", 9}, {"b", 9}, {"c", 9}, {"d", 9}}) .add_cube("a", 2, "b", 1, "c", 1) .add_cube("a", 1, "b", 2, "c", 1) .add_cube("a", 1, "b", 1, "c", 2) .add_cube("a", 1, "b", 1, "c", 1) .add_vector("a", 10) .add("xy_mapped", spec({x({"a", "b"}),y({"x", "y"})}, N())) .add("xyz_mixed", spec({x({"a", "b"}),y({"x", "y"}),z(3)}, N())); } EvalFixture::ParamRepo param_repo = make_params(); struct ReduceSpec { size_t outer_size; size_t reduce_size; size_t inner_size; Aggr aggr; }; void verify_optimized_impl(const vespalib::string &expr, const std::vector<ReduceSpec> &spec_list) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQUAL(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<DenseSingleReduceFunction>(); ASSERT_EQUAL(info.size(), spec_list.size()); for (size_t i = 0; i < spec_list.size(); ++i) { EXPECT_TRUE(info[i]->result_is_mutable()); EXPECT_EQUAL(info[i]->outer_size(), spec_list[i].outer_size); EXPECT_EQUAL(info[i]->reduce_size(), spec_list[i].reduce_size); EXPECT_EQUAL(info[i]->inner_size(), spec_list[i].inner_size); EXPECT_EQUAL(int(info[i]->aggr()), int(spec_list[i].aggr)); } } void verify_optimized(const vespalib::string &expr, const ReduceSpec &spec) { verify_optimized_impl(expr, {spec}); } void verify_optimized(const vespalib::string &expr, const ReduceSpec &spec1, const ReduceSpec &spec2) { verify_optimized_impl(expr, {spec1, spec2}); } void verify_not_optimized(const vespalib::string &expr) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQUAL(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<DenseSingleReduceFunction>(); EXPECT_TRUE(info.empty()); } TEST("require that reduce to scalar is not optimized") { TEST_DO(verify_not_optimized("reduce(a10,sum,a)")); TEST_DO(verify_not_optimized("reduce(a10,sum)")); } TEST("require that sparse reduce is not optimized") { TEST_DO(verify_not_optimized("reduce(xy_mapped,sum,x)")); TEST_DO(verify_not_optimized("reduce(xy_mapped,sum,y)")); } TEST("require that mixed reduce is not optimized") { TEST_DO(verify_not_optimized("reduce(xyz_mixed,sum,x)")); TEST_DO(verify_not_optimized("reduce(xyz_mixed,sum,y)")); TEST_DO(verify_not_optimized("reduce(xyz_mixed,sum,z)")); } TEST("require that reducing trivial dimensions is not optimized") { TEST_DO(verify_not_optimized("reduce(a1b1c1,avg,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,count,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,prod,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,sum,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,max,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,median,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,min,c)")); } TEST("require that atleast_8 dense single reduce works") { TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,a)", {1, 9, 729, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,b)", {9, 9, 81, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,c)", {81, 9, 9, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,d)", {729, 9, 1, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,sum,c,d)", {81, 81, 1, Aggr::SUM})); } TEST("require that simple aggregators can be decomposed into multiple reduce operations") { TEST_DO(verify_optimized("reduce(a2b3c4d5,sum,a,c)", {3, 4, 5, Aggr::SUM}, {1, 2, 60, Aggr::SUM})); TEST_DO(verify_optimized("reduce(a2b3c4d5,min,a,c)", {3, 4, 5, Aggr::MIN}, {1, 2, 60, Aggr::MIN})); TEST_DO(verify_optimized("reduce(a2b3c4d5,max,a,c)", {3, 4, 5, Aggr::MAX}, {1, 2, 60, Aggr::MAX})); } TEST("require that reduce dimensions can be listed in reverse order") { TEST_DO(verify_optimized("reduce(a2b3c4d5,sum,c,a)", {3, 4, 5, Aggr::SUM}, {1, 2, 60, Aggr::SUM})); TEST_DO(verify_optimized("reduce(a2b3c4d5,min,c,a)", {3, 4, 5, Aggr::MIN}, {1, 2, 60, Aggr::MIN})); TEST_DO(verify_optimized("reduce(a2b3c4d5,max,c,a)", {3, 4, 5, Aggr::MAX}, {1, 2, 60, Aggr::MAX})); } TEST("require that non-simple aggregators cannot be decomposed into multiple reduce operations") { TEST_DO(verify_not_optimized("reduce(a2b3c4d5,avg,a,c)")); TEST_DO(verify_not_optimized("reduce(a2b3c4d5,count,a,c)")); TEST_DO(verify_not_optimized("reduce(a2b3c4d5,median,a,c)")); } vespalib::string make_expr(const vespalib::string &arg, const vespalib::string &dim, bool float_cells, Aggr aggr) { return make_string("reduce(%s%s,%s,%s)", arg.c_str(), float_cells ? "f" : "", AggrNames::name_of(aggr)->c_str(), dim.c_str()); } void verify_optimized_multi(const vespalib::string &arg, const vespalib::string &dim, size_t outer_size, size_t reduce_size, size_t inner_size) { for (bool float_cells: {false, true}) { for (Aggr aggr: Aggregator::list()) { if (aggr != Aggr::PROD) { auto expr = make_expr(arg, dim, float_cells, aggr); TEST_DO(verify_optimized(expr, {outer_size, reduce_size, inner_size, aggr})); } } } } TEST("require that normal dense single reduce works") { TEST_DO(verify_optimized_multi("a2b3c4d5", "a", 1, 2, 60)); TEST_DO(verify_optimized_multi("a2b3c4d5", "b", 2, 3, 20)); TEST_DO(verify_optimized_multi("a2b3c4d5", "c", 6, 4, 5)); TEST_DO(verify_optimized_multi("a2b3c4d5", "d", 24, 5, 1)); } TEST("require that dimension-combined dense single reduce works") { TEST_DO(verify_optimized_multi("a2b3c4d5", "a,b", 1, 6, 20)); TEST_DO(verify_optimized_multi("a2b3c4d5", "b,c", 2, 12, 5)); TEST_DO(verify_optimized_multi("a2b3c4d5", "c,d", 6, 20, 1)); } TEST("require that minimal dense single reduce works") { TEST_DO(verify_optimized_multi("a2b1c1", "a", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b2c1", "b", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b1c2", "c", 1, 2, 1)); } TEST("require that trivial dimensions can be trivially reduced") { TEST_DO(verify_optimized_multi("a2b1c1", "a,b", 1, 2, 1)); TEST_DO(verify_optimized_multi("a2b1c1", "a,c", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b2c1", "b,a", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b2c1", "b,c", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b1c2", "c,a", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b1c2", "c,b", 1, 2, 1)); } TEST_MAIN() { TEST_RUN_ALL(); }
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/operation.h> #include <vespa/eval/instruction/dense_single_reduce_function.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add_variants("a2b3c4d5", GenSpec().idx("a", 2).idx("b", 3).idx("c", 4).idx("d", 5)) .add_variants("a9b9c9d9", GenSpec().idx("a", 9).idx("b", 9).idx("c", 9).idx("d", 9)) .add_variants("a2b1c1", GenSpec().idx("a", 2).idx("b", 1).idx("c", 1)) .add_variants("a1b2c1", GenSpec().idx("a", 1).idx("b", 2).idx("c", 1)) .add_variants("a1b1c2", GenSpec().idx("a", 1).idx("b", 1).idx("c", 2)) .add_variants("a1b1c1", GenSpec().idx("a", 1).idx("b", 1).idx("c", 1)) .add_variants("a10", GenSpec().idx("a", 10)) .add("xy_mapped", GenSpec().map("x", {"a", "b"}).map("y", {"x", "y"}).gen()) .add("xyz_mixed", GenSpec().map("x", {"a", "b"}).map("y", {"x", "y"}).idx("z", 3).gen()); } EvalFixture::ParamRepo param_repo = make_params(); struct ReduceSpec { size_t outer_size; size_t reduce_size; size_t inner_size; Aggr aggr; }; void verify_optimized_impl(const vespalib::string &expr, const std::vector<ReduceSpec> &spec_list) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQUAL(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<DenseSingleReduceFunction>(); ASSERT_EQUAL(info.size(), spec_list.size()); for (size_t i = 0; i < spec_list.size(); ++i) { EXPECT_TRUE(info[i]->result_is_mutable()); EXPECT_EQUAL(info[i]->outer_size(), spec_list[i].outer_size); EXPECT_EQUAL(info[i]->reduce_size(), spec_list[i].reduce_size); EXPECT_EQUAL(info[i]->inner_size(), spec_list[i].inner_size); EXPECT_EQUAL(int(info[i]->aggr()), int(spec_list[i].aggr)); } } void verify_optimized(const vespalib::string &expr, const ReduceSpec &spec) { verify_optimized_impl(expr, {spec}); } void verify_optimized(const vespalib::string &expr, const ReduceSpec &spec1, const ReduceSpec &spec2) { verify_optimized_impl(expr, {spec1, spec2}); } void verify_not_optimized(const vespalib::string &expr) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQUAL(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<DenseSingleReduceFunction>(); EXPECT_TRUE(info.empty()); } TEST("require that reduce to scalar is not optimized") { TEST_DO(verify_not_optimized("reduce(a10,sum,a)")); TEST_DO(verify_not_optimized("reduce(a10,sum)")); } TEST("require that sparse reduce is not optimized") { TEST_DO(verify_not_optimized("reduce(xy_mapped,sum,x)")); TEST_DO(verify_not_optimized("reduce(xy_mapped,sum,y)")); } TEST("require that mixed reduce is not optimized") { TEST_DO(verify_not_optimized("reduce(xyz_mixed,sum,x)")); TEST_DO(verify_not_optimized("reduce(xyz_mixed,sum,y)")); TEST_DO(verify_not_optimized("reduce(xyz_mixed,sum,z)")); } TEST("require that reducing trivial dimensions is not optimized") { TEST_DO(verify_not_optimized("reduce(a1b1c1,avg,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,count,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,prod,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,sum,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,max,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,median,c)")); TEST_DO(verify_not_optimized("reduce(a1b1c1,min,c)")); } TEST("require that atleast_8 dense single reduce works") { TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,a)", {1, 9, 729, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,b)", {9, 9, 81, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,c)", {81, 9, 9, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,avg,d)", {729, 9, 1, Aggr::AVG})); TEST_DO(verify_optimized("reduce(a9b9c9d9,sum,c,d)", {81, 81, 1, Aggr::SUM})); } TEST("require that simple aggregators can be decomposed into multiple reduce operations") { TEST_DO(verify_optimized("reduce(a2b3c4d5,sum,a,c)", {3, 4, 5, Aggr::SUM}, {1, 2, 60, Aggr::SUM})); TEST_DO(verify_optimized("reduce(a2b3c4d5,min,a,c)", {3, 4, 5, Aggr::MIN}, {1, 2, 60, Aggr::MIN})); TEST_DO(verify_optimized("reduce(a2b3c4d5,max,a,c)", {3, 4, 5, Aggr::MAX}, {1, 2, 60, Aggr::MAX})); } TEST("require that reduce dimensions can be listed in reverse order") { TEST_DO(verify_optimized("reduce(a2b3c4d5,sum,c,a)", {3, 4, 5, Aggr::SUM}, {1, 2, 60, Aggr::SUM})); TEST_DO(verify_optimized("reduce(a2b3c4d5,min,c,a)", {3, 4, 5, Aggr::MIN}, {1, 2, 60, Aggr::MIN})); TEST_DO(verify_optimized("reduce(a2b3c4d5,max,c,a)", {3, 4, 5, Aggr::MAX}, {1, 2, 60, Aggr::MAX})); } TEST("require that non-simple aggregators cannot be decomposed into multiple reduce operations") { TEST_DO(verify_not_optimized("reduce(a2b3c4d5,avg,a,c)")); TEST_DO(verify_not_optimized("reduce(a2b3c4d5,count,a,c)")); TEST_DO(verify_not_optimized("reduce(a2b3c4d5,median,a,c)")); } vespalib::string make_expr(const vespalib::string &arg, const vespalib::string &dim, bool float_cells, Aggr aggr) { return make_string("reduce(%s%s,%s,%s)", arg.c_str(), float_cells ? "_f" : "", AggrNames::name_of(aggr)->c_str(), dim.c_str()); } void verify_optimized_multi(const vespalib::string &arg, const vespalib::string &dim, size_t outer_size, size_t reduce_size, size_t inner_size) { for (bool float_cells: {false, true}) { for (Aggr aggr: Aggregator::list()) { if (aggr != Aggr::PROD) { auto expr = make_expr(arg, dim, float_cells, aggr); TEST_DO(verify_optimized(expr, {outer_size, reduce_size, inner_size, aggr})); } } } } TEST("require that normal dense single reduce works") { TEST_DO(verify_optimized_multi("a2b3c4d5", "a", 1, 2, 60)); TEST_DO(verify_optimized_multi("a2b3c4d5", "b", 2, 3, 20)); TEST_DO(verify_optimized_multi("a2b3c4d5", "c", 6, 4, 5)); TEST_DO(verify_optimized_multi("a2b3c4d5", "d", 24, 5, 1)); } TEST("require that dimension-combined dense single reduce works") { TEST_DO(verify_optimized_multi("a2b3c4d5", "a,b", 1, 6, 20)); TEST_DO(verify_optimized_multi("a2b3c4d5", "b,c", 2, 12, 5)); TEST_DO(verify_optimized_multi("a2b3c4d5", "c,d", 6, 20, 1)); } TEST("require that minimal dense single reduce works") { TEST_DO(verify_optimized_multi("a2b1c1", "a", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b2c1", "b", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b1c2", "c", 1, 2, 1)); } TEST("require that trivial dimensions can be trivially reduced") { TEST_DO(verify_optimized_multi("a2b1c1", "a,b", 1, 2, 1)); TEST_DO(verify_optimized_multi("a2b1c1", "a,c", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b2c1", "b,a", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b2c1", "b,c", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b1c2", "c,a", 1, 2, 1)); TEST_DO(verify_optimized_multi("a1b1c2", "c,b", 1, 2, 1)); } TEST_MAIN() { TEST_RUN_ALL(); }
use GenSpec in dense_single_reduce_function_test
use GenSpec in dense_single_reduce_function_test
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
97f94dc832596da01a0c026b6a16c49a68fa6f78
tensorflow/compiler/mlir/hlo/lib/Dialect/gml_st/transforms/compose_set_ops.cc
tensorflow/compiler/mlir/hlo/lib/Dialect/gml_st/transforms/compose_set_ops.cc
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iterator> #include <memory> #include <utility> #include "mlir-hlo/Dialect/gml_st/IR/gml_st_ops.h" #include "mlir-hlo/Dialect/gml_st/transforms/compose_set_interface.h" #include "mlir-hlo/Dialect/gml_st/transforms/pass_detail.h" #include "mlir-hlo/Dialect/gml_st/transforms/passes.h" #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" namespace mlir { namespace gml_st { namespace { template <typename TilingOp> struct ComposeSetPattern : public OpRewritePattern<TilingOp> { using OpRewritePattern<TilingOp>::OpRewritePattern; LogicalResult matchAndRewrite(TilingOp op, PatternRewriter& rewriter) const override { auto iface = llvm::dyn_cast<ComposeSetInterface>(op.getOperation()); if (!iface) return failure(); Value composed = iface.compose(rewriter); if (!composed) return failure(); rewriter.replaceOp(op, composed); return success(); } }; class ComposeSetOpsPass : public ComposeSetOpsPassBase<ComposeSetOpsPass> { void getDependentDialects(DialectRegistry& registry) const final { registry.insert<arith::ArithmeticDialect, GmlStDialect>(); } void runOnOperation() final { MLIRContext* ctx = &getContext(); RewritePatternSet patterns(ctx); // clang-format off patterns.insert< ComposeSetPattern<PointOp>, ComposeSetPattern<TileOp>>(ctx); // clang-format on // Apply patterns from the top down. This makes sure that we have already // composed the operand of a tiling op. mlir::GreedyRewriteConfig config; config.useTopDownTraversal = true; if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns), config))) { return signalPassFailure(); } } }; } // namespace std::unique_ptr<OperationPass<func::FuncOp>> createComposeSetOpsPass() { return std::make_unique<ComposeSetOpsPass>(); } } // namespace gml_st } // namespace mlir
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iterator> #include <memory> #include <utility> #include "mlir-hlo/Dialect/gml_st/IR/gml_st_ops.h" #include "mlir-hlo/Dialect/gml_st/transforms/compose_set_interface.h" #include "mlir-hlo/Dialect/gml_st/transforms/pass_detail.h" #include "mlir-hlo/Dialect/gml_st/transforms/passes.h" #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" namespace mlir { namespace gml_st { namespace { struct ComposeSetPattern : public OpInterfaceRewritePattern<ComposeSetInterface> { using OpInterfaceRewritePattern< ComposeSetInterface>::OpInterfaceRewritePattern; LogicalResult matchAndRewrite(ComposeSetInterface iface, PatternRewriter& rewriter) const override { Value composed = iface.compose(rewriter); if (!composed) return failure(); rewriter.replaceOp(iface.getOperation(), composed); return success(); } }; class ComposeSetOpsPass : public ComposeSetOpsPassBase<ComposeSetOpsPass> { void getDependentDialects(DialectRegistry& registry) const final { registry.insert<arith::ArithmeticDialect, GmlStDialect>(); } void runOnOperation() final { MLIRContext* ctx = &getContext(); RewritePatternSet patterns(ctx); patterns.insert<ComposeSetPattern>(ctx); // Apply patterns from the top down. This makes sure that we have already // composed the operand of a tiling op. mlir::GreedyRewriteConfig config; config.useTopDownTraversal = true; if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns), config))) { return signalPassFailure(); } } }; } // namespace std::unique_ptr<OperationPass<func::FuncOp>> createComposeSetOpsPass() { return std::make_unique<ComposeSetOpsPass>(); } } // namespace gml_st } // namespace mlir
Use OpInterfaceRewritePattern for subset composition pass
[GML] Use OpInterfaceRewritePattern for subset composition pass PiperOrigin-RevId: 459577592
C++
apache-2.0
karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow
fd3f9e48c3917f8542bdaa9d3742335397c736bf
src/themesdlg.cpp
src/themesdlg.cpp
/* * Copyright (C) 2005 Petri Damstn <[email protected]> * * This file is part of SuperKaramba. * * SuperKaramba is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * SuperKaramba is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SuperKaramba; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include "karambaapp.h" #include "dcopinterface_stub.h" #include "karambainterface.h" #include "themesdlg.h" #include "themewidget.h" #include "kwidgetlistbox.h" #include "karamba.h" #ifdef KDE_3_3 #include "sknewstuff.h" #endif #include "superkarambasettings.h" #include <kdebug.h> #include <kfiledialog.h> #include <kpushbutton.h> #include <kstandarddirs.h> #include <kapplication.h> #include <kiconloader.h> #include <klocale.h> #include <qlineedit.h> #include <qtable.h> #include <qdir.h> #include <qlabel.h> #include <qcombobox.h> #include <kio/job.h> #include <kprotocolinfo.h> ThemesDlg::ThemesDlg(QWidget *parent, const char *name) : ThemesLayout(parent, name) { populateListbox(); #ifdef KDE_3_3 mNewStuff = 0; #endif } ThemesDlg::~ThemesDlg() { //kdDebug() << k_funcinfo << endl; saveUserAddedThemes(); #ifdef KDE_3_3 if(mNewStuff) { delete mNewStuff; } #endif } void ThemesDlg::saveUserAddedThemes() { KStandardDirs ksd; QStringList t = themes(); QStringList dirs = ksd.findDirs("data", QString(kapp->name()) + "/themes"); QStringList::Iterator it = t.begin(); bool remove; while(it != t.end()) { remove = false; QStringList::Iterator jtend( dirs.end() ); for(QStringList::Iterator jt = dirs.begin(); jt != jtend; ++jt) { if(QFileInfo(*it).dir().path() + "/" == *jt) { remove = true; break; } } if(remove) it = t.remove(it); else ++it; } SuperKarambaSettings::setUserAddedThemes(t); SuperKarambaSettings::writeConfig(); } QStringList ThemesDlg::themes() { QStringList result; ThemeWidget* w; for(uint i = 2; i < tableThemes->count(); ++i) { w = static_cast<ThemeWidget*>(tableThemes->item(i)); result.append(w->themeFile()->file()); } return result; } void ThemesDlg::populateListbox() { ThemeWidget* item; QDir dir; QStringList dirs; QStringList t; KStandardDirs ksd; tableThemes->clear(); item = new ThemeWidget; item->icon->setPixmap(KGlobal::iconLoader()->loadIcon("knewstuff", KIcon::NoGroup, KIcon::SizeHuge)); item->setHeaderText(i18n("Get New Stuff")); item->setDescriptionText(i18n("Download new themes.")); item->buttonGo->setText(i18n("New Stuff...")); #ifdef KDE_3_3 item->buttonGo->setEnabled(true); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(getNewStuff())); #else item->buttonGo->setEnabled(false); #endif tableThemes->insertItem(item); item = new ThemeWidget; item->icon->setPixmap(KGlobal::iconLoader()->loadIcon("ksysguard", KIcon::NoGroup, KIcon::SizeHuge)); item->setHeaderText(i18n("Open Local Theme")); item->setDescriptionText(i18n("Add local theme to the list.")); item->buttonGo->setProperty("stdItem", 18); item->buttonGo->setText(i18n("Open...")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(openLocalTheme())); tableThemes->insertItem(item); dirs = ksd.findDirs("data", QString(kapp->name()) + "/themes"); // Get custom dirs from config here? QStringList::Iterator itend( dirs.end() ); for(QStringList::Iterator it = dirs.begin(); it != itend; ++it ) { dir.setPath(*it); t = dir.entryList("*.skz; *.theme"); for(QStringList::Iterator it = t.begin(); it != t.end(); ++it ) { item = new ThemeWidget(new ThemeFile(dir.filePath(*it))); tableThemes->insertItem(item); item->buttonGo->setText(i18n("Uninstall")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(uninstall())); } } t = SuperKarambaSettings::userAddedThemes(); for(QStringList::Iterator it = t.begin(); it != t.end(); ++it ) { ThemeFile* file = new ThemeFile(*it); if(file->isValid()) { item = new ThemeWidget(file); tableThemes->insertItem(item); item->buttonGo->setText(i18n("Uninstall")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(uninstall())); } else delete file; } tableThemes->setSelected(0); } void ThemesDlg::addToDesktop() { ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->selectedItem()); if(w) { ThemeFile* tf = w->themeFile(); if(tf) { (new karamba(tf->file(), false))->show(); } } } void ThemesDlg::openLocalTheme() { QStringList fileNames; fileNames = KFileDialog::getOpenFileNames(":<themes>", i18n("*.theme *.skz|Themes"), this, i18n("Open Themes")); for(QStringList::Iterator it = fileNames.begin(); it != fileNames.end(); ++it) { ThemeFile file(*it); if(file.isValid()) (new karamba(*it, false))->show(); } } void ThemesDlg::getNewStuff() { #ifdef KDE_3_3 KConfig* config = KGlobal::config(); config->setGroup("KNewStuff"); config->writeEntry("ProvidersUrl", "http://download.kde.org/khotnewstuff/karamba-providers.xml"); config->sync(); m_newStuffStatus = config->entryMap("KNewStuffStatus").keys(); if ( !mNewStuff ) { mNewStuff = new SKNewStuff(this); } mNewStuff->download(); #endif } void ThemesDlg::selectionChanged(int index) { buttonAddToDesktop->setEnabled(index > 1); for(uint i=2; i < tableThemes->count(); ++i) { ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(i)); w->showButton(false); } ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(index)); ThemeFile* themeFile = w->themeFile(); if(themeFile && themeFile->canUninstall()) w->showButton(true); } int ThemesDlg::themeIndex(QString file) { ThemeWidget* w; file = ThemeFile::canonicalFile(file); for(uint i = 2; i < tableThemes->count(); ++i) { w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w->themeFile()->file() == file) return i; } return -1; } void ThemesDlg::newSkzTheme(const QString &file) { addThemeToList(file); #ifdef KDE_3_3 KConfig* config = KGlobal::config(); QStringList keys = config->entryMap("KNewStuffStatus").keys(); for(QStringList::Iterator it = m_newStuffStatus.begin(); it != m_newStuffStatus.end(); ++it) { keys.remove(*it); } if(!keys.isEmpty()) { config->setGroup("KNewStuffNames"); config->writeEntry(file, keys[0]); } #endif } int ThemesDlg::addThemeToList(const QString &file) { int i = themeIndex(file); if(i < 0) { ThemeWidget* item = new ThemeWidget(new ThemeFile(file)); i = tableThemes->insertItem(item); item->buttonGo->setText(i18n("Uninstall")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(uninstall())); } tableThemes->setSelected(i); return i; } int ThemesDlg::addTheme(const QString& , const QString &file) { int i = addThemeToList(file); int result = -1; ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w) result = w->addInstance(); karambaApp->buildToolTip(); return result; } void ThemesDlg::removeTheme(const QString&, const QString& file, int instance) { int i = themeIndex(file); ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w) w->removeInstance(instance); karambaApp->buildToolTip(); } void ThemesDlg::search(const QString&) { tableThemes->showItems(&filter, this); } bool ThemesDlg::filter(int index, QWidget* widget, void* data) { if(index < 2) return true; ThemesDlg* dlg = static_cast<ThemesDlg*>(data); ThemeWidget* w = static_cast<ThemeWidget*>(widget); if(dlg->comboShow->currentItem() == 1) // Running themes if(w->instances() == 0) return false; QString searchText = dlg->editSearch->text().lower(); if(searchText.isEmpty()) { return true; } else { if(w->themeName->text().lower().contains(searchText)) return true; if(w->description->text().lower().contains(searchText)) return true; } return false; } void ThemesDlg::uninstall() { ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->selectedItem()); ThemeFile* tf = w->themeFile(); KURL trash("trash:/"); KURL theme(tf->file()); karambaApp->dcopIface()->closeTheme(tf->name()); if(!KProtocolInfo::isKnownProtocol(trash)) trash = KGlobalSettings::trashPath(); KIO::move(theme, trash); tableThemes->removeItem(w); #ifdef KDE_3_3 // Remove theme from KNewStuffStatus KConfig* config = KGlobal::config(); config->setGroup("KNewStuffNames"); QString name = config->readEntry(theme.path()); kdDebug() << theme.path() << name << endl; if(!name.isEmpty()) { kapp->config()->deleteEntry(theme.path()); config->setGroup("KNewStuffStatus"); kapp->config()->deleteEntry(name); } #endif } QStringList ThemesDlg::runningThemes() { QStringList list; ThemeWidget* w; for(uint i = 2; i < tableThemes->count(); ++i) { w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w->instances() > 0) list.append(w->themeFile()->name()); } return list; } #include "themesdlg.moc"
/* * Copyright (C) 2005 Petri Damstn <[email protected]> * * This file is part of SuperKaramba. * * SuperKaramba is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * SuperKaramba is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SuperKaramba; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include "karambaapp.h" #include "dcopinterface_stub.h" #include "karambainterface.h" #include "themesdlg.h" #include "themewidget.h" #include "kwidgetlistbox.h" #include "karamba.h" #ifdef KDE_3_3 #include "sknewstuff.h" #endif #include "superkarambasettings.h" #include <kdebug.h> #include <kfiledialog.h> #include <kpushbutton.h> #include <kstandarddirs.h> #include <kapplication.h> #include <kiconloader.h> #include <klocale.h> #include <qlineedit.h> #include <qtable.h> #include <qdir.h> #include <qlabel.h> #include <qcombobox.h> #include <kio/job.h> #include <kprotocolinfo.h> ThemesDlg::ThemesDlg(QWidget *parent, const char *name) : ThemesLayout(parent, name) { populateListbox(); #ifdef KDE_3_3 mNewStuff = 0; #endif } ThemesDlg::~ThemesDlg() { //kdDebug() << k_funcinfo << endl; saveUserAddedThemes(); #ifdef KDE_3_3 if(mNewStuff) { delete mNewStuff; } #endif } void ThemesDlg::saveUserAddedThemes() { KStandardDirs ksd; QStringList t = themes(); QStringList dirs = ksd.findDirs("data", QString(kapp->name()) + "/themes"); QStringList::Iterator it = t.begin(); bool remove; while(it != t.end()) { remove = false; QStringList::Iterator jtend( dirs.end() ); for(QStringList::Iterator jt = dirs.begin(); jt != jtend; ++jt) { if(QFileInfo(*it).dir().path() + "/" == *jt) { remove = true; break; } } if(remove) it = t.remove(it); else ++it; } SuperKarambaSettings::setUserAddedThemes(t); SuperKarambaSettings::writeConfig(); } QStringList ThemesDlg::themes() { QStringList result; ThemeWidget* w; for(uint i = 2; i < tableThemes->count(); ++i) { w = static_cast<ThemeWidget*>(tableThemes->item(i)); result.append(w->themeFile()->file()); } return result; } void ThemesDlg::populateListbox() { ThemeWidget* item; QDir dir; QStringList dirs; QStringList t; KStandardDirs ksd; tableThemes->clear(); item = new ThemeWidget; item->icon->setPixmap(KGlobal::iconLoader()->loadIcon("knewstuff", KIcon::NoGroup, KIcon::SizeHuge)); item->setHeaderText(i18n("Get New Stuff")); item->setDescriptionText(i18n("Download new themes.")); item->buttonGo->setText(i18n("New Stuff...")); #ifdef KDE_3_3 item->buttonGo->setEnabled(true); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(getNewStuff())); #else item->buttonGo->setEnabled(false); #endif tableThemes->insertItem(item); item = new ThemeWidget; item->icon->setPixmap(KGlobal::iconLoader()->loadIcon("ksysguard", KIcon::NoGroup, KIcon::SizeHuge)); item->setHeaderText(i18n("Open Local Theme")); item->setDescriptionText(i18n("Add local theme to the list.")); item->buttonGo->setProperty("stdItem", 18); item->buttonGo->setText(i18n("Open...")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(openLocalTheme())); tableThemes->insertItem(item); dirs = ksd.findDirs("data", QString(kapp->name()) + "/themes"); // Get custom dirs from config here? QStringList::Iterator itend( dirs.end() ); for(QStringList::Iterator it = dirs.begin(); it != itend; ++it ) { dir.setPath(*it); t = dir.entryList("*.skz; *.theme"); for(QStringList::Iterator it = t.begin(); it != t.end(); ++it ) { item = new ThemeWidget(new ThemeFile(dir.filePath(*it))); tableThemes->insertItem(item); item->buttonGo->setText(i18n("Uninstall")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(uninstall())); } } t = SuperKarambaSettings::userAddedThemes(); for(QStringList::Iterator it = t.begin(); it != t.end(); ++it ) { ThemeFile* file = new ThemeFile(*it); if(file->isValid()) { item = new ThemeWidget(file); tableThemes->insertItem(item); item->buttonGo->setText(i18n("Uninstall")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(uninstall())); } else delete file; } tableThemes->setSelected(0); } void ThemesDlg::addToDesktop() { ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->selectedItem()); if(w) { ThemeFile* tf = w->themeFile(); if(tf) { (new karamba(tf->file(), false))->show(); } } } void ThemesDlg::openLocalTheme() { QStringList fileNames; fileNames = KFileDialog::getOpenFileNames(":<themes>", i18n("*.theme *.skz|Themes"), this, i18n("Open Themes")); for(QStringList::Iterator it = fileNames.begin(); it != fileNames.end(); ++it) { ThemeFile file(*it); if(file.isValid()) (new karamba(*it, false))->show(); } } void ThemesDlg::getNewStuff() { #ifdef KDE_3_3 KConfig* config = KGlobal::config(); config->setGroup("KNewStuff"); config->writeEntry("ProvidersUrl", "http://download.kde.org/khotnewstuff/karamba-providers.xml"); config->sync(); m_newStuffStatus = config->entryMap("KNewStuffStatus").keys(); if ( !mNewStuff ) { mNewStuff = new SKNewStuff(this); } mNewStuff->download(); #endif } void ThemesDlg::selectionChanged(int index) { buttonAddToDesktop->setEnabled(index > 1); for(uint i=2; i < tableThemes->count(); ++i) { ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(i)); w->showButton(false); } ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(index)); ThemeFile* themeFile = w->themeFile(); if(themeFile && themeFile->canUninstall()) w->showButton(true); } int ThemesDlg::themeIndex(QString file) { ThemeWidget* w; file = ThemeFile::canonicalFile(file); for(uint i = 2; i < tableThemes->count(); ++i) { w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w->themeFile()->file() == file) return i; } return -1; } void ThemesDlg::newSkzTheme(const QString &file) { addThemeToList(file); #ifdef KDE_3_3 KConfig* config = KGlobal::config(); QStringList keys = config->entryMap("KNewStuffStatus").keys(); for(QStringList::Iterator it = m_newStuffStatus.begin(); it != m_newStuffStatus.end(); ++it) { keys.remove(*it); } if(!keys.isEmpty()) { config->setGroup("KNewStuffNames"); config->writeEntry(file, keys[0]); } #endif } int ThemesDlg::addThemeToList(const QString &file) { int i = themeIndex(file); if(i < 0) { ThemeWidget* item = new ThemeWidget(new ThemeFile(file)); i = tableThemes->insertItem(item); item->buttonGo->setText(i18n("Uninstall")); connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(uninstall())); } tableThemes->setSelected(i); return i; } int ThemesDlg::addTheme(const QString& , const QString &file) { int i = addThemeToList(file); int result = -1; ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w) result = w->addInstance(); karambaApp->buildToolTip(); return result; } void ThemesDlg::removeTheme(const QString&, const QString& file, int instance) { int i = themeIndex(file); ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w) w->removeInstance(instance); karambaApp->buildToolTip(); } void ThemesDlg::search(const QString&) { tableThemes->showItems(&filter, this); } bool ThemesDlg::filter(int index, QWidget* widget, void* data) { if(index < 2) return true; ThemesDlg* dlg = static_cast<ThemesDlg*>(data); ThemeWidget* w = static_cast<ThemeWidget*>(widget); if(dlg->comboShow->currentItem() == 1) // Running themes if(w->instances() == 0) return false; QString searchText = dlg->editSearch->text().lower(); if(searchText.isEmpty()) { return true; } else { if(w->themeName->text().lower().contains(searchText)) return true; if(w->description->text().lower().contains(searchText)) return true; } return false; } void ThemesDlg::uninstall() { ThemeWidget* w = static_cast<ThemeWidget*>(tableThemes->selectedItem()); ThemeFile* tf = w->themeFile(); KURL trash("trash:/"); KURL theme(tf->file()); karambaApp->dcopIface()->closeTheme(tf->name()); if(!KProtocolInfo::isKnownProtocol(trash)) trash = KGlobalSettings::trashPath(); KIO::move(theme, trash); tableThemes->removeItem(w); #ifdef KDE_3_3 // Remove theme from KNewStuffStatus KConfig* config = KGlobal::config(); config->setGroup("KNewStuffNames"); QString name = config->readEntry(theme.path()); kdDebug() << theme.path() << name << endl; if(!name.isEmpty()) { kapp->config()->deleteEntry(theme.path()); config->setGroup("KNewStuffStatus"); kapp->config()->deleteEntry(name); } #endif selectionChanged(tableThemes->selected()); } QStringList ThemesDlg::runningThemes() { QStringList list; ThemeWidget* w; for(uint i = 2; i < tableThemes->count(); ++i) { w = static_cast<ThemeWidget*>(tableThemes->item(i)); if(w->instances() > 0) list.append(w->themeFile()->name()); } return list; } #include "themesdlg.moc"
Fix enable/disable "add to desktop" button when we uninstall a themes
Fix enable/disable "add to desktop" button when we uninstall a themes svn path=/branches/KDE/3.5/kdeutils/superkaramba/; revision=484058
C++
lgpl-2.1
KDE/superkaramba,KDE/superkaramba,KDE/superkaramba
776a8406da82989183f9511b62fe7477d68d1233
Source/main.cpp
Source/main.cpp
#include "stdafx.h" //needed for the Windows display #include "globals.h" //some global variables are included here #include <cstdlib> //standard c library #include "mediaItem.h" //the mediaItem class (you need to write a class that extends this class) #include "song.h" #include <fstream> #include <string> using namespace std; //declare global variables here (your song and playlist arrays) ifstream file; song songname[MAX_SONGS]; int songplaylist[MAX_PLAYLIST]; //as well as ints describing the current number of entries in each of these) int number_of_songs = 0; int counter = 0; bool loadSongList(string filename) { string artist[100]; string name[100]; string location[100]; int a = 0; file.open(filename); // input string filename if (file.is_open()) { file >> number_of_songs; // number of songs. file.ignore(); // ignore the first line (number of songs = 33) from text file. while (file.good()) // gets next line { getline(file, artist[a]); //reads line by line. getline(file, name[a]); getline(file, location[a]); a++; } a--; for (int i = 0; i < number_of_songs; i++) { songname[i].setArtist(artist[i]); //sets artist songname[i].setTitle(name[i]); //sets title songname[i].setLocation(location[i]); //sets location } return true; } else return false; } int getNumberOfSongsInSongList() { return number_of_songs; } string getSongNameFromSongList(int songNum) { return songname[songNum].getArtist() + " - " + songname[songNum].getTitle(); } string getSongNameFromPlaylist(int playlistSpot) { string songfile; //song choice int songspot = songplaylist[playlistSpot]; string artist = songname[songspot].getArtist(); // get artist from playlist string songtitle = songname[songspot].getTitle(); int sizeofartist = artist.length(); // finds length of artist and title. int sizeofsong = songtitle.length(); for (int i = 0; i < sizeofartist; i++) //loads each character into array (artist) songfile.push_back(artist[i]); songfile.push_back(' '); //adds space between artist and title. songfile.push_back('-'); songfile.push_back(' '); for (int i = 0; i < sizeofsong; i++) // loads each character into array (title) songfile.push_back(songtitle[i]); return songfile; } void addSongToPlaylist(int songNum) { songplaylist[counter] = songNum; // playlist songs is equal to the number of the song. points to location of song. counter = counter + 1; // adds song to playlist, keeps a counter. } int getNumberOfSongsInPlaylist() { return counter; // amount of sonds in playlist. } void removeSongFromPlaylist(int playlistSpot) { int temp[MAX_PLAYLIST]; int j = 0; for (int i = 0; i < MAX_PLAYLIST; i++) // creates temp array, copies songplaylist temp[i] = songplaylist[i]; for (int i = 0; i < MAX_PLAYLIST; i++) // erases songplaylist songplaylist[i] = -1; for (int i = 0; i < MAX_PLAYLIST; i++) // reprints array. { if (i != playlistSpot) { songplaylist[j] = temp[i]; j++; } } counter--; // keeps counter of playlist songs. } void clearPlaylist() { for (int i = 0; i < MAX_PLAYLIST; i++) // takes all playlist songs and sets them to -1. songplaylist[i] = -1; counter = 0; //resets counter to zero. } void moveSongUpInPlaylist(int playlistSpot) { // flips the selected song with the song below. int counter2 = 0; int d = songplaylist[playlistSpot]; int temp = songplaylist[playlistSpot - 1]; songplaylist[playlistSpot] = temp; //flip the songs. songplaylist[playlistSpot - 1] = d; } void moveSongDownInPlaylist(int playlistSpot) { // same way as moving list up but in reversed. int d = songplaylist[playlistSpot]; int temp = songplaylist[playlistSpot + 1]; songplaylist[playlistSpot] = temp; songplaylist[playlistSpot + 1] = d; } void playSongFromPlaylist(int playlistSpot) { songname[songplaylist[playlistSpot]].playMedia(); } void pauseSongFromPlaylist(int playlistSpot) { songname[songplaylist[playlistSpot]].pauseMedia(); } void stopSongFromPlaylist(int playlistSpot) { songname[songplaylist[playlistSpot]].stopMedia(); }
#include "stdafx.h" //needed for the Windows display #include "globals.h" //some global variables are included here #include <cstdlib> //standard c library #include "mediaItem.h" //the mediaItem class #include "song.h" #include <fstream> #include <string> using namespace std; //Global declarations ifstream file; song songname[MAX_SONGS]; int songplaylist[MAX_PLAYLIST]; int number_of_songs = 0; int counter = 0; bool loadSongList(string filename) { string artist[100]; string name[100]; string location[100]; int a = 0; file.open(filename); // input string filename if (file.is_open()) { file >> number_of_songs; // number of songs. file.ignore(); // ignore the first line (number of songs) from text file. while (file.good()) // gets next line { getline(file, artist[a]); //reads line by line. getline(file, name[a]); getline(file, location[a]); a++; } a--; for (int i = 0; i < number_of_songs; i++) { songname[i].setArtist(artist[i]); //sets artist songname[i].setTitle(name[i]); //sets title songname[i].setLocation(location[i]); //sets location } return true; } else return false; } int getNumberOfSongsInSongList() { return number_of_songs; } string getSongNameFromSongList(int songNum) { return songname[songNum].getArtist() + " - " + songname[songNum].getTitle(); } string getSongNameFromPlaylist(int playlistSpot) { string songfile; //song choice int songspot = songplaylist[playlistSpot]; string artist = songname[songspot].getArtist(); // get artist from playlist string songtitle = songname[songspot].getTitle(); int sizeofartist = artist.length(); // finds length of artist and title. int sizeofsong = songtitle.length(); for (int i = 0; i < sizeofartist; i++) //loads each character into array (artist) songfile.push_back(artist[i]); songfile.push_back(' '); //adds space between artist and title. songfile.push_back('-'); songfile.push_back(' '); for (int i = 0; i < sizeofsong; i++) // loads each character into array (title) songfile.push_back(songtitle[i]); return songfile; } void addSongToPlaylist(int songNum) { songplaylist[counter] = songNum; // playlist songs is equal to the number of the song. points to location of song. counter = counter + 1; // adds song to playlist, keeps a counter. } int getNumberOfSongsInPlaylist() { return counter; // amount of songs in playlist. } void removeSongFromPlaylist(int playlistSpot) { int temp[MAX_PLAYLIST]; int j = 0; for (int i = 0; i < MAX_PLAYLIST; i++) // creates temp array, copies songplaylist temp[i] = songplaylist[i]; for (int i = 0; i < MAX_PLAYLIST; i++) // erases songplaylist songplaylist[i] = -1; for (int i = 0; i < MAX_PLAYLIST; i++) // reprints array. { if (i != playlistSpot) { songplaylist[j] = temp[i]; j++; } } counter--; // keeps counter of playlist songs. } void clearPlaylist() { for (int i = 0; i < MAX_PLAYLIST; i++) // takes all playlist songs and sets them to -1. songplaylist[i] = -1; counter = 0; //resets counter to zero. } void moveSongUpInPlaylist(int playlistSpot) { // flips the selected song with the song below. int counter2 = 0; int d = songplaylist[playlistSpot]; int temp = songplaylist[playlistSpot - 1]; songplaylist[playlistSpot] = temp; //flip the songs. songplaylist[playlistSpot - 1] = d; } void moveSongDownInPlaylist(int playlistSpot) { // same way as moving list up but in reversed. int d = songplaylist[playlistSpot]; int temp = songplaylist[playlistSpot + 1]; songplaylist[playlistSpot] = temp; songplaylist[playlistSpot + 1] = d; } void playSongFromPlaylist(int playlistSpot) { songname[songplaylist[playlistSpot]].playMedia(); } void pauseSongFromPlaylist(int playlistSpot) { songname[songplaylist[playlistSpot]].pauseMedia(); } void stopSongFromPlaylist(int playlistSpot) { songname[songplaylist[playlistSpot]].stopMedia(); }
Update main.cpp
Update main.cpp fixed some comment errors
C++
mit
InvdrZim13/Basic-Music-Player
4161b8317c026adeba489a393f1a2b7caedbb0ce
PWGPP/CalibMacros/CPass0/runCalibTrain.C
PWGPP/CalibMacros/CPass0/runCalibTrain.C
/* Template of calibration/filtering macro using ESD: - requires AliESDs.root and AliESDfriend.root - requires OCDB access (default set to "raw://") - requires run number as argument to init OCDB - calls LoadLibraries.C, ConfigCalibTrain.C and AddTaskTPCCalib.C macros - output CalibObjects.root with TPC and TRD calibration objects are created Example: .L $ALICE_PHYSICS/ANALYSIS/macros/runCalibTrain.C runCalibTrain("104892"); */ void runCalibTrain(Int_t runNumber, const char *inFileName = "AliESDs.root", const char *ocdb="raw://") { // // macro to run TPC calibration train // TStopwatch sw; sw.Start(); AliSysInfo::SetVerbose(kTRUE); AliLog::SetGlobalLogLevel(AliLog::kError); gROOT->Macro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/LoadLibraries.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/ConfigCalibTrain.C"); gSystem->SetIncludePath("-I$ALICE_PHYSICS/include -I$ALICE_ROOT/include"); if (gSystem->Exec("cp $ALICE_PHYSICS/PWGPP/CalibMacros/commonMacros/CleanGeom.C ./") || gROOT->LoadMacro("CleanGeom.C++")) { // comple local copy only printf("Failed to load/compile CleanGeom, exit\n"); return; } // detector tasks gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTPCCalib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTRDCalib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTOFAnalysisTaskCalibPass0.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskT0Calib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskMeanVertexCalib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskSDDCalib.C"); // switch off debug AliLog::SetClassDebugLevel("AliESDEvent",0); // steering input chain TChain *chain = new TChain("esdTree"); chain->Add(inFileName); // config calibration train // setting geometry and B-field from GRP printf("runNumber from runCalibTrain = %d\n",runNumber); printf("ocdb from runCalibTrain = %s\n",ocdb); if (gSystem->AccessPathName("OCDB.root", kFileExists)==0) { AliCDBManager::Instance()->SetSnapshotMode("OCDB.root"); printf("ocdb from snapshot\n"); } AliSysInfo::AddStamp("BeforeConfiguringCalibTrain"); ConfigCalibTrain(runNumber, ocdb); AliSysInfo::AddStamp("AfterConfiguringCalibTrain"); if (gROOT->LoadMacro("localOCDBaccessConfig.C")==0) { localOCDBaccessConfig(); } // // check the presence of the detectors AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data"); AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject()); if (!grpData) {printf("Failed to get GRP data for run",runNumber); return;} Int_t activeDetectors = grpData->GetDetectorMask(); TString detStr = AliDAQ::ListOfTriggeredDetectors(activeDetectors); printf("Detectors in the data:\n%s\n",detStr.Data()); // setup analysis // AliAnalysisManager *mgr = new AliAnalysisManager("ESD to ESD", "Analysis Manager"); // mgr->SetDebugLevel(3); mgr->SetNSysInfo(50); mgr->SetCacheSize(0); // Input AliESDInputHandler* inpHandler = new AliESDInputHandler(); inpHandler->SetReadFriends(1); mgr->SetInputEventHandler(inpHandler); // Output const char *outFile = "CalibObjects.root"; AliESDHandler* esdHandler = new AliESDHandler(); mgr->SetOutputEventHandler(esdHandler); esdHandler->SetOutputFileName(outFile); mgr->SetCommonFileName(outFile); // // Detector Tasks // AliSysInfo::AddStamp("BeforeTPC"); if ( detStr.Contains("TPC")) AddTaskTPCCalib(runNumber); AliSysInfo::AddStamp("BeforeTRD"); if ( detStr.Contains("TRD") && detStr.Contains("TPC")) AddTaskTRDCalib(runNumber); AliSysInfo::AddStamp("BeforeT0"); if ( detStr.Contains("T0")) AddTaskT0Calib(runNumber); AliSysInfo::AddStamp("BeforeMeanVertex"); if ( detStr.Contains("ITSSPD")) AddTaskMeanVertexCalib(); // /* Bool_t okTPC = detStr.Contains("TPC"); Bool_t useTPCcrv=kTRUE; Bool_t writeITSTP = kFALSE; if (!okTPC) useTPCcrv = kFALSE; AliSysInfo::AddStamp("BeforeSDD"); AliAnalysisTaskITSAlignQA *itsAlign = AddTaskSDDCalib(0,writeITSTP,useTPCcrv, detStr.Contains("TOF") ? 10.0:-1); if (!okTPC) itsAlign->SetUseITSstandaloneTracks(kTRUE); if (grpData->GetL3Current()[0] < 300) itsAlign->SetMinPt(0.001); */ // Make sure the TOF is the last one since it modifies the ESDevent AliSysInfo::AddStamp("BeforeTOF"); if ( detStr.Contains("TOF") && detStr.Contains("TPC")) AddTOFAnalysisTaskCalibPass0(); // // dummy task to clean geometry in Terminate >>>> CleanGeom* clgmTask = new CleanGeom("cleanGeom"); mgr->AddTask(clgmTask); AliAnalysisDataContainer *dummyInp = mgr->GetCommonInputContainer(); if (dummyInp) mgr->ConnectInput(clgmTask,0,dummyInp); // Run the analysis AliSysInfo::AddStamp("BeforeInitAnalysis"); if (!mgr->InitAnalysis()) { printf("Analysis cannot be started, returning\n"); return; } mgr->PrintStatus(); AliSysInfo::AddStamp("BeforeStartAnalysis"); sw.Stop(); printf("runCalibTrain: Config time: "); sw.Print(); sw.Start(kTRUE); mgr->StartAnalysis("local", chain); sw.Stop(); printf("runCalibTrain: Processing time: "); sw.Print(); return; }
/* Template of calibration/filtering macro using ESD: - requires AliESDs.root and AliESDfriend.root - requires OCDB access (default set to "raw://") - requires run number as argument to init OCDB - calls LoadLibraries.C, ConfigCalibTrain.C and AddTaskTPCCalib.C macros - output CalibObjects.root with TPC and TRD calibration objects are created Example: .L $ALICE_PHYSICS/ANALYSIS/macros/runCalibTrain.C runCalibTrain("104892"); */ void runCalibTrain(Int_t runNumber, const char *inFileName = "AliESDs.root", const char *ocdb="raw://") { // // macro to run TPC calibration train // TStopwatch sw; sw.Start(); AliSysInfo::SetVerbose(kTRUE); AliLog::SetGlobalLogLevel(AliLog::kError); gROOT->Macro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/LoadLibraries.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/ConfigCalibTrain.C"); gSystem->SetIncludePath("-I$ALICE_PHYSICS/include -I$ALICE_ROOT/include"); if (gSystem->Exec("cp $ALICE_PHYSICS/PWGPP/CalibMacros/commonMacros/CleanGeom.C ./") || gROOT->LoadMacro("CleanGeom.C++")) { // comple local copy only printf("Failed to load/compile CleanGeom, exit\n"); return; } // detector tasks gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTPCCalib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTRDCalib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTOFAnalysisTaskCalibPass0.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskT0Calib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskMeanVertexCalib.C"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskSDDCalib.C"); // switch off debug AliLog::SetClassDebugLevel("AliESDEvent",0); // steering input chain TChain *chain = new TChain("esdTree"); chain->Add(inFileName); // config calibration train // setting geometry and B-field from GRP printf("runNumber from runCalibTrain = %d\n",runNumber); printf("ocdb from runCalibTrain = %s\n",ocdb); if (gSystem->AccessPathName("OCDB.root", kFileExists)==0) { AliCDBManager::Instance()->SetSnapshotMode("OCDB.root"); printf("ocdb from snapshot\n"); } AliSysInfo::AddStamp("BeforeConfiguringCalibTrain"); ConfigCalibTrain(runNumber, ocdb); AliSysInfo::AddStamp("AfterConfiguringCalibTrain"); if (gROOT->LoadMacro("localOCDBaccessConfig.C")==0) { localOCDBaccessConfig(); } // // check the presence of the detectors AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data"); AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject()); if (!grpData) {printf("Failed to get GRP data for run",runNumber); return;} Int_t activeDetectors = grpData->GetDetectorMask(); TString detStr = AliDAQ::ListOfTriggeredDetectors(activeDetectors); printf("Detectors in the data:\n%s\n",detStr.Data()); // setup analysis // AliAnalysisManager *mgr = new AliAnalysisManager("ESD to ESD", "Analysis Manager"); // mgr->SetDebugLevel(3); mgr->SetNSysInfo(50); mgr->SetCacheSize(0); // Input AliESDInputHandler* inpHandler = new AliESDInputHandler(); inpHandler->SetReadFriends(1); mgr->SetInputEventHandler(inpHandler); // Output const char *outFile = "CalibObjects.root"; AliESDHandler* esdHandler = new AliESDHandler(); mgr->SetOutputEventHandler(esdHandler); esdHandler->SetOutputFileName(outFile); mgr->SetCommonFileName(outFile); // // Detector Tasks // AliSysInfo::AddStamp("BeforeTPC"); if ( detStr.Contains("TPC")) AddTaskTPCCalib(); AliSysInfo::AddStamp("BeforeTRD"); if ( detStr.Contains("TRD") && detStr.Contains("TPC")) AddTaskTRDCalib(runNumber); AliSysInfo::AddStamp("BeforeT0"); if ( detStr.Contains("T0")) AddTaskT0Calib(runNumber); AliSysInfo::AddStamp("BeforeMeanVertex"); if ( detStr.Contains("ITSSPD")) AddTaskMeanVertexCalib(); // /* Bool_t okTPC = detStr.Contains("TPC"); Bool_t useTPCcrv=kTRUE; Bool_t writeITSTP = kFALSE; if (!okTPC) useTPCcrv = kFALSE; AliSysInfo::AddStamp("BeforeSDD"); AliAnalysisTaskITSAlignQA *itsAlign = AddTaskSDDCalib(0,writeITSTP,useTPCcrv, detStr.Contains("TOF") ? 10.0:-1); if (!okTPC) itsAlign->SetUseITSstandaloneTracks(kTRUE); if (grpData->GetL3Current()[0] < 300) itsAlign->SetMinPt(0.001); */ // Make sure the TOF is the last one since it modifies the ESDevent AliSysInfo::AddStamp("BeforeTOF"); if ( detStr.Contains("TOF") && detStr.Contains("TPC")) AddTOFAnalysisTaskCalibPass0(); // // dummy task to clean geometry in Terminate >>>> CleanGeom* clgmTask = new CleanGeom("cleanGeom"); mgr->AddTask(clgmTask); AliAnalysisDataContainer *dummyInp = mgr->GetCommonInputContainer(); if (dummyInp) mgr->ConnectInput(clgmTask,0,dummyInp); // Run the analysis AliSysInfo::AddStamp("BeforeInitAnalysis"); if (!mgr->InitAnalysis()) { printf("Analysis cannot be started, returning\n"); return; } mgr->PrintStatus(); AliSysInfo::AddStamp("BeforeStartAnalysis"); sw.Stop(); printf("runCalibTrain: Config time: "); sw.Print(); sw.Start(kTRUE); mgr->StartAnalysis("local", chain); sw.Stop(); printf("runCalibTrain: Processing time: "); sw.Print(); return; }
Remove run number from calling AddTaskTPCCalib()
Remove run number from calling AddTaskTPCCalib()
C++
bsd-3-clause
aaniin/AliPhysics,aaniin/AliPhysics,aaniin/AliPhysics,aaniin/AliPhysics,aaniin/AliPhysics,aaniin/AliPhysics,aaniin/AliPhysics
5571ef225138cc7124aeed382c1e5f1d10907161
Parallel/Testing/Cxx/DistributedData.cxx
Parallel/Testing/Cxx/DistributedData.cxx
/*========================================================================= Program: Visualization Toolkit Module: DistributedData.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. =========================================================================*/ // Test of vtkDistributedDataFilter and supporting classes, covering as much // code as possible. This test requires 4 MPI processes. // // To cover ghost cell creation, use vtkDataSetSurfaceFilter. // // To cover clipping code: SetBoundaryModeToSplitBoundaryCells() // // To run fast redistribution: SetUseMinimalMemoryOff() (Default) // To run memory conserving code instead: SetUseMinimalMemoryOn() #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkParallelFactory.h" #include "vtkCompositeRenderManager.h" #include "vtkDataSetReader.h" #include "vtkUnstructuredGrid.h" #include "vtkDistributedDataFilter.h" #include "vtkDataSetSurfaceFilter.h" #include "vtkPieceScalars.h" #include "vtkMultiProcessController.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkPolyDataMapper.h" #include "vtkCamera.h" static int NumProcs, Me; struct DDArgs_tmp { int* retVal; int argc; char** argv; }; static void Run(vtkMultiProcessController *contr, void *arg) { int i; DDArgs_tmp *args = reinterpret_cast<DDArgs_tmp *>(arg); vtkCompositeRenderManager *prm = vtkCompositeRenderManager::New(); // READER vtkDataSetReader *dsr = vtkDataSetReader::New(); vtkUnstructuredGrid *ug = vtkUnstructuredGrid::New(); vtkDataSet *ds = NULL; if (Me == 0) { char* fname = vtkTestUtilities::ExpandDataFileName( args->argc, args->argv, "Data/tetraMesh.vtk"); dsr->SetFileName(fname); ds = dsr->GetOutput(); } else { ds = (vtkDataSet *)ug; } // DATA DISTRIBUTION FILTER vtkDistributedDataFilter *dd = vtkDistributedDataFilter::New(); dd->SetInput(ds); dd->SetController(contr); dd->SetBoundaryModeToSplitBoundaryCells(); // clipping dd->UseMinimalMemoryOff(); // COLOR BY PROCESS NUMBER vtkPieceScalars *ps = vtkPieceScalars::New(); ps->SetInput((vtkDataSet *)dd->GetOutput()); ps->SetScalarModeToCellData(); // MORE FILTERING - this will request ghost cells vtkDataSetSurfaceFilter *dss = vtkDataSetSurfaceFilter::New(); dss->SetInput(ps->GetOutput()); // COMPOSITE RENDER vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput(dss->GetOutput()); mapper->SetColorModeToMapScalars(); mapper->SetScalarModeToUseCellFieldData(); mapper->SelectColorArray("Piece"); mapper->SetScalarRange(0, NumProcs-1); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); vtkRenderer *renderer = prm->MakeRenderer(); renderer->AddActor(actor); vtkRenderWindow *renWin = prm->MakeRenderWindow(); renWin->AddRenderer(renderer); renderer->SetBackground(0,0,0); renWin->SetSize(300,300); renWin->SetPosition(0, 360*Me); prm->SetRenderWindow(renWin); prm->SetController(contr); prm->InitializeOffScreen(); // Mesa GL only // We must update the whole pipeline here, otherwise node 0 // goes into GetActiveCamera which updates the pipeline, putting // it into vtkDistributedDataFilter::Execute() which then hangs. // If it executes here, dd will be up-to-date won't have to // execute in GetActiveCamera. mapper->SetPiece(Me); mapper->SetNumberOfPieces(NumProcs); mapper->Update(); if (Me == 0) { vtkCamera *camera = renderer->GetActiveCamera(); camera->UpdateViewport(renderer); camera->ParallelProjectionOn(); camera->SetParallelScale(16); renWin->Render(); renWin->Render(); *(args->retVal) = vtkRegressionTester::Test(args->argc, args->argv, renWin, 10); for (i=1; i < NumProcs; i++) { contr->Send(args->retVal, 1, i, 0x11); } prm->StopServices(); } else { prm->StartServices(); contr->Receive(args->retVal, 1, 0, 0x11); } if (*(args->retVal) == vtkTesting::PASSED) { // Now try using the memory conserving *Lean methods. The // image produced should be identical dd->UseMinimalMemoryOn(); mapper->SetPiece(Me); mapper->SetNumberOfPieces(NumProcs); mapper->Update(); if (Me == 0) { vtkCamera *camera = renderer->GetActiveCamera(); camera->UpdateViewport(renderer); camera->ParallelProjectionOn(); camera->SetParallelScale(16); renWin->Render(); renWin->Render(); *(args->retVal) = vtkRegressionTester::Test(args->argc, args->argv, renWin, 10); for (i=1; i < NumProcs; i++) { contr->Send(args->retVal, 1, i, 0x11); } prm->StopServices(); } else { prm->StartServices(); contr->Receive(args->retVal, 1, 0, 0x11); } } // CLEAN UP mapper->Delete(); actor->Delete(); renderer->Delete(); renWin->Delete(); dd->Delete(); dsr->Delete(); ug->Delete(); ps->Delete(); dss->Delete(); prm->Delete(); } int main(int argc, char **argv) { int retVal = 1; vtkMultiProcessController *contr = vtkMultiProcessController::New(); contr->Initialize(&argc, &argv); vtkMultiProcessController::SetGlobalController(contr); NumProcs = contr->GetNumberOfProcesses(); Me = contr->GetLocalProcessId(); if (NumProcs != 2) { if (Me == 0) { cout << "DistributedData test requires 2 processes" << endl; } contr->Delete(); return retVal; } if (!contr->IsA("vtkMPIController")) { if (Me == 0) { cout << "DistributedData test requires MPI" << endl; } contr->Delete(); return retVal; // is this the right error val? TODO } // ---------------------------------------------- DDArgs_tmp args; args.retVal = &retVal; args.argc = argc; args.argv = argv; // --------------------------------------------- contr->SetSingleMethod(Run, &args); contr->SingleMethodExecute(); contr->Finalize(); contr->Delete(); return !retVal; }
/*========================================================================= Program: Visualization Toolkit Module: DistributedData.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. =========================================================================*/ // Test of vtkDistributedDataFilter and supporting classes, covering as much // code as possible. This test requires 4 MPI processes. // // To cover ghost cell creation, use vtkDataSetSurfaceFilter. // // To cover clipping code: SetBoundaryModeToSplitBoundaryCells() // // To run fast redistribution: SetUseMinimalMemoryOff() (Default) // To run memory conserving code instead: SetUseMinimalMemoryOn() #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkParallelFactory.h" #include "vtkCompositeRenderManager.h" #include "vtkDataSetReader.h" #include "vtkUnstructuredGrid.h" #include "vtkDistributedDataFilter.h" #include "vtkDataSetSurfaceFilter.h" #include "vtkPieceScalars.h" #include "vtkMultiProcessController.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkPolyDataMapper.h" #include "vtkCamera.h" /* ** This test only builds if MPI is in use */ #include "vtkMPICommunicator.h" static int NumProcs, Me; struct DDArgs_tmp { int* retVal; int argc; char** argv; }; static void Run(vtkMultiProcessController *contr, void *arg) { int i, go; DDArgs_tmp *args = reinterpret_cast<DDArgs_tmp *>(arg); vtkCompositeRenderManager *prm = vtkCompositeRenderManager::New(); // READER vtkDataSetReader *dsr = vtkDataSetReader::New(); vtkUnstructuredGrid *ug = vtkUnstructuredGrid::New(); vtkDataSet *ds = NULL; if (Me == 0) { char* fname = vtkTestUtilities::ExpandDataFileName( args->argc, args->argv, "Data/tetraMesh.vtk"); dsr->SetFileName(fname); ds = dsr->GetOutput(); dsr->Update(); go = 1; if ((ds == NULL) || (ds->GetNumberOfCells() == 0)) { if (ds) cout << "Failure: input file has no cells" << endl; go = 0; } } else { ds = (vtkDataSet *)ug; } vtkMPICommunicator *comm = vtkMPICommunicator::SafeDownCast(contr->GetCommunicator()); comm->Broadcast(&go, 1, 0); if (!go){ dsr->Delete(); ug->Delete(); prm->Delete(); return; } // DATA DISTRIBUTION FILTER vtkDistributedDataFilter *dd = vtkDistributedDataFilter::New(); dd->SetInput(ds); dd->SetController(contr); dd->SetBoundaryModeToSplitBoundaryCells(); // clipping dd->UseMinimalMemoryOff(); // COLOR BY PROCESS NUMBER vtkPieceScalars *ps = vtkPieceScalars::New(); ps->SetInput((vtkDataSet *)dd->GetOutput()); ps->SetScalarModeToCellData(); // MORE FILTERING - this will request ghost cells vtkDataSetSurfaceFilter *dss = vtkDataSetSurfaceFilter::New(); dss->SetInput(ps->GetOutput()); // COMPOSITE RENDER vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput(dss->GetOutput()); mapper->SetColorModeToMapScalars(); mapper->SetScalarModeToUseCellFieldData(); mapper->SelectColorArray("Piece"); mapper->SetScalarRange(0, NumProcs-1); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); vtkRenderer *renderer = prm->MakeRenderer(); renderer->AddActor(actor); vtkRenderWindow *renWin = prm->MakeRenderWindow(); renWin->AddRenderer(renderer); renderer->SetBackground(0,0,0); renWin->SetSize(300,300); renWin->SetPosition(0, 360*Me); prm->SetRenderWindow(renWin); prm->SetController(contr); prm->InitializeOffScreen(); // Mesa GL only // We must update the whole pipeline here, otherwise node 0 // goes into GetActiveCamera which updates the pipeline, putting // it into vtkDistributedDataFilter::Execute() which then hangs. // If it executes here, dd will be up-to-date won't have to // execute in GetActiveCamera. mapper->SetPiece(Me); mapper->SetNumberOfPieces(NumProcs); mapper->Update(); if (Me == 0) { vtkCamera *camera = renderer->GetActiveCamera(); camera->UpdateViewport(renderer); camera->ParallelProjectionOn(); camera->SetParallelScale(16); renWin->Render(); renWin->Render(); *(args->retVal) = vtkRegressionTester::Test(args->argc, args->argv, renWin, 10); for (i=1; i < NumProcs; i++) { contr->Send(args->retVal, 1, i, 0x11); } prm->StopServices(); } else { prm->StartServices(); contr->Receive(args->retVal, 1, 0, 0x11); } if (*(args->retVal) == vtkTesting::PASSED) { // Now try using the memory conserving *Lean methods. The // image produced should be identical dd->UseMinimalMemoryOn(); mapper->SetPiece(Me); mapper->SetNumberOfPieces(NumProcs); mapper->Update(); if (Me == 0) { vtkCamera *camera = renderer->GetActiveCamera(); camera->UpdateViewport(renderer); camera->ParallelProjectionOn(); camera->SetParallelScale(16); renWin->Render(); renWin->Render(); *(args->retVal) = vtkRegressionTester::Test(args->argc, args->argv, renWin, 10); for (i=1; i < NumProcs; i++) { contr->Send(args->retVal, 1, i, 0x11); } prm->StopServices(); } else { prm->StartServices(); contr->Receive(args->retVal, 1, 0, 0x11); } } // CLEAN UP mapper->Delete(); actor->Delete(); renderer->Delete(); renWin->Delete(); dd->Delete(); dsr->Delete(); ug->Delete(); ps->Delete(); dss->Delete(); prm->Delete(); } int main(int argc, char **argv) { int retVal = 1; vtkMultiProcessController *contr = vtkMultiProcessController::New(); contr->Initialize(&argc, &argv); vtkMultiProcessController::SetGlobalController(contr); NumProcs = contr->GetNumberOfProcesses(); Me = contr->GetLocalProcessId(); if (NumProcs != 2) { if (Me == 0) { cout << "DistributedData test requires 2 processes" << endl; } contr->Delete(); return retVal; } if (!contr->IsA("vtkMPIController")) { if (Me == 0) { cout << "DistributedData test requires MPI" << endl; } contr->Delete(); return retVal; // is this the right error val? TODO } // ---------------------------------------------- DDArgs_tmp args; args.retVal = &retVal; args.argc = argc; args.argv = argv; // --------------------------------------------- contr->SetSingleMethod(Run, &args); contr->SingleMethodExecute(); contr->Finalize(); contr->Delete(); return !retVal; }
Exit the test if the input file is not found.
BUG: Exit the test if the input file is not found.
C++
bsd-3-clause
sgh/vtk,spthaolt/VTK,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,sgh/vtk,demarle/VTK,jeffbaumes/jeffbaumes-vtk,spthaolt/VTK,SimVascular/VTK,keithroe/vtkoptix,sankhesh/VTK,cjh1/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,candy7393/VTK,arnaudgelas/VTK,ashray/VTK-EVM,sgh/vtk,hendradarwin/VTK,cjh1/VTK,mspark93/VTK,jmerkow/VTK,jmerkow/VTK,keithroe/vtkoptix,sumedhasingla/VTK,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,sgh/vtk,daviddoria/PointGraphsPhase1,aashish24/VTK-old,gram526/VTK,spthaolt/VTK,collects/VTK,ashray/VTK-EVM,SimVascular/VTK,Wuteyan/VTK,sankhesh/VTK,biddisco/VTK,collects/VTK,collects/VTK,ashray/VTK-EVM,msmolens/VTK,daviddoria/PointGraphsPhase1,msmolens/VTK,ashray/VTK-EVM,keithroe/vtkoptix,sumedhasingla/VTK,aashish24/VTK-old,aashish24/VTK-old,arnaudgelas/VTK,johnkit/vtk-dev,Wuteyan/VTK,sankhesh/VTK,SimVascular/VTK,spthaolt/VTK,hendradarwin/VTK,sankhesh/VTK,naucoin/VTKSlicerWidgets,msmolens/VTK,berendkleinhaneveld/VTK,candy7393/VTK,hendradarwin/VTK,Wuteyan/VTK,sgh/vtk,ashray/VTK-EVM,SimVascular/VTK,candy7393/VTK,jmerkow/VTK,demarle/VTK,msmolens/VTK,gram526/VTK,sankhesh/VTK,arnaudgelas/VTK,arnaudgelas/VTK,spthaolt/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,hendradarwin/VTK,candy7393/VTK,ashray/VTK-EVM,demarle/VTK,demarle/VTK,gram526/VTK,biddisco/VTK,SimVascular/VTK,spthaolt/VTK,daviddoria/PointGraphsPhase1,sankhesh/VTK,SimVascular/VTK,johnkit/vtk-dev,hendradarwin/VTK,aashish24/VTK-old,demarle/VTK,Wuteyan/VTK,jmerkow/VTK,candy7393/VTK,sumedhasingla/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,mspark93/VTK,mspark93/VTK,mspark93/VTK,arnaudgelas/VTK,daviddoria/PointGraphsPhase1,demarle/VTK,msmolens/VTK,sumedhasingla/VTK,naucoin/VTKSlicerWidgets,naucoin/VTKSlicerWidgets,SimVascular/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,gram526/VTK,biddisco/VTK,keithroe/vtkoptix,keithroe/vtkoptix,cjh1/VTK,johnkit/vtk-dev,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,gram526/VTK,johnkit/vtk-dev,gram526/VTK,sgh/vtk,jmerkow/VTK,arnaudgelas/VTK,biddisco/VTK,Wuteyan/VTK,sumedhasingla/VTK,collects/VTK,jmerkow/VTK,aashish24/VTK-old,collects/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,biddisco/VTK,Wuteyan/VTK,sankhesh/VTK,sumedhasingla/VTK,biddisco/VTK,mspark93/VTK,candy7393/VTK,cjh1/VTK,keithroe/vtkoptix,sankhesh/VTK,gram526/VTK,cjh1/VTK,jeffbaumes/jeffbaumes-vtk,gram526/VTK,johnkit/vtk-dev,spthaolt/VTK,berendkleinhaneveld/VTK,candy7393/VTK,SimVascular/VTK,Wuteyan/VTK,sumedhasingla/VTK,johnkit/vtk-dev,ashray/VTK-EVM,hendradarwin/VTK,collects/VTK,demarle/VTK,keithroe/vtkoptix,jmerkow/VTK,mspark93/VTK,mspark93/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,aashish24/VTK-old,msmolens/VTK,cjh1/VTK,biddisco/VTK,msmolens/VTK,candy7393/VTK,msmolens/VTK
fc5994fe8cc9a9d253501527a98f49f4eea8e445
syncevolution/ActiveSyncSourceRegister.cpp
syncevolution/ActiveSyncSourceRegister.cpp
/* * Copyright (C) 2008-2009 Patrick Ohly <[email protected]> * Copyright (C) 2009 Intel Corporation * * 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) version 3. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "ActiveSyncSource.h" #include "ActiveSyncCalendarSource.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef ENABLE_UNIT_TESTS # include <cppunit/extensions/TestFactoryRegistry.h> # include <cppunit/extensions/HelperMacros.h> #endif #include <fstream> #include <syncevo/declarations.h> SE_BEGIN_CXX static SyncSource *createSource(const SyncSourceParams &params) { SourceType sourceType = SyncSource::getSourceType(params.m_nodes); bool isMe; isMe = sourceType.m_backend == "ActiveSync Address Book"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncContactSource(params) #else RegisterSyncSource::InactiveSource #endif ; } isMe = sourceType.m_backend == "ActiveSync Events"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncCalendarSource(params, EAS_ITEM_CALENDAR) #else RegisterSyncSource::InactiveSource #endif ; } isMe = sourceType.m_backend == "ActiveSync Todos"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncCalFormatSource(params, EAS_ITEM_TODO) #else RegisterSyncSource::InactiveSource #endif ; } isMe = sourceType.m_backend == "ActiveSync Memos"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncCalFormatSource(params, EAS_ITEM_JOURNAL) #else RegisterSyncSource::InactiveSource #endif ; } return NULL; } static RegisterSyncSource registerMe("ActiveSync", #ifdef ENABLE_ACTIVESYNC true, #else false, #endif createSource, "ActiveSync Address Book = eas-contacts\n" "ActiveSync Events = eas-events\n" "ActiveSync Todos = eas-todos\n" "ActiveSync Memos = eas-memos", Values() + (Aliases("ActiveSync Address Book") + "eas-contacts") + (Aliases("ActiveSync Events") + "eas-events") + (Aliases("ActiveSync Todos") + "eas-todos") + (Aliases("ActiveSync Memos") + "eas-memos")); #ifdef ENABLE_ACTIVESYNC #ifdef ENABLE_UNIT_TESTS class ActiveSyncsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ActiveSyncsTest); CPPUNIT_TEST(testInstantiate); CPPUNIT_TEST_SUITE_END(); protected: void testInstantiate() { boost::shared_ptr<SyncSource> source; source.reset(SyncSource::createTestingSource("contacts", "ActiveSync Address Book", true)); source.reset(SyncSource::createTestingSource("events", "ActiveSync Events", true)); source.reset(SyncSource::createTestingSource("todos", "ActiveSync Todos", true)); source.reset(SyncSource::createTestingSource("memos", "ActiveSync Memos", true)); } }; SYNCEVOLUTION_TEST_SUITE_REGISTRATION(ActiveSyncsTest); #endif // ENABLE_UNIT_TESTS #ifdef ENABLE_INTEGRATION_TESTS namespace { #if 0 } #endif /** * Takes all existing items in the source and writes them into the file, * separated by a blank line. beginSync() with the previous sync key was * already called. * * Used for testing and thus should better not rely on cached information, * but ActiveSync doesn't offer an independent "list and/or retrieve all items" * operation. Using the cached information implies that we won't find bugs in * the handling of that information. */ static int DumpItems(ClientTest &client, TestingSyncSource &source, const char *file) { ActiveSyncSource &eassource = static_cast<ActiveSyncSource &>(source); ofstream out(file); // find all ActiveSync server IDs: in ActiveSyncCalendarSource, // each server ID might appear multiple times, once for each // recurrence associated with it std::set<std::string> easids; BOOST_FOREACH (const std::string &luid, eassource.getAllItems()) { // slight hack: we know that luids in ActiveSyncSource base // class pass through this method unmodified, so no need to // avoid it StringPair ids = ActiveSyncCalendarSource::splitLUID(luid); easids.insert(ids.first); } BOOST_FOREACH(const std::string &easid, easids) { std::string item; eassource.ActiveSyncSource::readItem(easid, item); out << item << '\n'; if (!boost::ends_with(item, "\n")) { out << '\n'; } } return 0; } static TestingSyncSource *createEASSource(const ClientTestConfig::createsource_t &create, ClientTest &client, int source, bool isSourceA) { TestingSyncSource *res = create(client, source, isSourceA); // Mangle username: if the base username in the config is account // "foo", then source B uses "foo_B", because otherwise it'll end // up sharing change tracking with source A. if (!isSourceA) { ActiveSyncSource *eassource = static_cast<ActiveSyncSource *>(res); std::string account = eassource->getSyncConfig().getSyncUsername(); account += "_B"; eassource->getSyncConfig().setSyncUsername(account, true); } if (boost::ends_with(res->getDatabaseID(), "_1")) { // only default database currently supported, // use that instead of first named database res->setDatabaseID(""); return res; } else { // sorry, no database delete res; return NULL; } } static class ActiveSyncContactTest : public RegisterSyncSourceTest { public: ActiveSyncContactTest() : RegisterSyncSourceTest("eas_contact", // name of test => Client::Source::eas_contact" "eds_contact" // name of test cases: inherit from EDS, override below ) {} virtual void updateConfig(ClientTestConfig &config) const { // override default eds_contact test config config.type = "eas-contacts"; // TODO: provide comprehensive set of vCard 3.0 contacts as they are understood by the ActiveSync library // config.testcases = "testcases/eas_contact.vcf"; // cannot run tests involving a second database: // wrap orginal source creation, set default database for // database #0 and refuse to return a source for database #1 config.createSourceA = boost::bind(createEASSource, config.createSourceA, _1, _2, _3); config.createSourceB = boost::bind(createEASSource, config.createSourceB, _1, _2, _3); config.dump = DumpItems; } } ActiveSyncContactTest; static class ActiveSyncEventTest : public RegisterSyncSourceTest { public: ActiveSyncEventTest() : RegisterSyncSourceTest("eas_event", "eds_event") {} virtual void updateConfig(ClientTestConfig &config) const { config.type = "eas-events"; config.createSourceA = boost::bind(createEASSource, config.createSourceA, _1, _2, _3); config.createSourceB = boost::bind(createEASSource, config.createSourceB, _1, _2, _3); config.dump = DumpItems; } } ActiveSyncEventTest; static class ActiveSyncTodoTest : public RegisterSyncSourceTest { public: ActiveSyncTodoTest() : RegisterSyncSourceTest("eas_task", "eds_task") {} virtual void updateConfig(ClientTestConfig &config) const { config.type = "eas-todos"; config.createSourceA = boost::bind(createEASSource, config.createSourceA, _1, _2, _3); config.createSourceB = boost::bind(createEASSource, config.createSourceB, _1, _2, _3); config.dump = DumpItems; } } ActiveSyncTodoTest; static class ActiveSyncMemoTest : public RegisterSyncSourceTest { public: ActiveSyncMemoTest() : RegisterSyncSourceTest("eas_memo", "eds_memo") {} virtual void updateConfig(ClientTestConfig &config) const { config.type = "eas-memos"; config.createSourceA = boost::bind(createEASSource, config.createSourceA, _1, _2, _3); config.createSourceB = boost::bind(createEASSource, config.createSourceB, _1, _2, _3); config.dump = DumpItems; } } ActiveSyncMemoTest; } // anonymous namespace #endif // ENABLE_INTEGRATION_TESTS #endif // ENABLE_ACTIVESYNC SE_END_CXX
/* * Copyright (C) 2008-2009 Patrick Ohly <[email protected]> * Copyright (C) 2009 Intel Corporation * * 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) version 3. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "ActiveSyncSource.h" #include "ActiveSyncCalendarSource.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef ENABLE_UNIT_TESTS # include <cppunit/extensions/TestFactoryRegistry.h> # include <cppunit/extensions/HelperMacros.h> #endif #include <fstream> #include <syncevo/declarations.h> SE_BEGIN_CXX static SyncSource *createSource(const SyncSourceParams &params) { SourceType sourceType = SyncSource::getSourceType(params.m_nodes); bool isMe; isMe = sourceType.m_backend == "ActiveSync Address Book"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncContactSource(params) #else RegisterSyncSource::InactiveSource #endif ; } isMe = sourceType.m_backend == "ActiveSync Events"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncCalendarSource(params, EAS_ITEM_CALENDAR) #else RegisterSyncSource::InactiveSource #endif ; } isMe = sourceType.m_backend == "ActiveSync Todos"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncCalFormatSource(params, EAS_ITEM_TODO) #else RegisterSyncSource::InactiveSource #endif ; } isMe = sourceType.m_backend == "ActiveSync Memos"; if (isMe) { return #ifdef ENABLE_ACTIVESYNC new ActiveSyncCalFormatSource(params, EAS_ITEM_JOURNAL) #else RegisterSyncSource::InactiveSource #endif ; } return NULL; } static RegisterSyncSource registerMe("ActiveSync", #ifdef ENABLE_ACTIVESYNC true, #else false, #endif createSource, "ActiveSync Address Book = eas-contacts\n" "ActiveSync Events = eas-events\n" "ActiveSync Todos = eas-todos\n" "ActiveSync Memos = eas-memos", Values() + (Aliases("ActiveSync Address Book") + "eas-contacts") + (Aliases("ActiveSync Events") + "eas-events") + (Aliases("ActiveSync Todos") + "eas-todos") + (Aliases("ActiveSync Memos") + "eas-memos")); #ifdef ENABLE_ACTIVESYNC #ifdef ENABLE_UNIT_TESTS class ActiveSyncsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ActiveSyncsTest); CPPUNIT_TEST(testInstantiate); CPPUNIT_TEST_SUITE_END(); protected: void testInstantiate() { boost::shared_ptr<SyncSource> source; source.reset(SyncSource::createTestingSource("contacts", "ActiveSync Address Book", true)); source.reset(SyncSource::createTestingSource("events", "ActiveSync Events", true)); source.reset(SyncSource::createTestingSource("todos", "ActiveSync Todos", true)); source.reset(SyncSource::createTestingSource("memos", "ActiveSync Memos", true)); } }; SYNCEVOLUTION_TEST_SUITE_REGISTRATION(ActiveSyncsTest); #endif // ENABLE_UNIT_TESTS #ifdef ENABLE_INTEGRATION_TESTS namespace { #if 0 } #endif /** * Takes all existing items in the source and writes them into the file, * separated by a blank line. beginSync() with the previous sync key was * already called. * * Used for testing and thus should better not rely on cached information, * but ActiveSync doesn't offer an independent "list and/or retrieve all items" * operation. Using the cached information implies that we won't find bugs in * the handling of that information. */ static int DumpItems(ClientTest &client, TestingSyncSource &source, const char *file) { ActiveSyncSource &eassource = static_cast<ActiveSyncSource &>(source); ofstream out(file); // find all ActiveSync server IDs: in ActiveSyncCalendarSource, // each server ID might appear multiple times, once for each // recurrence associated with it std::set<std::string> easids; BOOST_FOREACH (const std::string &luid, eassource.getAllItems()) { // slight hack: we know that luids in ActiveSyncSource base // class pass through this method unmodified, so no need to // avoid it StringPair ids = ActiveSyncCalendarSource::splitLUID(luid); easids.insert(ids.first); } BOOST_FOREACH(const std::string &easid, easids) { std::string item; eassource.ActiveSyncSource::readItem(easid, item); out << item << '\n'; if (!boost::ends_with(item, "\n")) { out << '\n'; } } return 0; } static TestingSyncSource *createEASSource(const ClientTestConfig::createsource_t &create, ClientTest &client, int source, bool isSourceA) { TestingSyncSource *res = create(client, source, isSourceA); // Mangle username: if the base username in the config is account // "foo", then source B uses "foo_B", because otherwise it'll end // up sharing change tracking with source A. if (!isSourceA) { ActiveSyncSource *eassource = static_cast<ActiveSyncSource *>(res); std::string account = eassource->getSyncConfig().getSyncUsername(); account += "_B"; eassource->getSyncConfig().setSyncUsername(account, true); } if (boost::ends_with(res->getDatabaseID(), "_1")) { // only default database currently supported, // use that instead of first named database res->setDatabaseID(""); return res; } else { // sorry, no database delete res; return NULL; } } // common settings for all kinds of data static void updateConfigEAS(const RegisterSyncSourceTest */* me */, ClientTestConfig &config) { // cannot run tests involving a second database: // wrap orginal source creation, set default database for // database #0 and refuse to return a source for database #1 config.createSourceA = boost::bind(createEASSource, config.createSourceA, _1, _2, _3); config.createSourceB = boost::bind(createEASSource, config.createSourceB, _1, _2, _3); config.dump = DumpItems; config.sourceLUIDsAreVolatile = true; } static class ActiveSyncContactTest : public RegisterSyncSourceTest { public: ActiveSyncContactTest() : RegisterSyncSourceTest("eas_contact", // name of test => Client::Source::eas_contact" "eds_contact" // name of test cases: inherit from EDS, override below ) {} virtual void updateConfig(ClientTestConfig &config) const { // override default eds_contact test config config.type = "eas-contacts"; // TODO: provide comprehensive set of vCard 3.0 contacts as they are understood by the ActiveSync library // config.testcases = "testcases/eas_contact.vcf"; updateConfigEAS(this, config); } } ActiveSyncContactTest; static class ActiveSyncEventTest : public RegisterSyncSourceTest { public: ActiveSyncEventTest() : RegisterSyncSourceTest("eas_event", "eds_event") {} virtual void updateConfig(ClientTestConfig &config) const { config.type = "eas-events"; updateConfigEAS(this, config); } } ActiveSyncEventTest; static class ActiveSyncTodoTest : public RegisterSyncSourceTest { public: ActiveSyncTodoTest() : RegisterSyncSourceTest("eas_task", "eds_task") {} virtual void updateConfig(ClientTestConfig &config) const { config.type = "eas-todos"; updateConfigEAS(this, config); } } ActiveSyncTodoTest; static class ActiveSyncMemoTest : public RegisterSyncSourceTest { public: ActiveSyncMemoTest() : RegisterSyncSourceTest("eas_memo", "eds_memo") {} virtual void updateConfig(ClientTestConfig &config) const { config.type = "eas-memos"; updateConfigEAS(this, config); } } ActiveSyncMemoTest; } // anonymous namespace #endif // ENABLE_INTEGRATION_TESTS #endif // ENABLE_ACTIVESYNC SE_END_CXX
set "sourceLUIDsAreVolatile"
syncevolution: set "sourceLUIDsAreVolatile" Client::Source::eas_event::TestLinkedItems failed because it made the assumption that LUIDs are the same for all clients. With ActiveSync they are not (get renumbered in the initial sync), so this particular aspect of the tests has to be disabled.
C++
lgpl-2.1
simo5/evolution-activesync,simo5/evolution-activesync,simo5/evolution-activesync
8c0f6ee4c6693cee1c349208a2606ebbb888444f
test/dyn_vector.cpp
test/dyn_vector.cpp
#include "catch.hpp" #include "etl/dyn_vector.hpp" //{{{ Init tests TEST_CASE( "dyn_vector/init_1", "dyn_vector::dyn_vector(T)" ) { etl::dyn_vector<double> test_vector(4, 3.3); REQUIRE(test_vector.size() == 4); for(std::size_t i = 0; i < test_vector.size(); ++i){ REQUIRE(test_vector[i] == 3.3); REQUIRE(test_vector(i) == 3.3); } } TEST_CASE( "dyn_vector/init_2", "dyn_vector::operator=(T)" ) { etl::dyn_vector<double> test_vector(4); test_vector = 3.3; REQUIRE(test_vector.size() == 4); for(std::size_t i = 0; i < test_vector.size(); ++i){ REQUIRE(test_vector[i] == 3.3); REQUIRE(test_vector(i) == 3.3); } } TEST_CASE( "dyn_vector/init_3", "dyn_vector::dyn_vector(initializer_list)" ) { etl::dyn_vector<double> test_vector = {1.0, 2.0, 3.0}; REQUIRE(test_vector.size() == 3); REQUIRE(test_vector[0] == 1.0); REQUIRE(test_vector[1] == 2.0); REQUIRE(test_vector[2] == 3.0); } //}}} Init tests
#include "catch.hpp" #include "etl/dyn_vector.hpp" //{{{ Init tests TEST_CASE( "dyn_vector/init_1", "dyn_vector::dyn_vector(T)" ) { etl::dyn_vector<double> test_vector(4, 3.3); REQUIRE(test_vector.size() == 4); for(std::size_t i = 0; i < test_vector.size(); ++i){ REQUIRE(test_vector[i] == 3.3); REQUIRE(test_vector(i) == 3.3); } } TEST_CASE( "dyn_vector/init_2", "dyn_vector::operator=(T)" ) { etl::dyn_vector<double> test_vector(4); test_vector = 3.3; REQUIRE(test_vector.size() == 4); for(std::size_t i = 0; i < test_vector.size(); ++i){ REQUIRE(test_vector[i] == 3.3); REQUIRE(test_vector(i) == 3.3); } } TEST_CASE( "dyn_vector/init_3", "dyn_vector::dyn_vector(initializer_list)" ) { etl::dyn_vector<double> test_vector({1.0, 2.0, 3.0}); REQUIRE(test_vector.size() == 3); REQUIRE(test_vector[0] == 1.0); REQUIRE(test_vector[1] == 2.0); REQUIRE(test_vector[2] == 3.0); } //}}} Init tests //{{{ Binary operators test TEST_CASE( "dyn_vector/add_scalar_1", "dyn_vector::operator+" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.5}; test_vector = 1.0 + test_vector; REQUIRE(test_vector[0] == 0.0); REQUIRE(test_vector[1] == 3.0); REQUIRE(test_vector[2] == 6.5); } TEST_CASE( "dyn_vector/add_scalar_2", "dyn_vector::operator+" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.5}; test_vector = test_vector + 1.0; REQUIRE(test_vector[0] == 0.0); REQUIRE(test_vector[1] == 3.0); REQUIRE(test_vector[2] == 6.5); } TEST_CASE( "dyn_vector/add_scalar_3", "dyn_vector::operator+=" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.5}; test_vector += 1.0; REQUIRE(test_vector[0] == 0.0); REQUIRE(test_vector[1] == 3.0); REQUIRE(test_vector[2] == 6.5); } TEST_CASE( "dyn_vector/add_1", "dyn_vector::operator+" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; etl::dyn_vector<double> c(a + b); REQUIRE(c[0] == 1.5); REQUIRE(c[1] == 5.0); REQUIRE(c[2] == 9.0); } TEST_CASE( "dyn_vector/add_2", "dyn_vector::operator+=" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; a += b; REQUIRE(a[0] == 1.5); REQUIRE(a[1] == 5.0); REQUIRE(a[2] == 9.0); } TEST_CASE( "dyn_vector/sub_scalar_1", "dyn_vector::operator+" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.5}; test_vector = 1.0 - test_vector; REQUIRE(test_vector[0] == 2.0); REQUIRE(test_vector[1] == -1.0); REQUIRE(test_vector[2] == -4.5); } TEST_CASE( "dyn_vector/sub_scalar_2", "dyn_vector::operator+" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.5}; test_vector = test_vector - 1.0; REQUIRE(test_vector[0] == -2.0); REQUIRE(test_vector[1] == 1.0); REQUIRE(test_vector[2] == 4.5); } TEST_CASE( "dyn_vector/sub_scalar_3", "dyn_vector::operator+=" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.5}; test_vector -= 1.0; REQUIRE(test_vector[0] == -2.0); REQUIRE(test_vector[1] == 1.0); REQUIRE(test_vector[2] == 4.5); } TEST_CASE( "dyn_vector/sub_1", "dyn_vector::operator-" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; etl::dyn_vector<double> c(a - b); REQUIRE(c[0] == -3.5); REQUIRE(c[1] == -1.0); REQUIRE(c[2] == 1.0); } TEST_CASE( "dyn_vector/sub_2", "dyn_vector::operator-=" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; a -= b; REQUIRE(a[0] == -3.5); REQUIRE(a[1] == -1.0); REQUIRE(a[2] == 1.0); } TEST_CASE( "dyn_vector/mul_scalar_1", "dyn_vector::operator*" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.0}; test_vector = 2.5 * test_vector; REQUIRE(test_vector[0] == -2.5); REQUIRE(test_vector[1] == 5.0); REQUIRE(test_vector[2] == 12.5); } TEST_CASE( "dyn_vector/mul_scalar_2", "dyn_vector::operator*" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.0}; test_vector = test_vector * 2.5; REQUIRE(test_vector[0] == -2.5); REQUIRE(test_vector[1] == 5.0); REQUIRE(test_vector[2] == 12.5); } TEST_CASE( "dyn_vector/mul_scalar_3", "dyn_vector::operator*=" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.0}; test_vector *= 2.5; REQUIRE(test_vector[0] == -2.5); REQUIRE(test_vector[1] == 5.0); REQUIRE(test_vector[2] == 12.5); } TEST_CASE( "dyn_vector/mul_1", "dyn_vector::operator*" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; etl::dyn_vector<double> c(a * b); REQUIRE(c[0] == -2.5); REQUIRE(c[1] == 6.0); REQUIRE(c[2] == 20.0); } TEST_CASE( "dyn_vector/mul_2", "dyn_vector::operator*=" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; a *= b; REQUIRE(a[0] == -2.5); REQUIRE(a[1] == 6.0); REQUIRE(a[2] == 20.0); } TEST_CASE( "dyn_vector/div_scalar_1", "dyn_vector::operator/" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.0}; test_vector = test_vector / 2.5; REQUIRE(test_vector[0] == -1.0 / 2.5); REQUIRE(test_vector[1] == 2.0 / 2.5); REQUIRE(test_vector[2] == 5.0 / 2.5); } TEST_CASE( "dyn_vector/div_scalar_2", "dyn_vector::operator/" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.0}; test_vector = 2.5 / test_vector; REQUIRE(test_vector[0] == 2.5 / -1.0); REQUIRE(test_vector[1] == 2.5 / 2.0); REQUIRE(test_vector[2] == 2.5 / 5.0); } TEST_CASE( "dyn_vector/div_scalar_3", "dyn_vector::operator/=" ) { etl::dyn_vector<double> test_vector = {-1.0, 2.0, 5.0}; test_vector /= 2.5; REQUIRE(test_vector[0] == -1.0 / 2.5); REQUIRE(test_vector[1] == 2.0 / 2.5); REQUIRE(test_vector[2] == 5.0 / 2.5); } TEST_CASE( "dyn_vector/div_1", "dyn_vector::operator/"){ etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; etl::dyn_vector<double> c(a / b); REQUIRE(c[0] == -1.0 / 2.5); REQUIRE(c[1] == 2.0 / 3.0); REQUIRE(c[2] == 5.0 / 4.0); } TEST_CASE( "dyn_vector/div_2", "dyn_vector::operator/="){ etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; a /= b; REQUIRE(a[0] == -1.0 / 2.5); REQUIRE(a[1] == 2.0 / 3.0); REQUIRE(a[2] == 5.0 / 4.0); } TEST_CASE( "dyn_vector/mod_scalar_1", "dyn_vector::operator%" ) { etl::dyn_vector<int> test_vector = {-1, 2, 5}; test_vector = test_vector % 2; REQUIRE(test_vector[0] == -1 % 2); REQUIRE(test_vector[1] == 2 % 2); REQUIRE(test_vector[2] == 5 % 2); } TEST_CASE( "dyn_vector/mod_scalar_2", "dyn_vector::operator%" ) { etl::dyn_vector<int> test_vector = {-1, 2, 5}; test_vector = 2 % test_vector; REQUIRE(test_vector[0] == 2 % -1); REQUIRE(test_vector[1] == 2 % 2); REQUIRE(test_vector[2] == 2 % 5); } TEST_CASE( "dyn_vector/mod_scalar_3", "dyn_vector::operator%=" ) { etl::dyn_vector<int> test_vector = {-1, 2, 5}; test_vector %= 2; REQUIRE(test_vector[0] == -1 % 2); REQUIRE(test_vector[1] == 2 % 2); REQUIRE(test_vector[2] == 5 % 2); } TEST_CASE( "dyn_vector/mod_1", "dyn_vector::operator%" ) { etl::dyn_vector<int> a = {-1, 2, 5}; etl::dyn_vector<int> b = {2, 3, 4}; etl::dyn_vector<int> c(a % b); REQUIRE(c[0] == -1 % 2); REQUIRE(c[1] == 2 % 3); REQUIRE(c[2] == 5 % 4); } TEST_CASE( "dyn_vector/mod_2", "dyn_vector::operator%" ) { etl::dyn_vector<int> a = {-1, 2, 5}; etl::dyn_vector<int> b = {2, 3, 4}; a %= b; REQUIRE(a[0] == -1 % 2); REQUIRE(a[1] == 2 % 3); REQUIRE(a[2] == 5 % 4); } //}}} Binary operator tests //{{{ Unary operator tests TEST_CASE( "dyn_vector/log", "dyn_vector::abs" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> d(log(a)); REQUIRE(std::isnan(d[0])); REQUIRE(d[1] == log(2.0)); REQUIRE(d[2] == log(5.0)); } TEST_CASE( "dyn_vector/abs", "dyn_vector::abs" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 0.0}; etl::dyn_vector<double> d(abs(a)); REQUIRE(d[0] == 1.0); REQUIRE(d[1] == 2.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "dyn_vector/sign", "dyn_vector::abs" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 0.0}; etl::dyn_vector<double> d(sign(a)); REQUIRE(d[0] == -1.0); REQUIRE(d[1] == 1.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "dyn_vector/unary_unary", "dyn_vector::abs" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 0.0}; etl::dyn_vector<double> d(abs(sign(a))); REQUIRE(d[0] == 1.0); REQUIRE(d[1] == 1.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "dyn_vector/unary_binary_1", "dyn_vector::abs" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 0.0}; etl::dyn_vector<double> d(abs(a + a)); REQUIRE(d[0] == 2.0); REQUIRE(d[1] == 4.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "dyn_vector/unary_binary_2", "dyn_vector::abs" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 0.0}; etl::dyn_vector<double> d(abs(a) + a); REQUIRE(d[0] == 0.0); REQUIRE(d[1] == 4.0); REQUIRE(d[2] == 0.0); } //}}} Unary operators test //{{{ Reductions TEST_CASE( "dyn_vector/sum", "sum" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 8.5}; auto d = sum(a); REQUIRE(d == 9.5); } TEST_CASE( "dyn_vector/sum_2", "sum" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 8.5}; auto d = sum(a + a); REQUIRE(d == 19); } TEST_CASE( "dyn_vector/sum_3", "sum" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 8.5}; auto d = sum(abs(a + a)); REQUIRE(d == 23.0); } //}}} Reductions //{{{ Complex tests TEST_CASE( "dyn_vector/complex", "dyn_vector::complex" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; etl::dyn_vector<double> c = {1.2, -3.0, 3.5}; etl::dyn_vector<double> d(2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c)); REQUIRE(d[0] == Approx(10.0)); REQUIRE(d[1] == Approx(5.0)); REQUIRE(d[2] == Approx(0.68627)); } TEST_CASE( "dyn_vector/complex_2", "dyn_vector::complex" ) { etl::dyn_vector<double> a = {1.1, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, -3.0, 4.0}; etl::dyn_vector<double> c = {2.2, 3.0, 3.5}; etl::dyn_vector<double> d(2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c)); REQUIRE(d[0] == Approx(46.39429)); REQUIRE(d[1] == Approx(9.13499)); REQUIRE(d[2] == Approx(5.8273)); } TEST_CASE( "dyn_vector/complex_3", "dyn_vector::complex" ) { etl::dyn_vector<double> a = {-1.0, 2.0, 5.0}; etl::dyn_vector<double> b = {2.5, 3.0, 4.0}; etl::dyn_vector<double> c = {1.2, -3.0, 3.5}; etl::dyn_vector<double> d(2.5 / (a * b)); REQUIRE(d[0] == Approx(-1.0)); REQUIRE(d[1] == Approx(0.416666)); REQUIRE(d[2] == Approx(0.125)); } //}}} Complex tests
Add test for dyn_vector
Add test for dyn_vector
C++
mit
wichtounet/etl,wichtounet/etl
365f13cd56305253269eec58714d0f40fc2b478b
tests/RawOpenCL.cpp
tests/RawOpenCL.cpp
/* * Copyright (C) 2014 Martin Preisler <[email protected]> * * This file is part of oclcrypto. * * 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 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 <oclcrypto/System.h> #include <oclcrypto/Device.h> #include <oclcrypto/Program.h> #include <oclcrypto/Kernel.h> #include <oclcrypto/CLError.h> #include <boost/test/unit_test.hpp> #include "TestSuiteFixture.h" struct RawOpenCLFixture { RawOpenCLFixture(): system(true) {} oclcrypto::System system; }; const char* opencl_sample_code = "__kernel void square(__global int* input, __global int* output)\n" "{\n" " int gid = get_global_id(0);\n" " output[gid] = input[gid] * input[gid];\n" //" printf(\"input[%i] is: %i\\n\", gid, input[gid]);\n" "}\n" "\n" "__kernel void set_to_constant(__global int* output, int c)\n" "{\n" " int gid = get_global_id(0);\n" //" printf(\"constant is: %i\\n\", c);\n" " output[gid] = c;\n" "}\n"; BOOST_FIXTURE_TEST_SUITE(RawOpenCL, RawOpenCLFixture) BOOST_AUTO_TEST_CASE(SimpleProgramCompilation) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); { // invalid syntax has to throw exception BOOST_CHECK_THROW(device.createProgram("invalid $ syntax"), oclcrypto::CLProgramCompilationError); } { // empty program should compile without exception oclcrypto::Program& empty = device.createProgram(""); BOOST_CHECK_EQUAL(empty.getKernelCount(), 0); // this crashes pocl //BOOST_CHECK_THROW(empty.createKernel("nonexistant"), oclcrypto::CLError); BOOST_CHECK_EQUAL(empty.getKernelCount(), 0); device.destroyProgram(empty); // destroying it twice should cause exception BOOST_CHECK_THROW(device.destroyProgram(empty), std::invalid_argument); } { // minimum one kernel program oclcrypto::Program& simple = device.createProgram(opencl_sample_code); // nothing requested yet, so the expected kernel count is 0 BOOST_CHECK_EQUAL(simple.getKernelCount(), 0); // this crashes pocl //BOOST_CHECK_THROW(simple.createKernel("nonexistant"), oclcrypto::CLError); // kernel count still zero after error BOOST_CHECK_EQUAL(simple.getKernelCount(), 0); oclcrypto::Kernel& kernel = simple.createKernel("square"); // translate was created, the kernel count should be 1 now BOOST_CHECK_EQUAL(simple.getKernelCount(), 1); { // another kernel of the same function oclcrypto::Kernel& kernel2 = simple.createKernel("square"); BOOST_CHECK_EQUAL(simple.getKernelCount(), 2); simple.destroyKernel(kernel2); BOOST_CHECK_EQUAL(simple.getKernelCount(), 1); } simple.destroyKernel(kernel); // destroying twice should throw BOOST_CHECK_THROW(simple.destroyKernel(kernel), std::invalid_argument); } } } BOOST_AUTO_TEST_CASE(DataBuffers) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); oclcrypto::Program& program = device.createProgram(opencl_sample_code); oclcrypto::DataBuffer& output = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Write); BOOST_CHECK_EQUAL(output.getSize(), 16 * sizeof(int)); BOOST_CHECK_EQUAL(output.getArraySize<int>(), 16); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::Unlocked); { auto data = output.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; // out of bounds should throw BOOST_CHECK_THROW(data[16] = 123, std::out_of_range); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::WriteLocked); data.flush(); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::Unlocked); // second flush should throw BOOST_CHECK_THROW(data.flush(), std::runtime_error); } { auto data = output.lockRead<int>(); for (int j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j); BOOST_CHECK_THROW(data[17] == 17, std::out_of_range); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::ReadLocked); data.unlock(); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::Unlocked); // second unlock should throw BOOST_CHECK_THROW(data.unlock(), std::runtime_error); } oclcrypto::DataBuffer& input = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Read); { auto data = input.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; // it will get flushed automatically when going of of scope BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::WriteLocked); } BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::Unlocked); // the following write gets discarded { auto data = input.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j * 10; BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::WriteLocked); data.discard(); // second discard should throw BOOST_CHECK_THROW(data.discard(), std::runtime_error); BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::Unlocked); // flushing after discard should throw BOOST_CHECK_THROW(data.flush(), std::runtime_error); } } } BOOST_AUTO_TEST_CASE(KernelExecution) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); oclcrypto::Program& program = device.createProgram(opencl_sample_code); { oclcrypto::DataBuffer& output = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Write); oclcrypto::Kernel& kernel = program.createKernel("set_to_constant"); //kernel.setParameter(0, input); kernel.setParameter(0, output); int param = 1; kernel.setParameter(1, &param); kernel.execute(16, 8); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], param); } // multiple executions of the same kernel have to work kernel.execute(16, 1); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], param); } } { oclcrypto::DataBuffer& input = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Read); { auto data = input.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; } oclcrypto::DataBuffer& output = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Write); oclcrypto::Kernel& kernel = program.createKernel("square"); kernel.setParameter(0, input); kernel.setParameter(1, output); kernel.execute(16, 8); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j * j); } // multiple executions of the same kernel have to work kernel.execute(16, 1); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j * j); } } } } BOOST_AUTO_TEST_SUITE_END()
/* * Copyright (C) 2014 Martin Preisler <[email protected]> * * This file is part of oclcrypto. * * 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 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 <oclcrypto/System.h> #include <oclcrypto/Device.h> #include <oclcrypto/Program.h> #include <oclcrypto/Kernel.h> #include <oclcrypto/CLError.h> #include <boost/test/unit_test.hpp> #include "TestSuiteFixture.h" struct RawOpenCLFixture { RawOpenCLFixture(): system(true) {} oclcrypto::System system; }; const char* opencl_sample_code = "__kernel void set_to_constant(__global int* output, int c)\n" "{\n" " int gid = get_global_id(0);\n" " output[gid] = c;\n" "}\n" "\n" "__kernel void square(__global int* input, __global int* output)\n" "{\n" " int gid = get_global_id(0);\n" " output[gid] = input[gid] * input[gid];\n" "}\n" "\n" "__kernel void square_in_place(__global int* io)\n" "{\n" " int gid = get_global_id(0);\n" " io[gid] = io[gid] * io[gid];\n" "}\n"; BOOST_FIXTURE_TEST_SUITE(RawOpenCL, RawOpenCLFixture) BOOST_AUTO_TEST_CASE(SimpleProgramCompilation) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); { // invalid syntax has to throw exception BOOST_CHECK_THROW(device.createProgram("invalid $ syntax"), oclcrypto::CLProgramCompilationError); } { // empty program should compile without exception oclcrypto::Program& empty = device.createProgram(""); BOOST_CHECK_EQUAL(empty.getKernelCount(), 0); // this crashes pocl //BOOST_CHECK_THROW(empty.createKernel("nonexistant"), oclcrypto::CLError); BOOST_CHECK_EQUAL(empty.getKernelCount(), 0); device.destroyProgram(empty); // destroying it twice should cause exception BOOST_CHECK_THROW(device.destroyProgram(empty), std::invalid_argument); } { // minimum one kernel program oclcrypto::Program& simple = device.createProgram(opencl_sample_code); // nothing requested yet, so the expected kernel count is 0 BOOST_CHECK_EQUAL(simple.getKernelCount(), 0); // this crashes pocl //BOOST_CHECK_THROW(simple.createKernel("nonexistant"), oclcrypto::CLError); // kernel count still zero after error BOOST_CHECK_EQUAL(simple.getKernelCount(), 0); oclcrypto::Kernel& kernel = simple.createKernel("square"); // translate was created, the kernel count should be 1 now BOOST_CHECK_EQUAL(simple.getKernelCount(), 1); { // another kernel of the same function oclcrypto::Kernel& kernel2 = simple.createKernel("square"); BOOST_CHECK_EQUAL(simple.getKernelCount(), 2); simple.destroyKernel(kernel2); BOOST_CHECK_EQUAL(simple.getKernelCount(), 1); } simple.destroyKernel(kernel); // destroying twice should throw BOOST_CHECK_THROW(simple.destroyKernel(kernel), std::invalid_argument); } } } BOOST_AUTO_TEST_CASE(DataBuffers) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); oclcrypto::Program& program = device.createProgram(opencl_sample_code); oclcrypto::DataBuffer& output = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Write); BOOST_CHECK_EQUAL(output.getSize(), 16 * sizeof(int)); BOOST_CHECK_EQUAL(output.getArraySize<int>(), 16); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::Unlocked); { auto data = output.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; // out of bounds should throw BOOST_CHECK_THROW(data[16] = 123, std::out_of_range); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::WriteLocked); data.flush(); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::Unlocked); // second flush should throw BOOST_CHECK_THROW(data.flush(), std::runtime_error); } { auto data = output.lockRead<int>(); for (int j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j); BOOST_CHECK_THROW(data[17] == 17, std::out_of_range); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::ReadLocked); data.unlock(); BOOST_CHECK_EQUAL(output.getLockState(), oclcrypto::DataBuffer::Unlocked); // second unlock should throw BOOST_CHECK_THROW(data.unlock(), std::runtime_error); } oclcrypto::DataBuffer& input = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Read); { auto data = input.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; // it will get flushed automatically when going of of scope BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::WriteLocked); } BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::Unlocked); // the following write gets discarded { auto data = input.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j * 10; BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::WriteLocked); data.discard(); // second discard should throw BOOST_CHECK_THROW(data.discard(), std::runtime_error); BOOST_CHECK_EQUAL(input.getLockState(), oclcrypto::DataBuffer::Unlocked); // flushing after discard should throw BOOST_CHECK_THROW(data.flush(), std::runtime_error); } } } BOOST_AUTO_TEST_CASE(KernelExecutionSetToConstant) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); oclcrypto::Program& program = device.createProgram(opencl_sample_code); { oclcrypto::DataBuffer& output = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Write); oclcrypto::Kernel& kernel = program.createKernel("set_to_constant"); //kernel.setParameter(0, input); kernel.setParameter(0, output); int param = 1; kernel.setParameter(1, &param); kernel.execute(16, 8); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], param); } // multiple executions of the same kernel have to work kernel.execute(16, 1); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], param); } } } } BOOST_AUTO_TEST_CASE(KernelExecutionSquare) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); oclcrypto::Program& program = device.createProgram(opencl_sample_code); { oclcrypto::DataBuffer& input = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Read); { auto data = input.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; } oclcrypto::DataBuffer& output = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::Write); oclcrypto::Kernel& kernel = program.createKernel("square"); kernel.setParameter(0, input); kernel.setParameter(1, output); kernel.execute(16, 8); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j * j); } // multiple executions of the same kernel have to work kernel.execute(16, 1); { auto data = output.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j * j); } } } } BOOST_AUTO_TEST_CASE(KernelExecutionSquareInPlace) { BOOST_REQUIRE_GT(system.getDeviceCount(), 0); for (size_t i = 0; i < system.getDeviceCount(); ++i) { oclcrypto::Device& device = system.getDevice(i); oclcrypto::Program& program = device.createProgram(opencl_sample_code); { oclcrypto::DataBuffer& io = device.allocateBuffer<int>(16, oclcrypto::DataBuffer::ReadWrite); { auto data = io.lockWrite<int>(); for (int j = 0; j < 16; ++j) data[j] = j; } oclcrypto::Kernel& kernel = program.createKernel("square_in_place"); kernel.setParameter(0, io); kernel.execute(16, 8); { auto data = io.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j * j); } // another execution will change the values in place, we expect (j^2)^2 = j^4 kernel.execute(16, 1); { auto data = io.lockRead<int>(); for (size_t j = 0; j < 16; ++j) BOOST_CHECK_EQUAL(data[j], j * j * j * j); } } } } BOOST_AUTO_TEST_SUITE_END()
Split up kernel execution into 3 test cases, added in place square
Split up kernel execution into 3 test cases, added in place square In place square tests read/write buffer functionality.
C++
mit
wdv4758h/oclcrypto,wdv4758h/oclcrypto
891b83e17d7e57ec54fa447fb4372ca21d523f5b
modules/plottinggl/src/processors/parallelcoordinates/pcpaxissettings.cpp
modules/plottinggl/src/processors/parallelcoordinates/pcpaxissettings.cpp
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2019 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/plottinggl/processors/parallelcoordinates/pcpaxissettings.h> #include <inviwo/dataframe/datastructures/column.h> #include <modules/base/algorithm/dataminmax.h> #include <modules/plotting/utils/statsutils.h> #include <modules/plottinggl/processors/parallelcoordinates/parallelcoordinates.h> #include <modules/plotting/utils/axisutils.h> #include <fmt/format.h> #include <fmt/printf.h> namespace inviwo { namespace plot { namespace detail { enum class FilterResult { Upper, Lower, None }; /** * Helper for brushing data * @param value to filter * @param range to use for filtering * @return true if value is outside range and not missing data. */ FilterResult filterValue(const double& value, const dvec2& range) { // Do not filter missing data (NaN) if (util::isnan(value)) return FilterResult::None; if (value < range.x) { return FilterResult::Lower; } if (value > range.y) { return FilterResult::Upper; } return FilterResult::None; } } // namespace detail const std::string PCPAxisSettings::classIdentifier = "org.inviwo.parallelcoordinates.axissettingsproperty"; std::string PCPAxisSettings::getClassIdentifier() const { return classIdentifier; } PCPAxisSettings::PCPAxisSettings(std::string identifier, std::string displayName, size_t columnId) : BoolCompositeProperty(identifier, displayName, true) , usePercentiles("usePercentiles", "Use Percentiles", false) , invertRange("invertRange", "Invert Range") , range("range", "Axis Range") , columnId_{columnId} { addProperty(range); addProperty(invertRange); addProperty(usePercentiles); setCollapsed(true); setSerializationMode(PropertySerializationMode::All); range.setSerializationMode(PropertySerializationMode::All); invertRange.setSerializationMode(PropertySerializationMode::All); usePercentiles.setSerializationMode(PropertySerializationMode::All); range.onChange([this]() { updateBrushing(); if (pcp_) pcp_->updateBrushing(*this); }); } PCPAxisSettings::PCPAxisSettings(const PCPAxisSettings& rhs) : BoolCompositeProperty(rhs) , usePercentiles{rhs.usePercentiles} , invertRange(rhs.invertRange) , range{rhs.range} , columnId_{rhs.columnId_} { addProperty(range); addProperty(invertRange); addProperty(usePercentiles); range.onChange([this]() { updateBrushing(); if (pcp_) pcp_->updateBrushing(*this); }); } PCPAxisSettings* PCPAxisSettings::clone() const { return new PCPAxisSettings(*this); } void PCPAxisSettings::updateFromColumn(std::shared_ptr<const Column> col) { col_ = col; catCol_ = dynamic_cast<const CategoricalColumn*>(col.get()); col->getBuffer()->getRepresentation<BufferRAM>()->dispatch<void, dispatching::filter::Scalars>( [&](auto ram) -> void { using T = typename util::PrecisionValueType<decltype(ram)>; auto& dataVector = ram->getDataContainer(); auto minMax = util::bufferMinMax(ram, IgnoreSpecialValues::Yes); double minV = minMax.first.x; double maxV = minMax.second.x; if (std::abs(maxV - minV) == 0.0) { minV -= 1.0; maxV += 1.0; } dvec2 prevVal = range.get(); dvec2 prevRange = range.getRange(); double l = prevRange.y - prevRange.x; double prevMinRatio = (prevVal.x - prevRange.x) / (l); double prevMaxRatio = (prevVal.y - prevRange.x) / (l); Property::OnChangeBlocker block{range}; range.setRange(glm::tvec2<T>(minV, maxV)); if (l > 0 && maxV != minV) { range.set( {minV + prevMinRatio * (maxV - minV), minV + prevMaxRatio * (maxV - minV)}); } auto pecentiles = statsutil::percentiles(dataVector, {0., 0.25, 0.75, 1.}); p0_ = static_cast<double>(pecentiles[0]); p25_ = static_cast<double>(pecentiles[1]); p75_ = static_cast<double>(pecentiles[2]); p100_ = static_cast<double>(pecentiles[3]); at = [vec = &dataVector](size_t idx) { return static_cast<double>(vec->at(idx)); }; }); range.propertyModified(); } double PCPAxisSettings::getNormalized(double v) const { if (range.getRangeMax() == range.getRangeMin()) { return 0.5; } const auto rangeTmp = range.getRange(); if (v <= rangeTmp.x) { return 0; } if (v >= rangeTmp.y) { return 1; } if (!usePercentiles.get()) { return (v - rangeTmp.x) / (rangeTmp.y - rangeTmp.x); } else { double minV, maxV; double o, r; if (v < p25_) { minV = p0_; maxV = p25_; o = 0; r = 0.25f; } else if (v < p75_) { minV = p25_; maxV = p75_; o = 0.25; r = 0.5; } else { minV = p75_; maxV = p100_; o = 0.75; r = 0.25; } double t = (v - minV) / (maxV - minV); return o + t * r; } } double PCPAxisSettings::getNormalizedAt(size_t idx) const { return getNormalized(at(idx)); } double PCPAxisSettings::getValue(double v) const { if (invertRange) { v = 1.0 - v; } const auto rangeTmp = range.getRange(); if (v <= 0) { return rangeTmp.x; } if (v >= 1) { return rangeTmp.y; } if (!usePercentiles.get()) { return rangeTmp.x + v * (rangeTmp.y - rangeTmp.x); } else { if (v < 0.25) { v /= 0.25; return p0_ + v * (p25_ - p0_); } else if (v < 0.75) { v -= 0.25; v /= 0.5; return p25_ + v * (p75_ - p25_); } else { v -= 0.75; v /= 0.25; return p75_ + v * (p100_ - p75_); } } } void PCPAxisSettings::moveHandle(bool upper, double mouseY) { auto rangeTmp = range.get(); double value = getValue(mouseY); if (upper) { if (value < rangeTmp.x) { value = rangeTmp.x; } rangeTmp.y = value; } else { if (value > rangeTmp.y) { value = rangeTmp.y; } rangeTmp.x = value; } range.set(rangeTmp); } void PCPAxisSettings::setParallelCoordinates(ParallelCoordinates* pcp) { pcp_ = pcp; labelSettings_.setSettings(this); captionSettings_.setSettings(this); major_.setSettings(this); minor_.setSettings(this); auto updateLabels = [this]() { const auto tickmarks = plot::getMajorTickPositions(major_, range); labels_.clear(); const auto& format = pcp_->labelFormat_.get(); std::transform(tickmarks.begin(), tickmarks.end(), std::back_inserter(labels_), [&](auto tick) { return fmt::sprintf(format, tick); }); }; labelUpdateCallback_ = pcp_->labelFormat_.onChangeScoped(updateLabels); updateLabels(); } void PCPAxisSettings::updateBrushing() { if (!col_) return; // Increase range to avoid conversion issues const dvec2 off{-std::numeric_limits<float>::epsilon(), std::numeric_limits<float>::epsilon()}; const auto rangeTmp = range.get() + off; const auto nRows = col_->getSize(); upperBrushed_ = false; lowerBrushed_ = false; brushed_.resize(nRows, false); for (size_t i = 0; i < nRows; i++) { const auto filtered = detail::filterValue(at(i), rangeTmp); if (filtered == detail::FilterResult::None) { brushed_[i] = false; continue; } brushed_[i] = true; if (filtered == detail::FilterResult::Upper) upperBrushed_ = true; if (filtered == detail::FilterResult::Lower) lowerBrushed_ = true; } } dvec2 PCPAxisSettings::getRange() const { if (catCol_) { return {0.0, static_cast<double>(catCol_->getCategories().size()) - 1.0}; } else { return dvec2{range.getRangeMin(), range.getRangeMax()}; } } bool PCPAxisSettings::getUseDataRange() const { return false; } bool PCPAxisSettings::getVisible() const { return BoolCompositeProperty::getVisible(); } bool PCPAxisSettings::getFlipped() const { return invertRange.get(); } vec4 PCPAxisSettings::getColor() const { const auto hover = pcp_->getHoveredAxis() == static_cast<int>(columnId_); const auto selected = pcp_->brushingAndLinking_.isColumnSelected(columnId_); if (hover && selected) { return glm::mix(pcp_->axisHoverColor_.get(), pcp_->axisSelectedColor_.get(), 0.5f); } else if (hover) { return pcp_->axisHoverColor_; } else if (selected) { return pcp_->axisSelectedColor_; } else { return pcp_->axisColor_; } } float PCPAxisSettings::getWidth() const { if (pcp_->getHoveredAxis() == static_cast<int>(columnId_)) { return 1.5f * pcp_->axisSize_; } else if (pcp_->brushingAndLinking_.isColumnSelected(columnId_)) { return 1.5f * pcp_->axisSize_; } else { return 1.0f * pcp_->axisSize_; } } AxisSettings::Orientation PCPAxisSettings::getOrientation() const { return Orientation::Vertical; } AxisSettings::Placement PCPAxisSettings::getPlacement() const { return Placement::Inside; } const std::string& PCPAxisSettings::getCaption() const { return col_->getHeader(); } const PlotTextSettings& PCPAxisSettings::getCaptionSettings() const { return captionSettings_; } const std::vector<std::string>& PCPAxisSettings::getLabels() const { return catCol_ ? catCol_->getCategories() : labels_; } const PlotTextSettings& PCPAxisSettings::getLabelSettings() const { return labelSettings_; } const MajorTickSettings& PCPAxisSettings::getMajorTicks() const { return major_; } const MinorTickSettings& PCPAxisSettings::getMinorTicks() const { return minor_; } bool PCPCaptionSettings::isEnabled() const { return settings_->pcp_->captionPosition_.get() != ParallelCoordinates::LabelPosition::None; } vec4 PCPCaptionSettings::getColor() const { return settings_->pcp_->captionColor_; } float PCPCaptionSettings::getPosition() const { return (settings_->pcp_->captionPosition_.get() == ParallelCoordinates::LabelPosition::Above) != settings_->getFlipped() ? 1.0f : 0.0f; } vec2 PCPCaptionSettings::getOffset() const { return {0.0f, settings_->pcp_->captionOffset_ * (settings_->getFlipped() ? -1.0f : 1.0f)}; } float PCPCaptionSettings::getRotation() const { return 270.f; } const FontSettings& PCPCaptionSettings::getFont() const { return settings_->pcp_->captionSettings_; } bool PCPLabelSettings::isEnabled() const { return settings_->pcp_->showLabels_; } vec4 PCPLabelSettings::getColor() const { return settings_->pcp_->labelColor_; } float PCPLabelSettings::getPosition() const { return 0.0f; } vec2 PCPLabelSettings::getOffset() const { return {settings_->pcp_->labelOffset_, 0.0f}; } float PCPLabelSettings::getRotation() const { return 0.0f; } const FontSettings& PCPLabelSettings::getFont() const { return settings_->pcp_->labelSettings_; } TickStyle PCPMajorTickSettings::getStyle() const { return TickStyle::Both; } vec4 PCPMajorTickSettings::getColor() const { return settings_->getColor(); } float PCPMajorTickSettings::getTickLength() const { return settings_->pcp_->axisSize_ * 2.0f; } float PCPMajorTickSettings::getTickWidth() const { return settings_->getWidth(); } double PCPMajorTickSettings::getTickDelta() const { return settings_->catCol_ ? 1.0 : 0.0; } bool PCPMajorTickSettings::getRangeBasedTicks() const { return false; } TickStyle PCPMinorTickSettings::getStyle() const { return TickStyle::None; } bool PCPMinorTickSettings::getFillAxis() const { return false; } vec4 PCPMinorTickSettings::getColor() const { return settings_->getColor(); } float PCPMinorTickSettings::getTickLength() const { return 0.0f; } float PCPMinorTickSettings::getTickWidth() const { return 0.0f; } int PCPMinorTickSettings::getTickFrequency() const { return 0; } } // namespace plot } // namespace inviwo
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2019 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/plottinggl/processors/parallelcoordinates/pcpaxissettings.h> #include <inviwo/dataframe/datastructures/column.h> #include <modules/base/algorithm/dataminmax.h> #include <modules/plotting/utils/statsutils.h> #include <modules/plottinggl/processors/parallelcoordinates/parallelcoordinates.h> #include <modules/plotting/utils/axisutils.h> #include <fmt/format.h> #include <fmt/printf.h> namespace inviwo { namespace plot { namespace detail { enum class FilterResult { Upper, Lower, None }; /** * Helper for brushing data * @param value to filter * @param range to use for filtering * @return true if value is outside range and not missing data. */ FilterResult filterValue(const double& value, const dvec2& range) { // Do not filter missing data (NaN) if (util::isnan(value)) return FilterResult::None; if (value < range.x) { return FilterResult::Lower; } if (value > range.y) { return FilterResult::Upper; } return FilterResult::None; } } // namespace detail const std::string PCPAxisSettings::classIdentifier = "org.inviwo.parallelcoordinates.axissettingsproperty"; std::string PCPAxisSettings::getClassIdentifier() const { return classIdentifier; } PCPAxisSettings::PCPAxisSettings(std::string identifier, std::string displayName, size_t columnId) : BoolCompositeProperty(identifier, displayName, true) , usePercentiles("usePercentiles", "Use Percentiles", false) , invertRange("invertRange", "Invert Range") , range("range", "Axis Range") , columnId_{columnId} { addProperty(range); addProperty(invertRange); addProperty(usePercentiles); setCollapsed(true); setSerializationMode(PropertySerializationMode::All); range.setSerializationMode(PropertySerializationMode::All); invertRange.setSerializationMode(PropertySerializationMode::All); usePercentiles.setSerializationMode(PropertySerializationMode::All); range.onChange([this]() { updateBrushing(); if (pcp_) pcp_->updateBrushing(*this); }); } PCPAxisSettings::PCPAxisSettings(const PCPAxisSettings& rhs) : BoolCompositeProperty(rhs) , usePercentiles{rhs.usePercentiles} , invertRange(rhs.invertRange) , range{rhs.range} , columnId_{rhs.columnId_} { addProperty(range); addProperty(invertRange); addProperty(usePercentiles); range.onChange([this]() { updateBrushing(); if (pcp_) pcp_->updateBrushing(*this); }); } PCPAxisSettings* PCPAxisSettings::clone() const { return new PCPAxisSettings(*this); } void PCPAxisSettings::updateFromColumn(std::shared_ptr<const Column> col) { col_ = col; catCol_ = dynamic_cast<const CategoricalColumn*>(col.get()); col->getBuffer()->getRepresentation<BufferRAM>()->dispatch<void, dispatching::filter::Scalars>( [&](auto ram) -> void { using T = typename util::PrecisionValueType<decltype(ram)>; auto& dataVector = ram->getDataContainer(); auto minMax = util::bufferMinMax(ram, IgnoreSpecialValues::Yes); double minV = minMax.first.x; double maxV = minMax.second.x; if (std::abs(maxV - minV) == 0.0) { minV -= 1.0; maxV += 1.0; } dvec2 prevVal = range.get(); dvec2 prevRange = range.getRange(); double l = prevRange.y - prevRange.x; double prevMinRatio = (prevVal.x - prevRange.x) / (l); double prevMaxRatio = (prevVal.y - prevRange.x) / (l); Property::OnChangeBlocker block{range}; range.setRange(glm::tvec2<T>(minV, maxV)); if (l > 0 && maxV != minV) { range.set( {minV + prevMinRatio * (maxV - minV), minV + prevMaxRatio * (maxV - minV)}); } auto pecentiles = statsutil::percentiles(dataVector, {0., 0.25, 0.75, 1.}); p0_ = static_cast<double>(pecentiles[0]); p25_ = static_cast<double>(pecentiles[1]); p75_ = static_cast<double>(pecentiles[2]); p100_ = static_cast<double>(pecentiles[3]); at = [vec = &dataVector](size_t idx) { return static_cast<double>(vec->at(idx)); }; }); range.propertyModified(); } double PCPAxisSettings::getNormalized(double v) const { if (range.getRangeMax() == range.getRangeMin()) { return 0.5; } const auto rangeTmp = range.getRange(); if (v <= rangeTmp.x) { return 0; } if (v >= rangeTmp.y) { return 1; } if (!usePercentiles.get()) { return (v - rangeTmp.x) / (rangeTmp.y - rangeTmp.x); } else { double minV, maxV; double o, r; if (v < p25_) { minV = p0_; maxV = p25_; o = 0; r = 0.25f; } else if (v < p75_) { minV = p25_; maxV = p75_; o = 0.25; r = 0.5; } else { minV = p75_; maxV = p100_; o = 0.75; r = 0.25; } double t = (v - minV) / (maxV - minV); return o + t * r; } } double PCPAxisSettings::getNormalizedAt(size_t idx) const { return getNormalized(at(idx)); } double PCPAxisSettings::getValue(double v) const { if (invertRange) { v = 1.0 - v; } const auto rangeTmp = range.getRange(); if (v <= 0) { return rangeTmp.x; } if (v >= 1) { return rangeTmp.y; } if (!usePercentiles.get()) { return rangeTmp.x + v * (rangeTmp.y - rangeTmp.x); } else { if (v < 0.25) { v /= 0.25; return p0_ + v * (p25_ - p0_); } else if (v < 0.75) { v -= 0.25; v /= 0.5; return p25_ + v * (p75_ - p25_); } else { v -= 0.75; v /= 0.25; return p75_ + v * (p100_ - p75_); } } } void PCPAxisSettings::moveHandle(bool upper, double mouseY) { auto rangeTmp = range.get(); double value = getValue(mouseY); if (upper) { if (value < rangeTmp.x) { value = rangeTmp.x; } rangeTmp.y = value; } else { if (value > rangeTmp.y) { value = rangeTmp.y; } rangeTmp.x = value; } range.set(rangeTmp); } void PCPAxisSettings::setParallelCoordinates(ParallelCoordinates* pcp) { pcp_ = pcp; labelSettings_.setSettings(this); captionSettings_.setSettings(this); major_.setSettings(this); minor_.setSettings(this); auto updateLabels = [this]() { const auto tickmarks = plot::getMajorTickPositions(major_, range.getRange()); labels_.clear(); const auto& format = pcp_->labelFormat_.get(); std::transform(tickmarks.begin(), tickmarks.end(), std::back_inserter(labels_), [&](auto tick) { return fmt::sprintf(format, tick); }); }; labelUpdateCallback_ = pcp_->labelFormat_.onChangeScoped(updateLabels); updateLabels(); } void PCPAxisSettings::updateBrushing() { if (!col_) return; // Increase range to avoid conversion issues const dvec2 off{-std::numeric_limits<float>::epsilon(), std::numeric_limits<float>::epsilon()}; const auto rangeTmp = range.get() + off; const auto nRows = col_->getSize(); upperBrushed_ = false; lowerBrushed_ = false; brushed_.resize(nRows, false); for (size_t i = 0; i < nRows; i++) { const auto filtered = detail::filterValue(at(i), rangeTmp); if (filtered == detail::FilterResult::None) { brushed_[i] = false; continue; } brushed_[i] = true; if (filtered == detail::FilterResult::Upper) upperBrushed_ = true; if (filtered == detail::FilterResult::Lower) lowerBrushed_ = true; } } dvec2 PCPAxisSettings::getRange() const { if (catCol_) { return {0.0, static_cast<double>(catCol_->getCategories().size()) - 1.0}; } else { return dvec2{range.getRangeMin(), range.getRangeMax()}; } } bool PCPAxisSettings::getUseDataRange() const { return false; } bool PCPAxisSettings::getVisible() const { return BoolCompositeProperty::getVisible(); } bool PCPAxisSettings::getFlipped() const { return invertRange.get(); } vec4 PCPAxisSettings::getColor() const { const auto hover = pcp_->getHoveredAxis() == static_cast<int>(columnId_); const auto selected = pcp_->brushingAndLinking_.isColumnSelected(columnId_); if (hover && selected) { return glm::mix(pcp_->axisHoverColor_.get(), pcp_->axisSelectedColor_.get(), 0.5f); } else if (hover) { return pcp_->axisHoverColor_; } else if (selected) { return pcp_->axisSelectedColor_; } else { return pcp_->axisColor_; } } float PCPAxisSettings::getWidth() const { if (pcp_->getHoveredAxis() == static_cast<int>(columnId_)) { return 1.5f * pcp_->axisSize_; } else if (pcp_->brushingAndLinking_.isColumnSelected(columnId_)) { return 1.5f * pcp_->axisSize_; } else { return 1.0f * pcp_->axisSize_; } } AxisSettings::Orientation PCPAxisSettings::getOrientation() const { return Orientation::Vertical; } AxisSettings::Placement PCPAxisSettings::getPlacement() const { return Placement::Inside; } const std::string& PCPAxisSettings::getCaption() const { return col_->getHeader(); } const PlotTextSettings& PCPAxisSettings::getCaptionSettings() const { return captionSettings_; } const std::vector<std::string>& PCPAxisSettings::getLabels() const { return catCol_ ? catCol_->getCategories() : labels_; } const PlotTextSettings& PCPAxisSettings::getLabelSettings() const { return labelSettings_; } const MajorTickSettings& PCPAxisSettings::getMajorTicks() const { return major_; } const MinorTickSettings& PCPAxisSettings::getMinorTicks() const { return minor_; } bool PCPCaptionSettings::isEnabled() const { return settings_->pcp_->captionPosition_.get() != ParallelCoordinates::LabelPosition::None; } vec4 PCPCaptionSettings::getColor() const { return settings_->pcp_->captionColor_; } float PCPCaptionSettings::getPosition() const { return (settings_->pcp_->captionPosition_.get() == ParallelCoordinates::LabelPosition::Above) != settings_->getFlipped() ? 1.0f : 0.0f; } vec2 PCPCaptionSettings::getOffset() const { return {0.0f, settings_->pcp_->captionOffset_ * (settings_->getFlipped() ? -1.0f : 1.0f)}; } float PCPCaptionSettings::getRotation() const { return 270.f; } const FontSettings& PCPCaptionSettings::getFont() const { return settings_->pcp_->captionSettings_; } bool PCPLabelSettings::isEnabled() const { return settings_->pcp_->showLabels_; } vec4 PCPLabelSettings::getColor() const { return settings_->pcp_->labelColor_; } float PCPLabelSettings::getPosition() const { return 0.0f; } vec2 PCPLabelSettings::getOffset() const { return {settings_->pcp_->labelOffset_, 0.0f}; } float PCPLabelSettings::getRotation() const { return 0.0f; } const FontSettings& PCPLabelSettings::getFont() const { return settings_->pcp_->labelSettings_; } TickStyle PCPMajorTickSettings::getStyle() const { return TickStyle::Both; } vec4 PCPMajorTickSettings::getColor() const { return settings_->getColor(); } float PCPMajorTickSettings::getTickLength() const { return settings_->pcp_->axisSize_ * 2.0f; } float PCPMajorTickSettings::getTickWidth() const { return settings_->getWidth(); } double PCPMajorTickSettings::getTickDelta() const { return settings_->catCol_ ? 1.0 : 0.0; } bool PCPMajorTickSettings::getRangeBasedTicks() const { return false; } TickStyle PCPMinorTickSettings::getStyle() const { return TickStyle::None; } bool PCPMinorTickSettings::getFillAxis() const { return false; } vec4 PCPMinorTickSettings::getColor() const { return settings_->getColor(); } float PCPMinorTickSettings::getTickLength() const { return 0.0f; } float PCPMinorTickSettings::getTickWidth() const { return 0.0f; } int PCPMinorTickSettings::getTickFrequency() const { return 0; } } // namespace plot } // namespace inviwo
Make PCP axes display the ranges instead of the values. We should display the values next to the slider boxes when hovering, or similar, instead
PlottingGL: Make PCP axes display the ranges instead of the values. We should display the values next to the slider boxes when hovering, or similar, instead
C++
bsd-2-clause
inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo
b12150a42e60db287120c9629db5ec570a6770a9
tools/appendzip.cpp
tools/appendzip.cpp
/* Zipios++ - a small C++ library that provides easy access to .zip files. Copyright (C) 2000-2007 Thomas Sondergaard Copyright (C) 2015 Made to Order Software Corporation This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** \file * \brief Tool used to append a Zip archive at the end of another file. * \anchor appendzip_anchor * * Source code to a small program appendzip that appends a zip * archive to another file. Run appendzip without arguments to * get a helpful usage message. */ #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> // static variables namespace { char *g_progname; void usage() { // see the ZipFile::openEmbeddedZipFile() function for details... std::cout << "Usage: " << g_progname << " exe-file zipfile" << std::endl; std::cout << "This tool appends a zipfile at the end of any other file (most often a .exe under MS-Windows)." << std::endl; std::cout << "The openEmbeddedZipFile() function can then be used to read the file." << std::endl; exit(1); } } // no name namespace int main(int argc, char *argv[]) { g_progname = argv[0]; char *e(strrchr(g_progname, '/')); if(e) { g_progname = e + 1; } e = strrchr(g_progname, '\\'); if(e) { g_progname = e + 1; } if(argc != 3) { usage(); } std::ofstream exef(argv[1], std::ios::app | std::ios::binary); if(!exef) { std::cerr << g_progname << ":error: Unable to open " << argv[1] << " for writing" << std::endl; usage(); } std::ifstream zipf(argv[2], std::ios::in | std::ios::binary); if(!zipf) { std::cerr << g_progname << ":error: Unable to open " << argv[2] << " for reading." << std::endl; usage(); } // get eof pos (to become zip file starting position). uint32_t const zip_start = exef.tellp(); std::cout << "zip start will be at " << zip_start << std::endl; // Append zip file to exe file exef << zipf.rdbuf(); // write zipfile start offset to file exef << static_cast<unsigned char>(zip_start); exef << static_cast<unsigned char>(zip_start >> 8); exef << static_cast<unsigned char>(zip_start >> 16); exef << static_cast<unsigned char>(zip_start >> 24); //zipios::writeUint32(zip_start, exef); -- TODO: delete once verified return 0; } // Local Variables: // mode: cpp // indent-tabs-mode: nil // c-basic-offset: 4 // tab-width: 4 // End: // vim: ts=4 sw=4 et
/* Zipios++ - a small C++ library that provides easy access to .zip files. Copyright (C) 2000-2007 Thomas Sondergaard Copyright (C) 2015 Made to Order Software Corporation This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** \file * \brief Tool used to append a Zip archive at the end of another file. * \anchor appendzip_anchor * * Source code to a small program appendzip that appends a zip * archive to another file. Run appendzip without arguments to * get a helpful usage message. */ #include <cstdlib> #include <cstring> #include <cstdint> #include <iostream> #include <fstream> // static variables namespace { char *g_progname; void usage() { // see the ZipFile::openEmbeddedZipFile() function for details... std::cout << "Usage: " << g_progname << " exe-file zipfile" << std::endl; std::cout << "This tool appends a zipfile at the end of any other file (most often a .exe under MS-Windows)." << std::endl; std::cout << "The openEmbeddedZipFile() function can then be used to read the file." << std::endl; exit(1); } } // no name namespace int main(int argc, char *argv[]) { g_progname = argv[0]; char *e(strrchr(g_progname, '/')); if(e) { g_progname = e + 1; } e = strrchr(g_progname, '\\'); if(e) { g_progname = e + 1; } if(argc != 3) { usage(); } std::ofstream exef(argv[1], std::ios::app | std::ios::binary); if(!exef) { std::cerr << g_progname << ":error: Unable to open " << argv[1] << " for writing" << std::endl; usage(); } std::ifstream zipf(argv[2], std::ios::in | std::ios::binary); if(!zipf) { std::cerr << g_progname << ":error: Unable to open " << argv[2] << " for reading." << std::endl; usage(); } // get eof pos (to become zip file starting position). std::uint32_t const zip_start = exef.tellp(); std::cout << "zip start will be at " << zip_start << std::endl; // Append zip file to exe file exef << zipf.rdbuf(); // write zipfile start offset to file exef << static_cast<unsigned char>(zip_start); exef << static_cast<unsigned char>(zip_start >> 8); exef << static_cast<unsigned char>(zip_start >> 16); exef << static_cast<unsigned char>(zip_start >> 24); //zipios::writeUint32(zip_start, exef); -- TODO: delete once verified return 0; } // Local Variables: // mode: cpp // indent-tabs-mode: nil // c-basic-offset: 4 // tab-width: 4 // End: // vim: ts=4 sw=4 et
Add missing header
Add missing header
C++
lgpl-2.1
martinmoene/zipios,pgquiles/zipios,martinmoene/zipios,martinmoene/zipios,pgquiles/zipios,martinmoene/zipios,pgquiles/zipios,pgquiles/zipios
e8335d67cd199f764c3838cc0cbaecb87c2ec913
matrix.cpp
matrix.cpp
#include <iostream> #include <pthread.h> #include <getopt.h> #include <time.h> using namespace std; int SIZE=5000; int NUM=2; long long **A,**B,**C; int sum=0; void init(long long **&mat,bool result=false) { int i=0,j=0,val=0; mat= new long long*[SIZE]; for(int i=0;i<SIZE;i++) { mat[i]=new long long [SIZE]; for(int j=0;j<SIZE;j++) { if(!result) mat[i][j]=++val; else mat[i][j]=0; } } } void print(long long **mat) { for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) { cout<<mat[i][j]<<" "; } cout<<endl; } } void* multiply (void *p) { int col=(long)p; col=col*(SIZE/NUM); int end=0; if((long)p==NUM-1) end=SIZE; else end=col+SIZE/NUM; for(int i=col;i<end;i++) { for(int j=0;j<SIZE;j++) { C[i][j]+=A[i][j]*B[j][i]; } } } int main(int argc,char** argv) { int c; while((c=getopt(argc,argv,"ht:s:"))!=-1) { switch(c) { case 'h': cout<<"-t :number of threads, default 2"<<endl <<"-s :size of matrix,deafult 5000x5000"<<endl; return 0; break; case 's': SIZE=atoi(optarg); break; case 't': NUM=atoi(optarg); break; case '?': break; default: cout<<"wrong input"<<endl; return -1; } } clock_t start=clock(); init(A); init(B); init(C,true); // print(A),print(B); pthread_t pt[NUM]; for(int i=0;i<NUM;i++) { pthread_create(&pt[i],NULL,multiply,(void *)i); } for(int i=0;i<NUM;i++) { pthread_join(pt[i],NULL); } // print(C); if your matrix size is not so big, do it. Otherwise, simply just don't; cout<<"For size "<<SIZE<<"x"<<SIZE<<" running time with "<<NUM<<" threads is "<<clock()-start<<endl; return 0; }
#include <iostream> #include <pthread.h> #include <getopt.h> #include <time.h> using namespace std; int SIZE=5000; int NUM=2; long long **A,**B,**C; int sum=0; void init(long long **&mat,bool result=false) { int i=0,j=0,val=0; mat= new long long*[SIZE]; for(int i=0;i<SIZE;i++) { mat[i]=new long long [SIZE]; for(int j=0;j<SIZE;j++) { if(!result) mat[i][j]=++val; else mat[i][j]=0; } } } void print(long long **mat) { for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) { cout<<mat[i][j]<<" "; } cout<<endl; } } void* multiply (void *p) { int col=(long)p; col=col*(SIZE/NUM); int end=0; if((long)p==NUM-1) end=SIZE; else end=col+SIZE/NUM; for(int i=col;i<end;i++) { for(int j=0;j<SIZE;j++) { C[i][j]+=A[i][j]*B[j][i]; } } } int main(int argc,char** argv) { int c; while((c=getopt(argc,argv,"ht:s:"))!=-1) { switch(c) { case 'h': cout<<"-t :number of threads, default 2"<<endl <<"-s :size of matrix,deafult 5000x5000"<<endl; return 0; break; case 's': SIZE=atoi(optarg); break; case 't': NUM=atoi(optarg); break; case '?': break; default: cout<<"wrong input"<<endl; return -1; } } clock_t start=clock(); init(A); init(B); init(C,true); // print(A),print(B); pthread_t pt[NUM]; for(int i=0;i<NUM;i++) { pthread_create(&pt[i],NULL,multiply,(void *)i); } for(int i=0;i<NUM;i++) { pthread_join(pt[i],NULL); } // print(C); if your matrix size is not so big, do it. Otherwise, simply just don't; cout<<"For size "<<SIZE<<"x"<<SIZE<<" running time with "<<NUM<<" threads is "<<clock()-start<<endl; return 0; }
Revert "testing"
Revert "testing" This reverts commit 25ce763e28a93d77be0d8b5347d302f122480499.
C++
apache-2.0
iroot900/pThread-Concurrency-Synchronization
50d1087a944f50c5c7159371449e305e4bb457dc
share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.cpp
share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "sgitemnodeinstance.h" #include "qt5nodeinstanceserver.h" #include <QDeclarativeExpression> #include <QSGView> #include <cmath> #include <QHash> #include <QtDebug> namespace QmlDesigner { namespace Internal { SGItemNodeInstance::SGItemNodeInstance(QSGItem *item) : ObjectNodeInstance(item), m_hasHeight(false), m_hasWidth(false), m_isResizable(true), m_hasContent(true), m_isMovable(true), m_x(0.0), m_y(0.0), m_width(0.0), m_height(0.0) { } SGItemNodeInstance::~SGItemNodeInstance() { if (sgItem()) designerSupport()->derefFromEffectItem(sgItem()); } bool SGItemNodeInstance::hasContent() const { return m_hasContent; } QList<ServerNodeInstance> SGItemNodeInstance::childItems() const { QList<ServerNodeInstance> instanceList; foreach (QSGItem *childItem, sgItem()->childItems()) { if (childItem && nodeInstanceServer()->hasInstanceForObject(childItem)) { instanceList.append(nodeInstanceServer()->instanceForObject(childItem)); } else { //there might be an item in between the parent instance //and the child instance. //Popular example is flickable which has a viewport item between //the flickable item and the flickable children instanceList.append(childItemsForChild(childItem)); //In such a case we go deeper inside the item and //search for child items with instances. } } return instanceList; } QList<ServerNodeInstance> SGItemNodeInstance::childItemsForChild(QSGItem *childItem) const { QList<ServerNodeInstance> instanceList; if (childItem) { foreach (QSGItem *childItem, childItem->childItems()) { if (childItem && nodeInstanceServer()->hasInstanceForObject(childItem)) { instanceList.append(nodeInstanceServer()->instanceForObject(childItem)); } else { instanceList.append(childItemsForChild(childItem)); } } } return instanceList; } void SGItemNodeInstance::setHasContent(bool hasContent) { m_hasContent = hasContent; } bool anyItemHasContent(QSGItem *graphicsItem) { if (graphicsItem->flags().testFlag(QSGItem::ItemHasContents)) return true; foreach (QSGItem *childItem, graphicsItem->childItems()) { if (anyItemHasContent(childItem)) return true; } return false; } QPointF SGItemNodeInstance::position() const { return sgItem()->pos(); } QTransform SGItemNodeInstance::transform() const { return DesignerSupport::parentTransform(sgItem()); } QTransform SGItemNodeInstance::customTransform() const { return QTransform(); } QTransform SGItemNodeInstance::sceneTransform() const { return DesignerSupport::canvasTransform(sgItem()); } double SGItemNodeInstance::rotation() const { return sgItem()->rotation(); } double SGItemNodeInstance::scale() const { return sgItem()->scale(); } QPointF SGItemNodeInstance::transformOriginPoint() const { return sgItem()->transformOriginPoint(); } double SGItemNodeInstance::zValue() const { return sgItem()->z(); } double SGItemNodeInstance::opacity() const { return sgItem()->opacity(); } QObject *SGItemNodeInstance::parent() const { if (!sgItem() || !sgItem()->parentItem()) return 0; return sgItem()->parentItem(); } bool SGItemNodeInstance::equalSGItem(QSGItem *item) const { return item == sgItem(); } QImage SGItemNodeInstance::renderImage() const { QImage image = designerSupport()->renderImageForItem(sgItem()); image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); qDebug() << __FUNCTION__ << image.size(); return image; } bool SGItemNodeInstance::isMovable() const { if (isRootNodeInstance()) return false; return m_isMovable && sgItem() && sgItem()->parentItem(); } void SGItemNodeInstance::setMovable(bool movable) { m_isMovable = movable; } SGItemNodeInstance::Pointer SGItemNodeInstance::create(QObject *object) { QSGItem *sgItem = qobject_cast<QSGItem*>(object); Q_ASSERT(sgItem); Pointer instance(new SGItemNodeInstance(sgItem)); instance->setHasContent(anyItemHasContent(sgItem)); sgItem->setFlag(QSGItem::ItemHasContents, true); static_cast<QDeclarativeParserStatus*>(sgItem)->classBegin(); instance->populateResetHashes(); return instance; } void SGItemNodeInstance::initialize(const ObjectNodeInstance::Pointer &objectNodeInstance) { if (instanceId() == 0) { DesignerSupport::setRootItem(nodeInstanceServer()->sgView(), sgItem()); } else { sgItem()->setParentItem(qobject_cast<QSGItem*>(nodeInstanceServer()->sgView()->rootObject())); } designerSupport()->refFromEffectItem(sgItem()); ObjectNodeInstance::initialize(objectNodeInstance); sgItem()->update(); } bool SGItemNodeInstance::isSGItem() const { return true; } QSizeF SGItemNodeInstance::size() const { double width; if (DesignerSupport::isValidWidth(sgItem())) { width = sgItem()->width(); } else { width = sgItem()->implicitWidth(); } double height; if (DesignerSupport::isValidHeight(sgItem())) { height = sgItem()->height(); } else { height = sgItem()->implicitHeight(); } return QSizeF(width, height); } static inline bool isRectangleSane(const QRectF &rect) { return rect.isValid() && (rect.width() < 10000) && (rect.height() < 10000); } QRectF SGItemNodeInstance::boundingRectWithStepChilds(QSGItem *parentItem) const { QRectF boundingRect = parentItem->boundingRect(); foreach (QSGItem *childItem, parentItem->childItems()) { if (nodeInstanceServer()->hasInstanceForObject(childItem)) { QRectF transformedRect = childItem->mapRectToItem(parentItem, boundingRectWithStepChilds(childItem)); if (isRectangleSane(transformedRect)) boundingRect = boundingRect.united(transformedRect); } } return boundingRect; } QRectF SGItemNodeInstance::boundingRect() const { if (sgItem()) { if (sgItem()->clip()) { return sgItem()->boundingRect(); } else { return boundingRectWithStepChilds(sgItem()); } } return QRectF(); } void SGItemNodeInstance::setPropertyVariant(const QString &name, const QVariant &value) { if (name == "state") return; // states are only set by us if (name == "height") { m_height = value.toDouble(); if (value.isValid()) m_hasHeight = true; else m_hasHeight = false; } if (name == "width") { m_width = value.toDouble(); if (value.isValid()) m_hasWidth = true; else m_hasWidth = false; } if (name == "x") m_x = value.toDouble(); if (name == "y") m_y = value.toDouble(); ObjectNodeInstance::setPropertyVariant(name, value); refresh(); } void SGItemNodeInstance::setPropertyBinding(const QString &name, const QString &expression) { if (name == "state") return; // states are only set by us ObjectNodeInstance::setPropertyBinding(name, expression); } QVariant SGItemNodeInstance::property(const QString &name) const { return ObjectNodeInstance::property(name); } void SGItemNodeInstance::resetHorizontal() { setPropertyVariant("x", m_x); if (m_width > 0.0) { setPropertyVariant("width", m_width); } else { setPropertyVariant("width", sgItem()->implicitWidth()); } } void SGItemNodeInstance::resetVertical() { setPropertyVariant("y", m_y); if (m_height > 0.0) { setPropertyVariant("height", m_height); } else { setPropertyVariant("height", sgItem()->implicitWidth()); } } static void repositioning(QSGItem *item) { if (!item) return; // QDeclarativeBasePositioner *positioner = qobject_cast<QDeclarativeBasePositioner*>(item); // if (positioner) // positioner->rePositioning(); if (item->parentItem()) repositioning(item->parentItem()); } void SGItemNodeInstance::refresh() { repositioning(sgItem()); } void SGItemNodeInstance::doComponentComplete() { if (sgItem()) { if (DesignerSupport::isComponentComplete(sgItem())) return; static_cast<QDeclarativeParserStatus*>(sgItem())->componentComplete(); } sgItem()->update(); } bool SGItemNodeInstance::isResizable() const { if (isRootNodeInstance()) return false; return m_isResizable && sgItem() && sgItem()->parentItem(); } void SGItemNodeInstance::setResizable(bool resizeable) { m_isResizable = resizeable; } int SGItemNodeInstance::penWidth() const { return DesignerSupport::borderWidth(sgItem()); } void SGItemNodeInstance::resetProperty(const QString &name) { if (name == "height") { m_hasHeight = false; m_height = 0.0; } if (name == "width") { m_hasWidth = false; m_width = 0.0; } if (name == "x") m_x = 0.0; if (name == "y") m_y = 0.0; DesignerSupport::resetAnchor(sgItem(), name); if (name == "anchors.fill") { resetHorizontal(); resetVertical(); } else if (name == "anchors.centerIn") { resetHorizontal(); resetVertical(); } else if (name == "anchors.top") { resetVertical(); } else if (name == "anchors.left") { resetHorizontal(); } else if (name == "anchors.right") { resetHorizontal(); } else if (name == "anchors.bottom") { resetVertical(); } else if (name == "anchors.horizontalCenter") { resetHorizontal(); } else if (name == "anchors.verticalCenter") { resetVertical(); } else if (name == "anchors.baseline") { resetVertical(); } ObjectNodeInstance::resetProperty(name); } void SGItemNodeInstance::reparent(const ObjectNodeInstance::Pointer &oldParentInstance, const QString &oldParentProperty, const ObjectNodeInstance::Pointer &newParentInstance, const QString &newParentProperty) { if (oldParentInstance && oldParentInstance->isPositioner()) { setInPositioner(false); setMovable(true); } ObjectNodeInstance::reparent(oldParentInstance, oldParentProperty, newParentInstance, newParentProperty); if (newParentInstance && newParentInstance->isPositioner()) { setInPositioner(true); setMovable(false); } if (oldParentInstance && oldParentInstance->isPositioner() && !(newParentInstance && newParentInstance->isPositioner())) { if (!hasBindingForProperty("x")) setPropertyVariant("x", m_x); if (!hasBindingForProperty("y")) setPropertyVariant("y", m_y); } refresh(); DesignerSupport::updateDirtyNode(sgItem()); } static bool isValidAnchorName(const QString &name) { static QStringList anchorNameList(QStringList() << "anchors.top" << "anchors.left" << "anchors.right" << "anchors.bottom" << "anchors.verticalCenter" << "anchors.horizontalCenter" << "anchors.fill" << "anchors.centerIn" << "anchors.baseline"); return anchorNameList.contains(name); } bool SGItemNodeInstance::hasAnchor(const QString &name) const { return DesignerSupport::hasAnchor(sgItem(), name); } QPair<QString, ServerNodeInstance> SGItemNodeInstance::anchor(const QString &name) const { if (!isValidAnchorName(name) || !DesignerSupport::hasAnchor(sgItem(), name)) return ObjectNodeInstance::anchor(name); QPair<QString, QObject*> nameObjectPair = DesignerSupport::anchorLineTarget(sgItem(), name, context()); QObject *targetObject = nameObjectPair.second; QString targetName = nameObjectPair.first; if (targetObject && nodeInstanceServer()->hasInstanceForObject(targetObject)) { return qMakePair(targetName, nodeInstanceServer()->instanceForObject(targetObject)); } else { return ObjectNodeInstance::anchor(name); } } QList<ServerNodeInstance> SGItemNodeInstance::stateInstances() const { QList<ServerNodeInstance> instanceList; QList<QObject*> stateList = DesignerSupport::statesForItem(sgItem()); foreach (QObject *state, stateList) { if (state && nodeInstanceServer()->hasInstanceForObject(state)) instanceList.append(nodeInstanceServer()->instanceForObject(state)); } return instanceList; } bool SGItemNodeInstance::isAnchoredBySibling() const { if (sgItem()->parentItem()) { foreach (QSGItem *siblingItem, sgItem()->parentItem()->childItems()) { // search in siblings for a anchor to this item if (siblingItem) { if (DesignerSupport::isAnchoredTo(siblingItem, sgItem())) return true; } } } return false; } bool SGItemNodeInstance::isAnchoredByChildren() const { if (DesignerSupport::areChildrenAnchoredTo(sgItem(), sgItem())) // search in children for a anchor to this item return true; return false; } QSGItem *SGItemNodeInstance::sgItem() const { if (object() == 0) return 0; Q_ASSERT(qobject_cast<QSGItem*>(object())); return static_cast<QSGItem*>(object()); } DesignerSupport *SGItemNodeInstance::designerSupport() const { return qt5NodeInstanceServer()->designerSupport(); } Qt5NodeInstanceServer *SGItemNodeInstance::qt5NodeInstanceServer() const { return qobject_cast<Qt5NodeInstanceServer*>(nodeInstanceServer()); } } // namespace Internal } // namespace QmlDesigner
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "sgitemnodeinstance.h" #include "qt5nodeinstanceserver.h" #include <QDeclarativeExpression> #include <QSGView> #include <cmath> #include <QHash> #include <QtDebug> namespace QmlDesigner { namespace Internal { SGItemNodeInstance::SGItemNodeInstance(QSGItem *item) : ObjectNodeInstance(item), m_hasHeight(false), m_hasWidth(false), m_isResizable(true), m_hasContent(true), m_isMovable(true), m_x(0.0), m_y(0.0), m_width(0.0), m_height(0.0) { } SGItemNodeInstance::~SGItemNodeInstance() { if (sgItem()) designerSupport()->derefFromEffectItem(sgItem()); } bool SGItemNodeInstance::hasContent() const { return m_hasContent; } QList<ServerNodeInstance> SGItemNodeInstance::childItems() const { QList<ServerNodeInstance> instanceList; foreach (QSGItem *childItem, sgItem()->childItems()) { if (childItem && nodeInstanceServer()->hasInstanceForObject(childItem)) { instanceList.append(nodeInstanceServer()->instanceForObject(childItem)); } else { //there might be an item in between the parent instance //and the child instance. //Popular example is flickable which has a viewport item between //the flickable item and the flickable children instanceList.append(childItemsForChild(childItem)); //In such a case we go deeper inside the item and //search for child items with instances. } } return instanceList; } QList<ServerNodeInstance> SGItemNodeInstance::childItemsForChild(QSGItem *childItem) const { QList<ServerNodeInstance> instanceList; if (childItem) { foreach (QSGItem *childItem, childItem->childItems()) { if (childItem && nodeInstanceServer()->hasInstanceForObject(childItem)) { instanceList.append(nodeInstanceServer()->instanceForObject(childItem)); } else { instanceList.append(childItemsForChild(childItem)); } } } return instanceList; } void SGItemNodeInstance::setHasContent(bool hasContent) { m_hasContent = hasContent; } bool anyItemHasContent(QSGItem *graphicsItem) { if (graphicsItem->flags().testFlag(QSGItem::ItemHasContents)) return true; foreach (QSGItem *childItem, graphicsItem->childItems()) { if (anyItemHasContent(childItem)) return true; } return false; } QPointF SGItemNodeInstance::position() const { return sgItem()->pos(); } QTransform SGItemNodeInstance::transform() const { return DesignerSupport::parentTransform(sgItem()); } QTransform SGItemNodeInstance::customTransform() const { return QTransform(); } QTransform SGItemNodeInstance::sceneTransform() const { return DesignerSupport::canvasTransform(sgItem()); } double SGItemNodeInstance::rotation() const { return sgItem()->rotation(); } double SGItemNodeInstance::scale() const { return sgItem()->scale(); } QPointF SGItemNodeInstance::transformOriginPoint() const { return sgItem()->transformOriginPoint(); } double SGItemNodeInstance::zValue() const { return sgItem()->z(); } double SGItemNodeInstance::opacity() const { return sgItem()->opacity(); } QObject *SGItemNodeInstance::parent() const { if (!sgItem() || !sgItem()->parentItem()) return 0; return sgItem()->parentItem(); } bool SGItemNodeInstance::equalSGItem(QSGItem *item) const { return item == sgItem(); } QImage SGItemNodeInstance::renderImage() const { QImage image = designerSupport()->renderImageForItem(sgItem()); image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); qDebug() << __FUNCTION__ << image.size(); return image; } bool SGItemNodeInstance::isMovable() const { if (isRootNodeInstance()) return false; return m_isMovable && sgItem() && sgItem()->parentItem(); } void SGItemNodeInstance::setMovable(bool movable) { m_isMovable = movable; } SGItemNodeInstance::Pointer SGItemNodeInstance::create(QObject *object) { QSGItem *sgItem = qobject_cast<QSGItem*>(object); Q_ASSERT(sgItem); Pointer instance(new SGItemNodeInstance(sgItem)); instance->setHasContent(anyItemHasContent(sgItem)); sgItem->setFlag(QSGItem::ItemHasContents, true); static_cast<QDeclarativeParserStatus*>(sgItem)->classBegin(); instance->populateResetHashes(); return instance; } void SGItemNodeInstance::initialize(const ObjectNodeInstance::Pointer &objectNodeInstance) { if (instanceId() == 0) { DesignerSupport::setRootItem(nodeInstanceServer()->sgView(), sgItem()); } else { sgItem()->setParentItem(qobject_cast<QSGItem*>(nodeInstanceServer()->sgView()->rootObject())); } designerSupport()->refFromEffectItem(sgItem()); ObjectNodeInstance::initialize(objectNodeInstance); sgItem()->update(); } bool SGItemNodeInstance::isSGItem() const { return true; } QSizeF SGItemNodeInstance::size() const { double width; if (DesignerSupport::isValidWidth(sgItem())) { width = sgItem()->width(); } else { width = sgItem()->implicitWidth(); } double height; if (DesignerSupport::isValidHeight(sgItem())) { height = sgItem()->height(); } else { height = sgItem()->implicitHeight(); } return QSizeF(width, height); } static inline bool isRectangleSane(const QRectF &rect) { return rect.isValid() && (rect.width() < 10000) && (rect.height() < 10000); } QRectF SGItemNodeInstance::boundingRectWithStepChilds(QSGItem *parentItem) const { QRectF boundingRect = parentItem->boundingRect(); foreach (QSGItem *childItem, parentItem->childItems()) { if (!nodeInstanceServer()->hasInstanceForObject(childItem)) { QRectF transformedRect = childItem->mapRectToItem(parentItem, boundingRectWithStepChilds(childItem)); if (isRectangleSane(transformedRect)) boundingRect = boundingRect.united(transformedRect); } } return boundingRect; } QRectF SGItemNodeInstance::boundingRect() const { if (sgItem()) { if (sgItem()->clip()) { return sgItem()->boundingRect(); } else { return boundingRectWithStepChilds(sgItem()); } } return QRectF(); } void SGItemNodeInstance::setPropertyVariant(const QString &name, const QVariant &value) { if (name == "state") return; // states are only set by us if (name == "height") { m_height = value.toDouble(); if (value.isValid()) m_hasHeight = true; else m_hasHeight = false; } if (name == "width") { m_width = value.toDouble(); if (value.isValid()) m_hasWidth = true; else m_hasWidth = false; } if (name == "x") m_x = value.toDouble(); if (name == "y") m_y = value.toDouble(); ObjectNodeInstance::setPropertyVariant(name, value); refresh(); } void SGItemNodeInstance::setPropertyBinding(const QString &name, const QString &expression) { if (name == "state") return; // states are only set by us ObjectNodeInstance::setPropertyBinding(name, expression); } QVariant SGItemNodeInstance::property(const QString &name) const { return ObjectNodeInstance::property(name); } void SGItemNodeInstance::resetHorizontal() { setPropertyVariant("x", m_x); if (m_width > 0.0) { setPropertyVariant("width", m_width); } else { setPropertyVariant("width", sgItem()->implicitWidth()); } } void SGItemNodeInstance::resetVertical() { setPropertyVariant("y", m_y); if (m_height > 0.0) { setPropertyVariant("height", m_height); } else { setPropertyVariant("height", sgItem()->implicitWidth()); } } static void repositioning(QSGItem *item) { if (!item) return; // QDeclarativeBasePositioner *positioner = qobject_cast<QDeclarativeBasePositioner*>(item); // if (positioner) // positioner->rePositioning(); if (item->parentItem()) repositioning(item->parentItem()); } void SGItemNodeInstance::refresh() { repositioning(sgItem()); } void SGItemNodeInstance::doComponentComplete() { if (sgItem()) { if (DesignerSupport::isComponentComplete(sgItem())) return; static_cast<QDeclarativeParserStatus*>(sgItem())->componentComplete(); } sgItem()->update(); } bool SGItemNodeInstance::isResizable() const { if (isRootNodeInstance()) return false; return m_isResizable && sgItem() && sgItem()->parentItem(); } void SGItemNodeInstance::setResizable(bool resizeable) { m_isResizable = resizeable; } int SGItemNodeInstance::penWidth() const { return DesignerSupport::borderWidth(sgItem()); } void SGItemNodeInstance::resetProperty(const QString &name) { if (name == "height") { m_hasHeight = false; m_height = 0.0; } if (name == "width") { m_hasWidth = false; m_width = 0.0; } if (name == "x") m_x = 0.0; if (name == "y") m_y = 0.0; DesignerSupport::resetAnchor(sgItem(), name); if (name == "anchors.fill") { resetHorizontal(); resetVertical(); } else if (name == "anchors.centerIn") { resetHorizontal(); resetVertical(); } else if (name == "anchors.top") { resetVertical(); } else if (name == "anchors.left") { resetHorizontal(); } else if (name == "anchors.right") { resetHorizontal(); } else if (name == "anchors.bottom") { resetVertical(); } else if (name == "anchors.horizontalCenter") { resetHorizontal(); } else if (name == "anchors.verticalCenter") { resetVertical(); } else if (name == "anchors.baseline") { resetVertical(); } ObjectNodeInstance::resetProperty(name); } void SGItemNodeInstance::reparent(const ObjectNodeInstance::Pointer &oldParentInstance, const QString &oldParentProperty, const ObjectNodeInstance::Pointer &newParentInstance, const QString &newParentProperty) { if (oldParentInstance && oldParentInstance->isPositioner()) { setInPositioner(false); setMovable(true); } ObjectNodeInstance::reparent(oldParentInstance, oldParentProperty, newParentInstance, newParentProperty); if (newParentInstance && newParentInstance->isPositioner()) { setInPositioner(true); setMovable(false); } if (oldParentInstance && oldParentInstance->isPositioner() && !(newParentInstance && newParentInstance->isPositioner())) { if (!hasBindingForProperty("x")) setPropertyVariant("x", m_x); if (!hasBindingForProperty("y")) setPropertyVariant("y", m_y); } refresh(); DesignerSupport::updateDirtyNode(sgItem()); } static bool isValidAnchorName(const QString &name) { static QStringList anchorNameList(QStringList() << "anchors.top" << "anchors.left" << "anchors.right" << "anchors.bottom" << "anchors.verticalCenter" << "anchors.horizontalCenter" << "anchors.fill" << "anchors.centerIn" << "anchors.baseline"); return anchorNameList.contains(name); } bool SGItemNodeInstance::hasAnchor(const QString &name) const { return DesignerSupport::hasAnchor(sgItem(), name); } QPair<QString, ServerNodeInstance> SGItemNodeInstance::anchor(const QString &name) const { if (!isValidAnchorName(name) || !DesignerSupport::hasAnchor(sgItem(), name)) return ObjectNodeInstance::anchor(name); QPair<QString, QObject*> nameObjectPair = DesignerSupport::anchorLineTarget(sgItem(), name, context()); QObject *targetObject = nameObjectPair.second; QString targetName = nameObjectPair.first; if (targetObject && nodeInstanceServer()->hasInstanceForObject(targetObject)) { return qMakePair(targetName, nodeInstanceServer()->instanceForObject(targetObject)); } else { return ObjectNodeInstance::anchor(name); } } QList<ServerNodeInstance> SGItemNodeInstance::stateInstances() const { QList<ServerNodeInstance> instanceList; QList<QObject*> stateList = DesignerSupport::statesForItem(sgItem()); foreach (QObject *state, stateList) { if (state && nodeInstanceServer()->hasInstanceForObject(state)) instanceList.append(nodeInstanceServer()->instanceForObject(state)); } return instanceList; } bool SGItemNodeInstance::isAnchoredBySibling() const { if (sgItem()->parentItem()) { foreach (QSGItem *siblingItem, sgItem()->parentItem()->childItems()) { // search in siblings for a anchor to this item if (siblingItem) { if (DesignerSupport::isAnchoredTo(siblingItem, sgItem())) return true; } } } return false; } bool SGItemNodeInstance::isAnchoredByChildren() const { if (DesignerSupport::areChildrenAnchoredTo(sgItem(), sgItem())) // search in children for a anchor to this item return true; return false; } QSGItem *SGItemNodeInstance::sgItem() const { if (object() == 0) return 0; Q_ASSERT(qobject_cast<QSGItem*>(object())); return static_cast<QSGItem*>(object()); } DesignerSupport *SGItemNodeInstance::designerSupport() const { return qt5NodeInstanceServer()->designerSupport(); } Qt5NodeInstanceServer *SGItemNodeInstance::qt5NodeInstanceServer() const { return qobject_cast<Qt5NodeInstanceServer*>(nodeInstanceServer()); } } // namespace Internal } // namespace QmlDesigner
Fix bounding rectangle calculation
QmlDesinger.NodeInstances: Fix bounding rectangle calculation Change-Id: Ia0633416e50da68377a781050e301e5721540d6b Reviewed-on: http://codereview.qt.nokia.com/3971 Reviewed-by: Qt Sanity Bot <[email protected]> Reviewed-by: Thomas Hartmann <[email protected]>
C++
lgpl-2.1
bakaiadam/collaborative_qt_creator,colede/qtcreator,jonnor/qt-creator,jonnor/qt-creator,xianian/qt-creator,omniacreator/qtcreator,richardmg/qtcreator,duythanhphan/qt-creator,xianian/qt-creator,danimo/qt-creator,darksylinc/qt-creator,KDAB/KDAB-Creator,kuba1/qtcreator,martyone/sailfish-qtcreator,kuba1/qtcreator,KDE/android-qt-creator,duythanhphan/qt-creator,kuba1/qtcreator,farseerri/git_code,jonnor/qt-creator,KDAB/KDAB-Creator,Distrotech/qtcreator,maui-packages/qt-creator,KDE/android-qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,KDAB/KDAB-Creator,syntheticpp/qt-creator,malikcjm/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,omniacreator/qtcreator,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,Distrotech/qtcreator,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,KDAB/KDAB-Creator,kuba1/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,xianian/qt-creator,farseerri/git_code,farseerri/git_code,syntheticpp/qt-creator,richardmg/qtcreator,hdweiss/qt-creator-visualizer,farseerri/git_code,hdweiss/qt-creator-visualizer,syntheticpp/qt-creator,farseerri/git_code,omniacreator/qtcreator,syntheticpp/qt-creator,Distrotech/qtcreator,danimo/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,colede/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,duythanhphan/qt-creator,colede/qtcreator,Distrotech/qtcreator,darksylinc/qt-creator,martyone/sailfish-qtcreator,richardmg/qtcreator,jonnor/qt-creator,maui-packages/qt-creator,richardmg/qtcreator,ostash/qt-creator-i18n-uk,azat/qtcreator,ostash/qt-creator-i18n-uk,azat/qtcreator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,syntheticpp/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,colede/qtcreator,hdweiss/qt-creator-visualizer,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,Distrotech/qtcreator,duythanhphan/qt-creator,azat/qtcreator,maui-packages/qt-creator,malikcjm/qtcreator,AltarBeastiful/qt-creator,azat/qtcreator,richardmg/qtcreator,xianian/qt-creator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,KDAB/KDAB-Creator,ostash/qt-creator-i18n-uk,azat/qtcreator,KDE/android-qt-creator,azat/qtcreator,amyvmiwei/qt-creator,KDE/android-qt-creator,darksylinc/qt-creator,richardmg/qtcreator,omniacreator/qtcreator,danimo/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,KDAB/KDAB-Creator,amyvmiwei/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,colede/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,maui-packages/qt-creator,syntheticpp/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,jonnor/qt-creator,omniacreator/qtcreator,bakaiadam/collaborative_qt_creator,farseerri/git_code,malikcjm/qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,maui-packages/qt-creator,KDE/android-qt-creator,Distrotech/qtcreator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,malikcjm/qtcreator,ostash/qt-creator-i18n-uk,farseerri/git_code,amyvmiwei/qt-creator,duythanhphan/qt-creator,bakaiadam/collaborative_qt_creator,Distrotech/qtcreator,KDE/android-qt-creator,KDE/android-qt-creator,malikcjm/qtcreator,omniacreator/qtcreator,kuba1/qtcreator,xianian/qt-creator,darksylinc/qt-creator,colede/qtcreator,AltarBeastiful/qt-creator,xianian/qt-creator,darksylinc/qt-creator,AltarBeastiful/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator,colede/qtcreator
e8347c954b78bf408e6445876797ed28368f641a
opencore/codecs_v2/audio/gsm_amr/amr_nb/enc/src/enc_output_format_tab.cpp
opencore/codecs_v2/audio/gsm_amr/amr_nb/enc/src/enc_output_format_tab.cpp
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.073 ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec Available from http://www.3gpp.org (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Pathname: .audio/gsm-amr/c/src/enc_output_format_tab.c Date: 03/08/2002 ------------------------------------------------------------------------------ REVISION HISTORY Description: Moved WMFBytesUsed and IF2BytesUsed tables from gsmamr_enc.h. Changed their type definition to 'const int'. Renamed tables to WmfEncBytesPerFrame and If2EncBytesPerFrame. Description: Added #ifdef __cplusplus and removed "extern" from table definition. Description: Put "extern" back. Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: None Outputs: None Returns: None Global Variables Used: None Local Variables Needed: None ------------------------------------------------------------------------------ FUNCTION DESCRIPTION This file contains the tables of the number of data bytes per codec mode in both WMF and IF2 output formats. ------------------------------------------------------------------------------ REQUIREMENTS None ------------------------------------------------------------------------------ REFERENCES [1] AMR Speech Codec Frame Structure, 3GPP TS 26.101 version 4.1.0 Release 4, June 2001 ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ RESOURCES USED When the code is written for a specific target processor the the resources used should be documented below. STACK USAGE: [stack count for this module] + [variable to represent stack usage for each subroutine called] where: [stack usage variable] = stack usage for [subroutine name] (see [filename].ext) DATA MEMORY USED: x words PROGRAM MEMORY USED: x words CLOCK CYCLES: [cycle count equation for this module] + [variable used to represent cycle count for each subroutine called] where: [cycle count variable] = cycle count for [subroutine name] (see [filename].ext) ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "typedef.h" /*--------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /* Number of data bytes in an encoder frame for each codec mode */ /* for WMF output format. */ /* Each entry is the sum of the 3GPP frame type byte and the */ /* number of packed core AMR data bytes */ extern const Word16 WmfEncBytesPerFrame[16] = { 13, /* 4.75 */ 14, /* 5.15 */ 16, /* 5.90 */ 18, /* 6.70 */ 20, /* 7.40 */ 21, /* 7.95 */ 27, /* 10.2 */ 32, /* 12.2 */ 6, /* GsmAmr comfort noise */ 7, /* Gsm-Efr comfort noise */ 6, /* IS-641 comfort noise */ 6, /* Pdc-Efr comfort noise */ 0, /* future use */ 0, /* future use */ 0, /* future use */ 1 /* No transmission */ }; /* Number of data bytes in an encoder frame for each codec mode */ /* for IF2 output format */ extern const Word16 If2EncBytesPerFrame[16] = { 13, /* 4.75 */ 14, /* 5.15 */ 16, /* 5.90 */ 18, /* 6.70 */ 19, /* 7.40 */ 21, /* 7.95 */ 26, /* 10.2 */ 31, /* 12.2 */ 6, /* GsmAmr comfort noise */ 6, /* Gsm-Efr comfort noise */ 6, /* IS-641 comfort noise */ 6, /* Pdc-Efr comfort noise */ 0, /* future use */ 0, /* future use */ 0, /* future use */ 1 /* No transmission */ }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Define all local variables ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Function body here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.073 ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec Available from http://www.3gpp.org (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Pathname: .audio/gsm-amr/c/src/enc_output_format_tab.c Date: 03/08/2002 ------------------------------------------------------------------------------ REVISION HISTORY Description: Moved WMFBytesUsed and IF2BytesUsed tables from gsmamr_enc.h. Changed their type definition to 'const int'. Renamed tables to WmfEncBytesPerFrame and If2EncBytesPerFrame. Description: Added #ifdef __cplusplus and removed "extern" from table definition. Description: Put "extern" back. Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: None Outputs: None Returns: None Global Variables Used: None Local Variables Needed: None ------------------------------------------------------------------------------ FUNCTION DESCRIPTION This file contains the tables of the number of data bytes per codec mode in both WMF and IF2 output formats. ------------------------------------------------------------------------------ REQUIREMENTS None ------------------------------------------------------------------------------ REFERENCES [1] AMR Speech Codec Frame Structure, 3GPP TS 26.101 version 4.1.0 Release 4, June 2001 ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ RESOURCES USED When the code is written for a specific target processor the the resources used should be documented below. STACK USAGE: [stack count for this module] + [variable to represent stack usage for each subroutine called] where: [stack usage variable] = stack usage for [subroutine name] (see [filename].ext) DATA MEMORY USED: x words PROGRAM MEMORY USED: x words CLOCK CYCLES: [cycle count equation for this module] + [variable used to represent cycle count for each subroutine called] where: [cycle count variable] = cycle count for [subroutine name] (see [filename].ext) ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "typedef.h" /*--------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /* Number of data bytes in an encoder frame for each codec mode */ /* for WMF output format. */ /* Each entry is the sum of the 3GPP frame type byte and the */ /* number of packed core AMR data bytes */ const Word16 WmfEncBytesPerFrame[16] = { 13, /* 4.75 */ 14, /* 5.15 */ 16, /* 5.90 */ 18, /* 6.70 */ 20, /* 7.40 */ 21, /* 7.95 */ 27, /* 10.2 */ 32, /* 12.2 */ 6, /* GsmAmr comfort noise */ 7, /* Gsm-Efr comfort noise */ 6, /* IS-641 comfort noise */ 6, /* Pdc-Efr comfort noise */ 0, /* future use */ 0, /* future use */ 0, /* future use */ 1 /* No transmission */ }; /* Number of data bytes in an encoder frame for each codec mode */ /* for IF2 output format */ const Word16 If2EncBytesPerFrame[16] = { 13, /* 4.75 */ 14, /* 5.15 */ 16, /* 5.90 */ 18, /* 6.70 */ 19, /* 7.40 */ 21, /* 7.95 */ 26, /* 10.2 */ 31, /* 12.2 */ 6, /* GsmAmr comfort noise */ 6, /* Gsm-Efr comfort noise */ 6, /* IS-641 comfort noise */ 6, /* Pdc-Efr comfort noise */ 0, /* future use */ 0, /* future use */ 0, /* future use */ 1 /* No transmission */ }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Define all local variables ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Function body here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/
Fix compiler warning.
Fix compiler warning. Remove extern keyword from defined variable.
C++
apache-2.0
yxl/opencore-amr-js,yxl/opencore-amr-js,Distrotech/opencore-amr,VFR-maniac/opencore-amr,Distrotech/opencore-amr,jiangjianping/opencore-amr,BelledonneCommunications/opencore-amr,KurentoLegacy/opencore-amr,lyx2014/-opencore-amr,BelledonneCommunications/opencore-amr,lyx2014/-opencore-amr,jiangjianping/opencore-amr,Distrotech/opencore-amr,VFR-maniac/opencore-amr,yxl/opencore-amr-js,VFR-maniac/opencore-amr,yxl/opencore-amr-js,KurentoLegacy/opencore-amr,yxl/opencore-amr-js,KurentoLegacy/opencore-amr
f07cdbd5670d0fa212784220de190ce24cd8d461
plugins/robots/generators/generatorBase/src/robotsGeneratorPluginBase.cpp
plugins/robots/generators/generatorBase/src/robotsGeneratorPluginBase.cpp
/* Copyright 2007-2015 QReal Research Group * * 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 "generatorBase/robotsGeneratorPluginBase.h" #include <QtCore/QDateTime> #include <qrkernel/platformInfo.h> #include <qrutils/inFile.h> #include <qrutils/nameNormalizer.h> #include <qrutils/parserErrorReporter.h> #include <qrgui/textEditor/qscintillaTextEdit.h> using namespace generatorBase; using namespace qReal; using namespace utils; /// If file info creation and modification timestamps differ less than on this value it is considered /// that file was created and filled at the same time. const int maxTimestampsDifference = 3000; RobotsGeneratorPluginBase::RobotsGeneratorPluginBase() { } RobotsGeneratorPluginBase::~RobotsGeneratorPluginBase() { } QString RobotsGeneratorPluginBase::defaultFilePath(const QString &projectName) const { return projectName; } QString RobotsGeneratorPluginBase::generatorName() const { return QString(); } QString RobotsGeneratorPluginBase::defaultProjectName() const { const QString filePath = mProjectManager->saveFilePath(); return filePath.isEmpty() ? "example" : QFileInfo(filePath).completeBaseName(); } bool RobotsGeneratorPluginBase::canGenerateTo(const QString &project) { const QFileInfo fileInfo = generationTarget(project); const int difference = fileInfo.lastModified().toMSecsSinceEpoch() - fileInfo.created().toMSecsSinceEpoch(); return !fileInfo.exists() || difference < maxTimestampsDifference; } void RobotsGeneratorPluginBase::onCurrentRobotModelChanged(kitBase::robotModel::RobotModelInterface &model) { if (robotModels().count() == 1) { kitBase::robotModel::RobotModelInterface * const ourModel = robotModels()[0];; for (const ActionInfo &action : customActions()) { if (action.isAction()) { action.action()->setVisible(ourModel == &model); } else { action.menu()->setVisible(ourModel == &model); } } } } void RobotsGeneratorPluginBase::onCurrentDiagramChanged(const TabInfo &info) { const bool enabled = info.type() == TabInfo::TabType::code || info.type() == TabInfo::TabType::editor; for (const ActionInfo &action : customActions()) { if (action.isAction()) { action.action()->setEnabled(enabled); } else { action.menu()->setEnabled(enabled); } } } QFileInfo RobotsGeneratorPluginBase::generationTarget(const QString &pathFromRoot) const { return QFileInfo(PlatformInfo::invariantSettingsPath("pathToGeneratorRoot") + "/" + defaultFilePath(pathFromRoot)); } QFileInfo RobotsGeneratorPluginBase::srcPath() { const Id &activeDiagram = mMainWindowInterface->activeDiagram(); int exampleNumber = 0; QString projectName; do { projectName = NameNormalizer::normalizeStrongly(defaultProjectName(), false) + (exampleNumber > 0 ? QString::number(exampleNumber) : ""); ++exampleNumber; } while (!canGenerateTo(projectName)); QFileInfo fileInfo = generationTarget(projectName); const QList<QFileInfo> pathsList = mCodePath.values(activeDiagram); if (!pathsList.isEmpty()) { for (const QFileInfo &path : pathsList) { if (mTextManager->isDefaultPath(path.absoluteFilePath()) && !mTextManager->isModifiedEver(path.absoluteFilePath()) && !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName())) { fileInfo = path; break; } } } return fileInfo; } QFileInfo RobotsGeneratorPluginBase::generateCodeForProcessing() { QFileInfo fileInfo; const Id &activeDiagram = mMainWindowInterface->activeDiagram(); if (!activeDiagram.isNull()) { if (generateCode(false)) { for (const QFileInfo &path : mCodePath.values(activeDiagram)) { if (mTextManager->isDefaultPath(path.absoluteFilePath()) && (!mTextManager->isModifiedEver(path.absoluteFilePath())) && !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName())) { fileInfo = path; break; } } } else { return QFileInfo(); } } else if (auto code = dynamic_cast<text::QScintillaTextEdit *>(mMainWindowInterface->currentTab())) { fileInfo = QFileInfo(mTextManager->path(code)); mTextManager->saveText(false); } return fileInfo; } void RobotsGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator) { mProjectManager = &configurator.qRealConfigurator().projectManager(); mSystemEvents = &configurator.qRealConfigurator().systemEvents(); mTextManager = &configurator.qRealConfigurator().textManager(); mMainWindowInterface = &configurator.qRealConfigurator().mainWindowInterpretersInterface(); mRepo = dynamic_cast<const qrRepo::RepoApi *>(&configurator.qRealConfigurator().logicalModelApi().logicalRepoApi()); mProjectManager = &configurator.qRealConfigurator().projectManager(); mRobotModelManager = &configurator.robotModelManager(); mTextLanguage = &configurator.textLanguage(); mParserErrorReporter.reset(new ParserErrorReporter(*mTextLanguage, *mMainWindowInterface->errorReporter() , configurator.qRealConfigurator().logicalModelApi().editorManagerInterface())); connect(mSystemEvents, SIGNAL(codePathChanged(qReal::Id, QFileInfo, QFileInfo)) , this, SLOT(regenerateCode(qReal::Id, QFileInfo, QFileInfo))); connect(mSystemEvents, SIGNAL(newCodeAppeared(qReal::Id, QFileInfo)), this, SLOT(addNewCode(qReal::Id, QFileInfo))); connect(mSystemEvents, SIGNAL(diagramClosed(qReal::Id)), this, SLOT(removeDiagram(qReal::Id))); connect(mSystemEvents, SIGNAL(codeTabClosed(QFileInfo)), this, SLOT(removeCode(QFileInfo))); connect(mRobotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged , this, &RobotsGeneratorPluginBase::onCurrentRobotModelChanged); connect(mSystemEvents, &SystemEvents::activeTabChanged, this, &RobotsGeneratorPluginBase::onCurrentDiagramChanged); } QString RobotsGeneratorPluginBase::friendlyKitName() const { // Kit friendly name is already defined in interpreter kit plugins. return QString(); } bool RobotsGeneratorPluginBase::generateCode(bool openTab) { mProjectManager->save(); /// @todo: clearErrors() and clear() are absolutely different methods without documentation - wtf? mMainWindowInterface->errorReporter()->clearErrors(); mMainWindowInterface->errorReporter()->clear(); MasterGeneratorBase * const generator = masterGenerator(); const QFileInfo path = srcPath(); generator->initialize(); generator->setProjectDir(path); const QString generatedSrcPath = generator->generate(language().indent()); if (mMainWindowInterface->errorReporter()->wereErrors()) { delete generator; return false; } const Id activeDiagram = mMainWindowInterface->activeDiagram(); const QString generatedCode = utils::InFile::readAll(generatedSrcPath); if (!generatedCode.isEmpty()) { mTextManager->showInTextEditor(path, generatorName(), language()); } if (!openTab) { mMainWindowInterface->activateItemOrDiagram(activeDiagram); } delete generator; return true; } void RobotsGeneratorPluginBase::regenerateCode(const qReal::Id &diagram , const QFileInfo &oldFileInfo , const QFileInfo &newFileInfo) { if (!oldFileInfo.completeSuffix().compare(language().extension)) { mCodePath.remove(diagram, oldFileInfo); mCodePath.insert(diagram, newFileInfo); regenerateExtraFiles(newFileInfo); } } void RobotsGeneratorPluginBase::addNewCode(const Id &diagram, const QFileInfo &fileInfo) { mCodePath.insert(diagram, fileInfo); } void RobotsGeneratorPluginBase::removeDiagram(const qReal::Id &diagram) { mCodePath.remove(diagram); } void RobotsGeneratorPluginBase::removeCode(const QFileInfo &fileInfo) { const Id &diagram = mCodePath.key(fileInfo); mCodePath.remove(diagram, fileInfo); }
/* Copyright 2007-2015 QReal Research Group * * 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 "generatorBase/robotsGeneratorPluginBase.h" #include <QtCore/QDateTime> #include <qrkernel/platformInfo.h> #include <qrutils/inFile.h> #include <qrutils/nameNormalizer.h> #include <qrutils/parserErrorReporter.h> #include <qrgui/textEditor/qscintillaTextEdit.h> using namespace generatorBase; using namespace qReal; using namespace utils; /// If file info creation and modification timestamps differ less than on this value it is considered /// that file was created and filled at the same time. const int maxTimestampsDifference = 3000; RobotsGeneratorPluginBase::RobotsGeneratorPluginBase() { } RobotsGeneratorPluginBase::~RobotsGeneratorPluginBase() { } QString RobotsGeneratorPluginBase::defaultFilePath(const QString &projectName) const { return projectName; } QString RobotsGeneratorPluginBase::generatorName() const { return QString(); } QString RobotsGeneratorPluginBase::defaultProjectName() const { const QString filePath = mProjectManager->saveFilePath(); return filePath.isEmpty() ? "example" : QFileInfo(filePath).completeBaseName(); } bool RobotsGeneratorPluginBase::canGenerateTo(const QString &project) { const QFileInfo fileInfo = generationTarget(project); const int difference = fileInfo.lastModified().toMSecsSinceEpoch() - fileInfo.created().toMSecsSinceEpoch(); return !fileInfo.exists() || difference < maxTimestampsDifference; } void RobotsGeneratorPluginBase::onCurrentRobotModelChanged(kitBase::robotModel::RobotModelInterface &model) { if (robotModels().count() == 1) { kitBase::robotModel::RobotModelInterface * const ourModel = robotModels()[0]; for (const ActionInfo &action : customActions()) { if (action.isAction()) { action.action()->setVisible(ourModel == &model); } else { action.menu()->setVisible(ourModel == &model); } } } } void RobotsGeneratorPluginBase::onCurrentDiagramChanged(const TabInfo &info) { const bool enabled = info.type() == TabInfo::TabType::code || info.type() == TabInfo::TabType::editor; for (const ActionInfo &action : customActions()) { if (action.isAction()) { action.action()->setEnabled(enabled); } else { action.menu()->setEnabled(enabled); } } } QFileInfo RobotsGeneratorPluginBase::generationTarget(const QString &pathFromRoot) const { return QFileInfo(PlatformInfo::invariantSettingsPath("pathToGeneratorRoot") + "/" + defaultFilePath(pathFromRoot)); } QFileInfo RobotsGeneratorPluginBase::srcPath() { const Id &activeDiagram = mMainWindowInterface->activeDiagram(); int exampleNumber = 0; QString projectName; do { projectName = NameNormalizer::normalizeStrongly(defaultProjectName(), false) + (exampleNumber > 0 ? QString::number(exampleNumber) : ""); ++exampleNumber; } while (!canGenerateTo(projectName)); QFileInfo fileInfo = generationTarget(projectName); const QList<QFileInfo> pathsList = mCodePath.values(activeDiagram); if (!pathsList.isEmpty()) { for (const QFileInfo &path : pathsList) { if (mTextManager->isDefaultPath(path.absoluteFilePath()) && !mTextManager->isModifiedEver(path.absoluteFilePath()) && !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName())) { fileInfo = path; break; } } } return fileInfo; } QFileInfo RobotsGeneratorPluginBase::generateCodeForProcessing() { QFileInfo fileInfo; const Id &activeDiagram = mMainWindowInterface->activeDiagram(); if (!activeDiagram.isNull()) { if (generateCode(false)) { for (const QFileInfo &path : mCodePath.values(activeDiagram)) { if (mTextManager->isDefaultPath(path.absoluteFilePath()) && (!mTextManager->isModifiedEver(path.absoluteFilePath())) && !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName())) { fileInfo = path; break; } } } else { return QFileInfo(); } } else if (auto code = dynamic_cast<text::QScintillaTextEdit *>(mMainWindowInterface->currentTab())) { fileInfo = QFileInfo(mTextManager->path(code)); mTextManager->saveText(false); } return fileInfo; } void RobotsGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator) { mProjectManager = &configurator.qRealConfigurator().projectManager(); mSystemEvents = &configurator.qRealConfigurator().systemEvents(); mTextManager = &configurator.qRealConfigurator().textManager(); mMainWindowInterface = &configurator.qRealConfigurator().mainWindowInterpretersInterface(); mRepo = dynamic_cast<const qrRepo::RepoApi *>(&configurator.qRealConfigurator().logicalModelApi().logicalRepoApi()); mProjectManager = &configurator.qRealConfigurator().projectManager(); mRobotModelManager = &configurator.robotModelManager(); mTextLanguage = &configurator.textLanguage(); mParserErrorReporter.reset(new ParserErrorReporter(*mTextLanguage, *mMainWindowInterface->errorReporter() , configurator.qRealConfigurator().logicalModelApi().editorManagerInterface())); connect(mSystemEvents, SIGNAL(codePathChanged(qReal::Id, QFileInfo, QFileInfo)) , this, SLOT(regenerateCode(qReal::Id, QFileInfo, QFileInfo))); connect(mSystemEvents, SIGNAL(newCodeAppeared(qReal::Id, QFileInfo)), this, SLOT(addNewCode(qReal::Id, QFileInfo))); connect(mSystemEvents, SIGNAL(diagramClosed(qReal::Id)), this, SLOT(removeDiagram(qReal::Id))); connect(mSystemEvents, SIGNAL(codeTabClosed(QFileInfo)), this, SLOT(removeCode(QFileInfo))); connect(mRobotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged , this, &RobotsGeneratorPluginBase::onCurrentRobotModelChanged); connect(mSystemEvents, &SystemEvents::activeTabChanged, this, &RobotsGeneratorPluginBase::onCurrentDiagramChanged); } QString RobotsGeneratorPluginBase::friendlyKitName() const { // Kit friendly name is already defined in interpreter kit plugins. return QString(); } bool RobotsGeneratorPluginBase::generateCode(bool openTab) { mProjectManager->save(); /// @todo: clearErrors() and clear() are absolutely different methods without documentation - wtf? mMainWindowInterface->errorReporter()->clearErrors(); mMainWindowInterface->errorReporter()->clear(); MasterGeneratorBase * const generator = masterGenerator(); const QFileInfo path = srcPath(); generator->initialize(); generator->setProjectDir(path); const QString generatedSrcPath = generator->generate(language().indent()); if (mMainWindowInterface->errorReporter()->wereErrors()) { delete generator; return false; } const Id activeDiagram = mMainWindowInterface->activeDiagram(); const QString generatedCode = utils::InFile::readAll(generatedSrcPath); if (!generatedCode.isEmpty()) { mTextManager->showInTextEditor(path, generatorName(), language()); } if (!openTab) { mMainWindowInterface->activateItemOrDiagram(activeDiagram); } delete generator; return true; } void RobotsGeneratorPluginBase::regenerateCode(const qReal::Id &diagram , const QFileInfo &oldFileInfo , const QFileInfo &newFileInfo) { if (!oldFileInfo.completeSuffix().compare(language().extension)) { mCodePath.remove(diagram, oldFileInfo); mCodePath.insert(diagram, newFileInfo); regenerateExtraFiles(newFileInfo); } } void RobotsGeneratorPluginBase::addNewCode(const Id &diagram, const QFileInfo &fileInfo) { mCodePath.insert(diagram, fileInfo); } void RobotsGeneratorPluginBase::removeDiagram(const qReal::Id &diagram) { mCodePath.remove(diagram); } void RobotsGeneratorPluginBase::removeCode(const QFileInfo &fileInfo) { const Id &diagram = mCodePath.key(fileInfo); mCodePath.remove(diagram, fileInfo); }
Fix redundant semicolon
Fix redundant semicolon
C++
apache-2.0
iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal
c43f60d000802a6c795c03eb7985dab9090c2662
code/ylikuutio/ontology/generic_lisp_function_overload.cpp
code/ylikuutio/ontology/generic_lisp_function_overload.cpp
// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "generic_lisp_function_overload.hpp" #include "code/ylikuutio/data/any_value.hpp" // Include standard headers #include <cstddef> // std::size_t #include <memory> // std::make_shared, std::shared_ptr namespace yli::ontology { class Entity; class Scene; GenericLispFunctionOverload::~GenericLispFunctionOverload() { // destructor. } yli::ontology::Entity* GenericLispFunctionOverload::get_parent() const { return this->child_of_lisp_function.get_parent(); } yli::ontology::Scene* GenericLispFunctionOverload::get_scene() const { yli::ontology::Entity* const parent = this->get_parent(); if (parent != nullptr) { return parent->get_scene(); } return nullptr; } std::size_t GenericLispFunctionOverload::get_number_of_children() const { return 0; // `GenericLispFunctionOverload` has no children. } std::size_t GenericLispFunctionOverload::get_number_of_descendants() const { return 0; // `GenericLispFunctionOverload` has no children. } }
// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "generic_lisp_function_overload.hpp" // Include standard headers #include <cstddef> // std::size_t #include <memory> // std::make_shared, std::shared_ptr namespace yli::ontology { class Entity; class Scene; GenericLispFunctionOverload::~GenericLispFunctionOverload() { // destructor. } yli::ontology::Entity* GenericLispFunctionOverload::get_parent() const { return this->child_of_lisp_function.get_parent(); } yli::ontology::Scene* GenericLispFunctionOverload::get_scene() const { yli::ontology::Entity* const parent = this->get_parent(); if (parent != nullptr) { return parent->get_scene(); } return nullptr; } std::size_t GenericLispFunctionOverload::get_number_of_children() const { return 0; // `GenericLispFunctionOverload` has no children. } std::size_t GenericLispFunctionOverload::get_number_of_descendants() const { return 0; // `GenericLispFunctionOverload` has no children. } }
Remove unnecessary `#include` line.
Remove unnecessary `#include` line.
C++
agpl-3.0
nrz/ylikuutio,nrz/ylikuutio,nrz/ylikuutio,nrz/ylikuutio
fd5fbfdfecfa5a1274eae0caed678c20d3ccfd08
WebCore/svg/SVGFEDiffuseLightingElement.cpp
WebCore/svg/SVGFEDiffuseLightingElement.cpp
/* Copyright (C) 2005 Oliver Hunt <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; 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 "config.h" #if ENABLE(SVG) && ENABLE(SVG_FILTERS) #include "SVGFEDiffuseLightingElement.h" #include "Attr.h" #include "RenderObject.h" #include "SVGColor.h" #include "SVGFELightElement.h" #include "SVGNames.h" #include "SVGParserUtilities.h" #include "SVGRenderStyle.h" #include "SVGFEDiffuseLighting.h" #include "SVGResourceFilter.h" namespace WebCore { char SVGKernelUnitLengthXIdentifier[] = "SVGKernelUnitLengthX"; char SVGKernelUnitLengthYIdentifier[] = "SVGKernelUnitLengthY"; SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(const QualifiedName& tagName, Document* doc) : SVGFilterPrimitiveStandardAttributes(tagName, doc) , m_in1(this, SVGNames::inAttr) , m_diffuseConstant(this, SVGNames::diffuseConstantAttr, 1.0f) , m_surfaceScale(this, SVGNames::surfaceScaleAttr, 1.0f) , m_kernelUnitLengthX(this, SVGNames::kernelUnitLengthAttr) , m_kernelUnitLengthY(this, SVGNames::kernelUnitLengthAttr) , m_filterEffect(0) { } SVGFEDiffuseLightingElement::~SVGFEDiffuseLightingElement() { } void SVGFEDiffuseLightingElement::parseMappedAttribute(MappedAttribute *attr) { const String& value = attr->value(); if (attr->name() == SVGNames::inAttr) setIn1BaseValue(value); else if (attr->name() == SVGNames::surfaceScaleAttr) setSurfaceScaleBaseValue(value.toFloat()); else if (attr->name() == SVGNames::diffuseConstantAttr) setDiffuseConstantBaseValue(value.toInt()); else if (attr->name() == SVGNames::kernelUnitLengthAttr) { float x, y; if (parseNumberOptionalNumber(value, x, y)) { setKernelUnitLengthXBaseValue(x); setKernelUnitLengthYBaseValue(y); } } else SVGFilterPrimitiveStandardAttributes::parseMappedAttribute(attr); } SVGFilterEffect* SVGFEDiffuseLightingElement::filterEffect(SVGResourceFilter* filter) const { ASSERT_NOT_REACHED(); return 0; } bool SVGFEDiffuseLightingElement::build(FilterBuilder* builder) { FilterEffect* input1 = builder->getEffectById(in1()); if(!input1) return false; RenderStyle* parentStyle = this->styleForRenderer(parent()->renderer()); RenderStyle* filterStyle = this->resolveStyle(parentStyle); Color color = filterStyle->svgStyle()->lightingColor(); parentStyle->deref(document()->renderArena()); filterStyle->deref(document()->renderArena()); RefPtr<FilterEffect> addedEffect = FEDiffuseLighting::create(input1, color, surfaceScale(), diffuseConstant(), kernelUnitLengthX(), kernelUnitLengthY(), findLights()); builder->add(result(), addedEffect.release()); return true; } LightSource* SVGFEDiffuseLightingElement::findLights() const { LightSource* light = 0; for (Node* n = firstChild(); n; n = n->nextSibling()) { if (n->hasTagName(SVGNames::feDistantLightTag) || n->hasTagName(SVGNames::fePointLightTag) || n->hasTagName(SVGNames::feSpotLightTag)) { SVGFELightElement* lightNode = static_cast<SVGFELightElement*>(n); light = lightNode->lightSource(); break; } } return light; } } #endif // ENABLE(SVG)
/* Copyright (C) 2005 Oliver Hunt <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; 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 "config.h" #if ENABLE(SVG) && ENABLE(SVG_FILTERS) #include "SVGFEDiffuseLightingElement.h" #include "Attr.h" #include "RenderObject.h" #include "SVGColor.h" #include "SVGFELightElement.h" #include "SVGNames.h" #include "SVGParserUtilities.h" #include "SVGRenderStyle.h" #include "SVGFEDiffuseLighting.h" #include "SVGResourceFilter.h" namespace WebCore { char SVGKernelUnitLengthXIdentifier[] = "SVGKernelUnitLengthX"; char SVGKernelUnitLengthYIdentifier[] = "SVGKernelUnitLengthY"; SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(const QualifiedName& tagName, Document* doc) : SVGFilterPrimitiveStandardAttributes(tagName, doc) , m_in1(this, SVGNames::inAttr) , m_diffuseConstant(this, SVGNames::diffuseConstantAttr, 1.0f) , m_surfaceScale(this, SVGNames::surfaceScaleAttr, 1.0f) , m_kernelUnitLengthX(this, SVGNames::kernelUnitLengthAttr) , m_kernelUnitLengthY(this, SVGNames::kernelUnitLengthAttr) , m_filterEffect(0) { } SVGFEDiffuseLightingElement::~SVGFEDiffuseLightingElement() { } void SVGFEDiffuseLightingElement::parseMappedAttribute(MappedAttribute *attr) { const String& value = attr->value(); if (attr->name() == SVGNames::inAttr) setIn1BaseValue(value); else if (attr->name() == SVGNames::surfaceScaleAttr) setSurfaceScaleBaseValue(value.toFloat()); else if (attr->name() == SVGNames::diffuseConstantAttr) setDiffuseConstantBaseValue(value.toInt()); else if (attr->name() == SVGNames::kernelUnitLengthAttr) { float x, y; if (parseNumberOptionalNumber(value, x, y)) { setKernelUnitLengthXBaseValue(x); setKernelUnitLengthYBaseValue(y); } } else SVGFilterPrimitiveStandardAttributes::parseMappedAttribute(attr); } SVGFilterEffect* SVGFEDiffuseLightingElement::filterEffect(SVGResourceFilter* filter) const { ASSERT_NOT_REACHED(); return 0; } bool SVGFEDiffuseLightingElement::build(FilterBuilder* builder) { FilterEffect* input1 = builder->getEffectById(in1()); if(!input1) return false; RefPtr<RenderStyle> parentStyle = styleForRenderer(parent()->renderer()); RefPtr<RenderStyle> filterStyle = resolveStyle(parentStyle); Color color = filterStyle->svgStyle()->lightingColor(); parentStyle->deref(document()->renderArena()); filterStyle->deref(document()->renderArena()); RefPtr<FilterEffect> addedEffect = FEDiffuseLighting::create(input1, color, surfaceScale(), diffuseConstant(), kernelUnitLengthX(), kernelUnitLengthY(), findLights()); builder->add(result(), addedEffect.release()); return true; } LightSource* SVGFEDiffuseLightingElement::findLights() const { LightSource* light = 0; for (Node* n = firstChild(); n; n = n->nextSibling()) { if (n->hasTagName(SVGNames::feDistantLightTag) || n->hasTagName(SVGNames::fePointLightTag) || n->hasTagName(SVGNames::feSpotLightTag)) { SVGFELightElement* lightNode = static_cast<SVGFELightElement*>(n); light = lightNode->lightSource(); break; } } return light; } } #endif // ENABLE(SVG)
Fix Qt bustage. Why are filters on in Qt?
Fix Qt bustage. Why are filters on in Qt? git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@37638 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
13d00aef9c58686d9e1a5b03a5e50d02943afed7
src/core/ext/filters/http/message_decompress/message_decompress_filter.cc
src/core/ext/filters/http/message_decompress/message_decompress_filter.cc
// // // Copyright 2020 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 <grpc/support/port_platform.h> #include <assert.h> #include <string.h> #include <grpc/compression.h> #include <grpc/slice_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/http/message_decompress/message_decompress_filter.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/compression/algorithm_metadata.h" #include "src/core/lib/compression/compression_args.h" #include "src/core/lib/compression/compression_internal.h" #include "src/core/lib/compression/message_compress.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" namespace { class ChannelData {}; class CallData { public: explicit CallData(const grpc_call_element_args& args) : call_combiner_(args.call_combiner) { // Initialize state for recv_initial_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_initial_metadata_ready_, OnRecvInitialMetadataReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_message_ready callback grpc_slice_buffer_init(&recv_slices_); GRPC_CLOSURE_INIT(&on_recv_message_next_done_, OnRecvMessageNextDone, this, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&on_recv_message_ready_, OnRecvMessageReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_trailing_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_trailing_metadata_ready_, OnRecvTrailingMetadataReady, this, grpc_schedule_on_exec_ctx); } ~CallData() { grpc_slice_buffer_destroy_internal(&recv_slices_); } public: void DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch); private: static void OnRecvInitialMetadataReady(void* arg, grpc_error* error); // Methods for processing a receive message event void MaybeResumeOnRecvMessageReady(); static void OnRecvMessageReady(void* arg, grpc_error* error); static void OnRecvMessageNextDone(void* arg, grpc_error* error); grpc_error* PullSliceFromRecvMessage(); void ContinueReadingRecvMessage(); void FinishRecvMessage(); void ContinueRecvMessageReadyCallback(grpc_error* error); // Methods for processing a recv_trailing_metadata event void MaybeResumeOnRecvTrailingMetadataReady(); static void OnRecvTrailingMetadataReady(void* arg, grpc_error* error); grpc_core::CallCombiner* call_combiner_; // Overall error for the call grpc_error* error_ = GRPC_ERROR_NONE; // Fields for handling recv_initial_metadata_ready callback grpc_closure on_recv_initial_metadata_ready_; grpc_closure* original_recv_initial_metadata_ready_ = nullptr; grpc_metadata_batch* recv_initial_metadata_ = nullptr; // Fields for handling recv_message_ready callback bool seen_recv_message_ready_ = false; grpc_message_compression_algorithm algorithm_ = GRPC_MESSAGE_COMPRESS_NONE; grpc_closure on_recv_message_ready_; grpc_closure* original_recv_message_ready_ = nullptr; grpc_closure on_recv_message_next_done_; grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message_ = nullptr; // recv_slices_ holds the slices read from the original recv_message stream. // It is initialized during construction and reset when a new stream is // created using it. grpc_slice_buffer recv_slices_; std::aligned_storage<sizeof(grpc_core::SliceBufferByteStream), alignof(grpc_core::SliceBufferByteStream)>::type recv_replacement_stream_; // Fields for handling recv_trailing_metadata_ready callback bool seen_recv_trailing_metadata_ready_ = false; grpc_closure on_recv_trailing_metadata_ready_; grpc_closure* original_recv_trailing_metadata_ready_ = nullptr; grpc_error* on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; }; grpc_message_compression_algorithm DecodeMessageCompressionAlgorithm( grpc_mdelem md) { grpc_message_compression_algorithm algorithm = grpc_message_compression_algorithm_from_slice(GRPC_MDVALUE(md)); if (algorithm == GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) { char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid incoming message compression algorithm: '%s'. " "Interpreting incoming data as uncompressed.", md_c_str); gpr_free(md_c_str); return GRPC_MESSAGE_COMPRESS_NONE; } return algorithm; } void CallData::OnRecvInitialMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { grpc_linked_mdelem* grpc_encoding = calld->recv_initial_metadata_->idx.named.grpc_encoding; if (grpc_encoding != nullptr) { calld->algorithm_ = DecodeMessageCompressionAlgorithm(grpc_encoding->md); } } calld->MaybeResumeOnRecvMessageReady(); calld->MaybeResumeOnRecvTrailingMetadataReady(); grpc_closure* closure = calld->original_recv_initial_metadata_ready_; calld->original_recv_initial_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error)); } void CallData::MaybeResumeOnRecvMessageReady() { if (seen_recv_message_ready_) { seen_recv_message_ready_ = false; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_message_ready_, GRPC_ERROR_NONE, "continue recv_message_ready callback"); } } void CallData::OnRecvMessageReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { if (calld->original_recv_initial_metadata_ready_ != nullptr) { calld->seen_recv_message_ready_ = true; GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "Deferring OnRecvMessageReady until after " "OnRecvInitialMetadataReady"); return; } if (calld->algorithm_ != GRPC_MESSAGE_COMPRESS_NONE) { // recv_message can be NULL if trailing metadata is received instead of // message, or it's possible that the message was not compressed. if (*calld->recv_message_ == nullptr || (*calld->recv_message_)->length() == 0 || ((*calld->recv_message_)->flags() & GRPC_WRITE_INTERNAL_COMPRESS) == 0) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_NONE); } grpc_slice_buffer_destroy_internal(&calld->recv_slices_); grpc_slice_buffer_init(&calld->recv_slices_); return calld->ContinueReadingRecvMessage(); } } calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } void CallData::ContinueReadingRecvMessage() { while ((*recv_message_) ->Next((*recv_message_)->length() - recv_slices_.length, &on_recv_message_next_done_)) { grpc_error* error = PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return ContinueRecvMessageReadyCallback(error); } // We have read the entire message. if (recv_slices_.length == (*recv_message_)->length()) { return FinishRecvMessage(); } } } grpc_error* CallData::PullSliceFromRecvMessage() { grpc_slice incoming_slice; grpc_error* error = (*recv_message_)->Pull(&incoming_slice); if (error == GRPC_ERROR_NONE) { grpc_slice_buffer_add(&recv_slices_, incoming_slice); } return error; } void CallData::OnRecvMessageNextDone(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } error = calld->PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(error); } if (calld->recv_slices_.length == (*calld->recv_message_)->length()) { calld->FinishRecvMessage(); } else { calld->ContinueReadingRecvMessage(); } } void CallData::FinishRecvMessage() { grpc_slice_buffer decompressed_slices; grpc_slice_buffer_init(&decompressed_slices); if (grpc_msg_decompress(algorithm_, &recv_slices_, &decompressed_slices) == 0) { char* msg; gpr_asprintf( &msg, "Unexpected error decompressing data for algorithm with enum value %d", algorithm_); GPR_DEBUG_ASSERT(error_ == GRPC_ERROR_NONE); error_ = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); grpc_slice_buffer_destroy_internal(&decompressed_slices); } else { uint32_t recv_flags = ((*recv_message_)->flags() & (~GRPC_WRITE_INTERNAL_COMPRESS)) | GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED; // Swap out the original receive byte stream with our new one and send the // batch down. // Initializing recv_replacement_stream_ with decompressed_slices removes // all the slices from decompressed_slices leaving it empty. new (&recv_replacement_stream_) grpc_core::SliceBufferByteStream(&decompressed_slices, recv_flags); recv_message_->reset(reinterpret_cast<grpc_core::SliceBufferByteStream*>( &recv_replacement_stream_)); recv_message_ = nullptr; } ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error_)); } void CallData::ContinueRecvMessageReadyCallback(grpc_error* error) { MaybeResumeOnRecvTrailingMetadataReady(); // The surface will clean up the receiving stream if there is an error. grpc_closure* closure = original_recv_message_ready_; original_recv_message_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::MaybeResumeOnRecvTrailingMetadataReady() { if (seen_recv_trailing_metadata_ready_) { seen_recv_trailing_metadata_ready_ = false; grpc_error* error = on_recv_trailing_metadata_ready_error_; on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_trailing_metadata_ready_, error, "Continuing OnRecvTrailingMetadataReady"); } } void CallData::OnRecvTrailingMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (calld->original_recv_initial_metadata_ready_ != nullptr || calld->original_recv_message_ready_ != nullptr) { calld->seen_recv_trailing_metadata_ready_ = true; calld->on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_REF(error); GRPC_CALL_COMBINER_STOP( calld->call_combiner_, "Deferring OnRecvTrailingMetadataReady until after " "OnRecvInitialMetadataReady and OnRecvMessageReady"); return; } error = grpc_error_add_child(GRPC_ERROR_REF(error), calld->error_); calld->error_ = GRPC_ERROR_NONE; grpc_closure* closure = calld->original_recv_trailing_metadata_ready_; calld->original_recv_trailing_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { // Handle recv_initial_metadata. if (batch->recv_initial_metadata) { recv_initial_metadata_ = batch->payload->recv_initial_metadata.recv_initial_metadata; original_recv_initial_metadata_ready_ = batch->payload->recv_initial_metadata.recv_initial_metadata_ready; batch->payload->recv_initial_metadata.recv_initial_metadata_ready = &on_recv_initial_metadata_ready_; } // Handle recv_message if (batch->recv_message) { recv_message_ = batch->payload->recv_message.recv_message; original_recv_message_ready_ = batch->payload->recv_message.recv_message_ready; batch->payload->recv_message.recv_message_ready = &on_recv_message_ready_; } // Handle recv_trailing_metadata if (batch->recv_trailing_metadata) { original_recv_trailing_metadata_ready_ = batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = &on_recv_trailing_metadata_ready_; } // Pass control down the stack. grpc_call_next_op(elem, batch); } void DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { GPR_TIMER_SCOPE("decompress_start_transport_stream_op_batch", 0); CallData* calld = static_cast<CallData*>(elem->call_data); calld->DecompressStartTransportStreamOpBatch(elem, batch); } static grpc_error* DecompressInitCallElem(grpc_call_element* elem, const grpc_call_element_args* args) { new (elem->call_data) CallData(*args); return GRPC_ERROR_NONE; } static void DecompressDestroyCallElem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { CallData* calld = static_cast<CallData*>(elem->call_data); calld->~CallData(); } static grpc_error* DecompressInitChannelElem( grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { return GRPC_ERROR_NONE; } void DecompressDestroyChannelElem(grpc_channel_element* /*elem*/) {} } // namespace const grpc_channel_filter grpc_message_decompress_filter = { DecompressStartTransportStreamOpBatch, grpc_channel_next_op, sizeof(CallData), DecompressInitCallElem, grpc_call_stack_ignore_set_pollset_or_pollset_set, DecompressDestroyCallElem, 0, // sizeof(ChannelData) DecompressInitChannelElem, DecompressDestroyChannelElem, grpc_channel_next_get_info, "message_decompress"};
// // // Copyright 2020 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 <grpc/support/port_platform.h> #include <assert.h> #include <string.h> #include <grpc/compression.h> #include <grpc/slice_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/http/message_decompress/message_decompress_filter.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/compression/algorithm_metadata.h" #include "src/core/lib/compression/compression_args.h" #include "src/core/lib/compression/compression_internal.h" #include "src/core/lib/compression/message_compress.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" namespace { class ChannelData {}; class CallData { public: explicit CallData(const grpc_call_element_args& args) : call_combiner_(args.call_combiner) { // Initialize state for recv_initial_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_initial_metadata_ready_, OnRecvInitialMetadataReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_message_ready callback grpc_slice_buffer_init(&recv_slices_); GRPC_CLOSURE_INIT(&on_recv_message_next_done_, OnRecvMessageNextDone, this, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&on_recv_message_ready_, OnRecvMessageReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_trailing_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_trailing_metadata_ready_, OnRecvTrailingMetadataReady, this, grpc_schedule_on_exec_ctx); } ~CallData() { grpc_slice_buffer_destroy_internal(&recv_slices_); } public: void DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch); private: static void OnRecvInitialMetadataReady(void* arg, grpc_error* error); // Methods for processing a receive message event void MaybeResumeOnRecvMessageReady(); static void OnRecvMessageReady(void* arg, grpc_error* error); static void OnRecvMessageNextDone(void* arg, grpc_error* error); grpc_error* PullSliceFromRecvMessage(); void ContinueReadingRecvMessage(); void FinishRecvMessage(); void ContinueRecvMessageReadyCallback(grpc_error* error); // Methods for processing a recv_trailing_metadata event void MaybeResumeOnRecvTrailingMetadataReady(); static void OnRecvTrailingMetadataReady(void* arg, grpc_error* error); grpc_core::CallCombiner* call_combiner_; // Overall error for the call grpc_error* error_ = GRPC_ERROR_NONE; // Fields for handling recv_initial_metadata_ready callback grpc_closure on_recv_initial_metadata_ready_; grpc_closure* original_recv_initial_metadata_ready_ = nullptr; grpc_metadata_batch* recv_initial_metadata_ = nullptr; // Fields for handling recv_message_ready callback bool seen_recv_message_ready_ = false; grpc_message_compression_algorithm algorithm_ = GRPC_MESSAGE_COMPRESS_NONE; grpc_closure on_recv_message_ready_; grpc_closure* original_recv_message_ready_ = nullptr; grpc_closure on_recv_message_next_done_; grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message_ = nullptr; // recv_slices_ holds the slices read from the original recv_message stream. // It is initialized during construction and reset when a new stream is // created using it. grpc_slice_buffer recv_slices_; std::aligned_storage<sizeof(grpc_core::SliceBufferByteStream), alignof(grpc_core::SliceBufferByteStream)>::type recv_replacement_stream_; // Fields for handling recv_trailing_metadata_ready callback bool seen_recv_trailing_metadata_ready_ = false; grpc_closure on_recv_trailing_metadata_ready_; grpc_closure* original_recv_trailing_metadata_ready_ = nullptr; grpc_error* on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; }; grpc_message_compression_algorithm DecodeMessageCompressionAlgorithm( grpc_mdelem md) { grpc_message_compression_algorithm algorithm = grpc_message_compression_algorithm_from_slice(GRPC_MDVALUE(md)); if (algorithm == GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) { char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid incoming message compression algorithm: '%s'. " "Interpreting incoming data as uncompressed.", md_c_str); gpr_free(md_c_str); return GRPC_MESSAGE_COMPRESS_NONE; } return algorithm; } void CallData::OnRecvInitialMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { grpc_linked_mdelem* grpc_encoding = calld->recv_initial_metadata_->idx.named.grpc_encoding; if (grpc_encoding != nullptr) { calld->algorithm_ = DecodeMessageCompressionAlgorithm(grpc_encoding->md); } } calld->MaybeResumeOnRecvMessageReady(); calld->MaybeResumeOnRecvTrailingMetadataReady(); grpc_closure* closure = calld->original_recv_initial_metadata_ready_; calld->original_recv_initial_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error)); } void CallData::MaybeResumeOnRecvMessageReady() { if (seen_recv_message_ready_) { seen_recv_message_ready_ = false; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_message_ready_, GRPC_ERROR_NONE, "continue recv_message_ready callback"); } } void CallData::OnRecvMessageReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { if (calld->original_recv_initial_metadata_ready_ != nullptr) { calld->seen_recv_message_ready_ = true; GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "Deferring OnRecvMessageReady until after " "OnRecvInitialMetadataReady"); return; } if (calld->algorithm_ != GRPC_MESSAGE_COMPRESS_NONE) { // recv_message can be NULL if trailing metadata is received instead of // message, or it's possible that the message was not compressed. if (*calld->recv_message_ == nullptr || (*calld->recv_message_)->length() == 0 || ((*calld->recv_message_)->flags() & GRPC_WRITE_INTERNAL_COMPRESS) == 0) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_NONE); } grpc_slice_buffer_destroy_internal(&calld->recv_slices_); grpc_slice_buffer_init(&calld->recv_slices_); return calld->ContinueReadingRecvMessage(); } } calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } void CallData::ContinueReadingRecvMessage() { while ((*recv_message_) ->Next((*recv_message_)->length() - recv_slices_.length, &on_recv_message_next_done_)) { grpc_error* error = PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return ContinueRecvMessageReadyCallback(error); } // We have read the entire message. if (recv_slices_.length == (*recv_message_)->length()) { return FinishRecvMessage(); } } } grpc_error* CallData::PullSliceFromRecvMessage() { grpc_slice incoming_slice; grpc_error* error = (*recv_message_)->Pull(&incoming_slice); if (error == GRPC_ERROR_NONE) { grpc_slice_buffer_add(&recv_slices_, incoming_slice); } return error; } void CallData::OnRecvMessageNextDone(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } error = calld->PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(error); } if (calld->recv_slices_.length == (*calld->recv_message_)->length()) { calld->FinishRecvMessage(); } else { calld->ContinueReadingRecvMessage(); } } void CallData::FinishRecvMessage() { grpc_slice_buffer decompressed_slices; grpc_slice_buffer_init(&decompressed_slices); if (grpc_msg_decompress(algorithm_, &recv_slices_, &decompressed_slices) == 0) { char* msg; gpr_asprintf( &msg, "Unexpected error decompressing data for algorithm with enum value %d", algorithm_); GPR_DEBUG_ASSERT(error_ == GRPC_ERROR_NONE); error_ = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); grpc_slice_buffer_destroy_internal(&decompressed_slices); } else { uint32_t recv_flags = ((*recv_message_)->flags() & (~GRPC_WRITE_INTERNAL_COMPRESS)) | GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED; // Swap out the original receive byte stream with our new one and send the // batch down. // Initializing recv_replacement_stream_ with decompressed_slices removes // all the slices from decompressed_slices leaving it empty. new (&recv_replacement_stream_) grpc_core::SliceBufferByteStream(&decompressed_slices, recv_flags); recv_message_->reset(reinterpret_cast<grpc_core::SliceBufferByteStream*>( &recv_replacement_stream_)); recv_message_ = nullptr; } ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error_)); } void CallData::ContinueRecvMessageReadyCallback(grpc_error* error) { MaybeResumeOnRecvTrailingMetadataReady(); // The surface will clean up the receiving stream if there is an error. grpc_closure* closure = original_recv_message_ready_; original_recv_message_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::MaybeResumeOnRecvTrailingMetadataReady() { if (seen_recv_trailing_metadata_ready_) { seen_recv_trailing_metadata_ready_ = false; grpc_error* error = on_recv_trailing_metadata_ready_error_; on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_trailing_metadata_ready_, error, "Continuing OnRecvTrailingMetadataReady"); } } void CallData::OnRecvTrailingMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (calld->original_recv_initial_metadata_ready_ != nullptr || calld->original_recv_message_ready_ != nullptr) { calld->seen_recv_trailing_metadata_ready_ = true; calld->on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_REF(error); GRPC_CALL_COMBINER_STOP( calld->call_combiner_, "Deferring OnRecvTrailingMetadataReady until after " "OnRecvInitialMetadataReady and OnRecvMessageReady"); return; } error = grpc_error_add_child(GRPC_ERROR_REF(error), calld->error_); calld->error_ = GRPC_ERROR_NONE; grpc_closure* closure = calld->original_recv_trailing_metadata_ready_; calld->original_recv_trailing_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { // Handle recv_initial_metadata. if (batch->recv_initial_metadata) { recv_initial_metadata_ = batch->payload->recv_initial_metadata.recv_initial_metadata; original_recv_initial_metadata_ready_ = batch->payload->recv_initial_metadata.recv_initial_metadata_ready; batch->payload->recv_initial_metadata.recv_initial_metadata_ready = &on_recv_initial_metadata_ready_; } // Handle recv_message if (batch->recv_message) { recv_message_ = batch->payload->recv_message.recv_message; original_recv_message_ready_ = batch->payload->recv_message.recv_message_ready; batch->payload->recv_message.recv_message_ready = &on_recv_message_ready_; } // Handle recv_trailing_metadata if (batch->recv_trailing_metadata) { original_recv_trailing_metadata_ready_ = batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = &on_recv_trailing_metadata_ready_; } // Pass control down the stack. grpc_call_next_op(elem, batch); } void DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { GPR_TIMER_SCOPE("decompress_start_transport_stream_op_batch", 0); CallData* calld = static_cast<CallData*>(elem->call_data); calld->DecompressStartTransportStreamOpBatch(elem, batch); } static grpc_error* DecompressInitCallElem(grpc_call_element* elem, const grpc_call_element_args* args) { new (elem->call_data) CallData(*args); return GRPC_ERROR_NONE; } static void DecompressDestroyCallElem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { CallData* calld = static_cast<CallData*>(elem->call_data); calld->~CallData(); } static grpc_error* DecompressInitChannelElem( grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { return GRPC_ERROR_NONE; } void DecompressDestroyChannelElem(grpc_channel_element* /*elem*/) {} } // namespace const grpc_channel_filter grpc_message_decompress_filter = { DecompressStartTransportStreamOpBatch, grpc_channel_next_op, sizeof(CallData), DecompressInitCallElem, grpc_call_stack_ignore_set_pollset_or_pollset_set, DecompressDestroyCallElem, 0, // sizeof(ChannelData) DecompressInitChannelElem, DecompressDestroyChannelElem, grpc_channel_next_get_info, "message_decompress"};
Remove unnecessary header
Remove unnecessary header
C++
apache-2.0
donnadionne/grpc,jboeuf/grpc,stanley-cheung/grpc,vjpai/grpc,firebase/grpc,vjpai/grpc,jtattermusch/grpc,firebase/grpc,ejona86/grpc,ctiller/grpc,firebase/grpc,jtattermusch/grpc,ctiller/grpc,vjpai/grpc,ctiller/grpc,ctiller/grpc,grpc/grpc,nicolasnoble/grpc,nicolasnoble/grpc,donnadionne/grpc,stanley-cheung/grpc,vjpai/grpc,nicolasnoble/grpc,donnadionne/grpc,grpc/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,vjpai/grpc,jtattermusch/grpc,grpc/grpc,firebase/grpc,ejona86/grpc,nicolasnoble/grpc,firebase/grpc,stanley-cheung/grpc,jtattermusch/grpc,nicolasnoble/grpc,jtattermusch/grpc,nicolasnoble/grpc,ctiller/grpc,vjpai/grpc,firebase/grpc,ejona86/grpc,jboeuf/grpc,donnadionne/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,ejona86/grpc,jboeuf/grpc,jboeuf/grpc,jtattermusch/grpc,firebase/grpc,stanley-cheung/grpc,donnadionne/grpc,vjpai/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jtattermusch/grpc,firebase/grpc,jboeuf/grpc,jboeuf/grpc,ejona86/grpc,ejona86/grpc,ctiller/grpc,jtattermusch/grpc,jboeuf/grpc,grpc/grpc,donnadionne/grpc,jtattermusch/grpc,nicolasnoble/grpc,jboeuf/grpc,ejona86/grpc,jtattermusch/grpc,firebase/grpc,jtattermusch/grpc,stanley-cheung/grpc,ctiller/grpc,grpc/grpc,grpc/grpc,nicolasnoble/grpc,grpc/grpc,ejona86/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,grpc/grpc,ctiller/grpc,firebase/grpc,ejona86/grpc,jtattermusch/grpc,jboeuf/grpc,donnadionne/grpc,jboeuf/grpc,firebase/grpc,nicolasnoble/grpc,jboeuf/grpc,ejona86/grpc,vjpai/grpc,vjpai/grpc,ctiller/grpc,ejona86/grpc,grpc/grpc,ctiller/grpc,nicolasnoble/grpc,donnadionne/grpc,donnadionne/grpc,nicolasnoble/grpc,vjpai/grpc,grpc/grpc,firebase/grpc,grpc/grpc,jboeuf/grpc,donnadionne/grpc,vjpai/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,donnadionne/grpc
2140b3654331281c7863c0566397d3d4aa7fa2b2
sandbox.cc
sandbox.cc
#include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <string> #include <vector> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "sandbox.h" using namespace std; static const uint32_t STACK_SIZE = 64 * 1024; bool loadRawData(machine& mach, const char *filename) { int fd; if (( fd = open ( filename, O_RDONLY , 0)) < 0) return false; struct stat st; if (fstat(fd, &st) < 0) { close(fd); return false; } void *p; p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (p == (void *)-1) { close(fd); return false; } static unsigned int dataCount = 0; char tmpstr[32]; sprintf(tmpstr, "data%u", dataCount++); addressRange *rdr = new addressRange(tmpstr, st.st_size); rdr->buf.assign((char *) p, (size_t) st.st_size); rdr->updateRoot(); munmap(p, st.st_size); close(fd); return mach.mapInsert(rdr); } static void usage(const char *progname) { fprintf(stderr, "Usage: %s [options]\n" "\n" "options:\n" "-e <moxie executable>\tLoad executable into address space\n" "-d <file>\t\tLoad data into address space\n" "-o <file>\t\tOutput data to <file>. \"-\" for stdout\n" "-t\t\tEnabling simulator tracing\n" , progname); } static void printMemMap(machine &mach) { for (unsigned int i = 0; i < mach.memmap.size(); i++) { addressRange *ar = mach.memmap[i]; fprintf(stderr, "%s %08x-%08x %s\n", ar->readOnly ? "ro" : "rw", ar->start, ar->end, ar->name.c_str()); } } static void addStackMem(machine& mach) { // alloc r/w memory range addressRange *rdr = new addressRange("stack", STACK_SIZE); rdr->buf.resize(STACK_SIZE); rdr->updateRoot(); rdr->readOnly = false; // add memory range to global memory map mach.mapInsert(rdr); // set SR #7 to now-initialized stack vaddr mach.cpu.asregs.sregs[7] = rdr->end; } static void addMapDescriptor(machine& mach) { // fill list from existing memory map vector<struct mach_memmap_ent> desc; mach.fillDescriptors(desc); // add entry for the mapdesc range to be added to memory map struct mach_memmap_ent mme_self; memset(&mme_self, 0, sizeof(mme_self)); desc.push_back(mme_self); // add blank entry for list terminator struct mach_memmap_ent mme_end; memset(&mme_end, 0, sizeof(mme_end)); desc.push_back(mme_end); // calc total region size size_t sz = sizeof(mme_end) * desc.size(); // manually fill in mapdesc range descriptor mme_self.length = sz; strcpy(mme_self.tags, "ro,mapdesc,"); // build entry for global memory map addressRange *ar = new addressRange("mapdesc", sz); // allocate space for descriptor array ar->buf.resize(sz); ar->updateRoot(); // copy 'desc' array into allocated memory space unsigned int i = 0; for (vector<struct mach_memmap_ent>::iterator it = desc.begin(); it != desc.end(); it++, i++) { struct mach_memmap_ent& mme = (*it); memcpy(&ar->buf[i * sizeof(mme)], &mme, sizeof(mme)); } // add memory range to global memory map mach.mapInsert(ar); // set SR #6 to now-initialized mapdesc start vaddr mach.cpu.asregs.sregs[6] = ar->start; } static void gatherOutput(machine& mach, const string& outFilename) { if (!outFilename.size()) return; uint32_t vaddr = mach.cpu.asregs.sregs[6]; uint32_t length = mach.cpu.asregs.sregs[7]; if (!vaddr || !length) return; char *p = (char *) mach.physaddr(vaddr, length); if (!p) { fprintf(stderr, "Sim exception %d (%s) upon output\n", SIGBUS, strsignal(SIGBUS)); exit(EXIT_FAILURE); } int fd; if (outFilename == "-") { fd = STDOUT_FILENO; } else { fd = open(outFilename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) { perror(outFilename.c_str()); exit(EXIT_FAILURE); } } while (length > 0) { ssize_t bytes = write(fd, p, length); if (bytes < 0) { perror(outFilename.c_str()); exit(EXIT_FAILURE); } length -= bytes; p += bytes; } close(fd); } int main (int argc, char *argv[]) { machine mach; string outFilename; int opt; while ((opt = getopt(argc, argv, "e:d:o:t")) != -1) { switch(opt) { case 'e': if (!loadElfProgram(mach, optarg)) { fprintf(stderr, "ELF load failed for %s\n", optarg); exit(EXIT_FAILURE); } break; case 'd': if (!loadRawData(mach, optarg)) { fprintf(stderr, "Data load failed for %s\n", optarg); exit(EXIT_FAILURE); } break; case 'o': outFilename = optarg; break; case 't': mach.tracing = true; break; default: usage(argv[0]); exit(EXIT_FAILURE); } } addStackMem(mach); addMapDescriptor(mach); printMemMap(mach); mach.cpu.asregs.regs[PC_REGNO] = mach.startAddr; sim_resume(mach); if (mach.cpu.asregs.exception) { fprintf(stderr, "Sim exception %d (%s)\n", mach.cpu.asregs.exception, strsignal(mach.cpu.asregs.exception)); if (mach.cpu.asregs.exception == SIGQUIT) gatherOutput(mach, outFilename); } return 0; }
#include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <string> #include <vector> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "sandbox.h" using namespace std; static const uint32_t STACK_SIZE = 64 * 1024; bool loadRawData(machine& mach, const char *filename) { int fd; if (( fd = open ( filename, O_RDONLY , 0)) < 0) return false; struct stat st; if (fstat(fd, &st) < 0) { close(fd); return false; } void *p; p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (p == (void *)-1) { close(fd); return false; } static unsigned int dataCount = 0; char tmpstr[32]; sprintf(tmpstr, "data%u", dataCount++); addressRange *rdr = new addressRange(tmpstr, st.st_size); rdr->buf.assign((char *) p, (size_t) st.st_size); rdr->updateRoot(); munmap(p, st.st_size); close(fd); return mach.mapInsert(rdr); } static void usage(const char *progname) { fprintf(stderr, "Usage: %s [options]\n" "\n" "options:\n" "-e <moxie executable>\tLoad executable into address space\n" "-d <file>\t\tLoad data into address space\n" "-o <file>\t\tOutput data to <file>. \"-\" for stdout\n" "-t\t\t\tEnabling simulator tracing\n" , progname); } static void printMemMap(machine &mach) { for (unsigned int i = 0; i < mach.memmap.size(); i++) { addressRange *ar = mach.memmap[i]; fprintf(stderr, "%s %08x-%08x %s\n", ar->readOnly ? "ro" : "rw", ar->start, ar->end, ar->name.c_str()); } } static void addStackMem(machine& mach) { // alloc r/w memory range addressRange *rdr = new addressRange("stack", STACK_SIZE); rdr->buf.resize(STACK_SIZE); rdr->updateRoot(); rdr->readOnly = false; // add memory range to global memory map mach.mapInsert(rdr); // set SR #7 to now-initialized stack vaddr mach.cpu.asregs.sregs[7] = rdr->end; } static void addMapDescriptor(machine& mach) { // fill list from existing memory map vector<struct mach_memmap_ent> desc; mach.fillDescriptors(desc); // add entry for the mapdesc range to be added to memory map struct mach_memmap_ent mme_self; memset(&mme_self, 0, sizeof(mme_self)); desc.push_back(mme_self); // add blank entry for list terminator struct mach_memmap_ent mme_end; memset(&mme_end, 0, sizeof(mme_end)); desc.push_back(mme_end); // calc total region size size_t sz = sizeof(mme_end) * desc.size(); // manually fill in mapdesc range descriptor mme_self.length = sz; strcpy(mme_self.tags, "ro,mapdesc,"); // build entry for global memory map addressRange *ar = new addressRange("mapdesc", sz); // allocate space for descriptor array ar->buf.resize(sz); ar->updateRoot(); // copy 'desc' array into allocated memory space unsigned int i = 0; for (vector<struct mach_memmap_ent>::iterator it = desc.begin(); it != desc.end(); it++, i++) { struct mach_memmap_ent& mme = (*it); memcpy(&ar->buf[i * sizeof(mme)], &mme, sizeof(mme)); } // add memory range to global memory map mach.mapInsert(ar); // set SR #6 to now-initialized mapdesc start vaddr mach.cpu.asregs.sregs[6] = ar->start; } static void gatherOutput(machine& mach, const string& outFilename) { if (!outFilename.size()) return; uint32_t vaddr = mach.cpu.asregs.sregs[6]; uint32_t length = mach.cpu.asregs.sregs[7]; if (!vaddr || !length) return; char *p = (char *) mach.physaddr(vaddr, length); if (!p) { fprintf(stderr, "Sim exception %d (%s) upon output\n", SIGBUS, strsignal(SIGBUS)); exit(EXIT_FAILURE); } int fd; if (outFilename == "-") { fd = STDOUT_FILENO; } else { fd = open(outFilename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) { perror(outFilename.c_str()); exit(EXIT_FAILURE); } } while (length > 0) { ssize_t bytes = write(fd, p, length); if (bytes < 0) { perror(outFilename.c_str()); exit(EXIT_FAILURE); } length -= bytes; p += bytes; } close(fd); } int main (int argc, char *argv[]) { machine mach; bool progLoaded = false; string outFilename; int opt; while ((opt = getopt(argc, argv, "e:d:o:t")) != -1) { switch(opt) { case 'e': if (!loadElfProgram(mach, optarg)) { fprintf(stderr, "ELF load failed for %s\n", optarg); exit(EXIT_FAILURE); } progLoaded = true; break; case 'd': if (!loadRawData(mach, optarg)) { fprintf(stderr, "Data load failed for %s\n", optarg); exit(EXIT_FAILURE); } break; case 'o': outFilename = optarg; break; case 't': mach.tracing = true; break; default: usage(argv[0]); exit(EXIT_FAILURE); } } if (!progLoaded) { fprintf(stderr, "No Moxie program loaded.\n"); usage(argv[0]); exit(EXIT_FAILURE); } addStackMem(mach); addMapDescriptor(mach); printMemMap(mach); mach.cpu.asregs.regs[PC_REGNO] = mach.startAddr; sim_resume(mach); if (mach.cpu.asregs.exception) { fprintf(stderr, "Sim exception %d (%s)\n", mach.cpu.asregs.exception, strsignal(mach.cpu.asregs.exception)); if (mach.cpu.asregs.exception == SIGQUIT) gatherOutput(mach, outFilename); } return 0; }
throw error if no program provided to execute
sandbox: throw error if no program provided to execute
C++
mit
atgreen/moxiebox,atgreen/moxiebox,jgarzik/moxiebox,atgreen/moxiebox,jgarzik/moxiebox,jgarzik/moxiebox
cc4051b5023c624a6ae28c1100ce4a1b79796bdb
chrome/browser/privacy_blacklist/blacklist_manager_unittest.cc
chrome/browser/privacy_blacklist/blacklist_manager_unittest.cc
// Copyright (c) 2009 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/privacy_blacklist/blacklist_manager.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/thread.h" #include "chrome/browser/privacy_blacklist/blacklist.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_service.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class MyTestingProfile : public TestingProfile { public: MyTestingProfile() { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); path_ = temp_dir_.path(); } private: ScopedTempDir temp_dir_; DISALLOW_COPY_AND_ASSIGN(MyTestingProfile); }; class TestBlacklistPathProvider : public BlacklistPathProvider { public: explicit TestBlacklistPathProvider(Profile* profile) : profile_(profile) { } virtual std::vector<FilePath> GetPersistentBlacklistPaths() { return persistent_paths_; } virtual std::vector<FilePath> GetTransientBlacklistPaths() { return transient_paths_; } void AddPersistentPath(const FilePath& path) { persistent_paths_.push_back(path); SendUpdateNotification(); } void AddTransientPath(const FilePath& path) { transient_paths_.push_back(path); SendUpdateNotification(); } void clear() { persistent_paths_.clear(); transient_paths_.clear(); SendUpdateNotification(); } private: void SendUpdateNotification() { #if defined(OS_WIN) FilePath path(FILE_PATH_LITERAL("c:\\foo")); #elif defined(OS_POSIX) FilePath path(FILE_PATH_LITERAL("/foo")); #endif Extension extension(path); NotificationService::current()->Notify( NotificationType::EXTENSION_LOADED, Source<Profile>(profile_), Details<Extension>(&extension)); } Profile* profile_; std::vector<FilePath> persistent_paths_; std::vector<FilePath> transient_paths_; DISALLOW_COPY_AND_ASSIGN(TestBlacklistPathProvider); }; class BlacklistManagerTest : public testing::Test, public NotificationObserver { public: BlacklistManagerTest() : path_provider_(&profile_), mock_ui_thread_(ChromeThread::UI, MessageLoop::current()), mock_file_thread_(ChromeThread::FILE) { } virtual void SetUp() { ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_)); test_data_dir_ = test_data_dir_.AppendASCII("blacklist_samples"); ASSERT_TRUE(mock_file_thread_.Start()); } virtual void TearDown() { loop_.RunAllPending(); } // NotificationObserver virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoop::current()->Quit(); } protected: void WaitForBlacklistError() { NotificationRegistrar registrar; registrar.Add(this, NotificationType::BLACKLIST_MANAGER_ERROR, Source<Profile>(&profile_)); MessageLoop::current()->Run(); } void WaitForBlacklistUpdate() { NotificationRegistrar registrar; registrar.Add(this, NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED, Source<Profile>(&profile_)); MessageLoop::current()->Run(); } FilePath test_data_dir_; MyTestingProfile profile_; TestBlacklistPathProvider path_provider_; private: MessageLoop loop_; ChromeThread mock_ui_thread_; ChromeThread mock_file_thread_; }; // Returns true if |blacklist| contains a match for |url|. bool BlacklistHasMatch(const Blacklist* blacklist, const char* url) { Blacklist::Match* match = blacklist->findMatch(GURL(url)); if (!match) return false; delete match; return true; } TEST_F(BlacklistManagerTest, Basic) { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(blacklist); // Repeated invocations of GetCompiledBlacklist should return the same object. EXPECT_EQ(blacklist, manager->GetCompiledBlacklist()); } TEST_F(BlacklistManagerTest, BlacklistPathProvider) { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); const Blacklist* blacklist1 = manager->GetCompiledBlacklist(); EXPECT_FALSE(BlacklistHasMatch(blacklist1, "http://host/annoying_ads/ad.jpg")); path_provider_.AddPersistentPath( test_data_dir_.AppendASCII("annoying_ads.pbl")); WaitForBlacklistUpdate(); const Blacklist* blacklist2 = manager->GetCompiledBlacklist(); // Added a real blacklist, the manager should recompile. EXPECT_NE(blacklist1, blacklist2); EXPECT_TRUE(BlacklistHasMatch(blacklist2, "http://host/annoying_ads/ad.jpg")); EXPECT_FALSE(BlacklistHasMatch(blacklist2, "http://host/other_ads/ad.jpg")); path_provider_.AddTransientPath(test_data_dir_.AppendASCII("other_ads.pbl")); WaitForBlacklistUpdate(); const Blacklist* blacklist3 = manager->GetCompiledBlacklist(); // In theory blacklist2 and blacklist3 could be the same object, so we're // not checking for inequality. EXPECT_TRUE(BlacklistHasMatch(blacklist3, "http://host/annoying_ads/ad.jpg")); EXPECT_TRUE(BlacklistHasMatch(blacklist3, "http://host/other_ads/ad.jpg")); // Now make sure that transient blacklists don't survive after re-creating // the BlacklistManager. manager = NULL; path_provider_.clear(); path_provider_.AddPersistentPath( test_data_dir_.AppendASCII("annoying_ads.pbl")); manager = new BlacklistManager(&profile_, &path_provider_); WaitForBlacklistUpdate(); const Blacklist* blacklist4 = manager->GetCompiledBlacklist(); EXPECT_TRUE(BlacklistHasMatch(blacklist4, "http://host/annoying_ads/ad.jpg")); EXPECT_FALSE(BlacklistHasMatch(blacklist4, "http://host/other_ads/ad.jpg")); } TEST_F(BlacklistManagerTest, BlacklistPathReadError) { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); FilePath bogus_path(test_data_dir_.AppendASCII("does_not_exist_randomness")); ASSERT_FALSE(file_util::PathExists(bogus_path)); path_provider_.AddPersistentPath(bogus_path); WaitForBlacklistError(); const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(blacklist); } TEST_F(BlacklistManagerTest, CompiledBlacklistReadError) { FilePath compiled_blacklist_path; { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); path_provider_.AddPersistentPath( test_data_dir_.AppendASCII("annoying_ads.pbl")); WaitForBlacklistUpdate(); const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(BlacklistHasMatch(blacklist, "http://host/annoying_ads/ad.jpg")); compiled_blacklist_path = manager->compiled_blacklist_path(); } ASSERT_TRUE(file_util::PathExists(compiled_blacklist_path)); ASSERT_TRUE(file_util::Delete(compiled_blacklist_path, false)); { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); // The manager should recompile the blacklist. const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(BlacklistHasMatch(blacklist, "http://host/annoying_ads/ad.jpg")); } } } // namespace
// Copyright (c) 2009 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/privacy_blacklist/blacklist_manager.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/thread.h" #include "chrome/browser/privacy_blacklist/blacklist.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_service.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class MyTestingProfile : public TestingProfile { public: MyTestingProfile() { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); path_ = temp_dir_.path(); } private: ScopedTempDir temp_dir_; DISALLOW_COPY_AND_ASSIGN(MyTestingProfile); }; class TestBlacklistPathProvider : public BlacklistPathProvider { public: explicit TestBlacklistPathProvider(Profile* profile) : profile_(profile) { } virtual std::vector<FilePath> GetPersistentBlacklistPaths() { return persistent_paths_; } virtual std::vector<FilePath> GetTransientBlacklistPaths() { return transient_paths_; } void AddPersistentPath(const FilePath& path) { persistent_paths_.push_back(path); SendUpdateNotification(); } void AddTransientPath(const FilePath& path) { transient_paths_.push_back(path); SendUpdateNotification(); } void clear() { persistent_paths_.clear(); transient_paths_.clear(); SendUpdateNotification(); } private: void SendUpdateNotification() { #if defined(OS_WIN) FilePath path(FILE_PATH_LITERAL("c:\\foo")); #elif defined(OS_POSIX) FilePath path(FILE_PATH_LITERAL("/foo")); #endif Extension extension(path); NotificationService::current()->Notify( NotificationType::EXTENSION_LOADED, Source<Profile>(profile_), Details<Extension>(&extension)); } Profile* profile_; std::vector<FilePath> persistent_paths_; std::vector<FilePath> transient_paths_; DISALLOW_COPY_AND_ASSIGN(TestBlacklistPathProvider); }; class BlacklistManagerTest : public testing::Test, public NotificationObserver { public: BlacklistManagerTest() : path_provider_(&profile_), mock_ui_thread_(ChromeThread::UI, MessageLoop::current()), mock_file_thread_(ChromeThread::FILE) { } virtual void SetUp() { ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_)); test_data_dir_ = test_data_dir_.AppendASCII("blacklist_samples"); ASSERT_TRUE(mock_file_thread_.Start()); } virtual void TearDown() { mock_file_thread_.Stop(); loop_.RunAllPending(); } // NotificationObserver virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoop::current()->Quit(); } protected: void WaitForBlacklistError() { NotificationRegistrar registrar; registrar.Add(this, NotificationType::BLACKLIST_MANAGER_ERROR, Source<Profile>(&profile_)); MessageLoop::current()->Run(); } void WaitForBlacklistUpdate() { NotificationRegistrar registrar; registrar.Add(this, NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED, Source<Profile>(&profile_)); MessageLoop::current()->Run(); } FilePath test_data_dir_; MyTestingProfile profile_; TestBlacklistPathProvider path_provider_; private: MessageLoop loop_; ChromeThread mock_ui_thread_; ChromeThread mock_file_thread_; }; // Returns true if |blacklist| contains a match for |url|. bool BlacklistHasMatch(const Blacklist* blacklist, const char* url) { Blacklist::Match* match = blacklist->findMatch(GURL(url)); if (!match) return false; delete match; return true; } TEST_F(BlacklistManagerTest, Basic) { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(blacklist); // Repeated invocations of GetCompiledBlacklist should return the same object. EXPECT_EQ(blacklist, manager->GetCompiledBlacklist()); } TEST_F(BlacklistManagerTest, BlacklistPathProvider) { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); const Blacklist* blacklist1 = manager->GetCompiledBlacklist(); EXPECT_FALSE(BlacklistHasMatch(blacklist1, "http://host/annoying_ads/ad.jpg")); path_provider_.AddPersistentPath( test_data_dir_.AppendASCII("annoying_ads.pbl")); WaitForBlacklistUpdate(); const Blacklist* blacklist2 = manager->GetCompiledBlacklist(); // Added a real blacklist, the manager should recompile. EXPECT_NE(blacklist1, blacklist2); EXPECT_TRUE(BlacklistHasMatch(blacklist2, "http://host/annoying_ads/ad.jpg")); EXPECT_FALSE(BlacklistHasMatch(blacklist2, "http://host/other_ads/ad.jpg")); path_provider_.AddTransientPath(test_data_dir_.AppendASCII("other_ads.pbl")); WaitForBlacklistUpdate(); const Blacklist* blacklist3 = manager->GetCompiledBlacklist(); // In theory blacklist2 and blacklist3 could be the same object, so we're // not checking for inequality. EXPECT_TRUE(BlacklistHasMatch(blacklist3, "http://host/annoying_ads/ad.jpg")); EXPECT_TRUE(BlacklistHasMatch(blacklist3, "http://host/other_ads/ad.jpg")); // Now make sure that transient blacklists don't survive after re-creating // the BlacklistManager. manager = NULL; path_provider_.clear(); path_provider_.AddPersistentPath( test_data_dir_.AppendASCII("annoying_ads.pbl")); manager = new BlacklistManager(&profile_, &path_provider_); WaitForBlacklistUpdate(); const Blacklist* blacklist4 = manager->GetCompiledBlacklist(); EXPECT_TRUE(BlacklistHasMatch(blacklist4, "http://host/annoying_ads/ad.jpg")); EXPECT_FALSE(BlacklistHasMatch(blacklist4, "http://host/other_ads/ad.jpg")); } TEST_F(BlacklistManagerTest, BlacklistPathReadError) { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); FilePath bogus_path(test_data_dir_.AppendASCII("does_not_exist_randomness")); ASSERT_FALSE(file_util::PathExists(bogus_path)); path_provider_.AddPersistentPath(bogus_path); WaitForBlacklistError(); const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(blacklist); } TEST_F(BlacklistManagerTest, CompiledBlacklistReadError) { FilePath compiled_blacklist_path; { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); path_provider_.AddPersistentPath( test_data_dir_.AppendASCII("annoying_ads.pbl")); WaitForBlacklistUpdate(); const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(BlacklistHasMatch(blacklist, "http://host/annoying_ads/ad.jpg")); compiled_blacklist_path = manager->compiled_blacklist_path(); } ASSERT_TRUE(file_util::PathExists(compiled_blacklist_path)); ASSERT_TRUE(file_util::Delete(compiled_blacklist_path, false)); { scoped_refptr<BlacklistManager> manager( new BlacklistManager(&profile_, &path_provider_)); WaitForBlacklistUpdate(); // The manager should recompile the blacklist. const Blacklist* blacklist = manager->GetCompiledBlacklist(); EXPECT_TRUE(BlacklistHasMatch(blacklist, "http://host/annoying_ads/ad.jpg")); } } } // namespace
Fix intermittent DCHECK failure in BlacklistManagerTest.
Fix intermittent DCHECK failure in BlacklistManagerTest. Ensure correct shutdown of threads. TEST=Covered by unit_tests. BUG=27726 Review URL: http://codereview.chromium.org/384149 git-svn-id: http://src.chromium.org/svn/trunk/src@32090 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: ee2c4a6add38eb09dadd8c31f8913b2ef5a35954
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
0a4cacb048ebf5ade3910777b74622ffd9a3c092
sdd/sdd.hh
sdd/sdd.hh
#ifndef _SDD_SDD_HH_ #define _SDD_SDD_HH_ #include "sdd/conf/default_configurations.hh" #include "sdd/dd/context.hh" #include "sdd/dd/count_combinations.hh" #include "sdd/dd/definition.hh" #include "sdd/dd/path_generator.hh" #include "sdd/hom/context.hh" #include "sdd/hom/definition.hh" #include "sdd/hom/rewrite.hh" #include "sdd/order/carrier.hh" #include "sdd/order/ordering.hh" #include "sdd/order/strategies/flatten.hh" #include "sdd/manager.hh" /// @brief The main namespace for the library. namespace sdd { /// @internal /// @brief Internal stuff related to the library configuration. namespace conf {} /// @internal /// @brief Internal stuff for decision diagrams. namespace dd {} /// @internal /// @brief Internal stuff for homomorphisms. namespace hom {} /// @internal /// @brief Internal stuff necessary for the memory management. namespace mem {} /// @internal /// @brief Contain miscellaneous utilities. namespace util {} /// @internal /// @brief Definition of values to be stored on arcs. namespace values {} } // namespace sdd /// @brief Essentially hash specialization. namespace std {} #endif // _SDD_SDD_HH_
#ifndef _SDD_SDD_HH_ #define _SDD_SDD_HH_ #include "sdd/conf/default_configurations.hh" #include "sdd/dd/context.hh" #include "sdd/dd/count_combinations.hh" #include "sdd/dd/definition.hh" #include "sdd/dd/path_generator.hh" #include "sdd/hom/context.hh" #include "sdd/hom/definition.hh" #include "sdd/hom/rewrite.hh" #include "sdd/order/carrier.hh" #include "sdd/order/ordering.hh" #include "sdd/order/strategies/flatten.hh" #include "sdd/order/strategies/variables_per_level.hh" #include "sdd/manager.hh" /// @brief The main namespace for the library. namespace sdd { /// @internal /// @brief Internal stuff related to the library configuration. namespace conf {} /// @internal /// @brief Internal stuff for decision diagrams. namespace dd {} /// @internal /// @brief Internal stuff for homomorphisms. namespace hom {} /// @internal /// @brief Internal stuff necessary for the memory management. namespace mem {} /// @internal /// @brief Contain miscellaneous utilities. namespace util {} /// @internal /// @brief Definition of values to be stored on arcs. namespace values {} } // namespace sdd /// @brief Essentially hash specialization. namespace std {} #endif // _SDD_SDD_HH_
Add new order strategy ‘’variables_per_level’.
Add new order strategy ‘’variables_per_level’.
C++
bsd-2-clause
ahamez/proto-dd,ahamez/proto-dd,ahamez/libsdd
b920a09de6a5cc0d73da08da28a2e64894876fec
src/chronotext/sound/AudioLoopImplCocoa.cpp
src/chronotext/sound/AudioLoopImplCocoa.cpp
#include "chronotext/sound/AudioLoopImplCocoa.h" #if TARGET_OS_IPHONE #define AUDIO_UNIT_COMPONENT_SUB_TYPE kAudioUnitSubType_RemoteIO #else #define AUDIO_UNIT_COMPONENT_SUB_TYPE kAudioUnitSubType_DefaultOutput #endif bool AudioLoopImplCocoa::init() { if (!initialized) { AudioComponentDescription defaultOutputDescription; defaultOutputDescription.componentType = kAudioUnitType_Output; defaultOutputDescription.componentSubType = AUDIO_UNIT_COMPONENT_SUB_TYPE; defaultOutputDescription.componentManufacturer = kAudioUnitManufacturer_Apple; defaultOutputDescription.componentFlags = 0; defaultOutputDescription.componentFlagsMask = 0; AudioComponent defaultOutput = AudioComponentFindNext(NULL, &defaultOutputDescription); if (!defaultOutput) { printf("Can't find default output\n"); return false; } OSStatus err = AudioComponentInstanceNew(defaultOutput, &audioUnit); if (err) { printf("AudioComponentInstanceNew ERROR: %d\n", (int)err); return false; } AURenderCallbackStruct input; input.inputProc = staticRenderCallback; input.inputProcRefCon = this; err = AudioUnitSetProperty(audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, sizeof(input)); if (err) { printf("AudioUnitSetProperty/kAudioUnitProperty_SetRenderCallback ERROR: %d\n", (int)err); return false; } AudioStreamBasicDescription streamFormat; streamFormat.mSampleRate = 44100; streamFormat.mFormatID = kAudioFormatLinearPCM; streamFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved; streamFormat.mBytesPerPacket = 4; streamFormat.mFramesPerPacket = 1; streamFormat.mBytesPerFrame = 4; streamFormat.mChannelsPerFrame = 1; streamFormat.mBitsPerChannel = 32; err = AudioUnitSetProperty(audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamFormat, sizeof(AudioStreamBasicDescription)); if (err) { printf("AudioUnitSetProperty/kAudioUnitProperty_StreamFormat ERROR: %d\n", (int)err); return false; } err = AudioUnitInitialize(audioUnit); if (err) { printf("AudioUnitInitialize ERROR: %d\n", (int)err); return false; } initialized = true; } return true; } void AudioLoopImplCocoa::shutdown() { if (initialized) { AudioOutputUnitStop(audioUnit); AudioUnitUninitialize(audioUnit); AudioComponentInstanceDispose(audioUnit); audioUnit = NULL; } } void AudioLoopImplCocoa::start() { if (initialized) { OSStatus err = AudioOutputUnitStart(audioUnit); if (err) printf("AudioOutputUnitStart ERROR: %d\n", (int)err); } } void AudioLoopImplCocoa::stop() { if (initialized) { OSStatus err = AudioOutputUnitStop(audioUnit); if (err) printf("AudioOutputUnitStop ERROR: %d\n", (int)err); } } void AudioLoopImplCocoa::setVolume(float volume) { if (initialized) { OSStatus err = AudioUnitSetParameter(audioUnit, kHALOutputParam_Volume, kAudioUnitScope_Output, 0, volume, 0); if (err) printf("AudioUnitSetParameter ERROR: %d\n", (int)err); } }
#include "chronotext/sound/AudioLoopImplCocoa.h" #if TARGET_OS_IPHONE #define AUDIO_UNIT_COMPONENT_SUB_TYPE kAudioUnitSubType_RemoteIO #else #define AUDIO_UNIT_COMPONENT_SUB_TYPE kAudioUnitSubType_DefaultOutput #endif bool AudioLoopImplCocoa::init() { if (!initialized) { AudioComponentDescription defaultOutputDescription; defaultOutputDescription.componentType = kAudioUnitType_Output; defaultOutputDescription.componentSubType = AUDIO_UNIT_COMPONENT_SUB_TYPE; defaultOutputDescription.componentManufacturer = kAudioUnitManufacturer_Apple; defaultOutputDescription.componentFlags = 0; defaultOutputDescription.componentFlagsMask = 0; AudioComponent defaultOutput = AudioComponentFindNext(NULL, &defaultOutputDescription); if (!defaultOutput) { printf("Can't find default output\n"); return false; } OSStatus err = AudioComponentInstanceNew(defaultOutput, &audioUnit); if (err) { printf("AudioComponentInstanceNew ERROR: %d\n", (int)err); return false; } AURenderCallbackStruct input; input.inputProc = staticRenderCallback; input.inputProcRefCon = this; err = AudioUnitSetProperty(audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, sizeof(input)); if (err) { printf("AudioUnitSetProperty/kAudioUnitProperty_SetRenderCallback ERROR: %d\n", (int)err); return false; } AudioStreamBasicDescription streamFormat; streamFormat.mSampleRate = 44100; streamFormat.mFormatID = kAudioFormatLinearPCM; streamFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved; streamFormat.mBytesPerPacket = 4; streamFormat.mFramesPerPacket = 1; streamFormat.mBytesPerFrame = 4; streamFormat.mChannelsPerFrame = 1; streamFormat.mBitsPerChannel = 32; err = AudioUnitSetProperty(audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamFormat, sizeof(AudioStreamBasicDescription)); if (err) { printf("AudioUnitSetProperty/kAudioUnitProperty_StreamFormat ERROR: %d\n", (int)err); return false; } err = AudioUnitInitialize(audioUnit); if (err) { printf("AudioUnitInitialize ERROR: %d\n", (int)err); return false; } initialized = true; } return true; } void AudioLoopImplCocoa::shutdown() { if (initialized) { AudioOutputUnitStop(audioUnit); AudioUnitUninitialize(audioUnit); AudioComponentInstanceDispose(audioUnit); audioUnit = NULL; } } void AudioLoopImplCocoa::start() { if (initialized) { OSStatus err = AudioOutputUnitStart(audioUnit); if (err) printf("AudioOutputUnitStart ERROR: %d\n", (int)err); } } void AudioLoopImplCocoa::stop() { if (initialized) { OSStatus err = AudioOutputUnitStop(audioUnit); if (err) printf("AudioOutputUnitStop ERROR: %d\n", (int)err); } } /* * FOR SETTING VOLUME ON iOS, AudioQueue SHOULD BE USED INSTEAD OF AudioUnit */ void AudioLoopImplCocoa::setVolume(float volume) { #if !TARGET_OS_IPHONE if (initialized) { OSStatus err = AudioUnitSetParameter(audioUnit, kHALOutputParam_Volume, kAudioUnitScope_Output, 0, volume, 0); if (err) printf("AudioUnitSetParameter ERROR: %d\n", (int)err); } #endif }
UPDATE REGARDING VOLUME-CONTROL ON iOS
AudioLoop: UPDATE REGARDING VOLUME-CONTROL ON iOS
C++
bsd-2-clause
neshume/new-chronotext-toolkit,neshume/new-chronotext-toolkit,arielm/new-chronotext-toolkit,arielm/new-chronotext-toolkit,michaelboccara/new-chronotext-toolkit,SlateScience/new-chronotext-toolkit,michaelboccara/new-chronotext-toolkit,arielm/new-chronotext-toolkit,SlateScience/new-chronotext-toolkit,neshume/new-chronotext-toolkit,michaelboccara/new-chronotext-toolkit,SlateScience/new-chronotext-toolkit
0f7209388674bb16cd0ef10f8d0f383c1e462c55
src/uoj348241.cpp
src/uoj348241.cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int cou=0; void dfs(int n,int p[],int a[],int cur){ if(cur==n){ REP(i,0,n-1){ cout<<a[i]; } cout<<endl; cou++; }else{ REP(i,0,n-1){ a[cur]=p[i]; dfs(n,p,a,cur+1); } } } void Init(){ return ; } void Solve(){ int p[]={1,2,3,4}; int a[800]; dfs(4,p,a,0); return ; } int main(){ freopen("uoj348241.in","r",stdin); int T; scanf("%d",&T); while(T--) Init(),Solve(); return 0; }
#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int cou=0; void dfs(int n,int p[],int a[],int cur){ if(cur==n){ REP(i,0,n-1){ cout<<a[i]; } cout<<endl; cou++; }else{ REP(i,0,n-1){ a[cur]=p[i]; dfs(n,p,a,cur+1); } } } void Init(){ return ; } void Solve(){ int p[]={1,2,3,4}; int a[800]; dfs(4,p,a,0); return ; } int main(){ freopen("uoj348241.in","r",stdin); int T; scanf("%d",&T); while(T--) Init(),Solve(); return 0; }
update uoj348241
update uoj348241
C++
mit
czfshine/my_oj,czfshine/my_oj,czfshine/my_oj,czfshine/my_oj
d3c52c1221a8373cfa8dec07a23df6fd500320e3
src/urlreader.cpp
src/urlreader.cpp
#include <fstream> #include <cstring> #include <urlreader.h> #include <utils.h> #include <logger.h> #include <sys/utsname.h> #include <config.h> namespace newsbeuter { urlreader::urlreader() : offline(false) { } urlreader::~urlreader() { } std::vector<std::string>& urlreader::get_urls() { return urls; } std::vector<std::string>& urlreader::get_tags(const std::string& url) { return tags[url]; } std::vector<std::string> urlreader::get_alltags() { std::vector<std::string> tmptags; for (auto t : alltags) { if (t.substr(0,1) != "~") tmptags.push_back(t); } return tmptags; } file_urlreader::file_urlreader(const std::string& file) : filename(file) { } file_urlreader::~file_urlreader() { } std::string file_urlreader::get_source() { return filename; } void file_urlreader::reload() { if (offline) return; urls.clear(); tags.clear(); alltags.clear(); std::fstream f; f.open(filename.c_str(),std::fstream::in); if (f.is_open()) { std::string line; do { getline(f,line); if (!f.eof() && line.length() > 0 && line[0] != '#') { std::vector<std::string> tokens = utils::tokenize_quoted(line); if (!tokens.empty()) { std::string url = tokens[0]; urls.push_back(url); tokens.erase(tokens.begin()); if (!tokens.empty()) { tags[url] = tokens; for (auto token : tokens) { alltags.insert(token); } } } } } while (!f.eof()); } } void file_urlreader::load_config(const std::string& file) { filename = file; reload(); } void file_urlreader::write_config() { std::fstream f; f.open(filename.c_str(),std::fstream::out); if (f.is_open()) { for (auto url : urls) { f << url; if (tags[url].size() > 0) { for (auto tag : tags[url]) { f << " \"" << tag << "\""; } } f << std::endl; } } } opml_urlreader::opml_urlreader(configcontainer * c) : cfg(c) { } opml_urlreader::~opml_urlreader() { } void opml_urlreader::write_config() { // do nothing. } void opml_urlreader::reload() { if (offline) return; urls.clear(); tags.clear(); alltags.clear(); std::string user_agent = utils::get_useragent(cfg); std::vector<std::string> urls = utils::tokenize_quoted(this->get_source(), " "); for (auto url : urls) { LOG(LOG_DEBUG, "opml_urlreader::reload: downloading `%s'", url.c_str()); std::string urlcontent = utils::retrieve_url(url, cfg, this->get_auth()); xmlDoc * doc = xmlParseMemory(urlcontent.c_str(), urlcontent.length()); if (doc == NULL) { LOG(LOG_ERROR, "opml_urlreader::reload: parsing XML file failed"); continue; } xmlNode * root = xmlDocGetRootElement(doc); if (root) { for (xmlNode * node = root->children; node != NULL; node = node->next) { if (strcmp((const char *)node->name, "body")==0) { LOG(LOG_DEBUG, "opml_urlreader::reload: found body"); rec_find_rss_outlines(node->children, ""); } } } xmlFreeDoc(doc); } } void opml_urlreader::handle_node(xmlNode * node, const std::string& tag) { if (node) { char * rssurl = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl"); if (rssurl && strlen(rssurl) > 0) { std::string theurl(rssurl); urls.push_back(theurl); if (tag.length() > 0) { std::vector<std::string> tmptags; tmptags.push_back(tag); tags[theurl] = tmptags; alltags.insert(tag); } } if (rssurl) xmlFree(rssurl); } } void opml_urlreader::rec_find_rss_outlines(xmlNode * node, std::string tag) { while (node) { char * type = (char *)xmlGetProp(node, (const xmlChar *)"type"); std::string newtag = tag; if (strcmp((const char *)node->name, "outline")==0) { if (type && strcmp(type,"rss")==0) { handle_node(node, tag); } else { char * text = (char *)xmlGetProp(node, (const xmlChar *)"title"); if (text) { if (newtag.length() > 0) { newtag.append("/"); } newtag.append(text); xmlFree(text); } } } rec_find_rss_outlines(node->children, newtag); node = node->next; } } std::string opml_urlreader::get_source() { return cfg->get_configvalue("opml-url"); } const char * opml_urlreader::get_auth() { return NULL; } }
#include <fstream> #include <cstring> #include <urlreader.h> #include <utils.h> #include <logger.h> #include <sys/utsname.h> #include <config.h> namespace newsbeuter { urlreader::urlreader() : offline(false) { } urlreader::~urlreader() { } std::vector<std::string>& urlreader::get_urls() { return urls; } std::vector<std::string>& urlreader::get_tags(const std::string& url) { return tags[url]; } std::vector<std::string> urlreader::get_alltags() { std::vector<std::string> tmptags; for (auto t : alltags) { if (t.substr(0,1) != "~") tmptags.push_back(t); } return tmptags; } file_urlreader::file_urlreader(const std::string& file) : filename(file) { } file_urlreader::~file_urlreader() { } std::string file_urlreader::get_source() { return filename; } void file_urlreader::reload() { if (offline) return; urls.clear(); tags.clear(); alltags.clear(); std::fstream f; f.open(filename.c_str(),std::fstream::in); if (f.is_open()) { std::string line; while (!f.eof()) { getline(f,line); if (line.length() > 0 && line[0] != '#') { std::vector<std::string> tokens = utils::tokenize_quoted(line); if (!tokens.empty()) { std::string url = tokens[0]; urls.push_back(url); tokens.erase(tokens.begin()); if (!tokens.empty()) { tags[url] = tokens; for (auto token : tokens) { alltags.insert(token); } } } } }; } } void file_urlreader::load_config(const std::string& file) { filename = file; reload(); } void file_urlreader::write_config() { std::fstream f; f.open(filename.c_str(),std::fstream::out); if (f.is_open()) { for (auto url : urls) { f << url; if (tags[url].size() > 0) { for (auto tag : tags[url]) { f << " \"" << tag << "\""; } } f << std::endl; } } } opml_urlreader::opml_urlreader(configcontainer * c) : cfg(c) { } opml_urlreader::~opml_urlreader() { } void opml_urlreader::write_config() { // do nothing. } void opml_urlreader::reload() { if (offline) return; urls.clear(); tags.clear(); alltags.clear(); std::string user_agent = utils::get_useragent(cfg); std::vector<std::string> urls = utils::tokenize_quoted(this->get_source(), " "); for (auto url : urls) { LOG(LOG_DEBUG, "opml_urlreader::reload: downloading `%s'", url.c_str()); std::string urlcontent = utils::retrieve_url(url, cfg, this->get_auth()); xmlDoc * doc = xmlParseMemory(urlcontent.c_str(), urlcontent.length()); if (doc == NULL) { LOG(LOG_ERROR, "opml_urlreader::reload: parsing XML file failed"); continue; } xmlNode * root = xmlDocGetRootElement(doc); if (root) { for (xmlNode * node = root->children; node != NULL; node = node->next) { if (strcmp((const char *)node->name, "body")==0) { LOG(LOG_DEBUG, "opml_urlreader::reload: found body"); rec_find_rss_outlines(node->children, ""); } } } xmlFreeDoc(doc); } } void opml_urlreader::handle_node(xmlNode * node, const std::string& tag) { if (node) { char * rssurl = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl"); if (rssurl && strlen(rssurl) > 0) { std::string theurl(rssurl); urls.push_back(theurl); if (tag.length() > 0) { std::vector<std::string> tmptags; tmptags.push_back(tag); tags[theurl] = tmptags; alltags.insert(tag); } } if (rssurl) xmlFree(rssurl); } } void opml_urlreader::rec_find_rss_outlines(xmlNode * node, std::string tag) { while (node) { char * type = (char *)xmlGetProp(node, (const xmlChar *)"type"); std::string newtag = tag; if (strcmp((const char *)node->name, "outline")==0) { if (type && strcmp(type,"rss")==0) { handle_node(node, tag); } else { char * text = (char *)xmlGetProp(node, (const xmlChar *)"title"); if (text) { if (newtag.length() > 0) { newtag.append("/"); } newtag.append(text); xmlFree(text); } } } rec_find_rss_outlines(node->children, newtag); node = node->next; } } std::string opml_urlreader::get_source() { return cfg->get_configvalue("opml-url"); } const char * opml_urlreader::get_auth() { return NULL; } }
Handle urls files lacking EOL mark at the end
Handle urls files lacking EOL mark at the end Kudos to @smaudet for pointing this out and providing the fix.
C++
mit
x4121/newsbeuter,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,x4121/newsbeuter,der-lyse/newsboat,newsboat/newsboat,x4121/newsbeuter,newsboat/newsboat,der-lyse/newsboat,x4121/newsbeuter
68fdde7d4ae0279bda786176299414e55087212a
tensorflow/core/lib/io/zlib_inputstream.cc
tensorflow/core/lib/io/zlib_inputstream.cc
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/lib/io/zlib_inputstream.h" #include <zlib.h> #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/strcat.h" namespace tensorflow { namespace io { struct ZStreamDef { ZStreamDef(size_t input_buffer_capacity, size_t output_buffer_capacity) : input(new Bytef[input_buffer_capacity]), output(new Bytef[output_buffer_capacity]), stream(new z_stream) {} // Buffer for storing contents read from compressed stream. // TODO(srbs): Consider using circular buffers. That would greatly simplify // the implementation. std::unique_ptr<Bytef[]> input; // Buffer for storing inflated contents of `input_stream_`. std::unique_ptr<Bytef[]> output; // Configuration passed to `inflate`. // // z_stream_def_->stream->next_in: // Next byte to de-compress. Points to some byte in // z_stream_def_->streamdef_.input buffer. // z_stream_def_->stream->avail_in: // Number of bytes available to be decompressed at this time. // z_stream_def_->stream->next_out: // Next byte to write de-compressed data to. Points to some byte in // z_stream_def_->streamdef_.output buffer. // z_stream_def_->stream->avail_out: // Number of free bytes available at write location. std::unique_ptr<z_stream> stream; }; ZlibInputStream::ZlibInputStream( InputStreamInterface* input_stream, size_t input_buffer_bytes, // size of z_stream.next_in buffer size_t output_buffer_bytes, // size of z_stream.next_out buffer const ZlibCompressionOptions& zlib_options, bool owns_input_stream) : owns_input_stream_(owns_input_stream), input_stream_(input_stream), input_buffer_capacity_(input_buffer_bytes), output_buffer_capacity_(output_buffer_bytes), zlib_options_(zlib_options), z_stream_def_( new ZStreamDef(input_buffer_capacity_, output_buffer_capacity_)), bytes_read_(0) { InitZlibBuffer(); } ZlibInputStream::ZlibInputStream(InputStreamInterface* input_stream, size_t input_buffer_bytes, size_t output_buffer_bytes, const ZlibCompressionOptions& zlib_options) : ZlibInputStream(input_stream, input_buffer_bytes, output_buffer_bytes, zlib_options, false) {} ZlibInputStream::~ZlibInputStream() { if (z_stream_def_->stream && !init_error_) { inflateEnd(z_stream_def_->stream.get()); } if (owns_input_stream_) { delete input_stream_; } } Status ZlibInputStream::Reset() { if (init_error_) { return errors::DataLoss("unable to reset stream, cannot decompress."); } TF_RETURN_IF_ERROR(input_stream_->Reset()); inflateEnd(z_stream_def_->stream.get()); InitZlibBuffer(); bytes_read_ = 0; return Status::OK(); } void ZlibInputStream::InitZlibBuffer() { memset(z_stream_def_->stream.get(), 0, sizeof(z_stream)); z_stream_def_->stream->zalloc = Z_NULL; z_stream_def_->stream->zfree = Z_NULL; z_stream_def_->stream->opaque = Z_NULL; z_stream_def_->stream->next_in = Z_NULL; z_stream_def_->stream->avail_in = 0; int status = inflateInit2(z_stream_def_->stream.get(), zlib_options_.window_bits); if (zlib_options_.soft_fail_on_error && status != Z_OK) { init_error_ = true; return; } CHECK_EQ(status, Z_OK) << "inflateInit failed with status " << status; z_stream_def_->stream->next_in = z_stream_def_->input.get(); z_stream_def_->stream->next_out = z_stream_def_->output.get(); next_unread_byte_ = reinterpret_cast<char*>(z_stream_def_->output.get()); z_stream_def_->stream->avail_in = 0; z_stream_def_->stream->avail_out = output_buffer_capacity_; } Status ZlibInputStream::ReadFromStream() { int bytes_to_read = input_buffer_capacity_; char* read_location = reinterpret_cast<char*>(z_stream_def_->input.get()); // If there are unread bytes in the input stream we move them to the head // of the stream to maximize the space available to read new data into. if (z_stream_def_->stream->avail_in > 0) { uLong read_bytes = z_stream_def_->stream->next_in - z_stream_def_->input.get(); // Remove `read_bytes` from the head of the input stream. // Move unread bytes to the head of the input stream. if (read_bytes > 0) { memmove(z_stream_def_->input.get(), z_stream_def_->stream->next_in, z_stream_def_->stream->avail_in); } bytes_to_read -= z_stream_def_->stream->avail_in; read_location += z_stream_def_->stream->avail_in; } tstring data; // Try to read enough data to fill up z_stream_def_->input. // TODO(rohanj): Add a char* version of ReadNBytes to InputStreamInterface // and use that instead to make this more efficient. Status s = input_stream_->ReadNBytes(bytes_to_read, &data); memcpy(read_location, data.data(), data.size()); // Since we moved unread data to the head of the input stream we can point // next_in to the head of the input stream. z_stream_def_->stream->next_in = z_stream_def_->input.get(); // Note: data.size() could be different from bytes_to_read. z_stream_def_->stream->avail_in += data.size(); if (!s.ok() && !errors::IsOutOfRange(s)) { return s; } // We throw OutOfRange error iff no new data has been read from stream. // Since we never check how much data is remaining in the stream, it is // possible that on the last read there isn't enough data in the stream to // fill up the buffer in which case input_stream_->ReadNBytes would return an // OutOfRange error. if (data.empty()) { return errors::OutOfRange("EOF reached"); } if (errors::IsOutOfRange(s)) { return Status::OK(); } return s; } size_t ZlibInputStream::ReadBytesFromCache(size_t bytes_to_read, tstring* result) { size_t unread_bytes = reinterpret_cast<char*>(z_stream_def_->stream->next_out) - next_unread_byte_; size_t can_read_bytes = std::min(bytes_to_read, unread_bytes); if (can_read_bytes > 0) { result->append(next_unread_byte_, can_read_bytes); next_unread_byte_ += can_read_bytes; } bytes_read_ += can_read_bytes; return can_read_bytes; } size_t ZlibInputStream::NumUnreadBytes() const { size_t read_bytes = next_unread_byte_ - reinterpret_cast<char*>(z_stream_def_->output.get()); return output_buffer_capacity_ - z_stream_def_->stream->avail_out - read_bytes; } Status ZlibInputStream::ReadNBytes(int64 bytes_to_read, tstring* result) { if (init_error_) { return errors::DataLoss("Unable to decompress Zlib file."); } result->clear(); // Read as many bytes as possible from cache. bytes_to_read -= ReadBytesFromCache(bytes_to_read, result); while (bytes_to_read > 0) { // At this point we can be sure that cache has been emptied. DCHECK_EQ(NumUnreadBytes(), 0); // Now that the cache is empty we need to inflate more data. // Step 1. Setup output stream. z_stream_def_->stream->next_out = z_stream_def_->output.get(); next_unread_byte_ = reinterpret_cast<char*>(z_stream_def_->output.get()); z_stream_def_->stream->avail_out = output_buffer_capacity_; // Step 2. Try to inflate some input data. TF_RETURN_IF_ERROR(Inflate()); // Step 3. Read any data produced by inflate. If no progress was made by // inflate, read more compressed data from the input stream. if (NumUnreadBytes() == 0) { TF_RETURN_IF_ERROR(ReadFromStream()); } else { bytes_to_read -= ReadBytesFromCache(bytes_to_read, result); } } return Status::OK(); } #if defined(TF_CORD_SUPPORT) Status ZlibInputStream::ReadNBytes(int64 bytes_to_read, absl::Cord* result) { // TODO(frankchn): Optimize this instead of bouncing through the buffer. tstring buf; TF_RETURN_IF_ERROR(ReadNBytes(bytes_to_read, &buf)); result->Clear(); result->Append(buf.data()); return Status::OK(); } #endif int64 ZlibInputStream::Tell() const { return bytes_read_; } Status ZlibInputStream::Inflate() { int error = inflate(z_stream_def_->stream.get(), zlib_options_.flush_mode); // Source: http://zlib.net/manual.html // Z_BUF_ERROR: `inflate` returns Z_BUF_ERROR if no progress was made. This is // not fatal and `inflate` can be called again with more input and output // space to continue inflating. if (error != Z_OK && error != Z_STREAM_END && error != Z_BUF_ERROR) { string error_string = strings::StrCat("inflate() failed with error ", error); if (z_stream_def_->stream->msg != nullptr) { strings::StrAppend(&error_string, ": ", z_stream_def_->stream->msg); } return errors::DataLoss(error_string); } return Status::OK(); } } // namespace io } // namespace tensorflow
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/lib/io/zlib_inputstream.h" #include <zlib.h> #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/strcat.h" namespace tensorflow { namespace io { struct ZStreamDef { ZStreamDef(size_t input_buffer_capacity, size_t output_buffer_capacity) : input(new Bytef[input_buffer_capacity]), output(new Bytef[output_buffer_capacity]), stream(new z_stream) {} // Buffer for storing contents read from compressed stream. // TODO(srbs): Consider using circular buffers. That would greatly simplify // the implementation. std::unique_ptr<Bytef[]> input; // Buffer for storing inflated contents of `input_stream_`. std::unique_ptr<Bytef[]> output; // Configuration passed to `inflate`. // // z_stream_def_->stream->next_in: // Next byte to de-compress. Points to some byte in // z_stream_def_->streamdef_.input buffer. // z_stream_def_->stream->avail_in: // Number of bytes available to be decompressed at this time. // z_stream_def_->stream->next_out: // Next byte to write de-compressed data to. Points to some byte in // z_stream_def_->streamdef_.output buffer. // z_stream_def_->stream->avail_out: // Number of free bytes available at write location. std::unique_ptr<z_stream> stream; }; ZlibInputStream::ZlibInputStream( InputStreamInterface* input_stream, size_t input_buffer_bytes, // size of z_stream.next_in buffer size_t output_buffer_bytes, // size of z_stream.next_out buffer const ZlibCompressionOptions& zlib_options, bool owns_input_stream) : owns_input_stream_(owns_input_stream), input_stream_(input_stream), input_buffer_capacity_(input_buffer_bytes), output_buffer_capacity_(output_buffer_bytes), zlib_options_(zlib_options), z_stream_def_( new ZStreamDef(input_buffer_capacity_, output_buffer_capacity_)), bytes_read_(0) { InitZlibBuffer(); } ZlibInputStream::ZlibInputStream(InputStreamInterface* input_stream, size_t input_buffer_bytes, size_t output_buffer_bytes, const ZlibCompressionOptions& zlib_options) : ZlibInputStream(input_stream, input_buffer_bytes, output_buffer_bytes, zlib_options, false) {} ZlibInputStream::~ZlibInputStream() { if (z_stream_def_->stream && !init_error_) { inflateEnd(z_stream_def_->stream.get()); } if (owns_input_stream_) { delete input_stream_; } } Status ZlibInputStream::Reset() { if (init_error_) { return errors::DataLoss("unable to reset stream, cannot decompress."); } TF_RETURN_IF_ERROR(input_stream_->Reset()); inflateEnd(z_stream_def_->stream.get()); InitZlibBuffer(); bytes_read_ = 0; return Status::OK(); } void ZlibInputStream::InitZlibBuffer() { memset(z_stream_def_->stream.get(), 0, sizeof(z_stream)); z_stream_def_->stream->zalloc = Z_NULL; z_stream_def_->stream->zfree = Z_NULL; z_stream_def_->stream->opaque = Z_NULL; z_stream_def_->stream->next_in = Z_NULL; z_stream_def_->stream->avail_in = 0; int status = inflateInit2(z_stream_def_->stream.get(), zlib_options_.window_bits); if (zlib_options_.soft_fail_on_error && status != Z_OK) { init_error_ = true; return; } CHECK_EQ(status, Z_OK) << "inflateInit failed with status " << status; z_stream_def_->stream->next_in = z_stream_def_->input.get(); z_stream_def_->stream->next_out = z_stream_def_->output.get(); next_unread_byte_ = reinterpret_cast<char*>(z_stream_def_->output.get()); z_stream_def_->stream->avail_in = 0; z_stream_def_->stream->avail_out = output_buffer_capacity_; } Status ZlibInputStream::ReadFromStream() { int bytes_to_read = input_buffer_capacity_; char* read_location = reinterpret_cast<char*>(z_stream_def_->input.get()); // If there are unread bytes in the input stream we move them to the head // of the stream to maximize the space available to read new data into. if (z_stream_def_->stream->avail_in > 0) { uLong read_bytes = z_stream_def_->stream->next_in - z_stream_def_->input.get(); // Remove `read_bytes` from the head of the input stream. // Move unread bytes to the head of the input stream. if (read_bytes > 0) { memmove(z_stream_def_->input.get(), z_stream_def_->stream->next_in, z_stream_def_->stream->avail_in); } bytes_to_read -= z_stream_def_->stream->avail_in; read_location += z_stream_def_->stream->avail_in; } tstring data; // Try to read enough data to fill up z_stream_def_->input. // TODO(rohanj): Add a char* version of ReadNBytes to InputStreamInterface // and use that instead to make this more efficient. Status s = input_stream_->ReadNBytes(bytes_to_read, &data); memcpy(read_location, data.data(), data.size()); // Since we moved unread data to the head of the input stream we can point // next_in to the head of the input stream. z_stream_def_->stream->next_in = z_stream_def_->input.get(); // Note: data.size() could be different from bytes_to_read. z_stream_def_->stream->avail_in += data.size(); if (!s.ok() && !errors::IsOutOfRange(s)) { return s; } // We throw OutOfRange error iff no new data has been read from stream. // Since we never check how much data is remaining in the stream, it is // possible that on the last read there isn't enough data in the stream to // fill up the buffer in which case input_stream_->ReadNBytes would return an // OutOfRange error. if (data.empty()) { return errors::OutOfRange("EOF reached"); } if (errors::IsOutOfRange(s)) { return Status::OK(); } return s; } size_t ZlibInputStream::ReadBytesFromCache(size_t bytes_to_read, tstring* result) { size_t unread_bytes = reinterpret_cast<char*>(z_stream_def_->stream->next_out) - next_unread_byte_; size_t can_read_bytes = std::min(bytes_to_read, unread_bytes); if (can_read_bytes > 0) { result->append(next_unread_byte_, can_read_bytes); next_unread_byte_ += can_read_bytes; } bytes_read_ += can_read_bytes; return can_read_bytes; } size_t ZlibInputStream::NumUnreadBytes() const { size_t read_bytes = next_unread_byte_ - reinterpret_cast<char*>(z_stream_def_->output.get()); return output_buffer_capacity_ - z_stream_def_->stream->avail_out - read_bytes; } Status ZlibInputStream::ReadNBytes(int64 bytes_to_read, tstring* result) { if (init_error_) { return errors::DataLoss("Unable to decompress Zlib file."); } result->clear(); // Read as many bytes as possible from cache. bytes_to_read -= ReadBytesFromCache(bytes_to_read, result); while (bytes_to_read > 0) { // At this point we can be sure that cache has been emptied. DCHECK_EQ(NumUnreadBytes(), 0); // Now that the cache is empty we need to inflate more data. // Step 1. Setup output stream. z_stream_def_->stream->next_out = z_stream_def_->output.get(); next_unread_byte_ = reinterpret_cast<char*>(z_stream_def_->output.get()); z_stream_def_->stream->avail_out = output_buffer_capacity_; // Step 2. Try to inflate some input data. TF_RETURN_IF_ERROR(Inflate()); // Step 3. Read any data produced by inflate. If no progress was made by // inflate, read more compressed data from the input stream. if (NumUnreadBytes() == 0) { TF_RETURN_IF_ERROR(ReadFromStream()); } else { bytes_to_read -= ReadBytesFromCache(bytes_to_read, result); } } return Status::OK(); } #if defined(TF_CORD_SUPPORT) Status ZlibInputStream::ReadNBytes(int64 bytes_to_read, absl::Cord* result) { // TODO(frankchn): Optimize this instead of bouncing through the buffer. tstring buf; TF_RETURN_IF_ERROR(ReadNBytes(bytes_to_read, &buf)); result->Clear(); result->Append(buf.data()); return Status::OK(); } #endif int64 ZlibInputStream::Tell() const { return bytes_read_; } Status ZlibInputStream::Inflate() { int error = inflate(z_stream_def_->stream.get(), zlib_options_.flush_mode); // Source: http://zlib.net/manual.html // Z_BUF_ERROR: `inflate` returns Z_BUF_ERROR if no progress was made. This is // not fatal and `inflate` can be called again with more input and output // space to continue inflating. if (error != Z_OK && error != Z_STREAM_END && error != Z_BUF_ERROR) { string error_string = strings::StrCat("inflate() failed with error ", error); if (z_stream_def_->stream->msg != nullptr) { strings::StrAppend(&error_string, ": ", z_stream_def_->stream->msg); } return errors::DataLoss(error_string); } if (error == Z_STREAM_END && zlib_options_.window_bits == MAX_WBITS + 16) { inflateReset(z_stream_def_->stream.get()); } return Status::OK(); } } // namespace io } // namespace tensorflow
add support for concatenated gzip in ZlibInputStream
add support for concatenated gzip in ZlibInputStream
C++
apache-2.0
frreiss/tensorflow-fred,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,petewarden/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,petewarden/tensorflow,sarvex/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,karllessard/tensorflow,annarev/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,karllessard/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,annarev/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,yongtang/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow
b3f285985f1380e96248fe5e9b49310994944ad9
notify.cpp
notify.cpp
#include <iostream> #include <string> #include <fstream> using namespace std; class Textfile { public: Textfile(string name) { setFilename(name); } void setFilename(string name) { filename = name; } void readFileContents() { ifstream olaf(filename); string str; int count = 0; while(getline(olaf, str)) { if(str.empty()) { continue; } if(str[0] == '#') { continue; } count++; } olaf.close(); numberOfLines = count; lines = new string[numberOfLines]; // open the file again olaf.open(filename); int i = 0; while(getline(olaf, str)) { if(str.empty()) { continue; } if(str[0] == '#') { continue; } lines[ i ] = string(str); i++; } } string lineAt(int i) { return lines[ i ]; } int getNumberOfLines() { return numberOfLines; } ~Textfile() { if(NULL != lines) { delete[] lines; } } private: string *lines = NULL; string filename; int numberOfLines = 0; }; int main( int argc, char** argv ) { Textfile a( argv[1] ); a.readFileContents(); for( int i = 0; i < a.getNumberOfLines(); i++ ) { cout << "\t" << a.lineAt(i) << endl; } }
#include <iostream> #include <string> #include <fstream> using namespace std; class Textfile { public: Textfile(string name) { setFilename(name); } void setFilename(string name) { filename = name; } void readFileContents() { ifstream olaf(filename); string str; int count = 0; while(getline(olaf, str)) { if(str.empty()) { continue; } if(str[0] == '#') { continue; } count++; } olaf.close(); numberOfLines = count; lines = new string[numberOfLines]; // open the file again olaf.open(filename); int i = 0; while(getline(olaf, str)) { if(str.empty()) { continue; } if(str[0] == '#') { continue; } lines[ i ] = string(str); i++; } } string lineAt(int i) { return lines[ i ]; } int getNumberOfLines() { return numberOfLines; } ~Textfile() { if(NULL != lines) { delete[] lines; } } private: string *lines = NULL; string filename; int numberOfLines = 0; }; int main( int argc, char** argv ) { Textfile a( argv[1] ); a.readFileContents(); for( int i = 0; i < a.getNumberOfLines(); i++ ) { cout << a.lineAt(i) << endl; } }
remove tab
remove tab
C++
mit
aleman/hw01,aleman/hw01
9f52f59a05cf15f194191c224e83f0225a267191
src/utils/sys.cpp
src/utils/sys.cpp
#include <utils/sys.hpp> #include <utils/string.hpp> #include <stdexcept> #if __unix || __unix__ #include <unistd.h> #include <ftw.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <cstring> #include <cstdlib> namespace utils { namespace sys { std::string whereis(const std::string& name) { //compute path dirs vector std::vector<std::string> paths = utils::string::split(std::string(::getenv("PATH")), #ifdef _WIN32 //_WIN64 ";" #else ":" #endif ); for(std::string& bpath : paths) { std::string fpath = bpath; if(bpath.size() > 1) { #ifdef _WIN32 //_WIN64 if(bpath[bpath.size()-1] != '\\') fpath += '\\'; #else if(bpath[bpath.size()-1] != '/') fpath += '/'; #endif } fpath += name; if(utils::sys::file::exists(fpath)) return fpath; } return {}; } //Library Library::Library(const std::string& name) : _name(name),lib(nullptr) { } bool Library::load() { #ifdef _WIN32 //_WIN64 lib = ::LoadLibrary(_name.c_str()); if (lib == nullptr) { utils::log::error("utils:sys::Library::load","Unable to load ",_name); return false; } #elif __linux //|| __unix //or __APPLE__ lib = ::dlopen(_name.c_str(), RTLD_LAZY); char* err = ::dlerror(); if (lib == nullptr or err) { utils::log::error("utils:sys::Library::load","Unable to load ",_name,err); return false; } #endif return true; } void Library::close() { //clear all linked functions for(auto& c : funcs) delete c.second; funcs.clear(); //delete the lib #ifdef _WIN32 //_WIN64 ::FreeLibrary(lib); #elif __linux ::dlclose(lib); ::dlerror(); #endif } utils::func::VFunc* Library::operator[](const std::string& name) { auto value = funcs.find(name); if(value != funcs.end()) return value->second; return nullptr; } //Compiler Compiler::Compiler() : _output("./out") { #ifdef _WIN32 //_WIN64 auto comp_list = {"mingw32-g++.exe","clang.exe"}; #else auto comp_list = {"g++","clang"}; #endif for(const std::string& c : comp_list) { std::string path = sys::whereis(c); if(not path.empty()) { _name = c; break; } } if(_name.empty()) throw std::runtime_error("no compilater " #ifdef _WIN32 //_WIN64 "mingw-g++.exe or clang.exe" #else "g++ or clang" #endif " find"); } Compiler::Compiler(const std::string& name) : _output("./out") { std::string path = sys::whereis(name); if(path.empty()) throw std::runtime_error(name); _name = path; } Compiler& Compiler::output(const std::string& out) { if(not out.empty()) { #ifdef _WIN32 //_WIN64 if(string::startswith(out,".\\")) _output = out; else _output = ".\\"+out; #else if(string::startswith(out,"./")) _output = out; else _output = "./"+out; #endif } return *this; } Library Compiler::get() const { for(const std::string& u : make_cmds()) { utils::log::info("utils:sys::Compiler::get","system("+u+")"); int res = ::system(u.c_str()); if(res == -1) { utils::log::error("utils:sys::Compiler::get","failed to make sytem call"); throw std::runtime_error("fork failed"); } else if(res != 0) { utils::log::error("utils:sys::Compiler::get","the command return the error code:",res); throw std::runtime_error("fork failed"); } } return {_output+ #ifdef _WIN32 ".dll" #else ".so" #endif }; } std::ostream& operator<<(std::ostream& output,const Compiler& self) { for(const std::string& u : self.make_cmds()) output<<u<<std::endl; return output; } std::vector<std::string> Compiler::make_cmds() const { std::vector<std::string> res; //compile as .o unsigned int _size = _inputs.size(); for(unsigned int i=0;i<_size;++i) { std::string tmp = _name + " -fpic "; unsigned int _s = _flags.size(); for(unsigned int i=0;i<_s;++i) tmp+=" "+_flags[i]; tmp +=" -x c++ -c \"" +_inputs[i]+"\" -o \""+_inputs[i]+".o\""; res.push_back(std::move(tmp)); } //compile .o as .so/.dll { std::string tmp = _name + " -shared -o "+_output+ #ifdef _WIN32 ".dll"; #else ".so"; #endif for(unsigned int i=0;i<_size;++i) tmp+= " \""+_inputs[i]+".o\""; unsigned int _s = _links.size(); if(_s>0) { for(unsigned int i=0;i<_s;++i) tmp += " -l"+_links[i]; } res.push_back(std::move(tmp)); } return res; } namespace dir { int create(const std::string& dirpath,const int permissions) { int res = 1; //0 => error, 1 => created, 2 => already exist auto sp = string::split(dirpath,"/"); std::string current; if(dirpath.size() > 0 and dirpath[0] == '/') current = "/"; const unsigned int _size = sp.size(); for(unsigned int i=0; i<_size and res != 0;++i) { current += sp[i] + "/"; #if __WIN32 res = ::mkdir(current.c_str()); #else res = ::mkdir(current.c_str(), permissions); #endif if(res == 0) res = 1; else if(errno == EEXIST) res = 2; else res = 0; } return res; } std::list<std::string> list_files(const std::string& dirpath) { DIR *curDir; std::list<std::string> res; if ((curDir = opendir(dirpath.c_str())) == NULL) return res; dirent *curEntry =readdir(curDir); while (curEntry != NULL) { if(curEntry->d_type == DT_REG) res.push_back(curEntry->d_name); curEntry =readdir(curDir); } ::closedir(curDir); return res; } std::list<std::string> list_dirs(const std::string& dirpath) { DIR *curDir; std::list<std::string> res; if ((curDir = opendir(dirpath.c_str())) == NULL) return res; dirent *curEntry =readdir(curDir); while (curEntry != NULL) { if(curEntry->d_type == DT_DIR and std::string(curEntry->d_name) != ".." and std::string(curEntry->d_name) != ".") res.push_back(curEntry->d_name); curEntry =readdir(curDir); } ::closedir(curDir); return res; } bool rm(const std::string& path,bool recusive) { bool res; if(not recusive) { #if __unix__ res = ::rmdir(path.c_str()) == 0; #endif } else { auto f = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) -> int { int rv; switch(typeflag) { case FTW_F: rv = ::unlink(fpath);break; case FTW_D: case FTW_DP: rv = ::rmdir(fpath);break; default: rv = ::remove(fpath);break; } if (rv) ::perror(fpath); return rv; }; res = ::nftw(path.c_str(),f, 64, FTW_DEPTH | FTW_PHYS) == 0; } return res; } bool rm_if_empty(const std::string& path,bool recusive) { bool res; if(not recusive) { res = ::rmdir(path.c_str()) == 0; } else { auto f = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) -> int { int rv; switch(typeflag) { case FTW_D: case FTW_DP: rv = ::rmdir(fpath);break; default: return 1; } if (rv) ::perror(fpath); return rv; }; res = ::nftw(path.c_str(),f, 64, FTW_DEPTH | FTW_PHYS) == 0; } return res; } std::string pwd() { char* path = ::get_current_dir_name(); std::string res(path); ::free(path); return res; } std::string abs_path(const std::string& relative_path) { char my_path[relative_path.size() + 1]; ::strcpy(my_path,relative_path.c_str()); char *resolved_path = ::realpath(my_path,nullptr); std::string res = resolved_path; ::free(resolved_path); return res; } } namespace file { bool rm(const std::string& path) { #if __unix__ return ::unlink(path.c_str()) == 0; #endif } bool exists(const std::string& name) { if (FILE *file = fopen(name.c_str(), "rb")) { fclose(file); return true; } return false; } bool touch(const std::string& file_path) { //build dir tree #ifdef _WIN32 //_WIN64 file_path = utils::replace(file_path,"\\","/"); #endif std::vector<std::string> dirs = utils::string::split(file_path,"/"); if(dirs.size()>1) dirs.pop_back(); std::string dir_path = "/"+utils::string::join("/",dirs); if(not dir::create(dir_path)) return false; //create file if (FILE *file = fopen(file_path.c_str(), "ab")) { fclose(file); return true; } return false; } } } }
#include <utils/sys.hpp> #include <utils/string.hpp> #include <stdexcept> #if __unix || __unix__ #include <unistd.h> #include <ftw.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <cstring> #include <cstdlib> namespace utils { namespace sys { std::string whereis(const std::string& name) { //compute path dirs vector std::vector<std::string> paths = utils::string::split(std::string(::getenv("PATH")), #ifdef _WIN32 //_WIN64 ";" #else ":" #endif ); for(std::string& bpath : paths) { std::string fpath = bpath; if(bpath.size() > 1) { #ifdef _WIN32 //_WIN64 if(bpath[bpath.size()-1] != '\\') fpath += '\\'; #else if(bpath[bpath.size()-1] != '/') fpath += '/'; #endif } fpath += name; if(utils::sys::file::exists(fpath)) return fpath; } return {}; } //Library Library::Library(const std::string& name) : _name(name),lib(nullptr) { } Library::~Library() { if(lib) close(); } bool Library::load() { #ifdef _WIN32 //_WIN64 lib = ::LoadLibrary(_name.c_str()); if (lib == nullptr) { utils::log::error("utils:sys::Library::load","Unable to load ",_name); return false; } #elif __linux //|| __unix //or __APPLE__ lib = ::dlopen(_name.c_str(), RTLD_LAZY); char* err = ::dlerror(); if (lib == nullptr or err) { utils::log::error("utils:sys::Library::load","Unable to load ",_name,err); return false; } #endif return true; } void Library::close() { //clear all linked functions for(auto& c : funcs) delete c.second; funcs.clear(); //delete the lib #ifdef _WIN32 //_WIN64 ::FreeLibrary(lib); #elif __linux ::dlclose(lib); ::dlerror(); #endif lib = nullptr; } utils::func::VFunc* Library::operator[](const std::string& name) { auto value = funcs.find(name); if(value != funcs.end()) return value->second; return nullptr; } //Compiler Compiler::Compiler() : _output("./out") { #ifdef _WIN32 //_WIN64 auto comp_list = {"mingw32-g++.exe","clang.exe"}; #else auto comp_list = {"g++","clang"}; #endif for(const std::string& c : comp_list) { std::string path = sys::whereis(c); if(not path.empty()) { _name = c; break; } } if(_name.empty()) throw std::runtime_error("no compilater " #ifdef _WIN32 //_WIN64 "mingw-g++.exe or clang.exe" #else "g++ or clang" #endif " find"); } Compiler::Compiler(const std::string& name) : _output("./out") { std::string path = sys::whereis(name); if(path.empty()) throw std::runtime_error(name); _name = path; } Compiler& Compiler::output(const std::string& out) { if(not out.empty()) { #ifdef _WIN32 //_WIN64 if(string::startswith(out,".\\")) _output = out; else _output = ".\\"+out; #else if(string::startswith(out,"./")) _output = out; else _output = "./"+out; #endif } return *this; } Library Compiler::get() const { for(const std::string& u : make_cmds()) { utils::log::info("utils:sys::Compiler::get","system("+u+")"); int res = ::system(u.c_str()); if(res == -1) { utils::log::error("utils:sys::Compiler::get","failed to make sytem call"); throw std::runtime_error("fork failed"); } else if(res != 0) { utils::log::error("utils:sys::Compiler::get","the command return the error code:",res); throw std::runtime_error("fork failed"); } } return {_output+ #ifdef _WIN32 ".dll" #else ".so" #endif }; } std::ostream& operator<<(std::ostream& output,const Compiler& self) { for(const std::string& u : self.make_cmds()) output<<u<<std::endl; return output; } std::vector<std::string> Compiler::make_cmds() const { std::vector<std::string> res; //compile as .o unsigned int _size = _inputs.size(); for(unsigned int i=0;i<_size;++i) { std::string tmp = _name + " -fpic "; unsigned int _s = _flags.size(); for(unsigned int i=0;i<_s;++i) tmp+=" "+_flags[i]; tmp +=" -x c++ -c \"" +_inputs[i]+"\" -o \""+_inputs[i]+".o\""; res.push_back(std::move(tmp)); } //compile .o as .so/.dll { std::string tmp = _name + " -shared -o "+_output+ #ifdef _WIN32 ".dll"; #else ".so"; #endif for(unsigned int i=0;i<_size;++i) tmp+= " \""+_inputs[i]+".o\""; unsigned int _s = _links.size(); if(_s>0) { for(unsigned int i=0;i<_s;++i) tmp += " -l"+_links[i]; } res.push_back(std::move(tmp)); } return res; } namespace dir { int create(const std::string& dirpath,const int permissions) { int res = 1; //0 => error, 1 => created, 2 => already exist auto sp = string::split(dirpath,"/"); std::string current; if(dirpath.size() > 0 and dirpath[0] == '/') current = "/"; const unsigned int _size = sp.size(); for(unsigned int i=0; i<_size and res != 0;++i) { current += sp[i] + "/"; #if __WIN32 res = ::mkdir(current.c_str()); #else res = ::mkdir(current.c_str(), permissions); #endif if(res == 0) res = 1; else if(errno == EEXIST) res = 2; else res = 0; } return res; } std::list<std::string> list_files(const std::string& dirpath) { DIR *curDir; std::list<std::string> res; if ((curDir = opendir(dirpath.c_str())) == NULL) return res; dirent *curEntry =readdir(curDir); while (curEntry != NULL) { if(curEntry->d_type == DT_REG) res.push_back(curEntry->d_name); curEntry =readdir(curDir); } ::closedir(curDir); return res; } std::list<std::string> list_dirs(const std::string& dirpath) { DIR *curDir; std::list<std::string> res; if ((curDir = opendir(dirpath.c_str())) == NULL) return res; dirent *curEntry =readdir(curDir); while (curEntry != NULL) { if(curEntry->d_type == DT_DIR and std::string(curEntry->d_name) != ".." and std::string(curEntry->d_name) != ".") res.push_back(curEntry->d_name); curEntry =readdir(curDir); } ::closedir(curDir); return res; } bool rm(const std::string& path,bool recusive) { bool res; if(not recusive) { #if __unix__ res = ::rmdir(path.c_str()) == 0; #endif } else { auto f = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) -> int { int rv; switch(typeflag) { case FTW_F: rv = ::unlink(fpath);break; case FTW_D: case FTW_DP: rv = ::rmdir(fpath);break; default: rv = ::remove(fpath);break; } if (rv) ::perror(fpath); return rv; }; res = ::nftw(path.c_str(),f, 64, FTW_DEPTH | FTW_PHYS) == 0; } return res; } bool rm_if_empty(const std::string& path,bool recusive) { bool res; if(not recusive) { res = ::rmdir(path.c_str()) == 0; } else { auto f = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) -> int { int rv; switch(typeflag) { case FTW_D: case FTW_DP: rv = ::rmdir(fpath);break; default: return 1; } if (rv) ::perror(fpath); return rv; }; res = ::nftw(path.c_str(),f, 64, FTW_DEPTH | FTW_PHYS) == 0; } return res; } std::string pwd() { char* path = ::get_current_dir_name(); std::string res(path); ::free(path); return res; } std::string abs_path(const std::string& relative_path) { char my_path[relative_path.size() + 1]; ::strcpy(my_path,relative_path.c_str()); char *resolved_path = ::realpath(my_path,nullptr); std::string res = resolved_path; ::free(resolved_path); return res; } } namespace file { bool rm(const std::string& path) { #if __unix__ return ::unlink(path.c_str()) == 0; #endif } bool exists(const std::string& name) { if (FILE *file = fopen(name.c_str(), "rb")) { fclose(file); return true; } return false; } bool touch(const std::string& file_path) { //build dir tree #ifdef _WIN32 //_WIN64 file_path = utils::replace(file_path,"\\","/"); #endif std::vector<std::string> dirs = utils::string::split(file_path,"/"); if(dirs.size()>1) dirs.pop_back(); std::string dir_path = "/"+utils::string::join("/",dirs); if(not dir::create(dir_path)) return false; //create file if (FILE *file = fopen(file_path.c_str(), "ab")) { fclose(file); return true; } return false; } } } }
add Library destructor
add Library destructor
C++
bsd-2-clause
Krozark/cpp-utils
f0baaa129d4d7148e2949ff479c85e539a6bb9db
RenderSystems/GL/src/OgreGLEngineDll.cpp
RenderSystems/GL/src/OgreGLEngineDll.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreRoot.h" #include "OgreGLPlugin.h" #ifndef OGRE_STATIC_LIB namespace Ogre { static GLPlugin* plugin; extern "C" void _OgreGLExport dllStartPlugin(void) throw() { plugin = new GLPlugin(); Root::getSingleton().installPlugin(plugin); } extern "C" void _OgreGLExport dllStopPlugin(void) { Root::getSingleton().uninstallPlugin(plugin); delete plugin; } } #endif
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreRoot.h" #include "OgreGLPlugin.h" #ifndef OGRE_STATIC_LIB namespace Ogre { static GLPlugin* plugin; extern "C" void _OgreGLExport dllStartPlugin(void) throw() { plugin = OGRE_NEW GLPlugin(); Root::getSingleton().installPlugin(plugin); } extern "C" void _OgreGLExport dllStopPlugin(void) { Root::getSingleton().uninstallPlugin(plugin); OGRE_DELETE plugin; } } #endif
Use OGRE_NEW and OGRE_DELETE in OgreGLEngineDLL
[GL] Use OGRE_NEW and OGRE_DELETE in OgreGLEngineDLL
C++
mit
paroj/ogre,RealityFactory/ogre,paroj/ogre,RealityFactory/ogre,RealityFactory/ogre,paroj/ogre,RealityFactory/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre,OGRECave/ogre,RealityFactory/ogre
587aa216bb96a87b004653694b5c5cf518a4b706
src/condor_utils/limit_directory_access.cpp
src/condor_utils/limit_directory_access.cpp
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_config.h" #include "subsystem_info.h" #include "nullfile.h" #include "basename.h" #include "condor_getcwd.h" #include "directory_util.h" #include "limit_directory_access.h" bool allow_shadow_access(const char *path, bool init, const char *job_ad_whitelist, const char *spool_dir) { bool allow = true; // Always allow access to /dev/null if (path && nullFile(path)) { return true; } if (get_mySubSystem()->isType(SUBSYSTEM_TYPE_SHADOW)) { static StringList allow_path_prefix_list; static bool path_prefix_initialized = false; if (init == false && path_prefix_initialized == false) { EXCEPT("allow_shadow_access() invoked before intialized"); } if ((init == false) && (job_ad_whitelist || spool_dir)) { EXCEPT("allow_shadow_access() invoked with init=false and job_ad_whitelist!=NULL"); } if (init) { allow_path_prefix_list.clearAll(); // If LIMIT_DIRECTORY_ACCESS is defined in the config file by the admin, // then honor it. Only if it is empty to we then allow the user to // specify the list in their job. StringList wlist; char *whitelist = param("LIMIT_DIRECTORY_ACCESS"); if (whitelist) { wlist.initializeFromString(whitelist, ','); free(whitelist); } if (wlist.isEmpty() && job_ad_whitelist && job_ad_whitelist[0]) { wlist.initializeFromString(job_ad_whitelist, ','); } // If there are any limits, then add the job's SPOOL directory to the list if (!wlist.isEmpty() && spool_dir) { wlist.append(spool_dir); std::string tmpSpool(spool_dir); // Also add spool_dir with ".tmp", since FileTransfer will also use that. tmpSpool += ".tmp"; wlist.append(tmpSpool.c_str()); } // Now go through all the directories and attempt to cannonicalize them const char *st; wlist.rewind(); while ((st = wlist.next())) { char *strp = NULL; std::string item; if ((strp = realpath(st, NULL))) { item = strp; free(strp); } else { item = st; } if (item.empty()) continue; if (!IS_ANY_DIR_DELIM_CHAR(item.back()) && item.back()!='*') { item += DIR_DELIM_CHAR; } allow_path_prefix_list.append(item.c_str()); } whitelist = allow_path_prefix_list.print_to_string(); if (whitelist == NULL) { whitelist = strdup("<unset>"); } dprintf(D_ALWAYS, "LIMIT_DIRECTORY_ACCESS = %s\n", whitelist); free(whitelist); path_prefix_initialized = true; } // If we are restricting pathnames the shadow can access, check now if (path && !allow_path_prefix_list.isEmpty()) { char *rpath = NULL; MyString full_pathname; // Make path fully qualified if it is relative to the cwd if (!fullpath(path)) { if (condor_getcwd(full_pathname)) { MyString result; full_pathname = dircat(full_pathname.Value(), path, result); path = full_pathname.Value(); } else { allow = false; dprintf(D_ALWAYS, "Access DENIED to file %s due to getcwd failure processing LIMIT_DIRECTORY_ACCESS\n", path); } } // Make our fully qualified path canonical via realpath(), to get rid of // dot-dots (e.g. /foo/../bar/xxx) and symlinks. if (allow) { rpath = realpath(path, NULL); if (!rpath) { rpath = realpath(condor_dirname(path), NULL); if (!rpath) { allow = false; dprintf(D_ALWAYS, "Access DENIED to file %s due to realpath failure processing LIMIT_DIRECTORY_ACCESS\n", path); } } } // Finally, see if the rpath of the file we are trying to access is contained // within any of the directories listed in allow_path_prefix_list. if (allow) { #ifdef WIN32 // On Win32 paths names are case insensitive allow = allow_path_prefix_list.prefix_anycase_withwildcard(rpath); #else // On everything other than Win32, path names are case sensitive allow = allow_path_prefix_list.prefix_withwildcard(rpath); #endif } free(rpath); } } // end of subsystem is SHADOW if (allow == false && path) { dprintf(D_ALWAYS, "Access DENIED to file %s due to LIMIT_DIRECTORY_ACCESS\n", path); } return allow; }
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_config.h" #include "subsystem_info.h" #include "nullfile.h" #include "basename.h" #include "condor_getcwd.h" #include "directory_util.h" #include "limit_directory_access.h" bool allow_shadow_access(const char *path, bool init, const char *job_ad_whitelist, const char *spool_dir) { bool allow = true; // Always allow access to /dev/null if (path && nullFile(path)) { return true; } if (get_mySubSystem()->isType(SUBSYSTEM_TYPE_SHADOW)) { static StringList allow_path_prefix_list; static bool path_prefix_initialized = false; if (init == false && path_prefix_initialized == false) { EXCEPT("allow_shadow_access() invoked before intialized"); } if ((init == false) && (job_ad_whitelist || spool_dir)) { EXCEPT("allow_shadow_access() invoked with init=false and job_ad_whitelist!=NULL"); } if (init) { allow_path_prefix_list.clearAll(); // If LIMIT_DIRECTORY_ACCESS is defined in the config file by the admin, // then honor it. Only if it is empty to we then allow the user to // specify the list in their job. StringList wlist; char *whitelist = param("LIMIT_DIRECTORY_ACCESS"); if (whitelist) { wlist.initializeFromString(whitelist, ','); free(whitelist); } if (wlist.isEmpty() && job_ad_whitelist && job_ad_whitelist[0]) { wlist.initializeFromString(job_ad_whitelist, ','); } // If there are any limits, then add the job's SPOOL directory to the list if (!wlist.isEmpty() && spool_dir) { wlist.append(spool_dir); std::string tmpSpool(spool_dir); // Also add spool_dir with ".tmp", since FileTransfer will also use that. tmpSpool += ".tmp"; wlist.append(tmpSpool.c_str()); } // Now go through all the directories and attempt to cannonicalize them const char *st; wlist.rewind(); while ((st = wlist.next())) { char *strp = NULL; std::string item; if ((strp = realpath(st, NULL))) { item = strp; free(strp); } else { item = st; } if (item.empty()) continue; if (!IS_ANY_DIR_DELIM_CHAR(item.back()) && item.back()!='*') { item += DIR_DELIM_CHAR; } allow_path_prefix_list.append(item.c_str()); } whitelist = allow_path_prefix_list.print_to_string(); if (whitelist == NULL) { whitelist = strdup("<unset>"); } dprintf(D_ALWAYS, "LIMIT_DIRECTORY_ACCESS = %s\n", whitelist); free(whitelist); path_prefix_initialized = true; } // If we are restricting pathnames the shadow can access, check now if (path && !allow_path_prefix_list.isEmpty()) { char *rpath = NULL; MyString full_pathname; // Make path fully qualified if it is relative to the cwd if (!fullpath(path)) { if (condor_getcwd(full_pathname)) { MyString result; full_pathname = dircat(full_pathname.Value(), path, result); path = full_pathname.Value(); } else { allow = false; dprintf(D_ALWAYS, "Access DENIED to file %s due to getcwd failure processing LIMIT_DIRECTORY_ACCESS\n", path); } } // Make our fully qualified path canonical via realpath(), to get rid of // dot-dots (e.g. /foo/../bar/xxx) and symlinks. if (allow) { rpath = realpath(path, nullptr); if (!rpath) { char *d = condor_dirname(path); rpath = realpath(d, nullptr); free(d); if (!rpath) { allow = false; dprintf(D_ALWAYS, "Access DENIED to file %s due to realpath failure processing LIMIT_DIRECTORY_ACCESS\n", path); } } } // Finally, see if the rpath of the file we are trying to access is contained // within any of the directories listed in allow_path_prefix_list. if (allow) { #ifdef WIN32 // On Win32 paths names are case insensitive allow = allow_path_prefix_list.prefix_anycase_withwildcard(rpath); #else // On everything other than Win32, path names are case sensitive allow = allow_path_prefix_list.prefix_withwildcard(rpath); #endif } free(rpath); } } // end of subsystem is SHADOW if (allow == false && path) { dprintf(D_ALWAYS, "Access DENIED to file %s due to LIMIT_DIRECTORY_ACCESS\n", path); } return allow; }
Fix memory leak in file xfer directory limiting code
Fix memory leak in file xfer directory limiting code
C++
apache-2.0
htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor
1f93784c294af5d6cdc8f99f093f0e4c021b9be5
src/core/grabber/include/device_grabber.hpp
src/core/grabber/include/device_grabber.hpp
#pragma once #include "apple_hid_usage_tables.hpp" #include "constants.hpp" #include "event_manipulator.hpp" #include "human_interface_device.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "manipulator.hpp" #include "types.hpp" #include <IOKit/hid/IOHIDManager.h> #include <thread> #include <time.h> class device_grabber final { public: device_grabber(const device_grabber&) = delete; device_grabber(manipulator::event_manipulator& event_manipulator) : event_manipulator_(event_manipulator), queue_(dispatch_queue_create(nullptr, nullptr)), grab_timer_(0), grabbed_(false) { manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__); return; } auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard), // std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl), // std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse), }); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); } } ~device_grabber(void) { cancel_grab_timer(); if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } dispatch_release(queue_); } void grab_devices(void) { auto __block last_warning_message_time = ::time(nullptr) - 1; cancel_grab_timer(); // ---------------------------------------- // setup grab_timer_ std::lock_guard<std::mutex> guard(grab_timer_mutex_); grab_timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue_); dispatch_source_set_timer(grab_timer_, dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), 0.1 * NSEC_PER_SEC, 0); dispatch_source_set_event_handler(grab_timer_, ^{ if (grabbed_) { return; } const char* warning_message = nullptr; if (!event_manipulator_.is_ready()) { warning_message = "event_manipulator_ is not ready. Please wait for a while."; } if (get_all_devices_pressed_keys_count() > 0) { warning_message = "There are pressed down keys in some devices. Please release them."; } if (warning_message) { auto time = ::time(nullptr); if (last_warning_message_time != time) { last_warning_message_time = time; logger::get_logger().warn(warning_message); return; } } // ---------------------------------------- // grab devices grabbed_ = true; { std::lock_guard<std::mutex> hids_guard(hids_mutex_); for (auto&& it : hids_) { grab(*(it.second)); } } event_manipulator_.reset(); logger::get_logger().info("devices are grabbed"); cancel_grab_timer(); }); dispatch_resume(grab_timer_); } void ungrab_devices(void) { if (!grabbed_) { return; } grabbed_ = false; cancel_grab_timer(); { std::lock_guard<std::mutex> guard(hids_mutex_); for (auto&& it : hids_) { ungrab(*(it.second)); } } event_manipulator_.reset(); logger::get_logger().info("devices are ungrabbed"); } void set_caps_lock_led_state(krbn::led_state state) { std::lock_guard<std::mutex> guard(hids_mutex_); for (const auto& it : hids_) { (it.second)->set_caps_lock_led_state(state); } } private: static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_matching_callback(device); } void device_matching_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } auto dev = std::make_unique<human_interface_device>(logger::get_logger(), device); auto manufacturer = dev->get_manufacturer(); auto product = dev->get_product(); auto vendor_id = dev->get_vendor_id(); auto product_id = dev->get_product_id(); auto location_id = dev->get_location_id(); auto serial_number = dev->get_serial_number(); logger::get_logger().info("matching device: " "manufacturer:{1}, " "product:{2}, " "vendor_id:{3:#x}, " "product_id:{4:#x}, " "location_id:{5:#x}, " "serial_number:{6} " "registry_entry_id:{7} " "@ {0}", __PRETTY_FUNCTION__, manufacturer ? *manufacturer : "", product ? *product : "", vendor_id ? *vendor_id : 0, product_id ? *product_id : 0, location_id ? *location_id : 0, serial_number ? *serial_number : "", dev->get_registry_entry_id()); if (grabbed_) { grab(*dev); } else { observe(*dev); } { std::lock_guard<std::mutex> guard(hids_mutex_); hids_[device] = std::move(dev); } } static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_removal_callback(device); } void device_removal_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } { std::lock_guard<std::mutex> guard(hids_mutex_); auto it = hids_.find(device); if (it != hids_.end()) { auto& dev = it->second; if (dev) { auto vendor_id = dev->get_vendor_id(); auto product_id = dev->get_product_id(); auto location_id = dev->get_location_id(); logger::get_logger().info("removal device: " "vendor_id:{1:#x}, " "product_id:{2:#x}, " "location_id:{3:#x} " "@ {0}", __PRETTY_FUNCTION__, vendor_id ? *vendor_id : 0, product_id ? *product_id : 0, location_id ? *location_id : 0); hids_.erase(it); } } } event_manipulator_.stop_key_repeat(); } void observe(human_interface_device& hid) { human_interface_device::value_callback callback; hid.observe(callback); } void unobserve(human_interface_device& hid) { hid.unobserve(); } void grab(human_interface_device& hid) { auto manufacturer = hid.get_manufacturer(); if (manufacturer && *manufacturer == "pqrs.org") { return; } unobserve(hid); // seize device hid.grab(std::bind(&device_grabber::value_callback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6)); // set keyboard led event_manipulator_.refresh_caps_lock_led(); } void ungrab(human_interface_device& hid) { auto manufacturer = hid.get_manufacturer(); if (manufacturer && *manufacturer == "pqrs.org") { return; } hid.ungrab(); observe(hid); } void value_callback(human_interface_device& device, IOHIDValueRef _Nonnull value, IOHIDElementRef _Nonnull element, uint32_t usage_page, uint32_t usage, CFIndex integer_value) { if (!grabbed_) { return; } auto device_registry_entry_id = manipulator::device_registry_entry_id(device.get_registry_entry_id()); switch (usage_page) { case kHIDPage_KeyboardOrKeypad: if (kHIDUsage_KeyboardErrorUndefined < usage && usage < kHIDUsage_Keyboard_Reserved) { bool pressed = integer_value; event_manipulator_.handle_keyboard_event(device_registry_entry_id, krbn::key_code(usage), pressed); } break; case kHIDPage_AppleVendorTopCase: if (usage == kHIDUsage_AV_TopCase_KeyboardFn) { bool pressed = integer_value; event_manipulator_.handle_keyboard_event(device_registry_entry_id, krbn::key_code::vk_fn_modifier, pressed); } break; default: break; } // reset modifier_flags state if all keys are released. if (get_all_devices_pressed_keys_count() == 0) { event_manipulator_.reset_modifier_flag_state(); } } size_t get_all_devices_pressed_keys_count(void) { std::lock_guard<std::mutex> guard(hids_mutex_); size_t total = 0; for (const auto& it : hids_) { total += (it.second)->get_pressed_keys_count(); } return total; } void cancel_grab_timer(void) { std::lock_guard<std::mutex> guard(grab_timer_mutex_); if (grab_timer_) { dispatch_source_cancel(grab_timer_); dispatch_release(grab_timer_); grab_timer_ = 0; } } manipulator::event_manipulator& event_manipulator_; IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_; std::mutex hids_mutex_; dispatch_queue_t _Nonnull queue_; dispatch_source_t _Nullable grab_timer_; std::mutex grab_timer_mutex_; std::atomic<bool> grabbed_; };
#pragma once #include "apple_hid_usage_tables.hpp" #include "constants.hpp" #include "event_manipulator.hpp" #include "human_interface_device.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "manipulator.hpp" #include "types.hpp" #include <IOKit/hid/IOHIDManager.h> #include <thread> #include <time.h> class device_grabber final { public: device_grabber(const device_grabber&) = delete; device_grabber(manipulator::event_manipulator& event_manipulator) : event_manipulator_(event_manipulator), queue_(dispatch_queue_create(nullptr, nullptr)), grab_timer_(0), grabbed_(false) { manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__); return; } auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard), // std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl), // std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse), }); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); } } ~device_grabber(void) { cancel_grab_timer(); if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } dispatch_release(queue_); } void grab_devices(void) { auto __block last_warning_message_time = ::time(nullptr) - 1; cancel_grab_timer(); // ---------------------------------------- // setup grab_timer_ std::lock_guard<std::mutex> guard(grab_timer_mutex_); grab_timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue_); dispatch_source_set_timer(grab_timer_, dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), 0.1 * NSEC_PER_SEC, 0); dispatch_source_set_event_handler(grab_timer_, ^{ if (grabbed_) { return; } const char* warning_message = nullptr; if (!event_manipulator_.is_ready()) { warning_message = "event_manipulator_ is not ready. Please wait for a while."; } if (get_all_devices_pressed_keys_count() > 0) { warning_message = "There are pressed down keys in some devices. Please release them."; } if (warning_message) { auto time = ::time(nullptr); if (last_warning_message_time != time) { last_warning_message_time = time; logger::get_logger().warn(warning_message); return; } } // ---------------------------------------- // grab devices grabbed_ = true; { std::lock_guard<std::mutex> hids_guard(hids_mutex_); for (auto&& it : hids_) { unobserve(*(it.second)); grab(*(it.second)); } } event_manipulator_.reset(); logger::get_logger().info("devices are grabbed"); cancel_grab_timer(); }); dispatch_resume(grab_timer_); } void ungrab_devices(void) { if (!grabbed_) { return; } grabbed_ = false; cancel_grab_timer(); { std::lock_guard<std::mutex> guard(hids_mutex_); for (auto&& it : hids_) { ungrab(*(it.second)); observe(*(it.second)); } } event_manipulator_.reset(); logger::get_logger().info("devices are ungrabbed"); } void set_caps_lock_led_state(krbn::led_state state) { std::lock_guard<std::mutex> guard(hids_mutex_); for (const auto& it : hids_) { (it.second)->set_caps_lock_led_state(state); } } private: static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_matching_callback(device); } void device_matching_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } auto dev = std::make_unique<human_interface_device>(logger::get_logger(), device); auto manufacturer = dev->get_manufacturer(); auto product = dev->get_product(); auto vendor_id = dev->get_vendor_id(); auto product_id = dev->get_product_id(); auto location_id = dev->get_location_id(); auto serial_number = dev->get_serial_number(); logger::get_logger().info("matching device: " "manufacturer:{1}, " "product:{2}, " "vendor_id:{3:#x}, " "product_id:{4:#x}, " "location_id:{5:#x}, " "serial_number:{6} " "registry_entry_id:{7} " "@ {0}", __PRETTY_FUNCTION__, manufacturer ? *manufacturer : "", product ? *product : "", vendor_id ? *vendor_id : 0, product_id ? *product_id : 0, location_id ? *location_id : 0, serial_number ? *serial_number : "", dev->get_registry_entry_id()); if (grabbed_) { grab(*dev); } else { observe(*dev); } { std::lock_guard<std::mutex> guard(hids_mutex_); hids_[device] = std::move(dev); } } static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_removal_callback(device); } void device_removal_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } { std::lock_guard<std::mutex> guard(hids_mutex_); auto it = hids_.find(device); if (it != hids_.end()) { auto& dev = it->second; if (dev) { auto vendor_id = dev->get_vendor_id(); auto product_id = dev->get_product_id(); auto location_id = dev->get_location_id(); logger::get_logger().info("removal device: " "vendor_id:{1:#x}, " "product_id:{2:#x}, " "location_id:{3:#x} " "@ {0}", __PRETTY_FUNCTION__, vendor_id ? *vendor_id : 0, product_id ? *product_id : 0, location_id ? *location_id : 0); hids_.erase(it); } } } event_manipulator_.stop_key_repeat(); } void observe(human_interface_device& hid) { human_interface_device::value_callback callback; hid.observe(callback); } void unobserve(human_interface_device& hid) { hid.unobserve(); } void grab(human_interface_device& hid) { auto manufacturer = hid.get_manufacturer(); if (manufacturer && *manufacturer == "pqrs.org") { return; } // seize device hid.grab(std::bind(&device_grabber::value_callback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6)); // set keyboard led event_manipulator_.refresh_caps_lock_led(); } void ungrab(human_interface_device& hid) { auto manufacturer = hid.get_manufacturer(); if (manufacturer && *manufacturer == "pqrs.org") { return; } hid.ungrab(); } void value_callback(human_interface_device& device, IOHIDValueRef _Nonnull value, IOHIDElementRef _Nonnull element, uint32_t usage_page, uint32_t usage, CFIndex integer_value) { if (!grabbed_) { return; } auto device_registry_entry_id = manipulator::device_registry_entry_id(device.get_registry_entry_id()); switch (usage_page) { case kHIDPage_KeyboardOrKeypad: if (kHIDUsage_KeyboardErrorUndefined < usage && usage < kHIDUsage_Keyboard_Reserved) { bool pressed = integer_value; event_manipulator_.handle_keyboard_event(device_registry_entry_id, krbn::key_code(usage), pressed); } break; case kHIDPage_AppleVendorTopCase: if (usage == kHIDUsage_AV_TopCase_KeyboardFn) { bool pressed = integer_value; event_manipulator_.handle_keyboard_event(device_registry_entry_id, krbn::key_code::vk_fn_modifier, pressed); } break; default: break; } // reset modifier_flags state if all keys are released. if (get_all_devices_pressed_keys_count() == 0) { event_manipulator_.reset_modifier_flag_state(); } } size_t get_all_devices_pressed_keys_count(void) { std::lock_guard<std::mutex> guard(hids_mutex_); size_t total = 0; for (const auto& it : hids_) { total += (it.second)->get_pressed_keys_count(); } return total; } void cancel_grab_timer(void) { std::lock_guard<std::mutex> guard(grab_timer_mutex_); if (grab_timer_) { dispatch_source_cancel(grab_timer_); dispatch_release(grab_timer_); grab_timer_ = 0; } } manipulator::event_manipulator& event_manipulator_; IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_; std::mutex hids_mutex_; dispatch_queue_t _Nonnull queue_; dispatch_source_t _Nullable grab_timer_; std::mutex grab_timer_mutex_; std::atomic<bool> grabbed_; };
remove automatically calls of unobserve,observe
remove automatically calls of unobserve,observe
C++
unlicense
epegzz/Karabiner-Elements,jrolfs/Karabiner-Elements,jgosmann/Karabiner-Elements-Neo,jgosmann/Karabiner-Elements-Neo,jrolfs/Karabiner-Elements,jgosmann/Karabiner-Elements-Neo,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,epegzz/Karabiner-Elements,jrolfs/Karabiner-Elements,tekezo/Karabiner-Elements,jgosmann/Karabiner-Elements-Neo,jrolfs/Karabiner-Elements,tekezo/Karabiner-Elements,epegzz/Karabiner-Elements,epegzz/Karabiner-Elements
42dcca690f55adcc793d7ee22c1b922d2ac6c570
test_rclcpp/test/test_local_parameters.cpp
test_rclcpp/test/test_local_parameters.cpp
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <stdexcept> #include <string> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #include "parameter_fixtures.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif TEST(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), to_string) { rclcpp::parameter::ParameterVariant pv("foo", "bar"); rclcpp::parameter::ParameterVariant pv2("foo2", "bar2"); std::string json_dict = std::to_string(pv); EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"string\", \"value\": \"bar\"}", json_dict.c_str()); json_dict = rclcpp::parameter::_to_json_dict_entry(pv); EXPECT_STREQ( "\"foo\": {\"type\": \"string\", \"value\": \"bar\"}", json_dict.c_str()); std::vector<rclcpp::parameter::ParameterVariant> vpv; vpv.push_back(pv); vpv.push_back(pv2); json_dict = std::to_string(vpv); EXPECT_STREQ( "{\"foo\": {\"type\": \"string\", \"value\": \"bar\"}, \"foo2\": {\"type\": \"string\", \"value\": \"bar2\"}}", json_dict.c_str()); pv = rclcpp::parameter::ParameterVariant("foo", 2.1); //TODO(tfoote) convert the value to a float and use epsilon test. EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"double\", \"value\": \"2.100000\"}", std::to_string(pv).c_str()); pv = rclcpp::parameter::ParameterVariant("foo", 8); EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"8\"}", std::to_string(pv).c_str()); } TEST(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_synchronous) { auto node = rclcpp::Node::make_shared(std::string("test_parameters_")); // TODO(esteve): Make the parameter service automatically start with the node. auto parameter_service = std::make_shared<rclcpp::parameter_service::ParameterService>(node); auto parameters_client = std::make_shared<rclcpp::parameter_client::SyncParametersClient>(node); set_test_parameters(parameters_client); verify_test_parameters(parameters_client); } TEST(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_asynchronous) { auto node = rclcpp::Node::make_shared(std::string("test_parameters_")); // TODO(esteve): Make the parameter service automatically start with the node. auto parameter_service = std::make_shared<rclcpp::parameter_service::ParameterService>(node); auto parameters_client = std::make_shared<rclcpp::parameter_client::AsyncParametersClient>(node); verify_set_parameters_async(node, parameters_client); verify_get_parameters_async(node, parameters_client); } int main(int argc, char ** argv) { // NOTE: use custom main to ensure that rclcpp::init is called only once rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <stdexcept> #include <string> #include <vector> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #include "parameter_fixtures.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif TEST(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), to_string) { rclcpp::parameter::ParameterVariant pv("foo", "bar"); rclcpp::parameter::ParameterVariant pv2("foo2", "bar2"); std::string json_dict = std::to_string(pv); EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"string\", \"value\": \"bar\"}", json_dict.c_str()); json_dict = rclcpp::parameter::_to_json_dict_entry(pv); EXPECT_STREQ( "\"foo\": {\"type\": \"string\", \"value\": \"bar\"}", json_dict.c_str()); std::vector<rclcpp::parameter::ParameterVariant> vpv; vpv.push_back(pv); vpv.push_back(pv2); json_dict = std::to_string(vpv); EXPECT_STREQ( "{\"foo\": {\"type\": \"string\", \"value\": \"bar\"}, " "\"foo2\": {\"type\": \"string\", \"value\": \"bar2\"}}", json_dict.c_str()); pv = rclcpp::parameter::ParameterVariant("foo", 2.1); // TODO(tfoote) convert the value to a float and use epsilon test. EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"double\", \"value\": \"2.100000\"}", std::to_string(pv).c_str()); pv = rclcpp::parameter::ParameterVariant("foo", 8); EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"8\"}", std::to_string(pv).c_str()); } TEST(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_synchronous) { auto node = rclcpp::Node::make_shared(std::string("test_parameters_")); // TODO(esteve): Make the parameter service automatically start with the node. auto parameter_service = std::make_shared<rclcpp::parameter_service::ParameterService>(node); auto parameters_client = std::make_shared<rclcpp::parameter_client::SyncParametersClient>(node); set_test_parameters(parameters_client); verify_test_parameters(parameters_client); } TEST(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_asynchronous) { auto node = rclcpp::Node::make_shared(std::string("test_parameters_")); // TODO(esteve): Make the parameter service automatically start with the node. auto parameter_service = std::make_shared<rclcpp::parameter_service::ParameterService>(node); auto parameters_client = std::make_shared<rclcpp::parameter_client::AsyncParametersClient>(node); verify_set_parameters_async(node, parameters_client); verify_get_parameters_async(node, parameters_client); } int main(int argc, char ** argv) { // NOTE: use custom main to ensure that rclcpp::init is called only once rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Fix cpplint warnings
Fix cpplint warnings
C++
apache-2.0
ros2/system_tests,ros2/system_tests
67d8c168de0cecdfe462bb533e88c4830ffe5625
src/exodus/test/script_extraction_tests.cpp
src/exodus/test/script_extraction_tests.cpp
#include "../script.h" #include "../../base58.h" #include "../../pubkey.h" #include "../../utilstrencodings.h" #include "../../script/script.h" #include "../../test/test_bitcoin.h" #include <boost/test/unit_test.hpp> #include <string> #include <vector> namespace exodus { BOOST_FIXTURE_TEST_SUITE(exodus_script_extraction_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(extract_pubkey_test) { std::vector<unsigned char> vchPayload = ParseHex( "0347d08029b5cbc934f6079b650c50718eab5a56d51cf6b742ec9f865a41fcfca3"); CPubKey pubKey(vchPayload.begin(), vchPayload.end()); // Pay-to-pubkey script CScript script; script << ToByteVector(pubKey) << OP_CHECKSIG; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_PUBKEY); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(HexStr(solutions[0]), HexStr(vchPayload)); } BOOST_AUTO_TEST_CASE(extract_pubkeyhash_test) { std::vector<unsigned char> vchPayload = ParseHex( "0347d08029b5cbc934f6079b650c50718eab5a56d51cf6b742ec9f865a41fcfca3"); CPubKey pubKey(vchPayload.begin(), vchPayload.end()); CKeyID keyId = pubKey.GetID(); // Pay-to-pubkey-hash script CScript script; script << OP_DUP << OP_HASH160 << ToByteVector(keyId) << OP_EQUALVERIFY << OP_CHECKSIG; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_PUBKEYHASH); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(HexStr(solutions[0]), HexStr(ToByteVector(keyId))); } BOOST_AUTO_TEST_CASE(extract_multisig_test) { std::vector<unsigned char> vchPayload1 = ParseHex( "03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd"); std::vector<unsigned char> vchPayload2 = ParseHex( "0276f798620d7d0930711ab68688fc67ee2f5bbe0c1481506b08bd65e6053c16ca"); std::vector<unsigned char> vchPayload3 = ParseHex( "02bf12b315172dc1b261d62dd146868ef9c9e2e108fa347f347f66bc048e9b15e4"); CPubKey pubKey1(vchPayload1.begin(), vchPayload1.end()); CPubKey pubKey2(vchPayload2.begin(), vchPayload2.end()); CPubKey pubKey3(vchPayload3.begin(), vchPayload3.end()); // 1-of-3 bare multisig script CScript script; script << CScript::EncodeOP_N(1); script << ToByteVector(pubKey1) << ToByteVector(pubKey2) << ToByteVector(pubKey3); script << CScript::EncodeOP_N(3); script << OP_CHECKMULTISIG; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_MULTISIG); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 3); BOOST_CHECK_EQUAL(HexStr(solutions[0]), HexStr(vchPayload1)); BOOST_CHECK_EQUAL(HexStr(solutions[1]), HexStr(vchPayload2)); BOOST_CHECK_EQUAL(HexStr(solutions[2]), HexStr(vchPayload3)); } BOOST_AUTO_TEST_CASE(extract_scripthash_test) { std::vector<unsigned char> vchInnerScript = ParseHex( "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000"); // A transaction puzzle (not relevant) CScript scriptInner; scriptInner << OP_HASH256 << vchInnerScript << OP_EQUAL; // The actual hash CScriptID innerId(scriptInner); // Pay-to-script-hash script CScript script; script << OP_HASH160 << ToByteVector(innerId) << OP_EQUAL; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_SCRIPTHASH); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(HexStr(solutions[0]), HexStr(ToByteVector(innerId))); } BOOST_AUTO_TEST_CASE(extract_no_nulldata_test) { // Null data script CScript script; script << OP_RETURN; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 0); } BOOST_AUTO_TEST_CASE(extract_empty_nulldata_test) { // Null data script CScript script; script << OP_RETURN << ParseHex(""); // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(solutions[0].size(), 0); } BOOST_AUTO_TEST_CASE(extract_nulldata_test) { std::vector<unsigned char> vchPayload = ParseHex( "657874726163745f6e756c6c646174615f74657374"); // Null data script CScript script; script << OP_RETURN << vchPayload; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(HexStr(solutions[0]), HexStr(vchPayload)); } BOOST_AUTO_TEST_CASE(extract_nulldata_multipush_test) { std::vector<std::string> vstrPayloads; vstrPayloads.push_back("6f6d"); vstrPayloads.push_back("00000000000000010000000006dac2c0"); vstrPayloads.push_back("01d84bcec5b65aa1a03d6abfd975824c75856a2961"); vstrPayloads.push_back("00000000000000030000000000000d48"); vstrPayloads.push_back("05627138bb55251bfb289a1ec390eafd3755b1a698"); vstrPayloads.push_back("00000032010001000000005465737473004f6d6e6920436f726500546573" "7420546f6b656e7300687474703a2f2f6275696c6465722e62697477617463682e636f2f005" "573656420746f2074657374207468652065787472616374696f6e206f66206d756c7469706c" "652070757368657320696e20616e204f505f52455455524e207363726970742e00000000000" "00f4240"); // Null data script CScript script; script << OP_RETURN; for (unsigned n = 0; n < vstrPayloads.size(); ++n) { script << ParseHex(vstrPayloads[n]); } // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), vstrPayloads.size()); for (unsigned n = 0; n < solutions.size(); ++n) { BOOST_CHECK_EQUAL(HexStr(solutions[n]), vstrPayloads[n]); } } BOOST_AUTO_TEST_CASE(extract_anypush_test) { std::vector<std::vector<unsigned char> > vvchPayloads; vvchPayloads.push_back(ParseHex("111111")); vvchPayloads.push_back(ParseHex("222222")); vvchPayloads.push_back(ParseHex("333333")); vvchPayloads.push_back(ParseHex("444444")); vvchPayloads.push_back(ParseHex("555555")); // Non-standard script CScript script; script << vvchPayloads[0] << OP_DROP; script << vvchPayloads[1] << OP_DROP; script << vvchPayloads[2] << OP_DROP; script << vvchPayloads[3] << OP_DROP; script << vvchPayloads[4]; // Check script type txnouttype outtype; BOOST_CHECK(!GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NONSTANDARD); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), vvchPayloads.size()); for (size_t n = 0; n < solutions.size(); ++n) { BOOST_CHECK_EQUAL(HexStr(solutions[n]), HexStr(vvchPayloads[n])); } } BOOST_AUTO_TEST_SUITE_END() } // namespace exodus
#include "../script.h" #include "../../base58.h" #include "../../pubkey.h" #include "../../utilstrencodings.h" #include "../../script/script.h" #include "../../test/test_bitcoin.h" #include <boost/test/unit_test.hpp> #include <ostream> #include <string> #include <vector> namespace std { template<typename Char, typename Traits, typename Allocator> basic_ostream<Char, Traits>& operator<<(basic_ostream<Char, Traits>& os, const std::vector<unsigned char, Allocator>& v) { return os << HexStr(v); } } // namespace std namespace exodus { BOOST_FIXTURE_TEST_SUITE(exodus_script_extraction_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(extract_pubkey_test) { std::vector<unsigned char> vchPayload = ParseHex( "0347d08029b5cbc934f6079b650c50718eab5a56d51cf6b742ec9f865a41fcfca3"); CPubKey pubKey(vchPayload.begin(), vchPayload.end()); // Pay-to-pubkey script CScript script; script << ToByteVector(pubKey) << OP_CHECKSIG; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_PUBKEY); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(solutions[0], vchPayload); } BOOST_AUTO_TEST_CASE(extract_pubkeyhash_test) { std::vector<unsigned char> vchPayload = ParseHex( "0347d08029b5cbc934f6079b650c50718eab5a56d51cf6b742ec9f865a41fcfca3"); CPubKey pubKey(vchPayload.begin(), vchPayload.end()); CKeyID keyId = pubKey.GetID(); // Pay-to-pubkey-hash script CScript script; script << OP_DUP << OP_HASH160 << ToByteVector(keyId) << OP_EQUALVERIFY << OP_CHECKSIG; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_PUBKEYHASH); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(solutions[0], ToByteVector(keyId)); } BOOST_AUTO_TEST_CASE(extract_multisig_test) { std::vector<unsigned char> vchPayload1 = ParseHex( "03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd"); std::vector<unsigned char> vchPayload2 = ParseHex( "0276f798620d7d0930711ab68688fc67ee2f5bbe0c1481506b08bd65e6053c16ca"); std::vector<unsigned char> vchPayload3 = ParseHex( "02bf12b315172dc1b261d62dd146868ef9c9e2e108fa347f347f66bc048e9b15e4"); CPubKey pubKey1(vchPayload1.begin(), vchPayload1.end()); CPubKey pubKey2(vchPayload2.begin(), vchPayload2.end()); CPubKey pubKey3(vchPayload3.begin(), vchPayload3.end()); // 1-of-3 bare multisig script CScript script; script << CScript::EncodeOP_N(1); script << ToByteVector(pubKey1) << ToByteVector(pubKey2) << ToByteVector(pubKey3); script << CScript::EncodeOP_N(3); script << OP_CHECKMULTISIG; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_MULTISIG); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 3); BOOST_CHECK_EQUAL(solutions[0], vchPayload1); BOOST_CHECK_EQUAL(solutions[1], vchPayload2); BOOST_CHECK_EQUAL(solutions[2], vchPayload3); } BOOST_AUTO_TEST_CASE(extract_scripthash_test) { std::vector<unsigned char> vchInnerScript = ParseHex( "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000"); // A transaction puzzle (not relevant) CScript scriptInner; scriptInner << OP_HASH256 << vchInnerScript << OP_EQUAL; // The actual hash CScriptID innerId(scriptInner); // Pay-to-script-hash script CScript script; script << OP_HASH160 << ToByteVector(innerId) << OP_EQUAL; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_SCRIPTHASH); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(solutions[0], ToByteVector(innerId)); } BOOST_AUTO_TEST_CASE(extract_no_nulldata_test) { // Null data script CScript script; script << OP_RETURN; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 0); } BOOST_AUTO_TEST_CASE(extract_empty_nulldata_test) { // Null data script CScript script; script << OP_RETURN << ParseHex(""); // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(solutions[0].size(), 0); } BOOST_AUTO_TEST_CASE(extract_nulldata_test) { std::vector<unsigned char> vchPayload = ParseHex( "657874726163745f6e756c6c646174615f74657374"); // Null data script CScript script; script << OP_RETURN << vchPayload; // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), 1); BOOST_CHECK_EQUAL(solutions[0], vchPayload); } BOOST_AUTO_TEST_CASE(extract_nulldata_multipush_test) { std::vector<std::string> vstrPayloads; vstrPayloads.push_back("6f6d"); vstrPayloads.push_back("00000000000000010000000006dac2c0"); vstrPayloads.push_back("01d84bcec5b65aa1a03d6abfd975824c75856a2961"); vstrPayloads.push_back("00000000000000030000000000000d48"); vstrPayloads.push_back("05627138bb55251bfb289a1ec390eafd3755b1a698"); vstrPayloads.push_back("00000032010001000000005465737473004f6d6e6920436f726500546573" "7420546f6b656e7300687474703a2f2f6275696c6465722e62697477617463682e636f2f005" "573656420746f2074657374207468652065787472616374696f6e206f66206d756c7469706c" "652070757368657320696e20616e204f505f52455455524e207363726970742e00000000000" "00f4240"); // Null data script CScript script; script << OP_RETURN; for (unsigned n = 0; n < vstrPayloads.size(); ++n) { script << ParseHex(vstrPayloads[n]); } // Check script type txnouttype outtype; BOOST_CHECK(GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NULL_DATA); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), vstrPayloads.size()); for (unsigned n = 0; n < solutions.size(); ++n) { BOOST_CHECK_EQUAL(HexStr(solutions[n]), vstrPayloads[n]); } } BOOST_AUTO_TEST_CASE(extract_anypush_test) { std::vector<std::vector<unsigned char> > vvchPayloads; vvchPayloads.push_back(ParseHex("111111")); vvchPayloads.push_back(ParseHex("222222")); vvchPayloads.push_back(ParseHex("333333")); vvchPayloads.push_back(ParseHex("444444")); vvchPayloads.push_back(ParseHex("555555")); // Non-standard script CScript script; script << vvchPayloads[0] << OP_DROP; script << vvchPayloads[1] << OP_DROP; script << vvchPayloads[2] << OP_DROP; script << vvchPayloads[3] << OP_DROP; script << vvchPayloads[4]; // Check script type txnouttype outtype; BOOST_CHECK(!GetOutputType(script, outtype)); BOOST_CHECK_EQUAL(outtype, TX_NONSTANDARD); // Confirm extracted data std::vector<std::vector<unsigned char>> solutions; GetPushedValues(script, std::back_inserter(solutions)); BOOST_CHECK_EQUAL(solutions.size(), vvchPayloads.size()); for (size_t n = 0; n < solutions.size(); ++n) { BOOST_CHECK_EQUAL(solutions[n], vvchPayloads[n]); } } BOOST_AUTO_TEST_SUITE_END() } // namespace exodus
Refactor exodus_script_extraction_tests
Refactor exodus_script_extraction_tests
C++
mit
zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin,zcoinofficial/zcoin
fca8b707516376102df236ae4a63039ec7fdf045
ConnectedComponentSegmentation/otbConnectedComponentSegmentation.cxx
ConnectedComponentSegmentation/otbConnectedComponentSegmentation.cxx
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConnectedComponentSegmentation.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbVectorData.h" #include "otbImageFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbStreamingConnectedComponentSegmentationOBIAToVectorDataFilter.h" #include "otbStandardFilterWatcher.h" namespace otb { int ConnectedComponentSegmentation::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("Connected Component Segmentation"); descriptor->SetDescription( "Connected Component Segmentation, which take mathematical formula as an Neighborhood thresholding criteria."); descriptor->AddInputImage(); descriptor->AddOption("OutputVectorData", "Output Shape file name", "outshape", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("MaskExpression", "Mask expression (only if support image is given)", "maskexpression", 1, false, ApplicationDescriptor::String); descriptor->AddOption("ConnectedComponentExpression", "Formula used for connected component segmentation", "expression", 1, true, ApplicationDescriptor::String); descriptor->AddOption("MinimumObjectSize", "Min object size (area in pixel)", "minsize", 1, false, ApplicationDescriptor::Real); descriptor->AddOption("OBIAExpression", "OBIA Mu Parser expression", "OBIAexpression", 1, false, ApplicationDescriptor::String); return EXIT_SUCCESS; } int ConnectedComponentSegmentation::Execute(otb::ApplicationOptionsResult* parseResult) { typedef float InputPixelType; const unsigned int Dimension = 2; typedef otb::VectorImage<InputPixelType, Dimension> InputVectorImageType; typedef otb::Image<unsigned int, Dimension> LabelImageType; typedef otb::Image<unsigned int, Dimension> MaskImageType; typedef otb::ImageFileReader<InputVectorImageType> ReaderType; typedef otb::VectorData<double, Dimension> VectorDataType; typedef VectorDataType::Pointer VectorDataPointerType; typedef otb::VectorDataFileWriter<VectorDataType> VectorDataFileWriterType; typedef VectorDataFileWriterType::Pointer VectorDataFileWriterPointerType; typedef otb::StreamingConnectedComponentSegmentationOBIAToVectorDataFilter < InputVectorImageType, LabelImageType, MaskImageType, VectorDataType > ConnectedComponentSegmentationOBIAToVectorDataFilterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(parseResult->GetInputImage()); reader->UpdateOutputInformation(); ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::Pointer connected = ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::New(); connected->GetFilter()->SetInput(reader->GetOutput()); if (parseResult->IsOptionPresent("MaskExpression")) connected->GetFilter()->SetMaskExpression(parseResult->GetParameterString("MaskExpression")); connected->GetFilter()->SetConnectedComponentExpression(parseResult->GetParameterString("ConnectedComponentExpression")); if (parseResult->IsOptionPresent("MinimumObjectSize")) connected->GetFilter()->SetMinimumObjectSize(parseResult->GetParameterInt("MinimumObjectSize")); else connected->GetFilter()->SetMinimumObjectSize(2); if (parseResult->IsOptionPresent("OBIAExpression")) connected->GetFilter()->SetOBIAExpression(parseResult->GetParameterString("OBIAExpression")); otb::StandardFilterWatcher watcher(connected->GetStreamer(),"Segmentation"); connected->Update(); VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New(); vdwriter->SetInput(connected->GetFilter()->GetOutputVectorData()); vdwriter->SetFileName(parseResult->GetParameterString("OutputVectorData")); vdwriter->Update(); return EXIT_SUCCESS; } }
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConnectedComponentSegmentation.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbVectorData.h" #include "otbImageFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbStreamingConnectedComponentSegmentationOBIAToVectorDataFilter.h" #include "otbStandardFilterWatcher.h" #include "otbVectorDataProjectionFilter.h" #include "otbVectorDataTransformFilter.h" #include "itkAffineTransform.h" namespace otb { int ConnectedComponentSegmentation::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("Connected Component Segmentation"); descriptor->SetDescription( "Connected Component Segmentation, which take mathematical formula as an Neighborhood thresholding criteria."); descriptor->AddInputImage(); descriptor->AddOption("OutputVectorData", "Output Shape file name", "outshape", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("MaskExpression", "Mask expression (only if support image is given)", "maskexpression", 1, false, ApplicationDescriptor::String); descriptor->AddOption("ConnectedComponentExpression", "Formula used for connected component segmentation", "expression", 1, true, ApplicationDescriptor::String); descriptor->AddOption("MinimumObjectSize", "Min object size (area in pixel)", "minsize", 1, false, ApplicationDescriptor::Real); descriptor->AddOption("OBIAExpression", "OBIA Mu Parser expression", "OBIAexpression", 1, false, ApplicationDescriptor::String); descriptor->AddOption("DEMDirectory", "DEM directory (used to reproject output in WGS84 if input image is in sensor model geometry)", "dem", 1, false, ApplicationDescriptor::DirectoryName); return EXIT_SUCCESS; } int ConnectedComponentSegmentation::Execute(otb::ApplicationOptionsResult* parseResult) { typedef float InputPixelType; const unsigned int Dimension = 2; typedef otb::VectorImage<InputPixelType, Dimension> InputVectorImageType; typedef otb::Image<unsigned int, Dimension> LabelImageType; typedef otb::Image<unsigned int, Dimension> MaskImageType; typedef otb::ImageFileReader<InputVectorImageType> ReaderType; typedef otb::VectorData<double, Dimension> VectorDataType; typedef VectorDataType::Pointer VectorDataPointerType; typedef otb::VectorDataFileWriter<VectorDataType> VectorDataFileWriterType; typedef VectorDataFileWriterType::Pointer VectorDataFileWriterPointerType; typedef otb::StreamingConnectedComponentSegmentationOBIAToVectorDataFilter < InputVectorImageType, LabelImageType, MaskImageType, VectorDataType > ConnectedComponentSegmentationOBIAToVectorDataFilterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(parseResult->GetInputImage()); reader->UpdateOutputInformation(); InputVectorImageType::Pointer inputImage = reader->GetOutput(); ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::Pointer connected = ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::New(); connected->GetFilter()->SetInput(inputImage); if (parseResult->IsOptionPresent("MaskExpression")) connected->GetFilter()->SetMaskExpression(parseResult->GetParameterString("MaskExpression")); connected->GetFilter()->SetConnectedComponentExpression(parseResult->GetParameterString("ConnectedComponentExpression")); if (parseResult->IsOptionPresent("MinimumObjectSize")) connected->GetFilter()->SetMinimumObjectSize(parseResult->GetParameterInt("MinimumObjectSize")); else connected->GetFilter()->SetMinimumObjectSize(2); if (parseResult->IsOptionPresent("OBIAExpression")) connected->GetFilter()->SetOBIAExpression(parseResult->GetParameterString("OBIAExpression")); otb::StandardFilterWatcher watcher(connected->GetStreamer(),"Segmentation"); connected->Update(); /* * Reprojection of the output VectorData * * The output of LSDFilterType is in image index coordinates * * 3 cases : * - input image has no geo-information : pass through * - input image is in cartographic projection : apply image spacing and origin, and set the ProjectionRef * - input image is in sensor model geometry : reproject in WGS84 * */ /* * Reprojection of the output VectorData * * The output of LSDFilterType is in image physical coordinates, * projection WKT applied if the input image has one * * We need to reproject in WGS84 if the input image is in sensor model geometry */ std::string projRef = inputImage->GetProjectionRef(); ImageKeywordlist kwl = inputImage->GetImageKeywordlist(); VectorDataType::Pointer vd = connected->GetFilter()->GetOutputVectorData(); VectorDataType::Pointer projectedVD = vd; if ( projRef.empty() && kwl.GetSize() > 0 ) { // image is in sensor model geometry // Reproject VectorData in image projection typedef otb::VectorDataProjectionFilter <VectorDataType, VectorDataType> VectorDataProjectionFilterType; VectorDataProjectionFilterType::Pointer vproj = VectorDataProjectionFilterType::New(); vproj->SetInput(vd); vproj->SetInputKeywordList(inputImage->GetImageKeywordlist()); vproj->SetInputOrigin(inputImage->GetOrigin()); vproj->SetInputSpacing(inputImage->GetSpacing()); if( parseResult->IsOptionPresent("DEMDirectory") ) { vproj->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory")); } vproj->Update(); projectedVD = vproj->GetOutput(); } VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New(); vdwriter->SetInput(projectedVD); vdwriter->SetFileName(parseResult->GetParameterString("OutputVectorData")); vdwriter->Update(); return EXIT_SUCCESS; } }
add VD reprojection only if input image is in sensor model geometry
ENH: add VD reprojection only if input image is in sensor model geometry
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
8aec124cf0e2b9fd4839c35d221f6a05bef3c576
src/gpu/tessellate/GrPathStencilCoverOp.cpp
src/gpu/tessellate/GrPathStencilCoverOp.cpp
/* * Copyright 2021 Google LLC. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/tessellate/GrPathStencilCoverOp.h" #include "src/gpu/GrDefaultGeoProcFactory.h" #include "src/gpu/GrEagerVertexAllocator.h" #include "src/gpu/GrGpu.h" #include "src/gpu/GrOpFlushState.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrResourceProvider.h" #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h" #include "src/gpu/tessellate/GrMiddleOutPolygonTriangulator.h" #include "src/gpu/tessellate/GrPathCurveTessellator.h" #include "src/gpu/tessellate/GrPathWedgeTessellator.h" #include "src/gpu/tessellate/GrTessellationPathRenderer.h" #include "src/gpu/tessellate/shaders/GrPathTessellationShader.h" using PathFlags = GrTessellationPathRenderer::PathFlags; namespace { // Fills a path's bounding box, with subpixel outset to avoid possible T-junctions with extreme // edges of the path. // NOTE: The emitted geometry may not be axis-aligned, depending on the view matrix. class BoundingBoxShader : public GrPathTessellationShader { public: BoundingBoxShader(const SkMatrix& viewMatrix, SkPMColor4f color, const GrShaderCaps& shaderCaps) : GrPathTessellationShader(kTessellate_BoundingBoxShader_ClassID, GrPrimitiveType::kTriangleStrip, 0, viewMatrix, color) { constexpr static Attribute kPathBoundsAttrib("pathBounds", kFloat4_GrVertexAttribType, kFloat4_GrSLType); this->setInstanceAttributes(&kPathBoundsAttrib, 1); if (!shaderCaps.vertexIDSupport()) { constexpr static Attribute kUnitCoordAttrib("unitCoord", kFloat2_GrVertexAttribType, kFloat2_GrSLType); this->setVertexAttributes(&kUnitCoordAttrib, 1); } } private: const char* name() const final { return "tessellate_BoundingBoxShader"; } void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const final {} GrGLSLGeometryProcessor* createGLSLInstance(const GrShaderCaps&) const final; }; GrGLSLGeometryProcessor* BoundingBoxShader::createGLSLInstance(const GrShaderCaps&) const { class Impl : public GrPathTessellationShader::Impl { void emitVertexCode(const GrShaderCaps& shaderCaps, const GrPathTessellationShader&, GrGLSLVertexBuilder* v, GrGPArgs* gpArgs) override { if (shaderCaps.vertexIDSupport()) { // If we don't have sk_VertexID support then "unitCoord" already came in as a vertex // attrib. v->codeAppendf(R"( float2 unitCoord = float2(sk_VertexID & 1, sk_VertexID >> 1);)"); } v->codeAppend(R"( // Bloat the bounding box by 1/4px to avoid potential T-junctions at the edges. float2x2 M_ = inverse(AFFINE_MATRIX); float2 bloat = float2(abs(M_[0]) + abs(M_[1])) * .25; // Find the vertex position. float2 localcoord = mix(pathBounds.xy - bloat, pathBounds.zw + bloat, unitCoord); float2 vertexpos = AFFINE_MATRIX * localcoord + TRANSLATE;)"); gpArgs->fLocalCoordVar.set(kFloat2_GrSLType, "localcoord"); gpArgs->fPositionVar.set(kFloat2_GrSLType, "vertexpos"); } }; return new Impl; } } // namespace void GrPathStencilCoverOp::visitProxies(const GrVisitProxyFunc& func) const { if (fCoverBBoxProgram) { fCoverBBoxProgram->pipeline().visitProxies(func); } else { fProcessors.visitProxies(func); } } GrDrawOp::FixedFunctionFlags GrPathStencilCoverOp::fixedFunctionFlags() const { auto flags = FixedFunctionFlags::kUsesStencil; if (fAAType != GrAAType::kNone) { flags |= FixedFunctionFlags::kUsesHWAA; } return flags; } GrProcessorSet::Analysis GrPathStencilCoverOp::finalize(const GrCaps& caps, const GrAppliedClip* clip, GrClampType clampType) { return fProcessors.finalize(fColor, GrProcessorAnalysisCoverage::kNone, clip, nullptr, caps, clampType, &fColor); } void GrPathStencilCoverOp::prePreparePrograms(const GrTessellationShader::ProgramArgs& args, GrAppliedClip&& appliedClip) { SkASSERT(!fTessellator); SkASSERT(!fStencilFanProgram); SkASSERT(!fStencilPathProgram); SkASSERT(!fCoverBBoxProgram); const GrPipeline* stencilPipeline = GrPathTessellationShader::MakeStencilOnlyPipeline( args, fAAType, fPathFlags, appliedClip.hardClip()); const GrUserStencilSettings* stencilPathSettings = GrPathTessellationShader::StencilPathSettings(GrFillRuleForSkPath(fPath)); if (fPath.countVerbs() > 50 && this->bounds().height() * this->bounds().width() > 256 * 256) { // Large complex paths do better with a dedicated triangle shader for the inner fan. // This takes less PCI bus bandwidth (6 floats per triangle instead of 8) and allows us // to make sure it has an efficient middle-out topology. auto triangleGP = GrDefaultGeoProcFactory::Make( args.fArena, GrDefaultGeoProcFactory::Color(SK_PMColor4fTRANSPARENT), GrDefaultGeoProcFactory::Coverage::kSolid_Type, GrDefaultGeoProcFactory::LocalCoords::kUnused_Type, fViewMatrix); fStencilFanProgram = GrSimpleMeshDrawOpHelper::CreateProgramInfo( args.fArena, stencilPipeline, args.fWriteView, triangleGP, GrPrimitiveType::kTriangles, args.fXferBarrierFlags, args.fColorLoadOp, stencilPathSettings); fTessellator = GrPathCurveTessellator::Make(args.fArena, fViewMatrix, SK_PMColor4fTRANSPARENT, GrPathCurveTessellator::DrawInnerFan::kNo, fPath.countVerbs(), *stencilPipeline, *args.fCaps); } else { fTessellator = GrPathWedgeTessellator::Make(args.fArena, fViewMatrix, SK_PMColor4fTRANSPARENT, fPath.countVerbs(), *stencilPipeline, *args.fCaps); } fStencilPathProgram = GrTessellationShader::MakeProgram(args, fTessellator->shader(), stencilPipeline, stencilPathSettings); if (!(fPathFlags & PathFlags::kStencilOnly)) { // Create a program that draws a bounding box over the path and fills its stencil coverage // into the color buffer. auto* bboxShader = args.fArena->make<BoundingBoxShader>(fViewMatrix, fColor, *args.fCaps->shaderCaps()); auto* bboxPipeline = GrTessellationShader::MakePipeline(args, fAAType, std::move(appliedClip), std::move(fProcessors)); auto* bboxStencil = GrPathTessellationShader::TestAndResetStencilSettings(fPath.isInverseFillType()); fCoverBBoxProgram = GrTessellationShader::MakeProgram(args, bboxShader, bboxPipeline, bboxStencil); } } void GrPathStencilCoverOp::onPrePrepare(GrRecordingContext* context, const GrSurfaceProxyView& writeView, GrAppliedClip* clip, const GrDstProxyView& dstProxyView, GrXferBarrierFlags renderPassXferBarriers, GrLoadOp colorLoadOp) { this->prePreparePrograms({context->priv().recordTimeAllocator(), writeView, &dstProxyView, renderPassXferBarriers, colorLoadOp, context->priv().caps()}, (clip) ? std::move(*clip) : GrAppliedClip::Disabled()); if (fStencilFanProgram) { context->priv().recordProgramInfo(fStencilFanProgram); } if (fStencilPathProgram) { context->priv().recordProgramInfo(fStencilPathProgram); } if (fCoverBBoxProgram) { context->priv().recordProgramInfo(fCoverBBoxProgram); } } GR_DECLARE_STATIC_UNIQUE_KEY(gUnitQuadBufferKey); void GrPathStencilCoverOp::onPrepare(GrOpFlushState* flushState) { if (!fTessellator) { this->prePreparePrograms({flushState->allocator(), flushState->writeView(), &flushState->dstProxyView(), flushState->renderPassBarriers(), flushState->colorLoadOp(), &flushState->caps()}, flushState->detachAppliedClip()); if (!fTessellator) { return; } } if (fStencilFanProgram) { // The inner fan isn't built into the tessellator. Generate a standard Redbook fan with a // middle-out topology. GrEagerDynamicVertexAllocator vertexAlloc(flushState, &fFanBuffer, &fFanBaseVertex); int maxFanTriangles = fPath.countVerbs() - 2; // n - 2 triangles make an n-gon. GrVertexWriter triangleVertexWriter = vertexAlloc.lock<SkPoint>(maxFanTriangles * 3); fFanVertexCount = 3 * GrMiddleOutPolygonTriangulator::WritePathInnerFan( &triangleVertexWriter, 0, 0, fPath); SkASSERT(fFanVertexCount <= maxFanTriangles * 3); vertexAlloc.unlock(fFanVertexCount); } fTessellator->prepare(flushState, this->bounds(), fPath); if (fCoverBBoxProgram) { GrVertexWriter vertexWriter = flushState->makeVertexSpace(sizeof(SkRect), 1, &fBBoxBuffer, &fBBoxBaseInstance); if (fPath.isInverseFillType()) { // Fill the entire backing store to make sure we clear every stencil value back to 0. If // there is a scissor it will have already clipped the stencil draw. auto rtBounds = flushState->writeView().asRenderTargetProxy()->backingStoreBoundsRect(); SkASSERT(rtBounds == fOriginalDrawBounds); SkRect pathSpaceRTBounds; if (SkMatrixPriv::InverseMapRect(fViewMatrix, &pathSpaceRTBounds, rtBounds)) { vertexWriter.write(pathSpaceRTBounds); } else { vertexWriter.write(fPath.getBounds()); } } else { vertexWriter.write(fPath.getBounds()); } } if (!flushState->caps().shaderCaps()->vertexIDSupport()) { constexpr static SkPoint kUnitQuad[4] = {{0,0}, {0,1}, {1,0}, {1,1}}; GR_DEFINE_STATIC_UNIQUE_KEY(gUnitQuadBufferKey); fBBoxVertexBufferIfNoIDSupport = flushState->resourceProvider()->findOrMakeStaticBuffer( GrGpuBufferType::kVertex, sizeof(kUnitQuad), kUnitQuad, gUnitQuadBufferKey); } } void GrPathStencilCoverOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) { if (!fTessellator) { return; } // Stencil the inner fan, if any. if (fFanVertexCount > 0) { SkASSERT(fStencilFanProgram); SkASSERT(fFanBuffer); flushState->bindPipelineAndScissorClip(*fStencilFanProgram, this->bounds()); flushState->bindBuffers(nullptr, nullptr, fFanBuffer); flushState->draw(fFanVertexCount, fFanBaseVertex); } // Stencil the rest of the path. SkASSERT(fStencilPathProgram); flushState->bindPipelineAndScissorClip(*fStencilPathProgram, this->bounds()); fTessellator->draw(flushState); if (flushState->caps().requiresManualFBBarrierAfterTessellatedStencilDraw()) { flushState->gpu()->insertManualFramebufferBarrier(); // http://skbug.com/9739 } // Fill in the bounding box (if not in stencil-only mode). if (fCoverBBoxProgram) { flushState->bindPipelineAndScissorClip(*fCoverBBoxProgram, this->bounds()); flushState->bindTextures(fCoverBBoxProgram->geomProc(), nullptr, fCoverBBoxProgram->pipeline()); flushState->bindBuffers(nullptr, fBBoxBuffer, fBBoxVertexBufferIfNoIDSupport); flushState->drawInstanced(1, fBBoxBaseInstance, 4, 0); } }
/* * Copyright 2021 Google LLC. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/tessellate/GrPathStencilCoverOp.h" #include "src/gpu/GrDefaultGeoProcFactory.h" #include "src/gpu/GrEagerVertexAllocator.h" #include "src/gpu/GrGpu.h" #include "src/gpu/GrOpFlushState.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrResourceProvider.h" #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h" #include "src/gpu/glsl/GrGLSLVarying.h" #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h" #include "src/gpu/tessellate/GrMiddleOutPolygonTriangulator.h" #include "src/gpu/tessellate/GrPathCurveTessellator.h" #include "src/gpu/tessellate/GrPathWedgeTessellator.h" #include "src/gpu/tessellate/GrTessellationPathRenderer.h" #include "src/gpu/tessellate/shaders/GrPathTessellationShader.h" using PathFlags = GrTessellationPathRenderer::PathFlags; namespace { // Fills a path's bounding box, with subpixel outset to avoid possible T-junctions with extreme // edges of the path. // NOTE: The emitted geometry may not be axis-aligned, depending on the view matrix. class BoundingBoxShader : public GrGeometryProcessor { public: BoundingBoxShader(const SkMatrix& viewMatrix, SkPMColor4f color, const GrShaderCaps& shaderCaps) : GrGeometryProcessor(kTessellate_BoundingBoxShader_ClassID) , fViewMatrix(viewMatrix) , fColor(color) { // The 1/4px outset logic does not work with perspective yet. SkASSERT(!fViewMatrix.hasPerspective()); if (!shaderCaps.vertexIDSupport()) { constexpr static Attribute kUnitCoordAttrib("unitCoord", kFloat2_GrVertexAttribType, kFloat2_GrSLType); this->setVertexAttributes(&kUnitCoordAttrib, 1); } constexpr static Attribute kPathBoundsAttrib("pathBounds", kFloat4_GrVertexAttribType, kFloat4_GrSLType); this->setInstanceAttributes(&kPathBoundsAttrib, 1); } private: const char* name() const final { return "tessellate_BoundingBoxShader"; } void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const final {} GrGLSLGeometryProcessor* createGLSLInstance(const GrShaderCaps&) const final; const SkMatrix fViewMatrix; const SkPMColor4f fColor; }; GrGLSLGeometryProcessor* BoundingBoxShader::createGLSLInstance(const GrShaderCaps&) const { class Impl : public GrGLSLGeometryProcessor { void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final { args.fVaryingHandler->emitAttributes(args.fGeomProc); // Vertex shader. const char* viewMatrix; fViewMatrixUniform = args.fUniformHandler->addUniform(nullptr, kVertex_GrShaderFlag, kFloat3x3_GrSLType, "viewMatrix", &viewMatrix); if (args.fShaderCaps->vertexIDSupport()) { // If we don't have sk_VertexID support then "unitCoord" already came in as a vertex // attrib. args.fVertBuilder->codeAppendf(R"( float2 unitCoord = float2(sk_VertexID & 1, sk_VertexID >> 1);)"); } args.fVertBuilder->codeAppendf(R"( float3x3 VIEW_MATRIX = %s; // Bloat the bounding box by 1/4px to be certain we will reset every stencil value. float2x2 M_ = inverse(float2x2(VIEW_MATRIX)); float2 bloat = float2(abs(M_[0]) + abs(M_[1])) * .25; // Find the vertex position. float2 localcoord = mix(pathBounds.xy - bloat, pathBounds.zw + bloat, unitCoord); float2 vertexpos = (VIEW_MATRIX * float3(localcoord, 1)).xy;)", viewMatrix); gpArgs->fLocalCoordVar.set(kFloat2_GrSLType, "localcoord"); gpArgs->fPositionVar.set(kFloat2_GrSLType, "vertexpos"); // Fragment shader. const char* color; fColorUniform = args.fUniformHandler->addUniform(nullptr, kFragment_GrShaderFlag, kHalf4_GrSLType, "color", &color); args.fFragBuilder->codeAppendf("half4 %s = %s;", args.fOutputColor, color); args.fFragBuilder->codeAppendf("const half4 %s = half4(1);", args.fOutputCoverage); } void setData(const GrGLSLProgramDataManager& pdman, const GrShaderCaps&, const GrGeometryProcessor& gp) override { const auto& bboxShader = gp.cast<BoundingBoxShader>(); pdman.setSkMatrix(fViewMatrixUniform, bboxShader.fViewMatrix); const SkPMColor4f& color = bboxShader.fColor; pdman.set4f(fColorUniform, color.fR, color.fG, color.fB, color.fA); } GrGLSLUniformHandler::UniformHandle fViewMatrixUniform; GrGLSLUniformHandler::UniformHandle fColorUniform; }; return new Impl; } } // namespace void GrPathStencilCoverOp::visitProxies(const GrVisitProxyFunc& func) const { if (fCoverBBoxProgram) { fCoverBBoxProgram->pipeline().visitProxies(func); } else { fProcessors.visitProxies(func); } } GrDrawOp::FixedFunctionFlags GrPathStencilCoverOp::fixedFunctionFlags() const { auto flags = FixedFunctionFlags::kUsesStencil; if (fAAType != GrAAType::kNone) { flags |= FixedFunctionFlags::kUsesHWAA; } return flags; } GrProcessorSet::Analysis GrPathStencilCoverOp::finalize(const GrCaps& caps, const GrAppliedClip* clip, GrClampType clampType) { return fProcessors.finalize(fColor, GrProcessorAnalysisCoverage::kNone, clip, nullptr, caps, clampType, &fColor); } void GrPathStencilCoverOp::prePreparePrograms(const GrTessellationShader::ProgramArgs& args, GrAppliedClip&& appliedClip) { SkASSERT(!fTessellator); SkASSERT(!fStencilFanProgram); SkASSERT(!fStencilPathProgram); SkASSERT(!fCoverBBoxProgram); const GrPipeline* stencilPipeline = GrPathTessellationShader::MakeStencilOnlyPipeline( args, fAAType, fPathFlags, appliedClip.hardClip()); const GrUserStencilSettings* stencilPathSettings = GrPathTessellationShader::StencilPathSettings(GrFillRuleForSkPath(fPath)); if (fPath.countVerbs() > 50 && this->bounds().height() * this->bounds().width() > 256 * 256) { // Large complex paths do better with a dedicated triangle shader for the inner fan. // This takes less PCI bus bandwidth (6 floats per triangle instead of 8) and allows us // to make sure it has an efficient middle-out topology. auto triangleGP = GrDefaultGeoProcFactory::Make( args.fArena, GrDefaultGeoProcFactory::Color(SK_PMColor4fTRANSPARENT), GrDefaultGeoProcFactory::Coverage::kSolid_Type, GrDefaultGeoProcFactory::LocalCoords::kUnused_Type, fViewMatrix); fStencilFanProgram = GrSimpleMeshDrawOpHelper::CreateProgramInfo( args.fArena, stencilPipeline, args.fWriteView, triangleGP, GrPrimitiveType::kTriangles, args.fXferBarrierFlags, args.fColorLoadOp, stencilPathSettings); fTessellator = GrPathCurveTessellator::Make(args.fArena, fViewMatrix, SK_PMColor4fTRANSPARENT, GrPathCurveTessellator::DrawInnerFan::kNo, fPath.countVerbs(), *stencilPipeline, *args.fCaps); } else { fTessellator = GrPathWedgeTessellator::Make(args.fArena, fViewMatrix, SK_PMColor4fTRANSPARENT, fPath.countVerbs(), *stencilPipeline, *args.fCaps); } fStencilPathProgram = GrTessellationShader::MakeProgram(args, fTessellator->shader(), stencilPipeline, stencilPathSettings); if (!(fPathFlags & PathFlags::kStencilOnly)) { // Create a program that draws a bounding box over the path and fills its stencil coverage // into the color buffer. auto* bboxShader = args.fArena->make<BoundingBoxShader>(fViewMatrix, fColor, *args.fCaps->shaderCaps()); auto* bboxPipeline = GrTessellationShader::MakePipeline(args, fAAType, std::move(appliedClip), std::move(fProcessors)); auto* bboxStencil = GrPathTessellationShader::TestAndResetStencilSettings(fPath.isInverseFillType()); fCoverBBoxProgram = GrSimpleMeshDrawOpHelper::CreateProgramInfo( args.fArena, bboxPipeline, args.fWriteView, bboxShader, GrPrimitiveType::kTriangleStrip, args.fXferBarrierFlags, args.fColorLoadOp, bboxStencil); } } void GrPathStencilCoverOp::onPrePrepare(GrRecordingContext* context, const GrSurfaceProxyView& writeView, GrAppliedClip* clip, const GrDstProxyView& dstProxyView, GrXferBarrierFlags renderPassXferBarriers, GrLoadOp colorLoadOp) { this->prePreparePrograms({context->priv().recordTimeAllocator(), writeView, &dstProxyView, renderPassXferBarriers, colorLoadOp, context->priv().caps()}, (clip) ? std::move(*clip) : GrAppliedClip::Disabled()); if (fStencilFanProgram) { context->priv().recordProgramInfo(fStencilFanProgram); } if (fStencilPathProgram) { context->priv().recordProgramInfo(fStencilPathProgram); } if (fCoverBBoxProgram) { context->priv().recordProgramInfo(fCoverBBoxProgram); } } GR_DECLARE_STATIC_UNIQUE_KEY(gUnitQuadBufferKey); void GrPathStencilCoverOp::onPrepare(GrOpFlushState* flushState) { if (!fTessellator) { this->prePreparePrograms({flushState->allocator(), flushState->writeView(), &flushState->dstProxyView(), flushState->renderPassBarriers(), flushState->colorLoadOp(), &flushState->caps()}, flushState->detachAppliedClip()); if (!fTessellator) { return; } } if (fStencilFanProgram) { // The inner fan isn't built into the tessellator. Generate a standard Redbook fan with a // middle-out topology. GrEagerDynamicVertexAllocator vertexAlloc(flushState, &fFanBuffer, &fFanBaseVertex); int maxFanTriangles = fPath.countVerbs() - 2; // n - 2 triangles make an n-gon. GrVertexWriter triangleVertexWriter = vertexAlloc.lock<SkPoint>(maxFanTriangles * 3); fFanVertexCount = 3 * GrMiddleOutPolygonTriangulator::WritePathInnerFan( &triangleVertexWriter, 0, 0, fPath); SkASSERT(fFanVertexCount <= maxFanTriangles * 3); vertexAlloc.unlock(fFanVertexCount); } fTessellator->prepare(flushState, this->bounds(), fPath); if (fCoverBBoxProgram) { GrVertexWriter vertexWriter = flushState->makeVertexSpace(sizeof(SkRect), 1, &fBBoxBuffer, &fBBoxBaseInstance); if (fPath.isInverseFillType()) { // Fill the entire backing store to make sure we clear every stencil value back to 0. If // there is a scissor it will have already clipped the stencil draw. auto rtBounds = flushState->writeView().asRenderTargetProxy()->backingStoreBoundsRect(); SkASSERT(rtBounds == fOriginalDrawBounds); SkRect pathSpaceRTBounds; if (SkMatrixPriv::InverseMapRect(fViewMatrix, &pathSpaceRTBounds, rtBounds)) { vertexWriter.write(pathSpaceRTBounds); } else { vertexWriter.write(fPath.getBounds()); } } else { vertexWriter.write(fPath.getBounds()); } } if (!flushState->caps().shaderCaps()->vertexIDSupport()) { constexpr static SkPoint kUnitQuad[4] = {{0,0}, {0,1}, {1,0}, {1,1}}; GR_DEFINE_STATIC_UNIQUE_KEY(gUnitQuadBufferKey); fBBoxVertexBufferIfNoIDSupport = flushState->resourceProvider()->findOrMakeStaticBuffer( GrGpuBufferType::kVertex, sizeof(kUnitQuad), kUnitQuad, gUnitQuadBufferKey); } } void GrPathStencilCoverOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) { if (!fTessellator) { return; } // Stencil the inner fan, if any. if (fFanVertexCount > 0) { SkASSERT(fStencilFanProgram); SkASSERT(fFanBuffer); flushState->bindPipelineAndScissorClip(*fStencilFanProgram, this->bounds()); flushState->bindBuffers(nullptr, nullptr, fFanBuffer); flushState->draw(fFanVertexCount, fFanBaseVertex); } // Stencil the rest of the path. SkASSERT(fStencilPathProgram); flushState->bindPipelineAndScissorClip(*fStencilPathProgram, this->bounds()); fTessellator->draw(flushState); if (flushState->caps().requiresManualFBBarrierAfterTessellatedStencilDraw()) { flushState->gpu()->insertManualFramebufferBarrier(); // http://skbug.com/9739 } // Fill in the bounding box (if not in stencil-only mode). if (fCoverBBoxProgram) { flushState->bindPipelineAndScissorClip(*fCoverBBoxProgram, this->bounds()); flushState->bindTextures(fCoverBBoxProgram->geomProc(), nullptr, fCoverBBoxProgram->pipeline()); flushState->bindBuffers(nullptr, fBBoxBuffer, fBBoxVertexBufferIfNoIDSupport); flushState->drawInstanced(1, fBBoxBaseInstance, 4, 0); } }
Make BoundingBoxShader inherit from GrGeometryProcessor directly
Make BoundingBoxShader inherit from GrGeometryProcessor directly This is not a tessellation shader, and only inherited from GrPathTessellationShader because it was used by the tessellation path renderer. Remove its dependence on GrPathTessellationShader. Bug: skia:10419 Change-Id: Ia97ef68488fae1c90674c5a006a62a3157bb707f Reviewed-on: https://skia-review.googlesource.com/c/skia/+/430019 Reviewed-by: Brian Osman <[email protected]> Commit-Queue: Chris Dalton <[email protected]>
C++
bsd-3-clause
aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia
81969bfb9139896c19f398ae4004826fa6813d41
src/import/generic/memory/lib/utils/c_str.H
src/import/generic/memory/lib/utils/c_str.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/c_str.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 c_str.H /// @brief Function to return the C-string name of a thing /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef _MSS_C_STR_H_ #define _MSS_C_STR_H_ #include <fapi2.H> #include <generic/memory/lib/utils/index.H> namespace mss { // Thread local storage for the string we're going to create. //TODO RTC:153924 Remove the else case when issue is resolved #ifndef PLAT_NO_THREAD_LOCAL_STORAGE extern thread_local char c_str_storage[fapi2::MAX_ECMD_STRING_LEN]; #else extern char c_str_storage[fapi2::MAX_ECMD_STRING_LEN]; #endif /// /// @brief non-target c_str general declaration /// @tparam T - type you want the const char * for /// @param[in] i_input - input you want the const char * for /// @return const char * /// template< typename T > const char* c_str( const T& i_input ); /// /// @brief fapi2::Target c_str general declaration /// @tparam T - fapi2::TargetType you want the name for /// @param[in] i_target - target you want the name for /// @return const char * /// template< fapi2::TargetType T > inline const char* c_str( const fapi2::template Target<T>& i_target ) { fapi2::toString( i_target, c_str_storage, fapi2::MAX_ECMD_STRING_LEN ); return c_str_storage; } template<> inline const char* c_str( const fapi2::template Target<fapi2::TARGET_TYPE_DIMM>& i_target ) { const auto l_mca = i_target.getParent<fapi2::TARGET_TYPE_MCA>(); const auto l_mcs = l_mca.getParent<fapi2::TARGET_TYPE_MCS>(); constexpr auto l_max_gen = 3; constexpr auto l_max_type = 4; const char* const l_map_gen_to_string[l_max_gen] = {"empty", "DDR3", "DDR4"}; const char* const l_map_type_to_string[l_max_type] = {"empty", "RDIMM", "UDIMM", "LRDIMM"}; uint8_t l_type = 0; uint8_t l_gen = 0; char l_buffer[fapi2::MAX_ECMD_STRING_LEN] = {}; fapi2::toString( i_target, c_str_storage, fapi2::MAX_ECMD_STRING_LEN ); // Had to unroll FAPI_TRY so that fapi2::current_err doesn't get overwritten, causes errors // when calling c_str inside of a function that returns fapi2::ReturnCode constexpr size_t PORTS_PER_MCS = 2; constexpr size_t MAX_DIMM_PER_PORT = 2; uint8_t l_value[PORTS_PER_MCS][MAX_DIMM_PER_PORT] = {}; if (FAPI_ATTR_GET(fapi2::ATTR_EFF_DIMM_TYPE, l_mcs, l_value) != fapi2::FAPI2_RC_SUCCESS) { goto fapi_try_exit; } l_type = l_value[mss::index(l_mca)][mss::index(i_target)]; if (l_type >= l_max_type) { goto fapi_try_exit; } // Had to unroll FAPI_TRY so that fapi2::current_err doesn't get overwritten, causes errors // when calling c_str inside of a function that returns fapi2::ReturnCode if (FAPI_ATTR_GET(fapi2::ATTR_EFF_DRAM_GEN, l_mcs, l_value) != fapi2::FAPI2_RC_SUCCESS) { goto fapi_try_exit; } l_gen = l_value[mss::index(l_mca)][mss::index(i_target)]; if (l_gen >= l_max_gen) { goto fapi_try_exit; } snprintf(l_buffer, fapi2::MAX_ECMD_STRING_LEN, " %s (%s)", l_map_type_to_string[l_type], l_map_gen_to_string[l_gen]); return strncat( c_str_storage, l_buffer, fapi2::MAX_ECMD_STRING_LEN - strlen(c_str_storage) ); fapi_try_exit: // Probably the best we're going to do ... return c_str_storage; } } #endif
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/c_str.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 c_str.H /// @brief Function to return the C-string name of a thing /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef _MSS_C_STR_H_ #define _MSS_C_STR_H_ #include <fapi2.H> #include <generic/memory/lib/utils/index.H> namespace mss { // Thread local storage for the string we're going to create. //TODO RTC:153924 Remove the else case when issue is resolved #ifndef PLAT_NO_THREAD_LOCAL_STORAGE extern thread_local char c_str_storage[fapi2::MAX_ECMD_STRING_LEN]; #else extern char c_str_storage[fapi2::MAX_ECMD_STRING_LEN]; #endif /// /// @brief non-target c_str general declaration /// @tparam T - type you want the const char * for /// @param[in] i_input - input you want the const char * for /// @return const char * /// template< typename T > const char* c_str( const T& i_input ); /// /// @brief fapi2::Target c_str general declaration /// @tparam T - fapi2::TargetType you want the name for /// @param[in] i_target - target you want the name for /// @return const char * /// template< fapi2::TargetType T > inline const char* c_str( const fapi2::template Target<T>& i_target ) { fapi2::toString( i_target, c_str_storage, fapi2::MAX_ECMD_STRING_LEN ); return c_str_storage; } template<> inline const char* c_str( const fapi2::template Target<fapi2::TARGET_TYPE_DIMM>& i_target ) { const auto l_mca = i_target.getParent<fapi2::TARGET_TYPE_MCA>(); const auto l_mcs = l_mca.getParent<fapi2::TARGET_TYPE_MCS>(); constexpr auto l_max_gen = 3; constexpr auto l_max_type = 4; const char* const l_map_gen_to_string[l_max_gen] = {"empty", "DDR3", "DDR4"}; const char* const l_map_type_to_string[l_max_type] = {"empty", "RDIMM", "UDIMM", "LRDIMM"}; uint8_t l_type = 0; uint8_t l_gen = 0; char l_buffer[fapi2::MAX_ECMD_STRING_LEN] = {}; fapi2::toString( i_target, c_str_storage, fapi2::MAX_ECMD_STRING_LEN ); // Had to unroll FAPI_TRY so that fapi2::current_err doesn't get overwritten, causes errors // when calling c_str inside of a function that returns fapi2::ReturnCode constexpr size_t PORTS_PER_MCS = 2; constexpr size_t MAX_DIMM_PER_PORT = 2; uint8_t l_value[PORTS_PER_MCS][MAX_DIMM_PER_PORT] = {}; if (FAPI_ATTR_GET(fapi2::ATTR_EFF_DIMM_TYPE, l_mcs, l_value) != fapi2::FAPI2_RC_SUCCESS) { goto fapi_try_exit; } l_type = l_value[mss::index(l_mca)][mss::index(i_target)]; if (l_type >= l_max_type) { goto fapi_try_exit; } // Had to unroll FAPI_TRY so that fapi2::current_err doesn't get overwritten, causes errors // when calling c_str inside of a function that returns fapi2::ReturnCode if (FAPI_ATTR_GET(fapi2::ATTR_EFF_DRAM_GEN, l_mcs, l_value) != fapi2::FAPI2_RC_SUCCESS) { goto fapi_try_exit; } l_gen = l_value[mss::index(l_mca)][mss::index(i_target)]; if (l_gen >= l_max_gen) { goto fapi_try_exit; } snprintf(l_buffer, fapi2::MAX_ECMD_STRING_LEN, " %s (%s)", l_map_type_to_string[l_type], l_map_gen_to_string[l_gen]); return strncat( c_str_storage, l_buffer, fapi2::MAX_ECMD_STRING_LEN - strlen(c_str_storage) ); fapi_try_exit: // Probably the best we're going to do ... return c_str_storage; } namespace spd { /// /// @brief fapi2::Target c_str general declaration /// @param[in] i_target - target you want the name for /// @return const char * /// inline const char* c_str( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target ) { fapi2::toString( i_target, c_str_storage, fapi2::MAX_ECMD_STRING_LEN ); return c_str_storage; } }// spd }// mss #endif
Add SPD reader and traits DDR4 def
Add SPD reader and traits DDR4 def Includes addition of a generic const file to store constants that are not controller dependent. In addition to spd::c_str for SPD decoder tracing. Change-Id: I4a3ef37d0c0a6c42a111948a3cae3d34a3bcdc70 Original-Change-Id: I6dafe1ff3328a1ac287b29f148e63e304f626ea5 Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/57492 Tested-by: FSP CI Jenkins <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Tested-by: Jenkins Server <[email protected]> Tested-by: HWSV CI <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
c850df8e27376924f732fb21e8d4dcfb1f08a9a9
grpc/server/dronecore_server.cpp
grpc/server/dronecore_server.cpp
#include <iostream> #include <thread> #include <chrono> #include <cstdint> #include <future> #include <grpc/grpc.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/security/server_credentials.h> #include "dronecore.h" #include "dronecore.grpc.pb.h" using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerReader; using grpc::ServerReaderWriter; using grpc::ServerWriter; using grpc::Status; using dronecorerpc::Empty; using dronecorerpc::DroneCoreRPC; using namespace dronecore; using namespace std::placeholders; class DroneCoreRPCImpl final : public DroneCoreRPC::Service { public: Status Arm(ServerContext *context, const Empty *request, dronecorerpc::ActionResult *response) override { const Action::Result action_result = dc.device().action().arm(); response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result)); response->set_result_str(Action::result_str(action_result)); return Status::OK; } Status TakeOff(ServerContext *context, const Empty *request, dronecorerpc::ActionResult *response) override { const Action::Result action_result = dc.device().action().takeoff(); response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result)); response->set_result_str(Action::result_str(action_result)); return Status::OK; } Status Land(ServerContext *context, const Empty *request, dronecorerpc::ActionResult *response) override { const Action::Result action_result = dc.device().action().land(); response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result)); response->set_result_str(Action::result_str(action_result)); return Status::OK; } Status SendMission(ServerContext *context, const dronecorerpc::Mission *mission, dronecorerpc::MissionResult *response) override { // TODO: there has to be a beter way than using std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); std::vector<std::shared_ptr<MissionItem>> mission_items; for (auto &mission_item : mission->mission_items()) { std::cout << "item" << std::endl; auto new_item = std::make_shared<MissionItem>(); new_item->set_position(mission_item.latitude(), mission_item.longitude()); new_item->set_relative_altitude(mission_item.altitude()); new_item->set_speed(mission_item.speed()); new_item->set_fly_through(mission_item.is_fly_through()); new_item->set_gimbal_pitch_and_yaw(mission_item.pitch(), mission_item.yaw()); new_item->set_camera_action(static_cast<dronecore::MissionItem::CameraAction> (mission_item.camera_action())); mission_items.push_back(new_item); } dc.device().mission().send_mission_async( mission_items, [prom, response](Mission::Result result) { response->set_result(static_cast<dronecorerpc::MissionResult::Result>(result)); response->set_result_str(Mission::result_str(result)); prom->set_value(); } ); future_result.wait(); future_result.get(); return Status::OK; } Status StartMission(ServerContext *context, const Empty *request, dronecorerpc::MissionResult *response) override { // TODO: there has to be a beter way than using std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); dc.device().mission().start_mission_async( [prom, response](Mission::Result result) { response->set_result(static_cast<dronecorerpc::MissionResult::Result>(result)); response->set_result_str(Mission::result_str(result)); prom->set_value(); } ); future_result.wait(); future_result.get(); return Status::OK; } DroneCore dc; private: }; void RunServer() { std::string server_address("0.0.0.0:50051"); DroneCoreRPCImpl service; bool discovered_device = false; DroneCore::ConnectionResult connection_result = service.dc.add_udp_connection(); if (connection_result != DroneCore::ConnectionResult::SUCCESS) { std::cout << "Connection failed: " << DroneCore::connection_result_str( connection_result) << std::endl; return; } std::cout << "Waiting to discover device..." << std::endl; service.dc.register_on_discover([&discovered_device](uint64_t uuid) { std::cout << "Discovered device with UUID: " << uuid << std::endl; discovered_device = true; }); // We usually receive heartbeats at 1Hz, therefore we should find a device after around 2 seconds. std::this_thread::sleep_for(std::chrono::seconds(2)); if (!discovered_device) { std::cout << "No device found, exiting." << std::endl; return; } ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } int main(int argc, char **argv) { RunServer(); return 0; }
#include <iostream> #include <thread> #include <chrono> #include <cstdint> #include <future> #include <grpc/grpc.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/security/server_credentials.h> #include "dronecore.h" #include "dronecore.grpc.pb.h" using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerReader; using grpc::ServerReaderWriter; using grpc::ServerWriter; using grpc::Status; using dronecorerpc::Empty; using dronecorerpc::DroneCoreRPC; using namespace dronecore; using namespace std::placeholders; class DroneCoreRPCImpl final : public DroneCoreRPC::Service { public: Status Arm(ServerContext *context, const Empty *request, dronecorerpc::ActionResult *response) override { const Action::Result action_result = dc.device().action().arm(); response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result)); response->set_result_str(Action::result_str(action_result)); return Status::OK; } Status TakeOff(ServerContext *context, const Empty *request, dronecorerpc::ActionResult *response) override { const Action::Result action_result = dc.device().action().takeoff(); response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result)); response->set_result_str(Action::result_str(action_result)); return Status::OK; } Status Land(ServerContext *context, const Empty *request, dronecorerpc::ActionResult *response) override { const Action::Result action_result = dc.device().action().land(); response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result)); response->set_result_str(Action::result_str(action_result)); return Status::OK; } Status SendMission(ServerContext *context, const dronecorerpc::Mission *mission, dronecorerpc::MissionResult *response) override { // TODO: there has to be a beter way than using std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); std::vector<std::shared_ptr<MissionItem>> mission_items; for (auto &mission_item : mission->mission_items()) { auto new_item = std::make_shared<MissionItem>(); new_item->set_position(mission_item.latitude(), mission_item.longitude()); new_item->set_relative_altitude(mission_item.altitude()); new_item->set_speed(mission_item.speed()); new_item->set_fly_through(mission_item.is_fly_through()); new_item->set_gimbal_pitch_and_yaw(mission_item.pitch(), mission_item.yaw()); new_item->set_camera_action(static_cast<dronecore::MissionItem::CameraAction> (mission_item.camera_action())); mission_items.push_back(new_item); } dc.device().mission().send_mission_async( mission_items, [prom, response](Mission::Result result) { response->set_result(static_cast<dronecorerpc::MissionResult::Result>(result)); response->set_result_str(Mission::result_str(result)); prom->set_value(); } ); future_result.wait(); future_result.get(); return Status::OK; } Status StartMission(ServerContext *context, const Empty *request, dronecorerpc::MissionResult *response) override { // TODO: there has to be a beter way than using std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); dc.device().mission().start_mission_async( [prom, response](Mission::Result result) { response->set_result(static_cast<dronecorerpc::MissionResult::Result>(result)); response->set_result_str(Mission::result_str(result)); prom->set_value(); } ); future_result.wait(); future_result.get(); return Status::OK; } DroneCore dc; private: }; void RunServer() { std::string server_address("0.0.0.0:50051"); DroneCoreRPCImpl service; bool discovered_device = false; DroneCore::ConnectionResult connection_result = service.dc.add_udp_connection(); if (connection_result != DroneCore::ConnectionResult::SUCCESS) { std::cout << "Connection failed: " << DroneCore::connection_result_str( connection_result) << std::endl; return; } std::cout << "Waiting to discover device..." << std::endl; service.dc.register_on_discover([&discovered_device](uint64_t uuid) { std::cout << "Discovered device with UUID: " << uuid << std::endl; discovered_device = true; }); // We usually receive heartbeats at 1Hz, therefore we should find a device after around 2 seconds. std::this_thread::sleep_for(std::chrono::seconds(2)); if (!discovered_device) { std::cout << "No device found, exiting." << std::endl; return; } ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } int main(int argc, char **argv) { RunServer(); return 0; }
remove debug cout
grpc: remove debug cout
C++
bsd-3-clause
dronecore/DroneCore,dronecore/DroneCore,dronecore/DroneCore,dronecore/DroneCore
7acd020b66859417d099f32f85d66ca75c7b0a9d
Modules/OpenCVVideoSupport/Commands/mitkGrabCutOpenCVImageFilter.cpp
Modules/OpenCVVideoSupport/Commands/mitkGrabCutOpenCVImageFilter.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkGrabCutOpenCVImageFilter.h" #include "mitkPointSet.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" #include "itkConditionVariable.h" mitk::GrabCutOpenCVImageFilter::GrabCutOpenCVImageFilter() : m_PointSetsChanged(false), m_InputImageChanged(false), m_NewResultReady(false), m_ModelPointsDilationSize(0), m_UseOnlyRegionAroundModelPoints(false), m_ProcessEveryNumImage(1), m_CurrentProcessImageNum(0), m_InputImageId(AbstractOpenCVImageFilter::INVALID_IMAGE_ID), m_ResultImageId(AbstractOpenCVImageFilter::INVALID_IMAGE_ID), m_ThreadId(-1), m_StopThread(false), m_MultiThreader(itk::MultiThreader::New()), m_WorkerBarrier(itk::ConditionVariable::New()), m_ImageMutex(itk::FastMutexLock::New()), m_ResultMutex(itk::FastMutexLock::New()), m_PointSetsMutex(itk::FastMutexLock::New()) { m_ThreadId = m_MultiThreader->SpawnThread(this->SegmentationWorker, this); } mitk::GrabCutOpenCVImageFilter::~GrabCutOpenCVImageFilter() { m_StopThread = true; m_WorkerBarrier->Broadcast(); if ( m_ThreadId >= 0) { m_MultiThreader->TerminateThread(m_ThreadId); } } bool mitk::GrabCutOpenCVImageFilter::OnFilterImage( cv::Mat& image ) { if ( image.empty() ) { MITK_WARN << "Filtering empty image?"; return false; } if ( m_NewResultReady ) { m_ResultMutex->Lock(); m_NewResultReady = false; m_ResultMutex->Unlock(); } // update just every x images (as configured) ++m_CurrentProcessImageNum %= m_ProcessEveryNumImage; if (m_CurrentProcessImageNum != 0) { return true; } m_ImageMutex->Lock(); // make sure that the image is an rgb image if (image.type() != CV_8UC3) { cv::Mat test = image.clone(); cv::cvtColor(test, image, CV_GRAY2RGB); } m_InputImage = image.clone(); m_InputImageId = this->GetCurrentImageId(); m_ImageMutex->Unlock(); if ( ! m_ForegroundPoints.empty()) { m_WorkerBarrier->Broadcast(); } return true; } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(ModelPointsList foregroundPoints) { m_PointSetsMutex->Lock(); m_ForegroundPoints = foregroundPoints; m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(ModelPointsList foregroundPoints, ModelPointsList backgroundPoints) { m_PointSetsMutex->Lock(); m_BackgroundPoints = backgroundPoints; m_ForegroundPoints = foregroundPoints; m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(cv::Mat foregroundMask) { m_PointSetsMutex->Lock(); m_ForegroundPoints = this->ConvertMaskToModelPointsList(foregroundMask); m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(cv::Mat foregroundMask, cv::Mat backgroundMask) { m_PointSetsMutex->Lock(); m_ForegroundPoints = this->ConvertMaskToModelPointsList(foregroundMask); m_BackgroundPoints = this->ConvertMaskToModelPointsList(backgroundMask); m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPointsDilationSize(int modelPointsDilationSize) { if ( modelPointsDilationSize < 0 ) { MITK_ERROR << "Model points dilation size must not be smaller then zero."; mitkThrow() << "Model points dilation size must not be smaller then zero."; } m_ModelPointsDilationSize = modelPointsDilationSize; } void mitk::GrabCutOpenCVImageFilter::SetUseOnlyRegionAroundModelPoints(unsigned int additionalWidth) { m_UseOnlyRegionAroundModelPoints = true; m_AdditionalWidth = additionalWidth; } void mitk::GrabCutOpenCVImageFilter::SetUseFullImage() { m_UseOnlyRegionAroundModelPoints = false; } int mitk::GrabCutOpenCVImageFilter::GetResultImageId() { return m_ResultImageId; } cv::Mat mitk::GrabCutOpenCVImageFilter::GetResultMask() { cv::Mat result; m_ResultMutex->Lock(); result = m_ResultMask.clone(); m_ResultMutex->Unlock(); return result; } std::vector<mitk::GrabCutOpenCVImageFilter::ModelPointsList> mitk::GrabCutOpenCVImageFilter::GetResultContours() { std::vector<std::vector<cv::Point> > cvContours; std::vector<cv::Vec4i> hierarchy; std::vector<mitk::GrabCutOpenCVImageFilter::ModelPointsList> contourPoints; cv::Mat resultMask = this->GetResultMask(); if (resultMask.empty()) { return contourPoints; } cv::findContours(resultMask, cvContours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_NONE); for ( unsigned int i = 0; i < cvContours.size(); ++i ) { mitk::GrabCutOpenCVImageFilter::ModelPointsList curContourPoints; for ( std::vector<cv::Point>::iterator it = cvContours[i].begin(); it != cvContours[i].end(); ++it) { itk::Index<2> index; index.SetElement(0, it->x); index.SetElement(1, it->y); curContourPoints.push_back(index); } contourPoints.push_back(curContourPoints); } return contourPoints; } mitk::GrabCutOpenCVImageFilter::ModelPointsList mitk::GrabCutOpenCVImageFilter::GetResultContourWithPixel(itk::Index<2> pixelIndex) { cv::Mat mask = this->GetResultMask(); cv::floodFill(mask, cv::Point(pixelIndex.GetElement(0), pixelIndex.GetElement(1)), 5); cv::Mat foregroundMask; cv::compare(mask, 5, foregroundMask, cv::CMP_EQ); std::vector<std::vector<cv::Point> > cvContours; std::vector<cv::Vec4i> hierarchy; cv::findContours(foregroundMask, cvContours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_NONE); ModelPointsList contourPoints; for ( std::vector<cv::Point>::iterator it = cvContours[0].begin(); it != cvContours[0].end(); ++it) { itk::Index<2> index; index.SetElement(0, it->x); index.SetElement(1, it->y); contourPoints.push_back(index); } return contourPoints; } cv::Mat mitk::GrabCutOpenCVImageFilter::GetMaskFromPointSets() { cv::Mat mask(m_InputImage.size().height, m_InputImage.size().width, CV_8UC1, cv::GC_PR_BGD); m_PointSetsMutex->Lock(); ModelPointsList pointsLists[2] = {ModelPointsList(m_ForegroundPoints), ModelPointsList(m_BackgroundPoints)}; m_PointSetsMutex->Unlock(); unsigned int pixelValues[2] = {cv::GC_FGD, cv::GC_BGD}; for (unsigned int n = 0; n < 2; ++n) { for (ModelPointsList::iterator it = pointsLists[n].begin(); it != pointsLists[n].end(); ++it) { for ( int i = -m_ModelPointsDilationSize; i <= m_ModelPointsDilationSize; ++i ) { for ( int j = -m_ModelPointsDilationSize; j <= m_ModelPointsDilationSize; ++j) { int x = it->GetElement(1) + i; int y = it->GetElement(0) + j; if ( x >= 0 && y >= 0 && x < mask.cols && y < mask.rows) { mask.at<unsigned char>(x, y) = pixelValues[n]; } } } } } return mask; } cv::Rect mitk::GrabCutOpenCVImageFilter::GetBoundingRectFromMask(cv::Mat mask) { cv::Mat nonPropablyBackgroundMask, modelPoints; cv::compare(mask, cv::GC_PR_BGD, nonPropablyBackgroundMask, cv::CMP_NE); cv::findNonZero(nonPropablyBackgroundMask, modelPoints); if (modelPoints.empty()) { MITK_WARN << "Cannot find any foreground points. Returning full image size as bounding rectangle."; return cv::Rect(0, 0, mask.rows, mask.cols); } cv::Rect boundingRect = cv::boundingRect(modelPoints); boundingRect.x = boundingRect.x > m_AdditionalWidth ? boundingRect.x - m_AdditionalWidth : 0; boundingRect.y = boundingRect.y > m_AdditionalWidth ? boundingRect.y - m_AdditionalWidth : 0; if ( boundingRect.x + boundingRect.width + m_AdditionalWidth < mask.size().width ) { boundingRect.width += m_AdditionalWidth; } else { boundingRect.width = mask.size().width - boundingRect.x - 1; } if ( boundingRect.y + boundingRect.height + m_AdditionalWidth < mask.size().height ) { boundingRect.height += m_AdditionalWidth; } else { boundingRect.height = mask.size().height - boundingRect.y - 1; } return boundingRect; } cv::Mat mitk::GrabCutOpenCVImageFilter::RunSegmentation(cv::Mat input, cv::Mat mask) { // do the actual grab cut segmentation (initialized with the mask) cv::Mat bgdModel, fgdModel; cv::grabCut(input, mask, cv::Rect(), bgdModel, fgdModel, 1, cv::GC_INIT_WITH_MASK); // set propably foreground pixels to white on result mask cv::Mat result; cv::compare(mask, cv::GC_PR_FGD, result, cv::CMP_EQ); // set foreground pixels to white on result mask cv::Mat foregroundMat; cv::compare(mask, cv::GC_FGD, foregroundMat, cv::CMP_EQ); foregroundMat.copyTo(result, foregroundMat); return result; // now the result mask can be returned } mitk::GrabCutOpenCVImageFilter::ModelPointsList mitk::GrabCutOpenCVImageFilter::ConvertMaskToModelPointsList(cv::Mat mask) { cv::Mat points; cv::findNonZero(mask, points); // push extracted points into a vector of itk indices ModelPointsList pointsVector; for ( size_t n = 0; n < points.total(); ++n) { itk::Index<2> index; index.SetElement(0, points.at<cv::Point>(n).x); index.SetElement(1, points.at<cv::Point>(n).y); pointsVector.push_back(index); } return pointsVector; } ITK_THREAD_RETURN_TYPE mitk::GrabCutOpenCVImageFilter::SegmentationWorker(void* pInfoStruct) { // extract this pointer from thread info structure struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct; mitk::GrabCutOpenCVImageFilter* thisObject = static_cast<mitk::GrabCutOpenCVImageFilter*>(pInfo->UserData); itk::SimpleMutexLock mutex; mutex.Lock(); while (true) { if (thisObject->m_StopThread) { break; } thisObject->m_WorkerBarrier->Wait(&mutex); if (thisObject->m_StopThread) { break; } thisObject->m_ImageMutex->Lock(); cv::Mat image = thisObject->m_InputImage.clone(); int inputImageId = thisObject->m_InputImageId; thisObject->m_ImageMutex->Unlock(); cv::Mat mask = thisObject->GetMaskFromPointSets(); cv::Mat result; if (thisObject->m_UseOnlyRegionAroundModelPoints) { result = cv::Mat(mask.rows, mask.cols, mask.type(), 0.0); cv::Rect boundingBox = thisObject->GetBoundingRectFromMask(mask); thisObject->RunSegmentation(image(boundingBox), mask(boundingBox)).copyTo(result(boundingBox)); } else { result = thisObject->RunSegmentation(image, mask); } thisObject->m_ResultMutex->Lock(); thisObject->m_ResultMask = result; thisObject->m_NewResultReady = true; thisObject->m_ResultImageId = inputImageId; thisObject->m_ResultMutex->Unlock(); } mutex.Unlock(); return ITK_THREAD_RETURN_VALUE; }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkGrabCutOpenCVImageFilter.h" #include "mitkPointSet.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" #include "itkConditionVariable.h" mitk::GrabCutOpenCVImageFilter::GrabCutOpenCVImageFilter() : m_PointSetsChanged(false), m_InputImageChanged(false), m_NewResultReady(false), m_ModelPointsDilationSize(0), m_UseOnlyRegionAroundModelPoints(false), m_ProcessEveryNumImage(1), m_CurrentProcessImageNum(0), m_InputImageId(AbstractOpenCVImageFilter::INVALID_IMAGE_ID), m_ResultImageId(AbstractOpenCVImageFilter::INVALID_IMAGE_ID), m_ThreadId(-1), m_StopThread(false), m_MultiThreader(itk::MultiThreader::New()), m_WorkerBarrier(itk::ConditionVariable::New()), m_ImageMutex(itk::FastMutexLock::New()), m_ResultMutex(itk::FastMutexLock::New()), m_PointSetsMutex(itk::FastMutexLock::New()) { m_ThreadId = m_MultiThreader->SpawnThread(this->SegmentationWorker, this); } mitk::GrabCutOpenCVImageFilter::~GrabCutOpenCVImageFilter() { m_StopThread = true; m_WorkerBarrier->Broadcast(); if ( m_ThreadId >= 0) { m_MultiThreader->TerminateThread(m_ThreadId); } } bool mitk::GrabCutOpenCVImageFilter::OnFilterImage( cv::Mat& image ) { if ( image.empty() ) { MITK_WARN << "Filtering empty image?"; return false; } if ( m_NewResultReady ) { m_ResultMutex->Lock(); m_NewResultReady = false; m_ResultMutex->Unlock(); } // update just every x images (as configured) ++m_CurrentProcessImageNum %= m_ProcessEveryNumImage; if (m_CurrentProcessImageNum != 0) { return true; } m_ImageMutex->Lock(); // make sure that the image is an rgb image if (image.type() != CV_8UC3) { cv::Mat test = image.clone(); cv::cvtColor(test, image, CV_GRAY2RGB); } m_InputImage = image.clone(); m_InputImageId = this->GetCurrentImageId(); m_ImageMutex->Unlock(); if ( ! m_ForegroundPoints.empty()) { m_WorkerBarrier->Broadcast(); } return true; } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(ModelPointsList foregroundPoints) { m_PointSetsMutex->Lock(); m_ForegroundPoints = foregroundPoints; m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(ModelPointsList foregroundPoints, ModelPointsList backgroundPoints) { m_PointSetsMutex->Lock(); m_BackgroundPoints = backgroundPoints; m_ForegroundPoints = foregroundPoints; m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(cv::Mat foregroundMask) { m_PointSetsMutex->Lock(); m_ForegroundPoints = this->ConvertMaskToModelPointsList(foregroundMask); m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPoints(cv::Mat foregroundMask, cv::Mat backgroundMask) { m_PointSetsMutex->Lock(); m_ForegroundPoints = this->ConvertMaskToModelPointsList(foregroundMask); m_BackgroundPoints = this->ConvertMaskToModelPointsList(backgroundMask); m_PointSetsChanged = true; m_PointSetsMutex->Unlock(); } void mitk::GrabCutOpenCVImageFilter::SetModelPointsDilationSize(int modelPointsDilationSize) { if ( modelPointsDilationSize < 0 ) { MITK_ERROR << "Model points dilation size must not be smaller then zero."; mitkThrow() << "Model points dilation size must not be smaller then zero."; } m_ModelPointsDilationSize = modelPointsDilationSize; } void mitk::GrabCutOpenCVImageFilter::SetUseOnlyRegionAroundModelPoints(unsigned int additionalWidth) { m_UseOnlyRegionAroundModelPoints = true; m_AdditionalWidth = additionalWidth; } void mitk::GrabCutOpenCVImageFilter::SetUseFullImage() { m_UseOnlyRegionAroundModelPoints = false; } int mitk::GrabCutOpenCVImageFilter::GetResultImageId() { return m_ResultImageId; } cv::Mat mitk::GrabCutOpenCVImageFilter::GetResultMask() { cv::Mat result; m_ResultMutex->Lock(); result = m_ResultMask.clone(); m_ResultMutex->Unlock(); return result; } std::vector<mitk::GrabCutOpenCVImageFilter::ModelPointsList> mitk::GrabCutOpenCVImageFilter::GetResultContours() { std::vector<std::vector<cv::Point> > cvContours; std::vector<cv::Vec4i> hierarchy; std::vector<mitk::GrabCutOpenCVImageFilter::ModelPointsList> contourPoints; cv::Mat resultMask = this->GetResultMask(); if (resultMask.empty()) { return contourPoints; } cv::findContours(resultMask, cvContours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_NONE); for ( unsigned int i = 0; i < cvContours.size(); ++i ) { mitk::GrabCutOpenCVImageFilter::ModelPointsList curContourPoints; for ( std::vector<cv::Point>::iterator it = cvContours[i].begin(); it != cvContours[i].end(); ++it) { itk::Index<2> index; index.SetElement(0, it->x); index.SetElement(1, it->y); curContourPoints.push_back(index); } contourPoints.push_back(curContourPoints); } return contourPoints; } mitk::GrabCutOpenCVImageFilter::ModelPointsList mitk::GrabCutOpenCVImageFilter::GetResultContourWithPixel(itk::Index<2> pixelIndex) { cv::Mat mask = this->GetResultMask(); if (mask.empty()) { return mitk::GrabCutOpenCVImageFilter::ModelPointsList(); } if (pixelIndex.GetElement(0) < 0 || pixelIndex.GetElement(0) >= mask.size().height || pixelIndex.GetElement(1) < 0 || pixelIndex.GetElement(1) >= mask.size().width) { MITK_WARN << "Given pixel index ("<< pixelIndex.GetElement(0) << ", " << pixelIndex.GetElement(1) << ") is outside the image (" << mask.size().height << ", " << mask.size().width << ")."; return mitk::GrabCutOpenCVImageFilter::ModelPointsList(); } cv::floodFill(mask, cv::Point(pixelIndex.GetElement(0), pixelIndex.GetElement(1)), 5); cv::Mat foregroundMask; cv::compare(mask, 5, foregroundMask, cv::CMP_EQ); std::vector<std::vector<cv::Point> > cvContours; std::vector<cv::Vec4i> hierarchy; cv::findContours(foregroundMask, cvContours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_NONE); ModelPointsList contourPoints; for ( std::vector<cv::Point>::iterator it = cvContours[0].begin(); it != cvContours[0].end(); ++it) { itk::Index<2> index; index.SetElement(0, it->x); index.SetElement(1, it->y); contourPoints.push_back(index); } return contourPoints; } cv::Mat mitk::GrabCutOpenCVImageFilter::GetMaskFromPointSets() { cv::Mat mask(m_InputImage.size().height, m_InputImage.size().width, CV_8UC1, cv::GC_PR_BGD); m_PointSetsMutex->Lock(); ModelPointsList pointsLists[2] = {ModelPointsList(m_ForegroundPoints), ModelPointsList(m_BackgroundPoints)}; m_PointSetsMutex->Unlock(); unsigned int pixelValues[2] = {cv::GC_FGD, cv::GC_BGD}; for (unsigned int n = 0; n < 2; ++n) { for (ModelPointsList::iterator it = pointsLists[n].begin(); it != pointsLists[n].end(); ++it) { for ( int i = -m_ModelPointsDilationSize; i <= m_ModelPointsDilationSize; ++i ) { for ( int j = -m_ModelPointsDilationSize; j <= m_ModelPointsDilationSize; ++j) { int x = it->GetElement(1) + i; int y = it->GetElement(0) + j; if ( x >= 0 && y >= 0 && x < mask.cols && y < mask.rows) { mask.at<unsigned char>(x, y) = pixelValues[n]; } } } } } return mask; } cv::Rect mitk::GrabCutOpenCVImageFilter::GetBoundingRectFromMask(cv::Mat mask) { cv::Mat nonPropablyBackgroundMask, modelPoints; cv::compare(mask, cv::GC_PR_BGD, nonPropablyBackgroundMask, cv::CMP_NE); cv::findNonZero(nonPropablyBackgroundMask, modelPoints); if (modelPoints.empty()) { MITK_WARN << "Cannot find any foreground points. Returning full image size as bounding rectangle."; return cv::Rect(0, 0, mask.rows, mask.cols); } cv::Rect boundingRect = cv::boundingRect(modelPoints); boundingRect.x = boundingRect.x > m_AdditionalWidth ? boundingRect.x - m_AdditionalWidth : 0; boundingRect.y = boundingRect.y > m_AdditionalWidth ? boundingRect.y - m_AdditionalWidth : 0; if ( boundingRect.x + boundingRect.width + m_AdditionalWidth < mask.size().width ) { boundingRect.width += m_AdditionalWidth; } else { boundingRect.width = mask.size().width - boundingRect.x - 1; } if ( boundingRect.y + boundingRect.height + m_AdditionalWidth < mask.size().height ) { boundingRect.height += m_AdditionalWidth; } else { boundingRect.height = mask.size().height - boundingRect.y - 1; } return boundingRect; } cv::Mat mitk::GrabCutOpenCVImageFilter::RunSegmentation(cv::Mat input, cv::Mat mask) { // do the actual grab cut segmentation (initialized with the mask) cv::Mat bgdModel, fgdModel; cv::grabCut(input, mask, cv::Rect(), bgdModel, fgdModel, 1, cv::GC_INIT_WITH_MASK); // set propably foreground pixels to white on result mask cv::Mat result; cv::compare(mask, cv::GC_PR_FGD, result, cv::CMP_EQ); // set foreground pixels to white on result mask cv::Mat foregroundMat; cv::compare(mask, cv::GC_FGD, foregroundMat, cv::CMP_EQ); foregroundMat.copyTo(result, foregroundMat); return result; // now the result mask can be returned } mitk::GrabCutOpenCVImageFilter::ModelPointsList mitk::GrabCutOpenCVImageFilter::ConvertMaskToModelPointsList(cv::Mat mask) { cv::Mat points; cv::findNonZero(mask, points); // push extracted points into a vector of itk indices ModelPointsList pointsVector; for ( size_t n = 0; n < points.total(); ++n) { itk::Index<2> index; index.SetElement(0, points.at<cv::Point>(n).x); index.SetElement(1, points.at<cv::Point>(n).y); pointsVector.push_back(index); } return pointsVector; } ITK_THREAD_RETURN_TYPE mitk::GrabCutOpenCVImageFilter::SegmentationWorker(void* pInfoStruct) { // extract this pointer from thread info structure struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct; mitk::GrabCutOpenCVImageFilter* thisObject = static_cast<mitk::GrabCutOpenCVImageFilter*>(pInfo->UserData); itk::SimpleMutexLock mutex; mutex.Lock(); while (true) { if (thisObject->m_StopThread) { break; } thisObject->m_WorkerBarrier->Wait(&mutex); if (thisObject->m_StopThread) { break; } thisObject->m_ImageMutex->Lock(); cv::Mat image = thisObject->m_InputImage.clone(); int inputImageId = thisObject->m_InputImageId; thisObject->m_ImageMutex->Unlock(); cv::Mat mask = thisObject->GetMaskFromPointSets(); cv::Mat result; if (thisObject->m_UseOnlyRegionAroundModelPoints) { result = cv::Mat(mask.rows, mask.cols, mask.type(), 0.0); cv::Rect boundingBox = thisObject->GetBoundingRectFromMask(mask); thisObject->RunSegmentation(image(boundingBox), mask(boundingBox)).copyTo(result(boundingBox)); } else { result = thisObject->RunSegmentation(image, mask); } thisObject->m_ResultMutex->Lock(); thisObject->m_ResultMask = result; thisObject->m_NewResultReady = true; thisObject->m_ResultImageId = inputImageId; thisObject->m_ResultMutex->Unlock(); } mutex.Unlock(); return ITK_THREAD_RETURN_VALUE; }
Check for wrong pixel index.
Check for wrong pixel index.
C++
bsd-3-clause
lsanzdiaz/MITK-BiiG,danielknorr/MITK,NifTK/MITK,RabadanLab/MITKats,fmilano/mitk,MITK/MITK,danielknorr/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,fmilano/mitk,RabadanLab/MITKats,danielknorr/MITK,iwegner/MITK,iwegner/MITK,iwegner/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,fmilano/mitk,RabadanLab/MITKats,NifTK/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,fmilano/mitk,lsanzdiaz/MITK-BiiG,danielknorr/MITK,iwegner/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,NifTK/MITK,MITK/MITK,MITK/MITK,fmilano/mitk,iwegner/MITK,danielknorr/MITK,MITK/MITK,iwegner/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,danielknorr/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,NifTK/MITK,MITK/MITK,NifTK/MITK,RabadanLab/MITKats,NifTK/MITK
330ba931aa7a98984270aa11aa2595b9a50df800
watcher/win32.cpp
watcher/win32.cpp
/* Copyright 2014-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include <folly/Synchronized.h> #include "InMemoryView.h" #include <algorithm> #include <condition_variable> #include <list> #include <iterator> #include <tuple> #include <mutex> #ifdef _WIN32 #define NETWORK_BUF_SIZE (64*1024) namespace { struct Item { w_string path; int flags; Item(w_string &&path, int flags) : path(std::move(path)), flags(flags) {} }; } struct WinWatcher : public Watcher { HANDLE ping{INVALID_HANDLE_VALUE}, olapEvent{INVALID_HANDLE_VALUE}; HANDLE dir_handle{INVALID_HANDLE_VALUE}; std::condition_variable cond; folly::Synchronized<std::list<Item>, std::mutex> changedItems; explicit WinWatcher(w_root_t* root); ~WinWatcher(); std::unique_ptr<watchman_dir_handle> startWatchDir( const std::shared_ptr<w_root_t>& root, struct watchman_dir* dir, const char* path) override; bool consumeNotify( const std::shared_ptr<w_root_t>& root, PendingCollection::LockedPtr& coll) override; bool waitNotify(int timeoutms) override; bool start(const std::shared_ptr<w_root_t>& root) override; void signalThreads() override; void readChangesThread(const std::shared_ptr<w_root_t>& root); }; WinWatcher::WinWatcher(w_root_t* root) : Watcher("win32", WATCHER_HAS_PER_FILE_NOTIFICATIONS) { int err; auto wpath = root->root_path.piece().asWideUNC(); // Create an overlapped handle so that we can avoid blocking forever // in ReadDirectoryChangesW dir_handle = CreateFileW( wpath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr); if (!dir_handle) { throw std::runtime_error( std::string("failed to open dir ") + root->root_path.c_str() + ": " + win32_strerror(GetLastError())); } ping = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!ping) { throw std::runtime_error( std::string("failed to create event: ") + win32_strerror(GetLastError())); } olapEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!olapEvent) { throw std::runtime_error( std::string("failed to create event: ") + win32_strerror(GetLastError())); } } WinWatcher::~WinWatcher() { if (ping != INVALID_HANDLE_VALUE) { CloseHandle(ping); } if (olapEvent != INVALID_HANDLE_VALUE) { CloseHandle(olapEvent); } if (dir_handle != INVALID_HANDLE_VALUE) { CloseHandle(dir_handle); } } void WinWatcher::signalThreads() { SetEvent(ping); } void WinWatcher::readChangesThread(const std::shared_ptr<w_root_t>& root) { std::vector<uint8_t> buf; DWORD err, filter; auto olap = OVERLAPPED(); BOOL initiate_read = true; HANDLE handles[2] = {olapEvent, ping}; DWORD bytes; w_set_thread_name("readchange %s", root->root_path.c_str()); watchman::log(watchman::DBG, "initializing\n"); // Artificial extra latency to impose around processing changes. // This is needed to avoid trying to access files and dirs too // soon after a change is noticed, as this can cause recursive // deletes to fail. auto extraLatency = root->config.getInt("win32_batch_latency_ms", 30); DWORD size = root->config.getInt("win32_rdcw_buf_size", 16384); // Block until winmatch_root_st is waiting for our initialization { auto wlock = changedItems.lock(); filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE; olap.hEvent = olapEvent; buf.resize(size); if (!ReadDirectoryChangesW( dir_handle, &buf[0], size, TRUE, filter, nullptr, &olap, nullptr)) { err = GetLastError(); w_log( W_LOG_ERR, "ReadDirectoryChangesW: failed, cancel watch. %s\n", win32_strerror(err)); root->cancel(); return; } // Signal that we are done with init. We MUST do this AFTER our first // successful ReadDirectoryChangesW, otherwise there is a race condition // where we'll miss observing the cookie for a query that comes in // after we've crawled but before the watch is established. w_log(W_LOG_DBG, "ReadDirectoryChangesW signalling as init done\n"); cond.notify_one(); } initiate_read = false; std::list<Item> items; // The mutex must not be held when we enter the loop while (!root->inner.cancelled) { if (initiate_read) { if (!ReadDirectoryChangesW( dir_handle, &buf[0], size, TRUE, filter, nullptr, &olap, nullptr)) { err = GetLastError(); w_log(W_LOG_ERR, "ReadDirectoryChangesW: failed, cancel watch. %s\n", win32_strerror(err)); root->cancel(); break; } else { initiate_read = false; } } watchman::log(watchman::DBG, "waiting for change notifications\n"); DWORD status = WaitForMultipleObjects( 2, handles, FALSE, // We use a 10 second timeout by default until we start accumulating a // batch. Once we have a batch we prefer to add more to it than notify // immediately, so we introduce a 30ms latency. Without this artificial // latency we'll wake up and start trying to look at a directory that // may be in the process of being recursively deleted and that act can // block the recursive delete. items.empty() ? 10000 : extraLatency); watchman::log(watchman::DBG, "wait returned with status ", status, "\n"); if (status == WAIT_OBJECT_0) { bytes = 0; if (!GetOverlappedResult(dir_handle, &olap, &bytes, FALSE)) { err = GetLastError(); w_log( W_LOG_ERR, "overlapped ReadDirectoryChangesW(%s): 0x%x %s\n", root->root_path.c_str(), err, win32_strerror(err)); if (err == ERROR_INVALID_PARAMETER && size > NETWORK_BUF_SIZE) { // May be a network buffer related size issue; the docs say that // we can hit this when watching a UNC path. Let's downsize and // retry the read just one time w_log( W_LOG_ERR, "retrying watch for possible network location %s " "with smaller buffer\n", root->root_path.c_str()); size = NETWORK_BUF_SIZE; initiate_read = true; continue; } if (err == ERROR_NOTIFY_ENUM_DIR) { root->scheduleRecrawl("ERROR_NOTIFY_ENUM_DIR"); } else { w_log( W_LOG_ERR, "Cancelling watch for %s\n", root->root_path.c_str()); root->cancel(); break; } } else { PFILE_NOTIFY_INFORMATION notify = (PFILE_NOTIFY_INFORMATION)buf.data(); while (true) { DWORD n_chars; // FileNameLength is in BYTES, but FileName is WCHAR n_chars = notify->FileNameLength / sizeof(notify->FileName[0]); w_string name(notify->FileName, n_chars); auto full = w_string::pathCat({root->root_path, name}); if (!root->ignore.isIgnored(full.data(), full.size())) { // If we have a delete or rename-away it may be part of // a recursive tree remove or rename. In that situation // the notifications that we'll receive from the OS will // be from the leaves and bubble up to the root of the // delete/rename. We want to flag those paths for recursive // analysis so that we can prune children from the trie // that is built when we pass this to the pending list // later. We don't do that here in this thread because // we're trying to minimize latency in this context. items.emplace_back( std::move(full), (notify->Action & (FILE_ACTION_REMOVED | FILE_ACTION_RENAMED_OLD_NAME)) != 0 ? W_PENDING_RECURSIVE : 0); } // Advance to next item if (notify->NextEntryOffset == 0) { break; } notify = (PFILE_NOTIFY_INFORMATION)( notify->NextEntryOffset + (char*)notify); } ResetEvent(olapEvent); initiate_read = true; } } else if (status == WAIT_OBJECT_0 + 1) { w_log(W_LOG_ERR, "signalled\n"); break; } else if (status == WAIT_TIMEOUT) { if (!items.empty()) { watchman::log(watchman::DBG, "timed out waiting for changes, and we have ", items.size(), " items; move and notify\n"); auto wlock = changedItems.lock(); wlock->splice(wlock->end(), items); cond.notify_one(); } } else { w_log(W_LOG_ERR, "impossible wait status=%d\n", status); break; } } w_log(W_LOG_DBG, "done\n"); } bool WinWatcher::start(const std::shared_ptr<w_root_t>& root) { int err; // Spin up the changes reading thread; it owns a ref on the root try { // Acquire the mutex so thread initialization waits until we release it auto wlock = changedItems.lock(); watchman::log(watchman::DBG, "starting readChangesThread\n"); auto self = std::dynamic_pointer_cast<WinWatcher>(shared_from_this()); std::thread thread([ self, root ]() noexcept { try { self->readChangesThread(root); } catch (const std::exception& e) { watchman::log(watchman::ERR, "uncaught exception: ", e.what()); root->cancel(); } // Ensure that we signal the condition variable before we // finish this thread. That ensures that don't get stuck // waiting in WinWatcher::start if something unexpected happens. auto wlock = self->changedItems.lock(); self->cond.notify_one(); }); // We have to detach because the readChangesThread may wind up // being the last thread to reference the watcher state and // cannot join itself. thread.detach(); // Allow thread init to proceed; wait for its signal if (cond.wait_for(wlock.getUniqueLock(), std::chrono::seconds(10)) == std::cv_status::timeout) { watchman::log( watchman::ERR, "timedout waiting for readChangesThread to start\n"); root->cancel(); return false; } if (root->failure_reason) { w_log( W_LOG_ERR, "failed to start readchanges thread: %s\n", root->failure_reason.c_str()); return false; } return true; } catch (const std::exception& e) { w_log(W_LOG_ERR, "failed to start readchanges thread: %s\n", e.what()); return false; } } std::unique_ptr<watchman_dir_handle> WinWatcher::startWatchDir( const std::shared_ptr<w_root_t>& root, struct watchman_dir* dir, const char* path) { return w_dir_open(path); } bool WinWatcher::consumeNotify( const std::shared_ptr<w_root_t>& root, PendingCollection::LockedPtr& coll) { std::list<Item> items; struct timeval now; { auto wlock = changedItems.lock(); std::swap(items, *wlock); } gettimeofday(&now, nullptr); for (auto& item : items) { watchman::log(watchman::DBG, "readchanges: add pending ", item.path, " ", item.flags, "\n"); coll->add(item.path, now, W_PENDING_VIA_NOTIFY | item.flags); } return !items.empty(); } bool WinWatcher::waitNotify(int timeoutms) { auto wlock = changedItems.lock(); cond.wait_for(wlock.getUniqueLock(), std::chrono::milliseconds(timeoutms)); return !wlock->empty(); } static RegisterWatcher<WinWatcher> reg("win32"); #endif // _WIN32 /* vim:ts=2:sw=2:et: */
/* Copyright 2014-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include <folly/Synchronized.h> #include "FileDescriptor.h" #include "InMemoryView.h" #include <algorithm> #include <condition_variable> #include <list> #include <iterator> #include <tuple> #include <mutex> using watchman::FileDescriptor; #ifdef _WIN32 #define NETWORK_BUF_SIZE (64*1024) namespace { struct Item { w_string path; int flags; Item(w_string &&path, int flags) : path(std::move(path)), flags(flags) {} }; } struct WinWatcher : public Watcher { HANDLE ping{INVALID_HANDLE_VALUE}, olapEvent{INVALID_HANDLE_VALUE}; FileDescriptor dir_handle; std::condition_variable cond; folly::Synchronized<std::list<Item>, std::mutex> changedItems; explicit WinWatcher(w_root_t* root); ~WinWatcher(); std::unique_ptr<watchman_dir_handle> startWatchDir( const std::shared_ptr<w_root_t>& root, struct watchman_dir* dir, const char* path) override; bool consumeNotify( const std::shared_ptr<w_root_t>& root, PendingCollection::LockedPtr& coll) override; bool waitNotify(int timeoutms) override; bool start(const std::shared_ptr<w_root_t>& root) override; void signalThreads() override; void readChangesThread(const std::shared_ptr<w_root_t>& root); }; WinWatcher::WinWatcher(w_root_t* root) : Watcher("win32", WATCHER_HAS_PER_FILE_NOTIFICATIONS) { int err; auto wpath = root->root_path.piece().asWideUNC(); // Create an overlapped handle so that we can avoid blocking forever // in ReadDirectoryChangesW dir_handle = FileDescriptor(intptr_t(CreateFileW( wpath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr))); if (!dir_handle) { throw std::runtime_error( std::string("failed to open dir ") + root->root_path.c_str() + ": " + win32_strerror(GetLastError())); } ping = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!ping) { throw std::runtime_error( std::string("failed to create event: ") + win32_strerror(GetLastError())); } olapEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!olapEvent) { throw std::runtime_error( std::string("failed to create event: ") + win32_strerror(GetLastError())); } } WinWatcher::~WinWatcher() { if (ping != INVALID_HANDLE_VALUE) { CloseHandle(ping); } if (olapEvent != INVALID_HANDLE_VALUE) { CloseHandle(olapEvent); } } void WinWatcher::signalThreads() { SetEvent(ping); } void WinWatcher::readChangesThread(const std::shared_ptr<w_root_t>& root) { std::vector<uint8_t> buf; DWORD err, filter; auto olap = OVERLAPPED(); BOOL initiate_read = true; HANDLE handles[2] = {olapEvent, ping}; DWORD bytes; w_set_thread_name("readchange %s", root->root_path.c_str()); watchman::log(watchman::DBG, "initializing\n"); // Artificial extra latency to impose around processing changes. // This is needed to avoid trying to access files and dirs too // soon after a change is noticed, as this can cause recursive // deletes to fail. auto extraLatency = root->config.getInt("win32_batch_latency_ms", 30); DWORD size = root->config.getInt("win32_rdcw_buf_size", 16384); // Block until winmatch_root_st is waiting for our initialization { auto wlock = changedItems.lock(); filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE; olap.hEvent = olapEvent; buf.resize(size); if (!ReadDirectoryChangesW( (HANDLE)dir_handle.handle(), &buf[0], size, TRUE, filter, nullptr, &olap, nullptr)) { err = GetLastError(); w_log( W_LOG_ERR, "ReadDirectoryChangesW: failed, cancel watch. %s\n", win32_strerror(err)); root->cancel(); return; } // Signal that we are done with init. We MUST do this AFTER our first // successful ReadDirectoryChangesW, otherwise there is a race condition // where we'll miss observing the cookie for a query that comes in // after we've crawled but before the watch is established. w_log(W_LOG_DBG, "ReadDirectoryChangesW signalling as init done\n"); cond.notify_one(); } initiate_read = false; std::list<Item> items; // The mutex must not be held when we enter the loop while (!root->inner.cancelled) { if (initiate_read) { if (!ReadDirectoryChangesW( (HANDLE)dir_handle.handle(), &buf[0], size, TRUE, filter, nullptr, &olap, nullptr)) { err = GetLastError(); w_log(W_LOG_ERR, "ReadDirectoryChangesW: failed, cancel watch. %s\n", win32_strerror(err)); root->cancel(); break; } else { initiate_read = false; } } watchman::log(watchman::DBG, "waiting for change notifications\n"); DWORD status = WaitForMultipleObjects( 2, handles, FALSE, // We use a 10 second timeout by default until we start accumulating a // batch. Once we have a batch we prefer to add more to it than notify // immediately, so we introduce a 30ms latency. Without this artificial // latency we'll wake up and start trying to look at a directory that // may be in the process of being recursively deleted and that act can // block the recursive delete. items.empty() ? 10000 : extraLatency); watchman::log(watchman::DBG, "wait returned with status ", status, "\n"); if (status == WAIT_OBJECT_0) { bytes = 0; if (!GetOverlappedResult( (HANDLE)dir_handle.handle(), &olap, &bytes, FALSE)) { err = GetLastError(); w_log( W_LOG_ERR, "overlapped ReadDirectoryChangesW(%s): 0x%x %s\n", root->root_path.c_str(), err, win32_strerror(err)); if (err == ERROR_INVALID_PARAMETER && size > NETWORK_BUF_SIZE) { // May be a network buffer related size issue; the docs say that // we can hit this when watching a UNC path. Let's downsize and // retry the read just one time w_log( W_LOG_ERR, "retrying watch for possible network location %s " "with smaller buffer\n", root->root_path.c_str()); size = NETWORK_BUF_SIZE; initiate_read = true; continue; } if (err == ERROR_NOTIFY_ENUM_DIR) { root->scheduleRecrawl("ERROR_NOTIFY_ENUM_DIR"); } else { w_log( W_LOG_ERR, "Cancelling watch for %s\n", root->root_path.c_str()); root->cancel(); break; } } else { PFILE_NOTIFY_INFORMATION notify = (PFILE_NOTIFY_INFORMATION)buf.data(); while (true) { DWORD n_chars; // FileNameLength is in BYTES, but FileName is WCHAR n_chars = notify->FileNameLength / sizeof(notify->FileName[0]); w_string name(notify->FileName, n_chars); auto full = w_string::pathCat({root->root_path, name}); if (!root->ignore.isIgnored(full.data(), full.size())) { // If we have a delete or rename-away it may be part of // a recursive tree remove or rename. In that situation // the notifications that we'll receive from the OS will // be from the leaves and bubble up to the root of the // delete/rename. We want to flag those paths for recursive // analysis so that we can prune children from the trie // that is built when we pass this to the pending list // later. We don't do that here in this thread because // we're trying to minimize latency in this context. items.emplace_back( std::move(full), (notify->Action & (FILE_ACTION_REMOVED | FILE_ACTION_RENAMED_OLD_NAME)) != 0 ? W_PENDING_RECURSIVE : 0); } // Advance to next item if (notify->NextEntryOffset == 0) { break; } notify = (PFILE_NOTIFY_INFORMATION)( notify->NextEntryOffset + (char*)notify); } ResetEvent(olapEvent); initiate_read = true; } } else if (status == WAIT_OBJECT_0 + 1) { w_log(W_LOG_ERR, "signalled\n"); break; } else if (status == WAIT_TIMEOUT) { if (!items.empty()) { watchman::log(watchman::DBG, "timed out waiting for changes, and we have ", items.size(), " items; move and notify\n"); auto wlock = changedItems.lock(); wlock->splice(wlock->end(), items); cond.notify_one(); } } else { w_log(W_LOG_ERR, "impossible wait status=%d\n", status); break; } } w_log(W_LOG_DBG, "done\n"); } bool WinWatcher::start(const std::shared_ptr<w_root_t>& root) { int err; // Spin up the changes reading thread; it owns a ref on the root try { // Acquire the mutex so thread initialization waits until we release it auto wlock = changedItems.lock(); watchman::log(watchman::DBG, "starting readChangesThread\n"); auto self = std::dynamic_pointer_cast<WinWatcher>(shared_from_this()); std::thread thread([ self, root ]() noexcept { try { self->readChangesThread(root); } catch (const std::exception& e) { watchman::log(watchman::ERR, "uncaught exception: ", e.what()); root->cancel(); } // Ensure that we signal the condition variable before we // finish this thread. That ensures that don't get stuck // waiting in WinWatcher::start if something unexpected happens. auto wlock = self->changedItems.lock(); self->cond.notify_one(); }); // We have to detach because the readChangesThread may wind up // being the last thread to reference the watcher state and // cannot join itself. thread.detach(); // Allow thread init to proceed; wait for its signal if (cond.wait_for(wlock.getUniqueLock(), std::chrono::seconds(10)) == std::cv_status::timeout) { watchman::log( watchman::ERR, "timedout waiting for readChangesThread to start\n"); root->cancel(); return false; } if (root->failure_reason) { w_log( W_LOG_ERR, "failed to start readchanges thread: %s\n", root->failure_reason.c_str()); return false; } return true; } catch (const std::exception& e) { w_log(W_LOG_ERR, "failed to start readchanges thread: %s\n", e.what()); return false; } } std::unique_ptr<watchman_dir_handle> WinWatcher::startWatchDir( const std::shared_ptr<w_root_t>& root, struct watchman_dir* dir, const char* path) { return w_dir_open(path); } bool WinWatcher::consumeNotify( const std::shared_ptr<w_root_t>& root, PendingCollection::LockedPtr& coll) { std::list<Item> items; struct timeval now; { auto wlock = changedItems.lock(); std::swap(items, *wlock); } gettimeofday(&now, nullptr); for (auto& item : items) { watchman::log(watchman::DBG, "readchanges: add pending ", item.path, " ", item.flags, "\n"); coll->add(item.path, now, W_PENDING_VIA_NOTIFY | item.flags); } return !items.empty(); } bool WinWatcher::waitNotify(int timeoutms) { auto wlock = changedItems.lock(); cond.wait_for(wlock.getUniqueLock(), std::chrono::milliseconds(timeoutms)); return !wlock->empty(); } static RegisterWatcher<WinWatcher> reg("win32"); #endif // _WIN32 /* vim:ts=2:sw=2:et: */
Check CreateFileW() return value correctly (#670)
Check CreateFileW() return value correctly (#670) Summary: `CreateFileW()` returns `INVALID_HANDLE_VALUE` if the handle is invalid, so this piece of code wouldn't correct handle a failure here. Switch the code to use the `FileDescriptor` class to make this less error prone. Pull Request resolved: https://github.com/facebook/watchman/pull/670 Reviewed By: simpkins Differential Revision: D13758292 Pulled By: wez fbshipit-source-id: 94a8abf3acfa6df52caa296adf79c595e930c132
C++
mit
nodakai/watchman,wez/watchman,wez/watchman,wez/watchman,wez/watchman,wez/watchman,nodakai/watchman,nodakai/watchman,wez/watchman,facebook/watchman,facebook/watchman,nodakai/watchman,facebook/watchman,nodakai/watchman,facebook/watchman,wez/watchman,nodakai/watchman,wez/watchman,nodakai/watchman,wez/watchman,facebook/watchman,facebook/watchman,facebook/watchman,nodakai/watchman,facebook/watchman,facebook/watchman,nodakai/watchman
b110e527599082a374517978187072092358b535
moveit_ros/perception/point_containment_filter/src/shape_mask.cpp
moveit_ros/perception/point_containment_filter/src/shape_mask.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, 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 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/point_containment_filter/shape_mask.h> #include <geometric_shapes/body_operations.h> #include <ros/console.h> #include <sensor_msgs/point_cloud2_iterator.h> point_containment_filter::ShapeMask::ShapeMask(const TransformCallback& transform_callback) : transform_callback_(transform_callback), next_handle_ (1), min_handle_ (1) { } point_containment_filter::ShapeMask::~ShapeMask() { freeMemory(); } void point_containment_filter::ShapeMask::freeMemory() { for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) delete it->body; bodies_.clear(); } void point_containment_filter::ShapeMask::setTransformCallback(const TransformCallback& transform_callback) { boost::mutex::scoped_lock _(shapes_lock_); transform_callback_ = transform_callback; } point_containment_filter::ShapeHandle point_containment_filter::ShapeMask::addShape(const shapes::ShapeConstPtr &shape, double scale, double padding) { boost::mutex::scoped_lock _(shapes_lock_); SeeShape ss; ss.body = bodies::createBodyFromShape(shape.get()); if (ss.body) { ss.body->setScale(scale); ss.body->setPadding(padding); ss.volume = ss.body->computeVolume(); ss.handle = next_handle_; std::pair<std::set<SeeShape, SortBodies>::iterator, bool> insert_op = bodies_.insert(ss); if (!insert_op.second) ROS_ERROR("Internal error in management of bodies in ShapeMask. This is a serious error."); used_handles_[next_handle_] = insert_op.first; } else return 0; ShapeHandle ret = next_handle_; const std::size_t sz = min_handle_ + bodies_.size() + 1; for (std::size_t i = min_handle_ ; i < sz ; ++i) if (used_handles_.find(i) == used_handles_.end()) { next_handle_ = i; break; } min_handle_ = next_handle_; return ret; } void point_containment_filter::ShapeMask::removeShape(ShapeHandle handle) { boost::mutex::scoped_lock _(shapes_lock_); std::map<ShapeHandle, std::set<SeeShape, SortBodies>::iterator>::iterator it = used_handles_.find(handle); if (it != used_handles_.end()) { delete it->second->body; bodies_.erase(it->second); used_handles_.erase(it); min_handle_ = handle; } else ROS_ERROR("Unable to remove shape handle %u", handle); } void point_containment_filter::ShapeMask::maskContainment(const sensor_msgs::PointCloud2& data_in, const Eigen::Vector3d &sensor_origin, const double min_sensor_dist, const double max_sensor_dist, std::vector<int> &mask) { boost::mutex::scoped_lock _(shapes_lock_); const unsigned int np = data_in.data.size() / data_in.point_step; mask.resize(np); if (bodies_.empty()) std::fill(mask.begin(), mask.end(), (int)OUTSIDE); else { Eigen::Affine3d tmp; bspheres_.resize(bodies_.size()); std::size_t j = 0; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) { if (transform_callback_(it->handle, tmp)) { it->body->setPose(tmp); it->body->computeBoundingSphere(bspheres_[j++]); } } // compute a sphere that bounds the entire robot bodies::BoundingSphere bound; bodies::mergeBoundingSpheres(bspheres_, bound); const double radiusSquared = bound.radius * bound.radius; // we now decide which points we keep sensor_msgs::PointCloud2ConstIterator<float> iter_x(data_in, "x"); sensor_msgs::PointCloud2ConstIterator<float> iter_y(data_in, "y"); sensor_msgs::PointCloud2ConstIterator<float> iter_z(data_in, "z"); // Cloud iterators are not incremented in the for loop, because of the pragma #pragma omp parallel for schedule(dynamic) for (int i = 0 ; i < (int)np ; ++i) { Eigen::Vector3d pt = Eigen::Vector3d(*(iter_x+i), *(iter_y+i), *(iter_z+i)); double d = pt.norm(); int out = OUTSIDE; if (d < min_sensor_dist || d > max_sensor_dist) out = CLIP; else if ((bound.center - pt).squaredNorm() < radiusSquared) for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) if (it->body->containsPoint(pt)) out = INSIDE; mask[i] = out; } } } int point_containment_filter::ShapeMask::getMaskContainment(const Eigen::Vector3d &pt) const { boost::mutex::scoped_lock _(shapes_lock_); int out = OUTSIDE; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) if (it->body->containsPoint(pt)) out = INSIDE; return out; } int point_containment_filter::ShapeMask::getMaskContainment(double x, double y, double z) const { return getMaskContainment(Eigen::Vector3d(x, y, z)); }
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, 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 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/point_containment_filter/shape_mask.h> #include <geometric_shapes/body_operations.h> #include <ros/console.h> #include <sensor_msgs/point_cloud2_iterator.h> point_containment_filter::ShapeMask::ShapeMask(const TransformCallback& transform_callback) : transform_callback_(transform_callback), next_handle_ (1), min_handle_ (1) { } point_containment_filter::ShapeMask::~ShapeMask() { freeMemory(); } void point_containment_filter::ShapeMask::freeMemory() { for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) delete it->body; bodies_.clear(); } void point_containment_filter::ShapeMask::setTransformCallback(const TransformCallback& transform_callback) { boost::mutex::scoped_lock _(shapes_lock_); transform_callback_ = transform_callback; } point_containment_filter::ShapeHandle point_containment_filter::ShapeMask::addShape(const shapes::ShapeConstPtr &shape, double scale, double padding) { boost::mutex::scoped_lock _(shapes_lock_); SeeShape ss; ss.body = bodies::createBodyFromShape(shape.get()); if (ss.body) { ss.body->setScale(scale); ss.body->setPadding(padding); ss.volume = ss.body->computeVolume(); ss.handle = next_handle_; std::pair<std::set<SeeShape, SortBodies>::iterator, bool> insert_op = bodies_.insert(ss); if (!insert_op.second) ROS_ERROR("Internal error in management of bodies in ShapeMask. This is a serious error."); used_handles_[next_handle_] = insert_op.first; } else return 0; ShapeHandle ret = next_handle_; const std::size_t sz = min_handle_ + bodies_.size() + 1; for (std::size_t i = min_handle_ ; i < sz ; ++i) if (used_handles_.find(i) == used_handles_.end()) { next_handle_ = i; break; } min_handle_ = next_handle_; return ret; } void point_containment_filter::ShapeMask::removeShape(ShapeHandle handle) { boost::mutex::scoped_lock _(shapes_lock_); std::map<ShapeHandle, std::set<SeeShape, SortBodies>::iterator>::iterator it = used_handles_.find(handle); if (it != used_handles_.end()) { delete it->second->body; bodies_.erase(it->second); used_handles_.erase(it); min_handle_ = handle; } else ROS_ERROR("Unable to remove shape handle %u", handle); } void point_containment_filter::ShapeMask::maskContainment(const sensor_msgs::PointCloud2& data_in, const Eigen::Vector3d &sensor_origin, const double min_sensor_dist, const double max_sensor_dist, std::vector<int> &mask) { boost::mutex::scoped_lock _(shapes_lock_); const unsigned int np = data_in.data.size() / data_in.point_step; mask.resize(np); if (bodies_.empty()) std::fill(mask.begin(), mask.end(), (int)OUTSIDE); else { Eigen::Affine3d tmp; bspheres_.resize(bodies_.size()); std::size_t j = 0; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) { if (transform_callback_(it->handle, tmp)) { it->body->setPose(tmp); it->body->computeBoundingSphere(bspheres_[j++]); } } // compute a sphere that bounds the entire robot bodies::BoundingSphere bound; bodies::mergeBoundingSpheres(bspheres_, bound); const double radiusSquared = bound.radius * bound.radius; // we now decide which points we keep sensor_msgs::PointCloud2ConstIterator<float> iter_x(data_in, "x"); sensor_msgs::PointCloud2ConstIterator<float> iter_y(data_in, "y"); sensor_msgs::PointCloud2ConstIterator<float> iter_z(data_in, "z"); // Cloud iterators are not incremented in the for loop, because of the pragma // Comment out below parallelization as it can result in very high CPU consumption //#pragma omp parallel for schedule(dynamic) for (int i = 0 ; i < (int)np ; ++i) { Eigen::Vector3d pt = Eigen::Vector3d(*(iter_x+i), *(iter_y+i), *(iter_z+i)); double d = pt.norm(); int out = OUTSIDE; if (d < min_sensor_dist || d > max_sensor_dist) out = CLIP; else if ((bound.center - pt).squaredNorm() < radiusSquared) for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) if (it->body->containsPoint(pt)) out = INSIDE; mask[i] = out; } } } int point_containment_filter::ShapeMask::getMaskContainment(const Eigen::Vector3d &pt) const { boost::mutex::scoped_lock _(shapes_lock_); int out = OUTSIDE; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) if (it->body->containsPoint(pt)) out = INSIDE; return out; } int point_containment_filter::ShapeMask::getMaskContainment(double x, double y, double z) const { return getMaskContainment(Eigen::Vector3d(x, y, z)); }
Remove OpenMP parallelization, fixes #563
Remove OpenMP parallelization, fixes #563
C++
bsd-3-clause
davetcoleman/moveit,v4hn/moveit,ros-planning/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit,davetcoleman/moveit,davetcoleman/moveit,v4hn/moveit,ros-planning/moveit,v4hn/moveit,v4hn/moveit,ros-planning/moveit
ea034078a6609c2090d04dd54587cbee51572be7
drivers/common/common.hpp
drivers/common/common.hpp
/// Common commands for all bitstreams /// /// (c) Koheron #ifndef __DRIVERS_COMMON_HPP__ #define __DRIVERS_COMMON_HPP__ #include <cstring> #include <array> extern "C" { #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <ifaddrs.h> } #include <drivers/lib/memory_manager.hpp> #include <drivers/init/init.hpp> #include <drivers/memory.hpp> class Common { public: Common(MemoryManager& mm_) : mm(mm_) , cfg(mm.get<mem::config>()) , sts(mm.get<mem::status>()) {} auto& get_bitstream_id() { return sts.read_array<uint32_t, prm::bitstream_id_size, reg::bitstream_id>(); } uint64_t get_dna() { return sts.read<reg::dna, uint64_t>(); } void set_led(uint32_t value) { cfg.write<reg::led>(value); } uint32_t get_led() { return cfg.read<reg::led>(); } void init() { ip_on_leds(); Init init(mm); init.load_settings(); }; void cfg_write(uint32_t offset, uint32_t value) { cfg.write_reg(offset, value); } uint32_t cfg_read(uint32_t offset) { return cfg.read_reg(offset); } auto& cfg_read_all() { return cfg.read_array<uint32_t, mem::config_range/4>(); } auto& sts_read_all() { return sts.read_array<uint32_t, mem::status_range/4>(); } uint32_t sts_read(uint32_t offset) { return sts.read_reg(offset); } std::string get_instrument_config() { return CFG_JSON; } void ip_on_leds() { struct ifaddrs *addrs; getifaddrs(&addrs); ifaddrs *tmp = addrs; // Turn all the leds ON cfg.write<reg::led>(255); char interface[] = "eth0"; while (tmp) { // Works only for IPv4 address if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr; int val = strcmp(tmp->ifa_name,interface); if (val != 0) { tmp = tmp->ifa_next; continue; } printf("Interface %s found: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr)); uint32_t ip = htonl(pAddr->sin_addr.s_addr); // Write IP address in FPGA memory // The 8 Least Significant Bits should be connected to the FPGA LEDs cfg.write<reg::led>(ip); break; } tmp = tmp->ifa_next; } freeifaddrs(addrs); } private: MemoryManager& mm; Memory<mem::config>& cfg; Memory<mem::status>& sts; }; #endif // __DRIVERS_COMMON_HPP__
/// Common commands for all bitstreams /// /// (c) Koheron #ifndef __DRIVERS_COMMON_HPP__ #define __DRIVERS_COMMON_HPP__ #include <cstring> #include <array> extern "C" { #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <ifaddrs.h> } #include <drivers/lib/memory_manager.hpp> #include <drivers/init/init.hpp> #include <drivers/memory.hpp> class Common { public: Common(MemoryManager& mm_) : mm(mm_) , cfg(mm.get<mem::config>()) , sts(mm.get<mem::status>()) {} auto& get_bitstream_id() { return sts.read_array<uint32_t, prm::bitstream_id_size, reg::bitstream_id>(); } uint64_t get_dna() { return sts.read<reg::dna, uint64_t>(); } void set_led(uint32_t value) { cfg.write<reg::led>(value); } uint32_t get_led() { return cfg.read<reg::led>(); } void init() { ip_on_leds(); Init init(mm); init.load_settings(); }; void cfg_write(uint32_t offset, uint32_t value) { cfg.write_reg(offset, value); } uint32_t cfg_read(uint32_t offset) { return cfg.read_reg(offset); } auto& cfg_read_all() { return cfg.read_array<uint32_t, mem::config_range/4>(); } auto& sts_read_all() { return sts.read_array<uint32_t, mem::status_range/4>(); } uint32_t sts_read(uint32_t offset) { return sts.read_reg(offset); } std::string get_instrument_config() { return CFG_JSON; } void ip_on_leds() { struct ifaddrs *addrs; getifaddrs(&addrs); ifaddrs *tmp = addrs; // Turn all the leds ON cfg.write<reg::led>(255); char interface[] = "eth0"; while (tmp) { // Works only for IPv4 address if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr; int val = strcmp(tmp->ifa_name,interface); if (val != 0) { tmp = tmp->ifa_next; continue; } printf("Interface %s found: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr)); uint32_t ip = htonl(pAddr->sin_addr.s_addr); // Write IP address in FPGA memory // The 8 Least Significant Bits should be connected to the FPGA LEDs cfg.write_mask<reg::led, 0xFF>(ip); break; } tmp = tmp->ifa_next; } freeifaddrs(addrs); } private: MemoryManager& mm; Memory<mem::config>& cfg; Memory<mem::status>& sts; }; #endif // __DRIVERS_COMMON_HPP__
write only the 8 least sign. bits of ip address (#298)
write only the 8 least sign. bits of ip address (#298)
C++
mit
Koheron/zynq-sdk,Koheron/zynq-sdk,Koheron/zynq-sdk,Koheron/zynq-sdk
937874bb9867c854a3e6bd2d111be9aabcaacd78
HelloWorld/HelloWorld.cpp
HelloWorld/HelloWorld.cpp
#include <iostream> #include <string> #include <vector> using namespace std; vector <string> Census; void Census2017(){ // Census.push_back("Name @ GitHub link"); Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci"); Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew"); Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58"); Census.push_back("TexasSnow @ https://github.com/TexasSnow"); Census.push_back("hotdogshabab @ https://github.com/hotdogshabab"); Census.push_back("alansunglee @ https://github.com/alansunglee"); Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12"); Census.push_back("spicyboi @ https://github.com/spicyboi"); Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff"); Census.push_back("CodeTimesTen @ https://github.com/CodeTimesTen"); Census.push_back("YourFriendlyNeighborhoodSpiderman @ https://github.com/YourFriendlyNeighborhoodSpiderman"); Census.push_back("Devin Petersen @ https://github.com/DevinPetersen"); Census.push_back("Cameron Mathis @ https://github.com/Phylux"); Census.push_back("Samuel Woon @ https://github.com/samuel-w"); Census.push_back("JustinV10 @ https://github.com/JustinV10"); Census.push_back("Kyleaustin36 @ https://github.com/kyleaustin36"); Census.push_back("Maaz Kamal @ https://github.com/Maze-Camel"); Census.push_back("bingood4ever @ https://github.com/bingood4ever"); Census.push_back("Gainz101 @ https://github.com/Gainz101"); } void printCensus(){ for(int i = 0; i < (int)Census.size(); i++){ cout << "Hello World from "Your name" + Census[i] << "\n"; } } //test void main(){ Census2017(); printCensus(); }
#include <iostream> #include <string> #include <vector> using namespace std; vector <string> Census; void Census2017(){ // Census.push_back("Name @ GitHub link"); Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci"); Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew"); Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58"); Census.push_back("TexasSnow @ https://github.com/TexasSnow"); Census.push_back("hotdogshabab @ https://github.com/hotdogshabab"); Census.push_back("alansunglee @ https://github.com/alansunglee"); Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12"); Census.push_back("spicyboi @ https://github.com/spicyboi"); Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff"); Census.push_back("CodeTimesTen @ https://github.com/CodeTimesTen"); Census.push_back("YourFriendlyNeighborhoodSpiderman @ https://github.com/YourFriendlyNeighborhoodSpiderman"); Census.push_back("Devin Petersen @ https://github.com/DevinPetersen"); Census.push_back("Cameron Mathis @ https://github.com/Phylux"); Census.push_back("Samuel Woon @ https://github.com/samuel-w"); Census.push_back("JustinV10 @ https://github.com/JustinV10"); Census.push_back("Kyleaustin36 @ https://github.com/kyleaustin36"); Census.push_back("Maaz Kamal @ https://github.com/Maze-Camel"); Census.push_back("bingood4ever @ https://github.com/bingood4ever"); Census.push_back("Gainz101 @ https://github.com/Gainz101"); Census.push_back("zachdogg @ https://github.com/Zachdogg1"); } void printCensus(){ for(int i = 0; i < (int)Census.size(); i++){ cout << "Hello World from "Your name" + Census[i] << "\n"; } } //test void main(){ Census2017(); printCensus(); }
Update HelloWorld.cpp
Update HelloWorld.cpp
C++
mit
AjiteshGupta/Hacktoberfest,AjiteshGupta/Hacktoberfest,PAWAN-KUMAR-GAUTAM000/Hacktoberfest,AllenCompSci/Hacktoberfest,TharinduDilshan/Hacktoberfest-1,deepanshu22/Hacktoberfest-1,deepanshu22/Hacktoberfest-1,deepanshu22/Hacktoberfest-1,joycemaaa/Hacktoberfest-2,PAWAN-KUMAR-GAUTAM000/Hacktoberfest,deepanshu22/Hacktoberfest-1,joycemaaa/Hacktoberfest-2,joycemaaa/Hacktoberfest-2,joycemaaa/Hacktoberfest-2,PAWAN-KUMAR-GAUTAM000/Hacktoberfest,TharinduDilshan/Hacktoberfest-1,AjiteshGupta/Hacktoberfest,AllenCompSci/Hacktoberfest,AllenCompSci/Hacktoberfest,deepanshu22/Hacktoberfest-1,PAWAN-KUMAR-GAUTAM000/Hacktoberfest,AllenCompSci/Hacktoberfest,deepanshu22/Hacktoberfest-1,AjiteshGupta/Hacktoberfest,PAWAN-KUMAR-GAUTAM000/Hacktoberfest,joycemaaa/Hacktoberfest-2,AllenCompSci/Hacktoberfest,AllenCompSci/Hacktoberfest,TharinduDilshan/Hacktoberfest-1,joycemaaa/Hacktoberfest-2,joycemaaa/Hacktoberfest-2,TharinduDilshan/Hacktoberfest-1,deepanshu22/Hacktoberfest-1,TharinduDilshan/Hacktoberfest-1,PAWAN-KUMAR-GAUTAM000/Hacktoberfest,TharinduDilshan/Hacktoberfest-1,AllenCompSci/Hacktoberfest,AjiteshGupta/Hacktoberfest,TharinduDilshan/Hacktoberfest-1,AjiteshGupta/Hacktoberfest
65a17539d2ab1866b2c8252155b0a7fbe127d861
gm/showmiplevels.cpp
gm/showmiplevels.cpp
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkBitmapScaler.h" #include "SkGradientShader.h" #include "SkTypeface.h" #include "SkStream.h" #include "SkPaint.h" #include "SkMipMap.h" #include "Resources.h" #include "sk_tool_utils.h" #define SHOW_MIP_COLOR 0xFF000000 static SkBitmap make_bitmap(int w, int h) { SkBitmap bm; bm.allocN32Pixels(w, h); SkCanvas canvas(bm); canvas.clear(0xFFFFFFFF); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(w / 16.0f); paint.setColor(SHOW_MIP_COLOR); canvas.drawCircle(w/2.0f, h/2.0f, w/3.0f, paint); return bm; } static SkBitmap make_bitmap2(int w, int h) { SkBitmap bm; bm.allocN32Pixels(w, h); SkCanvas canvas(bm); canvas.clear(0xFFFFFFFF); SkPaint paint; paint.setColor(SHOW_MIP_COLOR); paint.setStyle(SkPaint::kStroke_Style); SkScalar inset = 2; SkRect r = SkRect::MakeIWH(w, h).makeInset(0.5f, 0.5f); while (r.width() > 4) { canvas.drawRect(r, paint); r.inset(inset, inset); inset += 1; } return bm; } #include "SkNx.h" static SkBitmap make_bitmap3(int w, int h) { SkBitmap bm; bm.allocN32Pixels(w, h); SkCanvas canvas(bm); canvas.clear(0xFFFFFFFF); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(2.1f); paint.setColor(SHOW_MIP_COLOR); SkScalar s = SkIntToScalar(w); Sk4f p(s, -s, -s, s); Sk4f d(5); while (p[1] < s) { canvas.drawLine(p[0],p[1], p[2], p[3], paint); p = p + d; } return bm; } class ShowMipLevels : public skiagm::GM { const int fN; SkBitmap fBM[4]; public: static unsigned gamma(unsigned n) { float x = n / 255.0f; #if 0 x = sqrtf(x); #else if (x > 0.0031308f) { x = 1.055f * (powf(x, (1.0f / 2.4f))) - 0.055f; } else { x = 12.92f * x; } #endif return (int)(x * 255); } static void apply_gamma(const SkBitmap& bm) { return; // below is our experiment for sRGB correction bm.lockPixels(); for (int y = 0; y < bm.height(); ++y) { for (int x = 0; x < bm.width(); ++x) { SkPMColor c = *bm.getAddr32(x, y); unsigned r = gamma(SkGetPackedR32(c)); unsigned g = gamma(SkGetPackedG32(c)); unsigned b = gamma(SkGetPackedB32(c)); *bm.getAddr32(x, y) = SkPackARGB32(0xFF, r, g, b); } } } ShowMipLevels(int N) : fN(N) { } protected: SkString onShortName() override { SkString str; str.printf("showmiplevels_%d", fN); return str; } SkISize onISize() override { return { 824, 862 }; } static void DrawAndFrame(SkCanvas* canvas, const SkBitmap& orig, SkScalar x, SkScalar y) { SkBitmap bm; orig.copyTo(&bm); apply_gamma(bm); canvas->drawBitmap(bm, x, y, nullptr); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setColor(0xFFFFCCCC); canvas->drawRect(SkRect::MakeIWH(bm.width(), bm.height()).makeOffset(x, y).makeOutset(0.5f, 0.5f), paint); } template <typename F> void drawLevels(SkCanvas* canvas, const SkBitmap& baseBM, F func) { SkScalar x = 4; SkScalar y = 4; SkPixmap prevPM; baseBM.lockPixels(); baseBM.peekPixels(&prevPM); SkDestinationSurfaceColorMode colorMode = SkDestinationSurfaceColorMode::kLegacy; sk_sp<SkMipMap> mm(SkMipMap::Build(baseBM, colorMode, nullptr)); int index = 0; SkMipMap::Level level; SkScalar scale = 0.5f; while (mm->extractLevel(SkSize::Make(scale, scale), &level)) { SkBitmap bm = func(prevPM, level.fPixmap); DrawAndFrame(canvas, bm, x, y); if (level.fPixmap.width() <= 2 || level.fPixmap.height() <= 2) { break; } if (index & 1) { x += level.fPixmap.width() + 4; } else { y += level.fPixmap.height() + 4; } scale /= 2; prevPM = level.fPixmap; index += 1; } } void drawSet(SkCanvas* canvas, const SkBitmap& orig) { SkAutoCanvasRestore acr(canvas, true); drawLevels(canvas, orig, [](const SkPixmap& prev, const SkPixmap& curr) { SkBitmap bm; bm.installPixels(curr); return bm; }); const SkBitmapScaler::ResizeMethod methods[] = { SkBitmapScaler::RESIZE_BOX, SkBitmapScaler::RESIZE_TRIANGLE, SkBitmapScaler::RESIZE_LANCZOS3, SkBitmapScaler::RESIZE_HAMMING, SkBitmapScaler::RESIZE_MITCHELL, }; SkPixmap basePM; orig.lockPixels(); orig.peekPixels(&basePM); for (auto method : methods) { canvas->translate(orig.width()/2 + 8.0f, 0); drawLevels(canvas, orig, [basePM, method](const SkPixmap& prev, const SkPixmap& curr) { SkBitmap bm; SkBitmapScaler::Resize(&bm, prev, method, curr.width(), curr.height()); return bm; }); } } void onOnceBeforeDraw() override { fBM[0] = sk_tool_utils::create_checkerboard_bitmap(fN, fN, SK_ColorBLACK, SK_ColorWHITE, 2); fBM[1] = make_bitmap(fN, fN); fBM[2] = make_bitmap2(fN, fN); fBM[3] = make_bitmap3(fN, fN); } void onDraw(SkCanvas* canvas) override { canvas->translate(4, 4); for (const auto& bm : fBM) { this->drawSet(canvas, bm); canvas->translate(0, bm.height() * 0.85f); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new ShowMipLevels(255); ) DEF_GM( return new ShowMipLevels(256); ) /////////////////////////////////////////////////////////////////////////////////////////////////// void copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) { if (kGray_8_SkColorType == dstColorType) { return sk_tool_utils::copy_to_g8(dst, src); } src.copyTo(dst, dstColorType); } /** * Show mip levels that were built, for all supported colortypes */ class ShowMipLevels2 : public skiagm::GM { const int fW, fH; SkBitmap fBM[4]; public: ShowMipLevels2(int w, int h) : fW(w), fH(h) { } protected: SkString onShortName() override { SkString str; str.printf("showmiplevels2_%dx%d", fW, fH); return str; } SkISize onISize() override { return { 824, 862 }; } static void DrawAndFrame(SkCanvas* canvas, const SkBitmap& bm, SkScalar x, SkScalar y) { canvas->drawBitmap(bm, x, y, nullptr); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setColor(0xFFFFCCCC); canvas->drawRect(SkRect::MakeIWH(bm.width(), bm.height()).makeOffset(x, y).makeOutset(0.5f, 0.5f), paint); } void drawLevels(SkCanvas* canvas, const SkBitmap& baseBM) { SkScalar x = 4; SkScalar y = 4; SkDestinationSurfaceColorMode colorMode = SkDestinationSurfaceColorMode::kLegacy; sk_sp<SkMipMap> mm(SkMipMap::Build(baseBM, colorMode, nullptr)); int index = 0; SkMipMap::Level level; SkScalar scale = 0.5f; while (mm->extractLevel(SkSize::Make(scale, scale), &level)) { SkBitmap bm; bm.installPixels(level.fPixmap); DrawAndFrame(canvas, bm, x, y); if (level.fPixmap.width() <= 2 || level.fPixmap.height() <= 2) { break; } if (index & 1) { x += level.fPixmap.width() + 4; } else { y += level.fPixmap.height() + 4; } scale /= 2; index += 1; } } void drawSet(SkCanvas* canvas, const SkBitmap& orig) { const SkColorType ctypes[] = { kN32_SkColorType, kRGB_565_SkColorType, kARGB_4444_SkColorType, kGray_8_SkColorType }; SkAutoCanvasRestore acr(canvas, true); for (auto ctype : ctypes) { SkBitmap bm; copy_to(&bm, ctype, orig); drawLevels(canvas, bm); canvas->translate(orig.width()/2 + 8.0f, 0); } } void onOnceBeforeDraw() override { fBM[0] = sk_tool_utils::create_checkerboard_bitmap(fW, fH, SHOW_MIP_COLOR, SK_ColorWHITE, 2); fBM[1] = make_bitmap(fW, fH); fBM[2] = make_bitmap2(fW, fH); fBM[3] = make_bitmap3(fW, fH); } void onDraw(SkCanvas* canvas) override { canvas->translate(4, 4); for (const auto& bm : fBM) { this->drawSet(canvas, bm); // round so we always produce an integral translate, so the GOLD tool won't show // unimportant diffs if this is drawn on a GPU with different rounding rules // since we draw the bitmaps using nearest-neighbor canvas->translate(0, SkScalarRoundToScalar(bm.height() * 0.85f)); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new ShowMipLevels2(255, 255); ) DEF_GM( return new ShowMipLevels2(256, 255); ) DEF_GM( return new ShowMipLevels2(255, 256); ) DEF_GM( return new ShowMipLevels2(256, 256); )
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkBitmapScaler.h" #include "SkGradientShader.h" #include "SkTypeface.h" #include "SkStream.h" #include "SkPaint.h" #include "SkMipMap.h" #include "Resources.h" #include "sk_tool_utils.h" #define SHOW_MIP_COLOR 0xFF000000 static SkBitmap make_bitmap(int w, int h) { SkBitmap bm; bm.allocN32Pixels(w, h); SkCanvas canvas(bm); canvas.clear(0xFFFFFFFF); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(w / 16.0f); paint.setColor(SHOW_MIP_COLOR); canvas.drawCircle(w/2.0f, h/2.0f, w/3.0f, paint); return bm; } static SkBitmap make_bitmap2(int w, int h) { SkBitmap bm; bm.allocN32Pixels(w, h); SkCanvas canvas(bm); canvas.clear(0xFFFFFFFF); SkPaint paint; paint.setColor(SHOW_MIP_COLOR); paint.setStyle(SkPaint::kStroke_Style); SkScalar inset = 2; SkRect r = SkRect::MakeIWH(w, h).makeInset(0.5f, 0.5f); while (r.width() > 4) { canvas.drawRect(r, paint); r.inset(inset, inset); inset += 1; } return bm; } #include "SkNx.h" static SkBitmap make_bitmap3(int w, int h) { SkBitmap bm; bm.allocN32Pixels(w, h); SkCanvas canvas(bm); canvas.clear(0xFFFFFFFF); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(2.1f); paint.setColor(SHOW_MIP_COLOR); SkScalar s = SkIntToScalar(w); Sk4f p(s, -s, -s, s); Sk4f d(5); while (p[1] < s) { canvas.drawLine(p[0],p[1], p[2], p[3], paint); p = p + d; } return bm; } class ShowMipLevels : public skiagm::GM { const int fN; SkBitmap fBM[4]; public: static unsigned gamma(unsigned n) { float x = n / 255.0f; #if 0 x = sqrtf(x); #else if (x > 0.0031308f) { x = 1.055f * (powf(x, (1.0f / 2.4f))) - 0.055f; } else { x = 12.92f * x; } #endif return (int)(x * 255); } static void apply_gamma(const SkBitmap& bm) { return; // below is our experiment for sRGB correction bm.lockPixels(); for (int y = 0; y < bm.height(); ++y) { for (int x = 0; x < bm.width(); ++x) { SkPMColor c = *bm.getAddr32(x, y); unsigned r = gamma(SkGetPackedR32(c)); unsigned g = gamma(SkGetPackedG32(c)); unsigned b = gamma(SkGetPackedB32(c)); *bm.getAddr32(x, y) = SkPackARGB32(0xFF, r, g, b); } } } ShowMipLevels(int N) : fN(N) { } protected: SkString onShortName() override { SkString str; str.printf("showmiplevels_%d", fN); return str; } SkISize onISize() override { return { 824, 862 }; } static void DrawAndFrame(SkCanvas* canvas, const SkBitmap& orig, SkScalar x, SkScalar y) { SkBitmap bm; orig.copyTo(&bm); apply_gamma(bm); canvas->drawBitmap(bm, x, y, nullptr); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setColor(0xFFFFCCCC); canvas->drawRect(SkRect::MakeIWH(bm.width(), bm.height()).makeOffset(x, y).makeOutset(0.5f, 0.5f), paint); } template <typename F> void drawLevels(SkCanvas* canvas, const SkBitmap& baseBM, F func) { SkScalar x = 4; SkScalar y = 4; SkPixmap prevPM; baseBM.lockPixels(); baseBM.peekPixels(&prevPM); SkDestinationSurfaceColorMode colorMode = SkDestinationSurfaceColorMode::kLegacy; sk_sp<SkMipMap> mm(SkMipMap::Build(baseBM, colorMode, nullptr)); int index = 0; SkMipMap::Level level; SkScalar scale = 0.5f; while (mm->extractLevel(SkSize::Make(scale, scale), &level)) { SkBitmap bm = func(prevPM, level.fPixmap); DrawAndFrame(canvas, bm, x, y); if (level.fPixmap.width() <= 2 || level.fPixmap.height() <= 2) { break; } if (index & 1) { x += level.fPixmap.width() + 4; } else { y += level.fPixmap.height() + 4; } scale /= 2; prevPM = level.fPixmap; index += 1; } } void drawSet(SkCanvas* canvas, const SkBitmap& orig) { SkAutoCanvasRestore acr(canvas, true); drawLevels(canvas, orig, [](const SkPixmap& prev, const SkPixmap& curr) { SkBitmap bm; bm.installPixels(curr); return bm; }); const SkBitmapScaler::ResizeMethod methods[] = { SkBitmapScaler::RESIZE_BOX, SkBitmapScaler::RESIZE_TRIANGLE, SkBitmapScaler::RESIZE_LANCZOS3, SkBitmapScaler::RESIZE_HAMMING, SkBitmapScaler::RESIZE_MITCHELL, }; SkPixmap basePM; orig.lockPixels(); orig.peekPixels(&basePM); for (auto method : methods) { canvas->translate(orig.width()/2 + 8.0f, 0); drawLevels(canvas, orig, [method](const SkPixmap& prev, const SkPixmap& curr) { SkBitmap bm; SkBitmapScaler::Resize(&bm, prev, method, curr.width(), curr.height()); return bm; }); } } void onOnceBeforeDraw() override { fBM[0] = sk_tool_utils::create_checkerboard_bitmap(fN, fN, SK_ColorBLACK, SK_ColorWHITE, 2); fBM[1] = make_bitmap(fN, fN); fBM[2] = make_bitmap2(fN, fN); fBM[3] = make_bitmap3(fN, fN); } void onDraw(SkCanvas* canvas) override { canvas->translate(4, 4); for (const auto& bm : fBM) { this->drawSet(canvas, bm); canvas->translate(0, bm.height() * 0.85f); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new ShowMipLevels(255); ) DEF_GM( return new ShowMipLevels(256); ) /////////////////////////////////////////////////////////////////////////////////////////////////// void copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) { if (kGray_8_SkColorType == dstColorType) { return sk_tool_utils::copy_to_g8(dst, src); } src.copyTo(dst, dstColorType); } /** * Show mip levels that were built, for all supported colortypes */ class ShowMipLevels2 : public skiagm::GM { const int fW, fH; SkBitmap fBM[4]; public: ShowMipLevels2(int w, int h) : fW(w), fH(h) { } protected: SkString onShortName() override { SkString str; str.printf("showmiplevels2_%dx%d", fW, fH); return str; } SkISize onISize() override { return { 824, 862 }; } static void DrawAndFrame(SkCanvas* canvas, const SkBitmap& bm, SkScalar x, SkScalar y) { canvas->drawBitmap(bm, x, y, nullptr); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setColor(0xFFFFCCCC); canvas->drawRect(SkRect::MakeIWH(bm.width(), bm.height()).makeOffset(x, y).makeOutset(0.5f, 0.5f), paint); } void drawLevels(SkCanvas* canvas, const SkBitmap& baseBM) { SkScalar x = 4; SkScalar y = 4; SkDestinationSurfaceColorMode colorMode = SkDestinationSurfaceColorMode::kLegacy; sk_sp<SkMipMap> mm(SkMipMap::Build(baseBM, colorMode, nullptr)); int index = 0; SkMipMap::Level level; SkScalar scale = 0.5f; while (mm->extractLevel(SkSize::Make(scale, scale), &level)) { SkBitmap bm; bm.installPixels(level.fPixmap); DrawAndFrame(canvas, bm, x, y); if (level.fPixmap.width() <= 2 || level.fPixmap.height() <= 2) { break; } if (index & 1) { x += level.fPixmap.width() + 4; } else { y += level.fPixmap.height() + 4; } scale /= 2; index += 1; } } void drawSet(SkCanvas* canvas, const SkBitmap& orig) { const SkColorType ctypes[] = { kN32_SkColorType, kRGB_565_SkColorType, kARGB_4444_SkColorType, kGray_8_SkColorType }; SkAutoCanvasRestore acr(canvas, true); for (auto ctype : ctypes) { SkBitmap bm; copy_to(&bm, ctype, orig); drawLevels(canvas, bm); canvas->translate(orig.width()/2 + 8.0f, 0); } } void onOnceBeforeDraw() override { fBM[0] = sk_tool_utils::create_checkerboard_bitmap(fW, fH, SHOW_MIP_COLOR, SK_ColorWHITE, 2); fBM[1] = make_bitmap(fW, fH); fBM[2] = make_bitmap2(fW, fH); fBM[3] = make_bitmap3(fW, fH); } void onDraw(SkCanvas* canvas) override { canvas->translate(4, 4); for (const auto& bm : fBM) { this->drawSet(canvas, bm); // round so we always produce an integral translate, so the GOLD tool won't show // unimportant diffs if this is drawn on a GPU with different rounding rules // since we draw the bitmaps using nearest-neighbor canvas->translate(0, SkScalarRoundToScalar(bm.height() * 0.85f)); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new ShowMipLevels2(255, 255); ) DEF_GM( return new ShowMipLevels2(256, 255); ) DEF_GM( return new ShowMipLevels2(255, 256); ) DEF_GM( return new ShowMipLevels2(256, 256); )
Fix clang warning about unused lambda capture.
Fix clang warning about unused lambda capture. This was found by a tip of tree build of clang. Change-Id: I9aa3fecd47ae69350e8d58e796f960a991b7759e Reviewed-on: https://skia-review.googlesource.com/7586 Commit-Queue: Brian Salomon <[email protected]> Reviewed-by: Mike Klein <[email protected]>
C++
bsd-3-clause
HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,rubenvb/skia,aosp-mirror/platform_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,rubenvb/skia,google/skia,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,google/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,rubenvb/skia
e0f15fbc8856aa6930c5e34795f1006e7e4cbe20
TESTS/operators/fusedconvmaxpool/test_operators_fusedconvmaxpool.cpp
TESTS/operators/fusedconvmaxpool/test_operators_fusedconvmaxpool.cpp
#include "test_helper.h" #include "uTensor/loaders/tensorIdxImporter.hpp" #include "MatrixOps.hpp" #include <iostream> using std::cout; using std::endl; TensorIdxImporter t_import; Context ctx; void test_operators_fusedConvMaxpool12(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size2_input.idx"), "x_1_2"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size2_weights.idx"), "w_1_2"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth1_pool_size2_output.idx"), "ref_1_2"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_1_2"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 2, 2, 1 },SAME), { "x_1_2", "w_1_2"}, {"out_1_2"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool13(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size3_input.idx"), "x_1_3"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size3_weights.idx"), "w_1_3"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth1_pool_size3_output.idx"), "ref_1_3"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_1_3"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 3, 3, 1 },SAME), { "x_1_3", "w_1_3"}, {"out_1_3"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool14(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size4_input.idx"), "x_1_4"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size4_weights.idx"), "w_1_4"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth1_pool_size4_output.idx"), "ref_1_4"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_1_4"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 4, 4, 1 },SAME), { "x_1_4", "w_1_4"}, {"out_1_4"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool22(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size2_input.idx"), "x_2_2"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size2_weights.idx"), "w_2_2"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth2_pool_size2_output.idx"), "ref_2_2"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_2_2"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 2, 2, 1 },SAME), { "x_2_2", "w_2_2"}, {"out_2_2"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool23(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size3_input.idx"), "x_2_3"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size3_weights.idx"), "w_2_3"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth2_pool_size3_output.idx"), "ref_2_3"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_2_3"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 3, 3, 1 },SAME), { "x_2_3", "w_2_3"}, {"out_2_3"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool24(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size4_input.idx"), "x_2_4"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size4_weights.idx"), "w_2_4"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth2_pool_size4_output.idx"), "ref_2_4"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_2_4"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 4, 4, 1 },SAME), { "x_2_4", "w_2_4"}, {"out_2_4"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool32(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size2_input.idx"), "x_3_2"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size2_weights.idx"), "w_3_2"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth3_pool_size2_output.idx"), "ref_3_2"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_3_2"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 2, 2, 1 },SAME), { "x_3_2", "w_3_2"}, {"out_3_2"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool33(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size3_input.idx"), "x_3_3"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size3_weights.idx"), "w_3_3"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth3_pool_size3_output.idx"), "ref_3_3"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_3_3"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 3, 3, 1 },SAME), { "x_3_3", "w_3_3"}, {"out_3_3"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool34(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size4_input.idx"), "x_3_4"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size4_weights.idx"), "w_3_4"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth3_pool_size4_output.idx"), "ref_3_4"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_3_4"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 4, 4, 1 },SAME), { "x_3_4", "w_3_4"}, {"out_3_4"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } // First configure the uTensor test runner UTENSOR_TEST_CONFIGURE() // Second declare tests to run UTENSOR_TEST(operators, fusedConvMaxpool12, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool13, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool14, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool22, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool23, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool24, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool32, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool33, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool34, "Generated Fused Conv Maxpool test") // Third, run like hell UTENSOR_TEST_RUN()
#include "test_helper.h" #include "uTensor/loaders/tensorIdxImporter.hpp" #include "MatrixOps.hpp" #include <iostream> using std::cout; using std::endl; TensorIdxImporter t_import; Context ctx; void test_operators_fusedConvMaxpool12(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size2_input.idx"), "x_1_2"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size2_weights.idx"), "w_1_2"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth1_pool_size2_output.idx"), "ref_1_2"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_1_2"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 2, 2, 1 },SAME), { "x_1_2", "w_1_2"}, {"out_1_2"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool13(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size3_input.idx"), "x_1_3"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size3_weights.idx"), "w_1_3"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth1_pool_size3_output.idx"), "ref_1_3"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_1_3"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 3, 3, 1 },SAME), { "x_1_3", "w_1_3"}, {"out_1_3"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool14(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size4_input.idx"), "x_1_4"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth1_pool_size4_weights.idx"), "w_1_4"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth1_pool_size4_output.idx"), "ref_1_4"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_1_4"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 4, 4, 1 },SAME), { "x_1_4", "w_1_4"}, {"out_1_4"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool22(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size2_input.idx"), "x_2_2"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size2_weights.idx"), "w_2_2"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth2_pool_size2_output.idx"), "ref_2_2"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_2_2"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 2, 2, 1 },SAME), { "x_2_2", "w_2_2"}, {"out_2_2"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool23(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size3_input.idx"), "x_2_3"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size3_weights.idx"), "w_2_3"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth2_pool_size3_output.idx"), "ref_2_3"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_2_3"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 3, 3, 1 },SAME), { "x_2_3", "w_2_3"}, {"out_2_3"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool24(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size4_input.idx"), "x_2_4"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth2_pool_size4_weights.idx"), "w_2_4"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth2_pool_size4_output.idx"), "ref_2_4"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_2_4"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 4, 4, 1 },SAME), { "x_2_4", "w_2_4"}, {"out_2_4"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool32(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size2_input.idx"), "x_3_2"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size2_weights.idx"), "w_3_2"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth3_pool_size2_output.idx"), "ref_3_2"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_3_2"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 2, 2, 1 },SAME), { "x_3_2", "w_3_2"}, {"out_3_2"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool33(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size3_input.idx"), "x_3_3"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size3_weights.idx"), "w_3_3"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth3_pool_size3_output.idx"), "ref_3_3"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_3_3"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 3, 3, 1 },SAME), { "x_3_3", "w_3_3"}, {"out_3_3"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); EXPECT_EQ(result, 0); } void test_operators_fusedConvMaxpool34(void) { ctx.gc(); //inputs ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size4_input.idx"), "x_3_4"); ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/in/depth3_pool_size4_weights.idx"), "w_3_4"); //reference outputs S_TENSOR ref = ctx.add(t_import.float_import("/fs/constants/fusedConvMaxpool/out/depth3_pool_size4_output.idx"), "ref_3_4"); //Outputs S_TENSOR out = ctx.add(new RamTensor<float>(ref->getShape()), "out_3_4"); ctx.push(new FusedConvMaxpoolOp<float,float,float>({ 1, 1 }, { 1, 4, 4, 1 },SAME), { "x_3_4", "w_3_4"}, {"out_3_4"}); ctx.eval(); double result = meanPercentErr<float>(ref.get(), out.get()); printf("Mean Percent Error %f", result); EXPECT_EQ(result, 0); } // First configure the uTensor test runner UTENSOR_TEST_CONFIGURE() // Second declare tests to run UTENSOR_TEST(operators, fusedConvMaxpool12, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool13, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool14, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool22, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool23, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool24, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool32, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool33, "Generated Fused Conv Maxpool test") UTENSOR_TEST(operators, fusedConvMaxpool34, "Generated Fused Conv Maxpool test") // Third, run like hell UTENSOR_TEST_RUN()
Add print to test
Add print to test
C++
apache-2.0
neil-tan/uTensor,neil-tan/uTensor
29e641acd17f6bdc500348d1ef5fa4035cf4f146
xls/noc/drivers/sample_experiments_test.cc
xls/noc/drivers/sample_experiments_test.cc
// Copyright 2021 The XLS 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 "xls/noc/drivers/sample_experiments.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "xls/common/logging/logging.h" #include "xls/common/status/matchers.h" #include "xls/noc/drivers/experiment_factory.h" namespace xls::noc { namespace { TEST(SampleExperimentsTest, SimpleVCExperiment) { ExperimentFactory experiment_factory; XLS_ASSERT_OK(RegisterSampleExperiments(experiment_factory)); EXPECT_EQ(experiment_factory.ListExperimentTags().size(), 2); EXPECT_EQ(experiment_factory.ListExperimentTags().at(1), "SimpleVCExperiment"); XLS_ASSERT_OK_AND_ASSIGN( Experiment experiment, experiment_factory.BuildExperiment("SimpleVCExperiment")); EXPECT_EQ( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIds().size(), 2); XLS_EXPECT_OK( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIdByName( "flow_0")); XLS_EXPECT_OK( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIdByName( "flow_1")); XLS_EXPECT_OK( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficModeIdByName( "Main")); EXPECT_EQ(experiment.GetSweeps().GetStepCount(), 4); EXPECT_EQ(experiment.GetRunner().GetTrafficMode(), "Main"); EXPECT_EQ(experiment.GetRunner().GetSimulationCycleCount(), 100'000); EXPECT_EQ(experiment.GetRunner().GetSeed(), 100); EXPECT_EQ(experiment.GetRunner().GetCycleTimeInPs(), 500); std::vector<ExperimentData> experiment_data(4); for (int64_t i = 0; i < experiment.GetSweeps().GetStepCount(); ++i) { XLS_LOG(INFO) << absl::StreamFormat("Experiment Step %d", i); XLS_ASSERT_OK_AND_ASSIGN(experiment_data.at(i), experiment.RunStep(i)); XLS_EXPECT_OK(experiment_data.at(i).metrics.DebugDump()); } // Flow 0 @ 3 GBps and Flow 1 @ 2 GBps // Experiment 0 - Both on VC0 XLS_ASSERT_OK_AND_ASSIGN(double ex0_flow0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Flow:flow_0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex0_flow1_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Flow:flow_1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex0_flow0_traffic_rate) / 100, 30); EXPECT_EQ(static_cast<int64_t>(ex0_flow1_traffic_rate) / 100, 20); XLS_ASSERT_OK_AND_ASSIGN(double ex0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex0_traffic_rate) / 100, 51); XLS_ASSERT_OK_AND_ASSIGN(int64_t ex0_flits, experiment_data.at(0).metrics.GetIntegerMetric( "Sink:RecvPort0:FlitCount")); EXPECT_EQ(ex0_flits / 1000, 16); XLS_ASSERT_OK_AND_ASSIGN(double ex0_vc0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex0_vc1_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex0_vc0_traffic_rate) / 100, 51); EXPECT_DOUBLE_EQ(ex0_vc1_traffic_rate, 0.0); // Experiment 1 - Flow 0 on VC0, Flow 1 on VC1 XLS_ASSERT_OK_AND_ASSIGN(double ex1_vc0_traffic_rate, experiment_data.at(1).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex1_vc1_traffic_rate, experiment_data.at(1).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex1_vc0_traffic_rate) / 100, 30); EXPECT_EQ(static_cast<int64_t>(ex1_vc1_traffic_rate) / 100, 20); // Experiment 2 - Flow 0 on VC0, Flow 1 on VC1, but network can only // Support support 16 bits / cycle @ 500ps cycle == 3814 MiBps XLS_ASSERT_OK_AND_ASSIGN(double ex2_vc0_traffic_rate, experiment_data.at(2).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex2_vc1_traffic_rate, experiment_data.at(2).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex2_vc0_traffic_rate) / 100, 38); EXPECT_DOUBLE_EQ(ex2_vc1_traffic_rate, 0.0); // Experiment 3 - Flow 0 on VC0, Flow 1 on VC1, and VC0 gets priority XLS_ASSERT_OK_AND_ASSIGN(double ex3_vc0_traffic_rate, experiment_data.at(3).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex3_vc1_traffic_rate, experiment_data.at(3).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex3_vc0_traffic_rate) / 100, 30); EXPECT_EQ(static_cast<int64_t>(ex3_vc1_traffic_rate) / 100, 7); // Get route info for VC 1 of RecvPort0 for the four experiments. XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_0, experiment_data.at(0).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_1, experiment_data.at(1).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_2, experiment_data.at(2).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_3, experiment_data.at(3).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); EXPECT_EQ(timed_route_info_0.size(), 16843); EXPECT_EQ(timed_route_info_1.size(), 16843); EXPECT_EQ(timed_route_info_2.size(), 99986); EXPECT_EQ(timed_route_info_3.size(), 99986); } TEST(SampleExperimentsTest, AggregateTreeTest) { ExperimentFactory experiment_factory; XLS_ASSERT_OK(RegisterSampleExperiments(experiment_factory)); EXPECT_EQ(experiment_factory.ListExperimentTags().size(), 2); EXPECT_EQ(experiment_factory.ListExperimentTags().at(0), "AggregateTreeExperiment"); XLS_ASSERT_OK_AND_ASSIGN( Experiment experiment, experiment_factory.BuildExperiment("AggregateTreeExperiment")); TrafficFlowId flow0_id = experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIds().at(0); EXPECT_EQ(experiment.GetBaseConfig() .GetTrafficConfig() .GetTrafficFlow(flow0_id) .GetBandwidthBits(), 8l * 1024 * 1024 * 1024); int64_t step_count = experiment.GetSweeps().GetStepCount(); std::vector<ExperimentData> experiment_data(step_count); for (int64_t i = 0; i < step_count; ++i) { XLS_LOG(INFO) << absl::StreamFormat("Experiment Step %d", i); XLS_ASSERT_OK_AND_ASSIGN(experiment_data.at(i), experiment.RunStep(i)); XLS_EXPECT_OK(experiment_data.at(i).metrics.DebugDump()); } // Max rate used is 16 flows each at 1GBps. XLS_ASSERT_OK_AND_ASSIGN(double step0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(step0_traffic_rate) / 1000, 16); XLS_ASSERT_OK_AND_ASSIGN(double step0_flow0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Flow:flow_0:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(step0_flow0_traffic_rate) / 100, 10); // As we go in the steps, phit width decreases so traffic rate // will either stay the same or decrease int64_t prior_traffic_rate = static_cast<int64_t>(step0_traffic_rate) / 100; for (int64_t i = 1; i < step_count; ++i) { XLS_ASSERT_OK_AND_ASSIGN(double traffic_rate, experiment_data.at(i).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); int64_t next_traffic_rate = static_cast<int64_t>(traffic_rate) / 100; EXPECT_GE(prior_traffic_rate, next_traffic_rate); prior_traffic_rate = next_traffic_rate; } } } // namespace } // namespace xls::noc
// Copyright 2021 The XLS 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 "xls/noc/drivers/sample_experiments.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "xls/common/logging/logging.h" #include "xls/common/status/matchers.h" #include "xls/noc/drivers/experiment_factory.h" namespace xls::noc { namespace { TEST(SampleExperimentsTest, SimpleVCExperiment) { ExperimentFactory experiment_factory; XLS_ASSERT_OK(RegisterSampleExperiments(experiment_factory)); EXPECT_EQ(experiment_factory.ListExperimentTags().size(), 2); EXPECT_EQ(experiment_factory.ListExperimentTags().at(1), "SimpleVCExperiment"); XLS_ASSERT_OK_AND_ASSIGN( Experiment experiment, experiment_factory.BuildExperiment("SimpleVCExperiment")); EXPECT_EQ( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIds().size(), 2); XLS_EXPECT_OK( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIdByName( "flow_0")); XLS_EXPECT_OK( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIdByName( "flow_1")); XLS_EXPECT_OK( experiment.GetBaseConfig().GetTrafficConfig().GetTrafficModeIdByName( "Main")); EXPECT_EQ(experiment.GetSweeps().GetStepCount(), 4); EXPECT_EQ(experiment.GetRunner().GetTrafficMode(), "Main"); EXPECT_EQ(experiment.GetRunner().GetSimulationCycleCount(), 100'000); EXPECT_EQ(experiment.GetRunner().GetSeed(), 100); EXPECT_EQ(experiment.GetRunner().GetCycleTimeInPs(), 500); std::vector<ExperimentData> experiment_data(4); for (int64_t i = 0; i < experiment.GetSweeps().GetStepCount(); ++i) { XLS_LOG(INFO) << absl::StreamFormat("Experiment Step %d", i); XLS_ASSERT_OK_AND_ASSIGN(experiment_data.at(i), experiment.RunStep(i)); XLS_EXPECT_OK(experiment_data.at(i).metrics.DebugDump()); } // Flow 0 @ 3 GBps and Flow 1 @ 2 GBps // Experiment 0 - Both on VC0 XLS_ASSERT_OK_AND_ASSIGN(double ex0_flow0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Flow:flow_0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex0_flow1_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Flow:flow_1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex0_flow0_traffic_rate) / 100, 30); EXPECT_EQ(static_cast<int64_t>(ex0_flow1_traffic_rate) / 100, 20); XLS_ASSERT_OK_AND_ASSIGN(double ex0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex0_traffic_rate) / 100, 51); XLS_ASSERT_OK_AND_ASSIGN(int64_t ex0_flits, experiment_data.at(0).metrics.GetIntegerMetric( "Sink:RecvPort0:FlitCount")); EXPECT_EQ(ex0_flits / 1000, 16); XLS_ASSERT_OK_AND_ASSIGN(double ex0_vc0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex0_vc1_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex0_vc0_traffic_rate) / 100, 51); EXPECT_DOUBLE_EQ(ex0_vc1_traffic_rate, 0.0); // Experiment 1 - Flow 0 on VC0, Flow 1 on VC1 XLS_ASSERT_OK_AND_ASSIGN(double ex1_vc0_traffic_rate, experiment_data.at(1).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex1_vc1_traffic_rate, experiment_data.at(1).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex1_vc0_traffic_rate) / 100, 30); EXPECT_EQ(static_cast<int64_t>(ex1_vc1_traffic_rate) / 100, 20); // Experiment 2 - Flow 0 on VC0, Flow 1 on VC1, but network can only // Support support 16 bits / cycle @ 500ps cycle == 3814 MiBps XLS_ASSERT_OK_AND_ASSIGN(double ex2_vc0_traffic_rate, experiment_data.at(2).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex2_vc1_traffic_rate, experiment_data.at(2).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex2_vc0_traffic_rate) / 100, 38); EXPECT_DOUBLE_EQ(ex2_vc1_traffic_rate, 0.0); // Experiment 3 - Flow 0 on VC0, Flow 1 on VC1, and VC0 gets priority XLS_ASSERT_OK_AND_ASSIGN(double ex3_vc0_traffic_rate, experiment_data.at(3).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); XLS_ASSERT_OK_AND_ASSIGN(double ex3_vc1_traffic_rate, experiment_data.at(3).metrics.GetFloatMetric( "Sink:RecvPort0:VC:1:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(ex3_vc0_traffic_rate) / 100, 30); EXPECT_EQ(static_cast<int64_t>(ex3_vc1_traffic_rate) / 100, 7); // Get route info for VC 1 of RecvPort0 for the four experiments. XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_0, experiment_data.at(0).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_1, experiment_data.at(1).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_2, experiment_data.at(2).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); XLS_ASSERT_OK_AND_ASSIGN(std::vector<TimedRouteInfo> timed_route_info_3, experiment_data.at(3).info.GetTimedRouteInfo( "Sink:RecvPort0:VC:1:TimedRouteInfo")); EXPECT_THAT(timed_route_info_0.size(), ::testing::Gt(16800)); EXPECT_THAT(timed_route_info_2.size(), ::testing::Gt(99900)); EXPECT_EQ(timed_route_info_0.size(), timed_route_info_1.size()); EXPECT_EQ(timed_route_info_2.size(), timed_route_info_3.size()); } TEST(SampleExperimentsTest, AggregateTreeTest) { ExperimentFactory experiment_factory; XLS_ASSERT_OK(RegisterSampleExperiments(experiment_factory)); EXPECT_EQ(experiment_factory.ListExperimentTags().size(), 2); EXPECT_EQ(experiment_factory.ListExperimentTags().at(0), "AggregateTreeExperiment"); XLS_ASSERT_OK_AND_ASSIGN( Experiment experiment, experiment_factory.BuildExperiment("AggregateTreeExperiment")); TrafficFlowId flow0_id = experiment.GetBaseConfig().GetTrafficConfig().GetTrafficFlowIds().at(0); EXPECT_EQ(experiment.GetBaseConfig() .GetTrafficConfig() .GetTrafficFlow(flow0_id) .GetBandwidthBits(), 8l * 1024 * 1024 * 1024); int64_t step_count = experiment.GetSweeps().GetStepCount(); std::vector<ExperimentData> experiment_data(step_count); for (int64_t i = 0; i < step_count; ++i) { XLS_LOG(INFO) << absl::StreamFormat("Experiment Step %d", i); XLS_ASSERT_OK_AND_ASSIGN(experiment_data.at(i), experiment.RunStep(i)); XLS_EXPECT_OK(experiment_data.at(i).metrics.DebugDump()); } // Max rate used is 16 flows each at 1GBps. XLS_ASSERT_OK_AND_ASSIGN(double step0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(step0_traffic_rate) / 1000, 16); XLS_ASSERT_OK_AND_ASSIGN(double step0_flow0_traffic_rate, experiment_data.at(0).metrics.GetFloatMetric( "Flow:flow_0:TrafficRateInMiBps")); EXPECT_EQ(static_cast<int64_t>(step0_flow0_traffic_rate) / 100, 10); // As we go in the steps, phit width decreases so traffic rate // will either stay the same or decrease int64_t prior_traffic_rate = static_cast<int64_t>(step0_traffic_rate) / 100; for (int64_t i = 1; i < step_count; ++i) { XLS_ASSERT_OK_AND_ASSIGN(double traffic_rate, experiment_data.at(i).metrics.GetFloatMetric( "Sink:RecvPort0:VC:0:TrafficRateInMiBps")); int64_t next_traffic_rate = static_cast<int64_t>(traffic_rate) / 100; EXPECT_GE(prior_traffic_rate, next_traffic_rate); prior_traffic_rate = next_traffic_rate; } } } // namespace } // namespace xls::noc
Fix sample_experiments_test for OSS.
[NoC-Sim] Fix sample_experiments_test for OSS. PiperOrigin-RevId: 410089952
C++
apache-2.0
google/xls,google/xls,google/xls,google/xls,google/xls,google/xls
67bbfd1483d2300684fbe5e688e5c80c193776ee
system/Grappa.hpp
system/Grappa.hpp
// Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef __GRAPPA_HPP__ #define __GRAPPA_HPP__ #include <gflags/gflags.h> #include <glog/logging.h> #include "Communicator.hpp" #include "Worker.hpp" #include "tasks/TaskingScheduler.hpp" #include "PerformanceTools.hpp" /// /// Worker management routines /// #include "Addressing.hpp" #include "Tasking.hpp" #include "StateTimer.hpp" #include "Message.hpp" #include "Delegate.hpp" #include "AsyncDelegate.hpp" #include "Collective.hpp" #include "ParallelLoop.hpp" #include "GlobalAllocator.hpp" // #include "Cache.hpp" //#include <typeinfo> //#include <cxxabi.h> /// Helper to be passed to Grappa::init() for Boost Unit Tests #define GRAPPA_TEST_ARGS &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) namespace Grappa { /// Initialize Grappa. Call in SPMD context before running Grappa /// code. Running Grappa code before calling init() is illegal. void init( int * argc_p, char ** argv_p[], int64_t size = -1 ); /// Clean up Grappa. Call in SPMD context after all Grappa code /// finishes. Running Grappa code after calling finalize() is illegal. int finalize(); #ifndef GRAPPA_NO_ABBREV /// Specify non-default behavior: stealable tasks /// /// @code /// spawn<unbound>(...) /// forall<unbound>(...) /// forall<unbound,async>(...) /// @endcode #define unbound Grappa::TaskMode::Unbound #endif #ifndef GRAPPA_NO_ABBREV /// Specify non-blocking operation (to be used in loops, delegates, etc) /// /// @code /// forall<async>(...) /// delegate::call<async>(...) /// delegate::write<async>(...) /// @endcode #define async Grappa::SyncMode::Async #endif } #endif
// Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef __GRAPPA_HPP__ #define __GRAPPA_HPP__ #include <gflags/gflags.h> #include <glog/logging.h> #include "Communicator.hpp" #include "Worker.hpp" #include "tasks/TaskingScheduler.hpp" #include "PerformanceTools.hpp" /// /// Worker management routines /// #include "Addressing.hpp" #include "Tasking.hpp" #include "StateTimer.hpp" #include "Message.hpp" #include "Delegate.hpp" #include "AsyncDelegate.hpp" #include "Collective.hpp" #include "ParallelLoop.hpp" #include "GlobalAllocator.hpp" // #include "Cache.hpp" #include "Array.hpp" #include "Statistics.hpp" //#include <typeinfo> //#include <cxxabi.h> /// Helper to be passed to Grappa::init() for Boost Unit Tests #define GRAPPA_TEST_ARGS &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) namespace Grappa { /// Initialize Grappa. Call in SPMD context before running Grappa /// code. Running Grappa code before calling init() is illegal. void init( int * argc_p, char ** argv_p[], int64_t size = -1 ); /// Clean up Grappa. Call in SPMD context after all Grappa code /// finishes. Running Grappa code after calling finalize() is illegal. int finalize(); #ifndef GRAPPA_NO_ABBREV /// Specify non-default behavior: stealable tasks /// /// @code /// spawn<unbound>(...) /// forall<unbound>(...) /// forall<unbound,async>(...) /// @endcode #define unbound Grappa::TaskMode::Unbound #endif #ifndef GRAPPA_NO_ABBREV /// Specify non-blocking operation (to be used in loops, delegates, etc) /// /// @code /// forall<async>(...) /// delegate::call<async>(...) /// delegate::write<async>(...) /// @endcode #define async Grappa::SyncMode::Async #endif } #endif
add 'Array.hpp' and 'Statistics.hpp' to Grappa.hpp
add 'Array.hpp' and 'Statistics.hpp' to Grappa.hpp
C++
bsd-3-clause
buaasun/grappa,buaasun/grappa,uwsampa/grappa,alexfrolov/grappa,uwsampa/grappa,alexfrolov/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,buaasun/grappa,alexfrolov/grappa,uwsampa/grappa,uwsampa/grappa,buaasun/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,buaasun/grappa,alexfrolov/grappa,alexfrolov/grappa,uwsampa/grappa
7fecea1b803fbca7c5237a9607698f0ea272f65c
drake/solvers/test/mosek_test.cc
drake/solvers/test/mosek_test.cc
#include "drake/solvers/mosek_solver.h" #include <iostream> #include <Eigen/Core> #include "gtest/gtest.h" #include "drake/util/testUtil.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/optimization.h" #include "drake/util/eigen_matrix_compare.h" #include "drake/solvers/constraint.h" using drake::util::MatrixCompareType; namespace drake { namespace solvers { namespace { GTEST_TEST(testMosek, MosekLinearProgram) { // Taken from http://docs.mosek.com/7.1/capi/Linear_optimization.html OptimizationProblem prog; auto x = prog.AddContinuousVariables(4); Eigen::Vector4d A; A << 3, 1, 5, 1; LinearConstraint obj(A, Eigen::Vector4d::Constant(0), Eigen::Vector4d::Constant(0)); std::shared_ptr<LinearConstraint> ptrtoobj = std::make_shared<LinearConstraint>(obj); prog.AddCost(ptrtoobj); Eigen::MatrixXd constraint1(1, 4); Eigen::MatrixXd constraint2(1, 4); constraint1 << 2, 1, 3, 1; constraint2 << 0, 2, 0, 3; Eigen::MatrixXd lineqconstraint(1, 4); lineqconstraint << 3, 1, 2, 0; Eigen::MatrixXd lb1(1, 1), ub1(1, 1); Eigen::MatrixXd lb2(1, 1), ub2(1, 1); lb1 << 15; ub1 << +std::numeric_limits<double>::infinity(); lb2 << -std::numeric_limits<double>::infinity(); ub2 << 25; Eigen::MatrixXd lineqbounds(1, 1); lineqbounds << 30; prog.AddLinearConstraint(constraint1, lb1, ub1); prog.AddLinearConstraint(constraint2, lb2, ub2); prog.AddLinearEqualityConstraint(lineqconstraint, lineqbounds); Eigen::Vector4d bboxlow, bboxhigh; bboxlow << 0, 0, 0, 0; bboxhigh << std::numeric_limits<double>::infinity(), 10, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog.AddBoundingBoxConstraint(bboxlow, bboxhigh); prog.SetSolverOption("Mosek", "maxormin", "max"); prog.SetSolverOption("Mosek", "problemtype", "linear"); SolutionResult result = SolutionResult::kUnknownError; MosekSolver msk; ASSERT_NO_THROW(result = msk.Solve(prog)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::Vector4d solutions; solutions << 0, 0, 15, 8.33333333333333333333; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-10, MatrixCompareType::absolute)); } GTEST_TEST(testMosek, MosekQuadraticCost) { // http://docs.mosek.com/7.1/capi/Quadratic_optimization.html OptimizationProblem prog2; auto x = prog2.AddContinuousVariables(3); // Build the objective matrix and send it to the program. Eigen::Matrix3d Q; Q << 2, 0, -1, 0, 0.2, 0, -1, 0, 2; Eigen::Vector3d c; c << 0, -1, 0; prog2.AddQuadraticCost(std::make_shared<QuadraticConstraint>(Q, c, 0, 0)); // Build the constraint matrix and send it to the program. Eigen::Vector3d linearcon; linearcon << 1, 1, 1; std::shared_ptr<QuadraticConstraint> ptrtocon = std::make_shared<QuadraticConstraint>( Eigen::Matrix3d::Constant(0), linearcon, 1, std::numeric_limits<double>::infinity()); prog2.AddGenericConstraint(ptrtocon); // Create the bounding box. Eigen::Vector3d bboxlow, bboxhigh; bboxlow << 0, 0, 0; bboxhigh << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog2.AddBoundingBoxConstraint(bboxlow, bboxhigh); MosekSolver msk; SolutionResult result = SolutionResult::kUnknownError; prog2.SetSolverOption("Mosek", "maxormin", "min"); prog2.SetSolverOption("Mosek", "problemtype", "quadratic"); ASSERT_NO_THROW(result = msk.Solve(prog2)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::Vector3d solutions; solutions << 5.975006e-05, 5, 5.975006e-05; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-7, MatrixCompareType::absolute)); } GTEST_TEST(testMosek, MosekQuadraticConstraintAndCost) { // http://docs.mosek.com/7.1/capi/Quadratic_optimization.html OptimizationProblem prog2; auto x = prog2.AddContinuousVariables(3); // Build the objective matrix and send it to the program. Eigen::Matrix3d Q; Q << 2, 0, -1, 0, 0.2, 0, -1, 0, 2; Eigen::Vector3d c; c << 0, -1, 0; prog2.AddQuadraticCost(std::make_shared<QuadraticConstraint>(Q, c, 0, 0)); // Create the constraint matrix, and send it to the program. Eigen::Vector3d linearcon; linearcon << 1, 1, 1; Eigen::Matrix3d quadcon; quadcon << -2, 0, 0.2, 0, -2, 0, 0.2, 0, -0.2; std::shared_ptr<QuadraticConstraint> ptrtocon = std::make_shared<QuadraticConstraint>(quadcon, linearcon, 1, std::numeric_limits<double>::infinity()); prog2.AddGenericConstraint(ptrtocon); // Create the bounding box. Eigen::Vector3d bboxlow, bboxhigh; bboxlow << 0, 0, 0; bboxhigh << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog2.AddBoundingBoxConstraint(bboxlow, bboxhigh); MosekSolver msk; SolutionResult result = SolutionResult::kUnknownError; prog2.SetSolverOption("Mosek", "maxormin", "min"); prog2.SetSolverOption("Mosek", "problemtype", "quadratic"); ASSERT_NO_THROW(result = msk.Solve(prog2)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::Vector3d solutions; solutions << 4.487849e-01, 9.319130e-01, 6.741081e-01; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-7, MatrixCompareType::absolute)); } GTEST_TEST(testMosek, MosekSemiDefiniteProgram) { // http://docs.mosek.com/7.1/capi/Semidefinite_optimization.html OptimizationProblem prog3; auto x = prog3.AddContinuousVariables(9); prog3.SetSolverOption("Mosek", "numbarvar", 6); // Build the objective matrix and send it to the program. Eigen::Matrix3d Q; Q << 2, 1, 0, 1, 2, 1, 0, 1, 2; Eigen::Vector3d c; c << 1, 0, 0; prog3.AddQuadraticCost(std::make_shared<QuadraticConstraint>(Q, c, 0, 0)); // Create the constraint matrix, and send it to the program. Eigen::Vector3d linearcon1; linearcon1 << 1, 0, 0; Eigen::Matrix3d sdpcon1; sdpcon1 << 1, 0, 0, 0, 1, 0, 0, 0, 1; auto ptrtocon1 = std::make_shared<QuadraticConstraint>(sdpcon1, linearcon1, 1, 1); prog3.AddGenericConstraint(ptrtocon1); Eigen::Vector3d linearcon2; linearcon2 << 0, 1, 1; Eigen::Matrix3d sdpcon2; sdpcon2 << 1, 1, 1, 1, 1, 1, 1, 1, 1; auto ptrtocon2 = std::make_shared<QuadraticConstraint>(sdpcon2, linearcon2, 0.5, 0.5); prog3.AddGenericConstraint(ptrtocon2); // Create the bounding box. Eigen::Vector3d bboxlow, bboxhigh; bboxlow << -std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(); bboxhigh << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog3.AddBoundingBoxConstraint(bboxlow, bboxhigh); MosekSolver msk; SolutionResult result = SolutionResult::kUnknownError; prog3.SetSolverOption("Mosek", "maxormin", "min"); prog3.SetSolverOption("Mosek", "problemtype", "sdp"); ASSERT_NO_THROW(result = msk.Solve(prog3)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::VectorXd solutions(9); solutions << 2.543589e-01, 1.798589e-01, 1.798589e-01, 2.172859e-01, -2.599827e-01, 2.172859e-01, 3.110694e-01, -2.599827e-01, 2.172859e-01; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-7, MatrixCompareType::absolute)); } } // Anonymous namespace } // namespace solvers } // namespace drake
#include "drake/solvers/mosek_solver.h" #include <iostream> #include <Eigen/Core> #include "gtest/gtest.h" #include "drake/util/testUtil.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/optimization.h" #include "drake/util/eigen_matrix_compare.h" #include "drake/solvers/constraint.h" using drake::util::MatrixCompareType; namespace drake { namespace solvers { namespace { GTEST_TEST(testMosek, MosekLinearProgram) { // Taken from http://docs.mosek.com/7.1/capi/Linear_optimization.html OptimizationProblem prog; auto x = prog.AddContinuousVariables(4); Eigen::Vector4d A; A << 3, 1, 5, 1; LinearConstraint obj(A, Eigen::Vector4d::Constant(0), Eigen::Vector4d::Constant(0)); std::shared_ptr<LinearConstraint> ptrtoobj = std::make_shared<LinearConstraint>(obj); prog.AddCost(ptrtoobj); Eigen::MatrixXd constraint1(1, 4); Eigen::MatrixXd constraint2(1, 4); constraint1 << 2, 1, 3, 1; constraint2 << 0, 2, 0, 3; Eigen::MatrixXd lineqconstraint(1, 4); lineqconstraint << 3, 1, 2, 0; Eigen::MatrixXd lb1(1, 1), ub1(1, 1); Eigen::MatrixXd lb2(1, 1), ub2(1, 1); lb1 << 15; ub1 << +std::numeric_limits<double>::infinity(); lb2 << -std::numeric_limits<double>::infinity(); ub2 << 25; Eigen::MatrixXd lineqbounds(1, 1); lineqbounds << 30; prog.AddLinearConstraint(constraint1, lb1, ub1); prog.AddLinearConstraint(constraint2, lb2, ub2); prog.AddLinearEqualityConstraint(lineqconstraint, lineqbounds); Eigen::Vector4d bboxlow, bboxhigh; bboxlow << 0, 0, 0, 0; bboxhigh << std::numeric_limits<double>::infinity(), 10, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog.AddBoundingBoxConstraint(bboxlow, bboxhigh); prog.SetSolverOption("Mosek", "maxormin", "max"); prog.SetSolverOption("Mosek", "problemtype", "linear"); SolutionResult result = SolutionResult::kUnknownError; MosekSolver msk; ASSERT_NO_THROW(result = msk.Solve(prog)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::Vector4d solutions; solutions << 0, 0, 15, 8.33333333333333333333; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-10, MatrixCompareType::absolute)); } GTEST_TEST(testMosek, MosekQuadraticCost) { // http://docs.mosek.com/7.1/capi/Quadratic_optimization.html OptimizationProblem prog2; auto x = prog2.AddContinuousVariables(3); // Build the objective matrix and send it to the program. Eigen::Matrix3d Q; Q << 2, 0, -1, 0, 0.2, 0, -1, 0, 2; Eigen::Vector3d c; c << 0, -1, 0; prog2.AddQuadraticCost(std::make_shared<QuadraticConstraint>(Q, c, 0, 0)); // Build the constraint matrix and send it to the program. Eigen::Vector3d linearcon; linearcon << 1, 1, 1; std::shared_ptr<QuadraticConstraint> ptrtocon = std::make_shared<QuadraticConstraint>( Eigen::Matrix3d::Constant(0), linearcon, 1, std::numeric_limits<double>::infinity()); prog2.AddGenericConstraint(ptrtocon); // Create the bounding box. Eigen::Vector3d bboxlow, bboxhigh; bboxlow << 0, 0, 0; bboxhigh << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog2.AddBoundingBoxConstraint(bboxlow, bboxhigh); MosekSolver msk; SolutionResult result = SolutionResult::kUnknownError; prog2.SetSolverOption("Mosek", "maxormin", "min"); prog2.SetSolverOption("Mosek", "problemtype", "quadratic"); ASSERT_NO_THROW(result = msk.Solve(prog2)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::Vector3d solutions; solutions << 5.975006e-05, 5, 5.975006e-05; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-7, MatrixCompareType::absolute)); } GTEST_TEST(testMosek, MosekQuadraticConstraintAndCost) { // http://docs.mosek.com/7.1/capi/Quadratic_optimization.html OptimizationProblem prog2; auto x = prog2.AddContinuousVariables(3); // Build the objective matrix and send it to the program. Eigen::Matrix3d Q; Q << 2, 0, -1, 0, 0.2, 0, -1, 0, 2; Eigen::Vector3d c; c << 0, -1, 0; prog2.AddQuadraticCost(std::make_shared<QuadraticConstraint>(Q, c, 0, 0)); // Create the constraint matrix, and send it to the program. Eigen::Vector3d linearcon; linearcon << 1, 1, 1; Eigen::Matrix3d quadcon; quadcon << -2, 0, 0.2, 0, -2, 0, 0.2, 0, -0.2; std::shared_ptr<QuadraticConstraint> ptrtocon = std::make_shared<QuadraticConstraint>(quadcon, linearcon, 1, std::numeric_limits<double>::infinity()); prog2.AddGenericConstraint(ptrtocon); // Create the bounding box. Eigen::Vector3d bboxlow, bboxhigh; bboxlow << 0, 0, 0; bboxhigh << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog2.AddBoundingBoxConstraint(bboxlow, bboxhigh); MosekSolver msk; SolutionResult result = SolutionResult::kUnknownError; prog2.SetSolverOption("Mosek", "maxormin", "min"); prog2.SetSolverOption("Mosek", "problemtype", "quadratic"); ASSERT_NO_THROW(result = msk.Solve(prog2)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::Vector3d solutions; solutions << 4.487849e-01, 9.319130e-01, 6.741081e-01; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-7, MatrixCompareType::absolute)); } GTEST_TEST(testMosek, MosekSemiDefiniteProgram) { // http://docs.mosek.com/7.1/capi/Semidefinite_optimization.html OptimizationProblem prog3; auto x = prog3.AddContinuousVariables(9); prog3.SetSolverOption("Mosek", "numbarvar", 6); // Build the objective matrix and send it to the program. Eigen::Matrix3d Q; Q << 2, 1, 0, 1, 2, 1, 0, 1, 2; Eigen::Vector3d c; c << 1, 0, 0; prog3.AddQuadraticCost(std::make_shared<QuadraticConstraint>(Q, c, 0, 0)); // Create the constraint matrix, and send it to the program. Eigen::Vector3d linearcon1; linearcon1 << 1, 0, 0; Eigen::Matrix3d sdpcon1; sdpcon1 << 1, 0, 0, 0, 1, 0, 0, 0, 1; auto ptrtocon1 = std::make_shared<QuadraticConstraint>(sdpcon1, linearcon1, 1, 1); prog3.AddGenericConstraint(ptrtocon1); Eigen::Vector3d linearcon2; linearcon2 << 0, 1, 1; Eigen::Matrix3d sdpcon2; sdpcon2 << 1, 1, 1, 1, 1, 1, 1, 1, 1; auto ptrtocon2 = std::make_shared<QuadraticConstraint>(sdpcon2, linearcon2, 0.5, 0.5); prog3.AddGenericConstraint(ptrtocon2); // Create the bounding box. Eigen::Vector3d bboxlow, bboxhigh; bboxlow << -std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(); bboxhigh << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); prog3.AddBoundingBoxConstraint(bboxlow, bboxhigh); MosekSolver msk; SolutionResult result = SolutionResult::kUnknownError; prog3.SetSolverOption("Mosek", "maxormin", "min"); prog3.SetSolverOption("Mosek", "problemtype", "sdp"); ASSERT_NO_THROW(result = msk.Solve(prog3)); EXPECT_EQ(result, SolutionResult::kSolutionFound); Eigen::VectorXd solutions(9); solutions << 2.543589e-01, 1.798589e-01, 1.798589e-01, 2.172859e-01, -2.599827e-01, 2.172859e-01, 3.110694e-01, -2.599827e-01, 2.172859e-01; EXPECT_TRUE(CompareMatrices(solutions, x.value(), 1e-7, MatrixCompareType::absolute)); } } // Anonymous namespace } // namespace solvers } // namespace drake
indent change.
indent change.
C++
bsd-3-clause
sheim/drake,sheim/drake,sheim/drake,billhoffman/drake,sheim/drake,sheim/drake,sheim/drake,billhoffman/drake,sheim/drake,sheim/drake,billhoffman/drake,billhoffman/drake,billhoffman/drake,billhoffman/drake,billhoffman/drake,billhoffman/drake
dc786c20532b3039b964fba156c519001e837013
gason.cpp
gason.cpp
#include <stdlib.h> #include <ctype.h> #include "gason.h" inline bool is_delim(char c) { return isspace(c) || c == ',' || c == ':' || c == ']' || c == '}' || c == '\0'; } inline bool is_sign(char c) { return c == '-' || c == '+'; } inline int char2int(char c) { if (c >= 'a') return c - 'a' + 10; if (c >= 'A') return c - 'A' + 10; return c - '0'; } static double str2float(const char *str, char **endptr) { double sign = is_sign(*str) && *str++ == '-' ? -1 : 1; double result = 0; while (isdigit(*str)) result = (result * 10) + (*str++ - '0'); if (*str == '.') { ++str; double fraction = 1; while (isdigit(*str)) fraction *= 0.1, result += (*str++ - '0') * fraction; } if (*str == 'e' || *str == 'E') { ++str; double base = is_sign(*str) && *str++ == '-' ? 0.1 : 10; int exponent = 0; while (isdigit(*str)) exponent = (exponent * 10) + (*str++ - '0'); double power = 1; for (; exponent; exponent >>= 1, base *= base) if (exponent & 1) power *= base; result *= power; } *endptr = (char *)str; return sign * result; } JsonAllocator::~JsonAllocator() { while (head) { Zone *temp = head->next; free(head); head = temp; } } inline void *align_pointer(void *x, size_t align) { return (void *)(((uintptr_t)x + (align - 1)) & ~(align - 1)); } void *JsonAllocator::allocate(size_t n, size_t align) { if (head) { char *p = (char *)align_pointer(head->end, align); if (p + n <= (char *)head + JSON_ZONE_SIZE) { head->end = p + n; return p; } } size_t zone_size = sizeof(Zone) + n + align; Zone *z = (Zone *)malloc(zone_size <= JSON_ZONE_SIZE ? JSON_ZONE_SIZE : zone_size); char *p = (char *)align_pointer(z + 1, align); z->end = p + n; if (zone_size <= JSON_ZONE_SIZE || head == nullptr) { z->next = head; head = z; } else { z->next = head->next; head->next = z; } return p; } struct JsonList { JsonTag tag; JsonValue node; char *key; void grow_the_tail(JsonNode *p) { JsonNode *tail = (JsonNode *)node.getPayload(); if (tail) { p->next = tail->next; tail->next = p; } else { p->next = p; } node = JsonValue(tag, p); } JsonValue cut_the_head() { JsonNode *tail = (JsonNode *)node.getPayload(); if (tail) { JsonNode *head = tail->next; tail->next = nullptr; return JsonValue(tag, head); } return node; } }; JsonParseStatus json_parse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator) { JsonList stack[JSON_STACK_SIZE]; int top = -1; bool separator = true; while (*str) { JsonValue o; while (*str && isspace(*str)) ++str; *endptr = str++; switch (**endptr) { case '\0': continue; case '-': if (!isdigit(*str) && *str != '.') return *endptr = str, JSON_PARSE_BAD_NUMBER; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': o = JsonValue(str2float(*endptr, &str)); if (!is_delim(*str)) return *endptr = str, JSON_PARSE_BAD_NUMBER; break; case '"': o = JsonValue(JSON_TAG_STRING, str); for (char *s = str; *str; ++s, ++str) { int c = *s = *str; if (c == '\\') { c = *++str; switch (c) { case '\\': case '"': case '/': *s = c; break; case 'b': *s = '\b'; break; case 'f': *s = '\f'; break; case 'n': *s = '\n'; break; case 'r': *s = '\r'; break; case 't': *s = '\t'; break; case 'u': c = 0; for (int i = 0; i < 4; ++i) { if (!isxdigit(*++str)) return *endptr = str, JSON_PARSE_BAD_STRING; c = c * 16 + char2int(*str); } if (c < 0x80) { *s = c; } else if (c < 0x800) { *s++ = 0xC0 | (c >> 6); *s = 0x80 | (c & 0x3F); } else { *s++ = 0xE0 | (c >> 12); *s++ = 0x80 | ((c >> 6) & 0x3F); *s = 0x80 | (c & 0x3F); } break; default: return *endptr = str, JSON_PARSE_BAD_STRING; } } else if (c == '"') { *s = 0; ++str; break; } } if (!is_delim(*str)) return *endptr = str, JSON_PARSE_BAD_STRING; break; case 't': for (const char *s = "rue"; *s; ++s, ++str) { if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER; } if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER; o = JsonValue(JSON_TAG_BOOL, (void *)true); break; case 'f': for (const char *s = "alse"; *s; ++s, ++str) { if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER; } if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER; o = JsonValue(JSON_TAG_BOOL, (void *)false); break; case 'n': for (const char *s = "ull"; *s; ++s, ++str) { if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER; } if (!is_delim(*str)) return JSON_PARSE_BAD_IDENTIFIER; break; case ']': if (top == -1) return JSON_PARSE_STACK_UNDERFLOW; if (stack[top].tag != JSON_TAG_ARRAY) return JSON_PARSE_MISMATCH_BRACKET; o = stack[top--].cut_the_head(); break; case '}': if (top == -1) return JSON_PARSE_STACK_UNDERFLOW; if (stack[top].tag != JSON_TAG_OBJECT) return JSON_PARSE_MISMATCH_BRACKET; o = stack[top--].cut_the_head(); break; case '[': if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW; stack[top] = {JSON_TAG_ARRAY, JsonValue(JSON_TAG_ARRAY, nullptr), nullptr}; continue; case '{': if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW; stack[top] = {JSON_TAG_OBJECT, JsonValue(JSON_TAG_OBJECT, nullptr), nullptr}; continue; case ':': if (separator || stack[top].key == nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER; separator = true; continue; case ',': if (separator || stack[top].key != nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER; separator = true; continue; default: return JSON_PARSE_UNEXPECTED_CHARACTER; } separator = false; if (top == -1) { *endptr = str; *value = o; return JSON_PARSE_OK; } if (stack[top].tag == JSON_TAG_OBJECT) { if (!stack[top].key) { if (o.getTag() != JSON_TAG_STRING) return JSON_PARSE_UNQUOTED_KEY; stack[top].key = o.toString(); continue; } JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode)); p->value = o; p->key = stack[top].key; stack[top].key = nullptr; stack[top].grow_the_tail((JsonNode *)p); continue; } JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode) - sizeof(char *)); p->value = o; stack[top].grow_the_tail(p); } return JSON_PARSE_BREAKING_BAD; }
#include <stdlib.h> #include <ctype.h> #include "gason.h" inline bool isdelim(char c) { return isspace(c) || c == ',' || c == ':' || c == ']' || c == '}' || c == '\0'; } inline int char2int(char c) { if (c >= 'a') return c - 'a' + 10; if (c >= 'A') return c - 'A' + 10; return c - '0'; } static double str2float(const char *str, char **endptr) { char sign = *str; if (sign == '+' || sign == '-') ++str; double result = 0; while (isdigit(*str)) result = (result * 10) + (*str++ - '0'); if (*str == '.') { ++str; double fraction = 1; while (isdigit(*str)) fraction *= 0.1, result += (*str++ - '0') * fraction; } if (*str == 'e' || *str == 'E') { ++str; double base = 10; if (*str == '+') ++str; else if (*str == '-') { ++str; base = 0.1; } int exponent = 0; while (isdigit(*str)) exponent = (exponent * 10) + (*str++ - '0'); double power = 1; for (; exponent; exponent >>= 1, base *= base) if (exponent & 1) power *= base; result *= power; } *endptr = (char *)str; return sign == '-' ? -result : result; } JsonAllocator::~JsonAllocator() { while (head) { Zone *temp = head->next; free(head); head = temp; } } inline void *align_pointer(void *x, size_t align) { return (void *)(((uintptr_t)x + (align - 1)) & ~(align - 1)); } void *JsonAllocator::allocate(size_t n, size_t align) { if (head) { char *p = (char *)align_pointer(head->end, align); if (p + n <= (char *)head + JSON_ZONE_SIZE) { head->end = p + n; return p; } } size_t zone_size = sizeof(Zone) + n + align; Zone *z = (Zone *)malloc(zone_size <= JSON_ZONE_SIZE ? JSON_ZONE_SIZE : zone_size); char *p = (char *)align_pointer(z + 1, align); z->end = p + n; if (zone_size <= JSON_ZONE_SIZE || head == nullptr) { z->next = head; head = z; } else { z->next = head->next; head->next = z; } return p; } struct JsonList { JsonTag tag; JsonValue node; char *key; void grow_the_tail(JsonNode *p) { JsonNode *tail = (JsonNode *)node.getPayload(); if (tail) { p->next = tail->next; tail->next = p; } else { p->next = p; } node = JsonValue(tag, p); } JsonValue cut_the_head() { JsonNode *tail = (JsonNode *)node.getPayload(); if (tail) { JsonNode *head = tail->next; tail->next = nullptr; return JsonValue(tag, head); } return node; } }; JsonParseStatus json_parse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator) { JsonList stack[JSON_STACK_SIZE]; int top = -1; bool separator = true; while (*str) { JsonValue o; while (*str && isspace(*str)) ++str; *endptr = str++; switch (**endptr) { case '\0': continue; case '-': if (!isdigit(*str) && *str != '.') return *endptr = str, JSON_PARSE_BAD_NUMBER; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': o = JsonValue(str2float(*endptr, &str)); if (!isdelim(*str)) return *endptr = str, JSON_PARSE_BAD_NUMBER; break; case '"': o = JsonValue(JSON_TAG_STRING, str); for (char *s = str; *str; ++s, ++str) { int c = *s = *str; if (c == '\\') { c = *++str; switch (c) { case '\\': case '"': case '/': *s = c; break; case 'b': *s = '\b'; break; case 'f': *s = '\f'; break; case 'n': *s = '\n'; break; case 'r': *s = '\r'; break; case 't': *s = '\t'; break; case 'u': c = 0; for (int i = 0; i < 4; ++i) { if (!isxdigit(*++str)) return *endptr = str, JSON_PARSE_BAD_STRING; c = c * 16 + char2int(*str); } if (c < 0x80) { *s = c; } else if (c < 0x800) { *s++ = 0xC0 | (c >> 6); *s = 0x80 | (c & 0x3F); } else { *s++ = 0xE0 | (c >> 12); *s++ = 0x80 | ((c >> 6) & 0x3F); *s = 0x80 | (c & 0x3F); } break; default: return *endptr = str, JSON_PARSE_BAD_STRING; } } else if (c == '"') { *s = 0; ++str; break; } } if (!isdelim(*str)) return *endptr = str, JSON_PARSE_BAD_STRING; break; case 't': for (const char *s = "rue"; *s; ++s, ++str) { if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER; } if (!isdelim(*str)) return JSON_PARSE_BAD_IDENTIFIER; o = JsonValue(JSON_TAG_BOOL, (void *)true); break; case 'f': for (const char *s = "alse"; *s; ++s, ++str) { if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER; } if (!isdelim(*str)) return JSON_PARSE_BAD_IDENTIFIER; o = JsonValue(JSON_TAG_BOOL, (void *)false); break; case 'n': for (const char *s = "ull"; *s; ++s, ++str) { if (*s != *str) return JSON_PARSE_BAD_IDENTIFIER; } if (!isdelim(*str)) return JSON_PARSE_BAD_IDENTIFIER; break; case ']': if (top == -1) return JSON_PARSE_STACK_UNDERFLOW; if (stack[top].tag != JSON_TAG_ARRAY) return JSON_PARSE_MISMATCH_BRACKET; o = stack[top--].cut_the_head(); break; case '}': if (top == -1) return JSON_PARSE_STACK_UNDERFLOW; if (stack[top].tag != JSON_TAG_OBJECT) return JSON_PARSE_MISMATCH_BRACKET; o = stack[top--].cut_the_head(); break; case '[': if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW; stack[top] = {JSON_TAG_ARRAY, JsonValue(JSON_TAG_ARRAY, nullptr), nullptr}; continue; case '{': if (++top == JSON_STACK_SIZE) return JSON_PARSE_STACK_OVERFLOW; stack[top] = {JSON_TAG_OBJECT, JsonValue(JSON_TAG_OBJECT, nullptr), nullptr}; continue; case ':': if (separator || stack[top].key == nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER; separator = true; continue; case ',': if (separator || stack[top].key != nullptr) return JSON_PARSE_UNEXPECTED_CHARACTER; separator = true; continue; default: return JSON_PARSE_UNEXPECTED_CHARACTER; } separator = false; if (top == -1) { *endptr = str; *value = o; return JSON_PARSE_OK; } if (stack[top].tag == JSON_TAG_OBJECT) { if (!stack[top].key) { if (o.getTag() != JSON_TAG_STRING) return JSON_PARSE_UNQUOTED_KEY; stack[top].key = o.toString(); continue; } JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode)); p->value = o; p->key = stack[top].key; stack[top].key = nullptr; stack[top].grow_the_tail((JsonNode *)p); continue; } JsonNode *p = (JsonNode *)allocator.allocate(sizeof(JsonNode) - sizeof(char *)); p->value = o; stack[top].grow_the_tail(p); } return JSON_PARSE_BREAKING_BAD; }
Remove is_sign function
Remove is_sign function
C++
mit
duckie/gason,tvanderbruggen/gason,vivkin/gason,duckie/gason,tvanderbruggen/gason,vivkin/gason,ChrisJefferson/gason,ChrisJefferson/gason,bagobor/gason,ChrisJefferson/gason,bagobor/gason
63e000c7d1743ef31ba5e9c02c91734930e9033f
deal.II/bundled/boost-1.49.0/include/boost/signals2/detail/foreign_ptr.hpp
deal.II/bundled/boost-1.49.0/include/boost/signals2/detail/foreign_ptr.hpp
// helper code for dealing with tracking non-boost shared_ptr/weak_ptr // Copyright Frank Mori Hess 2009. // Distributed under the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/signals2 for library home page. #ifndef BOOST_SIGNALS2_FOREIGN_PTR_HPP #define BOOST_SIGNALS2_FOREIGN_PTR_HPP #include <algorithm> #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/scoped_ptr.hpp> #include <boost/smart_ptr/bad_weak_ptr.hpp> #include <boost/utility/swap.hpp> namespace boost { template<typename T> class shared_ptr; template<typename T> class weak_ptr; namespace signals2 { template<typename WeakPtr> struct weak_ptr_traits {}; template<typename T> struct weak_ptr_traits<boost::weak_ptr<T> > { typedef boost::shared_ptr<T> shared_type; }; // Workaround for a bug in boost: // https://svn.boost.org/trac/boost/ticket/6655 // // It should be save to depend on DEAL macros at this point as this header // should only be used by deal.II and dependend projects... // // - Maier, 2013 #ifdef DEAL_II_CAN_USE_CXX11 template<typename T> struct weak_ptr_traits<std::weak_ptr<T> > { typedef std::shared_ptr<T> shared_type; }; #endif template<typename SharedPtr> struct shared_ptr_traits {}; template<typename T> struct shared_ptr_traits<boost::shared_ptr<T> > { typedef boost::weak_ptr<T> weak_type; }; // as above #ifdef DEAL_II_CAN_USE_CXX11 template<typename T> struct shared_ptr_traits<std::shared_ptr<T> > { typedef std::weak_ptr<T> weak_type; }; #endif namespace detail { struct foreign_shared_ptr_impl_base { virtual ~foreign_shared_ptr_impl_base() {} virtual void* get() const = 0; virtual foreign_shared_ptr_impl_base * clone() const = 0; }; template<typename FSP> class foreign_shared_ptr_impl: public foreign_shared_ptr_impl_base { public: foreign_shared_ptr_impl(const FSP &p): _p(p) {} virtual void * get() const { return _p.get(); } virtual foreign_shared_ptr_impl * clone() const { return new foreign_shared_ptr_impl(*this); } private: FSP _p; }; class foreign_void_shared_ptr { public: foreign_void_shared_ptr(): _p(0) {} foreign_void_shared_ptr(const foreign_void_shared_ptr &other): _p(other._p->clone()) {} template<typename FSP> explicit foreign_void_shared_ptr(const FSP &fsp): _p(new foreign_shared_ptr_impl<FSP>(fsp)) {} ~foreign_void_shared_ptr() { delete _p; } foreign_void_shared_ptr & operator=(const foreign_void_shared_ptr &other) { if(&other == this) return *this; foreign_void_shared_ptr(other).swap(*this); return *this; } void swap(foreign_void_shared_ptr &other) { boost::swap(_p, other._p); } private: foreign_shared_ptr_impl_base *_p; }; struct foreign_weak_ptr_impl_base { virtual ~foreign_weak_ptr_impl_base() {} virtual foreign_void_shared_ptr lock() const = 0; virtual bool expired() const = 0; virtual foreign_weak_ptr_impl_base * clone() const = 0; }; template<typename FWP> class foreign_weak_ptr_impl: public foreign_weak_ptr_impl_base { public: foreign_weak_ptr_impl(const FWP &p): _p(p) {} virtual foreign_void_shared_ptr lock() const { return foreign_void_shared_ptr(_p.lock()); } virtual bool expired() const { return _p.expired(); } virtual foreign_weak_ptr_impl * clone() const { return new foreign_weak_ptr_impl(*this); } private: FWP _p; }; class foreign_void_weak_ptr { public: foreign_void_weak_ptr() {} foreign_void_weak_ptr(const foreign_void_weak_ptr &other): _p(other._p->clone()) {} template<typename FWP> explicit foreign_void_weak_ptr(const FWP &fwp): _p(new foreign_weak_ptr_impl<FWP>(fwp)) {} foreign_void_weak_ptr & operator=(const foreign_void_weak_ptr &other) { if(&other == this) return *this; foreign_void_weak_ptr(other).swap(*this); return *this; } void swap(foreign_void_weak_ptr &other) { boost::swap(_p, other._p); } foreign_void_shared_ptr lock() const { return _p->lock(); } bool expired() const { return _p->expired(); } private: boost::scoped_ptr<foreign_weak_ptr_impl_base> _p; }; } // namespace detail } // namespace signals2 } // namespace boost #endif // BOOST_SIGNALS2_FOREIGN_PTR_HPP
// helper code for dealing with tracking non-boost shared_ptr/weak_ptr // Copyright Frank Mori Hess 2009. // Distributed under the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/signals2 for library home page. #ifndef BOOST_SIGNALS2_FOREIGN_PTR_HPP #define BOOST_SIGNALS2_FOREIGN_PTR_HPP #include <algorithm> #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/scoped_ptr.hpp> #include <boost/smart_ptr/bad_weak_ptr.hpp> #include <boost/utility/swap.hpp> namespace boost { template<typename T> class shared_ptr; template<typename T> class weak_ptr; namespace signals2 { template<typename WeakPtr> struct weak_ptr_traits {}; template<typename T> struct weak_ptr_traits<boost::weak_ptr<T> > { typedef boost::shared_ptr<T> shared_type; }; // Workaround for a bug in boost: // https://svn.boost.org/trac/boost/ticket/6655 // // It should be safe to depend on DEAL macros at this point as this header // should only be used by deal.II and dependent projects... // // - Maier, 2013 #ifdef DEAL_II_CAN_USE_CXX11 template<typename T> struct weak_ptr_traits<std::weak_ptr<T> > { typedef std::shared_ptr<T> shared_type; }; #endif template<typename SharedPtr> struct shared_ptr_traits {}; template<typename T> struct shared_ptr_traits<boost::shared_ptr<T> > { typedef boost::weak_ptr<T> weak_type; }; // as above #ifdef DEAL_II_CAN_USE_CXX11 template<typename T> struct shared_ptr_traits<std::shared_ptr<T> > { typedef std::weak_ptr<T> weak_type; }; #endif namespace detail { struct foreign_shared_ptr_impl_base { virtual ~foreign_shared_ptr_impl_base() {} virtual void* get() const = 0; virtual foreign_shared_ptr_impl_base * clone() const = 0; }; template<typename FSP> class foreign_shared_ptr_impl: public foreign_shared_ptr_impl_base { public: foreign_shared_ptr_impl(const FSP &p): _p(p) {} virtual void * get() const { return _p.get(); } virtual foreign_shared_ptr_impl * clone() const { return new foreign_shared_ptr_impl(*this); } private: FSP _p; }; class foreign_void_shared_ptr { public: foreign_void_shared_ptr(): _p(0) {} foreign_void_shared_ptr(const foreign_void_shared_ptr &other): _p(other._p->clone()) {} template<typename FSP> explicit foreign_void_shared_ptr(const FSP &fsp): _p(new foreign_shared_ptr_impl<FSP>(fsp)) {} ~foreign_void_shared_ptr() { delete _p; } foreign_void_shared_ptr & operator=(const foreign_void_shared_ptr &other) { if(&other == this) return *this; foreign_void_shared_ptr(other).swap(*this); return *this; } void swap(foreign_void_shared_ptr &other) { boost::swap(_p, other._p); } private: foreign_shared_ptr_impl_base *_p; }; struct foreign_weak_ptr_impl_base { virtual ~foreign_weak_ptr_impl_base() {} virtual foreign_void_shared_ptr lock() const = 0; virtual bool expired() const = 0; virtual foreign_weak_ptr_impl_base * clone() const = 0; }; template<typename FWP> class foreign_weak_ptr_impl: public foreign_weak_ptr_impl_base { public: foreign_weak_ptr_impl(const FWP &p): _p(p) {} virtual foreign_void_shared_ptr lock() const { return foreign_void_shared_ptr(_p.lock()); } virtual bool expired() const { return _p.expired(); } virtual foreign_weak_ptr_impl * clone() const { return new foreign_weak_ptr_impl(*this); } private: FWP _p; }; class foreign_void_weak_ptr { public: foreign_void_weak_ptr() {} foreign_void_weak_ptr(const foreign_void_weak_ptr &other): _p(other._p->clone()) {} template<typename FWP> explicit foreign_void_weak_ptr(const FWP &fwp): _p(new foreign_weak_ptr_impl<FWP>(fwp)) {} foreign_void_weak_ptr & operator=(const foreign_void_weak_ptr &other) { if(&other == this) return *this; foreign_void_weak_ptr(other).swap(*this); return *this; } void swap(foreign_void_weak_ptr &other) { boost::swap(_p, other._p); } foreign_void_shared_ptr lock() const { return _p->lock(); } bool expired() const { return _p->expired(); } private: boost::scoped_ptr<foreign_weak_ptr_impl_base> _p; }; } // namespace detail } // namespace signals2 } // namespace boost #endif // BOOST_SIGNALS2_FOREIGN_PTR_HPP
Fix typos
Fix typos git-svn-id: c76ba5783a977acea081caf371e30e6fdf9e4459@30263 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
sriharisundar/dealii,jperryhouts/dealii,EGP-CIG-REU/dealii,nicolacavallini/dealii,Arezou-gh/dealii,pesser/dealii,ESeNonFossiIo/dealii,angelrca/dealii,sriharisundar/dealii,jperryhouts/dealii,mac-a/dealii,danshapero/dealii,kalj/dealii,rrgrove6/dealii,natashasharma/dealii,johntfoster/dealii,EGP-CIG-REU/dealii,flow123d/dealii,nicolacavallini/dealii,Arezou-gh/dealii,ibkim11/dealii,flow123d/dealii,lue/dealii,spco/dealii,msteigemann/dealii,maieneuro/dealii,angelrca/dealii,shakirbsm/dealii,adamkosik/dealii,nicolacavallini/dealii,spco/dealii,maieneuro/dealii,adamkosik/dealii,andreamola/dealii,rrgrove6/dealii,maieneuro/dealii,ibkim11/dealii,Arezou-gh/dealii,natashasharma/dealii,andreamola/dealii,nicolacavallini/dealii,ibkim11/dealii,johntfoster/dealii,lpolster/dealii,shakirbsm/dealii,natashasharma/dealii,ibkim11/dealii,gpitton/dealii,naliboff/dealii,naliboff/dealii,ibkim11/dealii,rrgrove6/dealii,naliboff/dealii,sriharisundar/dealii,andreamola/dealii,gpitton/dealii,johntfoster/dealii,natashasharma/dealii,angelrca/dealii,EGP-CIG-REU/dealii,ibkim11/dealii,maieneuro/dealii,sairajat/dealii,lue/dealii,nicolacavallini/dealii,maieneuro/dealii,kalj/dealii,JaeryunYim/dealii,kalj/dealii,gpitton/dealii,johntfoster/dealii,angelrca/dealii,lue/dealii,natashasharma/dealii,jperryhouts/dealii,pesser/dealii,danshapero/dealii,mtezzele/dealii,mtezzele/dealii,natashasharma/dealii,sriharisundar/dealii,pesser/dealii,sairajat/dealii,sriharisundar/dealii,flow123d/dealii,mac-a/dealii,jperryhouts/dealii,msteigemann/dealii,naliboff/dealii,lue/dealii,YongYang86/dealii,pesser/dealii,andreamola/dealii,rrgrove6/dealii,angelrca/dealii,gpitton/dealii,rrgrove6/dealii,YongYang86/dealii,EGP-CIG-REU/dealii,pesser/dealii,pesser/dealii,mtezzele/dealii,johntfoster/dealii,danshapero/dealii,sairajat/dealii,JaeryunYim/dealii,mac-a/dealii,spco/dealii,YongYang86/dealii,maieneuro/dealii,gpitton/dealii,JaeryunYim/dealii,flow123d/dealii,ESeNonFossiIo/dealii,rrgrove6/dealii,sairajat/dealii,adamkosik/dealii,EGP-CIG-REU/dealii,adamkosik/dealii,adamkosik/dealii,jperryhouts/dealii,ESeNonFossiIo/dealii,spco/dealii,maieneuro/dealii,msteigemann/dealii,lpolster/dealii,YongYang86/dealii,johntfoster/dealii,sairajat/dealii,lue/dealii,sriharisundar/dealii,kalj/dealii,lpolster/dealii,kalj/dealii,nicolacavallini/dealii,angelrca/dealii,pesser/dealii,naliboff/dealii,gpitton/dealii,YongYang86/dealii,msteigemann/dealii,lue/dealii,adamkosik/dealii,ESeNonFossiIo/dealii,EGP-CIG-REU/dealii,mtezzele/dealii,msteigemann/dealii,JaeryunYim/dealii,msteigemann/dealii,Arezou-gh/dealii,spco/dealii,naliboff/dealii,mtezzele/dealii,naliboff/dealii,flow123d/dealii,angelrca/dealii,flow123d/dealii,lpolster/dealii,jperryhouts/dealii,jperryhouts/dealii,rrgrove6/dealii,danshapero/dealii,shakirbsm/dealii,YongYang86/dealii,mtezzele/dealii,lpolster/dealii,spco/dealii,JaeryunYim/dealii,Arezou-gh/dealii,danshapero/dealii,lpolster/dealii,lue/dealii,nicolacavallini/dealii,msteigemann/dealii,Arezou-gh/dealii,shakirbsm/dealii,danshapero/dealii,natashasharma/dealii,andreamola/dealii,andreamola/dealii,shakirbsm/dealii,adamkosik/dealii,kalj/dealii,sairajat/dealii,Arezou-gh/dealii,sairajat/dealii,spco/dealii,ESeNonFossiIo/dealii,flow123d/dealii,danshapero/dealii,mac-a/dealii,ESeNonFossiIo/dealii,kalj/dealii,mtezzele/dealii,shakirbsm/dealii,gpitton/dealii,sriharisundar/dealii,JaeryunYim/dealii,ESeNonFossiIo/dealii,shakirbsm/dealii,JaeryunYim/dealii,YongYang86/dealii,mac-a/dealii,mac-a/dealii,ibkim11/dealii,EGP-CIG-REU/dealii,andreamola/dealii,lpolster/dealii,johntfoster/dealii,mac-a/dealii
9953102813e473dba8cd7d714d70ca33d1a98fb7
src/trace_processor/importers/json/json_trace_parser.cc
src/trace_processor/importers/json/json_trace_parser.cc
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/json/json_trace_parser.h" #include <inttypes.h> #include <limits> #include <string> #include "perfetto/base/logging.h" #include "perfetto/ext/base/string_utils.h" #include "perfetto/ext/base/string_view.h" #include "perfetto/ext/base/utils.h" #include "src/trace_processor/importers/common/event_tracker.h" #include "src/trace_processor/importers/common/flow_tracker.h" #include "src/trace_processor/importers/common/process_tracker.h" #include "src/trace_processor/importers/common/slice_tracker.h" #include "src/trace_processor/importers/common/track_tracker.h" #include "src/trace_processor/importers/json/json_tracker.h" #include "src/trace_processor/importers/json/json_utils.h" #include "src/trace_processor/types/trace_processor_context.h" namespace perfetto { namespace trace_processor { #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) namespace { base::Optional<uint64_t> MaybeExtractFlowIdentifier(const Json::Value& value, bool version2) { std::string id_key = (version2 ? "bind_id" : "id"); if (!value.isMember(id_key)) return base::nullopt; auto id = value[id_key]; if (id.isNumeric()) return id.asUInt64(); if (!id.isString()) return base::nullopt; const char* c_string = id.asCString(); return base::CStringToUInt64(c_string, 16); } } // namespace #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) JsonTraceParser::JsonTraceParser(TraceProcessorContext* context) : context_(context), systrace_line_parser_(context) {} JsonTraceParser::~JsonTraceParser() = default; void JsonTraceParser::ParseFtracePacket(uint32_t, int64_t, TimestampedTracePiece) { PERFETTO_FATAL("Json Trace Parser cannot handle ftrace packets."); } void JsonTraceParser::ParseTracePacket(int64_t timestamp, TimestampedTracePiece ttp) { PERFETTO_DCHECK(json::IsJsonSupported()); #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) PERFETTO_DCHECK(ttp.type == TimestampedTracePiece::Type::kJsonValue || ttp.type == TimestampedTracePiece::Type::kSystraceLine); if (ttp.type == TimestampedTracePiece::Type::kSystraceLine) { systrace_line_parser_.ParseLine(*ttp.systrace_line); return; } auto opt_value = json::ParseJsonString(base::StringView(ttp.json_value)); if (!opt_value) { context_->storage->IncrementStats(stats::json_parser_failure); return; } ProcessTracker* procs = context_->process_tracker.get(); TraceStorage* storage = context_->storage.get(); SliceTracker* slice_tracker = context_->slice_tracker.get(); FlowTracker* flow_tracker = context_->flow_tracker.get(); const Json::Value& value = *opt_value; auto& ph = value["ph"]; if (!ph.isString()) return; char phase = *ph.asCString(); base::Optional<uint32_t> opt_pid; base::Optional<uint32_t> opt_tid; if (value.isMember("pid")) opt_pid = json::CoerceToUint32(value["pid"]); if (value.isMember("tid")) opt_tid = json::CoerceToUint32(value["tid"]); uint32_t pid = opt_pid.value_or(0); uint32_t tid = opt_tid.value_or(pid); base::StringView cat = value.isMember("cat") ? base::StringView(value["cat"].asCString()) : base::StringView(); base::StringView name = value.isMember("name") ? base::StringView(value["name"].asCString()) : base::StringView(); StringId cat_id = storage->InternString(cat); StringId name_id = storage->InternString(name); UniqueTid utid = procs->UpdateThread(tid, pid); auto args_inserter = [this, &value](ArgsTracker::BoundInserter* inserter) { if (value.isMember("args")) { json::AddJsonValueToArgs(value["args"], /* flat_key = */ "args", /* key = */ "args", context_->storage.get(), inserter); } }; switch (phase) { case 'B': { // TRACE_EVENT_BEGIN. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Begin(timestamp, track_id, cat_id, name_id, args_inserter); MaybeAddFlow(track_id, value); break; } case 'E': { // TRACE_EVENT_END. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->End(timestamp, track_id, cat_id, name_id, args_inserter); break; } case 'X': { // TRACE_EVENT (scoped event). base::Optional<int64_t> opt_dur = JsonTracker::GetOrCreate(context_)->CoerceToTs(value["dur"]); if (!opt_dur.has_value()) return; TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Scoped(timestamp, track_id, cat_id, name_id, opt_dur.value(), args_inserter); MaybeAddFlow(track_id, value); break; } case 'C': { // TRACE_EVENT_COUNTER auto args = value["args"]; if (!args.isObject()) { context_->storage->IncrementStats(stats::json_parser_failure); break; } std::string counter_name_prefix = name.ToStdString(); if (value.isMember("id")) { counter_name_prefix += " id: " + value["id"].asString(); } for (auto it = args.begin(); it != args.end(); ++it) { std::string counter_name = counter_name_prefix + " " + it.name(); StringId counter_name_id = context_->storage->InternString(base::StringView(counter_name)); TrackId track_id = context_->track_tracker->InternProcessCounterTrack( counter_name_id, utid); context_->event_tracker->PushCounter(timestamp, it->asDouble(), track_id); } break; } case 'i': { // TRACE_EVENT_INSTANT base::StringView scope; if (value.isMember("s")) { scope = value["s"].asCString(); } TrackId track_id; if (scope == "g") { track_id = context_->track_tracker ->GetOrCreateLegacyChromeGlobalInstantTrack(); } else if (scope == "p") { if (!opt_pid) { context_->storage->IncrementStats(stats::json_parser_failure); break; } UniquePid upid = context_->process_tracker->GetOrCreateProcess(pid); track_id = context_->track_tracker->InternLegacyChromeProcessInstantTrack( upid); } else if (scope == "t" || scope.data() == nullptr) { if (!opt_tid) { context_->storage->IncrementStats(stats::json_parser_failure); break; } track_id = context_->track_tracker->InternThreadTrack(utid); } else { context_->storage->IncrementStats(stats::json_parser_failure); break; } context_->slice_tracker->Scoped(timestamp, track_id, cat_id, name_id, 0); break; } case 's': { // TRACE_EVENT_FLOW_START TrackId track_id = context_->track_tracker->InternThreadTrack(utid); auto opt_source_id = MaybeExtractFlowIdentifier(value, /* version2 = */ false); if (opt_source_id) { FlowId flow_id = flow_tracker->GetFlowIdForV1Event( opt_source_id.value(), cat_id, name_id); flow_tracker->Begin(track_id, flow_id); } else { context_->storage->IncrementStats(stats::flow_invalid_id); } break; } case 't': { // TRACE_EVENT_FLOW_STEP TrackId track_id = context_->track_tracker->InternThreadTrack(utid); auto opt_source_id = MaybeExtractFlowIdentifier(value, /* version2 = */ false); if (opt_source_id) { FlowId flow_id = flow_tracker->GetFlowIdForV1Event( opt_source_id.value(), cat_id, name_id); flow_tracker->Step(track_id, flow_id); } else { context_->storage->IncrementStats(stats::flow_invalid_id); } break; } case 'f': { // TRACE_EVENT_FLOW_END TrackId track_id = context_->track_tracker->InternThreadTrack(utid); auto opt_source_id = MaybeExtractFlowIdentifier(value, /* version2 = */ false); if (opt_source_id) { FlowId flow_id = flow_tracker->GetFlowIdForV1Event( opt_source_id.value(), cat_id, name_id); bool bind_enclosing_slice = value.isMember("bp") && strcmp(value["bp"].asCString(), "e") == 0; flow_tracker->End(track_id, flow_id, bind_enclosing_slice, /* close_flow = */ false); } else { context_->storage->IncrementStats(stats::flow_invalid_id); } break; } case 'M': { // Metadata events (process and thread names). if (strcmp(value["name"].asCString(), "thread_name") == 0 && !value["args"]["name"].empty()) { const char* thread_name = value["args"]["name"].asCString(); auto thread_name_id = context_->storage->InternString(thread_name); procs->UpdateThreadName(tid, thread_name_id, ThreadNamePriority::kOther); break; } if (strcmp(value["name"].asCString(), "process_name") == 0 && !value["args"]["name"].empty()) { const char* proc_name = value["args"]["name"].asCString(); procs->SetProcessMetadata(pid, base::nullopt, proc_name, base::StringView()); break; } } } #else perfetto::base::ignore_result(timestamp); perfetto::base::ignore_result(ttp); perfetto::base::ignore_result(context_); PERFETTO_ELOG("Cannot parse JSON trace due to missing JSON support"); #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) } void JsonTraceParser::MaybeAddFlow(TrackId track_id, const Json::Value& event) { PERFETTO_DCHECK(json::IsJsonSupported()); #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) auto opt_bind_id = MaybeExtractFlowIdentifier(event, /* version2 = */ true); if (opt_bind_id) { FlowTracker* flow_tracker = context_->flow_tracker.get(); bool flow_out = event.isMember("flow_out") && event["flow_out"].asBool(); bool flow_in = event.isMember("flow_in") && event["flow_in"].asBool(); if (flow_in && flow_out) { flow_tracker->Step(track_id, opt_bind_id.value()); } else if (flow_out) { flow_tracker->Begin(track_id, opt_bind_id.value()); } else if (flow_in) { // bind_enclosing_slice is always true for v2 flow events flow_tracker->End(track_id, opt_bind_id.value(), true, /* close_flow = */ false); } else { context_->storage->IncrementStats(stats::flow_without_direction); } } #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) } } // namespace trace_processor } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/json/json_trace_parser.h" #include <inttypes.h> #include <limits> #include <string> #include "perfetto/base/logging.h" #include "perfetto/ext/base/string_utils.h" #include "perfetto/ext/base/string_view.h" #include "perfetto/ext/base/utils.h" #include "src/trace_processor/importers/common/event_tracker.h" #include "src/trace_processor/importers/common/flow_tracker.h" #include "src/trace_processor/importers/common/process_tracker.h" #include "src/trace_processor/importers/common/slice_tracker.h" #include "src/trace_processor/importers/common/track_tracker.h" #include "src/trace_processor/importers/json/json_tracker.h" #include "src/trace_processor/importers/json/json_utils.h" #include "src/trace_processor/types/trace_processor_context.h" namespace perfetto { namespace trace_processor { #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) namespace { base::Optional<uint64_t> MaybeExtractFlowIdentifier(const Json::Value& value, bool version2) { std::string id_key = (version2 ? "bind_id" : "id"); if (!value.isMember(id_key)) return base::nullopt; auto id = value[id_key]; if (id.isNumeric()) return id.asUInt64(); if (!id.isString()) return base::nullopt; const char* c_string = id.asCString(); return base::CStringToUInt64(c_string, 16); } } // namespace #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) JsonTraceParser::JsonTraceParser(TraceProcessorContext* context) : context_(context), systrace_line_parser_(context) {} JsonTraceParser::~JsonTraceParser() = default; void JsonTraceParser::ParseFtracePacket(uint32_t, int64_t, TimestampedTracePiece) { PERFETTO_FATAL("Json Trace Parser cannot handle ftrace packets."); } void JsonTraceParser::ParseTracePacket(int64_t timestamp, TimestampedTracePiece ttp) { PERFETTO_DCHECK(json::IsJsonSupported()); #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) PERFETTO_DCHECK(ttp.type == TimestampedTracePiece::Type::kJsonValue || ttp.type == TimestampedTracePiece::Type::kSystraceLine); if (ttp.type == TimestampedTracePiece::Type::kSystraceLine) { systrace_line_parser_.ParseLine(*ttp.systrace_line); return; } auto opt_value = json::ParseJsonString(base::StringView(ttp.json_value)); if (!opt_value) { context_->storage->IncrementStats(stats::json_parser_failure); return; } ProcessTracker* procs = context_->process_tracker.get(); TraceStorage* storage = context_->storage.get(); SliceTracker* slice_tracker = context_->slice_tracker.get(); FlowTracker* flow_tracker = context_->flow_tracker.get(); const Json::Value& value = *opt_value; auto& ph = value["ph"]; if (!ph.isString()) return; char phase = *ph.asCString(); base::Optional<uint32_t> opt_pid; base::Optional<uint32_t> opt_tid; if (value.isMember("pid")) opt_pid = json::CoerceToUint32(value["pid"]); if (value.isMember("tid")) opt_tid = json::CoerceToUint32(value["tid"]); uint32_t pid = opt_pid.value_or(0); uint32_t tid = opt_tid.value_or(pid); base::StringView cat = value.isMember("cat") ? base::StringView(value["cat"].asCString()) : base::StringView(); base::StringView name = value.isMember("name") ? base::StringView(value["name"].asCString()) : base::StringView(); StringId cat_id = storage->InternString(cat); StringId name_id = storage->InternString(name); UniqueTid utid = procs->UpdateThread(tid, pid); auto args_inserter = [this, &value](ArgsTracker::BoundInserter* inserter) { if (value.isMember("args")) { json::AddJsonValueToArgs(value["args"], /* flat_key = */ "args", /* key = */ "args", context_->storage.get(), inserter); } }; switch (phase) { case 'B': { // TRACE_EVENT_BEGIN. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Begin(timestamp, track_id, cat_id, name_id, args_inserter); MaybeAddFlow(track_id, value); break; } case 'E': { // TRACE_EVENT_END. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->End(timestamp, track_id, cat_id, name_id, args_inserter); break; } case 'X': { // TRACE_EVENT (scoped event). base::Optional<int64_t> opt_dur = JsonTracker::GetOrCreate(context_)->CoerceToTs(value["dur"]); if (!opt_dur.has_value()) return; TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Scoped(timestamp, track_id, cat_id, name_id, opt_dur.value(), args_inserter); MaybeAddFlow(track_id, value); break; } case 'C': { // TRACE_EVENT_COUNTER auto args = value["args"]; if (!args.isObject()) { context_->storage->IncrementStats(stats::json_parser_failure); break; } std::string counter_name_prefix = name.ToStdString(); if (value.isMember("id")) { counter_name_prefix += " id: " + value["id"].asString(); } for (auto it = args.begin(); it != args.end(); ++it) { std::string counter_name = counter_name_prefix + " " + it.name(); StringId counter_name_id = context_->storage->InternString(base::StringView(counter_name)); context_->event_tracker->PushProcessCounterForThread( timestamp, it->asDouble(), counter_name_id, utid); } break; } case 'i': { // TRACE_EVENT_INSTANT base::StringView scope; if (value.isMember("s")) { scope = value["s"].asCString(); } TrackId track_id; if (scope == "g") { track_id = context_->track_tracker ->GetOrCreateLegacyChromeGlobalInstantTrack(); } else if (scope == "p") { if (!opt_pid) { context_->storage->IncrementStats(stats::json_parser_failure); break; } UniquePid upid = context_->process_tracker->GetOrCreateProcess(pid); track_id = context_->track_tracker->InternLegacyChromeProcessInstantTrack( upid); } else if (scope == "t" || scope.data() == nullptr) { if (!opt_tid) { context_->storage->IncrementStats(stats::json_parser_failure); break; } track_id = context_->track_tracker->InternThreadTrack(utid); } else { context_->storage->IncrementStats(stats::json_parser_failure); break; } context_->slice_tracker->Scoped(timestamp, track_id, cat_id, name_id, 0); break; } case 's': { // TRACE_EVENT_FLOW_START TrackId track_id = context_->track_tracker->InternThreadTrack(utid); auto opt_source_id = MaybeExtractFlowIdentifier(value, /* version2 = */ false); if (opt_source_id) { FlowId flow_id = flow_tracker->GetFlowIdForV1Event( opt_source_id.value(), cat_id, name_id); flow_tracker->Begin(track_id, flow_id); } else { context_->storage->IncrementStats(stats::flow_invalid_id); } break; } case 't': { // TRACE_EVENT_FLOW_STEP TrackId track_id = context_->track_tracker->InternThreadTrack(utid); auto opt_source_id = MaybeExtractFlowIdentifier(value, /* version2 = */ false); if (opt_source_id) { FlowId flow_id = flow_tracker->GetFlowIdForV1Event( opt_source_id.value(), cat_id, name_id); flow_tracker->Step(track_id, flow_id); } else { context_->storage->IncrementStats(stats::flow_invalid_id); } break; } case 'f': { // TRACE_EVENT_FLOW_END TrackId track_id = context_->track_tracker->InternThreadTrack(utid); auto opt_source_id = MaybeExtractFlowIdentifier(value, /* version2 = */ false); if (opt_source_id) { FlowId flow_id = flow_tracker->GetFlowIdForV1Event( opt_source_id.value(), cat_id, name_id); bool bind_enclosing_slice = value.isMember("bp") && strcmp(value["bp"].asCString(), "e") == 0; flow_tracker->End(track_id, flow_id, bind_enclosing_slice, /* close_flow = */ false); } else { context_->storage->IncrementStats(stats::flow_invalid_id); } break; } case 'M': { // Metadata events (process and thread names). if (strcmp(value["name"].asCString(), "thread_name") == 0 && !value["args"]["name"].empty()) { const char* thread_name = value["args"]["name"].asCString(); auto thread_name_id = context_->storage->InternString(thread_name); procs->UpdateThreadName(tid, thread_name_id, ThreadNamePriority::kOther); break; } if (strcmp(value["name"].asCString(), "process_name") == 0 && !value["args"]["name"].empty()) { const char* proc_name = value["args"]["name"].asCString(); procs->SetProcessMetadata(pid, base::nullopt, proc_name, base::StringView()); break; } } } #else perfetto::base::ignore_result(timestamp); perfetto::base::ignore_result(ttp); perfetto::base::ignore_result(context_); PERFETTO_ELOG("Cannot parse JSON trace due to missing JSON support"); #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) } void JsonTraceParser::MaybeAddFlow(TrackId track_id, const Json::Value& event) { PERFETTO_DCHECK(json::IsJsonSupported()); #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) auto opt_bind_id = MaybeExtractFlowIdentifier(event, /* version2 = */ true); if (opt_bind_id) { FlowTracker* flow_tracker = context_->flow_tracker.get(); bool flow_out = event.isMember("flow_out") && event["flow_out"].asBool(); bool flow_in = event.isMember("flow_in") && event["flow_in"].asBool(); if (flow_in && flow_out) { flow_tracker->Step(track_id, opt_bind_id.value()); } else if (flow_out) { flow_tracker->Begin(track_id, opt_bind_id.value()); } else if (flow_in) { // bind_enclosing_slice is always true for v2 flow events flow_tracker->End(track_id, opt_bind_id.value(), true, /* close_flow = */ false); } else { context_->storage->IncrementStats(stats::flow_without_direction); } } #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) } } // namespace trace_processor } // namespace perfetto
fix parsing JSON counter events
tp: fix parsing JSON counter events We were accidentally passing utid to InternProcessCounterTrack which is very wrong. Fix by using the correct process function Change-Id: I1c9532d75b06b7d9fa8d4e7079ce331c5f62788c Bug: #140 (https://github.com/google/perfetto/issues/140)
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
0720eabef22d4b4d772f84bca226ccdd3fc32497
rx24t_GPS_sample/main.cpp
rx24t_GPS_sample/main.cpp
//=====================================================================// /*! @file @brief RX24T GPS サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n ・PB6/RXD5(27) <--- GPS-TX @n ・PB5/TXD5(28) ---> GPS-RX Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fifo.hpp" #include "common/format.hpp" namespace { class cmt_task { public: void operator() () { } }; device::cmt_io<device::CMT0, cmt_task> cmt_; typedef utils::fifo<uint8_t, 256> fifo256; typedef utils::fifo<uint16_t, 512> fifo512; device::sci_io<device::SCI1, fifo256, fifo256> sci1_; device::sci_io<device::SCI5, fifo512, fifo256> sci5_; } extern "C" { void sci_putch(char ch) { sci1_.putch(ch); } void sci_puts(const char* str) { sci1_.puts(str); } char sci_getch(void) { return sci1_.getch(); } uint16_t sci_length() { return sci1_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); device::SYSTEM::OPCCR = 0; // 高速モード選択 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); // clock osc 10MHz device::SYSTEM::MOSCWTCR = 9; // 4ms wait // メインクロック・ドライブ能力設定、内部発信 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop"); device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz) device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop"); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20) | device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40) | device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60) device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 { // タイマー設定(60Hz) uint8_t cmt_level = 4; cmt_.start(60, cmt_level); } { // SCI1 設定 uint8_t sci_level = 2; sci1_.start(115200, sci_level); } { // SCI5 設定 (GPS) uint8_t sci_level = 2; sci5_.start(9600, sci_level); } utils::format("RX24T GPS sample\n"); device::PORT0::PDR.B0 = 1; // output uint32_t cnt = 0; while(1) { cmt_.sync(); while(sci5_.recv_length() > 0) { auto ch = sci5_.getch(); sci1_.putch(ch); } ++cnt; if(cnt >= 30) { cnt = 0; } device::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1; } }
//=====================================================================// /*! @file @brief RX24T GPS サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n ・PB6/RXD5(27) <--- GPS-TX @n ・PB5/TXD5(28) ---> GPS-RX Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/nmea_dec.hpp" namespace { class cmt_task { public: void operator() () { } }; device::cmt_io<device::CMT0, cmt_task> cmt_; typedef utils::fifo<uint8_t, 256> fifo256; typedef utils::fifo<uint16_t, 512> fifo512; device::sci_io<device::SCI1, fifo256, fifo256> sci1_; typedef device::sci_io<device::SCI5, fifo512, fifo256> SCI5; SCI5 sci5_; utils::nmea_dec<SCI5> nmea_(sci5_); } extern "C" { void sci_putch(char ch) { sci1_.putch(ch); } void sci_puts(const char* str) { sci1_.puts(str); } char sci_getch(void) { return sci1_.getch(); } uint16_t sci_length() { return sci1_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); device::SYSTEM::OPCCR = 0; // 高速モード選択 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); // clock osc 10MHz device::SYSTEM::MOSCWTCR = 9; // 4ms wait // メインクロック・ドライブ能力設定、内部発信 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop"); device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz) device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop"); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20) | device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40) | device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60) device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 { // タイマー設定(60Hz) uint8_t cmt_level = 4; cmt_.start(60, cmt_level); } { // SCI1 設定 uint8_t sci_level = 2; sci1_.start(115200, sci_level); } { // SCI5 設定 (GPS) uint8_t sci_level = 2; sci5_.start(9600, sci_level); } utils::format("RX24T GPS sample\n"); device::PORT0::PDR.B0 = 1; // output uint32_t cnt = 0; while(1) { cmt_.sync(); auto f = nmea_.service(); if(f) { utils::format("Time: %s, ") % nmea_.get_time(); utils::format("Lat: %s, ") % nmea_.get_lat(); utils::format("Lon: %s\n") % nmea_.get_lon(); }; // while(sci5_.recv_length() > 0) { // auto ch = sci5_.getch(); // sci1_.putch(ch); // } ++cnt; if(cnt >= 30) { cnt = 0; } device::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1; } }
update basic decode
update basic decode
C++
bsd-3-clause
hirakuni45/RX,hirakuni45/RX,hirakuni45/RX,hirakuni45/RX
721a82cd907d3d453f2a472eaf3fe3a31c00fe44
MFWebCamToFile/MFWebCamToFile.cpp
MFWebCamToFile/MFWebCamToFile.cpp
/****************************************************************************** * Filename: MFWebCamToFile.cpp * * Description: * This file contains a C++ console application that captures the realtime video * stream from a webcam to an MP4 file. * * Note: The webcam index and the source reader media output type will need * adjustment depending on the the configuration of video devices on any machine * running this sample. * * Author: * Aaron Clauson ([email protected]) * * History: * 26 Feb 2015 Aaron Clauson ([email protected]) Created. * * License: Public Domain (no warranty, use at own risk) /******************************************************************************/ #include "../Common/MFUtility.h" #include <stdio.h> #include <tchar.h> #include <evr.h> #include <mfapi.h> #include <mfplay.h> #include <mfreadwrite.h> #include <mferror.h> #include <wmcodecdsp.h> #include <fstream> #pragma comment(lib, "mf.lib") #pragma comment(lib, "mfplat.lib") #pragma comment(lib, "mfplay.lib") #pragma comment(lib, "mfreadwrite.lib") #pragma comment(lib, "mfuuid.lib") #pragma comment(lib, "wmcodecdspuuid.lib") #define WEBCAM_DEVICE_INDEX 0 // Adjust according to desired video capture device. #define SAMPLE_COUNT 100 // Adjust depending on number of samples to capture. #define CAPTURE_FILENAME L"capture.mp4" int main() { IMFMediaSource *videoSource = NULL; UINT32 videoDeviceCount = 0; IMFAttributes *videoConfig = NULL; IMFActivate **videoDevices = NULL; IMFSourceReader *videoReader = NULL; WCHAR *webcamFriendlyName; IMFMediaType*videoSourceOutputType = NULL; IMFSinkWriter *pWriter; IMFMediaType *pVideoOutType = NULL; DWORD writerVideoStreamIndex = 0; UINT webcamNameLength = 0; CHECK_HR(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE), "COM initialisation failed."); CHECK_HR(MFStartup(MF_VERSION), "Media Foundation initialisation failed."); // Get the first available webcam. CHECK_HR(MFCreateAttributes(&videoConfig, 1), "Error creating video configuation.\n"); // Request video capture devices. CHECK_HR(videoConfig->SetGUID( MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), "Error initialising video configuration object."); CHECK_HR(MFEnumDeviceSources(videoConfig, &videoDevices, &videoDeviceCount), "Error enumerating video devices.\n"); CHECK_HR(videoDevices[WEBCAM_DEVICE_INDEX]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &webcamFriendlyName, &webcamNameLength), "Error retrieving vide device friendly name.\n"); wprintf(L"First available webcam: %s\n", webcamFriendlyName); CHECK_HR(videoDevices[WEBCAM_DEVICE_INDEX]->ActivateObject(IID_PPV_ARGS(&videoSource)), "Error activating video device.\n"); // Create a source reader. CHECK_HR(MFCreateSourceReaderFromMediaSource( videoSource, videoConfig, &videoReader), "Error creating video source reader.\n"); CHECK_HR(videoReader->GetCurrentMediaType( (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, &videoSourceOutputType), "Error retrieving current media type from first video stream.\n"); // Create the MP4 sink writer. CHECK_HR(MFCreateSinkWriterFromURL( CAPTURE_FILENAME, NULL, NULL, &pWriter), "Error creating mp4 sink writer."); CHECK_HR(MFTRegisterLocalByCLSID( __uuidof(CColorConvertDMO), MFT_CATEGORY_VIDEO_PROCESSOR, L"", MFT_ENUM_FLAG_SYNCMFT, 0, NULL, 0, NULL ), "Error registering colour converter DSP.\n"); // Configure the output video type on the sink writer. CHECK_HR(MFCreateMediaType(&pVideoOutType), "Configure encoder failed to create media type for video output sink."); CHECK_HR(pVideoOutType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video writer attribute, media type."); CHECK_HR(pVideoOutType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264), "Failed to set video writer attribute, video format (H.264)."); CHECK_HR(pVideoOutType->SetUINT32(MF_MT_AVG_BITRATE, 240 * 1000), "Failed to set video writer attribute, bit rate."); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_SIZE), "Failed to set video writer attribute, frame size."); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_RATE), "Failed to set video writer attribute, frame rate."); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_PIXEL_ASPECT_RATIO), "Failed to set video writer attribute, aspect ratio."); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_INTERLACE_MODE), "Failed to set video writer attribute, interlace mode."); CHECK_HR(pWriter->AddStream(pVideoOutType, &writerVideoStreamIndex), "Failed to add the video stream to the sink writer."); pVideoOutType->Release(); CHECK_HR(pWriter->SetInputMediaType(writerVideoStreamIndex, videoSourceOutputType, NULL), "Error setting the sink writer video input type.\n"); CHECK_HR(pWriter->BeginWriting(), "Failed to begin writing on the H.264 sink.\n"); DWORD streamIndex, flags; LONGLONG llVideoTimeStamp; IMFSample *videoSample = NULL; LONGLONG llVideoBaseTime = 0; int sampleCount = 0; printf("Recording...\n"); while (sampleCount < SAMPLE_COUNT) { CHECK_HR(videoReader->ReadSample( MF_SOURCE_READER_ANY_STREAM, // Stream index. 0, // Flags. &streamIndex, // Receives the actual stream index. &flags, // Receives status flags. &llVideoTimeStamp, // Receives the time stamp. &videoSample // Receives the sample or NULL. ), "Error reading video sample.\n"); if (videoSample) { // rebase the time stamp llVideoTimeStamp -= llVideoBaseTime; CHECK_HR(videoSample->SetSampleTime(llVideoTimeStamp), "Set video sample time failed.\n"); CHECK_HR(pWriter->WriteSample(writerVideoStreamIndex, videoSample), "Write video sample failed.\n"); SAFE_RELEASE(&videoSample); } sampleCount++; } printf("Finalising the capture.\n"); if (pWriter) { CHECK_HR(pWriter->Finalize(), "Error finalising H.264 sink writer.\n"); } done: printf("finished.\n"); auto c = getchar(); SAFE_RELEASE(videoSource); SAFE_RELEASE(videoConfig); SAFE_RELEASE(videoDevices); SAFE_RELEASE(videoReader); SAFE_RELEASE(videoSourceOutputType); SAFE_RELEASE(pWriter); return 0; }
/****************************************************************************** * Filename: MFWebCamToFile.cpp * * Description: * This file contains a C++ console application that captures the realtime video * stream from a webcam to an MP4 file. * * Note: The webcam index and the source reader media output type will need * adjustment depending on the the configuration of video devices on the machine * running this sample. * * Author: * Aaron Clauson ([email protected]) * * History: * 26 Feb 2015 Aaron Clauson Created. * * License: Public Domain (no warranty, use at own risk) /******************************************************************************/ #include "../Common/MFUtility.h" #include <stdio.h> #include <tchar.h> #include <evr.h> #include <mfapi.h> #include <mfplay.h> #include <mfreadwrite.h> #include <mferror.h> #include <wmcodecdsp.h> #include <fstream> #pragma comment(lib, "mf.lib") #pragma comment(lib, "mfplat.lib") #pragma comment(lib, "mfplay.lib") #pragma comment(lib, "mfreadwrite.lib") #pragma comment(lib, "mfuuid.lib") #pragma comment(lib, "wmcodecdspuuid.lib") #define WEBCAM_DEVICE_INDEX 0 // Adjust according to desired video capture device. #define SAMPLE_COUNT 100 // Adjust depending on number of samples to capture. #define CAPTURE_FILENAME L"capture.mp4" int main() { IMFMediaSource *videoSource = NULL; UINT32 videoDeviceCount = 0; IMFAttributes *videoConfig = NULL; IMFActivate **videoDevices = NULL; IMFSourceReader *videoReader = NULL; WCHAR *webcamFriendlyName; IMFMediaType*videoSourceOutputType = NULL; IMFSinkWriter *pWriter; IMFMediaType *pVideoOutType = NULL; DWORD writerVideoStreamIndex = 0; UINT webcamNameLength = 0; CHECK_HR(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE), "COM initialisation failed."); CHECK_HR(MFStartup(MF_VERSION), "Media Foundation initialisation failed."); // Get the first available webcam. CHECK_HR(MFCreateAttributes(&videoConfig, 1), "Error creating video configuation."); // Request video capture devices. CHECK_HR(videoConfig->SetGUID( MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), "Error initialising video configuration object."); CHECK_HR(MFEnumDeviceSources(videoConfig, &videoDevices, &videoDeviceCount), "Error enumerating video devices."); CHECK_HR(videoDevices[WEBCAM_DEVICE_INDEX]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &webcamFriendlyName, &webcamNameLength), "Error retrieving vide device friendly name."); wprintf(L"First available webcam: %s\n", webcamFriendlyName); CHECK_HR(videoDevices[WEBCAM_DEVICE_INDEX]->ActivateObject(IID_PPV_ARGS(&videoSource)), "Error activating video device."); // Create a source reader. CHECK_HR(MFCreateSourceReaderFromMediaSource( videoSource, videoConfig, &videoReader), "Error creating video source reader."); CHECK_HR(videoReader->GetCurrentMediaType( (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, &videoSourceOutputType), "Error retrieving current media type from first video stream."); // Create the MP4 sink writer. CHECK_HR(MFCreateSinkWriterFromURL( CAPTURE_FILENAME, NULL, NULL, &pWriter), "Error creating mp4 sink writer."); CHECK_HR(MFTRegisterLocalByCLSID( __uuidof(CColorConvertDMO), MFT_CATEGORY_VIDEO_PROCESSOR, L"", MFT_ENUM_FLAG_SYNCMFT, 0, NULL, 0, NULL ), "Error registering colour converter DSP.\n"); // Configure the output video type on the sink writer. CHECK_HR(MFCreateMediaType(&pVideoOutType), "Configure encoder failed to create media type for video output sink."); CHECK_HR(videoSourceOutputType->CopyAllItems(pVideoOutType), "Error copying media type attributes from source output media type."); // Only thing we want to change from source to sink is to get an mp4 output. CHECK_HR(pVideoOutType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264), "Failed to set video writer attribute, video format (H.264)."); CHECK_HR(pWriter->AddStream(pVideoOutType, &writerVideoStreamIndex), "Failed to add the video stream to the sink writer."); CHECK_HR(pWriter->SetInputMediaType(writerVideoStreamIndex, videoSourceOutputType, NULL), "Error setting the sink writer video input type."); CHECK_HR(pWriter->BeginWriting(), "Failed to begin writing on the H.264 sink."); DWORD streamIndex, flags; LONGLONG llVideoTimeStamp; IMFSample *videoSample = NULL; LONGLONG llVideoBaseTime = 0; int sampleCount = 0; printf("Recording...\n"); while (sampleCount < SAMPLE_COUNT) { CHECK_HR(videoReader->ReadSample( MF_SOURCE_READER_ANY_STREAM, // Stream index. 0, // Flags. &streamIndex, // Receives the actual stream index. &flags, // Receives status flags. &llVideoTimeStamp, // Receives the time stamp. &videoSample // Receives the sample or NULL. ), "Error reading video sample."); if (videoSample) { // rebase the time stamp llVideoTimeStamp -= llVideoBaseTime; CHECK_HR(videoSample->SetSampleTime(llVideoTimeStamp), "Set video sample time failed."); CHECK_HR(pWriter->WriteSample(writerVideoStreamIndex, videoSample), "Write video sample failed."); SAFE_RELEASE(&videoSample); } sampleCount++; } printf("Finalising the capture.\n"); if (pWriter) { CHECK_HR(pWriter->Finalize(), "Error finalising H.264 sink writer."); } done: printf("finished.\n"); auto c = getchar(); SAFE_RELEASE(videoSource); SAFE_RELEASE(videoConfig); SAFE_RELEASE(videoDevices); SAFE_RELEASE(videoReader); SAFE_RELEASE(pVideoOutType); SAFE_RELEASE(videoSourceOutputType); SAFE_RELEASE(pWriter); return 0; }
Tweak to MFWebCamToFile sample.
Tweak to MFWebCamToFile sample.
C++
unlicense
sipsorcery/mediafoundationsamples,sipsorcery/mediafoundationsamples,sipsorcery/mediafoundationsamples,sipsorcery/mediafoundationsamples
0f4440125b8693053726fda650591832bb13d468
src/solvers/dpll.cpp
src/solvers/dpll.cpp
#include <set> #include <map> #include <iostream> #include <cassert> #include <memory> #include <exception> #include <stdexcept> #include "structures/affectation.h" #include "structures/deductions.h" #include "structures/CL_proof.h" #include "structures/formula.h" #include "structures/clause.h" #include "solvers/dpll.h" #include "config.h" #define CONFLICT_GRAPH_FILE_NAME "/tmp/conflict_graph.dot" #define CL_PROOF_FILE_NAME "/tmp/CL_proof.tex" using namespace satsolver; #define AS_AFF(a, l) (a.is_true(l) ? l : -l) void make_conflict_graph(const Deductions &deductions, const Affectation &aff, int root, int literal) { FILE *graph_file = NULL; graph_file = fopen(CONFLICT_GRAPH_FILE_NAME, "w"); fprintf(graph_file, "digraph G {\n"); // Arêtes deductions.print_edges(graph_file,aff) ; // Noeuds deductions.print_UIP(graph_file,aff,root,literal) ; fprintf(graph_file, "\t%d [color = \"red\"];\n", literal); fprintf(graph_file, "}\n"); fclose(graph_file); } unsigned int cl_interact(const Deductions &deductions, const Affectation &aff, int last_bet, int literal, bool *with_proof) { char mode; unsigned int steps; assert(deductions.has_variable(abs(literal))); std::cout << "Conflict on literal " << literal << ". Action? [g/r/c/s/t] "; assert(with_proof); *with_proof = false; while (true) { std::cin >> mode; switch (mode) { case 'g': make_conflict_graph(deductions, aff, last_bet, literal); return 1; case 'r': if (!WITH_CL) { std::cout << "Clause learning is not enabled. Use -CL. [g/r/c/s/t]. " << std::endl; continue; } *with_proof = true; return 0; case 'c': return 1; case 's': std::cin >> steps; return steps; case 't': CL_INTERACT = false; return 0; default: std::cout << "Invalid character [g/r/c/s/t]. "; continue; } } } std::shared_ptr<Clause> learn_clause(const Deductions &deductions, const std::vector<std::pair<int, bool>> &mem, const Affectation &aff, int nb_variables, int literal, CLProof *proof) { (void) aff; long unsigned int mem_top = mem.size()-1; // The index in the memory “stack” of the literal we are making the resolution on. std::unordered_set<int> clause(deductions.get_deduced_from(literal)), clause2; assert(clause.find(literal) != clause.end()); mem_top--; while (mem.at(mem_top).second) { literal = mem.at(mem_top).first; assert(mem.at(mem_top).first == literal); clause2 = deductions.get_deduced_from(literal); // This is the clause we will make the resolution with if (!clause2.size()) break; if (clause.find(-literal) == clause.end()) break; assert(clause2.find(literal) != clause.end()); // Resolution // TODO: Replace 0 with the clause id. proof->insert_top(literal, std::make_pair(0, Clause(nb_variables, clause)), std::make_pair(0, Clause(nb_variables, clause2))); clause.erase(clause.find(-literal)); clause2.erase(clause2.find(literal)); clause.insert(clause2.begin(), clause2.end()); mem_top--; } return std::shared_ptr<Clause>(new Clause(nb_variables, clause)); } Affectation* satsolver::solve(Formula *formula) { int literal; bool with_proof; CLProof *proof; unsigned int clause_id; bool contains_false_clause; unsigned int skip_conflicts = 1; // Number of conflicts we will skip before showing another prompt int last_bet = 0; // Used for generating the graph. while(formula->get_aff()->get_nb_unknown() != 0 && !formula->only_true_clauses(NULL)) { formula->get_ded()->print() ; if(!WITH_WL && (literal = formula->monome(&clause_id))) { // We set the clause identified by “claused_id” as the one which // made us deduce the value of the literal. formula->deduce_true(literal, clause_id); // Return value ignored, WITH_WL is false contains_false_clause = formula->contains_false_clause(&clause_id); } else if((literal = formula->isolated_literal(&clause_id))) { formula->deduce_true(literal,-1) ; } else { literal = formula->choose_literal(HEURISTIC) ; if (WITH_WL) contains_false_clause = !formula->bet_true(literal); else { formula->bet_true(literal); contains_false_clause = formula->contains_false_clause(&clause_id); } last_bet = literal; } while(contains_false_clause) { if (CL_INTERACT && --skip_conflicts == 0) { assert(last_bet); skip_conflicts = cl_interact(*formula->get_ded(), formula->get_aff(), last_bet, literal, &with_proof); } if (WITH_CL) { proof = new CLProof(formula->to_clauses_vector()[clause_id]); learn_clause(*formula->get_ded(), formula->get_mem(), formula->get_aff(), formula->get_nb_variables(), literal, proof); if (with_proof) proof->to_latex_file(CL_PROOF_FILE_NAME); delete proof; } literal = formula->back() ; last_bet = -last_bet; if(literal == 0) throw Conflict() ; if (WITH_WL) contains_false_clause = !formula->deduce_false(literal,-1); else { formula->deduce_false(literal, -1); contains_false_clause = formula->contains_false_clause(&clause_id); } } } return formula->get_aff() ; }
#include <set> #include <map> #include <iostream> #include <cassert> #include <memory> #include <exception> #include <stdexcept> #include "structures/affectation.h" #include "structures/deductions.h" #include "structures/CL_proof.h" #include "structures/formula.h" #include "structures/clause.h" #include "solvers/dpll.h" #include "config.h" #define CONFLICT_GRAPH_FILE_NAME "/tmp/conflict_graph.dot" #define CL_PROOF_FILE_NAME "/tmp/CL_proof.tex" using namespace satsolver; #define AS_AFF(a, l) (a.is_true(l) ? l : -l) void make_conflict_graph(const Deductions &deductions, const Affectation &aff, int root, int literal) { FILE *graph_file = NULL; graph_file = fopen(CONFLICT_GRAPH_FILE_NAME, "w"); fprintf(graph_file, "digraph G {\n"); // Arêtes deductions.print_edges(graph_file,aff) ; // Noeuds deductions.print_UIP(graph_file,aff,root,literal) ; fprintf(graph_file, "\t%d [color = \"red\"];\n", literal); fprintf(graph_file, "}\n"); fclose(graph_file); } unsigned int cl_interact(const Deductions &deductions, const Affectation &aff, int last_bet, int literal, bool *with_proof) { char mode; unsigned int steps; assert(deductions.has_variable(abs(literal))); std::cout << "Conflict on literal " << literal << ". Action? [g/r/c/s/t] "; assert(with_proof); *with_proof = false; while (true) { std::cin >> mode; switch (mode) { case 'g': make_conflict_graph(deductions, aff, last_bet, literal); return 1; case 'r': if (!WITH_CL) { std::cout << "Clause learning is not enabled. Use -CL. [g/r/c/s/t]. " << std::endl; continue; } *with_proof = true; return 1; case 'c': return 1; case 's': std::cin >> steps; return steps; case 't': CL_INTERACT = false; return 0; default: std::cout << "Invalid character [g/r/c/s/t]. "; continue; } } } std::shared_ptr<Clause> learn_clause(const Deductions &deductions, const std::vector<std::pair<int, bool>> &mem, const Affectation &aff, int nb_variables, int literal, CLProof *proof) { (void) aff; long unsigned int mem_top = mem.size()-1; // The index in the memory “stack” of the literal we are making the resolution on. std::unordered_set<int> clause(deductions.get_deduced_from(literal)), clause2; assert(clause.find(literal) != clause.end()); mem_top--; while (mem.at(mem_top).second) { literal = mem.at(mem_top).first; assert(mem.at(mem_top).first == literal); clause2 = deductions.get_deduced_from(literal); // This is the clause we will make the resolution with if (!clause2.size()) break; if (clause.find(-literal) == clause.end()) break; assert(clause2.find(literal) != clause.end()); // Resolution // TODO: Replace 0 with the clause id. proof->insert_top(literal, std::make_pair(0, Clause(nb_variables, clause)), std::make_pair(0, Clause(nb_variables, clause2))); clause.erase(clause.find(-literal)); clause2.erase(clause2.find(literal)); clause.insert(clause2.begin(), clause2.end()); mem_top--; } return std::shared_ptr<Clause>(new Clause(nb_variables, clause)); } Affectation* satsolver::solve(Formula *formula) { int literal; bool with_proof; CLProof *proof; unsigned int clause_id; bool contains_false_clause; unsigned int skip_conflicts = 1; // Number of conflicts we will skip before showing another prompt int last_bet = 0; // Used for generating the graph. while(formula->get_aff()->get_nb_unknown() != 0 && !formula->only_true_clauses(NULL)) { formula->get_ded()->print() ; if(!WITH_WL && (literal = formula->monome(&clause_id))) { // We set the clause identified by “claused_id” as the one which // made us deduce the value of the literal. formula->deduce_true(literal, clause_id); // Return value ignored, WITH_WL is false contains_false_clause = formula->contains_false_clause(&clause_id); } else if((literal = formula->isolated_literal(&clause_id))) { formula->deduce_true(literal,-1) ; } else { literal = formula->choose_literal(HEURISTIC) ; if (WITH_WL) contains_false_clause = !formula->bet_true(literal); else { formula->bet_true(literal); contains_false_clause = formula->contains_false_clause(&clause_id); } last_bet = literal; } while(contains_false_clause) { if (CL_INTERACT && --skip_conflicts == 0) { assert(last_bet); skip_conflicts = cl_interact(*formula->get_ded(), formula->get_aff(), last_bet, literal, &with_proof); } if (WITH_CL) { proof = new CLProof(formula->to_clauses_vector()[clause_id]); learn_clause(*formula->get_ded(), formula->get_mem(), formula->get_aff(), formula->get_nb_variables(), literal, proof); if (with_proof) proof->to_latex_file(CL_PROOF_FILE_NAME); delete proof; } literal = formula->back() ; last_bet = -last_bet; if(literal == 0) throw Conflict() ; if (WITH_WL) contains_false_clause = !formula->deduce_false(literal,-1); else { formula->deduce_false(literal, -1); contains_false_clause = formula->contains_false_clause(&clause_id); } } } return formula->get_aff() ; }
Fix handling of 'r' in command-line interaction.
Fix handling of 'r' in command-line interaction.
C++
mit
Ezibenroc/satsolver,Ezibenroc/satsolver,Ezibenroc/satsolver,Ezibenroc/satsolver
462351f24c67c9233fb122cdc5c9fe8b72f9fd91
cmm_socket_passthrough.cpp
cmm_socket_passthrough.cpp
#include "cmm_socket.h" #include "cmm_socket.private.h" #include "debug.h" static void passthrough_debug_alert(const char *fn) { dbgprintf("Passthrough socket function called: %s\n", fn); } CMMSocketPassThrough::CMMSocketPassThrough(mc_socket_t sock_) { sock = sock_; } ssize_t CMMSocketPassThrough::mc_send(const void *buf, size_t len, int flags, u_long send_labels, resume_handler_t rh, void *arg) { passthrough_debug_alert("cmm_send"); return send(sock, buf, len, flags); } int CMMSocketPassThrough::mc_writev(const struct iovec *vec, int count, u_long send_labels, resume_handler_t rh, void *arg) { passthrough_debug_alert("cmm_writev"); return writev(sock, vec, count); } int CMMSocketPassThrough::mc_getpeername(struct sockaddr *address, socklen_t *address_len) { passthrough_debug_alert("cmm_getpeername"); return getpeername(sock, address, address_len); } int CMMSocketPassThrough::mc_recv(void *buf, size_t count, int flags, u_long *recv_labels) { passthrough_debug_alert("cmm_recv"); return recv(sock, buf, count, flags); } int CMMSocketPassThrough::mc_connect(const struct sockaddr *serv_addr, socklen_t addrlen_) { passthrough_debug_alert("cmm_connect"); return connect(sock, serv_addr, addrlen_); } int CMMSocketPassThrough::mc_getsockopt(int level, int optname, void *optval, socklen_t *optlen) { passthrough_debug_alert("cmm_getsockopt"); return getsockopt(sock, level, optname, optval, optlen); } int CMMSocketPassThrough::mc_setsockopt(int level, int optname, const void *optval, socklen_t optlen) { passthrough_debug_alert("cmm_setsockopt"); return setsockopt(sock, level, optname, optval, optlen); } int CMMSocketPassThrough::mc_shutdown(int how) { passthrough_debug_alert("cmm_shutdown"); return shutdown(sock, how); } irob_id_t CMMSocketPassThrough::mc_begin_irob(int numdeps, const irob_id_t *deps, u_long send_labels, resume_handler_t rh, void *rh_arg) { passthrough_debug_alert("cmm_begin_irob"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_end_irob(irob_id_t id) { passthrough_debug_alert("cmm_end_irob"); errno = EBADF; return -1; } ssize_t CMMSocketPassThrough::mc_irob_send(irob_id_t id, const void *buf, size_t len, int flags) { passthrough_debug_alert("cmm_irob_send"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_irob_writev(irob_id_t id, const struct iovec *vector, int count) { passthrough_debug_alert("cmm_irob_writev"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_get_failure_timeout(u_long label, struct timespec *ts) { passthrough_debug_alert("cmm_get_failure_timeout"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_set_failure_timeout(u_long label, const struct timespec *ts) { passthrough_debug_alert("cmm_set_failure_timeout"); errno = EBADF; return -1; }
#include "cmm_socket.h" #include "cmm_socket.private.h" #include "debug.h" static void passthrough_debug_alert(const char *fn) { dbgprintf("Passthrough socket function called: %s\n", fn); } CMMSocketPassThrough::CMMSocketPassThrough(mc_socket_t sock_) { sock = sock_; } ssize_t CMMSocketPassThrough::mc_send(const void *buf, size_t len, int flags, u_long send_labels, resume_handler_t rh, void *arg) { if (flags == 0) { passthrough_debug_alert("cmm_write"); return write(sock, buf, len); } else { passthrough_debug_alert("cmm_send"); return send(sock, buf, len, flags); } } int CMMSocketPassThrough::mc_writev(const struct iovec *vec, int count, u_long send_labels, resume_handler_t rh, void *arg) { passthrough_debug_alert("cmm_writev"); return writev(sock, vec, count); } int CMMSocketPassThrough::mc_getpeername(struct sockaddr *address, socklen_t *address_len) { passthrough_debug_alert("cmm_getpeername"); return getpeername(sock, address, address_len); } int CMMSocketPassThrough::mc_recv(void *buf, size_t count, int flags, u_long *recv_labels) { if (flags == 0) { passthrough_debug_alert("cmm_read"); return read(sock, buf, count); } else { passthrough_debug_alert("cmm_recv"); return recv(sock, buf, count, flags); } } int CMMSocketPassThrough::mc_connect(const struct sockaddr *serv_addr, socklen_t addrlen_) { passthrough_debug_alert("cmm_connect"); return connect(sock, serv_addr, addrlen_); } int CMMSocketPassThrough::mc_getsockopt(int level, int optname, void *optval, socklen_t *optlen) { passthrough_debug_alert("cmm_getsockopt"); return getsockopt(sock, level, optname, optval, optlen); } int CMMSocketPassThrough::mc_setsockopt(int level, int optname, const void *optval, socklen_t optlen) { passthrough_debug_alert("cmm_setsockopt"); return setsockopt(sock, level, optname, optval, optlen); } int CMMSocketPassThrough::mc_shutdown(int how) { passthrough_debug_alert("cmm_shutdown"); return shutdown(sock, how); } irob_id_t CMMSocketPassThrough::mc_begin_irob(int numdeps, const irob_id_t *deps, u_long send_labels, resume_handler_t rh, void *rh_arg) { passthrough_debug_alert("cmm_begin_irob"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_end_irob(irob_id_t id) { passthrough_debug_alert("cmm_end_irob"); errno = EBADF; return -1; } ssize_t CMMSocketPassThrough::mc_irob_send(irob_id_t id, const void *buf, size_t len, int flags) { passthrough_debug_alert("cmm_irob_send"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_irob_writev(irob_id_t id, const struct iovec *vector, int count) { passthrough_debug_alert("cmm_irob_writev"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_get_failure_timeout(u_long label, struct timespec *ts) { passthrough_debug_alert("cmm_get_failure_timeout"); errno = EBADF; return -1; } int CMMSocketPassThrough::mc_set_failure_timeout(u_long label, const struct timespec *ts) { passthrough_debug_alert("cmm_set_failure_timeout"); errno = EBADF; return -1; }
Make flags==0 recv/send default to read/write, just in case I call them on a non-socket.
Make flags==0 recv/send default to read/write, just in case I call them on a non-socket.
C++
bsd-2-clause
brettdh/libcmm,brettdh/libcmm,brettdh/libcmm,brettdh/libcmm,brettdh/libcmm
1fdc5a90e3bd5d5e93adfad4f4fd31141336574f
test/pybind11/pybind11_test_01.cpp
test/pybind11/pybind11_test_01.cpp
#include <mp++/extra/pybind11.hpp> #include <mp++/mp++.hpp> #include <string> #include <unordered_map> #include <vector> #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" #endif #include <pybind11/pybind11.h> #include <pybind11/stl.h> #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic pop #endif namespace py = pybind11; template <typename T> static inline std::vector<T> test_vector(const std::vector<T> &v) { return v; } template <typename T> static inline std::unordered_map<std::string, T> test_unordered_map(const std::unordered_map<std::string, T> &us) { return us; } PYBIND11_MODULE(pybind11_test_01, m) { mppp_pybind11::init(m); m.def("test_int1_conversion", [](const mppp::integer<1> &n) { return n; }); m.def("test_int2_conversion", [](const mppp::integer<2> &n) { return n; }); m.def("test_rat1_conversion", [](const mppp::rational<1> &q) { return q; }); m.def("test_rat2_conversion", [](const mppp::rational<2> &q) { return q; }); #if defined(MPPP_WITH_MPFR) m.def("test_real_conversion", [](const mppp::real &r) { return r; }); #endif #if defined(MPPP_WITH_QUADMATH) m.def("test_real128_conversion", [](const mppp::real128 &r) { return r; }); #endif m.def("test_vector_conversion", test_vector<mppp::integer<1>>); m.def("test_vector_conversion", test_vector<mppp::integer<2>>); m.def("test_vector_conversion", test_vector<mppp::rational<1>>); m.def("test_vector_conversion", test_vector<mppp::rational<2>>); #if defined(MPPP_WITH_QUADMATH) m.def("test_vector_conversion", test_vector<mppp::real128>); #endif #if defined(MPPP_WITH_MPFR) m.def("test_vector_conversion", test_vector<mppp::real>); #endif m.def("test_unordered_map_conversion", test_unordered_map<mppp::integer<1>>); m.def("test_unordered_map_conversion", test_unordered_map<mppp::integer<2>>); m.def("test_unordered_map_conversion", test_unordered_map<mppp::rational<1>>); m.def("test_unordered_map_conversion", test_unordered_map<mppp::rational<2>>); #if defined(MPPP_WITH_QUADMATH) m.def("test_unordered_map_conversion", test_unordered_map<mppp::real128>); #endif #if defined(MPPP_WITH_MPFR) m.def("test_unordered_map_conversion", test_unordered_map<mppp::real>); #endif }
#include <mp++/extra/pybind11.hpp> #include <mp++/mp++.hpp> #include <string> #include <unordered_map> #include <vector> #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" #endif #include <pybind11/pybind11.h> #include <pybind11/stl.h> #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic pop #endif namespace py = pybind11; template <typename T> static inline std::vector<T> test_vector(const std::vector<T> &v) { return v; } template <typename T> static inline std::unordered_map<std::string, T> test_unordered_map(const std::unordered_map<std::string, T> &us) { return us; } PYBIND11_MODULE(pybind11_test_01, m) { mppp_pybind11::init(m); m.def("has_quadmath", []() { #if defined(MPPP_WITH_QUADMATH) return true; #else return false; #endif }); m.def("has_mpfr", []() { #if defined(MPPP_WITH_MPFR) return true; #else return false; #endif }); m.def("test_int1_conversion", [](const mppp::integer<1> &n) { return n; }); m.def("test_int2_conversion", [](const mppp::integer<2> &n) { return n; }); m.def("test_rat1_conversion", [](const mppp::rational<1> &q) { return q; }); m.def("test_rat2_conversion", [](const mppp::rational<2> &q) { return q; }); #if defined(MPPP_WITH_MPFR) m.def("test_real_conversion", [](const mppp::real &r) { return r; }); m.def("test_real_conversion", [](const mppp::real &r, ::mpfr_prec_t prec) { return mppp::real{r, prec}; }); #endif #if defined(MPPP_WITH_QUADMATH) m.def("test_real128_conversion", [](const mppp::real128 &r) { return r; }); #endif m.def("test_overload", [](const mppp::integer<1> &n) { return n; }); m.def("test_overload", [](const mppp::rational<1> &q) { return q; }); #if defined(MPPP_WITH_QUADMATH) m.def("test_overload", [](const mppp::real128 &r) { return r; }); #endif #if defined(MPPP_WITH_MPFR) m.def("test_overload", [](const mppp::real &r) { return r; }); #endif m.def("test_vector_conversion", test_vector<mppp::integer<1>>); m.def("test_vector_conversion", test_vector<mppp::integer<2>>); m.def("test_vector_conversion", test_vector<mppp::rational<1>>); m.def("test_vector_conversion", test_vector<mppp::rational<2>>); #if defined(MPPP_WITH_QUADMATH) m.def("test_vector_conversion", test_vector<mppp::real128>); #endif #if defined(MPPP_WITH_MPFR) m.def("test_vector_conversion", test_vector<mppp::real>); #endif m.def("test_unordered_map_conversion", test_unordered_map<mppp::integer<1>>); m.def("test_unordered_map_conversion", test_unordered_map<mppp::integer<2>>); m.def("test_unordered_map_conversion", test_unordered_map<mppp::rational<1>>); m.def("test_unordered_map_conversion", test_unordered_map<mppp::rational<2>>); #if defined(MPPP_WITH_QUADMATH) m.def("test_unordered_map_conversion", test_unordered_map<mppp::real128>); #endif #if defined(MPPP_WITH_MPFR) m.def("test_unordered_map_conversion", test_unordered_map<mppp::real>); #endif }
Add a few more functions to the pybind11 testing module.
Add a few more functions to the pybind11 testing module.
C++
mpl-2.0
bluescarni/mppp,bluescarni/mppp,bluescarni/mppp
a6d1d14013b77c4df692c408d7075e7ebbfbf700
src/storm-replay.cpp
src/storm-replay.cpp
/*****************************************************************************/ /* storm-replay.cpp Copyright 2016 Justin J. Novack */ /*---------------------------------------------------------------------------*/ /* Common functions to interface with StormLib */ /*****************************************************************************/ #include <nan.h> #include <iostream> // NOLINT(readability/streams) #include <fstream> // NOLINT(readability/streams) #include "StormLib/src/StormLib.h" #include "StormLib/src/StormCommon.h" #include "StormLib/src/StormPort.h" // Extract a file from the archive void extractFile(const Nan::FunctionCallbackInfo<v8::Value> & args) { Nan::HandleScope scope; HANDLE hArchive = NULL; HANDLE hFile = NULL; // Open the Archive bool bArchive = SFileOpenArchive(*v8::String::Utf8Value(args[0]->ToString()), 0, 0, &hArchive); if (bArchive) { // Read the File bool bFile = SFileOpenFileEx(hArchive, *v8::String::Utf8Value(args[1]->ToString()), 0, &hFile); if (bFile) { // Capture the file char szBuffer[0x3FFFFF]; DWORD dwBytes = 1; v8::MaybeLocal<v8::Object> buffer; while (dwBytes > 0) { SFileReadFile(hFile, szBuffer, sizeof(szBuffer), &dwBytes, NULL); if (dwBytes > 0) { buffer = Nan::CopyBuffer(szBuffer, dwBytes); } } SFileCloseFile(hFile); if (!buffer.IsEmpty()) { args.GetReturnValue().Set(buffer.ToLocalChecked()); } else { args.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); } } else { args.GetReturnValue().Set(Nan::New<v8::Boolean>(bFile)); } } else { args.GetReturnValue().Set(Nan::New<v8::Boolean>(bArchive)); } } // Get the full header from archive void getHeader(const Nan::FunctionCallbackInfo<v8::Value> & args) { Nan::HandleScope scope; HANDLE hArchive = NULL; // Open the Archive bool bArchive = SFileOpenArchive(*v8::String::Utf8Value(args[0]->ToString()), 0, 0, &hArchive); if (bArchive) { // set up variables std::ifstream archive; // open the binary file archive.open(*v8::String::Utf8Value(args[0]->ToString()), std::ifstream::binary | std::ios::in); if (archive.is_open() == true) { // set up variables char * readBuffer; uint32_t userDataHeaderSize; // seek to the position of the size of the header archive.seekg(12); archive.read(reinterpret_cast<char *>(&userDataHeaderSize), sizeof(userDataHeaderSize)); // Get back to the beginning of the file. archive.seekg(0); // create a readBuffer for entire header readBuffer = new char[16 + userDataHeaderSize + 1]; // read entire header from the file archive.read(readBuffer, 16 + userDataHeaderSize); // append the null byte to terminate the string readBuffer[16 + userDataHeaderSize] = '\0'; // DEBUG // for (uint32_t i = 0; i < 16 + userDataHeaderSize; i++) { // printf("readBuffer[%d] is %X\n", i, static_cast<unsigned char>(readBuffer[i])); // } // Copy the readDuffer to a buffer that will be garbage collected by v8. v8::MaybeLocal<v8::Object> buffer = Nan::CopyBuffer(readBuffer, 16 + userDataHeaderSize); // Garbage cleanup. delete[] readBuffer; archive.close(); // Return buffer args.GetReturnValue().Set(buffer.ToLocalChecked()); return; } } // File was closed, return false args.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); } // Remove 'replay.message.events' from the archive void removeMessages(const Nan::FunctionCallbackInfo<v8::Value> & args) { // Allocate a new scope when we create v8 JavaScript objects. Nan::HandleScope scope; // Define variables HANDLE hArchive = NULL; DWORD ignored = 0; bool bRetVal; // Open the Archive bool bArchive = SFileOpenArchive(*v8::String::Utf8Value(args[0]->ToString()), 0, 0, &hArchive); if (bArchive) { // Remove the File SFileRemoveFile(hArchive, "replay.message.events", ignored); // Confirm if file has been removed. bRetVal = !SFileHasFile(hArchive, "replay.message.events"); // Close Archive SFileCloseArchive(hArchive); } else { bRetVal = bArchive; } args.GetReturnValue().Set(Nan::New<v8::Boolean>(bRetVal)); return; } void init(v8::Handle<v8::Object> exports) { Nan::Export(exports, "extractFile", extractFile); Nan::Export(exports, "getHeader", getHeader); Nan::Export(exports, "removeMessages", removeMessages); } NODE_MODULE(StormLib, init);
/*****************************************************************************/ /* storm-replay.cpp Copyright 2016 Justin J. Novack */ /*---------------------------------------------------------------------------*/ /* Common functions to interface with StormLib */ /*****************************************************************************/ #include <nan.h> #include <iostream> // NOLINT(readability/streams) #include <fstream> // NOLINT(readability/streams) #include "StormLib/src/StormLib.h" #include "StormLib/src/StormCommon.h" #include "StormLib/src/StormPort.h" // Extract a file from the archive void extractFile(const Nan::FunctionCallbackInfo<v8::Value> & args) { Nan::HandleScope scope; HANDLE hArchive = NULL; HANDLE hFile = NULL; // Open the Archive bool bArchive = SFileOpenArchive(*v8::String::Utf8Value(args[0]->ToString()), 0, 0, &hArchive); if (bArchive) { // Read the File bool bFile = SFileOpenFileEx(hArchive, *v8::String::Utf8Value(args[1]->ToString()), 0, &hFile); if (bFile) { // Capture the file char szBuffer[0x3FFFFF]; DWORD dwBytes = 1; v8::MaybeLocal<v8::Object> buffer; while (dwBytes > 0) { SFileReadFile(hFile, szBuffer, sizeof(szBuffer), &dwBytes, NULL); if (dwBytes > 0) { buffer = Nan::CopyBuffer(szBuffer, dwBytes); } } SFileCloseFile(hFile); if (!buffer.IsEmpty()) { args.GetReturnValue().Set(buffer.ToLocalChecked()); } else { args.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); } } else { args.GetReturnValue().Set(Nan::New<v8::Boolean>(bFile)); } } else { args.GetReturnValue().Set(Nan::New<v8::Boolean>(bArchive)); } } // Get the full header from archive void getHeader(const Nan::FunctionCallbackInfo<v8::Value> & args) { Nan::HandleScope scope; HANDLE hArchive = NULL; // Open the Archive bool bArchive = SFileOpenArchive(*v8::String::Utf8Value(args[0]->ToString()), 0, 0, &hArchive); if (bArchive) { // set up variables std::ifstream archive; // open the binary file archive.open(*v8::String::Utf8Value(args[0]->ToString()), std::ifstream::binary | std::ios::in); if (archive.is_open() == true) { // set up variables char * readBuffer; uint32_t userDataHeaderSize; // seek to the position of the size of the header archive.seekg(12); archive.read(reinterpret_cast<char *>(&userDataHeaderSize), sizeof(userDataHeaderSize)); // Get back to the beginning of the file. archive.seekg(0); // create a readBuffer for entire header readBuffer = new char[16 + userDataHeaderSize + 1]; // read entire header from the file archive.read(readBuffer, 16 + userDataHeaderSize); // append the null byte to terminate the string readBuffer[16 + userDataHeaderSize] = '\0'; // DEBUG // for (uint32_t i = 0; i < 16 + userDataHeaderSize; i++) { // printf("readBuffer[%d] is %X\n", i, static_cast<unsigned char>(readBuffer[i])); // } // Copy the readDuffer to a buffer that will be garbage collected by v8. v8::MaybeLocal<v8::Object> buffer = Nan::CopyBuffer(readBuffer, 16 + userDataHeaderSize); // Garbage cleanup. delete[] readBuffer; archive.close(); // Return buffer args.GetReturnValue().Set(buffer.ToLocalChecked()); return; } } // File was closed, return false args.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); } // Remove 'replay.message.events' from the archive void removeMessages(const Nan::FunctionCallbackInfo<v8::Value> & args) { // Allocate a new scope when we create v8 JavaScript objects. Nan::HandleScope scope; // Define variables HANDLE hArchive = NULL; DWORD ignored = 0; bool bRetVal; // Open the Archive bool bArchive = SFileOpenArchive(*v8::String::Utf8Value(args[0]->ToString()), 0, 0, &hArchive); if (bArchive) { // Remove the File SFileRemoveFile(hArchive, "replay.message.events", ignored); // Confirm if file has been removed. bRetVal = !SFileHasFile(hArchive, "replay.message.events"); // Close Archive SFileCloseArchive(hArchive); } else { bRetVal = bArchive; } args.GetReturnValue().Set(Nan::New<v8::Boolean>(bRetVal)); return; } void init(v8::Handle<v8::Object> exports) { Nan::Export(exports, "extractFile", extractFile); Nan::Export(exports, "getHeader", getHeader); Nan::Export(exports, "removeMessages", removeMessages); } NODE_MODULE(StormLib, init);
remove eol at eof
remove eol at eof
C++
mit
nydus/storm-replay,nydus/storm-replay,nydus/storm-replay
281b1089302a7fa4e7568bbf148f20912856b1f0
src/symbol_table.cpp
src/symbol_table.cpp
/* Project: TUC File: symbol_table.cpp Author: Leonardo Banderali Created: October 8, 2015 Last Modified: October 8, 2015 Description: TUC is a simple, experimental compiler designed for learning and experimenting. It is not intended to have any useful purpose other than being a way to learn how compilers work. Copyright (C) 2015 Leonardo Banderali License: 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 "symbol_table.hpp"
/* Project: TUC File: symbol_table.cpp Author: Leonardo Banderali Created: October 8, 2015 Last Modified: October 8, 2015 Description: TUC is a simple, experimental compiler designed for learning and experimenting. It is not intended to have any useful purpose other than being a way to learn how compilers work. Copyright (C) 2015 Leonardo Banderali License: 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 "symbol_table.hpp" //~class implementations~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tuc::Symbol::Symbol(SymbolType _type, std::string _value, int _argCount) : symbolType{_type}, symbolValue{_value}, argumentCount{_argCount} {} tuc::Symbol::SymbolType tuc::Symbol::type() const noexcept { return symbolType; } std::string tuc::Symbol::value() const noexcept { return symbolValue; } /* returns the number of arguments the entity can take */ int tuc::Symbol::arg_count() const noexcept { return argumentCount; }
Implement symbol type.
Implement symbol type.
C++
mit
Leonardo2718/tuc
69262d9eb435c8c043945a208c3ee4d2fc586b20
src/utils/daemon.cpp
src/utils/daemon.cpp
#include "daemon.h" #include <err.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> namespace clc { namespace utils { bool read_pidfile(const char* pid_path, pid_t* pid) { FILE* f; f = fopen(pid_path, "r"); if (f == NULL) return false; fscanf(f, "%d", pid); fclose(f); return true; } bool write_pidfile(const char* pid_path) { FILE* f; f = fopen(pid_path, "w"); if (f == NULL) return false; fprintf(f, "%d", getpid()); fclose(f); return true; } bool daemonize(const char* pid_path) { /* Double fork. */ pid_t ret; ret = fork(); if (ret == -1) { err(EXIT_FAILURE, "fork()"); } else if (ret > 0) { waitpid(ret, NULL, 0); return false; } ret = fork(); if (ret == -1) { err(EXIT_FAILURE, "fork()"); } else if (ret > 0) { exit(EXIT_SUCCESS); } /* Write PID. */ if (!write_pidfile(pid_path)) err(EXIT_FAILURE, "%s", pid_path); /* Change directory. */ if (chdir("/") == -1) warn("%s", "/"); /* Create new session ID. */ if (setsid() == -1) warn("setsid()"); /* Close standard streams. */ if (int fd = open("/dev/null", O_RDWR) > 0) for (int i = 0; i < 3; ++i) dup2(fd, i); return true; } }} // namespace clc::utils
#include "daemon.h" #include <err.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> namespace clc { namespace utils { bool read_pidfile(const char* pid_path, pid_t* pid) { FILE* f; f = fopen(pid_path, "r"); if (f == NULL) return false; fscanf(f, "%d", pid); fclose(f); return true; } bool write_pidfile(const char* pid_path) { FILE* f; f = fopen(pid_path, "w"); if (f == NULL) return false; fprintf(f, "%d", getpid()); fclose(f); return true; } bool daemonize(const char* pid_path) { /* Double fork. */ pid_t ret; ret = fork(); if (ret == -1) { err(EXIT_FAILURE, "fork()"); } else if (ret > 0) { waitpid(ret, NULL, 0); return false; } ret = fork(); if (ret == -1) { err(EXIT_FAILURE, "fork()"); } else if (ret > 0) { exit(EXIT_SUCCESS); } /* Write PID. */ if (!write_pidfile(pid_path)) err(EXIT_FAILURE, "%s", pid_path); /* Change directory. */ if (chdir("/") == -1) warn("%s", "/"); /* Create new session ID. */ if (setsid() == -1) warn("setsid()"); /* Close standard streams. */ int fd; if ((fd = open("/dev/null", O_RDWR)) >= 0) for (int i = 0; i < 3; ++i) dup2(fd, i); return true; } }} // namespace clc::utils
Fix a bug in daemonize().
Fix a bug in daemonize(). Our std stream closing was broken.
C++
bsd-3-clause
sas/clang-cache,sas/clang-cache
c54e83d8922833d921ed3c83225fd98d195847f3
distributions/rng.hpp
distributions/rng.hpp
// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2009 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef BOOM_DISTRIBUTIONS_RNG_HPP #define BOOM_DISTRIBUTIONS_RNG_HPP // #include <boost/random/ranlux.hpp> #include <random> namespace BOOM { // typedef boost::random::ranlux64_base_01 RNG; // A random number generator for simulating real valued U[0, 1) deviates. class RNG { public: // Seed with std::random_device. RNG(); // Seed with a specified value. explicit RNG(long seed); // Seed from a C++ standard random device, if one is present. void seed(); // Seed using a specified value. void seed(long seed) {generator_.seed(seed);} // Simulate a U[0, 1) random deviate. double operator()() {return dist_(generator_);} std::mt19937_64 & generator() {return generator_;} private: // TODO(steve): once you can use c++17 in R and elsewhere replace this with // a std::variant that will choose the fastest RNG for each implementation. std::mt19937_64 generator_; std::uniform_real_distribution<double> dist_; }; // The GlobalRng is a singleton. struct GlobalRng { public: static RNG rng; }; unsigned long seed_rng(); // generates a random seed from the global RNG // used to seed other RNG's unsigned long seed_rng(RNG &); } // namespace BOOM #endif // BOOM_DISTRIBUTIONS_RNG_HPP
// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2009 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef BOOM_DISTRIBUTIONS_RNG_HPP #define BOOM_DISTRIBUTIONS_RNG_HPP #include <random> namespace BOOM { // A random number generator for simulating real valued U[0, 1) deviates. class RNG { public: // Seed with std::random_device. RNG(); // Seed with a specified value. explicit RNG(long seed); // Seed from a C++ standard random device, if one is present. void seed(); // Seed using a specified value. void seed(long seed) {generator_.seed(seed);} // Simulate a U[0, 1) random deviate. double operator()() {return dist_(generator_);} std::mt19937_64 & generator() {return generator_;} private: // TODO(steve): once you can use c++17 in R and elsewhere replace this with // a std::variant that will choose the fastest RNG for each implementation. std::mt19937_64 generator_; std::uniform_real_distribution<double> dist_; }; // The GlobalRng is a singleton. struct GlobalRng { public: static RNG rng; }; unsigned long seed_rng(); // generates a random seed from the global RNG // used to seed other RNG's unsigned long seed_rng(RNG &); } // namespace BOOM #endif // BOOM_DISTRIBUTIONS_RNG_HPP
Remove commented out boost code.
Remove commented out boost code.
C++
lgpl-2.1
steve-the-bayesian/BOOM,steve-the-bayesian/BOOM,steve-the-bayesian/BOOM,steve-the-bayesian/BOOM,steve-the-bayesian/BOOM
195152b5bec8c4ee4cec525f9202508ae4092c15
src/view/surface.cpp
src/view/surface.cpp
#include <algorithm> extern "C" { #define static #include <wlr/render/wlr_renderer.h> #include <wlr/types/wlr_matrix.h> #include <wlr/types/wlr_buffer.h> #include <wlr/util/region.h> #undef static } #include "priv-view.hpp" #include "opengl.hpp" #include "core.hpp" #include "output.hpp" #include "debug.hpp" #include "signal-definitions.hpp" void handle_surface_committed(wl_listener*, void *data) { auto wlr_surf = (wlr_surface*) data; auto surface = wf_surface_from_void(wlr_surf->data); assert(surface); surface->commit(); } void handle_subsurface_created(wl_listener*, void *data) { auto sub = static_cast<wlr_subsurface*> (data); if (sub->surface->data) return; auto parent = wf_surface_from_void(sub->parent->data); if (!parent) { log_error("subsurface created with invalid parent!"); return; } auto it = std::find_if(parent->surface_children.begin(), parent->surface_children.end(), [=] (wayfire_surface_t *surface) { return surface->surface == sub->surface; }); if (it == parent->surface_children.end()) { auto surf = new wayfire_surface_t(parent); surf->map(sub->surface); } else { log_debug("adding same subsurface twice"); } } void handle_subsurface_destroyed(wl_listener*, void *data) { auto wlr_surf = (wlr_surface*) data; auto surface = wf_surface_from_void(wlr_surf->data); log_error ("subsurface destroyed %p", wlr_surf); surface->unmap(); surface->dec_keep_count(); } wayfire_surface_t::wayfire_surface_t(wayfire_surface_t* parent) { inc_keep_count(); this->parent_surface = parent; if (parent) { set_output(parent->output); parent->surface_children.push_back(this); } new_sub.notify = handle_subsurface_created; committed.notify = handle_surface_committed; destroy.notify = nullptr; } wayfire_surface_t::~wayfire_surface_t() { if (parent_surface) { auto it = parent_surface->surface_children.begin(); while(it != parent_surface->surface_children.end()) { if (*it == this) it = parent_surface->surface_children.erase(it); else ++it; } } for (auto c : surface_children) c->parent_surface = nullptr; } wayfire_surface_t *wayfire_surface_t::get_main_surface() { return this->parent_surface ? this->parent_surface->get_main_surface() : this; } bool wayfire_surface_t::is_subsurface() { return wlr_surface_is_subsurface(surface); } void wayfire_surface_t::get_child_position(int &x, int &y) { auto sub = wlr_subsurface_from_wlr_surface(surface); x = sub->current.x; y = sub->current.y; } void wayfire_surface_t::get_child_offset(int &x, int &y) { x = 0; y = 0; }; void wayfire_surface_t::send_frame_done(const timespec& time) { wlr_surface_send_frame_done(surface, &time); } bool wayfire_surface_t::accepts_input(int32_t sx, int32_t sy) { if (!surface) return false; return wlr_surface_point_accepts_input(surface, sx, sy); } wf_point wayfire_surface_t::get_output_position() { auto pos = parent_surface->get_output_position(); int dx, dy; get_child_position(dx, dy); pos.x += dx; pos.y += dy; return pos; } wf_geometry wayfire_surface_t::get_output_geometry() { if (!is_mapped()) return geometry; auto pos = get_output_position(); return { pos.x, pos.y, surface->current.width, surface->current.height }; } void emit_map_state_change(wayfire_surface_t *surface) { std::string state = surface->is_mapped() ? "_surface_mapped" : "_surface_unmapped"; wayfire_output *wo = surface->get_output(); if (!wo) return; _surface_map_state_changed_signal data; data.surface = surface; wo->emit_signal(state, &data); } void wayfire_surface_t::map(wlr_surface *surface) { assert(!this->surface && surface); this->surface = surface; /* force surface_send_enter() */ set_output(output); wl_signal_add(&surface->events.new_subsurface, &new_sub); wl_signal_add(&surface->events.commit, &committed); /* map by default if this is a subsurface, only toplevels/popups have map/unmap events */ if (wlr_surface_is_subsurface(surface)) { destroy.notify = handle_subsurface_destroyed; wl_signal_add(&surface->events.destroy, &destroy); } surface->data = this; damage(); wlr_subsurface *sub; wl_list_for_each(sub, &surface->subsurfaces, parent_link) handle_subsurface_created(NULL, sub); if (core->uses_csd.count(surface)) this->has_client_decoration = core->uses_csd[surface]; if (is_subsurface()) emit_map_state_change(this); } void wayfire_surface_t::unmap() { assert(this->surface); damage(); this->surface = nullptr; emit_map_state_change(this); wl_list_remove(&new_sub.link); wl_list_remove(&committed.link); if (destroy.notify) wl_list_remove(&destroy.link); } wlr_buffer* wayfire_surface_t::get_buffer() { if (surface && wlr_surface_has_buffer(surface)) return surface->buffer; return nullptr; } void wayfire_surface_t::inc_keep_count() { ++keep_count; } void wayfire_surface_t::dec_keep_count() { --keep_count; if (!keep_count) destruct(); } void wayfire_surface_t::damage(pixman_region32_t *region) { int n_rect; auto rects = pixman_region32_rectangles(region, &n_rect); for (int i = 0; i < n_rect; i++) damage(wlr_box_from_pixman_box(rects[i])); } void wayfire_surface_t::damage(const wlr_box& box) { if (parent_surface) parent_surface->damage(box); } void wayfire_surface_t::damage() { /* TODO: bounding box damage */ damage(geometry); } void wayfire_surface_t::update_output_position() { wf_geometry rect = get_output_geometry(); /* TODO: recursively damage children? */ if (is_subsurface() && rect != geometry) { damage(geometry); damage(rect); geometry = rect; } } void wayfire_surface_t::apply_surface_damage(int x, int y) { pixman_region32_t dmg; pixman_region32_init(&dmg); pixman_region32_copy(&dmg, &surface->buffer_damage); wl_output_transform transform = wlr_output_transform_invert(surface->current.transform); wlr_region_transform(&dmg, &dmg, transform, surface->current.buffer_width, surface->current.buffer_height); float scale = 1.0 / (float)surface->current.scale; wlr_region_scale(&dmg, &dmg, scale); if (surface->current.scale != 1 || surface->current.scale != output->handle->scale) wlr_region_expand(&dmg, &dmg, 1); pixman_region32_translate(&dmg, x, y); damage(&dmg); pixman_region32_fini(&dmg); } void wayfire_surface_t::commit() { update_output_position(); auto pos = get_output_position(); apply_surface_damage(pos.x, pos.y); } void wayfire_surface_t::set_output(wayfire_output *out) { if (output && surface) wlr_surface_send_leave(surface, output->handle); if (out && surface) wlr_surface_send_enter(surface, out->handle); output = out; for (auto c : surface_children) c->set_output(out); } void wayfire_surface_t::for_each_surface_recursive(wf_surface_iterator_callback call, int x, int y, bool reverse) { if (reverse) { if (is_mapped()) call(this, x, y); int dx, dy; for (auto c : surface_children) { if (!c->is_mapped()) continue; c->get_child_position(dx, dy); c->for_each_surface_recursive(call, x + dx, y + dy, reverse); } } else { auto it = surface_children.rbegin(); int dx, dy; while(it != surface_children.rend()) { auto& c = *it; if (c->is_mapped()) { c->get_child_position(dx, dy); c->for_each_surface_recursive(call, x + dx, y + dy, reverse); } ++it; } if (is_mapped()) call(this, x, y); } } void wayfire_surface_t::for_each_surface(wf_surface_iterator_callback call, bool reverse) { auto pos = get_output_position(); for_each_surface_recursive(call, pos.x, pos.y, reverse); } void wayfire_surface_t::_wlr_render_box(const wlr_fb_attribs& fb, int x, int y, const wlr_box& scissor) { if (!get_buffer()) return; wlr_box geometry {x, y, surface->current.width, surface->current.height}; geometry = get_output_box_from_box(geometry, output->handle->scale); float projection[9]; wlr_matrix_projection(projection, fb.width, fb.height, fb.transform); float matrix[9]; wlr_matrix_project_box(matrix, &geometry, surface->current.transform, 0, projection); wlr_renderer_begin(core->renderer, fb.width, fb.height); auto sbox = scissor; wlr_renderer_scissor(core->renderer, &sbox); wlr_render_texture_with_matrix(core->renderer, get_buffer()->texture, matrix, alpha); #ifdef WAYFIRE_GRAPHICS_DEBUG float scissor_proj[9]; wlr_matrix_projection(scissor_proj, fb.width, fb.height, WL_OUTPUT_TRANSFORM_NORMAL); float col[4] = {0, 0.2, 0, 0.5}; wlr_render_rect(core->renderer, &scissor, col, scissor_proj); #endif wlr_renderer_end(core->renderer); } void wayfire_surface_t::_render_pixman(const wlr_fb_attribs& fb, int x, int y, pixman_region32_t *damage) { int n_rect; auto rects = pixman_region32_rectangles(damage, &n_rect); for (int i = 0; i < n_rect; i++) { auto rect = wlr_box_from_pixman_box(rects[i]); auto box = get_scissor_box(output, rect); _wlr_render_box(fb, x, y, box); } } void wayfire_surface_t::render_pixman(const wlr_fb_attribs& fb, int x, int y, pixman_region32_t *damage) { if (damage) return _render_pixman(fb, x, y, damage); pixman_region32_t full_region; // auto box = get_output_box_from_box({x, y, geometry.width, geometry.height}, output->handle->scale); pixman_region32_init_rect(&full_region, 0, 0, fb.width, fb.height); _render_pixman(fb, x, y, &full_region); pixman_region32_fini(&full_region); } void wayfire_surface_t::render_fb(pixman_region32_t *damage, wf_framebuffer fb) { if (!is_mapped() || !wlr_surface_has_buffer(surface)) return; GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb.fb)); auto obox = get_output_geometry(); wlr_fb_attribs attribs; attribs.width = output->handle->width; attribs.height = output->handle->height; attribs.transform = output->handle->transform; render_pixman(attribs, obox.x - fb.geometry.x, obox.y - fb.geometry.y, damage); }
#include <algorithm> extern "C" { #define static #include <wlr/render/wlr_renderer.h> #include <wlr/types/wlr_matrix.h> #include <wlr/types/wlr_buffer.h> #include <wlr/util/region.h> #undef static } #include "priv-view.hpp" #include "opengl.hpp" #include "core.hpp" #include "output.hpp" #include "debug.hpp" #include "signal-definitions.hpp" void handle_surface_committed(wl_listener*, void *data) { auto wlr_surf = (wlr_surface*) data; auto surface = wf_surface_from_void(wlr_surf->data); assert(surface); surface->commit(); } void handle_subsurface_created(wl_listener*, void *data) { auto sub = static_cast<wlr_subsurface*> (data); if (sub->surface->data) return; auto parent = wf_surface_from_void(sub->parent->data); if (!parent) { log_error("subsurface created with invalid parent!"); return; } auto it = std::find_if(parent->surface_children.begin(), parent->surface_children.end(), [=] (wayfire_surface_t *surface) { return surface->surface == sub->surface; }); if (it == parent->surface_children.end()) { auto surf = new wayfire_surface_t(parent); surf->map(sub->surface); } else { log_debug("adding same subsurface twice"); } } void handle_subsurface_destroyed(wl_listener*, void *data) { auto wlr_surf = (wlr_surface*) data; auto surface = wf_surface_from_void(wlr_surf->data); log_error ("subsurface destroyed %p", wlr_surf); surface->unmap(); surface->dec_keep_count(); } wayfire_surface_t::wayfire_surface_t(wayfire_surface_t* parent) { inc_keep_count(); this->parent_surface = parent; if (parent) { set_output(parent->output); parent->surface_children.push_back(this); } new_sub.notify = handle_subsurface_created; committed.notify = handle_surface_committed; destroy.notify = nullptr; } wayfire_surface_t::~wayfire_surface_t() { if (parent_surface) { auto it = parent_surface->surface_children.begin(); while(it != parent_surface->surface_children.end()) { if (*it == this) it = parent_surface->surface_children.erase(it); else ++it; } } for (auto c : surface_children) c->parent_surface = nullptr; } wayfire_surface_t *wayfire_surface_t::get_main_surface() { return this->parent_surface ? this->parent_surface->get_main_surface() : this; } bool wayfire_surface_t::is_subsurface() { return wlr_surface_is_subsurface(surface); } void wayfire_surface_t::get_child_position(int &x, int &y) { auto sub = wlr_subsurface_from_wlr_surface(surface); x = sub->current.x; y = sub->current.y; } void wayfire_surface_t::get_child_offset(int &x, int &y) { x = 0; y = 0; }; void wayfire_surface_t::send_frame_done(const timespec& time) { wlr_surface_send_frame_done(surface, &time); } bool wayfire_surface_t::accepts_input(int32_t sx, int32_t sy) { if (!surface) return false; return wlr_surface_point_accepts_input(surface, sx, sy); } wf_point wayfire_surface_t::get_output_position() { auto pos = parent_surface->get_output_position(); int dx, dy; get_child_position(dx, dy); pos.x += dx; pos.y += dy; return pos; } wf_geometry wayfire_surface_t::get_output_geometry() { if (!is_mapped()) return geometry; auto pos = get_output_position(); return { pos.x, pos.y, surface->current.width, surface->current.height }; } void emit_map_state_change(wayfire_surface_t *surface) { std::string state = surface->is_mapped() ? "_surface_mapped" : "_surface_unmapped"; wayfire_output *wo = surface->get_output(); if (!wo) return; _surface_map_state_changed_signal data; data.surface = surface; wo->emit_signal(state, &data); } void wayfire_surface_t::map(wlr_surface *surface) { assert(!this->surface && surface); this->surface = surface; /* force surface_send_enter() */ set_output(output); wl_signal_add(&surface->events.new_subsurface, &new_sub); wl_signal_add(&surface->events.commit, &committed); /* map by default if this is a subsurface, only toplevels/popups have map/unmap events */ if (wlr_surface_is_subsurface(surface)) { destroy.notify = handle_subsurface_destroyed; wl_signal_add(&surface->events.destroy, &destroy); } surface->data = this; damage(); wlr_subsurface *sub; wl_list_for_each(sub, &surface->subsurfaces, parent_link) handle_subsurface_created(NULL, sub); if (core->uses_csd.count(surface)) this->has_client_decoration = core->uses_csd[surface]; if (is_subsurface()) emit_map_state_change(this); } void wayfire_surface_t::unmap() { assert(this->surface); damage(); this->surface = nullptr; emit_map_state_change(this); wl_list_remove(&new_sub.link); wl_list_remove(&committed.link); if (destroy.notify) wl_list_remove(&destroy.link); } wlr_buffer* wayfire_surface_t::get_buffer() { if (surface && wlr_surface_has_buffer(surface)) return surface->buffer; return nullptr; } void wayfire_surface_t::inc_keep_count() { ++keep_count; } void wayfire_surface_t::dec_keep_count() { --keep_count; if (!keep_count) destruct(); } void wayfire_surface_t::damage(pixman_region32_t *region) { int n_rect; auto rects = pixman_region32_rectangles(region, &n_rect); for (int i = 0; i < n_rect; i++) damage(wlr_box_from_pixman_box(rects[i])); } void wayfire_surface_t::damage(const wlr_box& box) { if (parent_surface) parent_surface->damage(box); } void wayfire_surface_t::damage() { /* TODO: bounding box damage */ damage(geometry); } void wayfire_surface_t::update_output_position() { wf_geometry rect = get_output_geometry(); /* TODO: recursively damage children? */ if (is_subsurface() && rect != geometry) { damage(geometry); damage(rect); geometry = rect; } } void wayfire_surface_t::apply_surface_damage(int x, int y) { if (!output || !is_mapped()) return; pixman_region32_t dmg; pixman_region32_init(&dmg); pixman_region32_copy(&dmg, &surface->buffer_damage); wl_output_transform transform = wlr_output_transform_invert(surface->current.transform); wlr_region_transform(&dmg, &dmg, transform, surface->current.buffer_width, surface->current.buffer_height); float scale = 1.0 / (float)surface->current.scale; wlr_region_scale(&dmg, &dmg, scale); if (surface->current.scale != 1 || surface->current.scale != output->handle->scale) wlr_region_expand(&dmg, &dmg, 1); pixman_region32_translate(&dmg, x, y); damage(&dmg); pixman_region32_fini(&dmg); } void wayfire_surface_t::commit() { update_output_position(); auto pos = get_output_position(); apply_surface_damage(pos.x, pos.y); } void wayfire_surface_t::set_output(wayfire_output *out) { if (output && surface) wlr_surface_send_leave(surface, output->handle); if (out && surface) wlr_surface_send_enter(surface, out->handle); output = out; for (auto c : surface_children) c->set_output(out); } void wayfire_surface_t::for_each_surface_recursive(wf_surface_iterator_callback call, int x, int y, bool reverse) { if (reverse) { if (is_mapped()) call(this, x, y); int dx, dy; for (auto c : surface_children) { if (!c->is_mapped()) continue; c->get_child_position(dx, dy); c->for_each_surface_recursive(call, x + dx, y + dy, reverse); } } else { auto it = surface_children.rbegin(); int dx, dy; while(it != surface_children.rend()) { auto& c = *it; if (c->is_mapped()) { c->get_child_position(dx, dy); c->for_each_surface_recursive(call, x + dx, y + dy, reverse); } ++it; } if (is_mapped()) call(this, x, y); } } void wayfire_surface_t::for_each_surface(wf_surface_iterator_callback call, bool reverse) { auto pos = get_output_position(); for_each_surface_recursive(call, pos.x, pos.y, reverse); } void wayfire_surface_t::_wlr_render_box(const wlr_fb_attribs& fb, int x, int y, const wlr_box& scissor) { if (!get_buffer()) return; wlr_box geometry {x, y, surface->current.width, surface->current.height}; geometry = get_output_box_from_box(geometry, output->handle->scale); float projection[9]; wlr_matrix_projection(projection, fb.width, fb.height, fb.transform); float matrix[9]; wlr_matrix_project_box(matrix, &geometry, surface->current.transform, 0, projection); wlr_renderer_begin(core->renderer, fb.width, fb.height); auto sbox = scissor; wlr_renderer_scissor(core->renderer, &sbox); wlr_render_texture_with_matrix(core->renderer, get_buffer()->texture, matrix, alpha); #ifdef WAYFIRE_GRAPHICS_DEBUG float scissor_proj[9]; wlr_matrix_projection(scissor_proj, fb.width, fb.height, WL_OUTPUT_TRANSFORM_NORMAL); float col[4] = {0, 0.2, 0, 0.5}; wlr_render_rect(core->renderer, &scissor, col, scissor_proj); #endif wlr_renderer_end(core->renderer); } void wayfire_surface_t::_render_pixman(const wlr_fb_attribs& fb, int x, int y, pixman_region32_t *damage) { int n_rect; auto rects = pixman_region32_rectangles(damage, &n_rect); for (int i = 0; i < n_rect; i++) { auto rect = wlr_box_from_pixman_box(rects[i]); auto box = get_scissor_box(output, rect); _wlr_render_box(fb, x, y, box); } } void wayfire_surface_t::render_pixman(const wlr_fb_attribs& fb, int x, int y, pixman_region32_t *damage) { if (damage) return _render_pixman(fb, x, y, damage); pixman_region32_t full_region; // auto box = get_output_box_from_box({x, y, geometry.width, geometry.height}, output->handle->scale); pixman_region32_init_rect(&full_region, 0, 0, fb.width, fb.height); _render_pixman(fb, x, y, &full_region); pixman_region32_fini(&full_region); } void wayfire_surface_t::render_fb(pixman_region32_t *damage, wf_framebuffer fb) { if (!is_mapped() || !wlr_surface_has_buffer(surface)) return; GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb.fb)); auto obox = get_output_geometry(); wlr_fb_attribs attribs; attribs.width = output->handle->width; attribs.height = output->handle->height; attribs.transform = output->handle->transform; render_pixman(attribs, obox.x - fb.geometry.x, obox.y - fb.geometry.y, damage); }
fix drag icons
fix drag icons Fixes #33
C++
mit
ammen99/wayfire,ammen99/wayfire
23a838f8337158df1c4f22aa1f260e330c8dd0ac
tests/src/main.cpp
tests/src/main.cpp
#include <QTest> #include "test-suite.h" #include "custom-network-access-manager.h" #include <iostream> int main(int argc, char *argv[]) { #ifdef HEADLESS QCoreApplication a(argc, argv); #else QGuiApplication a(argc, argv); #endif QMap<QString,int> results; int failed = 0; CustomNetworkAccessManager::TestMode = true; for (QObject *suite : TestSuite::suites) { int result = QTest::qExec(suite); results.insert(suite->metaObject()->className(), result); if (result != 0) { failed++; } } for (auto key : results.keys()) { std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl; } return failed; }
#include <QTest> #include "test-suite.h" #include "custom-network-access-manager.h" #include <iostream> int main(int argc, char *argv[]) { #ifdef HEADLESS QCoreApplication a(argc, argv); #else QGuiApplication a(argc, argv); #endif QStringList testSuites; for (int i = 1; i < argc; ++i) testSuites.append(argv[i]); QMap<QString,int> results; int failed = 0; CustomNetworkAccessManager::TestMode = true; for (QObject *suite : TestSuite::suites) { if (!testSuites.isEmpty() && !testSuites.contains(suite->metaObject()->className())) continue; int result = QTest::qExec(suite); results.insert(suite->metaObject()->className(), result); if (result != 0) { failed++; } } for (auto key : results.keys()) { std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl; } return failed; }
Allow to only run some test suites from the test runner
Allow to only run some test suites from the test runner
C++
apache-2.0
Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber
da842eabb2a6773f939eb099a3d3a41d16d94cac
src/was/was_glue.cxx
src/was/was_glue.cxx
/* * High level WAS client. * * author: Max Kellermann <[email protected]> */ #include "was_glue.hxx" #include "was_quark.h" #include "was_stock.hxx" #include "was_client.hxx" #include "http_response.hxx" #include "lease.hxx" #include "tcp_stock.hxx" #include "stock/GetHandler.hxx" #include "abort_close.hxx" #include "spawn/ChildOptions.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include "pool.hxx" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <assert.h> #include <sys/socket.h> #include <errno.h> #include <string.h> #include <unistd.h> struct WasRequest final : public StockGetHandler, Lease { struct pool &pool; StockMap &was_stock; const char *action; StockItem *stock_item; http_method_t method; const char *uri; const char *script_name; const char *path_info; const char *query_string; struct strmap *headers; Istream *body = nullptr; ConstBuffer<const char *> parameters; struct http_response_handler_ref handler; struct async_operation_ref *async_ref; WasRequest(struct pool &_pool, StockMap &_was_stock, const char *_action, http_method_t _method, const char *_uri, const char *_script_name, const char *_path_info, const char *_query_string, struct strmap *_headers, ConstBuffer<const char *> _parameters, const struct http_response_handler &_handler, void *_handler_ctx, struct async_operation_ref *_async_ref) :pool(_pool), was_stock(_was_stock), action(_action), method(_method), uri(_uri), script_name(_script_name), path_info(_path_info), query_string(_query_string), headers(_headers), parameters(_parameters), async_ref(_async_ref) { handler.Set(_handler, _handler_ctx); } struct async_operation_ref *SetBody(Istream *_body, struct async_operation_ref *_async_ref) { assert(body == nullptr); if (_body != nullptr) { body = istream_hold_new(pool, *_body); _async_ref = &async_close_on_abort(pool, *body, *_async_ref); } return _async_ref; } /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { was_stock_put(&was_stock, *stock_item, !reuse); } }; /* * stock callback * */ void WasRequest::OnStockItemReady(StockItem &item) { stock_item = &item; const auto &process = was_stock_item_get(item); was_client_request(&pool, process.control_fd, process.input_fd, process.output_fd, *this, method, uri, script_name, path_info, query_string, headers, body, parameters, handler.handler, handler.ctx, async_ref); } void WasRequest::OnStockItemError(GError *error) { handler.InvokeAbort(error); if (body != nullptr) body->CloseUnused(); } /* * constructor * */ void was_request(struct pool *pool, StockMap *was_stock, const ChildOptions &options, const char *action, const char *path, ConstBuffer<const char *> args, http_method_t method, const char *uri, const char *script_name, const char *path_info, const char *query_string, struct strmap *headers, Istream *body, ConstBuffer<const char *> parameters, const struct http_response_handler *handler, void *handler_ctx, struct async_operation_ref *async_ref) { if (action == nullptr) action = path; auto request = NewFromPool<WasRequest>(*pool, *pool, *was_stock, action, method, uri, script_name, path_info, query_string, headers, parameters, *handler, handler_ctx, async_ref); async_ref = request->SetBody(body, async_ref); was_stock_get(was_stock, pool, options, action, args, *request, *async_ref); }
/* * High level WAS client. * * author: Max Kellermann <[email protected]> */ #include "was_glue.hxx" #include "was_quark.h" #include "was_stock.hxx" #include "was_client.hxx" #include "http_response.hxx" #include "lease.hxx" #include "tcp_stock.hxx" #include "stock/GetHandler.hxx" #include "abort_close.hxx" #include "spawn/ChildOptions.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include "pool.hxx" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <assert.h> #include <sys/socket.h> #include <errno.h> #include <string.h> #include <unistd.h> class WasRequest final : public StockGetHandler, Lease { struct pool &pool; StockMap &was_stock; const char *action; StockItem *stock_item; http_method_t method; const char *uri; const char *script_name; const char *path_info; const char *query_string; struct strmap *headers; Istream *body = nullptr; ConstBuffer<const char *> parameters; struct http_response_handler_ref handler; struct async_operation_ref *async_ref; public: WasRequest(struct pool &_pool, StockMap &_was_stock, const char *_action, http_method_t _method, const char *_uri, const char *_script_name, const char *_path_info, const char *_query_string, struct strmap *_headers, ConstBuffer<const char *> _parameters, const struct http_response_handler &_handler, void *_handler_ctx, struct async_operation_ref *_async_ref) :pool(_pool), was_stock(_was_stock), action(_action), method(_method), uri(_uri), script_name(_script_name), path_info(_path_info), query_string(_query_string), headers(_headers), parameters(_parameters), async_ref(_async_ref) { handler.Set(_handler, _handler_ctx); } struct async_operation_ref *SetBody(Istream *_body, struct async_operation_ref *_async_ref) { assert(body == nullptr); if (_body != nullptr) { body = istream_hold_new(pool, *_body); _async_ref = &async_close_on_abort(pool, *body, *_async_ref); } return _async_ref; } /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; private: /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { was_stock_put(&was_stock, *stock_item, !reuse); } }; /* * stock callback * */ void WasRequest::OnStockItemReady(StockItem &item) { stock_item = &item; const auto &process = was_stock_item_get(item); was_client_request(&pool, process.control_fd, process.input_fd, process.output_fd, *this, method, uri, script_name, path_info, query_string, headers, body, parameters, handler.handler, handler.ctx, async_ref); } void WasRequest::OnStockItemError(GError *error) { handler.InvokeAbort(error); if (body != nullptr) body->CloseUnused(); } /* * constructor * */ void was_request(struct pool *pool, StockMap *was_stock, const ChildOptions &options, const char *action, const char *path, ConstBuffer<const char *> args, http_method_t method, const char *uri, const char *script_name, const char *path_info, const char *query_string, struct strmap *headers, Istream *body, ConstBuffer<const char *> parameters, const struct http_response_handler *handler, void *handler_ctx, struct async_operation_ref *async_ref) { if (action == nullptr) action = path; auto request = NewFromPool<WasRequest>(*pool, *pool, *was_stock, action, method, uri, script_name, path_info, query_string, headers, parameters, *handler, handler_ctx, async_ref); async_ref = request->SetBody(body, async_ref); was_stock_get(was_stock, pool, options, action, args, *request, *async_ref); }
convert struct to class
was/glue: convert struct to class
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
5d2e8e333eb30d38e636d329f03dda36a1189d9e
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/src/SSMTestApp.cpp
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/src/SSMTestApp.cpp
/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include <string> #include <stdio.h> #include <iostream> #include "SSMTestApp.h" using namespace std; SSMTestApp::SSMTestApp() { } void SSMTestApp::displayMenu() { printf("===============================================\n"); printf(" Iotivity Soft Sensor Manager Test Application \n"); printf("===============================================\n"); printf(" 1. Register Query \n"); printf(" 2. Unregister Query \n"); printf(" 3. Register DiscomfortIndexSensor sample query \n"); printf(" 4. Register IndoorTrajectorySensor sample query \n"); printf(" 9. exit \n"); printf("===============================================\n"); printf(" Please Enter the NO: "); } /* Register Query.*/ void SSMTestApp::registerQuery(std::string queryString) { int qid; SSMRESULT rtn = SSM_E_FAIL; if (queryString.size() == 0) { printf(" Please Enter query string: "); cin.ignore(); getline(cin, queryString); } rtn = RegisterQuery(queryString, this, qid); if (rtn == SSM_S_OK) { printf("The query has been registered!\n"); printf("QID : %d\n", qid); } else printf("Error occured(%d)\n", rtn); } /* unRegister Query.*/ void SSMTestApp::unregisterQuery(void) { std::string qid; SSMRESULT rtn = SSM_E_FAIL; printf(" Please Enter query Id: "); cin.ignore(); getline(cin, qid); rtn = UnregisterQuery(atoi(qid.c_str())); if (rtn == SSM_S_OK) printf("The query has been unregistered!\n"); else printf("Error occured(%d)\n", (int) rtn); } #define INPUT_EA 9 char input_name[INPUT_EA][10] = { "trackeeID", "timeT0", "ref01T0", "ref02T0", "ref03T0", "timeT1", "ref01T1", "ref02T1", "ref03T1" }; void SSMTestApp::TrajectoryDataOutput(IModelData *pModelData) { std::string name = ""; int l = 0; std::string trackeeID; std::string T0DateTime; std::string T0Ref01; std::string T0Ref02; std::string T0Ref03; std::string T1DateTime; std::string T1Ref01; std::string T1Ref02; std::string T1Ref03; for (int j = 0; j < pModelData->getPropertyCount(); j++) { name = pModelData->getPropertyName(j); for (l = 0; l < INPUT_EA; l++) { if (name.compare(input_name[l]) == 0) break; } switch (l) { case 0: trackeeID = pModelData->getPropertyValue(j); break; case 1: T0DateTime = pModelData->getPropertyValue(j); break; case 2: T0Ref01 = pModelData->getPropertyValue(j); break; case 3: T0Ref02 = pModelData->getPropertyValue(j); break; case 4: T0Ref03 = pModelData->getPropertyValue(j); break; case 5: T1DateTime = pModelData->getPropertyValue(j); break; case 6: T1Ref01 = pModelData->getPropertyValue(j); break; case 7: T1Ref02 = pModelData->getPropertyValue(j); break; case 8: T1Ref03 = pModelData->getPropertyValue(j); break; default: ; } } printf("===========================================\n"); printf(" ITS Trajectory Data Output \n"); printf("===========================================\n"); printf("\n"); printf(" < Trackee Thing ID : %s > \n", trackeeID.c_str()); printf(" - Trajectory 01 \n"); printf(" 0. Date, Time : %s \n", T0DateTime.c_str()); printf(" 1. Ref. Thing : %s \n", T0Ref01.c_str()); printf(" 2. Ref. Thing : %s \n", T0Ref02.c_str()); printf(" 3. Ref. Thing : %s \n", T0Ref03.c_str()); printf("\n"); printf(" - Trajectory 02 \n"); printf(" 0. Date, Time : %s \n", T1DateTime.c_str()); printf(" 1. Ref. Thing : %s \n", T1Ref01.c_str()); printf(" 2. Ref. Thing : %s \n", T1Ref02.c_str()); printf(" 3. Ref. Thing : %s \n", T1Ref03.c_str()); printf("\n"); printf("===========================================\n"); } /* APP. Level Callback Function for Observer of client. */ SSMRESULT SSMTestApp::onQueryEngineEvent(int cqid, IDataReader *pResult) { int dataCount = 0; IModelData *pModelData = NULL; std::vector<std::string> affectedModels; cout << "Event received! cqid = " << cqid << endl; pResult->getAffectedModels(&affectedModels); for (std::vector<std::string>::iterator itor = affectedModels.begin(); itor != affectedModels.end(); ++itor) { cout << "Printing " << *itor << " model" << endl; pResult->getModelDataCount(*itor, &dataCount); for (int i = 0; i < dataCount; i++) { pResult->getModelData(*itor, i, &pModelData); cout << "dataId: " << pModelData->getDataId() << endl; for (int j = 0; j < pModelData->getPropertyCount(); j++) { cout << "Type: " << pModelData->getPropertyName(j) << " Value: " << pModelData->getPropertyValue( j) << endl; } //TrajectoryDataOutput(pModelData); } } return SSM_S_OK; } /** * APP. Main Function. */ int main() { printf("program start.\n"); printf("searching SSMResource\n"); SSMTestApp *SSMApp = new SSMTestApp(); APPMenu::APPMenu menu = APPMenu::NONE; std::string strMenu; std::string xmlDescription = "<SSMCore>" "<Device>" "<UDN>abcde123-31f8-11b4-a222-08002b34c003</UDN>" "<Name>MyPC</Name>" "<Type>PC</Type>" "</Device>" "</SSMCore>"; if (InitializeSSM(xmlDescription) != SSM_S_OK) std::cout << "core init failed" << std::endl; while (menu != APPMenu::EXIT) { SSMApp->displayMenu(); getline(cin, strMenu); menu = (APPMenu::APPMenu) (atoi(strMenu.c_str())); switch (menu) { case APPMenu::REGISTER: std::cout << "register operate." << std::endl; SSMApp->registerQuery(""); break; case APPMenu::UNREGISTER: std::cout << "unregister operate." << std::endl; SSMApp->unregisterQuery(); break; case APPMenu::DISCOMFORT_SAMPLE: SSMApp->registerQuery("subscribe Device.DiscomfortIndexSensor "\ "if Device.DiscomfortIndexSensor.discomfortIndex > 0"); break; case APPMenu::ITS_SAMPLE: SSMApp->registerQuery("subscribe Device.IndoorTrajectorySensor "\ "if Device.IndoorTrajectorySensor.trackeeID == \"9059AF16FEF7\""); break; case APPMenu::EXIT: std::cout << "program exit." << std::endl; break; default: std::cout << "Not supported yet." << std::endl; } } // while TerminateSSM(); delete SSMApp; }
/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include <string> #include <stdio.h> #include <iostream> #include "SSMTestApp.h" using namespace std; SSMTestApp::SSMTestApp() { } void SSMTestApp::displayMenu() { printf("===============================================\n"); printf(" Iotivity Soft Sensor Manager Test Application \n"); printf("===============================================\n"); printf(" 1. Register Query \n"); printf(" 2. Unregister Query \n"); printf(" 3. Register DiscomfortIndexSensor sample query \n"); printf(" 4. Register IndoorTrajectorySensor sample query \n"); printf(" 9. exit \n"); printf("===============================================\n"); printf(" Please Enter the NO: "); } /* Register Query.*/ void SSMTestApp::registerQuery(std::string queryString) { int qid; SSMRESULT rtn = SSM_E_FAIL; if (queryString.size() == 0) { printf(" Please Enter query string: "); getline(cin, queryString); } rtn = RegisterQuery(queryString, this, qid); if (rtn == SSM_S_OK) { printf("The query has been registered!\n"); printf("QID : %d\n", qid); } else printf("Error occured(%d)\n", rtn); } /* unRegister Query.*/ void SSMTestApp::unregisterQuery(void) { std::string qid; SSMRESULT rtn = SSM_E_FAIL; printf(" Please Enter query Id: "); getline(cin, qid); rtn = UnregisterQuery(atoi(qid.c_str())); if (rtn == SSM_S_OK) printf("The query has been unregistered!\n"); else printf("Error occured(%d)\n", (int) rtn); } #define INPUT_EA 9 char input_name[INPUT_EA][10] = { "trackeeID", "timeT0", "ref01T0", "ref02T0", "ref03T0", "timeT1", "ref01T1", "ref02T1", "ref03T1" }; void SSMTestApp::TrajectoryDataOutput(IModelData *pModelData) { std::string name = ""; int l = 0; std::string trackeeID; std::string T0DateTime; std::string T0Ref01; std::string T0Ref02; std::string T0Ref03; std::string T1DateTime; std::string T1Ref01; std::string T1Ref02; std::string T1Ref03; for (int j = 0; j < pModelData->getPropertyCount(); j++) { name = pModelData->getPropertyName(j); for (l = 0; l < INPUT_EA; l++) { if (name.compare(input_name[l]) == 0) break; } switch (l) { case 0: trackeeID = pModelData->getPropertyValue(j); break; case 1: T0DateTime = pModelData->getPropertyValue(j); break; case 2: T0Ref01 = pModelData->getPropertyValue(j); break; case 3: T0Ref02 = pModelData->getPropertyValue(j); break; case 4: T0Ref03 = pModelData->getPropertyValue(j); break; case 5: T1DateTime = pModelData->getPropertyValue(j); break; case 6: T1Ref01 = pModelData->getPropertyValue(j); break; case 7: T1Ref02 = pModelData->getPropertyValue(j); break; case 8: T1Ref03 = pModelData->getPropertyValue(j); break; default: ; } } printf("===========================================\n"); printf(" ITS Trajectory Data Output \n"); printf("===========================================\n"); printf("\n"); printf(" < Trackee Thing ID : %s > \n", trackeeID.c_str()); printf(" - Trajectory 01 \n"); printf(" 0. Date, Time : %s \n", T0DateTime.c_str()); printf(" 1. Ref. Thing : %s \n", T0Ref01.c_str()); printf(" 2. Ref. Thing : %s \n", T0Ref02.c_str()); printf(" 3. Ref. Thing : %s \n", T0Ref03.c_str()); printf("\n"); printf(" - Trajectory 02 \n"); printf(" 0. Date, Time : %s \n", T1DateTime.c_str()); printf(" 1. Ref. Thing : %s \n", T1Ref01.c_str()); printf(" 2. Ref. Thing : %s \n", T1Ref02.c_str()); printf(" 3. Ref. Thing : %s \n", T1Ref03.c_str()); printf("\n"); printf("===========================================\n"); } /* APP. Level Callback Function for Observer of client. */ SSMRESULT SSMTestApp::onQueryEngineEvent(int cqid, IDataReader *pResult) { int dataCount = 0; IModelData *pModelData = NULL; std::vector<std::string> affectedModels; cout << "Event received! cqid = " << cqid << endl; pResult->getAffectedModels(&affectedModels); for (std::vector<std::string>::iterator itor = affectedModels.begin(); itor != affectedModels.end(); ++itor) { cout << "Printing " << *itor << " model" << endl; pResult->getModelDataCount(*itor, &dataCount); for (int i = 0; i < dataCount; i++) { pResult->getModelData(*itor, i, &pModelData); cout << "dataId: " << pModelData->getDataId() << endl; for (int j = 0; j < pModelData->getPropertyCount(); j++) { cout << "Type: " << pModelData->getPropertyName(j) << " Value: " << pModelData->getPropertyValue( j) << endl; } //TrajectoryDataOutput(pModelData); } } return SSM_S_OK; } /** * APP. Main Function. */ int main() { printf("program start.\n"); printf("searching SSMResource\n"); SSMTestApp *SSMApp = new SSMTestApp(); APPMenu::APPMenu menu = APPMenu::NONE; std::string strMenu; std::string xmlDescription = "<SSMCore>" "<Device>" "<UDN>abcde123-31f8-11b4-a222-08002b34c003</UDN>" "<Name>MyPC</Name>" "<Type>PC</Type>" "</Device>" "</SSMCore>"; if (InitializeSSM(xmlDescription) != SSM_S_OK) std::cout << "core init failed" << std::endl; while (menu != APPMenu::EXIT) { SSMApp->displayMenu(); getline(cin, strMenu); menu = (APPMenu::APPMenu) (atoi(strMenu.c_str())); switch (menu) { case APPMenu::REGISTER: std::cout << "register operate." << std::endl; SSMApp->registerQuery(""); break; case APPMenu::UNREGISTER: std::cout << "unregister operate." << std::endl; SSMApp->unregisterQuery(); break; case APPMenu::DISCOMFORT_SAMPLE: SSMApp->registerQuery("subscribe Device.DiscomfortIndexSensor "\ "if Device.DiscomfortIndexSensor.discomfortIndex > 0"); break; case APPMenu::ITS_SAMPLE: SSMApp->registerQuery("subscribe Device.IndoorTrajectorySensor "\ "if Device.IndoorTrajectorySensor.trackeeID == \"9059AF16FEF7\""); break; case APPMenu::EXIT: std::cout << "program exit." << std::endl; break; default: std::cout << "Not supported yet." << std::endl; } } // while TerminateSSM(); delete SSMApp; }
Fix console sample
[SSM] Fix console sample 1. Fix sample application while reading query string from console Change-Id: I90076ad0711ce165293a4db159e5796f1b7c93ee Signed-off-by: jk13 <[email protected]> Reviewed-on: https://gerrit.iotivity.org/gerrit/347 Tested-by: jenkins-iotivity <[email protected]> Reviewed-by: Uze Choi <[email protected]>
C++
apache-2.0
WojciechLuczkow/iotivity,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,tienfuc/iotivity-democlient-snap,iotivity/iotivity,WojciechLuczkow/iotivity,rzr/iotivity,WojciechLuczkow/iotivity,kartben/iotivity,rzr/iotivity,santais/iotivity_1.1,santais/iotivity_1.1.0,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1.0,santais/iotivity_1.1.0,kartben/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,santais/iotivity,kartben/iotivity,kartben/iotivity,kartben/iotivity,WojciechLuczkow/iotivity,WojciechLuczkow/iotivity,WojciechLuczkow/iotivity,santais/iotivity_1.1.0,WojciechLuczkow/iotivity,tienfuc/iotivity-democlient-snap,iotivity/iotivity,santais/iotivity_1.1.0,iotivity/iotivity,tienfuc/iotivity-democlient-snap,kartben/iotivity,santais/iotivity,tienfuc/iotivity-democlient-snap,iotivity/iotivity,santais/iotivity,WojciechLuczkow/iotivity,iotivity/iotivity,santais/iotivity_1.1.0,iotivity/iotivity,kartben/iotivity,rzr/iotivity,rzr/iotivity,iotivity/iotivity,tienfuc/iotivity-democlient-snap,iotivity/iotivity,santais/iotivity,santais/iotivity,rzr/iotivity,kartben/iotivity,santais/iotivity,rzr/iotivity,santais/iotivity,santais/iotivity_1.1,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1,santais/iotivity_1.1,santais/iotivity_1.1.0,santais/iotivity_1.1,rzr/iotivity
2aa6bd6afe1b32601dc1bbe1cffc0f354b959669
src/world/skybox.cpp
src/world/skybox.cpp
// skybox.cpp // Skybox info // Copyright 2015 Matthew Chandler // 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 "world/skybox.hpp" #define GLM_FORCE_RADIANS #include <glm/gtc/matrix_transform.hpp> #include "config.hpp" #include "opengl/gl_helpers.hpp" #include "util/logger.hpp" // TODO: replace bottom half of skybox with ground (if doing environment mapping) Skybox::Skybox(): _vbo(GL_ARRAY_BUFFER), _ebo(GL_ELEMENT_ARRAY_BUFFER), _tex(Texture_cubemap::create(check_in_pwd("img/bluecloud_lf.jpg"), check_in_pwd("img/bluecloud_rt.jpg"), check_in_pwd("img/bluecloud_bk.jpg"), check_in_pwd("img/bluecloud_ft.jpg"), check_in_pwd("img/bluecloud_dn.jpg"), check_in_pwd("img/bluecloud_up.jpg"))), _prog({std::make_pair("shaders/skybox.vert", GL_VERTEX_SHADER), std::make_pair("shaders/skybox.frag", GL_FRAGMENT_SHADER)}, {std::make_pair("vert_pos", 0)}) { Logger_locator::get()(Logger::DBG, "Creating skybox"); // TODO: a sphere might look better std::vector<glm::vec3> vert_pos = { glm::vec3(-1.0f, -1.0f, -1.0f), // 0 glm::vec3(1.0f, -1.0f, -1.0f), // 1 glm::vec3(-1.0f, -1.0f, 1.0f), // 2 glm::vec3(1.0f, -1.0f, 1.0f), // 3 glm::vec3(-1.0f, 1.0f, -1.0f), // 4 glm::vec3(1.0f, 1.0f, -1.0f), // 5 glm::vec3(-1.0f, 1.0f, 1.0f), // 6 glm::vec3(1.0f, 1.0f, 1.0f) // 7 }; std::vector<GLuint> index = { // front 0, 1, 5, 0, 5, 4, // right 1, 3, 7, 1, 7, 5, // back 3, 2, 6, 3, 6, 7, // left 2, 0, 4, 2, 4, 6, // top 4, 5, 7, 4, 7, 6, // bottom 2, 3, 1, 2, 1, 0 }; // create OpenGL vertex objects _vao.bind(); _vbo.bind(); glBufferData(_vbo.type(), sizeof(glm::vec3) * vert_pos.size(), vert_pos.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); _ebo.bind(); glBufferData(_ebo.type(), sizeof(GLuint) * index.size(), index.data(), GL_STATIC_DRAW); glBindVertexArray(0); _num_indexes = index.size(); _prog.use(); _prog.add_uniform("model_view_proj"); glUseProgram(0); // TODO get prev val check_error("Skybox::Skybox"); } void Skybox::draw(const Entity & cam, const glm::mat4 & proj) { glDepthFunc(GL_LEQUAL); _prog.use(); _tex->bind(); glm::mat4 model_view_proj = proj * glm::translate(cam.view_mat(), cam.pos()); glUniformMatrix4fv(_prog.get_uniform("model_view_proj"), 1, GL_FALSE, &model_view_proj[0][0]); glActiveTexture(GL_TEXTURE0); _vao.bind(); glDrawElements(GL_TRIANGLES, _num_indexes, GL_UNSIGNED_INT, (GLvoid *)0); glBindVertexArray(0); // get prev val? glUseProgram(0); // get prev val? check_error("Skybox::draw"); }
// skybox.cpp // Skybox info // Copyright 2015 Matthew Chandler // 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 "world/skybox.hpp" #define GLM_FORCE_RADIANS #include <glm/gtc/matrix_transform.hpp> #include "config.hpp" #include "opengl/gl_helpers.hpp" #include "util/logger.hpp" // TODO: replace bottom half of skybox with ground (if doing environment mapping) Skybox::Skybox(): _vbo(GL_ARRAY_BUFFER), _ebo(GL_ELEMENT_ARRAY_BUFFER), _tex(Texture_cubemap::create(check_in_pwd("img/bluecloud_lf.jpg"), check_in_pwd("img/bluecloud_rt.jpg"), check_in_pwd("img/bluecloud_bk.jpg"), check_in_pwd("img/bluecloud_ft.jpg"), check_in_pwd("img/bluecloud_dn.jpg"), check_in_pwd("img/bluecloud_up.jpg"))), _prog({std::make_pair("shaders/skybox.vert", GL_VERTEX_SHADER), std::make_pair("shaders/skybox.frag", GL_FRAGMENT_SHADER)}, {std::make_pair("vert_pos", 0)}) { Logger_locator::get()(Logger::DBG, "Creating skybox"); // TODO: a sphere might look better std::vector<glm::vec3> vert_pos = { glm::vec3(-1.0f, -1.0f, -1.0f), // 0 glm::vec3(1.0f, -1.0f, -1.0f), // 1 glm::vec3(-1.0f, -1.0f, 1.0f), // 2 glm::vec3(1.0f, -1.0f, 1.0f), // 3 glm::vec3(-1.0f, 1.0f, -1.0f), // 4 glm::vec3(1.0f, 1.0f, -1.0f), // 5 glm::vec3(-1.0f, 1.0f, 1.0f), // 6 glm::vec3(1.0f, 1.0f, 1.0f) // 7 }; std::vector<GLuint> index = { // front 0, 1, 5, 0, 5, 4, // right 1, 3, 7, 1, 7, 5, // back 3, 2, 6, 3, 6, 7, // left 2, 0, 4, 2, 4, 6, // top 4, 5, 7, 4, 7, 6, // bottom 2, 3, 1, 2, 1, 0 }; // create OpenGL vertex objects _vao.bind(); _vbo.bind(); glBufferData(_vbo.type(), sizeof(glm::vec3) * vert_pos.size(), vert_pos.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); _ebo.bind(); glBufferData(_ebo.type(), sizeof(GLuint) * index.size(), index.data(), GL_STATIC_DRAW); glBindVertexArray(0); _num_indexes = index.size(); _prog.use(); _prog.add_uniform("model_view_proj"); glUseProgram(0); // TODO get prev val check_error("Skybox::Skybox"); } void Skybox::draw(const Entity & cam, const glm::mat4 & proj) { glDepthFunc(GL_LEQUAL); _prog.use(); glActiveTexture(GL_TEXTURE0); _tex->bind(); glm::mat4 model_view_proj = proj * glm::translate(cam.view_mat(), cam.pos()); glUniformMatrix4fv(_prog.get_uniform("model_view_proj"), 1, GL_FALSE, &model_view_proj[0][0]); _vao.bind(); glDrawElements(GL_TRIANGLES, _num_indexes, GL_UNSIGNED_INT, (GLvoid *)0); glBindVertexArray(0); // get prev val? glUseProgram(0); // get prev val? check_error("Skybox::draw"); }
fix skybox texture binding
fix skybox texture binding
C++
mit
mattvchandler/mazerun
73fb136e9ab1c4e2250fcf088ee9b2c5a5160ac3
src/xpiks-qt/Models/logsmodel.cpp
src/xpiks-qt/Models/logsmodel.cpp
/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2016 Taras Kushnir <[email protected]> * * Xpiks is distributed under the GNU General Public License, version 3.0 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "logsmodel.h" #include "../Helpers/loggingworker.h" #include <QThread> #include <QString> #include <QFile> #include <QDir> #include <QDateTime> #include <QTextStream> #include <QStandardPaths> #include "../Helpers/stringhelper.h" #include "../Helpers/logger.h" #include "../Helpers/loghighlighter.h" #include "../Common/defines.h" namespace Models { LogsModel::LogsModel(QMLExtensions::ColorsModel *colorsModel, QObject *parent) : QObject(parent), m_LoggingWorker(new Helpers::LoggingWorker()), m_ColorsModel(colorsModel) { #ifdef WITH_LOGS m_WithLogs = true; #else m_WithLogs = false; #endif } LogsModel::~LogsModel() { } void LogsModel::startLogging() { QThread *loggingThread = new QThread(); m_LoggingWorker->moveToThread(loggingThread); QObject::connect(loggingThread, SIGNAL(started()), m_LoggingWorker, SLOT(process())); QObject::connect(m_LoggingWorker, SIGNAL(stopped()), loggingThread, SLOT(quit())); QObject::connect(m_LoggingWorker, SIGNAL(stopped()), m_LoggingWorker, SLOT(deleteLater())); QObject::connect(loggingThread, SIGNAL(finished()), loggingThread, SLOT(deleteLater())); loggingThread->start(); } void LogsModel::stopLogging() { m_LoggingWorker->cancel(); } QString LogsModel::getAllLogsText(bool moreLogs) { QString result; #ifdef WITH_LOGS Helpers::Logger &logger = Helpers::Logger::getInstance(); QString logFilePath = logger.getLogFilePath(); QFile f(logFilePath); if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { // 1000 - do not load the UI // advanced users will open logs it notepad int numberOfLines = moreLogs ? 1000 : 100; QString text = f.readAll(); result = Helpers::getLastNLines(text, numberOfLines); f.close(); } #else Q_UNUSED(moreLogs); result = QString::fromLatin1("Logs are not available in this version"); #endif return result; } void LogsModel::initLogHighlighting(QQuickTextDocument *document) { Helpers::LogHighlighter *highlighter = new Helpers::LogHighlighter(m_ColorsModel, document->textDocument()); Q_UNUSED(highlighter); } }
/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2016 Taras Kushnir <[email protected]> * * Xpiks is distributed under the GNU General Public License, version 3.0 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "logsmodel.h" #include "../Helpers/loggingworker.h" #include <QThread> #include <QString> #include <QFile> #include <QDir> #include <QDateTime> #include <QTextStream> #include <QStandardPaths> #include "../Helpers/stringhelper.h" #include "../Helpers/logger.h" #include "../Helpers/loghighlighter.h" #include "../Common/defines.h" namespace Models { LogsModel::LogsModel(QMLExtensions::ColorsModel *colorsModel, QObject *parent) : QObject(parent), m_LoggingWorker(new Helpers::LoggingWorker()), m_ColorsModel(colorsModel) { #ifdef WITH_LOGS m_WithLogs = true; #else m_WithLogs = false; #endif } LogsModel::~LogsModel() { } void LogsModel::startLogging() { QThread *loggingThread = new QThread(); m_LoggingWorker->moveToThread(loggingThread); QObject::connect(loggingThread, SIGNAL(started()), m_LoggingWorker, SLOT(process())); QObject::connect(m_LoggingWorker, SIGNAL(stopped()), loggingThread, SLOT(quit())); QObject::connect(m_LoggingWorker, SIGNAL(stopped()), m_LoggingWorker, SLOT(deleteLater())); QObject::connect(loggingThread, SIGNAL(finished()), loggingThread, SLOT(deleteLater())); loggingThread->start(); } void LogsModel::stopLogging() { m_LoggingWorker->cancel(); } QString LogsModel::getAllLogsText(bool moreLogs) { QString result; #ifdef WITH_LOGS Helpers::Logger &logger = Helpers::Logger::getInstance(); QString logFilePath = logger.getLogFilePath(); QFile f(logFilePath); if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { // 1000 - do not load the UI // advanced users will open logs it notepad int numberOfLines = moreLogs ? 1000 : 100; QString text = QString::fromUtf8(f.readAll()); result = Helpers::getLastNLines(text, numberOfLines); f.close(); } #else Q_UNUSED(moreLogs); result = QString::fromLatin1("Logs are not available in this version"); #endif return result; } void LogsModel::initLogHighlighting(QQuickTextDocument *document) { Helpers::LogHighlighter *highlighter = new Helpers::LogHighlighter(m_ColorsModel, document->textDocument()); Q_UNUSED(highlighter); } }
Fix for tests
Fix for tests
C++
mpl-2.0
Artiom-M/xpiks,Ribtoks/xpiks,Artiom-M/xpiks,Ribtoks/xpiks,Ribtoks/xpiks,Artiom-M/xpiks,Artiom-M/xpiks,Ribtoks/xpiks
3d6c476e7437cd971ddb546837b7418582241db2
stateplex/core/receiversource.cpp
stateplex/core/receiversource.cpp
/* * Stateplex - A server-side actor model library. * * core/upstreamsource.cpp * * (c) 2013 Henrik Hedberg <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Authors: Henrik Hedberg */ #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include "receiversource.h" #include "writebuffer.h" namespace Stateplex { void ReceiverSource::handleReady(bool readyToRead, bool readyToWrite) { if (readyToRead) { WriteBuffer buffer(actor()); buffer.ensurePushLength(buffer.blockSize()); ssize_t size = ::read(fd(), buffer.pushPointer(), buffer.pushLength()); if (size == -1) { if (errno != EAGAIN && errno != EWOULDBLOCK) { perror("read"); abort(); } } else if (size == 0) { mReadEof = true; mReceiver->receiveEnd(); } else { buffer.pushed(size); mReceiver->receive(&buffer); // TODO: If receive() returns false, do not read any more } } if (readyToWrite && mWriteBuffer) { } } void ReceiverSource::receiveEnd() { mWriteEof = true; } bool ReceiverSource::receive(const char *data, Size length) { if (mWriteEof) return false; if (mWriteBuffer) { mWriteBuffer->append(data, length); return true; } while (1) { ssize_t size = ::write(fd(), data, length); if (size == (ssize_t)length) return true; if (size == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } else if (errno == ECONNRESET) { mWriteEof = true; return false; } else { perror("read"); abort(); } } data += size; length -= size; }; mWriteBuffer = new WriteBuffer(actor()); mWriteBuffer->append(data, length); return true; } bool ReceiverSource::receive(const String *string) { return receive(string->chars(), string->length()); } bool ReceiverSource::receive(Buffer *buffer) { if (mWriteBuffer) { mWriteBuffer->append(buffer); return true; } Buffer::Iterator iterator(buffer); Size length; while ((length = iterator.charBlockLength()) > 0) { if (!receive(iterator.charBlock(), length)) return false; iterator.advance(length); } return true; } }
/* * Stateplex - A server-side actor model library. * * core/upstreamsource.cpp * * (c) 2013 Henrik Hedberg <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Authors: Henrik Hedberg */ #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include "receiversource.h" #include "writebuffer.h" namespace Stateplex { void ReceiverSource::handleReady(bool readyToRead, bool readyToWrite) { if (readyToRead) { WriteBuffer buffer(actor()); buffer.ensurePushLength(buffer.blockSize()); ssize_t size = ::read(fd(), buffer.pushPointer(), buffer.pushLength()); if (size == -1) { if (errno == ECONNRESET) { mReadEof = true; mWriteEof = true; // TODO: Clear mWriteBuffer mReceiver->receiveEnd(); } else if (errno != EAGAIN && errno != EWOULDBLOCK) { perror("read"); abort(); } } else if (size == 0) { mReadEof = true; mReceiver->receiveEnd(); } else { buffer.pushed(size); mReceiver->receive(&buffer); // TODO: If receive() returns false, do not read any more } } if (readyToWrite && mWriteBuffer) { } } void ReceiverSource::receiveEnd() { mWriteEof = true; } bool ReceiverSource::receive(const char *data, Size length) { if (mWriteEof) return false; if (mWriteBuffer) { mWriteBuffer->append(data, length); return true; } while (1) { ssize_t size = ::write(fd(), data, length); if (size == (ssize_t)length) return true; if (size == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } else if (errno == ECONNRESET) { mWriteEof = true; return false; } else { perror("read"); abort(); } } data += size; length -= size; }; mWriteBuffer = new WriteBuffer(actor()); mWriteBuffer->append(data, length); return true; } bool ReceiverSource::receive(const String *string) { return receive(string->chars(), string->length()); } bool ReceiverSource::receive(Buffer *buffer) { if (mWriteBuffer) { mWriteBuffer->append(buffer); return true; } Buffer::Iterator iterator(buffer); Size length; while ((length = iterator.charBlockLength()) > 0) { if (!receive(iterator.charBlock(), length)) return false; iterator.advance(length); } return true; } }
handle Connection reset by peer error in read
ReceiverSource: handle Connection reset by peer error in read
C++
lgpl-2.1
hhedberg/stateplex,hhedberg/stateplex
fa47a419d856cf187be6cb6d97fd98087694b2b6
chrome/browser/views/tab_contents/native_tab_contents_container_gtk.cc
chrome/browser/views/tab_contents/native_tab_contents_container_gtk.cc
// Copyright (c) 2009 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/native_tab_contents_container_gtk.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/tab_contents/interstitial_page.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/tab_contents/tab_contents_container.h" #include "views/focus/focus_manager.h" #include "views/widget/root_view.h" #include "views/widget/widget.h" //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerGtk, public: NativeTabContentsContainerGtk::NativeTabContentsContainerGtk( TabContentsContainer* container) : container_(container) { } NativeTabContentsContainerGtk::~NativeTabContentsContainerGtk() { } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerGtk, NativeTabContentsContainer overrides: void NativeTabContentsContainerGtk::AttachContents(TabContents* contents) { // We need to register the tab contents window with the BrowserContainer so // that the BrowserContainer is the focused view when the focus is on the // TabContents window (for the TabContents case). set_focus_view(this); Attach(contents->GetNativeView()); // TODO(port): figure out focus interception #if defined(OS_WIN) HWND contents_hwnd = contents->GetContentNativeView(); if (contents_hwnd) views::FocusManager::InstallFocusSubclass(contents_hwnd, this); #else NOTIMPLEMENTED(); #endif } void NativeTabContentsContainerGtk::DetachContents(TabContents* contents) { // TODO(port): figure out focus interception #if defined(OS_WIN) // TODO(brettw) should this move to NativeViewHost::Detach which is called below? // It needs cleanup regardless. HWND container_hwnd = contents->GetNativeView(); // Hide the contents before adjusting its parent to avoid a full desktop // flicker. ShowWindow(container_hwnd, SW_HIDE); // Reset the parent to NULL to ensure hidden tabs don't receive messages. ::SetParent(container_hwnd, NULL); // Unregister the tab contents window from the FocusManager. views::FocusManager::UninstallFocusSubclass(container_hwnd); HWND hwnd = contents->GetContentNativeView(); if (hwnd) { // We may not have an HWND anymore, if the renderer crashed and we are // displaying the sad tab for example. views::FocusManager::UninstallFocusSubclass(hwnd); } #else gtk_widget_hide(contents->GetNativeView()); #endif // Now detach the TabContents. Detach(); } void NativeTabContentsContainerGtk::SetFastResize(bool fast_resize) { set_fast_resize(fast_resize); } void NativeTabContentsContainerGtk::RenderViewHostChanged( RenderViewHost* old_host, RenderViewHost* new_host) { // TODO(port): figure out focus interception #if defined(OS_WIN) if (old_host && old_host->view()) { views::FocusManager::UninstallFocusSubclass( old_host->view()->GetNativeView()); } if (new_host && new_host->view()) { views::FocusManager::InstallFocusSubclass( new_host->view()->GetNativeView(), this); } // If we are focused, we need to pass the focus to the new RenderViewHost. views::FocusManager* focus_manager = views::FocusManager::GetFocusManager( GetRootView()->GetWidget()->GetNativeView()); if (focus_manager->GetFocusedView() == this) Focus(); #else // If we are focused, we need to pass the focus to the new RenderViewHost. // TODO: uncomment this once FocusManager has been ported. // views::FocusManager* focus_manager = views::FocusManager::GetFocusManager( // GetRootView()->GetWidget()->GetNativeView()); // if (focus_manager->GetFocusedView() == this) // Focus(); #endif } views::View* NativeTabContentsContainerGtk::GetView() { return this; } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerGtk, views::View overrides: bool NativeTabContentsContainerGtk::SkipDefaultKeyEventProcessing( const views::KeyEvent& e) { // Don't look-up accelerators or tab-traverse if we are showing a non-crashed // TabContents. // We'll first give the page a chance to process the key events. If it does // not process them, they'll be returned to us and we'll treat them as // accelerators then. return container_->tab_contents() && !container_->tab_contents()->is_crashed(); } views::FocusTraversable* NativeTabContentsContainerGtk::GetFocusTraversable() { return NULL; } bool NativeTabContentsContainerGtk::IsFocusable() const { // We need to be focusable when our contents is not a view hierarchy, as // clicking on the contents needs to focus us. return container_->tab_contents() != NULL; } void NativeTabContentsContainerGtk::Focus() { if (container_->tab_contents()) { // Set the native focus on the actual content of the tab, that is the // interstitial if one is showing. if (container_->tab_contents()->interstitial_page()) { container_->tab_contents()->interstitial_page()->Focus(); return; } gtk_widget_grab_focus(container_->tab_contents()->GetContentNativeView()); } } void NativeTabContentsContainerGtk::RequestFocus() { // This is a hack to circumvent the fact that a view does not explicitly get // a call to set the focus if it already has the focus. This causes a problem // with tabs such as the TabContents that instruct the RenderView that it got // focus when they actually get the focus. When switching from one TabContents // tab that has focus to another TabContents tab that had focus, since the // TabContentsContainerView already has focus, Focus() would not be called and // the RenderView would not get notified it got focused. // By clearing the focused view before-hand, we ensure Focus() will be called. GetRootView()->FocusView(NULL); View::RequestFocus(); } void NativeTabContentsContainerGtk::AboutToRequestFocusFromTabTraversal( bool reverse) { if (!container_->tab_contents()) return; // Give an opportunity to the tab to reset its focus. if (container_->tab_contents()->interstitial_page()) { container_->tab_contents()->interstitial_page()->SetInitialFocus(reverse); return; } container_->tab_contents()->SetInitialFocus(reverse); } bool NativeTabContentsContainerGtk::GetAccessibleRole( AccessibilityTypes::Role* role) { // TODO(port): figure out a11y #if defined(OS_WIN) DCHECK(role); *role = AccessibilityTypes::ROLE_GROUPING; #endif return true; } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainer, public: // static NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer( TabContentsContainer* container) { return new NativeTabContentsContainerGtk(container); }
// Copyright (c) 2009 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/native_tab_contents_container_gtk.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/tab_contents/interstitial_page.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/tab_contents/tab_contents_container.h" #include "views/focus/focus_manager.h" #include "views/widget/root_view.h" #include "views/widget/widget.h" //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerGtk, public: NativeTabContentsContainerGtk::NativeTabContentsContainerGtk( TabContentsContainer* container) : container_(container) { } NativeTabContentsContainerGtk::~NativeTabContentsContainerGtk() { } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerGtk, NativeTabContentsContainer overrides: void NativeTabContentsContainerGtk::AttachContents(TabContents* contents) { // We need to register the tab contents window with the BrowserContainer so // that the BrowserContainer is the focused view when the focus is on the // TabContents window (for the TabContents case). set_focus_view(this); Attach(contents->GetNativeView()); // TODO(port): figure out focus interception #if defined(OS_WIN) HWND contents_hwnd = contents->GetContentNativeView(); if (contents_hwnd) views::FocusManager::InstallFocusSubclass(contents_hwnd, this); #else NOTIMPLEMENTED(); #endif } void NativeTabContentsContainerGtk::DetachContents(TabContents* contents) { // TODO(port): figure out focus interception #if defined(OS_WIN) // TODO(brettw) should this move to NativeViewHost::Detach which is called below? // It needs cleanup regardless. HWND container_hwnd = contents->GetNativeView(); // Hide the contents before adjusting its parent to avoid a full desktop // flicker. ShowWindow(container_hwnd, SW_HIDE); // Reset the parent to NULL to ensure hidden tabs don't receive messages. ::SetParent(container_hwnd, NULL); // Unregister the tab contents window from the FocusManager. views::FocusManager::UninstallFocusSubclass(container_hwnd); HWND hwnd = contents->GetContentNativeView(); if (hwnd) { // We may not have an HWND anymore, if the renderer crashed and we are // displaying the sad tab for example. views::FocusManager::UninstallFocusSubclass(hwnd); } #else gtk_widget_hide(contents->GetNativeView()); #endif // Now detach the TabContents. Detach(); } void NativeTabContentsContainerGtk::SetFastResize(bool fast_resize) { set_fast_resize(fast_resize); } void NativeTabContentsContainerGtk::RenderViewHostChanged( RenderViewHost* old_host, RenderViewHost* new_host) { // TODO(port): figure out focus interception #if defined(OS_WIN) if (old_host && old_host->view()) { views::FocusManager::UninstallFocusSubclass( old_host->view()->GetNativeView()); } if (new_host && new_host->view()) { views::FocusManager::InstallFocusSubclass( new_host->view()->GetNativeView(), this); } // If we are focused, we need to pass the focus to the new RenderViewHost. views::FocusManager* focus_manager = views::FocusManager::GetFocusManager( GetRootView()->GetWidget()->GetNativeView()); if (focus_manager->GetFocusedView() == this) Focus(); #else // If we are focused, we need to pass the focus to the new RenderViewHost. // TODO: uncomment this once FocusManager has been ported. // views::FocusManager* focus_manager = views::FocusManager::GetFocusManager( // GetRootView()->GetWidget()->GetNativeView()); // if (focus_manager->GetFocusedView() == this) // Focus(); #endif } views::View* NativeTabContentsContainerGtk::GetView() { return this; } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerGtk, views::View overrides: bool NativeTabContentsContainerGtk::SkipDefaultKeyEventProcessing( const views::KeyEvent& e) { // Don't look-up accelerators or tab-traverse if we are showing a non-crashed // TabContents. // We'll first give the page a chance to process the key events. If it does // not process them, they'll be returned to us and we'll treat them as // accelerators then. return container_->tab_contents() && !container_->tab_contents()->is_crashed(); } views::FocusTraversable* NativeTabContentsContainerGtk::GetFocusTraversable() { return NULL; } bool NativeTabContentsContainerGtk::IsFocusable() const { // We need to be focusable when our contents is not a view hierarchy, as // clicking on the contents needs to focus us. return container_->tab_contents() != NULL; } void NativeTabContentsContainerGtk::Focus() { if (container_->tab_contents()) { // Set the native focus on the actual content of the tab, that is the // interstitial if one is showing. if (container_->tab_contents()->interstitial_page()) { container_->tab_contents()->interstitial_page()->Focus(); return; } gtk_widget_grab_focus(container_->tab_contents()->GetContentNativeView()); } } void NativeTabContentsContainerGtk::RequestFocus() { // This is a hack to circumvent the fact that a view does not explicitly get // a call to set the focus if it already has the focus. This causes a problem // with tabs such as the TabContents that instruct the RenderView that it got // focus when they actually get the focus. When switching from one TabContents // tab that has focus to another TabContents tab that had focus, since the // TabContentsContainerView already has focus, Focus() would not be called and // the RenderView would not get notified it got focused. // By clearing the focused view before-hand, we ensure Focus() will be called. GetRootView()->FocusView(NULL); View::RequestFocus(); } void NativeTabContentsContainerGtk::AboutToRequestFocusFromTabTraversal( bool reverse) { if (!container_->tab_contents()) return; // Give an opportunity to the tab to reset its focus. if (container_->tab_contents()->interstitial_page()) { container_->tab_contents()->interstitial_page()->FocusThroughTabTraversal( reverse); return; } container_->tab_contents()->FocusThroughTabTraversal(reverse); } bool NativeTabContentsContainerGtk::GetAccessibleRole( AccessibilityTypes::Role* role) { // TODO(port): figure out a11y #if defined(OS_WIN) DCHECK(role); *role = AccessibilityTypes::ROLE_GROUPING; #endif return true; } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainer, public: // static NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer( TabContentsContainer* container) { return new NativeTabContentsContainerGtk(container); }
Fix toolkit_views bustage by updating callsite to use the new function name.
Fix toolkit_views bustage by updating callsite to use the new function name. BUG=none TEST=none TBR=jcampan Review URL: http://codereview.chromium.org/118419 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@17929 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
c59d0040b6a830d867b6471acc9b74afaa616350
Base/Analysis/voHierarchicalClustering.cpp
Base/Analysis/voHierarchicalClustering.cpp
// Qt includes #include <QDebug> // QtPropertyBrowser includes #include <QtVariantPropertyManager> // Visomics includes #include "voDataObject.h" #include "voHierarchicalClustering.h" #include "vtkExtendedTable.h" #include "voTableDataObject.h" // VTK includes #include <vtkDataSetAttributes.h> #include <vtkDenseArray.h> #include <vtkDoubleArray.h> #include <vtkMutableDirectedGraph.h> #include <vtkRCalculatorFilter.h> #include <vtkSmartPointer.h> #include <vtkStringArray.h> #include <vtkTable.h> #include <vtkTableToArray.h> #include <vtkTree.h> // -------------------------------------------------------------------------- // voHierarchicalClustering methods // -------------------------------------------------------------------------- voHierarchicalClustering::voHierarchicalClustering(): Superclass() { // Q_D(voHierarchicalClustering); } // -------------------------------------------------------------------------- voHierarchicalClustering::~voHierarchicalClustering() { } // -------------------------------------------------------------------------- void voHierarchicalClustering::setInputInformation() { this->addInputType("input", "vtkExtendedTable"); } // -------------------------------------------------------------------------- void voHierarchicalClustering::setOutputInformation() { this->addOutputType("clusterTree", "vtkTree", "voTreeGraphView", "clusterTree"); this->addOutputType("cluster", "vtkTable", "voHierarchicalClusteringHeatMapView", "HeatMap"); } // -------------------------------------------------------------------------- void voHierarchicalClustering::setParameterInformation() { QList<QtProperty*> hclust_parameters; // HClust / Method QStringList hclust_methods; hclust_methods << "complete" << "average" << "mcquitty" << "median" << "centroid"; hclust_parameters << this->addEnumParameter("method", tr("Method"), hclust_methods, "average"); this->addParameterGroup("HClust parameters", hclust_parameters); } // -------------------------------------------------------------------------- bool voHierarchicalClustering::execute() { // Q_D(voHierarchicalClustering); vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(this->input()->data()); if (!extendedTable) { qWarning() << "Input is Null"; return false; } vtkSmartPointer<vtkTable> table = vtkSmartPointer<vtkTable>::Take(extendedTable->GetDataWithRowHeader()); // Parameters QString hclust_method = this->enumParameter("method"); vtkSmartPointer< vtkTableToArray > tableToArray = vtkSmartPointer< vtkTableToArray>::New(); tableToArray->SetInput(table); int start = 1; int end = table->GetNumberOfColumns(); for (int ctr=start; ctr<end; ctr++) { tableToArray->AddColumn(table->GetColumnName(ctr)); } tableToArray->Update(); //Print ouf the array data for debugging purposes // vtkSmartPointer< vtkArrayData > arrayData = vtkSmartPointer< vtkArrayData>::New(); // arrayData = tableToArray->GetOutput(); // vtkIdType numberOfArrays = arrayData->GetNumberOfArrays(); // for( vtkIdType i=0; i < numberOfArrays; i++) // { // vtkDenseArray<double> *array = vtkDenseArray<double>::SafeDownCast(arrayData->GetArray(i)); // const vtkArrayExtents extents = array->GetExtents(); // for(vtkIdType i = extents[0].GetBegin(); i != extents[0].GetEnd(); ++i) // { // for(vtkIdType j = extents[1].GetBegin(); j != extents[1].GetEnd(); ++j) // { // std::cout << array->GetValue(vtkArrayCoordinates(i, j)) << "\t"; // } // std::cout << std::endl; // } // } vtkSmartPointer< vtkRCalculatorFilter > calc = vtkSmartPointer< vtkRCalculatorFilter>::New(); calc->SetRoutput(0); calc->SetInput(tableToArray->GetOutput()); /* * hclust class in R has the following attributes * * labels: labels for each of the objects being clustered. * * merge: an n-1 by 2 matrix. Row i of ‘merge’ describes the * merging of clusters at step i of the clustering. If an * element j in the row is negative, then observation -j was * merged at this stage. If j is positive then the merge was * with the cluster formed at the (earlier) stage j of the * algorithm. Thus negative entries in ‘merge’ indicate * agglomerations of singletons, and positive entries indicate * agglomerations of non-singletons. * * * height: a set of n-1 non-decreasing real values. The clustering * _height_: that is, the value of the criterion associated with * the clustering ‘method’ for the particular agglomeration. * * order: a vector giving the permutation of the original observations * suitable for plotting, in the sense that a cluster plot using * this ordering and matrix ‘merge’ will not have crossings * of the branches. * * * labels : labels for each of the objects being clustered. * */ calc->PutArray("0", "metabData"); calc->GetArray("height","height"); calc->GetArray("order","order"); calc->GetArray("merge","merge"); calc->SetRscript(QString( "dEuc<-dist(t(metabData))\n" "cluster<-hclust(dEuc,method=\"%1\")\n" "height<-as.numeric(cluster$height)\n" "order<-as.numeric(cluster$order)\n" "merge<-as.numeric(cluster$merge)\n" ).arg(hclust_method).toLatin1()); calc->Update(); vtkArrayData *temp = vtkArrayData::SafeDownCast(calc->GetOutput()); if (!temp) { std::cout << "Downcast DID NOT work." << std::endl; return 1; } vtkSmartPointer<vtkArrayData> clustReturn = vtkSmartPointer<vtkArrayData>::New(); clustReturn->DeepCopy(temp); vtkSmartPointer<vtkArrayData> heightData = vtkSmartPointer<vtkArrayData>::New(); heightData->AddArray(clustReturn->GetArrayByName("height")); vtkDenseArray<double> *heigtArray = vtkDenseArray<double>::SafeDownCast(heightData->GetArray(0)); const vtkArrayExtents heightExtent = heigtArray->GetExtents(); vtkSmartPointer<vtkArrayData> orderData = vtkSmartPointer<vtkArrayData>::New(); orderData->AddArray(clustReturn->GetArrayByName("order")); vtkSmartPointer<vtkArrayData> mergeData = vtkSmartPointer<vtkArrayData>::New(); mergeData->AddArray(clustReturn->GetArrayByName("merge")); vtkDenseArray<double> *mergeArray = vtkDenseArray<double>::SafeDownCast(mergeData->GetArray(0)); // const vtkArrayExtents matrixExtent = mergeArray->GetExtents(); //Start constructing the graph too vtkSmartPointer<vtkMutableDirectedGraph> builder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); //generate array to label the vertices vtkSmartPointer<vtkStringArray> clusterLabel = vtkSmartPointer<vtkStringArray>::New(); clusterLabel->SetName("id"); //generate array to store the vertices height vtkSmartPointer<vtkDoubleArray> distanceArray = vtkSmartPointer<vtkDoubleArray>::New(); distanceArray->SetName("Height"); /* Each time we create a parent "id", store the corresponding vertex id */ vtkstd::map<int,int> clusterMap; int clusterIndex=0; for(int i = 0; i != heightExtent[0].GetEnd(); ++i) { int firstClusterIndex; int secondClusterIndex; /* The following is needed to find the corresponding indices in the matrix */ firstClusterIndex = i; secondClusterIndex = firstClusterIndex + heightExtent[0].GetEnd(); int firstCluster = mergeArray->GetValue(vtkArrayCoordinates(firstClusterIndex)); int secondCluster = mergeArray->GetValue(vtkArrayCoordinates(secondClusterIndex)); /** Three scenario: * if both values are negative, create two new childs and a new vertex in the tree * if either one is positive, create a new child and join it with already existing vertex * if both positive, join two already existing vertices in the tree */ if( firstCluster < 0 && secondCluster < 0 ) { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue( "" ); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); double heightChildrean = heightParent - 0.02; // arbitrary distanceArray->InsertNextValue(heightParent); vtkIdType child1 = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(firstCluster)) ); distanceArray->InsertNextValue(heightChildrean); vtkIdType child2 = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(secondCluster)) ); distanceArray->InsertNextValue(heightChildrean); builder->AddEdge( parent, child1); builder->AddEdge( parent, child2); } else if( firstCluster > 0 && secondCluster > 0 ) { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue ( ""); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); // double heightChildrean = heightParent - 0.1; // arbitrary distanceArray->InsertNextValue(heightParent); int clusterNumber1 = clusterMap[firstCluster - 1]; int clusterNumber2 = clusterMap[secondCluster - 1]; builder->AddEdge( parent, clusterNumber1 ); builder->AddEdge( parent, clusterNumber2 ); } else { if ( firstCluster < 0 ) { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue ( ""); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); double heightChildrean = heightParent - 0.1;// arbitrary distanceArray->InsertNextValue(heightParent); vtkIdType child = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(firstCluster)) ); distanceArray->InsertNextValue(heightChildrean); int clusterNumber = clusterMap[secondCluster - 1]; // R cluster index starts from 1 builder->AddEdge( parent, child ); builder->AddEdge( parent, clusterNumber ); } else { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue ( ""); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); double heightChildrean = heightParent-0.1; // arbitrary distanceArray->InsertNextValue(heightParent); vtkIdType child = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(secondCluster)) ); distanceArray->InsertNextValue(heightChildrean); // int clusterNumber = clusterMap[firstCluster - 1]; // R cluster index start from 1 builder->AddEdge( parent, child ); builder->AddEdge( parent, firstCluster ); } } } vtkSmartPointer<vtkTree> tree = vtkSmartPointer<vtkTree>::New(); tree->ShallowCopy(builder); //Add vertex attributes tree->GetVertexData()->AddArray(clusterLabel); tree->GetVertexData()->AddArray(distanceArray); this->setOutput("clusterTree", new voDataObject("clusterTree", tree)); //Generate the heat map for the cluster vtkSmartPointer<vtkTable> clusterTable = vtkSmartPointer<vtkTable>::New(); vtkSmartPointer<vtkStringArray> header = vtkStringArray::SafeDownCast(table->GetColumn(0)); if (!header) { std::cout << "Downcast DID NOT work." << std::endl; return 1; } clusterTable->AddColumn(header); for (vtkIdType c = 1;c < table->GetNumberOfColumns(); ++c) { vtkAbstractArray* col = table->GetColumn(c); col->SetName(col->GetName()); clusterTable->AddColumn(col); } this->setOutput("cluster", new voTableDataObject("cluster", clusterTable)); return true; }
// Qt includes #include <QDebug> // QtPropertyBrowser includes #include <QtVariantPropertyManager> // Visomics includes #include "voDataObject.h" #include "voHierarchicalClustering.h" #include "vtkExtendedTable.h" #include "voTableDataObject.h" // VTK includes #include <vtkDataSetAttributes.h> #include <vtkDenseArray.h> #include <vtkDoubleArray.h> #include <vtkMutableDirectedGraph.h> #include <vtkRCalculatorFilter.h> #include <vtkSmartPointer.h> #include <vtkStringArray.h> #include <vtkTable.h> #include <vtkTableToArray.h> #include <vtkTree.h> #include <vtkAdjacentVertexIterator.h> #include <vtkTreeDFSIterator.h> // -------------------------------------------------------------------------- // voHierarchicalClustering methods // -------------------------------------------------------------------------- voHierarchicalClustering::voHierarchicalClustering(): Superclass() { // Q_D(voHierarchicalClustering); } // -------------------------------------------------------------------------- voHierarchicalClustering::~voHierarchicalClustering() { } // -------------------------------------------------------------------------- void voHierarchicalClustering::setInputInformation() { this->addInputType("input", "vtkExtendedTable"); } // -------------------------------------------------------------------------- void voHierarchicalClustering::setOutputInformation() { this->addOutputType("clusterTree", "vtkTree", "voTreeGraphView", "clusterTree"); this->addOutputType("cluster", "vtkTable", "voHierarchicalClusteringHeatMapView", "HeatMap"); } // -------------------------------------------------------------------------- void voHierarchicalClustering::setParameterInformation() { QList<QtProperty*> hclust_parameters; // HClust / Method QStringList hclust_methods; hclust_methods << "complete" << "average" << "mcquitty" << "median" << "centroid"; hclust_parameters << this->addEnumParameter("method", tr("Method"), hclust_methods, "average"); this->addParameterGroup("HClust parameters", hclust_parameters); } // -------------------------------------------------------------------------- bool voHierarchicalClustering::execute() { // Q_D(voHierarchicalClustering); vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(this->input()->data()); if (!extendedTable) { qWarning() << "Input is Null"; return false; } vtkSmartPointer<vtkTable> table = vtkSmartPointer<vtkTable>::Take(extendedTable->GetDataWithRowHeader()); // Parameters QString hclust_method = this->enumParameter("method"); vtkSmartPointer< vtkTableToArray > tableToArray = vtkSmartPointer< vtkTableToArray>::New(); tableToArray->SetInput(table); int start = 1; int end = table->GetNumberOfColumns(); for (int ctr=start; ctr<end; ctr++) { tableToArray->AddColumn(table->GetColumnName(ctr)); } tableToArray->Update(); //Print ouf the array data for debugging purposes // vtkSmartPointer< vtkArrayData > arrayData = vtkSmartPointer< vtkArrayData>::New(); // arrayData = tableToArray->GetOutput(); // vtkIdType numberOfArrays = arrayData->GetNumberOfArrays(); // for( vtkIdType i=0; i < numberOfArrays; i++) // { // vtkDenseArray<double> *array = vtkDenseArray<double>::SafeDownCast(arrayData->GetArray(i)); // const vtkArrayExtents extents = array->GetExtents(); // for(vtkIdType i = extents[0].GetBegin(); i != extents[0].GetEnd(); ++i) // { // for(vtkIdType j = extents[1].GetBegin(); j != extents[1].GetEnd(); ++j) // { // std::cout << array->GetValue(vtkArrayCoordinates(i, j)) << "\t"; // } // std::cout << std::endl; // } // } vtkSmartPointer< vtkRCalculatorFilter > calc = vtkSmartPointer< vtkRCalculatorFilter>::New(); calc->SetRoutput(0); calc->SetInput(tableToArray->GetOutput()); /* * hclust class in R has the following attributes * * labels: labels for each of the objects being clustered. * * merge: an n-1 by 2 matrix. Row i of ‘merge’ describes the * merging of clusters at step i of the clustering. If an * element j in the row is negative, then observation -j was * merged at this stage. If j is positive then the merge was * with the cluster formed at the (earlier) stage j of the * algorithm. Thus negative entries in ‘merge’ indicate * agglomerations of singletons, and positive entries indicate * agglomerations of non-singletons. * * * height: a set of n-1 non-decreasing real values. The clustering * _height_: that is, the value of the criterion associated with * the clustering ‘method’ for the particular agglomeration. * * order: a vector giving the permutation of the original observations * suitable for plotting, in the sense that a cluster plot using * this ordering and matrix ‘merge’ will not have crossings * of the branches. * * * labels : labels for each of the objects being clustered. * */ calc->PutArray("0", "metabData"); calc->GetArray("height","height"); calc->GetArray("order","order"); calc->GetArray("merge","merge"); calc->SetRscript(QString( "dEuc<-dist(t(metabData))\n" "cluster<-hclust(dEuc,method=\"%1\")\n" "height<-as.numeric(cluster$height)\n" "order<-as.numeric(cluster$order)\n" "merge<-as.numeric(cluster$merge)\n" ).arg(hclust_method).toLatin1()); calc->Update(); vtkArrayData *temp = vtkArrayData::SafeDownCast(calc->GetOutput()); if (!temp) { std::cout << "Downcast DID NOT work." << std::endl; return 1; } vtkSmartPointer<vtkArrayData> clustReturn = vtkSmartPointer<vtkArrayData>::New(); clustReturn->DeepCopy(temp); vtkSmartPointer<vtkArrayData> heightData = vtkSmartPointer<vtkArrayData>::New(); heightData->AddArray(clustReturn->GetArrayByName("height")); vtkDenseArray<double> *heigtArray = vtkDenseArray<double>::SafeDownCast(heightData->GetArray(0)); const vtkArrayExtents heightExtent = heigtArray->GetExtents(); vtkSmartPointer<vtkArrayData> orderData = vtkSmartPointer<vtkArrayData>::New(); orderData->AddArray(clustReturn->GetArrayByName("order")); vtkSmartPointer<vtkArrayData> mergeData = vtkSmartPointer<vtkArrayData>::New(); mergeData->AddArray(clustReturn->GetArrayByName("merge")); vtkDenseArray<double> *mergeArray = vtkDenseArray<double>::SafeDownCast(mergeData->GetArray(0)); // const vtkArrayExtents matrixExtent = mergeArray->GetExtents(); //Start constructing the graph too vtkSmartPointer<vtkMutableDirectedGraph> builder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); //generate array to label the vertices vtkSmartPointer<vtkStringArray> clusterLabel = vtkSmartPointer<vtkStringArray>::New(); clusterLabel->SetName("id"); //generate array to store the vertices height vtkSmartPointer<vtkDoubleArray> distanceArray = vtkSmartPointer<vtkDoubleArray>::New(); distanceArray->SetName("Height"); /* Each time we create a parent "id", store the corresponding vertex id */ vtkstd::map<int,int> clusterMap; int clusterIndex=0; for(int i = 0; i != heightExtent[0].GetEnd(); ++i) { int firstClusterIndex; int secondClusterIndex; /* The following is needed to find the corresponding indices in the matrix */ firstClusterIndex = i; secondClusterIndex = firstClusterIndex + heightExtent[0].GetEnd(); int firstCluster = mergeArray->GetValue(vtkArrayCoordinates(firstClusterIndex)); int secondCluster = mergeArray->GetValue(vtkArrayCoordinates(secondClusterIndex)); /** Three scenario: * if both values are negative, create two new childs and a new vertex in the tree * if either one is positive, create a new child and join it with already existing vertex * if both positive, join two already existing vertices in the tree */ if( firstCluster < 0 && secondCluster < 0 ) { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue( "" ); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); double heightChildrean = heightParent - 0.02; // arbitrary distanceArray->InsertNextValue(heightParent); vtkIdType child1 = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(firstCluster)) ); distanceArray->InsertNextValue(heightChildrean); vtkIdType child2 = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(secondCluster)) ); distanceArray->InsertNextValue(heightChildrean); builder->AddEdge( parent, child1); builder->AddEdge( parent, child2); } else if( firstCluster > 0 && secondCluster > 0 ) { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue ( ""); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); // double heightChildrean = heightParent - 0.1; // arbitrary distanceArray->InsertNextValue(heightParent); int clusterNumber1 = clusterMap[firstCluster - 1]; int clusterNumber2 = clusterMap[secondCluster - 1]; builder->AddEdge( parent, clusterNumber1 ); builder->AddEdge( parent, clusterNumber2 ); } else { if ( firstCluster < 0 ) { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue ( ""); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); double heightChildrean = heightParent - 0.1;// arbitrary distanceArray->InsertNextValue(heightParent); vtkIdType child = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(firstCluster)) ); distanceArray->InsertNextValue(heightChildrean); int clusterNumber = clusterMap[secondCluster - 1]; // R cluster index starts from 1 builder->AddEdge( parent, child ); builder->AddEdge( parent, clusterNumber ); } else { vtkIdType parent = builder->AddVertex(); clusterLabel->InsertNextValue ( ""); clusterMap[clusterIndex] = parent; clusterIndex++; double heightParent = heigtArray->GetValue(vtkArrayCoordinates(i)); double heightChildrean = heightParent-0.1; // arbitrary distanceArray->InsertNextValue(heightParent); vtkIdType child = builder->AddVertex(); clusterLabel->InsertNextValue( table->GetColumnName( abs(secondCluster)) ); distanceArray->InsertNextValue(heightChildrean); // int clusterNumber = clusterMap[firstCluster - 1]; // R cluster index start from 1 builder->AddEdge( parent, child ); builder->AddEdge( parent, firstCluster ); } } } vtkSmartPointer<vtkTree> tree = vtkSmartPointer<vtkTree>::New(); tree->ShallowCopy(builder); //Add vertex attributes tree->GetVertexData()->AddArray(clusterLabel); tree->GetVertexData()->AddArray(distanceArray); this->setOutput("clusterTree", new voDataObject("clusterTree", tree)); //Generate the heat map for the cluster vtkSmartPointer<vtkAdjacentVertexIterator> it = vtkSmartPointer<vtkAdjacentVertexIterator>::New(); int numberOfChildren = clusterLabel->GetNumberOfValues(); qDebug() << "Number of Children" << numberOfChildren; unsigned int childrenIndex = 0; vtkIdType vertex; vtkIdType level; vtkIdType root = tree->GetRoot(); const char* labelArray = "id"; const char* heightArray = "Height"; if( tree->GetVertexData()->GetAbstractArray(labelArray) == NULL || tree->GetVertexData()->GetAbstractArray(heightArray) == NULL ) { qDebug() << "ERROR: The label or height attribute is not defined in the tree."; } else { vtkStringArray* labels = vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray(labelArray)); vtkDoubleArray* heights = vtkDoubleArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray(heightArray)); for (int i = 0; i < labels->GetNumberOfValues(); ++i) { double * value = heights->GetTuple(i); qDebug() << "\t\tValue " << i << ": " << labels->GetValue(i) <<"\t" << value[0] << endl; } } vtkStringArray* labels = vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray(labelArray)); vtkSmartPointer<vtkTreeDFSIterator> dfs = vtkSmartPointer<vtkTreeDFSIterator>::New(); dfs->SetStartVertex(root); dfs->SetTree(tree); vtkIdType leafCount = 0; vtkIdType maxLevel = 0; vtkIdType lastLeafLevel = 0; while (dfs->HasNext()) { vtkIdType vertex = dfs->Next(); if (tree->IsLeaf(vertex)) { leafCount++; lastLeafLevel = tree->GetLevel(vertex); } if (tree->GetLevel(vertex) > maxLevel) { maxLevel = tree->GetLevel(vertex); } level = tree->GetLevel(vertex); qDebug() << "Vertex:\t " << vertex << "\t" << level << "\t" << labels->GetValue(vertex); } qDebug() << "Maximum Level: " << maxLevel; vtkSmartPointer<vtkTable> clusterTable = vtkSmartPointer<vtkTable>::New(); vtkSmartPointer<vtkStringArray> header = vtkStringArray::SafeDownCast(table->GetColumn(0)); if (!header) { std::cout << "Downcast DID NOT work." << std::endl; return 1; } clusterTable->AddColumn(header); for( int i=maxLevel; i >= 0; i-- ) { qDebug() << "Dealing with level \t" << i; vtkSmartPointer<vtkTreeDFSIterator> dfs = vtkSmartPointer<vtkTreeDFSIterator>::New(); dfs->SetStartVertex(root); dfs->SetTree(tree); while (dfs->HasNext()) { vtkIdType vertex = dfs->Next(); level = tree->GetLevel(vertex); qDebug() << "\t\t..." << level; if ( level == i ) { if ( labels->GetValue(vertex) != "") { qDebug() << "\t" << labels->GetValue(vertex); vtkAbstractArray* col = table->GetColumnByName(labels->GetValue(vertex)); col->SetName(col->GetName()); clusterTable->AddColumn(col); } } } } /* for (vtkIdType c = 1;c < table->GetNumberOfColumns(); ++c) { vtkAbstractArray* col = table->GetColumn(c); col->SetName(col->GetName()); clusterTable->AddColumn(col); } */ this->setOutput("cluster", new voTableDataObject("cluster", clusterTable)); return true; }
Rearrange the columns to reflect the clustering
ENH: Rearrange the columns to reflect the clustering
C++
apache-2.0
Visomics/Visomics,arborworkflows/Visomics,Visomics/Visomics,arborworkflows/Visomics,arborworkflows/Visomics,Visomics/Visomics,arborworkflows/Visomics,Visomics/Visomics,Visomics/Visomics,Visomics/Visomics,arborworkflows/Visomics,arborworkflows/Visomics
0e52af6437ff9c62b55c77c175d11cdafe1cad81
searchlib/src/tests/features/expression_replacement_features/expression_replacement_features_test.cpp
searchlib/src/tests/features/expression_replacement_features/expression_replacement_features_test.cpp
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/fef/test/ftlib.h> #include <vespa/searchlib/features/max_reduce_prod_join_feature.h> #include <vespa/searchlib/attribute/attribute.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using search::AttributeFactory; using search::IntegerAttribute; using CollectionType = FieldInfo::CollectionType; typedef search::attribute::Config AVC; typedef search::attribute::BasicType AVBT; typedef search::attribute::CollectionType AVCT; typedef search::AttributeVector::SP AttributePtr; typedef FtTestApp FTA; struct SetupFixture { InternalMaxReduceProdJoinBlueprint blueprint; IndexEnvironment indexEnv; SetupFixture(const vespalib::string &attr) : blueprint(), indexEnv() { FieldInfo attr_info(FieldType::ATTRIBUTE, CollectionType::ARRAY, attr, 0); indexEnv.getFields().push_back(attr_info); } }; TEST_F("require that blueprint can be created", SetupFixture("attribute(foo)")) { EXPECT_TRUE(FTA::assertCreateInstance(f.blueprint, "internalMaxReduceProdJoin")); } TEST_F("require that setup fails if source spec is invalid", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("source(foo)")); } TEST_F("require that setup fails if attribute does not exist", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("attribute(bar)").add("query(baz)")); } TEST_F("require that setup succeeds with attribute and query parameters", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add("attribute(foo)").add("query(bar)"), StringList(), StringList().add("scalar")); } struct ExecFixture { BlueprintFactory factory; FtFeatureTest test; ExecFixture(const vespalib::string &feature) : factory(), test(factory, feature) { factory.addPrototype(std::make_shared<InternalMaxReduceProdJoinBlueprint>()); setupAttributeVectors(); setupQueryEnvironment(); ASSERT_TRUE(test.setup()); } void setupAttributeVectors() { vespalib::string attrIntArray = "attribute(intarray)"; vespalib::string attrLongArray = "attribute(longarray)"; test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrLongArray); test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrIntArray); std::vector<AttributePtr> attrs; attrs.push_back(AttributeFactory::createAttribute(attrLongArray, AVC(AVBT::INT64, AVCT::ARRAY))); attrs.push_back(AttributeFactory::createAttribute(attrIntArray, AVC(AVBT::INT32, AVCT::ARRAY))); for (const auto &attr : attrs) { attr->addReservedDoc(); attr->addDocs(1); test.getIndexEnv().getAttributeMap().add(attr); } IntegerAttribute *longArray = static_cast<IntegerAttribute *>(attrs[0].get()); longArray->append(1, 1111, 0); longArray->append(1, 2222, 0); longArray->append(1, 78, 0); IntegerAttribute *intArray = static_cast<IntegerAttribute *>(attrs[1].get()); intArray->append(1, 78, 0); intArray->append(1, 1111, 0); for (const auto &attr : attrs) { attr->commit(); } } void setupQueryEnvironment() { test.getQueryEnv().getProperties().add("query(wset)", "{1111:1234, 2222:2245}"); test.getQueryEnv().getProperties().add("query(wsetnomatch)", "{1:1000, 2:2000}"); test.getQueryEnv().getProperties().add("query(array)", "[1111,2222]"); } bool evaluatesTo(feature_t expected) { return test.execute(expected); } }; TEST_F("require that executor returns correct result for long array", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(2245)); } TEST_F("require that executor returns correct result for int array", ExecFixture("internalMaxReduceProdJoin(attribute(intarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(1234)); } TEST_F("require that executor returns 0 if no items match", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wsetnomatch))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_F("require that executor return 0 if query is not a weighted set", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(array))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_MAIN() { TEST_RUN_ALL(); }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/fef/test/ftlib.h> #include <vespa/searchlib/features/max_reduce_prod_join_feature.h> #include <vespa/searchlib/attribute/attribute.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using search::AttributeFactory; using search::IntegerAttribute; using CollectionType = FieldInfo::CollectionType; typedef search::attribute::Config AVC; typedef search::attribute::BasicType AVBT; typedef search::attribute::CollectionType AVCT; typedef search::AttributeVector::SP AttributePtr; typedef FtTestApp FTA; struct SetupFixture { InternalMaxReduceProdJoinBlueprint blueprint; IndexEnvironment indexEnv; SetupFixture(const vespalib::string &attr) : blueprint(), indexEnv() { FieldInfo attr_info(FieldType::ATTRIBUTE, CollectionType::ARRAY, attr, 0); indexEnv.getFields().push_back(attr_info); } }; TEST_F("require that blueprint can be created", SetupFixture("attribute(foo)")) { EXPECT_TRUE(FTA::assertCreateInstance(f.blueprint, "internalMaxReduceProdJoin")); } TEST_F("require that setup fails if source spec is invalid", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("source(foo)")); } TEST_F("require that setup fails if attribute does not exist", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("attribute(bar)").add("query(baz)")); } TEST_F("require that setup succeeds with attribute and query parameters", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add("attribute(foo)").add("query(bar)"), StringList(), StringList().add("scalar")); } struct ExecFixture { BlueprintFactory factory; FtFeatureTest test; ExecFixture(const vespalib::string &feature) : factory(), test(factory, feature) { factory.addPrototype(std::make_shared<InternalMaxReduceProdJoinBlueprint>()); setupAttributeVectors(); setupQueryEnvironment(); ASSERT_TRUE(test.setup()); } void setupAttributeVectors() { vespalib::string attrIntArray = "attribute(intarray)"; vespalib::string attrLongArray = "attribute(longarray)"; test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrLongArray); test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrIntArray); std::vector<AttributePtr> attrs; attrs.push_back(AttributeFactory::createAttribute(attrLongArray, AVC(AVBT::INT64, AVCT::ARRAY))); attrs.push_back(AttributeFactory::createAttribute(attrIntArray, AVC(AVBT::INT32, AVCT::ARRAY))); for (const auto &attr : attrs) { attr->addReservedDoc(); attr->addDocs(1); test.getIndexEnv().getAttributeMap().add(attr); } IntegerAttribute *longArray = static_cast<IntegerAttribute *>(attrs[0].get()); longArray->append(1, 1111, 0); longArray->append(1, 2222, 0); longArray->append(1, 78, 0); IntegerAttribute *intArray = static_cast<IntegerAttribute *>(attrs[1].get()); intArray->append(1, 78, 0); intArray->append(1, 1111, 0); for (const auto &attr : attrs) { attr->commit(); } } void setupQueryEnvironment() { test.getQueryEnv().getProperties().add("query(wset)", "{1111:1234, 2222:2245}"); test.getQueryEnv().getProperties().add("query(wsetnomatch)", "{1:1000, 2:2000}"); test.getQueryEnv().getProperties().add("query(array)", "[1111,2222]"); } bool evaluatesTo(feature_t expectedValue) { return test.execute(expectedValue); } }; TEST_F("require that executor returns correct result for long array", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wset))")) { EXPECT_FALSE(f.evaluatesTo(1234)); EXPECT_TRUE(f.evaluatesTo(2245)); } TEST_F("require that executor returns correct result for int array", ExecFixture("internalMaxReduceProdJoin(attribute(intarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(1234)); EXPECT_FALSE(f.evaluatesTo(2245)); } TEST_F("require that executor returns 0 if no items match", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wsetnomatch))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_F("require that executor return 0 if query is not a weighted set", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(array))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_MAIN() { TEST_RUN_ALL(); }
Add some extra asserts in feature test
Add some extra asserts in feature test
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
d6778146901a534098045f7888dd53bf34a66b5a
commander/ExeCommander.cpp
commander/ExeCommander.cpp
#include "ExeCommander.h" #include "../parser/ExeNodeWrapper.h" #include "../parser/Formatter.h" #include "../parser/FileBuffer.h" //------------------------------------------ char cmd_util::addrTypeToChar(Executable::addr_type type) { switch (type) { case Executable::RAW: return 'r'; case Executable::RVA: return 'v'; case Executable::VA: return 'V'; default: return '_'; } return '_'; } std::string cmd_util::addrTypeToStr(Executable::addr_type type) { switch (type) { case Executable::RAW: return "raw"; case Executable::RVA: return "RVA"; case Executable::VA: return "VA"; default: return ""; } return ""; } Executable* cmd_util::getExeFromContext(CmdContext *context) { ExeCmdContext *exeContext = dynamic_cast<ExeCmdContext*>(context); if (exeContext == NULL) throw CustomException("Invalid command context!"); Executable *exe = exeContext->getExe(); if (exe == NULL) throw CustomException("Invalid command context: no Exe"); return exe; } offset_t cmd_util::readOffset(Executable::addr_type aType) { if (aType == Executable::NOT_ADDR) { return INVALID_ADDR; } std::string prompt = addrTypeToStr(aType); offset_t offset = 0; std::cout << prompt.c_str() << ": "; std::cin >> std::hex >> offset; return offset; } size_t cmd_util::readNumber(std::string prompt, bool read_hex) { unsigned int num = 0; std::cout << prompt.c_str() << ": "; if (read_hex) { std::cin >> std::hex >> num; } else { std::cin >> std::dec >> num; } return num; } void cmd_util::fetch(Executable *peExe, offset_t offset, Executable::addr_type aType, bool hex) { offset = peExe->toRaw(offset, aType); if (offset == INVALID_ADDR) { std::cerr << "ERROR: Invalid Address suplied" << std::endl; return; } BufferView *sub = new BufferView(peExe, offset, 100); if (sub->getContent() == nullptr) { std::cout << "[ERROR] Cannot fetch" << std::endl; delete sub; return; } AbstractFormatter *formatter = nullptr; std::string separator = " "; if (hex) formatter = new HexFormatter(sub); else { formatter = new Formatter(sub); separator = ""; } std::cout << "Fetched:" << std::endl; for (bufsize_t i = 0; i < sub->getContentSize(); i++) { std::cout << (*formatter)[i].toStdString() << separator.c_str(); } std::cout << std::endl; delete formatter; delete sub; } void cmd_util::printWrapperNames(MappedExe *exe) { size_t count = exe->wrappersCount(); for (size_t i = 0; i < count; i++) { ExeElementWrapper *wr = exe->getWrapper(i); if (wr == NULL || wr->getPtr() == NULL) { continue; } std::cout << "[" << std::dec << i << "] "; std::cout << exe->getWrapperName(i).toStdString() << std::endl; } } void cmd_util::dumpEntryInfo(ExeElementWrapper *w) { if (w == nullptr) return; std::cout << "\n------\n"; size_t fields = w->getFieldsCount(); std::cout << "[" << w->getName().toStdString() << "] "; std::cout << "size: "; OUT_PADDED_HEX(std::cout, w->getSize(), sizeof(bufsize_t)); std::cout << " "; std::cout << "fieldsCount: " << std::dec << fields << "\n" << std::endl; for (size_t i = 0; i < fields; i++) { offset_t offset = w->getFieldOffset(i); if (offset == INVALID_ADDR) { continue; } OUT_PADDED_OFFSET(std::cout, offset); std::cout << " " << w->getFieldName(i).toStdString() << "\t"; size_t subfields = w->getSubFieldsCount(); for (size_t y = 0; y < subfields; y++) { WrappedValue value = w->getWrappedValue(i, y); QString str = value.toQString(); Executable::addr_type aType = w->containsAddrType(i, y); char c = addrTypeToChar(aType); std::cout << "[" << str.toStdString() << " " << c << "]"; } QString translated = w->translateFieldContent(i); if (translated.size() > 0) { std::cout << " " << translated.toStdString() << " "; } std::cout << "\n"; } std::cout << "------" << std::endl; } void cmd_util::dumpNodeInfo(ExeNodeWrapper *w) { if (w == nullptr) return; std::cout << "------" << std::endl; size_t entriesCnt = w->getEntriesCount(); std::cout << "\t [" << w->getName().toStdString() << "] " << "entriesCount: " << std::dec << entriesCnt << std::endl; for (size_t i = 0; i < entriesCnt; i++) { ExeNodeWrapper* entry = w->getEntryAt(i); if (entry == NULL) break; std::cout << "Entry #" << std::dec << i << "\n"; dumpEntryInfo(entry); size_t subEntries = entry->getEntriesCount(); if (subEntries > 0) { std::cout << "Have entries: " << std::dec << subEntries << " ( " << std::hex << "0x" << subEntries << " )"; } std::cout << "\n"; } } void ExeCommander::initCommands() { this->addCommand("info", new ExeInfoCommand()); this->addCommand("r-v", new ConvertAddrCommand(Executable::RAW, Executable::RVA, "Convert: RAW -> RVA")); this->addCommand("v-r", new ConvertAddrCommand(Executable::RVA, Executable::RAW, "Convert: RVA -> RAW")); this->addCommand("printc", new FetchCommand(false, Executable::RAW, "Print content by Raw address")); //this->addCommand("cV", new FetchCommand(false, Executable::RVA, "Fetch content by Virtual address")); this->addCommand("printx", new FetchCommand(true, Executable::RAW, "Print content by Raw address - HEX")); //this->addCommand("hV", new FetchCommand(true, Executable::RVA, "Fetch content by Virtual address - HEX")); this->addCommand("cl", new ClearWrapperCommand("Clear chosen wrapper Content")); this->addCommand("fdump", new DumpWrapperToFileCommand("Dump chosen wrapper Content into a file")); this->addCommand("winfo", new DumpWrapperCommand("Dump chosen wrapper info")); this->addCommand("einfo", new DumpWrapperEntriesCommand("Dump wrapper entries")); this->addCommand("e_add", new AddEntryCommand("Add entry to a wrapper")); this->addCommand("save", new SaveExeToFileCommand()); } //--- void ConvertAddrCommand::execute(CmdParams *params, CmdContext *context) { Executable *exe = cmd_util::getExeFromContext(context); offset_t offset = cmd_util::readOffset(addrFrom); offset_t outOffset = exe->convertAddr(offset, addrFrom, addrTo); if (outOffset == INVALID_ADDR) { std::cerr << "[WARNING] This address cannot be mapped" << std::endl; return; } std::cout << "[" << cmd_util::addrTypeToStr(addrFrom) << "]"; std::cout << "\t->\t"; std::cout << "[" << cmd_util::addrTypeToStr(addrTo) << "]"; std::cout << ":\n"; OUT_PADDED_OFFSET(std::cout, offset); std::cout << "\t->\t"; OUT_PADDED_OFFSET(std::cout, outOffset); std::cout << std::endl; } //--- void ExeInfoCommand::execute(CmdParams *params, CmdContext *context) { Executable *exe = cmd_util::getExeFromContext(context); std::cout << "Bit mode: \t" << std::dec << exe->getBitMode() << "\n"; offset_t entryPoint = exe->getEntryPoint(); std::cout << "Entry point: \t"; std::cout << "["; OUT_PADDED_OFFSET(std::cout, entryPoint); std::cout << " " << cmd_util::addrTypeToChar(Executable::RVA); std::cout << "]\n"; //Raw: std::cout << "Raw size: \t"; OUT_PADDED_OFFSET(std::cout, exe->getMappedSize(Executable::RAW)); std::cout << "\n"; std::cout << "Raw align. \t"; OUT_PADDED_OFFSET(std::cout, exe->getAlignment(Executable::RAW)); std::cout << "\n"; //Virtual: std::cout << "Virtual size: \t"; OUT_PADDED_OFFSET(std::cout, exe->getMappedSize(Executable::RVA)); std::cout << "\n"; std::cout << "Virtual align. \t"; OUT_PADDED_OFFSET(std::cout, exe->getAlignment(Executable::RVA)); std::cout << "\n"; MappedExe *mappedExe = cmd_util::getMappedExeFromContext(context); if (mappedExe) { std::cout << "Contains:\n"; cmd_util::printWrapperNames(mappedExe); } std::cout << std::endl; }
#include "ExeCommander.h" #include "../parser/ExeNodeWrapper.h" #include "../parser/Formatter.h" #include "../parser/FileBuffer.h" //------------------------------------------ char cmd_util::addrTypeToChar(Executable::addr_type type) { switch (type) { case Executable::RAW: return 'r'; case Executable::RVA: return 'v'; case Executable::VA: return 'V'; default: return '_'; } return '_'; } std::string cmd_util::addrTypeToStr(Executable::addr_type type) { switch (type) { case Executable::RAW: return "raw"; case Executable::RVA: return "RVA"; case Executable::VA: return "VA"; default: return ""; } return ""; } Executable* cmd_util::getExeFromContext(CmdContext *context) { ExeCmdContext *exeContext = dynamic_cast<ExeCmdContext*>(context); if (exeContext == NULL) throw CustomException("Invalid command context!"); Executable *exe = exeContext->getExe(); if (exe == NULL) throw CustomException("Invalid command context: no Exe"); return exe; } offset_t cmd_util::readOffset(Executable::addr_type aType) { if (aType == Executable::NOT_ADDR) { return INVALID_ADDR; } std::string prompt = addrTypeToStr(aType); offset_t offset = 0; std::cout << prompt.c_str() << ": "; std::cin >> std::hex >> offset; return offset; } size_t cmd_util::readNumber(std::string prompt, bool read_hex) { unsigned int num = 0; std::cout << prompt.c_str() << ": "; if (read_hex) { std::cin >> std::hex >> num; } else { std::cin >> std::dec >> num; } return num; } void cmd_util::fetch(Executable *peExe, offset_t offset, Executable::addr_type aType, bool hex) { offset = peExe->toRaw(offset, aType); if (offset == INVALID_ADDR) { std::cerr << "ERROR: Invalid Address suplied" << std::endl; return; } BufferView *sub = new BufferView(peExe, offset, 100); if (sub->getContent() == nullptr) { std::cout << "[ERROR] Cannot fetch" << std::endl; delete sub; return; } AbstractFormatter *formatter = nullptr; std::string separator = " "; if (hex) formatter = new HexFormatter(sub); else { formatter = new Formatter(sub); separator = ""; } std::cout << "Fetched:" << std::endl; for (bufsize_t i = 0; i < sub->getContentSize(); i++) { std::cout << (*formatter)[i].toStdString() << separator.c_str(); } std::cout << std::endl; delete formatter; delete sub; } void cmd_util::printWrapperNames(MappedExe *exe) { size_t count = exe->wrappersCount(); for (size_t i = 0; i < count; i++) { ExeElementWrapper *wr = exe->getWrapper(i); if (wr == NULL || wr->getPtr() == NULL) { continue; } std::cout << "[" << std::dec << i << "] "; std::cout << exe->getWrapperName(i).toStdString() << std::endl; } } void cmd_util::dumpEntryInfo(ExeElementWrapper *w) { if (w == nullptr) return; std::cout << "\n------\n"; size_t fields = w->getFieldsCount(); std::cout << "[" << w->getName().toStdString() << "] "; std::cout << "size: "; OUT_PADDED_HEX(std::cout, w->getSize(), sizeof(bufsize_t)); std::cout << " "; std::cout << "fieldsCount: " << std::dec << fields << "\n" << std::endl; for (size_t i = 0; i < fields; i++) { offset_t offset = w->getFieldOffset(i); if (offset == INVALID_ADDR) { continue; } OUT_PADDED_OFFSET(std::cout, offset); std::cout << " " << w->getFieldName(i).toStdString() << "\t"; size_t subfields = w->getSubFieldsCount(); for (size_t y = 0; y < subfields; y++) { WrappedValue value = w->getWrappedValue(i, y); QString str = value.toQString(); Executable::addr_type aType = w->containsAddrType(i, y); char c = addrTypeToChar(aType); std::cout << "[" << str.toStdString() << " " << c << "]"; } QString translated = w->translateFieldContent(i); if (translated.size() > 0) { std::cout << " " << translated.toStdString() << " "; } std::cout << "\n"; } std::cout << "------" << std::endl; } void cmd_util::dumpNodeInfo(ExeNodeWrapper *w) { if (w == nullptr) return; std::cout << "------" << std::endl; size_t entriesCnt = w->getEntriesCount(); std::cout << "\t [" << w->getName().toStdString() << "] " << "entriesCount: " << std::dec << entriesCnt << std::endl; for (size_t i = 0; i < entriesCnt; i++) { ExeNodeWrapper* entry = w->getEntryAt(i); if (entry == NULL) break; std::cout << "Entry #" << std::dec << i << "\n"; dumpEntryInfo(entry); size_t subEntries = entry->getEntriesCount(); if (subEntries > 0) { std::cout << "Have entries: " << std::dec << subEntries << " ( " << std::hex << "0x" << subEntries << " )"; } std::cout << "\n"; } } void ExeCommander::initCommands() { this->addCommand("info", new ExeInfoCommand()); this->addCommand("r-v", new ConvertAddrCommand(Executable::RAW, Executable::RVA, "Convert: RAW -> RVA")); this->addCommand("v-r", new ConvertAddrCommand(Executable::RVA, Executable::RAW, "Convert: RVA -> RAW")); this->addCommand("printc", new FetchCommand(false, Executable::RAW, "Print content by Raw address")); //this->addCommand("cV", new FetchCommand(false, Executable::RVA, "Fetch content by Virtual address")); this->addCommand("printx", new FetchCommand(true, Executable::RAW, "Print content by Raw address - HEX")); //this->addCommand("hV", new FetchCommand(true, Executable::RVA, "Fetch content by Virtual address - HEX")); this->addCommand("cl", new ClearWrapperCommand("Clear chosen wrapper Content")); this->addCommand("fdump", new DumpWrapperToFileCommand("Dump chosen wrapper Content into a file")); this->addCommand("winfo", new DumpWrapperCommand("Dump chosen wrapper info")); this->addCommand("einfo", new DumpWrapperEntriesCommand("Dump wrapper entries")); this->addCommand("e_add", new AddEntryCommand("Add entry to a wrapper")); this->addCommand("save", new SaveExeToFileCommand()); } //--- void ConvertAddrCommand::execute(CmdParams *params, CmdContext *context) { Executable *exe = cmd_util::getExeFromContext(context); offset_t offset = cmd_util::readOffset(addrFrom); offset_t outOffset = exe->convertAddr(offset, addrFrom, addrTo); if (outOffset == INVALID_ADDR) { std::cerr << "[WARNING] This address cannot be mapped" << std::endl; return; } std::cout << "[" << cmd_util::addrTypeToStr(addrFrom) << "]"; std::cout << "\t->\t"; std::cout << "[" << cmd_util::addrTypeToStr(addrTo) << "]"; std::cout << ":\n"; OUT_PADDED_OFFSET(std::cout, offset); std::cout << "\t->\t"; OUT_PADDED_OFFSET(std::cout, outOffset); std::cout << std::endl; } //--- void ExeInfoCommand::execute(CmdParams *params, CmdContext *context) { Executable *exe = cmd_util::getExeFromContext(context); std::cout << "Bit mode: \t" << std::dec << exe->getBitMode() << "\n"; offset_t entryPoint = exe->getEntryPoint(); std::cout << "Entry point: \t"; std::cout << "["; OUT_PADDED_HEX(std::cout, entryPoint, sizeof(entryPoint)); std::cout << " " << cmd_util::addrTypeToChar(Executable::RVA); std::cout << "]\n"; //Raw: std::cout << "Raw size: \t"; OUT_PADDED_OFFSET(std::cout, exe->getMappedSize(Executable::RAW)); std::cout << "\n"; std::cout << "Raw align. \t"; OUT_PADDED_OFFSET(std::cout, exe->getAlignment(Executable::RAW)); std::cout << "\n"; //Virtual: std::cout << "Virtual size: \t"; OUT_PADDED_OFFSET(std::cout, exe->getMappedSize(Executable::RVA)); std::cout << "\n"; std::cout << "Virtual align. \t"; OUT_PADDED_OFFSET(std::cout, exe->getAlignment(Executable::RVA)); std::cout << "\n"; MappedExe *mappedExe = cmd_util::getMappedExeFromContext(context); if (mappedExe) { std::cout << "Contains:\n"; cmd_util::printWrapperNames(mappedExe); } std::cout << std::endl; }
Print EntryPoint as hex field, not as offset
[BUGFIX][commander] Print EntryPoint as hex field, not as offset
C++
bsd-2-clause
hasherezade/bearparser,hasherezade/bearparser,hasherezade/bearparser
8779970f39a7a3dcaeb5aca9919f691fe64826a0
src/classify/confusion_matrix.cpp
src/classify/confusion_matrix.cpp
/** * @file confusion_matrix.cpp * @author Sean Massung */ #include <iomanip> #include <algorithm> #include <vector> #include "util/common.h" #include "classify/confusion_matrix.h" namespace meta { namespace classify { confusion_matrix::confusion_matrix(): _predictions{32, string_pair_hash}, _total{0} { /* nothing */ } void confusion_matrix::add(const class_label & predicted, const class_label & actual, size_t times) { std::pair<class_label, class_label> prediction{predicted, actual}; _predictions[prediction] += times; _counts[actual] += times; _classes.insert(predicted); _classes.insert(actual); _total += times; } void confusion_matrix::print_result_pairs(std::ostream & out) const { for(auto & p: _predictions) for(size_t i = 0; i < p.second; ++i) out << p.first.first << " " << p.first.second << "\n"; } void confusion_matrix::print(std::ostream & out) const { size_t w = 12; out << std::endl << std::setw(w) << ""; for(auto & aClass: _classes) out << std::setw(w - 1) << aClass << " "; out << std::endl; out << std::string(w, ' ') << std::string(_classes.size() * w, '-') << std::endl; for(auto & aClass: _classes) { out << std::setw(w - 1) << aClass << " | "; for(auto & pClass: _classes) { auto predIt = _predictions.find(std::make_pair(pClass, aClass)); if(predIt != _predictions.end()) { size_t numPred = predIt->second; double percent = static_cast<double>(numPred) / _counts.at(aClass); out.precision(3); std::stringstream ss; ss.precision(3); ss << percent; if(aClass == pClass) out << std::setw(w) << ("[" + ss.str() + "]"); else out << std::setw(w) << std::fixed << percent; } else out << std::setw(w) << "- "; } out << std::endl; } out << std::endl; } void confusion_matrix::print_class_stats(std::ostream & out, const class_label & label, double & prec, double & rec, double & f1, size_t width) const { for(auto & cls: _classes) { prec += common::safe_at(_predictions, std::make_pair(cls, label)); rec += common::safe_at(_predictions, std::make_pair(label, cls)); } double correct = common::safe_at(_predictions, std::make_pair(label, label)); if(rec != 0.0) rec = correct / rec; if(prec != 0.0) prec = correct / prec; if(prec + rec != 0.0) f1 = (2.0 * prec * rec) / (prec + rec); auto w1 = std::setw(width); auto w2 = std::setw(12); out << std::left << w1 << label << std::left << w2 << f1 << std::left << w2 << prec << std::left << w2 << rec << std::endl; } void confusion_matrix::print_stats(std::ostream & out) const { double t_prec = 0.0; double t_rec = 0.0; double t_f1 = 0.0; double t_corr = 0.0; auto max_label = std::max_element(_classes.begin(), _classes.end(), [](const class_label & a, const class_label & b) { return static_cast<std::string>(a).size() < static_cast<std::string>(b).size(); } ); size_t width = static_cast<std::string>(*max_label).size() + 2; auto w1 = std::setw(width); auto w2 = std::setw(12); out.precision(3); out << std::string(width * 4, '-') << std::endl << std::left << w1 << "Class" << std::left << w2 << "F1 Score" << std::left << w2 << "Precision" << std::left << w2 << "Recall" << std::endl << std::string(width * 4, '-') << std::endl; for(auto & cls: _classes) { double prec = 0.0, rec = 0.0, f1 = 0.0; auto it = _predictions.find(std::make_pair(cls, cls)); if(it != _predictions.end()) t_corr += it->second; print_class_stats(out, cls, prec, rec, f1, width); t_prec += prec; t_rec += rec; t_f1 += f1; } out << std::string(width * 4, '-') << std::endl << w1 << "Total" << w2 << t_f1 / _classes.size() << w2 << t_prec / _classes.size() << w2 << t_rec / _classes.size() << std::endl << std::string(width * 4, '-') << std::endl << _total << " predictions attempted, overall accuracy: " << t_corr / _total << std::endl; } double confusion_matrix::accuracy() const { double correct = 0.0; for(auto & cls: _classes) correct += common::safe_at(_predictions, std::make_pair(cls, cls)); return correct / _total; } size_t confusion_matrix::string_pair_hash(const std::pair<std::string, std::string> & str_pair) { return std::hash<std::string>()(str_pair.first + str_pair.second); } const confusion_matrix::prediction_counts & confusion_matrix::predictions() const { return _predictions; } confusion_matrix confusion_matrix::operator+(const confusion_matrix & other) const { confusion_matrix sum{*this}; for(auto & pred: other.predictions()) sum.add(pred.first.first, pred.first.second, pred.second); return sum; } confusion_matrix & confusion_matrix::operator+=(const confusion_matrix & other) { *this = *this + other; return *this; } bool confusion_matrix::mcnemar_significant(const confusion_matrix & a, const confusion_matrix & b) { std::set<class_label> classes = a._classes; classes.insert(b._classes.begin(), b._classes.end()); double a_adv = 0; double b_adv = 0; for(auto & cls: classes) { auto a_count = common::safe_at(a._predictions, std::make_pair(cls, cls)); auto b_count = common::safe_at(b._predictions, std::make_pair(cls, cls)); if(a_count > b_count) a_adv += (a_count - b_count); else if(b_count > a_count) b_adv += (b_count - a_count); } // does not approximate well if less than 25 samples if(a_adv + b_adv < 25) return false; double numerator = std::abs(a_adv - b_adv) - 0.5; double chi_square = (numerator * numerator) / (a_adv + b_adv); // check if significant with chi square, 1 degree of freedom, alpha == 0.05 return chi_square > 3.84; } } }
/** * @file confusion_matrix.cpp * @author Sean Massung */ #include <iomanip> #include <algorithm> #include <vector> #include "util/common.h" #include "classify/confusion_matrix.h" namespace meta { namespace classify { confusion_matrix::confusion_matrix(): _predictions{32, string_pair_hash}, _total{0} { /* nothing */ } void confusion_matrix::add(const class_label & predicted, const class_label & actual, size_t times) { std::pair<class_label, class_label> prediction{predicted, actual}; _predictions[prediction] += times; _counts[actual] += times; _classes.insert(predicted); _classes.insert(actual); _total += times; } void confusion_matrix::print_result_pairs(std::ostream & out) const { for(auto & p: _predictions) for(size_t i = 0; i < p.second; ++i) out << p.first.first << " " << p.first.second << "\n"; } void confusion_matrix::print(std::ostream & out) const { size_t w = 12; out << std::endl << std::setw(w) << ""; for(auto & aClass: _classes) out << std::setw(w - 1) << aClass << " "; out << std::endl; out << std::string(w, ' ') << std::string(_classes.size() * w, '-') << std::endl; for(auto & aClass: _classes) { out << std::setw(w - 1) << aClass << " | "; for(auto & pClass: _classes) { auto predIt = _predictions.find(std::make_pair(pClass, aClass)); if(predIt != _predictions.end()) { size_t numPred = predIt->second; double percent = static_cast<double>(numPred) / _counts.at(aClass); out.precision(3); std::stringstream ss; ss.precision(3); ss << percent; if(aClass == pClass) out << std::setw(w) << ("[" + ss.str() + "]"); else out << std::setw(w) << std::fixed << percent; } else out << std::setw(w) << "- "; } out << std::endl; } out << std::endl; } void confusion_matrix::print_class_stats(std::ostream & out, const class_label & label, double & prec, double & rec, double & f1, size_t width) const { for(auto & cls: _classes) { prec += common::safe_at(_predictions, std::make_pair(cls, label)); rec += common::safe_at(_predictions, std::make_pair(label, cls)); } double correct = common::safe_at(_predictions, std::make_pair(label, label)); if(rec != 0.0) rec = correct / rec; if(prec != 0.0) prec = correct / prec; if(prec + rec != 0.0) f1 = (2.0 * prec * rec) / (prec + rec); auto w1 = std::setw(width); auto w2 = std::setw(12); out << std::left << w1 << label << std::left << w2 << f1 << std::left << w2 << prec << std::left << w2 << rec << std::endl; } void confusion_matrix::print_stats(std::ostream & out) const { double t_prec = 0.0; double t_rec = 0.0; double t_f1 = 0.0; double t_corr = 0.0; auto max_label = std::max_element(_classes.begin(), _classes.end(), [](const class_label & a, const class_label & b) { return static_cast<std::string>(a).size() < static_cast<std::string>(b).size(); } ); size_t width = std::max<size_t>(5, static_cast<std::string>(*max_label).size()) + 2; auto w1 = std::setw(width); auto w2 = std::setw(12); out.precision(3); out << std::string(width * 4, '-') << std::endl << std::left << w1 << "Class" << std::left << w2 << "F1 Score" << std::left << w2 << "Precision" << std::left << w2 << "Recall" << std::endl << std::string(width * 4, '-') << std::endl; for(auto & cls: _classes) { double prec = 0.0, rec = 0.0, f1 = 0.0; auto it = _predictions.find(std::make_pair(cls, cls)); if(it != _predictions.end()) t_corr += it->second; print_class_stats(out, cls, prec, rec, f1, width); t_prec += prec; t_rec += rec; t_f1 += f1; } out << std::string(width * 4, '-') << std::endl << w1 << "Total" << w2 << t_f1 / _classes.size() << w2 << t_prec / _classes.size() << w2 << t_rec / _classes.size() << std::endl << std::string(width * 4, '-') << std::endl << _total << " predictions attempted, overall accuracy: " << t_corr / _total << std::endl; } double confusion_matrix::accuracy() const { double correct = 0.0; for(auto & cls: _classes) correct += common::safe_at(_predictions, std::make_pair(cls, cls)); return correct / _total; } size_t confusion_matrix::string_pair_hash(const std::pair<std::string, std::string> & str_pair) { return std::hash<std::string>()(str_pair.first + str_pair.second); } const confusion_matrix::prediction_counts & confusion_matrix::predictions() const { return _predictions; } confusion_matrix confusion_matrix::operator+(const confusion_matrix & other) const { confusion_matrix sum{*this}; for(auto & pred: other.predictions()) sum.add(pred.first.first, pred.first.second, pred.second); return sum; } confusion_matrix & confusion_matrix::operator+=(const confusion_matrix & other) { *this = *this + other; return *this; } bool confusion_matrix::mcnemar_significant(const confusion_matrix & a, const confusion_matrix & b) { std::set<class_label> classes = a._classes; classes.insert(b._classes.begin(), b._classes.end()); double a_adv = 0; double b_adv = 0; for(auto & cls: classes) { auto a_count = common::safe_at(a._predictions, std::make_pair(cls, cls)); auto b_count = common::safe_at(b._predictions, std::make_pair(cls, cls)); if(a_count > b_count) a_adv += (a_count - b_count); else if(b_count > a_count) b_adv += (b_count - a_count); } // does not approximate well if less than 25 samples if(a_adv + b_adv < 25) return false; double numerator = std::abs(a_adv - b_adv) - 0.5; double chi_square = (numerator * numerator) / (a_adv + b_adv); // check if significant with chi square, 1 degree of freedom, alpha == 0.05 return chi_square > 3.84; } } }
Fix minor display bug with confusion matrix stats with short class labels.
Fix minor display bug with confusion matrix stats with short class labels.
C++
mit
husseinhazimeh/meta,esparza83/meta,saq7/MeTA,husseinhazimeh/meta,gef756/meta,husseinhazimeh/meta,gef756/meta,esparza83/meta,gef756/meta,saq7/MeTA,esparza83/meta,husseinhazimeh/meta,esparza83/meta,gef756/meta,saq7/MeTA,esparza83/meta,husseinhazimeh/meta,gef756/meta
904b1434fb75dbe6024bb8d07b520a65d438a403
Filtering/vtkInformationVector.cxx
Filtering/vtkInformationVector.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkInformationVector.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. =========================================================================*/ #include "vtkInformationVector.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include <vtkstd/vector> vtkCxxRevisionMacro(vtkInformationVector, "1.9"); vtkStandardNewMacro(vtkInformationVector); class vtkInformationVectorInternals { public: vtkstd::vector<vtkInformation*> Vector; ~vtkInformationVectorInternals(); }; //---------------------------------------------------------------------------- vtkInformationVectorInternals::~vtkInformationVectorInternals() { // Delete all the information objects. for(vtkstd::vector<vtkInformation*>::iterator i = this->Vector.begin(); i != this->Vector.end(); ++i) { if(vtkInformation* info = *i) { info->Delete(); } } } //---------------------------------------------------------------------------- vtkInformationVector::vtkInformationVector() { this->Internal = new vtkInformationVectorInternals; this->NumberOfInformationObjects = 0; } //---------------------------------------------------------------------------- vtkInformationVector::~vtkInformationVector() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkInformationVector::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Number of Information Objects: " << this->NumberOfInformationObjects << "\n"; os << indent << "Information Objects:\n"; for(int i=0; i < this->NumberOfInformationObjects; ++i) { vtkInformation* info = this->GetInformationObject(i); vtkIndent nextIndent = indent.GetNextIndent(); os << nextIndent << info->GetClassName() << "(" << info << "):\n"; info->PrintSelf(os, nextIndent.GetNextIndent()); } } //---------------------------------------------------------------------------- void vtkInformationVector::SetNumberOfInformationObjects(int newNumber) { // Adjust the number of objects. int oldNumber = this->NumberOfInformationObjects; if(newNumber > oldNumber) { // Create new information objects. this->Internal->Vector.resize(newNumber, 0); for(int i=oldNumber; i < newNumber; ++i) { this->Internal->Vector[i] = vtkInformation::New(); } } else if(newNumber < oldNumber) { // Delete old information objects. for(int i=newNumber; i < oldNumber; ++i) { if(vtkInformation* info = this->Internal->Vector[i]) { // Set the pointer to NULL first to avoid reporting of the // entry if deleting the information object causes a garbage // collection reference walk. this->Internal->Vector[i] = 0; info->Delete(); } } this->Internal->Vector.resize(newNumber); } this->NumberOfInformationObjects = newNumber; } //---------------------------------------------------------------------------- void vtkInformationVector::SetInformationObject(int index, vtkInformation* newInfo) { if(newInfo && index >= 0 && index < this->NumberOfInformationObjects) { // Replace an existing information object. vtkInformation* oldInfo = this->Internal->Vector[index]; if(oldInfo != newInfo) { newInfo->Register(this); this->Internal->Vector[index] = newInfo; oldInfo->UnRegister(this); } } else if(newInfo && index >= this->NumberOfInformationObjects) { // If a hole will be created fill it with empty objects. if(index > this->NumberOfInformationObjects) { this->SetNumberOfInformationObjects(index); } // Store the information object in a new entry. newInfo->Register(this); this->Internal->Vector.push_back(newInfo); this->NumberOfInformationObjects++; } else if(!newInfo && index >= 0 && index < this->NumberOfInformationObjects-1) { // We do not allow NULL information objects. Create an empty one // to fill in the hole. vtkInformation* oldInfo = this->Internal->Vector[index]; this->Internal->Vector[index] = vtkInformation::New(); oldInfo->UnRegister(this); } else if(!newInfo && index >= 0 && index == this->NumberOfInformationObjects-1) { // Remove the last information object. this->SetNumberOfInformationObjects(index); } } //---------------------------------------------------------------------------- vtkInformation* vtkInformationVector::GetInformationObject(int index) { if(index >= 0 && index < this->NumberOfInformationObjects) { return this->Internal->Vector[index]; } return 0; } //---------------------------------------------------------------------------- void vtkInformationVector::Append(vtkInformation* info) { // Setting an entry beyond the end will automatically append. this->SetInformationObject(this->NumberOfInformationObjects, info); } //---------------------------------------------------------------------------- void vtkInformationVector::Remove(vtkInformation* info) { // Search for the information object and remove it. for(unsigned int i=0; i < this->NumberOfInformationObjects; ++i) { if(this->Internal->Vector[i] == info) { this->Internal->Vector.erase(this->Internal->Vector.begin()+i); info->UnRegister(this); this->NumberOfInformationObjects--; } } } //---------------------------------------------------------------------------- void vtkInformationVector::Copy(vtkInformationVector* from, int deep) { // if deep we can reuse existing info objects if (deep) { this->SetNumberOfInformationObjects(from->GetNumberOfInformationObjects()); for (int i = 0; i < from->GetNumberOfInformationObjects(); ++i) { this->Internal->Vector[i]->Copy(from->GetInformationObject(i),deep); } return; } // otherwise it is a shallow copy and we must copy pointers this->SetNumberOfInformationObjects(0); // copy the data for (int i = 0; i < from->GetNumberOfInformationObjects(); ++i) { vtkInformation *fromI = from->GetInformationObject(i); this->SetInformationObject(i,fromI); } } //---------------------------------------------------------------------------- void vtkInformationVector::Register(vtkObjectBase* o) { this->RegisterInternal(o, 1); } //---------------------------------------------------------------------------- void vtkInformationVector::UnRegister(vtkObjectBase* o) { this->UnRegisterInternal(o, 1); } //---------------------------------------------------------------------------- void vtkInformationVector::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); for(unsigned int i=0; i < this->NumberOfInformationObjects; ++i) { vtkGarbageCollectorReport(collector, this->Internal->Vector[i], "Entry"); } }
/*========================================================================= Program: Visualization Toolkit Module: vtkInformationVector.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. =========================================================================*/ #include "vtkInformationVector.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include <vtkstd/vector> vtkCxxRevisionMacro(vtkInformationVector, "1.10"); vtkStandardNewMacro(vtkInformationVector); class vtkInformationVectorInternals { public: vtkstd::vector<vtkInformation*> Vector; ~vtkInformationVectorInternals(); }; //---------------------------------------------------------------------------- vtkInformationVectorInternals::~vtkInformationVectorInternals() { // Delete all the information objects. for(vtkstd::vector<vtkInformation*>::iterator i = this->Vector.begin(); i != this->Vector.end(); ++i) { if(vtkInformation* info = *i) { info->Delete(); } } } //---------------------------------------------------------------------------- vtkInformationVector::vtkInformationVector() { this->Internal = new vtkInformationVectorInternals; this->NumberOfInformationObjects = 0; } //---------------------------------------------------------------------------- vtkInformationVector::~vtkInformationVector() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkInformationVector::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Number of Information Objects: " << this->NumberOfInformationObjects << "\n"; os << indent << "Information Objects:\n"; for(int i=0; i < this->NumberOfInformationObjects; ++i) { vtkInformation* info = this->GetInformationObject(i); vtkIndent nextIndent = indent.GetNextIndent(); os << nextIndent << info->GetClassName() << "(" << info << "):\n"; info->PrintSelf(os, nextIndent.GetNextIndent()); } } //---------------------------------------------------------------------------- void vtkInformationVector::SetNumberOfInformationObjects(int newNumber) { // Adjust the number of objects. int oldNumber = this->NumberOfInformationObjects; if(newNumber > oldNumber) { // Create new information objects. this->Internal->Vector.resize(newNumber, 0); for(int i=oldNumber; i < newNumber; ++i) { this->Internal->Vector[i] = vtkInformation::New(); } } else if(newNumber < oldNumber) { // Delete old information objects. for(int i=newNumber; i < oldNumber; ++i) { if(vtkInformation* info = this->Internal->Vector[i]) { // Set the pointer to NULL first to avoid reporting of the // entry if deleting the information object causes a garbage // collection reference walk. this->Internal->Vector[i] = 0; info->Delete(); } } this->Internal->Vector.resize(newNumber); } this->NumberOfInformationObjects = newNumber; } //---------------------------------------------------------------------------- void vtkInformationVector::SetInformationObject(int index, vtkInformation* newInfo) { if(newInfo && index >= 0 && index < this->NumberOfInformationObjects) { // Replace an existing information object. vtkInformation* oldInfo = this->Internal->Vector[index]; if(oldInfo != newInfo) { newInfo->Register(this); this->Internal->Vector[index] = newInfo; oldInfo->UnRegister(this); } } else if(newInfo && index >= this->NumberOfInformationObjects) { // If a hole will be created fill it with empty objects. if(index > this->NumberOfInformationObjects) { this->SetNumberOfInformationObjects(index); } // Store the information object in a new entry. newInfo->Register(this); this->Internal->Vector.push_back(newInfo); this->NumberOfInformationObjects++; } else if(!newInfo && index >= 0 && index < this->NumberOfInformationObjects-1) { // We do not allow NULL information objects. Create an empty one // to fill in the hole. vtkInformation* oldInfo = this->Internal->Vector[index]; this->Internal->Vector[index] = vtkInformation::New(); oldInfo->UnRegister(this); } else if(!newInfo && index >= 0 && index == this->NumberOfInformationObjects-1) { // Remove the last information object. this->SetNumberOfInformationObjects(index); } } //---------------------------------------------------------------------------- vtkInformation* vtkInformationVector::GetInformationObject(int index) { if(index >= 0 && index < this->NumberOfInformationObjects) { return this->Internal->Vector[index]; } return 0; } //---------------------------------------------------------------------------- void vtkInformationVector::Append(vtkInformation* info) { // Setting an entry beyond the end will automatically append. this->SetInformationObject(this->NumberOfInformationObjects, info); } //---------------------------------------------------------------------------- void vtkInformationVector::Remove(vtkInformation* info) { // Search for the information object and remove it. for(int i=0; i < this->NumberOfInformationObjects; ++i) { if(this->Internal->Vector[i] == info) { this->Internal->Vector.erase(this->Internal->Vector.begin()+i); info->UnRegister(this); this->NumberOfInformationObjects--; } } } //---------------------------------------------------------------------------- void vtkInformationVector::Copy(vtkInformationVector* from, int deep) { // if deep we can reuse existing info objects if (deep) { this->SetNumberOfInformationObjects(from->GetNumberOfInformationObjects()); for (int i = 0; i < from->GetNumberOfInformationObjects(); ++i) { this->Internal->Vector[i]->Copy(from->GetInformationObject(i),deep); } return; } // otherwise it is a shallow copy and we must copy pointers this->SetNumberOfInformationObjects(0); // copy the data for (int i = 0; i < from->GetNumberOfInformationObjects(); ++i) { vtkInformation *fromI = from->GetInformationObject(i); this->SetInformationObject(i,fromI); } } //---------------------------------------------------------------------------- void vtkInformationVector::Register(vtkObjectBase* o) { this->RegisterInternal(o, 1); } //---------------------------------------------------------------------------- void vtkInformationVector::UnRegister(vtkObjectBase* o) { this->UnRegisterInternal(o, 1); } //---------------------------------------------------------------------------- void vtkInformationVector::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); for(int i=0; i < this->NumberOfInformationObjects; ++i) { vtkGarbageCollectorReport(collector, this->Internal->Vector[i], "Entry"); } }
fix warning
COMP: fix warning
C++
bsd-3-clause
demarle/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,candy7393/VTK,berendkleinhaneveld/VTK,collects/VTK,SimVascular/VTK,collects/VTK,aashish24/VTK-old,aashish24/VTK-old,candy7393/VTK,sankhesh/VTK,spthaolt/VTK,naucoin/VTKSlicerWidgets,ashray/VTK-EVM,jmerkow/VTK,naucoin/VTKSlicerWidgets,biddisco/VTK,cjh1/VTK,arnaudgelas/VTK,Wuteyan/VTK,jeffbaumes/jeffbaumes-vtk,johnkit/vtk-dev,sumedhasingla/VTK,SimVascular/VTK,demarle/VTK,jmerkow/VTK,keithroe/vtkoptix,hendradarwin/VTK,collects/VTK,hendradarwin/VTK,gram526/VTK,ashray/VTK-EVM,jeffbaumes/jeffbaumes-vtk,keithroe/vtkoptix,Wuteyan/VTK,mspark93/VTK,aashish24/VTK-old,sumedhasingla/VTK,msmolens/VTK,spthaolt/VTK,gram526/VTK,daviddoria/PointGraphsPhase1,Wuteyan/VTK,spthaolt/VTK,mspark93/VTK,johnkit/vtk-dev,johnkit/vtk-dev,berendkleinhaneveld/VTK,daviddoria/PointGraphsPhase1,daviddoria/PointGraphsPhase1,mspark93/VTK,jmerkow/VTK,mspark93/VTK,msmolens/VTK,biddisco/VTK,Wuteyan/VTK,arnaudgelas/VTK,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,SimVascular/VTK,gram526/VTK,biddisco/VTK,sankhesh/VTK,hendradarwin/VTK,spthaolt/VTK,demarle/VTK,demarle/VTK,candy7393/VTK,gram526/VTK,sgh/vtk,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,biddisco/VTK,sankhesh/VTK,aashish24/VTK-old,sumedhasingla/VTK,sumedhasingla/VTK,gram526/VTK,aashish24/VTK-old,arnaudgelas/VTK,mspark93/VTK,sankhesh/VTK,candy7393/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,cjh1/VTK,spthaolt/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,spthaolt/VTK,demarle/VTK,candy7393/VTK,sankhesh/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,mspark93/VTK,cjh1/VTK,collects/VTK,msmolens/VTK,johnkit/vtk-dev,gram526/VTK,SimVascular/VTK,mspark93/VTK,SimVascular/VTK,naucoin/VTKSlicerWidgets,naucoin/VTKSlicerWidgets,jmerkow/VTK,arnaudgelas/VTK,jmerkow/VTK,ashray/VTK-EVM,johnkit/vtk-dev,candy7393/VTK,cjh1/VTK,ashray/VTK-EVM,sgh/vtk,arnaudgelas/VTK,SimVascular/VTK,arnaudgelas/VTK,hendradarwin/VTK,sumedhasingla/VTK,johnkit/vtk-dev,candy7393/VTK,biddisco/VTK,naucoin/VTKSlicerWidgets,Wuteyan/VTK,berendkleinhaneveld/VTK,msmolens/VTK,sgh/vtk,keithroe/vtkoptix,msmolens/VTK,sankhesh/VTK,biddisco/VTK,ashray/VTK-EVM,keithroe/vtkoptix,sumedhasingla/VTK,keithroe/vtkoptix,spthaolt/VTK,gram526/VTK,jeffbaumes/jeffbaumes-vtk,SimVascular/VTK,Wuteyan/VTK,cjh1/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,demarle/VTK,keithroe/vtkoptix,sgh/vtk,collects/VTK,naucoin/VTKSlicerWidgets,demarle/VTK,sumedhasingla/VTK,hendradarwin/VTK,jeffbaumes/jeffbaumes-vtk,msmolens/VTK,mspark93/VTK,sankhesh/VTK,sgh/vtk,hendradarwin/VTK,demarle/VTK,keithroe/vtkoptix,msmolens/VTK,johnkit/vtk-dev,collects/VTK,biddisco/VTK,cjh1/VTK,msmolens/VTK,gram526/VTK,berendkleinhaneveld/VTK,aashish24/VTK-old,jeffbaumes/jeffbaumes-vtk,candy7393/VTK,ashray/VTK-EVM,SimVascular/VTK,ashray/VTK-EVM,sgh/vtk,sankhesh/VTK,keithroe/vtkoptix
df0db9dae9c8061403a9a3eafa4b9b8893fd6396
src/import/chips/ocmb/odyssey/procedures/hwp/memory/lib/phy/ody_phy_utils.C
src/import/chips/ocmb/odyssey/procedures/hwp/memory/lib/phy/ody_phy_utils.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/odyssey/procedures/hwp/memory/lib/phy/ody_phy_utils.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2022 */ /* [+] 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 */ // EKB-Mirror-To: hostboot /// /// @file ody_phy_utils.C /// @brief Odyssey PHY utility functions /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Louis Stermole <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <generic/memory/lib/utils/mss_generic_check.H> #include <lib/phy/ody_phy_utils.H> // TODO:ZEN:MST-1571 Update Odyssey PHY registers when the official values are merged into the EKB namespace mss { namespace ody { namespace phy { /// /// @brief Configure the PHY to allow/disallow register accesses via scom /// @param[in] i_target the target on which to operate /// @param[in] i_state the state to set the PHY to - either mss::states::ON_N (scom access) or mss::states::OFF_N (training access) /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode configure_phy_scom_access(const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const mss::states i_state) { // TODO:ZEN:MST-1571 Update Odyssey PHY registers when the official values are merged into the EKB // For now using the Synopsys register location documentation constexpr uint64_t MICROCONTMUXSEL = 0x000d0000; const uint64_t MICROCONTMUXSEL_IBM = convert_synopsys_to_ibm_reg_addr(MICROCONTMUXSEL); constexpr uint64_t MICROCONTMUXSEL_MICROCONTMUXSEL = 63; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, MICROCONTMUXSEL_IBM, l_data)); l_data.writeBit<MICROCONTMUXSEL_MICROCONTMUXSEL>(i_state); FAPI_TRY(fapi2::putScom(i_target, MICROCONTMUXSEL_IBM, l_data)); fapi_try_exit: return fapi2::current_err; } /// /// @brief Converts from a Synopsys register address to an IBM register address /// @param[in] i_synopsys_addr the Synopsys register address to convert /// @return The IBM register address converted from /// uint64_t convert_synopsys_to_ibm_reg_addr( const uint64_t i_synopsys_addr) { return static_cast<uint64_t>((i_synopsys_addr << 32) | 0x800000000801303f); } /// /// @brief Loads two contiguous 8-bit fields into the DMEM register format /// @param[in] i_even_field field at the even byte offset /// @param[in] i_odd_field field at the odd byte offset /// @param[in,out] io_data the register data /// void load_dmem_8bit_fields( const uint8_t i_even_field, const uint8_t i_odd_field, fapi2::buffer<uint64_t>& io_data) { constexpr uint64_t ODD_DATA = 48; constexpr uint64_t EVEN_DATA = 56; io_data.insertFromRight<ODD_DATA, BITS_PER_BYTE>(i_odd_field) .insertFromRight<EVEN_DATA, BITS_PER_BYTE>(i_even_field); } /// /// @brief Reads two contiguous 8-bit fields from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_even_field field at the even byte offset /// @param[out] o_odd_field field at the odd byte offset /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint8_t& o_even_field, uint8_t& o_odd_field) { constexpr uint64_t ODD_DATA = 48; constexpr uint64_t EVEN_DATA = 56; o_even_field = 0; o_odd_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<ODD_DATA, BITS_PER_BYTE>(o_odd_field) .extractToRight<EVEN_DATA, BITS_PER_BYTE>(o_even_field); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reads a 16-bit field from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_field the 16-bit field /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint16_t& o_field) { constexpr uint64_t SYNOPSYS_DATA = 48; constexpr uint64_t DATA_16B_LEN = 16; o_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reads a 32-bit field from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_field the 32-bit field, read in from two registers /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint32_t& o_field) { constexpr uint64_t SYNOPSYS_DATA = 48; constexpr uint64_t DATA_16B_LEN = 16; o_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + 1, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reads a 64-bit field from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_field the 64-bit field, read in from four registers /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint64_t& o_field) { constexpr uint64_t SYNOPSYS_DATA = 48; constexpr uint64_t DATA_16B_LEN = 16; o_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + 1, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + 2, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + 3, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); fapi_try_exit: return fapi2::current_err; } } // namespace phy } // namespace ody } // namespace mss
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/odyssey/procedures/hwp/memory/lib/phy/ody_phy_utils.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2022 */ /* [+] 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 */ // EKB-Mirror-To: hostboot /// /// @file ody_phy_utils.C /// @brief Odyssey PHY utility functions /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Louis Stermole <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <generic/memory/lib/utils/mss_generic_check.H> #include <lib/phy/ody_phy_utils.H> // TODO:ZEN:MST-1571 Update Odyssey PHY registers when the official values are merged into the EKB namespace mss { namespace ody { namespace phy { /// /// @brief Configure the PHY to allow/disallow register accesses via scom /// @param[in] i_target the target on which to operate /// @param[in] i_state the state to set the PHY to - either mss::states::ON_N (scom access) or mss::states::OFF_N (training access) /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode configure_phy_scom_access(const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const mss::states i_state) { // TODO:ZEN:MST-1571 Update Odyssey PHY registers when the official values are merged into the EKB // For now using the Synopsys register location documentation constexpr uint64_t MICROCONTMUXSEL = 0x000d0000; const uint64_t MICROCONTMUXSEL_IBM = convert_synopsys_to_ibm_reg_addr(MICROCONTMUXSEL); constexpr uint64_t MICROCONTMUXSEL_MICROCONTMUXSEL = 63; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, MICROCONTMUXSEL_IBM, l_data)); l_data.writeBit<MICROCONTMUXSEL_MICROCONTMUXSEL>(i_state); FAPI_TRY(fapi2::putScom(i_target, MICROCONTMUXSEL_IBM, l_data)); fapi_try_exit: return fapi2::current_err; } /// /// @brief Converts from a Synopsys register address to an IBM register address /// @param[in] i_synopsys_addr the Synopsys register address to convert /// @return The IBM register address converted from /// uint64_t convert_synopsys_to_ibm_reg_addr( const uint64_t i_synopsys_addr) { return static_cast<uint64_t>((i_synopsys_addr << 32) | 0x800000000801303f); } /// /// @brief Loads two contiguous 8-bit fields into the DMEM register format /// @param[in] i_even_field field at the even byte offset /// @param[in] i_odd_field field at the odd byte offset /// @param[in,out] io_data the register data /// void load_dmem_8bit_fields( const uint8_t i_even_field, const uint8_t i_odd_field, fapi2::buffer<uint64_t>& io_data) { constexpr uint64_t ODD_DATA = 48; constexpr uint64_t EVEN_DATA = 56; io_data.insertFromRight<ODD_DATA, BITS_PER_BYTE>(i_odd_field) .insertFromRight<EVEN_DATA, BITS_PER_BYTE>(i_even_field); } /// /// @brief Reads two contiguous 8-bit fields from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_even_field field at the even byte offset /// @param[out] o_odd_field field at the odd byte offset /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint8_t& o_even_field, uint8_t& o_odd_field) { constexpr uint64_t ODD_DATA = 48; constexpr uint64_t EVEN_DATA = 56; o_even_field = 0; o_odd_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<ODD_DATA, BITS_PER_BYTE>(o_odd_field) .extractToRight<EVEN_DATA, BITS_PER_BYTE>(o_even_field); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reads a 16-bit field from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_field the 16-bit field /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint16_t& o_field) { constexpr uint64_t SYNOPSYS_DATA = 48; constexpr uint64_t DATA_16B_LEN = 16; o_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reads a 32-bit field from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_field the 32-bit field, read in from two registers /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint32_t& o_field) { constexpr uint64_t SYNOPSYS_ADDR_INCREMENT = 0x0000000100000000; constexpr uint64_t SYNOPSYS_DATA = 48; constexpr uint64_t DATA_16B_LEN = 16; o_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + SYNOPSYS_ADDR_INCREMENT, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reads a 64-bit field from the DMEM /// @param[in] i_target the target on which to operate /// @param[in] i_addr the starting address to read from /// @param[out] o_field the 64-bit field, read in from four registers /// @return fapi2::FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode read_dmem_field( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target, const uint64_t i_addr, uint64_t& o_field) { constexpr uint64_t SYNOPSYS_ADDR_INCREMENT = 0x0000000100000000; constexpr uint64_t SYNOPSYS_DATA = 48; constexpr uint64_t DATA_16B_LEN = 16; o_field = 0; fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target, i_addr, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + SYNOPSYS_ADDR_INCREMENT, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + 2 * SYNOPSYS_ADDR_INCREMENT, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); o_field <<= DATA_16B_LEN; FAPI_TRY(fapi2::getScom(i_target, i_addr + 3 * SYNOPSYS_ADDR_INCREMENT, l_data)); l_data.extractToRight<SYNOPSYS_DATA, DATA_16B_LEN>(o_field); fapi_try_exit: return fapi2::current_err; } } // namespace phy } // namespace ody } // namespace mss
Add unit tests for Odyssey IMEM/DMEM load/read
Add unit tests for Odyssey IMEM/DMEM load/read Also fix a couple bugs: Address increment in read_dmem_field Loop parameters in ate::read_message_block Zen:MST-1617 Change-Id: I408543ff388f6437e094c007738080c84309eaba Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/132035 Tested-by: Jenkins Server <[email protected]> Tested-by: FSP CI Jenkins <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Reviewed-by: Geetha Pisapati <[email protected]> Reviewed-by: Edgar Cordero <[email protected]> Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/132044 Tested-by: Jenkins OP Build CI <[email protected]> Tested-by: Jenkins Combined Simics CI <[email protected]> Tested-by: Jenkins OP HW <[email protected]> Reviewed-by: Daniel M Crowell <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
b97499b37a1fae59978bb328d901d5d6ffa56387
tutorials/latex3.C
tutorials/latex3.C
{ //example illustrating a TPaveText with Latex inside gROOT->Reset(); TCanvas c1("c1"); TPaveText pt(.05,.1,.95,.8); pt.AddText("#frac{2s}{#pi#alpha^{2}} #frac{d#sigma}{dcos#theta} (e^{+}e^{-} #rightarrow f#bar{f} ) = \ #left| #frac{1}{1 - #Delta#alpha} #right|^{2} (1+cos^{2}#theta)"); pt.AddText("+ 4 Re #left{ #frac{2}{1 - #Delta#alpha} #chi(s) #[]{#hat{g}_{#nu}^{e}#hat{g}_{#nu}^{f} \ (1 + cos^{2}#theta) + 2 #hat{g}_{a}^{e}#hat{g}_{a}^{f} cos#theta) } #right}"); pt.AddText("+ 16#left|#chi(s)#right|^{2} #left[(#hat{g}_{a}^{e}^{2} + #hat{g}_{v}^{e}^{2}) (#hat{g}_{a}^{f}^{2} + #hat{g}_{v}^{f}^{2})(1+cos^{2}#theta) + 8 #hat{g}_{a}^{e} #hat{g}_{a}^{f} #hat{g}_{v}^{e} #hat{g}_{v}^{f}cos#theta#right] "); pt.SetLabel("Born equation"); pt.Draw(); }
{ //example illustrating a TPaveText with Latex inside gROOT->Reset(); TCanvas c1("c1"); TPaveText pt(.05,.1,.95,.8); pt.AddText("#frac{2s}{#pi#alpha^{2}} #frac{d#sigma}{dcos#theta} (e^{+}e^{-} #rightarrow f#bar{f} ) = \ #left| #frac{1}{1 - #Delta#alpha} #right|^{2} (1+cos^{2}#theta)"); pt.AddText("+ 4 Re #left{ #frac{2}{1 - #Delta#alpha} #chi(s) #[]{#hat{g}_{#nu}^{e}#hat{g}_{#nu}^{f} \ (1 + cos^{2}#theta) + 2 #hat{g}_{a}^{e}#hat{g}_{a}^{f} cos#theta) } #right}"); pt.AddText("+ 16#left|#chi(s)#right|^{2}\ #left[(#hat{g}_{a}^{e}^{2} + #hat{g}_{v}^{e}^{2})\ (#hat{g}_{a}^{f}^{2} + #hat{g}_{v}^{f}^{2})(1+cos^{2}#theta)\ + 8 #hat{g}_{a}^{e} #hat{g}_{a}^{f} #hat{g}_{v}^{e} #hat{g}_{v}^{f}cos#theta#right] "); pt.SetLabel("Born equation"); pt.Draw(); }
Add missing "\" at the end of the lines continuing the definition of a string in the next line(s).
Add missing "\" at the end of the lines continuing the definition of a string in the next line(s). git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@12577 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
mhuwiler/rootauto,olifre/root,tc3t/qoot,veprbl/root,Dr15Jones/root,dfunke/root,cxx-hep/root-cern,arch1tect0r/root,alexschlueter/cern-root,BerserkerTroll/root,simonpf/root,mhuwiler/rootauto,sawenzel/root,lgiommi/root,bbockelm/root,root-mirror/root,pspe/root,krafczyk/root,esakellari/root,sirinath/root,georgtroska/root,bbockelm/root,gganis/root,zzxuanyuan/root,sbinet/cxx-root,mattkretz/root,CristinaCristescu/root,mkret2/root,zzxuanyuan/root-compressor-dummy,tc3t/qoot,gganis/root,pspe/root,veprbl/root,mhuwiler/rootauto,esakellari/my_root_for_test,satyarth934/root,cxx-hep/root-cern,zzxuanyuan/root,esakellari/root,0x0all/ROOT,perovic/root,sirinath/root,dfunke/root,BerserkerTroll/root,gbitzes/root,mattkretz/root,sbinet/cxx-root,buuck/root,jrtomps/root,buuck/root,esakellari/root,abhinavmoudgil95/root,CristinaCristescu/root,BerserkerTroll/root,mkret2/root,jrtomps/root,mkret2/root,olifre/root,sirinath/root,thomaskeck/root,BerserkerTroll/root,agarciamontoro/root,BerserkerTroll/root,simonpf/root,karies/root,buuck/root,mattkretz/root,CristinaCristescu/root,zzxuanyuan/root,mhuwiler/rootauto,nilqed/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,veprbl/root,arch1tect0r/root,pspe/root,olifre/root,davidlt/root,sirinath/root,jrtomps/root,bbockelm/root,ffurano/root5,CristinaCristescu/root,gbitzes/root,jrtomps/root,mkret2/root,Dr15Jones/root,arch1tect0r/root,agarciamontoro/root,buuck/root,Y--/root,pspe/root,davidlt/root,omazapa/root-old,satyarth934/root,kirbyherm/root-r-tools,BerserkerTroll/root,karies/root,lgiommi/root,abhinavmoudgil95/root,mkret2/root,pspe/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,esakellari/my_root_for_test,satyarth934/root,smarinac/root,vukasinmilosevic/root,Y--/root,agarciamontoro/root,veprbl/root,mkret2/root,Dr15Jones/root,beniz/root,gbitzes/root,karies/root,0x0all/ROOT,karies/root,zzxuanyuan/root,nilqed/root,vukasinmilosevic/root,strykejern/TTreeReader,smarinac/root,krafczyk/root,alexschlueter/cern-root,sirinath/root,pspe/root,evgeny-boger/root,olifre/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,vukasinmilosevic/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,nilqed/root,olifre/root,strykejern/TTreeReader,BerserkerTroll/root,Duraznos/root,dfunke/root,simonpf/root,nilqed/root,strykejern/TTreeReader,perovic/root,simonpf/root,omazapa/root-old,veprbl/root,perovic/root,omazapa/root,0x0all/ROOT,pspe/root,evgeny-boger/root,satyarth934/root,davidlt/root,tc3t/qoot,arch1tect0r/root,omazapa/root,mhuwiler/rootauto,root-mirror/root,Duraznos/root,alexschlueter/cern-root,strykejern/TTreeReader,beniz/root,olifre/root,cxx-hep/root-cern,tc3t/qoot,abhinavmoudgil95/root,beniz/root,omazapa/root-old,veprbl/root,olifre/root,pspe/root,omazapa/root-old,veprbl/root,lgiommi/root,zzxuanyuan/root-compressor-dummy,sbinet/cxx-root,esakellari/my_root_for_test,beniz/root,gbitzes/root,Duraznos/root,tc3t/qoot,perovic/root,simonpf/root,lgiommi/root,esakellari/root,0x0all/ROOT,esakellari/root,thomaskeck/root,sawenzel/root,sawenzel/root,beniz/root,omazapa/root,gbitzes/root,evgeny-boger/root,lgiommi/root,olifre/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,omazapa/root,0x0all/ROOT,olifre/root,CristinaCristescu/root,krafczyk/root,perovic/root,sawenzel/root,abhinavmoudgil95/root,mattkretz/root,esakellari/my_root_for_test,alexschlueter/cern-root,lgiommi/root,mkret2/root,jrtomps/root,buuck/root,veprbl/root,nilqed/root,zzxuanyuan/root,jrtomps/root,abhinavmoudgil95/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,jrtomps/root,veprbl/root,abhinavmoudgil95/root,dfunke/root,smarinac/root,sawenzel/root,strykejern/TTreeReader,satyarth934/root,bbockelm/root,tc3t/qoot,veprbl/root,Dr15Jones/root,nilqed/root,Duraznos/root,smarinac/root,beniz/root,root-mirror/root,georgtroska/root,satyarth934/root,tc3t/qoot,Y--/root,dfunke/root,smarinac/root,zzxuanyuan/root,Duraznos/root,mattkretz/root,Duraznos/root,vukasinmilosevic/root,CristinaCristescu/root,pspe/root,esakellari/my_root_for_test,davidlt/root,georgtroska/root,vukasinmilosevic/root,BerserkerTroll/root,evgeny-boger/root,omazapa/root,gbitzes/root,gganis/root,sawenzel/root,cxx-hep/root-cern,kirbyherm/root-r-tools,jrtomps/root,omazapa/root,omazapa/root-old,esakellari/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,esakellari/my_root_for_test,cxx-hep/root-cern,tc3t/qoot,davidlt/root,omazapa/root-old,strykejern/TTreeReader,sbinet/cxx-root,simonpf/root,omazapa/root-old,georgtroska/root,agarciamontoro/root,dfunke/root,0x0all/ROOT,ffurano/root5,karies/root,cxx-hep/root-cern,Y--/root,mattkretz/root,sirinath/root,evgeny-boger/root,vukasinmilosevic/root,alexschlueter/cern-root,BerserkerTroll/root,pspe/root,simonpf/root,buuck/root,bbockelm/root,omazapa/root-old,mattkretz/root,krafczyk/root,CristinaCristescu/root,evgeny-boger/root,arch1tect0r/root,abhinavmoudgil95/root,krafczyk/root,perovic/root,bbockelm/root,gganis/root,omazapa/root,agarciamontoro/root,kirbyherm/root-r-tools,simonpf/root,esakellari/my_root_for_test,vukasinmilosevic/root,sawenzel/root,buuck/root,Y--/root,root-mirror/root,perovic/root,tc3t/qoot,satyarth934/root,omazapa/root,sawenzel/root,mkret2/root,tc3t/qoot,esakellari/root,esakellari/root,mkret2/root,krafczyk/root,veprbl/root,Y--/root,simonpf/root,root-mirror/root,omazapa/root-old,mhuwiler/rootauto,karies/root,zzxuanyuan/root,Dr15Jones/root,Duraznos/root,sirinath/root,krafczyk/root,root-mirror/root,davidlt/root,sbinet/cxx-root,gganis/root,Duraznos/root,vukasinmilosevic/root,evgeny-boger/root,Y--/root,abhinavmoudgil95/root,krafczyk/root,CristinaCristescu/root,buuck/root,abhinavmoudgil95/root,nilqed/root,evgeny-boger/root,mkret2/root,esakellari/my_root_for_test,karies/root,Duraznos/root,krafczyk/root,thomaskeck/root,nilqed/root,buuck/root,CristinaCristescu/root,smarinac/root,vukasinmilosevic/root,thomaskeck/root,pspe/root,simonpf/root,ffurano/root5,lgiommi/root,bbockelm/root,georgtroska/root,zzxuanyuan/root,gganis/root,gganis/root,mkret2/root,agarciamontoro/root,smarinac/root,arch1tect0r/root,Y--/root,agarciamontoro/root,beniz/root,thomaskeck/root,strykejern/TTreeReader,agarciamontoro/root,Y--/root,zzxuanyuan/root-compressor-dummy,kirbyherm/root-r-tools,beniz/root,mattkretz/root,arch1tect0r/root,mhuwiler/rootauto,Duraznos/root,perovic/root,dfunke/root,lgiommi/root,ffurano/root5,karies/root,dfunke/root,sirinath/root,buuck/root,thomaskeck/root,alexschlueter/cern-root,jrtomps/root,davidlt/root,mattkretz/root,jrtomps/root,lgiommi/root,satyarth934/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,gbitzes/root,esakellari/root,esakellari/my_root_for_test,buuck/root,smarinac/root,davidlt/root,dfunke/root,perovic/root,Y--/root,root-mirror/root,georgtroska/root,sawenzel/root,mhuwiler/rootauto,Dr15Jones/root,thomaskeck/root,arch1tect0r/root,dfunke/root,mhuwiler/rootauto,Y--/root,abhinavmoudgil95/root,omazapa/root,perovic/root,olifre/root,karies/root,vukasinmilosevic/root,beniz/root,arch1tect0r/root,gbitzes/root,arch1tect0r/root,sirinath/root,arch1tect0r/root,agarciamontoro/root,beniz/root,georgtroska/root,georgtroska/root,evgeny-boger/root,gbitzes/root,smarinac/root,davidlt/root,CristinaCristescu/root,bbockelm/root,mattkretz/root,karies/root,karies/root,satyarth934/root,agarciamontoro/root,davidlt/root,sawenzel/root,Dr15Jones/root,zzxuanyuan/root,sbinet/cxx-root,georgtroska/root,zzxuanyuan/root,perovic/root,ffurano/root5,cxx-hep/root-cern,georgtroska/root,CristinaCristescu/root,sbinet/cxx-root,bbockelm/root,sbinet/cxx-root,nilqed/root,BerserkerTroll/root,georgtroska/root,omazapa/root-old,root-mirror/root,0x0all/ROOT,esakellari/root,sawenzel/root,gbitzes/root,gganis/root,gbitzes/root,cxx-hep/root-cern,root-mirror/root,nilqed/root,omazapa/root-old,gganis/root,olifre/root,davidlt/root,satyarth934/root,mhuwiler/rootauto,ffurano/root5,root-mirror/root,omazapa/root,lgiommi/root,krafczyk/root,mattkretz/root,esakellari/root,sirinath/root,gganis/root,0x0all/ROOT,sbinet/cxx-root,kirbyherm/root-r-tools,ffurano/root5,abhinavmoudgil95/root,BerserkerTroll/root,thomaskeck/root,simonpf/root,omazapa/root,Duraznos/root,lgiommi/root,satyarth934/root,evgeny-boger/root,gganis/root,dfunke/root,nilqed/root,krafczyk/root,esakellari/my_root_for_test,kirbyherm/root-r-tools,agarciamontoro/root,0x0all/ROOT,alexschlueter/cern-root,smarinac/root,thomaskeck/root,beniz/root,sirinath/root,kirbyherm/root-r-tools,sbinet/cxx-root,bbockelm/root
5b5718eb32655b93d556cff0bdc8762524e0ba94
app/src/Main.cpp
app/src/Main.cpp
#include <docopt.h> #include <iostream> #include <utility> #include <nsearch/Sequence.h> #include <nsearch/FASTQ/Writer.h> #include <nsearch/FASTA/Reader.h> #include <nsearch/PairedEnd/Merger.h> #include <nsearch/PairedEnd/Reader.h> #include <nsearch/Database.h> #include <nsearch/Aligner.h> #include <nsearch/Alignment/ExtendAlign.h> #include <nsearch/Alignment/BandedAlign.h> #include "Stats.h" #include "WorkerQueue.h" Stats gStats; static const char USAGE[] = R"( Process and search sequences. Usage: nsearch merge <forward.fastq> <reverse.fastq> <merged.fastq> nsearch search <query.fasta> <database.fasta> )"; void PrintProgressLine( size_t numProcessedReads, size_t numTotalReads ) { static int PROGRESS_BAR_WIDTH = 50; double done = double( numProcessedReads ) / double( numTotalReads ); int pos = done * PROGRESS_BAR_WIDTH; std::cout << "\r["; std::cout << std::string( pos, '=' ); if( done < 1.0 ) std::cout << '>'; std::cout << std::string( std::max( PROGRESS_BAR_WIDTH - pos - 1, 0 ), ' ' ); std::cout << "] "; printf( " %.1f%%", done * 100.0 ); std::cout << std::flush; } void PrintSummaryLine( double value, const char *line, double total = 0.0 ) { printf( "%10.1f %s", value, line ); if( total > 0.0 ) { printf( " (%.1f%%)", value / total * 100.0 ); } printf( "\n" ); } class QueuedWriter : public WorkerQueue< SequenceList > { public: QueuedWriter( const std::string &path ) : WorkerQueue( 1 ), mWriter( path ) { } protected: void Process( const SequenceList &list ) { for( auto seq : list ) { mWriter << seq; } } private: FASTQ::Writer mWriter; }; class QueuedMerger : public WorkerQueue< std::pair< SequenceList, SequenceList > > { public: QueuedMerger( QueuedWriter &writer ) : WorkerQueue( -1 ), mWriter( writer ) { } protected: void Process( const std::pair< SequenceList, SequenceList > &queueItem ) { const SequenceList &fwd = queueItem.first; const SequenceList &rev = queueItem.second; const PairedEnd::Merger &merger = mMerger; Sequence mergedRead; SequenceList mergedReads; auto fit = fwd.begin(); auto rit = rev.begin(); while( fit != fwd.end() && rit != rev.end() ) { if( merger.Merge( mergedRead, *fit, *rit ) ) { gStats.numMerged++; gStats.mergedReadsTotalLength += mergedRead.Length(); mergedReads.push_back( std::move( mergedRead ) ); } gStats.numProcessed++; ++fit; ++rit; } if( !mergedReads.empty() ) mWriter.Enqueue( mergedReads ); } private: QueuedWriter &mWriter; PairedEnd::Merger mMerger; }; bool Merge( const std::string &fwdPath, const std::string &revPath, const std::string &mergedPath ) { PairedEnd::Reader reader( fwdPath, revPath ); QueuedWriter writer( mergedPath ); QueuedMerger merger( writer ); SequenceList fwdReads, revReads; while( !reader.EndOfFile() ) { reader.Read( fwdReads, revReads, 512 ); auto pair = std::pair< SequenceList, SequenceList >( std::move( fwdReads ), std::move( revReads ) ); merger.Enqueue( pair ); PrintProgressLine( reader.NumBytesRead(), reader.NumBytesTotal() ); } merger.WaitTillDone(); writer.WaitTillDone(); return true; } bool Search( const std::string &queryPath, const std::string &databasePath ) { Sequence seq; Database db( 8 ); FASTA::Reader dbReader( databasePath ); std::cout << "Indexing DB" << std::endl; while( !dbReader.EndOfFile() ) { dbReader >> seq; db.AddSequence( seq ); } std::cout << "Querying DB" << std::endl; FASTA::Reader qryReader( queryPath ); while( !qryReader.EndOfFile() ) { qryReader >> seq; SequenceList candidates = db.Query( seq ); /* std::cout << seq.identifier << std::endl; */ /* for( auto &candidate : candidates ) { */ /* std::cout << " " << candidate.identifier << std::endl; */ /* } */ /* std::cout << "===" << std::endl; */ } return true; } int main( int argc, const char **argv ) { std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc }, true, // help "nsearch"); // Test cases // A>>>>B // B>>>>A // Empty A // empty B // A breaking case when first row is not initialized properly (beyond bandwidth) // THIS CASE: /* Sequence A = "AAAAAAAAAAAAAAA"; */ /* Sequence B = "CCCCCCAAAAAAAAA"; */ /* int score = ba.Align( A, B, &cig, 0, 0, AlignmentDirection::forwards ); */ /* std::cout << score << std::endl; */ /* std::cout << cig << std::endl; */ /* std::cout << A.sequence << std::endl; */ /* A = "CCCCCCCCCCCCCCC"; */ /* B = "CCCCCCAAAAAAAAA"; */ /* score = ba.Align( A, B, &cig, 0, 0, AlignmentDirection::forwards ); */ /* std::cout << score << std::endl; */ /* std::cout << cig << std::endl; */ /* std::cout << A.sequence << std::endl; */ // TEST CASE FOR WHEN STARTA>>>LENA /* BandedAlignParams bap; */ /* BandedAlign ba( bap ); */ /* Cigar cig; */ /* Sequence A = "ATGCC"; */ /* Sequence B = "XXXATGCC"; */ /* int score = ba.Align( A, B, &cig, AlignmentDirection::forwards, 6, 3 ); */ /* std::cout << score << std::endl; */ /* std::cout << cig << std::endl; */ /* std::cout << A.sequence << std::endl; */ /* return 0; */ /* ExtendAlign ea; */ /* ExtendedAlignment aln; */ /* Sequence A = "AATTT"; */ /* Sequence B = "GGGGT"; */ /* size_t bestA, bestB; */ /* Cigar cigar; */ /* int score = ea.Extend( A, B, &bestA, &bestB, &cigar, AlignmentDirection::backwards, A.Length(), B.Length() ); */ /* std::cout << score << std::endl; */ /* std::cout << aln.cigar << std::endl; */ /* std::cout << bestA << ", " << bestB << std::endl; */ if( args[ "search" ].asBool() ) { gStats.StartTimer(); Search( args[ "<query.fasta>" ].asString(), args[ "<database.fasta>" ].asString() ); gStats.StopTimer(); std::cout << std::endl; std::cout << "Summary:" << std::endl; PrintSummaryLine( gStats.ElapsedMillis() / 1000.0, "Seconds" ); } if( args[ "merge" ].asBool() ) { gStats.StartTimer(); Merge( args[ "<forward.fastq>" ].asString(), args[ "<reverse.fastq>" ].asString(), args[ "<merged.fastq>" ].asString() ); gStats.StopTimer(); std::cout << std::endl; std::cout << "Summary:" << std::endl; PrintSummaryLine( gStats.ElapsedMillis() / 1000.0, "Seconds" ); PrintSummaryLine( gStats.numProcessed / gStats.ElapsedMillis(), "Processed/ms" ); PrintSummaryLine( gStats.numProcessed, "Pairs" ); PrintSummaryLine( gStats.numMerged, "Merged", gStats.numProcessed ); PrintSummaryLine( gStats.MeanMergedLength(), "Mean merged length" ); } return 0; }
#include <docopt.h> #include <iostream> #include <utility> #include <nsearch/Sequence.h> #include <nsearch/FASTQ/Writer.h> #include <nsearch/FASTA/Reader.h> #include <nsearch/PairedEnd/Merger.h> #include <nsearch/PairedEnd/Reader.h> #include <nsearch/Database.h> #include <nsearch/Aligner.h> #include <nsearch/Alignment/ExtendAlign.h> #include <nsearch/Alignment/BandedAlign.h> #include "Stats.h" #include "WorkerQueue.h" Stats gStats; static const char USAGE[] = R"( Process and search sequences. Usage: nsearch merge <forward.fastq> <reverse.fastq> <merged.fastq> nsearch search <query.fasta> <database.fasta> )"; void PrintProgressLine( size_t numProcessedReads, size_t numTotalReads ) { static int PROGRESS_BAR_WIDTH = 50; double done = double( numProcessedReads ) / double( numTotalReads ); int pos = done * PROGRESS_BAR_WIDTH; std::cout << "\r["; std::cout << std::string( pos, '=' ); if( done < 1.0 ) std::cout << '>'; std::cout << std::string( std::max( PROGRESS_BAR_WIDTH - pos - 1, 0 ), ' ' ); std::cout << "] "; printf( " %.1f%%", done * 100.0 ); std::cout << std::flush; } void PrintSummaryLine( double value, const char *line, double total = 0.0 ) { printf( "%10.1f %s", value, line ); if( total > 0.0 ) { printf( " (%.1f%%)", value / total * 100.0 ); } printf( "\n" ); } class QueuedWriter : public WorkerQueue< SequenceList > { public: QueuedWriter( const std::string &path ) : WorkerQueue( 1 ), mWriter( path ) { } protected: void Process( const SequenceList &list ) { for( auto seq : list ) { mWriter << seq; } } private: FASTQ::Writer mWriter; }; class QueuedMerger : public WorkerQueue< std::pair< SequenceList, SequenceList > > { public: QueuedMerger( QueuedWriter &writer ) : WorkerQueue( -1 ), mWriter( writer ) { } protected: void Process( const std::pair< SequenceList, SequenceList > &queueItem ) { const SequenceList &fwd = queueItem.first; const SequenceList &rev = queueItem.second; const PairedEnd::Merger &merger = mMerger; Sequence mergedRead; SequenceList mergedReads; auto fit = fwd.begin(); auto rit = rev.begin(); while( fit != fwd.end() && rit != rev.end() ) { if( merger.Merge( mergedRead, *fit, *rit ) ) { gStats.numMerged++; gStats.mergedReadsTotalLength += mergedRead.Length(); mergedReads.push_back( std::move( mergedRead ) ); } gStats.numProcessed++; ++fit; ++rit; } if( !mergedReads.empty() ) mWriter.Enqueue( mergedReads ); } private: QueuedWriter &mWriter; PairedEnd::Merger mMerger; }; bool Merge( const std::string &fwdPath, const std::string &revPath, const std::string &mergedPath ) { PairedEnd::Reader reader( fwdPath, revPath ); QueuedWriter writer( mergedPath ); QueuedMerger merger( writer ); SequenceList fwdReads, revReads; while( !reader.EndOfFile() ) { reader.Read( fwdReads, revReads, 512 ); auto pair = std::pair< SequenceList, SequenceList >( std::move( fwdReads ), std::move( revReads ) ); merger.Enqueue( pair ); PrintProgressLine( reader.NumBytesRead(), reader.NumBytesTotal() ); } merger.WaitTillDone(); writer.WaitTillDone(); return true; } bool Search( const std::string &queryPath, const std::string &databasePath ) { Sequence seq; // TODO: Different word sizes for indexing & alignment! Database db( 8 ); FASTA::Reader dbReader( databasePath ); std::cout << "Indexing DB" << std::endl; while( !dbReader.EndOfFile() ) { dbReader >> seq; db.AddSequence( seq ); } std::cout << "Querying DB" << std::endl; FASTA::Reader qryReader( queryPath ); while( !qryReader.EndOfFile() ) { qryReader >> seq; SequenceList candidates = db.Query( seq ); /* std::cout << seq.identifier << std::endl; */ /* for( auto &candidate : candidates ) { */ /* std::cout << " " << candidate.identifier << std::endl; */ /* } */ /* std::cout << "===" << std::endl; */ } return true; } int main( int argc, const char **argv ) { std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc }, true, // help "nsearch"); // Test cases // A>>>>B // B>>>>A // Empty A // empty B // A breaking case when first row is not initialized properly (beyond bandwidth) // THIS CASE: /* Sequence A = "AAAAAAAAAAAAAAA"; */ /* Sequence B = "CCCCCCAAAAAAAAA"; */ /* int score = ba.Align( A, B, &cig, 0, 0, AlignmentDirection::forwards ); */ /* std::cout << score << std::endl; */ /* std::cout << cig << std::endl; */ /* std::cout << A.sequence << std::endl; */ /* A = "CCCCCCCCCCCCCCC"; */ /* B = "CCCCCCAAAAAAAAA"; */ /* score = ba.Align( A, B, &cig, 0, 0, AlignmentDirection::forwards ); */ /* std::cout << score << std::endl; */ /* std::cout << cig << std::endl; */ /* std::cout << A.sequence << std::endl; */ // TEST CASE FOR WHEN STARTA>>>LENA /* BandedAlignParams bap; */ /* BandedAlign ba( bap ); */ /* Cigar cig; */ /* Sequence A = "ATGCC"; */ /* Sequence B = "XXXATGCC"; */ /* int score = ba.Align( A, B, &cig, AlignmentDirection::forwards, 6, 3 ); */ /* std::cout << score << std::endl; */ /* std::cout << cig << std::endl; */ /* std::cout << A.sequence << std::endl; */ /* return 0; */ /* ExtendAlign ea; */ /* ExtendedAlignment aln; */ /* Sequence A = "AATTT"; */ /* Sequence B = "GGGGT"; */ /* size_t bestA, bestB; */ /* Cigar cigar; */ /* int score = ea.Extend( A, B, &bestA, &bestB, &cigar, AlignmentDirection::backwards, A.Length(), B.Length() ); */ /* std::cout << score << std::endl; */ /* std::cout << aln.cigar << std::endl; */ /* std::cout << bestA << ", " << bestB << std::endl; */ if( args[ "search" ].asBool() ) { gStats.StartTimer(); Search( args[ "<query.fasta>" ].asString(), args[ "<database.fasta>" ].asString() ); gStats.StopTimer(); std::cout << std::endl; std::cout << "Summary:" << std::endl; PrintSummaryLine( gStats.ElapsedMillis() / 1000.0, "Seconds" ); } if( args[ "merge" ].asBool() ) { gStats.StartTimer(); Merge( args[ "<forward.fastq>" ].asString(), args[ "<reverse.fastq>" ].asString(), args[ "<merged.fastq>" ].asString() ); gStats.StopTimer(); std::cout << std::endl; std::cout << "Summary:" << std::endl; PrintSummaryLine( gStats.ElapsedMillis() / 1000.0, "Seconds" ); PrintSummaryLine( gStats.numProcessed / gStats.ElapsedMillis(), "Processed/ms" ); PrintSummaryLine( gStats.numProcessed, "Pairs" ); PrintSummaryLine( gStats.numMerged, "Merged", gStats.numProcessed ); PrintSummaryLine( gStats.MeanMergedLength(), "Mean merged length" ); } return 0; }
Add todo
Add todo
C++
bsd-3-clause
stevschmid/nsearch
87563a030e1f7836f5349fc4864e3a6fc6271621
app/src/main.cpp
app/src/main.cpp
/* Copyright (C) 2016 INRA * * 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 <fstream> #include <sstream> #include <limits> #include <experimental/optional> #include <lpcore> #include <cstdio> #include <cerrno> #include <cstring> #include <getopt.h> namespace std { using experimental::optional; using experimental::make_optional; }; const char* file_format_error_format(lp::file_format_error::tag); const char* problem_definition_error_format(lp::problem_definition_error::tag); const char* solver_error_format(lp::solver_error::tag); void help() { std::fprintf(stdout, "--help|-h This help message\n" "--kappa|-k real Set Kappa parameter\n" "--delta|-d real Set Delta parameter\n" "--theta|-t real Set Theta parameter\n" "--limit int Set limit\n" "--quiet Remove any verbose message\n" "--verbose|-v int Set verbose level\n"); } std::optional<double> to_double(const char* s, double min, double max) { char *c; errno = 0; double value = std::strtof(s, &c); if ((errno == ERANGE and (value == std::numeric_limits<double>::lowest() or value == -std::numeric_limits<double>::max())) or (errno != 0 and value == 0) or (c == ::optarg) or (value < min) or (value > max)) return std::make_optional(value); return std::optional<double>{}; } std::optional<long> to_long(const char* s, long min, long max) { char *c; errno = 0; long value = std::strtol(s, &c, 10); if ((errno == ERANGE and (value == std::numeric_limits<long>::lowest() or value == std::numeric_limits<long>::max())) or (errno != 0 and value == 0) or (c == ::optarg) or (value < min) or (value > max)) return std::make_optional(value); return std::optional<long>{}; } int main(int argc, char *argv[]) { const char* const short_opts = "hk:d:t:l:qv:"; const struct option long_opts[] = { {"help", 0, nullptr, 'h'}, {"kappa", 1, nullptr, 'k'}, {"delta", 1, nullptr, 'd'}, {"theta", 1, nullptr, 't'}, {"limit", 1, nullptr, 'l'}, {"quiet", 0, nullptr, 0}, {"verbose", 1, nullptr, 'v'}, {0, 0, nullptr, 0}}; int opt_index; double kappa = 0.001; double delta = 0.0001; double theta = 0.001; int verbose = 1; long limit = 1000; bool fail = false; bool quiet = false; while (not fail) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, &opt_index); if (opt == -1) break; switch (opt) { case 0: break; case 'h': help(); return EXIT_SUCCESS; case 'k': { auto val = to_double(::optarg, 0, 1); if (not val) std::fprintf(stderr, "fail to convert parameter `%s' for " " parameter kappa (or k)\n", ::optarg); else kappa = *val; } break; case 'd': { auto val = to_double(::optarg, 0, std::numeric_limits<double>::max()); if (not val) std::fprintf(stderr, "fail to convert parameter `%s' for" " parameter delta (or d)\n", ::optarg); else delta = *val; } break; case 't': { auto val = to_double(::optarg, 0, 1); if (not val) std::fprintf(stderr, "fail to convert parameter `%s' for" " parameter theta (or t)\n", ::optarg); else theta = *val; } break; case 'l': { auto val = to_long(::optarg, 0, std::numeric_limits<long>::max()); if (not val) std::fprintf(stderr, "fail to convert parameter `%s' for" " parameterffff limit (or l)\n", ::optarg); else limit = *val; } break; case '?': default: fail = true; std::fprintf(stderr, "Unknown command line option\n"); break; }; } if (fail) return EXIT_FAILURE; (void)verbose; (void)quiet; for (int i = ::optind; i < argc; ++i) { try { auto pb = lp::make_problem(argv[i]); std::map<std::string, lp::parameter> params; params["kappa"] = kappa; params["theta"] = theta; params["delta"] = delta; params["limit"] = limit; auto ret = lp::solve(pb, params); for (std::size_t i {0}, e {ret.variable_name.size()}; i != e; ++i) std::fprintf(stdout, "%s = %d\n", ret.variable_name[i].c_str(), ret.variable_value[i]); } catch(const lp::precondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch(const lp::postcondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch(const lp::numeric_cast_error& e) { std::fprintf(stderr, "numeric cast interal failure\n"); } catch(const lp::file_access_error& e) { std::fprintf(stderr, "file `%s' fail %d: %s\n", e.file().c_str(), e.error(), std::strerror(e.error())); } catch(const lp::file_format_error& e) { std::fprintf(stderr, "file format error at line %d column %d " "%s\n", e.line(), e.column(), file_format_error_format(e.failure())); } catch(const lp::problem_definition_error& e) { std::fprintf(stderr, "definition problem error at %s: %s\n", e.element().c_str(), problem_definition_error_format(e.failure())); } catch(const lp::solver_error& e) { std::fprintf(stderr, "solver error: %s\n", solver_error_format(e.failure())); } catch(const std::exception& e) { std::fprintf(stderr, "failure: %s.\n", e.what()); } } return EXIT_SUCCESS; } const char* file_format_error_format(lp::file_format_error::tag failure) { static const char *const tag[] = { "end of file", "unknown", "already defined", "incomplete", "bad name", "bad operator", "bad integer", "bad objective function type", "bad bound", "bad function element", "bad constraint" }; switch(failure) { case lp::file_format_error::tag::end_of_file: return tag[0]; case lp::file_format_error::tag::unknown: return tag[1]; case lp::file_format_error::tag::already_defined: return tag[2]; case lp::file_format_error::tag::incomplete: return tag[3]; case lp::file_format_error::tag::bad_name: return tag[4]; case lp::file_format_error::tag::bad_operator: return tag[5]; case lp::file_format_error::tag::bad_integer: return tag[6]; case lp::file_format_error::tag::bad_objective_function_type: return tag[7]; case lp::file_format_error::tag::bad_bound: return tag[8]; case lp::file_format_error::tag::bad_function_element: return tag[9]; case lp::file_format_error::tag::bad_constraint : return tag[10]; } return nullptr; } const char* problem_definition_error_format(lp::problem_definition_error::tag failure) { static const char *const tag[] = { "empty variables", "empty objective function", "variable not used", "bad bound" }; switch (failure) { case lp::problem_definition_error::tag::empty_variables: return tag[0]; case lp::problem_definition_error::tag::empty_objective_function: return tag[1]; case lp::problem_definition_error::tag::variable_not_used: return tag[2]; case lp::problem_definition_error::tag::bad_bound: return tag[3]; } return nullptr; } const char* solver_error_format(lp::solver_error::tag failure) { static const char *const tag[] = { "no solver available", "not enough memory" }; switch (failure) { case lp::solver_error::tag::no_solver_available: return tag[0]; case lp::solver_error::tag::not_enough_memory: return tag[1]; } return nullptr; }
/* Copyright (C) 2016 INRA * * 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 <fstream> #include <sstream> #include <limits> #include <experimental/optional> #include <lpcore> #include <cstdio> #include <cerrno> #include <cstring> #include <getopt.h> namespace std { using experimental::optional; using experimental::make_optional; }; std::tuple<std::string, std::string> split_param(const char *param) { std::string name, value; while (*param) { if (isalpha(*param) or *param == '_') name += *param; else break; param++; } if (*param and *param == ':') { param++; while (*param) { if (isalnum(*param) or *param == '_' or *param == ':') value += *param; else break; param++; } } return std::make_tuple(name, value); } const char* file_format_error_format(lp::file_format_error::tag); const char* problem_definition_error_format(lp::problem_definition_error::tag); const char* solver_error_format(lp::solver_error::tag); void help() { std::fprintf(stdout, "--help|-h This help message\n" "--param|-p [name]:[value] Add a new parameter (name is" " [a-z][A-Z]_ value can be a double, an integer otherwise a" " string.\n" "--limit int Set limit\n" "--quiet Remove any verbose message\n" "--verbose|-v int Set verbose level\n"); } std::optional<double> to_double(const char* s) { char *c; errno = 0; double value = std::strtof(s, &c); if ((errno == ERANGE and (value == std::numeric_limits<double>::lowest() or value == -std::numeric_limits<double>::max())) or (errno != 0 and value == 0) or (c == ::optarg) return std::make_optional(value); return std::optional<double>{}; } std::optional<long> to_long(const char* s) { char *c; errno = 0; long value = std::strtol(s, &c, 10); if ((errno == ERANGE and (value == std::numeric_limits<long>::lowest() or value == std::numeric_limits<long>::max())) or (errno != 0 and value == 0) or (c == ::optarg) return std::make_optional(value); return std::optional<long>{}; } int main(int argc, char *argv[]) { const char* const short_opts = "hp:l:qv:"; const struct option long_opts[] = { {"help", 0, nullptr, 'h'}, {"param", 1, nullptr, 'p'}, {"limit", 1, nullptr, 'l'}, {"quiet", 0, nullptr, 0}, {"verbose", 1, nullptr, 'v'}, {0, 0, nullptr, 0}}; int opt_index; int verbose = 1; long limit = 1000; bool fail = false; bool quiet = false; std::map<std::string, lp::parameter> parameters; while (not fail) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, &opt_index); if (opt == -1) break; switch (opt) { case 0: break; case 'h': help(); return EXIT_SUCCESS; case 'p': { std::string name, value; std::tie(name, value) = split_param(::optarg); if (name.empty() or value.empty()) { std::fprintf(stderr, "fail to parse parameter `%s'\n", ::optarg); break; } auto valuel = to_long(::optarg); if (valuel) { parameters[name] = * valuel; } else { auto valued = to_double(::optarg); if (valued) parameters[name] = *valued; else parameters[name] = value; } } break; case '?': default: fail = true; std::fprintf(stderr, "Unknown command line option\n"); break; }; } if (fail) return EXIT_FAILURE; (void)verbose; (void)quiet; for (int i = ::optind; i < argc; ++i) { try { auto pb = lp::make_problem(argv[i]); std::map<std::string, lp::parameter> params; params["kappa"] = kappa; params["theta"] = theta; params["delta"] = delta; params["limit"] = limit; auto ret = lp::solve(pb, params); for (std::size_t i {0}, e {ret.variable_name.size()}; i != e; ++i) std::fprintf(stdout, "%s = %d\n", ret.variable_name[i].c_str(), ret.variable_value[i]); } catch(const lp::precondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch(const lp::postcondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch(const lp::numeric_cast_error& e) { std::fprintf(stderr, "numeric cast interal failure\n"); } catch(const lp::file_access_error& e) { std::fprintf(stderr, "file `%s' fail %d: %s\n", e.file().c_str(), e.error(), std::strerror(e.error())); } catch(const lp::file_format_error& e) { std::fprintf(stderr, "file format error at line %d column %d " "%s\n", e.line(), e.column(), file_format_error_format(e.failure())); } catch(const lp::problem_definition_error& e) { std::fprintf(stderr, "definition problem error at %s: %s\n", e.element().c_str(), problem_definition_error_format(e.failure())); } catch(const lp::solver_error& e) { std::fprintf(stderr, "solver error: %s\n", solver_error_format(e.failure())); } catch(const std::exception& e) { std::fprintf(stderr, "failure: %s.\n", e.what()); } } return EXIT_SUCCESS; } const char* file_format_error_format(lp::file_format_error::tag failure) { static const char *const tag[] = { "end of file", "unknown", "already defined", "incomplete", "bad name", "bad operator", "bad integer", "bad objective function type", "bad bound", "bad function element", "bad constraint" }; switch(failure) { case lp::file_format_error::tag::end_of_file: return tag[0]; case lp::file_format_error::tag::unknown: return tag[1]; case lp::file_format_error::tag::already_defined: return tag[2]; case lp::file_format_error::tag::incomplete: return tag[3]; case lp::file_format_error::tag::bad_name: return tag[4]; case lp::file_format_error::tag::bad_operator: return tag[5]; case lp::file_format_error::tag::bad_integer: return tag[6]; case lp::file_format_error::tag::bad_objective_function_type: return tag[7]; case lp::file_format_error::tag::bad_bound: return tag[8]; case lp::file_format_error::tag::bad_function_element: return tag[9]; case lp::file_format_error::tag::bad_constraint : return tag[10]; } return nullptr; } const char* problem_definition_error_format(lp::problem_definition_error::tag failure) { static const char *const tag[] = { "empty variables", "empty objective function", "variable not used", "bad bound" }; switch (failure) { case lp::problem_definition_error::tag::empty_variables: return tag[0]; case lp::problem_definition_error::tag::empty_objective_function: return tag[1]; case lp::problem_definition_error::tag::variable_not_used: return tag[2]; case lp::problem_definition_error::tag::bad_bound: return tag[3]; } return nullptr; } const char* solver_error_format(lp::solver_error::tag failure) { static const char *const tag[] = { "no solver available", "not enough memory" }; switch (failure) { case lp::solver_error::tag::no_solver_available: return tag[0]; case lp::solver_error::tag::not_enough_memory: return tag[1]; } return nullptr; }
update main parameter
update main parameter
C++
mit
quesnel/baryonyx,quesnel/baryonyx,quesnel/baryonyx
ca27f78e299a86fc1aca2c087270a6133eb1a79e
paddle/fluid/operators/load_op.cc
paddle/fluid/operators/load_op.cc
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <fstream> #include "paddle/fluid/framework/data_type_transform.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/profiler.h" namespace paddle { namespace operators { class LoadOp : public framework::OperatorBase { public: LoadOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} private: void RunImpl(const framework::Scope &scope, const platform::Place &place) const override { auto *dev_ctx = platform::DeviceContextPool::Instance().Get(place); platform::RecordEvent record_event(Type(), dev_ctx); auto filename = Attr<std::string>("file_path"); std::ifstream fin(filename); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open file %s for load op", filename); auto out_var_name = Output("Out"); auto *out_var = scope.FindVar(out_var_name); PADDLE_ENFORCE(out_var != nullptr, "Output variable %s cannot be found", out_var_name); if (out_var->IsType<framework::LoDTensor>()) { SaveLodTensor(filename, place, out_var); } else if (out_var->IsType<framework::SelectedRows>()) { SaveSelectedRows(filename, scope, place, out_var); } else { PADDLE_ENFORCE( false, "Load only support LoDTensor and SelectedRows, %s has wrong type", iname); } } } void LoadLodTensor(const std::string &filename, const platform::Place &place, framework::Variable *var) const { auto &tensor = var->Get<framework::LoDTensor>(); // get device context from pool platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); // FIXME(yuyang18): We save variable to local file now, but we should change // it to save an output stream. std::ifstream fin(filename); PADDLE_ENFORCE(static_cast<bool>(fout), "Cannot open %s to write", filename); auto *tensor = out_var->GetMutable<framework::LoDTensor>(); DeserializeFromStream(fin, tensor, *dev_ctx); auto load_as_fp16 = Attr<bool>("load_as_fp16"); auto in_dtype = framework::ToDataType(tensor->type()); auto out_dtype = load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype; if (in_dtype != out_dtype) { // convert to float16 tensor auto in_kernel_type = framework::OpKernelType(in_dtype, place); auto out_kernel_type = framework::OpKernelType(out_dtype, place); framework::LoDTensor fp16_tensor; // copy LoD info to the new tensor fp16_tensor.set_lod(tensor->lod()); framework::TransDataType(in_kernel_type, out_kernel_type, *tensor, &fp16_tensor); // reset output tensor out_var->Clear(); tensor = out_var->GetMutable<framework::LoDTensor>(); tensor->set_lod(fp16_tensor.lod()); tensor->ShareDataWith(fp16_tensor); } void LoadSelectedRows(const std::string &filename, const framework::Scope &scope, const platform::Place &place, framework::Variable *var) const { auto *selectedRows = var->GetMutable<framework::SelectedRows>(); // get device context from pool platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); // FIXME(yuyang18): We save variable to local file now, but we should change // it to save an output stream. std::ifstream fin(filename); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open %s to write", filename); framework::DeserializeFromStream(fin, selectedRows, dev_ctx); } }; class LoadOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddOutput("Out", "The tensor need to be loaded"); AddAttr<bool>( "load_as_fp16", "If true, the tensor will be first loaded and then " "converted to float16 data type. Otherwise, the tensor will be " "directly loaded without data type conversion. Default is false.") .SetDefault(false); AddAttr<std::string>("file_path", R"(Variable will be loaded from "file_path")") .AddCustomChecker( [](const std::string &path) { return !path.empty(); }); AddComment("Load operator will load a tensor variable from disk file."); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(load, ops::LoadOp, ops::LoadOpProtoMaker);
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <fstream> #include "paddle/fluid/framework/data_type_transform.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/profiler.h" namespace paddle { namespace operators { class LoadOp : public framework::OperatorBase { public: LoadOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} private: void RunImpl(const framework::Scope &scope, const platform::Place &place) const override { auto *dev_ctx = platform::DeviceContextPool::Instance().Get(place); platform::RecordEvent record_event(Type(), dev_ctx); auto filename = Attr<std::string>("file_path"); std::ifstream fin(filename); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open file %s for load op", filename); auto out_var_name = Output("Out"); auto *out_var = scope.FindVar(out_var_name); PADDLE_ENFORCE(out_var != nullptr, "Output variable %s cannot be found", out_var_name); if (out_var->IsType<framework::LoDTensor>()) { LoadLodTensor(filename, place, out_var); } else if (out_var->IsType<framework::SelectedRows>()) { LoadSelectedRows(filename, scope, place, out_var); } else { PADDLE_ENFORCE( false, "Load only support LoDTensor and SelectedRows, %s has wrong type", out_var_name); } } void LoadLodTensor(const std::string &filename, const platform::Place &place, framework::Variable *var) const { // get device context from pool platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); // FIXME(yuyang18): We save variable to local file now, but we should change // it to save an output stream. std::ifstream fin(filename); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open %s to read", filename); auto *tensor = var->GetMutable<framework::LoDTensor>(); DeserializeFromStream(fin, tensor, *dev_ctx); auto load_as_fp16 = Attr<bool>("load_as_fp16"); auto in_dtype = framework::ToDataType(tensor->type()); auto out_dtype = load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype; if (in_dtype != out_dtype) { // convert to float16 tensor auto in_kernel_type = framework::OpKernelType(in_dtype, place); auto out_kernel_type = framework::OpKernelType(out_dtype, place); framework::LoDTensor fp16_tensor; // copy LoD info to the new tensor fp16_tensor.set_lod(tensor->lod()); framework::TransDataType(in_kernel_type, out_kernel_type, *tensor, &fp16_tensor); // reset output tensor var->Clear(); tensor = var->GetMutable<framework::LoDTensor>(); tensor->set_lod(fp16_tensor.lod()); tensor->ShareDataWith(fp16_tensor); } } void LoadSelectedRows(const std::string &filename, const framework::Scope &scope, const platform::Place &place, framework::Variable *var) const { auto *selectedRows = var->GetMutable<framework::SelectedRows>(); // get device context from pool platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); // FIXME(yuyang18): We save variable to local file now, but we should change // it to save an output stream. std::ifstream fin(filename); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open %s to read", filename); framework::DeserializeFromStream(fin, selectedRows, dev_ctx); } }; class LoadOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddOutput("Out", "The tensor need to be loaded"); AddAttr<bool>( "load_as_fp16", "If true, the tensor will be first loaded and then " "converted to float16 data type. Otherwise, the tensor will be " "directly loaded without data type conversion. Default is false.") .SetDefault(false); AddAttr<std::string>("file_path", R"(Variable will be loaded from "file_path")") .AddCustomChecker( [](const std::string &path) { return !path.empty(); }); AddComment("Load operator will load a tensor variable from disk file."); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(load, ops::LoadOp, ops::LoadOpProtoMaker);
load op add seletedRows
load op add seletedRows
C++
apache-2.0
tensor-tang/Paddle,jacquesqiao/Paddle,jacquesqiao/Paddle,tensor-tang/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,QiJune/Paddle,tensor-tang/Paddle,QiJune/Paddle,QiJune/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,chengduoZH/Paddle,PaddlePaddle/Paddle,baidu/Paddle,jacquesqiao/Paddle,chengduoZH/Paddle,baidu/Paddle,tensor-tang/Paddle,tensor-tang/Paddle,jacquesqiao/Paddle,reyoung/Paddle,reyoung/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,QiJune/Paddle,luotao1/Paddle,reyoung/Paddle,luotao1/Paddle,baidu/Paddle,QiJune/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,jacquesqiao/Paddle,reyoung/Paddle,baidu/Paddle,chengduoZH/Paddle,chengduoZH/Paddle,baidu/Paddle,reyoung/Paddle,chengduoZH/Paddle,jacquesqiao/Paddle,reyoung/Paddle,luotao1/Paddle,PaddlePaddle/Paddle