text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: anchoreddrawobject.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:32:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ANCHOREDDRAWOBJECT_HXX #define _ANCHOREDDRAWOBJECT_HXX #ifndef _ANCHOREDOBJECT_HXX #include <anchoredobject.hxx> #endif #ifndef _GEN_HXX #include <tools/gen.hxx> #endif /** class for the positioning of drawing objects OD 2004-03-25 #i26791# @author OD */ class SwAnchoredDrawObject : public SwAnchoredObject { private: // boolean, indicating that the object position has been invalidated // and that a positioning has to be performed. bool mbValidPos; // rectangle, keeping the last object rectangle after the postioning // --> OD 2004-09-29 #i34748# - change <maLastObjRect> to a pointer Rectangle* mpLastObjRect; // boolean, indicating that anchored drawing object hasn't been attached // to a anchor frame yet. Once, it is attached to a anchor frame the // boolean changes its state. bool mbNotYetAttachedToAnchorFrame; // --> OD 2004-08-09 #i28749# - boolean, indicating that anchored // drawing object hasn't been positioned yet. Once, it's positioned the // boolean changes its state. bool mbNotYetPositioned; /** method for the intrinsic positioning of a at-paragraph|at-character anchored drawing object OD 2004-08-12 #i32795# - helper method for method <MakeObjPos> @author OD */ void _MakeObjPosAnchoredAtPara(); /** method for the intrinsic positioning of a at-page|at-frame anchored drawing object OD 2004-08-12 #i32795# - helper method for method <MakeObjPos> @author OD */ void _MakeObjPosAnchoredAtLayout(); /** method to set positioning attributes (not for as-character anchored) OD 2004-10-20 #i35798# During load the positioning attributes aren't set. Thus, the positioning attributes are set by the current object geometry. This method is also used for the conversion for drawing objects (not anchored as-character) imported from OpenOffice.org file format once and directly before the first positioning. @author OD */ void _SetPositioningAttr(); /** method to set internal anchor position of <SdrObject> instance of the drawing object For drawing objects the internal anchor position of the <SdrObject> instance has to be set. Note: This adjustment is not be done for as-character anchored drawing object - the positioning code takes care of this. OD 2004-07-29 #i31698# - API for drawing objects in Writer has been adjusted. Thus, this method will only set the internal anchor position of the <SdrObject> instance to the anchor position given by its anchor frame. @author OD */ void _SetDrawObjAnchor(); /** method to invalidate the given page frame OD 2004-07-02 #i28701# @author OD */ void _InvalidatePage( SwPageFrm* _pPageFrm ); protected: virtual void ObjectAttachedToAnchorFrame(); /** method to assure that anchored object is registered at the correct page frame OD 2004-07-02 #i28701# @author OD */ virtual void RegisterAtCorrectPage(); public: TYPEINFO(); SwAnchoredDrawObject(); virtual ~SwAnchoredDrawObject(); // declaration of pure virtual methods of base class <SwAnchoredObject> virtual void MakeObjPos(); virtual void InvalidateObjPos(); inline bool IsValidPos() const { return mbValidPos; } // accessors to the format virtual SwFrmFmt& GetFrmFmt(); virtual const SwFrmFmt& GetFrmFmt() const; // accessors to the object area and its position virtual const SwRect GetObjRect() const; virtual void SetObjTop( const SwTwips _nTop); virtual void SetObjLeft( const SwTwips _nLeft); // --> OD 2004-09-29 #i34748# - change return type to a pointer. // Return value can be NULL. const Rectangle* GetLastObjRect() const; // <-- // --> OD 2004-09-29 #i34748# - change method void SetLastObjRect( const Rectangle& _rNewObjRect ); // <-- /** adjust positioning and alignment attributes for new anchor frame OD 2004-04-21 Set horizontal and vertical position/alignment to manual position relative to anchor frame area using the anchor position of the new anchor frame and the current absolute drawing object position. Note: For correct Undo/Redo method should only be called inside a Undo-/Redo-action. OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect> @author OD @param <_pNewAnchorFrm> input parameter - new anchor frame for the anchored object. @param <_pNewObjRect> optional input parameter - proposed new object rectangle. If not provided the current object rectangle is taken. */ void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm, const SwRect* _pNewObjRect = 0L ); /** anchored drawing object not yet attached to a anchor frame OD 2004-08-04 #i31698# @author OD */ inline bool NotYetAttachedToAnchorFrm() const { return mbNotYetAttachedToAnchorFrame; } /** method to notify background of drawing object OD 2004-06-30 #i28701# @author OD */ virtual void NotifyBackground( SwPageFrm* _pPageFrm, const SwRect& _rRect, PrepareHint _eHint ); }; #endif <commit_msg>INTEGRATION: CWS dbwizardpp1 (1.7.212); FILE MERGED 2005/12/05 12:54:25 bc 1.7.212.2: RESYNC: (1.7-1.8); FILE MERGED 2005/08/16 12:27:54 od 1.7.212.1: #i53320# class <SwAnchoredDrawObject> - remove method <NotYetAttachedToAnchorFrm()> - add method <NotYetPositioned()><commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: anchoreddrawobject.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2005-12-28 17:11:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ANCHOREDDRAWOBJECT_HXX #define _ANCHOREDDRAWOBJECT_HXX #ifndef _ANCHOREDOBJECT_HXX #include <anchoredobject.hxx> #endif #ifndef _GEN_HXX #include <tools/gen.hxx> #endif /** class for the positioning of drawing objects OD 2004-03-25 #i26791# @author OD */ class SwAnchoredDrawObject : public SwAnchoredObject { private: // boolean, indicating that the object position has been invalidated // and that a positioning has to be performed. bool mbValidPos; // rectangle, keeping the last object rectangle after the postioning // --> OD 2004-09-29 #i34748# - change <maLastObjRect> to a pointer Rectangle* mpLastObjRect; // boolean, indicating that anchored drawing object hasn't been attached // to a anchor frame yet. Once, it is attached to a anchor frame the // boolean changes its state. bool mbNotYetAttachedToAnchorFrame; // --> OD 2004-08-09 #i28749# - boolean, indicating that anchored // drawing object hasn't been positioned yet. Once, it's positioned the // boolean changes its state. bool mbNotYetPositioned; /** method for the intrinsic positioning of a at-paragraph|at-character anchored drawing object OD 2004-08-12 #i32795# - helper method for method <MakeObjPos> @author OD */ void _MakeObjPosAnchoredAtPara(); /** method for the intrinsic positioning of a at-page|at-frame anchored drawing object OD 2004-08-12 #i32795# - helper method for method <MakeObjPos> @author OD */ void _MakeObjPosAnchoredAtLayout(); /** method to set positioning attributes (not for as-character anchored) OD 2004-10-20 #i35798# During load the positioning attributes aren't set. Thus, the positioning attributes are set by the current object geometry. This method is also used for the conversion for drawing objects (not anchored as-character) imported from OpenOffice.org file format once and directly before the first positioning. @author OD */ void _SetPositioningAttr(); /** method to set internal anchor position of <SdrObject> instance of the drawing object For drawing objects the internal anchor position of the <SdrObject> instance has to be set. Note: This adjustment is not be done for as-character anchored drawing object - the positioning code takes care of this. OD 2004-07-29 #i31698# - API for drawing objects in Writer has been adjusted. Thus, this method will only set the internal anchor position of the <SdrObject> instance to the anchor position given by its anchor frame. @author OD */ void _SetDrawObjAnchor(); /** method to invalidate the given page frame OD 2004-07-02 #i28701# @author OD */ void _InvalidatePage( SwPageFrm* _pPageFrm ); protected: virtual void ObjectAttachedToAnchorFrame(); /** method to assure that anchored object is registered at the correct page frame OD 2004-07-02 #i28701# @author OD */ virtual void RegisterAtCorrectPage(); public: TYPEINFO(); SwAnchoredDrawObject(); virtual ~SwAnchoredDrawObject(); // declaration of pure virtual methods of base class <SwAnchoredObject> virtual void MakeObjPos(); virtual void InvalidateObjPos(); inline bool IsValidPos() const { return mbValidPos; } // accessors to the format virtual SwFrmFmt& GetFrmFmt(); virtual const SwFrmFmt& GetFrmFmt() const; // accessors to the object area and its position virtual const SwRect GetObjRect() const; virtual void SetObjTop( const SwTwips _nTop); virtual void SetObjLeft( const SwTwips _nLeft); // --> OD 2004-09-29 #i34748# - change return type to a pointer. // Return value can be NULL. const Rectangle* GetLastObjRect() const; // <-- // --> OD 2004-09-29 #i34748# - change method void SetLastObjRect( const Rectangle& _rNewObjRect ); // <-- /** adjust positioning and alignment attributes for new anchor frame OD 2004-04-21 Set horizontal and vertical position/alignment to manual position relative to anchor frame area using the anchor position of the new anchor frame and the current absolute drawing object position. Note: For correct Undo/Redo method should only be called inside a Undo-/Redo-action. OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect> @author OD @param <_pNewAnchorFrm> input parameter - new anchor frame for the anchored object. @param <_pNewObjRect> optional input parameter - proposed new object rectangle. If not provided the current object rectangle is taken. */ void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm, const SwRect* _pNewObjRect = 0L ); /** method to notify background of drawing object OD 2004-06-30 #i28701# @author OD */ virtual void NotifyBackground( SwPageFrm* _pPageFrm, const SwRect& _rRect, PrepareHint _eHint ); // --> OD 2005-08-16 #i53320# inline bool NotYetPositioned() const { return mbNotYetPositioned; } // <-- }; #endif <|endoftext|>
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*- * kmail: KDE mail client * Copyright (c) 1996-1998 Stefan Taferner <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include <kontactinterface/pimuniqueapplication.h> #include <kglobal.h> #include "kmkernel.h" //control center #include "kmmainwidget.h" #include "kmail_options.h" #include <kdebug.h> #include <akonadi/control.h> #undef Status // stupid X headers #include "aboutdata.h" #include "kmstartup.h" #ifdef Q_WS_WIN #include <unistd.h> #include <windows.h> #endif //----------------------------------------------------------------------------- class KMailApplication : public KontactInterface::PimUniqueApplication { public: KMailApplication() : KontactInterface::PimUniqueApplication(), mDelayedInstanceCreation( false ), mEventLoopReached( false ) { } virtual int newInstance(); void commitData(QSessionManager& sm); void setEventLoopReached(); void delayedInstanceCreation(); protected: bool mDelayedInstanceCreation; bool mEventLoopReached; }; void KMailApplication::commitData(QSessionManager& sm) { kmkernel->dumpDeadLetters(); kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls KApplication::commitData( sm ); } void KMailApplication::setEventLoopReached() { mEventLoopReached = true; } int KMailApplication::newInstance() { kDebug(); // If the event loop hasn't been reached yet, the kernel is probably not // fully initialized. Creating an instance would therefore fail, this is why // that is delayed until delayedInstanceCreation() is called. if ( !mEventLoopReached ) { kDebug() << "Delaying instance creation."; mDelayedInstanceCreation = true; return 0; } if (!kmkernel) return 0; if (!kmkernel->firstInstance() || !kapp->isSessionRestored()) kmkernel->handleCommandLine( true ); kmkernel->setFirstInstance(false); return 0; } void KMailApplication::delayedInstanceCreation() { if ( mDelayedInstanceCreation ) newInstance(); } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". #if 0 // for testing KUniqueAppliaction on Windows MessageBoxA(NULL, QString("main() %1 pid=%2").arg(argv[0]).arg(getpid()).toLatin1(), QString("main() \"%1\"").arg(argv[0]).toLatin1(), MB_OK|MB_ICONINFORMATION|MB_TASKMODAL); #endif KMail::AboutData about; KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmail_options() ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; // Qt doesn't treat the system tray as a window, and therefore Qt would quit // the event loop when an error message is clicked away while KMail is in the // tray. // Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3. // See http://bugs.kde.org/show_bug.cgi?id=163479 QApplication::setQuitOnLastWindowClosed( false ); // import i18n data and icons from libraries: KMail::insertLibraryCataloguesAndIcons(); KMail::lockOrDie(); //local, do the init KMKernel kmailKernel; kmailKernel.init(); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); kmsetSignalHandler(kmsignalHandler); kmkernel->setupDBus(); // Ok. We are ready for D-Bus requests. kmkernel->setStartingUp( false ); // Starting up is finished //If the instance hasn't been created yet, do that now app.setEventLoopReached(); app.delayedInstanceCreation(); // Start Akonadi if ( !Akonadi::Control::start( kmkernel->getKMMainWidget() ) ) { //TODO: add message box after string freeze kWarning() << "Unable to start Akonadi server, exit application"; return 1; } // Go! int ret = qApp->exec(); // clean up kmailKernel.cleanup(); KMail::cleanup(); // pid file (see kmstartup.cpp) return ret; } <commit_msg>Revert "Abort application if Akonadi couldn't be started"<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*- * kmail: KDE mail client * Copyright (c) 1996-1998 Stefan Taferner <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include <kontactinterface/pimuniqueapplication.h> #include <kglobal.h> #include "kmkernel.h" //control center #include "kmmainwidget.h" #include "kmail_options.h" #include <kdebug.h> #include <akonadi/control.h> #undef Status // stupid X headers #include "aboutdata.h" #include "kmstartup.h" #ifdef Q_WS_WIN #include <unistd.h> #include <windows.h> #endif //----------------------------------------------------------------------------- class KMailApplication : public KontactInterface::PimUniqueApplication { public: KMailApplication() : KontactInterface::PimUniqueApplication(), mDelayedInstanceCreation( false ), mEventLoopReached( false ) { } virtual int newInstance(); void commitData(QSessionManager& sm); void setEventLoopReached(); void delayedInstanceCreation(); protected: bool mDelayedInstanceCreation; bool mEventLoopReached; }; void KMailApplication::commitData(QSessionManager& sm) { kmkernel->dumpDeadLetters(); kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls KApplication::commitData( sm ); } void KMailApplication::setEventLoopReached() { mEventLoopReached = true; } int KMailApplication::newInstance() { kDebug(); // If the event loop hasn't been reached yet, the kernel is probably not // fully initialized. Creating an instance would therefore fail, this is why // that is delayed until delayedInstanceCreation() is called. if ( !mEventLoopReached ) { kDebug() << "Delaying instance creation."; mDelayedInstanceCreation = true; return 0; } if (!kmkernel) return 0; if (!kmkernel->firstInstance() || !kapp->isSessionRestored()) kmkernel->handleCommandLine( true ); kmkernel->setFirstInstance(false); return 0; } void KMailApplication::delayedInstanceCreation() { if ( mDelayedInstanceCreation ) newInstance(); } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". #if 0 // for testing KUniqueAppliaction on Windows MessageBoxA(NULL, QString("main() %1 pid=%2").arg(argv[0]).arg(getpid()).toLatin1(), QString("main() \"%1\"").arg(argv[0]).toLatin1(), MB_OK|MB_ICONINFORMATION|MB_TASKMODAL); #endif KMail::AboutData about; KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmail_options() ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; // Qt doesn't treat the system tray as a window, and therefore Qt would quit // the event loop when an error message is clicked away while KMail is in the // tray. // Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3. // See http://bugs.kde.org/show_bug.cgi?id=163479 QApplication::setQuitOnLastWindowClosed( false ); // import i18n data and icons from libraries: KMail::insertLibraryCataloguesAndIcons(); KMail::lockOrDie(); //local, do the init KMKernel kmailKernel; kmailKernel.init(); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); kmsetSignalHandler(kmsignalHandler); kmkernel->setupDBus(); // Ok. We are ready for D-Bus requests. kmkernel->setStartingUp( false ); // Starting up is finished //If the instance hasn't been created yet, do that now app.setEventLoopReached(); app.delayedInstanceCreation(); // Start Akonadi Akonadi::Control::start( kmkernel->getKMMainWidget() ); // Go! int ret = qApp->exec(); // clean up kmailKernel.cleanup(); KMail::cleanup(); // pid file (see kmstartup.cpp) return ret; } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <memory> #include "SurgSim/Collision/BoxCapsuleDcdContact.h" #include "SurgSim/Collision/Representation.h" #include "SurgSim/Collision/ShapeCollisionRepresentation.h" #include "SurgSim/Math/BoxShape.h" #include "SurgSim/Math/CapsuleShape.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" using SurgSim::Math::BoxShape; using SurgSim::Math::CapsuleShape; namespace SurgSim { namespace Collision { void doBoxCapsuleTest(std::shared_ptr<BoxShape> box, const SurgSim::Math::Quaterniond& boxQuat, const SurgSim::Math::Vector3d& boxTrans, std::shared_ptr<CapsuleShape> capsule, const SurgSim::Math::Quaterniond& capsuleQuat, const SurgSim::Math::Vector3d& capsuleTrans, const bool expectedInContact) { std::shared_ptr<ShapeCollisionRepresentation> boxRep = std::make_shared<ShapeCollisionRepresentation>("Collision Box 0"); boxRep->setShape(box); boxRep->setLocalPose(SurgSim::Math::makeRigidTransform(boxQuat, boxTrans)); std::shared_ptr<ShapeCollisionRepresentation> capsuleRep = std::make_shared<ShapeCollisionRepresentation>("Collision Capsule 0"); capsuleRep->setShape(capsule); capsuleRep->setLocalPose(SurgSim::Math::makeRigidTransform(capsuleQuat, capsuleTrans)); // Perform collision detection. BoxCapsuleDcdContact calcContact; std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(boxRep, capsuleRep); calcContact.calculateContact(pair); EXPECT_EQ(expectedInContact, pair->hasContacts()); if (expectedInContact) { SurgSim::Math::Vector3d capsuleToBox; capsuleToBox = boxTrans - capsuleTrans; double depthMax = box->getSize().norm(); depthMax += capsule->getLength() / 2.0 + capsule->getRadius(); auto contacts = pair->getContacts(); for (auto contact=contacts.cbegin(); contact!=contacts.cend(); ++contact) { if (! capsuleToBox.isZero()) { // Check that each normal is pointing into the box EXPECT_LT(0.0, (*contact)->normal.dot(capsuleToBox)); } // Check that the depth is sane EXPECT_LT(0.0, (*contact)->depth); EXPECT_GT(depthMax, (*contact)->depth); } } } TEST(BoxCapsuleContactCalculationTests, UnitTests) { std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(1.0, 1.0, 1.0); std::shared_ptr<CapsuleShape> capsule = std::make_shared<CapsuleShape>(4.0, 1.0); SurgSim::Math::Quaterniond boxQuat; SurgSim::Math::Vector3d boxTrans; SurgSim::Math::Quaterniond capsuleQuat; SurgSim::Math::Vector3d capsuleTrans; { SCOPED_TRACE("No intersection, box in front of capsule"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(10.6, 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = false; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("No intersection, capsule beyond corner of box"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d::Zero(); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); bool expectedInContact = false; capsuleTrans = SurgSim::Math::Vector3d(1.5, 0.0, 1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); capsuleTrans = SurgSim::Math::Vector3d(1.5, 0.0, -1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); capsuleTrans = SurgSim::Math::Vector3d(-1.5, 0.0, 1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); capsuleTrans = SurgSim::Math::Vector3d(-1.5, 0.0, -1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("No intersection, box below capsule"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(0.0, -3.6, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = false; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with capsule side"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with upside down capsule"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with z-axis capsule"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(1.0, 0.0, 0.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with x-axis capsule"); boxQuat = SurgSim::Math::makeRotationQuaternion(M_PI, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(1.0, 0.0, 0.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with capsule cap"); boxQuat = SurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(0.1 , 0.0, 0.1); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d(0.0 , 2.6, 0.0); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("No intersection, capsule near box corner, but not intersecting"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(0.0 , 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d(1.3 , 0.0, 1.3); bool expectedInContact = false; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, capsule intersecting with box corner"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d(0.0 , 0.0, 0.0); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d(1.2 , 0.0, 1.2); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box inside capsule"); boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); boxTrans = SurgSim::Math::Vector3d::Zero(); capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0)); capsuleTrans = SurgSim::Math::Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, capsule inside box"); std::shared_ptr<BoxShape> bigBox = std::make_shared<BoxShape>(10.0, 10.0, 10.0); boxQuat = SurgSim::Math::makeRotationQuaternion(-M_PI_4, SurgSim::Math::Vector3d(0.0, 1.0, 0.0)); boxTrans = SurgSim::Math::Vector3d::Zero(); capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI, SurgSim::Math::Vector3d(1.0, 0.0, 0.0)); capsuleTrans = SurgSim::Math::Vector3d(0.0, 0.0, 0.0); bool expectedInContact = true; doBoxCapsuleTest(bigBox, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } } }; // namespace Collision }; // namespace SurgSim <commit_msg>Add Unit Test to Box Capsule Dcd Contact<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <memory> #include "SurgSim/Collision/BoxCapsuleDcdContact.h" #include "SurgSim/Collision/Representation.h" #include "SurgSim/Collision/ShapeCollisionRepresentation.h" #include "SurgSim/Math/BoxShape.h" #include "SurgSim/Math/CapsuleShape.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" using SurgSim::Math::BoxShape; using SurgSim::Math::CapsuleShape; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; using SurgSim::Math::Quaterniond; using SurgSim::Math::Vector3d; namespace SurgSim { namespace Collision { void doBoxCapsuleTest(std::shared_ptr<BoxShape> box, const Quaterniond& boxQuat, const Vector3d& boxTrans, std::shared_ptr<CapsuleShape> capsule, const Quaterniond& capsuleQuat, const Vector3d& capsuleTrans, const bool expectedInContact) { std::shared_ptr<ShapeCollisionRepresentation> boxRep = std::make_shared<ShapeCollisionRepresentation>("Collision Box 0"); boxRep->setShape(box); boxRep->setLocalPose(makeRigidTransform(boxQuat, boxTrans)); std::shared_ptr<ShapeCollisionRepresentation> capsuleRep = std::make_shared<ShapeCollisionRepresentation>("Collision Capsule 0"); capsuleRep->setShape(capsule); capsuleRep->setLocalPose(makeRigidTransform(capsuleQuat, capsuleTrans)); // Perform collision detection. BoxCapsuleDcdContact calcContact; std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(boxRep, capsuleRep); calcContact.calculateContact(pair); EXPECT_EQ(expectedInContact, pair->hasContacts()); if (expectedInContact) { Vector3d capsuleToBox = boxTrans - capsuleTrans; double depthMax = box->getSize().norm(); depthMax += capsule->getLength() / 2.0 + capsule->getRadius(); auto contacts = pair->getContacts(); for (auto contact=contacts.cbegin(); contact!=contacts.cend(); ++contact) { if (! capsuleToBox.isZero()) { // Check that each normal is pointing into the box EXPECT_LT(0.0, (*contact)->normal.dot(capsuleToBox)); } // Check that the depth is sane EXPECT_LT(0.0, (*contact)->depth); EXPECT_GT(depthMax, (*contact)->depth); // Check that the locations are sane Vector3d boxPenetrationPoint = (*contact)->penetrationPoints.first.globalPosition.getValue(); Vector3d capsulePenetrationPoint = (*contact)->penetrationPoints.second.globalPosition.getValue(); EXPECT_GT(0.0, (*contact)->normal.dot(boxPenetrationPoint - boxTrans)); EXPECT_LT(0.0, (*contact)->normal.dot(capsulePenetrationPoint - capsuleTrans)); } } } TEST(BoxCapsuleContactCalculationTests, UnitTests) { std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(1.0, 1.0, 1.0); std::shared_ptr<CapsuleShape> capsule = std::make_shared<CapsuleShape>(4.0, 1.0); Quaterniond boxQuat; Vector3d boxTrans; Quaterniond capsuleQuat; Vector3d capsuleTrans; { SCOPED_TRACE("No intersection, box in front of capsule"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(10.6, 0.0, 0.0); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = false; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("No intersection, capsule beyond corner of box"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d::Zero(); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); bool expectedInContact = false; capsuleTrans = Vector3d(1.5, 0.0, 1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); capsuleTrans = Vector3d(1.5, 0.0, -1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); capsuleTrans = Vector3d(-1.5, 0.0, 1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); capsuleTrans = Vector3d(-1.5, 0.0, -1.5); doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("No intersection, box below capsule"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(0.0, -3.6, 0.0); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = false; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with capsule side"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(1.0 , 0.0, 0.0); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with upside down capsule"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(1.0 , 0.0, 0.0); capsuleQuat = makeRotationQuaternion(M_PI, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with z-axis capsule"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(1.0 , 0.0, 0.0); capsuleQuat = makeRotationQuaternion(M_PI_2, Vector3d(1.0, 0.0, 0.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with x-axis capsule"); boxQuat = makeRotationQuaternion(M_PI, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(1.0 , 0.0, 0.0); capsuleQuat = makeRotationQuaternion(M_PI_2, Vector3d(1.0, 0.0, 0.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box intersection with capsule cap"); boxQuat = makeRotationQuaternion(M_PI_2, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(0.1 , 0.0, 0.1); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d(0.0 , 2.6, 0.0); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("No intersection, capsule near box corner, but not intersecting"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(0.0 , 0.0, 0.0); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d(1.3 , 0.0, 1.3); bool expectedInContact = false; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, capsule intersecting with box corner"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d(0.0 , 0.0, 0.0); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d(1.2 , 0.0, 1.2); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, box inside capsule"); boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); boxTrans = Vector3d::Zero(); capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0)); capsuleTrans = Vector3d::Zero(); bool expectedInContact = true; doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } { SCOPED_TRACE("Intersection, capsule inside box"); std::shared_ptr<BoxShape> bigBox = std::make_shared<BoxShape>(10.0, 10.0, 10.0); boxQuat = makeRotationQuaternion(-M_PI_4, Vector3d(0.0, 1.0, 0.0)); boxTrans = Vector3d::Zero(); capsuleQuat = makeRotationQuaternion(M_PI, Vector3d(1.0, 0.0, 0.0)); capsuleTrans = Vector3d(0.0, 0.0, 0.0); bool expectedInContact = true; doBoxCapsuleTest(bigBox, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact); } } }; // namespace Collision }; // namespace SurgSim <|endoftext|>
<commit_before>#include <csignal> #include <fcntl.h> #include <sys/stat.h> #include "driver.h" #include "../main/version.h" #include "files.h" #include "chpl.h" #include "baseAST.h" #include "symbol.h" #include "expr.h" #include "stmt.h" #include "stringutil.h" #include "misc.h" #include "yy.h" static void cleanup_for_exit(void) { deleteTmpDir(); stopCatchingSignals(); } // must be non-static to avoid dead-code elim. when compiling -O3 void gdbShouldBreakHere(void) { } // Support for internal errors, adopted from ZPL compiler static bool exit_immediately = true; static bool exit_eventually = false; static const char* err_filename; static int err_lineno; static int err_fatal; static int err_user; static int err_print; static int err_ignore; static FnSymbol* err_fn = NULL; const char* cleanFilename(const char* name) { static int chplHomeLen = strlen(CHPL_HOME); if (!strncmp(name, CHPL_HOME, chplHomeLen)) { return astr("$CHPL_HOME", name + chplHomeLen); } else { return name; } } static const char* cleanFilename(BaseAST* ast) { ModuleSymbol* mod = ast->getModule(); if (mod) { return cleanFilename(ast->getModule()->filename); } else { return cleanFilename(yyfilename); } } static void print_user_internal_error() { static char error[8]; const char* filename_start = strrchr(err_filename, '/'); if (filename_start) filename_start++; else filename_start = err_filename; strncpy(error, filename_start, 3); sprintf(error+3, "%04d", err_lineno); for (int i = 0; i < 7; i++) { if (error[i] >= 'a' && error[i] <= 'z') { error[i] += 'A' - 'a'; } } fprintf(stderr, "internal failure %s ", error); char version[128]; get_version(version); fprintf(stderr, "chpl Version %s\n", version); if (err_fatal) clean_exit(1); } void setupError(const char *filename, int lineno, int tag) { err_filename = filename; err_lineno = lineno; err_fatal = tag == 1 || tag == 2 || tag == 3; err_user = tag != 1; err_print = tag == 5; err_ignore = ignore_warnings && tag == 4; exit_immediately = tag == 1 || tag == 2; exit_eventually |= tag == 3; } static void printDevelErrorHeader(BaseAST* ast) { if (!err_print) { if (Expr* expr = toExpr(ast)) { Symbol* parent = expr->parentSymbol; if (isArgSymbol(parent)) parent = parent->defPoint->parentSymbol; FnSymbol* fn = toFnSymbol(parent); if (fn && fn != err_fn) { err_fn = fn; while ((fn = toFnSymbol(err_fn->defPoint->parentSymbol))) { if (fn == fn->getModule()->initFn) break; err_fn = fn; } if (err_fn->getModule()->initFn != err_fn && !err_fn->hasFlag(FLAG_TEMP) && !err_fn->hasFlag(FLAG_INLINE) && err_fn->lineno) { fprintf(stderr, "%s:%d: In ", cleanFilename(err_fn), err_fn->lineno); if (!strncmp(err_fn->name, "_construct_", 11)) { fprintf(stderr, "constructor '%s':\n", err_fn->name+11); } else { fprintf(stderr, "%s '%s':\n", (err_fn->hasFlag(FLAG_ITERATOR_FN) ? "iterator" : "function"), err_fn->name); } } } } } if (ast && ast->lineno) fprintf(stderr, "%s:%d: ", cleanFilename(ast), ast->lineno); fprintf(stderr, err_print ? "note: " : err_fatal ? "error: " : "warning: "); if (!err_user && !developer) { print_user_internal_error(); } } static void printDevelErrorFooter(void) { if (developer) fprintf(stderr, " [%s:%d]", err_filename, err_lineno); } void handleError(const char *fmt, ...) { fflush(stdout); fflush(stderr); if (err_ignore) return; printDevelErrorHeader(NULL); if (!err_user && !developer) return; va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); printDevelErrorFooter(); fprintf(stderr, "\n"); if (exit_immediately && !ignore_errors) { clean_exit(1); } } void handleError(BaseAST* ast, const char *fmt, ...) { if (err_ignore) return; printDevelErrorHeader(ast); if (!err_user && !developer) return; va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); printDevelErrorFooter(); fprintf(stderr, "\n"); if (exit_immediately && !ignore_errors) { clean_exit(1); } } void exitIfFatalErrorsEncountered() { if (exit_eventually && !ignore_errors) { clean_exit(1); } } static void handleInterrupt(int sig) { INT_FATAL("received interrupt"); } static void handleSegFault(int sig) { INT_FATAL("seg fault"); } void startCatchingSignals(void) { signal(SIGINT, handleInterrupt); signal(SIGSEGV, handleSegFault); } void stopCatchingSignals(void) { signal(SIGINT, SIG_DFL); signal(SIGSEGV, SIG_DFL); } // // Put this last to minimize the amount of code affected by this #undef // #ifdef exit #undef exit #endif void clean_exit(int status) { if (status != 0) { gdbShouldBreakHere(); } cleanup_for_exit(); deleteStrings(); exit(status); } <commit_msg>Installed handlers for SIGTERM and SIGHUP that will clean up the /tmp directories and exit cleanly.<commit_after>#include <csignal> #include <fcntl.h> #include <sys/stat.h> #include "driver.h" #include "../main/version.h" #include "files.h" #include "chpl.h" #include "baseAST.h" #include "symbol.h" #include "expr.h" #include "stmt.h" #include "stringutil.h" #include "misc.h" #include "yy.h" static void cleanup_for_exit(void) { deleteTmpDir(); stopCatchingSignals(); } // must be non-static to avoid dead-code elim. when compiling -O3 void gdbShouldBreakHere(void) { } // Support for internal errors, adopted from ZPL compiler static bool exit_immediately = true; static bool exit_eventually = false; static const char* err_filename; static int err_lineno; static int err_fatal; static int err_user; static int err_print; static int err_ignore; static FnSymbol* err_fn = NULL; const char* cleanFilename(const char* name) { static int chplHomeLen = strlen(CHPL_HOME); if (!strncmp(name, CHPL_HOME, chplHomeLen)) { return astr("$CHPL_HOME", name + chplHomeLen); } else { return name; } } static const char* cleanFilename(BaseAST* ast) { ModuleSymbol* mod = ast->getModule(); if (mod) { return cleanFilename(ast->getModule()->filename); } else { return cleanFilename(yyfilename); } } static void print_user_internal_error() { static char error[8]; const char* filename_start = strrchr(err_filename, '/'); if (filename_start) filename_start++; else filename_start = err_filename; strncpy(error, filename_start, 3); sprintf(error+3, "%04d", err_lineno); for (int i = 0; i < 7; i++) { if (error[i] >= 'a' && error[i] <= 'z') { error[i] += 'A' - 'a'; } } fprintf(stderr, "internal failure %s ", error); char version[128]; get_version(version); fprintf(stderr, "chpl Version %s\n", version); if (err_fatal) clean_exit(1); } void setupError(const char *filename, int lineno, int tag) { err_filename = filename; err_lineno = lineno; err_fatal = tag == 1 || tag == 2 || tag == 3; err_user = tag != 1; err_print = tag == 5; err_ignore = ignore_warnings && tag == 4; exit_immediately = tag == 1 || tag == 2; exit_eventually |= tag == 3; } static void printDevelErrorHeader(BaseAST* ast) { if (!err_print) { if (Expr* expr = toExpr(ast)) { Symbol* parent = expr->parentSymbol; if (isArgSymbol(parent)) parent = parent->defPoint->parentSymbol; FnSymbol* fn = toFnSymbol(parent); if (fn && fn != err_fn) { err_fn = fn; while ((fn = toFnSymbol(err_fn->defPoint->parentSymbol))) { if (fn == fn->getModule()->initFn) break; err_fn = fn; } if (err_fn->getModule()->initFn != err_fn && !err_fn->hasFlag(FLAG_TEMP) && !err_fn->hasFlag(FLAG_INLINE) && err_fn->lineno) { fprintf(stderr, "%s:%d: In ", cleanFilename(err_fn), err_fn->lineno); if (!strncmp(err_fn->name, "_construct_", 11)) { fprintf(stderr, "constructor '%s':\n", err_fn->name+11); } else { fprintf(stderr, "%s '%s':\n", (err_fn->hasFlag(FLAG_ITERATOR_FN) ? "iterator" : "function"), err_fn->name); } } } } } if (ast && ast->lineno) fprintf(stderr, "%s:%d: ", cleanFilename(ast), ast->lineno); fprintf(stderr, err_print ? "note: " : err_fatal ? "error: " : "warning: "); if (!err_user && !developer) { print_user_internal_error(); } } static void printDevelErrorFooter(void) { if (developer) fprintf(stderr, " [%s:%d]", err_filename, err_lineno); } void handleError(const char *fmt, ...) { fflush(stdout); fflush(stderr); if (err_ignore) return; printDevelErrorHeader(NULL); if (!err_user && !developer) return; va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); printDevelErrorFooter(); fprintf(stderr, "\n"); if (exit_immediately && !ignore_errors) { clean_exit(1); } } void handleError(BaseAST* ast, const char *fmt, ...) { if (err_ignore) return; printDevelErrorHeader(ast); if (!err_user && !developer) return; va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); printDevelErrorFooter(); fprintf(stderr, "\n"); if (exit_immediately && !ignore_errors) { clean_exit(1); } } void exitIfFatalErrorsEncountered() { if (exit_eventually && !ignore_errors) { clean_exit(1); } } static void handleInterrupt(int sig) { INT_FATAL("received interrupt"); } static void handleSegFault(int sig) { INT_FATAL("seg fault"); } void startCatchingSignals(void) { signal(SIGINT, handleInterrupt); signal(SIGTERM, handleInterrupt); signal(SIGHUP, handleInterrupt); signal(SIGSEGV, handleSegFault); } void stopCatchingSignals(void) { signal(SIGINT, SIG_DFL); signal(SIGSEGV, SIG_DFL); } // // Put this last to minimize the amount of code affected by this #undef // #ifdef exit #undef exit #endif void clean_exit(int status) { if (status != 0) { gdbShouldBreakHere(); } cleanup_for_exit(); deleteStrings(); exit(status); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <string.h> #include <memory> #include "webrtc/media/base/videoframe_unittest.h" #include "webrtc/media/engine/webrtcvideoframe.h" #include "webrtc/media/engine/webrtcvideoframefactory.h" class WebRtcVideoFrameFactoryTest : public VideoFrameTest<cricket::WebRtcVideoFrameFactory> { public: WebRtcVideoFrameFactoryTest() {} void InitFrame(webrtc::VideoRotation frame_rotation) { const int frame_width = 1920; const int frame_height = 1080; // Build the CapturedFrame. captured_frame_.fourcc = cricket::FOURCC_I420; captured_frame_.pixel_width = 1; captured_frame_.pixel_height = 1; captured_frame_.time_stamp = rtc::TimeNanos(); captured_frame_.rotation = frame_rotation; captured_frame_.width = frame_width; captured_frame_.height = frame_height; captured_frame_.data_size = (frame_width * frame_height) + ((frame_width + 1) / 2) * ((frame_height + 1) / 2) * 2; captured_frame_buffer_.reset(new uint8_t[captured_frame_.data_size]); // Initialize memory to satisfy DrMemory tests. memset(captured_frame_buffer_.get(), 0, captured_frame_.data_size); captured_frame_.data = captured_frame_buffer_.get(); } void VerifyFrame(cricket::VideoFrame* dest_frame, webrtc::VideoRotation src_rotation, int src_width, int src_height, bool apply_rotation) { if (!apply_rotation) { EXPECT_EQ(dest_frame->rotation(), src_rotation); EXPECT_EQ(dest_frame->width(), src_width); EXPECT_EQ(dest_frame->height(), src_height); } else { EXPECT_EQ(dest_frame->rotation(), webrtc::kVideoRotation_0); if (src_rotation == webrtc::kVideoRotation_90 || src_rotation == webrtc::kVideoRotation_270) { EXPECT_EQ(dest_frame->width(), src_height); EXPECT_EQ(dest_frame->height(), src_width); } else { EXPECT_EQ(dest_frame->width(), src_width); EXPECT_EQ(dest_frame->height(), src_height); } } } void TestCreateAliasedFrame(bool apply_rotation) { cricket::VideoFrameFactory& factory = factory_; factory.SetApplyRotation(apply_rotation); InitFrame(webrtc::kVideoRotation_270); const cricket::CapturedFrame& captured_frame = get_captured_frame(); // Create the new frame from the CapturedFrame. std::unique_ptr<cricket::VideoFrame> frame; int new_width = captured_frame.width / 2; int new_height = captured_frame.height / 2; frame.reset(factory.CreateAliasedFrame(&captured_frame, new_width, new_height, new_width, new_height)); VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width, new_height, apply_rotation); frame.reset(factory.CreateAliasedFrame( &captured_frame, new_width, new_height, new_width / 2, new_height / 2)); VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2, new_height / 2, apply_rotation); // Reset the frame first so it's exclusive hence we could go through the // StretchToFrame code path in CreateAliasedFrame. frame.reset(); frame.reset(factory.CreateAliasedFrame( &captured_frame, new_width, new_height, new_width / 2, new_height / 2)); VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2, new_height / 2, apply_rotation); } const cricket::CapturedFrame& get_captured_frame() { return captured_frame_; } private: cricket::CapturedFrame captured_frame_; std::unique_ptr<uint8_t[]> captured_frame_buffer_; cricket::WebRtcVideoFrameFactory factory_; }; TEST_F(WebRtcVideoFrameFactoryTest, NoApplyRotation) { TestCreateAliasedFrame(false); } TEST_F(WebRtcVideoFrameFactoryTest, ApplyRotation) { TestCreateAliasedFrame(true); } <commit_msg>WebRtcVideoFrameFactoryTest shouldn't inherit VideoFrameTest.<commit_after>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <string.h> #include <memory> #include "webrtc/base/gunit.h" #include "webrtc/media/base/videocapturer.h" #include "webrtc/media/engine/webrtcvideoframe.h" #include "webrtc/media/engine/webrtcvideoframefactory.h" class WebRtcVideoFrameFactoryTest : public testing::Test { public: WebRtcVideoFrameFactoryTest() {} void InitFrame(webrtc::VideoRotation frame_rotation) { const int frame_width = 1920; const int frame_height = 1080; // Build the CapturedFrame. captured_frame_.fourcc = cricket::FOURCC_I420; captured_frame_.pixel_width = 1; captured_frame_.pixel_height = 1; captured_frame_.time_stamp = rtc::TimeNanos(); captured_frame_.rotation = frame_rotation; captured_frame_.width = frame_width; captured_frame_.height = frame_height; captured_frame_.data_size = (frame_width * frame_height) + ((frame_width + 1) / 2) * ((frame_height + 1) / 2) * 2; captured_frame_buffer_.reset(new uint8_t[captured_frame_.data_size]); // Initialize memory to satisfy DrMemory tests. memset(captured_frame_buffer_.get(), 0, captured_frame_.data_size); captured_frame_.data = captured_frame_buffer_.get(); } void VerifyFrame(cricket::VideoFrame* dest_frame, webrtc::VideoRotation src_rotation, int src_width, int src_height, bool apply_rotation) { if (!apply_rotation) { EXPECT_EQ(dest_frame->rotation(), src_rotation); EXPECT_EQ(dest_frame->width(), src_width); EXPECT_EQ(dest_frame->height(), src_height); } else { EXPECT_EQ(dest_frame->rotation(), webrtc::kVideoRotation_0); if (src_rotation == webrtc::kVideoRotation_90 || src_rotation == webrtc::kVideoRotation_270) { EXPECT_EQ(dest_frame->width(), src_height); EXPECT_EQ(dest_frame->height(), src_width); } else { EXPECT_EQ(dest_frame->width(), src_width); EXPECT_EQ(dest_frame->height(), src_height); } } } void TestCreateAliasedFrame(bool apply_rotation) { cricket::VideoFrameFactory& factory = factory_; factory.SetApplyRotation(apply_rotation); InitFrame(webrtc::kVideoRotation_270); const cricket::CapturedFrame& captured_frame = get_captured_frame(); // Create the new frame from the CapturedFrame. std::unique_ptr<cricket::VideoFrame> frame; int new_width = captured_frame.width / 2; int new_height = captured_frame.height / 2; frame.reset(factory.CreateAliasedFrame(&captured_frame, new_width, new_height, new_width, new_height)); VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width, new_height, apply_rotation); frame.reset(factory.CreateAliasedFrame( &captured_frame, new_width, new_height, new_width / 2, new_height / 2)); VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2, new_height / 2, apply_rotation); // Reset the frame first so it's exclusive hence we could go through the // StretchToFrame code path in CreateAliasedFrame. frame.reset(); frame.reset(factory.CreateAliasedFrame( &captured_frame, new_width, new_height, new_width / 2, new_height / 2)); VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2, new_height / 2, apply_rotation); } const cricket::CapturedFrame& get_captured_frame() { return captured_frame_; } private: cricket::CapturedFrame captured_frame_; std::unique_ptr<uint8_t[]> captured_frame_buffer_; cricket::WebRtcVideoFrameFactory factory_; }; TEST_F(WebRtcVideoFrameFactoryTest, NoApplyRotation) { TestCreateAliasedFrame(false); } TEST_F(WebRtcVideoFrameFactoryTest, ApplyRotation) { TestCreateAliasedFrame(true); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <sal/config.h> #include <rtl/uuid.h> #include "xmlencryption_nssimpl.hxx" #include "xmldocumentwrapper_xmlsecimpl.hxx" #include "xmlelementwrapper_xmlsecimpl.hxx" #include "securityenvironment_nssimpl.hxx" #include "errorcallback.hxx" #include <sal/types.h> //For reasons that escape me, this is what xmlsec does when size_t is not 4 #if SAL_TYPES_SIZEOFPOINTER != 4 # define XMLSEC_NO_SIZE_T #endif #include "xmlsec/xmlsec.h" #include "xmlsec/xmltree.h" #include "xmlsec/xmlenc.h" #include "xmlsec/crypto.h" #ifdef UNX #define stricmp strcasecmp #endif using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::lang ; using ::com::sun::star::lang::XMultiServiceFactory ; using ::com::sun::star::lang::XSingleServiceFactory ; using ::rtl::OUString ; using ::com::sun::star::xml::wrapper::XXMLElementWrapper ; using ::com::sun::star::xml::wrapper::XXMLDocumentWrapper ; using ::com::sun::star::xml::crypto::XSecurityEnvironment ; using ::com::sun::star::xml::crypto::XXMLEncryption ; using ::com::sun::star::xml::crypto::XXMLEncryptionTemplate ; using ::com::sun::star::xml::crypto::XXMLSecurityContext ; using ::com::sun::star::xml::crypto::XMLEncryptionException ; XMLEncryption_NssImpl :: XMLEncryption_NssImpl( const Reference< XMultiServiceFactory >& aFactory ) : m_xServiceManager( aFactory ) { } XMLEncryption_NssImpl :: ~XMLEncryption_NssImpl() { } /* XXMLEncryption */ Reference< XXMLEncryptionTemplate > SAL_CALL XMLEncryption_NssImpl :: encrypt( const Reference< XXMLEncryptionTemplate >& aTemplate , const Reference< XSecurityEnvironment >& aEnvironment ) throw( com::sun::star::xml::crypto::XMLEncryptionException, com::sun::star::uno::SecurityException ) { xmlSecKeysMngrPtr pMngr = NULL ; xmlSecEncCtxPtr pEncCtx = NULL ; xmlNodePtr pEncryptedData = NULL ; xmlNodePtr pContent = NULL ; if( !aTemplate.is() ) throw RuntimeException() ; if( !aEnvironment.is() ) throw RuntimeException() ; //Get Keys Manager Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ; if( !xSecTunnel.is() ) { throw RuntimeException() ; } SecurityEnvironment_NssImpl* pSecEnv = reinterpret_cast<SecurityEnvironment_NssImpl*>( sal::static_int_cast<sal_uIntPtr>(xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ; if( pSecEnv == NULL ) throw RuntimeException() ; //Get the encryption template Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ; if( !xTemplate.is() ) { throw RuntimeException() ; } Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ; if( !xTplTunnel.is() ) { throw RuntimeException() ; } XMLElementWrapper_XmlSecImpl* pTemplate = reinterpret_cast<XMLElementWrapper_XmlSecImpl*>( sal::static_int_cast<sal_uIntPtr>( xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))); if( pTemplate == NULL ) { throw RuntimeException() ; } // Get the element to be encrypted Reference< XXMLElementWrapper > xTarget = aTemplate->getTarget() ; if( !xTarget.is() ) { throw XMLEncryptionException() ; } Reference< XUnoTunnel > xTgtTunnel( xTarget , UNO_QUERY ) ; if( !xTgtTunnel.is() ) { throw XMLEncryptionException() ; } XMLElementWrapper_XmlSecImpl* pTarget = reinterpret_cast<XMLElementWrapper_XmlSecImpl*>( sal::static_int_cast<sal_uIntPtr>( xTgtTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))); if( pTarget == NULL ) { throw RuntimeException() ; } pContent = pTarget->getNativeElement() ; if( pContent == NULL ) { throw XMLEncryptionException() ; } //remember the position of the element to be signed sal_Bool isParentRef = sal_True; pEncryptedData = pTemplate->getNativeElement(); xmlNodePtr pParent = pEncryptedData->parent; xmlNodePtr referenceNode; if (pEncryptedData == pParent->children) { referenceNode = pParent; } else { referenceNode = pEncryptedData->prev; isParentRef = sal_False; } setErrorRecorder( ); pMngr = pSecEnv->createKeysManager() ; //i39448 if( !pMngr ) { throw RuntimeException() ; } //Create Encryption context pEncCtx = xmlSecEncCtxCreate( pMngr ) ; if( pEncCtx == NULL ) { pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //throw XMLEncryptionException() ; clearErrorRecorder(); return aTemplate; } //Find the element to be encrypted. //Encrypt the template if( xmlSecEncCtxXmlEncrypt( pEncCtx , pEncryptedData , pContent ) < 0 ) { xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //throw XMLEncryptionException() ; clearErrorRecorder(); return aTemplate; } xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //get the new EncryptedData element if (isParentRef) { pTemplate->setNativeElement(referenceNode->children) ; } else { pTemplate->setNativeElement(referenceNode->next); } return aTemplate ; } /* XXMLEncryption */ Reference< XXMLEncryptionTemplate > SAL_CALL XMLEncryption_NssImpl :: decrypt( const Reference< XXMLEncryptionTemplate >& aTemplate , const Reference< XXMLSecurityContext >& aSecurityCtx ) throw( com::sun::star::xml::crypto::XMLEncryptionException , com::sun::star::uno::SecurityException) { xmlSecKeysMngrPtr pMngr = NULL ; xmlSecEncCtxPtr pEncCtx = NULL ; xmlNodePtr pEncryptedData = NULL ; if( !aTemplate.is() ) throw RuntimeException() ; if( !aSecurityCtx.is() ) throw RuntimeException() ; //Get the encryption template Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ; if( !xTemplate.is() ) { throw RuntimeException() ; } Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ; if( !xTplTunnel.is() ) { throw RuntimeException() ; } XMLElementWrapper_XmlSecImpl* pTemplate = reinterpret_cast<XMLElementWrapper_XmlSecImpl*>( sal::static_int_cast<sal_uIntPtr>( xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))); if( pTemplate == NULL ) { throw RuntimeException() ; } pEncryptedData = pTemplate->getNativeElement() ; //remember the position of the element to be signed sal_Bool isParentRef = sal_True; xmlNodePtr pParent = pEncryptedData->parent; xmlNodePtr referenceNode; if (pEncryptedData == pParent->children) { referenceNode = pParent; } else { referenceNode = pEncryptedData->prev; isParentRef = sal_False; } setErrorRecorder( ); sal_Int32 nSecurityEnvironment = aSecurityCtx->getSecurityEnvironmentNumber(); sal_Int32 i; for (i=0; i<nSecurityEnvironment; ++i) { Reference< XSecurityEnvironment > aEnvironment = aSecurityCtx->getSecurityEnvironmentByIndex(i); //Get Keys Manager Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ; if( !aEnvironment.is() ) { throw RuntimeException() ; } SecurityEnvironment_NssImpl* pSecEnv = reinterpret_cast<SecurityEnvironment_NssImpl*>( sal::static_int_cast<sal_uIntPtr>( xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ))); if( pSecEnv == NULL ) throw RuntimeException() ; pMngr = pSecEnv->createKeysManager() ; //i39448 if( !pMngr ) { throw RuntimeException() ; } //Create Encryption context pEncCtx = xmlSecEncCtxCreate( pMngr ) ; if( pEncCtx == NULL ) { pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //throw XMLEncryptionException() ; clearErrorRecorder(); return aTemplate; } //Decrypt the template if(!( xmlSecEncCtxDecrypt( pEncCtx , pEncryptedData ) < 0 || pEncCtx->result == NULL )) { //The decryption succeeds //Destroy the encryption context xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //get the decrypted element XMLElementWrapper_XmlSecImpl * ret = new XMLElementWrapper_XmlSecImpl(isParentRef? (referenceNode->children):(referenceNode->next)); //return ret; aTemplate->setTemplate(ret); break; } else { //The decryption fails, continue with the next security environment xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 } } clearErrorRecorder(); return aTemplate; } /* XInitialization */ void SAL_CALL XMLEncryption_NssImpl :: initialize( const Sequence< Any >& /*aArguments*/ ) throw( Exception, RuntimeException ) { // TBD } ; /* XServiceInfo */ OUString SAL_CALL XMLEncryption_NssImpl :: getImplementationName() throw( RuntimeException ) { return impl_getImplementationName() ; } /* XServiceInfo */ sal_Bool SAL_CALL XMLEncryption_NssImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) { Sequence< OUString > seqServiceNames = getSupportedServiceNames() ; const OUString* pArray = seqServiceNames.getConstArray() ; for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) { if( *( pArray + i ) == serviceName ) return sal_True ; } return sal_False ; } /* XServiceInfo */ Sequence< OUString > SAL_CALL XMLEncryption_NssImpl :: getSupportedServiceNames() throw( RuntimeException ) { return impl_getSupportedServiceNames() ; } //Helper for XServiceInfo Sequence< OUString > XMLEncryption_NssImpl :: impl_getSupportedServiceNames() { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ; Sequence< OUString > seqServiceNames( 1 ) ; seqServiceNames.getArray()[0] = OUString("com.sun.star.xml.crypto.XMLEncryption") ; return seqServiceNames ; } OUString XMLEncryption_NssImpl :: impl_getImplementationName() throw( RuntimeException ) { return OUString("com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_NssImpl") ; } //Helper for registry Reference< XInterface > SAL_CALL XMLEncryption_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) { return Reference< XInterface >( *new XMLEncryption_NssImpl( aServiceManager ) ) ; } Reference< XSingleServiceFactory > XMLEncryption_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) { //Reference< XSingleServiceFactory > xFactory ; //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ; //return xFactory ; return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>stricmp macro is unused<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <sal/config.h> #include <rtl/uuid.h> #include "xmlencryption_nssimpl.hxx" #include "xmldocumentwrapper_xmlsecimpl.hxx" #include "xmlelementwrapper_xmlsecimpl.hxx" #include "securityenvironment_nssimpl.hxx" #include "errorcallback.hxx" #include <sal/types.h> //For reasons that escape me, this is what xmlsec does when size_t is not 4 #if SAL_TYPES_SIZEOFPOINTER != 4 # define XMLSEC_NO_SIZE_T #endif #include "xmlsec/xmlsec.h" #include "xmlsec/xmltree.h" #include "xmlsec/xmlenc.h" #include "xmlsec/crypto.h" using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::lang ; using ::com::sun::star::lang::XMultiServiceFactory ; using ::com::sun::star::lang::XSingleServiceFactory ; using ::rtl::OUString ; using ::com::sun::star::xml::wrapper::XXMLElementWrapper ; using ::com::sun::star::xml::wrapper::XXMLDocumentWrapper ; using ::com::sun::star::xml::crypto::XSecurityEnvironment ; using ::com::sun::star::xml::crypto::XXMLEncryption ; using ::com::sun::star::xml::crypto::XXMLEncryptionTemplate ; using ::com::sun::star::xml::crypto::XXMLSecurityContext ; using ::com::sun::star::xml::crypto::XMLEncryptionException ; XMLEncryption_NssImpl :: XMLEncryption_NssImpl( const Reference< XMultiServiceFactory >& aFactory ) : m_xServiceManager( aFactory ) { } XMLEncryption_NssImpl :: ~XMLEncryption_NssImpl() { } /* XXMLEncryption */ Reference< XXMLEncryptionTemplate > SAL_CALL XMLEncryption_NssImpl :: encrypt( const Reference< XXMLEncryptionTemplate >& aTemplate , const Reference< XSecurityEnvironment >& aEnvironment ) throw( com::sun::star::xml::crypto::XMLEncryptionException, com::sun::star::uno::SecurityException ) { xmlSecKeysMngrPtr pMngr = NULL ; xmlSecEncCtxPtr pEncCtx = NULL ; xmlNodePtr pEncryptedData = NULL ; xmlNodePtr pContent = NULL ; if( !aTemplate.is() ) throw RuntimeException() ; if( !aEnvironment.is() ) throw RuntimeException() ; //Get Keys Manager Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ; if( !xSecTunnel.is() ) { throw RuntimeException() ; } SecurityEnvironment_NssImpl* pSecEnv = reinterpret_cast<SecurityEnvironment_NssImpl*>( sal::static_int_cast<sal_uIntPtr>(xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ; if( pSecEnv == NULL ) throw RuntimeException() ; //Get the encryption template Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ; if( !xTemplate.is() ) { throw RuntimeException() ; } Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ; if( !xTplTunnel.is() ) { throw RuntimeException() ; } XMLElementWrapper_XmlSecImpl* pTemplate = reinterpret_cast<XMLElementWrapper_XmlSecImpl*>( sal::static_int_cast<sal_uIntPtr>( xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))); if( pTemplate == NULL ) { throw RuntimeException() ; } // Get the element to be encrypted Reference< XXMLElementWrapper > xTarget = aTemplate->getTarget() ; if( !xTarget.is() ) { throw XMLEncryptionException() ; } Reference< XUnoTunnel > xTgtTunnel( xTarget , UNO_QUERY ) ; if( !xTgtTunnel.is() ) { throw XMLEncryptionException() ; } XMLElementWrapper_XmlSecImpl* pTarget = reinterpret_cast<XMLElementWrapper_XmlSecImpl*>( sal::static_int_cast<sal_uIntPtr>( xTgtTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))); if( pTarget == NULL ) { throw RuntimeException() ; } pContent = pTarget->getNativeElement() ; if( pContent == NULL ) { throw XMLEncryptionException() ; } //remember the position of the element to be signed sal_Bool isParentRef = sal_True; pEncryptedData = pTemplate->getNativeElement(); xmlNodePtr pParent = pEncryptedData->parent; xmlNodePtr referenceNode; if (pEncryptedData == pParent->children) { referenceNode = pParent; } else { referenceNode = pEncryptedData->prev; isParentRef = sal_False; } setErrorRecorder( ); pMngr = pSecEnv->createKeysManager() ; //i39448 if( !pMngr ) { throw RuntimeException() ; } //Create Encryption context pEncCtx = xmlSecEncCtxCreate( pMngr ) ; if( pEncCtx == NULL ) { pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //throw XMLEncryptionException() ; clearErrorRecorder(); return aTemplate; } //Find the element to be encrypted. //Encrypt the template if( xmlSecEncCtxXmlEncrypt( pEncCtx , pEncryptedData , pContent ) < 0 ) { xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //throw XMLEncryptionException() ; clearErrorRecorder(); return aTemplate; } xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //get the new EncryptedData element if (isParentRef) { pTemplate->setNativeElement(referenceNode->children) ; } else { pTemplate->setNativeElement(referenceNode->next); } return aTemplate ; } /* XXMLEncryption */ Reference< XXMLEncryptionTemplate > SAL_CALL XMLEncryption_NssImpl :: decrypt( const Reference< XXMLEncryptionTemplate >& aTemplate , const Reference< XXMLSecurityContext >& aSecurityCtx ) throw( com::sun::star::xml::crypto::XMLEncryptionException , com::sun::star::uno::SecurityException) { xmlSecKeysMngrPtr pMngr = NULL ; xmlSecEncCtxPtr pEncCtx = NULL ; xmlNodePtr pEncryptedData = NULL ; if( !aTemplate.is() ) throw RuntimeException() ; if( !aSecurityCtx.is() ) throw RuntimeException() ; //Get the encryption template Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ; if( !xTemplate.is() ) { throw RuntimeException() ; } Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ; if( !xTplTunnel.is() ) { throw RuntimeException() ; } XMLElementWrapper_XmlSecImpl* pTemplate = reinterpret_cast<XMLElementWrapper_XmlSecImpl*>( sal::static_int_cast<sal_uIntPtr>( xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))); if( pTemplate == NULL ) { throw RuntimeException() ; } pEncryptedData = pTemplate->getNativeElement() ; //remember the position of the element to be signed sal_Bool isParentRef = sal_True; xmlNodePtr pParent = pEncryptedData->parent; xmlNodePtr referenceNode; if (pEncryptedData == pParent->children) { referenceNode = pParent; } else { referenceNode = pEncryptedData->prev; isParentRef = sal_False; } setErrorRecorder( ); sal_Int32 nSecurityEnvironment = aSecurityCtx->getSecurityEnvironmentNumber(); sal_Int32 i; for (i=0; i<nSecurityEnvironment; ++i) { Reference< XSecurityEnvironment > aEnvironment = aSecurityCtx->getSecurityEnvironmentByIndex(i); //Get Keys Manager Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ; if( !aEnvironment.is() ) { throw RuntimeException() ; } SecurityEnvironment_NssImpl* pSecEnv = reinterpret_cast<SecurityEnvironment_NssImpl*>( sal::static_int_cast<sal_uIntPtr>( xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ))); if( pSecEnv == NULL ) throw RuntimeException() ; pMngr = pSecEnv->createKeysManager() ; //i39448 if( !pMngr ) { throw RuntimeException() ; } //Create Encryption context pEncCtx = xmlSecEncCtxCreate( pMngr ) ; if( pEncCtx == NULL ) { pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //throw XMLEncryptionException() ; clearErrorRecorder(); return aTemplate; } //Decrypt the template if(!( xmlSecEncCtxDecrypt( pEncCtx , pEncryptedData ) < 0 || pEncCtx->result == NULL )) { //The decryption succeeds //Destroy the encryption context xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 //get the decrypted element XMLElementWrapper_XmlSecImpl * ret = new XMLElementWrapper_XmlSecImpl(isParentRef? (referenceNode->children):(referenceNode->next)); //return ret; aTemplate->setTemplate(ret); break; } else { //The decryption fails, continue with the next security environment xmlSecEncCtxDestroy( pEncCtx ) ; pSecEnv->destroyKeysManager( pMngr ) ; //i39448 } } clearErrorRecorder(); return aTemplate; } /* XInitialization */ void SAL_CALL XMLEncryption_NssImpl :: initialize( const Sequence< Any >& /*aArguments*/ ) throw( Exception, RuntimeException ) { // TBD } ; /* XServiceInfo */ OUString SAL_CALL XMLEncryption_NssImpl :: getImplementationName() throw( RuntimeException ) { return impl_getImplementationName() ; } /* XServiceInfo */ sal_Bool SAL_CALL XMLEncryption_NssImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) { Sequence< OUString > seqServiceNames = getSupportedServiceNames() ; const OUString* pArray = seqServiceNames.getConstArray() ; for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) { if( *( pArray + i ) == serviceName ) return sal_True ; } return sal_False ; } /* XServiceInfo */ Sequence< OUString > SAL_CALL XMLEncryption_NssImpl :: getSupportedServiceNames() throw( RuntimeException ) { return impl_getSupportedServiceNames() ; } //Helper for XServiceInfo Sequence< OUString > XMLEncryption_NssImpl :: impl_getSupportedServiceNames() { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ; Sequence< OUString > seqServiceNames( 1 ) ; seqServiceNames.getArray()[0] = OUString("com.sun.star.xml.crypto.XMLEncryption") ; return seqServiceNames ; } OUString XMLEncryption_NssImpl :: impl_getImplementationName() throw( RuntimeException ) { return OUString("com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_NssImpl") ; } //Helper for registry Reference< XInterface > SAL_CALL XMLEncryption_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) { return Reference< XInterface >( *new XMLEncryption_NssImpl( aServiceManager ) ) ; } Reference< XSingleServiceFactory > XMLEncryption_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) { //Reference< XSingleServiceFactory > xFactory ; //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ; //return xFactory ; return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: delete.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2006-07-19 09:30:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif #ifndef _SWCRSR_HXX #include <swcrsr.hxx> #endif #include <svx/lrspitem.hxx> // #i23725# // --> OD 2006-07-10 #134369# #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DRAWBASE_HXX #include <drawbase.hxx> #endif // <-- inline void SwWrtShell::OpenMark() { StartAllAction(); ResetCursorStack(); KillPams(); SetMark(); } inline void SwWrtShell::CloseMark( BOOL bOkFlag ) { if( bOkFlag ) UpdateAttr(); else SwapPam(); ClearMark(); EndAllAction(); } // #i23725# BOOL SwWrtShell::TryRemoveIndent() { BOOL bResult = FALSE; SfxItemSet aAttrSet(GetAttrPool(), RES_LR_SPACE, RES_LR_SPACE); GetAttr(aAttrSet); SvxLRSpaceItem aItem = (const SvxLRSpaceItem &)aAttrSet.Get(RES_LR_SPACE); short aOldFirstLineOfst = aItem.GetTxtFirstLineOfst(); if (aOldFirstLineOfst > 0) { aItem.SetTxtFirstLineOfst(0); bResult = TRUE; } else if (aOldFirstLineOfst < 0) { aItem.SetTxtFirstLineOfst(0); aItem.SetLeft(aItem.GetLeft() + aOldFirstLineOfst); bResult = TRUE; } else if (aItem.GetLeft() != 0) { aItem.SetLeft(0); bResult = TRUE; } if (bResult) { aAttrSet.Put(aItem); SetAttr(aAttrSet); } return bResult; } /*------------------------------------------------------------------------ Beschreibung: Zeile loeschen ------------------------------------------------------------------------*/ long SwWrtShell::DelLine() { ACT_KONTEXT(this); ResetCursorStack(); // alten Cursor merken Push(); ClearMark(); SwCrsrShell::LeftMargin(); SetMark(); SwCrsrShell::RightMargin(); //Warum soll hier noch ein Zeichen in der naechsten Zeile geloescht werden? // if(!IsEndOfPara()) // SwCrsrShell::Right(); long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfLine() { OpenMark(); SwCrsrShell::LeftMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfLine() { OpenMark(); SwCrsrShell::RightMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return 1; } long SwWrtShell::DelLeft() { // wenns denn ein Fly ist, wech damit int nSelType = GetSelectionType(); const int nCmp = SEL_FRM | SEL_GRF | SEL_OLE | SEL_DRW; if( nCmp & nSelType ) { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); nSelType = GetSelectionType(); if ( nCmp & nSelType ) { EnterSelFrmMode(); GotoNextFly(); } return 1L; } // wenn eine Selektion existiert, diese loeschen. if ( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); return 1L; } // JP 29.06.95: nie eine davor stehende Tabelle loeschen. BOOL bSwap = FALSE; const SwTableNode * pWasInTblNd = SwCrsrShell::IsCrsrInTbl(); if( SwCrsrShell::IsSttPara()) { /* If the cursor is at the beginning of a paragraph, try to step backwards. On failure we are done. */ if( !SwCrsrShell::Left(1,CRSR_SKIP_CHARS) ) return 0; /* If the cursor entered or left a table (or both) we are done. No step back. */ if( SwCrsrShell::IsCrsrInTbl() != pWasInTblNd ) return 0; OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CHARS); SwCrsrShell::SwapPam(); bSwap = TRUE; } else { OpenMark(); SwCrsrShell::Left(1,CRSR_SKIP_CHARS); } long nRet = Delete(); if( !nRet && bSwap ) SwCrsrShell::SwapPam(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelRight(BOOL bDelFrm) { // werden verodert, wenn Tabellenselektion vorliegt; // wird hier auf SEL_TBL umgesetzt. long nRet = 0; int nSelection = GetSelectionType(); if(nSelection & SwWrtShell::SEL_TBL_CELLS) nSelection = SwWrtShell::SEL_TBL; if(nSelection & SwWrtShell::SEL_TXT) nSelection = SwWrtShell::SEL_TXT; const SwTableNode * pWasInTblNd = NULL; switch( nSelection & ~(SEL_BEZ) ) { case SEL_TXT: case SEL_TBL: case SEL_NUM: // wenn eine Selektion existiert, diese loeschen. if( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); nRet = 1L; break; } pWasInTblNd = IsCrsrInTbl(); if( SEL_TXT & nSelection && SwCrsrShell::IsSttPara() && SwCrsrShell::IsEndPara() ) { // save cursor SwCrsrShell::Push(); bool bDelFull = false; if ( SwCrsrShell::Right(1,CRSR_SKIP_CHARS) ) { const SwTableNode * pCurrTblNd = IsCrsrInTbl(); bDelFull = pCurrTblNd && pCurrTblNd != pWasInTblNd; } // restore cursor SwCrsrShell::Pop( FALSE ); if( bDelFull ) { DelFullPara(); UpdateAttr(); break; } } { /* #108049# Save the startnode of the current cell */ const SwStartNode * pSNdOld; pSNdOld = GetSwCrsr()->GetNode()-> FindTableBoxStartNode(); if ( SwCrsrShell::IsEndPara() ) { // --> FME 2005-01-28 #i41424# Introduced a couple of // Push()-Pop() pairs here. The reason for this is thet a // Right()-Left() combination does not make sure, that // the cursor will be in its initial state, because there // may be a numbering in front of the next paragraph. SwCrsrShell::Push(); // <-- if ( SwCrsrShell::Right(1, CRSR_SKIP_CHARS) ) { if (IsCrsrInTbl() || (pWasInTblNd != IsCrsrInTbl())) { /* #108049# Save the startnode of the current cell. May be different to pSNdOld as we have moved. */ const SwStartNode * pSNdNew = GetSwCrsr() ->GetNode()->FindTableBoxStartNode(); /* #108049# Only move instead of deleting if we have moved to a different cell */ if (pSNdOld != pSNdNew) { SwCrsrShell::Pop( TRUE ); break; } } } // restore cursor SwCrsrShell::Pop( FALSE ); } } OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CELLS); nRet = Delete(); CloseMark( 0 != nRet ); break; case SEL_FRM: case SEL_GRF: case SEL_OLE: case SEL_DRW: case SEL_DRW_TXT: case SEL_DRW_FORM: { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); // --> OD 2006-07-06 #134369# ASSERT( !IsFrmSelected(), "<SwWrtShell::DelRight(..)> - <SwWrtShell::UnSelectFrm()> should unmark all objects" ) // <-- // --> OD 2006-07-10 #134369# // leave draw mode, if necessary. { if (GetView().GetDrawFuncPtr()) { GetView().GetDrawFuncPtr()->Deactivate(); GetView().SetDrawFuncPtr(NULL); } if ( GetView().IsDrawMode() ) { GetView().LeaveDrawCreate(); } } // <-- } // --> OD 2006-07-07 #134369# // <IsFrmSelected()> can't be true - see above. // <-- { nSelection = GetSelectionType(); if ( SEL_FRM & nSelection || SEL_GRF & nSelection || SEL_OLE & nSelection || SEL_DRW & nSelection ) { EnterSelFrmMode(); GotoNextFly(); } } nRet = 1; break; } return nRet; } long SwWrtShell::DelToEndOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaEnd)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaStart)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } /* * alle Loeschoperationen sollten mit Find statt mit * Nxt-/PrvDelim arbeiten, da letzteren mit Wrap Around arbeiten * -- das ist wohl nicht gewuenscht. */ long SwWrtShell::DelToStartOfSentence() { if(IsStartOfDoc()) return 0; OpenMark(); long nRet = _BwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfSentence() { if(IsEndOfDoc()) return 0; OpenMark(); long nRet = _FwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelNxtWord() { if(IsEndOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if(IsEndWrd() && !IsSttWrd()) _NxtWrd(); if(IsSttWrd() || IsEndPara()) _NxtWrd(); else _EndWrd(); long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } long SwWrtShell::DelPrvWord() { if(IsStartOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if( !IsSttWrd() || !_PrvWrd() ) { if( IsEndWrd() ) { if( _PrvWrd() ) { // skip over all-1 spaces short n = -1; while( ' ' == GetChar( FALSE, n )) --n; if( ++n ) ExtendSelection( FALSE, -n ); } } else if( IsSttPara()) _PrvWrd(); else _SttWrd(); } long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } <commit_msg>INTEGRATION: CWS pchfix02 (1.14.58); FILE MERGED 2006/09/01 17:53:36 kaib 1.14.58.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: delete.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:39:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif #ifndef _SWCRSR_HXX #include <swcrsr.hxx> #endif #include <svx/lrspitem.hxx> // #i23725# // --> OD 2006-07-10 #134369# #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DRAWBASE_HXX #include <drawbase.hxx> #endif // <-- inline void SwWrtShell::OpenMark() { StartAllAction(); ResetCursorStack(); KillPams(); SetMark(); } inline void SwWrtShell::CloseMark( BOOL bOkFlag ) { if( bOkFlag ) UpdateAttr(); else SwapPam(); ClearMark(); EndAllAction(); } // #i23725# BOOL SwWrtShell::TryRemoveIndent() { BOOL bResult = FALSE; SfxItemSet aAttrSet(GetAttrPool(), RES_LR_SPACE, RES_LR_SPACE); GetAttr(aAttrSet); SvxLRSpaceItem aItem = (const SvxLRSpaceItem &)aAttrSet.Get(RES_LR_SPACE); short aOldFirstLineOfst = aItem.GetTxtFirstLineOfst(); if (aOldFirstLineOfst > 0) { aItem.SetTxtFirstLineOfst(0); bResult = TRUE; } else if (aOldFirstLineOfst < 0) { aItem.SetTxtFirstLineOfst(0); aItem.SetLeft(aItem.GetLeft() + aOldFirstLineOfst); bResult = TRUE; } else if (aItem.GetLeft() != 0) { aItem.SetLeft(0); bResult = TRUE; } if (bResult) { aAttrSet.Put(aItem); SetAttr(aAttrSet); } return bResult; } /*------------------------------------------------------------------------ Beschreibung: Zeile loeschen ------------------------------------------------------------------------*/ long SwWrtShell::DelLine() { ACT_KONTEXT(this); ResetCursorStack(); // alten Cursor merken Push(); ClearMark(); SwCrsrShell::LeftMargin(); SetMark(); SwCrsrShell::RightMargin(); //Warum soll hier noch ein Zeichen in der naechsten Zeile geloescht werden? // if(!IsEndOfPara()) // SwCrsrShell::Right(); long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfLine() { OpenMark(); SwCrsrShell::LeftMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfLine() { OpenMark(); SwCrsrShell::RightMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return 1; } long SwWrtShell::DelLeft() { // wenns denn ein Fly ist, wech damit int nSelType = GetSelectionType(); const int nCmp = SEL_FRM | SEL_GRF | SEL_OLE | SEL_DRW; if( nCmp & nSelType ) { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); nSelType = GetSelectionType(); if ( nCmp & nSelType ) { EnterSelFrmMode(); GotoNextFly(); } return 1L; } // wenn eine Selektion existiert, diese loeschen. if ( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); return 1L; } // JP 29.06.95: nie eine davor stehende Tabelle loeschen. BOOL bSwap = FALSE; const SwTableNode * pWasInTblNd = SwCrsrShell::IsCrsrInTbl(); if( SwCrsrShell::IsSttPara()) { /* If the cursor is at the beginning of a paragraph, try to step backwards. On failure we are done. */ if( !SwCrsrShell::Left(1,CRSR_SKIP_CHARS) ) return 0; /* If the cursor entered or left a table (or both) we are done. No step back. */ if( SwCrsrShell::IsCrsrInTbl() != pWasInTblNd ) return 0; OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CHARS); SwCrsrShell::SwapPam(); bSwap = TRUE; } else { OpenMark(); SwCrsrShell::Left(1,CRSR_SKIP_CHARS); } long nRet = Delete(); if( !nRet && bSwap ) SwCrsrShell::SwapPam(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelRight(BOOL bDelFrm) { // werden verodert, wenn Tabellenselektion vorliegt; // wird hier auf SEL_TBL umgesetzt. long nRet = 0; int nSelection = GetSelectionType(); if(nSelection & SwWrtShell::SEL_TBL_CELLS) nSelection = SwWrtShell::SEL_TBL; if(nSelection & SwWrtShell::SEL_TXT) nSelection = SwWrtShell::SEL_TXT; const SwTableNode * pWasInTblNd = NULL; switch( nSelection & ~(SEL_BEZ) ) { case SEL_TXT: case SEL_TBL: case SEL_NUM: // wenn eine Selektion existiert, diese loeschen. if( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); nRet = 1L; break; } pWasInTblNd = IsCrsrInTbl(); if( SEL_TXT & nSelection && SwCrsrShell::IsSttPara() && SwCrsrShell::IsEndPara() ) { // save cursor SwCrsrShell::Push(); bool bDelFull = false; if ( SwCrsrShell::Right(1,CRSR_SKIP_CHARS) ) { const SwTableNode * pCurrTblNd = IsCrsrInTbl(); bDelFull = pCurrTblNd && pCurrTblNd != pWasInTblNd; } // restore cursor SwCrsrShell::Pop( FALSE ); if( bDelFull ) { DelFullPara(); UpdateAttr(); break; } } { /* #108049# Save the startnode of the current cell */ const SwStartNode * pSNdOld; pSNdOld = GetSwCrsr()->GetNode()-> FindTableBoxStartNode(); if ( SwCrsrShell::IsEndPara() ) { // --> FME 2005-01-28 #i41424# Introduced a couple of // Push()-Pop() pairs here. The reason for this is thet a // Right()-Left() combination does not make sure, that // the cursor will be in its initial state, because there // may be a numbering in front of the next paragraph. SwCrsrShell::Push(); // <-- if ( SwCrsrShell::Right(1, CRSR_SKIP_CHARS) ) { if (IsCrsrInTbl() || (pWasInTblNd != IsCrsrInTbl())) { /* #108049# Save the startnode of the current cell. May be different to pSNdOld as we have moved. */ const SwStartNode * pSNdNew = GetSwCrsr() ->GetNode()->FindTableBoxStartNode(); /* #108049# Only move instead of deleting if we have moved to a different cell */ if (pSNdOld != pSNdNew) { SwCrsrShell::Pop( TRUE ); break; } } } // restore cursor SwCrsrShell::Pop( FALSE ); } } OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CELLS); nRet = Delete(); CloseMark( 0 != nRet ); break; case SEL_FRM: case SEL_GRF: case SEL_OLE: case SEL_DRW: case SEL_DRW_TXT: case SEL_DRW_FORM: { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); // --> OD 2006-07-06 #134369# ASSERT( !IsFrmSelected(), "<SwWrtShell::DelRight(..)> - <SwWrtShell::UnSelectFrm()> should unmark all objects" ) // <-- // --> OD 2006-07-10 #134369# // leave draw mode, if necessary. { if (GetView().GetDrawFuncPtr()) { GetView().GetDrawFuncPtr()->Deactivate(); GetView().SetDrawFuncPtr(NULL); } if ( GetView().IsDrawMode() ) { GetView().LeaveDrawCreate(); } } // <-- } // --> OD 2006-07-07 #134369# // <IsFrmSelected()> can't be true - see above. // <-- { nSelection = GetSelectionType(); if ( SEL_FRM & nSelection || SEL_GRF & nSelection || SEL_OLE & nSelection || SEL_DRW & nSelection ) { EnterSelFrmMode(); GotoNextFly(); } } nRet = 1; break; } return nRet; } long SwWrtShell::DelToEndOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaEnd)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaStart)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } /* * alle Loeschoperationen sollten mit Find statt mit * Nxt-/PrvDelim arbeiten, da letzteren mit Wrap Around arbeiten * -- das ist wohl nicht gewuenscht. */ long SwWrtShell::DelToStartOfSentence() { if(IsStartOfDoc()) return 0; OpenMark(); long nRet = _BwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfSentence() { if(IsEndOfDoc()) return 0; OpenMark(); long nRet = _FwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelNxtWord() { if(IsEndOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if(IsEndWrd() && !IsSttWrd()) _NxtWrd(); if(IsSttWrd() || IsEndPara()) _NxtWrd(); else _EndWrd(); long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } long SwWrtShell::DelPrvWord() { if(IsStartOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if( !IsSttWrd() || !_PrvWrd() ) { if( IsEndWrd() ) { if( _PrvWrd() ) { // skip over all-1 spaces short n = -1; while( ' ' == GetChar( FALSE, n )) --n; if( ++n ) ExtendSelection( FALSE, -n ); } } else if( IsSttPara()) _PrvWrd(); else _SttWrd(); } long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } <|endoftext|>
<commit_before>// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler 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/>. */ /*}}}*/ /* $Id$ */ // INCLUDE/*{{{*/ #include <string> #include <gloox/gloox.h> /*}}}*/ std::string &generateErrorText(/*{{{*/ gloox::ConnectionError connectionError, gloox::StreamError streamError, const std::string &streamErrorText, gloox::AuthenticationError authError) { std::string text; switch (connectionError) { case gloox::ConnNoError: break; case gloox::ConnStreamError: { text = "A stream error occured: "; switch (streamError) { case gloox::StreamErrorUndefined: text += "Undefined/unknown error."; break; case gloox::StreamErrorBadFormat: text += "The entity has sent XML that cannot be processed."; break; case gloox::StreamErrorBadNamespacePrefix: text += "The entity has sent a namespace prefix that is " "unsupported, or has sent no namespace prefix on an " "element that requires such a prefix."; break; case gloox::StreamErrorConflict: text += "The server is closing the active stream for this " "entity because a new stream has been initiated that " "conflicts with the existing stream."; break; case gloox::StreamErrorConnectionTimeout: text += "The entity has not generated any traffic over the " "stream for some period of time."; break; case gloox::StreamErrorHostGone: text += "The value of the 'to' attribute provided by the " "initiating entity in the stream header corresponds to " "a hostname that is no longer hosted by the server."; break; case gloox::StreamErrorHostUnknown: text += "The value of the 'to' attribute provided by the " "initiating entity in the stream header does not " "correspond to a hostname that is hosted by the " "server."; break; case gloox::StreamErrorImproperAddressing: text += "A stanza sent between two servers lacks a 'to' or " "'from' attribute."; break; case gloox::StreamErrorInternalServerError: text += "The server has experienced a misconfiguration or an " "otherwise-undefined internal error that prevents it " "from servicing the stream."; break; case gloox::StreamErrorInvalidFrom: text += "The JID or hostname provided in a 'from' address does " "not match an authorized JID or validated domain " "negotiated between servers via SASL or dialback, or " "between a client and a server via authentication and " "resource binding."; break; case gloox::StreamErrorInvalidId: text += "The stream ID or dialback ID is invalid or does not " "match an ID previously provided."; break; case gloox::StreamErrorInvalidNamespace: text += "The streams namespace name is something other than " "\"http://etherx.jabber.org/streams\" or the dialback " "namespace name is something other than " "\"jabber:server:dialback\"."; break; case gloox::StreamErrorInvalidXml: text += "The entity has sent invalid XML over the stream to a " "server that performs validation."; break; case gloox::StreamErrorNotAuthorized: text += "The entity has attempted to send data before the " "stream has been authenticated, or otherwise is not " "authorized to perform an action related to stream " "negotiation."; break; case gloox::StreamErrorPolicyViolation: text += "The entity has violated some local service policy."; break; case gloox::StreamErrorRemoteConnectionFailed: text += "The server is unable to properly connect to a remote " "entity that is required for authentication or " "authorization."; break; case gloox::StreamErrorResourceConstraint: text += "The server lacks the system resources necessary to " "service the stream."; break; case gloox::StreamErrorRestrictedXml: text += "The entity has attempted to send restricted XML " "features."; break; case gloox::StreamErrorSeeOtherHost: text += "The server will not provide service to the initiating " "entity but is redirecting traffic to another host."; break; case gloox::StreamErrorSystemShutdown: text += "The server is being shut down and all active streams " "are being closed."; break; case gloox::StreamErrorUndefinedCondition: text += "The error condition is not one of those defined by " "the other conditions in this list."; break; case gloox::StreamErrorUnsupportedEncoding: text += "The initiating entity has encoded the stream in an " "encoding that is not supported by the server."; break; case gloox::StreamErrorUnsupportedStanzaType: text += "The initiating entity has sent a first-level child of " "the stream that is not supported by the server."; break; case gloox::StreamErrorUnsupportedVersion: text += "The initiating entity specifies a version of XMPP " "that is not supported by the server."; break; case gloox::StreamErrorXmlNotWellFormed: text += "The initiating entity has sent XML that is not " "well-formed."; break; default: text += "Unknown error."; break; } if (!streamErrorText.empty()) text += " (Addition information: " + streamErrorText + ")"; } case gloox::ConnStreamVersionError: text = "The incoming stream's version is not supported."; break; case gloox::ConnStreamClosed: text = "The stream has been closed by the server."; break; case gloox::ConnProxyAuthRequired: text = "The HTTP/SOCKS5 proxy requires authentication."; break; case gloox::ConnProxyAuthFailed: text = "The HTTP/SOCKS5 proxy authentication failed."; break; case gloox::ConnProxyNoSupportedAuth: text = "The HTTP/SOCKS5 proxy requires an unsupported auth " "mechanism."; break; case gloox::ConnIoError: text = "An I/O error occured."; break; case gloox::ConnParseError: text = "An XML parse error occured."; break; case gloox::ConnConnectionRefused: text = "The connection was refused by the server (on the socket " "level)."; break; case gloox::ConnDnsError: text = "Resolving the server's hostname failed."; break; case gloox::ConnOutOfMemory: text = "Out of memory."; break; case gloox::ConnNoSupportedAuth: text = "The auth mechanisms the server offers are not supported " "or the server offered no auth mechanisms at all."; break; case gloox::ConnTlsFailed: text = "The server's certificate could not be verified or the TLS " "handshake did not complete successfully."; break; case gloox::ConnTlsNotAvailable: text = "The server doesn't offer TLS."; break; case gloox::ConnCompressionFailed: text = "Negotiating or initializing compression failed."; break; case gloox::ConnAuthenticationFailed: text = "Authentication failed: "; switch (authError) { case gloox::AuthErrorUndefined: text += "Error condition unknown."; break; case gloox::SaslAborted: text += "The receiving entity acknowledges an abort sent by " "the initiating entity."; break; case gloox::SaslIncorrectEncoding: text += "The data provided by the initiating entity could not " "be processed because the [BASE64] encoding is " "incorrect."; break; case gloox::SaslInvalidAuthzid: text += "The authzid provided by the initiating entity is " "invalid, either because it is incorrectly formatted " "or because the initiating entity does not have " "permissions to authorize that ID."; break; case gloox::SaslInvalidMechanism: text += "The initiating entity did not provide a mechanism or " "requested a mechanism that is not supported by the " "receiving entity."; break; case gloox::SaslMalformedRequest: text += "The request is malformed."; break; case gloox::SaslMechanismTooWeak: text += "The mechanism requested by the initiating entity is " "weaker than server policy permits for that initiating " "entity."; break; case gloox::SaslNotAuthorized: text += "The authentication failed because the initiating " "entity did not provide valid credentials."; break; case gloox::SaslTemporaryAuthFailure: text += "The authentication failed because of a temporary " "error condition within the receiving entity."; break; case gloox::NonSaslConflict: text += "Resource conflict."; break; case gloox::NonSaslNotAcceptable: text += "Required Information not provided."; break; case gloox::NonSaslNotAuthorized: text += "Incorrect credentials."; break; default: text += "Unknown error."; } break; case gloox::ConnUserDisconnected: // The user (or higher-level protocol) requested a disconnect. break; case gloox::ConnNotConnected: text = "There is no active connection."; break; default: text = "An unknown error occured."; } }/*}}}*/ // Use no tabs at all; four spaces indentation; max. eighty chars per line. // vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker <commit_msg>Fix: generateErrorText return<commit_after>// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler 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/>. */ /*}}}*/ /* $Id$ */ // INCLUDE/*{{{*/ #include <string> #include <gloox/gloox.h> /*}}}*/ std::string &generateErrorText(/*{{{*/ gloox::ConnectionError connectionError, gloox::StreamError streamError, const std::string &streamErrorText, gloox::AuthenticationError authError) { static std::string text; switch (connectionError) { case gloox::ConnNoError: break; case gloox::ConnStreamError: { text = "A stream error occured: "; switch (streamError) { case gloox::StreamErrorUndefined: text += "Undefined/unknown error."; break; case gloox::StreamErrorBadFormat: text += "The entity has sent XML that cannot be processed."; break; case gloox::StreamErrorBadNamespacePrefix: text += "The entity has sent a namespace prefix that is " "unsupported, or has sent no namespace prefix on an " "element that requires such a prefix."; break; case gloox::StreamErrorConflict: text += "The server is closing the active stream for this " "entity because a new stream has been initiated that " "conflicts with the existing stream."; break; case gloox::StreamErrorConnectionTimeout: text += "The entity has not generated any traffic over the " "stream for some period of time."; break; case gloox::StreamErrorHostGone: text += "The value of the 'to' attribute provided by the " "initiating entity in the stream header corresponds to " "a hostname that is no longer hosted by the server."; break; case gloox::StreamErrorHostUnknown: text += "The value of the 'to' attribute provided by the " "initiating entity in the stream header does not " "correspond to a hostname that is hosted by the " "server."; break; case gloox::StreamErrorImproperAddressing: text += "A stanza sent between two servers lacks a 'to' or " "'from' attribute."; break; case gloox::StreamErrorInternalServerError: text += "The server has experienced a misconfiguration or an " "otherwise-undefined internal error that prevents it " "from servicing the stream."; break; case gloox::StreamErrorInvalidFrom: text += "The JID or hostname provided in a 'from' address does " "not match an authorized JID or validated domain " "negotiated between servers via SASL or dialback, or " "between a client and a server via authentication and " "resource binding."; break; case gloox::StreamErrorInvalidId: text += "The stream ID or dialback ID is invalid or does not " "match an ID previously provided."; break; case gloox::StreamErrorInvalidNamespace: text += "The streams namespace name is something other than " "\"http://etherx.jabber.org/streams\" or the dialback " "namespace name is something other than " "\"jabber:server:dialback\"."; break; case gloox::StreamErrorInvalidXml: text += "The entity has sent invalid XML over the stream to a " "server that performs validation."; break; case gloox::StreamErrorNotAuthorized: text += "The entity has attempted to send data before the " "stream has been authenticated, or otherwise is not " "authorized to perform an action related to stream " "negotiation."; break; case gloox::StreamErrorPolicyViolation: text += "The entity has violated some local service policy."; break; case gloox::StreamErrorRemoteConnectionFailed: text += "The server is unable to properly connect to a remote " "entity that is required for authentication or " "authorization."; break; case gloox::StreamErrorResourceConstraint: text += "The server lacks the system resources necessary to " "service the stream."; break; case gloox::StreamErrorRestrictedXml: text += "The entity has attempted to send restricted XML " "features."; break; case gloox::StreamErrorSeeOtherHost: text += "The server will not provide service to the initiating " "entity but is redirecting traffic to another host."; break; case gloox::StreamErrorSystemShutdown: text += "The server is being shut down and all active streams " "are being closed."; break; case gloox::StreamErrorUndefinedCondition: text += "The error condition is not one of those defined by " "the other conditions in this list."; break; case gloox::StreamErrorUnsupportedEncoding: text += "The initiating entity has encoded the stream in an " "encoding that is not supported by the server."; break; case gloox::StreamErrorUnsupportedStanzaType: text += "The initiating entity has sent a first-level child of " "the stream that is not supported by the server."; break; case gloox::StreamErrorUnsupportedVersion: text += "The initiating entity specifies a version of XMPP " "that is not supported by the server."; break; case gloox::StreamErrorXmlNotWellFormed: text += "The initiating entity has sent XML that is not " "well-formed."; break; default: text += "Unknown error."; break; } if (!streamErrorText.empty()) text += " (Addition information: " + streamErrorText + ")"; } case gloox::ConnStreamVersionError: text = "The incoming stream's version is not supported."; break; case gloox::ConnStreamClosed: text = "The stream has been closed by the server."; break; case gloox::ConnProxyAuthRequired: text = "The HTTP/SOCKS5 proxy requires authentication."; break; case gloox::ConnProxyAuthFailed: text = "The HTTP/SOCKS5 proxy authentication failed."; break; case gloox::ConnProxyNoSupportedAuth: text = "The HTTP/SOCKS5 proxy requires an unsupported auth " "mechanism."; break; case gloox::ConnIoError: text = "An I/O error occured."; break; case gloox::ConnParseError: text = "An XML parse error occured."; break; case gloox::ConnConnectionRefused: text = "The connection was refused by the server (on the socket " "level)."; break; case gloox::ConnDnsError: text = "Resolving the server's hostname failed."; break; case gloox::ConnOutOfMemory: text = "Out of memory."; break; case gloox::ConnNoSupportedAuth: text = "The auth mechanisms the server offers are not supported " "or the server offered no auth mechanisms at all."; break; case gloox::ConnTlsFailed: text = "The server's certificate could not be verified or the TLS " "handshake did not complete successfully."; break; case gloox::ConnTlsNotAvailable: text = "The server doesn't offer TLS."; break; case gloox::ConnCompressionFailed: text = "Negotiating or initializing compression failed."; break; case gloox::ConnAuthenticationFailed: text = "Authentication failed: "; switch (authError) { case gloox::AuthErrorUndefined: text += "Error condition unknown."; break; case gloox::SaslAborted: text += "The receiving entity acknowledges an abort sent by " "the initiating entity."; break; case gloox::SaslIncorrectEncoding: text += "The data provided by the initiating entity could not " "be processed because the [BASE64] encoding is " "incorrect."; break; case gloox::SaslInvalidAuthzid: text += "The authzid provided by the initiating entity is " "invalid, either because it is incorrectly formatted " "or because the initiating entity does not have " "permissions to authorize that ID."; break; case gloox::SaslInvalidMechanism: text += "The initiating entity did not provide a mechanism or " "requested a mechanism that is not supported by the " "receiving entity."; break; case gloox::SaslMalformedRequest: text += "The request is malformed."; break; case gloox::SaslMechanismTooWeak: text += "The mechanism requested by the initiating entity is " "weaker than server policy permits for that initiating " "entity."; break; case gloox::SaslNotAuthorized: text += "The authentication failed because the initiating " "entity did not provide valid credentials."; break; case gloox::SaslTemporaryAuthFailure: text += "The authentication failed because of a temporary " "error condition within the receiving entity."; break; case gloox::NonSaslConflict: text += "Resource conflict."; break; case gloox::NonSaslNotAcceptable: text += "Required Information not provided."; break; case gloox::NonSaslNotAuthorized: text += "Incorrect credentials."; break; default: text += "Unknown error."; } break; case gloox::ConnUserDisconnected: // The user (or higher-level protocol) requested a disconnect. break; case gloox::ConnNotConnected: text = "There is no active connection."; break; default: text = "An unknown error occured."; } return text; }/*}}}*/ // Use no tabs at all; four spaces indentation; max. eighty chars per line. // vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2006 by Lukáš Lalinský email : [email protected] copyright : (C) 2004 by Allan Sandfeld Jensen email : [email protected] (original MPC implementation) ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <id3v2tag.h> #include "aifffile.h" using namespace TagLib; class RIFF::AIFF::File::FilePrivate { public: FilePrivate() : properties(0), tag(0) { } ~FilePrivate() { delete properties; delete tag; } Properties *properties; ID3v2::Tag *tag; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// RIFF::AIFF::File::File(FileName file, bool readProperties, Properties::ReadStyle propertiesStyle) : RIFF::File(file, BigEndian) { d = new FilePrivate; if(isOpen()) read(readProperties, propertiesStyle); } RIFF::AIFF::File::~File() { delete d; } ID3v2::Tag *RIFF::AIFF::File::tag() const { return d->tag; } RIFF::AIFF::Properties *RIFF::AIFF::File::audioProperties() const { return d->properties; } bool RIFF::AIFF::File::save() { if(readOnly()) { debug("RIFF::AIFF::File::save() -- File is read only."); return false; } setChunkData("ID3 ", d->tag->render()); return true; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void RIFF::AIFF::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) { for(uint i = 0; i < chunkCount(); i++) { if(chunkName(i) == "ID3 ") d->tag = new ID3v2::Tag(this, chunkOffset(i)); else if(chunkName(i) == "COMM" && readProperties) d->properties = new Properties(chunkData(i), propertiesStyle); } if(!d->tag) d->tag = new ID3v2::Tag; } <commit_msg>wrong copyright<commit_after>/*************************************************************************** copyright : (C) 2008 by Scott Wheeler email : [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. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <id3v2tag.h> #include "aifffile.h" using namespace TagLib; class RIFF::AIFF::File::FilePrivate { public: FilePrivate() : properties(0), tag(0) { } ~FilePrivate() { delete properties; delete tag; } Properties *properties; ID3v2::Tag *tag; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// RIFF::AIFF::File::File(FileName file, bool readProperties, Properties::ReadStyle propertiesStyle) : RIFF::File(file, BigEndian) { d = new FilePrivate; if(isOpen()) read(readProperties, propertiesStyle); } RIFF::AIFF::File::~File() { delete d; } ID3v2::Tag *RIFF::AIFF::File::tag() const { return d->tag; } RIFF::AIFF::Properties *RIFF::AIFF::File::audioProperties() const { return d->properties; } bool RIFF::AIFF::File::save() { if(readOnly()) { debug("RIFF::AIFF::File::save() -- File is read only."); return false; } setChunkData("ID3 ", d->tag->render()); return true; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void RIFF::AIFF::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) { for(uint i = 0; i < chunkCount(); i++) { if(chunkName(i) == "ID3 ") d->tag = new ID3v2::Tag(this, chunkOffset(i)); else if(chunkName(i) == "COMM" && readProperties) d->properties = new Properties(chunkData(i), propertiesStyle); } if(!d->tag) d->tag = new ID3v2::Tag; } <|endoftext|>
<commit_before>#ifndef CALLBACK_HPP #define CALLBACK_HPP #include "noncopyable.hpp" #include <type_traits> #include <cstring> struct callback_t : private noncopyable_t { enum {INTERNAL_STORAGE_SIZE = 64}; template <typename T> callback_t(T &&object) { typedef typename std::remove_reference<T>::type unref_type; const size_t alignment = std::alignment_of<unref_type>::value; static_assert(sizeof(unref_type) + alignment < INTERNAL_STORAGE_SIZE, "functional object don't fit into internal storage"); m_object_ptr = new (m_storage + alignment) unref_type(std::forward<T>(object)); m_method_ptr = &method_stub<unref_type>; m_delete_ptr = &delete_stub<unref_type>; } callback_t(callback_t &&o) { move_from_other(o); } callback_t & operator=(callback_t &&o) { move_from_other(o); return *this; } ~callback_t() { if (m_delete_ptr) { (*m_delete_ptr)(m_object_ptr); } } void operator()() const { if (m_method_ptr) { (*m_method_ptr)(m_object_ptr); } } private: char m_storage[INTERNAL_STORAGE_SIZE]; void *m_object_ptr = m_storage; typedef void (*method_type)(void *); method_type m_method_ptr = nullptr; method_type m_delete_ptr = nullptr; void move_from_other(callback_t &o) { size_t o_alignment = o.m_method_ptr - o.m_storage; m_object_ptr = m_storage + o_alignment; m_method_ptr = o.m_method_ptr; m_delete_ptr = o.m_delete_ptr; memcpy(m_storage, o.m_storage, INTERNAL_STORAGE_SIZE); o.m_method_ptr = nullptr; o.m_delete_ptr = nullptr; } template <class T> static void method_stub(void *object_ptr) { static_cast<T *>(object_ptr)->operator()(); } template <class T> static void delete_stub(void *object_ptr) { static_cast<T *>(object_ptr)->~T(); } }; #endif // CALLBACK_HPP <commit_msg>brackets<commit_after>#ifndef CALLBACK_HPP #define CALLBACK_HPP #include "noncopyable.hpp" #include <type_traits> #include <cstring> template <size_t STORAGE_SIZE = 32> struct callback_t : private noncopyable_t { template <typename T> callback_t(T &&object) { typedef typename std::remove_reference<T>::type unref_type; const size_t alignment = std::alignment_of<unref_type>::value; static_assert(sizeof(unref_type) + alignment < STORAGE_SIZE, "functional object don't fit into internal storage"); m_object_ptr = new (m_storage + alignment) unref_type(std::forward<T>(object)); m_method_ptr = &method_stub<unref_type>; m_delete_ptr = &delete_stub<unref_type>; } callback_t(callback_t &&o) { move_from_other(o); } callback_t & operator=(callback_t &&o) { move_from_other(o); return *this; } ~callback_t() { if (m_delete_ptr) { (*m_delete_ptr)(m_object_ptr); } } void operator()() const { if (m_method_ptr) { (*m_method_ptr)(m_object_ptr); } } private: char m_storage[STORAGE_SIZE]; void *m_object_ptr = m_storage; typedef void (*method_type)(void *); method_type m_method_ptr = nullptr; method_type m_delete_ptr = nullptr; void move_from_other(callback_t &o) { const size_t o_alignment = o.m_method_ptr - o.m_storage; m_object_ptr = m_storage + o_alignment; m_method_ptr = o.m_method_ptr; m_delete_ptr = o.m_delete_ptr; memcpy(m_storage, o.m_storage, STORAGE_SIZE); o.m_method_ptr = nullptr; o.m_delete_ptr = nullptr; } template <class T> static void method_stub(void *object_ptr) { static_cast<T *>(object_ptr)->operator()(); } template <class T> static void delete_stub(void *object_ptr) { static_cast<T *>(object_ptr)->~T(); } }; #endif // CALLBACK_HPP <|endoftext|>
<commit_before>// @(#)root/tmva $\Id$ // Author: Andreas Hoecker, Peter Speckmayer /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : MetricEuler * * Web : http://tmva.sourceforge.net * * * * Description: * * Implementation * * * * Authors (alphabetical): * * Peter Speckmayer <[email protected]> - CERN, Switzerland * * * * Copyright (c) 2005: * * CERN, Switzerland * * MPI-K Heidelberg, Germany * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ //_______________________________________________________________________ // // interface for a metric // //_______________________________________________________________________ #include "TMVA/MetricEuler.h" ClassImp(TMVA::MetricEuler) //_______________________________________________________________________ TMVA::MetricEuler::MetricEuler() : IMetric() { // constructor } //_______________________________________________________________________ Double_t TMVA::MetricEuler::Distance( std::vector<Double_t>& pointA, std::vector<Double_t>& pointB ) { Double_t distance = 0.0; Double_t val = 0.0; std::vector<Double_t>::iterator itA; std::vector<Double_t>::iterator itB; if( fParameters == NULL ){ itA = pointA.begin(); for( itB = pointB.begin(); itB != pointB.end(); itB++ ){ if( itA == pointA.end() ){ break; } val = (*itA)-(*itB); distance += pow( val, 2 ); itA++; } }else{ std::vector<Double_t>::iterator itPar; itA = pointA.begin(); itPar = fParameters->begin(); for( itB = pointB.begin(); itB != pointB.end(); itB++ ){ if( itA == pointA.end() ){ break; } if( itPar == fParameters->end() ){ break; } val = (*itPar)*( (*itA)-(*itB) ); distance += pow( val, 2 ); itA++; itPar++; } if( itA != pointA.end() ){ distance *= pow( (*itA),2 ); } } return sqrt( distance ); } <commit_msg>From Lorenzo: Fix for MacOS<commit_after>// @(#)root/tmva $\Id$ // Author: Andreas Hoecker, Peter Speckmayer /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : MetricEuler * * Web : http://tmva.sourceforge.net * * * * Description: * * Implementation * * * * Authors (alphabetical): * * Peter Speckmayer <[email protected]> - CERN, Switzerland * * * * Copyright (c) 2005: * * CERN, Switzerland * * MPI-K Heidelberg, Germany * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ //_______________________________________________________________________ // // interface for a metric // //_______________________________________________________________________ #include "TMVA/MetricEuler.h" #include <cmath> ClassImp(TMVA::MetricEuler) //_______________________________________________________________________ TMVA::MetricEuler::MetricEuler() : IMetric() { // constructor } //_______________________________________________________________________ Double_t TMVA::MetricEuler::Distance( std::vector<Double_t>& pointA, std::vector<Double_t>& pointB ) { Double_t distance = 0.0; Double_t val = 0.0; std::vector<Double_t>::iterator itA; std::vector<Double_t>::iterator itB; if( fParameters == NULL ){ itA = pointA.begin(); for( itB = pointB.begin(); itB != pointB.end(); itB++ ){ if( itA == pointA.end() ){ break; } val = (*itA)-(*itB); distance += std::pow( val, 2 ); itA++; } }else{ std::vector<Double_t>::iterator itPar; itA = pointA.begin(); itPar = fParameters->begin(); for( itB = pointB.begin(); itB != pointB.end(); itB++ ){ if( itA == pointA.end() ){ break; } if( itPar == fParameters->end() ){ break; } val = (*itPar)*( (*itA)-(*itB) ); distance += std::pow( val, 2 ); itA++; itPar++; } if( itA != pointA.end() ){ distance *= std::pow( (*itA),2 ); } } return sqrt( distance ); } <|endoftext|>
<commit_before><commit_msg>add missing include<commit_after><|endoftext|>
<commit_before>/** *Licensed to the Apache Software Foundation (ASF) under one *or more contributor license agreements. See the NOTICE file *distributed with this work for additional information *regarding copyright ownership. The ASF licenses this file *to you 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 <sstream> #include <arpa/inet.h> #include <pubsub_wire_v2_protocol_common.h> #include "gtest/gtest.h" #include "pubsub_wire_v2_protocol_impl.h" #include "celix_byteswap.h" #include <cstring> class WireProtocolV2Test : public ::testing::Test { public: WireProtocolV2Test() = default; ~WireProtocolV2Test() override = default; }; TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeHeader_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); pubsub_protocol_message_t message; message.header.msgId = 1; message.header.seqNr = 4; message.header.msgMajorVersion = 0; message.header.msgMinorVersion = 0; message.header.payloadSize = 2; message.header.metadataSize = 3; message.header.payloadPartSize = 4; message.header.payloadOffset = 2; message.header.isLastSegment = 1; message.header.convertEndianess = 1; void *headerData = nullptr; size_t headerLength = 0; celix_status_t status = pubsubProtocol_wire_v2_encodeHeader(nullptr, &message, &headerData, &headerLength); unsigned char exp[40]; uint32_t s = bswap_32(0xABBADEAF); memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x04000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); uint32_t pps = 0x04000000; memcpy(exp+28, &pps, sizeof(uint32_t)); uint32_t ppo = 0x02000000; memcpy(exp+32, &ppo, sizeof(uint32_t)); uint32_t ils = 0x01000000; memcpy(exp+36, &ils, sizeof(uint32_t)); ASSERT_EQ(status, CELIX_SUCCESS); ASSERT_EQ(40, headerLength); for (int i = 0; i < 40; i++) { ASSERT_EQ(((unsigned char*) headerData)[i], exp[i]); } pubsubProtocol_wire_v2_destroy(wireprotocol); free(headerData); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = bswap_32(0xABBADEAF); memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); uint32_t pps = 0x04000000; memcpy(exp+28, &pps, sizeof(uint32_t)); uint32_t ppo = 0x02000000; memcpy(exp+32, &ppo, sizeof(uint32_t)); uint32_t ils = 0x01000000; memcpy(exp+36, &ils, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_SUCCESS, status); ASSERT_EQ(1, message.header.msgId); ASSERT_EQ(8, message.header.seqNr); ASSERT_EQ(0, message.header.msgMajorVersion); ASSERT_EQ(0, message.header.msgMinorVersion); ASSERT_EQ(2, message.header.payloadSize); ASSERT_EQ(3, message.header.metadataSize); ASSERT_EQ(4, message.header.payloadPartSize); ASSERT_EQ(2, message.header.payloadOffset); ASSERT_EQ(1, message.header.isLastSegment); ASSERT_EQ(1, message.header.convertEndianess); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectSync_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = 0xBAABABBA; memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectVersion_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = 0xABBADEAF; memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x02000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeFooter_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); pubsub_protocol_message_t message; void *footerData = nullptr; size_t footerLength = 0; celix_status_t status = pubsubProtocol_wire_v2_encodeFooter(nullptr, &message, &footerData, &footerLength); unsigned char exp[4]; uint32_t s = 0xDEAFABBA; memcpy(exp, &s, sizeof(uint32_t)); ASSERT_EQ(status, CELIX_SUCCESS); ASSERT_EQ(4, footerLength); for (int i = 0; i < 4; i++) { ASSERT_EQ(((unsigned char*) footerData)[i], exp[i]); } pubsubProtocol_wire_v2_destroy(wireprotocol); free(footerData); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[4]; uint32_t s = 0xDEAFABBA; memcpy(exp, &s, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message); ASSERT_EQ(CELIX_SUCCESS, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_IncorrectSync_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[4]; uint32_t s = 0xABBADEAF; memcpy(exp, &s, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); }<commit_msg>Fix wire_v2 unit test<commit_after>/** *Licensed to the Apache Software Foundation (ASF) under one *or more contributor license agreements. See the NOTICE file *distributed with this work for additional information *regarding copyright ownership. The ASF licenses this file *to you 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 <sstream> #include <arpa/inet.h> #include <pubsub_wire_v2_protocol_common.h> #include "gtest/gtest.h" #include "pubsub_wire_v2_protocol_impl.h" #include "celix_byteswap.h" #include <cstring> class WireProtocolV2Test : public ::testing::Test { public: WireProtocolV2Test() = default; ~WireProtocolV2Test() override = default; }; TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeHeader_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); pubsub_protocol_message_t message; message.header.msgId = 1; message.header.seqNr = 4; message.header.msgMajorVersion = 0; message.header.msgMinorVersion = 0; message.header.payloadSize = 2; message.header.metadataSize = 3; message.header.payloadPartSize = 4; message.header.payloadOffset = 2; message.header.isLastSegment = 1; message.header.convertEndianess = 1; void *headerData = nullptr; size_t headerLength = 0; celix_status_t status = pubsubProtocol_wire_v2_encodeHeader(nullptr, &message, &headerData, &headerLength); unsigned char exp[40]; uint32_t s = bswap_32(0xABBADEAF); memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x04000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); uint32_t pps = 0x04000000; memcpy(exp+28, &pps, sizeof(uint32_t)); uint32_t ppo = 0x02000000; memcpy(exp+32, &ppo, sizeof(uint32_t)); uint32_t ils = 0x01000000; memcpy(exp+36, &ils, sizeof(uint32_t)); ASSERT_EQ(status, CELIX_SUCCESS); ASSERT_EQ(40, headerLength); for (int i = 0; i < 40; i++) { ASSERT_EQ(((unsigned char*) headerData)[i], exp[i]); } pubsubProtocol_wire_v2_destroy(wireprotocol); free(headerData); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = bswap_32(0xABBADEAF); memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); uint32_t pps = 0x04000000; memcpy(exp+28, &pps, sizeof(uint32_t)); uint32_t ppo = 0x02000000; memcpy(exp+32, &ppo, sizeof(uint32_t)); uint32_t ils = 0x01000000; memcpy(exp+36, &ils, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_SUCCESS, status); ASSERT_EQ(1, message.header.msgId); ASSERT_EQ(8, message.header.seqNr); ASSERT_EQ(0, message.header.msgMajorVersion); ASSERT_EQ(0, message.header.msgMinorVersion); ASSERT_EQ(2, message.header.payloadSize); ASSERT_EQ(3, message.header.metadataSize); ASSERT_EQ(4, message.header.payloadPartSize); ASSERT_EQ(2, message.header.payloadOffset); ASSERT_EQ(1, message.header.isLastSegment); ASSERT_EQ(1, message.header.convertEndianess); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectSync_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = 0xBAABABBA; memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectVersion_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = 0xABBADEAF; memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x02000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeFooter_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); pubsub_protocol_message_t message; message.header.convertEndianess = 0; void *footerData = nullptr; size_t footerLength = 0; celix_status_t status = pubsubProtocol_wire_v2_encodeFooter(nullptr, &message, &footerData, &footerLength); unsigned char exp[4]; uint32_t s = 0xDEAFABBA; memcpy(exp, &s, sizeof(uint32_t)); ASSERT_EQ(status, CELIX_SUCCESS); ASSERT_EQ(4, footerLength); for (int i = 0; i < 4; i++) { ASSERT_EQ(((unsigned char*) footerData)[i], exp[i]); } pubsubProtocol_wire_v2_destroy(wireprotocol); free(footerData); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[4]; uint32_t s = 0xDEAFABBA; memcpy(exp, &s, sizeof(uint32_t)); pubsub_protocol_message_t message; message.header.convertEndianess = 0; celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message); ASSERT_EQ(CELIX_SUCCESS, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_IncorrectSync_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[4]; uint32_t s = 0xABBADEAF; memcpy(exp, &s, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); }<|endoftext|>
<commit_before>#include <stx/algorithm/MinMax.h> #include <gtest/gtest.h> TEST(Min, BasicFirst) { int x = 0; auto& result = stx::Min(x, 1); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Min, BasicSecond) { int x = 0; auto& result = stx::Min(1, x); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Min, Stable) { int x = 0; int y = 0; auto& result = stx::Min(x, y); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Max, BasicFirst) { int x = 0; auto& result = stx::Max(x, -1); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Max, BasicSecond) { int x = 0; auto& result = stx::Max(-1, x); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Max, Stable) { int x = 0; int y = 0; auto& result = stx::Max(x, y); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } <commit_msg>added some tests for min/max|element methods<commit_after>#include <stx/algorithm/MinMax.h> #include <gtest/gtest.h> #include <vector> TEST(Min, BasicFirst) { int x = 0; auto& result = stx::Min(x, 1); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Min, BasicSecond) { int x = 0; auto& result = stx::Min(1, x); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Min, Stable) { int x = 0; int y = 0; auto& result = stx::Min(x, y); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Max, BasicFirst) { int x = 0; auto& result = stx::Max(x, -1); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Max, BasicSecond) { int x = 0; auto& result = stx::Max(-1, x); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(Max, Stable) { int x = 0; int y = 0; auto& result = stx::Max(x, y); EXPECT_EQ(0, result); EXPECT_EQ(&x, &result); } TEST(MinElement, Empty) { std::vector<int> v; auto result = stx::MinElement(v.begin(), v.end()); EXPECT_EQ(v.end(), result); } TEST(MinElement, Basic) { std::vector<int> v = { 1, 2, 1, 3 }; auto result = stx::MinElement(v.begin(), v.end()); EXPECT_EQ(v.begin(), result); } TEST(MaxElement, Empty) { std::vector<int> v; auto result = stx::MaxElement(v.begin(), v.end()); EXPECT_EQ(v.end(), result); } TEST(MaxElement, Basic) { std::vector<int> v = { 1, 2, 3, 3 }; auto result = stx::MaxElement(v.begin(), v.end()); EXPECT_EQ(v.end() - 2, result); } <|endoftext|>
<commit_before>#include <tightdb.hpp> #include <gperftools/profiler.h> #include <unistd.h> #include <wait.h> // benchmark - requires linux and links with google-pprof using namespace tightdb; int main(int argc, char* argv []) { int spawns = 0; if (argc != 4) { printf("Arguments: profile_name num_processes reads_per_write\n"); return 0; } spawns = atoi(argv[2]); const int reads_per_write = atoi(argv[3]); int pid = 0; for (int i=0; i < spawns - 1; i++) { pid = fork(); if (pid == 0) { spawns = 0; break; } } srand(time(NULL)); if (spawns) { char name[100]; sprintf(name,"%s_%s_%s.prof", argv[1], argv[2], argv[3]); if (strcmp("0", argv[1])) ProfilerStart(name); } { SharedGroup db("parallel_benchmark.tightdb", true, SharedGroup::durability_Async); for (size_t round = 0; round < 20; ++round) { for (size_t i = 0; i < 1000000; ++i) { if (reads_per_write != 0 && (i % reads_per_write) == 0) { WriteTransaction trx(db); TableRef t = trx.get_table("test"); size_t key = rand() % 1000000; size_t ndx = t->lower_bound_int(0, key); StringData str = t->get_string(1, ndx); t->set_string(1, ndx, str); trx.commit(); } else { ReadTransaction trx(db); ConstTableRef t = trx.get_table("test"); size_t key = rand() % 1000000; size_t ndx = t->lower_bound_int(0, key); StringData str = t->get_string(1, ndx); const char* s = str.data(); } } } } if (spawns) if (strcmp("0", argv[1])) ProfilerStop(); while (spawns > 1) { int status = 0; wait(&status); // wait for child to complete spawns--; } return 0; } <commit_msg>increased benchmark focus on transaction overhead<commit_after>#include <tightdb.hpp> #include <gperftools/profiler.h> #include <unistd.h> #include <wait.h> // benchmark - requires linux and links with google-pprof using namespace tightdb; int main(int argc, char* argv []) { int spawns = 0; if (argc != 4) { printf("Arguments: profile_name num_processes reads_per_write\n"); return 0; } spawns = atoi(argv[2]); const int reads_per_write = atoi(argv[3]); int pid = 0; for (int i=0; i < spawns - 1; i++) { pid = fork(); if (pid == 0) { spawns = 0; break; } } srand(time(NULL)); if (spawns) { char name[100]; sprintf(name,"%s_%s_%s.prof", argv[1], argv[2], argv[3]); if (strcmp("0", argv[1])) ProfilerStart(name); } { SharedGroup db("parallel_benchmark.tightdb", true, SharedGroup::durability_Async); for (size_t round = 0; round < 20; ++round) { for (size_t i = 0; i < 1000000; ++i) { if (reads_per_write != 0 && (i % reads_per_write) == 0) { WriteTransaction trx(db); TableRef t = trx.get_table("test"); size_t ndx = rand() % 1000000; int v = t->get_int(0, ndx); t->set_int(0, ndx, v + 1); trx.commit(); } else { ReadTransaction trx(db); ConstTableRef t = trx.get_table("test"); size_t ndx = rand() % 1000000; volatile int v; v = t->get_int(0, ndx); (void) v; } } } } if (spawns) if (strcmp("0", argv[1])) ProfilerStop(); while (spawns > 1) { int status = 0; wait(&status); // wait for child to complete spawns--; } return 0; } <|endoftext|>
<commit_before>// local includes #include "augment_sparsity_on_interface.h" // libMesh includes #include "libmesh/elem.h" using namespace libMesh; AugmentSparsityOnInterface::AugmentSparsityOnInterface(MeshBase & mesh, boundary_id_type crack_boundary_lower, boundary_id_type crack_boundary_upper) : _mesh(mesh), _crack_boundary_lower(crack_boundary_lower), _crack_boundary_upper(crack_boundary_upper), _initialized(false) { this->mesh_reinit(); } const ElementSideMap & AugmentSparsityOnInterface::get_lower_to_upper() const { libmesh_assert(this->_initialized); return _lower_to_upper; } void AugmentSparsityOnInterface::mesh_reinit () { this->_initialized = true; // Loop over all elements (not just local elements) to make sure we find // "neighbor" elements on opposite sides of the crack. MeshBase::const_element_iterator el = _mesh.active_elements_begin(); const MeshBase::const_element_iterator end_el = _mesh.active_elements_end(); // Map from (elem, side) to centroid std::map< std::pair<const Elem *, unsigned char>, Point> lower_centroids; std::map< std::pair<const Elem *, unsigned char>, Point> upper_centroids; for ( ; el != end_el; ++el) { const Elem * elem = *el; { for (unsigned char side=0; side<elem->n_sides(); side++) if (elem->neighbor_ptr(side) == libmesh_nullptr) { if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_lower)) { UniquePtr<const Elem> side_elem = elem->build_side_ptr(side); lower_centroids[std::make_pair(elem, side)] = side_elem->centroid(); } } } { for (unsigned char side=0; side<elem->n_sides(); side++) if (elem->neighbor_ptr(side) == libmesh_nullptr) { if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_upper)) { UniquePtr<const Elem> side_elem = elem->build_side_ptr(side); upper_centroids[std::make_pair(elem, side)] = side_elem->centroid(); } } } } std::size_t n_lower_centroids = lower_centroids.size(); std::size_t n_upper_centroids = upper_centroids.size(); libmesh_assert(n_lower_centroids == n_upper_centroids); // Clear _lower_to_upper. This map will be used for matrix assembly later on. _lower_to_upper.clear(); // Clear _upper_to_lower. This map will be used for element ghosting // on distributed meshes, communication send_list construction in // parallel, and sparsity calculations _upper_to_lower.clear(); // We do an N^2 search to find elements with matching centroids. This could be optimized, // e.g. by first sorting the centroids based on their (x,y,z) location. { std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it = lower_centroids.begin(); std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it_end = lower_centroids.end(); for ( ; it != it_end; ++it) { Point lower_centroid = it->second; // find centroid in upper_centroids std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it = upper_centroids.begin(); std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it_end = upper_centroids.end(); Real min_distance = std::numeric_limits<Real>::max(); for ( ; inner_it != inner_it_end; ++inner_it) { Point upper_centroid = inner_it->second; Real distance = (upper_centroid - lower_centroid).norm(); if (distance < min_distance) { min_distance = distance; _lower_to_upper[it->first] = inner_it->first.first; } } // We should've found matching elements on either side of the crack by now libmesh_assert_less(min_distance, TOLERANCE); // fill up the inverse map const Elem * elem = it->first.first; const Elem * neighbor = _lower_to_upper[it->first]; _upper_to_lower[neighbor] = elem; } } } void AugmentSparsityOnInterface::operator() (const MeshBase::const_element_iterator & range_begin, const MeshBase::const_element_iterator & range_end, processor_id_type p, map_type & coupled_elements) { libmesh_assert(this->_initialized); const CouplingMatrix * const null_mat = libmesh_nullptr; for (MeshBase::const_element_iterator elem_it = range_begin; elem_it != range_end; ++elem_it) { const Elem * const elem = *elem_it; if (elem->processor_id() != p) coupled_elements.insert (std::make_pair(elem, null_mat)); for (unsigned int side=0; side<elem->n_sides(); side++) if (elem->neighbor_ptr(side) == libmesh_nullptr) { ElementSideMap::const_iterator ltu_it = _lower_to_upper.find(std::make_pair(elem, side)); if (ltu_it != _lower_to_upper.end()) { const Elem * neighbor = ltu_it->second; if (neighbor->processor_id() != p) coupled_elements.insert (std::make_pair(neighbor, null_mat)); } } ElementMap::const_iterator utl_it = _upper_to_lower.find(elem); if (utl_it != _upper_to_lower.end()) { const Elem * neighbor = utl_it->second; if (neighbor->processor_id() != p) coupled_elements.insert (std::make_pair(neighbor, null_mat)); } } } <commit_msg>Handle crack lookup reinit on distributed meshes<commit_after>// local includes #include "augment_sparsity_on_interface.h" // libMesh includes #include "libmesh/elem.h" using namespace libMesh; AugmentSparsityOnInterface::AugmentSparsityOnInterface(MeshBase & mesh, boundary_id_type crack_boundary_lower, boundary_id_type crack_boundary_upper) : _mesh(mesh), _crack_boundary_lower(crack_boundary_lower), _crack_boundary_upper(crack_boundary_upper), _initialized(false) { this->mesh_reinit(); } const ElementSideMap & AugmentSparsityOnInterface::get_lower_to_upper() const { libmesh_assert(this->_initialized); return _lower_to_upper; } void AugmentSparsityOnInterface::mesh_reinit () { this->_initialized = true; // Loop over all elements (not just local elements) to make sure we find // "neighbor" elements on opposite sides of the crack. MeshBase::const_element_iterator el = _mesh.active_elements_begin(); const MeshBase::const_element_iterator end_el = _mesh.active_elements_end(); // Map from (elem, side) to centroid std::map< std::pair<const Elem *, unsigned char>, Point> lower_centroids; std::map< std::pair<const Elem *, unsigned char>, Point> upper_centroids; for ( ; el != end_el; ++el) { const Elem * elem = *el; { for (unsigned char side=0; side<elem->n_sides(); side++) if (elem->neighbor_ptr(side) == libmesh_nullptr) { if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_lower)) { UniquePtr<const Elem> side_elem = elem->build_side_ptr(side); lower_centroids[std::make_pair(elem, side)] = side_elem->centroid(); } } } { for (unsigned char side=0; side<elem->n_sides(); side++) if (elem->neighbor_ptr(side) == libmesh_nullptr) { if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_upper)) { UniquePtr<const Elem> side_elem = elem->build_side_ptr(side); upper_centroids[std::make_pair(elem, side)] = side_elem->centroid(); } } } } // If we're doing a reinit on a distributed mesh then we may not see // all the centroids, or even a matching number of centroids. // std::size_t n_lower_centroids = lower_centroids.size(); // std::size_t n_upper_centroids = upper_centroids.size(); // libmesh_assert(n_lower_centroids == n_upper_centroids); // Clear _lower_to_upper. This map will be used for matrix assembly later on. _lower_to_upper.clear(); // Clear _upper_to_lower. This map will be used for element ghosting // on distributed meshes, communication send_list construction in // parallel, and sparsity calculations _upper_to_lower.clear(); // We do an N^2 search to find elements with matching centroids. This could be optimized, // e.g. by first sorting the centroids based on their (x,y,z) location. { std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it = lower_centroids.begin(); std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it_end = lower_centroids.end(); for ( ; it != it_end; ++it) { Point lower_centroid = it->second; // find closest centroid in upper_centroids Real min_distance = std::numeric_limits<Real>::max(); std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it = upper_centroids.begin(); std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it_end = upper_centroids.end(); for ( ; inner_it != inner_it_end; ++inner_it) { Point upper_centroid = inner_it->second; Real distance = (upper_centroid - lower_centroid).norm(); if (distance < min_distance) { min_distance = distance; _lower_to_upper[it->first] = inner_it->first.first; } } // For pairs with local elements, we should have found a // matching pair by now. const Elem * elem = it->first.first; const Elem * neighbor = _lower_to_upper[it->first]; if (min_distance < TOLERANCE) { // fill up the inverse map _upper_to_lower[neighbor] = elem; } else { libmesh_assert_not_equal_to(elem->processor_id(), _mesh.processor_id()); // This must have a false positive; a remote element would // have been closer. _lower_to_upper.erase(it->first); } } // Let's make sure we didn't miss any upper elements either #ifndef NDEBUG std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it = upper_centroids.begin(); std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it_end = upper_centroids.end(); for ( ; inner_it != inner_it_end; ++inner_it) { const Elem * neighbor = inner_it->first.first; if (neighbor->processor_id() != _mesh.processor_id()) continue; ElementMap::const_iterator utl_it = _upper_to_lower.find(neighbor); libmesh_assert(utl_it != _upper_to_lower.end()); } #endif } } void AugmentSparsityOnInterface::operator() (const MeshBase::const_element_iterator & range_begin, const MeshBase::const_element_iterator & range_end, processor_id_type p, map_type & coupled_elements) { libmesh_assert(this->_initialized); const CouplingMatrix * const null_mat = libmesh_nullptr; for (MeshBase::const_element_iterator elem_it = range_begin; elem_it != range_end; ++elem_it) { const Elem * const elem = *elem_it; if (elem->processor_id() != p) coupled_elements.insert (std::make_pair(elem, null_mat)); for (unsigned int side=0; side<elem->n_sides(); side++) if (elem->neighbor_ptr(side) == libmesh_nullptr) { ElementSideMap::const_iterator ltu_it = _lower_to_upper.find(std::make_pair(elem, side)); if (ltu_it != _lower_to_upper.end()) { const Elem * neighbor = ltu_it->second; if (neighbor->processor_id() != p) coupled_elements.insert (std::make_pair(neighbor, null_mat)); } } ElementMap::const_iterator utl_it = _upper_to_lower.find(elem); if (utl_it != _upper_to_lower.end()) { const Elem * neighbor = utl_it->second; if (neighbor->processor_id() != p) coupled_elements.insert (std::make_pair(neighbor, null_mat)); } } } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include "grins_config.h" #include <iostream> // GRINS #include "grins/mesh_builder.h" #include "grins/simulation.h" #include "grins/simulation_builder.h" #include "grins/multiphysics_sys.h" #include "grins/parabolic_profile.h" //libMesh #include "libmesh/dirichlet_boundaries.h" #include "libmesh/dof_map.h" #include "libmesh/fe_base.h" #include "libmesh/fe_interface.h" #include "libmesh/mesh_function.h" #include "libmesh/linear_implicit_system.h" #include "libmesh/gmv_io.h" #include "libmesh/exact_solution.h" // GRVY #ifdef GRINS_HAVE_GRVY #include "grvy.h" #endif class TurbulentBCFactory : public GRINS::BoundaryConditionsFactory { public: TurbulentBCFactory(libMesh::MeshFunction* _turbulent_bc_values) : GRINS::BoundaryConditionsFactory(), turbulent_bc_values(_turbulent_bc_values) { return; }; ~TurbulentBCFactory(){return;}; std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > build_dirichlet( ); private: // A pointer to a TurbulentBdyFunction object that build_dirichlet can use to set bcs libMesh::MeshFunction* turbulent_bc_values; }; // Class to construct the Dirichlet boundary object and operator for the inlet u velocity and nu profiles class TurbulentBdyFunction : public libMesh::FunctionBase<libMesh::Number> { public: TurbulentBdyFunction (libMesh::MeshFunction* _turbulent_bc_values) : turbulent_bc_values(_turbulent_bc_values) { this->_initialized = true; } virtual libMesh::Number operator() (const libMesh::Point&, const libMesh::Real = 0) { libmesh_not_implemented(); } virtual void operator() (const libMesh::Point& p, const libMesh::Real t, libMesh::DenseVector<libMesh::Number>& output) { output.resize(4); output.zero(); // Since the turbulent_bc_values object has a solution from a 1-d problem, we have to zero out the y coordinate of p libMesh::Point p_copy(p); // Also the 1-d solution provided is on the domain [0, 1] on the x axis and we need to map this to the corresponding point on the y axis p_copy(0) = p_copy(1); p_copy(1)= 0.0; if(p_copy(0) > 0.5) { p_copy(0) = 1 - p_copy(0); } libMesh::DenseVector<libMesh::Number> u_nu_values; turbulent_bc_values->operator()(p_copy, t, u_nu_values); output(0) = u_nu_values(0); std::cout<<"Velocity bc at ("<<p_copy(1)<<","<<p_copy(0)<<"): "<<u_nu_values(0)<<std::endl; output(3) = u_nu_values(1); std::cout<<"Viscosity bc at ("<<p_copy(1)<<","<<p_copy(0)<<"): "<<u_nu_values(1)<<std::endl; } virtual libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > clone() const { return libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > (new TurbulentBdyFunction(turbulent_bc_values)); } private: libMesh::MeshFunction* turbulent_bc_values; }; int main(int argc, char* argv[]) { #ifdef GRINS_USE_GRVY_TIMERS GRVY::GRVY_Timer_Class grvy_timer; grvy_timer.Init("GRINS Timer"); #endif // Check command line count. if( argc < 2 ) { // TODO: Need more consistent error handling. std::cerr << "Error: Must specify libMesh input file." << std::endl; exit(1); // TODO: something more sophisticated for parallel runs? } // libMesh input file should be first argument std::string libMesh_input_filename = argv[1]; // Create our GetPot object. GetPot libMesh_inputfile( libMesh_input_filename ); #ifdef GRINS_USE_GRVY_TIMERS grvy_timer.BeginTimer("Initialize Solver"); #endif // Initialize libMesh library. libMesh::LibMeshInit libmesh_init(argc, argv); // Build a 1-d turbulent_bc_system to get the bc data from files libMesh::SerialMesh mesh(libmesh_init.comm()); mesh.read("test_data/turbulent_channel_Re944_grid.xda"); //mesh.all_second_order(); // And an EquationSystems to run on it libMesh::EquationSystems equation_systems (mesh); equation_systems.read("test_data/turbulent_channel_soln.xda", libMesh::XdrMODE::READ, libMesh::EquationSystems::READ_HEADER | libMesh::EquationSystems::READ_DATA | libMesh::EquationSystems::READ_ADDITIONAL_DATA); // Get a reference to the system so that we can call update() on it libMesh::System & turbulent_bc_system = equation_systems.get_system<libMesh::System>("flow"); // We need to call update to put system in a consistent state // with the solution that was read in turbulent_bc_system.update(); // Write out this solution to make sure it was read properly std::ostringstream file_name_gmv; file_name_gmv << "turbulent_bc.gmv"; libMesh::GMVIO(mesh).write_equation_systems (file_name_gmv.str(), equation_systems); // Print information about the system to the screen. equation_systems.print_info(); // Prepare a global solution and a MeshFunction of the Turbulent system libMesh::AutoPtr<libMesh::MeshFunction> turbulent_bc_values; libMesh::AutoPtr<libMesh::NumericVector<libMesh::Number> > turbulent_bc_soln = libMesh::NumericVector<libMesh::Number>::build(equation_systems.comm()); std::vector<unsigned int>turbulent_bc_system_variables; turbulent_bc_system_variables.push_back(0); turbulent_bc_system_variables.push_back(1); std::vector<libMesh::Number> flow_soln; turbulent_bc_system.update_global_solution(flow_soln); std::cout<<"Flow solution size: "<<flow_soln.size()<<std::endl; turbulent_bc_soln->init(libMesh::cast_int<libMesh::numeric_index_type>(flow_soln.size()), true, libMesh::SERIAL); turbulent_bc_values = libMesh::AutoPtr<libMesh::MeshFunction> (new libMesh::MeshFunction(equation_systems, *turbulent_bc_soln, turbulent_bc_system.get_dof_map(), turbulent_bc_system_variables )); turbulent_bc_values->init(); libMesh::Point p_test(0.3, 0.0); libMesh::Real t; libMesh::DenseVector<libMesh::Number> u_nu_values; turbulent_bc_values->operator()(p_test, t, u_nu_values); std::cout<<"Viscosity bc at ("<<p_test(1)<<","<<p_test(0)<<"): "<<u_nu_values(1)<<std::endl; std::cout<<"Velocity bc at ("<<p_test(1)<<","<<p_test(0)<<"): "<<u_nu_values(0)<<std::endl; GRINS::SimulationBuilder sim_builder; std::tr1::shared_ptr<TurbulentBCFactory> bc_factory( new TurbulentBCFactory(turbulent_bc_values.get()) ); sim_builder.attach_bc_factory(bc_factory); GRINS::Simulation grins( libMesh_inputfile, sim_builder, libmesh_init.comm() ); #ifdef GRINS_USE_GRVY_TIMERS grvy_timer.EndTimer("Initialize Solver"); // Attach GRVY timer to solver grins.attach_grvy_timer( &grvy_timer ); #endif // Solve grins.run(); // Get equation systems to create ExactSolution object //std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system(); // Create Exact solution object and attach exact solution quantities //libMesh::ExactSolution exact_sol(*es); //exact_sol.attach_exact_value(&exact_solution); //exact_sol.attach_exact_deriv(&exact_derivative); // Compute error and get it in various norms //exact_sol.compute_error("GRINS", "u"); //double l2error = exact_sol.l2_error("GRINS", "u"); //double h1error = exact_sol.h1_error("GRINS", "u"); // Needs to change to 1 based on comparison int return_flag = 0; // if( l2error > 1.0e-9 || h1error > 1.0e-9 ) // { // return_flag = 1; // std::cout << "Tolerance exceeded for velocity in Poiseuille test." << std::endl // << "l2 error = " << l2error << std::endl // << "h1 error = " << h1error << std::endl; // } // // Compute error and get it in various norms // exact_sol.compute_error("GRINS", "p"); // l2error = exact_sol.l2_error("GRINS", "p"); // h1error = exact_sol.h1_error("GRINS", "p"); // if( l2error > 2.0e-9 || h1error > 2.0e-9 ) // { // return_flag = 1; // std::cout << "Tolerance exceeded for pressure in Poiseuille test." << std::endl // << "l2 error = " << l2error << std::endl // << "h1 error = " << h1error << std::endl; // } return return_flag; } std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > TurbulentBCFactory::build_dirichlet( ) { std::tr1::shared_ptr<libMesh::FunctionBase<libMesh::Number> > turbulent_inlet( new TurbulentBdyFunction(this->turbulent_bc_values) ); GRINS::DBCContainer cont_u; cont_u.add_var_name( "u" ); cont_u.add_bc_id( 3 ); cont_u.set_func( turbulent_inlet ); GRINS::DBCContainer cont_nu; cont_nu.add_var_name( "nu" ); cont_nu.add_bc_id( 3 ); cont_nu.set_func( turbulent_inlet ); std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > mymap; mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::incompressible_navier_stokes, cont_u) ); mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::spalart_allmaras, cont_nu) ); return mymap; } // libMesh::Number // exact_solution( const libMesh::Point& p, // const libMesh::Parameters&, // parameters, not needed // const std::string&, // sys_name, not needed // const std::string&); // unk_name, not needed); // libMesh::Gradient // exact_derivative( const libMesh::Point& p, // const libMesh::Parameters&, // parameters, not needed // const std::string&, // sys_name, not needed // const std::string&); // unk_name, not needed); // libMesh::Number // exact_solution( const libMesh::Point& p, // const libMesh::Parameters& /*params*/, // parameters, not needed // const std::string& /*sys_name*/, // sys_name, not needed // const std::string& var ) // unk_name, not needed); // { // const double x = p(0); // const double y = p(1); // libMesh::Number f = 0; // // Hardcoded to velocity in input file. // if( var == "u" ) f = 4*y*(1-y); // else if( var == "p" ) f = 120.0 + (80.0-120.0)/5.0*x; // else libmesh_assert(false); // return f; // } // libMesh::Gradient // exact_derivative( const libMesh::Point& p, // const libMesh::Parameters& /*params*/, // parameters, not needed // const std::string& /*sys_name*/, // sys_name, not needed // const std::string& var) // unk_name, not needed); // { // const double y = p(1); // libMesh::Gradient g; // // Hardcoded to velocity in input file. // if( var == "u" ) // { // g(0) = 0.0; // g(1) = 4*(1-y) - 4*y; // #if LIBMESH_DIM > 2 // g(2) = 0.0; // #endif // } // if( var == "p" ) // { // g(0) = (80.0-120.0)/5.0; // g(1) = 0.0; // #if LIBMESH_DIM > 2 // g(2) = 0.0; // #endif // } // return g; // } <commit_msg>Finally got the MeshFunction to work. The problem was that I was not setting the turbulent_bc_soln equal to flow_soln.<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include "grins_config.h" #include <iostream> // GRINS #include "grins/mesh_builder.h" #include "grins/simulation.h" #include "grins/simulation_builder.h" #include "grins/multiphysics_sys.h" #include "grins/parabolic_profile.h" //libMesh #include "libmesh/dirichlet_boundaries.h" #include "libmesh/dof_map.h" #include "libmesh/fe_base.h" #include "libmesh/fe_interface.h" #include "libmesh/mesh_function.h" #include "libmesh/linear_implicit_system.h" #include "libmesh/gmv_io.h" #include "libmesh/exact_solution.h" // GRVY #ifdef GRINS_HAVE_GRVY #include "grvy.h" #endif class TurbulentBCFactory : public GRINS::BoundaryConditionsFactory { public: TurbulentBCFactory(libMesh::MeshFunction* _turbulent_bc_values) : GRINS::BoundaryConditionsFactory(), turbulent_bc_values(_turbulent_bc_values) { return; }; ~TurbulentBCFactory(){return;}; std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > build_dirichlet( ); private: // A pointer to a TurbulentBdyFunction object that build_dirichlet can use to set bcs libMesh::MeshFunction* turbulent_bc_values; }; // Class to construct the Dirichlet boundary object and operator for the inlet u velocity and nu profiles class TurbulentBdyFunction : public libMesh::FunctionBase<libMesh::Number> { public: TurbulentBdyFunction (libMesh::MeshFunction* _turbulent_bc_values) : turbulent_bc_values(_turbulent_bc_values) { this->_initialized = true; } virtual libMesh::Number operator() (const libMesh::Point&, const libMesh::Real = 0) { libmesh_not_implemented(); } virtual void operator() (const libMesh::Point& p, const libMesh::Real t, libMesh::DenseVector<libMesh::Number>& output) { output.resize(4); output.zero(); // Since the turbulent_bc_values object has a solution from a 1-d problem, we have to zero out the y coordinate of p libMesh::Point p_copy(p); // Also the 1-d solution provided is on the domain [0, 1] on the x axis and we need to map this to the corresponding point on the y axis p_copy(0) = p_copy(1); p_copy(1)= 0.0; if(p_copy(0) > 0.5) { p_copy(0) = 1 - p_copy(0); } libMesh::DenseVector<libMesh::Number> u_nu_values; turbulent_bc_values->operator()(p_copy, t, u_nu_values); output(0) = u_nu_values(0); //std::cout<<"Velocity bc at ("<<p_copy(1)<<","<<p_copy(0)<<"): "<<u_nu_values(0)<<std::endl; output(3) = u_nu_values(1); //std::cout<<"Viscosity bc at ("<<p_copy(1)<<","<<p_copy(0)<<"): "<<u_nu_values(1)<<std::endl; } virtual libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > clone() const { return libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > (new TurbulentBdyFunction(turbulent_bc_values)); } private: libMesh::MeshFunction* turbulent_bc_values; }; int main(int argc, char* argv[]) { #ifdef GRINS_USE_GRVY_TIMERS GRVY::GRVY_Timer_Class grvy_timer; grvy_timer.Init("GRINS Timer"); #endif // Check command line count. if( argc < 2 ) { // TODO: Need more consistent error handling. std::cerr << "Error: Must specify libMesh input file." << std::endl; exit(1); // TODO: something more sophisticated for parallel runs? } // libMesh input file should be first argument std::string libMesh_input_filename = argv[1]; // Create our GetPot object. GetPot libMesh_inputfile( libMesh_input_filename ); #ifdef GRINS_USE_GRVY_TIMERS grvy_timer.BeginTimer("Initialize Solver"); #endif // Initialize libMesh library. libMesh::LibMeshInit libmesh_init(argc, argv); // Build a 1-d turbulent_bc_system to get the bc data from files libMesh::SerialMesh mesh(libmesh_init.comm()); mesh.read("test_data/turbulent_channel_Re944_grid.xda"); //mesh.all_second_order(); // And an EquationSystems to run on it libMesh::EquationSystems equation_systems (mesh); equation_systems.read("test_data/turbulent_channel_soln.xda", libMesh::XdrMODE::READ, libMesh::EquationSystems::READ_HEADER | libMesh::EquationSystems::READ_DATA | libMesh::EquationSystems::READ_ADDITIONAL_DATA); // Get a reference to the system so that we can call update() on it libMesh::System & turbulent_bc_system = equation_systems.get_system<libMesh::System>("flow"); // We need to call update to put system in a consistent state // with the solution that was read in turbulent_bc_system.update(); // Write out this solution to make sure it was read properly std::ostringstream file_name_gmv; file_name_gmv << "turbulent_bc.gmv"; libMesh::GMVIO(mesh).write_equation_systems (file_name_gmv.str(), equation_systems); // Print information about the system to the screen. equation_systems.print_info(); // Prepare a global solution and a MeshFunction of the Turbulent system libMesh::AutoPtr<libMesh::MeshFunction> turbulent_bc_values; libMesh::AutoPtr<libMesh::NumericVector<libMesh::Number> > turbulent_bc_soln = libMesh::NumericVector<libMesh::Number>::build(equation_systems.comm()); std::vector<unsigned int>turbulent_bc_system_variables; turbulent_bc_system_variables.push_back(0); turbulent_bc_system_variables.push_back(1); std::vector<libMesh::Number> flow_soln; turbulent_bc_system.update_global_solution(flow_soln); std::cout<<"Flow solution size: "<<flow_soln.size()<<std::endl; turbulent_bc_soln->init(libMesh::cast_int<libMesh::numeric_index_type>(flow_soln.size()), true, libMesh::SERIAL); (*turbulent_bc_soln) = flow_soln; turbulent_bc_values = libMesh::AutoPtr<libMesh::MeshFunction> (new libMesh::MeshFunction(equation_systems, *turbulent_bc_soln, turbulent_bc_system.get_dof_map(), turbulent_bc_system_variables )); turbulent_bc_values->init(); // libMesh::Point p_test(0.3, 0.0); // libMesh::Real t; // libMesh::DenseVector<libMesh::Number> u_nu_values; // turbulent_bc_values->operator()(p_test, t, u_nu_values); // std::cout<<"Viscosity bc at ("<<p_test(1)<<","<<p_test(0)<<"): "<<u_nu_values(1)<<std::endl; // std::cout<<"Velocity bc at ("<<p_test(1)<<","<<p_test(0)<<"): "<<u_nu_values(0)<<std::endl; GRINS::SimulationBuilder sim_builder; std::tr1::shared_ptr<TurbulentBCFactory> bc_factory( new TurbulentBCFactory(turbulent_bc_values.get()) ); sim_builder.attach_bc_factory(bc_factory); GRINS::Simulation grins( libMesh_inputfile, sim_builder, libmesh_init.comm() ); #ifdef GRINS_USE_GRVY_TIMERS grvy_timer.EndTimer("Initialize Solver"); // Attach GRVY timer to solver grins.attach_grvy_timer( &grvy_timer ); #endif // Solve grins.run(); // Get equation systems to create ExactSolution object //std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system(); // Create Exact solution object and attach exact solution quantities //libMesh::ExactSolution exact_sol(*es); //exact_sol.attach_exact_value(&exact_solution); //exact_sol.attach_exact_deriv(&exact_derivative); // Compute error and get it in various norms //exact_sol.compute_error("GRINS", "u"); //double l2error = exact_sol.l2_error("GRINS", "u"); //double h1error = exact_sol.h1_error("GRINS", "u"); // Needs to change to 1 based on comparison int return_flag = 0; // if( l2error > 1.0e-9 || h1error > 1.0e-9 ) // { // return_flag = 1; // std::cout << "Tolerance exceeded for velocity in Poiseuille test." << std::endl // << "l2 error = " << l2error << std::endl // << "h1 error = " << h1error << std::endl; // } // // Compute error and get it in various norms // exact_sol.compute_error("GRINS", "p"); // l2error = exact_sol.l2_error("GRINS", "p"); // h1error = exact_sol.h1_error("GRINS", "p"); // if( l2error > 2.0e-9 || h1error > 2.0e-9 ) // { // return_flag = 1; // std::cout << "Tolerance exceeded for pressure in Poiseuille test." << std::endl // << "l2 error = " << l2error << std::endl // << "h1 error = " << h1error << std::endl; // } return return_flag; } std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > TurbulentBCFactory::build_dirichlet( ) { std::tr1::shared_ptr<libMesh::FunctionBase<libMesh::Number> > turbulent_inlet( new TurbulentBdyFunction(this->turbulent_bc_values) ); GRINS::DBCContainer cont_u; cont_u.add_var_name( "u" ); cont_u.add_bc_id( 3 ); cont_u.set_func( turbulent_inlet ); GRINS::DBCContainer cont_nu; cont_nu.add_var_name( "nu" ); cont_nu.add_bc_id( 3 ); cont_nu.set_func( turbulent_inlet ); std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > mymap; mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::incompressible_navier_stokes, cont_u) ); mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::spalart_allmaras, cont_nu) ); return mymap; } // libMesh::Number // exact_solution( const libMesh::Point& p, // const libMesh::Parameters&, // parameters, not needed // const std::string&, // sys_name, not needed // const std::string&); // unk_name, not needed); // libMesh::Gradient // exact_derivative( const libMesh::Point& p, // const libMesh::Parameters&, // parameters, not needed // const std::string&, // sys_name, not needed // const std::string&); // unk_name, not needed); // libMesh::Number // exact_solution( const libMesh::Point& p, // const libMesh::Parameters& /*params*/, // parameters, not needed // const std::string& /*sys_name*/, // sys_name, not needed // const std::string& var ) // unk_name, not needed); // { // const double x = p(0); // const double y = p(1); // libMesh::Number f = 0; // // Hardcoded to velocity in input file. // if( var == "u" ) f = 4*y*(1-y); // else if( var == "p" ) f = 120.0 + (80.0-120.0)/5.0*x; // else libmesh_assert(false); // return f; // } // libMesh::Gradient // exact_derivative( const libMesh::Point& p, // const libMesh::Parameters& /*params*/, // parameters, not needed // const std::string& /*sys_name*/, // sys_name, not needed // const std::string& var) // unk_name, not needed); // { // const double y = p(1); // libMesh::Gradient g; // // Hardcoded to velocity in input file. // if( var == "u" ) // { // g(0) = 0.0; // g(1) = 4*(1-y) - 4*y; // #if LIBMESH_DIM > 2 // g(2) = 0.0; // #endif // } // if( var == "p" ) // { // g(0) = (80.0-120.0)/5.0; // g(1) = 0.0; // #if LIBMESH_DIM > 2 // g(2) = 0.0; // #endif // } // return g; // } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkVolumeTextureMapper.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkVolumeTextureMapper.h" #include "vtkVolume.h" #include "vtkRenderer.h" #include "vtkFiniteDifferenceGradientEstimator.h" vtkVolumeTextureMapper::vtkVolumeTextureMapper() { this->ScalarOpacityArray = NULL; this->GradientOpacityArray = NULL; this->RGBArray = NULL; this->GrayArray = NULL; this->ArraySize = -1; this->GradientOpacityConstant = 0.0; this->SampleDistance = 1.0; this->GradientEstimator = vtkFiniteDifferenceGradientEstimator::New(); this->GradientShader = vtkEncodedGradientShader::New(); } vtkVolumeTextureMapper::~vtkVolumeTextureMapper() { this->SetGradientEstimator( NULL ); this->GradientShader->Delete(); if ( this->ScalarOpacityArray ) { delete [] this->ScalarOpacityArray; } if ( this->GrayArray ) { delete [] this->GrayArray; } if ( this->RGBArray ) { delete [] this->RGBArray; } } void vtkVolumeTextureMapper::SetGradientEstimator( vtkEncodedGradientEstimator *gradest ) { // If we are setting it to its current value, don't do anything if ( this->GradientEstimator == gradest ) { return; } // If we already have a gradient estimator, unregister it. if ( this->GradientEstimator ) { this->GradientEstimator->UnRegister(this); this->GradientEstimator = NULL; } // If we are passing in a non-NULL estimator, register it if ( gradest ) { gradest->Register( this ); } // Actually set the estimator, and consider the object Modified this->GradientEstimator = gradest; this->Modified(); } void vtkVolumeTextureMapper::Update() { if ( this->GetInput() ) { this->GetInput()->Update(); } if ( this->GetRGBTextureInput() ) { this->GetRGBTextureInput()->Update(); } } void vtkVolumeTextureMapper::InitializeRender( vtkRenderer *ren, vtkVolume *vol ) { int size, i; float *tmpArray; int colorChannels; // Hang on to the render window - we'll need it to test for abort this->RenderWindow = ren->GetRenderWindow(); vol->UpdateTransferFunctions( ren ); vol->UpdateScalarOpacityforSampleSize( ren, this->SampleDistance ); colorChannels = vol->GetProperty()->GetColorChannels(); size = vol->GetArraySize(); if ( this->ArraySize != size ) { if ( this->ScalarOpacityArray ) { delete [] this->ScalarOpacityArray; } if ( this->RGBArray ) { delete [] this->ScalarOpacityArray; } if ( this->GrayArray ) { delete [] this->ScalarOpacityArray; } this->ScalarOpacityArray = new unsigned char[size]; this->RGBArray = new unsigned char[3*size]; this->GrayArray = new unsigned char[size]; this->ArraySize = size; } tmpArray = vol->GetCorrectedScalarOpacityArray(); for ( i = 0; i < size; i++ ) { this->ScalarOpacityArray[i] = tmpArray[i]*255.99; } this->GradientOpacityArray = vol->GetGradientOpacityArray(); if ( colorChannels == 3 ) { tmpArray = vol->GetRGBArray(); for ( i = 0; i < 3*size; i++ ) { this->RGBArray[i] = tmpArray[i]*255.99; } } else if ( colorChannels == 1 ) { tmpArray = vol->GetGrayArray(); for ( i = 0; i < size; i++ ) { this->GrayArray[i] = tmpArray[i]*255.99; } } this->GradientOpacityConstant = vol->GetGradientOpacityConstant(); this->Shade = vol->GetProperty()->GetShade(); this->GradientEstimator->SetInput( this->GetInput() ); if ( this->Shade ) { this->GradientShader->UpdateShadingTable( ren, vol, this->GradientEstimator ); this->EncodedNormals = this->GradientEstimator->GetEncodedNormals(); this->RedDiffuseShadingTable = this->GradientShader->GetRedDiffuseShadingTable(vol); this->GreenDiffuseShadingTable = this->GradientShader->GetGreenDiffuseShadingTable(vol); this->BlueDiffuseShadingTable = this->GradientShader->GetBlueDiffuseShadingTable(vol); this->RedSpecularShadingTable = this->GradientShader->GetRedSpecularShadingTable(vol); this->GreenSpecularShadingTable = this->GradientShader->GetGreenSpecularShadingTable(vol); this->BlueSpecularShadingTable = this->GradientShader->GetBlueSpecularShadingTable(vol); } else { this->EncodedNormals = NULL; this->RedDiffuseShadingTable = NULL; this->GreenDiffuseShadingTable = NULL; this->BlueDiffuseShadingTable = NULL; this->RedSpecularShadingTable = NULL; this->GreenSpecularShadingTable = NULL; this->BlueSpecularShadingTable = NULL; } // If we have non-constant opacity on the gradient magnitudes, // we need to use the gradient magnitudes to look up the opacity if ( this->GradientOpacityConstant == -1.0 ) { this->GradientMagnitudes = this->GradientEstimator->GetGradientMagnitudes(); } else { this->GradientMagnitudes = NULL; } this->GetInput()->GetOrigin( this->DataOrigin ); this->GetInput()->GetSpacing( this->DataSpacing ); } // Print the vtkVolumeTextureMapper void vtkVolumeTextureMapper::PrintSelf(ostream& os, vtkIndent indent) { this->vtkVolumeMapper::PrintSelf(os,indent); if ( this->GradientEstimator ) { os << indent << "Gradient Estimator: " << (this->GradientEstimator) << endl; } else { os << indent << "Gradient Estimator: (none)" << endl; } if ( this->GradientShader ) { os << indent << "Gradient Shader: " << (this->GradientShader) << endl; } else { os << indent << "Gradient Shader: (none)" << endl; } // this->Shade is a temporary variable that should not be printed } <commit_msg>Added some comments to get around PrintSelf defects.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkVolumeTextureMapper.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkVolumeTextureMapper.h" #include "vtkVolume.h" #include "vtkRenderer.h" #include "vtkFiniteDifferenceGradientEstimator.h" vtkVolumeTextureMapper::vtkVolumeTextureMapper() { this->ScalarOpacityArray = NULL; this->GradientOpacityArray = NULL; this->RGBArray = NULL; this->GrayArray = NULL; this->ArraySize = -1; this->GradientOpacityConstant = 0.0; this->SampleDistance = 1.0; this->GradientEstimator = vtkFiniteDifferenceGradientEstimator::New(); this->GradientShader = vtkEncodedGradientShader::New(); } vtkVolumeTextureMapper::~vtkVolumeTextureMapper() { this->SetGradientEstimator( NULL ); this->GradientShader->Delete(); if ( this->ScalarOpacityArray ) { delete [] this->ScalarOpacityArray; } if ( this->GrayArray ) { delete [] this->GrayArray; } if ( this->RGBArray ) { delete [] this->RGBArray; } } void vtkVolumeTextureMapper::SetGradientEstimator( vtkEncodedGradientEstimator *gradest ) { // If we are setting it to its current value, don't do anything if ( this->GradientEstimator == gradest ) { return; } // If we already have a gradient estimator, unregister it. if ( this->GradientEstimator ) { this->GradientEstimator->UnRegister(this); this->GradientEstimator = NULL; } // If we are passing in a non-NULL estimator, register it if ( gradest ) { gradest->Register( this ); } // Actually set the estimator, and consider the object Modified this->GradientEstimator = gradest; this->Modified(); } void vtkVolumeTextureMapper::Update() { if ( this->GetInput() ) { this->GetInput()->Update(); } if ( this->GetRGBTextureInput() ) { this->GetRGBTextureInput()->Update(); } } void vtkVolumeTextureMapper::InitializeRender( vtkRenderer *ren, vtkVolume *vol ) { int size, i; float *tmpArray; int colorChannels; // Hang on to the render window - we'll need it to test for abort this->RenderWindow = ren->GetRenderWindow(); vol->UpdateTransferFunctions( ren ); vol->UpdateScalarOpacityforSampleSize( ren, this->SampleDistance ); colorChannels = vol->GetProperty()->GetColorChannels(); size = vol->GetArraySize(); if ( this->ArraySize != size ) { if ( this->ScalarOpacityArray ) { delete [] this->ScalarOpacityArray; } if ( this->RGBArray ) { delete [] this->ScalarOpacityArray; } if ( this->GrayArray ) { delete [] this->ScalarOpacityArray; } this->ScalarOpacityArray = new unsigned char[size]; this->RGBArray = new unsigned char[3*size]; this->GrayArray = new unsigned char[size]; this->ArraySize = size; } tmpArray = vol->GetCorrectedScalarOpacityArray(); for ( i = 0; i < size; i++ ) { this->ScalarOpacityArray[i] = tmpArray[i]*255.99; } this->GradientOpacityArray = vol->GetGradientOpacityArray(); if ( colorChannels == 3 ) { tmpArray = vol->GetRGBArray(); for ( i = 0; i < 3*size; i++ ) { this->RGBArray[i] = tmpArray[i]*255.99; } } else if ( colorChannels == 1 ) { tmpArray = vol->GetGrayArray(); for ( i = 0; i < size; i++ ) { this->GrayArray[i] = tmpArray[i]*255.99; } } this->GradientOpacityConstant = vol->GetGradientOpacityConstant(); this->Shade = vol->GetProperty()->GetShade(); this->GradientEstimator->SetInput( this->GetInput() ); if ( this->Shade ) { this->GradientShader->UpdateShadingTable( ren, vol, this->GradientEstimator ); this->EncodedNormals = this->GradientEstimator->GetEncodedNormals(); this->RedDiffuseShadingTable = this->GradientShader->GetRedDiffuseShadingTable(vol); this->GreenDiffuseShadingTable = this->GradientShader->GetGreenDiffuseShadingTable(vol); this->BlueDiffuseShadingTable = this->GradientShader->GetBlueDiffuseShadingTable(vol); this->RedSpecularShadingTable = this->GradientShader->GetRedSpecularShadingTable(vol); this->GreenSpecularShadingTable = this->GradientShader->GetGreenSpecularShadingTable(vol); this->BlueSpecularShadingTable = this->GradientShader->GetBlueSpecularShadingTable(vol); } else { this->EncodedNormals = NULL; this->RedDiffuseShadingTable = NULL; this->GreenDiffuseShadingTable = NULL; this->BlueDiffuseShadingTable = NULL; this->RedSpecularShadingTable = NULL; this->GreenSpecularShadingTable = NULL; this->BlueSpecularShadingTable = NULL; } // If we have non-constant opacity on the gradient magnitudes, // we need to use the gradient magnitudes to look up the opacity if ( this->GradientOpacityConstant == -1.0 ) { this->GradientMagnitudes = this->GradientEstimator->GetGradientMagnitudes(); } else { this->GradientMagnitudes = NULL; } this->GetInput()->GetOrigin( this->DataOrigin ); this->GetInput()->GetSpacing( this->DataSpacing ); } // Print the vtkVolumeTextureMapper void vtkVolumeTextureMapper::PrintSelf(ostream& os, vtkIndent indent) { this->vtkVolumeMapper::PrintSelf(os,indent); if ( this->GradientEstimator ) { os << indent << "Gradient Estimator: " << (this->GradientEstimator) << endl; } else { os << indent << "Gradient Estimator: (none)" << endl; } if ( this->GradientShader ) { os << indent << "Gradient Shader: " << (this->GradientShader) << endl; } else { os << indent << "Gradient Shader: (none)" << endl; } // this->Shade is a temporary variable that should not be printed // this->RenderWindow is a temporary variable that should not be printed // this->DataSpacing is a temporary variable that should not be printed // this->DataOrigin is a temporary variable that should not be printed } <|endoftext|>
<commit_before>#include <RenHook/RenHook.hpp> #include <RenHook/Hooks/Hook.hpp> #include <RenHook/Memory/Protection.hpp> #include <RenHook/Threads/Threads.hpp> RenHook::Hook::Hook(const uintptr_t Address, const uintptr_t Detour) : m_address(Address) { RenHook::Managers::Threads Threads; Threads.Suspend(); m_size = GetMinimumSize(Address); m_memoryBlock = std::make_unique<RenHook::Memory::Block>(Address, m_size); // Backup the original bytes. m_memoryBlock->CopyFrom(Address, m_size); Memory::Protection Protection(Address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // TODO: Check for relative jumps and fix them. //auto HookSize = WriteJump(Address, Detour, m_size); // Jump back to the original code (16 bytes). //WriteJump(m_memoryBlock.GetAddress() + m_size, Address + m_size, 16); // Set unused bytes as NOP. //if (HookSize < m_size) { //std::memset(reinterpret_cast<uintptr_t*>(Address + HookSize), 0x90, m_size - HookSize); } Protection.Restore(); Threads.Resume(); } RenHook::Hook::~Hook() { RenHook::Managers::Threads Threads; Threads.Suspend(); Memory::Protection Protection(m_address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // Restore the original bytes. m_memoryBlock->CopyTo(m_address, m_size); Protection.Restore(); Threads.Resume(); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const uintptr_t Address) { return RenHook::Managers::Hooks::Get(Address); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Key) { return RenHook::Managers::Hooks::Get(Key); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Get(Module, Function); } void RenHook::Hook::Remove(const uintptr_t Address) { return RenHook::Managers::Hooks::Remove(Address); } void RenHook::Hook::Remove(const std::wstring& Key) { return RenHook::Managers::Hooks::Remove(Key); } void RenHook::Hook::Remove(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Remove(Module, Function); } const size_t RenHook::Hook::CheckSize(const RenHook::Capstone& Capstone, const size_t MinimumSize) const { size_t Result = 0; for (size_t i = 0; i < Capstone.GetTotalNumberOfInstruction(); i++) { Result += Capstone.GetInstructionSize(i); if (Result >= MinimumSize) { break; } } return Result >= MinimumSize ? Result : 0; } const size_t RenHook::Hook::GetMinimumSize(const uintptr_t Address) const { size_t Length = 0; RenHook::Capstone Capstone; Capstone.Disassemble(Address, 128); // Check if we can do a 16 byte jump. Length = CheckSize(Capstone, 16); // Check if we can do a 6 byte jump if we can't do a 16 byte jump. if (Length == 0) { Length = CheckSize(Capstone, 6); // Check if we can do a 5 byte jump if we can't do a 6 byte jump. if (Length == 0) { Length = CheckSize(Capstone, 5); } } return Length; } const size_t RenHook::Hook::WriteJump(const uintptr_t Address, const uintptr_t Detour, const size_t Size) const { std::vector<uint8_t> Bytes; // Should we do a x64 or x86 jump? if (Size >= 16) { /* * push rax * mov rax, 0xCCCCCCCCCCCCCCCC * xchg rax, [rsp] * ret */ Bytes = { 0x50, 0x48, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x48, 0x87, 0x04, 0x24, 0xC3 }; // Set our detour function. *reinterpret_cast<uintptr_t*>(Bytes.data() + 3) = Detour; } else { // If the displacement is less than 2048 MB do a near jump or if the hook size is equal with 5, otherwise do a far jump. if (std::abs(reinterpret_cast<uintptr_t*>(Address) - reinterpret_cast<uintptr_t*>(Detour)) <= 0x7fff0000 || Size == 5) { /* * jmp 0xCCCCCCCC */ Bytes = { 0xE9, 0xCC, 0xCC, 0xCC, 0xCC }; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 1) = CalculateDisplacement<int32_t>(Address, Detour, Bytes.size()); } else { /* * jmp qword ptr ds:[0xCCCCCCCC] */ Bytes = { 0xFF, 0x25, 0xCC, 0xCC, 0xCC, 0xCC }; // Add the displacement right after our jump back to the original function which is located at "m_memoryBlock.GetAddress() + Size" and has a size of 16 bytes. auto Displacement = m_memoryBlock->GetAddress() + Size + 17; // Write the address in memory at RIP + Displacement. *reinterpret_cast<uintptr_t*>(Displacement) = Detour; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 2) = CalculateDisplacement<int32_t>(Address, Displacement, Bytes.size()); } } // Calculate the hook size in bytes. auto HookSize = sizeof(uint8_t) * Bytes.size(); // Override the original bytes. std::memcpy(reinterpret_cast<uintptr_t*>(Address), Bytes.data(), HookSize); return HookSize; }<commit_msg>Write jump instructions<commit_after>#include <RenHook/RenHook.hpp> #include <RenHook/Hooks/Hook.hpp> #include <RenHook/Memory/Protection.hpp> #include <RenHook/Threads/Threads.hpp> RenHook::Hook::Hook(const uintptr_t Address, const uintptr_t Detour) : m_address(Address) { RenHook::Managers::Threads Threads; Threads.Suspend(); m_size = GetMinimumSize(Address); m_memoryBlock = std::make_unique<RenHook::Memory::Block>(Address, m_size); // Backup the original bytes. m_memoryBlock->CopyFrom(Address, m_size); Memory::Protection Protection(Address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // TODO: Check for relative jumps and fix them. auto HookSize = WriteJump(Address, Detour, m_size); // Jump back to the original code (16 bytes). WriteJump(m_memoryBlock->GetAddress() + m_size, Address + m_size, 16); // Set unused bytes as NOP. if (HookSize < m_size) { std::memset(reinterpret_cast<uintptr_t*>(Address + HookSize), 0x90, m_size - HookSize); } Protection.Restore(); Threads.Resume(); } RenHook::Hook::~Hook() { RenHook::Managers::Threads Threads; Threads.Suspend(); Memory::Protection Protection(m_address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // Restore the original bytes. m_memoryBlock->CopyTo(m_address, m_size); Protection.Restore(); Threads.Resume(); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const uintptr_t Address) { return RenHook::Managers::Hooks::Get(Address); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Key) { return RenHook::Managers::Hooks::Get(Key); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Get(Module, Function); } void RenHook::Hook::Remove(const uintptr_t Address) { return RenHook::Managers::Hooks::Remove(Address); } void RenHook::Hook::Remove(const std::wstring& Key) { return RenHook::Managers::Hooks::Remove(Key); } void RenHook::Hook::Remove(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Remove(Module, Function); } const size_t RenHook::Hook::CheckSize(const RenHook::Capstone& Capstone, const size_t MinimumSize) const { size_t Result = 0; for (size_t i = 0; i < Capstone.GetTotalNumberOfInstruction(); i++) { Result += Capstone.GetInstructionSize(i); if (Result >= MinimumSize) { break; } } return Result >= MinimumSize ? Result : 0; } const size_t RenHook::Hook::GetMinimumSize(const uintptr_t Address) const { size_t Length = 0; RenHook::Capstone Capstone; Capstone.Disassemble(Address, 128); // Check if we can do a 16 byte jump. Length = CheckSize(Capstone, 16); // Check if we can do a 6 byte jump if we can't do a 16 byte jump. if (Length == 0) { Length = CheckSize(Capstone, 6); // Check if we can do a 5 byte jump if we can't do a 6 byte jump. if (Length == 0) { Length = CheckSize(Capstone, 5); } } return Length; } const size_t RenHook::Hook::WriteJump(const uintptr_t Address, const uintptr_t Detour, const size_t Size) const { std::vector<uint8_t> Bytes; // Should we do a x64 or x86 jump? if (Size >= 16) { /* * push rax * mov rax, 0xCCCCCCCCCCCCCCCC * xchg rax, [rsp] * ret */ Bytes = { 0x50, 0x48, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x48, 0x87, 0x04, 0x24, 0xC3 }; // Set our detour function. *reinterpret_cast<uintptr_t*>(Bytes.data() + 3) = Detour; } else { // If the displacement is less than 2048 MB do a near jump or if the hook size is equal with 5, otherwise do a far jump. if (std::abs(reinterpret_cast<uintptr_t*>(Address) - reinterpret_cast<uintptr_t*>(Detour)) <= 0x7fff0000 || Size == 5) { /* * jmp 0xCCCCCCCC */ Bytes = { 0xE9, 0xCC, 0xCC, 0xCC, 0xCC }; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 1) = CalculateDisplacement<int32_t>(Address, Detour, Bytes.size()); } else { /* * jmp qword ptr ds:[0xCCCCCCCC] */ Bytes = { 0xFF, 0x25, 0xCC, 0xCC, 0xCC, 0xCC }; // Add the displacement right after our jump back to the original function which is located at "m_memoryBlock.GetAddress() + Size" and has a size of 16 bytes. auto Displacement = m_memoryBlock->GetAddress() + Size + 17; // Write the address in memory at RIP + Displacement. *reinterpret_cast<uintptr_t*>(Displacement) = Detour; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 2) = CalculateDisplacement<int32_t>(Address, Displacement, Bytes.size()); } } // Calculate the hook size in bytes. auto HookSize = sizeof(uint8_t) * Bytes.size(); // Override the original bytes. std::memcpy(reinterpret_cast<uintptr_t*>(Address), Bytes.data(), HookSize); return HookSize; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MNameMapper.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-03-17 10:42:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Darren Kenny * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ #define _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ 1 #include <map> // Mozilla includes #include <MNSInclude.hxx> // Star Includes #include <rtl/ustring.hxx> namespace connectivity { namespace mozab { class MNameMapper { private: struct ltstr { bool operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const; }; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > dirMap; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > uriMap; static MNameMapper *instance; dirMap *mDirMap; uriMap *mUriMap; //clear dirs void clear(); public: static MNameMapper* getInstance(); MNameMapper(); ~MNameMapper(); // May modify the name passed in so that it's unique nsresult add( ::rtl::OUString& str, nsIAbDirectory* abook ); //reset dirs void reset(); // Will replace the given dir void replace( const ::rtl::OUString& str, nsIAbDirectory* abook ); // Get the directory corresponding to str bool getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook ); }; } } #endif //_CONNECTIVITY_MAB_NAMEMAPPER_HXX_ <commit_msg>INTEGRATION: CWS mozab04 (1.2.2); FILE MERGED 2004/04/12 10:15:55 windly 1.2.2.1: #i6883# make mozab driver threadsafe<commit_after>/************************************************************************* * * $RCSfile: MNameMapper.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hjs $ $Date: 2004-06-25 18:33:16 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Darren Kenny * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ #define _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ 1 #include <map> // Mozilla includes #include <MNSInclude.hxx> // Star Includes #include <rtl/ustring.hxx> namespace connectivity { namespace mozab { class MNameMapper { private: struct ltstr { bool operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const; }; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > dirMap; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > uriMap; static MNameMapper *instance; dirMap *mDirMap; uriMap *mUriMap; //clear dirs void clear(); public: static MNameMapper* getInstance(); MNameMapper(); ~MNameMapper(); // May modify the name passed in so that it's unique nsresult add( ::rtl::OUString& str, nsIAbDirectory* abook ); //reset dirs void reset(); // Will replace the given dir void replace( const ::rtl::OUString& str, nsIAbDirectory* abook ); // Get the directory corresponding to str bool getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook ); }; } } #endif //_CONNECTIVITY_MAB_NAMEMAPPER_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrwnd.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-26 09:30:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <math.h> #include <limits.h> #ifndef _TOOLS_TIME_HXX #include <tools/time.hxx> #endif #include <tools/debug.hxx> #ifndef _SV_SVIDS_HRC #include <svids.hrc> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _VCL_TIMER_HXX #include <timer.hxx> #endif #ifndef _VCL_EVENT_HXX #include <event.hxx> #endif #ifndef _VCL_SCRWND_HXX #include <scrwnd.hxx> #endif // ----------- // - Defines - // ----------- #define WHEEL_WIDTH 25 #define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 ) #define MAX_TIME 300 #define MIN_TIME 20 #define DEF_TIMEOUT 50 // ------------------- // - ImplWheelWindow - // ------------------- ImplWheelWindow::ImplWheelWindow( Window* pParent ) : FloatingWindow ( pParent, 0 ), mnRepaintTime ( 1UL ), mnTimeout ( DEF_TIMEOUT ), mnWheelMode ( WHEELMODE_NONE ), mnActDist ( 0UL ), mnActDeltaX ( 0L ), mnActDeltaY ( 0L ) { // we need a parent DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" ); const Size aSize( pParent->GetOutputSizePixel() ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; // calculate maximum speed distance mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) ); // create wheel window SetTitleType( FLOATWIN_TITLE_NONE ); ImplCreateImageList(); ResMgr* pResMgr = ImplGetResMgr(); Bitmap aBmp; if( pResMgr ) aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, *pResMgr ) ); ImplSetRegion( aBmp ); // set wheel mode if( bHorz && bVert ) ImplSetWheelMode( WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( WHEELMODE_H ); else ImplSetWheelMode( WHEELMODE_V ); // init timer mpTimer = new Timer; mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) ); mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); CaptureMouse(); } // ------------------------------------------------------------------------ ImplWheelWindow::~ImplWheelWindow() { ImplStop(); delete mpTimer; } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplStop() { ReleaseMouse(); mpTimer->Stop(); Show(FALSE); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp ) { Point aPos( GetPointerPosPixel() ); const Size aSize( rRegionBmp.GetSizePixel() ); Point aPoint; const Rectangle aRect( aPoint, aSize ); maCenter = maLastMousePos = aPos; aPos.X() -= aSize.Width() >> 1; aPos.Y() -= aSize.Height() >> 1; SetPosSizePixel( aPos, aSize ); SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplCreateImageList() { Bitmap aImgBmp; ResMgr* pResMgr = ImplGetResMgr(); if( pResMgr ) aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, *pResMgr ) ); maImgList = ImageList( aImgBmp, 6 ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode ) { if( nWheelMode != mnWheelMode ) { mnWheelMode = nWheelMode; if( WHEELMODE_NONE == mnWheelMode ) { if( IsVisible() ) Hide(); } else { if( !IsVisible() ) Show(); ImplDrawWheel(); } } } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplDrawWheel() { USHORT nId; switch( mnWheelMode ) { case( WHEELMODE_VH ): nId = 1; break; case( WHEELMODE_V ): nId = 2; break; case( WHEELMODE_H ): nId = 3; break; case( WHEELMODE_SCROLL_VH ):nId = 4; break; case( WHEELMODE_SCROLL_V ): nId = 5; break; case( WHEELMODE_SCROLL_H ): nId = 6; break; default: nId = 0; break; } if( nId ) DrawImage( Point(), maImgList.GetImage( nId ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplRecalcScrollValues() { if( mnActDist < WHEEL_RADIUS ) { mnActDeltaX = mnActDeltaY = 0L; mnTimeout = DEF_TIMEOUT; } else { ULONG nCurTime; // calc current time if( mnMaxWidth ) { const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME ); nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) ); } else nCurTime = MAX_TIME; if( !nCurTime ) nCurTime = 1UL; if( mnRepaintTime <= nCurTime ) mnTimeout = nCurTime - mnRepaintTime; else { long nMult = mnRepaintTime / nCurTime; if( !( mnRepaintTime % nCurTime ) ) mnTimeout = 0UL; else mnTimeout = ++nMult * nCurTime - mnRepaintTime; double fValX = (double) mnActDeltaX * nMult; double fValY = (double) mnActDeltaY * nMult; if( fValX > LONG_MAX ) mnActDeltaX = LONG_MAX; else if( fValX < LONG_MIN ) mnActDeltaX = LONG_MIN; else mnActDeltaX = (long) fValX; if( fValY > LONG_MAX ) mnActDeltaY = LONG_MAX; else if( fValY < LONG_MIN ) mnActDeltaY = LONG_MIN; else mnActDeltaY = (long) fValY; } } } // ------------------------------------------------------------------------ PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY ) { PointerStyle eStyle; const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; if( bHorz || bVert ) { if( mnActDist < WHEEL_RADIUS ) { if( bHorz && bVert ) eStyle = POINTER_AUTOSCROLL_NSWE; else if( bHorz ) eStyle = POINTER_AUTOSCROLL_WE; else eStyle = POINTER_AUTOSCROLL_NS; } else { double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180; if( fAngle < 0.0 ) fAngle += 360.; if( bHorz && bVert ) { if( fAngle >= 22.5 && fAngle <= 67.5 ) eStyle = POINTER_AUTOSCROLL_NE; else if( fAngle >= 67.5 && fAngle <= 112.5 ) eStyle = POINTER_AUTOSCROLL_N; else if( fAngle >= 112.5 && fAngle <= 157.5 ) eStyle = POINTER_AUTOSCROLL_NW; else if( fAngle >= 157.5 && fAngle <= 202.5 ) eStyle = POINTER_AUTOSCROLL_W; else if( fAngle >= 202.5 && fAngle <= 247.5 ) eStyle = POINTER_AUTOSCROLL_SW; else if( fAngle >= 247.5 && fAngle <= 292.5 ) eStyle = POINTER_AUTOSCROLL_S; else if( fAngle >= 292.5 && fAngle <= 337.5 ) eStyle = POINTER_AUTOSCROLL_SE; else eStyle = POINTER_AUTOSCROLL_E; } else if( bHorz ) { if( fAngle >= 270. || fAngle <= 90. ) eStyle = POINTER_AUTOSCROLL_E; else eStyle = POINTER_AUTOSCROLL_W; } else { if( fAngle >= 0. && fAngle <= 180. ) eStyle = POINTER_AUTOSCROLL_N; else eStyle = POINTER_AUTOSCROLL_S; } } } else eStyle = POINTER_ARROW; return eStyle; } // ------------------------------------------------------------------------ void ImplWheelWindow::Paint( const Rectangle& ) { ImplDrawWheel(); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt ) { FloatingWindow::MouseMove( rMEvt ); const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) ); const long nDistX = aMousePos.X() - maCenter.X(); const long nDistY = aMousePos.Y() - maCenter.Y(); mnActDist = (ULONG) hypot( (double) nDistX, nDistY ); const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; const BOOL bOuter = mnActDist > WHEEL_RADIUS; if( bOuter && ( maLastMousePos != aMousePos ) ) { switch( eActStyle ) { case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break; default: break; } } ImplRecalcScrollValues(); maLastMousePos = aMousePos; SetPointer( eActStyle ); if( bHorz && bVert ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H ); else ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V ); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt ) { if( mnActDist > WHEEL_RADIUS ) GetParent()->EndAutoScroll(); else FloatingWindow::MouseButtonUp( rMEvt ); } // ------------------------------------------------------------------------ IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG ) { if ( mnActDeltaX || mnActDeltaY ) { Window* pWindow = GetParent(); const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) ); Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) ); CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY ); CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData ); NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt ); if ( !ImplCallPreNotify( aNCmdEvt ) ) { const ULONG nTime = Time::GetSystemTicks(); ImplDelData aDel( this ); pWindow->Command( aCEvt ); if( aDel.IsDead() ) return 0; mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL ); ImplRecalcScrollValues(); } } if ( mnTimeout != mpTimer->GetTimeout() ) mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); return 0L; } <commit_msg>INTEGRATION: CWS ka009 (1.7.36); FILE MERGED 2007/06/06 13:15:05 ka 1.7.36.3: resolved conflicts 2006/10/13 16:39:37 ka 1.7.36.2: RESYNC: (1.7-1.8); FILE MERGED 2006/07/12 22:03:53 ka 1.7.36.1: #i66680#: added patch for optimized ImageList handling<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrwnd.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2007-06-06 14:21:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <math.h> #include <limits.h> #ifndef _TOOLS_TIME_HXX #include <tools/time.hxx> #endif #include <tools/debug.hxx> #ifndef _SV_SVIDS_HRC #include <svids.hrc> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _VCL_TIMER_HXX #include <timer.hxx> #endif #ifndef _VCL_EVENT_HXX #include <event.hxx> #endif #ifndef _VCL_SCRWND_HXX #include <scrwnd.hxx> #endif // ----------- // - Defines - // ----------- #define WHEEL_WIDTH 25 #define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 ) #define MAX_TIME 300 #define MIN_TIME 20 #define DEF_TIMEOUT 50 // ------------------- // - ImplWheelWindow - // ------------------- ImplWheelWindow::ImplWheelWindow( Window* pParent ) : FloatingWindow ( pParent, 0 ), mnRepaintTime ( 1UL ), mnTimeout ( DEF_TIMEOUT ), mnWheelMode ( WHEELMODE_NONE ), mnActDist ( 0UL ), mnActDeltaX ( 0L ), mnActDeltaY ( 0L ) { // we need a parent DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" ); const Size aSize( pParent->GetOutputSizePixel() ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; // calculate maximum speed distance mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) ); // create wheel window SetTitleType( FLOATWIN_TITLE_NONE ); ImplCreateImageList(); ResMgr* pResMgr = ImplGetResMgr(); Bitmap aBmp; if( pResMgr ) aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, *pResMgr ) ); ImplSetRegion( aBmp ); // set wheel mode if( bHorz && bVert ) ImplSetWheelMode( WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( WHEELMODE_H ); else ImplSetWheelMode( WHEELMODE_V ); // init timer mpTimer = new Timer; mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) ); mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); CaptureMouse(); } // ------------------------------------------------------------------------ ImplWheelWindow::~ImplWheelWindow() { ImplStop(); delete mpTimer; } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplStop() { ReleaseMouse(); mpTimer->Stop(); Show(FALSE); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp ) { Point aPos( GetPointerPosPixel() ); const Size aSize( rRegionBmp.GetSizePixel() ); Point aPoint; const Rectangle aRect( aPoint, aSize ); maCenter = maLastMousePos = aPos; aPos.X() -= aSize.Width() >> 1; aPos.Y() -= aSize.Height() >> 1; SetPosSizePixel( aPos, aSize ); SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplCreateImageList() { ResMgr* pResMgr = ImplGetResMgr(); if( pResMgr ) maImgList.InsertFromHorizontalBitmap ( ResId( SV_RESID_BITMAP_SCROLLBMP, *pResMgr ), 6, NULL ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode ) { if( nWheelMode != mnWheelMode ) { mnWheelMode = nWheelMode; if( WHEELMODE_NONE == mnWheelMode ) { if( IsVisible() ) Hide(); } else { if( !IsVisible() ) Show(); ImplDrawWheel(); } } } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplDrawWheel() { USHORT nId; switch( mnWheelMode ) { case( WHEELMODE_VH ): nId = 1; break; case( WHEELMODE_V ): nId = 2; break; case( WHEELMODE_H ): nId = 3; break; case( WHEELMODE_SCROLL_VH ):nId = 4; break; case( WHEELMODE_SCROLL_V ): nId = 5; break; case( WHEELMODE_SCROLL_H ): nId = 6; break; default: nId = 0; break; } if( nId ) DrawImage( Point(), maImgList.GetImage( nId ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplRecalcScrollValues() { if( mnActDist < WHEEL_RADIUS ) { mnActDeltaX = mnActDeltaY = 0L; mnTimeout = DEF_TIMEOUT; } else { ULONG nCurTime; // calc current time if( mnMaxWidth ) { const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME ); nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) ); } else nCurTime = MAX_TIME; if( !nCurTime ) nCurTime = 1UL; if( mnRepaintTime <= nCurTime ) mnTimeout = nCurTime - mnRepaintTime; else { long nMult = mnRepaintTime / nCurTime; if( !( mnRepaintTime % nCurTime ) ) mnTimeout = 0UL; else mnTimeout = ++nMult * nCurTime - mnRepaintTime; double fValX = (double) mnActDeltaX * nMult; double fValY = (double) mnActDeltaY * nMult; if( fValX > LONG_MAX ) mnActDeltaX = LONG_MAX; else if( fValX < LONG_MIN ) mnActDeltaX = LONG_MIN; else mnActDeltaX = (long) fValX; if( fValY > LONG_MAX ) mnActDeltaY = LONG_MAX; else if( fValY < LONG_MIN ) mnActDeltaY = LONG_MIN; else mnActDeltaY = (long) fValY; } } } // ------------------------------------------------------------------------ PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY ) { PointerStyle eStyle; const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; if( bHorz || bVert ) { if( mnActDist < WHEEL_RADIUS ) { if( bHorz && bVert ) eStyle = POINTER_AUTOSCROLL_NSWE; else if( bHorz ) eStyle = POINTER_AUTOSCROLL_WE; else eStyle = POINTER_AUTOSCROLL_NS; } else { double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180; if( fAngle < 0.0 ) fAngle += 360.; if( bHorz && bVert ) { if( fAngle >= 22.5 && fAngle <= 67.5 ) eStyle = POINTER_AUTOSCROLL_NE; else if( fAngle >= 67.5 && fAngle <= 112.5 ) eStyle = POINTER_AUTOSCROLL_N; else if( fAngle >= 112.5 && fAngle <= 157.5 ) eStyle = POINTER_AUTOSCROLL_NW; else if( fAngle >= 157.5 && fAngle <= 202.5 ) eStyle = POINTER_AUTOSCROLL_W; else if( fAngle >= 202.5 && fAngle <= 247.5 ) eStyle = POINTER_AUTOSCROLL_SW; else if( fAngle >= 247.5 && fAngle <= 292.5 ) eStyle = POINTER_AUTOSCROLL_S; else if( fAngle >= 292.5 && fAngle <= 337.5 ) eStyle = POINTER_AUTOSCROLL_SE; else eStyle = POINTER_AUTOSCROLL_E; } else if( bHorz ) { if( fAngle >= 270. || fAngle <= 90. ) eStyle = POINTER_AUTOSCROLL_E; else eStyle = POINTER_AUTOSCROLL_W; } else { if( fAngle >= 0. && fAngle <= 180. ) eStyle = POINTER_AUTOSCROLL_N; else eStyle = POINTER_AUTOSCROLL_S; } } } else eStyle = POINTER_ARROW; return eStyle; } // ------------------------------------------------------------------------ void ImplWheelWindow::Paint( const Rectangle& ) { ImplDrawWheel(); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt ) { FloatingWindow::MouseMove( rMEvt ); const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) ); const long nDistX = aMousePos.X() - maCenter.X(); const long nDistY = aMousePos.Y() - maCenter.Y(); mnActDist = (ULONG) hypot( (double) nDistX, nDistY ); const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; const BOOL bOuter = mnActDist > WHEEL_RADIUS; if( bOuter && ( maLastMousePos != aMousePos ) ) { switch( eActStyle ) { case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break; default: break; } } ImplRecalcScrollValues(); maLastMousePos = aMousePos; SetPointer( eActStyle ); if( bHorz && bVert ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H ); else ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V ); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt ) { if( mnActDist > WHEEL_RADIUS ) GetParent()->EndAutoScroll(); else FloatingWindow::MouseButtonUp( rMEvt ); } // ------------------------------------------------------------------------ IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG ) { if ( mnActDeltaX || mnActDeltaY ) { Window* pWindow = GetParent(); const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) ); Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) ); CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY ); CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData ); NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt ); if ( !ImplCallPreNotify( aNCmdEvt ) ) { const ULONG nTime = Time::GetSystemTicks(); ImplDelData aDel( this ); pWindow->Command( aCEvt ); if( aDel.IsDead() ) return 0; mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL ); ImplRecalcScrollValues(); } } if ( mnTimeout != mpTimer->GetTimeout() ) mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); return 0L; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "worksheetsettings.hxx" #include <com/sun/star/util/XProtectable.hpp> #include "oox/core/filterbase.hxx" #include "oox/helper/attributelist.hxx" #include "oox/token/properties.hxx" #include "biffinputstream.hxx" #include "pagesettings.hxx" #include "workbooksettings.hxx" #include "tabprotection.hxx" #include "document.hxx" namespace oox { namespace xls { // ============================================================================ using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using ::oox::core::CodecHelper; // ============================================================================ namespace { const sal_uInt8 BIFF12_SHEETPR_FILTERMODE = 0x01; const sal_uInt8 BIFF12_SHEETPR_EVAL_CF = 0x02; const sal_uInt32 BIFF_SHEETEXT_NOTABCOLOR = 0x7F; const sal_uInt16 BIFF_SHEETPR_DIALOGSHEET = 0x0010; const sal_uInt16 BIFF_SHEETPR_APPLYSTYLES = 0x0020; const sal_uInt16 BIFF_SHEETPR_SYMBOLSBELOW = 0x0040; const sal_uInt16 BIFF_SHEETPR_SYMBOLSRIGHT = 0x0080; const sal_uInt16 BIFF_SHEETPR_FITTOPAGES = 0x0100; const sal_uInt16 BIFF_SHEETPR_SKIPEXT = 0x0200; // BIFF3-BIFF4 const sal_uInt32 BIFF_SHEETPROT_OBJECTS = 0x00000001; const sal_uInt32 BIFF_SHEETPROT_SCENARIOS = 0x00000002; const sal_uInt32 BIFF_SHEETPROT_FORMAT_CELLS = 0x00000004; const sal_uInt32 BIFF_SHEETPROT_FORMAT_COLUMNS = 0x00000008; const sal_uInt32 BIFF_SHEETPROT_FORMAT_ROWS = 0x00000010; const sal_uInt32 BIFF_SHEETPROT_INSERT_COLUMNS = 0x00000020; const sal_uInt32 BIFF_SHEETPROT_INSERT_ROWS = 0x00000040; const sal_uInt32 BIFF_SHEETPROT_INSERT_HLINKS = 0x00000080; const sal_uInt32 BIFF_SHEETPROT_DELETE_COLUMNS = 0x00000100; const sal_uInt32 BIFF_SHEETPROT_DELETE_ROWS = 0x00000200; const sal_uInt32 BIFF_SHEETPROT_SELECT_LOCKED = 0x00000400; const sal_uInt32 BIFF_SHEETPROT_SORT = 0x00000800; const sal_uInt32 BIFF_SHEETPROT_AUTOFILTER = 0x00001000; const sal_uInt32 BIFF_SHEETPROT_PIVOTTABLES = 0x00002000; const sal_uInt32 BIFF_SHEETPROT_SELECT_UNLOCKED = 0x00004000; } // namespace // ============================================================================ SheetSettingsModel::SheetSettingsModel() : mbFilterMode( false ), mbApplyStyles( false ), mbSummaryBelow( true ), mbSummaryRight( true ) { } // ============================================================================ SheetProtectionModel::SheetProtectionModel() : mnPasswordHash( 0 ), mbSheet( false ), mbObjects( false ), mbScenarios( false ), mbFormatCells( true ), mbFormatColumns( true ), mbFormatRows( true ), mbInsertColumns( true ), mbInsertRows( true ), mbInsertHyperlinks( true ), mbDeleteColumns( true ), mbDeleteRows( true ), mbSelectLocked( false ), mbSort( true ), mbAutoFilter( true ), mbPivotTables( true ), mbSelectUnlocked( false ) { } // ============================================================================ WorksheetSettings::WorksheetSettings( const WorksheetHelper& rHelper ) : WorksheetHelper( rHelper ), maPhoneticSett( rHelper ) { } void WorksheetSettings::importSheetPr( const AttributeList& rAttribs ) { maSheetSettings.maCodeName = rAttribs.getString( XML_codeName, OUString() ); maSheetSettings.mbFilterMode = rAttribs.getBool( XML_filterMode, false ); } void WorksheetSettings::importChartSheetPr( const AttributeList& rAttribs ) { maSheetSettings.maCodeName = rAttribs.getString( XML_codeName, OUString() ); } void WorksheetSettings::importTabColor( const AttributeList& rAttribs ) { maSheetSettings.maTabColor.importColor( rAttribs ); } void WorksheetSettings::importOutlinePr( const AttributeList& rAttribs ) { maSheetSettings.mbApplyStyles = rAttribs.getBool( XML_applyStyles, false ); maSheetSettings.mbSummaryBelow = rAttribs.getBool( XML_summaryBelow, true ); maSheetSettings.mbSummaryRight = rAttribs.getBool( XML_summaryRight, true ); } void WorksheetSettings::importSheetProtection( const AttributeList& rAttribs ) { maSheetProt.mnPasswordHash = CodecHelper::getPasswordHash( rAttribs, XML_password ); maSheetProt.mbSheet = rAttribs.getBool( XML_sheet, false ); maSheetProt.mbObjects = rAttribs.getBool( XML_objects, false ); maSheetProt.mbScenarios = rAttribs.getBool( XML_scenarios, false ); maSheetProt.mbFormatCells = rAttribs.getBool( XML_formatCells, true ); maSheetProt.mbFormatColumns = rAttribs.getBool( XML_formatColumns, true ); maSheetProt.mbFormatRows = rAttribs.getBool( XML_formatRows, true ); maSheetProt.mbInsertColumns = rAttribs.getBool( XML_insertColumns, true ); maSheetProt.mbInsertRows = rAttribs.getBool( XML_insertRows, true ); maSheetProt.mbInsertHyperlinks = rAttribs.getBool( XML_insertHyperlinks, true ); maSheetProt.mbDeleteColumns = rAttribs.getBool( XML_deleteColumns, true ); maSheetProt.mbDeleteRows = rAttribs.getBool( XML_deleteRows, true ); maSheetProt.mbSelectLocked = rAttribs.getBool( XML_selectLockedCells, false ); maSheetProt.mbSort = rAttribs.getBool( XML_sort, true ); maSheetProt.mbAutoFilter = rAttribs.getBool( XML_autoFilter, true ); maSheetProt.mbPivotTables = rAttribs.getBool( XML_pivotTables, true ); maSheetProt.mbSelectUnlocked = rAttribs.getBool( XML_selectUnlockedCells, false ); } void WorksheetSettings::importChartProtection( const AttributeList& rAttribs ) { maSheetProt.mnPasswordHash = CodecHelper::getPasswordHash( rAttribs, XML_password ); maSheetProt.mbSheet = rAttribs.getBool( XML_content, false ); maSheetProt.mbObjects = rAttribs.getBool( XML_objects, false ); } void WorksheetSettings::importPhoneticPr( const AttributeList& rAttribs ) { maPhoneticSett.importPhoneticPr( rAttribs ); } void WorksheetSettings::importSheetPr( SequenceInputStream& rStrm ) { sal_uInt16 nFlags1; sal_uInt8 nFlags2; rStrm >> nFlags1 >> nFlags2 >> maSheetSettings.maTabColor; rStrm.skip( 8 ); // sync anchor cell rStrm >> maSheetSettings.maCodeName; // sheet settings maSheetSettings.mbFilterMode = getFlag( nFlags2, BIFF12_SHEETPR_FILTERMODE ); // outline settings, equal flags in all BIFFs maSheetSettings.mbApplyStyles = getFlag( nFlags1, BIFF_SHEETPR_APPLYSTYLES ); maSheetSettings.mbSummaryRight = getFlag( nFlags1, BIFF_SHEETPR_SYMBOLSRIGHT ); maSheetSettings.mbSummaryBelow = getFlag( nFlags1, BIFF_SHEETPR_SYMBOLSBELOW ); /* Fit printout to width/height - for whatever reason, this flag is still stored separated from the page settings */ getPageSettings().setFitToPagesMode( getFlag( nFlags1, BIFF_SHEETPR_FITTOPAGES ) ); } void WorksheetSettings::importChartSheetPr( SequenceInputStream& rStrm ) { rStrm.skip( 2 ); // flags, contains only the 'published' flag rStrm >> maSheetSettings.maTabColor >> maSheetSettings.maCodeName; } void WorksheetSettings::importSheetProtection( SequenceInputStream& rStrm ) { rStrm >> maSheetProt.mnPasswordHash; // no flags field for all these boolean flags?!? maSheetProt.mbSheet = rStrm.readInt32() != 0; maSheetProt.mbObjects = rStrm.readInt32() != 0; maSheetProt.mbScenarios = rStrm.readInt32() != 0; maSheetProt.mbFormatCells = rStrm.readInt32() != 0; maSheetProt.mbFormatColumns = rStrm.readInt32() != 0; maSheetProt.mbFormatRows = rStrm.readInt32() != 0; maSheetProt.mbInsertColumns = rStrm.readInt32() != 0; maSheetProt.mbInsertRows = rStrm.readInt32() != 0; maSheetProt.mbInsertHyperlinks = rStrm.readInt32() != 0; maSheetProt.mbDeleteColumns = rStrm.readInt32() != 0; maSheetProt.mbDeleteRows = rStrm.readInt32() != 0; maSheetProt.mbSelectLocked = rStrm.readInt32() != 0; maSheetProt.mbSort = rStrm.readInt32() != 0; maSheetProt.mbAutoFilter = rStrm.readInt32() != 0; maSheetProt.mbPivotTables = rStrm.readInt32() != 0; maSheetProt.mbSelectUnlocked = rStrm.readInt32() != 0; } void WorksheetSettings::importChartProtection( SequenceInputStream& rStrm ) { rStrm >> maSheetProt.mnPasswordHash; // no flags field for all these boolean flags?!? maSheetProt.mbSheet = rStrm.readInt32() != 0; maSheetProt.mbObjects = rStrm.readInt32() != 0; } void WorksheetSettings::importPhoneticPr( SequenceInputStream& rStrm ) { maPhoneticSett.importPhoneticPr( rStrm ); } void WorksheetSettings::finalizeImport() { // sheet protection if( maSheetProt.mbSheet ) { ScTableProtection aProtect; aProtect.setProtected(true); if (maSheetProt.mnPasswordHash) { Sequence<sal_Int8> aPass(2); aPass[0] = ( maSheetProt.mnPasswordHash>> 8) & 0xFF; aPass[1] = maSheetProt.mnPasswordHash & 0xFF; aProtect.setPasswordHash(aPass, PASSHASH_XL); } aProtect.setOption( ScTableProtection::OBJECTS, maSheetProt.mbObjects); aProtect.setOption( ScTableProtection::SCENARIOS, maSheetProt.mbScenarios ); aProtect.setOption( ScTableProtection::FORMAT_CELLS, maSheetProt.mbFormatCells ); aProtect.setOption( ScTableProtection::FORMAT_COLUMNS, maSheetProt.mbFormatColumns ); aProtect.setOption( ScTableProtection::FORMAT_ROWS, maSheetProt.mbFormatRows ); aProtect.setOption( ScTableProtection::INSERT_COLUMNS, maSheetProt.mbInsertColumns ); aProtect.setOption( ScTableProtection::INSERT_ROWS, maSheetProt.mbInsertRows ); aProtect.setOption( ScTableProtection::INSERT_HYPERLINKS, maSheetProt.mbInsertHyperlinks ); aProtect.setOption( ScTableProtection::DELETE_COLUMNS, maSheetProt.mbDeleteColumns ); aProtect.setOption( ScTableProtection::DELETE_ROWS,maSheetProt.mbDeleteRows ); aProtect.setOption( ScTableProtection::SELECT_LOCKED_CELLS, maSheetProt.mbSelectLocked ); aProtect.setOption( ScTableProtection::SORT, maSheetProt.mbSort ); aProtect.setOption( ScTableProtection::AUTOFILTER, maSheetProt.mbAutoFilter ); aProtect.setOption( ScTableProtection::PIVOT_TABLES, maSheetProt.mbPivotTables ); aProtect.setOption( ScTableProtection::SELECT_UNLOCKED_CELLS, maSheetProt.mbSelectUnlocked ); getScDocument().SetTabProtection( getSheetIndex(), &aProtect ); } // VBA code name PropertySet aPropSet( getSheet() ); aPropSet.setProperty( PROP_CodeName, maSheetSettings.maCodeName ); // sheet tab color if( !maSheetSettings.maTabColor.isAuto() ) { sal_Int32 nColor = maSheetSettings.maTabColor.getColor( getBaseFilter().getGraphicHelper() ); aPropSet.setProperty( PROP_TabColor, nColor ); } } // ============================================================================ } // namespace xls } // namespace oox /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>-Werror,-Wunused-const-variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "worksheetsettings.hxx" #include <com/sun/star/util/XProtectable.hpp> #include "oox/core/filterbase.hxx" #include "oox/helper/attributelist.hxx" #include "oox/token/properties.hxx" #include "biffinputstream.hxx" #include "pagesettings.hxx" #include "workbooksettings.hxx" #include "tabprotection.hxx" #include "document.hxx" namespace oox { namespace xls { // ============================================================================ using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using ::oox::core::CodecHelper; // ============================================================================ namespace { const sal_uInt8 BIFF12_SHEETPR_FILTERMODE = 0x01; const sal_uInt16 BIFF_SHEETPR_APPLYSTYLES = 0x0020; const sal_uInt16 BIFF_SHEETPR_SYMBOLSBELOW = 0x0040; const sal_uInt16 BIFF_SHEETPR_SYMBOLSRIGHT = 0x0080; const sal_uInt16 BIFF_SHEETPR_FITTOPAGES = 0x0100; } // namespace // ============================================================================ SheetSettingsModel::SheetSettingsModel() : mbFilterMode( false ), mbApplyStyles( false ), mbSummaryBelow( true ), mbSummaryRight( true ) { } // ============================================================================ SheetProtectionModel::SheetProtectionModel() : mnPasswordHash( 0 ), mbSheet( false ), mbObjects( false ), mbScenarios( false ), mbFormatCells( true ), mbFormatColumns( true ), mbFormatRows( true ), mbInsertColumns( true ), mbInsertRows( true ), mbInsertHyperlinks( true ), mbDeleteColumns( true ), mbDeleteRows( true ), mbSelectLocked( false ), mbSort( true ), mbAutoFilter( true ), mbPivotTables( true ), mbSelectUnlocked( false ) { } // ============================================================================ WorksheetSettings::WorksheetSettings( const WorksheetHelper& rHelper ) : WorksheetHelper( rHelper ), maPhoneticSett( rHelper ) { } void WorksheetSettings::importSheetPr( const AttributeList& rAttribs ) { maSheetSettings.maCodeName = rAttribs.getString( XML_codeName, OUString() ); maSheetSettings.mbFilterMode = rAttribs.getBool( XML_filterMode, false ); } void WorksheetSettings::importChartSheetPr( const AttributeList& rAttribs ) { maSheetSettings.maCodeName = rAttribs.getString( XML_codeName, OUString() ); } void WorksheetSettings::importTabColor( const AttributeList& rAttribs ) { maSheetSettings.maTabColor.importColor( rAttribs ); } void WorksheetSettings::importOutlinePr( const AttributeList& rAttribs ) { maSheetSettings.mbApplyStyles = rAttribs.getBool( XML_applyStyles, false ); maSheetSettings.mbSummaryBelow = rAttribs.getBool( XML_summaryBelow, true ); maSheetSettings.mbSummaryRight = rAttribs.getBool( XML_summaryRight, true ); } void WorksheetSettings::importSheetProtection( const AttributeList& rAttribs ) { maSheetProt.mnPasswordHash = CodecHelper::getPasswordHash( rAttribs, XML_password ); maSheetProt.mbSheet = rAttribs.getBool( XML_sheet, false ); maSheetProt.mbObjects = rAttribs.getBool( XML_objects, false ); maSheetProt.mbScenarios = rAttribs.getBool( XML_scenarios, false ); maSheetProt.mbFormatCells = rAttribs.getBool( XML_formatCells, true ); maSheetProt.mbFormatColumns = rAttribs.getBool( XML_formatColumns, true ); maSheetProt.mbFormatRows = rAttribs.getBool( XML_formatRows, true ); maSheetProt.mbInsertColumns = rAttribs.getBool( XML_insertColumns, true ); maSheetProt.mbInsertRows = rAttribs.getBool( XML_insertRows, true ); maSheetProt.mbInsertHyperlinks = rAttribs.getBool( XML_insertHyperlinks, true ); maSheetProt.mbDeleteColumns = rAttribs.getBool( XML_deleteColumns, true ); maSheetProt.mbDeleteRows = rAttribs.getBool( XML_deleteRows, true ); maSheetProt.mbSelectLocked = rAttribs.getBool( XML_selectLockedCells, false ); maSheetProt.mbSort = rAttribs.getBool( XML_sort, true ); maSheetProt.mbAutoFilter = rAttribs.getBool( XML_autoFilter, true ); maSheetProt.mbPivotTables = rAttribs.getBool( XML_pivotTables, true ); maSheetProt.mbSelectUnlocked = rAttribs.getBool( XML_selectUnlockedCells, false ); } void WorksheetSettings::importChartProtection( const AttributeList& rAttribs ) { maSheetProt.mnPasswordHash = CodecHelper::getPasswordHash( rAttribs, XML_password ); maSheetProt.mbSheet = rAttribs.getBool( XML_content, false ); maSheetProt.mbObjects = rAttribs.getBool( XML_objects, false ); } void WorksheetSettings::importPhoneticPr( const AttributeList& rAttribs ) { maPhoneticSett.importPhoneticPr( rAttribs ); } void WorksheetSettings::importSheetPr( SequenceInputStream& rStrm ) { sal_uInt16 nFlags1; sal_uInt8 nFlags2; rStrm >> nFlags1 >> nFlags2 >> maSheetSettings.maTabColor; rStrm.skip( 8 ); // sync anchor cell rStrm >> maSheetSettings.maCodeName; // sheet settings maSheetSettings.mbFilterMode = getFlag( nFlags2, BIFF12_SHEETPR_FILTERMODE ); // outline settings, equal flags in all BIFFs maSheetSettings.mbApplyStyles = getFlag( nFlags1, BIFF_SHEETPR_APPLYSTYLES ); maSheetSettings.mbSummaryRight = getFlag( nFlags1, BIFF_SHEETPR_SYMBOLSRIGHT ); maSheetSettings.mbSummaryBelow = getFlag( nFlags1, BIFF_SHEETPR_SYMBOLSBELOW ); /* Fit printout to width/height - for whatever reason, this flag is still stored separated from the page settings */ getPageSettings().setFitToPagesMode( getFlag( nFlags1, BIFF_SHEETPR_FITTOPAGES ) ); } void WorksheetSettings::importChartSheetPr( SequenceInputStream& rStrm ) { rStrm.skip( 2 ); // flags, contains only the 'published' flag rStrm >> maSheetSettings.maTabColor >> maSheetSettings.maCodeName; } void WorksheetSettings::importSheetProtection( SequenceInputStream& rStrm ) { rStrm >> maSheetProt.mnPasswordHash; // no flags field for all these boolean flags?!? maSheetProt.mbSheet = rStrm.readInt32() != 0; maSheetProt.mbObjects = rStrm.readInt32() != 0; maSheetProt.mbScenarios = rStrm.readInt32() != 0; maSheetProt.mbFormatCells = rStrm.readInt32() != 0; maSheetProt.mbFormatColumns = rStrm.readInt32() != 0; maSheetProt.mbFormatRows = rStrm.readInt32() != 0; maSheetProt.mbInsertColumns = rStrm.readInt32() != 0; maSheetProt.mbInsertRows = rStrm.readInt32() != 0; maSheetProt.mbInsertHyperlinks = rStrm.readInt32() != 0; maSheetProt.mbDeleteColumns = rStrm.readInt32() != 0; maSheetProt.mbDeleteRows = rStrm.readInt32() != 0; maSheetProt.mbSelectLocked = rStrm.readInt32() != 0; maSheetProt.mbSort = rStrm.readInt32() != 0; maSheetProt.mbAutoFilter = rStrm.readInt32() != 0; maSheetProt.mbPivotTables = rStrm.readInt32() != 0; maSheetProt.mbSelectUnlocked = rStrm.readInt32() != 0; } void WorksheetSettings::importChartProtection( SequenceInputStream& rStrm ) { rStrm >> maSheetProt.mnPasswordHash; // no flags field for all these boolean flags?!? maSheetProt.mbSheet = rStrm.readInt32() != 0; maSheetProt.mbObjects = rStrm.readInt32() != 0; } void WorksheetSettings::importPhoneticPr( SequenceInputStream& rStrm ) { maPhoneticSett.importPhoneticPr( rStrm ); } void WorksheetSettings::finalizeImport() { // sheet protection if( maSheetProt.mbSheet ) { ScTableProtection aProtect; aProtect.setProtected(true); if (maSheetProt.mnPasswordHash) { Sequence<sal_Int8> aPass(2); aPass[0] = ( maSheetProt.mnPasswordHash>> 8) & 0xFF; aPass[1] = maSheetProt.mnPasswordHash & 0xFF; aProtect.setPasswordHash(aPass, PASSHASH_XL); } aProtect.setOption( ScTableProtection::OBJECTS, maSheetProt.mbObjects); aProtect.setOption( ScTableProtection::SCENARIOS, maSheetProt.mbScenarios ); aProtect.setOption( ScTableProtection::FORMAT_CELLS, maSheetProt.mbFormatCells ); aProtect.setOption( ScTableProtection::FORMAT_COLUMNS, maSheetProt.mbFormatColumns ); aProtect.setOption( ScTableProtection::FORMAT_ROWS, maSheetProt.mbFormatRows ); aProtect.setOption( ScTableProtection::INSERT_COLUMNS, maSheetProt.mbInsertColumns ); aProtect.setOption( ScTableProtection::INSERT_ROWS, maSheetProt.mbInsertRows ); aProtect.setOption( ScTableProtection::INSERT_HYPERLINKS, maSheetProt.mbInsertHyperlinks ); aProtect.setOption( ScTableProtection::DELETE_COLUMNS, maSheetProt.mbDeleteColumns ); aProtect.setOption( ScTableProtection::DELETE_ROWS,maSheetProt.mbDeleteRows ); aProtect.setOption( ScTableProtection::SELECT_LOCKED_CELLS, maSheetProt.mbSelectLocked ); aProtect.setOption( ScTableProtection::SORT, maSheetProt.mbSort ); aProtect.setOption( ScTableProtection::AUTOFILTER, maSheetProt.mbAutoFilter ); aProtect.setOption( ScTableProtection::PIVOT_TABLES, maSheetProt.mbPivotTables ); aProtect.setOption( ScTableProtection::SELECT_UNLOCKED_CELLS, maSheetProt.mbSelectUnlocked ); getScDocument().SetTabProtection( getSheetIndex(), &aProtect ); } // VBA code name PropertySet aPropSet( getSheet() ); aPropSet.setProperty( PROP_CodeName, maSheetSettings.maCodeName ); // sheet tab color if( !maSheetSettings.maTabColor.isAuto() ) { sal_Int32 nColor = maSheetSettings.maTabColor.getColor( getBaseFilter().getGraphicHelper() ); aPropSet.setProperty( PROP_TabColor, nColor ); } } // ============================================================================ } // namespace xls } // namespace oox /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include <thread> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } Status Planning::InitFrame(const uint32_t sequence_num, const TrajectoryPoint& init_adc_point) { frame_.reset(new Frame(sequence_num)); frame_->SetPlanningStartPoint(init_adc_point); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return Status(ErrorCode::PLANNING_ERROR, "routing is empty"); } frame_->SetVehicleInitPose(VehicleState::instance()->pose()); frame_->SetRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction done."; } auto status = frame_->Init(config_, start_timestamp_); if (!status.ok()) { AERROR << "failed to init frame"; return Status(ErrorCode::PLANNING_ERROR, "init frame failed"); } frame_->RecordInputDebug(); return Status::OK(); } Status Planning::Init() { pnc_map_.reset(new hdmap::PncMap(apollo::hdmap::BaseMapFile())); Frame::SetMap(pnc_map_.get()); CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) << "failed to load planning config file " << FLAGS_planning_config_file; if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (FLAGS_enable_prediction && AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } Status Planning::Start() { static ros::Rate loop_rate(FLAGS_planning_loop_rate); while (ros::ok()) { RunOnce(); if (frame_) { auto seq_num = frame_->SequenceNum(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } ros::spinOnce(); loop_rate.sleep(); } return Status::OK(); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb, double timestamp) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::RunOnce() { start_timestamp_ = Clock::NowInSecond(); AdapterManager::Observe(); ADCTrajectory not_ready_pb; auto* not_ready = not_ready_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (AdapterManager::GetLocalization()->Empty()) { not_ready->set_reason("localization not ready"); } else if (AdapterManager::GetChassis()->Empty()) { not_ready->set_reason("chassis not ready"); } else if (AdapterManager::GetRoutingResponse()->Empty()) { not_ready->set_reason("routing not ready"); } else if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { not_ready->set_reason("prediction not ready"); } if (not_ready->has_reason()) { AERROR << not_ready->reason() << "; skip the planning cycle."; PublishPlanningPb(&not_ready_pb); return; } // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::Status status = common::VehicleState::instance()->Update(localization, chassis); if (!status.ok()) { AERROR << "Update VehicleState failed."; not_ready->set_reason("Update VehicleState failed."); status.Save(not_ready_pb.mutable_header()->mutable_status()); PublishPlanningPb(&not_ready_pb); return; } const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_auto_mode, start_timestamp_, planning_cycle_time, last_publishable_trajectory_); const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; status = InitFrame(frame_num, stitching_trajectory.back()); if (!status.ok()) { ADCTrajectory estop; estop.mutable_estop(); AERROR << "Init frame failed"; status.Save(estop.mutable_header()->mutable_status()); PublishPlanningPb(&estop, start_timestamp_); return; } status = Plan(start_timestamp_, stitching_trajectory); const double end_timestamp = Clock::NowInSecond(); const double time_diff_ms = (end_timestamp - start_timestamp_) * 1000; auto trajectory_pb = frame_->MutableADCTrajectory(); trajectory_pb->mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb->latency_stats().DebugString(); if (status.ok()) { PublishPlanningPb(trajectory_pb, start_timestamp_); ADEBUG << "Planning succeeded:" << trajectory_pb->header().DebugString(); } else { status.Save(trajectory_pb->mutable_header()->mutable_status()); PublishPlanningPb(trajectory_pb, start_timestamp_); AERROR << "Planning failed"; } } void Planning::Stop() { last_publishable_trajectory_.Clear(); frame_.reset(nullptr); planner_.reset(nullptr); } common::Status Planning::Plan( const double current_time_stamp, const std::vector<common::TrajectoryPoint>& stitching_trajectory) { auto trajectory_pb = frame_->MutableADCTrajectory(); if (FLAGS_enable_record_debug) { trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_init_point() ->CopyFrom(stitching_trajectory.back()); } auto status = Status::OK(); for (auto& reference_line_info : frame_->reference_line_info()) { status = planner_->Plan(stitching_trajectory.back(), frame_.get(), &reference_line_info); AERROR_IF(!status.ok()) << "planner failed to make a driving plan."; } const auto* best_reference_line = frame_->FindDriveReferenceLineInfo(); if (!best_reference_line) { std::string msg("planner failed to make a driving plan"); AERROR << msg; last_publishable_trajectory_.Clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } auto* ptr_debug = frame_->MutableADCTrajectory()->mutable_debug(); ptr_debug->MergeFrom(best_reference_line->debug()); frame_->MutableADCTrajectory()->mutable_latency_stats()->MergeFrom( best_reference_line->latency_stats()); // Add debug information. if (FLAGS_enable_record_debug) { auto* reference_line = ptr_debug->mutable_planning_data()->add_path(); reference_line->set_name("planning_reference_line"); const auto& reference_points = best_reference_line->reference_line().reference_points(); for (const auto& reference_point : reference_points) { auto* path_point = reference_line->add_path_point(); path_point->set_x(reference_point.x()); path_point->set_y(reference_point.y()); path_point->set_theta(reference_point.heading()); path_point->set_kappa(reference_point.kappa()); path_point->set_dkappa(reference_point.dkappa()); } } PublishableTrajectory publishable_trajectory( current_time_stamp, best_reference_line->trajectory()); publishable_trajectory.PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); publishable_trajectory.PopulateTrajectoryProtobuf(trajectory_pb); trajectory_pb->set_is_replan(stitching_trajectory.size() == 1); // update last publishable trajectory; last_publishable_trajectory_ = std::move(publishable_trajectory); return status; } } // namespace planning } // namespace apollo <commit_msg>planning: remove hard code planning name.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include <thread> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } Status Planning::InitFrame(const uint32_t sequence_num, const TrajectoryPoint& init_adc_point) { frame_.reset(new Frame(sequence_num)); frame_->SetPlanningStartPoint(init_adc_point); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return Status(ErrorCode::PLANNING_ERROR, "routing is empty"); } frame_->SetVehicleInitPose(VehicleState::instance()->pose()); frame_->SetRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction done."; } auto status = frame_->Init(config_, start_timestamp_); if (!status.ok()) { AERROR << "failed to init frame"; return Status(ErrorCode::PLANNING_ERROR, "init frame failed"); } frame_->RecordInputDebug(); return Status::OK(); } Status Planning::Init() { pnc_map_.reset(new hdmap::PncMap(apollo::hdmap::BaseMapFile())); Frame::SetMap(pnc_map_.get()); CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) << "failed to load planning config file " << FLAGS_planning_config_file; if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (FLAGS_enable_prediction && AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } Status Planning::Start() { static ros::Rate loop_rate(FLAGS_planning_loop_rate); while (ros::ok()) { RunOnce(); if (frame_) { auto seq_num = frame_->SequenceNum(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } ros::spinOnce(); loop_rate.sleep(); } return Status::OK(); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb) { AdapterManager::FillPlanningHeader(Name(), trajectory_pb); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb, double timestamp) { AdapterManager::FillPlanningHeader(Name(), trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::RunOnce() { start_timestamp_ = Clock::NowInSecond(); AdapterManager::Observe(); ADCTrajectory not_ready_pb; auto* not_ready = not_ready_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (AdapterManager::GetLocalization()->Empty()) { not_ready->set_reason("localization not ready"); } else if (AdapterManager::GetChassis()->Empty()) { not_ready->set_reason("chassis not ready"); } else if (AdapterManager::GetRoutingResponse()->Empty()) { not_ready->set_reason("routing not ready"); } else if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { not_ready->set_reason("prediction not ready"); } if (not_ready->has_reason()) { AERROR << not_ready->reason() << "; skip the planning cycle."; PublishPlanningPb(&not_ready_pb); return; } // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::Status status = common::VehicleState::instance()->Update(localization, chassis); if (!status.ok()) { AERROR << "Update VehicleState failed."; not_ready->set_reason("Update VehicleState failed."); status.Save(not_ready_pb.mutable_header()->mutable_status()); PublishPlanningPb(&not_ready_pb); return; } const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_auto_mode, start_timestamp_, planning_cycle_time, last_publishable_trajectory_); const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; status = InitFrame(frame_num, stitching_trajectory.back()); if (!status.ok()) { ADCTrajectory estop; estop.mutable_estop(); AERROR << "Init frame failed"; status.Save(estop.mutable_header()->mutable_status()); PublishPlanningPb(&estop, start_timestamp_); return; } status = Plan(start_timestamp_, stitching_trajectory); const double end_timestamp = Clock::NowInSecond(); const double time_diff_ms = (end_timestamp - start_timestamp_) * 1000; auto trajectory_pb = frame_->MutableADCTrajectory(); trajectory_pb->mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb->latency_stats().DebugString(); if (status.ok()) { PublishPlanningPb(trajectory_pb, start_timestamp_); ADEBUG << "Planning succeeded:" << trajectory_pb->header().DebugString(); } else { status.Save(trajectory_pb->mutable_header()->mutable_status()); PublishPlanningPb(trajectory_pb, start_timestamp_); AERROR << "Planning failed"; } } void Planning::Stop() { last_publishable_trajectory_.Clear(); frame_.reset(nullptr); planner_.reset(nullptr); } common::Status Planning::Plan( const double current_time_stamp, const std::vector<common::TrajectoryPoint>& stitching_trajectory) { auto trajectory_pb = frame_->MutableADCTrajectory(); if (FLAGS_enable_record_debug) { trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_init_point() ->CopyFrom(stitching_trajectory.back()); } auto status = Status::OK(); for (auto& reference_line_info : frame_->reference_line_info()) { status = planner_->Plan(stitching_trajectory.back(), frame_.get(), &reference_line_info); AERROR_IF(!status.ok()) << "planner failed to make a driving plan."; } const auto* best_reference_line = frame_->FindDriveReferenceLineInfo(); if (!best_reference_line) { std::string msg("planner failed to make a driving plan"); AERROR << msg; last_publishable_trajectory_.Clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } auto* ptr_debug = frame_->MutableADCTrajectory()->mutable_debug(); ptr_debug->MergeFrom(best_reference_line->debug()); frame_->MutableADCTrajectory()->mutable_latency_stats()->MergeFrom( best_reference_line->latency_stats()); // Add debug information. if (FLAGS_enable_record_debug) { auto* reference_line = ptr_debug->mutable_planning_data()->add_path(); reference_line->set_name("planning_reference_line"); const auto& reference_points = best_reference_line->reference_line().reference_points(); for (const auto& reference_point : reference_points) { auto* path_point = reference_line->add_path_point(); path_point->set_x(reference_point.x()); path_point->set_y(reference_point.y()); path_point->set_theta(reference_point.heading()); path_point->set_kappa(reference_point.kappa()); path_point->set_dkappa(reference_point.dkappa()); } } PublishableTrajectory publishable_trajectory( current_time_stamp, best_reference_line->trajectory()); publishable_trajectory.PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); publishable_trajectory.PopulateTrajectoryProtobuf(trajectory_pb); trajectory_pb->set_is_replan(stitching_trajectory.size() == 1); // update last publishable trajectory; last_publishable_trajectory_ = std::move(publishable_trajectory); return status; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <sstream> #include <cstring> #include <string> #include "BoyerMoore.h" using namespace v8; using namespace node; namespace { // this is an application of the Curiously Recurring Template Pattern template <class Derived> struct UnaryAction { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } return static_cast<Derived*>(this)->apply(self, args, scope); } }; template <class Derived> struct BinaryAction { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return static_cast<Derived*>(this)->apply(self, *s, s.length(), args, scope); } if (Buffer::HasInstance(args[0])) { Local<Object> other = args[0]->ToObject(); return static_cast<Derived*>(this)->apply( self, Buffer::Data(other), Buffer::Length(other), args, scope); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument must be a string or a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; // // helper functions // Handle<Value> clear(Handle<Object>& buffer, int c) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); memset(data, c, length); return buffer; } Handle<Value> fill(Handle<Object>& buffer, void* pattern, size_t size) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); if (size >= length) { memcpy(data, pattern, length); } else { const int n_copies = length / size; const int remainder = length % size; for (int i = 0; i < n_copies; i++) { memcpy(data + size * i, pattern, size); } memcpy(data + size * n_copies, pattern, remainder); } return buffer; } int compare(Handle<Object>& buffer, const char* data2, size_t length2) { size_t length = Buffer::Length(buffer); if (length != length2) { return length > length2 ? 1 : -1; } char* data = Buffer::Data(buffer); return memcmp(data, data2, length); } // // actions // struct ClearAction: UnaryAction<ClearAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { return clear(buffer, 0); } }; struct FillAction: UnaryAction<FillAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { if (args[0]->IsInt32()) { int c = args[0]->ToInt32()->Int32Value(); return clear(buffer, c); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return fill(buffer, *s, s.length()); } if (Buffer::HasInstance(args[0])) { Handle<Object> other = args[0]->ToObject(); size_t length = Buffer::Length(other); char* data = Buffer::Data(other); return fill(buffer, data, length); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument should be either a string, a buffer or an integer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; struct ReverseAction: UnaryAction<ReverseAction> { // O(n/2) for all cases which is okay, might be optimized some more with whole-word swaps // XXX won't this trash the L1 cache something awful? Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { char* head = Buffer::Data(buffer); char* tail = head + Buffer::Length(buffer) - 1; // xor swap, just because I can while (head < tail) *head ^= *tail, *tail ^= *head, *head ^= *tail, ++head, --tail; return buffer; } }; struct EqualsAction: BinaryAction<EqualsAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return compare(buffer, data, size) == 0 ? True() : False(); } }; struct CompareAction: BinaryAction<CompareAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return scope.Close(Integer::New(compare(buffer, data, size))); } }; struct IndexOfAction: BinaryAction<IndexOfAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data2, size_t size2, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t size = Buffer::Length(buffer); const char* p = boyermoore_search(data, size, data2, size2); const ptrdiff_t offset = p ? (p - data) : -1; return scope.Close(Integer::New(offset)); } }; static char toHexTable[] = "0123456789abcdef"; // CHECKME is this cache efficient? static char fromHexTable[] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; inline Handle<Value> decodeHex(const char* data, size_t size, const Arguments& args, HandleScope& scope) { if (size & 1) { return ThrowException(Exception::Error(String::New( "Odd string length, this is not hexadecimal data."))); } if (size == 0) { return String::Empty(); } Handle<Object>& buffer = Buffer::New(size / 2)->handle_; for (char* s = Buffer::Data(buffer); size > 0; size -= 2) { int a = fromHexTable[*data++]; int b = fromHexTable[*data++]; if (a == -1 || b == -1) { return ThrowException(Exception::Error(String::New( "This is not hexadecimal data."))); } *s++ = b | (a << 4); } return buffer; } struct FromHexAction: UnaryAction<FromHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t length = Buffer::Length(buffer); return decodeHex(data, length, args, scope); } }; struct ToHexAction: UnaryAction<ToHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const size_t size = Buffer::Length(buffer); const char* data = Buffer::Data(buffer); if (size == 0) { return String::Empty(); } std::string s(size * 2, 0); for (size_t i = 0; i < size; ++i) { const uint8_t c = (uint8_t) data[i]; s[i * 2] = toHexTable[c >> 4]; s[i * 2 + 1] = toHexTable[c & 15]; } return scope.Close(String::New(s.c_str(), s.size())); } }; // // V8 function callbacks // Handle<Value> Clear(const Arguments& args) { return ClearAction()(args); } Handle<Value> Fill(const Arguments& args) { return FillAction()(args); } Handle<Value> Reverse(const Arguments& args) { return ReverseAction()(args); } Handle<Value> Equals(const Arguments& args) { return EqualsAction()(args); } Handle<Value> Compare(const Arguments& args) { return CompareAction()(args); } Handle<Value> IndexOf(const Arguments& args) { return IndexOfAction()(args); } Handle<Value> FromHex(const Arguments& args) { return FromHexAction()(args); } Handle<Value> ToHex(const Arguments& args) { return ToHexAction()(args); } Handle<Value> Concat(const Arguments& args) { HandleScope scope; size_t size = 0; for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { // Utf8Length() because we need the length in bytes, not characters size += arg->ToString()->Utf8Length(); } else if (Buffer::HasInstance(arg)) { size += Buffer::Length(arg->ToObject()); } else { std::stringstream s; s << "Argument #" << index << " is neither a string nor a buffer object."; const char* message = s.str().c_str(); return ThrowException(Exception::TypeError(String::New(message))); } } Buffer& dst = *Buffer::New(size); char* s = Buffer::Data(dst.handle_); for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { String::Utf8Value v(arg->ToString()); memcpy(s, *v, v.length()); s += v.length(); } else if (Buffer::HasInstance(arg)) { Local<Object> b = arg->ToObject(); const char* data = Buffer::Data(b); size_t length = Buffer::Length(b); memcpy(s, data, length); s += length; } else { return ThrowException(Exception::Error(String::New( "Congratulations! You have run into a bug: argument is neither a string nor a buffer object. " "Please make the world a better place and report it."))); } } return scope.Close(dst.handle_); } void RegisterModule(Handle<Object> target) { target->Set(String::NewSymbol("concat"), FunctionTemplate::New(Concat)->GetFunction()); target->Set(String::NewSymbol("fill"), FunctionTemplate::New(Fill)->GetFunction()); target->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction()); target->Set(String::NewSymbol("reverse"), FunctionTemplate::New(Reverse)->GetFunction()); target->Set(String::NewSymbol("equals"), FunctionTemplate::New(Equals)->GetFunction()); target->Set(String::NewSymbol("compare"), FunctionTemplate::New(Compare)->GetFunction()); target->Set(String::NewSymbol("indexOf"), FunctionTemplate::New(IndexOf)->GetFunction()); target->Set(String::NewSymbol("fromHex"), FunctionTemplate::New(FromHex)->GetFunction()); target->Set(String::NewSymbol("toHex"), FunctionTemplate::New(ToHex)->GetFunction()); } } // anonymous namespace NODE_MODULE(buffertools, RegisterModule); <commit_msg>Use unsigned data types when decoding hexadecimal data, avoid negative or out-of-bounds array indexing.<commit_after>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <sstream> #include <cstring> #include <string> #include "BoyerMoore.h" using namespace v8; using namespace node; namespace { // this is an application of the Curiously Recurring Template Pattern template <class Derived> struct UnaryAction { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } return static_cast<Derived*>(this)->apply(self, args, scope); } }; template <class Derived> struct BinaryAction { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return static_cast<Derived*>(this)->apply(self, *s, s.length(), args, scope); } if (Buffer::HasInstance(args[0])) { Local<Object> other = args[0]->ToObject(); return static_cast<Derived*>(this)->apply( self, Buffer::Data(other), Buffer::Length(other), args, scope); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument must be a string or a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; // // helper functions // Handle<Value> clear(Handle<Object>& buffer, int c) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); memset(data, c, length); return buffer; } Handle<Value> fill(Handle<Object>& buffer, void* pattern, size_t size) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); if (size >= length) { memcpy(data, pattern, length); } else { const int n_copies = length / size; const int remainder = length % size; for (int i = 0; i < n_copies; i++) { memcpy(data + size * i, pattern, size); } memcpy(data + size * n_copies, pattern, remainder); } return buffer; } int compare(Handle<Object>& buffer, const char* data2, size_t length2) { size_t length = Buffer::Length(buffer); if (length != length2) { return length > length2 ? 1 : -1; } char* data = Buffer::Data(buffer); return memcmp(data, data2, length); } // // actions // struct ClearAction: UnaryAction<ClearAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { return clear(buffer, 0); } }; struct FillAction: UnaryAction<FillAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { if (args[0]->IsInt32()) { int c = args[0]->ToInt32()->Int32Value(); return clear(buffer, c); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return fill(buffer, *s, s.length()); } if (Buffer::HasInstance(args[0])) { Handle<Object> other = args[0]->ToObject(); size_t length = Buffer::Length(other); char* data = Buffer::Data(other); return fill(buffer, data, length); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument should be either a string, a buffer or an integer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; struct ReverseAction: UnaryAction<ReverseAction> { // O(n/2) for all cases which is okay, might be optimized some more with whole-word swaps // XXX won't this trash the L1 cache something awful? Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { char* head = Buffer::Data(buffer); char* tail = head + Buffer::Length(buffer) - 1; // xor swap, just because I can while (head < tail) *head ^= *tail, *tail ^= *head, *head ^= *tail, ++head, --tail; return buffer; } }; struct EqualsAction: BinaryAction<EqualsAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return compare(buffer, data, size) == 0 ? True() : False(); } }; struct CompareAction: BinaryAction<CompareAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return scope.Close(Integer::New(compare(buffer, data, size))); } }; struct IndexOfAction: BinaryAction<IndexOfAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data2, size_t size2, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t size = Buffer::Length(buffer); const char* p = boyermoore_search(data, size, data2, size2); const ptrdiff_t offset = p ? (p - data) : -1; return scope.Close(Integer::New(offset)); } }; static char toHexTable[] = "0123456789abcdef"; // CHECKME is this cache efficient? static char fromHexTable[] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; inline Handle<Value> decodeHex(const char* const data, const size_t size, const Arguments& args, HandleScope& scope) { if (size & 1) { return ThrowException(Exception::Error(String::New( "Odd string length, this is not hexadecimal data."))); } if (size == 0) { return String::Empty(); } Handle<Object>& buffer = Buffer::New(size / 2)->handle_; uint8_t *src = (uint8_t *) data; uint8_t *dst = (uint8_t *) Buffer::Data(buffer); for (size_t i = 0; i < size; i += 2) { int a = fromHexTable[*src++]; int b = fromHexTable[*src++]; if (a == -1 || b == -1) { return ThrowException(Exception::Error(String::New( "This is not hexadecimal data."))); } *dst++ = b | (a << 4); } return buffer; } struct FromHexAction: UnaryAction<FromHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t length = Buffer::Length(buffer); return decodeHex(data, length, args, scope); } }; struct ToHexAction: UnaryAction<ToHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const size_t size = Buffer::Length(buffer); const char* data = Buffer::Data(buffer); if (size == 0) { return String::Empty(); } std::string s(size * 2, 0); for (size_t i = 0; i < size; ++i) { const uint8_t c = (uint8_t) data[i]; s[i * 2] = toHexTable[c >> 4]; s[i * 2 + 1] = toHexTable[c & 15]; } return scope.Close(String::New(s.c_str(), s.size())); } }; // // V8 function callbacks // Handle<Value> Clear(const Arguments& args) { return ClearAction()(args); } Handle<Value> Fill(const Arguments& args) { return FillAction()(args); } Handle<Value> Reverse(const Arguments& args) { return ReverseAction()(args); } Handle<Value> Equals(const Arguments& args) { return EqualsAction()(args); } Handle<Value> Compare(const Arguments& args) { return CompareAction()(args); } Handle<Value> IndexOf(const Arguments& args) { return IndexOfAction()(args); } Handle<Value> FromHex(const Arguments& args) { return FromHexAction()(args); } Handle<Value> ToHex(const Arguments& args) { return ToHexAction()(args); } Handle<Value> Concat(const Arguments& args) { HandleScope scope; size_t size = 0; for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { // Utf8Length() because we need the length in bytes, not characters size += arg->ToString()->Utf8Length(); } else if (Buffer::HasInstance(arg)) { size += Buffer::Length(arg->ToObject()); } else { std::stringstream s; s << "Argument #" << index << " is neither a string nor a buffer object."; const char* message = s.str().c_str(); return ThrowException(Exception::TypeError(String::New(message))); } } Buffer& dst = *Buffer::New(size); char* s = Buffer::Data(dst.handle_); for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { String::Utf8Value v(arg->ToString()); memcpy(s, *v, v.length()); s += v.length(); } else if (Buffer::HasInstance(arg)) { Local<Object> b = arg->ToObject(); const char* data = Buffer::Data(b); size_t length = Buffer::Length(b); memcpy(s, data, length); s += length; } else { return ThrowException(Exception::Error(String::New( "Congratulations! You have run into a bug: argument is neither a string nor a buffer object. " "Please make the world a better place and report it."))); } } return scope.Close(dst.handle_); } void RegisterModule(Handle<Object> target) { target->Set(String::NewSymbol("concat"), FunctionTemplate::New(Concat)->GetFunction()); target->Set(String::NewSymbol("fill"), FunctionTemplate::New(Fill)->GetFunction()); target->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction()); target->Set(String::NewSymbol("reverse"), FunctionTemplate::New(Reverse)->GetFunction()); target->Set(String::NewSymbol("equals"), FunctionTemplate::New(Equals)->GetFunction()); target->Set(String::NewSymbol("compare"), FunctionTemplate::New(Compare)->GetFunction()); target->Set(String::NewSymbol("indexOf"), FunctionTemplate::New(IndexOf)->GetFunction()); target->Set(String::NewSymbol("fromHex"), FunctionTemplate::New(FromHex)->GetFunction()); target->Set(String::NewSymbol("toHex"), FunctionTemplate::New(ToHex)->GetFunction()); } } // anonymous namespace NODE_MODULE(buffertools, RegisterModule); <|endoftext|>
<commit_before>/*------------gauss_vis.cpp----------------------------------------------------/ * * Purpose: Simple visualization script for difference scenes for computus video * 2020 * * Notes: Compilation instructions: * g++ -L/path/to/GathVL -I/path/to/GathVL -lgathvl -o gauss_vis gauss_vis.cpp `pkg-config --cflags --libs cairo libavformat libavcodec libswresample libswscale libavutil` -Wl,-rpath,/path/to/GathVL * *-----------------------------------------------------------------------------*/ #include <iostream> #include <cmath> #include <memory> #include <vector> #include "include/camera.h" #include "include/scene.h" void orbit_scene(camera& cam, scene& world, double end_frame, double timestep){ color sun_clr = {1, 1, 0.5, 1}; color earth_clr = {0, 1, 1, 1}; color moon_clr = {0.5, 0.5, 0.5, 1}; double earth_radius = 200; double moon_radius = 100; vec earth_offset = vec{sqrt(earth_radius*earth_radius/2), sqrt(earth_radius*earth_radius/2)}; vec moon_offset = vec{sqrt(moon_radius*moon_radius/2), sqrt(moon_radius*moon_radius/2)}; vec sun_loc = {world.size.x/2, world.size.y/2}; vec earth_loc = sun_loc + earth_offset; vec moon_loc = earth_loc + moon_offset; auto sun = std::make_shared<ellipse>(sun_clr, sun_loc, vec{0,0}, 0, true); sun->add_animator<vec_animator>(0,20, &sun->size, vec{0,0}, vec{60,60}); sun->add_animator<vec_animator>(20,25, &sun->size, vec{60,60}, vec{55,55}); std::shared_ptr<ellipse> earths[3]; std::shared_ptr<ellipse> moons[3]; for (int i = 0; i < 3; ++i){ earths[i] = std::make_shared<ellipse>(earth_clr, earth_loc, vec{0,0}, 0, true); earths[i]->add_animator<vec_animator>(10,30, &earths[i]->size, vec{0,0}, vec{30,30}); earths[i]->add_animator<vec_animator>(30,35, &earths[i]->size, vec{30,30}, vec{25,25}); moons[i] = std::make_shared<ellipse>(moon_clr, moon_loc, vec{0,0}, 0, true); moons[i]->add_animator<vec_animator>(20,40, &moons[i]->size, vec{0,0}, vec{15,15}); moons[i]->add_animator<vec_animator>(40,45, &moons[i]->size, vec{15,15}, vec{10,10}); } // Creating a theta for the earth that changes with time double earth_theta[2] = {M_PI/4, 0}; double moon_theta[2] = {M_PI/4, 0}; double earth_freq = 0.1; double moon_freq = earth_freq*365*12/354; // TODO: figure out exact number for lunar cycle double gregorian_year_frames = 2*M_PI/earth_freq/timestep; double lunar_year_frames = gregorian_year_frames*29.53*12/365.2524; int indices = 2; for (int i = 50; i < gregorian_year_frames + 51; ++i){ //if (i > lunar_year_frames + 32){ if (i == floor(lunar_year_frames) + 51){ indices = 1; earth_theta[1] = fmod(earth_theta[0], 2*M_PI); } earth_theta[0] -= earth_freq*timestep; moon_theta[0] -= moon_freq*timestep + earth_freq*timestep; for (int j = 0; j < indices; ++j){ vec new_loc = sun_loc + vec(earth_radius*cos(earth_theta[0]), earth_radius*sin(earth_theta[0])); earths[j]->add_animator<vec_animator>(i-1,i, &earths[j]->location, earth_loc, new_loc); earth_loc = new_loc; new_loc = earth_loc + vec(moon_radius*cos(moon_theta[0]), moon_radius*sin(moon_theta[0])); moons[j]->add_animator<vec_animator>(i-1,i, &moons[j]->location, moon_loc, new_loc); moon_loc = new_loc; } } moon_theta[1] = fmod(moon_theta[0], 2*M_PI); moon_theta[0] = M_PI/4; // Drawing the line for the Earths auto earth_arc = std::make_shared<arc>(sun_loc, vec(earth_radius,earth_radius), vec{0,0}); earth_arc->add_animator<vec_animator>(50+gregorian_year_frames, 80+gregorian_year_frames, &earth_arc->angles, vec{earth_theta[0], earth_theta[0]}, vec{earth_theta[0], earth_theta[1]}); // Drawing the line for the Earths auto moon_arc = std::make_shared<arc>(earth_loc, vec(moon_radius,moon_radius), vec{0,0}); moon_arc->add_animator<vec_animator>(90+gregorian_year_frames, 120+gregorian_year_frames, &moon_arc->angles, vec{moon_theta[1], moon_theta[1]}, vec{moon_theta[1], moon_theta[0]}); world.add_layer(); world.add_layer(); world.add_object(sun, 1); for (int i = 0; i < 3; ++i){ world.add_object(earths[i], 1); world.add_object(moons[i], 1); } for (int i = 0; i < end_frame; ++i){ world.update(i); if (i > 50+gregorian_year_frames){ world.add_object(earth_arc, 1); } if (i > 90+gregorian_year_frames){ world.add_object(moon_arc, 1); } cam.encode_frame(world); } } int main() { camera cam(vec{1280, 720}); scene world = scene({1280, 720}, {0, 0, 0, 1}); cam.add_encoder<video_encoder>("/tmp/video.mp4", cam.size, 60); orbit_scene(cam, world, 1000, 0.1); cam.clear_encoders(); return 0; } <commit_msg>Adding 'complete' animation for synodic year<commit_after>/*------------gauss_vis.cpp----------------------------------------------------/ * * Purpose: Simple visualization script for difference scenes for computus video * 2020 * * Notes: Compilation instructions: * g++ -L/path/to/GathVL -I/path/to/GathVL -lgathvl -o gauss_vis gauss_vis.cpp `pkg-config --cflags --libs cairo libavformat libavcodec libswresample libswscale libavutil` -Wl,-rpath,/path/to/GathVL * *-----------------------------------------------------------------------------*/ #include <iostream> #include <cmath> #include <memory> #include <vector> #include "include/camera.h" #include "include/scene.h" void orbit_scene(camera& cam, scene& world, double end_frame, double timestep){ vec sun_size = {world.size.y*0.09, world.size.y*0.09}; vec earth_size = {world.size.y*0.045, world.size.y*0.045}; vec moon_size = {world.size.y*0.018, world.size.y*0.018}; color sun_clr = {1, 1, 0.5, 1}; color earth_clr = {0, 1, 1, 1}; color moon_clr = {0.5, 0.5, 0.5, 1}; double earth_radius = 200; double moon_radius = 100; vec earth_offset = vec{sqrt(earth_radius*earth_radius/2), sqrt(earth_radius*earth_radius/2)}; vec moon_offset = vec{sqrt(moon_radius*moon_radius/2), sqrt(moon_radius*moon_radius/2)}; vec sun_loc = {world.size.x/2, world.size.y/2}; vec earth_loc[3] = {sun_loc + earth_offset, vec(0,0), vec(0,0)}; vec moon_loc[3] = {earth_loc[0] + moon_offset, vec(0,0), vec(0,0)}; // Don't Judge Me! for (int i = 1; i < 3; ++i){ earth_loc[i] = earth_loc[0]; moon_loc[i] = moon_loc[0]; } auto sun = std::make_shared<ellipse>(sun_clr, sun_loc, vec{0,0}, 0, true); sun->add_animator<vec_animator>(0,20, &sun->size, vec{0,0}, sun_size*1.1); sun->add_animator<vec_animator>(20,25, &sun->size, sun_size*1.1, sun_size); std::shared_ptr<ellipse> earth; std::shared_ptr<ellipse> moon; earth = std::make_shared<ellipse>(earth_clr, earth_loc[0], vec{0,0}, 0, true); earth->add_animator<vec_animator>(10,30, &earth->size, vec{0,0}, earth_size*1.1); earth->add_animator<vec_animator>(30,35, &earth->size, earth_size*1.1, earth_size); moon = std::make_shared<ellipse>(moon_clr, moon_loc[0], vec{0,0}, 0, true); moon->add_animator<vec_animator>(20,40, &moon->size, vec{0,0}, moon_size*1.1); moon->add_animator<vec_animator>(40,45, &moon->size, moon_size*1.1, moon_size); // Creating a theta for the earth that changes with time double earth_theta[2] = {M_PI/4, 0}; double moon_theta[2] = {M_PI/4, 0}; double earth_freq = 0.1; double moon_freq = earth_freq*365*12/354; double gregorian_year_frames = 2*M_PI/earth_freq/timestep; double lunar_year_frames = gregorian_year_frames*29.53*12/365.2524; int indices = 2; for (int i = 50; i < gregorian_year_frames + 51; ++i){ //if (i > lunar_year_frames + 32){ if (i == floor(lunar_year_frames) + 51){ indices = 1; earth_theta[1] = fmod(earth_theta[0] + earth_freq*timestep, 2*M_PI); } earth_theta[0] -= earth_freq*timestep; moon_theta[0] -= (moon_freq + earth_freq)*timestep; for (int j = 0; j < indices; ++j){ vec new_loc = sun_loc + vec(earth_radius*cos(earth_theta[0]), earth_radius*sin(earth_theta[0])); earth->add_animator<vec_animator>(i-1,i, &earth->location, earth_loc[0], new_loc); earth_loc[j] = new_loc; new_loc = earth_loc[0] + vec(moon_radius*cos(moon_theta[0]), moon_radius*sin(moon_theta[0])); moon->add_animator<vec_animator>(i-1,i, &moon->location, moon_loc[0], new_loc); moon_loc[j] = new_loc; } } moon_theta[1] = fmod(moon_theta[0] + (moon_freq+earth_freq)*timestep, 2*M_PI); moon_theta[0] = M_PI/4 + (moon_freq+earth_freq)*timestep; // Drawing the line for the Earths auto earth_arc = std::make_shared<arc>(sun_loc, vec(earth_radius,earth_radius), vec{0,0}); earth_arc->add_animator<vec_animator>(50+gregorian_year_frames, 80+gregorian_year_frames, &earth_arc->angles, vec{earth_theta[0], earth_theta[0]}, vec{earth_theta[0], earth_theta[1]}); // Drawing the line for the Earths auto moon_arc = std::make_shared<arc>(earth_loc[0], vec(moon_radius,moon_radius), vec{0,0}); moon_arc->add_animator<vec_animator>(90+gregorian_year_frames, 120+gregorian_year_frames, &moon_arc->angles, vec{moon_theta[1], moon_theta[1]}, vec{moon_theta[1], moon_theta[0]}); std::shared_ptr<arc> earth_shadows[2]; std::shared_ptr<arc> moon_shadows[2]; for (int i = 0; i < 2; ++i){ earth_shadows[i] = std::make_shared<arc>(earth_loc[i+1], earth_size*0.95, vec{0,2*M_PI}); moon_shadows[i] = std::make_shared<arc>(moon_loc[i+1], moon_size*0.95, vec{0,2*M_PI}); } world.add_layer(); world.add_layer(); world.add_object(sun, 1); world.add_object(earth, 2); world.add_object(moon, 2); for (int i = 0; i < end_frame; ++i){ world.update(i); if (i == 51){ world.add_object(earth_shadows[1], 1); world.add_object(moon_shadows[1], 1); } if (i == floor(lunar_year_frames) + 51){ world.add_object(earth_shadows[0], 1); world.add_object(moon_shadows[0], 1); } if (i == 50+floor(gregorian_year_frames)){ world.add_object(earth_arc, 2); } if (i == 90+floor(gregorian_year_frames)){ world.add_object(moon_arc, 2); } cam.encode_frame(world); } } int main() { camera cam(vec{1280, 720}); scene world = scene({1280, 720}, {0, 0, 0, 1}); cam.add_encoder<video_encoder>("/tmp/video.mp4", cam.size, 60); orbit_scene(cam, world, 1000, 0.1); cam.clear_encoders(); return 0; } <|endoftext|>
<commit_before>/* * dht11.c: * Simple test program to test the wiringPi functions * DHT11 test */ #include <wiringPi.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <sys/types.h> #include <sys/xattr.h> #include <string> #include <iostream> #include <fstream> #define MAXTIMINGS 85 #define PARAM_ASSIGN_ERROR 22 int dht_buff_data[5] = { 0, 0, 0, 0, 0 }; void dht11_print(int DHTPIN, bool MACHINE_READABLE, bool SKIP, bool DEBUG, int DHVER, int dht_buff_data[5], uint8_t j, float f){ /* * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte */ if ( (j >= 40) && (dht_buff_data[4] == ( (dht_buff_data[0] + dht_buff_data[1] + dht_buff_data[2] + dht_buff_data[3]) & 0xFF) ) ) { f = dht_buff_data[2] * 9. / 5. + 32; if(MACHINE_READABLE){ printf( "%d.%d %d.%d\n", dht_buff_data[0], dht_buff_data[1], dht_buff_data[2], dht_buff_data[3], f ); }else{ printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n", dht_buff_data[0], dht_buff_data[1], dht_buff_data[2], dht_buff_data[3], f ); } }else if(!SKIP) { if(MACHINE_READABLE){ printf("Error \n"); }else{ printf("Error reading data from sensor, skipping...\n"); } } } void dht22_print(int DHTPIN, bool MACHINE_READABLE, bool SKIP, bool DEBUG, int DHVER, int dht_buff_data[5], uint8_t j, float f){ // check we read 40 bits (8bit x 5 ) + verify checksum in the last byte if ((j >= 40) && (dht_buff_data[4] == ((dht_buff_data[0] + dht_buff_data[1] + dht_buff_data[2] + dht_buff_data[3]) & 0xFF)) ) { float t, h; h = (float)dht_buff_data[0] * 256 + (float)dht_buff_data[1]; h /= 10; t = (float)(dht_buff_data[2] & 0x7F)* 256 + (float)dht_buff_data[3]; t /= 10.0; if ((dht_buff_data[2] & 0x80) != 0) t *= -1; if(MACHINE_READABLE){ printf("%.2f %% %.2f\n", h, t ); }else{ printf("Humidity = %.2f %% Temperature = %.2f *C \n", h, t ); } } else if(!SKIP) { if(MACHINE_READABLE){ printf("Error \n"); }else{ printf("Error reading data from sensor, skipping...\n"); } } } void read_dht_buff_data(int DHTPIN, bool MACHINE_READABLE, bool SKIP, bool DEBUG, int DHVER) { uint8_t laststate = HIGH; uint8_t counter = 0; uint8_t j = 0, i; float f; /* fahrenheit */ dht_buff_data[0] = dht_buff_data[1] = dht_buff_data[2] = dht_buff_data[3] = dht_buff_data[4] = 0; /* pull pin down for 18 milliseconds */ pinMode( DHTPIN, OUTPUT ); digitalWrite( DHTPIN, LOW ); delay( 18 ); /* then pull it up for 40 microseconds */ digitalWrite( DHTPIN, HIGH ); delayMicroseconds( 40 ); /* prepare to read the pin */ pinMode( DHTPIN, INPUT ); /* detect change and read data */ for ( i = 0; i < MAXTIMINGS; i++ ) { counter = 0; while ( digitalRead( DHTPIN ) == laststate ) { counter++; delayMicroseconds( 1 ); if ( counter == 255 ) { break; } } laststate = digitalRead( DHTPIN ); // Print stream of data to terminal. if (DEBUG){ printf("%d ", laststate); } if ( counter == 255 ) break; /* ignore first 3 transitions */ if ( (i >= 4) && (i % 2 == 0) ) { /* shove each bit into the storage bytes */ dht_buff_data[j / 8] <<= 1; if ( counter > 16 ) dht_buff_data[j / 8] |= 1; j++; } } // Depending the version how we print out the data. if (DHVER == 11){ dht11_print(DHTPIN, MACHINE_READABLE, SKIP, DEBUG, DHVER, dht_buff_data, j, f); }else{ dht22_print(DHTPIN, MACHINE_READABLE, SKIP, DEBUG, DHVER, dht_buff_data, j, f); } } int main( int argc, char *argv[] ) { int interval = 1000; int opt; bool skip = false; bool machineReadable = false; bool justOne = false; bool debug = false; int dataPin = 7; int version = 11; while ((opt = getopt(argc, argv, "MDJI:V:P:s")) != -1) { switch (opt) { case 'I': interval = atoi(optarg) * 1000; break; case 'M': machineReadable = true; break; case 'P': dataPin = atoi(optarg); break; case 'J': justOne = true; break; case 'D': debug = true; break; case 'V': version = atoi(optarg); break; case 's': skip = true; break; case ':': /* missing option argument */ fprintf(stderr, "%s: option '-%c' requires an argument\n", argv[0], optopt); exit(PARAM_ASSIGN_ERROR); break; case '?': default: printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" ); printf( "I number is the interval to run [Seconds].\n" ); printf( "M flag to set machine readable which is [Humidity Temperature]\n" ); printf( "P number is the data pin to use, default is 7\n" ); printf( "J is just one value pair, for scripting mainly...\n" ); printf( "D Will print everything in the pin out...\n" ); printf( "V Sensor version, default 11...\n" ); } } if ( wiringPiSetup() == -1 ) exit( 1 ); if ( justOne ){ read_dht_buff_data(dataPin, machineReadable, skip, debug, version); }else{ while ( 1 ) { read_dht_buff_data(dataPin, machineReadable, skip, debug, version); delay(interval); /* wait 1sec to refresh */ } } return(0); } <commit_msg>Removed % from print out, and removed extra spaces.<commit_after>/* * dht11.c: * Simple test program to test the wiringPi functions * DHT11 test */ #include <wiringPi.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <sys/types.h> #include <sys/xattr.h> #include <string> #include <iostream> #include <fstream> #define MAXTIMINGS 85 #define PARAM_ASSIGN_ERROR 22 int dht_buff_data[5] = { 0, 0, 0, 0, 0 }; void dht11_print(int DHTPIN, bool MACHINE_READABLE, bool SKIP, bool DEBUG, int DHVER, int dht_buff_data[5], uint8_t j, float f){ /* * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte */ if ( (j >= 40) && (dht_buff_data[4] == ( (dht_buff_data[0] + dht_buff_data[1] + dht_buff_data[2] + dht_buff_data[3]) & 0xFF) ) ) { f = dht_buff_data[2] * 9. / 5. + 32; if(MACHINE_READABLE){ printf( "%d.%d %d.%d\n", dht_buff_data[0], dht_buff_data[1], dht_buff_data[2], dht_buff_data[3], f ); }else{ printf( "Humidity = %d.%d Temperature = %d.%d *C (%.1f *F)\n", dht_buff_data[0], dht_buff_data[1], dht_buff_data[2], dht_buff_data[3], f ); } }else if(!SKIP) { if(MACHINE_READABLE){ printf("Error \n"); }else{ printf("Error reading data from sensor, skipping...\n"); } } } void dht22_print(int DHTPIN, bool MACHINE_READABLE, bool SKIP, bool DEBUG, int DHVER, int dht_buff_data[5], uint8_t j, float f){ // check we read 40 bits (8bit x 5 ) + verify checksum in the last byte if ((j >= 40) && (dht_buff_data[4] == ((dht_buff_data[0] + dht_buff_data[1] + dht_buff_data[2] + dht_buff_data[3]) & 0xFF)) ) { float t, h; h = (float)dht_buff_data[0] * 256 + (float)dht_buff_data[1]; h /= 10; t = (float)(dht_buff_data[2] & 0x7F)* 256 + (float)dht_buff_data[3]; t /= 10.0; if ((dht_buff_data[2] & 0x80) != 0) t *= -1; if(MACHINE_READABLE){ printf("%.2f %.2f\n", h, t ); }else{ printf("Humidity = %.2f Temperature = %.2f *C \n", h, t ); } } else if(!SKIP) { if(MACHINE_READABLE){ printf("Error \n"); }else{ printf("Error reading data from sensor, skipping...\n"); } } } void read_dht_buff_data(int DHTPIN, bool MACHINE_READABLE, bool SKIP, bool DEBUG, int DHVER) { uint8_t laststate = HIGH; uint8_t counter = 0; uint8_t j = 0, i; float f; /* fahrenheit */ dht_buff_data[0] = dht_buff_data[1] = dht_buff_data[2] = dht_buff_data[3] = dht_buff_data[4] = 0; /* pull pin down for 18 milliseconds */ pinMode( DHTPIN, OUTPUT ); digitalWrite( DHTPIN, LOW ); delay( 18 ); /* then pull it up for 40 microseconds */ digitalWrite( DHTPIN, HIGH ); delayMicroseconds( 40 ); /* prepare to read the pin */ pinMode( DHTPIN, INPUT ); /* detect change and read data */ for ( i = 0; i < MAXTIMINGS; i++ ) { counter = 0; while ( digitalRead( DHTPIN ) == laststate ) { counter++; delayMicroseconds( 1 ); if ( counter == 255 ) { break; } } laststate = digitalRead( DHTPIN ); // Print stream of data to terminal. if (DEBUG){ printf("%d ", laststate); } if ( counter == 255 ) break; /* ignore first 3 transitions */ if ( (i >= 4) && (i % 2 == 0) ) { /* shove each bit into the storage bytes */ dht_buff_data[j / 8] <<= 1; if ( counter > 16 ) dht_buff_data[j / 8] |= 1; j++; } } // Depending the version how we print out the data. if (DHVER == 11){ dht11_print(DHTPIN, MACHINE_READABLE, SKIP, DEBUG, DHVER, dht_buff_data, j, f); }else{ dht22_print(DHTPIN, MACHINE_READABLE, SKIP, DEBUG, DHVER, dht_buff_data, j, f); } } int main( int argc, char *argv[] ) { int interval = 1000; int opt; bool skip = false; bool machineReadable = false; bool justOne = false; bool debug = false; int dataPin = 7; int version = 11; while ((opt = getopt(argc, argv, "MDJI:V:P:s")) != -1) { switch (opt) { case 'I': interval = atoi(optarg) * 1000; break; case 'M': machineReadable = true; break; case 'P': dataPin = atoi(optarg); break; case 'J': justOne = true; break; case 'D': debug = true; break; case 'V': version = atoi(optarg); break; case 's': skip = true; break; case ':': /* missing option argument */ fprintf(stderr, "%s: option '-%c' requires an argument\n", argv[0], optopt); exit(PARAM_ASSIGN_ERROR); break; case '?': default: printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" ); printf( "I number is the interval to run [Seconds].\n" ); printf( "M flag to set machine readable which is [Humidity Temperature]\n" ); printf( "P number is the data pin to use, default is 7\n" ); printf( "J is just one value pair, for scripting mainly...\n" ); printf( "D Will print everything in the pin out...\n" ); printf( "V Sensor version, default 11...\n" ); } } if ( wiringPiSetup() == -1 ) exit( 1 ); if ( justOne ){ read_dht_buff_data(dataPin, machineReadable, skip, debug, version); }else{ while ( 1 ) { read_dht_buff_data(dataPin, machineReadable, skip, debug, version); delay(interval); /* wait 1sec to refresh */ } } return(0); } <|endoftext|>
<commit_before>/** * Capture.cpp */ #include <iomanip> #include <bites.hpp> #include "Capture.hpp" namespace wabbit { Capture::Capture( bites::Config& config, const int& duration, std::ostream* output_stream ) : m_config( config ), m_duration( duration ), m_output_stream( output_stream ), m_video_capture( stod( m_config["device"] )), m_rate_ticker({1, 5, 10}) { m_video_capture.set( 3, stod( m_config["width"] )); m_video_capture.set( 4, stod( m_config["height"] )); // Compute interval needed to observe maximum FPS limit. float max_fps = stof( m_config["max_fps"] ); max_fps = max_fps >= 0 ? max_fps : std::numeric_limits<float>::max(); float interval_seconds = 1 / max_fps; int interval_ms = interval_seconds * 1000000; m_min_interval = std::chrono::microseconds( interval_ms ); // Set the minimum read time for detecting camera disconnect. m_min_read = stof( m_config["min_read"] ); m_prev_time = std::chrono::system_clock::now(); m_end_time = m_prev_time + std::chrono::seconds( m_duration ); } Capture::Capture( const Capture& capture ) : m_config( capture.m_config ), m_duration( capture.m_duration ), m_output_stream( capture.m_output_stream ), m_video_capture( capture.m_video_capture ), m_rate_ticker( capture.m_rate_ticker ), m_prev_time( capture.m_prev_time ), m_end_time( capture.m_end_time ), m_min_interval( capture.m_min_interval ), m_min_read( capture.m_min_read ) {} std::vector <float> Capture::getFramerate () { return m_framerate.get(); } bool Capture::operator()( wabbit::ImageAndTime& image_and_time ) { if( !m_video_capture.isOpened() ){ return false; } if( m_end_time <= std::chrono::system_clock::now() and m_duration >= 0 ){ return false; } // Insert delay to observe maximum framerate limit. auto elapsed = std::chrono::system_clock::now() - m_prev_time; auto elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ); auto sleep_ms = m_min_interval - elapsed_ms; sleep_ms = sleep_ms.count() < 0 ? std::chrono::microseconds(0) : sleep_ms; usleep( sleep_ms.count()); // Take a snapshot. // The only way I could detect camera disconnect was by // thresholding the length of time to call read() method. // For some reason return value of read() is always True, // even after disconnecting the camera. m_prev_time = std::chrono::system_clock::now(); m_video_capture >> image_and_time.image; // Read the image. elapsed = std::chrono::system_clock::now() - m_prev_time; image_and_time.time = m_prev_time; elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ); if( elapsed_ms.count()/1000000. < m_min_read ) { // TODO: Write error to log instead of stdout. std::cout << "Error: Read time failed to meet threshold: " << std::endl; std::cout << std::fixed << std::setw( 10 ) << std::setprecision( 6 ) << elapsed_ms.count() / 1000000. << " (readtime) < " << m_min_read << " (threshold)" << std::endl; std::cout << "Probably disconnected camera." << std::endl; return false; } // Set the framerate. auto fps = m_rate_ticker.tick(); m_framerate.set( fps ); // Optionally print the current framerate. if( m_output_stream ){ *m_output_stream << std::fixed << std::setw( 10 ) << std::setprecision( 6 ) << elapsed_ms.count()/1000000.; for(auto ii=begin( fps ); ii!=end( fps ); ++ii){ *m_output_stream << std::fixed << std::setw( 7 ) << std::setprecision( 2 ) << *ii; } *m_output_stream << std::endl; } return true; } } // namespace wabbit. <commit_msg>Enable use of /dev/v4l path as video device.<commit_after>/** * Capture.cpp */ #include <iomanip> #include <regex> #include <stdexcept> // std::invalid_argument #include <bites.hpp> #include <boost/filesystem.hpp> #include "Capture.hpp" namespace wabbit { Capture::Capture( bites::Config& config, const int& duration, std::ostream* output_stream ) : m_config( config ), m_duration( duration ), m_output_stream( output_stream ), m_video_capture(), m_rate_ticker({1, 5, 10}) { // Attempt to open device given as integer. // If that fails, attempt to resolve the device as a path. int device = -1; try{ device = stod( m_config["device"] ); } catch( std::invalid_argument){ boost::filesystem::path path( m_config["device"] ); auto target = boost::filesystem::canonical(path).string(); std::regex exp( ".*video(\\d+)" ); std::smatch match; std::regex_search( target, match, exp ); device = stod( match[1] ); } if( m_output_stream ){ *m_output_stream << "device: " << device << std::endl; } // Setup the OpenCV VideoCapture object. m_video_capture.open( device ); m_video_capture.set( 3, stod( m_config["width"] )); m_video_capture.set( 4, stod( m_config["height"] )); // Compute interval needed to observe maximum FPS limit. float max_fps = stof( m_config["max_fps"] ); max_fps = max_fps >= 0 ? max_fps : std::numeric_limits<float>::max(); float interval_seconds = 1 / max_fps; int interval_ms = interval_seconds * 1000000; m_min_interval = std::chrono::microseconds( interval_ms ); // Set the minimum read time for detecting camera disconnect. m_min_read = stof( m_config["min_read"] ); m_prev_time = std::chrono::system_clock::now(); m_end_time = m_prev_time + std::chrono::seconds( m_duration ); } Capture::Capture( const Capture& capture ) : m_config( capture.m_config ), m_duration( capture.m_duration ), m_output_stream( capture.m_output_stream ), m_video_capture( capture.m_video_capture ), m_rate_ticker( capture.m_rate_ticker ), m_prev_time( capture.m_prev_time ), m_end_time( capture.m_end_time ), m_min_interval( capture.m_min_interval ), m_min_read( capture.m_min_read ) {} std::vector <float> Capture::getFramerate () { return m_framerate.get(); } bool Capture::operator()( wabbit::ImageAndTime& image_and_time ) { if( !m_video_capture.isOpened() ){ return false; } if( m_end_time <= std::chrono::system_clock::now() and m_duration >= 0 ){ return false; } // Insert delay to observe maximum framerate limit. auto elapsed = std::chrono::system_clock::now() - m_prev_time; auto elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ); auto sleep_ms = m_min_interval - elapsed_ms; sleep_ms = sleep_ms.count() < 0 ? std::chrono::microseconds(0) : sleep_ms; usleep( sleep_ms.count()); // Take a snapshot. // The only way I could detect camera disconnect was by // thresholding the length of time to call read() method. // For some reason return value of read() is always True, // even after disconnecting the camera. m_prev_time = std::chrono::system_clock::now(); m_video_capture >> image_and_time.image; // Read the image. elapsed = std::chrono::system_clock::now() - m_prev_time; image_and_time.time = m_prev_time; elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ); if( elapsed_ms.count()/1000000. < m_min_read ) { // TODO: Write error to log instead of stdout. std::cout << "Error: Read time failed to meet threshold: " << std::endl; std::cout << std::fixed << std::setw( 10 ) << std::setprecision( 6 ) << elapsed_ms.count() / 1000000. << " (readtime) < " << m_min_read << " (threshold)" << std::endl; std::cout << "Probably disconnected camera." << std::endl; return false; } // Set the framerate. auto fps = m_rate_ticker.tick(); m_framerate.set( fps ); // Optionally print the current framerate. if( m_output_stream ){ *m_output_stream << std::fixed << std::setw( 10 ) << std::setprecision( 6 ) << elapsed_ms.count()/1000000.; for(auto ii=begin( fps ); ii!=end( fps ); ++ii){ *m_output_stream << std::fixed << std::setw( 7 ) << std::setprecision( 2 ) << *ii; } *m_output_stream << std::endl; } return true; } } // namespace wabbit. <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, //1 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. #define OS_TERMINATE_ON_CONTRACT_VIOLATION #include <os> #include <fs/disk.hpp> std::shared_ptr<fs::Disk> disk; void list_partitions(decltype(disk)); #define MYINFO(X,...) INFO("VirtioBlk",X,##__VA_ARGS__) void Service::start() { // instantiate memdisk with FAT filesystem auto& device = hw::Dev::disk<1, VirtioBlk>(); disk = std::make_shared<fs::Disk> (device); // assert that we have a disk CHECKSERT(disk, "Disk created"); // if the disk is empty, we can't mount a filesystem CHECKSERT(not disk->empty(), "Disk is not empty"); // list extended partitions list_partitions(disk); // mount first valid partition (auto-detect and mount) disk->mount( [] (fs::error_t err) { if (err) { printf("Could not mount filesystem\n"); panic("mount() failed"); } // async ls disk->fs().ls("/", [] (fs::error_t err, auto ents) { if (err) { printf("Could not list '/' directory\n"); panic("ls() failed"); } // go through directory entries for (auto& e : *ents) { printf("%s: %s\t of size %llu bytes (CL: %llu)\n", e.type_string().c_str(), e.name().c_str(), e.size, e.block); if (e.is_file()) { printf("*** Read %s\n", e.name().c_str()); disk->fs().read(e, 0, e.size, [e] (fs::error_t err, fs::buffer_t buffer, size_t len) { if (err) { printf("Failed to read %s!\n", e.name().c_str()); panic("read() failed"); } std::string contents((const char*) buffer.get(), len); printf("[%s contents]:\n%s\nEOF\n\n", e.name().c_str(), contents.c_str()); // --- INFO("Virtioblk Test", "SUCCESS"); }); } // is_file } // ents }); // ls }); // disk->auto_detect() printf("*** TEST SERVICE STARTED *** \n"); } void list_partitions(decltype(disk) disk) { disk->partitions([] (fs::error_t err, auto& parts) { CHECKSERT (not err, "Was able to fetch partition table"); for (auto& part : parts) printf("[Partition] '%s' at LBA %u\n", part.name().c_str(), part.lba()); }); } <commit_msg>Fixed virtio_block test<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, //1 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. #define OS_TERMINATE_ON_CONTRACT_VIOLATION #include <os> #include <fs/disk.hpp> std::shared_ptr<fs::Disk> disk; void list_partitions(decltype(disk)); #define MYINFO(X,...) INFO("VirtioBlk",X,##__VA_ARGS__) void Service::start() { // instantiate memdisk with FAT filesystem auto& device = hw::Dev::disk<1, VirtioBlk>(); disk = std::make_shared<fs::Disk> (device); // assert that we have a disk CHECKSERT(disk, "Disk created"); // if the disk is empty, we can't mount a filesystem CHECKSERT(not disk->empty(), "Disk is not empty"); // list extended partitions list_partitions(disk); // mount first valid partition (auto-detect and mount) disk->mount( [] (fs::error_t err) { if (err) { printf("Could not mount filesystem\n"); panic("mount() failed"); } // async ls disk->fs().ls("/", [] (fs::error_t err, auto ents) { if (err) { printf("Could not list '/' directory\n"); panic("ls() failed"); } // go through directory entries for (auto& e : *ents) { printf("%s: %s\t of size %llu bytes (CL: %llu)\n", e.type_string().c_str(), e.name().c_str(), e.size(), e.block); if (e.is_file()) { printf("*** Read %s\n", e.name().c_str()); disk->fs().read(e, 0, e.size(), [e] (fs::error_t err, fs::buffer_t buffer, size_t len) { if (err) { printf("Failed to read %s!\n", e.name().c_str()); panic("read() failed"); } std::string contents((const char*) buffer.get(), len); printf("[%s contents]:\n%s\nEOF\n\n", e.name().c_str(), contents.c_str()); // --- INFO("Virtioblk Test", "SUCCESS"); }); } // is_file } // ents }); // ls }); // disk->auto_detect() printf("*** TEST SERVICE STARTED *** \n"); } void list_partitions(decltype(disk) disk) { disk->partitions([] (fs::error_t err, auto& parts) { CHECKSERT (not err, "Was able to fetch partition table"); for (auto& part : parts) printf("[Partition] '%s' at LBA %u\n", part.name().c_str(), part.lba()); }); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <SimpleITK.h> #include <memory> #include "ImageCompare.h" namespace sitk = itk::simple; void ImageCompare::NormalizeAndSave ( const sitk::Image &input, const std::string &filename ) { sitk::Image image = input; // Extract the center slice of our image if ( input.GetDimension() == 3 ) { std::vector<int> idx( 3, 0 ); std::vector<unsigned int> sz = input.GetSize(); // set to just the center slice idx[2] = (int)( input.GetDepth() / 2.0 ); sz[2] = 1; image = sitk::Extract( input, sz, idx ); } sitk::StatisticsImageFilter stats; stats.Execute ( image ); sitk::Image out = sitk::IntensityWindowing ( image, stats.GetMinimum(), stats.GetMaximum(), 0, 255 ); out = sitk::Cast ( out, sitk::sitkUInt8 ); sitk::WriteImage ( out, filename ); } ImageCompare::ImageCompare() { mTolerance = 0.0; mMessage = ""; } bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, std::string inTag ) { sitk::Image centerSlice( 0, 0, sitk::sitkUInt8 ); std::string testCase = inTestCase; std::string tag = inTag; std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name(); if ( testCase == "" ) { testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); } std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl; // Does the baseline exist? std::string extension = ".nrrd"; std::string OutputDir = dataFinder.GetOutputDirectory(); std::string name = testCase .append( "_" ) .append(testName); if ( tag != "" ) { name.append("_").append ( tag ); } // Extract the center slice of our image if ( image.GetDimension() == 3 ) { std::vector<int> idx( 3, 0 ); std::vector<unsigned int> sz = image.GetSize(); // set to just the center slice idx[2] = (int)( image.GetDepth() / 2.0 ); sz[2] = 1; centerSlice = sitk::RegionOfInterest( image, sz, idx ); } else { centerSlice = image; } std::string baselineFileName = dataFinder.GetSourceDirectory() + "/Testing/Data/Baseline/" + name + extension; if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) ) { // Baseline does not exist, write out what we've been given std::string newBaselineDir = OutputDir + "/Newbaseline/"; itksys::SystemTools::MakeDirectory ( newBaselineDir.c_str() ); std::cout << "Making directory " << newBaselineDir << std::endl; std::string newBaseline = newBaselineDir + name + extension; sitk::ImageFileWriter().SetFileName ( newBaseline ).Execute ( centerSlice ); mMessage = "Baseline does not exist, wrote " + newBaseline + "\ncp " + newBaseline + " " + baselineFileName; return false; } sitk::Image baseline( 0, 0, sitk::sitkUInt8 ); std::cout << "Loading baseline " << baselineFileName << std::endl; try { baseline = sitk::ImageFileReader().SetFileName ( baselineFileName ).Execute(); } catch ( std::exception& e ) { mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what(); return false; } // verify they have the same size if ( baseline.GetHeight() != centerSlice.GetHeight() || baseline.GetWidth() != centerSlice.GetWidth() || baseline.GetDepth() != centerSlice.GetDepth() ) { mMessage = "ImageCompare: Image dimensions are different"; return false; } // Get the center slices sitk::Image diffSquared( 0, 0, itk::simple::sitkUInt8 ); try { if ( baseline.GetPixelIDValue() == sitk::sitkComplexFloat32 || baseline.GetPixelIDValue() == sitk::sitkComplexFloat64 ) { sitk::Image diff = sitk::Subtract( centerSlice, baseline ); // for complex number we multiply the image by it's complex // conjugate, this will produce only a real value result sitk::Image conj = sitk::RealAndImaginaryToComplex( sitk::ComplexToReal( diff ), sitk::MultiplyByConstant( sitk::ComplexToImaginary( diff ), -1 ) ); diffSquared = sitk::ComplexToReal( sitk::Multiply( diff, conj ) ); } else if ( baseline.GetNumberOfComponentsPerPixel() > 1 ) { sitk::Image diff = sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkVectorFloat32 ), sitk::Cast( baseline, sitk::sitkVectorFloat32 ) ); // for vector image just do a sum of the components diffSquared = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, 0 ), 2 ); for ( unsigned int i = 1; i < diff.GetNumberOfComponentsPerPixel(); ++i ) { sitk::Image temp = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, i ), 2 ); diffSquared = sitk::Add( temp, diffSquared ); } diffSquared = sitk::DivideByConstant( diffSquared, diff.GetNumberOfComponentsPerPixel() ); } else { sitk::Image diff = sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkFloat32 ), sitk::Cast( baseline, sitk::sitkFloat32 ) ); diffSquared = sitk::Multiply( diff, diff ); } } catch ( std::exception& e ) { mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what(); return false; } sitk::StatisticsImageFilter stats; stats.Execute ( diffSquared ); double rms = std::sqrt ( stats.GetMean() ); if ( rms > fabs ( mTolerance ) ) { std::ostringstream msg; msg << "ImageCompare: image Root Mean Square (RMS) difference was " << rms << " which exceeds the tolerance of " << mTolerance; msg << "\n"; mMessage = msg.str(); std::cout << "<DartMeasurement name=\"RMSeDifference\" type=\"numeric/float\">" << rms << "</DartMeasurement>" << std::endl; std::cout << "<DartMeasurement name=\"Tolerance\" type=\"numeric/float\">" << mTolerance << "</DartMeasurement>" << std::endl; std::string volumeName = OutputDir + "/" + name + ".nrrd"; sitk::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice ); // Save pngs std::string ExpectedImageFilename = OutputDir + "/" + name + "_Expected.png"; std::string ActualImageFilename = OutputDir + "/" + name + "_Actual.png"; std::string DifferenceImageFilename = OutputDir + "/" + name + "_Difference.png"; NormalizeAndSave ( baseline, ExpectedImageFilename ); NormalizeAndSave ( centerSlice, ActualImageFilename ); NormalizeAndSave ( sitk::Sqrt(diffSquared), DifferenceImageFilename ); // Let ctest know about it std::cout << "<DartMeasurementFile name=\"ExpectedImage\" type=\"image/png\">"; std::cout << ExpectedImageFilename << "</DartMeasurementFile>" << std::endl; std::cout << "<DartMeasurementFile name=\"ActualImage\" type=\"image/png\">"; std::cout << ActualImageFilename << "</DartMeasurementFile>" << std::endl; std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"; std::cout << DifferenceImageFilename << "</DartMeasurementFile>" << std::endl; return false; } return true; } <commit_msg>Fix runtime error in extracting slice.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <SimpleITK.h> #include <memory> #include "ImageCompare.h" namespace sitk = itk::simple; void ImageCompare::NormalizeAndSave ( const sitk::Image &input, const std::string &filename ) { sitk::Image image = input; // Extract the center slice of our image if ( input.GetDimension() == 3 ) { std::vector<int> idx( 3, 0 ); std::vector<unsigned int> sz = input.GetSize(); // set to just the center slice idx[2] = (int)( input.GetDepth() / 2 ); sz[2] = 0; image = sitk::Extract( input, sz, idx ); } sitk::StatisticsImageFilter stats; stats.Execute ( image ); sitk::Image out = sitk::IntensityWindowing ( image, stats.GetMinimum(), stats.GetMaximum(), 0, 255 ); out = sitk::Cast ( out, sitk::sitkUInt8 ); sitk::WriteImage ( out, filename ); } ImageCompare::ImageCompare() { mTolerance = 0.0; mMessage = ""; } bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, std::string inTag ) { sitk::Image centerSlice( 0, 0, sitk::sitkUInt8 ); std::string testCase = inTestCase; std::string tag = inTag; std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name(); if ( testCase == "" ) { testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); } std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl; // Does the baseline exist? std::string extension = ".nrrd"; std::string OutputDir = dataFinder.GetOutputDirectory(); std::string name = testCase .append( "_" ) .append(testName); if ( tag != "" ) { name.append("_").append ( tag ); } // Extract the center slice of our image if ( image.GetDimension() == 3 ) { std::vector<int> idx( 3, 0 ); std::vector<unsigned int> sz = image.GetSize(); // set to just the center slice idx[2] = (int)( image.GetDepth() / 2 ); sz[2] = 1; centerSlice = sitk::RegionOfInterest( image, sz, idx ); } else { centerSlice = image; } std::string baselineFileName = dataFinder.GetSourceDirectory() + "/Testing/Data/Baseline/" + name + extension; if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) ) { // Baseline does not exist, write out what we've been given std::string newBaselineDir = OutputDir + "/Newbaseline/"; itksys::SystemTools::MakeDirectory ( newBaselineDir.c_str() ); std::cout << "Making directory " << newBaselineDir << std::endl; std::string newBaseline = newBaselineDir + name + extension; sitk::ImageFileWriter().SetFileName ( newBaseline ).Execute ( centerSlice ); mMessage = "Baseline does not exist, wrote " + newBaseline + "\ncp " + newBaseline + " " + baselineFileName; return false; } sitk::Image baseline( 0, 0, sitk::sitkUInt8 ); std::cout << "Loading baseline " << baselineFileName << std::endl; try { baseline = sitk::ImageFileReader().SetFileName ( baselineFileName ).Execute(); } catch ( std::exception& e ) { mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what(); return false; } // verify they have the same size if ( baseline.GetHeight() != centerSlice.GetHeight() || baseline.GetWidth() != centerSlice.GetWidth() || baseline.GetDepth() != centerSlice.GetDepth() ) { mMessage = "ImageCompare: Image dimensions are different"; return false; } // Get the center slices sitk::Image diffSquared( 0, 0, itk::simple::sitkUInt8 ); try { if ( baseline.GetPixelIDValue() == sitk::sitkComplexFloat32 || baseline.GetPixelIDValue() == sitk::sitkComplexFloat64 ) { sitk::Image diff = sitk::Subtract( centerSlice, baseline ); // for complex number we multiply the image by it's complex // conjugate, this will produce only a real value result sitk::Image conj = sitk::RealAndImaginaryToComplex( sitk::ComplexToReal( diff ), sitk::MultiplyByConstant( sitk::ComplexToImaginary( diff ), -1 ) ); diffSquared = sitk::ComplexToReal( sitk::Multiply( diff, conj ) ); } else if ( baseline.GetNumberOfComponentsPerPixel() > 1 ) { sitk::Image diff = sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkVectorFloat32 ), sitk::Cast( baseline, sitk::sitkVectorFloat32 ) ); // for vector image just do a sum of the components diffSquared = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, 0 ), 2 ); for ( unsigned int i = 1; i < diff.GetNumberOfComponentsPerPixel(); ++i ) { sitk::Image temp = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, i ), 2 ); diffSquared = sitk::Add( temp, diffSquared ); } diffSquared = sitk::DivideByConstant( diffSquared, diff.GetNumberOfComponentsPerPixel() ); } else { sitk::Image diff = sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkFloat32 ), sitk::Cast( baseline, sitk::sitkFloat32 ) ); diffSquared = sitk::Multiply( diff, diff ); } } catch ( std::exception& e ) { mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what(); return false; } sitk::StatisticsImageFilter stats; stats.Execute ( diffSquared ); double rms = std::sqrt ( stats.GetMean() ); if ( rms > fabs ( mTolerance ) ) { std::ostringstream msg; msg << "ImageCompare: image Root Mean Square (RMS) difference was " << rms << " which exceeds the tolerance of " << mTolerance; msg << "\n"; mMessage = msg.str(); std::cout << "<DartMeasurement name=\"RMSeDifference\" type=\"numeric/float\">" << rms << "</DartMeasurement>" << std::endl; std::cout << "<DartMeasurement name=\"Tolerance\" type=\"numeric/float\">" << mTolerance << "</DartMeasurement>" << std::endl; std::string volumeName = OutputDir + "/" + name + ".nrrd"; sitk::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice ); // Save pngs std::string ExpectedImageFilename = OutputDir + "/" + name + "_Expected.png"; std::string ActualImageFilename = OutputDir + "/" + name + "_Actual.png"; std::string DifferenceImageFilename = OutputDir + "/" + name + "_Difference.png"; try { NormalizeAndSave ( baseline, ExpectedImageFilename ); NormalizeAndSave ( centerSlice, ActualImageFilename ); NormalizeAndSave ( sitk::Sqrt(diffSquared), DifferenceImageFilename ); // Let ctest know about it std::cout << "<DartMeasurementFile name=\"ExpectedImage\" type=\"image/png\">"; std::cout << ExpectedImageFilename << "</DartMeasurementFile>" << std::endl; std::cout << "<DartMeasurementFile name=\"ActualImage\" type=\"image/png\">"; std::cout << ActualImageFilename << "</DartMeasurementFile>" << std::endl; std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"; std::cout << DifferenceImageFilename << "</DartMeasurementFile>" << std::endl; } catch( std::exception &e ) { std::cerr << "Exception encountered while trying to normalize and save images for dashboard!" << std::endl; std::cerr << e.what() << std::endl; } catch(...) { std::cerr << "Unexpected error while trying to normalize and save images for dashboard!" << std::endl; } return false; } return true; } <|endoftext|>
<commit_before>/******************************************************************************* * tests/api/operations_test.cpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/api/dia_base.hpp> #include <c7a/net/endpoint.hpp> #include <c7a/core/job_manager.hpp> #include <c7a/core/stage_builder.hpp> #include <c7a/api/dia.hpp> #include <c7a/api/reduce_node.hpp> #include <c7a/api/sum_node.hpp> #include <c7a/api/bootstrap.hpp> #include <algorithm> #include <random> #include "gtest/gtest.h" using namespace c7a::core; using namespace c7a::net; TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) { using c7a::Context; Context ctx; std::vector<std::string> self = { "127.0.0.1:1234" }; ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self)); std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(1000, 10000); size_t generate_size = distribution(generator); auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { std::cout << line << std::endl; return std::stoi(line); }, generate_size); size_t writer_size = 0; input.WriteToFileSystem("test1.out", [&writer_size](const int& item) { //file contains ints between 1 and 15 //fails if wrong integer is generated EXPECT_GE(item, 1); EXPECT_GE(16, item); writer_size++; return std::to_string(item); }); ASSERT_EQ(generate_size, writer_size); } TEST(Operations, ReadAndAllGatherElementsCorrect) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::vector<int> out_vec; integers.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_EQ(element, i++); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, MapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> double_elements = [](int in) { return (double) 2 * in; }; auto doubled = integers.Map(double_elements); std::vector<double> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FlatMapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto flatmap_double = [](int in, auto emit) { emit((double) 2 * in); emit((double) 2 * (in + 16)); }; auto doubled = integers.FlatMap(flatmap_double); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 32, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FilterResultsCorrectly) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> even = [](int in) { return (in % 2 == 0); }; auto doubled = integers.Filter(even); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 8, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_ReduceModulo2CorrectResults) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto modulo_two = [](int in) { return (in / 2); }; auto add_function = [](int in1, int in2) { return in1 + in2; }; auto reduced = integers.ReduceBy(modulo_two, add_function); std::vector<int> out_vec; std::cout << "starting" << std::endl; reduced.AllGather(&out_vec); std::cout << "testing" << std::endl; std::sort(out_vec.begin(), out_vec.end()); std::cout << "["; for (int element : out_vec) { std::cout << element << ","; } std::cout<<"]"<<std::endl; int i = 1; for (int element : out_vec) { ASSERT_EQ(element, 56 + (8 * i++)); } ASSERT_EQ((size_t) 2, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::uniform_int_distribution<int> distribution2(1000, 10000); size_t generate_size = distribution2(generator); std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) { auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { return std::stoi(line); }, generate_size); auto ones = input.Map([](int){ return 1; }); auto add_function = [](int in1, int in2) { return in1 + in2; }; ASSERT_EQ((int) generate_size, ones.Sum(add_function)); }; c7a::ExecuteThreads(workers, port_base, start_func); } /******************************************************************************/ <commit_msg>re-enable reduce test, trying to fix clang build<commit_after>/******************************************************************************* * tests/api/operations_test.cpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/api/dia_base.hpp> #include <c7a/net/endpoint.hpp> #include <c7a/core/job_manager.hpp> #include <c7a/core/stage_builder.hpp> #include <c7a/api/dia.hpp> #include <c7a/api/reduce_node.hpp> #include <c7a/api/sum_node.hpp> #include <c7a/api/bootstrap.hpp> #include <algorithm> #include <random> #include <string> #include "gtest/gtest.h" using namespace c7a::core; using namespace c7a::net; TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) { using c7a::Context; Context ctx; std::vector<std::string> self = { "127.0.0.1:1234" }; ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self)); std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(1000, 10000); size_t generate_size = distribution(generator); auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { std::cout << line << std::endl; return std::stoi(line); }, generate_size); size_t writer_size = 0; input.WriteToFileSystem("test1.out", [&writer_size](const int& item) { //file contains ints between 1 and 15 //fails if wrong integer is generated EXPECT_GE(item, 1); EXPECT_GE(16, item); writer_size++; return std::to_string(item); }); ASSERT_EQ(generate_size, writer_size); } TEST(Operations, ReadAndAllGatherElementsCorrect) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { try { return std::stoi(line); } catch (const std::invalid_argument&) { std::cout << "\"" << line << "\"" << std::endl; return 0; } }); std::vector<int> out_vec; integers.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_EQ(element, i++); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, MapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> double_elements = [](int in) { return (double) 2 * in; }; auto doubled = integers.Map(double_elements); std::vector<double> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FlatMapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto flatmap_double = [](int in, auto emit) { emit((double) 2 * in); emit((double) 2 * (in + 16)); }; auto doubled = integers.FlatMap(flatmap_double); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 32, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FilterResultsCorrectly) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> even = [](int in) { return (in % 2 == 0); }; auto doubled = integers.Filter(even); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 8, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, ReduceModulo2CorrectResults) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto modulo_two = [](int in) { return (in % 2); }; auto add_function = [](int in1, int in2) { return in1 + in2; }; auto reduced = integers.ReduceBy(modulo_two, add_function); std::vector<int> out_vec; std::cout << "starting" << std::endl; reduced.AllGather(&out_vec); std::cout << "testing" << std::endl; std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_EQ(element, 56 + (8 * i++)); } ASSERT_EQ((size_t) 2, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::uniform_int_distribution<int> distribution2(1000, 10000); size_t generate_size = distribution2(generator); std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) { auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { return std::stoi(line); }, generate_size); auto ones = input.Map([](int){ return 1; }); auto add_function = [](int in1, int in2) { return in1 + in2; }; ASSERT_EQ((int) generate_size, ones.Sum(add_function)); }; c7a::ExecuteThreads(workers, port_base, start_func); } /******************************************************************************/ <|endoftext|>
<commit_before><commit_msg>Files.app: Disable all browser tests of Files.app in slow environment.<commit_after><|endoftext|>
<commit_before>#include "SwitchingFunctionMaterial.h" template<> InputParameters validParams<SwitchingFunctionMaterial>() { InputParameters params = validParams<OrderParameterFunctionMaterial>(); params.addClassDescription("Helper material to provide h(eta) and its derivative in one of two polynomial forms.\nSIMPLE: 3*eta^2-2*eta^3\nHIGH: eta^3*(6*eta^2-15*eta+10)"); MooseEnum h_order("SIMPLE=0 HIGH", "SIMPLE"); params.addParam<MooseEnum>("h_order", h_order, "Polynomial order of the switching function h(eta)"); params.set<std::string>("function_name") = std::string("h"); return params; } SwitchingFunctionMaterial::SwitchingFunctionMaterial(const std::string & name, InputParameters parameters) : OrderParameterFunctionMaterial(name, parameters), _h_order(getParam<MooseEnum>("h_order")) { } void SwitchingFunctionMaterial::computeQpProperties() { switch (_h_order) { case 0: // SIMPLE _prop_f[_qp] = 3.0 * _eta[_qp]*_eta[_qp] - 2.0 * _eta[_qp]*_eta[_qp]*_eta[_qp]; _prop_df[_qp] = 6.0 * _eta[_qp] - 6.0 * _eta[_qp]*_eta[_qp]; _prop_d2f[_qp] = 6.0 - 12.0 * _eta[_qp]; break; case 1: // HIGH _prop_f[_qp] = _eta[_qp]*_eta[_qp]*_eta[_qp] * (6.0 * _eta[_qp]*_eta[_qp] - 15.0 * _eta[_qp] + 10.0); _prop_df[_qp] = 30.0 * _eta[_qp]*_eta[_qp] * (_eta[_qp]*_eta[_qp] - 2.0 * _eta[_qp] + 1.0); _prop_d2f[_qp] = _eta[_qp] * (120.0 * _eta[_qp]*_eta[_qp] - 180.0 * _eta[_qp] + 60.0); break; default: mooseError("Internal error"); } } <commit_msg>Limit SwitchingFunctionMaterial (#4665)<commit_after>#include "SwitchingFunctionMaterial.h" template<> InputParameters validParams<SwitchingFunctionMaterial>() { InputParameters params = validParams<OrderParameterFunctionMaterial>(); params.addClassDescription("Helper material to provide h(eta) and its derivative in one of two polynomial forms.\nSIMPLE: 3*eta^2-2*eta^3\nHIGH: eta^3*(6*eta^2-15*eta+10)"); MooseEnum h_order("SIMPLE=0 HIGH", "SIMPLE"); params.addParam<MooseEnum>("h_order", h_order, "Polynomial order of the switching function h(eta)"); params.set<std::string>("function_name") = std::string("h"); return params; } SwitchingFunctionMaterial::SwitchingFunctionMaterial(const std::string & name, InputParameters parameters) : OrderParameterFunctionMaterial(name, parameters), _h_order(getParam<MooseEnum>("h_order")) { } void SwitchingFunctionMaterial::computeQpProperties() { Real n = _eta[_qp]; n = n>1 ? 1 : (n<0 ? 0 : n); switch (_h_order) { case 0: // SIMPLE _prop_f[_qp] = 3.0 * n*n - 2.0 * n*n*n; _prop_df[_qp] = 6.0 * n - 6.0 * n*n; _prop_d2f[_qp] = 6.0 - 12.0 * n; break; case 1: // HIGH _prop_f[_qp] = n*n*n * (6.0 * n*n - 15.0 * n + 10.0); _prop_df[_qp] = 30.0 * n*n * (n*n - 2.0 * n + 1.0); _prop_d2f[_qp] = n * (120.0 * n*n - 180.0 * n + 60.0); break; default: mooseError("Internal error"); } } <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_GEO_TRAVERSAL_HPP_ #define RDB_PROTOCOL_GEO_TRAVERSAL_HPP_ #include <set> #include <vector> #include "errors.hpp" #include <boost/optional.hpp> #include "btree/keys.hpp" #include "btree/slice.hpp" #include "containers/counted.hpp" #include "geo/indexing.hpp" #include "rdb_protocol/datum.hpp" #include "rdb_protocol/protocol.hpp" namespace ql { class datum_t; class func_t; class op_t; } class profile::disabler_t; class profile::sampler_t; class geo_io_data_t { public: geo_io_data_t(intersecting_geo_read_response_t *_response, btree_slice_t *_slice) : response(_response), slice(_slice) { } private: friend class geo_intersecting_cb_t; intersecting_geo_read_response_t *const response; btree_slice_t *const slice; }; class geo_sindex_data_t { public: geo_sindex_data_t(const key_range_t &_pkey_range, const counted_t<const ql::datum_t> &_query_geometry, ql::map_wire_func_t wire_func, sindex_multi_bool_t _multi) : pkey_range(_pkey_range), query_geometry(_query_geometry), func(wire_func.compile_wire_func()), multi(_multi) { } private: friend class geo_intersecting_cb_t; const key_range_t pkey_range; const counted_t<const ql::datum_t> query_geometry; const counted_t<ql::func_t> func; const sindex_multi_bool_t multi; }; class geo_intersecting_cb_t : public geo_index_traversal_helper_t { public: geo_intersecting_cb_t( geo_io_data_t &&_io, const geo_sindex_data_t &&_sindex, ql::env_t *_env); void on_candidate( const btree_key_t *key, const void *value, buf_parent_t parent) THROWS_ONLY(interrupted_exc_t); void finish() THROWS_ONLY(interrupted_exc_t); private: const geo_io_data_t io; // How do get data in/out. const geo_sindex_data_t sindex; ql::env_t *env; // Accumulates the data ql::datum_ptr_t result_acc; // Stores the primary key of previously processed documents std::set<store_key_t> already_processed; // State for profiling. scoped_ptr_t<profile::disabler_t> disabler; scoped_ptr_t<profile::sampler_t> sampler; }; #endif // RDB_PROTOCOL_GEO_TRAVERSAL_HPP_ <commit_msg>Compilation fix<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_GEO_TRAVERSAL_HPP_ #define RDB_PROTOCOL_GEO_TRAVERSAL_HPP_ #include <set> #include <vector> #include "errors.hpp" #include <boost/optional.hpp> #include "btree/keys.hpp" #include "btree/slice.hpp" #include "containers/counted.hpp" #include "geo/indexing.hpp" #include "rdb_protocol/datum.hpp" #include "rdb_protocol/protocol.hpp" namespace ql { class datum_t; class func_t; class op_t; } namespace profile { class disabler_t; class sampler_t; } class geo_io_data_t { public: geo_io_data_t(intersecting_geo_read_response_t *_response, btree_slice_t *_slice) : response(_response), slice(_slice) { } private: friend class geo_intersecting_cb_t; intersecting_geo_read_response_t *const response; btree_slice_t *const slice; }; class geo_sindex_data_t { public: geo_sindex_data_t(const key_range_t &_pkey_range, const counted_t<const ql::datum_t> &_query_geometry, ql::map_wire_func_t wire_func, sindex_multi_bool_t _multi) : pkey_range(_pkey_range), query_geometry(_query_geometry), func(wire_func.compile_wire_func()), multi(_multi) { } private: friend class geo_intersecting_cb_t; const key_range_t pkey_range; const counted_t<const ql::datum_t> query_geometry; const counted_t<ql::func_t> func; const sindex_multi_bool_t multi; }; class geo_intersecting_cb_t : public geo_index_traversal_helper_t { public: geo_intersecting_cb_t( geo_io_data_t &&_io, const geo_sindex_data_t &&_sindex, ql::env_t *_env); void on_candidate( const btree_key_t *key, const void *value, buf_parent_t parent) THROWS_ONLY(interrupted_exc_t); void finish() THROWS_ONLY(interrupted_exc_t); private: const geo_io_data_t io; // How do get data in/out. const geo_sindex_data_t sindex; ql::env_t *env; // Accumulates the data ql::datum_ptr_t result_acc; // Stores the primary key of previously processed documents std::set<store_key_t> already_processed; // State for profiling. scoped_ptr_t<profile::disabler_t> disabler; scoped_ptr_t<profile::sampler_t> sampler; }; #endif // RDB_PROTOCOL_GEO_TRAVERSAL_HPP_ <|endoftext|>
<commit_before>#include "generatorBase/converters/stringPropertyConverter.h" using namespace generatorBase::converters; using namespace qReal; QString StringPropertyConverter::convert(QString const &data) const { QString result = data; return "\"" + result.replace("\"", "\\\"") + "\""; } <commit_msg>Fixed print text block containing line breaks generation<commit_after>#include "generatorBase/converters/stringPropertyConverter.h" using namespace generatorBase::converters; using namespace qReal; QString StringPropertyConverter::convert(QString const &data) const { QString result = data; return "\"" + result.replace("\"", "\\\"").replace("\n", "\"\\\n\t\t\"") + "\""; } <|endoftext|>
<commit_before>/* Copyright (c) 2012 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <sys/types.h> // Include something that will define __GLIBC__. // The entire file is wrapped in this #if. We do this so this .cc file can be // compiled, even on a non-newlib build. #if defined(__native_client__) && !defined(__GLIBC__) #include "nacl_io/kernel_wrap.h" #include <dirent.h> #include <errno.h> #include <irt.h> #include <sys/mman.h> #include <sys/stat.h> #include "nacl_io/kernel_intercept.h" EXTERN_C_BEGIN #define REAL(name) __nacl_irt_##name##_real #define WRAP(name) __nacl_irt_##name##_wrap #define STRUCT_NAME(group) __libnacl_irt_##group #define DECLARE_STRUCT(group) \ extern struct nacl_irt_##group STRUCT_NAME(group); #define DECLARE_STRUCT_VERSION(group, version) \ extern struct nacl_irt_##group##_##version STRUCT_NAME(group); #define MUX(group, name) STRUCT_NAME(group).name #define DECLARE(group, name) typeof(MUX(group, name)) REAL(name); #define DO_WRAP(group, name) do { \ REAL(name) = MUX(group, name); \ MUX(group, name) = (typeof(REAL(name))) WRAP(name); \ } while (0) DECLARE_STRUCT(fdio) DECLARE_STRUCT(filename) DECLARE_STRUCT_VERSION(memory, v0_2) DECLARE(fdio, close) DECLARE(fdio, dup) DECLARE(fdio, dup2) DECLARE(fdio, fstat) DECLARE(fdio, getdents) DECLARE(fdio, read) DECLARE(fdio, seek) DECLARE(fdio, write) DECLARE(filename, open) DECLARE(filename, stat) DECLARE(memory, mmap) DECLARE(memory, munmap) int access(const char* path, int amode) { return ki_access(path, amode); } int chdir(const char* path) { return ki_chdir(path); } int chmod(const char* path, mode_t mode) { return ki_chmod(path, mode); } int WRAP(close)(int fd) { return (ki_close(fd) < 0) ? errno : 0; } int WRAP(dup)(int fd, int* newfd) { *newfd = ki_dup(fd); return (*newfd < 0) ? errno : 0; } int WRAP(dup2)(int fd, int newfd) { newfd = ki_dup2(fd, newfd); return (newfd < 0) ? errno : 0; } int WRAP(fstat)(int fd, struct stat *buf) { return (ki_fstat(fd, buf) < 0) ? errno : 0; } int fsync(int fd) { return ki_fsync(fd); } char* getcwd(char* buf, size_t size) { return ki_getcwd(buf, size); } char* getwd(char* buf) { return ki_getwd(buf); } int getdents(int fd, void* buf, unsigned int count) { return ki_getdents(fd, buf, count); } int WRAP(getdents)(int fd, dirent* buf, size_t count, size_t *nread) { return (ki_getdents(fd, buf, count) < 0) ? errno : 0; } int isatty(int fd) { return ki_isatty(fd); } int link(const char* oldpath, const char* newpath) { return ki_link(oldpath, newpath); } int mkdir(const char* path, mode_t mode) { return ki_mkdir(path, mode); } int WRAP(mmap)(void** addr, size_t length, int prot, int flags, int fd, off_t offset) { if (flags & MAP_ANONYMOUS) return REAL(mmap)(addr, length, prot, flags, fd, offset); *addr = ki_mmap(*addr, length, prot, flags, fd, offset); return *addr == (void*)-1 ? errno : 0; } int mount(const char* source, const char* target, const char* filesystemtype, unsigned long mountflags, const void* data) { return ki_mount(source, target, filesystemtype, mountflags, data); } int WRAP(munmap)(void* addr, size_t length) { // Always let the real munmap run on the address range. It is not an error if // there are no mapped pages in that range. ki_munmap(addr, length); return REAL(munmap)(addr, length); } int WRAP(open)(const char* pathname, int oflag, mode_t cmode, int* newfd) { *newfd = ki_open(pathname, oflag); return (*newfd < 0) ? errno : 0; } int WRAP(read)(int fd, void *buf, size_t count, size_t *nread) { if (!ki_is_initialized()) return REAL(read)(fd, buf, count, nread); ssize_t signed_nread = ki_read(fd, buf, count); *nread = static_cast<size_t>(signed_nread); return (signed_nread < 0) ? errno : 0; } int remove(const char* path) { return ki_remove(path); } int rmdir(const char* path) { return ki_rmdir(path); } int WRAP(seek)(int fd, off_t offset, int whence, off_t* new_offset) { *new_offset = ki_lseek(fd, offset, whence); return (*new_offset < 0) ? errno : 0; } int WRAP(stat)(const char *pathname, struct stat *buf) { return (ki_stat(pathname, buf) < 0) ? errno : 0; } int symlink(const char* oldpath, const char* newpath) { return ki_symlink(oldpath, newpath); } int umount(const char* path) { return ki_umount(path); } int unlink(const char* path) { return ki_unlink(path); } int WRAP(write)(int fd, const void *buf, size_t count, size_t *nwrote) { if (!ki_is_initialized()) return REAL(write)(fd, buf, count, nwrote); ssize_t signed_nwrote = ki_write(fd, buf, count); *nwrote = static_cast<size_t>(signed_nwrote); return (signed_nwrote < 0) ? errno : 0; } // "real" functions, i.e. the unwrapped original functions. int _real_close(int fd) { return REAL(close)(fd); } int _real_fstat(int fd, struct stat *buf) { return REAL(fstat)(fd, buf); } int _real_getdents(int fd, dirent* nacl_buf, size_t nacl_count, size_t *nread) { return REAL(getdents)(fd, nacl_buf, nacl_count, nread); } int _real_lseek(int fd, off_t offset, int whence, off_t* new_offset) { return REAL(seek)(fd, offset, whence, new_offset); } int _real_mkdir(const char* pathname, mode_t mode) { return ENOSYS; } int _real_mmap(void** addr, size_t length, int prot, int flags, int fd, off_t offset) { return REAL(mmap)(addr, length, prot, flags, fd, offset); } int _real_munmap(void* addr, size_t length) { return REAL(munmap)(addr, length); } int _real_open(const char* pathname, int oflag, mode_t cmode, int* newfd) { return REAL(open)(pathname, oflag, cmode, newfd); } int _real_open_resource(const char* file, int* fd) { return ENOSYS; } int _real_read(int fd, void *buf, size_t count, size_t *nread) { return REAL(read)(fd, buf, count, nread); } int _real_rmdir(const char* pathname) { return ENOSYS; } int _real_write(int fd, const void *buf, size_t count, size_t *nwrote) { return REAL(write)(fd, buf, count, nwrote); } void kernel_wrap_init() { static bool wrapped = false; if (!wrapped) { wrapped = true; DO_WRAP(fdio, close); DO_WRAP(fdio, dup); DO_WRAP(fdio, dup2); DO_WRAP(fdio, fstat); DO_WRAP(fdio, getdents); DO_WRAP(fdio, read); DO_WRAP(fdio, seek); DO_WRAP(fdio, write); DO_WRAP(filename, open); DO_WRAP(filename, stat); DO_WRAP(memory, mmap); DO_WRAP(memory, munmap); } } EXTERN_C_END #endif // defined(__native_client__) && !defined(__GLIBC__) <commit_msg>[NaCl SDK] nacl_irt_memory renamed again, broke nacl_io build.<commit_after>/* Copyright (c) 2012 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <sys/types.h> // Include something that will define __GLIBC__. // The entire file is wrapped in this #if. We do this so this .cc file can be // compiled, even on a non-newlib build. #if defined(__native_client__) && !defined(__GLIBC__) #include "nacl_io/kernel_wrap.h" #include <dirent.h> #include <errno.h> #include <irt.h> #include <sys/mman.h> #include <sys/stat.h> #include "nacl_io/kernel_intercept.h" EXTERN_C_BEGIN #define REAL(name) __nacl_irt_##name##_real #define WRAP(name) __nacl_irt_##name##_wrap #define STRUCT_NAME(group) __libnacl_irt_##group #define DECLARE_STRUCT(group) \ extern struct nacl_irt_##group STRUCT_NAME(group); #define DECLARE_STRUCT_VERSION(group, version) \ extern struct nacl_irt_##group##_##version STRUCT_NAME(group); #define MUX(group, name) STRUCT_NAME(group).name #define DECLARE(group, name) typeof(MUX(group, name)) REAL(name); #define DO_WRAP(group, name) do { \ REAL(name) = MUX(group, name); \ MUX(group, name) = (typeof(REAL(name))) WRAP(name); \ } while (0) DECLARE_STRUCT(fdio) DECLARE_STRUCT(filename) DECLARE_STRUCT(memory) DECLARE(fdio, close) DECLARE(fdio, dup) DECLARE(fdio, dup2) DECLARE(fdio, fstat) DECLARE(fdio, getdents) DECLARE(fdio, read) DECLARE(fdio, seek) DECLARE(fdio, write) DECLARE(filename, open) DECLARE(filename, stat) DECLARE(memory, mmap) DECLARE(memory, munmap) int access(const char* path, int amode) { return ki_access(path, amode); } int chdir(const char* path) { return ki_chdir(path); } int chmod(const char* path, mode_t mode) { return ki_chmod(path, mode); } int WRAP(close)(int fd) { return (ki_close(fd) < 0) ? errno : 0; } int WRAP(dup)(int fd, int* newfd) { *newfd = ki_dup(fd); return (*newfd < 0) ? errno : 0; } int WRAP(dup2)(int fd, int newfd) { newfd = ki_dup2(fd, newfd); return (newfd < 0) ? errno : 0; } int WRAP(fstat)(int fd, struct stat *buf) { return (ki_fstat(fd, buf) < 0) ? errno : 0; } int fsync(int fd) { return ki_fsync(fd); } char* getcwd(char* buf, size_t size) { return ki_getcwd(buf, size); } char* getwd(char* buf) { return ki_getwd(buf); } int getdents(int fd, void* buf, unsigned int count) { return ki_getdents(fd, buf, count); } int WRAP(getdents)(int fd, dirent* buf, size_t count, size_t *nread) { return (ki_getdents(fd, buf, count) < 0) ? errno : 0; } int isatty(int fd) { return ki_isatty(fd); } int link(const char* oldpath, const char* newpath) { return ki_link(oldpath, newpath); } int mkdir(const char* path, mode_t mode) { return ki_mkdir(path, mode); } int WRAP(mmap)(void** addr, size_t length, int prot, int flags, int fd, off_t offset) { if (flags & MAP_ANONYMOUS) return REAL(mmap)(addr, length, prot, flags, fd, offset); *addr = ki_mmap(*addr, length, prot, flags, fd, offset); return *addr == (void*)-1 ? errno : 0; } int mount(const char* source, const char* target, const char* filesystemtype, unsigned long mountflags, const void* data) { return ki_mount(source, target, filesystemtype, mountflags, data); } int WRAP(munmap)(void* addr, size_t length) { // Always let the real munmap run on the address range. It is not an error if // there are no mapped pages in that range. ki_munmap(addr, length); return REAL(munmap)(addr, length); } int WRAP(open)(const char* pathname, int oflag, mode_t cmode, int* newfd) { *newfd = ki_open(pathname, oflag); return (*newfd < 0) ? errno : 0; } int WRAP(read)(int fd, void *buf, size_t count, size_t *nread) { if (!ki_is_initialized()) return REAL(read)(fd, buf, count, nread); ssize_t signed_nread = ki_read(fd, buf, count); *nread = static_cast<size_t>(signed_nread); return (signed_nread < 0) ? errno : 0; } int remove(const char* path) { return ki_remove(path); } int rmdir(const char* path) { return ki_rmdir(path); } int WRAP(seek)(int fd, off_t offset, int whence, off_t* new_offset) { *new_offset = ki_lseek(fd, offset, whence); return (*new_offset < 0) ? errno : 0; } int WRAP(stat)(const char *pathname, struct stat *buf) { return (ki_stat(pathname, buf) < 0) ? errno : 0; } int symlink(const char* oldpath, const char* newpath) { return ki_symlink(oldpath, newpath); } int umount(const char* path) { return ki_umount(path); } int unlink(const char* path) { return ki_unlink(path); } int WRAP(write)(int fd, const void *buf, size_t count, size_t *nwrote) { if (!ki_is_initialized()) return REAL(write)(fd, buf, count, nwrote); ssize_t signed_nwrote = ki_write(fd, buf, count); *nwrote = static_cast<size_t>(signed_nwrote); return (signed_nwrote < 0) ? errno : 0; } // "real" functions, i.e. the unwrapped original functions. int _real_close(int fd) { return REAL(close)(fd); } int _real_fstat(int fd, struct stat *buf) { return REAL(fstat)(fd, buf); } int _real_getdents(int fd, dirent* nacl_buf, size_t nacl_count, size_t *nread) { return REAL(getdents)(fd, nacl_buf, nacl_count, nread); } int _real_lseek(int fd, off_t offset, int whence, off_t* new_offset) { return REAL(seek)(fd, offset, whence, new_offset); } int _real_mkdir(const char* pathname, mode_t mode) { return ENOSYS; } int _real_mmap(void** addr, size_t length, int prot, int flags, int fd, off_t offset) { return REAL(mmap)(addr, length, prot, flags, fd, offset); } int _real_munmap(void* addr, size_t length) { return REAL(munmap)(addr, length); } int _real_open(const char* pathname, int oflag, mode_t cmode, int* newfd) { return REAL(open)(pathname, oflag, cmode, newfd); } int _real_open_resource(const char* file, int* fd) { return ENOSYS; } int _real_read(int fd, void *buf, size_t count, size_t *nread) { return REAL(read)(fd, buf, count, nread); } int _real_rmdir(const char* pathname) { return ENOSYS; } int _real_write(int fd, const void *buf, size_t count, size_t *nwrote) { return REAL(write)(fd, buf, count, nwrote); } void kernel_wrap_init() { static bool wrapped = false; if (!wrapped) { wrapped = true; DO_WRAP(fdio, close); DO_WRAP(fdio, dup); DO_WRAP(fdio, dup2); DO_WRAP(fdio, fstat); DO_WRAP(fdio, getdents); DO_WRAP(fdio, read); DO_WRAP(fdio, seek); DO_WRAP(fdio, write); DO_WRAP(filename, open); DO_WRAP(filename, stat); DO_WRAP(memory, mmap); DO_WRAP(memory, munmap); } } EXTERN_C_END #endif // defined(__native_client__) && !defined(__GLIBC__) <|endoftext|>
<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "batterywidget.h" #include "batteryimage.h" #include "batterydbusinterface.h" #include "dcpbattery.h" #include "slidercontainer.h" #include "timecontainer.h" #include <QGraphicsLinearLayout> #include <QDebug> #include <DuiButton> #include <DuiContainer> #include <DuiGridLayoutPolicy> #include <DuiLayout> #include <DuiLinearLayoutPolicy> #define DEBUG #include "../debug.h" /* TODO list: 1) what is the correct interval for updating the battery image when charging? Is there a difference between USB and normal charging? */ BatteryWidget::BatteryWidget (QGraphicsWidget *parent) : DcpWidget (parent), batteryIf (NULL), batteryImage (NULL), PSMButton (NULL), sliderContainer (NULL), standByTimeContainer (NULL), talkTimeContainer (NULL) { SYS_DEBUG ("Starting in %p", this); /* * One can assume, that when the applet is started the power save mode is * not active. This way we show a value that makes sense even if the DBus * interface to the sysuid is not usable. */ PSMButtonToggle = false; initWidget(); } BatteryWidget::~BatteryWidget () { SYS_DEBUG ("Destroying %p", this); if (batteryIf) { delete batteryIf; batteryIf = NULL; } } bool BatteryWidget::back() { return true; // back is handled by main window by default } void BatteryWidget::initWidget() { SYS_DEBUG ("Start"); // proxy for dbus interface on remote object batteryIf = new BatteryDBusInterface(); // battery image batteryImage = new BatteryImage (); // talkTimeContainer //% "Estimated talk time:" talkTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_tt"), batteryImage); // standByTimeContainer //% "Estimated stand-by time:" standByTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_st"), new DuiImageWidget ()); //"qgn_ener_standby" ^ // PSMButton PSMButton = new DuiButton(); connect (PSMButton, SIGNAL(released()), this, SLOT(PSMButtonReleased())); // sliderContainer sliderContainer = new SliderContainer(); connect (sliderContainer, SIGNAL(PSMAutoToggled(bool)), batteryIf, SLOT(setPSMAutoValue(bool))); connect (sliderContainer, SIGNAL(PSMThresholdValueChanged(QString)), batteryIf, SLOT(setPSMThresholdValue(QString))); // mainContainer DuiLayout *orientationLayout = new DuiLayout(); DuiGridLayoutPolicy *landscapeLayoutPolicy = new DuiGridLayoutPolicy(orientationLayout); landscapeLayoutPolicy->addItem(talkTimeContainer, 0, 0); landscapeLayoutPolicy->addItem(standByTimeContainer, 0, 1); landscapeLayoutPolicy->addItem(PSMButton, 1, 0, 1, 2); landscapeLayoutPolicy->addItem(sliderContainer, 2, 0, 1, 2); landscapeLayoutPolicy->setSpacing (10); orientationLayout->setLandscapePolicy(landscapeLayoutPolicy); DuiLinearLayoutPolicy *portraitLayoutPolicy = new DuiLinearLayoutPolicy(orientationLayout, Qt::Vertical); portraitLayoutPolicy->addItem(talkTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem(standByTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem(PSMButton, Qt::AlignCenter); portraitLayoutPolicy->addItem (sliderContainer, Qt::AlignLeft); portraitLayoutPolicy->setSpacing(10); orientationLayout->setPortraitPolicy(portraitLayoutPolicy); DuiContainer *mainContainer = new DuiContainer(); mainContainer->setHeaderVisible(false); mainContainer->centralWidget()->setLayout(orientationLayout); // connect the value receive signals connect (batteryIf, SIGNAL(remainingTimeValuesReceived(QStringList)), this, SLOT(remainingTimeValuesReceived(QStringList))); connect (batteryIf, SIGNAL(batteryCharging(int)), batteryImage, SLOT(startCharging(int))); connect (batteryIf, SIGNAL(batteryNotCharging()), batteryImage, SLOT(stopCharging())); connect (batteryIf, SIGNAL(batteryNotCharging()), batteryIf, SLOT(batteryBarValueRequired())); connect (batteryIf, SIGNAL(batteryBarValueReceived(int)), batteryImage, SLOT(updateBatteryLevel(int))); connect (batteryIf, SIGNAL(PSMValueReceived(bool)), this, SLOT(updatePSMButton(bool))); connect (batteryIf, SIGNAL(PSMAutoValueReceived(bool)), sliderContainer, SLOT(initPSMAutoButton(bool))); connect (batteryIf, SIGNAL(PSMAutoDisabled()), sliderContainer, SLOT(PSMAutoDisabled())); connect (batteryIf, SIGNAL(PSMThresholdValuesReceived(QStringList)), sliderContainer, SLOT(initSlider(QStringList))); connect (batteryIf, SIGNAL(PSMThresholdValuesReceived(QStringList)), batteryIf, SLOT(PSMThresholdValueRequired())); connect (batteryIf, SIGNAL(PSMThresholdValueReceived(QString)), sliderContainer, SLOT(updateSlider(QString))); // send value requests over dbus batteryIf->remainingTimeValuesRequired(); batteryIf->batteryBarValueRequired(); batteryIf->batteryChargingStateRequired(); batteryIf->PSMValueRequired(); batteryIf->PSMAutoValueRequired(); batteryIf->PSMThresholdValuesRequired(); // mainLayout QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical); mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->addItem(mainContainer); this->setLayout(mainLayout); SYS_DEBUG ("End"); } /*! * This function is called when the user clicked on the 'power save mode' button * that activates and disactivates the power saving mode. The function will call * the battery interface, but the UI will be changed only when the sysuid * reports the change. */ void BatteryWidget::PSMButtonReleased () { batteryIf->setPSMValue (!PSMButtonToggle); } void BatteryWidget::updatePSMButton ( bool toggle) { PSMButtonToggle = toggle; SYS_DEBUG ("PSMButtonToggle now is %s", PSMButtonToggle ? "on" : "off"); if (toggle) { //% "Deactivate power save now" PSMButton->setText (qtTrId ("qtn_ener_dps")); } else { //% "Activate power save now" PSMButton->setText (qtTrId ("qtn_ener_aps")); } } void BatteryWidget::remainingTimeValuesReceived(const QStringList &timeValues) { qDebug() << "BatteryWidget::remainingTimeValuesReceived(" << timeValues.at(0) << ", " << timeValues.at(1) << ")"; talkTimeContainer->updateTimeLabel(timeValues.at(0)); standByTimeContainer->updateTimeLabel(timeValues.at(1)); } void BatteryWidget::retranslateUi () { // This call will reload the translated text on PSButton updatePSMButton (PSMButtonToggle); // This call will retranslate the label (infoText) sliderContainer->retranslate (); talkTimeContainer->setText(qtTrId ("qtn_ener_tt")); standByTimeContainer->setText (qtTrId ("qtn_ener_st")); // This call will reload timelabels on timercontainers batteryIf->remainingTimeValuesRequired(); } <commit_msg>Code-reformat<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "batterywidget.h" #include "batteryimage.h" #include "batterydbusinterface.h" #include "dcpbattery.h" #include "slidercontainer.h" #include "timecontainer.h" #include <QGraphicsLinearLayout> #include <DuiButton> #include <DuiContainer> #include <DuiGridLayoutPolicy> #include <DuiLayout> #include <DuiLinearLayoutPolicy> #define DEBUG #include "../debug.h" /* TODO list: 1) what is the correct interval for updating the battery image when charging? Is there a difference between USB and normal charging? */ BatteryWidget::BatteryWidget (QGraphicsWidget *parent) : DcpWidget (parent), batteryIf (NULL), batteryImage (NULL), PSMButton (NULL), sliderContainer (NULL), standByTimeContainer (NULL), talkTimeContainer (NULL) { SYS_DEBUG ("Starting in %p", this); /* * One can assume, that when the applet is started the power save mode is * not active. This way we show a value that makes sense even if the DBus * interface to the sysuid is not usable. */ PSMButtonToggle = false; initWidget(); } BatteryWidget::~BatteryWidget () { SYS_DEBUG ("Destroying %p", this); if (batteryIf) { delete batteryIf; batteryIf = NULL; } } bool BatteryWidget::back () { return true; // back is handled by main window by default } void BatteryWidget::initWidget () { SYS_DEBUG ("Start"); // proxy for dbus interface on remote object batteryIf = new BatteryDBusInterface; // battery image batteryImage = new BatteryImage; // talkTimeContainer //% "Estimated talk time:" talkTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_tt"), batteryImage); // standByTimeContainer //% "Estimated stand-by time:" standByTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_st"), new DuiImageWidget); //"qgn_ener_standby" ^ // PSMButton PSMButton = new DuiButton ; connect (PSMButton, SIGNAL (released ()), this, SLOT (PSMButtonReleased ())); // sliderContainer sliderContainer = new SliderContainer; connect (sliderContainer, SIGNAL (PSMAutoToggled (bool)), batteryIf, SLOT (setPSMAutoValue (bool))); connect (sliderContainer, SIGNAL (PSMThresholdValueChanged (QString)), batteryIf, SLOT (setPSMThresholdValue (QString))); // mainContainer DuiLayout *orientationLayout = new DuiLayout; DuiGridLayoutPolicy *landscapeLayoutPolicy = new DuiGridLayoutPolicy (orientationLayout); landscapeLayoutPolicy->addItem (talkTimeContainer, 0, 0); landscapeLayoutPolicy->addItem (standByTimeContainer, 0, 1); landscapeLayoutPolicy->addItem (PSMButton, 1, 0, 1, 2); landscapeLayoutPolicy->addItem (sliderContainer, 2, 0, 1, 2); landscapeLayoutPolicy->setSpacing (10); orientationLayout->setLandscapePolicy (landscapeLayoutPolicy); DuiLinearLayoutPolicy *portraitLayoutPolicy = new DuiLinearLayoutPolicy (orientationLayout, Qt::Vertical); portraitLayoutPolicy->addItem (talkTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem (standByTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem (PSMButton, Qt::AlignCenter); portraitLayoutPolicy->addItem (sliderContainer, Qt::AlignLeft); portraitLayoutPolicy->setSpacing (10); orientationLayout->setPortraitPolicy (portraitLayoutPolicy); DuiContainer *mainContainer = new DuiContainer; mainContainer->setHeaderVisible (false); mainContainer->centralWidget ()->setLayout (orientationLayout); // connect the value receive signals connect (batteryIf, SIGNAL (remainingTimeValuesReceived (QStringList)), this, SLOT (remainingTimeValuesReceived (QStringList))); connect (batteryIf, SIGNAL (batteryCharging (int)), batteryImage, SLOT (startCharging (int))); connect (batteryIf, SIGNAL (batteryNotCharging ()), batteryImage, SLOT (stopCharging ())); connect (batteryIf, SIGNAL (batteryNotCharging ()), batteryIf, SLOT (batteryBarValueRequired ())); connect (batteryIf, SIGNAL (batteryBarValueReceived (int)), batteryImage, SLOT (updateBatteryLevel (int))); connect (batteryIf, SIGNAL (PSMValueReceived (bool)), this, SLOT (updatePSMButton (bool))); connect (batteryIf, SIGNAL (PSMAutoValueReceived (bool)), sliderContainer, SLOT (initPSMAutoButton (bool))); connect (batteryIf, SIGNAL (PSMAutoDisabled ()), sliderContainer, SLOT (PSMAutoDisabled ())); connect (batteryIf, SIGNAL (PSMThresholdValuesReceived (QStringList)), sliderContainer, SLOT (initSlider (QStringList))); connect (batteryIf, SIGNAL (PSMThresholdValuesReceived (QStringList)), batteryIf, SLOT (PSMThresholdValueRequired ())); connect (batteryIf, SIGNAL (PSMThresholdValueReceived (QString)), sliderContainer, SLOT (updateSlider (QString))); // send value requests over dbus batteryIf->remainingTimeValuesRequired (); batteryIf->batteryBarValueRequired (); batteryIf->batteryChargingStateRequired (); batteryIf->PSMValueRequired (); batteryIf->PSMAutoValueRequired (); batteryIf->PSMThresholdValuesRequired (); // mainLayout QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout (Qt::Vertical); mainLayout->setContentsMargins (0, 0, 0, 0); mainLayout->addItem (mainContainer); this->setLayout (mainLayout); SYS_DEBUG ("End"); } /*! * This function is called when the user clicked on the 'power save mode' button * that activates and disactivates the power saving mode. The function will call * the battery interface, but the UI will be changed only when the sysuid * reports the change. */ void BatteryWidget::PSMButtonReleased () { batteryIf->setPSMValue (!PSMButtonToggle); } void BatteryWidget::updatePSMButton ( bool toggle) { PSMButtonToggle = toggle; SYS_DEBUG ("PSMButtonToggle now is %s", PSMButtonToggle ? "on" : "off"); if (toggle) { //% "Deactivate power save now" PSMButton->setText (qtTrId ("qtn_ener_dps")); } else { //% "Activate power save now" PSMButton->setText (qtTrId ("qtn_ener_aps")); } } void BatteryWidget::remainingTimeValuesReceived(const QStringList &timeValues) { SYS_DEBUG ("timevalues = %s, %s", SYS_STR (timeValues.at (0)), SYS_STR (timeValues.at (1))); talkTimeContainer->updateTimeLabel (timeValues.at (0)); standByTimeContainer->updateTimeLabel (timeValues.at (1)); } void BatteryWidget::retranslateUi () { // This call will reload the translated text on PSButton updatePSMButton (PSMButtonToggle); // This call will retranslate the label (infoText) sliderContainer->retranslate (); talkTimeContainer->setText(qtTrId ("qtn_ener_tt")); standByTimeContainer->setText (qtTrId ("qtn_ener_st")); // This call will reload timelabels on timercontainers batteryIf->remainingTimeValuesRequired (); } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Nagoya University * 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "pacmod_interface.h" namespace pacmod { // Constructor PacmodInterface::PacmodInterface() : private_nh_("~"), control_mode_(false) { initForROS(); } // Destructor PacmodInterface::~PacmodInterface() { } void PacmodInterface::initForROS() { // ros parameter settings private_nh_.param<double>("acceleration_limit", acceleration_limit_, 3.0); private_nh_.param<double>("deceleration_limit", deceleration_limit_, 3.0); private_nh_.param<double>("max_curvature_rate", max_curvature_rate_, 0.75); // setup subscriber twist_cmd_sub_ = nh_.subscribe("twist_cmd", 10, &PacmodInterface::callbackFromTwistCmd, this); control_mode_sub_ = nh_.subscribe("/as/control_mode", 10, &PacmodInterface::callbackFromControlMode, this); speed_sub_ = nh_.subscribe("/vehicle/steering_report", 10, &PacmodInterface::callbackFromTwistCmd, this); // setup publisher steer_mode_pub_ = nh_.advertise<module_comm_msgs::SteerMode>("/as/arbitrated_steering_commands", 10); speed_mode_pub_ = nh_.advertise<module_comm_msgs::SpeedMode>("/as/arbitrated_speed_commands", 10); current_twist_pub_ = nh_.advertise<geometry_msgs::TwistStamped>("as_current_twist", 10); } void PacmodInterface::run() { ros::spin(); } void PacmodInterface::callbackFromTwistCmd(const geometry_msgs::TwistStampedConstPtr &msg) { int mode; if (control_mode_) { mode = 1; } else { mode = 0; } module_comm_msgs::SpeedMode speed_mode; speed_mode.header = msg->header; speed_mode.mode = mode; speed_mode.speed = msg->twist.linear.x; speed_mode.acceleration_limit = 3.0; speed_mode.deceleration_limit = 3.0; module_comm_msgs::SteerMode steer_mode; steer_mode.header = msg->header; steer_mode.mode = mode; double curvature = msg->twist.angular.z / msg->twist.linear.x; steer_mode.curvature = msg->twist.linear.x <= 0 ? 0 : curvature; steer_mode.max_curvature_rate = 0.75; std::cout << "mode: " << mode << std::endl; std::cout << "speed: " << speed_mode.speed << std::endl; std::cout << "steer: " << steer_mode.curvature << std::endl; speed_mode_pub_.publish(speed_mode); steer_mode_pub_.publish(steer_mode); } void PacmodInterface::callbackFromControlMode(const std_msgs::BoolConstPtr &msg) { control_mode_ = msg->data; } void PacmodInterface::callbackFromSteeringReport(const dbw_mkz_msgs::SteeringReportConstPtr &msg) { geometry_msgs::TwistStamped ts; std_msgs::Header header; header.stamp = ros::Time::now(); ts.header = header; ts.twist.linear.x = msg->speed; // [m/sec] // Can we get angular velocity? current_twist_pub_.publish(ts); } } // pacmod <commit_msg>Use correct callback function<commit_after>/* * Copyright (c) 2017, Nagoya University * 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "pacmod_interface.h" namespace pacmod { // Constructor PacmodInterface::PacmodInterface() : private_nh_("~"), control_mode_(false) { initForROS(); } // Destructor PacmodInterface::~PacmodInterface() { } void PacmodInterface::initForROS() { // ros parameter settings private_nh_.param<double>("acceleration_limit", acceleration_limit_, 3.0); private_nh_.param<double>("deceleration_limit", deceleration_limit_, 3.0); private_nh_.param<double>("max_curvature_rate", max_curvature_rate_, 0.75); // setup subscriber twist_cmd_sub_ = nh_.subscribe("twist_cmd", 10, &PacmodInterface::callbackFromTwistCmd, this); control_mode_sub_ = nh_.subscribe("/as/control_mode", 10, &PacmodInterface::callbackFromControlMode, this); speed_sub_ = nh_.subscribe("/vehicle/steering_report", 10, &PacmodInterface::callbackFromSteeringReport, this); // setup publisher steer_mode_pub_ = nh_.advertise<module_comm_msgs::SteerMode>("/as/arbitrated_steering_commands", 10); speed_mode_pub_ = nh_.advertise<module_comm_msgs::SpeedMode>("/as/arbitrated_speed_commands", 10); current_twist_pub_ = nh_.advertise<geometry_msgs::TwistStamped>("as_current_twist", 10); } void PacmodInterface::run() { ros::spin(); } void PacmodInterface::callbackFromTwistCmd(const geometry_msgs::TwistStampedConstPtr &msg) { int mode; if (control_mode_) { mode = 1; } else { mode = 0; } module_comm_msgs::SpeedMode speed_mode; speed_mode.header = msg->header; speed_mode.mode = mode; speed_mode.speed = msg->twist.linear.x; speed_mode.acceleration_limit = 3.0; speed_mode.deceleration_limit = 3.0; module_comm_msgs::SteerMode steer_mode; steer_mode.header = msg->header; steer_mode.mode = mode; double curvature = msg->twist.angular.z / msg->twist.linear.x; steer_mode.curvature = msg->twist.linear.x <= 0 ? 0 : curvature; steer_mode.max_curvature_rate = 0.75; std::cout << "mode: " << mode << std::endl; std::cout << "speed: " << speed_mode.speed << std::endl; std::cout << "steer: " << steer_mode.curvature << std::endl; speed_mode_pub_.publish(speed_mode); steer_mode_pub_.publish(steer_mode); } void PacmodInterface::callbackFromControlMode(const std_msgs::BoolConstPtr &msg) { control_mode_ = msg->data; } void PacmodInterface::callbackFromSteeringReport(const dbw_mkz_msgs::SteeringReportConstPtr &msg) { geometry_msgs::TwistStamped ts; std_msgs::Header header; header.stamp = ros::Time::now(); ts.header = header; ts.twist.linear.x = msg->speed; // [m/sec] // Can we get angular velocity? current_twist_pub_.publish(ts); } } // pacmod <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/image_transport_factory_android.h" #include "base/memory/singleton.h" #include "content/browser/gpu/browser_gpu_channel_host_factory.h" #include "content/browser/renderer_host/compositor_impl_android.h" #include "content/common/gpu/client/gl_helper.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/gpu/gpu_process_launch_causes.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/khronos/GLES2/gl2.h" #include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h" namespace content { namespace { using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl; static ImageTransportFactoryAndroid* g_factory = NULL; class DirectGLImageTransportFactory : public ImageTransportFactoryAndroid { public: DirectGLImageTransportFactory(); virtual ~DirectGLImageTransportFactory(); virtual uint32_t InsertSyncPoint() OVERRIDE { return 0; } virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE {} virtual uint32_t CreateTexture() OVERRIDE { return context_->createTexture(); } virtual void DeleteTexture(uint32_t id) OVERRIDE { context_->deleteTexture(id); } virtual void AcquireTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE {} virtual void ReleaseTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE {} virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE { return context_.get(); } virtual GLHelper* GetGLHelper() OVERRIDE { return NULL; } private: scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context_; DISALLOW_COPY_AND_ASSIGN(DirectGLImageTransportFactory); }; DirectGLImageTransportFactory::DirectGLImageTransportFactory() { WebKit::WebGraphicsContext3D::Attributes attrs; attrs.shareResources = true; attrs.noAutomaticFlushes = true; context_.reset(webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl:: CreateViewContext(attrs, NULL)); } DirectGLImageTransportFactory::~DirectGLImageTransportFactory() { } class CmdBufferImageTransportFactory : public ImageTransportFactoryAndroid { public: CmdBufferImageTransportFactory(); virtual ~CmdBufferImageTransportFactory(); virtual uint32_t InsertSyncPoint() OVERRIDE; virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE; virtual uint32_t CreateTexture() OVERRIDE; virtual void DeleteTexture(uint32_t id) OVERRIDE; virtual void AcquireTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE; virtual void ReleaseTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE; virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE { return context_.get(); } virtual GLHelper* GetGLHelper() OVERRIDE; private: scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_; scoped_ptr<GLHelper> gl_helper_; DISALLOW_COPY_AND_ASSIGN(CmdBufferImageTransportFactory); }; CmdBufferImageTransportFactory::CmdBufferImageTransportFactory() { WebKit::WebGraphicsContext3D::Attributes attrs; attrs.shareResources = true; GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance(); GURL url("chrome://gpu/ImageTransportFactoryAndroid"); base::WeakPtr<WebGraphicsContext3DSwapBuffersClient> swap_client; context_.reset(new WebGraphicsContext3DCommandBufferImpl(0, // offscreen url, factory, swap_client)); context_->InitializeWithDefaultBufferSizes( attrs, false, CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE); } CmdBufferImageTransportFactory::~CmdBufferImageTransportFactory() { } uint32_t CmdBufferImageTransportFactory::InsertSyncPoint() { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return 0; } return context_->insertSyncPoint(); } void CmdBufferImageTransportFactory::WaitSyncPoint(uint32_t sync_point) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->waitSyncPoint(sync_point); } uint32_t CmdBufferImageTransportFactory::CreateTexture() { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return false; } return context_->createTexture(); } void CmdBufferImageTransportFactory::DeleteTexture(uint32_t id) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->deleteTexture(id); } void CmdBufferImageTransportFactory::AcquireTexture( uint32 texture_id, const signed char* mailbox_name) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->bindTexture(GL_TEXTURE_2D, texture_id); context_->consumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name); context_->flush(); } void CmdBufferImageTransportFactory::ReleaseTexture( uint32 texture_id, const signed char* mailbox_name) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->bindTexture(GL_TEXTURE_2D, texture_id); context_->produceTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name); } GLHelper* CmdBufferImageTransportFactory::GetGLHelper() { if (!gl_helper_) gl_helper_.reset(new GLHelper(context_.get())); return gl_helper_.get(); } } // anonymous namespace // static ImageTransportFactoryAndroid* ImageTransportFactoryAndroid::GetInstance() { if (!g_factory) { if (CompositorImpl::UsesDirectGL()) g_factory = new DirectGLImageTransportFactory(); else g_factory = new CmdBufferImageTransportFactory(); } return g_factory; } ImageTransportFactoryAndroid::ImageTransportFactoryAndroid() { } ImageTransportFactoryAndroid::~ImageTransportFactoryAndroid() { } } // namespace content <commit_msg>gpu: Label some more contexts<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/image_transport_factory_android.h" #include "base/memory/singleton.h" #include "base/strings/stringprintf.h" #include "content/browser/gpu/browser_gpu_channel_host_factory.h" #include "content/browser/renderer_host/compositor_impl_android.h" #include "content/common/gpu/client/gl_helper.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/gpu/gpu_process_launch_causes.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/khronos/GLES2/gl2.h" #include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h" namespace content { namespace { using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl; static ImageTransportFactoryAndroid* g_factory = NULL; class DirectGLImageTransportFactory : public ImageTransportFactoryAndroid { public: DirectGLImageTransportFactory(); virtual ~DirectGLImageTransportFactory(); virtual uint32_t InsertSyncPoint() OVERRIDE { return 0; } virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE {} virtual uint32_t CreateTexture() OVERRIDE { return context_->createTexture(); } virtual void DeleteTexture(uint32_t id) OVERRIDE { context_->deleteTexture(id); } virtual void AcquireTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE {} virtual void ReleaseTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE {} virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE { return context_.get(); } virtual GLHelper* GetGLHelper() OVERRIDE { return NULL; } private: scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context_; DISALLOW_COPY_AND_ASSIGN(DirectGLImageTransportFactory); }; DirectGLImageTransportFactory::DirectGLImageTransportFactory() { WebKit::WebGraphicsContext3D::Attributes attrs; attrs.shareResources = true; attrs.noAutomaticFlushes = true; context_.reset(webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl:: CreateViewContext(attrs, NULL)); if (context_->makeContextCurrent()) context_->pushGroupMarkerEXT( base::StringPrintf("DirectGLImageTransportFactory-%p", this).c_str()); } DirectGLImageTransportFactory::~DirectGLImageTransportFactory() { } class CmdBufferImageTransportFactory : public ImageTransportFactoryAndroid { public: CmdBufferImageTransportFactory(); virtual ~CmdBufferImageTransportFactory(); virtual uint32_t InsertSyncPoint() OVERRIDE; virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE; virtual uint32_t CreateTexture() OVERRIDE; virtual void DeleteTexture(uint32_t id) OVERRIDE; virtual void AcquireTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE; virtual void ReleaseTexture( uint32 texture_id, const signed char* mailbox_name) OVERRIDE; virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE { return context_.get(); } virtual GLHelper* GetGLHelper() OVERRIDE; private: scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_; scoped_ptr<GLHelper> gl_helper_; DISALLOW_COPY_AND_ASSIGN(CmdBufferImageTransportFactory); }; CmdBufferImageTransportFactory::CmdBufferImageTransportFactory() { WebKit::WebGraphicsContext3D::Attributes attrs; attrs.shareResources = true; GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance(); GURL url("chrome://gpu/ImageTransportFactoryAndroid"); base::WeakPtr<WebGraphicsContext3DSwapBuffersClient> swap_client; context_.reset(new WebGraphicsContext3DCommandBufferImpl(0, // offscreen url, factory, swap_client)); context_->InitializeWithDefaultBufferSizes( attrs, false, CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE); if (context_->makeContextCurrent()) context_->pushGroupMarkerEXT( base::StringPrintf("CmdBufferImageTransportFactory-%p", this).c_str()); } CmdBufferImageTransportFactory::~CmdBufferImageTransportFactory() { } uint32_t CmdBufferImageTransportFactory::InsertSyncPoint() { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return 0; } return context_->insertSyncPoint(); } void CmdBufferImageTransportFactory::WaitSyncPoint(uint32_t sync_point) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->waitSyncPoint(sync_point); } uint32_t CmdBufferImageTransportFactory::CreateTexture() { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return false; } return context_->createTexture(); } void CmdBufferImageTransportFactory::DeleteTexture(uint32_t id) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->deleteTexture(id); } void CmdBufferImageTransportFactory::AcquireTexture( uint32 texture_id, const signed char* mailbox_name) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->bindTexture(GL_TEXTURE_2D, texture_id); context_->consumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name); context_->flush(); } void CmdBufferImageTransportFactory::ReleaseTexture( uint32 texture_id, const signed char* mailbox_name) { if (!context_->makeContextCurrent()) { LOG(ERROR) << "Failed to make helper context current."; return; } context_->bindTexture(GL_TEXTURE_2D, texture_id); context_->produceTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name); } GLHelper* CmdBufferImageTransportFactory::GetGLHelper() { if (!gl_helper_) gl_helper_.reset(new GLHelper(context_.get())); return gl_helper_.get(); } } // anonymous namespace // static ImageTransportFactoryAndroid* ImageTransportFactoryAndroid::GetInstance() { if (!g_factory) { if (CompositorImpl::UsesDirectGL()) g_factory = new DirectGLImageTransportFactory(); else g_factory = new CmdBufferImageTransportFactory(); } return g_factory; } ImageTransportFactoryAndroid::ImageTransportFactoryAndroid() { } ImageTransportFactoryAndroid::~ImageTransportFactoryAndroid() { } } // namespace content <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qt5rendernodeinstanceserver.h" #include <QQuickItem> #include <QQuickView> #include "servernodeinstance.h" #include "childrenchangeeventfilter.h" #include "propertyabstractcontainer.h" #include "propertybindingcontainer.h" #include "propertyvaluecontainer.h" #include "instancecontainer.h" #include "createinstancescommand.h" #include "changefileurlcommand.h" #include "clearscenecommand.h" #include "reparentinstancescommand.h" #include "changevaluescommand.h" #include "changebindingscommand.h" #include "changeidscommand.h" #include "removeinstancescommand.h" #include "nodeinstanceclientinterface.h" #include "removepropertiescommand.h" #include "valueschangedcommand.h" #include "informationchangedcommand.h" #include "pixmapchangedcommand.h" #include "commondefines.h" #include "changestatecommand.h" #include "childrenchangedcommand.h" #include "completecomponentcommand.h" #include "componentcompletedcommand.h" #include "createscenecommand.h" #include "quickitemnodeinstance.h" #include "removesharedmemorycommand.h" #include "dummycontextobject.h" #include <designersupport.h> namespace QmlDesigner { Qt5RenderNodeInstanceServer::Qt5RenderNodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) : Qt5NodeInstanceServer(nodeInstanceClient) { Internal::QuickItemNodeInstance::createEffectItem(true); } void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands() { static bool inFunction = false; if (!inFunction) { inFunction = true; DesignerSupport::polishItems(quickView()); if (quickView() && nodeInstanceClient()->bytesToWrite() < 10000) { foreach (QQuickItem *item, allItems()) { if (item) { if (hasInstanceForObject(item) && DesignerSupport::isDirty(item, DesignerSupport::ContentUpdateMask)) { m_dirtyInstanceSet.insert(instanceForObject(item)); } else if (DesignerSupport::isDirty(item, DesignerSupport::AllMask)) { ServerNodeInstance ancestorInstance = findNodeInstanceForItem(item->parentItem()); if (ancestorInstance.isValid()) m_dirtyInstanceSet.insert(ancestorInstance); } DesignerSupport::updateDirtyNode(item); } } clearChangedPropertyList(); if (!m_dirtyInstanceSet.isEmpty()) { nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(m_dirtyInstanceSet.toList())); m_dirtyInstanceSet.clear(); } resetAllItems(); slowDownRenderTimer(); nodeInstanceClient()->flush(); nodeInstanceClient()->synchronizeWithClientProcess(); } inFunction = false; } } ServerNodeInstance Qt5RenderNodeInstanceServer::findNodeInstanceForItem(QQuickItem *item) const { if (item) { if (hasInstanceForObject(item)) return instanceForObject(item); else if (item->parentItem()) return findNodeInstanceForItem(item->parentItem()); } return ServerNodeInstance(); } void Qt5RenderNodeInstanceServer::createScene(const CreateSceneCommand &command) { Qt5NodeInstanceServer::createScene(command); QList<ServerNodeInstance> instanceList; foreach (const InstanceContainer &container, command.instances()) { ServerNodeInstance instance = instanceForId(container.instanceId()); if (instance.isValid()) { instanceList.append(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } void Qt5RenderNodeInstanceServer::clearScene(const ClearSceneCommand &command) { Qt5NodeInstanceServer::clearScene(command); m_dirtyInstanceSet.clear(); } void Qt5RenderNodeInstanceServer::completeComponent(const CompleteComponentCommand &command) { Qt5NodeInstanceServer::completeComponent(command); QList<ServerNodeInstance> instanceList; foreach (qint32 instanceId, command.instances()) { ServerNodeInstance instance = instanceForId(instanceId); if (instance.isValid()) { instanceList.append(instance); m_dirtyInstanceSet.insert(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } void QmlDesigner::Qt5RenderNodeInstanceServer::removeSharedMemory(const QmlDesigner::RemoveSharedMemoryCommand &command) { if (command.typeName() == "Image") ImageContainer::removeSharedMemorys(command.keyNumbers()); } } // namespace QmlDesigner <commit_msg>QmlDesigner: Fix rendering rendering of items<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qt5rendernodeinstanceserver.h" #include <QQuickItem> #include <QQuickView> #include "servernodeinstance.h" #include "childrenchangeeventfilter.h" #include "propertyabstractcontainer.h" #include "propertybindingcontainer.h" #include "propertyvaluecontainer.h" #include "instancecontainer.h" #include "createinstancescommand.h" #include "changefileurlcommand.h" #include "clearscenecommand.h" #include "reparentinstancescommand.h" #include "changevaluescommand.h" #include "changebindingscommand.h" #include "changeidscommand.h" #include "removeinstancescommand.h" #include "nodeinstanceclientinterface.h" #include "removepropertiescommand.h" #include "valueschangedcommand.h" #include "informationchangedcommand.h" #include "pixmapchangedcommand.h" #include "commondefines.h" #include "changestatecommand.h" #include "childrenchangedcommand.h" #include "completecomponentcommand.h" #include "componentcompletedcommand.h" #include "createscenecommand.h" #include "quickitemnodeinstance.h" #include "removesharedmemorycommand.h" #include "dummycontextobject.h" #include <designersupport.h> namespace QmlDesigner { Qt5RenderNodeInstanceServer::Qt5RenderNodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) : Qt5NodeInstanceServer(nodeInstanceClient) { Internal::QuickItemNodeInstance::createEffectItem(true); } void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands() { static bool inFunction = false; if (!inFunction) { inFunction = true; DesignerSupport::polishItems(quickView()); if (quickView() && nodeInstanceClient()->bytesToWrite() < 10000) { foreach (QQuickItem *item, allItems()) { if (item) { if (hasInstanceForObject(item)) { if (DesignerSupport::isDirty(item, DesignerSupport::ContentUpdateMask)) m_dirtyInstanceSet.insert(instanceForObject(item)); } else if (DesignerSupport::isDirty(item, DesignerSupport::AllMask)) { ServerNodeInstance ancestorInstance = findNodeInstanceForItem(item->parentItem()); if (ancestorInstance.isValid()) m_dirtyInstanceSet.insert(ancestorInstance); } DesignerSupport::updateDirtyNode(item); } } clearChangedPropertyList(); if (!m_dirtyInstanceSet.isEmpty()) { nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(m_dirtyInstanceSet.toList())); m_dirtyInstanceSet.clear(); } resetAllItems(); slowDownRenderTimer(); nodeInstanceClient()->flush(); nodeInstanceClient()->synchronizeWithClientProcess(); } inFunction = false; } } ServerNodeInstance Qt5RenderNodeInstanceServer::findNodeInstanceForItem(QQuickItem *item) const { if (item) { if (hasInstanceForObject(item)) return instanceForObject(item); else if (item->parentItem()) return findNodeInstanceForItem(item->parentItem()); } return ServerNodeInstance(); } void Qt5RenderNodeInstanceServer::createScene(const CreateSceneCommand &command) { Qt5NodeInstanceServer::createScene(command); QList<ServerNodeInstance> instanceList; foreach (const InstanceContainer &container, command.instances()) { ServerNodeInstance instance = instanceForId(container.instanceId()); if (instance.isValid()) { instanceList.append(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } void Qt5RenderNodeInstanceServer::clearScene(const ClearSceneCommand &command) { Qt5NodeInstanceServer::clearScene(command); m_dirtyInstanceSet.clear(); } void Qt5RenderNodeInstanceServer::completeComponent(const CompleteComponentCommand &command) { Qt5NodeInstanceServer::completeComponent(command); QList<ServerNodeInstance> instanceList; foreach (qint32 instanceId, command.instances()) { ServerNodeInstance instance = instanceForId(instanceId); if (instance.isValid()) { instanceList.append(instance); m_dirtyInstanceSet.insert(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } void QmlDesigner::Qt5RenderNodeInstanceServer::removeSharedMemory(const QmlDesigner::RemoveSharedMemoryCommand &command) { if (command.typeName() == "Image") ImageContainer::removeSharedMemorys(command.keyNumbers()); } } // namespace QmlDesigner <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/glue/image_decoder.h" #pragma warning(push, 0) #include "ImageSourceSkia.h" #include "IntSize.h" #include "RefPtr.h" #include "SharedBuffer.h" #pragma warning(pop) #include "SkBitmap.h" namespace webkit_glue { ImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) { } ImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size) : desired_icon_size_(desired_icon_size) { } ImageDecoder::~ImageDecoder() { } SkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) { WebCore::ImageSourceSkia source; WTF::RefPtr<WebCore::SharedBuffer> buffer(new WebCore::SharedBuffer( data, static_cast<int>(size))); source.setData(buffer.get(), true, WebCore::IntSize(desired_icon_size_.width(), desired_icon_size_.height())); if (!source.isSizeAvailable()) return SkBitmap(); WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0); if (!frame0) return SkBitmap(); return *reinterpret_cast<SkBitmap*>(frame0); } } // namespace webkit_glue <commit_msg>include config.h first otherwise bad things happen<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "webkit/glue/image_decoder.h" #pragma warning(push, 0) #include "ImageSourceSkia.h" #include "IntSize.h" #include "RefPtr.h" #include "SharedBuffer.h" #pragma warning(pop) #include "SkBitmap.h" namespace webkit_glue { ImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) { } ImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size) : desired_icon_size_(desired_icon_size) { } ImageDecoder::~ImageDecoder() { } SkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) { WebCore::ImageSourceSkia source; WTF::RefPtr<WebCore::SharedBuffer> buffer(new WebCore::SharedBuffer( data, static_cast<int>(size))); source.setData(buffer.get(), true, WebCore::IntSize(desired_icon_size_.width(), desired_icon_size_.height())); if (!source.isSizeAvailable()) return SkBitmap(); WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0); if (!frame0) return SkBitmap(); return *reinterpret_cast<SkBitmap*>(frame0); } } // namespace webkit_glue <|endoftext|>
<commit_before>// // FirebaseRemoteConfig.cpp // ee_x // // Created by Zinge on 5/9/17. // // #include "ee/firebase_remote_config/internal/FirebaseRemoteConfigBridge.hpp" #include <ee/core/IMessageBridge.hpp> #include <ee/core/Task.hpp> #include <ee/core/Utils.hpp> #include <ee/core/internal/JsonUtils.hpp> #include <ee/nlohmann/json.hpp> #include "ee/firebase_remote_config/FirebaseFetchStatus.hpp" namespace ee { namespace firebase { namespace remote_config { namespace { const std::string kPrefix = "FirebaseRemoteConfigBridge"; const std::string kInitialize = kPrefix + "Initialize"; const std::string kSetSettings = kPrefix + "SetSettings"; const std::string kFetch = kPrefix + "Fetch"; const std::string kActivate = kPrefix + "Activate"; const std::string kSetDefaults = kPrefix + "SetDefaults"; const std::string kGetBool = kPrefix + "GetBool"; const std::string kGetLong = kPrefix + "GetLong"; const std::string kGetDouble = kPrefix + "GetDouble"; const std::string kGetString = kPrefix + "GetString"; } // namespace using Self = Bridge; Self::Bridge(IMessageBridge& bridge, ILogger& logger, const Destroyer& destroyer) : bridge_(bridge) , logger_(logger) , destroyer_(destroyer) {} Self::~Bridge() = default; void Self::destroy() { destroyer_(); } Task<bool> Self::initialize() { auto response = co_await bridge_.callAsync(kInitialize); co_return core::toBool(response); } Task<> Self::setSettings(std::int64_t fetchTimeOut, std::int64_t fetchInterval) { nlohmann::json request; request["fetchTimeOut"] = fetchTimeOut; request["fetchInterval"] = fetchInterval; co_await bridge_.callAsync(kSetSettings, request.dump()); } Task<FetchStatus> Self::fetch(std::int64_t fetchInterval) { nlohmann::json request; request["fetchInterval"] = fetchTimeOut; auto response = co_await bridge_.callAsync(kFetch, request.dump()); co_return static_cast<FetchStatus>(std::stoi(response)); } Task<bool> Self::activate() { auto response = co_await bridge_.callAsync(kActivate); co_return core::toBool(response); } Task<> Self::setDefaults( const std::unordered_map< std::string, std::variant<bool, std::int64_t, double, std::string>>& defaults) { nlohmann::json request; request["defaults"] = defaults; co_await bridge_.callAsync(kSetDefaults, request.dump()); } bool Self::getBool(const std::string& key) { auto response = bridge_.call(kGetBool, key); return core::toBool(response); } std::int64_t Self::getLong(const std::string& key) { auto response = bridge_.call(kGetLong, key); return std::stoll(response); } double Self::getDouble(const std::string& key) { auto response = bridge_.call(kGetDouble, key); return std::stod(response); } std::string Self::getString(const std::string& key) { auto response = bridge_.call(kGetString, key); return response; } } // namespace remote_config } // namespace firebase } // namespace ee <commit_msg>Fix typo.<commit_after>// // FirebaseRemoteConfig.cpp // ee_x // // Created by Zinge on 5/9/17. // // #include "ee/firebase_remote_config/internal/FirebaseRemoteConfigBridge.hpp" #include <ee/core/IMessageBridge.hpp> #include <ee/core/Task.hpp> #include <ee/core/Utils.hpp> #include <ee/core/internal/JsonUtils.hpp> #include <ee/nlohmann/json.hpp> #include "ee/firebase_remote_config/FirebaseFetchStatus.hpp" namespace ee { namespace firebase { namespace remote_config { namespace { const std::string kPrefix = "FirebaseRemoteConfigBridge"; const std::string kInitialize = kPrefix + "Initialize"; const std::string kSetSettings = kPrefix + "SetSettings"; const std::string kFetch = kPrefix + "Fetch"; const std::string kActivate = kPrefix + "Activate"; const std::string kSetDefaults = kPrefix + "SetDefaults"; const std::string kGetBool = kPrefix + "GetBool"; const std::string kGetLong = kPrefix + "GetLong"; const std::string kGetDouble = kPrefix + "GetDouble"; const std::string kGetString = kPrefix + "GetString"; } // namespace using Self = Bridge; Self::Bridge(IMessageBridge& bridge, ILogger& logger, const Destroyer& destroyer) : bridge_(bridge) , logger_(logger) , destroyer_(destroyer) {} Self::~Bridge() = default; void Self::destroy() { destroyer_(); } Task<bool> Self::initialize() { auto response = co_await bridge_.callAsync(kInitialize); co_return core::toBool(response); } Task<> Self::setSettings(std::int64_t fetchTimeOut, std::int64_t fetchInterval) { nlohmann::json request; request["fetchTimeOut"] = fetchTimeOut; request["fetchInterval"] = fetchInterval; co_await bridge_.callAsync(kSetSettings, request.dump()); } Task<FetchStatus> Self::fetch(std::int64_t fetchInterval) { nlohmann::json request; request["fetchInterval"] = fetchInterval; auto response = co_await bridge_.callAsync(kFetch, request.dump()); co_return static_cast<FetchStatus>(std::stoi(response)); } Task<bool> Self::activate() { auto response = co_await bridge_.callAsync(kActivate); co_return core::toBool(response); } Task<> Self::setDefaults( const std::unordered_map< std::string, std::variant<bool, std::int64_t, double, std::string>>& defaults) { nlohmann::json request; request["defaults"] = defaults; co_await bridge_.callAsync(kSetDefaults, request.dump()); } bool Self::getBool(const std::string& key) { auto response = bridge_.call(kGetBool, key); return core::toBool(response); } std::int64_t Self::getLong(const std::string& key) { auto response = bridge_.call(kGetLong, key); return std::stoll(response); } double Self::getDouble(const std::string& key) { auto response = bridge_.call(kGetDouble, key); return std::stod(response); } std::string Self::getString(const std::string& key) { auto response = bridge_.call(kGetString, key); return response; } } // namespace remote_config } // namespace firebase } // namespace ee <|endoftext|>
<commit_before>#include "Duet.hpp" #include "PrintHostSendDialog.hpp" #include <algorithm> #include <ctime> #include <boost/filesystem/path.hpp> #include <boost/format.hpp> #include <boost/log/trivial.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <wx/frame.h> #include <wx/event.h> #include <wx/progdlg.h> #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/checkbox.h> #include "libslic3r/PrintConfig.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/MsgDialog.hpp" #include "Http.hpp" namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace Slic3r { Duet::Duet(DynamicPrintConfig *config) : host(config->opt_string("print_host")), password(config->opt_string("printhost_apikey")) {} Duet::~Duet() {} bool Duet::test(wxString &msg) const { bool connected = connect(msg); if (connected) { disconnect(); } return connected; } wxString Duet::get_test_ok_msg () const { return wxString::Format("%s", _(L("Connection to Duet works correctly."))); } wxString Duet::get_test_failed_msg (wxString &msg) const { return wxString::Format("%s: %s", _(L("Could not connect to Duet")), msg); } bool Duet::send_gcode(const std::string &filename) const { enum { PROGRESS_RANGE = 1000 }; const auto errortitle = _(L("Error while uploading to the Duet")); fs::path filepath(filename); PrintHostSendDialog send_dialog(filepath.filename(), true); if (send_dialog.ShowModal() != wxID_OK) { return false; } const bool print = send_dialog.print(); const auto upload_filepath = send_dialog.filename(); const auto upload_filename = upload_filepath.filename(); const auto upload_parent_path = upload_filepath.parent_path(); wxProgressDialog progress_dialog( _(L("Duet upload")), _(L("Sending G-code file to Duet...")), PROGRESS_RANGE, nullptr, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT); progress_dialog.Pulse(); wxString connect_msg; if (!connect(connect_msg)) { auto errormsg = wxString::Format("%s: %s", errortitle, connect_msg); GUI::show_error(&progress_dialog, std::move(errormsg)); return false; } bool res = true; auto upload_cmd = get_upload_url(upload_filepath.string()); BOOST_LOG_TRIVIAL(info) << boost::format("Duet: Uploading file %1%, filename: %2%, path: %3%, print: %4%, command: %5%") % filepath.string() % upload_filename.string() % upload_parent_path.string() % print % upload_cmd; auto http = Http::post(std::move(upload_cmd)); http.set_post_body(filename) .on_complete([&](std::string body, unsigned status) { BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: File uploaded: HTTP %1%: %2%") % status % body; progress_dialog.Update(PROGRESS_RANGE); int err_code = get_err_code_from_body(body); if (err_code != 0) { auto msg = format_error(body, L("Unknown error occured"), 0); GUI::show_error(&progress_dialog, std::move(msg)); res = false; } else if (print) { wxString errormsg; res = start_print(errormsg, upload_filepath.string()); if (!res) { GUI::show_error(&progress_dialog, std::move(errormsg)); } } }) .on_error([&](std::string body, std::string error, unsigned status) { BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error uploading file: %1%, HTTP %2%, body: `%3%`") % error % status % body; auto errormsg = wxString::Format("%s: %s", errortitle, format_error(body, error, status)); GUI::show_error(&progress_dialog, std::move(errormsg)); res = false; }) .on_progress([&](Http::Progress progress, bool &cancel) { if (cancel) { // Upload was canceled res = false; } else if (progress.ultotal > 0) { int value = PROGRESS_RANGE * progress.ulnow / progress.ultotal; cancel = !progress_dialog.Update(std::min(value, PROGRESS_RANGE - 1)); // Cap the value to prevent premature dialog closing } else { cancel = !progress_dialog.Pulse(); } }) .perform_sync(); disconnect(); return res; } bool Duet::has_auto_discovery() const { return false; } bool Duet::can_test() const { return true; } bool Duet::connect(wxString &msg) const { bool res = false; auto url = get_connect_url(); auto http = Http::get(std::move(url)); http.on_error([&](std::string body, std::string error, unsigned status) { BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error connecting: %1%, HTTP %2%, body: `%3%`") % error % status % body; msg = format_error(body, error, status); }) .on_complete([&](std::string body, unsigned) { BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: Got: %1%") % body; int err_code = get_err_code_from_body(body); switch (err_code) { case 0: res = true; break; case 1: msg = format_error(body, L("Wrong password"), 0); break; case 2: msg = format_error(body, L("Could not get resources to create a new connection"), 0); break; default: msg = format_error(body, L("Unknown error occured"), 0); break; } }) .perform_sync(); return res; } void Duet::disconnect() const { auto url = (boost::format("%1%rr_disconnect") % get_base_url()).str(); auto http = Http::get(std::move(url)); http.on_error([&](std::string body, std::string error, unsigned status) { // we don't care about it, if disconnect is not working Duet will disconnect automatically after some time BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error disconnecting: %1%, HTTP %2%, body: `%3%`") % error % status % body; }) .perform_sync(); } std::string Duet::get_upload_url(const std::string &filename) const { return (boost::format("%1%rr_upload?name=0:/gcodes/%2%&%3%") % get_base_url() % filename % timestamp_str()).str(); } std::string Duet::get_connect_url() const { return (boost::format("%1%rr_connect?password=%2%&%3%") % get_base_url() % (password.empty() ? "reprap" : password) % timestamp_str()).str(); } std::string Duet::get_base_url() const { if (host.find("http://") == 0 || host.find("https://") == 0) { if (host.back() == '/') { return host; } else { return (boost::format("%1%/") % host).str(); } } else { return (boost::format("http://%1%/") % host).str(); } } std::string Duet::timestamp_str() const { enum { BUFFER_SIZE = 32 }; auto t = std::time(nullptr); auto tm = *std::localtime(&t); char buffer[BUFFER_SIZE]; std::strftime(buffer, BUFFER_SIZE, "time=%Y-%d-%mT%H:%M:%S", &tm); return std::string(buffer); } wxString Duet::format_error(const std::string &body, const std::string &error, unsigned status) { if (status != 0) { auto wxbody = wxString::FromUTF8(body.data()); return wxString::Format("HTTP %u: %s", status, wxbody); } else { return wxString::FromUTF8(error.data()); } } bool Duet::start_print(wxString &msg, const std::string &filename) const { bool res = false; auto url = (boost::format("%1%rr_gcode?gcode=M32%%20\"%2%\"") % get_base_url() % filename).str(); auto http = Http::get(std::move(url)); http.on_error([&](std::string body, std::string error, unsigned status) { BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error starting print: %1%, HTTP %2%, body: `%3%`") % error % status % body; msg = format_error(body, error, status); }) .on_complete([&](std::string body, unsigned) { BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: Got: %1%") % body; res = true; }) .perform_sync(); return res; } int Duet::get_err_code_from_body(const std::string &body) const { pt::ptree root; std::istringstream iss (body); // wrap returned json to istringstream pt::read_json(iss, root); return root.get<int>("err", 0); } } <commit_msg>fixes date for uploaded files<commit_after>#include "Duet.hpp" #include "PrintHostSendDialog.hpp" #include <algorithm> #include <ctime> #include <boost/filesystem/path.hpp> #include <boost/format.hpp> #include <boost/log/trivial.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <wx/frame.h> #include <wx/event.h> #include <wx/progdlg.h> #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/checkbox.h> #include "libslic3r/PrintConfig.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/MsgDialog.hpp" #include "Http.hpp" namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace Slic3r { Duet::Duet(DynamicPrintConfig *config) : host(config->opt_string("print_host")), password(config->opt_string("printhost_apikey")) {} Duet::~Duet() {} bool Duet::test(wxString &msg) const { bool connected = connect(msg); if (connected) { disconnect(); } return connected; } wxString Duet::get_test_ok_msg () const { return wxString::Format("%s", _(L("Connection to Duet works correctly."))); } wxString Duet::get_test_failed_msg (wxString &msg) const { return wxString::Format("%s: %s", _(L("Could not connect to Duet")), msg); } bool Duet::send_gcode(const std::string &filename) const { enum { PROGRESS_RANGE = 1000 }; const auto errortitle = _(L("Error while uploading to the Duet")); fs::path filepath(filename); PrintHostSendDialog send_dialog(filepath.filename(), true); if (send_dialog.ShowModal() != wxID_OK) { return false; } const bool print = send_dialog.print(); const auto upload_filepath = send_dialog.filename(); const auto upload_filename = upload_filepath.filename(); const auto upload_parent_path = upload_filepath.parent_path(); wxProgressDialog progress_dialog( _(L("Duet upload")), _(L("Sending G-code file to Duet...")), PROGRESS_RANGE, nullptr, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT); progress_dialog.Pulse(); wxString connect_msg; if (!connect(connect_msg)) { auto errormsg = wxString::Format("%s: %s", errortitle, connect_msg); GUI::show_error(&progress_dialog, std::move(errormsg)); return false; } bool res = true; auto upload_cmd = get_upload_url(upload_filepath.string()); BOOST_LOG_TRIVIAL(info) << boost::format("Duet: Uploading file %1%, filename: %2%, path: %3%, print: %4%, command: %5%") % filepath.string() % upload_filename.string() % upload_parent_path.string() % print % upload_cmd; auto http = Http::post(std::move(upload_cmd)); http.set_post_body(filename) .on_complete([&](std::string body, unsigned status) { BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: File uploaded: HTTP %1%: %2%") % status % body; progress_dialog.Update(PROGRESS_RANGE); int err_code = get_err_code_from_body(body); if (err_code != 0) { auto msg = format_error(body, L("Unknown error occured"), 0); GUI::show_error(&progress_dialog, std::move(msg)); res = false; } else if (print) { wxString errormsg; res = start_print(errormsg, upload_filepath.string()); if (!res) { GUI::show_error(&progress_dialog, std::move(errormsg)); } } }) .on_error([&](std::string body, std::string error, unsigned status) { BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error uploading file: %1%, HTTP %2%, body: `%3%`") % error % status % body; auto errormsg = wxString::Format("%s: %s", errortitle, format_error(body, error, status)); GUI::show_error(&progress_dialog, std::move(errormsg)); res = false; }) .on_progress([&](Http::Progress progress, bool &cancel) { if (cancel) { // Upload was canceled res = false; } else if (progress.ultotal > 0) { int value = PROGRESS_RANGE * progress.ulnow / progress.ultotal; cancel = !progress_dialog.Update(std::min(value, PROGRESS_RANGE - 1)); // Cap the value to prevent premature dialog closing } else { cancel = !progress_dialog.Pulse(); } }) .perform_sync(); disconnect(); return res; } bool Duet::has_auto_discovery() const { return false; } bool Duet::can_test() const { return true; } bool Duet::connect(wxString &msg) const { bool res = false; auto url = get_connect_url(); auto http = Http::get(std::move(url)); http.on_error([&](std::string body, std::string error, unsigned status) { BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error connecting: %1%, HTTP %2%, body: `%3%`") % error % status % body; msg = format_error(body, error, status); }) .on_complete([&](std::string body, unsigned) { BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: Got: %1%") % body; int err_code = get_err_code_from_body(body); switch (err_code) { case 0: res = true; break; case 1: msg = format_error(body, L("Wrong password"), 0); break; case 2: msg = format_error(body, L("Could not get resources to create a new connection"), 0); break; default: msg = format_error(body, L("Unknown error occured"), 0); break; } }) .perform_sync(); return res; } void Duet::disconnect() const { auto url = (boost::format("%1%rr_disconnect") % get_base_url()).str(); auto http = Http::get(std::move(url)); http.on_error([&](std::string body, std::string error, unsigned status) { // we don't care about it, if disconnect is not working Duet will disconnect automatically after some time BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error disconnecting: %1%, HTTP %2%, body: `%3%`") % error % status % body; }) .perform_sync(); } std::string Duet::get_upload_url(const std::string &filename) const { return (boost::format("%1%rr_upload?name=0:/gcodes/%2%&%3%") % get_base_url() % filename % timestamp_str()).str(); } std::string Duet::get_connect_url() const { return (boost::format("%1%rr_connect?password=%2%&%3%") % get_base_url() % (password.empty() ? "reprap" : password) % timestamp_str()).str(); } std::string Duet::get_base_url() const { if (host.find("http://") == 0 || host.find("https://") == 0) { if (host.back() == '/') { return host; } else { return (boost::format("%1%/") % host).str(); } } else { return (boost::format("http://%1%/") % host).str(); } } std::string Duet::timestamp_str() const { enum { BUFFER_SIZE = 32 }; auto t = std::time(nullptr); auto tm = *std::localtime(&t); char buffer[BUFFER_SIZE]; std::strftime(buffer, BUFFER_SIZE, "time=%Y-%m-%dT%H:%M:%S", &tm); return std::string(buffer); } wxString Duet::format_error(const std::string &body, const std::string &error, unsigned status) { if (status != 0) { auto wxbody = wxString::FromUTF8(body.data()); return wxString::Format("HTTP %u: %s", status, wxbody); } else { return wxString::FromUTF8(error.data()); } } bool Duet::start_print(wxString &msg, const std::string &filename) const { bool res = false; auto url = (boost::format("%1%rr_gcode?gcode=M32%%20\"%2%\"") % get_base_url() % filename).str(); auto http = Http::get(std::move(url)); http.on_error([&](std::string body, std::string error, unsigned status) { BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error starting print: %1%, HTTP %2%, body: `%3%`") % error % status % body; msg = format_error(body, error, status); }) .on_complete([&](std::string body, unsigned) { BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: Got: %1%") % body; res = true; }) .perform_sync(); return res; } int Duet::get_err_code_from_body(const std::string &body) const { pt::ptree root; std::istringstream iss (body); // wrap returned json to istringstream pt::read_json(iss, root); return root.get<int>("err", 0); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Date.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:26:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_UTIL_DATE_HXX_ #define _CONNECTIVITY_JAVA_UTIL_DATE_HXX_ #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif namespace connectivity { //************************************************************** //************ Class: java.util.Date //************************************************************** class java_util_Date : public java_lang_Object { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); public: static jclass getMyClass(); virtual ~java_util_Date(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_util_Date( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){} }; } #endif // _CONNECTIVITY_JAVA_UTIL_DATE_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.3.372); FILE MERGED 2008/04/01 10:53:39 thb 1.3.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:31 rt 1.3.372.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Date.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_UTIL_DATE_HXX_ #define _CONNECTIVITY_JAVA_UTIL_DATE_HXX_ #include "java/lang/Object.hxx" #include <com/sun/star/util/Date.hpp> namespace connectivity { //************************************************************** //************ Class: java.util.Date //************************************************************** class java_util_Date : public java_lang_Object { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); public: static jclass getMyClass(); virtual ~java_util_Date(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_util_Date( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){} }; } #endif // _CONNECTIVITY_JAVA_UTIL_DATE_HXX_ <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014 William T. James 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. */ #pragma once #include <cryptopp/cryptlib.h> #include <cryptopp/filters.h> #include <Python.h> #include <CXX/Objects.hxx> #include "PyArray.hxx" #include <stdexcept> #include <sstream> class PyBytesSink : public CryptoPP::Bufferless<CryptoPP::Sink> { public: PyBytesSink() : _offset(0) { _buffer = py_from_string_and_size(0,4); if (!_buffer) { throw std::runtime_error("Unable to create python array object"); } //std::cout << "Created python buffer object at: " << std::hex << (int)_buffer << " with reference count " << _buffer->ob_refcnt << std::endl; } size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking) { //std::cout << "entered PyBytesSink::Put2()" << std::endl; if (length > 0) { size_t size = py_get_size(_buffer); if (length < _offset && _offset + length > size) { reserve(2*_offset); } append(begin,length); } return 0; } void reserve(size_t n = 0) { //std::cout << "Attempting to resize buffer: " << std::hex << (int)_buffer << " to have length " << n << " bytes." << std::endl; //std::cout << "Reference count: " << _buffer->ob_refcnt << std::endl; if (py_resize(&_buffer,n)) { std::stringstream msg; msg << "Unable to resize PyBytesSink. Requested size: " << n << ", new buffer is at " << std::hex << (int)_buffer; throw std::runtime_error(msg.str()); } //std::cout << "Buffer resized to: " << std::hex << (int)_buffer << std::endl; } void append(const byte *begin,size_t n) { //std::cout << "entered PyBytesSink::append()" << std::endl; char *c_ptr; ssize_t size = py_get_size(_buffer); if (_offset + n > (size_t)size) { // resize reserve(_offset + n); } if (py_as_string_and_size(_buffer,&c_ptr,&size)) { throw std::runtime_error("AsStringAndSize failed in PyBytesSink::append."); } memcpy(c_ptr+_offset,begin,n); _offset += n; } py_array finish() { //std::cout << "Attempting to resize buffer: " << std::hex << (int)_buffer << " to have length " << _offset << " bytes." << std::endl; //std::cout << "Reference count: " << _buffer->ob_refcnt << std::endl; if (py_resize(&_buffer,_offset)) { std::stringstream msg; msg << "Unable to resize PyBytesSink. Requested size: " << _offset << ", new buffer is at " << std::hex << (int)_buffer; throw std::runtime_error(msg.str()); } //std::cout << "Buffer resized to: " << std::hex << (int)_buffer << std::endl; //std::cout << "PyBytesSink finished." << std::endl; return py_array( _buffer, true ); } private: PyObject *_buffer; size_t _offset; };<commit_msg>fixed compilation error on unix.<commit_after>/* The MIT License (MIT) Copyright (c) 2014 William T. James 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. */ #pragma once #include <cryptopp/cryptlib.h> #include <cryptopp/filters.h> #include <Python.h> #include <CXX/Objects.hxx> #include "PyArray.hxx" #include <stdexcept> #include <sstream> class PyBytesSink : public CryptoPP::Bufferless<CryptoPP::Sink> { public: PyBytesSink() : _offset(0) { _buffer = py_from_string_and_size(0,4); if (!_buffer) { throw std::runtime_error("Unable to create python array object"); } //std::cout << "Created python buffer object at: " << std::hex << (int)_buffer << " with reference count " << _buffer->ob_refcnt << std::endl; } size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking) { //std::cout << "entered PyBytesSink::Put2()" << std::endl; if (length > 0) { size_t size = py_get_size(_buffer); if (length < _offset && _offset + length > size) { reserve(2*_offset); } append(begin,length); } return 0; } void reserve(size_t n = 0) { //std::cout << "Attempting to resize buffer: " << std::hex << (int)_buffer << " to have length " << n << " bytes." << std::endl; //std::cout << "Reference count: " << _buffer->ob_refcnt << std::endl; if (py_resize(&_buffer,n)) { std::stringstream msg; msg << "Unable to resize PyBytesSink. Requested size: " << n; throw std::runtime_error(msg.str()); } //std::cout << "Buffer resized to: " << std::hex << (int)_buffer << std::endl; } void append(const byte *begin,size_t n) { //std::cout << "entered PyBytesSink::append()" << std::endl; char *c_ptr; ssize_t size = py_get_size(_buffer); if (_offset + n > (size_t)size) { // resize reserve(_offset + n); } if (py_as_string_and_size(_buffer,&c_ptr,&size)) { throw std::runtime_error("AsStringAndSize failed in PyBytesSink::append."); } memcpy(c_ptr+_offset,begin,n); _offset += n; } py_array finish() { //std::cout << "Attempting to resize buffer: " << std::hex << (int)_buffer << " to have length " << _offset << " bytes." << std::endl; //std::cout << "Reference count: " << _buffer->ob_refcnt << std::endl; if (py_resize(&_buffer,_offset)) { std::stringstream msg; msg << "Unable to resize PyBytesSink. Requested size: " << _offset; throw std::runtime_error(msg.str()); } //std::cout << "Buffer resized to: " << std::hex << (int)_buffer << std::endl; //std::cout << "PyBytesSink finished." << std::endl; return py_array( _buffer, true ); } private: PyObject *_buffer; size_t _offset; };<|endoftext|>
<commit_before>// The object hash map. // (C) 2013 Cybozu. #ifndef CYBOZU_HASH_MAP_HPP #define CYBOZU_HASH_MAP_HPP #include "MurmurHash3.h" #include <algorithm> #include <cstring> #include <memory> #include <mutex> #include <string> #include <type_traits> #include <utility> #include <vector> namespace cybozu { // Key class for <hash_map>. class hash_key final { public: // Construct from a statically allocated memory. // @p Pointer to a statically allocated memory. // @len Length of the key. // // Construct from a statically allocated memory. // // As long as the constructed object lives, the memory pointed by `p` // must not be freed. hash_key(const char* p, std::size_t len) noexcept: m_p(p), m_len(len) { MurmurHash3_x86_32(m_p, (int)m_len, 0, &m_hash); } // Construct by moving a <std::vector>. // // Construct by moving a <std::vector>. Sample usage: // ``` // hash_key( std::vector<char>(p, p+len) ) // ``` hash_key(std::vector<char> v): m_v(std::move(v)), m_p(m_v.data()), m_len(m_v.size()) { MurmurHash3_x86_32(m_p, (int)m_len, 0, &m_hash); } // Copy constructor. hash_key(const hash_key& rhs): m_v(rhs.m_p, rhs.m_p+rhs.m_len), m_p(m_v.data()), m_len(m_v.size()), m_hash(rhs.m_hash) {} hash_key& operator=(const hash_key& rhs) = delete; // Move contructor and assign operator. hash_key(hash_key&& rhs) noexcept = default; hash_key& operator=(hash_key&& rhs) = default; std::uint32_t hash() const noexcept { return m_hash; } const char* data() const noexcept { return m_p; } std::size_t length() const noexcept { return m_len; } std::string str() const { return std::string(m_p, m_len); } private: std::vector<char> m_v; const char* m_p; std::size_t m_len; std::uint32_t m_hash; friend bool operator==(const hash_key&, const hash_key&) noexcept; }; inline bool operator==(const hash_key& lhs, const hash_key& rhs) noexcept { if( lhs.m_len != rhs.m_len ) return false; if( lhs.m_p == rhs.m_p ) return true; return std::memcmp(lhs.m_p, rhs.m_p, lhs.m_len) == 0; } // Return the nearest prime number. unsigned int nearest_prime(unsigned int n) noexcept; // Highly concurrent object hash map. // // Keys for this hash map are <hash_key> whereas objects are of type `T`. // `T` must be either move-constructible or copyable. // // Each bucket in the hash map has its unique mutex to guard itself. // This design reduces contensions between threads drastically in exchange // for some functions such as dynamic resizing of the number of buckets. template<typename T> class hash_map { static_assert( std::is_move_constructible<T>::value || std::is_copy_constructible<T>::value, "T must be move- or copy- constructible." ); public: typedef std::function<bool(const hash_key&, T&)> handler; typedef std::function<T(const hash_key&)> creator; // Hash map bucket. // // Each hash value corresponds to a bucket. // Member functions whose names end with `_nolock` are not thread-safe. class bucket { struct item { const hash_key key; T object; item* next; // perfect forwarding template<typename X> item(const hash_key& k, X&& o, item* n): key(k), object(std::forward<X>(o)), next(n) {} }; public: bucket(): m_objects(nullptr) {} // Handle or insert an object. // @key The object's key. // @h A function to handle an existing object. // @c A function to create a new object. // // This function can be used to handle an existing object, or // to insert a new object when such an object does not exist. // // If `h` is not `nullptr` and there is no existing object for // `key`, `false` is returned. If `c` is not `nullptr` and an // object for `key` exists, `false` is returned. // // `h` can return `false` if it failed to handle the object. // Otherwise, `h` should return `true`. // // @return `true` if succeeded, `false` otherwise. bool apply_nolock(const hash_key& key, const handler& h, const creator& c) { for( item* p = m_objects; p != nullptr; p = p->next ) { if( p->key == key ) { if( ! h ) return false; return h(p->key, p->object); } } if( ! c ) return false; m_objects = new item(key, c(key), m_objects); return true; } // Thread-safe <apply_nolock>. bool apply(const hash_key& key, const handler& h, const creator& c) { lock_guard g(m_lock); return apply_nolock(key, h, c); } // Remove an object for `key`. // @key The object's key. // @callback A function called when an object is removed. // // This removes an object associated with `key`. If there is no // object associated with `key`, return `false`. If `callback` // is not `nullptr`, it is called when an object is removed. // // @return `true` if successfully removed, `false` otherwise. bool remove_nolock(const hash_key& key, const std::function<void(const hash_key&)>& callback) { for( item** p = &m_objects; *p != nullptr; p = &((*p)->next) ) { if( (*p)->key == key ) { item* to_delete = *p; *p = to_delete->next; delete to_delete; if( callback ) callback(key); return true; } } return false; } // Thread-safe <remove_nolock>. bool remove(const hash_key& key, const std::function<void(const hash_key&)>& callback) { lock_guard g(m_lock); return remove_nolock(key, callback); } // Remove an object for `key` if `pred` returns `true`. // @key The object's key. // @pred A predicate function. // // This function removes an object assiciated with `key` if a // predicate function returns `true`. This function is thread-safe. // // @return `true` if object existed, `false` otherwise. bool remove_if(const hash_key& key, const std::function<bool(const hash_key&, T&)>& pred) { lock_guard g(m_lock); for( item** p = &m_objects; *p != nullptr; p = &((*p)->next) ) { item* to_delete = *p; if( to_delete->key == key ) { if( pred(key, to_delete->object) ) { *p = to_delete->next; delete to_delete; } return true; } } return false; } // Collect garbage objects. // @pred Predicate function. // // This function collects garbage objects. // Objects for which `pred` returns `true` will be removed. void gc(const std::function<bool(const hash_key&, T&)>& pred) { lock_guard g(m_lock); for( item** p = &m_objects; *p != nullptr; ) { item* to_delete = *p; if( pred(to_delete->key, to_delete->object) ) { *p = to_delete->next; delete to_delete; } else { p = &(to_delete->next); } } } // Clear objects in this bucket. void clear_nolock() { while( m_objects ) { item* next = m_objects->next; delete m_objects; m_objects = next; } } private: using lock_guard = std::lock_guard<std::mutex>; alignas(CACHELINE_SIZE) mutable std::mutex m_lock; item* m_objects; }; hash_map(unsigned int buckets): m_size(nearest_prime(buckets)), m_buckets(m_size) {} // Handle or insert an object. // @key The object's key. // @h A function to handle an existing object. // @c A function to create a new object. // // This function can be used to handle an existing object, or // to insert a new object when such an object does not exist. // // If `h` is not `nullptr` and there is no existing object for // `key`, `false` is returned. If `c` is not `nullptr` and an // object for `key` exists, `false` is returned. // // `h` can return `false` if it failed to handle the object. // Otherwise, `h` should return `true`. // // @return `true` if succeeded, `false` otherwise. bool apply_nolock(const hash_key& key, const handler& h, const creator& c) { return get_bucket(key).apply_nolock(key, h, c); } // Thread-safe <apply_nolock>. bool apply(const hash_key& key, const handler& h, const creator& c) { return get_bucket(key).apply(key, h, c); } // Remove an object for `key`. // @key The object's key. // @callback A function called when an object is removed. // // This removes an object associated with `key`. If there is no // object associated with `key`, return `false`. If `callback` // is not `nullptr`, it is called when an object is removed. // // @return `true` if successfully removed, `false` otherwise. bool remove_nolock(const hash_key& key, const std::function<void(const hash_key&)>& callback) { return get_bucket(key).remove_nolock(key, callback); } // Thread-safe <remove_nolock>. bool remove(const hash_key& key, const std::function<void(const hash_key&)>& callback) { return get_bucket(key).remove(key, callback); } // Remove an object for `key` if `pred` returns `true`. // @key The object's key. // @pred A predicate function. // // This function removes an object assiciated with `key` if a // predicate function returns `true`. This function is thread-safe. // // @return `true` if object existed, `false` otherwise. bool remove_if(const hash_key& key, const std::function<bool(const hash_key&, T&)>& pred) { return get_bucket(key).remove_if(key, pred); } /* Bucket interfaces */ // Return the number of buckets in this hash map. std::size_t bucket_count() const noexcept { return m_size; } bucket& get_bucket(const hash_key& key) noexcept { return m_buckets[key.hash() % m_size]; } // <bucket> iterator. using iterator = typename std::vector<bucket>::iterator; iterator begin() { return m_buckets.begin(); } iterator end() { return m_buckets.end(); } private: const std::size_t m_size; std::vector<bucket> m_buckets; }; } // namespace cybozu #endif // CYBOZU_HASH_MAP_HPP <commit_msg>Delete objects in hash_map at dtor.<commit_after>// The object hash map. // (C) 2013 Cybozu. #ifndef CYBOZU_HASH_MAP_HPP #define CYBOZU_HASH_MAP_HPP #include "MurmurHash3.h" #include <algorithm> #include <cstring> #include <memory> #include <mutex> #include <string> #include <type_traits> #include <utility> #include <vector> namespace cybozu { // Key class for <hash_map>. class hash_key final { public: // Construct from a statically allocated memory. // @p Pointer to a statically allocated memory. // @len Length of the key. // // Construct from a statically allocated memory. // // As long as the constructed object lives, the memory pointed by `p` // must not be freed. hash_key(const char* p, std::size_t len) noexcept: m_p(p), m_len(len) { MurmurHash3_x86_32(m_p, (int)m_len, 0, &m_hash); } // Construct by moving a <std::vector>. // // Construct by moving a <std::vector>. Sample usage: // ``` // hash_key( std::vector<char>(p, p+len) ) // ``` hash_key(std::vector<char> v): m_v(std::move(v)), m_p(m_v.data()), m_len(m_v.size()) { MurmurHash3_x86_32(m_p, (int)m_len, 0, &m_hash); } // Copy constructor. hash_key(const hash_key& rhs): m_v(rhs.m_p, rhs.m_p+rhs.m_len), m_p(m_v.data()), m_len(m_v.size()), m_hash(rhs.m_hash) {} hash_key& operator=(const hash_key& rhs) = delete; // Move contructor and assign operator. hash_key(hash_key&& rhs) noexcept = default; hash_key& operator=(hash_key&& rhs) = default; std::uint32_t hash() const noexcept { return m_hash; } const char* data() const noexcept { return m_p; } std::size_t length() const noexcept { return m_len; } std::string str() const { return std::string(m_p, m_len); } private: std::vector<char> m_v; const char* m_p; std::size_t m_len; std::uint32_t m_hash; friend bool operator==(const hash_key&, const hash_key&) noexcept; }; inline bool operator==(const hash_key& lhs, const hash_key& rhs) noexcept { if( lhs.m_len != rhs.m_len ) return false; if( lhs.m_p == rhs.m_p ) return true; return std::memcmp(lhs.m_p, rhs.m_p, lhs.m_len) == 0; } // Return the nearest prime number. unsigned int nearest_prime(unsigned int n) noexcept; // Highly concurrent object hash map. // // Keys for this hash map are <hash_key> whereas objects are of type `T`. // `T` must be either move-constructible or copyable. // // Each bucket in the hash map has its unique mutex to guard itself. // This design reduces contensions between threads drastically in exchange // for some functions such as dynamic resizing of the number of buckets. template<typename T> class hash_map { static_assert( std::is_move_constructible<T>::value || std::is_copy_constructible<T>::value, "T must be move- or copy- constructible." ); public: typedef std::function<bool(const hash_key&, T&)> handler; typedef std::function<T(const hash_key&)> creator; // Hash map bucket. // // Each hash value corresponds to a bucket. // Member functions whose names end with `_nolock` are not thread-safe. class bucket { struct item { const hash_key key; T object; item* next; // perfect forwarding template<typename X> item(const hash_key& k, X&& o, item* n): key(k), object(std::forward<X>(o)), next(n) {} }; public: bucket(): m_objects(nullptr) {} ~bucket() { clear_nolock(); } // Handle or insert an object. // @key The object's key. // @h A function to handle an existing object. // @c A function to create a new object. // // This function can be used to handle an existing object, or // to insert a new object when such an object does not exist. // // If `h` is not `nullptr` and there is no existing object for // `key`, `false` is returned. If `c` is not `nullptr` and an // object for `key` exists, `false` is returned. // // `h` can return `false` if it failed to handle the object. // Otherwise, `h` should return `true`. // // @return `true` if succeeded, `false` otherwise. bool apply_nolock(const hash_key& key, const handler& h, const creator& c) { for( item* p = m_objects; p != nullptr; p = p->next ) { if( p->key == key ) { if( ! h ) return false; return h(p->key, p->object); } } if( ! c ) return false; m_objects = new item(key, c(key), m_objects); return true; } // Thread-safe <apply_nolock>. bool apply(const hash_key& key, const handler& h, const creator& c) { lock_guard g(m_lock); return apply_nolock(key, h, c); } // Remove an object for `key`. // @key The object's key. // @callback A function called when an object is removed. // // This removes an object associated with `key`. If there is no // object associated with `key`, return `false`. If `callback` // is not `nullptr`, it is called when an object is removed. // // @return `true` if successfully removed, `false` otherwise. bool remove_nolock(const hash_key& key, const std::function<void(const hash_key&)>& callback) { for( item** p = &m_objects; *p != nullptr; p = &((*p)->next) ) { if( (*p)->key == key ) { item* to_delete = *p; *p = to_delete->next; delete to_delete; if( callback ) callback(key); return true; } } return false; } // Thread-safe <remove_nolock>. bool remove(const hash_key& key, const std::function<void(const hash_key&)>& callback) { lock_guard g(m_lock); return remove_nolock(key, callback); } // Remove an object for `key` if `pred` returns `true`. // @key The object's key. // @pred A predicate function. // // This function removes an object assiciated with `key` if a // predicate function returns `true`. This function is thread-safe. // // @return `true` if object existed, `false` otherwise. bool remove_if(const hash_key& key, const std::function<bool(const hash_key&, T&)>& pred) { lock_guard g(m_lock); for( item** p = &m_objects; *p != nullptr; p = &((*p)->next) ) { item* to_delete = *p; if( to_delete->key == key ) { if( pred(key, to_delete->object) ) { *p = to_delete->next; delete to_delete; } return true; } } return false; } // Collect garbage objects. // @pred Predicate function. // // This function collects garbage objects. // Objects for which `pred` returns `true` will be removed. void gc(const std::function<bool(const hash_key&, T&)>& pred) { lock_guard g(m_lock); for( item** p = &m_objects; *p != nullptr; ) { item* to_delete = *p; if( pred(to_delete->key, to_delete->object) ) { *p = to_delete->next; delete to_delete; } else { p = &(to_delete->next); } } } // Clear objects in this bucket. void clear_nolock() { while( m_objects ) { item* next = m_objects->next; delete m_objects; m_objects = next; } } private: using lock_guard = std::lock_guard<std::mutex>; mutable std::mutex m_lock; item* m_objects; }; hash_map(unsigned int buckets): m_size(nearest_prime(buckets)), m_buckets(m_size) {} // Handle or insert an object. // @key The object's key. // @h A function to handle an existing object. // @c A function to create a new object. // // This function can be used to handle an existing object, or // to insert a new object when such an object does not exist. // // If `h` is not `nullptr` and there is no existing object for // `key`, `false` is returned. If `c` is not `nullptr` and an // object for `key` exists, `false` is returned. // // `h` can return `false` if it failed to handle the object. // Otherwise, `h` should return `true`. // // @return `true` if succeeded, `false` otherwise. bool apply_nolock(const hash_key& key, const handler& h, const creator& c) { return get_bucket(key).apply_nolock(key, h, c); } // Thread-safe <apply_nolock>. bool apply(const hash_key& key, const handler& h, const creator& c) { return get_bucket(key).apply(key, h, c); } // Remove an object for `key`. // @key The object's key. // @callback A function called when an object is removed. // // This removes an object associated with `key`. If there is no // object associated with `key`, return `false`. If `callback` // is not `nullptr`, it is called when an object is removed. // // @return `true` if successfully removed, `false` otherwise. bool remove_nolock(const hash_key& key, const std::function<void(const hash_key&)>& callback) { return get_bucket(key).remove_nolock(key, callback); } // Thread-safe <remove_nolock>. bool remove(const hash_key& key, const std::function<void(const hash_key&)>& callback) { return get_bucket(key).remove(key, callback); } // Remove an object for `key` if `pred` returns `true`. // @key The object's key. // @pred A predicate function. // // This function removes an object assiciated with `key` if a // predicate function returns `true`. This function is thread-safe. // // @return `true` if object existed, `false` otherwise. bool remove_if(const hash_key& key, const std::function<bool(const hash_key&, T&)>& pred) { return get_bucket(key).remove_if(key, pred); } /* Bucket interfaces */ // Return the number of buckets in this hash map. std::size_t bucket_count() const noexcept { return m_size; } bucket& get_bucket(const hash_key& key) noexcept { return m_buckets[key.hash() % m_size]; } // <bucket> iterator. using iterator = typename std::vector<bucket>::iterator; iterator begin() { return m_buckets.begin(); } iterator end() { return m_buckets.end(); } private: const std::size_t m_size; std::vector<bucket> m_buckets; }; } // namespace cybozu #endif // CYBOZU_HASH_MAP_HPP <|endoftext|>
<commit_before>// Spinlock. // (C) 2013 Cybozu. #ifndef CYBOZU_SPINLOCK_HPP #define CYBOZU_SPINLOCK_HPP #include <atomic> #if defined(__i386__) || defined(__x86_64__) # include <x86intrin.h> #endif namespace cybozu { // A simple spinlock. class spinlock { public: spinlock(): m_flag(ATOMIC_FLAG_INIT) {} void lock() { while( m_flag.test_and_set(std::memory_order_acquire) ) pause(); } void unlock() { m_flag.clear(std::memory_order_release); } private: std::atomic_flag m_flag; void pause() { #if defined(__i386__) || defined(__x86_64__) # if defined(__SSE__) _mm_pause(); # else __asm__ __volatile__ ("rep; nop"); # endif #endif } }; } // namespace cybozu #endif // CYBOZU_SPINLOCK_HPP <commit_msg>correct initialization of atomic_flag<commit_after>// Spinlock. // (C) 2013 Cybozu. #ifndef CYBOZU_SPINLOCK_HPP #define CYBOZU_SPINLOCK_HPP #include <atomic> #if defined(__i386__) || defined(__x86_64__) # include <x86intrin.h> #endif namespace cybozu { // A simple spinlock. class spinlock { public: spinlock() {} void lock() { while( m_flag.test_and_set(std::memory_order_acquire) ) pause(); } void unlock() { m_flag.clear(std::memory_order_release); } private: std::atomic_flag m_flag = ATOMIC_FLAG_INIT; void pause() { #if defined(__i386__) || defined(__x86_64__) # if defined(__SSE__) _mm_pause(); # else __asm__ __volatile__ ("rep; nop"); # endif #endif } }; } // namespace cybozu #endif // CYBOZU_SPINLOCK_HPP <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ // Copyright (c) 2008 Roberto Raggi <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "CheckName.h" #include "Semantic.h" #include "AST.h" #include "Control.h" #include "TranslationUnit.h" #include "Literals.h" #include "Names.h" #include "CoreTypes.h" #include "Symbols.h" #include "Scope.h" #include <cassert> using namespace CPlusPlus; CheckName::CheckName(Semantic *semantic) : SemanticCheck(semantic), _name(0), _scope(0) { } CheckName::~CheckName() { } const Name *CheckName::check(NameAST *name, Scope *scope) { const Name *previousName = switchName(0); Scope *previousScope = switchScope(scope); accept(name); if (_name && name) name->name = _name; (void) switchScope(previousScope); return switchName(previousName); } const Name *CheckName::check(NestedNameSpecifierListAST *nested_name_specifier_list, Scope *scope) { const Name *previousName = switchName(0); Scope *previousScope = switchScope(scope); std::vector<const Name *> names; for (NestedNameSpecifierListAST *it = nested_name_specifier_list; it; it = it->next) { NestedNameSpecifierAST *nested_name_specifier = it->value; names.push_back(semantic()->check(nested_name_specifier->class_or_namespace_name, _scope)); } if (! names.empty()) _name = control()->qualifiedNameId(&names[0], names.size()); (void) switchScope(previousScope); return switchName(previousName); } void CheckName::check(ObjCMessageArgumentDeclarationAST *arg, Scope *scope) { const Name *previousName = switchName(0); Scope *previousScope = switchScope(scope); accept(arg); (void) switchScope(previousScope); (void) switchName(previousName); } const Name *CheckName::switchName(const Name *name) { const Name *previousName = _name; _name = name; return previousName; } Scope *CheckName::switchScope(Scope *scope) { Scope *previousScope = _scope; _scope = scope; return previousScope; } bool CheckName::visit(QualifiedNameAST *ast) { std::vector<const Name *> names; for (NestedNameSpecifierListAST *it = ast->nested_name_specifier_list; it; it = it->next) { NestedNameSpecifierAST *nested_name_specifier = it->value; names.push_back(semantic()->check(nested_name_specifier->class_or_namespace_name, _scope)); } names.push_back(semantic()->check(ast->unqualified_name, _scope)); _name = control()->qualifiedNameId(&names[0], names.size(), ast->global_scope_token != 0); ast->name = _name; return false; } bool CheckName::visit(OperatorFunctionIdAST *ast) { assert(ast->op != 0); OperatorNameId::Kind kind = OperatorNameId::InvalidOp; switch (tokenKind(ast->op->op_token)) { case T_NEW: if (ast->op->open_token) kind = OperatorNameId::NewArrayOp; else kind = OperatorNameId::NewOp; break; case T_DELETE: if (ast->op->open_token) kind = OperatorNameId::DeleteArrayOp; else kind = OperatorNameId::DeleteOp; break; case T_PLUS: kind = OperatorNameId::PlusOp; break; case T_MINUS: kind = OperatorNameId::MinusOp; break; case T_STAR: kind = OperatorNameId::StarOp; break; case T_SLASH: kind = OperatorNameId::SlashOp; break; case T_PERCENT: kind = OperatorNameId::PercentOp; break; case T_CARET: kind = OperatorNameId::CaretOp; break; case T_AMPER: kind = OperatorNameId::AmpOp; break; case T_PIPE: kind = OperatorNameId::PipeOp; break; case T_TILDE: kind = OperatorNameId::TildeOp; break; case T_EXCLAIM: kind = OperatorNameId::ExclaimOp; break; case T_EQUAL: kind = OperatorNameId::EqualOp; break; case T_LESS: kind = OperatorNameId::LessOp; break; case T_GREATER: kind = OperatorNameId::GreaterOp; break; case T_PLUS_EQUAL: kind = OperatorNameId::PlusEqualOp; break; case T_MINUS_EQUAL: kind = OperatorNameId::MinusEqualOp; break; case T_STAR_EQUAL: kind = OperatorNameId::StarEqualOp; break; case T_SLASH_EQUAL: kind = OperatorNameId::SlashEqualOp; break; case T_PERCENT_EQUAL: kind = OperatorNameId::PercentEqualOp; break; case T_CARET_EQUAL: kind = OperatorNameId::CaretEqualOp; break; case T_AMPER_EQUAL: kind = OperatorNameId::AmpEqualOp; break; case T_PIPE_EQUAL: kind = OperatorNameId::PipeEqualOp; break; case T_LESS_LESS: kind = OperatorNameId::LessLessOp; break; case T_GREATER_GREATER: kind = OperatorNameId::GreaterGreaterOp; break; case T_LESS_LESS_EQUAL: kind = OperatorNameId::LessLessEqualOp; break; case T_GREATER_GREATER_EQUAL: kind = OperatorNameId::GreaterGreaterEqualOp; break; case T_EQUAL_EQUAL: kind = OperatorNameId::EqualEqualOp; break; case T_EXCLAIM_EQUAL: kind = OperatorNameId::ExclaimEqualOp; break; case T_LESS_EQUAL: kind = OperatorNameId::LessEqualOp; break; case T_GREATER_EQUAL: kind = OperatorNameId::GreaterEqualOp; break; case T_AMPER_AMPER: kind = OperatorNameId::AmpAmpOp; break; case T_PIPE_PIPE: kind = OperatorNameId::PipePipeOp; break; case T_PLUS_PLUS: kind = OperatorNameId::PlusPlusOp; break; case T_MINUS_MINUS: kind = OperatorNameId::MinusMinusOp; break; case T_COMMA: kind = OperatorNameId::CommaOp; break; case T_ARROW_STAR: kind = OperatorNameId::ArrowStarOp; break; case T_ARROW: kind = OperatorNameId::ArrowOp; break; case T_LPAREN: kind = OperatorNameId::FunctionCallOp; break; case T_LBRACKET: kind = OperatorNameId::ArrayAccessOp; break; default: kind = OperatorNameId::InvalidOp; } // switch _name = control()->operatorNameId(kind); ast->name = _name; return false; } bool CheckName::visit(ConversionFunctionIdAST *ast) { FullySpecifiedType ty = semantic()->check(ast->type_specifier_list, _scope); ty = semantic()->check(ast->ptr_operator_list, ty, _scope); _name = control()->conversionNameId(ty); return false; } bool CheckName::visit(SimpleNameAST *ast) { const Identifier *id = identifier(ast->identifier_token); _name = control()->nameId(id); ast->name = _name; return false; } bool CheckName::visit(DestructorNameAST *ast) { const Identifier *id = identifier(ast->identifier_token); _name = control()->destructorNameId(id); ast->name = _name; return false; } bool CheckName::visit(TemplateIdAST *ast) { const Identifier *id = identifier(ast->identifier_token); std::vector<FullySpecifiedType> templateArguments; for (TemplateArgumentListAST *it = ast->template_argument_list; it; it = it->next) { ExpressionAST *arg = it->value; FullySpecifiedType exprTy = semantic()->check(arg, _scope); templateArguments.push_back(exprTy); } if (templateArguments.empty()) _name = control()->templateNameId(id); else _name = control()->templateNameId(id, &templateArguments[0], templateArguments.size()); ast->name = _name; return false; } bool CheckName::visit(ObjCSelectorAST *ast) { std::vector<const Name *> names; for (ObjCSelectorArgumentListAST *it = ast->selector_argument_list; it; it = it->next) { if (it->value->name_token) { const Identifier *id = control()->findOrInsertIdentifier(spell(it->value->name_token)); const NameId *nameId = control()->nameId(id); names.push_back(nameId); } else { // we have an incomplete name due, probably due to error recovery. So, back out completely return false; } } if (!names.empty()) { _name = control()->selectorNameId(&names[0], names.size(), true); ast->name = _name; } return false; } bool CheckName::visit(ObjCMessageArgumentDeclarationAST *ast) { FullySpecifiedType type; if (ast->type_name) type = semantic()->check(ast->type_name, _scope); if (ast->param_name) { accept(ast->param_name); Argument *arg = control()->newArgument(ast->param_name->firstToken(), ast->param_name->name); ast->argument = arg; arg->setType(type); arg->setInitializer(0); _scope->enterSymbol(arg); } return false; } <commit_msg>Fixed ObjC selector name creation.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ // Copyright (c) 2008 Roberto Raggi <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "CheckName.h" #include "Semantic.h" #include "AST.h" #include "Control.h" #include "TranslationUnit.h" #include "Literals.h" #include "Names.h" #include "CoreTypes.h" #include "Symbols.h" #include "Scope.h" #include <cassert> using namespace CPlusPlus; CheckName::CheckName(Semantic *semantic) : SemanticCheck(semantic), _name(0), _scope(0) { } CheckName::~CheckName() { } const Name *CheckName::check(NameAST *name, Scope *scope) { const Name *previousName = switchName(0); Scope *previousScope = switchScope(scope); accept(name); if (_name && name) name->name = _name; (void) switchScope(previousScope); return switchName(previousName); } const Name *CheckName::check(NestedNameSpecifierListAST *nested_name_specifier_list, Scope *scope) { const Name *previousName = switchName(0); Scope *previousScope = switchScope(scope); std::vector<const Name *> names; for (NestedNameSpecifierListAST *it = nested_name_specifier_list; it; it = it->next) { NestedNameSpecifierAST *nested_name_specifier = it->value; names.push_back(semantic()->check(nested_name_specifier->class_or_namespace_name, _scope)); } if (! names.empty()) _name = control()->qualifiedNameId(&names[0], names.size()); (void) switchScope(previousScope); return switchName(previousName); } void CheckName::check(ObjCMessageArgumentDeclarationAST *arg, Scope *scope) { const Name *previousName = switchName(0); Scope *previousScope = switchScope(scope); accept(arg); (void) switchScope(previousScope); (void) switchName(previousName); } const Name *CheckName::switchName(const Name *name) { const Name *previousName = _name; _name = name; return previousName; } Scope *CheckName::switchScope(Scope *scope) { Scope *previousScope = _scope; _scope = scope; return previousScope; } bool CheckName::visit(QualifiedNameAST *ast) { std::vector<const Name *> names; for (NestedNameSpecifierListAST *it = ast->nested_name_specifier_list; it; it = it->next) { NestedNameSpecifierAST *nested_name_specifier = it->value; names.push_back(semantic()->check(nested_name_specifier->class_or_namespace_name, _scope)); } names.push_back(semantic()->check(ast->unqualified_name, _scope)); _name = control()->qualifiedNameId(&names[0], names.size(), ast->global_scope_token != 0); ast->name = _name; return false; } bool CheckName::visit(OperatorFunctionIdAST *ast) { assert(ast->op != 0); OperatorNameId::Kind kind = OperatorNameId::InvalidOp; switch (tokenKind(ast->op->op_token)) { case T_NEW: if (ast->op->open_token) kind = OperatorNameId::NewArrayOp; else kind = OperatorNameId::NewOp; break; case T_DELETE: if (ast->op->open_token) kind = OperatorNameId::DeleteArrayOp; else kind = OperatorNameId::DeleteOp; break; case T_PLUS: kind = OperatorNameId::PlusOp; break; case T_MINUS: kind = OperatorNameId::MinusOp; break; case T_STAR: kind = OperatorNameId::StarOp; break; case T_SLASH: kind = OperatorNameId::SlashOp; break; case T_PERCENT: kind = OperatorNameId::PercentOp; break; case T_CARET: kind = OperatorNameId::CaretOp; break; case T_AMPER: kind = OperatorNameId::AmpOp; break; case T_PIPE: kind = OperatorNameId::PipeOp; break; case T_TILDE: kind = OperatorNameId::TildeOp; break; case T_EXCLAIM: kind = OperatorNameId::ExclaimOp; break; case T_EQUAL: kind = OperatorNameId::EqualOp; break; case T_LESS: kind = OperatorNameId::LessOp; break; case T_GREATER: kind = OperatorNameId::GreaterOp; break; case T_PLUS_EQUAL: kind = OperatorNameId::PlusEqualOp; break; case T_MINUS_EQUAL: kind = OperatorNameId::MinusEqualOp; break; case T_STAR_EQUAL: kind = OperatorNameId::StarEqualOp; break; case T_SLASH_EQUAL: kind = OperatorNameId::SlashEqualOp; break; case T_PERCENT_EQUAL: kind = OperatorNameId::PercentEqualOp; break; case T_CARET_EQUAL: kind = OperatorNameId::CaretEqualOp; break; case T_AMPER_EQUAL: kind = OperatorNameId::AmpEqualOp; break; case T_PIPE_EQUAL: kind = OperatorNameId::PipeEqualOp; break; case T_LESS_LESS: kind = OperatorNameId::LessLessOp; break; case T_GREATER_GREATER: kind = OperatorNameId::GreaterGreaterOp; break; case T_LESS_LESS_EQUAL: kind = OperatorNameId::LessLessEqualOp; break; case T_GREATER_GREATER_EQUAL: kind = OperatorNameId::GreaterGreaterEqualOp; break; case T_EQUAL_EQUAL: kind = OperatorNameId::EqualEqualOp; break; case T_EXCLAIM_EQUAL: kind = OperatorNameId::ExclaimEqualOp; break; case T_LESS_EQUAL: kind = OperatorNameId::LessEqualOp; break; case T_GREATER_EQUAL: kind = OperatorNameId::GreaterEqualOp; break; case T_AMPER_AMPER: kind = OperatorNameId::AmpAmpOp; break; case T_PIPE_PIPE: kind = OperatorNameId::PipePipeOp; break; case T_PLUS_PLUS: kind = OperatorNameId::PlusPlusOp; break; case T_MINUS_MINUS: kind = OperatorNameId::MinusMinusOp; break; case T_COMMA: kind = OperatorNameId::CommaOp; break; case T_ARROW_STAR: kind = OperatorNameId::ArrowStarOp; break; case T_ARROW: kind = OperatorNameId::ArrowOp; break; case T_LPAREN: kind = OperatorNameId::FunctionCallOp; break; case T_LBRACKET: kind = OperatorNameId::ArrayAccessOp; break; default: kind = OperatorNameId::InvalidOp; } // switch _name = control()->operatorNameId(kind); ast->name = _name; return false; } bool CheckName::visit(ConversionFunctionIdAST *ast) { FullySpecifiedType ty = semantic()->check(ast->type_specifier_list, _scope); ty = semantic()->check(ast->ptr_operator_list, ty, _scope); _name = control()->conversionNameId(ty); return false; } bool CheckName::visit(SimpleNameAST *ast) { const Identifier *id = identifier(ast->identifier_token); _name = control()->nameId(id); ast->name = _name; return false; } bool CheckName::visit(DestructorNameAST *ast) { const Identifier *id = identifier(ast->identifier_token); _name = control()->destructorNameId(id); ast->name = _name; return false; } bool CheckName::visit(TemplateIdAST *ast) { const Identifier *id = identifier(ast->identifier_token); std::vector<FullySpecifiedType> templateArguments; for (TemplateArgumentListAST *it = ast->template_argument_list; it; it = it->next) { ExpressionAST *arg = it->value; FullySpecifiedType exprTy = semantic()->check(arg, _scope); templateArguments.push_back(exprTy); } if (templateArguments.empty()) _name = control()->templateNameId(id); else _name = control()->templateNameId(id, &templateArguments[0], templateArguments.size()); ast->name = _name; return false; } bool CheckName::visit(ObjCSelectorAST *ast) { std::vector<const Name *> names; bool hasArgs = false; for (ObjCSelectorArgumentListAST *it = ast->selector_argument_list; it; it = it->next) { if (it->value->name_token) { const Identifier *id = control()->findOrInsertIdentifier(spell(it->value->name_token)); const NameId *nameId = control()->nameId(id); names.push_back(nameId); if (!hasArgs && it->value->colon_token) hasArgs = true; } else { // we have an incomplete name due, probably due to error recovery. So, back out completely return false; } } if (!names.empty()) { _name = control()->selectorNameId(&names[0], names.size(), hasArgs); ast->name = _name; } return false; } bool CheckName::visit(ObjCMessageArgumentDeclarationAST *ast) { FullySpecifiedType type; if (ast->type_name) type = semantic()->check(ast->type_name, _scope); if (ast->param_name) { accept(ast->param_name); Argument *arg = control()->newArgument(ast->param_name->firstToken(), ast->param_name->name); ast->argument = arg; arg->setType(type); arg->setInitializer(0); _scope->enterSymbol(arg); } return false; } <|endoftext|>
<commit_before>// // Created by salmon on 17-9-18. // #include "MPIUpdater.h" #include <mpi.h> #include "MPIComm.h" #include "simpla/SIMPLA_config.h" #include "simpla/utilities/macro.h" namespace simpla { namespace parallel { struct MPIUpdater::pimpl_s { bool m_is_setup_ = false; MPI_Comm comm; int ndims = 3; int mpi_topology_ndims = 0; int mpi_dims[3], mpi_periods[3], mpi_coords[3]; index_box_type local_box_; index_box_type send_box[6]; index_box_type recv_box[6]; index_tuple m_gw_{2, 2, 2}; MPI_Datatype ele_type; int tag; void *send_buffer[6]; void *recv_buffer[6]; int send_size[6]; int recv_size[6]; }; MPIUpdater::MPIUpdater() : m_pimpl_(new pimpl_s) { if (GLOBAL_COMM.comm() == MPI_COMM_NULL) { return; } m_pimpl_->comm = GLOBAL_COMM.comm(); if (GLOBAL_COMM.comm() == MPI_COMM_NULL) { return; } int tope_type = MPI_CART; MPI_CALL(MPI_Topo_test(GLOBAL_COMM.comm(), &tope_type)); if (tope_type != MPI_CART) { return; } int tag = 0; MPI_CALL(MPI_Cartdim_get(GLOBAL_COMM.comm(), &m_pimpl_->mpi_topology_ndims)); }; MPIUpdater::~MPIUpdater() { TearDown(); }; void MPIUpdater::SetGhostWidth(index_tuple const &gw) { m_pimpl_->m_gw_ = gw; } index_tuple MPIUpdater::GetGhostWidth() const { return m_pimpl_->m_gw_; } void MPIUpdater::SetIndexBox(index_box_type const &idx_box) { m_pimpl_->local_box_ = idx_box; } index_box_type MPIUpdater::GetIndexBox() const { return m_pimpl_->local_box_; } bool MPIUpdater::isSetUp() const { return m_pimpl_->m_is_setup_; } bool MPIUpdater::isEnable() const { return m_pimpl_->comm != MPI_COMM_NULL && GLOBAL_COMM.size() > 1; } void MPIUpdater::SetUp() { m_pimpl_->m_is_setup_ = true; int topo_type = MPI_CART; MPI_CALL(MPI_Topo_test(m_pimpl_->comm, &topo_type)); ASSERT(topo_type == MPI_CART); MPI_CALL(MPI_Cartdim_get(m_pimpl_->comm, &m_pimpl_->mpi_topology_ndims)); ASSERT(m_pimpl_->mpi_topology_ndims <= m_pimpl_->ndims); MPI_CALL(MPI_Cart_get(m_pimpl_->comm, 3, m_pimpl_->mpi_dims, m_pimpl_->mpi_periods, m_pimpl_->mpi_coords)); for (int i = 0; i < 6; ++i) { m_pimpl_->send_box[i] = m_pimpl_->local_box_; m_pimpl_->recv_box[i] = m_pimpl_->local_box_; } for (int d = 0; d < m_pimpl_->mpi_topology_ndims; ++d) { if (m_pimpl_->mpi_dims[d] == 1) { std::get<0>(m_pimpl_->send_box[2 * d + 0]) = 0; std::get<0>(m_pimpl_->send_box[2 * d + 1]) = 0; std::get<0>(m_pimpl_->recv_box[2 * d + 0]) = 0; std::get<0>(m_pimpl_->recv_box[2 * d + 1]) = 0; std::get<1>(m_pimpl_->send_box[2 * d + 0]) = 0; std::get<1>(m_pimpl_->send_box[2 * d + 1]) = 0; std::get<1>(m_pimpl_->recv_box[2 * d + 0]) = 0; std::get<1>(m_pimpl_->recv_box[2 * d + 1]) = 0; continue; } std::get<0>(m_pimpl_->send_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d]; std::get<1>(m_pimpl_->send_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d] + m_pimpl_->m_gw_[d]; std::get<0>(m_pimpl_->recv_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d] - m_pimpl_->m_gw_[d]; std::get<1>(m_pimpl_->recv_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d]; std::get<0>(m_pimpl_->send_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d] - m_pimpl_->m_gw_[d]; std::get<1>(m_pimpl_->send_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d]; std::get<0>(m_pimpl_->recv_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d]; std::get<1>(m_pimpl_->recv_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d] + m_pimpl_->m_gw_[d]; // for (int i = 0; i < d; ++i) { // std::get<0>(m_pimpl_->send_box[2 * d + 0])[i] = std::get<0>(m_pimpl_->local_box_)[i] - // m_pimpl_->m_gw_[i]; // std::get<1>(m_pimpl_->send_box[2 * d + 0])[i] = std::get<0>(m_pimpl_->local_box_)[i] + // m_pimpl_->m_gw_[i]; // // std::get<0>(m_pimpl_->recv_box[2 * d + 0])[i] = std::get<0>(m_pimpl_->local_box_)[i] - // m_pimpl_->m_gw_[i]; // std::get<1>(m_pimpl_->recv_box[2 * d + 0])[i] = std::get<0>(m_pimpl_->local_box_)[i] + // m_pimpl_->m_gw_[i]; // // std::get<0>(m_pimpl_->send_box[2 * d + 1])[i] = std::get<1>(m_pimpl_->local_box_)[i] - // m_pimpl_->m_gw_[i]; // std::get<1>(m_pimpl_->send_box[2 * d + 1])[i] = std::get<1>(m_pimpl_->local_box_)[i] + // m_pimpl_->m_gw_[i]; // // std::get<0>(m_pimpl_->recv_box[2 * d + 1])[i] = std::get<1>(m_pimpl_->local_box_)[i] - // m_pimpl_->m_gw_[i]; // std::get<1>(m_pimpl_->recv_box[2 * d + 1])[i] = std::get<1>(m_pimpl_->local_box_)[i] + // m_pimpl_->m_gw_[i]; // } } size_type ele_size = 0; if (value_type_info() == typeid(int)) { ele_size = sizeof(int); m_pimpl_->ele_type = MPI_INT; } else if (value_type_info() == typeid(double)) { ele_size = sizeof(double); m_pimpl_->ele_type = MPI_DOUBLE; } else if (value_type_info() == typeid(float)) { ele_size = sizeof(float); m_pimpl_->ele_type = MPI_FLOAT; } else if (value_type_info() == typeid(long)) { ele_size = sizeof(long); m_pimpl_->ele_type = MPI_LONG; } else if (value_type_info() == typeid(unsigned long)) { ele_size = sizeof(unsigned long); m_pimpl_->ele_type = MPI_UNSIGNED_LONG; } else { UNIMPLEMENTED; } for (int i = 0; i < 6; ++i) { m_pimpl_->send_size[i] = static_cast<int>(std::get<1>(m_pimpl_->send_box[i])[0] - std::get<0>(m_pimpl_->send_box[i])[0]) * static_cast<int>(std::get<1>(m_pimpl_->send_box[i])[1] - std::get<0>(m_pimpl_->send_box[i])[1]) * static_cast<int>(std::get<1>(m_pimpl_->send_box[i])[2] - std::get<0>(m_pimpl_->send_box[i])[2]); m_pimpl_->recv_size[i] = static_cast<int>(std::get<1>(m_pimpl_->recv_box[i])[0] - std::get<0>(m_pimpl_->recv_box[i])[0]) * static_cast<int>(std::get<1>(m_pimpl_->recv_box[i])[1] - std::get<0>(m_pimpl_->recv_box[i])[1]) * static_cast<int>(std::get<1>(m_pimpl_->recv_box[i])[2] - std::get<0>(m_pimpl_->recv_box[i])[2]); if (m_pimpl_->send_buffer[i] != nullptr) { delete m_pimpl_->send_buffer[i]; } if (m_pimpl_->recv_buffer[i] != nullptr) { delete m_pimpl_->recv_buffer[i]; } if (m_pimpl_->send_size[i] > 0) m_pimpl_->send_buffer[i] = operator new(m_pimpl_->send_size[i] * ele_size); if (m_pimpl_->recv_size[i] > 0) m_pimpl_->recv_buffer[i] = operator new(m_pimpl_->recv_size[i] * ele_size); } for (int i = 0; i < 6; ++i) { GetSendBuffer(i).reset(m_pimpl_->send_buffer[i], &std::get<0>(m_pimpl_->send_box[i])[0], &std::get<1>(m_pimpl_->send_box[i])[0]); GetRecvBuffer(i).reset(m_pimpl_->recv_buffer[i], &std::get<0>(m_pimpl_->recv_box[i])[0], &std::get<1>(m_pimpl_->recv_box[i])[0]); GetSendBuffer(i).Clear(); GetRecvBuffer(i).Clear(); } } void MPIUpdater::TearDown() { for (auto *v : m_pimpl_->send_buffer) { delete v; } for (auto *v : m_pimpl_->recv_buffer) { delete v; } m_pimpl_->m_is_setup_ = false; } void MPIUpdater::SetTag(int tag) { m_pimpl_->tag = tag; } void MPIUpdater::Update(ArrayBase &d) { if (!isSetUp()) { return; } for (int dir = 0; dir < 3; ++dir) { Push(d, dir); SendRecv(dir); Pop(d, dir); } } void MPIUpdater::Push(ArrayBase const &d, int direction) { if (!isSetUp()) { return; } CHECK(GetSendBuffer(2 * direction + 0).CopyIn(d)); GetSendBuffer(2 * direction + 1).CopyIn(d); } void MPIUpdater::Pop(ArrayBase &d, int direction) const { if (!isSetUp()) { return; } CHECK(d.CopyIn(GetRecvBuffer(2 * direction + 0))); d.CopyIn(GetRecvBuffer(2 * direction + 1)); } void MPIUpdater::SendRecv(int d) { if (!isSetUp()) { return; } // for (int d = 0; d < m_pimpl_->mpi_topology_ndims; ++d) { int left, right; MPI_CALL(MPI_Cart_shift(m_pimpl_->comm, d, 1, &left, &right)); GLOBAL_COMM.barrier(); MPI_CALL(MPI_Sendrecv(m_pimpl_->send_buffer[d * 2 + 0], m_pimpl_->send_size[d * 2 + 0], m_pimpl_->ele_type, left, m_pimpl_->tag, m_pimpl_->recv_buffer[d * 2 + 1], m_pimpl_->recv_size[d * 2 + 1], m_pimpl_->ele_type, right, m_pimpl_->tag, m_pimpl_->comm, MPI_STATUS_IGNORE)); GLOBAL_COMM.barrier(); MPI_CALL(MPI_Sendrecv(m_pimpl_->send_buffer[d * 2 + 1], m_pimpl_->send_size[d * 2 + 1], m_pimpl_->ele_type, right, m_pimpl_->tag, m_pimpl_->recv_buffer[d * 2 + 0], m_pimpl_->recv_size[d * 2 + 0], m_pimpl_->ele_type, left, m_pimpl_->tag, m_pimpl_->comm, MPI_STATUS_IGNORE)); GLOBAL_COMM.barrier(); // } } } // namespace parallel { } // namespace simpla {<commit_msg>MPIUpdater<commit_after>// // Created by salmon on 17-9-18. // #include "MPIUpdater.h" #include <mpi.h> #include "MPIComm.h" #include "simpla/SIMPLA_config.h" #include "simpla/utilities/macro.h" namespace simpla { namespace parallel { struct MPIUpdater::pimpl_s { bool m_is_setup_ = false; MPI_Comm comm; int ndims = 3; int mpi_topology_ndims = 0; int mpi_dims[3], mpi_periods[3], mpi_coords[3]; index_box_type local_box_; index_box_type send_box[6]; index_box_type recv_box[6]; index_tuple m_gw_{2, 2, 2}; MPI_Datatype ele_type; int tag; void *send_buffer[6]; void *recv_buffer[6]; int send_size[6]; int recv_size[6]; }; MPIUpdater::MPIUpdater() : m_pimpl_(new pimpl_s) { if (GLOBAL_COMM.comm() == MPI_COMM_NULL) { return; } m_pimpl_->comm = GLOBAL_COMM.comm(); if (GLOBAL_COMM.comm() == MPI_COMM_NULL) { return; } int tope_type = MPI_CART; MPI_CALL(MPI_Topo_test(GLOBAL_COMM.comm(), &tope_type)); if (tope_type != MPI_CART) { return; } int tag = 0; MPI_CALL(MPI_Cartdim_get(GLOBAL_COMM.comm(), &m_pimpl_->mpi_topology_ndims)); }; MPIUpdater::~MPIUpdater() { TearDown(); }; void MPIUpdater::SetGhostWidth(index_tuple const &gw) { m_pimpl_->m_gw_ = gw; } index_tuple MPIUpdater::GetGhostWidth() const { return m_pimpl_->m_gw_; } void MPIUpdater::SetIndexBox(index_box_type const &idx_box) { m_pimpl_->local_box_ = idx_box; } index_box_type MPIUpdater::GetIndexBox() const { return m_pimpl_->local_box_; } bool MPIUpdater::isSetUp() const { return m_pimpl_->m_is_setup_; } bool MPIUpdater::isEnable() const { return m_pimpl_->comm != MPI_COMM_NULL && GLOBAL_COMM.size() > 1; } void MPIUpdater::SetUp() { m_pimpl_->m_is_setup_ = true; int topo_type = MPI_CART; MPI_CALL(MPI_Topo_test(m_pimpl_->comm, &topo_type)); ASSERT(topo_type == MPI_CART); MPI_CALL(MPI_Cartdim_get(m_pimpl_->comm, &m_pimpl_->mpi_topology_ndims)); ASSERT(m_pimpl_->mpi_topology_ndims <= m_pimpl_->ndims); MPI_CALL(MPI_Cart_get(m_pimpl_->comm, 3, m_pimpl_->mpi_dims, m_pimpl_->mpi_periods, m_pimpl_->mpi_coords)); for (int i = 0; i < 6; ++i) { m_pimpl_->send_box[i] = m_pimpl_->local_box_; m_pimpl_->recv_box[i] = m_pimpl_->local_box_; } for (int d = 0; d < m_pimpl_->mpi_topology_ndims; ++d) { if (m_pimpl_->mpi_dims[d] == 1) { std::get<0>(m_pimpl_->send_box[2 * d + 0]) = 0; std::get<0>(m_pimpl_->send_box[2 * d + 1]) = 0; std::get<0>(m_pimpl_->recv_box[2 * d + 0]) = 0; std::get<0>(m_pimpl_->recv_box[2 * d + 1]) = 0; std::get<1>(m_pimpl_->send_box[2 * d + 0]) = 0; std::get<1>(m_pimpl_->send_box[2 * d + 1]) = 0; std::get<1>(m_pimpl_->recv_box[2 * d + 0]) = 0; std::get<1>(m_pimpl_->recv_box[2 * d + 1]) = 0; continue; } std::get<0>(m_pimpl_->send_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d]; std::get<1>(m_pimpl_->send_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d] + m_pimpl_->m_gw_[d]; std::get<0>(m_pimpl_->recv_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d] - m_pimpl_->m_gw_[d]; std::get<1>(m_pimpl_->recv_box[2 * d + 0])[d] = std::get<0>(m_pimpl_->local_box_)[d]; std::get<0>(m_pimpl_->send_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d] - m_pimpl_->m_gw_[d]; std::get<1>(m_pimpl_->send_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d]; std::get<0>(m_pimpl_->recv_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d]; std::get<1>(m_pimpl_->recv_box[2 * d + 1])[d] = std::get<1>(m_pimpl_->local_box_)[d] + m_pimpl_->m_gw_[d]; for (int i = 0; i < d; ++i) { std::get<0>(m_pimpl_->send_box[2 * d + 0])[i] = std::get<0>(m_pimpl_->local_box_)[i] - m_pimpl_->m_gw_[i]; std::get<1>(m_pimpl_->send_box[2 * d + 0])[i] = std::get<1>(m_pimpl_->local_box_)[i] + m_pimpl_->m_gw_[i]; std::get<0>(m_pimpl_->recv_box[2 * d + 0])[i] = std::get<0>(m_pimpl_->local_box_)[i] - m_pimpl_->m_gw_[i]; std::get<1>(m_pimpl_->recv_box[2 * d + 0])[i] = std::get<1>(m_pimpl_->local_box_)[i] + m_pimpl_->m_gw_[i]; std::get<0>(m_pimpl_->send_box[2 * d + 1])[i] = std::get<0>(m_pimpl_->local_box_)[i] - m_pimpl_->m_gw_[i]; std::get<1>(m_pimpl_->send_box[2 * d + 1])[i] = std::get<1>(m_pimpl_->local_box_)[i] + m_pimpl_->m_gw_[i]; std::get<0>(m_pimpl_->recv_box[2 * d + 1])[i] = std::get<0>(m_pimpl_->local_box_)[i] - m_pimpl_->m_gw_[i]; std::get<1>(m_pimpl_->recv_box[2 * d + 1])[i] = std::get<1>(m_pimpl_->local_box_)[i] + m_pimpl_->m_gw_[i]; } } size_type ele_size = 0; if (value_type_info() == typeid(int)) { ele_size = sizeof(int); m_pimpl_->ele_type = MPI_INT; } else if (value_type_info() == typeid(double)) { ele_size = sizeof(double); m_pimpl_->ele_type = MPI_DOUBLE; } else if (value_type_info() == typeid(float)) { ele_size = sizeof(float); m_pimpl_->ele_type = MPI_FLOAT; } else if (value_type_info() == typeid(long)) { ele_size = sizeof(long); m_pimpl_->ele_type = MPI_LONG; } else if (value_type_info() == typeid(unsigned long)) { ele_size = sizeof(unsigned long); m_pimpl_->ele_type = MPI_UNSIGNED_LONG; } else { UNIMPLEMENTED; } for (int i = 0; i < 6; ++i) { m_pimpl_->send_size[i] = static_cast<int>(std::get<1>(m_pimpl_->send_box[i])[0] - std::get<0>(m_pimpl_->send_box[i])[0]) * static_cast<int>(std::get<1>(m_pimpl_->send_box[i])[1] - std::get<0>(m_pimpl_->send_box[i])[1]) * static_cast<int>(std::get<1>(m_pimpl_->send_box[i])[2] - std::get<0>(m_pimpl_->send_box[i])[2]); m_pimpl_->recv_size[i] = static_cast<int>(std::get<1>(m_pimpl_->recv_box[i])[0] - std::get<0>(m_pimpl_->recv_box[i])[0]) * static_cast<int>(std::get<1>(m_pimpl_->recv_box[i])[1] - std::get<0>(m_pimpl_->recv_box[i])[1]) * static_cast<int>(std::get<1>(m_pimpl_->recv_box[i])[2] - std::get<0>(m_pimpl_->recv_box[i])[2]); if (m_pimpl_->send_buffer[i] != nullptr) { delete m_pimpl_->send_buffer[i]; } if (m_pimpl_->recv_buffer[i] != nullptr) { delete m_pimpl_->recv_buffer[i]; } if (m_pimpl_->send_size[i] > 0) m_pimpl_->send_buffer[i] = operator new(m_pimpl_->send_size[i] * ele_size); if (m_pimpl_->recv_size[i] > 0) m_pimpl_->recv_buffer[i] = operator new(m_pimpl_->recv_size[i] * ele_size); } for (int i = 0; i < 6; ++i) { GetSendBuffer(i).reset(m_pimpl_->send_buffer[i], &std::get<0>(m_pimpl_->send_box[i])[0], &std::get<1>(m_pimpl_->send_box[i])[0]); GetRecvBuffer(i).reset(m_pimpl_->recv_buffer[i], &std::get<0>(m_pimpl_->recv_box[i])[0], &std::get<1>(m_pimpl_->recv_box[i])[0]); GetSendBuffer(i).Clear(); GetRecvBuffer(i).Clear(); } } void MPIUpdater::TearDown() { for (auto *v : m_pimpl_->send_buffer) { delete v; } for (auto *v : m_pimpl_->recv_buffer) { delete v; } m_pimpl_->m_is_setup_ = false; } void MPIUpdater::SetTag(int tag) { m_pimpl_->tag = tag; } void MPIUpdater::Update(ArrayBase &d) { if (!isSetUp()) { return; } for (int dir = 0; dir < 3; ++dir) { Push(d, dir); SendRecv(dir); Pop(d, dir); } } void MPIUpdater::Push(ArrayBase const &d, int direction) { if (!isSetUp()) { return; } CHECK(GetSendBuffer(2 * direction + 0).CopyIn(d)); GetSendBuffer(2 * direction + 1).CopyIn(d); } void MPIUpdater::Pop(ArrayBase &d, int direction) const { if (!isSetUp()) { return; } CHECK(d.CopyIn(GetRecvBuffer(2 * direction + 0))); d.CopyIn(GetRecvBuffer(2 * direction + 1)); } void MPIUpdater::SendRecv(int d) { if (!isSetUp()) { return; } // for (int d = 0; d < m_pimpl_->mpi_topology_ndims; ++d) { int left, right; MPI_CALL(MPI_Cart_shift(m_pimpl_->comm, d, 1, &left, &right)); GLOBAL_COMM.barrier(); MPI_CALL(MPI_Sendrecv(m_pimpl_->send_buffer[d * 2 + 0], m_pimpl_->send_size[d * 2 + 0], m_pimpl_->ele_type, left, m_pimpl_->tag, m_pimpl_->recv_buffer[d * 2 + 1], m_pimpl_->recv_size[d * 2 + 1], m_pimpl_->ele_type, right, m_pimpl_->tag, m_pimpl_->comm, MPI_STATUS_IGNORE)); GLOBAL_COMM.barrier(); MPI_CALL(MPI_Sendrecv(m_pimpl_->send_buffer[d * 2 + 1], m_pimpl_->send_size[d * 2 + 1], m_pimpl_->ele_type, right, m_pimpl_->tag, m_pimpl_->recv_buffer[d * 2 + 0], m_pimpl_->recv_size[d * 2 + 0], m_pimpl_->ele_type, left, m_pimpl_->tag, m_pimpl_->comm, MPI_STATUS_IGNORE)); GLOBAL_COMM.barrier(); // } } } // namespace parallel { } // namespace simpla {<|endoftext|>
<commit_before>#include <hop_bits/optimisationAlgorithm/covarianceMatrixAdaptationEvolutionStrategy.hpp> namespace hop { CovarianceMatrixAdaptationEvolutionStrategy::CovarianceMatrixAdaptationEvolutionStrategy(const std::shared_ptr<OptimisationProblem> optimisationProblem) : OptimisationAlgorithm(optimisationProblem) { // init input parameters // TODO: iteration number gets multiplied with dimensions² on wiki, also do that here? } void CovarianceMatrixAdaptationEvolutionStrategy::optimiseImplementation() { unsigned int numberOfDimensions = optimisationProblem_->getNumberOfDimensions(); arma::Col<double> objectiveValues = arma::randu<arma::vec>(numberOfDimensions); double sigma = 0.3; double stopValue = 1e-10; //init selection parameters unsigned int lambda = 4 + std::floor(3 * std::log(numberOfDimensions)); double mu = lambda / 2; arma::Col<double> weights = arma::Col<double>(mu); for(std::size_t n = 0; n < weights.n_elem; ++n) { weights.at(n) = std::log(mu + 0.5) - std::log(n); } mu = std::floor(mu); weights = weights / arma::sum(weights); double mueff = std::pow(arma::sum(weights), 2) / arma::sum(arma::square(weights)); //init adaptation parameters double cc = (4 + mueff / numberOfDimensions) / (numberOfDimensions + 4 + 2 * mueff / numberOfDimensions); double cs = (mueff+2) / (numberOfDimensions + mueff + 5); double c1 = 2 / (std::pow(numberOfDimensions + 1.3, 2) + mueff); double cmu = std::min(1 - c1, 2 * (mueff - 2 + 1 / mueff) / (std::pow(numberOfDimensions + 2, 2) + mueff)); double damps = 1 + 2 * std::max(0.0, std::sqrt((mueff - 1) / (numberOfDimensions + 1)) - 1) + cs; //init dynamic parameters and constants arma::Col<double> pc(numberOfDimensions, arma::fill::zeros); arma::Col<double> ps(numberOfDimensions, arma::fill::zeros); arma::Mat<double> B(numberOfDimensions, numberOfDimensions, arma::fill::eye); arma::Col<double> D(numberOfDimensions, arma::fill::ones); arma::Mat<double> C(numberOfDimensions, numberOfDimensions, arma::fill::eye); arma::Mat<double> invsqrtC(numberOfDimensions, numberOfDimensions, arma::fill::eye); double eigeneval = 0; double chiN = std::sqrt(numberOfDimensions) * (1 - 1 / (4 * numberOfDimensions) + 1 / (21 * std::pow(numberOfDimensions, 2))); while(!isFinished() && !isTerminated()) { //generate and evaluate lambda offspring arma::Col<double> arfitness = arma::Col<double>(lambda); arma::Mat<double> arx = arma::Mat<double>(numberOfDimensions, lambda); for(std::size_t n = 0; n < lambda; ++n) { arx.col(n) = objectiveValues + sigma * B * (D % arma::randn<arma::Col<double>>(numberOfDimensions)); arfitness(n) = optimisationProblem_->getObjectiveValue(arx.col(n)); ++numberOfIterations_; } //sort by fitness and compute weighted mean into objectiveValues arma::Col<arma::uword> arindex = arma::sort_index(arfitness); arma::Col<double> oldObjectiveValues = objectiveValues; //next line should be unnecessary, depending on if arma returns a copy or not in the line after that objectiveValues = arma::Col<double>(numberOfDimensions); //TODO: xmean = arx(:,arindex(1:mu))*weights; //is the actual matlab syntax for the following line, not a 100% sure if this is correct objectiveValues = arx.cols(arindex) * weights; //cumulation: update evolution paths ps = (1 - cs) * ps + std::sqrt(cs * (2 - cs) * mueff) * invsqrtC * (objectiveValues - oldObjectiveValues) / sigma; int hsig = arma::norm(ps) / std::sqrt(std::pow(1 - (1 - cs), 2 * numberOfIterations_ / lambda)) / chiN < 1.4 + 2 / (numberOfDimensions + 1); pc = (1 - cc) * pc + hsig * std::sqrt(cc * (2-cc) * mueff) * (objectiveValues - oldObjectiveValues) / sigma; //adapt covariance matrix C arma::Mat<double> artmp = (1 / sigma) * arx.cols(arindex) - arma::repmat(oldObjectiveValues, 1, mu); C = (1-c1-cmu) * C + //old matrix c1 * (pc*pc.t() + //rank one update (1-hsig) * cc * (2-cc) * C) + //correction for hsig==0 cmu * artmp * arma::diagmat(weights) * artmp.t(); // rank mu update //adapt step size sigma sigma = sigma * std::exp((cs / damps) * (arma::norm(ps) / chiN - 1)); //decomposition of C into B*diag(D.^2)*B' (diagonalization) if((numberOfIterations_ - eigeneval) > (lambda / (c1 + cmu) / numberOfIterations_ / 10)) { eigeneval = numberOfIterations_; //TODO: C = triu(C) + triu(C,1)'; //is the actual matlab syntax for the next lines, unfortunately arma doesn't have triu with a second parameter (yet) arma::Mat<double> tempC = arma::trimatu(C); tempC.diag().zeros(); C = arma::trimatu(C) + tempC.t(); //enforce symmetry //matlab code is [B,D] = eig(C); arma uses switched arguments according to API arma::Col<double> tempD = arma::Col<double>(); arma::eig_sym(tempD, B, C); D = arma::sqrt(arma::diagmat(tempD)); // TODO: From wiki "D is a vector of standard deviations now" which it obviously isn't here. // also not sure what the point of that is, since it's going to be used as a matrix in the next line anyway. invsqrtC = B * arma::diagmat(1 / D) * B.t(); } //break, if fitness is good enough or condition exceeds 1e14, better termination methods are advisable if(arfitness.at(1) <= stopValue || D.max() / D.min() > 1e7) { break; } } //while loop has ended //TODO: matlab returns xmin = arx(:, arindex(1)); //not sure where to safe our return value? } std::string CovarianceMatrixAdaptationEvolutionStrategy::to_string() const { return "CovarianceMatrixAdaptationEvolutionStrategy"; } } <commit_msg>devel: Removed extra stop condition<commit_after>#include <hop_bits/optimisationAlgorithm/covarianceMatrixAdaptationEvolutionStrategy.hpp> namespace hop { CovarianceMatrixAdaptationEvolutionStrategy::CovarianceMatrixAdaptationEvolutionStrategy(const std::shared_ptr<OptimisationProblem> optimisationProblem) : OptimisationAlgorithm(optimisationProblem) { // init input parameters // TODO: iteration number gets multiplied with dimensions² on wiki, also do that here? } void CovarianceMatrixAdaptationEvolutionStrategy::optimiseImplementation() { unsigned int numberOfDimensions = optimisationProblem_->getNumberOfDimensions(); arma::Col<double> objectiveValues = arma::randu<arma::vec>(numberOfDimensions); double sigma = 0.3; //init selection parameters unsigned int lambda = 4 + std::floor(3 * std::log(numberOfDimensions)); double mu = lambda / 2; arma::Col<double> weights = arma::Col<double>(mu); for(std::size_t n = 0; n < weights.n_elem; ++n) { weights.at(n) = std::log(mu + 0.5) - std::log(n); } mu = std::floor(mu); weights = weights / arma::sum(weights); double mueff = std::pow(arma::sum(weights), 2) / arma::sum(arma::square(weights)); //init adaptation parameters double cc = (4 + mueff / numberOfDimensions) / (numberOfDimensions + 4 + 2 * mueff / numberOfDimensions); double cs = (mueff+2) / (numberOfDimensions + mueff + 5); double c1 = 2 / (std::pow(numberOfDimensions + 1.3, 2) + mueff); double cmu = std::min(1 - c1, 2 * (mueff - 2 + 1 / mueff) / (std::pow(numberOfDimensions + 2, 2) + mueff)); double damps = 1 + 2 * std::max(0.0, std::sqrt((mueff - 1) / (numberOfDimensions + 1)) - 1) + cs; //init dynamic parameters and constants arma::Col<double> pc(numberOfDimensions, arma::fill::zeros); arma::Col<double> ps(numberOfDimensions, arma::fill::zeros); arma::Mat<double> B(numberOfDimensions, numberOfDimensions, arma::fill::eye); arma::Col<double> D(numberOfDimensions, arma::fill::ones); arma::Mat<double> C(numberOfDimensions, numberOfDimensions, arma::fill::eye); arma::Mat<double> invsqrtC(numberOfDimensions, numberOfDimensions, arma::fill::eye); double eigeneval = 0; double chiN = std::sqrt(numberOfDimensions) * (1 - 1 / (4 * numberOfDimensions) + 1 / (21 * std::pow(numberOfDimensions, 2))); while(!isFinished() && !isTerminated()) { //generate and evaluate lambda offspring arma::Col<double> arfitness = arma::Col<double>(lambda); arma::Mat<double> arx = arma::Mat<double>(numberOfDimensions, lambda); for(std::size_t n = 0; n < lambda; ++n) { arx.col(n) = objectiveValues + sigma * B * (D % arma::randn<arma::Col<double>>(numberOfDimensions)); arfitness(n) = optimisationProblem_->getObjectiveValue(arx.col(n)); ++numberOfIterations_; } //sort by fitness and compute weighted mean into objectiveValues arma::Col<arma::uword> arindex = arma::sort_index(arfitness); arma::Col<double> oldObjectiveValues = objectiveValues; //next line should be unnecessary, depending on if arma returns a copy or not in the line after that objectiveValues = arma::Col<double>(numberOfDimensions); //TODO: xmean = arx(:,arindex(1:mu))*weights; //is the actual matlab syntax for the following line, not a 100% sure if this is correct objectiveValues = arx.cols(arindex) * weights; //cumulation: update evolution paths ps = (1 - cs) * ps + std::sqrt(cs * (2 - cs) * mueff) * invsqrtC * (objectiveValues - oldObjectiveValues) / sigma; int hsig = arma::norm(ps) / std::sqrt(std::pow(1 - (1 - cs), 2 * numberOfIterations_ / lambda)) / chiN < 1.4 + 2 / (numberOfDimensions + 1); pc = (1 - cc) * pc + hsig * std::sqrt(cc * (2-cc) * mueff) * (objectiveValues - oldObjectiveValues) / sigma; //adapt covariance matrix C arma::Mat<double> artmp = (1 / sigma) * arx.cols(arindex) - arma::repmat(oldObjectiveValues, 1, mu); C = (1-c1-cmu) * C + //old matrix c1 * (pc*pc.t() + //rank one update (1-hsig) * cc * (2-cc) * C) + //correction for hsig==0 cmu * artmp * arma::diagmat(weights) * artmp.t(); // rank mu update //adapt step size sigma sigma = sigma * std::exp((cs / damps) * (arma::norm(ps) / chiN - 1)); //decomposition of C into B*diag(D.^2)*B' (diagonalization) if((numberOfIterations_ - eigeneval) > (lambda / (c1 + cmu) / numberOfIterations_ / 10)) { eigeneval = numberOfIterations_; //TODO: C = triu(C) + triu(C,1)'; //is the actual matlab syntax for the next lines, unfortunately arma doesn't have triu with a second parameter (yet) arma::Mat<double> tempC = arma::trimatu(C); tempC.diag().zeros(); C = arma::trimatu(C) + tempC.t(); //enforce symmetry //matlab code is [B,D] = eig(C); arma uses switched arguments according to API arma::Col<double> tempD = arma::Col<double>(); arma::eig_sym(tempD, B, C); D = arma::sqrt(arma::diagmat(tempD)); // TODO: From wiki "D is a vector of standard deviations now" which it obviously isn't here. // also not sure what the point of that is, since it's going to be used as a matrix in the next line anyway. invsqrtC = B * arma::diagmat(1 / D) * B.t(); } } //while loop has ended //TODO: matlab returns xmin = arx(:, arindex(1)); //not sure where to safe our return value? } std::string CovarianceMatrixAdaptationEvolutionStrategy::to_string() const { return "CovarianceMatrixAdaptationEvolutionStrategy"; } } <|endoftext|>
<commit_before>#include <QtTest> #include <QtJsonSerializer> #include "typeconvertertestbase.h" #include <QtJsonSerializer/private/datetimeconverter_p.h> using namespace QtJsonSerializer; using namespace QtJsonSerializer::TypeConverters; class DateTimeConverterTest : public TypeConverterTestBase { Q_OBJECT protected: TypeConverter *converter() override; void addConverterData() override; void addMetaData() override; void addCommonSerData() override; void addSerData() override; void addDeserData() override; private: DateTimeConverter _converter; }; TypeConverter *DateTimeConverterTest::converter() { return &_converter; } void DateTimeConverterTest::addConverterData() { QTest::newRow("datetime") << static_cast<int>(TypeConverter::Standard); } void DateTimeConverterTest::addMetaData() { QTest::newRow("dt.string") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("dt.string.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("dt.string.invalid") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("dt.tstamp") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::UnixTime_t) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("dt.tstamp.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(QCborKnownTags::UnixTime_t) << QCborValue::Integer << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("dt.tstamp.invalid") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::UnixTime_t) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("date.date") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("date.date.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("date.date.invalid") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("date.dt") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("date.dt.invalid") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("time.time") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("time.time.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("time.time.invalid") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("time.dt") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("time.dt.invalid") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("invalid.type") << static_cast<int>(QMetaType::QString) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("invalid.tag.dt") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::WrongTag; QTest::newRow("invalid.tag.date") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::WrongTag; QTest::newRow("invalid.tag.time") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::WrongTag; } void DateTimeConverterTest::addCommonSerData() { QTest::newRow("datetime.string") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{{2019, 1, 3}, {13, 42, 15, 563}}} << QCborValue{QDateTime{{2019, 1, 3}, {13, 42, 15, 563}}} << QJsonValue{QStringLiteral("2019-01-03T13:42:15.563")}; QTest::newRow("datetime.string.empty") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{}} << QCborValue{QDateTime{}} << QJsonValue{QString{}}; QTest::newRow("datetime.string.tag") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{{2019, 1, 3}, {13, 42, 15, 563}}} << QCborValue{QCborKnownTags::DateTimeString, QStringLiteral("2019-01-03T13:42:15.563")} << QJsonValue{QJsonValue::Undefined}; QTest::newRow("datetime.tstamp") << QVariantHash{{QStringLiteral("dateAsTimeStamp"), true}} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{{2019, 1, 3}, {13, 42, 15}}} << QCborValue{QCborKnownTags::UnixTime_t, 1546519335ll} << QJsonValue{1546519335ll}; QTest::newRow("date.datestr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDate) << QVariant{QDate{2019, 1, 3}} << QCborValue{static_cast<QCborTag>(CborSerializer::Date), QStringLiteral("2019-01-03")} << QJsonValue{QStringLiteral("2019-01-03")}; QTest::newRow("date.datestr.empty") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDate) << QVariant{QDate{}} << QCborValue{static_cast<QCborTag>(CborSerializer::Date), QString{}} << QJsonValue{QString{}}; QTest::newRow("time.timestr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QTime) << QVariant{QTime{13, 42, 15, 563}} << QCborValue{static_cast<QCborTag>(CborSerializer::Time), QStringLiteral("13:42:15.563")} << QJsonValue{QStringLiteral("13:42:15.563")}; QTest::newRow("time.timestr.empty") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QTime) << QVariant{QTime{}} << QCborValue{static_cast<QCborTag>(CborSerializer::Time), QString{}} << QJsonValue{QString{}}; } void DateTimeConverterTest::addSerData() { QTest::newRow("datetime.tstamp.empty") << QVariantHash{{QStringLiteral("dateAsTimeStamp"), true}} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{}} << QCborValue{QCborKnownTags::UnixTime_t, 0ll} << QJsonValue{0ll}; } void DateTimeConverterTest::addDeserData() { QTest::newRow("datetime.tstamp.empty") << QVariantHash{{QStringLiteral("dateAsTimeStamp"), true}} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime::fromMSecsSinceEpoch(0, Qt::UTC).toLocalTime()} << QCborValue{QCborKnownTags::UnixTime_t, 0ll} << QJsonValue{0ll}; QTest::newRow("date.dtstr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDate) << QVariant{QDate{2019, 1, 3}} << QCborValue{QCborKnownTags::DateTimeString, QStringLiteral("2019-01-03T00:00:00.000")} << QJsonValue{QJsonValue::Undefined}; QTest::newRow("time.dtstr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QTime) << QVariant{QTime{13, 42, 15, 563}} << QCborValue{QCborKnownTags::DateTimeString, QStringLiteral("1970-01-01T13:42:15.563")} << QJsonValue{QJsonValue::Undefined}; } QTEST_MAIN(DateTimeConverterTest) #include "tst_datetimeconverter.moc" <commit_msg>use utc for timestamp comparison<commit_after>#include <QtTest> #include <QtJsonSerializer> #include "typeconvertertestbase.h" #include <QtJsonSerializer/private/datetimeconverter_p.h> using namespace QtJsonSerializer; using namespace QtJsonSerializer::TypeConverters; class DateTimeConverterTest : public TypeConverterTestBase { Q_OBJECT protected: TypeConverter *converter() override; void addConverterData() override; void addMetaData() override; void addCommonSerData() override; void addSerData() override; void addDeserData() override; private: DateTimeConverter _converter; }; TypeConverter *DateTimeConverterTest::converter() { return &_converter; } void DateTimeConverterTest::addConverterData() { QTest::newRow("datetime") << static_cast<int>(TypeConverter::Standard); } void DateTimeConverterTest::addMetaData() { QTest::newRow("dt.string") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("dt.string.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("dt.string.invalid") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("dt.tstamp") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::UnixTime_t) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("dt.tstamp.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(QCborKnownTags::UnixTime_t) << QCborValue::Integer << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("dt.tstamp.invalid") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(QCborKnownTags::UnixTime_t) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("date.date") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("date.date.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("date.date.invalid") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("date.dt") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("date.dt.invalid") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("time.time") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("time.time.guessed") << static_cast<int>(QMetaType::UnknownType) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Guessed; QTest::newRow("time.time.invalid") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("time.dt") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::Positive; QTest::newRow("time.dt.invalid") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::Integer << true << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("invalid.type") << static_cast<int>(QMetaType::QString) << static_cast<QCborTag>(QCborKnownTags::DateTimeString) << QCborValue::String << false << TypeConverter::DeserializationCapabilityResult::Negative; QTest::newRow("invalid.tag.dt") << static_cast<int>(QMetaType::QDateTime) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::WrongTag; QTest::newRow("invalid.tag.date") << static_cast<int>(QMetaType::QDate) << static_cast<QCborTag>(CborSerializer::Time) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::WrongTag; QTest::newRow("invalid.tag.time") << static_cast<int>(QMetaType::QTime) << static_cast<QCborTag>(CborSerializer::Date) << QCborValue::String << true << TypeConverter::DeserializationCapabilityResult::WrongTag; } void DateTimeConverterTest::addCommonSerData() { QTest::newRow("datetime.string") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{{2019, 1, 3}, {13, 42, 15, 563}}} << QCborValue{QDateTime{{2019, 1, 3}, {13, 42, 15, 563}}} << QJsonValue{QStringLiteral("2019-01-03T13:42:15.563")}; QTest::newRow("datetime.string.empty") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{}} << QCborValue{QDateTime{}} << QJsonValue{QString{}}; QTest::newRow("datetime.string.tag") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{{2019, 1, 3}, {13, 42, 15, 563}}} << QCborValue{QCborKnownTags::DateTimeString, QStringLiteral("2019-01-03T13:42:15.563")} << QJsonValue{QJsonValue::Undefined}; QTest::newRow("datetime.tstamp") << QVariantHash{{QStringLiteral("dateAsTimeStamp"), true}} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{{2019, 1, 3}, {13, 42, 15}, Qt::UTC}} << QCborValue{QCborKnownTags::UnixTime_t, 1546522935ll} << QJsonValue{1546522935ll}; QTest::newRow("date.datestr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDate) << QVariant{QDate{2019, 1, 3}} << QCborValue{static_cast<QCborTag>(CborSerializer::Date), QStringLiteral("2019-01-03")} << QJsonValue{QStringLiteral("2019-01-03")}; QTest::newRow("date.datestr.empty") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDate) << QVariant{QDate{}} << QCborValue{static_cast<QCborTag>(CborSerializer::Date), QString{}} << QJsonValue{QString{}}; QTest::newRow("time.timestr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QTime) << QVariant{QTime{13, 42, 15, 563}} << QCborValue{static_cast<QCborTag>(CborSerializer::Time), QStringLiteral("13:42:15.563")} << QJsonValue{QStringLiteral("13:42:15.563")}; QTest::newRow("time.timestr.empty") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QTime) << QVariant{QTime{}} << QCborValue{static_cast<QCborTag>(CborSerializer::Time), QString{}} << QJsonValue{QString{}}; } void DateTimeConverterTest::addSerData() { QTest::newRow("datetime.tstamp.empty") << QVariantHash{{QStringLiteral("dateAsTimeStamp"), true}} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime{}} << QCborValue{QCborKnownTags::UnixTime_t, 0ll} << QJsonValue{0ll}; } void DateTimeConverterTest::addDeserData() { QTest::newRow("datetime.tstamp.empty") << QVariantHash{{QStringLiteral("dateAsTimeStamp"), true}} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDateTime) << QVariant{QDateTime::fromMSecsSinceEpoch(0, Qt::UTC).toLocalTime()} << QCborValue{QCborKnownTags::UnixTime_t, 0ll} << QJsonValue{0ll}; QTest::newRow("date.dtstr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QDate) << QVariant{QDate{2019, 1, 3}} << QCborValue{QCborKnownTags::DateTimeString, QStringLiteral("2019-01-03T00:00:00.000")} << QJsonValue{QJsonValue::Undefined}; QTest::newRow("time.dtstr") << QVariantHash{} << TestQ{} << static_cast<QObject*>(nullptr) << static_cast<int>(QMetaType::QTime) << QVariant{QTime{13, 42, 15, 563}} << QCborValue{QCborKnownTags::DateTimeString, QStringLiteral("1970-01-01T13:42:15.563")} << QJsonValue{QJsonValue::Undefined}; } QTEST_MAIN(DateTimeConverterTest) #include "tst_datetimeconverter.moc" <|endoftext|>
<commit_before>#include <catch2/catch.hpp> #include "manipulator/manipulators/mouse_motion_to_scroll/count_converter.hpp" TEST_CASE("count_converter::update") { krbn::manipulator::manipulators::mouse_motion_to_scroll::count_converter c(8); REQUIRE(c.update(0) == 0); REQUIRE(c.update(8) == 1); REQUIRE(c.update(16) == 2); for (int i = 0; i < 10; ++i) { for (int j = 0; j < 7; ++j) { REQUIRE(c.update(1) == 0); } REQUIRE(c.update(1) == 1); } } TEST_CASE("count_converter::make_momentum_value") { krbn::manipulator::manipulators::mouse_motion_to_scroll::count_converter c(8); REQUIRE(c.make_momentum_value() == 0); { c.reset(); c.update(16); std::vector<int> values{8, 6, 5, 4, 3, 3, 3, 3, 2, 1, 1, 1, 1, 0}; for (const auto v : values) { REQUIRE(c.make_momentum_value() == v); c.update(c.make_momentum_value()); } } // Fill zero before update { c.reset(); for (int i = 0; i < 8; ++i) { c.update(0); } c.update(8); REQUIRE(c.make_momentum_value() == 0); c.update(8); REQUIRE(c.make_momentum_value() == 1); c.update(8); REQUIRE(c.make_momentum_value() == 1); c.update(8); REQUIRE(c.make_momentum_value() == 2); } } <commit_msg>update tests<commit_after>#include <catch2/catch.hpp> #include "manipulator/manipulators/mouse_motion_to_scroll/count_converter.hpp" TEST_CASE("count_converter::update") { krbn::manipulator::manipulators::mouse_motion_to_scroll::count_converter c(8); REQUIRE(c.update(0) == 0); REQUIRE(c.update(8) == 1); REQUIRE(c.update(16) == 2); for (int i = 0; i < 10; ++i) { for (int j = 0; j < 7; ++j) { REQUIRE(c.update(1) == 0); } REQUIRE(c.update(1) == 1); } c.reset(); REQUIRE(c.update(-8) == -1); REQUIRE(c.update(-16) == -2); for (int i = 0; i < 10; ++i) { for (int j = 0; j < 7; ++j) { REQUIRE(c.update(-1) == 0); } REQUIRE(c.update(-1) == -1); } } TEST_CASE("count_converter::make_momentum_value") { krbn::manipulator::manipulators::mouse_motion_to_scroll::count_converter c(8); REQUIRE(c.make_momentum_value() == 0); { c.reset(); c.update(16); std::vector<int> values{8, 6, 5, 4, 3, 3, 3, 3, 2, 1, 1, 1, 1, 0}; for (const auto v : values) { REQUIRE(c.make_momentum_value() == v); c.update(c.make_momentum_value()); } } // Fill zero before update { c.reset(); for (int i = 0; i < 8; ++i) { c.update(0); } c.update(8); REQUIRE(c.make_momentum_value() == 0); c.update(8); REQUIRE(c.make_momentum_value() == 1); c.update(8); REQUIRE(c.make_momentum_value() == 1); c.update(8); REQUIRE(c.make_momentum_value() == 2); } } <|endoftext|>
<commit_before>#include "UASQuickViewTextItem.h" #include "QsLog.h" #include <QVBoxLayout> UASQuickViewTextItem::UASQuickViewTextItem(QWidget *parent) : UASQuickViewItem(parent) { QVBoxLayout *layout = new QVBoxLayout(); this->setLayout(layout); layout->setSpacing(0); layout->setMargin(0); titleLabel = new QLabel(this); //titleLabel->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored); titleLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom); this->layout()->addWidget(titleLabel); valueLabel = new QLabel(this); //valueLabel->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored); valueLabel->setAlignment(Qt::AlignHCenter | Qt::AlignTop); valueLabel->setText("0.00"); this->layout()->addWidget(valueLabel); //spacerItem = new QSpacerItem(20,40,QSizePolicy::Minimum,QSizePolicy::Ignored); //layout->addSpacerItem(spacerItem); QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(this->height() / 2.0); titlefont.setPixelSize(this->height() / 4.0); valueLabel->setFont(valuefont); titleLabel->setFont(titlefont); } QString UASQuickViewTextItem::value() { return valueLabel->text(); } QString UASQuickViewTextItem::title() { return titleLabel->text(); } void UASQuickViewTextItem::setValue(double value) { if (value < 10 && value > -10) { valueLabel->setText(QString::number(value,'f',2)); } else if (value < 100 && value > -100) { valueLabel->setText(QString::number(value,'f',2)); } else if (value < 1000 && value > -1000) { valueLabel->setText(QString::number(value,'f',1)); } else if (value < 10000 && value > -10000) { valueLabel->setText(QString::number(value,'f',1)); } else if (value >= 100000 || value <= -100000) { valueLabel->setText(QString::number(value,'f',0)); } } void UASQuickViewTextItem::setTitle(QString title) { if (title.indexOf(".") != -1 && title.indexOf(":") != -1) { titleLabel->setText(title.mid(title.indexOf(".")+1)); } else { titleLabel->setText(title); } } int UASQuickViewTextItem::minValuePixelSize() { QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(this->height()); titlefont.setPixelSize(valuefont.pixelSize() / 1.3); //spacerItem->setGeometry(QRect(0,0,20,this->height()/10.0)); QFontMetrics metrics(valuefont); //valuefont.setPixelSize(this->height() / 2.0); bool fit = false; while (!fit) { QFontMetrics valfm( valuefont ); QRect valbound = valfm.boundingRect(0,0, valueLabel->width(), valueLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, "45678.00"/*valueLabel->text()*/); //QFontMetrics titlefm( titlefont ); //QRect titlebound = titlefm.boundingRect(0,0, titleLabel->width(), titleLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, titleLabel->text()); if ((valbound.width() <= valueLabel->width() && valbound.height() <= valueLabel->height()))// && (titlebound.width() <= titleLabel->width() && titlebound.height() <= titleLabel->height())) fit = true; else { if (valuefont.pixelSize()-5 <= 0) { fit = true; valuefont.setPixelSize(5); } else { valuefont.setPixelSize(valuefont.pixelSize() - 5); } //titlefont.setPixelSize(valuefont.pixelSize() / 2.0); QLOG_TRACE() << "Point size:" << valuefont.pixelSize() << valueLabel->width() << valueLabel->height(); } } return valuefont.pixelSize(); } void UASQuickViewTextItem::setValuePixelSize(int size) { QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(size); titlefont.setPixelSize(valuefont.pixelSize() / 1.3); valueLabel->setFont(valuefont); titleLabel->setFont(titlefont); update(); } void UASQuickViewTextItem::resizeEvent(QResizeEvent *event) { return; QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(this->height()); titlefont.setPixelSize(valuefont.pixelSize() / 1.6); //spacerItem->setGeometry(QRect(0,0,20,this->height()/10.0)); QFontMetrics metrics(valuefont); //valuefont.setPixelSize(this->height() / 2.0); bool fit = false; while (!fit) { QFontMetrics valfm( valuefont ); QRect valbound = valfm.boundingRect(0,0, valueLabel->width(), valueLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, valueLabel->text()); //QFontMetrics titlefm( titlefont ); //QRect titlebound = titlefm.boundingRect(0,0, titleLabel->width(), titleLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, titleLabel->text()); if ((valbound.width() <= valueLabel->width() && valbound.height() <= valueLabel->height()))// && (titlebound.width() <= titleLabel->width() && titlebound.height() <= titleLabel->height())) fit = true; else { if (valuefont.pixelSize()-5 <= 0) { fit = true; valuefont.setPixelSize(5); } else { valuefont.setPixelSize(valuefont.pixelSize() - 5); } //titlefont.setPixelSize(valuefont.pixelSize() / 2.0); QLOG_TRACE() << "Point size:" << valuefont.pixelSize() << valueLabel->width() << valueLabel->height(); } } titlefont.setPixelSize(valuefont.pixelSize() / 1.6); valueLabel->setFont(valuefont); titleLabel->setFont(titlefont); update(); } <commit_msg>Fixed values being 0.00 if they are over 10,000 in UASQuickView text items<commit_after>#include "UASQuickViewTextItem.h" #include "QsLog.h" #include <QVBoxLayout> UASQuickViewTextItem::UASQuickViewTextItem(QWidget *parent) : UASQuickViewItem(parent) { QVBoxLayout *layout = new QVBoxLayout(); this->setLayout(layout); layout->setSpacing(0); layout->setMargin(0); titleLabel = new QLabel(this); //titleLabel->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored); titleLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom); this->layout()->addWidget(titleLabel); valueLabel = new QLabel(this); //valueLabel->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored); valueLabel->setAlignment(Qt::AlignHCenter | Qt::AlignTop); valueLabel->setText("0.00"); this->layout()->addWidget(valueLabel); //spacerItem = new QSpacerItem(20,40,QSizePolicy::Minimum,QSizePolicy::Ignored); //layout->addSpacerItem(spacerItem); QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(this->height() / 2.0); titlefont.setPixelSize(this->height() / 4.0); valueLabel->setFont(valuefont); titleLabel->setFont(titlefont); } QString UASQuickViewTextItem::value() { return valueLabel->text(); } QString UASQuickViewTextItem::title() { return titleLabel->text(); } void UASQuickViewTextItem::setValue(double value) { if (value < 10 && value > -10) { valueLabel->setText(QString::number(value,'f',2)); } else if (value < 100 && value > -100) { valueLabel->setText(QString::number(value,'f',2)); } else if (value < 1000 && value > -1000) { valueLabel->setText(QString::number(value,'f',1)); } else if (value < 10000 && value > -10000) { valueLabel->setText(QString::number(value,'f',1)); } else { valueLabel->setText(QString::number(value,'f',0)); } } void UASQuickViewTextItem::setTitle(QString title) { if (title.indexOf(".") != -1 && title.indexOf(":") != -1) { titleLabel->setText(title.mid(title.indexOf(".")+1)); } else { titleLabel->setText(title); } } int UASQuickViewTextItem::minValuePixelSize() { QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(this->height()); titlefont.setPixelSize(valuefont.pixelSize() / 1.3); //spacerItem->setGeometry(QRect(0,0,20,this->height()/10.0)); QFontMetrics metrics(valuefont); //valuefont.setPixelSize(this->height() / 2.0); bool fit = false; while (!fit) { QFontMetrics valfm( valuefont ); QRect valbound = valfm.boundingRect(0,0, valueLabel->width(), valueLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, "45678.00"/*valueLabel->text()*/); //QFontMetrics titlefm( titlefont ); //QRect titlebound = titlefm.boundingRect(0,0, titleLabel->width(), titleLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, titleLabel->text()); if ((valbound.width() <= valueLabel->width() && valbound.height() <= valueLabel->height()))// && (titlebound.width() <= titleLabel->width() && titlebound.height() <= titleLabel->height())) fit = true; else { if (valuefont.pixelSize()-5 <= 0) { fit = true; valuefont.setPixelSize(5); } else { valuefont.setPixelSize(valuefont.pixelSize() - 5); } //titlefont.setPixelSize(valuefont.pixelSize() / 2.0); QLOG_TRACE() << "Point size:" << valuefont.pixelSize() << valueLabel->width() << valueLabel->height(); } } return valuefont.pixelSize(); } void UASQuickViewTextItem::setValuePixelSize(int size) { QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(size); titlefont.setPixelSize(valuefont.pixelSize() / 1.3); valueLabel->setFont(valuefont); titleLabel->setFont(titlefont); update(); } void UASQuickViewTextItem::resizeEvent(QResizeEvent *event) { return; QFont valuefont = valueLabel->font(); QFont titlefont = titleLabel->font(); valuefont.setPixelSize(this->height()); titlefont.setPixelSize(valuefont.pixelSize() / 1.6); //spacerItem->setGeometry(QRect(0,0,20,this->height()/10.0)); QFontMetrics metrics(valuefont); //valuefont.setPixelSize(this->height() / 2.0); bool fit = false; while (!fit) { QFontMetrics valfm( valuefont ); QRect valbound = valfm.boundingRect(0,0, valueLabel->width(), valueLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, valueLabel->text()); //QFontMetrics titlefm( titlefont ); //QRect titlebound = titlefm.boundingRect(0,0, titleLabel->width(), titleLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, titleLabel->text()); if ((valbound.width() <= valueLabel->width() && valbound.height() <= valueLabel->height()))// && (titlebound.width() <= titleLabel->width() && titlebound.height() <= titleLabel->height())) fit = true; else { if (valuefont.pixelSize()-5 <= 0) { fit = true; valuefont.setPixelSize(5); } else { valuefont.setPixelSize(valuefont.pixelSize() - 5); } //titlefont.setPixelSize(valuefont.pixelSize() / 2.0); QLOG_TRACE() << "Point size:" << valuefont.pixelSize() << valueLabel->width() << valueLabel->height(); } } titlefont.setPixelSize(valuefont.pixelSize() / 1.6); valueLabel->setFont(valuefont); titleLabel->setFont(titlefont); update(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/scom/handleSpecialWakeup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2018 */ /* [+] 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 */ #include <stdint.h> #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <errl/errludtarget.H> #include <trace/interface.H> #include <targeting/common/commontargeting.H> #include <targeting/common/targetservice.H> #include <targeting/common/utilFilter.H> #include <targeting/common/util.H> #include <scom/scomreasoncodes.H> #include <initservice/initserviceif.H> #ifdef __HOSTBOOT_RUNTIME #include <runtime/rt_targeting.H> #include <runtime/interface.h> #endif // __HOSTBOOT_RUNTIME #include <fapi2/plat_hwp_invoker.H> #include <p9_cpu_special_wakeup.H> extern "C" { // Trace definition extern trace_desc_t* g_trac_scom; using namespace TARGETING; using namespace SCOM; /** * @brief Enable and disable special wakeup for SCOM operations * FSP: Call the Host interface wakeup function for all core * targets under the specified target, HOST wakeup bit is used * BMC: Call the wakeup HWP for the target type specified (EQ/EX/CORE), * Proc type calls the HWP for all cores, FSP wakeup bit is used */ errlHndl_t handleSpecialWakeup(TARGETING::Target* i_target, bool i_enable) { errlHndl_t l_errl = NULL; fapi2::ReturnCode l_rc; TARGETING::TYPE l_type = i_target->getAttr<TARGETING::ATTR_TYPE>(); #ifdef __HOSTBOOT_RUNTIME // FSP if(INITSERVICE::spBaseServicesEnabled()) { // Check for valid interface function if( g_hostInterfaces == NULL || g_hostInterfaces->wakeup == NULL ) { TRACFCOMP( g_trac_scom, ERR_MRK"Hypervisor wakeup interface not linked"); /*@ * @errortype * @moduleid SCOM_HANDLE_SPECIAL_WAKEUP * @reasoncode SCOM_RUNTIME_INTERFACE_ERR * @userdata1 Target HUID * @userdata2 Wakeup Enable * @devdesc Wakeup runtime interface not linked. */ l_errl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_INFORMATIONAL, SCOM_HANDLE_SPECIAL_WAKEUP, SCOM_RUNTIME_INTERFACE_ERR, get_huid(i_target), i_enable); l_errl->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); return l_errl; } TargetHandleList pCoreList; // If the target is already a core just push it on the list if(l_type == TARGETING::TYPE_CORE) { pCoreList.clear(); pCoreList.push_back(i_target); } else { getChildChiplets( pCoreList, i_target, TARGETING::TYPE_CORE ); } // Call wakeup on all core targets // Wakeup may be called twice for fused cores for ( auto pCore_it = pCoreList.begin(); pCore_it != pCoreList.end(); ++pCore_it ) { // Runtime target id RT_TARG::rtChipId_t rtTargetId = 0; l_errl = RT_TARG::getRtTarget(*pCore_it, rtTargetId); if(l_errl) { break; } uint32_t mode; if(i_enable) { mode = HBRT_WKUP_FORCE_AWAKE; } else { mode = HBRT_WKUP_CLEAR_FORCE; } // Do the special wakeup int l_rc = g_hostInterfaces->wakeup(rtTargetId,mode); if(l_rc) { TRACFCOMP( g_trac_scom,ERR_MRK "Hypervisor wakeup failed. " "rc 0x%X target_huid 0x%llX rt_target_id 0x%llX mode %d", l_rc, get_huid(*pCore_it), rtTargetId, mode ); // convert rc to error log /*@ * @errortype * @moduleid SCOM_HANDLE_SPECIAL_WAKEUP * @reasoncode SCOM_RUNTIME_WAKEUP_ERR * @userdata1 Hypervisor return code * @userdata2[0:31] Runtime Target ID * @userdata2[32:63] Wakeup Mode * @devdesc Hypervisor wakeup failed. */ l_errl = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_INFORMATIONAL, SCOM_HANDLE_SPECIAL_WAKEUP, SCOM_RUNTIME_WAKEUP_ERR, l_rc, TWO_UINT32_TO_UINT64( rtTargetId, mode)); l_errl->addHwCallout(i_target, HWAS::SRCI_PRIORITY_LOW, HWAS::NO_DECONFIG, HWAS::GARD_NULL); break; } } } // BMC else { #endif // __HOSTBOOT_RUNTIME if(l_type == TARGETING::TYPE_PROC) { // Call wakeup on all core targets TargetHandleList pCoreList; getChildChiplets( pCoreList, i_target, TARGETING::TYPE_CORE ); for ( auto pCore_it = pCoreList.begin(); pCore_it != pCoreList.end(); ++pCore_it ) { // To simplify, just call recursively with the core target l_errl = handleSpecialWakeup(*pCore_it, i_enable); if(l_errl) { break; } } return l_errl; } // Need to handle multiple calls to enable special wakeup // Count attribute will keep track and disable when zero // Assume HBRT is single-threaded, so no issues with concurrency uint32_t l_count = (i_target)->getAttr<ATTR_SPCWKUP_COUNT>(); if((l_count==0) && !i_enable) { TRACFCOMP( g_trac_scom,ERR_MRK "Disabling special wakeup on target with SPCWKUP_COUNT=0"); /*@ * @errortype * @moduleid SCOM_HANDLE_SPECIAL_WAKEUP * @reasoncode SCOM_SPCWKUP_COUNT_ERR * @userdata1 Target HUID * @userdata2[0:31] Wakeup Enable * @userdata2[32:63] Wakeup Count * @devdesc Disabling special wakeup when not enabled. */ l_errl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_INFORMATIONAL, SCOM_HANDLE_SPECIAL_WAKEUP, SCOM_SPCWKUP_COUNT_ERR, get_huid(i_target), TWO_UINT32_TO_UINT64( i_enable, l_count)); l_errl->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_LOW); errlCommit( l_errl, RUNTIME_COMP_ID ); } // Only call the HWP if 0-->1 or 1-->0 if( ((l_count==0) && i_enable) || ((l_count==1) && !i_enable) ) { // NOTE Regarding the entity type passed to the HWP: // There are 3 independent registers used to trigger a // special wakeup (FSP,HOST,OCC), we are using the FSP // bit because HOST/OCC are already in use. p9specialWakeup::PROC_SPCWKUP_OPS l_spcwkupType; p9specialWakeup::PROC_SPCWKUP_ENTITY l_spcwkupSrc; if(! INITSERVICE::spBaseServicesEnabled()) { l_spcwkupSrc = p9specialWakeup::FSP; } else { l_spcwkupSrc = p9specialWakeup::HOST; } if(i_enable) { l_spcwkupType = p9specialWakeup::SPCWKUP_ENABLE; } else { l_spcwkupType = p9specialWakeup::SPCWKUP_DISABLE; } if(l_type == TARGETING::TYPE_EQ) { fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapi_target(const_cast<TARGETING::Target*>(i_target)); FAPI_EXEC_HWP(l_rc, p9_cpu_special_wakeup_eq, l_fapi_target, l_spcwkupType, l_spcwkupSrc ); l_errl = rcToErrl(l_rc, ERRORLOG::ERRL_SEV_UNRECOVERABLE); } else if(l_type == TARGETING::TYPE_EX) { fapi2::Target<fapi2::TARGET_TYPE_EX_CHIPLET> l_fapi_target(const_cast<TARGETING::Target*>(i_target)); FAPI_EXEC_HWP(l_rc, p9_cpu_special_wakeup_ex, l_fapi_target, l_spcwkupType, l_spcwkupSrc ); l_errl = rcToErrl(l_rc, ERRORLOG::ERRL_SEV_UNRECOVERABLE); } else if(l_type == TARGETING::TYPE_CORE) { fapi2::Target<fapi2::TARGET_TYPE_CORE> l_fapi_target(const_cast<TARGETING::Target*>(i_target)); FAPI_EXEC_HWP(l_rc, p9_cpu_special_wakeup_core, l_fapi_target, l_spcwkupType, l_spcwkupSrc ); l_errl = rcToErrl(l_rc, ERRORLOG::ERRL_SEV_UNRECOVERABLE); } if(l_errl) { TRACFCOMP( g_trac_scom, "p9_cpu_special_wakeup ERROR :" " Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // Capture the target data in the elog ERRORLOG::ErrlUserDetailsTarget(i_target).addToLog( l_errl ); } } // Update the counter if(!l_errl) { if(i_enable) { l_count++; } else { l_count--; } i_target->setAttr<ATTR_SPCWKUP_COUNT>(l_count); } #ifdef __HOSTBOOT_RUNTIME } #endif return l_errl; } } <commit_msg>Use hostservice to do special wakeup at runtime for open-power systems<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/scom/handleSpecialWakeup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2018 */ /* [+] 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 */ #include <stdint.h> #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <errl/errludtarget.H> #include <trace/interface.H> #include <targeting/common/commontargeting.H> #include <targeting/common/targetservice.H> #include <targeting/common/utilFilter.H> #include <targeting/common/util.H> #include <scom/scomreasoncodes.H> #include <initservice/initserviceif.H> #ifdef __HOSTBOOT_RUNTIME #include <runtime/rt_targeting.H> #include <runtime/interface.h> #endif // __HOSTBOOT_RUNTIME #include <fapi2/plat_hwp_invoker.H> #include <p9_cpu_special_wakeup.H> extern "C" { // Trace definition extern trace_desc_t* g_trac_scom; using namespace TARGETING; using namespace SCOM; /** * @brief Enable and disable special wakeup for SCOM operations * FSP: Call the Host interface wakeup function for all core * targets under the specified target, HOST wakeup bit is used * BMC: Call the wakeup HWP for the target type specified (EQ/EX/CORE), * Proc type calls the HWP for all cores, FSP wakeup bit is used */ errlHndl_t handleSpecialWakeup(TARGETING::Target* i_target, bool i_enable) { errlHndl_t l_errl = NULL; fapi2::ReturnCode l_rc; TARGETING::TYPE l_type = i_target->getAttr<TARGETING::ATTR_TYPE>(); #ifdef __HOSTBOOT_RUNTIME // FSP and BMC runtime use hostservice for wakeup // Check for valid interface function if( g_hostInterfaces == NULL || g_hostInterfaces->wakeup == NULL ) { TRACFCOMP( g_trac_scom, ERR_MRK"Hypervisor wakeup interface not linked"); /*@ * @errortype * @moduleid SCOM_HANDLE_SPECIAL_WAKEUP * @reasoncode SCOM_RUNTIME_INTERFACE_ERR * @userdata1 Target HUID * @userdata2 Wakeup Enable * @devdesc Wakeup runtime interface not linked. */ l_errl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_INFORMATIONAL, SCOM_HANDLE_SPECIAL_WAKEUP, SCOM_RUNTIME_INTERFACE_ERR, get_huid(i_target), i_enable); l_errl->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); return l_errl; } TargetHandleList pCoreList; // If the target is already a core just push it on the list if(l_type == TARGETING::TYPE_CORE) { pCoreList.clear(); pCoreList.push_back(i_target); } else { getChildChiplets( pCoreList, i_target, TARGETING::TYPE_CORE ); } // Call wakeup on all core targets // Wakeup may be called twice for fused cores for ( auto pCore_it = pCoreList.begin(); pCore_it != pCoreList.end(); ++pCore_it ) { // Runtime target id RT_TARG::rtChipId_t rtTargetId = 0; l_errl = RT_TARG::getRtTarget(*pCore_it, rtTargetId); if(l_errl) { break; } uint32_t mode; if(i_enable) { mode = HBRT_WKUP_FORCE_AWAKE; } else { mode = HBRT_WKUP_CLEAR_FORCE; } // Do the special wakeup int l_rc = g_hostInterfaces->wakeup(rtTargetId,mode); if(l_rc) { TRACFCOMP( g_trac_scom,ERR_MRK "Hypervisor wakeup failed. " "rc 0x%X target_huid 0x%llX rt_target_id 0x%llX mode %d", l_rc, get_huid(*pCore_it), rtTargetId, mode ); // convert rc to error log /*@ * @errortype * @moduleid SCOM_HANDLE_SPECIAL_WAKEUP * @reasoncode SCOM_RUNTIME_WAKEUP_ERR * @userdata1 Hypervisor return code * @userdata2[0:31] Runtime Target ID * @userdata2[32:63] Wakeup Mode * @devdesc Hypervisor wakeup failed. */ l_errl = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_INFORMATIONAL, SCOM_HANDLE_SPECIAL_WAKEUP, SCOM_RUNTIME_WAKEUP_ERR, l_rc, TWO_UINT32_TO_UINT64( rtTargetId, mode)); l_errl->addHwCallout(i_target, HWAS::SRCI_PRIORITY_LOW, HWAS::NO_DECONFIG, HWAS::GARD_NULL); break; } } #else // IPL time so use HWP for wakeup if(l_type == TARGETING::TYPE_PROC) { // Call wakeup on all core targets TargetHandleList pCoreList; getChildChiplets( pCoreList, i_target, TARGETING::TYPE_CORE ); for ( auto pCore_it = pCoreList.begin(); pCore_it != pCoreList.end(); ++pCore_it ) { // To simplify, just call recursively with the core target l_errl = handleSpecialWakeup(*pCore_it, i_enable); if(l_errl) { break; } } return l_errl; } // Need to handle multiple calls to enable special wakeup // Count attribute will keep track and disable when zero // Assume HBRT is single-threaded, so no issues with concurrency uint32_t l_count = (i_target)->getAttr<ATTR_SPCWKUP_COUNT>(); if((l_count==0) && !i_enable) { TRACFCOMP( g_trac_scom,ERR_MRK "Disabling special wakeup on target with SPCWKUP_COUNT=0"); /*@ * @errortype * @moduleid SCOM_HANDLE_SPECIAL_WAKEUP * @reasoncode SCOM_SPCWKUP_COUNT_ERR * @userdata1 Target HUID * @userdata2[0:31] Wakeup Enable * @userdata2[32:63] Wakeup Count * @devdesc Disabling special wakeup when not enabled. */ l_errl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_INFORMATIONAL, SCOM_HANDLE_SPECIAL_WAKEUP, SCOM_SPCWKUP_COUNT_ERR, get_huid(i_target), TWO_UINT32_TO_UINT64( i_enable, l_count)); l_errl->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_LOW); errlCommit( l_errl, RUNTIME_COMP_ID ); } // Only call the HWP if 0-->1 or 1-->0 if( ((l_count==0) && i_enable) || ((l_count==1) && !i_enable) ) { // NOTE Regarding the entity type passed to the HWP: // There are 3 independent registers used to trigger a // special wakeup (FSP,HOST,OCC), we are using the FSP // bit because HOST/OCC are already in use. p9specialWakeup::PROC_SPCWKUP_OPS l_spcwkupType; p9specialWakeup::PROC_SPCWKUP_ENTITY l_spcwkupSrc; if(! INITSERVICE::spBaseServicesEnabled()) { l_spcwkupSrc = p9specialWakeup::FSP; } else { l_spcwkupSrc = p9specialWakeup::HOST; } if(i_enable) { l_spcwkupType = p9specialWakeup::SPCWKUP_ENABLE; } else { l_spcwkupType = p9specialWakeup::SPCWKUP_DISABLE; } if(l_type == TARGETING::TYPE_EQ) { fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapi_target(const_cast<TARGETING::Target*>(i_target)); FAPI_EXEC_HWP(l_rc, p9_cpu_special_wakeup_eq, l_fapi_target, l_spcwkupType, l_spcwkupSrc ); l_errl = rcToErrl(l_rc, ERRORLOG::ERRL_SEV_UNRECOVERABLE); } else if(l_type == TARGETING::TYPE_EX) { fapi2::Target<fapi2::TARGET_TYPE_EX_CHIPLET> l_fapi_target(const_cast<TARGETING::Target*>(i_target)); FAPI_EXEC_HWP(l_rc, p9_cpu_special_wakeup_ex, l_fapi_target, l_spcwkupType, l_spcwkupSrc ); l_errl = rcToErrl(l_rc, ERRORLOG::ERRL_SEV_UNRECOVERABLE); } else if(l_type == TARGETING::TYPE_CORE) { fapi2::Target<fapi2::TARGET_TYPE_CORE> l_fapi_target(const_cast<TARGETING::Target*>(i_target)); FAPI_EXEC_HWP(l_rc, p9_cpu_special_wakeup_core, l_fapi_target, l_spcwkupType, l_spcwkupSrc ); l_errl = rcToErrl(l_rc, ERRORLOG::ERRL_SEV_UNRECOVERABLE); } if(l_errl) { TRACFCOMP( g_trac_scom, "p9_cpu_special_wakeup ERROR :" " Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // Capture the target data in the elog ERRORLOG::ErrlUserDetailsTarget(i_target).addToLog( l_errl ); } } // Update the counter if(!l_errl) { if(i_enable) { l_count++; } else { l_count--; } i_target->setAttr<ATTR_SPCWKUP_COUNT>(l_count); } #endif // __HOSTBOOT_RUNTIME return l_errl; } } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // Copyright 2006 Carnegie Mellon University. All rights reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file COPYING at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // // __END_LICENSE__ /// \file DiskImageResource.cc /// /// An abstract base class referring to an image on disk. /// #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #include <vw/config.h> #include <iostream> #include <map> #include <boost/algorithm/string.hpp> #include <vw/FileIO/DiskImageResource.h> #include <vw/FileIO/DiskImageResourcePDS.h> #if defined(VW_HAVE_PKG_PNG) && VW_HAVE_PKG_PNG==1 #include <vw/FileIO/DiskImageResourcePNG.h> #endif #if defined(VW_HAVE_PKG_JPEG) && VW_HAVE_PKG_JPEG==1 #include <vw/FileIO/DiskImageResourceJPEG.h> #endif #if defined(VW_HAVE_PKG_TIFF) && VW_HAVE_PKG_TIFF==1 #include <vw/FileIO/DiskImageResourceTIFF.h> #endif #if defined(VW_HAVE_PKG_OPENEXR) && VW_HAVE_PKG_OPENEXR==1 #include <vw/FileIO/DiskImageResourceOpenEXR.h> #endif namespace { typedef std::map<std::string,vw::DiskImageResource::construct_open_func> OpenMapType; typedef std::map<std::string,vw::DiskImageResource::construct_create_func> CreateMapType; OpenMapType *open_map = 0; CreateMapType *create_map = 0; } void vw::DiskImageResource::register_file_type( std::string const& extension, vw::DiskImageResource::construct_open_func open_func, vw::DiskImageResource::construct_create_func create_func ) { if( ! open_map ) open_map = new OpenMapType(); if( ! create_map ) create_map = new CreateMapType(); open_map->insert( std::make_pair( extension, open_func ) ); create_map->insert( std::make_pair( extension, create_func ) ); } static std::string file_extension( std::string const& filename ) { std::string::size_type dot = filename.find_last_of('.'); if (dot != std::string::npos) { std::string extension = filename.substr( dot ); boost::to_lower( extension ); return extension; } else { throw vw::IOErr() << "DiskImageResource: Cannot infer file format from filename with no file extension."; } } static void register_default_file_types() { static bool already = false; if( already ) return; already = true; vw::DiskImageResource::register_file_type( ".img", &vw::DiskImageResourcePDS::construct_open, &vw::DiskImageResourcePDS::construct_create ); #if defined(VW_HAVE_PKG_PNG) && VW_HAVE_PKG_PNG==1 vw::DiskImageResource::register_file_type( ".png", &vw::DiskImageResourcePNG::construct_open, &vw::DiskImageResourcePNG::construct_create ); #endif #if defined(VW_HAVE_PKG_JPEG) && VW_HAVE_PKG_JPEG==1 vw::DiskImageResource::register_file_type( ".jpg", &vw::DiskImageResourceJPEG::construct_open, &vw::DiskImageResourceJPEG::construct_create ); vw::DiskImageResource::register_file_type( ".jpeg", &vw::DiskImageResourceJPEG::construct_open, &vw::DiskImageResourceJPEG::construct_create ); #endif #if defined(VW_HAVE_PKG_TIFF) && VW_HAVE_PKG_TIFF==1 vw::DiskImageResource::register_file_type( ".tif", &vw::DiskImageResourceTIFF::construct_open, &vw::DiskImageResourceTIFF::construct_create ); vw::DiskImageResource::register_file_type( ".tiff", &vw::DiskImageResourceTIFF::construct_open, &vw::DiskImageResourceTIFF::construct_create ); #endif #if defined(VW_HAVE_PKG_OPENEXR) && VW_HAVE_PKG_OPENEXR==1 vw::DiskImageResource::register_file_type( ".exr", &vw::DiskImageResourceOpenEXR::construct_open, &vw::DiskImageResourceOpenEXR::construct_create ); #endif } vw::DiskImageResource* vw::DiskImageResource::open( std::string const& filename ) { register_default_file_types(); if( open_map ) { OpenMapType::const_iterator i = open_map->find( file_extension( filename ) ); if( i != open_map->end() ) return i->second( filename ); } throw NoImplErr() << "Unsuppported file format: " << filename; } vw::DiskImageResource* vw::DiskImageResource::create( std::string const& filename, GenericImageFormat const& format ) { register_default_file_types(); if( create_map ) { CreateMapType::const_iterator i = create_map->find( file_extension( filename ) ); if( i != create_map->end() ) return i->second( filename, format ); } throw NoImplErr() << "Unsuppported file format: " << filename; } <commit_msg>Added include for DDD image header, and registered file type ".ddd".<commit_after>// __BEGIN_LICENSE__ // // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // Copyright 2006 Carnegie Mellon University. All rights reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file COPYING at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // // __END_LICENSE__ /// \file DiskImageResource.cc /// /// An abstract base class referring to an image on disk. /// #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #include <vw/config.h> #include <iostream> #include <map> #include <boost/algorithm/string.hpp> #include <vw/FileIO/DiskImageResource.h> #include <vw/FileIO/DiskImageResourcePDS.h> #include <vw/FileIO/DiskImageResourceDDD.h> #if defined(VW_HAVE_PKG_PNG) && VW_HAVE_PKG_PNG==1 #include <vw/FileIO/DiskImageResourcePNG.h> #endif #if defined(VW_HAVE_PKG_JPEG) && VW_HAVE_PKG_JPEG==1 #include <vw/FileIO/DiskImageResourceJPEG.h> #endif #if defined(VW_HAVE_PKG_TIFF) && VW_HAVE_PKG_TIFF==1 #include <vw/FileIO/DiskImageResourceTIFF.h> #endif #if defined(VW_HAVE_PKG_OPENEXR) && VW_HAVE_PKG_OPENEXR==1 #include <vw/FileIO/DiskImageResourceOpenEXR.h> #endif namespace { typedef std::map<std::string,vw::DiskImageResource::construct_open_func> OpenMapType; typedef std::map<std::string,vw::DiskImageResource::construct_create_func> CreateMapType; OpenMapType *open_map = 0; CreateMapType *create_map = 0; } void vw::DiskImageResource::register_file_type( std::string const& extension, vw::DiskImageResource::construct_open_func open_func, vw::DiskImageResource::construct_create_func create_func ) { if( ! open_map ) open_map = new OpenMapType(); if( ! create_map ) create_map = new CreateMapType(); open_map->insert( std::make_pair( extension, open_func ) ); create_map->insert( std::make_pair( extension, create_func ) ); } static std::string file_extension( std::string const& filename ) { std::string::size_type dot = filename.find_last_of('.'); if (dot != std::string::npos) { std::string extension = filename.substr( dot ); boost::to_lower( extension ); return extension; } else { throw vw::IOErr() << "DiskImageResource: Cannot infer file format from filename with no file extension."; } } static void register_default_file_types() { static bool already = false; if( already ) return; already = true; vw::DiskImageResource::register_file_type( ".img", &vw::DiskImageResourcePDS::construct_open, &vw::DiskImageResourcePDS::construct_create ); vw::DiskImageResource::register_file_type( ".ddd", &vw::DiskImageResourceDDD::construct_open, &vw::DiskImageResourceDDD::construct_create ); #if defined(VW_HAVE_PKG_PNG) && VW_HAVE_PKG_PNG==1 vw::DiskImageResource::register_file_type( ".png", &vw::DiskImageResourcePNG::construct_open, &vw::DiskImageResourcePNG::construct_create ); #endif #if defined(VW_HAVE_PKG_JPEG) && VW_HAVE_PKG_JPEG==1 vw::DiskImageResource::register_file_type( ".jpg", &vw::DiskImageResourceJPEG::construct_open, &vw::DiskImageResourceJPEG::construct_create ); vw::DiskImageResource::register_file_type( ".jpeg", &vw::DiskImageResourceJPEG::construct_open, &vw::DiskImageResourceJPEG::construct_create ); #endif #if defined(VW_HAVE_PKG_TIFF) && VW_HAVE_PKG_TIFF==1 vw::DiskImageResource::register_file_type( ".tif", &vw::DiskImageResourceTIFF::construct_open, &vw::DiskImageResourceTIFF::construct_create ); vw::DiskImageResource::register_file_type( ".tiff", &vw::DiskImageResourceTIFF::construct_open, &vw::DiskImageResourceTIFF::construct_create ); #endif #if defined(VW_HAVE_PKG_OPENEXR) && VW_HAVE_PKG_OPENEXR==1 vw::DiskImageResource::register_file_type( ".exr", &vw::DiskImageResourceOpenEXR::construct_open, &vw::DiskImageResourceOpenEXR::construct_create ); #endif } vw::DiskImageResource* vw::DiskImageResource::open( std::string const& filename ) { register_default_file_types(); if( open_map ) { OpenMapType::const_iterator i = open_map->find( file_extension( filename ) ); if( i != open_map->end() ) return i->second( filename ); } throw NoImplErr() << "Unsuppported file format: " << filename; } vw::DiskImageResource* vw::DiskImageResource::create( std::string const& filename, GenericImageFormat const& format ) { register_default_file_types(); if( create_map ) { CreateMapType::const_iterator i = create_map->find( file_extension( filename ) ); if( i != create_map->end() ) return i->second( filename, format ); } throw NoImplErr() << "Unsuppported file format: " << filename; } <|endoftext|>
<commit_before>/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "client_win.h" #include "cefclient/util.h" //#include "Capture.h" #include <Winuser.h> Client_Win::Client_Win() :INIT_LOGGER(Client_Win) { } Client_Win::~Client_Win() { } bool Client_Win::OnKeyEvent( CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event ) { // see chrome shortcuts: https://support.google.com/chrome/topic/25799?hl=en // see windows key codes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx REQUIRE_UI_THREAD(); LOG_TRACE(logger()) << "OnKeyEvent, type=" << event.type << " modifiers=" << event.modifiers << " windows_key_code=" << event.windows_key_code << " unmodified_character=" << event.unmodified_character; if(!event.focus_on_editable_field && event.type == KEYEVENT_RAWKEYDOWN) // shortcut only on non edit field { if(event.modifiers == EVENTFLAG_NONE) // modifiers: none { switch (event.windows_key_code) { case VK_F5: { browser->Reload(); return true; } case VK_F11: { // GC: Wait // toggleFullScreen(browser->GetHost()->GetWindowHandle(), true); // FM: Also show dev tools when exiting full screen for debugging purposes showDevTools(browser); return true; } default: break; } } if(event.modifiers & EVENTFLAG_CONTROL_DOWN) // modifiers: CTRL { switch (event.windows_key_code) { case VK_F5: case 0x52: // R - Key { browser->ReloadIgnoreCache(); return true; } default: break; } } if(event.modifiers & EVENTFLAG_SHIFT_DOWN) // modifiers: SHIFT { switch (event.windows_key_code) { case VK_F5: { browser->ReloadIgnoreCache(); return true; } default: break; } } if( (event.modifiers & EVENTFLAG_SHIFT_DOWN) && (event.modifiers & EVENTFLAG_CONTROL_DOWN) ) // modifiers: SHIFT + CTRL { switch (event.windows_key_code) { case 0x49: // I - Key { showDevTools(browser); return true; } default: break; } } } return false; } void Client_Win::toggleFullScreen(CefWindowHandle window, bool visible) { LONG visibleFlag = (visible ? WS_VISIBLE : 0); window = GetParent(window); // Save current window state if not already fullscreen. if(!_bIsFullScreen) { _savedWindowInfo.maximized = ::IsZoomed(window); if(_savedWindowInfo.maximized) ::SendMessage(window, WM_SYSCOMMAND, SC_RESTORE, 0); _savedWindowInfo.style = GetWindowLong(window, GWL_STYLE); _savedWindowInfo.ex_style = GetWindowLong(window, GWL_EXSTYLE); GetWindowRect(window, &_savedWindowInfo.rect); } _bIsFullScreen =! _bIsFullScreen; // toggle if(_bIsFullScreen) { SetWindowLong(window, GWL_STYLE, _savedWindowInfo.style & ~(WS_CAPTION | WS_THICKFRAME) | visibleFlag); SetWindowLong(window, GWL_EXSTYLE, _savedWindowInfo.ex_style & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE) | visibleFlag); MONITORINFO monitor_info; monitor_info.cbSize = sizeof(monitor_info); GetMonitorInfo(MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST), &monitor_info); SetWindowPos(window, NULL, monitor_info.rcMonitor.left, monitor_info.rcMonitor.top, monitor_info.rcMonitor.right - monitor_info.rcMonitor.left, monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); } else { SetWindowLong(window, GWL_STYLE, _savedWindowInfo.style | visibleFlag); SetWindowLong(window, GWL_EXSTYLE, _savedWindowInfo.ex_style | visibleFlag); SetWindowPos(window, NULL, _savedWindowInfo.rect.left, _savedWindowInfo.rect.top, _savedWindowInfo.rect.right - _savedWindowInfo.rect.left, _savedWindowInfo.rect.bottom - _savedWindowInfo.rect.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); if (_savedWindowInfo.maximized) ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); } } <commit_msg>Remove obsolete include<commit_after>/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "client_win.h" #include "cefclient/util.h" #include <Winuser.h> Client_Win::Client_Win() :INIT_LOGGER(Client_Win) { } Client_Win::~Client_Win() { } bool Client_Win::OnKeyEvent( CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event ) { // see chrome shortcuts: https://support.google.com/chrome/topic/25799?hl=en // see windows key codes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx REQUIRE_UI_THREAD(); LOG_TRACE(logger()) << "OnKeyEvent, type=" << event.type << " modifiers=" << event.modifiers << " windows_key_code=" << event.windows_key_code << " unmodified_character=" << event.unmodified_character; if(!event.focus_on_editable_field && event.type == KEYEVENT_RAWKEYDOWN) // shortcut only on non edit field { if(event.modifiers == EVENTFLAG_NONE) // modifiers: none { switch (event.windows_key_code) { case VK_F5: { browser->Reload(); return true; } case VK_F11: { // GC: Wait // toggleFullScreen(browser->GetHost()->GetWindowHandle(), true); // FM: Also show dev tools when exiting full screen for debugging purposes showDevTools(browser); return true; } default: break; } } if(event.modifiers & EVENTFLAG_CONTROL_DOWN) // modifiers: CTRL { switch (event.windows_key_code) { case VK_F5: case 0x52: // R - Key { browser->ReloadIgnoreCache(); return true; } default: break; } } if(event.modifiers & EVENTFLAG_SHIFT_DOWN) // modifiers: SHIFT { switch (event.windows_key_code) { case VK_F5: { browser->ReloadIgnoreCache(); return true; } default: break; } } if( (event.modifiers & EVENTFLAG_SHIFT_DOWN) && (event.modifiers & EVENTFLAG_CONTROL_DOWN) ) // modifiers: SHIFT + CTRL { switch (event.windows_key_code) { case 0x49: // I - Key { showDevTools(browser); return true; } default: break; } } } return false; } void Client_Win::toggleFullScreen(CefWindowHandle window, bool visible) { LONG visibleFlag = (visible ? WS_VISIBLE : 0); window = GetParent(window); // Save current window state if not already fullscreen. if(!_bIsFullScreen) { _savedWindowInfo.maximized = ::IsZoomed(window); if(_savedWindowInfo.maximized) ::SendMessage(window, WM_SYSCOMMAND, SC_RESTORE, 0); _savedWindowInfo.style = GetWindowLong(window, GWL_STYLE); _savedWindowInfo.ex_style = GetWindowLong(window, GWL_EXSTYLE); GetWindowRect(window, &_savedWindowInfo.rect); } _bIsFullScreen =! _bIsFullScreen; // toggle if(_bIsFullScreen) { SetWindowLong(window, GWL_STYLE, _savedWindowInfo.style & ~(WS_CAPTION | WS_THICKFRAME) | visibleFlag); SetWindowLong(window, GWL_EXSTYLE, _savedWindowInfo.ex_style & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE) | visibleFlag); MONITORINFO monitor_info; monitor_info.cbSize = sizeof(monitor_info); GetMonitorInfo(MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST), &monitor_info); SetWindowPos(window, NULL, monitor_info.rcMonitor.left, monitor_info.rcMonitor.top, monitor_info.rcMonitor.right - monitor_info.rcMonitor.left, monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); } else { SetWindowLong(window, GWL_STYLE, _savedWindowInfo.style | visibleFlag); SetWindowLong(window, GWL_EXSTYLE, _savedWindowInfo.ex_style | visibleFlag); SetWindowPos(window, NULL, _savedWindowInfo.rect.left, _savedWindowInfo.rect.top, _savedWindowInfo.rect.right - _savedWindowInfo.rect.left, _savedWindowInfo.rect.bottom - _savedWindowInfo.rect.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); if (_savedWindowInfo.maximized) ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); } } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2020 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/platform_android.h" #include <android/configuration.h> #include <dlfcn.h> #include "xenia/base/assert.h" namespace xe { namespace platform { namespace android { static bool initialized = false; static int32_t api_level_ = __ANDROID_API__; static ApiFunctions api_functions_; void Initialize(const ANativeActivity* activity) { if (initialized) { return; } AConfiguration* configuration = AConfiguration_new(); AConfiguration_fromAssetManager(configuration, activity->assetManager); api_level_ = AConfiguration_getSdkVersion(configuration); AConfiguration_delete(configuration); if (api_level_ >= 26) { // Leaked intentionally as these will be usable anywhere, already loaded // into the address space as the application is linked against them. // https://chromium.googlesource.com/chromium/src/+/master/third_party/ashmem/ashmem-dev.c#201 void* libandroid = dlopen("libandroid.so", RTLD_NOW); assert_not_null(libandroid); void* libc = dlopen("libc.so", RTLD_NOW); assert_not_null(libc); #define XE_PLATFORM_ANDROID_LOAD_API_FUNCTION(lib, name, api) \ api_functions_.api_##api.name = \ reinterpret_cast<decltype(api_functions_.api_##api.name)>( \ dlsym(lib, #name)); \ assert_not_null(api_functions_.api_##api.name); XE_PLATFORM_ANDROID_LOAD_API_FUNCTION(libandroid, ASharedMemory_create, 26); XE_PLATFORM_ANDROID_LOAD_API_FUNCTION(libc, pthread_getname_np, 26); #undef XE_PLATFORM_ANDROID_LOAD_API_FUNCTION } initialized = true; } int32_t api_level() { return api_level_; } const ApiFunctions& api_functions() { return api_functions_; } } // namespace android } // namespace platform } // namespace xe <commit_msg>[Android] Add a comment about pthreads dynamic loading<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2020 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/platform_android.h" #include <android/configuration.h> #include <dlfcn.h> #include "xenia/base/assert.h" namespace xe { namespace platform { namespace android { static bool initialized = false; static int32_t api_level_ = __ANDROID_API__; static ApiFunctions api_functions_; void Initialize(const ANativeActivity* activity) { if (initialized) { return; } AConfiguration* configuration = AConfiguration_new(); AConfiguration_fromAssetManager(configuration, activity->assetManager); api_level_ = AConfiguration_getSdkVersion(configuration); AConfiguration_delete(configuration); if (api_level_ >= 26) { // Leaked intentionally as these will be usable anywhere, already loaded // into the address space as the application is linked against them. // https://chromium.googlesource.com/chromium/src/+/master/third_party/ashmem/ashmem-dev.c#201 void* libandroid = dlopen("libandroid.so", RTLD_NOW); assert_not_null(libandroid); void* libc = dlopen("libc.so", RTLD_NOW); assert_not_null(libc); #define XE_PLATFORM_ANDROID_LOAD_API_FUNCTION(lib, name, api) \ api_functions_.api_##api.name = \ reinterpret_cast<decltype(api_functions_.api_##api.name)>( \ dlsym(lib, #name)); \ assert_not_null(api_functions_.api_##api.name); XE_PLATFORM_ANDROID_LOAD_API_FUNCTION(libandroid, ASharedMemory_create, 26); // pthreads are a part of Bionic libc on Android. XE_PLATFORM_ANDROID_LOAD_API_FUNCTION(libc, pthread_getname_np, 26); #undef XE_PLATFORM_ANDROID_LOAD_API_FUNCTION } initialized = true; } int32_t api_level() { return api_level_; } const ApiFunctions& api_functions() { return api_functions_; } } // namespace android } // namespace platform } // namespace xe <|endoftext|>
<commit_before>// Copyright 2011 Gregory Szorc // // 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 <zippylog/envelope.hpp> #include <zippylog/protocol/request.pb.h> #include <gtest/gtest.h> #include <string.h> using ::std::invalid_argument; using ::std::string; using ::zippylog::Envelope; using ::zippylog::protocol::request::GetStreamSegmentV1; using ::zippylog::protocol::request::PingV1; using ::zmq::message_t; namespace zippylog { TEST(EnvelopeTest, ConstructorEmptyEnvelope) { ASSERT_NO_THROW(Envelope e()); Envelope e; EXPECT_EQ(0, e.MessageCount()); string s; EXPECT_TRUE(e.Serialize(s)); } TEST(EnvelopeTest, ConstructorInvalidData) { ASSERT_THROW(Envelope e(NULL, 0), invalid_argument); ASSERT_THROW(Envelope e(NULL, 10), invalid_argument); ASSERT_THROW(Envelope e((void *)324234, 0), invalid_argument); ASSERT_THROW(Envelope e((void *)352537, -10), invalid_argument); } TEST(EnvelopeTest, ConstructorZmqMessage) { message_t m; // empty message EXPECT_THROW(Envelope e(m), invalid_argument); // offset >= size m.rebuild(10); EXPECT_THROW(Envelope e(m, 9), invalid_argument); Envelope e; ASSERT_TRUE(e.ToZmqMessage(m)); EXPECT_NO_THROW(Envelope e2(m)); message_t m2(m.size() + 1); memset(m.data(), 1, 1); memcpy((void *)((char *)m2.data() + 1), m.data(), m.size()); EXPECT_NO_THROW(Envelope e2(m2, 1)); } TEST(EnvelopeTest, ConstructorString) { EXPECT_NO_THROW(Envelope e("hello, world")); Envelope e("hello, world"); EXPECT_EQ("hello, world", e.GetStringValueField()); } TEST(EnvelopeTest, EquivalenceAndCopying) { Envelope e1("hello, world"); Envelope e2(e1); Envelope e3 = e1; EXPECT_TRUE(e1 == e2); EXPECT_TRUE(e1 == e3); EXPECT_TRUE(e2 == e3); Envelope e4; EXPECT_TRUE(e1 != e4); } TEST(EnvelopeTest, Serialize) { Envelope e; string s; ASSERT_TRUE(e.Serialize(s)); string s2 = "foo"; ASSERT_TRUE(e.Serialize(s2)); ASSERT_EQ(3 + s.length(), s2.length()); } TEST(EnvelopeTest, ZMQSerialization) { Envelope e; string expected; ASSERT_TRUE(e.Serialize(expected)); message_t m; ASSERT_TRUE(e.ToZmqMessage(m)); ASSERT_EQ(expected.length(), m.size()); EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size())); } TEST(EnvelopeTest, ZMQProtocolSerialization) { Envelope e; string expected(1, 0x01); ASSERT_TRUE(e.Serialize(expected)); message_t m; ASSERT_TRUE(e.ToProtocolZmqMessage(m)); ASSERT_EQ(expected.length(), m.size()); EXPECT_EQ(0x01, *((char *)m.data())); EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size())); } TEST(EnvelopeTest, GetMessageErrors) { Envelope e; EXPECT_THROW(e.GetMessage(-1), invalid_argument); EXPECT_TRUE(NULL == e.GetMessage(0)); EXPECT_TRUE(NULL == e.GetMessage(10)); } TEST(EnvelopeTest, UnknownMessageTypes) { Envelope e; e.envelope.add_message("foo bar"); e.envelope.add_message_namespace(32423432); e.envelope.add_message_type(89672356); string serialized; EXPECT_TRUE(e.Serialize(serialized)); Envelope e2(serialized.data(), serialized.length()); EXPECT_EQ(1, e2.MessageCount()); EXPECT_TRUE(NULL == e2.GetMessage(0)); } TEST(EnvelopeTest, MessageSemantics) { Envelope e; GetStreamSegmentV1 get_stream; get_stream.set_path("/"); get_stream.set_start_offset(0); get_stream.add_to_envelope(e); uint32 expected_namespace = GetStreamSegmentV1::zippylog_namespace; uint32 expected_type = GetStreamSegmentV1::zippylog_enumeration; EXPECT_EQ(1, e.MessageCount()); EXPECT_EQ(expected_namespace, e.MessageNamespace(0)); EXPECT_EQ(expected_type, e.MessageType(0)); GetStreamSegmentV1 *message = (GetStreamSegmentV1 *)e.GetMessage(0); ASSERT_TRUE(NULL != message); // verify the pointer is the same GetStreamSegmentV1 *message2 = (GetStreamSegmentV1 *)e.GetMessage(0); EXPECT_EQ(message, message2); // verify change in original doesn't touch what's in envelope get_stream.set_start_offset(100); EXPECT_EQ(0, message->start_offset()); } TEST(EnvelopeTest, MessagesAndCopying) { Envelope e1; PingV1 p1; p1.add_to_envelope(e1); EXPECT_TRUE(NULL != e1.GetMessage(0)); Envelope e2 = e1; EXPECT_EQ(1, e2.MessageCount()); PingV1 *p2 = (PingV1 *)e2.GetMessage(0); ASSERT_TRUE(NULL != p2); EXPECT_TRUE(&p1 != p2); } } // namespace <commit_msg>convert to test fixture; test random functions<commit_after>// Copyright 2011 Gregory Szorc // // 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 <zippylog/testing.hpp> #include <zippylog/envelope.hpp> #include <zippylog/protocol/request.pb.h> #include <gtest/gtest.h> #include <string> #include <utility> #include <vector> using ::std::invalid_argument; using ::std::pair; using ::std::string; using ::std::vector; using ::zippylog::Envelope; using ::zippylog::protocol::request::GetStreamSegmentV1; using ::zippylog::protocol::request::PingV1; using ::zmq::message_t; namespace zippylog { class EnvelopeTest : public ::zippylog::testing::TestBase { }; TEST_F(EnvelopeTest, ConstructorEmptyEnvelope) { ASSERT_NO_THROW(Envelope e()); Envelope e; EXPECT_EQ(0, e.MessageCount()); string s; EXPECT_TRUE(e.Serialize(s)); } TEST_F(EnvelopeTest, ConstructorInvalidData) { ASSERT_THROW(Envelope e(NULL, 0), invalid_argument); ASSERT_THROW(Envelope e(NULL, 10), invalid_argument); ASSERT_THROW(Envelope e((void *)324234, 0), invalid_argument); ASSERT_THROW(Envelope e((void *)352537, -10), invalid_argument); } TEST_F(EnvelopeTest, ConstructorZmqMessage) { message_t m; // empty message EXPECT_THROW(Envelope e(m), invalid_argument); // offset >= size m.rebuild(10); EXPECT_THROW(Envelope e(m, 9), invalid_argument); Envelope e; ASSERT_TRUE(e.ToZmqMessage(m)); EXPECT_NO_THROW(Envelope e2(m)); message_t m2(m.size() + 1); memset(m.data(), 1, 1); memcpy((void *)((char *)m2.data() + 1), m.data(), m.size()); EXPECT_NO_THROW(Envelope e2(m2, 1)); } TEST_F(EnvelopeTest, ConstructorString) { EXPECT_NO_THROW(Envelope e("hello, world")); Envelope e("hello, world"); EXPECT_EQ("hello, world", e.GetStringValueField()); } TEST_F(EnvelopeTest, EquivalenceAndCopying) { Envelope e1("hello, world"); Envelope e2(e1); Envelope e3 = e1; EXPECT_TRUE(e1 == e2); EXPECT_TRUE(e1 == e3); EXPECT_TRUE(e2 == e3); Envelope e4; EXPECT_TRUE(e1 != e4); } TEST_F(EnvelopeTest, Serialize) { Envelope e; string s; ASSERT_TRUE(e.Serialize(s)); string s2 = "foo"; ASSERT_TRUE(e.Serialize(s2)); ASSERT_EQ(3 + s.length(), s2.length()); } TEST_F(EnvelopeTest, ZMQSerialization) { Envelope e; string expected; ASSERT_TRUE(e.Serialize(expected)); message_t m; ASSERT_TRUE(e.ToZmqMessage(m)); ASSERT_EQ(expected.length(), m.size()); EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size())); } TEST_F(EnvelopeTest, ZMQProtocolSerialization) { Envelope e; string expected(1, 0x01); ASSERT_TRUE(e.Serialize(expected)); message_t m; ASSERT_TRUE(e.ToProtocolZmqMessage(m)); ASSERT_EQ(expected.length(), m.size()); EXPECT_EQ(0x01, *((char *)m.data())); EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size())); } TEST_F(EnvelopeTest, GetMessageErrors) { Envelope e; EXPECT_THROW(e.GetMessage(-1), invalid_argument); EXPECT_TRUE(NULL == e.GetMessage(0)); EXPECT_TRUE(NULL == e.GetMessage(10)); } TEST_F(EnvelopeTest, UnknownMessageTypes) { Envelope e; e.envelope.add_message("foo bar"); e.envelope.add_message_namespace(32423432); e.envelope.add_message_type(89672356); string serialized; EXPECT_TRUE(e.Serialize(serialized)); Envelope e2(serialized.data(), serialized.length()); EXPECT_EQ(1, e2.MessageCount()); EXPECT_TRUE(NULL == e2.GetMessage(0)); } TEST_F(EnvelopeTest, MessageSemantics) { Envelope e; GetStreamSegmentV1 get_stream; get_stream.set_path("/"); get_stream.set_start_offset(0); get_stream.add_to_envelope(e); uint32 expected_namespace = GetStreamSegmentV1::zippylog_namespace; uint32 expected_type = GetStreamSegmentV1::zippylog_enumeration; EXPECT_EQ(1, e.MessageCount()); EXPECT_EQ(expected_namespace, e.MessageNamespace(0)); EXPECT_EQ(expected_type, e.MessageType(0)); GetStreamSegmentV1 *message = (GetStreamSegmentV1 *)e.GetMessage(0); ASSERT_TRUE(NULL != message); // verify the pointer is the same GetStreamSegmentV1 *message2 = (GetStreamSegmentV1 *)e.GetMessage(0); EXPECT_EQ(message, message2); // verify change in original doesn't touch what's in envelope get_stream.set_start_offset(100); EXPECT_EQ(0, message->start_offset()); } TEST_F(EnvelopeTest, MessagesAndCopying) { Envelope e1; PingV1 p1; p1.add_to_envelope(e1); EXPECT_TRUE(NULL != e1.GetMessage(0)); Envelope e2 = e1; EXPECT_EQ(1, e2.MessageCount()); PingV1 *p2 = (PingV1 *)e2.GetMessage(0); ASSERT_TRUE(NULL != p2); EXPECT_TRUE(&p1 != p2); } TEST_F(EnvelopeTest, RandomGeneration) { vector< pair<uint32, uint32> > enumerations; MessageRegistrar::instance()->GetAllEnumerations(enumerations); vector < pair<uint32, uint32> >::iterator i = enumerations.begin(); for (; i != enumerations.end(); i++) { for (int32 j = 10; j; j--) { ::google::protobuf::Message *m = this->GetRandomMessage(i->first, i->second); delete m; } } for (int32 j = 1000; j; j--) { this->GetRandomEnvelope(); } } } // namespace <|endoftext|>
<commit_before>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ #ifndef PROPERTYMANAGER_HH_ #define PROPERTYMANAGER_HH_ #include <sstream> namespace OpenMesh { /** * This class is intended to manage the lifecycle of properties. * It also defines convenience operators to access the encapsulated * property's value. * * Usage example: * * \code * TriMesh mesh; * PropertyManager<VPropHandleT<bool>, MeshT> visited(mesh, "visited.plugin-example.i8.informatik.rwth-aachen.de"); * * for (TriMesh::VertexIter vh_it = mesh.begin(); ... ; ...) { * if (!visited[*vh_it]) { * visitComponent(mesh, *vh_it, visited); * } * } * \endcode * */ template<typename PROPTYPE, typename MeshT> class PropertyManager { private: /** * Noncopyable because there aren't not straightforward copy semantics. */ PropertyManager(const PropertyManager&); /** * Noncopyable because there aren't not straightforward copy semantics. */ const PropertyManager& operator=(const PropertyManager&); public: /** * Constructor. * * Throws an \p std::runtime_error if \p existing is true and * no property named \p propname of the appropriate property type * exists. * * @param mesh The mesh on which to create the property. * @param propname The name of the property. * @param existing If false, a new property is created and its lifecycle is managed (i.e. * the property is deleted upon destruction of the PropertyManager instance). If true, * the instance merely acts as a convenience wrapper around an existing property with no * lifecycle management whatsoever. */ PropertyManager(MeshT &mesh, const char *propname, bool existing = false) : mesh_(&mesh), retain_(existing) { if (existing) { if (!mesh_->get_property_handle(prop_, propname)) { std::ostringstream oss; oss << "Requested property handle \"" << propname << "\" does not exist."; throw std::runtime_error(oss.str()); } } else { mesh_->add_property(prop_, propname); } } ~PropertyManager() { deleteProperty(); } #if __cplusplus > 199711L or __GXX_EXPERIMENTAL_CXX0X__ /** * Move constructor. Transfers ownership (delete responsibility). */ PropertyManager(PropertyManager &&rhs) : mesh_(rhs.mesh_), prop_(rhs.prop_), retain_(rhs.retain_) { rhs.retain_ = true; } /** * Move assignment. Transfers ownership (delete responsibility). */ PropertyManager &operator=(PropertyManager &&rhs) { deleteProperty(); mesh_ = rhs.mesh_; prop_ = rhs.prop_; retain_ = rhs.retain_; rhs.retain_ = true; return *this; } /** * Create a property manager for the supplied property and mesh. * If the property doesn't exist, it is created. In any case, * lifecycle management is disabled. */ static PropertyManager createIfNotExists(MeshT &mesh, const char *propname) { PROPTYPE dummy_prop; PropertyManager pm(mesh, propname, mesh.get_property_handle(dummy_prop, propname)); pm.retain(); return std::move(pm); } #endif /** * \brief Disable lifecycle management for this property. * * If this method is called, the encapsulated property will not be deleted * upon destruction of the PropertyManager instance. */ inline void retain() { retain_ = true; } /** * Access the encapsulated property. */ inline PROPTYPE &operator* () { return prop_; } /** * Access the encapsulated property. */ inline const PROPTYPE &operator* () const { return prop_; } /** * Enables convenient access to the encapsulated property. * * For a usage example see this class' documentation. * * @param handle A handle of the appropriate handle type. (I.e. \p VertexHandle for \p VPropHandleT, etc.) */ template<typename HandleType> inline typename PROPTYPE::reference operator[] (const HandleType &handle) { return mesh_->property(prop_, handle); } /** * Enables convenient access to the encapsulated property. * * For a usage example see this class' documentation. * * @param handle A handle of the appropriate handle type. (I.e. \p VertexHandle for \p VPropHandleT, etc.) */ template<typename HandleType> inline typename PROPTYPE::const_reference operator[] (const HandleType &handle) const { return mesh_->property(prop_, handle); } private: void deleteProperty() { if (!retain_) mesh_->remove_property(prop_); } private: MeshT *mesh_; PROPTYPE prop_; bool retain_; }; } /* namespace OpenMesh */ #endif /* PROPERTYMANAGER_HH_ */ <commit_msg>OpenMesh/Core/Utils/PropertyManager: Added property to retain() method.<commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ #ifndef PROPERTYMANAGER_HH_ #define PROPERTYMANAGER_HH_ #include <sstream> namespace OpenMesh { /** * This class is intended to manage the lifecycle of properties. * It also defines convenience operators to access the encapsulated * property's value. * * Usage example: * * \code * TriMesh mesh; * PropertyManager<VPropHandleT<bool>, MeshT> visited(mesh, "visited.plugin-example.i8.informatik.rwth-aachen.de"); * * for (TriMesh::VertexIter vh_it = mesh.begin(); ... ; ...) { * if (!visited[*vh_it]) { * visitComponent(mesh, *vh_it, visited); * } * } * \endcode * */ template<typename PROPTYPE, typename MeshT> class PropertyManager { private: /** * Noncopyable because there aren't not straightforward copy semantics. */ PropertyManager(const PropertyManager&); /** * Noncopyable because there aren't not straightforward copy semantics. */ const PropertyManager& operator=(const PropertyManager&); public: /** * Constructor. * * Throws an \p std::runtime_error if \p existing is true and * no property named \p propname of the appropriate property type * exists. * * @param mesh The mesh on which to create the property. * @param propname The name of the property. * @param existing If false, a new property is created and its lifecycle is managed (i.e. * the property is deleted upon destruction of the PropertyManager instance). If true, * the instance merely acts as a convenience wrapper around an existing property with no * lifecycle management whatsoever. */ PropertyManager(MeshT &mesh, const char *propname, bool existing = false) : mesh_(&mesh), retain_(existing) { if (existing) { if (!mesh_->get_property_handle(prop_, propname)) { std::ostringstream oss; oss << "Requested property handle \"" << propname << "\" does not exist."; throw std::runtime_error(oss.str()); } } else { mesh_->add_property(prop_, propname); } } ~PropertyManager() { deleteProperty(); } #if __cplusplus > 199711L or __GXX_EXPERIMENTAL_CXX0X__ /** * Move constructor. Transfers ownership (delete responsibility). */ PropertyManager(PropertyManager &&rhs) : mesh_(rhs.mesh_), prop_(rhs.prop_), retain_(rhs.retain_) { rhs.retain_ = true; } /** * Move assignment. Transfers ownership (delete responsibility). */ PropertyManager &operator=(PropertyManager &&rhs) { deleteProperty(); mesh_ = rhs.mesh_; prop_ = rhs.prop_; retain_ = rhs.retain_; rhs.retain_ = true; return *this; } /** * Create a property manager for the supplied property and mesh. * If the property doesn't exist, it is created. In any case, * lifecycle management is disabled. */ static PropertyManager createIfNotExists(MeshT &mesh, const char *propname) { PROPTYPE dummy_prop; PropertyManager pm(mesh, propname, mesh.get_property_handle(dummy_prop, propname)); pm.retain(); return std::move(pm); } #endif /** * \brief Disable lifecycle management for this property. * * If this method is called, the encapsulated property will not be deleted * upon destruction of the PropertyManager instance. */ inline void retain(bool doRetain = true) { retain_ = doRetain; } /** * Access the encapsulated property. */ inline PROPTYPE &operator* () { return prop_; } /** * Access the encapsulated property. */ inline const PROPTYPE &operator* () const { return prop_; } /** * Enables convenient access to the encapsulated property. * * For a usage example see this class' documentation. * * @param handle A handle of the appropriate handle type. (I.e. \p VertexHandle for \p VPropHandleT, etc.) */ template<typename HandleType> inline typename PROPTYPE::reference operator[] (const HandleType &handle) { return mesh_->property(prop_, handle); } /** * Enables convenient access to the encapsulated property. * * For a usage example see this class' documentation. * * @param handle A handle of the appropriate handle type. (I.e. \p VertexHandle for \p VPropHandleT, etc.) */ template<typename HandleType> inline typename PROPTYPE::const_reference operator[] (const HandleType &handle) const { return mesh_->property(prop_, handle); } private: void deleteProperty() { if (!retain_) mesh_->remove_property(prop_); } private: MeshT *mesh_; PROPTYPE prop_; bool retain_; }; } /* namespace OpenMesh */ #endif /* PROPERTYMANAGER_HH_ */ <|endoftext|>
<commit_before><commit_msg>Refactoring ...<commit_after><|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #if OPENSSL_VERSION_MAJOR >= 3 #include <openssl/provider.h> #endif #endif #include "../../Debug/Assertions.h" #include "../../Execution/Exceptions.h" #include "LibraryContext.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::OpenSSL; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #if qHasFeature_OpenSSL && defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #if OPENSSL_VERSION_NUMBER < 0x1010000fL #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") #else #pragma comment(lib, "libcrypto.lib") #pragma comment(lib, "libssl.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "crypt32.lib") #endif #endif #if qHasFeature_OpenSSL namespace { void AccumulateIntoSetOfCipherNames_ (const ::EVP_CIPHER* ciph, Set<String>* ciphers) { RequireNotNull (ciphers); if (ciph != nullptr) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ #if OPENSSL_VERSION_MAJOR >= 3 DbgTrace (L"cipher: %p (name: %s), provider: %p (name %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_get0_provider (ciph), (::EVP_CIPHER_get0_provider (ciph) == nullptr ? L"null" : String::FromNarrowSDKString (::OSSL_PROVIDER_get0_name (::EVP_CIPHER_get0_provider (ciph))).c_str ())); #else DbgTrace (L"cipher: %p (name: %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str ()); #endif #if 0 int flags = ::EVP_CIPHER_flags (ciph); DbgTrace ("flags=%x", flags); #endif #endif ciphers->Add (CipherAlgorithm{ciph}.pName ()); } }; void AccumulateIntoSetOfDigestNames_ (const ::EVP_MD* digest, Set<String>* digestNames) { RequireNotNull (digestNames); if (digest != nullptr) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ #if OPENSSL_VERSION_MAJOR >= 3 DbgTrace (L"digest: %p (name: %s), provider: %p (name %s)", digest, DigestAlgorithm{digest}.pName ().c_str (), ::EVP_MD_get0_provider (digest), (::EVP_MD_get0_provider (digest) == nullptr ? L"null" : String::FromNarrowSDKString (::OSSL_PROVIDER_get0_name (::EVP_MD_get0_provider (digest))).c_str ())); #else DbgTrace (L"digest: %p (name: %s)", digest, DigestAlgorithm{digest}.pName ().c_str ()); #endif #endif digestNames->Add (DigestAlgorithm{digest}.pName ()); } }; } /* ******************************************************************************** ******************* Cryptography::OpenSSL::LibraryContext ********************** ******************************************************************************** */ #if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy LibraryContext LibraryContext::sDefault; #endif LibraryContext::LibraryContext () : pAvailableCipherAlgorithms{ [qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableCipherAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<String> cipherNames; #if OPENSSL_VERSION_MAJOR >= 3 ::EVP_CIPHER_do_all_provided ( nullptr, [] (::EVP_CIPHER* ciph, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); }, &cipherNames); #else ::EVP_CIPHER_do_all_sorted ( #if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy [] (const ::EVP_CIPHER* ciph, const char*, const char*, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); }, #else [] (const ::EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); }, #endif &cipherNames); #endif #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Found pAvailableCipherAlgorithms-FIRST-PASS (cnt=%d): %s", cipherNames.size (), Characters::ToString (cipherNames).c_str ()); #endif Set<CipherAlgorithm> results{cipherNames.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::CipherAlgorithm::GetByNameQuietly (n); })}; DbgTrace (L"Found pAvailableCipherAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ()); return results; }} , pStandardCipherAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardCipherAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<CipherAlgorithm> results; results += CipherAlgorithms::kAES_128_CBC; results += CipherAlgorithms::kAES_128_ECB; results += CipherAlgorithms::kAES_128_OFB; results += CipherAlgorithms::kAES_128_CFB1; results += CipherAlgorithms::kAES_128_CFB8; results += CipherAlgorithms::kAES_128_CFB128; results += CipherAlgorithms::kAES_192_CBC; results += CipherAlgorithms::kAES_192_ECB; results += CipherAlgorithms::kAES_192_OFB; results += CipherAlgorithms::kAES_192_CFB1; results += CipherAlgorithms::kAES_192_CFB8; results += CipherAlgorithms::kAES_192_CFB128; results += CipherAlgorithms::kAES_256_CBC; results += CipherAlgorithms::kAES_256_ECB; results += CipherAlgorithms::kAES_256_OFB; results += CipherAlgorithms::kAES_256_CFB1; results += CipherAlgorithms::kAES_256_CFB8; results += CipherAlgorithms::kAES_256_CFB128; /* * @todo mark these below as deprecated...??? in openssl3? */ #if OPENSSL_VERSION_MAJOR < 3 results += CipherAlgorithms::kBlowfish_CBC; results += CipherAlgorithms::kBlowfish_ECB; results += CipherAlgorithms::kBlowfish_CFB; results += CipherAlgorithms::kBlowfish_OFB; results += CipherAlgorithms::kBlowfish; results += CipherAlgorithms::kRC2_CBC; results += CipherAlgorithms::kRC2_ECB; results += CipherAlgorithms::kRC2_CFB; results += CipherAlgorithms::kRC2_OFB; results += CipherAlgorithms::kRC4; #endif return results; }} , pAvailableDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableDigestAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<String> digestNames; #if OPENSSL_VERSION_MAJOR >= 3 ::EVP_MD_do_all_provided ( nullptr, [] (::EVP_MD* md, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); }, &digestNames); #else ::EVP_MD_do_all_sorted ( #if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy [] (const ::EVP_MD* md, const char*, const char*, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); }, #else [] (const ::EVP_MD* md, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); }, #endif &digestNames); #endif #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Found pAvailableDigestAlgorithms-FIRST-PASS (cnt=%d): %s", digestNames.size (), Characters::ToString (digestNames).c_str ()); #endif Set<DigestAlgorithm> results{digestNames.Select<DigestAlgorithm> ([] (const String& n) -> optional<DigestAlgorithm> { return OpenSSL::DigestAlgorithm::GetByNameQuietly (n); })}; DbgTrace (L"Found pAvailableDigestAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ()); return results; }} , pStandardDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardDigestAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<DigestAlgorithm> results; results += DigestAlgorithms::kMD5; results += DigestAlgorithms::kSHA1; results += DigestAlgorithms::kSHA1_224; results += DigestAlgorithms::kSHA1_256; results += DigestAlgorithms::kSHA1_384; results += DigestAlgorithms::kSHA1_512; results += DigestAlgorithms::kSHA3_224; results += DigestAlgorithms::kSHA3_256; results += DigestAlgorithms::kSHA3_384; results += DigestAlgorithms::kSHA3_512; return results; }} { LoadProvider (kDefaultProvider); } LibraryContext ::~LibraryContext () { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 // reference counts dont matter here, just unload all the providers we loaded for (auto i : fLoadedProviders_.MappedValues ()) { Verify (::OSSL_PROVIDER_unload (i) == 1); } #endif } void LibraryContext::LoadProvider ([[maybe_unused]] const String& providerName) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::LoadProvider", L"%s", providerName.c_str ())}; lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 auto p = fLoadedProviders_.LookupOneValue (providerName); if (p == nullptr) { // really load cuz not already loaded DbgTrace (L"calling OSSL_PROVIDER_load"); p = ::OSSL_PROVIDER_load (nullptr, providerName.AsNarrowSDKString ().c_str ()); static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv}; Execution::ThrowIfNull (p, kErr_); } fLoadedProviders_.Add (providerName, p); // add association (perhaps redundantly) #else Require (providerName == kDefaultProvider or providerName == kLegacyProvider); #endif } void LibraryContext ::UnLoadProvider ([[maybe_unused]] const String& providerName) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::UnLoadProvider", L"%s", providerName.c_str ())}; lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 Require (fLoadedProviders_.ContainsKey (providerName)); fLoadedProviders_.Remove (providerName); if (auto p = fLoadedProviders_.LookupOneValue (providerName)) { DbgTrace (L"calling OSSL_PROVIDER_unload"); Verify (::OSSL_PROVIDER_unload (p) == 1); } #endif } #endif <commit_msg>fixed small regression with recent OpenSSL/LibraryContext change to using Association<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #if OPENSSL_VERSION_MAJOR >= 3 #include <openssl/provider.h> #endif #endif #include "../../Debug/Assertions.h" #include "../../Execution/Exceptions.h" #include "LibraryContext.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::OpenSSL; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #if qHasFeature_OpenSSL && defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #if OPENSSL_VERSION_NUMBER < 0x1010000fL #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") #else #pragma comment(lib, "libcrypto.lib") #pragma comment(lib, "libssl.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "crypt32.lib") #endif #endif #if qHasFeature_OpenSSL namespace { void AccumulateIntoSetOfCipherNames_ (const ::EVP_CIPHER* ciph, Set<String>* ciphers) { RequireNotNull (ciphers); if (ciph != nullptr) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ #if OPENSSL_VERSION_MAJOR >= 3 DbgTrace (L"cipher: %p (name: %s), provider: %p (name %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_get0_provider (ciph), (::EVP_CIPHER_get0_provider (ciph) == nullptr ? L"null" : String::FromNarrowSDKString (::OSSL_PROVIDER_get0_name (::EVP_CIPHER_get0_provider (ciph))).c_str ())); #else DbgTrace (L"cipher: %p (name: %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str ()); #endif #if 0 int flags = ::EVP_CIPHER_flags (ciph); DbgTrace ("flags=%x", flags); #endif #endif ciphers->Add (CipherAlgorithm{ciph}.pName ()); } }; void AccumulateIntoSetOfDigestNames_ (const ::EVP_MD* digest, Set<String>* digestNames) { RequireNotNull (digestNames); if (digest != nullptr) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ #if OPENSSL_VERSION_MAJOR >= 3 DbgTrace (L"digest: %p (name: %s), provider: %p (name %s)", digest, DigestAlgorithm{digest}.pName ().c_str (), ::EVP_MD_get0_provider (digest), (::EVP_MD_get0_provider (digest) == nullptr ? L"null" : String::FromNarrowSDKString (::OSSL_PROVIDER_get0_name (::EVP_MD_get0_provider (digest))).c_str ())); #else DbgTrace (L"digest: %p (name: %s)", digest, DigestAlgorithm{digest}.pName ().c_str ()); #endif #endif digestNames->Add (DigestAlgorithm{digest}.pName ()); } }; } /* ******************************************************************************** ******************* Cryptography::OpenSSL::LibraryContext ********************** ******************************************************************************** */ #if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy LibraryContext LibraryContext::sDefault; #endif LibraryContext::LibraryContext () : pAvailableCipherAlgorithms{ [qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableCipherAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<String> cipherNames; #if OPENSSL_VERSION_MAJOR >= 3 ::EVP_CIPHER_do_all_provided ( nullptr, [] (::EVP_CIPHER* ciph, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); }, &cipherNames); #else ::EVP_CIPHER_do_all_sorted ( #if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy [] (const ::EVP_CIPHER* ciph, const char*, const char*, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); }, #else [] (const ::EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); }, #endif &cipherNames); #endif #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Found pAvailableCipherAlgorithms-FIRST-PASS (cnt=%d): %s", cipherNames.size (), Characters::ToString (cipherNames).c_str ()); #endif Set<CipherAlgorithm> results{cipherNames.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::CipherAlgorithm::GetByNameQuietly (n); })}; DbgTrace (L"Found pAvailableCipherAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ()); return results; }} , pStandardCipherAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardCipherAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<CipherAlgorithm> results; results += CipherAlgorithms::kAES_128_CBC; results += CipherAlgorithms::kAES_128_ECB; results += CipherAlgorithms::kAES_128_OFB; results += CipherAlgorithms::kAES_128_CFB1; results += CipherAlgorithms::kAES_128_CFB8; results += CipherAlgorithms::kAES_128_CFB128; results += CipherAlgorithms::kAES_192_CBC; results += CipherAlgorithms::kAES_192_ECB; results += CipherAlgorithms::kAES_192_OFB; results += CipherAlgorithms::kAES_192_CFB1; results += CipherAlgorithms::kAES_192_CFB8; results += CipherAlgorithms::kAES_192_CFB128; results += CipherAlgorithms::kAES_256_CBC; results += CipherAlgorithms::kAES_256_ECB; results += CipherAlgorithms::kAES_256_OFB; results += CipherAlgorithms::kAES_256_CFB1; results += CipherAlgorithms::kAES_256_CFB8; results += CipherAlgorithms::kAES_256_CFB128; /* * @todo mark these below as deprecated...??? in openssl3? */ #if OPENSSL_VERSION_MAJOR < 3 results += CipherAlgorithms::kBlowfish_CBC; results += CipherAlgorithms::kBlowfish_ECB; results += CipherAlgorithms::kBlowfish_CFB; results += CipherAlgorithms::kBlowfish_OFB; results += CipherAlgorithms::kBlowfish; results += CipherAlgorithms::kRC2_CBC; results += CipherAlgorithms::kRC2_ECB; results += CipherAlgorithms::kRC2_CFB; results += CipherAlgorithms::kRC2_OFB; results += CipherAlgorithms::kRC4; #endif return results; }} , pAvailableDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableDigestAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<String> digestNames; #if OPENSSL_VERSION_MAJOR >= 3 ::EVP_MD_do_all_provided ( nullptr, [] (::EVP_MD* md, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); }, &digestNames); #else ::EVP_MD_do_all_sorted ( #if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy [] (const ::EVP_MD* md, const char*, const char*, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); }, #else [] (const ::EVP_MD* md, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); }, #endif &digestNames); #endif #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Found pAvailableDigestAlgorithms-FIRST-PASS (cnt=%d): %s", digestNames.size (), Characters::ToString (digestNames).c_str ()); #endif Set<DigestAlgorithm> results{digestNames.Select<DigestAlgorithm> ([] (const String& n) -> optional<DigestAlgorithm> { return OpenSSL::DigestAlgorithm::GetByNameQuietly (n); })}; DbgTrace (L"Found pAvailableDigestAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ()); return results; }} , pStandardDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardDigestAlgorithms); shared_lock<const AssertExternallySynchronizedMutex> critSec{*thisObj}; Set<DigestAlgorithm> results; results += DigestAlgorithms::kMD5; results += DigestAlgorithms::kSHA1; results += DigestAlgorithms::kSHA1_224; results += DigestAlgorithms::kSHA1_256; results += DigestAlgorithms::kSHA1_384; results += DigestAlgorithms::kSHA1_512; results += DigestAlgorithms::kSHA3_224; results += DigestAlgorithms::kSHA3_256; results += DigestAlgorithms::kSHA3_384; results += DigestAlgorithms::kSHA3_512; return results; }} { LoadProvider (kDefaultProvider); } LibraryContext ::~LibraryContext () { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 // reference counts dont matter here, just unload all the providers we loaded for (auto i : fLoadedProviders_.MappedValues ()) { Verify (::OSSL_PROVIDER_unload (i) == 1); } #endif } void LibraryContext::LoadProvider ([[maybe_unused]] const String& providerName) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::LoadProvider", L"%s", providerName.c_str ())}; lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 auto p = fLoadedProviders_.LookupOneValue (providerName); if (p == nullptr) { // really load cuz not already loaded DbgTrace (L"calling OSSL_PROVIDER_load"); p = ::OSSL_PROVIDER_load (nullptr, providerName.AsNarrowSDKString ().c_str ()); static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv}; Execution::ThrowIfNull (p, kErr_); } fLoadedProviders_.Add (providerName, p); // add association (perhaps redundantly) #else Require (providerName == kDefaultProvider or providerName == kLegacyProvider); #endif } void LibraryContext ::UnLoadProvider ([[maybe_unused]] const String& providerName) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::UnLoadProvider", L"%s", providerName.c_str ())}; lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 Require (fLoadedProviders_.ContainsKey (providerName)); auto providerToMaybeRemove = fLoadedProviders_.LookupOneValue (providerName); fLoadedProviders_.Remove (providerName); if (not fLoadedProviders_.ContainsKey (providerName)) { DbgTrace (L"calling OSSL_PROVIDER_unload"); Verify (::OSSL_PROVIDER_unload (providerToMaybeRemove) == 1); } #endif } #endif <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../../StroikaPreComp.h" #include "../../../Characters/Format.h" #include "Reader.h" //// SEEE http://www.zlib.net/zlib_how.html /// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object /// where inner loop is done each time through with a CHUNK #if qHasFeature_ZLib #include <zlib.h> #if defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment(lib, "zlib.lib") #endif using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::DataExchange::Compression; using namespace Stroika::Foundation::Streams; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { void ThrowIfZLibErr_ (int err) { // VERY ROUGH DRAFT - probably need a more specific exception object type if (err != Z_OK) [[UNLIKELY_ATTR]] { switch (err) { case Z_VERSION_ERROR: Execution::Throw (Execution::RuntimeErrorException{L"ZLIB Z_VERSION_ERROR"sv}); case Z_DATA_ERROR: Execution::Throw (Execution::RuntimeErrorException{L"ZLIB Z_DATA_ERROR"sv}); case Z_ERRNO: Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L"ZLIB Z_ERRNO (errno=%d", errno)}); default: Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L"ZLIB ERR %d", err)}); } } } struct MyCompressionStream_ : InputStream<byte>::Ptr { struct BaseRep_ : public InputStream<byte>::_IRep { private: static constexpr size_t CHUNK_ = 16384; public: Streams::InputStream<Memory::byte>::Ptr fInStream_; z_stream fZStream_; byte fInBuf_[CHUNK_]; SeekOffsetType _fSeekOffset{}; BaseRep_ (const Streams::InputStream<byte>::Ptr& in) : fInStream_ (in) , fZStream_{} { } virtual ~BaseRep_ () = default; virtual bool IsSeekable () const override { // for now - KISS return false; // SHOULD allow seekable IFF src is seekable } virtual void CloseRead () override { Require (IsOpenRead ()); fInStream_.Close (); Assert (fInStream_ == nullptr); Ensure (not IsOpenRead ()); } virtual bool IsOpenRead () const override { return fInStream_ != nullptr; } virtual SeekOffsetType GetReadOffset () const override { Require (IsOpenRead ()); return _fSeekOffset; } virtual SeekOffsetType SeekRead (Whence /*whence*/, SignedSeekOffsetType /*offset*/) override { RequireNotReached (); Require (IsOpenRead ()); return SeekOffsetType{}; } nonvirtual bool _AssureInputAvailableReturnTrueIfAtEOF () { Require (IsOpenRead ()); if (fZStream_.avail_in == 0) { Assert (Memory::NEltsOf (fInBuf_) < numeric_limits<uInt>::max ()); fZStream_.avail_in = static_cast<uInt> (fInStream_.Read (begin (fInBuf_), end (fInBuf_))); fZStream_.next_in = reinterpret_cast<Bytef*> (begin (fInBuf_)); } return fZStream_.avail_in == 0; } }; struct DeflateRep_ : BaseRep_ { DeflateRep_ (const Streams::InputStream<byte>::Ptr& in) : BaseRep_ (in) { int level = Z_DEFAULT_COMPRESSION; ThrowIfZLibErr_ (::deflateInit (&fZStream_, level)); } virtual ~DeflateRep_ () { Verify (::deflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override { Require (intoStart < intoEnd); // API rule for streams Require (IsOpenRead ()); Again: bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF (); Require (intoStart < intoEnd); ptrdiff_t outBufSize = intoEnd - intoStart; int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH; fZStream_.avail_out = static_cast<uInt> (outBufSize); fZStream_.next_out = reinterpret_cast<Bytef*> (intoStart); int ret; switch (ret = ::deflate (&fZStream_, flush)) { case Z_OK: break; case Z_STREAM_END: break; default: ThrowIfZLibErr_ (ret); } ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out; Assert (pulledOut <= outBufSize); if (pulledOut == 0 and not isAtSrcEOF and flush == Z_NO_FLUSH) { goto Again; } _fSeekOffset += pulledOut; return pulledOut; } virtual optional<size_t> ReadNonBlocking ([[maybe_unused]] ElementType* intoStart, [[maybe_unused]] ElementType* intoEnd) override { Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); Require (IsOpenRead ()); // https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - INCOMPLETE IMPL #if 0 if (intoStart == nullptr) { // Just check if any data available } else { Assert (intoStart < intoEnd); Again: if (fZStream_.avail_in == 0) { Assert (Memory::NEltsOf (fInBuf_) < numeric_limits<uInt>::max ()); if (auto o = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) { fZStream_.avail_in = static_cast<uInt> (*o); fZStream_.next_in = begin (fInBuf_); } else { return {}; } } ptrdiff_t outBufSize = intoEnd - intoStart; fZStream_.avail_out = static_cast<uInt> (outBufSize); fZStream_.next_out = intoStart; bool isAtSrcEOF = fZStream_.avail_in == 0; int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH; int ret; switch (ret = ::deflate (&fZStream_, flush)) { case Z_OK: break; case Z_STREAM_END: break; default: ThrowIfZLibErr_ (ret); } ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out; Assert (pulledOut <= outBufSize); if (pulledOut == 0 and not isAtSrcEOF) { goto Again; } _fSeekOffset += pulledOut; return pulledOut; } #else // while nothing available to output, try getting more from input stream until we cannot (either cuz {} or EOF) // and then report accordingly // // INCOMPLETE - tricky... most common cases easy, but edges hard... //&&&& issues are: //>> wrong meaning for available_out - we have no output buffer // >> need output buffer for this API, since could pass in no argument buffer (OK to be one byte in that case) while (fZStream_.avail_out == 0) { if (fZStream_.avail_in == 0) { if (optional<size_t> tmpAvail = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) { } else { return {}; } } } #endif WeakAssert (false); // @todo - FIX TO REALLY CHECK return {}; } }; struct InflateRep_ : BaseRep_ { InflateRep_ (const Streams::InputStream<byte>::Ptr& in) : BaseRep_ (in) { // see http://zlib.net/manual.html for meaning of params and http://www.lemoda.net/c/zlib-open-read/ for example constexpr int windowBits = 15; constexpr int ENABLE_ZLIB_GZIP = 32; ThrowIfZLibErr_ (::inflateInit2 (&fZStream_, windowBits | ENABLE_ZLIB_GZIP)); } virtual ~InflateRep_ () { Verify (::inflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override { Require (intoStart < intoEnd); // API rule for streams Require (IsOpenRead ()); Again: bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF (); ptrdiff_t outBufSize = intoEnd - intoStart; fZStream_.avail_out = static_cast<uInt> (outBufSize); fZStream_.next_out = reinterpret_cast<Bytef*> (intoStart); int ret; switch (ret = ::inflate (&fZStream_, Z_NO_FLUSH)) { case Z_OK: break; case Z_STREAM_END: break; default: ThrowIfZLibErr_ (ret); } ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out; Assert (pulledOut <= outBufSize); if (pulledOut == 0 and not isAtSrcEOF) { goto Again; } _fSeekOffset += pulledOut; return pulledOut; } virtual optional<size_t> ReadNonBlocking ([[maybe_unused]] ElementType* intoStart, [[maybe_unused]] ElementType* intoEnd) override { // https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - incomplete IMPL Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); Require (IsOpenRead ()); WeakAssert (false); // @todo - FIX TO REALLY CHECK return {}; } }; enum Compression { eCompression }; enum DeCompression { eDeCompression }; MyCompressionStream_ (Compression, const Streams::InputStream<byte>::Ptr& in) : InputStream<byte>::Ptr (make_shared<DeflateRep_> (in)) { } MyCompressionStream_ (DeCompression, const Streams::InputStream<byte>::Ptr& in) : InputStream<byte>::Ptr (make_shared<InflateRep_> (in)) { } }; } #endif #if qHasFeature_ZLib class Zip::Reader::Rep_ : public Reader::_IRep { public: virtual InputStream<byte>::Ptr Compress (const InputStream<byte>::Ptr& src) const override { return MyCompressionStream_ (MyCompressionStream_::eCompression, src); } virtual InputStream<byte>::Ptr Decompress (const InputStream<byte>::Ptr& src) const override { return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src); } }; Zip::Reader::Reader () : DataExchange::Compression::Reader{make_shared<Rep_> ()} { } #endif <commit_msg>cosmetic cleanups to DataExchange/Compression/Zip/Reader<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../../StroikaPreComp.h" #include "../../../Characters/Format.h" #include "Reader.h" //// SEEE http://www.zlib.net/zlib_how.html /// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object /// where inner loop is done each time through with a CHUNK #if qHasFeature_ZLib #include <zlib.h> #if defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment(lib, "zlib.lib") #endif using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::DataExchange::Compression; using namespace Stroika::Foundation::Streams; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { void ThrowIfZLibErr_ (int err) { // VERY ROUGH DRAFT - probably need a more specific exception object type if (err != Z_OK) [[UNLIKELY_ATTR]] { switch (err) { case Z_VERSION_ERROR: Execution::Throw (Execution::RuntimeErrorException{L"ZLIB Z_VERSION_ERROR"sv}); case Z_DATA_ERROR: Execution::Throw (Execution::RuntimeErrorException{L"ZLIB Z_DATA_ERROR"sv}); case Z_ERRNO: Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L"ZLIB Z_ERRNO (errno=%d", errno)}); default: Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L"ZLIB ERR %d", err)}); } } } struct MyCompressionStream_ : InputStream<byte>::Ptr { struct BaseRep_ : public InputStream<byte>::_IRep { private: static constexpr size_t CHUNK_ = 16384; public: Streams::InputStream<Memory::byte>::Ptr fInStream_; z_stream fZStream_{}; byte fInBuf_[CHUNK_]; SeekOffsetType _fSeekOffset{}; BaseRep_ (const Streams::InputStream<byte>::Ptr& in) : fInStream_{in} { } virtual ~BaseRep_ () = default; virtual bool IsSeekable () const override { // for now - KISS return false; // SHOULD allow seekable IFF src is seekable } virtual void CloseRead () override { Require (IsOpenRead ()); fInStream_.Close (); Assert (fInStream_ == nullptr); Ensure (not IsOpenRead ()); } virtual bool IsOpenRead () const override { return fInStream_ != nullptr; } virtual SeekOffsetType GetReadOffset () const override { Require (IsOpenRead ()); return _fSeekOffset; } virtual SeekOffsetType SeekRead (Whence /*whence*/, SignedSeekOffsetType /*offset*/) override { RequireNotReached (); Require (IsOpenRead ()); return SeekOffsetType{}; } nonvirtual bool _AssureInputAvailableReturnTrueIfAtEOF () { Require (IsOpenRead ()); if (fZStream_.avail_in == 0) { Assert (Memory::NEltsOf (fInBuf_) < numeric_limits<uInt>::max ()); fZStream_.avail_in = static_cast<uInt> (fInStream_.Read (begin (fInBuf_), end (fInBuf_))); fZStream_.next_in = reinterpret_cast<Bytef*> (begin (fInBuf_)); } return fZStream_.avail_in == 0; } }; struct DeflateRep_ : BaseRep_ { DeflateRep_ (const Streams::InputStream<byte>::Ptr& in) : BaseRep_{in} { int level = Z_DEFAULT_COMPRESSION; ThrowIfZLibErr_ (::deflateInit (&fZStream_, level)); } virtual ~DeflateRep_ () { Verify (::deflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override { Require (intoStart < intoEnd); // API rule for streams Require (IsOpenRead ()); Again: bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF (); Require (intoStart < intoEnd); ptrdiff_t outBufSize = intoEnd - intoStart; int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH; fZStream_.avail_out = static_cast<uInt> (outBufSize); fZStream_.next_out = reinterpret_cast<Bytef*> (intoStart); int ret; switch (ret = ::deflate (&fZStream_, flush)) { case Z_OK: break; case Z_STREAM_END: break; default: ThrowIfZLibErr_ (ret); } ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out; Assert (pulledOut <= outBufSize); if (pulledOut == 0 and not isAtSrcEOF and flush == Z_NO_FLUSH) { goto Again; } _fSeekOffset += pulledOut; return pulledOut; } virtual optional<size_t> ReadNonBlocking ([[maybe_unused]] ElementType* intoStart, [[maybe_unused]] ElementType* intoEnd) override { Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); Require (IsOpenRead ()); // https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - INCOMPLETE IMPL #if 0 if (intoStart == nullptr) { // Just check if any data available } else { Assert (intoStart < intoEnd); Again: if (fZStream_.avail_in == 0) { Assert (Memory::NEltsOf (fInBuf_) < numeric_limits<uInt>::max ()); if (auto o = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) { fZStream_.avail_in = static_cast<uInt> (*o); fZStream_.next_in = begin (fInBuf_); } else { return {}; } } ptrdiff_t outBufSize = intoEnd - intoStart; fZStream_.avail_out = static_cast<uInt> (outBufSize); fZStream_.next_out = intoStart; bool isAtSrcEOF = fZStream_.avail_in == 0; int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH; int ret; switch (ret = ::deflate (&fZStream_, flush)) { case Z_OK: break; case Z_STREAM_END: break; default: ThrowIfZLibErr_ (ret); } ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out; Assert (pulledOut <= outBufSize); if (pulledOut == 0 and not isAtSrcEOF) { goto Again; } _fSeekOffset += pulledOut; return pulledOut; } #else // while nothing available to output, try getting more from input stream until we cannot (either cuz {} or EOF) // and then report accordingly // // INCOMPLETE - tricky... most common cases easy, but edges hard... //&&&& issues are: //>> wrong meaning for available_out - we have no output buffer // >> need output buffer for this API, since could pass in no argument buffer (OK to be one byte in that case) while (fZStream_.avail_out == 0) { if (fZStream_.avail_in == 0) { if (optional<size_t> tmpAvail = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) { } else { return {}; } } } #endif WeakAssert (false); // @todo - FIX TO REALLY CHECK return {}; } }; struct InflateRep_ : BaseRep_ { InflateRep_ (const Streams::InputStream<byte>::Ptr& in) : BaseRep_{in} { // see http://zlib.net/manual.html for meaning of params and http://www.lemoda.net/c/zlib-open-read/ for example constexpr int windowBits = 15; constexpr int ENABLE_ZLIB_GZIP = 32; ThrowIfZLibErr_ (::inflateInit2 (&fZStream_, windowBits | ENABLE_ZLIB_GZIP)); } virtual ~InflateRep_ () { Verify (::inflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override { Require (intoStart < intoEnd); // API rule for streams Require (IsOpenRead ()); Again: bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF (); ptrdiff_t outBufSize = intoEnd - intoStart; fZStream_.avail_out = static_cast<uInt> (outBufSize); fZStream_.next_out = reinterpret_cast<Bytef*> (intoStart); int ret; switch (ret = ::inflate (&fZStream_, Z_NO_FLUSH)) { case Z_OK: break; case Z_STREAM_END: break; default: ThrowIfZLibErr_ (ret); } ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out; Assert (pulledOut <= outBufSize); if (pulledOut == 0 and not isAtSrcEOF) { goto Again; } _fSeekOffset += pulledOut; return pulledOut; } virtual optional<size_t> ReadNonBlocking ([[maybe_unused]] ElementType* intoStart, [[maybe_unused]] ElementType* intoEnd) override { // https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - incomplete IMPL Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); Require (IsOpenRead ()); WeakAssert (false); // @todo - FIX TO REALLY CHECK return {}; } }; enum Compression { eCompression }; enum DeCompression { eDeCompression }; MyCompressionStream_ (Compression, const Streams::InputStream<byte>::Ptr& in) : InputStream<byte>::Ptr{make_shared<DeflateRep_> (in)} { } MyCompressionStream_ (DeCompression, const Streams::InputStream<byte>::Ptr& in) : InputStream<byte>::Ptr{make_shared<InflateRep_> (in)} { } }; } #endif #if qHasFeature_ZLib class Zip::Reader::Rep_ : public Reader::_IRep { public: virtual InputStream<byte>::Ptr Compress (const InputStream<byte>::Ptr& src) const override { return MyCompressionStream_ (MyCompressionStream_::eCompression, src); } virtual InputStream<byte>::Ptr Decompress (const InputStream<byte>::Ptr& src) const override { return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src); } }; Zip::Reader::Reader () : DataExchange::Compression::Reader{make_shared<Rep_> ()} { } #endif <|endoftext|>
<commit_before>// // Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include <atria/xform/concepts.hpp> #include <atria/xform/into_vector.hpp> #include <atria/xform/transducer/product.hpp> #include <atria/xform/transducer/take.hpp> #include <atria/prelude/comp.hpp> #include <atria/testing/gtest.hpp> namespace atria { namespace xform { TEST(product, product) { using tup = std::tuple<int, int>; auto v1 = std::vector<int> { 1, 2 }; auto v2 = std::vector<int> { 4, 5 }; auto res = into_vector(product(v2), v1); EXPECT_EQ(res, (decltype(res) { tup(1, 4), tup(1, 5), tup(2, 4), tup(2, 5) })); } TEST(product, variadic) { using tup = std::tuple<int, int, char>; auto v1 = std::vector<int> { 1, 2 }; auto v2 = std::vector<int> { 4, 5 }; auto v3 = std::vector<char> { 'a', 'b' }; auto res = into_vector(product(v2, v3), v1); EXPECT_EQ(res, (decltype(res) { tup(1, 4, 'a'), tup(1, 4, 'b'), tup(1, 5, 'a'), tup(1, 5, 'b'), tup(2, 4, 'a'), tup(2, 4, 'b'), tup(2, 5, 'a'), tup(2, 5, 'b') })); } TEST(product, generator) { using tup = std::tuple<int, int>; auto v1 = std::vector<int> { 1, 2 }; auto v2 = std::vector<int> { 4, 5 }; auto res = into_vector(comp(take(1), product(v1, v2))); EXPECT_EQ(res, (decltype(res) { tup(1, 4), tup(1, 5), tup(2, 4), tup(2, 5) })); } } // namespace xform } // namespace atria <commit_msg>xform: add example for issue #13<commit_after>// // Copyright (C) 2014, 2015, 2016 Ableton AG, Berlin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include <atria/xform/concepts.hpp> #include <atria/xform/into_vector.hpp> #include <atria/xform/transducer/product.hpp> #include <atria/xform/transducer/range.hpp> #include <atria/xform/transducer/take.hpp> #include <atria/xform/sequence.hpp> #include <atria/prelude/comp.hpp> #include <atria/testing/gtest.hpp> namespace atria { namespace xform { TEST(product, product) { using tup = std::tuple<int, int>; auto v1 = std::vector<int> { 1, 2 }; auto v2 = std::vector<int> { 4, 5 }; auto res = into_vector(product(v2), v1); EXPECT_EQ(res, (decltype(res) { tup(1, 4), tup(1, 5), tup(2, 4), tup(2, 5) })); } TEST(product, variadic) { using tup = std::tuple<int, int, char>; auto v1 = std::vector<int> { 1, 2 }; auto v2 = std::vector<int> { 4, 5 }; auto v3 = std::vector<char> { 'a', 'b' }; auto res = into_vector(product(v2, v3), v1); EXPECT_EQ(res, (decltype(res) { tup(1, 4, 'a'), tup(1, 4, 'b'), tup(1, 5, 'a'), tup(1, 5, 'b'), tup(2, 4, 'a'), tup(2, 4, 'b'), tup(2, 5, 'a'), tup(2, 5, 'b') })); } TEST(product, generator) { using tup = std::tuple<int, int>; auto v1 = std::vector<int> { 1, 2 }; auto v2 = std::vector<int> { 4, 5 }; auto res = into_vector(comp(take(1), product(v1, v2))); EXPECT_EQ(res, (decltype(res) { tup(1, 4), tup(1, 5), tup(2, 4), tup(2, 5) })); } TEST(product, tranducer_product_example) { using tup = std::tuple<int, int>; auto idx = sequence(range(2)); auto res = into_vector(product(idx), idx); EXPECT_EQ(res, (decltype(res) { tup(0, 0), tup(0, 1), tup(1, 0), tup(1, 1) })); } } // namespace xform } // namespace atria <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2020, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <backend.hpp> #include <memory.hpp> #include <platform.hpp> #include <thrust/system/cuda/execution_policy.h> namespace cuda { struct ThrustArrayFirePolicy : thrust::cuda::execution_policy<ThrustArrayFirePolicy> {}; template<typename T> thrust::pair<thrust::pointer<T, ThrustArrayFirePolicy>, std::ptrdiff_t> get_temporary_buffer(ThrustArrayFirePolicy, std::ptrdiff_t n) { thrust::pointer<T, ThrustArrayFirePolicy> result( cuda::memAlloc<T>(n / sizeof(T)).release()); return thrust::make_pair(result, n); } template<typename Pointer> inline void return_temporary_buffer(ThrustArrayFirePolicy, Pointer p) { memFree(thrust::raw_pointer_cast(p)); } } // namespace cuda namespace thrust { namespace cuda_cub { template<> __DH__ inline cudaStream_t get_stream<::cuda::ThrustArrayFirePolicy>( execution_policy<::cuda::ThrustArrayFirePolicy> &) { #if defined(__CUDA_ARCH__) return 0; #else return ::cuda::getActiveStream(); #endif } __DH__ inline cudaError_t synchronize_stream(const ::cuda::ThrustArrayFirePolicy &) { #if defined(__CUDA_ARCH__) return cudaDeviceSynchronize(); #else return cudaStreamSynchronize(::cuda::getActiveStream()); #endif } } // namespace cuda_cub } // namespace thrust <commit_msg>Remove cudaDeviceSynchronize from the ThrustArrayFirePolicy<commit_after>/******************************************************* * Copyright (c) 2020, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <backend.hpp> #include <memory.hpp> #include <platform.hpp> #include <thrust/system/cuda/execution_policy.h> namespace cuda { struct ThrustArrayFirePolicy : thrust::cuda::execution_policy<ThrustArrayFirePolicy> {}; template<typename T> thrust::pair<thrust::pointer<T, ThrustArrayFirePolicy>, std::ptrdiff_t> get_temporary_buffer(ThrustArrayFirePolicy, std::ptrdiff_t n) { thrust::pointer<T, ThrustArrayFirePolicy> result( cuda::memAlloc<T>(n / sizeof(T)).release()); return thrust::make_pair(result, n); } template<typename Pointer> inline void return_temporary_buffer(ThrustArrayFirePolicy, Pointer p) { memFree(thrust::raw_pointer_cast(p)); } } // namespace cuda namespace thrust { namespace cuda_cub { template<> __DH__ inline cudaStream_t get_stream<::cuda::ThrustArrayFirePolicy>( execution_policy<::cuda::ThrustArrayFirePolicy> &) { #if defined(__CUDA_ARCH__) return 0; #else return ::cuda::getActiveStream(); #endif } __DH__ inline cudaError_t synchronize_stream(const ::cuda::ThrustArrayFirePolicy &) { #if defined(__CUDA_ARCH__) return cudaSuccess; #else return cudaStreamSynchronize(::cuda::getActiveStream()); #endif } } // namespace cuda_cub } // namespace thrust <|endoftext|>
<commit_before>/** * Copyright (C) 2015 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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 <iostream> #include <string> #include <stdexcept> #include <tclap/CmdLine.h> #include <virgil/sdk/ServicesHub.h> #include <virgil/sdk/io/Marshaller.h> #include <cli/version.h> #include <cli/config.h> #include <cli/pair.h> #include <cli/util.h> namespace vsdk = virgil::sdk; namespace vcrypto = virgil::crypto; namespace vcli = virgil::cli; #ifdef SPLIT_CLI #define MAIN main #else #define MAIN card_search_app_main #endif int MAIN(int argc, char** argv) { try { std::string description = "Search for an Application Virgil Card from the Virgil Keys service.\n"; std::vector<std::string> examples; examples.push_back("Search for application cards:\n" "Virgil card-search-app -c <app_name>\n"); examples.push_back("Get all application cards:\n" "Virgil card-search-app -c \"*\"\n"); std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples); // Parse arguments. TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version()); TCLAP::ValueArg<std::string> outArg("o", "out", "Application cards. If omitted, stdout is used.", false, "", "file"); TCLAP::ValueArg<std::string> applicationNameArg( "c", "application-name", "Application name, name = '*' - get all Cards\n", true, "", "arg"); cmd.add(applicationNameArg); cmd.add(outArg); cmd.parse(argc, argv); vsdk::ServicesHub servicesHub(VIRGIL_ACCESS_TOKEN); std::string appName = "com.virgilsecurity." + applicationNameArg.getValue(); std::vector<vsdk::models::CardModel> appCards = servicesHub.card().searchApp(appName); std::string appCardsStr = virgil::sdk::io::cardsToJson(appCards, 4); vcli::writeBytes(outArg.getValue(), appCardsStr); if (appCards.empty()) { std::cout << "Application card by name: " << applicationNameArg.getValue() << " hasn't been found" << std::endl; } else { std::cout << "Application card by name: " << applicationNameArg.getValue() << " has been received" << std::endl; } } catch (TCLAP::ArgException& exception) { std::cerr << "card-search-app. Error: " << exception.error() << " for arg " << exception.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& exception) { std::cerr << "card-search-app. Error: " << exception.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>'card-search-app' - saves Application Cards found in separate files<commit_after>/** * Copyright (C) 2015 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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 <iostream> #include <string> #include <stdexcept> #include <tclap/CmdLine.h> #include <virgil/sdk/ServicesHub.h> #include <virgil/sdk/io/Marshaller.h> #include <cli/version.h> #include <cli/config.h> #include <cli/pair.h> #include <cli/util.h> namespace vsdk = virgil::sdk; namespace vcrypto = virgil::crypto; namespace vcli = virgil::cli; #ifdef SPLIT_CLI #define MAIN main #else #define MAIN card_search_app_main #endif int MAIN(int argc, char** argv) { try { std::string description = "Search for an Application Virgil Card from the Virgil Keys service.\n"; std::vector<std::string> examples; examples.push_back("Search for application cards:\n" "Virgil card-search-app -c <app_name>\n"); examples.push_back("Get all application cards:\n" "Virgil card-search-app -c \"*\"\n"); std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples); // Parse arguments. TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version()); TCLAP::ValueArg<std::string> outArg("o", "out", "Folder in which will be saved a Virgil Cards", false, "", "arg"); TCLAP::ValueArg<std::string> applicationNameArg( "c", "application-name", "Application name, name = '*' - get all Cards\n", true, "", "arg"); cmd.add(applicationNameArg); cmd.add(outArg); cmd.parse(argc, argv); vsdk::ServicesHub servicesHub(VIRGIL_ACCESS_TOKEN); std::string appName = "com.virgilsecurity." + applicationNameArg.getValue(); std::vector<vsdk::models::CardModel> appCards = servicesHub.card().searchApp(appName); if (appCards.empty()) { std::cout << "Cards by name: " << applicationNameArg.getValue() << " haven't been found." << std::endl; return EXIT_FAILURE; } std::string pathTofolder = outArg.getValue(); if (pathTofolder.empty()) { for(auto&& appCard : appCards) { std::string appCardStr = vsdk::io::Marshaller<vsdk::models::CardModel>::toJson<4>(appCard); vcli::writeBytes(pathTofolder, appCardStr); } } else { for(auto&& appCard : appCards) { std::string identity = appCard.getCardIdentity().getValue(); std::string cardId = appCard.getId(); std::string fileName = identity + "-id-" + appCard.getId() + ".vcard"; std::string appCardStr = vsdk::io::Marshaller<vsdk::models::CardModel>::toJson<4>(appCard); vcli::writeBytes(pathTofolder + "/" + fileName, appCardStr); } } std::cout << "По заданному application name:" << applicationNameArg.getValue() << " получено " << appCards.size() << " Карт." << std::endl; } catch (TCLAP::ArgException& exception) { std::cerr << "card-search-app. Error: " << exception.error() << " for arg " << exception.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& exception) { std::cerr << "card-search-app. Error: " << exception.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <fstream> #include <essentia/algorithmfactory.h> #include <essentia/pool.h> #include <essentia/essentiamath.h> //#define INCLUDE_DELTA_SC using namespace std; using namespace essentia; using namespace standard; int main(int argc, char* argv[]) { if (argc != 3) { cout << "ERROR: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input yaml_output" << endl; exit(1); } string audioFilename = argv[1]; string outputFilename = argv[2]; essentia::init(); /********** SETUP ALGORITHMS **********/ int frameSize = 2048; int hopSize = 1024; int sampleRate = 44100; AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* audio = factory.create("EqloudLoader", "filename", audioFilename, "sampleRate", sampleRate, "replayGain", -6.0); Algorithm* fcutter = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize); Algorithm* window = factory.create("Windowing", "type", "blackmanharris62"); Algorithm* fft = factory.create("Spectrum"); Algorithm* sc = factory.create("SpectralContrast", "frameSize", frameSize, "sampleRate", sampleRate, "numberBands", 6, "lowFrequencyBound", 20, "highFrequencyBound", 11000, "neighbourRatio", 0.4, "staticDistribution", 0.15); /********** SETUP CONNECTIONS **********/ vector<Real> audioBuffer; audio->output("audio").set(audioBuffer); fcutter->input("signal").set(audioBuffer); vector<Real> frame, windowedFrame; fcutter->output("frame").set(frame); window->input("frame").set(frame); window->output("frame").set(windowedFrame); fft->input("frame").set(windowedFrame); vector<Real> spectrum; fft->output("spectrum").set(spectrum); sc->input("spectrum").set(spectrum); vector<Real> sccoeffs; vector<Real> scvalleys; sc->output("spectralContrast").set(sccoeffs); sc->output("spectralValley").set(scvalleys); /********** COMPUTATION **********/ audio->compute(); Pool poolSc, poolTransformed, poolOut; #ifdef INCLUDE_DELTA_SC bool add = false; vector<Real> prevFrame; #endif /**** frame by frame ****/ while (true) { // get a single frame fcutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) break; // if the frame is silent, just drop it and go on processing if (isSilent(frame)) continue; // C.O.M.P.U.T.E. window->compute(); fft->compute(); sc->compute(); // merge the valleys and the contrasts so they can be transformed in one go vector<Real> merged; for(uint i=0; i<sccoeffs.size(); i++) { merged.push_back(sccoeffs[i]); merged.push_back(scvalleys[i]); } #ifndef INCLUDE_DELTA_SC poolSc.add("contrast", merged); #endif #ifdef INCLUDE_DELTA_SC uint size = merged.size(); if(add) { vector<Real> diff; for(uint i=0; i<size; i++) { merged.push_back(merged[i]-prevFrame[i]); } poolSc.add("contrast", merged); } prevFrame.clear(); for(uint i=0; i<size; i++) prevFrame.push_back(merged[i]); add = true; #endif // INCLUDE_DELTA_SC } /**** song by song ****/ // do the PCA Algorithm* pca = AlgorithmFactory::create("PCA", "namespaceIn", "contrast", "namespaceOut", "contrast"); pca->input("poolIn").set(poolSc); pca->output("poolOut").set(poolTransformed); pca->compute(); /* without PCA vector<vector<Real> > rawFeats = poolSC.value<vector<Real> >("contrast"); poolOUT.add("contrast.means", meanFrames(rawFeats)); poolOUT.add("contrast.vars" , varianceFrames(rawFeats)); */ poolOut.add("contrast.means", meanFrames(poolTransformed.value<vector<vector<Real> > >("contrast"))); poolOut.add("contrast.variances", varianceFrames(poolTransformed.value<vector<vector<Real> > >("contrast"))); // write yaml file Algorithm* output = AlgorithmFactory::create("YamlOutput", "filename", outputFilename); output->input("pool").set(poolOut); output->compute(); // clean up delete audio; delete fcutter; delete window; delete fft; delete sc; delete pca; delete output; essentia::shutdown(); return 0; } <commit_msg>fixed spectral contrast extractor (removed pca, output both coeffs and valleys separately)<commit_after>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <fstream> #include <essentia/algorithmfactory.h> #include <essentia/pool.h> #include <essentia/essentiamath.h> using namespace std; using namespace essentia; using namespace standard; int main(int argc, char* argv[]) { if (argc != 3) { cout << "ERROR: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input yaml_output" << endl; exit(1); } string audioFilename = argv[1]; string outputFilename = argv[2]; essentia::init(); /********** SETUP ALGORITHMS **********/ int frameSize = 2048; int hopSize = 1024; int sampleRate = 44100; AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* audio = factory.create("EqloudLoader", "filename", audioFilename, "sampleRate", sampleRate, "replayGain", -6.0); Algorithm* fcutter = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize); Algorithm* window = factory.create("Windowing", "type", "blackmanharris62"); Algorithm* fft = factory.create("Spectrum"); Algorithm* sc = factory.create("SpectralContrast", "frameSize", frameSize, "sampleRate", sampleRate, "numberBands", 6, "lowFrequencyBound", 20, "highFrequencyBound", 11000, "neighbourRatio", 0.4, "staticDistribution", 0.15); /********** SETUP CONNECTIONS **********/ vector<Real> audioBuffer; audio->output("audio").set(audioBuffer); fcutter->input("signal").set(audioBuffer); vector<Real> frame, windowedFrame; fcutter->output("frame").set(frame); window->input("frame").set(frame); window->output("frame").set(windowedFrame); fft->input("frame").set(windowedFrame); vector<Real> spectrum; fft->output("spectrum").set(spectrum); sc->input("spectrum").set(spectrum); vector<Real> sccoeffs; vector<Real> scvalleys; sc->output("spectralContrast").set(sccoeffs); sc->output("spectralValley").set(scvalleys); /********** COMPUTATION **********/ audio->compute(); Pool poolSc, poolOut; /**** frame by frame ****/ while (true) { // get a single frame fcutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) break; // if the frame is silent, just drop it and go on processing if (isSilent(frame)) continue; // compute window->compute(); fft->compute(); sc->compute(); poolSc.add("contrast_coeffs", sccoeffs); poolSc.add("contrast_valleys", scvalleys); } poolOut.add("contrast_coeffs.means", meanFrames(poolSc.value<vector<vector<Real> > >("contrast_coeffs"))); poolOut.add("contrast_coeffs.vars" , varianceFrames(poolSc.value<vector<vector<Real> > >("contrast_coeffs"))); poolOut.add("contrast_valleys.means", meanFrames(poolSc.value<vector<vector<Real> > >("contrast_valleys"))); poolOut.add("contrast_valleys.vars" , varianceFrames(poolSc.value<vector<vector<Real> > >("contrast_valleys"))); // write yaml file Algorithm* output = AlgorithmFactory::create("YamlOutput", "filename", outputFilename); output->input("pool").set(poolOut); output->compute(); // clean up delete audio; delete fcutter; delete window; delete fft; delete sc; delete output; essentia::shutdown(); return 0; } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2014, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file TivaNRZ.hxx * * Device driver for TivaWare to decode DCC track signal. * * @author Balazs Racz * @date 29 Nov 2014 */ #include "TivaDCC.hxx" // for FixedQueue #include "TivaGPIO.hxx" // for debug pins #include "dcc/Receiver.hxx" typedef DummyPin PIN_RailcomCutout; #define SIGNAL_LEVEL_ONE 0x80000000UL /* struct DCCDecode { static const auto TIMER_BASE = WTIMER4_BASE; static const auto TIMER_PERIPH = SYSCTL_PERIPH_WTIMER4; static const auto TIMER_INTERRUPT = INT_WTIMER4A; static const auto TIMER = TIMER_A; static const auto CFG_CAP_TIME_UP = TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_CAP_TIME_UP | TIMER_CFG_B_ONE_SHOT; // Interrupt bits. static const auto TIMER_CAP_EVENT = TIMER_CAPA_EVENT; static const auto TIMER_TIM_TIMEOUT = TIMER_TIMA_TIMEOUT; static const auto OS_INTERRUPT = INT_WTIMER4B; DECL_PIN(NRZPIN, D, 4); static const auto NRZPIN_CONFIG = GPIO_PD4_WT4CCP0; static const uint32_t TIMER_MAX_VALUE = 0x8000000UL; static const int Q_SIZE = 16; }; */ template <class HW> class TivaDccDecoder : public Node { public: TivaDccDecoder(const char *name); ~TivaDccDecoder() { } /** Handles a raw interrupt. */ inline void interrupt_handler() __attribute__((always_inline)); /** Handles a software interrupt to FreeRTOS. */ inline void os_interrupt_handler() __attribute__((always_inline)); private: /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ ssize_t read(File *file, void *buf, size_t count) OVERRIDE; /** Write to a file or device. * @param file file reference for this device * @param buf location to find write data * @param count number of bytes to write * @return number of bytes written upon success, -1 upon failure with errno * containing the cause */ ssize_t write(File *file, const void *buf, size_t count) OVERRIDE { return -EINVAL; } /** Request an ioctl transaction * @param file file reference for this device * @param node node reference for this device * @param key ioctl key * @param data key data */ int ioctl(File *file, unsigned long int key, unsigned long data) OVERRIDE; void enable(); /**< function to enable device */ void disable(); /**< function to disable device */ /** Discards all pending buffers. Called after disable(). */ void flush_buffers() { while (!inputData_.empty()) { inputData_.increment_front(); } }; FixedQueue<uint32_t, HW::Q_SIZE> inputData_; uint32_t lastTimerValue_; uint32_t reloadCount_; unsigned lastLevel_; bool overflowed_ = false; Notifiable *readableNotifiable_ = nullptr; dcc::DccDecoder decoder_; DISALLOW_COPY_AND_ASSIGN(TivaDccDecoder); }; template <class HW> TivaDccDecoder<HW>::TivaDccDecoder(const char *name) : Node(name) { MAP_SysCtlPeripheralEnable(HW::TIMER_PERIPH); MAP_SysCtlPeripheralEnable(HW::NRZPIN_PERIPH); MAP_GPIOPinConfigure(HW::NRZPIN_CONFIG); MAP_GPIOPinTypeTimer(HW::NRZPIN_BASE, HW::NRZPIN_PIN); disable(); } template <class HW> void TivaDccDecoder<HW>::enable() { disable(); MAP_TimerClockSourceSet(HW::TIMER_BASE, TIMER_CLOCK_SYSTEM); MAP_TimerConfigure(HW::TIMER_BASE, HW::CFG_CAP_TIME_UP); MAP_TimerControlStall(HW::TIMER_BASE, HW::TIMER, true); MAP_TimerControlEvent(HW::TIMER_BASE, HW::TIMER, TIMER_EVENT_BOTH_EDGES); MAP_TimerLoadSet(HW::TIMER_BASE, HW::TIMER, HW::TIMER_MAX_VALUE); MAP_TimerPrescaleSet(HW::TIMER_BASE, HW::TIMER, HW::PS_MAX); reloadCount_ = 0; lastTimerValue_ = 0; MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); MAP_IntPrioritySet(HW::TIMER_INTERRUPT, 0); MAP_IntPrioritySet(HW::OS_INTERRUPT, configKERNEL_INTERRUPT_PRIORITY); MAP_IntEnable(HW::OS_INTERRUPT); MAP_IntEnable(HW::TIMER_INTERRUPT); MAP_TimerEnable(HW::TIMER_BASE, HW::TIMER); } template <class HW> void TivaDccDecoder<HW>::disable() { MAP_IntDisable(HW::TIMER_INTERRUPT); MAP_IntDisable(HW::OS_INTERRUPT); MAP_TimerDisable(HW::TIMER_BASE, HW::TIMER); } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::interrupt_handler() { // get masked interrupt status auto status = MAP_TimerIntStatus(HW::TIMER_BASE, true); if (status & HW::TIMER_TIM_TIMEOUT) { // The timer got reloaded. reloadCount_++; MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); } // TODO(balazs.racz): Technically it is possible that the timer reload // happens between the event match and the interrupt entry. In this case we // will incorrectly add a full cycle to the event length. if (status & HW::TIMER_CAP_EVENT) { MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); static uint32_t raw_new_value; raw_new_value = MAP_TimerValueGet(HW::TIMER_BASE, HW::TIMER); static uint32_t new_value; new_value = raw_new_value; while (reloadCount_ > 0) { new_value += HW::TIMER_MAX_VALUE; reloadCount_--; } //HASSERT(new_value > lastTimerValue_); new_value -= lastTimerValue_; /*if (!inputData_.full()) { inputData_.back() = overflowed_ ? 3 : new_value; overflowed_ = false; inputData_.increment_back(); } else { overflowed_ = true; }*/ decoder_.process_data(new_value); if (decoder_.state() == dcc::DccDecoder::DCC_MAYBE_CUTOUT) { PIN_RailcomCutout::set(true); for (unsigned i = 0; i < ARRAYSIZE(HW::RAILCOM_UART_BASE); ++i) { HWREG(HW::RAILCOM_UART_BASE[i] + UART_O_CTL) |= UART_CTL_RXE; } } else if (decoder_.state() == dcc::DccDecoder::DCC_PREAMBLE) { PIN_RailcomCutout::set(false); } lastTimerValue_ = raw_new_value; MAP_IntPendSet(HW::OS_INTERRUPT); } } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::os_interrupt_handler() { if (!inputData_.empty()) { Notifiable *n = readableNotifiable_; readableNotifiable_ = nullptr; if (n) { n->notify_from_isr(); os_isr_exit_yield_test(true); } } } template <class HW> int TivaDccDecoder<HW>::ioctl(File *file, unsigned long int key, unsigned long data) { if (IOC_TYPE(key) == CAN_IOC_MAGIC && IOC_SIZE(key) == NOTIFIABLE_TYPE && key == CAN_IOC_READ_ACTIVE) { Notifiable *n = reinterpret_cast<Notifiable *>(data); HASSERT(n); // If there is no data for reading, we put the incoming notification // into the holder. Otherwise we notify it immediately. if (inputData_.empty()) { portENTER_CRITICAL(); if (inputData_.empty()) { // We are in a critical section now. If we got into this // branch, then the buffer was full at the beginning of the // critical section. If the hardware interrupt kicks in now, // and sets the os_interrupt to pending, the os interrupt will // not happen until we leave the critical section, and thus the // swap will be in effect by then. swap(n, readableNotifiable_); } portEXIT_CRITICAL(); } if (n) { n->notify(); } return 0; } errno = EINVAL; return -1; } /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno containing the cause */ template<class HW> ssize_t TivaDccDecoder<HW>::read(File *file, void *buf, size_t count) { if (count != 4) { return -EINVAL; } // We only need this critical section to prevent concurrent threads from // reading at the same time. portENTER_CRITICAL(); if (inputData_.empty()) { portEXIT_CRITICAL(); return -EAGAIN; } uint32_t v = reinterpret_cast<uint32_t>(buf); HASSERT((v & 3) == 0); // alignment check. uint32_t* pv = static_cast<uint32_t*>(buf); *pv = inputData_.front(); inputData_.increment_front(); portEXIT_CRITICAL(); return count; } <commit_msg>removes direct access to the railcom UART registers and adds railcom driver pointer for notifying about the cutout.<commit_after>/** \copyright * Copyright (c) 2014, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file TivaNRZ.hxx * * Device driver for TivaWare to decode DCC track signal. * * @author Balazs Racz * @date 29 Nov 2014 */ #include "TivaDCC.hxx" // for FixedQueue #include "TivaGPIO.hxx" // for pin definitions #include "RailcomDriver.hxx" // for debug pins #include "dcc/Receiver.hxx" typedef DummyPin PIN_RailcomCutout; #define SIGNAL_LEVEL_ONE 0x80000000UL /* struct DCCDecode { static const auto TIMER_BASE = WTIMER4_BASE; static const auto TIMER_PERIPH = SYSCTL_PERIPH_WTIMER4; static const auto TIMER_INTERRUPT = INT_WTIMER4A; static const auto TIMER = TIMER_A; static const auto CFG_CAP_TIME_UP = TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_CAP_TIME_UP | TIMER_CFG_B_ONE_SHOT; // Interrupt bits. static const auto TIMER_CAP_EVENT = TIMER_CAPA_EVENT; static const auto TIMER_TIM_TIMEOUT = TIMER_TIMA_TIMEOUT; static const auto OS_INTERRUPT = INT_WTIMER4B; DECL_PIN(NRZPIN, D, 4); static const auto NRZPIN_CONFIG = GPIO_PD4_WT4CCP0; static const uint32_t TIMER_MAX_VALUE = 0x8000000UL; static const int Q_SIZE = 16; }; */ template <class HW> class TivaDccDecoder : public Node { public: TivaDccDecoder(const char *name, RailcomDriver *railcom_driver); ~TivaDccDecoder() { } /** Handles a raw interrupt. */ inline void interrupt_handler() __attribute__((always_inline)); /** Handles a software interrupt to FreeRTOS. */ inline void os_interrupt_handler() __attribute__((always_inline)); private: /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ ssize_t read(File *file, void *buf, size_t count) OVERRIDE; /** Write to a file or device. * @param file file reference for this device * @param buf location to find write data * @param count number of bytes to write * @return number of bytes written upon success, -1 upon failure with errno * containing the cause */ ssize_t write(File *file, const void *buf, size_t count) OVERRIDE { return -EINVAL; } /** Request an ioctl transaction * @param file file reference for this device * @param node node reference for this device * @param key ioctl key * @param data key data */ int ioctl(File *file, unsigned long int key, unsigned long data) OVERRIDE; void enable(); /**< function to enable device */ void disable(); /**< function to disable device */ /** Discards all pending buffers. Called after disable(). */ void flush_buffers() { while (!inputData_.empty()) { inputData_.increment_front(); } }; FixedQueue<uint32_t, HW::Q_SIZE> inputData_; uint32_t lastTimerValue_; uint32_t reloadCount_; unsigned lastLevel_; bool overflowed_ = false; Notifiable *readableNotifiable_ = nullptr; RailcomDriver *railcomDriver_; //< notified for cutout events. dcc::DccDecoder decoder_; DISALLOW_COPY_AND_ASSIGN(TivaDccDecoder); }; template <class HW> TivaDccDecoder<HW>::TivaDccDecoder(const char *name, RailcomDriver *railcom_driver) : Node(name) , railcomDriver_(railcom_driver) { MAP_SysCtlPeripheralEnable(HW::TIMER_PERIPH); MAP_SysCtlPeripheralEnable(HW::NRZPIN_PERIPH); MAP_GPIOPinConfigure(HW::NRZPIN_CONFIG); MAP_GPIOPinTypeTimer(HW::NRZPIN_BASE, HW::NRZPIN_PIN); disable(); } template <class HW> void TivaDccDecoder<HW>::enable() { disable(); MAP_TimerClockSourceSet(HW::TIMER_BASE, TIMER_CLOCK_SYSTEM); MAP_TimerConfigure(HW::TIMER_BASE, HW::CFG_CAP_TIME_UP); MAP_TimerControlStall(HW::TIMER_BASE, HW::TIMER, true); MAP_TimerControlEvent(HW::TIMER_BASE, HW::TIMER, TIMER_EVENT_BOTH_EDGES); MAP_TimerLoadSet(HW::TIMER_BASE, HW::TIMER, HW::TIMER_MAX_VALUE); MAP_TimerPrescaleSet(HW::TIMER_BASE, HW::TIMER, HW::PS_MAX); reloadCount_ = 0; lastTimerValue_ = 0; MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); MAP_IntPrioritySet(HW::TIMER_INTERRUPT, 0); MAP_IntPrioritySet(HW::OS_INTERRUPT, configKERNEL_INTERRUPT_PRIORITY); MAP_IntEnable(HW::OS_INTERRUPT); MAP_IntEnable(HW::TIMER_INTERRUPT); MAP_TimerEnable(HW::TIMER_BASE, HW::TIMER); } template <class HW> void TivaDccDecoder<HW>::disable() { MAP_IntDisable(HW::TIMER_INTERRUPT); MAP_IntDisable(HW::OS_INTERRUPT); MAP_TimerDisable(HW::TIMER_BASE, HW::TIMER); } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::interrupt_handler() { // get masked interrupt status auto status = MAP_TimerIntStatus(HW::TIMER_BASE, true); if (status & HW::TIMER_TIM_TIMEOUT) { // The timer got reloaded. reloadCount_++; MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); } // TODO(balazs.racz): Technically it is possible that the timer reload // happens between the event match and the interrupt entry. In this case we // will incorrectly add a full cycle to the event length. if (status & HW::TIMER_CAP_EVENT) { MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); static uint32_t raw_new_value; raw_new_value = MAP_TimerValueGet(HW::TIMER_BASE, HW::TIMER); static uint32_t new_value; new_value = raw_new_value; while (reloadCount_ > 0) { new_value += HW::TIMER_MAX_VALUE; reloadCount_--; } // HASSERT(new_value > lastTimerValue_); new_value -= lastTimerValue_; /*if (!inputData_.full()) { inputData_.back() = overflowed_ ? 3 : new_value; overflowed_ = false; inputData_.increment_back(); } else { overflowed_ = true; }*/ decoder_.process_data(new_value); if (decoder_.state() == dcc::DccDecoder::DCC_MAYBE_CUTOUT) { railcomDriver_->start_cutout(); } /// TODO(balazs.racz) recognize middle cutout. else if (decoder_.state() == dcc::DccDecoder::DCC_PREAMBLE) { railcomDriver_->end_cutout(); } lastTimerValue_ = raw_new_value; MAP_IntPendSet(HW::OS_INTERRUPT); } } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::os_interrupt_handler() { if (!inputData_.empty()) { Notifiable *n = readableNotifiable_; readableNotifiable_ = nullptr; if (n) { n->notify_from_isr(); os_isr_exit_yield_test(true); } } } template <class HW> int TivaDccDecoder<HW>::ioctl(File *file, unsigned long int key, unsigned long data) { if (IOC_TYPE(key) == CAN_IOC_MAGIC && IOC_SIZE(key) == NOTIFIABLE_TYPE && key == CAN_IOC_READ_ACTIVE) { Notifiable *n = reinterpret_cast<Notifiable *>(data); HASSERT(n); // If there is no data for reading, we put the incoming notification // into the holder. Otherwise we notify it immediately. if (inputData_.empty()) { portENTER_CRITICAL(); if (inputData_.empty()) { // We are in a critical section now. If we got into this // branch, then the buffer was full at the beginning of the // critical section. If the hardware interrupt kicks in now, // and sets the os_interrupt to pending, the os interrupt will // not happen until we leave the critical section, and thus the // swap will be in effect by then. swap(n, readableNotifiable_); } portEXIT_CRITICAL(); } if (n) { n->notify(); } return 0; } errno = EINVAL; return -1; } /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ template <class HW> ssize_t TivaDccDecoder<HW>::read(File *file, void *buf, size_t count) { if (count != 4) { return -EINVAL; } // We only need this critical section to prevent concurrent threads from // reading at the same time. portENTER_CRITICAL(); if (inputData_.empty()) { portEXIT_CRITICAL(); return -EAGAIN; } uint32_t v = reinterpret_cast<uint32_t>(buf); HASSERT((v & 3) == 0); // alignment check. uint32_t *pv = static_cast<uint32_t *>(buf); *pv = inputData_.front(); inputData_.increment_front(); portEXIT_CRITICAL(); return count; } <|endoftext|>
<commit_before>#include "animation.h" #include "abstractframeset.h" #include "limits.h" #include "models/common/namechecks.h" #include <cmath> using namespace UnTech; using namespace UnTech::MetaSpriteCommon; /* * ANIMATION * ========= */ const char* Animation::TYPE_NAME = "Animation"; Animation::Animation(AbstractFrameSet& parent) : _frameSet(parent) , _instructions(*this, MAX_ANIMATION_INSTRUCTIONS) { } Animation::Animation(const Animation& animation, AbstractFrameSet& parent) : _frameSet(parent) , _instructions(*this, MAX_ANIMATION_INSTRUCTIONS) { for (const auto& inst : animation._instructions) { _instructions.clone(inst); } } /* * Valid if: * * has at least one instruction * * instruction ends with a stop or a goto * * all instructions are valid */ bool Animation::isValid() const { if (_instructions.size() == 0) { return false; } if (_instructions.last().operation().isValidTerminator() == false) { return false; } for (unsigned i = 0; i < _instructions.size(); i++) { const auto& inst = _instructions.at(i); if (inst.isValid(i) == false) { return false; } } // ::TODO verify animations do not have an infinite loop:: return true; } /* * ANIMATION INSTRUCTIONS * ====================== */ const char* AnimationInstruction::TYPE_NAME = "Animation Instruction"; AnimationInstruction::AnimationInstruction(Animation& parent) : _animation(parent) , _operation() , _frame() , _parameter(0) { } AnimationInstruction::AnimationInstruction(const AnimationInstruction& ani, Animation& parent) : _animation(parent) , _operation(ani._operation) , _frame(ani._frame) , _parameter(ani._parameter) { } void AnimationInstruction::setParameter(int p) { if (_operation.usesParameter()) { if (_operation.parameterUnsigned()) { if (p >= 0 && p < 256) { _parameter = p; } } else { // parameter is unsigned _parameter = p; } } } void AnimationInstruction::setFrame(const FrameReference& frame) { if (_operation.usesFrame()) { _frame = frame; } } void AnimationInstruction::setGotoLabel(const std::string& label) { if (_operation.usesGotoLabel() && isNameValid(label)) { _gotoLabel = label; } } /* * Valid if: * * GOTO_OFFSET points to an instruction inside the animation * * Animation nane exists in the frameset * * Frame name exists in the frameset */ bool AnimationInstruction::isValid(unsigned position) const { const unsigned MAX_BYTECODE_SIZE = 3; if (_operation == AnimationBytecode::Enum::GOTO_OFFSET) { const int p = _parameter; const unsigned aSize = _animation.instructions().size(); if (p == 0 || p < (int)-position || p >= (int)(aSize - position)) { return false; } if ((unsigned)abs(p) > 256 / MAX_BYTECODE_SIZE) { // simple bounds checking, prevent overflow return false; } } if (_operation.usesGotoLabel()) { if (_animation.frameSet().animations().nameExists(_gotoLabel) == false) { return false; } } if (_operation.usesFrame()) { if (_animation.frameSet().containsFrameName(_frame.frameName) == false) { return false; } } return true; } <commit_msg>fix: forgot field in AnimationInstruction clone constructor<commit_after>#include "animation.h" #include "abstractframeset.h" #include "limits.h" #include "models/common/namechecks.h" #include <cmath> using namespace UnTech; using namespace UnTech::MetaSpriteCommon; /* * ANIMATION * ========= */ const char* Animation::TYPE_NAME = "Animation"; Animation::Animation(AbstractFrameSet& parent) : _frameSet(parent) , _instructions(*this, MAX_ANIMATION_INSTRUCTIONS) { } Animation::Animation(const Animation& animation, AbstractFrameSet& parent) : _frameSet(parent) , _instructions(*this, MAX_ANIMATION_INSTRUCTIONS) { for (const auto& inst : animation._instructions) { _instructions.clone(inst); } } /* * Valid if: * * has at least one instruction * * instruction ends with a stop or a goto * * all instructions are valid */ bool Animation::isValid() const { if (_instructions.size() == 0) { return false; } if (_instructions.last().operation().isValidTerminator() == false) { return false; } for (unsigned i = 0; i < _instructions.size(); i++) { const auto& inst = _instructions.at(i); if (inst.isValid(i) == false) { return false; } } // ::TODO verify animations do not have an infinite loop:: return true; } /* * ANIMATION INSTRUCTIONS * ====================== */ const char* AnimationInstruction::TYPE_NAME = "Animation Instruction"; AnimationInstruction::AnimationInstruction(Animation& parent) : _animation(parent) , _operation() , _gotoLabel() , _frame() , _parameter(0) { } AnimationInstruction::AnimationInstruction(const AnimationInstruction& ani, Animation& parent) : _animation(parent) , _operation(ani._operation) , _gotoLabel(ani._gotoLabel) , _frame(ani._frame) , _parameter(ani._parameter) { } void AnimationInstruction::setParameter(int p) { if (_operation.usesParameter()) { if (_operation.parameterUnsigned()) { if (p >= 0 && p < 256) { _parameter = p; } } else { // parameter is unsigned _parameter = p; } } } void AnimationInstruction::setFrame(const FrameReference& frame) { if (_operation.usesFrame()) { _frame = frame; } } void AnimationInstruction::setGotoLabel(const std::string& label) { if (_operation.usesGotoLabel() && isNameValid(label)) { _gotoLabel = label; } } /* * Valid if: * * GOTO_OFFSET points to an instruction inside the animation * * Animation nane exists in the frameset * * Frame name exists in the frameset */ bool AnimationInstruction::isValid(unsigned position) const { const unsigned MAX_BYTECODE_SIZE = 3; if (_operation == AnimationBytecode::Enum::GOTO_OFFSET) { const int p = _parameter; const unsigned aSize = _animation.instructions().size(); if (p == 0 || p < (int)-position || p >= (int)(aSize - position)) { return false; } if ((unsigned)abs(p) > 256 / MAX_BYTECODE_SIZE) { // simple bounds checking, prevent overflow return false; } } if (_operation.usesGotoLabel()) { if (_animation.frameSet().animations().nameExists(_gotoLabel) == false) { return false; } } if (_operation.usesFrame()) { if (_animation.frameSet().containsFrameName(_frame.frameName) == false) { return false; } } return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Log.h> #include <Module.h> #include <processor/types.h> #include <processor/Processor.h> #include <processor/MemoryMappedIo.h> #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <utilities/StaticString.h> #include <processor/MemoryRegion.h> #include <utilities/List.h> #include <machine/Machine.h> #include <machine/Display.h> #include <config/Config.h> #include <machine/Framebuffer.h> #include <graphics/Graphics.h> #include <graphics/GraphicsService.h> #include "vm_device_version.h" #include "svga_reg.h" #define DEBUG_VMWARE_GFX 0 class VmwareFramebuffer; // Can refer to http://sourceware.org/ml/ecos-devel/2006-10/msg00008/README.xfree86 // for information about programming this device, as well as the Haiku driver. class VmwareGraphics : public Display { friend class VmwareFramebuffer; public: VmwareGraphics(Device *pDev) : Device(pDev), Display(pDev), m_pIo(0), m_Framebuffer(0), m_CommandRegion(0) { m_pIo = m_Addresses[0]->m_Io; // Support ID2, as we are expecting an SVGA2 functional device writeRegister(SVGA_REG_ID, SVGA_MAKE_ID(2)); if(readRegister(SVGA_REG_ID) != SVGA_MAKE_ID(2)) { WARNING("vmware-gfx not a compatible SVGA device"); return; } // Read the framebuffer base (should match BAR1) uintptr_t fbBase = readRegister(SVGA_REG_FB_START); size_t fbSize = readRegister(SVGA_REG_VRAM_SIZE); // Read the command FIFO (should match BAR2) uintptr_t cmdBase = readRegister(SVGA_REG_MEM_START); size_t cmdSize = readRegister(SVGA_REG_MEM_SIZE); // Find the capabilities of the device size_t caps = readRegister(SVGA_REG_CAPABILITIES); // Read maximum resolution size_t maxWidth = readRegister(SVGA_REG_MAX_WIDTH); size_t maxHeight = readRegister(SVGA_REG_MAX_HEIGHT); // Tell VMware what OS we are - "Other" writeRegister(SVGA_REG_GUEST_ID, 0x500A); // Debug notification NOTICE("vmware-gfx found, caps=" << caps << ", maximum resolution is " << Dec << maxWidth << "x" << maxHeight << Hex); NOTICE("vmware-gfx framebuffer at " << fbBase << " - " << (fbBase + fbSize) << ", command FIFO at " << cmdBase); if(m_Addresses[1]->m_Address == fbBase) { m_Framebuffer = static_cast<MemoryMappedIo*>(m_Addresses[1]->m_Io); m_CommandRegion = static_cast<MemoryMappedIo*>(m_Addresses[2]->m_Io); } else { m_Framebuffer = static_cast<MemoryMappedIo*>(m_Addresses[2]->m_Io); m_CommandRegion = static_cast<MemoryMappedIo*>(m_Addresses[1]->m_Io); } // Set mode writeRegister(SVGA_REG_WIDTH, 1024); writeRegister(SVGA_REG_HEIGHT, 768); writeRegister(SVGA_REG_BITS_PER_PIXEL, 32); size_t fbOffset = readRegister(SVGA_REG_FB_OFFSET); size_t bytesPerLine = readRegister(SVGA_REG_BYTES_PER_LINE); size_t width = readRegister(SVGA_REG_WIDTH); size_t height = readRegister(SVGA_REG_HEIGHT); size_t depth = readRegister(SVGA_REG_DEPTH); NOTICE("vmware-gfx entered mode " << Dec << width << "x" << height << "x" << depth << Hex << ", mode framebuffer is " << (fbBase + fbOffset)); // Disable the command FIFO in case it was already enabled writeRegister(SVGA_REG_CONFIG_DONE, 0); // Enable the SVGA now writeRegister(SVGA_REG_ENABLE, 1); // Initialise the FIFO volatile uint32_t *fifo = reinterpret_cast<volatile uint32_t*>(m_CommandRegion->virtualAddress()); if(caps & SVGA_CAP_EXTENDED_FIFO) { size_t numFifoRegs = readRegister(SVGA_REG_MEM_REGS); size_t fifoExtendedBase = numFifoRegs * 4; fifo[SVGA_FIFO_MIN] = fifoExtendedBase; // Start right after this information block fifo[SVGA_FIFO_MAX] = cmdSize & ~0x3; // Permit the full FIFO to be used fifo[SVGA_FIFO_NEXT_CMD] = fifo[SVGA_FIFO_STOP] = fifo[SVGA_FIFO_MIN]; // Empty FIFO NOTICE("vmware-gfx using extended fifo, caps=" << fifo[SVGA_FIFO_CAPABILITIES] << ", flags=" << fifo[SVGA_FIFO_FLAGS]); } else { fifo[SVGA_FIFO_MIN] = 16; // Start right after this information block fifo[SVGA_FIFO_MAX] = cmdSize & ~0x3; // Permit the full FIFO to be used fifo[SVGA_FIFO_NEXT_CMD] = fifo[SVGA_FIFO_STOP] = 16; // Empty FIFO } // Try some hardware accelerated stuff if(caps & SVGA_CAP_RECT_FILL) { NOTICE("vmware-gfx rect fill supported"); writeFifo(SVGA_CMD_RECT_FILL); // RECT FILL writeFifo(0xFFFFFFFF); // White writeFifo(64); // X writeFifo(64); // Y writeFifo(256); // Width writeFifo(256); // Height } else NOTICE("vmware-gfx no rect fill available"); if(caps & SVGA_CAP_RECT_COPY) { NOTICE("vmware-gfx rect copy supported"); writeFifo(SVGA_CMD_RECT_COPY); // RECT COPY writeFifo(8); // Source X writeFifo(8); // Source Y writeFifo(256); // Dest X writeFifo(256); // Dest Y writeFifo(256); // Width writeFifo(256); // Height } else NOTICE("vmware-gfx no rect copy available"); // Start running the FIFO writeRegister(SVGA_REG_CONFIG_DONE, 1); m_pFramebuffer = new VmwareFramebuffer(reinterpret_cast<uintptr_t>(m_Framebuffer->virtualAddress()), this); GraphicsService::GraphicsProvider *pProvider = new GraphicsService::GraphicsProvider; pProvider->pDisplay = this; pProvider->pFramebuffer = m_pFramebuffer; pProvider->maxWidth = maxWidth; pProvider->maxHeight = maxHeight; pProvider->maxDepth = 32; // Register with the graphics service ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics")); Service *pService = ServiceManager::instance().getService(String("graphics")); if(pFeatures->provides(ServiceFeatures::touch)) if(pService) pService->serve(ServiceFeatures::touch, reinterpret_cast<void*>(pProvider), sizeof(*pProvider)); } virtual ~VmwareGraphics() { } /** Returns the current screen mode. \return True if operation succeeded, false otherwise. */ virtual bool getCurrentScreenMode(ScreenMode &sm) { sm.width = readRegister(SVGA_REG_WIDTH); sm.height = readRegister(SVGA_REG_HEIGHT); sm.pf.nBpp = readRegister(SVGA_REG_BITS_PER_PIXEL); sm.pf2 = Graphics::Bits24_Rgb; sm.bytesPerPixel = sm.pf.nBpp / 8; sm.bytesPerLine = readRegister(SVGA_REG_BYTES_PER_LINE); return true; } void redraw(size_t x, size_t y, size_t w, size_t h) { // Disable the command FIFO while we link the command writeRegister(SVGA_REG_CONFIG_DONE, 0); writeFifo(SVGA_CMD_UPDATE); writeFifo(x); writeFifo(y); writeFifo(w); writeFifo(h); // Start running the FIFO writeRegister(SVGA_REG_CONFIG_DONE, 1); } void copy(size_t x1, size_t y1, size_t x2, size_t y2, size_t w, size_t h) { // Disable the command FIFO while we link the command writeRegister(SVGA_REG_CONFIG_DONE, 0); writeFifo(SVGA_CMD_RECT_COPY); // RECT COPY writeFifo(x1); // Source X writeFifo(y1); // Source Y writeFifo(x2); // Dest X writeFifo(y2); // Dest Y writeFifo(w); // Width writeFifo(h); // Height // Start running the FIFO writeRegister(SVGA_REG_CONFIG_DONE, 1); } class VmwareFramebuffer : public Framebuffer { public: VmwareFramebuffer() : Framebuffer() { } VmwareFramebuffer(uintptr_t fb, Display *pDisplay) : Framebuffer() { setFramebuffer(fb); setDisplay(pDisplay); } virtual ~VmwareFramebuffer() { } virtual void redraw(size_t x = ~0UL, size_t y = ~0UL, size_t w = ~0UL, size_t h = ~0UL) { static_cast<VmwareGraphics*>(m_pDisplay)->redraw(x, y, w, h); } virtual inline void copy(size_t srcx, size_t srcy, size_t destx, size_t desty, size_t w, size_t h) { /// \todo Caps to determine whether to fall back to software static_cast<VmwareGraphics*>(m_pDisplay)->copy(srcx, srcy, destx, desty, w, h); } }; private: IoBase *m_pIo; /// \todo Lock these size_t readRegister(size_t offset) { m_pIo->write32(offset, SVGA_INDEX_PORT); return m_pIo->read32(SVGA_VALUE_PORT); } void writeRegister(size_t offset, uint32_t value) { m_pIo->write32(offset, SVGA_INDEX_PORT); m_pIo->write32(value, SVGA_VALUE_PORT); } void writeFifo(uint32_t value) { volatile uint32_t *fifo = reinterpret_cast<volatile uint32_t*>(m_CommandRegion->virtualAddress()); // Check for sync conditions if(((fifo[SVGA_FIFO_NEXT_CMD] + 4) == fifo[SVGA_FIFO_STOP]) || (fifo[SVGA_FIFO_NEXT_CMD] == (fifo[SVGA_FIFO_MAX] - 4))) { #if DEBUG_VMWARE_GFX DEBUG_LOG("vmware-gfx synchronising full fifo"); #endif syncFifo(); } #if DEBUG_VMWARE_GFX DEBUG_LOG("vmware-gfx fifo write at " << fifo[SVGA_FIFO_NEXT_CMD] << " val=" << value); DEBUG_LOG("vmware-gfx min is at " << fifo[SVGA_FIFO_MIN] << " and current position is " << fifo[SVGA_FIFO_STOP]); #endif // Load the new item into the FIFO fifo[fifo[SVGA_FIFO_NEXT_CMD] / 4] = value; if(fifo[SVGA_FIFO_NEXT_CMD] == (fifo[SVGA_FIFO_MAX] - 4)) fifo[SVGA_FIFO_NEXT_CMD] = fifo[SVGA_FIFO_MIN]; else fifo[SVGA_FIFO_NEXT_CMD] += 4; asm volatile("" : : : "memory"); } void syncFifo() { writeRegister(SVGA_REG_SYNC, 1); while(readRegister(SVGA_REG_BUSY)); } MemoryMappedIo *m_Framebuffer; MemoryMappedIo *m_CommandRegion; VmwareFramebuffer *m_pFramebuffer; }; #if 0 #include "abc.c" #endif void callback(Device *pDevice) { VmwareGraphics *pGraphics = new VmwareGraphics(pDevice); #if 0 GraphicsService::GraphicsProvider pProvider; // Testing... ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics")); Service *pService = ServiceManager::instance().getService(String("graphics")); if(pFeatures->provides(ServiceFeatures::probe)) if(pService) pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&pProvider), sizeof(pProvider)); Framebuffer *pFramebuffer = pProvider.pFramebuffer; // Pixel conversion test - RGB565 to 32-bit ARGB, should be green pFramebuffer->rect(64, 64, 256, 256, 0x7E0, Graphics::Bits16_Rgb565); pFramebuffer->redraw(64, 64, 256, 256); // Software copy test pFramebuffer->copy(64, 64, 512, 256, 64, 64); pFramebuffer->redraw(512, 256, 64, 64); // Big 24-bit to 32-bit blit test Graphics::Buffer *pBuffer = pFramebuffer->createBuffer(gimp_image.pixel_data, Graphics::Bits24_Bgr, gimp_image.width, gimp_image.height); pFramebuffer->blit(pBuffer, 0, 0, 128, 128, gimp_image.width, gimp_image.height); pFramebuffer->redraw(128, 128, gimp_image.width, gimp_image.height); pFramebuffer->destroyBuffer(pBuffer); // Hardware-accelerated copy test, with a redraw afterwards pGraphics->copy(64, 64, 512, 512, 64, 64); pFramebuffer->redraw(512, 512, 64, 64); pFramebuffer->line(64, 512, 128, 512, 0xff0000, Graphics::Bits24_Rgb); pFramebuffer->redraw(63, 511, 66, 3); #endif } void entry() { // Don't care about non-SVGA2 devices, just use VBE for them. Device::root().searchByVendorIdAndDeviceId(PCI_VENDOR_ID_VMWARE, PCI_DEVICE_ID_VMWARE_SVGA2, callback); } void exit() { } MODULE_INFO("vmware-gfx", &entry, &exit, "pci", "config"); <commit_msg>Disable vmware-gfx for now.<commit_after>/* * Copyright (c) 2010 Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Log.h> #include <Module.h> #include <processor/types.h> #include <processor/Processor.h> #include <processor/MemoryMappedIo.h> #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <utilities/StaticString.h> #include <processor/MemoryRegion.h> #include <utilities/List.h> #include <machine/Machine.h> #include <machine/Display.h> #include <config/Config.h> #include <machine/Framebuffer.h> #include <graphics/Graphics.h> #include <graphics/GraphicsService.h> #include "vm_device_version.h" #include "svga_reg.h" #define DEBUG_VMWARE_GFX 0 class VmwareFramebuffer; // Can refer to http://sourceware.org/ml/ecos-devel/2006-10/msg00008/README.xfree86 // for information about programming this device, as well as the Haiku driver. class VmwareGraphics : public Display { friend class VmwareFramebuffer; public: VmwareGraphics(Device *pDev) : Device(pDev), Display(pDev), m_pIo(0), m_Framebuffer(0), m_CommandRegion(0) { m_pIo = m_Addresses[0]->m_Io; // Support ID2, as we are expecting an SVGA2 functional device writeRegister(SVGA_REG_ID, SVGA_MAKE_ID(2)); if(readRegister(SVGA_REG_ID) != SVGA_MAKE_ID(2)) { WARNING("vmware-gfx not a compatible SVGA device"); return; } // Read the framebuffer base (should match BAR1) uintptr_t fbBase = readRegister(SVGA_REG_FB_START); size_t fbSize = readRegister(SVGA_REG_VRAM_SIZE); // Read the command FIFO (should match BAR2) uintptr_t cmdBase = readRegister(SVGA_REG_MEM_START); size_t cmdSize = readRegister(SVGA_REG_MEM_SIZE); // Find the capabilities of the device size_t caps = readRegister(SVGA_REG_CAPABILITIES); // Read maximum resolution size_t maxWidth = readRegister(SVGA_REG_MAX_WIDTH); size_t maxHeight = readRegister(SVGA_REG_MAX_HEIGHT); // Tell VMware what OS we are - "Other" writeRegister(SVGA_REG_GUEST_ID, 0x500A); // Debug notification NOTICE("vmware-gfx found, caps=" << caps << ", maximum resolution is " << Dec << maxWidth << "x" << maxHeight << Hex); NOTICE("vmware-gfx framebuffer at " << fbBase << " - " << (fbBase + fbSize) << ", command FIFO at " << cmdBase); if(m_Addresses[1]->m_Address == fbBase) { m_Framebuffer = static_cast<MemoryMappedIo*>(m_Addresses[1]->m_Io); m_CommandRegion = static_cast<MemoryMappedIo*>(m_Addresses[2]->m_Io); } else { m_Framebuffer = static_cast<MemoryMappedIo*>(m_Addresses[2]->m_Io); m_CommandRegion = static_cast<MemoryMappedIo*>(m_Addresses[1]->m_Io); } // Set mode writeRegister(SVGA_REG_WIDTH, 1024); writeRegister(SVGA_REG_HEIGHT, 768); writeRegister(SVGA_REG_BITS_PER_PIXEL, 32); size_t fbOffset = readRegister(SVGA_REG_FB_OFFSET); size_t bytesPerLine = readRegister(SVGA_REG_BYTES_PER_LINE); size_t width = readRegister(SVGA_REG_WIDTH); size_t height = readRegister(SVGA_REG_HEIGHT); size_t depth = readRegister(SVGA_REG_DEPTH); NOTICE("vmware-gfx entered mode " << Dec << width << "x" << height << "x" << depth << Hex << ", mode framebuffer is " << (fbBase + fbOffset)); // Disable the command FIFO in case it was already enabled writeRegister(SVGA_REG_CONFIG_DONE, 0); // Enable the SVGA now writeRegister(SVGA_REG_ENABLE, 1); // Initialise the FIFO volatile uint32_t *fifo = reinterpret_cast<volatile uint32_t*>(m_CommandRegion->virtualAddress()); if(caps & SVGA_CAP_EXTENDED_FIFO) { size_t numFifoRegs = readRegister(SVGA_REG_MEM_REGS); size_t fifoExtendedBase = numFifoRegs * 4; fifo[SVGA_FIFO_MIN] = fifoExtendedBase; // Start right after this information block fifo[SVGA_FIFO_MAX] = cmdSize & ~0x3; // Permit the full FIFO to be used fifo[SVGA_FIFO_NEXT_CMD] = fifo[SVGA_FIFO_STOP] = fifo[SVGA_FIFO_MIN]; // Empty FIFO NOTICE("vmware-gfx using extended fifo, caps=" << fifo[SVGA_FIFO_CAPABILITIES] << ", flags=" << fifo[SVGA_FIFO_FLAGS]); } else { fifo[SVGA_FIFO_MIN] = 16; // Start right after this information block fifo[SVGA_FIFO_MAX] = cmdSize & ~0x3; // Permit the full FIFO to be used fifo[SVGA_FIFO_NEXT_CMD] = fifo[SVGA_FIFO_STOP] = 16; // Empty FIFO } // Try some hardware accelerated stuff if(caps & SVGA_CAP_RECT_FILL) { NOTICE("vmware-gfx rect fill supported"); writeFifo(SVGA_CMD_RECT_FILL); // RECT FILL writeFifo(0xFFFFFFFF); // White writeFifo(64); // X writeFifo(64); // Y writeFifo(256); // Width writeFifo(256); // Height } else NOTICE("vmware-gfx no rect fill available"); if(caps & SVGA_CAP_RECT_COPY) { NOTICE("vmware-gfx rect copy supported"); writeFifo(SVGA_CMD_RECT_COPY); // RECT COPY writeFifo(8); // Source X writeFifo(8); // Source Y writeFifo(256); // Dest X writeFifo(256); // Dest Y writeFifo(256); // Width writeFifo(256); // Height } else NOTICE("vmware-gfx no rect copy available"); // Start running the FIFO writeRegister(SVGA_REG_CONFIG_DONE, 1); m_pFramebuffer = new VmwareFramebuffer(reinterpret_cast<uintptr_t>(m_Framebuffer->virtualAddress()), this); GraphicsService::GraphicsProvider *pProvider = new GraphicsService::GraphicsProvider; pProvider->pDisplay = this; pProvider->pFramebuffer = m_pFramebuffer; pProvider->maxWidth = maxWidth; pProvider->maxHeight = maxHeight; pProvider->maxDepth = 32; // Register with the graphics service ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics")); Service *pService = ServiceManager::instance().getService(String("graphics")); if(pFeatures->provides(ServiceFeatures::touch)) if(pService) pService->serve(ServiceFeatures::touch, reinterpret_cast<void*>(pProvider), sizeof(*pProvider)); } virtual ~VmwareGraphics() { } /** Returns the current screen mode. \return True if operation succeeded, false otherwise. */ virtual bool getCurrentScreenMode(ScreenMode &sm) { sm.width = readRegister(SVGA_REG_WIDTH); sm.height = readRegister(SVGA_REG_HEIGHT); sm.pf.nBpp = readRegister(SVGA_REG_BITS_PER_PIXEL); sm.pf2 = Graphics::Bits24_Rgb; sm.bytesPerPixel = sm.pf.nBpp / 8; sm.bytesPerLine = readRegister(SVGA_REG_BYTES_PER_LINE); return true; } void redraw(size_t x, size_t y, size_t w, size_t h) { // Disable the command FIFO while we link the command writeRegister(SVGA_REG_CONFIG_DONE, 0); writeFifo(SVGA_CMD_UPDATE); writeFifo(x); writeFifo(y); writeFifo(w); writeFifo(h); // Start running the FIFO writeRegister(SVGA_REG_CONFIG_DONE, 1); } void copy(size_t x1, size_t y1, size_t x2, size_t y2, size_t w, size_t h) { // Disable the command FIFO while we link the command writeRegister(SVGA_REG_CONFIG_DONE, 0); writeFifo(SVGA_CMD_RECT_COPY); // RECT COPY writeFifo(x1); // Source X writeFifo(y1); // Source Y writeFifo(x2); // Dest X writeFifo(y2); // Dest Y writeFifo(w); // Width writeFifo(h); // Height // Start running the FIFO writeRegister(SVGA_REG_CONFIG_DONE, 1); } class VmwareFramebuffer : public Framebuffer { public: VmwareFramebuffer() : Framebuffer() { } VmwareFramebuffer(uintptr_t fb, Display *pDisplay) : Framebuffer() { setFramebuffer(fb); setDisplay(pDisplay); } virtual ~VmwareFramebuffer() { } virtual void redraw(size_t x = ~0UL, size_t y = ~0UL, size_t w = ~0UL, size_t h = ~0UL) { static_cast<VmwareGraphics*>(m_pDisplay)->redraw(x, y, w, h); } virtual inline void copy(size_t srcx, size_t srcy, size_t destx, size_t desty, size_t w, size_t h) { /// \todo Caps to determine whether to fall back to software static_cast<VmwareGraphics*>(m_pDisplay)->copy(srcx, srcy, destx, desty, w, h); } }; private: IoBase *m_pIo; /// \todo Lock these size_t readRegister(size_t offset) { m_pIo->write32(offset, SVGA_INDEX_PORT); return m_pIo->read32(SVGA_VALUE_PORT); } void writeRegister(size_t offset, uint32_t value) { m_pIo->write32(offset, SVGA_INDEX_PORT); m_pIo->write32(value, SVGA_VALUE_PORT); } void writeFifo(uint32_t value) { volatile uint32_t *fifo = reinterpret_cast<volatile uint32_t*>(m_CommandRegion->virtualAddress()); // Check for sync conditions if(((fifo[SVGA_FIFO_NEXT_CMD] + 4) == fifo[SVGA_FIFO_STOP]) || (fifo[SVGA_FIFO_NEXT_CMD] == (fifo[SVGA_FIFO_MAX] - 4))) { #if DEBUG_VMWARE_GFX DEBUG_LOG("vmware-gfx synchronising full fifo"); #endif syncFifo(); } #if DEBUG_VMWARE_GFX DEBUG_LOG("vmware-gfx fifo write at " << fifo[SVGA_FIFO_NEXT_CMD] << " val=" << value); DEBUG_LOG("vmware-gfx min is at " << fifo[SVGA_FIFO_MIN] << " and current position is " << fifo[SVGA_FIFO_STOP]); #endif // Load the new item into the FIFO fifo[fifo[SVGA_FIFO_NEXT_CMD] / 4] = value; if(fifo[SVGA_FIFO_NEXT_CMD] == (fifo[SVGA_FIFO_MAX] - 4)) fifo[SVGA_FIFO_NEXT_CMD] = fifo[SVGA_FIFO_MIN]; else fifo[SVGA_FIFO_NEXT_CMD] += 4; asm volatile("" : : : "memory"); } void syncFifo() { writeRegister(SVGA_REG_SYNC, 1); while(readRegister(SVGA_REG_BUSY)); } MemoryMappedIo *m_Framebuffer; MemoryMappedIo *m_CommandRegion; VmwareFramebuffer *m_pFramebuffer; }; #if 0 #include "abc.c" #endif void callback(Device *pDevice) { // VmwareGraphics *pGraphics = new VmwareGraphics(pDevice); #if 0 GraphicsService::GraphicsProvider pProvider; // Testing... ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics")); Service *pService = ServiceManager::instance().getService(String("graphics")); if(pFeatures->provides(ServiceFeatures::probe)) if(pService) pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&pProvider), sizeof(pProvider)); Framebuffer *pFramebuffer = pProvider.pFramebuffer; // Pixel conversion test - RGB565 to 32-bit ARGB, should be green pFramebuffer->rect(64, 64, 256, 256, 0x7E0, Graphics::Bits16_Rgb565); pFramebuffer->redraw(64, 64, 256, 256); // Software copy test pFramebuffer->copy(64, 64, 512, 256, 64, 64); pFramebuffer->redraw(512, 256, 64, 64); // Big 24-bit to 32-bit blit test Graphics::Buffer *pBuffer = pFramebuffer->createBuffer(gimp_image.pixel_data, Graphics::Bits24_Bgr, gimp_image.width, gimp_image.height); pFramebuffer->blit(pBuffer, 0, 0, 128, 128, gimp_image.width, gimp_image.height); pFramebuffer->redraw(128, 128, gimp_image.width, gimp_image.height); pFramebuffer->destroyBuffer(pBuffer); // Hardware-accelerated copy test, with a redraw afterwards pGraphics->copy(64, 64, 512, 512, 64, 64); pFramebuffer->redraw(512, 512, 64, 64); pFramebuffer->line(64, 512, 128, 512, 0xff0000, Graphics::Bits24_Rgb); pFramebuffer->redraw(63, 511, 66, 3); #endif } void entry() { // Don't care about non-SVGA2 devices, just use VBE for them. Device::root().searchByVendorIdAndDeviceId(PCI_VENDOR_ID_VMWARE, PCI_DEVICE_ID_VMWARE_SVGA2, callback); } void exit() { } MODULE_INFO("vmware-gfx", &entry, &exit, "pci", "config"); <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file vtol_type.cpp * * @author Roman Bapst <[email protected]> * @author Andreas Antener <[email protected]> * */ #include "vtol_type.h" #include "vtol_att_control_main.h" #include <cfloat> #include <px4_defines.h> #include <matrix/math.hpp> VtolType::VtolType(VtolAttitudeControl *att_controller) : _attc(att_controller), _vtol_mode(ROTARY_WING) { _v_att = _attc->get_att(); _v_att_sp = _attc->get_att_sp(); _mc_virtual_att_sp = _attc->get_mc_virtual_att_sp(); _fw_virtual_att_sp = _attc->get_fw_virtual_att_sp(); _v_rates_sp = _attc->get_rates_sp(); _mc_virtual_v_rates_sp = _attc->get_mc_virtual_rates_sp(); _fw_virtual_v_rates_sp = _attc->get_fw_virtual_rates_sp(); _manual_control_sp = _attc->get_manual_control_sp(); _v_control_mode = _attc->get_control_mode(); _vtol_vehicle_status = _attc->get_vtol_vehicle_status(); _actuators_out_0 = _attc->get_actuators_out0(); _actuators_out_1 = _attc->get_actuators_out1(); _actuators_mc_in = _attc->get_actuators_mc_in(); _actuators_fw_in = _attc->get_actuators_fw_in(); _local_pos = _attc->get_local_pos(); _local_pos_sp = _attc->get_local_pos_sp(); _airspeed = _attc->get_airspeed(); _batt_status = _attc->get_batt_status(); _tecs_status = _attc->get_tecs_status(); _land_detected = _attc->get_land_detected(); _params = _attc->get_params(); flag_idle_mc = true; } VtolType::~VtolType() { } /** * Adjust idle speed for mc mode. */ void VtolType::set_idle_mc() { const char *dev = PWM_OUTPUT0_DEVICE_PATH; int fd = px4_open(dev, 0); if (fd < 0) { PX4_WARN("can't open %s", dev); } unsigned servo_count; int ret = px4_ioctl(fd, PWM_SERVO_GET_COUNT, (unsigned long)&servo_count); unsigned pwm_value = _params->idle_pwm_mc; struct pwm_output_values pwm_values; memset(&pwm_values, 0, sizeof(pwm_values)); for (int i = 0; i < _params->vtol_motor_count; i++) { pwm_values.values[i] = pwm_value; pwm_values.channel_count++; } ret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values); if (ret != OK) { PX4_WARN("failed setting min values"); } px4_close(fd); flag_idle_mc = true; } /** * Adjust idle speed for fw mode. */ void VtolType::set_idle_fw() { const char *dev = PWM_OUTPUT0_DEVICE_PATH; int fd = px4_open(dev, 0); if (fd < 0) { PX4_WARN("can't open %s", dev); } struct pwm_output_values pwm_values; memset(&pwm_values, 0, sizeof(pwm_values)); for (int i = 0; i < _params->vtol_motor_count; i++) { pwm_values.values[i] = PWM_MOTOR_OFF; pwm_values.channel_count++; } int ret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values); if (ret != OK) { PX4_WARN("failed setting min values"); } px4_close(fd); } void VtolType::update_mc_state() { // copy virtual attitude setpoint to real attitude setpoint memcpy(_v_att_sp, _mc_virtual_att_sp, sizeof(vehicle_attitude_setpoint_s)); _mc_roll_weight = 1.0f; _mc_pitch_weight = 1.0f; _mc_yaw_weight = 1.0f; // VTOL weathervane _v_att_sp->disable_mc_yaw_control = false; if (_attc->get_pos_sp_triplet()->current.valid && !_v_control_mode->flag_control_manual_enabled) { if (_params->wv_takeoff && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_TAKEOFF) { _v_att_sp->disable_mc_yaw_control = true; } else if (_params->wv_loiter && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LOITER) { _v_att_sp->disable_mc_yaw_control = true; } else if (_params->wv_land && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND) { _v_att_sp->disable_mc_yaw_control = true; } } } void VtolType::update_fw_state() { // copy virtual attitude setpoint to real attitude setpoint memcpy(_v_att_sp, _fw_virtual_att_sp, sizeof(vehicle_attitude_setpoint_s)); _mc_roll_weight = 0.0f; _mc_pitch_weight = 0.0f; _mc_yaw_weight = 0.0f; // tecs didn't publish an update yet after the transition if (_tecs_status->timestamp < _trans_finished_ts) { _tecs_running = false; } else if (!_tecs_running) { _tecs_running = true; _tecs_running_ts = hrt_absolute_time(); } // TECS didn't publish yet or the position controller didn't publish yet AFTER tecs // only wait on TECS we're in a mode where it is actually running if ((!_tecs_running || (_tecs_running && _fw_virtual_att_sp->timestamp <= _tecs_running_ts)) && _v_control_mode->flag_control_altitude_enabled) { waiting_on_tecs(); } check_quadchute_condition(); } void VtolType::update_transition_state() { check_quadchute_condition(); } bool VtolType::can_transition_on_ground() { return !_v_control_mode->flag_armed || _land_detected->landed; } void VtolType::check_quadchute_condition() { if (_v_control_mode->flag_armed && !_land_detected->landed) { matrix::Eulerf euler = matrix::Quatf(_v_att->q); // fixed-wing minimum altitude if (_params->fw_min_alt > FLT_EPSILON) { if (-(_local_pos->z) < _params->fw_min_alt) { _attc->abort_front_transition("QuadChute: Minimum altitude breached"); } } // adaptive quadchute // We use tecs for tracking in FW and local_pos_sp during transitions if (_params->fw_alt_err > FLT_EPSILON) { float altErr = 0.0f; if (_tecs_running) { altErr = _tecs_status->altitudeSp - _tecs_status->altitude_filtered; } else { altErr = -_local_pos_sp->z - -_local_pos->z; if (!_local_pos->z_valid) { altErr = 0.0f; } } if (altErr > _params->fw_alt_err) { _attc->abort_front_transition("QuadChute: Altitude error too large"); } } // fixed-wing maximum pitch angle if (_params->fw_qc_max_pitch > 0) { if (fabsf(euler.theta()) > fabsf(math::radians(_params->fw_qc_max_pitch))) { _attc->abort_front_transition("Maximum pitch angle exceeded"); } } // fixed-wing maximum roll angle if (_params->fw_qc_max_roll > 0) { if (fabsf(euler.phi()) > fabsf(math::radians(_params->fw_qc_max_roll))) { _attc->abort_front_transition("Maximum roll angle exceeded"); } } } } <commit_msg>Adaptive QuadChute disabled in manual modes<commit_after>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file vtol_type.cpp * * @author Roman Bapst <[email protected]> * @author Andreas Antener <[email protected]> * */ #include "vtol_type.h" #include "vtol_att_control_main.h" #include <cfloat> #include <px4_defines.h> #include <matrix/math.hpp> VtolType::VtolType(VtolAttitudeControl *att_controller) : _attc(att_controller), _vtol_mode(ROTARY_WING) { _v_att = _attc->get_att(); _v_att_sp = _attc->get_att_sp(); _mc_virtual_att_sp = _attc->get_mc_virtual_att_sp(); _fw_virtual_att_sp = _attc->get_fw_virtual_att_sp(); _v_rates_sp = _attc->get_rates_sp(); _mc_virtual_v_rates_sp = _attc->get_mc_virtual_rates_sp(); _fw_virtual_v_rates_sp = _attc->get_fw_virtual_rates_sp(); _manual_control_sp = _attc->get_manual_control_sp(); _v_control_mode = _attc->get_control_mode(); _vtol_vehicle_status = _attc->get_vtol_vehicle_status(); _actuators_out_0 = _attc->get_actuators_out0(); _actuators_out_1 = _attc->get_actuators_out1(); _actuators_mc_in = _attc->get_actuators_mc_in(); _actuators_fw_in = _attc->get_actuators_fw_in(); _local_pos = _attc->get_local_pos(); _local_pos_sp = _attc->get_local_pos_sp(); _airspeed = _attc->get_airspeed(); _batt_status = _attc->get_batt_status(); _tecs_status = _attc->get_tecs_status(); _land_detected = _attc->get_land_detected(); _params = _attc->get_params(); flag_idle_mc = true; } VtolType::~VtolType() { } /** * Adjust idle speed for mc mode. */ void VtolType::set_idle_mc() { const char *dev = PWM_OUTPUT0_DEVICE_PATH; int fd = px4_open(dev, 0); if (fd < 0) { PX4_WARN("can't open %s", dev); } unsigned servo_count; int ret = px4_ioctl(fd, PWM_SERVO_GET_COUNT, (unsigned long)&servo_count); unsigned pwm_value = _params->idle_pwm_mc; struct pwm_output_values pwm_values; memset(&pwm_values, 0, sizeof(pwm_values)); for (int i = 0; i < _params->vtol_motor_count; i++) { pwm_values.values[i] = pwm_value; pwm_values.channel_count++; } ret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values); if (ret != OK) { PX4_WARN("failed setting min values"); } px4_close(fd); flag_idle_mc = true; } /** * Adjust idle speed for fw mode. */ void VtolType::set_idle_fw() { const char *dev = PWM_OUTPUT0_DEVICE_PATH; int fd = px4_open(dev, 0); if (fd < 0) { PX4_WARN("can't open %s", dev); } struct pwm_output_values pwm_values; memset(&pwm_values, 0, sizeof(pwm_values)); for (int i = 0; i < _params->vtol_motor_count; i++) { pwm_values.values[i] = PWM_MOTOR_OFF; pwm_values.channel_count++; } int ret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values); if (ret != OK) { PX4_WARN("failed setting min values"); } px4_close(fd); } void VtolType::update_mc_state() { // copy virtual attitude setpoint to real attitude setpoint memcpy(_v_att_sp, _mc_virtual_att_sp, sizeof(vehicle_attitude_setpoint_s)); _mc_roll_weight = 1.0f; _mc_pitch_weight = 1.0f; _mc_yaw_weight = 1.0f; // VTOL weathervane _v_att_sp->disable_mc_yaw_control = false; if (_attc->get_pos_sp_triplet()->current.valid && !_v_control_mode->flag_control_manual_enabled) { if (_params->wv_takeoff && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_TAKEOFF) { _v_att_sp->disable_mc_yaw_control = true; } else if (_params->wv_loiter && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LOITER) { _v_att_sp->disable_mc_yaw_control = true; } else if (_params->wv_land && _attc->get_pos_sp_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND) { _v_att_sp->disable_mc_yaw_control = true; } } } void VtolType::update_fw_state() { // copy virtual attitude setpoint to real attitude setpoint memcpy(_v_att_sp, _fw_virtual_att_sp, sizeof(vehicle_attitude_setpoint_s)); _mc_roll_weight = 0.0f; _mc_pitch_weight = 0.0f; _mc_yaw_weight = 0.0f; // tecs didn't publish an update yet after the transition if (_tecs_status->timestamp < _trans_finished_ts) { _tecs_running = false; } else if (!_tecs_running) { _tecs_running = true; _tecs_running_ts = hrt_absolute_time(); } // TECS didn't publish yet or the position controller didn't publish yet AFTER tecs // only wait on TECS we're in a mode where it is actually running if ((!_tecs_running || (_tecs_running && _fw_virtual_att_sp->timestamp <= _tecs_running_ts)) && _v_control_mode->flag_control_altitude_enabled) { waiting_on_tecs(); } check_quadchute_condition(); } void VtolType::update_transition_state() { check_quadchute_condition(); } bool VtolType::can_transition_on_ground() { return !_v_control_mode->flag_armed || _land_detected->landed; } void VtolType::check_quadchute_condition() { if (_v_control_mode->flag_armed && !_land_detected->landed) { matrix::Eulerf euler = matrix::Quatf(_v_att->q); // fixed-wing minimum altitude if (_params->fw_min_alt > FLT_EPSILON) { if (-(_local_pos->z) < _params->fw_min_alt) { _attc->abort_front_transition("QuadChute: Minimum altitude breached"); } } // adaptive quadchute // We use tecs for tracking in FW and local_pos_sp during transitions if (_params->fw_alt_err > FLT_EPSILON && _v_control_mode->flag_control_altitude_enabled) { float altErr = 0.0f; if (_tecs_running) { altErr = _tecs_status->altitudeSp - _tecs_status->altitude_filtered; } else { altErr = -_local_pos_sp->z - -_local_pos->z; if (!_local_pos->z_valid) { altErr = 0.0f; } } if (altErr > _params->fw_alt_err) { _attc->abort_front_transition("QuadChute: Altitude error too large"); } } // fixed-wing maximum pitch angle if (_params->fw_qc_max_pitch > 0) { if (fabsf(euler.theta()) > fabsf(math::radians(_params->fw_qc_max_pitch))) { _attc->abort_front_transition("Maximum pitch angle exceeded"); } } // fixed-wing maximum roll angle if (_params->fw_qc_max_roll > 0) { if (fabsf(euler.phi()) > fabsf(math::radians(_params->fw_qc_max_roll))) { _attc->abort_front_transition("Maximum roll angle exceeded"); } } } } <|endoftext|>
<commit_before>/* * 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. * * Written (W) 2012 Heiko Strathmann */ #include <shogun/statistics/QuadraticTimeMMD.h> #include <shogun/features/Features.h> #include <shogun/mathematics/Statistics.h> using namespace shogun; CQuadraticTimeMMD::CQuadraticTimeMMD() : CKernelTwoSampleTestStatistic() { init(); } CQuadraticTimeMMD::CQuadraticTimeMMD(CKernel* kernel, CFeatures* p_and_q, index_t q_start) : CKernelTwoSampleTestStatistic(kernel, p_and_q, q_start) { init(); if (q_start!=p_and_q->get_num_vectors()/2) { SG_ERROR("CQuadraticTimeMMD: Only features with equal number of vectors " "are currently possible\n"); } } CQuadraticTimeMMD::~CQuadraticTimeMMD() { } void CQuadraticTimeMMD::init() { /* TODO register parameters*/ m_num_samples_spectrum=0; m_num_eigenvalues_spectrum=0; } float64_t CQuadraticTimeMMD::compute_statistic() { /* split computations into three terms from JLMR paper (see documentation )*/ index_t m=m_q_start; index_t n=m_p_and_q->get_num_vectors(); /* init kernel with features */ m_kernel->init(m_p_and_q, m_p_and_q); /* first term */ float64_t first=0; for (index_t i=0; i<m; ++i) { for (index_t j=0; j<m; ++j) { /* ensure i!=j */ if (i==j) continue; first+=m_kernel->kernel(i,j); } } first/=m*(m-1); /* second term */ float64_t second=0; for (index_t i=m_q_start; i<n; ++i) { for (index_t j=m_q_start; j<n; ++j) { /* ensure i!=j */ if (i==j) continue; second+=m_kernel->kernel(i,j); } } second/=n*(n-1); /* third term */ float64_t third=0; for (index_t i=0; i<m; ++i) { for (index_t j=m_q_start; j<n; ++j) third+=m_kernel->kernel(i,j); } third*=-2.0/(m*n); return first+second-third; } float64_t CQuadraticTimeMMD::compute_p_value(float64_t statistic) { float64_t result=0; switch (m_p_value_method) { case MMD2_SPECTRUM: { /* get samples from null-distribution and compute p-value of statistic */ SGVector<float64_t> null_samples=sample_null_spectrum( m_num_samples_spectrum, m_num_eigenvalues_spectrum); CMath::qsort(null_samples); float64_t pos=CMath::find_position_to_insert(null_samples, statistic); result=1.0-pos/null_samples.vlen; break; } case MMD2_GAMMA: result=compute_p_value_gamma(statistic); break; default: result=CKernelTwoSampleTestStatistic::compute_p_value(statistic); break; } return result; } #ifdef HAVE_LAPACK SGVector<float64_t> CQuadraticTimeMMD::sample_null_spectrum(index_t num_samples, index_t num_eigenvalues) { /* the whole procedure is already checked against MATLAB implementation */ if (m_q_start!=m_p_and_q->get_num_vectors()/2) { /* TODO support different numbers of samples */ SG_ERROR("%s::sample_null_spectrum(): Currently, only equal " "sample sizes are supported\n", get_name()); } if (num_samples<=2) { SG_ERROR("%s::sample_null_spectrum(): Number of samples has to be at" " least 2, better in the hundrets", get_name()); } if (num_eigenvalues>2*m_q_start-1) { SG_ERROR("%s::sample_null_spectrum(): Number of Eigenvalues too large\n", get_name()); } if (num_eigenvalues<1) { SG_ERROR("%s::sample_null_spectrum(): Number of Eigenvalues too small\n", get_name()); } /* imaginary matrix K=[K KL; KL' L] (MATLAB notation) * K is matrix for XX, L is matrix for YY, KL is XY, LK is YX * works since X and Y are concatenated here */ m_kernel->init(m_p_and_q, m_p_and_q); SGMatrix<float64_t> K=m_kernel->get_kernel_matrix(); /* center matrix K=H*K*H */ K.center(); /* compute eigenvalues and select num_eigenvalues largest ones */ SGVector<float64_t> eigenvalues=SGMatrix<float64_t>::compute_eigenvectors(K); SGVector<float64_t> largest_ev(num_eigenvalues); /* scale by 1/2/m on the fly and take abs value*/ for (index_t i=0; i<num_eigenvalues; ++i) largest_ev[i]=CMath::abs(1.0/2/m_q_start*eigenvalues[eigenvalues.vlen-1-i]); /* finally, sample from null distribution */ SGVector<float64_t> null_samples(num_samples); for (index_t i=0; i<num_samples; ++i) { /* 2*sum(kEigs.*(randn(length(kEigs),1)).^2); */ null_samples[i]=0; for (index_t j=0; j<largest_ev.vlen; ++j) null_samples[i]+=largest_ev[j]*CMath::pow(2.0, 2); null_samples[i]*=2; } return null_samples; } #endif // HAVE_LAPACK float64_t CQuadraticTimeMMD::compute_p_value_gamma(float64_t statistic) { /* the whole procedure is already checked against MATLAB implementation */ if (m_q_start!=m_p_and_q->get_num_vectors()/2) { /* TODO support different numbers of samples */ SG_ERROR("%s::compute_threshold_gamma(): Currently, only equal " "sample sizes are supported\n", get_name()); } /* imaginary matrix K=[K KL; KL' L] (MATLAB notation) * K is matrix for XX, L is matrix for YY, KL is XY, LK is YX * works since X and Y are concatenated here */ m_kernel->init(m_p_and_q, m_p_and_q); SGMatrix<float64_t> K=m_kernel->get_kernel_matrix(); /* compute mean under H0 of MMD, which is * meanMMD = 2/m * ( 1 - 1/m*sum(diag(KL)) ); * in MATLAB */ float64_t mean_mmd=0; for (index_t i=0; i<m_q_start; ++i) { /* virtual KL matrix is in upper right corner of SHOGUN K matrix * so this sums the diagonal of the matrix between X and Y*/ mean_mmd+=K(i, m_q_start+i); /* remove diagonal of all pairs of kernel matrices on the fly */ K(i, i)=0; K(m_q_start+i, m_q_start+i)=0; K(i, m_q_start+i)=0; K(m_q_start+i, i)=0; } mean_mmd=2.0/m_q_start*(1.0-1.0/m_q_start*mean_mmd); /* compute variance under H0 of MMD, which is * varMMD = 2/m/(m-1) * 1/m/(m-1) * sum(sum( (K + L - KL - KL').^2 )); * in MATLAB, so sum up all elements */ float64_t var_mmd=0; for (index_t i=0; i<m_q_start; ++i) { for (index_t j=0; j<m_q_start; ++j) { float64_t to_add=0; to_add+=K(i, j); to_add+=K(m_q_start+i, m_q_start+j); to_add-=K(i, m_q_start+j); to_add-=K(m_q_start+i, j); var_mmd+=CMath::pow(to_add, 2); } } var_mmd*=2.0/m_q_start/(m_q_start-1)*1.0/m_q_start/(m_q_start-1); /* parameters for gamma distribution */ float64_t a=CMath::pow(mean_mmd, 2)/var_mmd; float64_t b=var_mmd*m_q_start / mean_mmd; /* return: cdf('gam',statistic,al,bet) (MATLAB) * which will get the position in the null distribution */ return CStatistics::gamma_cdf(statistic, a, b); } void CQuadraticTimeMMD::set_num_samples_sepctrum(index_t num_samples_spectrum) { m_num_samples_spectrum=num_samples_spectrum; } void CQuadraticTimeMMD::set_num_eigenvalues_spectrum( index_t num_eigenvalues_spectrum) { m_num_eigenvalues_spectrum=num_eigenvalues_spectrum; } <commit_msg>another check for LAPACK<commit_after>/* * 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. * * Written (W) 2012 Heiko Strathmann */ #include <shogun/statistics/QuadraticTimeMMD.h> #include <shogun/features/Features.h> #include <shogun/mathematics/Statistics.h> using namespace shogun; CQuadraticTimeMMD::CQuadraticTimeMMD() : CKernelTwoSampleTestStatistic() { init(); } CQuadraticTimeMMD::CQuadraticTimeMMD(CKernel* kernel, CFeatures* p_and_q, index_t q_start) : CKernelTwoSampleTestStatistic(kernel, p_and_q, q_start) { init(); if (q_start!=p_and_q->get_num_vectors()/2) { SG_ERROR("CQuadraticTimeMMD: Only features with equal number of vectors " "are currently possible\n"); } } CQuadraticTimeMMD::~CQuadraticTimeMMD() { } void CQuadraticTimeMMD::init() { /* TODO register parameters*/ m_num_samples_spectrum=0; m_num_eigenvalues_spectrum=0; } float64_t CQuadraticTimeMMD::compute_statistic() { /* split computations into three terms from JLMR paper (see documentation )*/ index_t m=m_q_start; index_t n=m_p_and_q->get_num_vectors(); /* init kernel with features */ m_kernel->init(m_p_and_q, m_p_and_q); /* first term */ float64_t first=0; for (index_t i=0; i<m; ++i) { for (index_t j=0; j<m; ++j) { /* ensure i!=j */ if (i==j) continue; first+=m_kernel->kernel(i,j); } } first/=m*(m-1); /* second term */ float64_t second=0; for (index_t i=m_q_start; i<n; ++i) { for (index_t j=m_q_start; j<n; ++j) { /* ensure i!=j */ if (i==j) continue; second+=m_kernel->kernel(i,j); } } second/=n*(n-1); /* third term */ float64_t third=0; for (index_t i=0; i<m; ++i) { for (index_t j=m_q_start; j<n; ++j) third+=m_kernel->kernel(i,j); } third*=-2.0/(m*n); return first+second-third; } float64_t CQuadraticTimeMMD::compute_p_value(float64_t statistic) { float64_t result=0; switch (m_p_value_method) { #ifdef HAVE_LAPACK case MMD2_SPECTRUM: { /* get samples from null-distribution and compute p-value of statistic */ SGVector<float64_t> null_samples=sample_null_spectrum( m_num_samples_spectrum, m_num_eigenvalues_spectrum); CMath::qsort(null_samples); float64_t pos=CMath::find_position_to_insert(null_samples, statistic); result=1.0-pos/null_samples.vlen; break; } #endif // HAVE_LAPACK case MMD2_GAMMA: result=compute_p_value_gamma(statistic); break; default: result=CKernelTwoSampleTestStatistic::compute_p_value(statistic); break; } return result; } #ifdef HAVE_LAPACK SGVector<float64_t> CQuadraticTimeMMD::sample_null_spectrum(index_t num_samples, index_t num_eigenvalues) { /* the whole procedure is already checked against MATLAB implementation */ if (m_q_start!=m_p_and_q->get_num_vectors()/2) { /* TODO support different numbers of samples */ SG_ERROR("%s::sample_null_spectrum(): Currently, only equal " "sample sizes are supported\n", get_name()); } if (num_samples<=2) { SG_ERROR("%s::sample_null_spectrum(): Number of samples has to be at" " least 2, better in the hundrets", get_name()); } if (num_eigenvalues>2*m_q_start-1) { SG_ERROR("%s::sample_null_spectrum(): Number of Eigenvalues too large\n", get_name()); } if (num_eigenvalues<1) { SG_ERROR("%s::sample_null_spectrum(): Number of Eigenvalues too small\n", get_name()); } /* imaginary matrix K=[K KL; KL' L] (MATLAB notation) * K is matrix for XX, L is matrix for YY, KL is XY, LK is YX * works since X and Y are concatenated here */ m_kernel->init(m_p_and_q, m_p_and_q); SGMatrix<float64_t> K=m_kernel->get_kernel_matrix(); /* center matrix K=H*K*H */ K.center(); /* compute eigenvalues and select num_eigenvalues largest ones */ SGVector<float64_t> eigenvalues=SGMatrix<float64_t>::compute_eigenvectors(K); SGVector<float64_t> largest_ev(num_eigenvalues); /* scale by 1/2/m on the fly and take abs value*/ for (index_t i=0; i<num_eigenvalues; ++i) largest_ev[i]=CMath::abs(1.0/2/m_q_start*eigenvalues[eigenvalues.vlen-1-i]); /* finally, sample from null distribution */ SGVector<float64_t> null_samples(num_samples); for (index_t i=0; i<num_samples; ++i) { /* 2*sum(kEigs.*(randn(length(kEigs),1)).^2); */ null_samples[i]=0; for (index_t j=0; j<largest_ev.vlen; ++j) null_samples[i]+=largest_ev[j]*CMath::pow(2.0, 2); null_samples[i]*=2; } return null_samples; } #endif // HAVE_LAPACK float64_t CQuadraticTimeMMD::compute_p_value_gamma(float64_t statistic) { /* the whole procedure is already checked against MATLAB implementation */ if (m_q_start!=m_p_and_q->get_num_vectors()/2) { /* TODO support different numbers of samples */ SG_ERROR("%s::compute_threshold_gamma(): Currently, only equal " "sample sizes are supported\n", get_name()); } /* imaginary matrix K=[K KL; KL' L] (MATLAB notation) * K is matrix for XX, L is matrix for YY, KL is XY, LK is YX * works since X and Y are concatenated here */ m_kernel->init(m_p_and_q, m_p_and_q); SGMatrix<float64_t> K=m_kernel->get_kernel_matrix(); /* compute mean under H0 of MMD, which is * meanMMD = 2/m * ( 1 - 1/m*sum(diag(KL)) ); * in MATLAB */ float64_t mean_mmd=0; for (index_t i=0; i<m_q_start; ++i) { /* virtual KL matrix is in upper right corner of SHOGUN K matrix * so this sums the diagonal of the matrix between X and Y*/ mean_mmd+=K(i, m_q_start+i); /* remove diagonal of all pairs of kernel matrices on the fly */ K(i, i)=0; K(m_q_start+i, m_q_start+i)=0; K(i, m_q_start+i)=0; K(m_q_start+i, i)=0; } mean_mmd=2.0/m_q_start*(1.0-1.0/m_q_start*mean_mmd); /* compute variance under H0 of MMD, which is * varMMD = 2/m/(m-1) * 1/m/(m-1) * sum(sum( (K + L - KL - KL').^2 )); * in MATLAB, so sum up all elements */ float64_t var_mmd=0; for (index_t i=0; i<m_q_start; ++i) { for (index_t j=0; j<m_q_start; ++j) { float64_t to_add=0; to_add+=K(i, j); to_add+=K(m_q_start+i, m_q_start+j); to_add-=K(i, m_q_start+j); to_add-=K(m_q_start+i, j); var_mmd+=CMath::pow(to_add, 2); } } var_mmd*=2.0/m_q_start/(m_q_start-1)*1.0/m_q_start/(m_q_start-1); /* parameters for gamma distribution */ float64_t a=CMath::pow(mean_mmd, 2)/var_mmd; float64_t b=var_mmd*m_q_start / mean_mmd; /* return: cdf('gam',statistic,al,bet) (MATLAB) * which will get the position in the null distribution */ return CStatistics::gamma_cdf(statistic, a, b); } void CQuadraticTimeMMD::set_num_samples_sepctrum(index_t num_samples_spectrum) { m_num_samples_spectrum=num_samples_spectrum; } void CQuadraticTimeMMD::set_num_eigenvalues_spectrum( index_t num_eigenvalues_spectrum) { m_num_eigenvalues_spectrum=num_eigenvalues_spectrum; } <|endoftext|>
<commit_before>// alembicPlugin // Initial code generated by Softimage SDK Wizard // Executed Fri Aug 19 09:14:49 UTC+0200 2011 by helge // // Tip: You need to compile the generated code before you can load the plug-in. // After you compile the plug-in, you can load it by clicking Update All in the Plugin Manager. #include <xsi_application.h> #include <xsi_context.h> #include <xsi_pluginregistrar.h> #include <xsi_status.h> #include <xsi_argument.h> #include <xsi_command.h> #include <xsi_menu.h> #include <xsi_uitoolkit.h> #include <xsi_progressbar.h> #include <xsi_comapihandler.h> #include <xsi_project.h> #include <xsi_selection.h> #include <xsi_model.h> #include <xsi_null.h> #include <xsi_camera.h> #include <xsi_customoperator.h> #include <xsi_expression.h> #include <xsi_kinematics.h> #include <xsi_kinematicstate.h> #include <xsi_factory.h> #include <xsi_primitive.h> #include <xsi_math.h> #include <xsi_cluster.h> #include <xsi_clusterproperty.h> #include <xsi_primitive.h> #include <xsi_geometry.h> #include <xsi_polygonmesh.h> #include <xsi_ppglayout.h> #include <xsi_ppgitem.h> #include <xsi_ppgeventcontext.h> #include <xsi_icetree.h> #include <xsi_icenode.h> #include <xsi_icenodeinputport.h> #include <xsi_icecompoundnode.h> #include <xsi_utils.h> #include <xsi_time.h> #include <time.h> #include <xsi_customoperator.h> #include <xsi_operatorcontext.h> #include <xsi_outputport.h> #include "arnoldHelpers.h" using namespace XSI; using namespace MATH; #include <boost/exception/all.hpp> #include "AlembicLicensing.h" #include "AlembicWriteJob.h" #include "AlembicPoints.h" #include "AlembicCurves.h" #include "CommonProfiler.h" #include "CommonMeshUtilities.h" #include "CommonUtilities.h" SICALLBACK XSILoadPlugin_2( PluginRegistrar& in_reg ) ; SICALLBACK XSILoadPlugin( PluginRegistrar& in_reg ) { in_reg.PutAuthor(L"Helge Mathee"); in_reg.PutName(L"ExocortexAlembicSoftimage"); in_reg.PutVersion(1,0); //if( HasAlembicWriterLicense() ) { in_reg.RegisterCommand(L"alembic_export",L"alembic_export"); in_reg.RegisterMenu(siMenuMainFileExportID,L"alembic_MenuExport",false,false); in_reg.RegisterProperty(L"alembic_export_settings"); //} //if( HasAlembicReaderLicense() ) { in_reg.RegisterCommand(L"alembic_import",L"alembic_import"); in_reg.RegisterCommand(L"alembic_attach_metadata",L"alembic_attach_metadata"); in_reg.RegisterCommand(L"alembic_create_item",L"alembic_create_item"); in_reg.RegisterCommand(L"alembic_path_manager",L"alembic_path_manager"); in_reg.RegisterCommand(L"alembic_profile_stats",L"alembic_profile_stats"); in_reg.RegisterOperator(L"alembic_xform"); in_reg.RegisterOperator(L"alembic_camera"); in_reg.RegisterOperator(L"alembic_polymesh"); in_reg.RegisterOperator(L"alembic_polymesh_topo"); in_reg.RegisterOperator(L"alembic_nurbs"); in_reg.RegisterOperator(L"alembic_bbox"); in_reg.RegisterOperator(L"alembic_normals"); in_reg.RegisterOperator(L"alembic_uvs"); in_reg.RegisterOperator(L"alembic_crvlist"); in_reg.RegisterOperator(L"alembic_crvlist_topo"); in_reg.RegisterOperator(L"alembic_visibility"); in_reg.RegisterOperator(L"alembic_geomapprox"); in_reg.RegisterOperator(L"alembic_standinop"); in_reg.RegisterMenu(siMenuMainFileImportID,L"alembic_MenuImport",false,false); in_reg.RegisterMenu(siMenuMainFileProjectID,L"alembic_MenuPathManager",false,false); in_reg.RegisterMenu(siMenuMainFileProjectID,L"alembic_ProfileStats",false,false); in_reg.RegisterMenu(siMenuTbGetPropertyID,L"alembic_MenuMetaData",false,false); in_reg.RegisterProperty(L"alembic_import_settings"); in_reg.RegisterProperty(L"alembic_timecontrol"); in_reg.RegisterProperty(L"alembic_metadata"); // register ICE nodes Register_alembic_curves(in_reg); Register_alembic_points(in_reg); //XSILoadPlugin_2( in_reg ); // register events in_reg.RegisterEvent(L"alembic_OnCloseScene",siOnCloseScene); //} ESS_LOG_INFO("PLUGIN loaded"); return CStatus::OK; } SICALLBACK XSIUnloadPlugin( const PluginRegistrar& in_reg ) { deleteAllArchives(); CString strPluginName; strPluginName = in_reg.GetName(); Application().LogMessage(strPluginName + L" has been unloaded.",siVerboseMsg); return CStatus::OK; } ESS_CALLBACK_START(alembic_MenuExport_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic 1.0",L"alembic_export",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_MenuImport_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic 1.0",L"alembic_import",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_MenuPathManager_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic Path Manager",L"alembic_path_manager",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_ProfileStats_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic Profile Stats",L"alembic_profile_stats",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_profile_stats_Init,CRef&) Context ctxt( in_ctxt ); Command oCmd; oCmd = ctxt.GetSource(); oCmd.PutDescription(L""); oCmd.EnableReturnValue(true); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_profile_stats_Execute, CRef&) ESS_PROFILE_REPORT(); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_OnCloseScene_OnEvent,CRef&) deleteAllArchives(); return CStatus::OK; ESS_CALLBACK_END <commit_msg>fixed #146<commit_after>// alembicPlugin // Initial code generated by Softimage SDK Wizard // Executed Fri Aug 19 09:14:49 UTC+0200 2011 by helge // // Tip: You need to compile the generated code before you can load the plug-in. // After you compile the plug-in, you can load it by clicking Update All in the Plugin Manager. #include <xsi_application.h> #include <xsi_context.h> #include <xsi_pluginregistrar.h> #include <xsi_status.h> #include <xsi_argument.h> #include <xsi_command.h> #include <xsi_menu.h> #include <xsi_uitoolkit.h> #include <xsi_progressbar.h> #include <xsi_comapihandler.h> #include <xsi_project.h> #include <xsi_selection.h> #include <xsi_model.h> #include <xsi_null.h> #include <xsi_camera.h> #include <xsi_customoperator.h> #include <xsi_expression.h> #include <xsi_kinematics.h> #include <xsi_kinematicstate.h> #include <xsi_factory.h> #include <xsi_primitive.h> #include <xsi_math.h> #include <xsi_cluster.h> #include <xsi_clusterproperty.h> #include <xsi_primitive.h> #include <xsi_geometry.h> #include <xsi_polygonmesh.h> #include <xsi_ppglayout.h> #include <xsi_ppgitem.h> #include <xsi_ppgeventcontext.h> #include <xsi_icetree.h> #include <xsi_icenode.h> #include <xsi_icenodeinputport.h> #include <xsi_icecompoundnode.h> #include <xsi_utils.h> #include <xsi_time.h> #include <time.h> #include <xsi_customoperator.h> #include <xsi_operatorcontext.h> #include <xsi_outputport.h> #include "arnoldHelpers.h" using namespace XSI; using namespace MATH; #include <boost/exception/all.hpp> #include "AlembicLicensing.h" #include "AlembicWriteJob.h" #include "AlembicPoints.h" #include "AlembicCurves.h" #include "CommonProfiler.h" #include "CommonMeshUtilities.h" #include "CommonUtilities.h" SICALLBACK XSILoadPlugin_2( PluginRegistrar& in_reg ) ; SICALLBACK XSILoadPlugin( PluginRegistrar& in_reg ) { in_reg.PutAuthor(L"Exocortex Technologies, Inc and Helge Mathee"); in_reg.PutName(L"ExocortexAlembicSoftimage"); in_reg.PutEmail(L"[email protected]"); in_reg.PutURL(L"http://www.exocortex.com/alembic"); in_reg.PutVersion(1,0); //if( HasAlembicWriterLicense() ) { in_reg.RegisterCommand(L"alembic_export",L"alembic_export"); in_reg.RegisterMenu(siMenuMainFileExportID,L"alembic_MenuExport",false,false); in_reg.RegisterProperty(L"alembic_export_settings"); //} //if( HasAlembicReaderLicense() ) { in_reg.RegisterCommand(L"alembic_import",L"alembic_import"); in_reg.RegisterCommand(L"alembic_attach_metadata",L"alembic_attach_metadata"); in_reg.RegisterCommand(L"alembic_create_item",L"alembic_create_item"); in_reg.RegisterCommand(L"alembic_path_manager",L"alembic_path_manager"); in_reg.RegisterCommand(L"alembic_profile_stats",L"alembic_profile_stats"); in_reg.RegisterOperator(L"alembic_xform"); in_reg.RegisterOperator(L"alembic_camera"); in_reg.RegisterOperator(L"alembic_polymesh"); in_reg.RegisterOperator(L"alembic_polymesh_topo"); in_reg.RegisterOperator(L"alembic_nurbs"); in_reg.RegisterOperator(L"alembic_bbox"); in_reg.RegisterOperator(L"alembic_normals"); in_reg.RegisterOperator(L"alembic_uvs"); in_reg.RegisterOperator(L"alembic_crvlist"); in_reg.RegisterOperator(L"alembic_crvlist_topo"); in_reg.RegisterOperator(L"alembic_visibility"); in_reg.RegisterOperator(L"alembic_geomapprox"); in_reg.RegisterOperator(L"alembic_standinop"); in_reg.RegisterMenu(siMenuMainFileImportID,L"alembic_MenuImport",false,false); in_reg.RegisterMenu(siMenuMainFileProjectID,L"alembic_MenuPathManager",false,false); in_reg.RegisterMenu(siMenuMainFileProjectID,L"alembic_ProfileStats",false,false); in_reg.RegisterMenu(siMenuTbGetPropertyID,L"alembic_MenuMetaData",false,false); in_reg.RegisterProperty(L"alembic_import_settings"); in_reg.RegisterProperty(L"alembic_timecontrol"); in_reg.RegisterProperty(L"alembic_metadata"); // register ICE nodes Register_alembic_curves(in_reg); Register_alembic_points(in_reg); //XSILoadPlugin_2( in_reg ); // register events in_reg.RegisterEvent(L"alembic_OnCloseScene",siOnCloseScene); //} ESS_LOG_INFO("PLUGIN loaded"); return CStatus::OK; } SICALLBACK XSIUnloadPlugin( const PluginRegistrar& in_reg ) { deleteAllArchives(); CString strPluginName; strPluginName = in_reg.GetName(); Application().LogMessage(strPluginName + L" has been unloaded.",siVerboseMsg); return CStatus::OK; } ESS_CALLBACK_START(alembic_MenuExport_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic 1.0",L"alembic_export",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_MenuImport_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic 1.0",L"alembic_import",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_MenuPathManager_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic Path Manager",L"alembic_path_manager",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_ProfileStats_Init,CRef&) Context ctxt( in_ctxt ); Menu oMenu; oMenu = ctxt.GetSource(); MenuItem oNewItem; oMenu.AddCommandItem(L"Alembic Profile Stats",L"alembic_profile_stats",oNewItem); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_profile_stats_Init,CRef&) Context ctxt( in_ctxt ); Command oCmd; oCmd = ctxt.GetSource(); oCmd.PutDescription(L""); oCmd.EnableReturnValue(true); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_profile_stats_Execute, CRef&) ESS_PROFILE_REPORT(); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_OnCloseScene_OnEvent,CRef&) deleteAllArchives(); return CStatus::OK; ESS_CALLBACK_END <|endoftext|>
<commit_before>// vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 : /// @addtogroup ahbmem /// @{ /// @file ahbmem.cpp /// /// @date 2010-2014 /// @copyright All rights reserved. /// Any reproduction, use, distribution or disclosure of this /// program, without the express, prior written consent of the /// authors is strictly prohibited. /// @author Rolf Meyer /// /// Provide a test bench memory class with AHB slave interface. DMI and /// streaming width fields are ignored. Delays are not modeled. Address checking /// is performed in that way, that transactions are only executed if the slave /// select condition defined in grlib user manual holds. Transactions generating /// a correct slave select but exceeding the memory region due to their length /// are reported as warning and executed anyhow. #include <fstream> #include "core/models/ahbmem/ahbmem.h" #include "core/common/sr_report.h" #include "core/common/verbose.h" #include "core/common/sr_registry.h" SR_HAS_MODULE(AHBMem); /// Constructor AHBMem::AHBMem(const ModuleName nm, // Module name uint16_t haddr, // AMBA AHB address (12 bit) uint16_t hmask, // AMBA AHB address mask (12 bit) AbstractionLayer ambaLayer, // abstraction layer uint32_t hindex, bool cacheable, uint32_t wait_states, bool pow_mon) : AHBSlave<>(nm, hindex, 0x01, // Gaisler 0x00E, // AHB Mem, 0, 0, ambaLayer, BAR(AHBMEM, hmask, cacheable, 0, haddr)), ahbBaseAddress(static_cast<uint32_t>((hmask) & haddr) << 20), ahbSize(~(static_cast<uint32_t>(hmask) << 20) + 1), g_haddr("haddr", haddr, m_generics), g_hmask("hmask", hmask, m_generics), g_hindex("hindex", hindex, m_generics), g_cacheable("cacheable", cacheable, m_generics), g_wait_states("wait_states", wait_states, m_generics), g_pow_mon("pow_mon", pow_mon, m_generics), g_storage_type("storage", "ArrayStorage", m_generics), sta_power_norm("sta_power_norm", 1269.53125, m_power), // Normalized static power input int_power_norm("int_power_norm", 1.61011e-12, m_power), // Normalized internal power input dyn_read_energy_norm("dyn_read_energy_norm", 7.57408e-13, m_power), // Normalized read energy input dyn_write_energy_norm("dyn_write_energy_norm", 7.57408e-13, m_power), // Normalized write energy iput sta_power("sta_power", 0.0, m_power), // Static power output int_power("int_power", 0.0, m_power), // Internal power of module (dyn. switching independent) swi_power("swi_power", 0.0, m_power), // Switching power of modules power_frame_starting_time("power_frame_starting_time", SC_ZERO_TIME, m_power), dyn_read_energy("dyn_read_energy", 0.0, m_power), // Energy per read access dyn_write_energy("dyn_write_energy", 0.0, m_power), // Energy per write access dyn_reads("dyn_reads", 0ull, m_power), // Read access counter for power computation dyn_writes("dyn_writes", 0ull, m_power) { // Write access counter for power computation // haddr and hmask must be 12 bit assert(!((g_haddr | g_hmask) >> 12)); // Register power callback functions if (g_pow_mon) { GC_REGISTER_TYPED_PARAM_CALLBACK(&sta_power, gs::cnf::pre_read, AHBMem, sta_power_cb); GC_REGISTER_TYPED_PARAM_CALLBACK(&int_power, gs::cnf::pre_read, AHBMem, int_power_cb); GC_REGISTER_TYPED_PARAM_CALLBACK(&swi_power, gs::cnf::pre_read, AHBMem, swi_power_cb); } AHBMem::init_generics(); ahb.register_get_direct_mem_ptr(this, &AHBMem::get_direct_mem_ptr); // Display AHB slave information srInfo("/configuration/ahbmem/ahbslave") ("addr", (uint64_t)get_ahb_base_addr()) ("size", (uint64_t)get_ahb_size()) ("AHB Slave Configuration"); srInfo("/configuration/ahbmem/generics") ("haddr", g_haddr) ("hmask", g_hmask) ("hindex", g_hindex) ("cacheable", g_cacheable) ("wait_states", g_wait_states) ("Create AHB simulation memory"); } /// Destructor AHBMem::~AHBMem() { // Delete memory contents GC_UNREGISTER_CALLBACKS(); } void AHBMem::init_generics() { // set name, type, default, range, hint and description for gs_configs g_hindex.add_properties() ("name", "Bus Index") ("vhdl_name","hindex") ("range", "0..15") ("Slave index at the AHB bus"); g_haddr.add_properties() ("name", "AHB Address") ("vhdl_name","haddr") ("base","hex") ("range", "0..0xFFF") ("The 12bit MSB address at the AHB bus"); g_hmask.add_properties() ("name", "AHB Mask") ("vhdl_name","hmask") ("base","hex") ("range", "0..0xFFF") ("The 12bit AHB address mask"); g_cacheable.add_properties() ("name", "Memory Cachability") ("If true the AHB Bus will set the cachability flag for all transactions from the memory"); g_wait_states.add_properties() ("name", "Wait States") ("Number of wait states for each transaction"); g_pow_mon.add_properties() ("name", "Power Monitoring") ("If true enable power monitoring"); g_pow_mon.add_properties() ("name", "Memory Storage Type") ("enum", "ArrayStorage, MapStorage") ("Defines the type of memory used as a backend implementation"); } void AHBMem::dorst() { erase(0, get_ahb_size()-1); } /// Encapsulated functionality uint32_t AHBMem::exec_func( tlm::tlm_generic_payload &trans, // NOLINT(runtime/references) sc_core::sc_time &delay, // NOLINT(runtime/references) bool debug) { uint32_t words_transferred; // Is the address for me if (!((g_haddr ^ (trans.get_address() >> 20)) & g_hmask)) { // Warn if access exceeds slave memory region if ((trans.get_address() + trans.get_data_length()) > (ahbBaseAddress + ahbSize)) { srWarn(name()) ("Transaction exceeds slave memory region"); } trans.set_dmi_allowed(m_storage->allow_dmi_rw()); if (trans.is_write()) { // write simulation memory write_block(get_ahb_bar_relative_addr(0,trans.get_address()), trans.get_data_ptr(), trans.get_data_length()); // Base delay is one clock cycle per word words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2); if (g_pow_mon) { dyn_writes += words_transferred; } // Total delay is base delay + wait states delay += clock_cycle * (words_transferred + g_wait_states); trans.set_response_status(tlm::TLM_OK_RESPONSE); } else { // read simulation memory read_block(get_ahb_bar_relative_addr(0,trans.get_address()), trans.get_data_ptr(), trans.get_data_length()); // Base delay is one clock cycle per word words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2); if (g_pow_mon) { dyn_reads += words_transferred; } // Total delay is base delay + wait states delay += clock_cycle * (words_transferred + g_wait_states); trans.set_response_status(tlm::TLM_OK_RESPONSE); // set cacheability if (g_cacheable) { ahb.validate_extension<amba::amba_cacheable>(trans); } } srDebug(name()) ("delay", delay) ("Delay increment!"); } else { // address not valid srError(name()) ("taddress", (uint64_t)trans.get_address()) ("taddr", (uint64_t)trans.get_address() >> 20) ("haddr", g_haddr) ("hmask", g_hmask) ("Address not within permissable slave memory space"); trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE); } return trans.get_data_length(); } // Returns clock cycle time for e.g. use in AHBSlave parent sc_core::sc_time AHBMem::get_clock() { return clock_cycle; } bool AHBMem::get_direct_mem_ptr(tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data) { // access to ROM adress space dmi_data.allow_read_write(); dmi_data.set_dmi_ptr(m_storage->get_dmi_ptr()); dmi_data.set_start_address(0); dmi_data.set_end_address(get_ahb_bar_size(0)); dmi_data.set_read_latency(SC_ZERO_TIME); dmi_data.set_write_latency(SC_ZERO_TIME); v::info << name() << "allow_dmi_rw is: " << v::uint32 << m_storage->allow_dmi_rw() << v::endl; return m_storage->allow_dmi_rw(); } void AHBMem::writeByteDBG(const uint32_t address, const uint8_t byte) { write_dbg(address, byte); } void AHBMem::before_end_of_elaboration() { set_storage(g_storage_type, get_ahb_bar_size(0)); } // Automatically called at the beginning of the simulation void AHBMem::start_of_simulation() { // Initialize power model if (g_pow_mon) { power_model(); } } // Calculate power/energy values from normalized input data void AHBMem::power_model() { // Static power calculation (pW) sta_power = sta_power_norm * (get_ahb_size() << 3); // Cell internal power (uW) int_power = int_power_norm * (get_ahb_size() << 3) * 1 / (clock_cycle.to_seconds()); // Energy per read access (uJ) dyn_read_energy = dyn_read_energy_norm * 32 * (get_ahb_size() << 3); // Energy per write access (uJ) dyn_write_energy = dyn_write_energy_norm * 32 * (get_ahb_size() << 3); } // Static power callback gs::cnf::callback_return_type AHBMem::sta_power_cb( gs::gs_param_base &changed_param, // NOLINT(runtime/references) gs::cnf::callback_type reason) { // Nothing to do !! // Static power of AHBMem is constant !! return GC_RETURN_OK; } // Internal power callback gs::cnf::callback_return_type AHBMem::int_power_cb( gs::gs_param_base &changed_param, // NOLINT(runtime/references) gs::cnf::callback_type reason) { // Nothing to do !! // AHBMem internal power is constant !! return GC_RETURN_OK; } // Switching power callback gs::cnf::callback_return_type AHBMem::swi_power_cb( gs::gs_param_base &changed_param, // NOLINT(runtime/references) gs::cnf::callback_type reason) { swi_power = ((dyn_read_energy * dyn_reads) + (dyn_write_energy * dyn_writes)) / (sc_time_stamp() - power_frame_starting_time).to_seconds(); return GC_RETURN_OK; } // Automatically called at the end of the simulation void AHBMem::end_of_simulation() { v::report << name() << " **************************************************** " << v::endl; v::report << name() << " * AHBMem Statistics: " << v::endl; v::report << name() << " * ------------------ " << v::endl; print_transport_statistics(name()); v::report << name() << " * ************************************************** " << v::endl; } /// @} <commit_msg>corrected small copy and paste error in ahbmem<commit_after>// vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 : /// @addtogroup ahbmem /// @{ /// @file ahbmem.cpp /// /// @date 2010-2014 /// @copyright All rights reserved. /// Any reproduction, use, distribution or disclosure of this /// program, without the express, prior written consent of the /// authors is strictly prohibited. /// @author Rolf Meyer /// /// Provide a test bench memory class with AHB slave interface. DMI and /// streaming width fields are ignored. Delays are not modeled. Address checking /// is performed in that way, that transactions are only executed if the slave /// select condition defined in grlib user manual holds. Transactions generating /// a correct slave select but exceeding the memory region due to their length /// are reported as warning and executed anyhow. #include <fstream> #include "core/models/ahbmem/ahbmem.h" #include "core/common/sr_report.h" #include "core/common/verbose.h" #include "core/common/sr_registry.h" SR_HAS_MODULE(AHBMem); /// Constructor AHBMem::AHBMem(const ModuleName nm, // Module name uint16_t haddr, // AMBA AHB address (12 bit) uint16_t hmask, // AMBA AHB address mask (12 bit) AbstractionLayer ambaLayer, // abstraction layer uint32_t hindex, bool cacheable, uint32_t wait_states, bool pow_mon) : AHBSlave<>(nm, hindex, 0x01, // Gaisler 0x00E, // AHB Mem, 0, 0, ambaLayer, BAR(AHBMEM, hmask, cacheable, 0, haddr)), ahbBaseAddress(static_cast<uint32_t>((hmask) & haddr) << 20), ahbSize(~(static_cast<uint32_t>(hmask) << 20) + 1), g_haddr("haddr", haddr, m_generics), g_hmask("hmask", hmask, m_generics), g_hindex("hindex", hindex, m_generics), g_cacheable("cacheable", cacheable, m_generics), g_wait_states("wait_states", wait_states, m_generics), g_pow_mon("pow_mon", pow_mon, m_generics), g_storage_type("storage", "ArrayStorage", m_generics), sta_power_norm("sta_power_norm", 1269.53125, m_power), // Normalized static power input int_power_norm("int_power_norm", 1.61011e-12, m_power), // Normalized internal power input dyn_read_energy_norm("dyn_read_energy_norm", 7.57408e-13, m_power), // Normalized read energy input dyn_write_energy_norm("dyn_write_energy_norm", 7.57408e-13, m_power), // Normalized write energy iput sta_power("sta_power", 0.0, m_power), // Static power output int_power("int_power", 0.0, m_power), // Internal power of module (dyn. switching independent) swi_power("swi_power", 0.0, m_power), // Switching power of modules power_frame_starting_time("power_frame_starting_time", SC_ZERO_TIME, m_power), dyn_read_energy("dyn_read_energy", 0.0, m_power), // Energy per read access dyn_write_energy("dyn_write_energy", 0.0, m_power), // Energy per write access dyn_reads("dyn_reads", 0ull, m_power), // Read access counter for power computation dyn_writes("dyn_writes", 0ull, m_power) { // Write access counter for power computation // haddr and hmask must be 12 bit assert(!((g_haddr | g_hmask) >> 12)); // Register power callback functions if (g_pow_mon) { GC_REGISTER_TYPED_PARAM_CALLBACK(&sta_power, gs::cnf::pre_read, AHBMem, sta_power_cb); GC_REGISTER_TYPED_PARAM_CALLBACK(&int_power, gs::cnf::pre_read, AHBMem, int_power_cb); GC_REGISTER_TYPED_PARAM_CALLBACK(&swi_power, gs::cnf::pre_read, AHBMem, swi_power_cb); } AHBMem::init_generics(); ahb.register_get_direct_mem_ptr(this, &AHBMem::get_direct_mem_ptr); // Display AHB slave information srInfo("/configuration/ahbmem/ahbslave") ("addr", (uint64_t)get_ahb_base_addr()) ("size", (uint64_t)get_ahb_size()) ("AHB Slave Configuration"); srInfo("/configuration/ahbmem/generics") ("haddr", g_haddr) ("hmask", g_hmask) ("hindex", g_hindex) ("cacheable", g_cacheable) ("wait_states", g_wait_states) ("Create AHB simulation memory"); } /// Destructor AHBMem::~AHBMem() { // Delete memory contents GC_UNREGISTER_CALLBACKS(); } void AHBMem::init_generics() { // set name, type, default, range, hint and description for gs_configs g_hindex.add_properties() ("name", "Bus Index") ("vhdl_name","hindex") ("range", "0..15") ("Slave index at the AHB bus"); g_haddr.add_properties() ("name", "AHB Address") ("vhdl_name","haddr") ("base","hex") ("range", "0..0xFFF") ("The 12bit MSB address at the AHB bus"); g_hmask.add_properties() ("name", "AHB Mask") ("vhdl_name","hmask") ("base","hex") ("range", "0..0xFFF") ("The 12bit AHB address mask"); g_cacheable.add_properties() ("name", "Memory Cachability") ("If true the AHB Bus will set the cachability flag for all transactions from the memory"); g_wait_states.add_properties() ("name", "Wait States") ("Number of wait states for each transaction"); g_pow_mon.add_properties() ("name", "Power Monitoring") ("If true enable power monitoring"); g_storage_type.add_properties() ("name", "Memory Storage Type") ("enum", "ArrayStorage, MapStorage") ("Defines the type of memory used as a backend implementation"); } void AHBMem::dorst() { erase(0, get_ahb_size()-1); } /// Encapsulated functionality uint32_t AHBMem::exec_func( tlm::tlm_generic_payload &trans, // NOLINT(runtime/references) sc_core::sc_time &delay, // NOLINT(runtime/references) bool debug) { uint32_t words_transferred; // Is the address for me if (!((g_haddr ^ (trans.get_address() >> 20)) & g_hmask)) { // Warn if access exceeds slave memory region if ((trans.get_address() + trans.get_data_length()) > (ahbBaseAddress + ahbSize)) { srWarn(name()) ("Transaction exceeds slave memory region"); } trans.set_dmi_allowed(m_storage->allow_dmi_rw()); if (trans.is_write()) { // write simulation memory write_block(get_ahb_bar_relative_addr(0,trans.get_address()), trans.get_data_ptr(), trans.get_data_length()); // Base delay is one clock cycle per word words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2); if (g_pow_mon) { dyn_writes += words_transferred; } // Total delay is base delay + wait states delay += clock_cycle * (words_transferred + g_wait_states); trans.set_response_status(tlm::TLM_OK_RESPONSE); } else { // read simulation memory read_block(get_ahb_bar_relative_addr(0,trans.get_address()), trans.get_data_ptr(), trans.get_data_length()); // Base delay is one clock cycle per word words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2); if (g_pow_mon) { dyn_reads += words_transferred; } // Total delay is base delay + wait states delay += clock_cycle * (words_transferred + g_wait_states); trans.set_response_status(tlm::TLM_OK_RESPONSE); // set cacheability if (g_cacheable) { ahb.validate_extension<amba::amba_cacheable>(trans); } } srDebug(name()) ("delay", delay) ("Delay increment!"); } else { // address not valid srError(name()) ("taddress", (uint64_t)trans.get_address()) ("taddr", (uint64_t)trans.get_address() >> 20) ("haddr", g_haddr) ("hmask", g_hmask) ("Address not within permissable slave memory space"); trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE); } return trans.get_data_length(); } // Returns clock cycle time for e.g. use in AHBSlave parent sc_core::sc_time AHBMem::get_clock() { return clock_cycle; } bool AHBMem::get_direct_mem_ptr(tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data) { // access to ROM adress space dmi_data.allow_read_write(); dmi_data.set_dmi_ptr(m_storage->get_dmi_ptr()); dmi_data.set_start_address(0); dmi_data.set_end_address(get_ahb_bar_size(0)); dmi_data.set_read_latency(SC_ZERO_TIME); dmi_data.set_write_latency(SC_ZERO_TIME); v::info << name() << "allow_dmi_rw is: " << v::uint32 << m_storage->allow_dmi_rw() << v::endl; return m_storage->allow_dmi_rw(); } void AHBMem::writeByteDBG(const uint32_t address, const uint8_t byte) { write_dbg(address, byte); } void AHBMem::before_end_of_elaboration() { set_storage(g_storage_type, get_ahb_bar_size(0)); } // Automatically called at the beginning of the simulation void AHBMem::start_of_simulation() { // Initialize power model if (g_pow_mon) { power_model(); } } // Calculate power/energy values from normalized input data void AHBMem::power_model() { // Static power calculation (pW) sta_power = sta_power_norm * (get_ahb_size() << 3); // Cell internal power (uW) int_power = int_power_norm * (get_ahb_size() << 3) * 1 / (clock_cycle.to_seconds()); // Energy per read access (uJ) dyn_read_energy = dyn_read_energy_norm * 32 * (get_ahb_size() << 3); // Energy per write access (uJ) dyn_write_energy = dyn_write_energy_norm * 32 * (get_ahb_size() << 3); } // Static power callback gs::cnf::callback_return_type AHBMem::sta_power_cb( gs::gs_param_base &changed_param, // NOLINT(runtime/references) gs::cnf::callback_type reason) { // Nothing to do !! // Static power of AHBMem is constant !! return GC_RETURN_OK; } // Internal power callback gs::cnf::callback_return_type AHBMem::int_power_cb( gs::gs_param_base &changed_param, // NOLINT(runtime/references) gs::cnf::callback_type reason) { // Nothing to do !! // AHBMem internal power is constant !! return GC_RETURN_OK; } // Switching power callback gs::cnf::callback_return_type AHBMem::swi_power_cb( gs::gs_param_base &changed_param, // NOLINT(runtime/references) gs::cnf::callback_type reason) { swi_power = ((dyn_read_energy * dyn_reads) + (dyn_write_energy * dyn_writes)) / (sc_time_stamp() - power_frame_starting_time).to_seconds(); return GC_RETURN_OK; } // Automatically called at the end of the simulation void AHBMem::end_of_simulation() { v::report << name() << " **************************************************** " << v::endl; v::report << name() << " * AHBMem Statistics: " << v::endl; v::report << name() << " * ------------------ " << v::endl; print_transport_statistics(name()); v::report << name() << " * ************************************************** " << v::endl; } /// @} <|endoftext|>
<commit_before>#include <Windows.h> #include <cstdio> #include <cstring> using namespace std; enum DisplaySelection { DS_MONITOR = 1, DS_HDMI = 2, DS_TOGGLE = 3, }; /* This array must match the above enum */ char *DisplaySelectionString[] = { "Monitor", "HDMI", "Toggle", }; #define MAX_PATH_ELEMENTS 10 #define MAX_MODE_ELEMENTS 10 int main(int argc, char *argv[]) { LONG retval; DISPLAYCONFIG_PATH_INFO pathArray[MAX_PATH_ELEMENTS]; DISPLAYCONFIG_MODE_INFO modeArray[MAX_MODE_ELEMENTS]; UINT32 numPathElements = sizeof(pathArray)/sizeof(pathArray[0]); UINT32 numModeElements = sizeof(modeArray)/sizeof(modeArray[0]); UINT32 hdmi_idx = MAX_PATH_ELEMENTS; UINT32 dvi_idx = MAX_PATH_ELEMENTS; DisplaySelection current_selection = DS_TOGGLE; retval = QueryDisplayConfig(QDC_ALL_PATHS, &numPathElements, pathArray, &numModeElements, modeArray, NULL); if (ERROR_SUCCESS != retval) { printf("Query failure - unable to set new path!!\n"); return 2; } /* Find the target paths we care about */ for (unsigned int path = 0; path < numPathElements; path++) { if (pathArray[path].sourceInfo.modeInfoIdx >= 0 && pathArray[path].sourceInfo.modeInfoIdx < numModeElements) { if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { hdmi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection = DS_HDMI; } else if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { dvi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection = DS_MONITOR; } } } if (current_selection == DS_TOGGLE) { printf("Unable to determine current video output -- exiting\n"); return 3; } /* No argument means toggle output */ unsigned int input = DS_TOGGLE; DISPLAYCONFIG_PATH_INFO desiredSettings; /* Try to get the desired output setting */ if (argc > 1) { input = atoi(argv[1]); } /* input should match the enum above. indexed into the string array as (input - 1) */ if ((input - 1) < (sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]))) { printf("Device to be selected is the %s selection.\n", DisplaySelectionString[input - 1]); if ((DS_MONITOR == input && current_selection == DS_HDMI) || (DS_TOGGLE == input && DS_HDMI == current_selection)) { if (dvi_idx < MAX_PATH_ELEMENTS) desiredSettings = pathArray[dvi_idx]; else { printf("Attempting to switch to DVI, but unable to find config element -- exiting\n"); return 4; } } else if ((DS_HDMI == input && current_selection == DS_MONITOR) || (DS_TOGGLE == input && DS_MONITOR == current_selection)) { if (hdmi_idx < MAX_PATH_ELEMENTS) desiredSettings = pathArray[hdmi_idx]; else { printf("Attempting to switch to HDMI, but unable to find config element -- exiting\n"); return 5; } } else { printf("Output already set to the desired selection.\n"); return 0; } } else { printf("Unknown display selection: %d\n\n", input); printf("Usage:\n"); printf("\tDisplayController_Config.exe [new_output]\n"); for (int i = 0; i < sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]); i++) { printf("\t\t%d: %s\n", i + 1, DisplaySelectionString[i]); } printf("\n\tNo parameter means Toggle\n"); return 1; } /* If we get here we will attempt to set the path -- let SetDisplayConfig pick the mode info */ desiredSettings.flags = DISPLAYCONFIG_PATH_ACTIVE; desiredSettings.targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; desiredSettings.sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_APPLY | SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_PATH_ORDER_CHANGES); if (ERROR_SUCCESS != retval) { printf("Unable to set -- trying again with SetDisplayConfig creating mode info\n"); retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_CHANGES | SDC_ALLOW_PATH_ORDER_CHANGES |SDC_USE_SUPPLIED_DISPLAY_CONFIG); if (ERROR_SUCCESS != retval) { printf("Unable to set the new display config!!\n"); return 3; } } return 0; }<commit_msg>Increase path elements buffer<commit_after>#include <Windows.h> #include <cstdio> #include <cstring> using namespace std; enum DisplaySelection { DS_MONITOR = 1, DS_HDMI = 2, DS_TOGGLE = 3, }; /* This array must match the above enum */ char *DisplaySelectionString[] = { "Monitor", "HDMI", "Toggle", }; #define MAX_PATH_ELEMENTS 128 #define MAX_MODE_ELEMENTS 8 int main(int argc, char *argv[]) { LONG retval; DISPLAYCONFIG_PATH_INFO pathArray[MAX_PATH_ELEMENTS]; DISPLAYCONFIG_MODE_INFO modeArray[MAX_MODE_ELEMENTS]; UINT32 numPathElements = sizeof(pathArray)/sizeof(pathArray[0]); UINT32 numModeElements = sizeof(modeArray)/sizeof(modeArray[0]); UINT32 hdmi_idx = MAX_PATH_ELEMENTS; UINT32 dvi_idx = MAX_PATH_ELEMENTS; DisplaySelection current_selection = DS_TOGGLE; retval = QueryDisplayConfig(QDC_ALL_PATHS, &numPathElements, pathArray, &numModeElements, modeArray, NULL); if (ERROR_SUCCESS != retval) { printf("Query failure - unable to set new path!!\n"); return 2; } /* Find the target paths we care about */ for (unsigned int path = 0; path < numPathElements; path++) { if (pathArray[path].sourceInfo.modeInfoIdx >= 0 && pathArray[path].sourceInfo.modeInfoIdx < numModeElements) { if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { hdmi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection = DS_HDMI; } else if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { dvi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection = DS_MONITOR; } } } if (current_selection == DS_TOGGLE) { printf("Unable to determine current video output -- exiting\n"); return 3; } /* No argument means toggle output */ unsigned int input = DS_TOGGLE; DISPLAYCONFIG_PATH_INFO desiredSettings; /* Try to get the desired output setting */ if (argc > 1) { input = atoi(argv[1]); } /* input should match the enum above. indexed into the string array as (input - 1) */ if ((input - 1) < (sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]))) { printf("Device to be selected is the %s selection.\n", DisplaySelectionString[input - 1]); if ((DS_MONITOR == input && current_selection == DS_HDMI) || (DS_TOGGLE == input && DS_HDMI == current_selection)) { if (dvi_idx < MAX_PATH_ELEMENTS) desiredSettings = pathArray[dvi_idx]; else { printf("Attempting to switch to DVI, but unable to find config element -- exiting\n"); return 4; } } else if ((DS_HDMI == input && current_selection == DS_MONITOR) || (DS_TOGGLE == input && DS_MONITOR == current_selection)) { if (hdmi_idx < MAX_PATH_ELEMENTS) desiredSettings = pathArray[hdmi_idx]; else { printf("Attempting to switch to HDMI, but unable to find config element -- exiting\n"); return 5; } } else { printf("Output already set to the desired selection.\n"); return 0; } } else { printf("Unknown display selection: %d\n\n", input); printf("Usage:\n"); printf("\tDisplayController_Config.exe [new_output]\n"); for (int i = 0; i < sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]); i++) { printf("\t\t%d: %s\n", i + 1, DisplaySelectionString[i]); } printf("\n\tNo parameter means Toggle\n"); return 1; } /* If we get here we will attempt to set the path -- let SetDisplayConfig pick the mode info */ desiredSettings.flags = DISPLAYCONFIG_PATH_ACTIVE; desiredSettings.targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; desiredSettings.sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_APPLY | SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_PATH_ORDER_CHANGES); if (ERROR_SUCCESS != retval) { printf("Unable to set -- trying again with SetDisplayConfig creating mode info\n"); retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_CHANGES | SDC_ALLOW_PATH_ORDER_CHANGES |SDC_USE_SUPPLIED_DISPLAY_CONFIG); if (ERROR_SUCCESS != retval) { printf("Unable to set the new display config!!\n"); return 3; } } return 0; }<|endoftext|>
<commit_before>// [WriteFile Name=GenerateGeodatabase, Category=Features] // [Legal] // Copyright 2016 Esri. // 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. // [Legal] #include "GenerateGeodatabase.h" #include "Map.h" #include "MapQuickView.h" #include "FeatureLayer.h" #include "Basemap.h" #include "SpatialReference.h" #include "ServiceFeatureTable.h" #include "ArcGISTiledLayer.h" #include "Envelope.h" #include "GenerateGeodatabaseParameters.h" #include "GeodatabaseSyncTask.h" #include "GeometryEngine.h" #include "GenerateLayerOption.h" #include "GeodatabaseFeatureTable.h" #include <QUrl> #include <QQmlProperty> using namespace Esri::ArcGISRuntime; GenerateGeodatabase::GenerateGeodatabase(QQuickItem* parent) : QQuickItem(parent), m_map(nullptr), m_mapView(nullptr), m_syncTask(nullptr), m_dataPath(""), m_featureServiceUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer/"), m_serviceIds(QStringList() << "0" << "1" << "2") { } GenerateGeodatabase::~GenerateGeodatabase() { } void GenerateGeodatabase::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); // Create a map using a local tile package m_dataPath = QQmlProperty::read(m_mapView, "dataPath").toString(); TileCache* tileCache = new TileCache(m_dataPath + "tpk/SanFrancisco.tpk", this); ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(tileCache, this); Basemap* basemap = new Basemap(tiledLayer, this); m_map = new Map(basemap, this); // Set map to map view m_mapView->setMap(m_map); // add feature layers to map addFeatureLayers(m_featureServiceUrl, m_serviceIds); // create the GeodatabaseSyncTask m_syncTask = new GeodatabaseSyncTask(QUrl(m_featureServiceUrl), this); } void GenerateGeodatabase::addFeatureLayers(QString serviceUrl, QStringList serviceIds) { foreach (auto id, serviceIds) { ServiceFeatureTable* serviceFeatureTable = new ServiceFeatureTable(QUrl(serviceUrl + id)); FeatureLayer* featureLayer = new FeatureLayer(serviceFeatureTable, this); m_map->operationalLayers()->append(featureLayer); } } GenerateGeodatabaseParameters GenerateGeodatabase::getUpdatedParameters(Envelope gdbExtent) { // create the parameters GenerateGeodatabaseParameters params; params.setReturnAttachments(false); params.setOutSpatialReference(SpatialReference::webMercator()); params.setExtent(gdbExtent); // set the layer options for all of the service IDs QList<GenerateLayerOption> layerOptions; foreach (auto id, m_serviceIds) { GenerateLayerOption generateLayerOption(id.toInt()); layerOptions << generateLayerOption; } params.setLayerOptions(layerOptions); return params; } void GenerateGeodatabase::generateGeodatabaseFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2) { // create an envelope from the QML rectangle corners auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1); auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2); auto extent = Envelope(corner1, corner2); auto geodatabaseExtent = GeometryEngine::project(extent, SpatialReference::webMercator()); // get the updated parameters auto params = getUpdatedParameters(geodatabaseExtent); // execute the task and obtain the job auto generateJob = m_syncTask->generateGeodatabase(params, m_dataPath + "Wildfire.geodatabase"); // connect to the job's status changed signal connect(generateJob, &GenerateGeodatabaseJob::jobStatusChanged, [this, generateJob]() { // connect to the job's status changed signal to know once it is done switch (generateJob->jobStatus()) { case JobStatus::Failed: emit updateStatus("Generate failed"); emit hideWindow(5000, false); break; case JobStatus::NotStarted: emit updateStatus("Job not started"); break; case JobStatus::Paused: emit updateStatus("Job paused"); break; case JobStatus::Started: emit updateStatus("In progress..."); break; case JobStatus::Succeeded: emit updateStatus("Complete"); emit hideWindow(1500, true); addOfflineData(generateJob->result()); break; default: break; } }); // start the generate job generateJob->start(); } void GenerateGeodatabase::addOfflineData(Geodatabase* gdb) { // remove the original online feature layers m_map->operationalLayers()->clear(); // load the geodatabase connect(gdb, &Geodatabase::doneLoading, [this, gdb](Error) { // create a feature layer from each feature table, and add to the map foreach (auto featureTable, gdb->geodatabaseFeatureTables()) { FeatureLayer* featureLayer = new FeatureLayer(featureTable, this); m_map->operationalLayers()->append(featureLayer); } // unregister geodatabase since there will be no edits uploaded m_syncTask->unregisterGeodatabase(gdb); }); gdb->load(); } <commit_msg>Update GenerateGeodatabase.cpp<commit_after>// [WriteFile Name=GenerateGeodatabase, Category=Features] // [Legal] // Copyright 2016 Esri. // 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. // [Legal] #include "GenerateGeodatabase.h" #include "Map.h" #include "MapQuickView.h" #include "FeatureLayer.h" #include "Basemap.h" #include "SpatialReference.h" #include "ServiceFeatureTable.h" #include "ArcGISTiledLayer.h" #include "Envelope.h" #include "GenerateGeodatabaseParameters.h" #include "GeodatabaseSyncTask.h" #include "GeometryEngine.h" #include "GenerateLayerOption.h" #include "GeodatabaseFeatureTable.h" #include <QUrl> #include <QQmlProperty> using namespace Esri::ArcGISRuntime; GenerateGeodatabase::GenerateGeodatabase(QQuickItem* parent) : QQuickItem(parent), m_map(nullptr), m_mapView(nullptr), m_syncTask(nullptr), m_dataPath(""), m_featureServiceUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer/"), m_serviceIds(QStringList() << "0" << "1" << "2") { } GenerateGeodatabase::~GenerateGeodatabase() { } void GenerateGeodatabase::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); // Create a map using a local tile package m_dataPath = QQmlProperty::read(m_mapView, "dataPath").toString(); TileCache* tileCache = new TileCache(m_dataPath + "tpk/SanFrancisco.tpk", this); ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(tileCache, this); Basemap* basemap = new Basemap(tiledLayer, this); m_map = new Map(basemap, this); // Set map to map view m_mapView->setMap(m_map); // add feature layers to map addFeatureLayers(m_featureServiceUrl, m_serviceIds); // create the GeodatabaseSyncTask m_syncTask = new GeodatabaseSyncTask(QUrl(m_featureServiceUrl), this); } void GenerateGeodatabase::addFeatureLayers(QString serviceUrl, QStringList serviceIds) { foreach (auto id, serviceIds) { ServiceFeatureTable* serviceFeatureTable = new ServiceFeatureTable(QUrl(serviceUrl + id)); FeatureLayer* featureLayer = new FeatureLayer(serviceFeatureTable, this); m_map->operationalLayers()->append(featureLayer); } } GenerateGeodatabaseParameters GenerateGeodatabase::getUpdatedParameters(Envelope gdbExtent) { // create the parameters GenerateGeodatabaseParameters params; params.setReturnAttachments(false); params.setOutSpatialReference(SpatialReference::webMercator()); params.setExtent(gdbExtent); // set the layer options for all of the service IDs QList<GenerateLayerOption> layerOptions; foreach (auto id, m_serviceIds) { GenerateLayerOption generateLayerOption(id.toInt()); layerOptions << generateLayerOption; } params.setLayerOptions(layerOptions); return params; } void GenerateGeodatabase::generateGeodatabaseFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2) { // create an envelope from the QML rectangle corners auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1); auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2); auto extent = Envelope(corner1, corner2); auto geodatabaseExtent = GeometryEngine::project(extent, SpatialReference::webMercator()); // get the updated parameters auto params = getUpdatedParameters(geodatabaseExtent); // execute the task and obtain the job auto generateJob = m_syncTask->generateGeodatabase(params, m_dataPath + "WildfireCpp.geodatabase"); // connect to the job's status changed signal connect(generateJob, &GenerateGeodatabaseJob::jobStatusChanged, [this, generateJob]() { // connect to the job's status changed signal to know once it is done switch (generateJob->jobStatus()) { case JobStatus::Failed: emit updateStatus("Generate failed"); emit hideWindow(5000, false); break; case JobStatus::NotStarted: emit updateStatus("Job not started"); break; case JobStatus::Paused: emit updateStatus("Job paused"); break; case JobStatus::Started: emit updateStatus("In progress..."); break; case JobStatus::Succeeded: emit updateStatus("Complete"); emit hideWindow(1500, true); addOfflineData(generateJob->result()); break; default: break; } }); // start the generate job generateJob->start(); } void GenerateGeodatabase::addOfflineData(Geodatabase* gdb) { // remove the original online feature layers m_map->operationalLayers()->clear(); // load the geodatabase connect(gdb, &Geodatabase::doneLoading, [this, gdb](Error) { // create a feature layer from each feature table, and add to the map foreach (auto featureTable, gdb->geodatabaseFeatureTables()) { FeatureLayer* featureLayer = new FeatureLayer(featureTable, this); m_map->operationalLayers()->append(featureLayer); } // unregister geodatabase since there will be no edits uploaded m_syncTask->unregisterGeodatabase(gdb); }); gdb->load(); } <|endoftext|>
<commit_before>#include "inverseIndexStorageUnorderedMap.h" InverseIndexStorageUnorderedMap::InverseIndexStorageUnorderedMap(size_t pSizeOfInverseIndex, size_t pMaxBinSize) { mSignatureStorage = new vector__umapVector(pSizeOfInverseIndex); mMaxBinSize = pMaxBinSize; mKeys = new vvsize_t(pSizeOfInverseIndex, vsize_t()); mValues = new vvsize_t(pSizeOfInverseIndex, vsize_t()); } InverseIndexStorageUnorderedMap::~InverseIndexStorageUnorderedMap() { } size_t InverseIndexStorageUnorderedMap::size() { return mSignatureStorage->size(); } vsize_t* InverseIndexStorageUnorderedMap::getElement(size_t pVectorId, size_t pHashValue) { auto iterator = (*mSignatureStorage)[pVectorId].find(pHashValue); if (iterator != (*mSignatureStorage)[pVectorId].end()) { return &(iterator->second); } return new vsize_t(0); // auto itHashValue_InstanceVector = mInverseIndexUmapVector->operator[](j).find((*signature)[j]); // // if for hash function h_i() the given hash values is already stored // if (itHashValue_InstanceVector != mInverseIndexUmapVector->operator[](j).end()) { // // insert the instance id if not too many collisions (maxBinSize) // if (itHashValue_InstanceVector->second.size() } void InverseIndexStorageUnorderedMap::insert(size_t pVectorId, size_t pHashValue, size_t pInstance) { auto itHashValue_InstanceVector = (*mSignatureStorage)[pVectorId].find(pHashValue); // if for hash function h_i() the given hash values is already stored if (itHashValue_InstanceVector != (*mSignatureStorage)[pVectorId].end()) { // insert the instance id if not too many collisions (maxBinSize) if (itHashValue_InstanceVector->second.size() < mMaxBinSize) { // insert only if there wasn't any collisions in the past if (itHashValue_InstanceVector->second.size() > 0) { itHashValue_InstanceVector->second.push_back(pInstance); } } else { // too many collisions: delete stored ids. empty vector is interpreted as an error code // for too many collisions itHashValue_InstanceVector->second.clear(); } } else { // given hash value for the specific hash function was not avaible: insert new hash value vsize_t instanceIdVector; instanceIdVector.push_back(pInstance); (*mSignatureStorage)[pVectorId][pHashValue] = instanceIdVector; } } // void InverseIndexStorageUnorderedMap::create() { // }<commit_msg>Added debugging line<commit_after>#include "inverseIndexStorageUnorderedMap.h" InverseIndexStorageUnorderedMap::InverseIndexStorageUnorderedMap(size_t pSizeOfInverseIndex, size_t pMaxBinSize) { mSignatureStorage = new vector__umapVector(pSizeOfInverseIndex); mMaxBinSize = pMaxBinSize; mKeys = new vvsize_t(pSizeOfInverseIndex, vsize_t()); mValues = new vvsize_t(pSizeOfInverseIndex, vsize_t()); } InverseIndexStorageUnorderedMap::~InverseIndexStorageUnorderedMap() { } size_t InverseIndexStorageUnorderedMap::size() { return mSignatureStorage->size(); } vsize_t* InverseIndexStorageUnorderedMap::getElement(size_t pVectorId, size_t pHashValue) { auto iterator = (*mSignatureStorage)[pVectorId].find(pHashValue); if (iterator != (*mSignatureStorage)[pVectorId].end()) { return &(iterator->second); } return new vsize_t(0); // auto itHashValue_InstanceVector = mInverseIndexUmapVector->operator[](j).find((*signature)[j]); // // if for hash function h_i() the given hash values is already stored // if (itHashValue_InstanceVector != mInverseIndexUmapVector->operator[](j).end()) { // // insert the instance id if not too many collisions (maxBinSize) // if (itHashValue_InstanceVector->second.size() } void InverseIndexStorageUnorderedMap::insert(size_t pVectorId, size_t pHashValue, size_t pInstance) { // std::cout << "insert" << std::endl; auto itHashValue_InstanceVector = (*mSignatureStorage)[pVectorId].find(pHashValue); // if for hash function h_i() the given hash values is already stored if (itHashValue_InstanceVector != (*mSignatureStorage)[pVectorId].end()) { // insert the instance id if not too many collisions (maxBinSize) if (itHashValue_InstanceVector->second.size() < mMaxBinSize) { // insert only if there wasn't any collisions in the past if (itHashValue_InstanceVector->second.size() > 0) { itHashValue_InstanceVector->second.push_back(pInstance); } } else { // too many collisions: delete stored ids. empty vector is interpreted as an error code // for too many collisions itHashValue_InstanceVector->second.clear(); } } else { // given hash value for the specific hash function was not avaible: insert new hash value vsize_t instanceIdVector; instanceIdVector.push_back(pInstance); (*mSignatureStorage)[pVectorId][pHashValue] = instanceIdVector; } } // void InverseIndexStorageUnorderedMap::create() { // }<|endoftext|>
<commit_before>// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "git_command.h" int GitCommand::parseFileSystem(pp::VarDictionary message, std::string name, pp::FileSystem& system) { pp::Var var_filesystem = message.Get(name); if (!var_filesystem.is_resource()) { //TODO(grv): return error code; return 1; } pp::Resource resource_filesystem = var_filesystem.AsResource(); fileSystem = pp::FileSystem(resource_filesystem); return 0; } int GitCommand::parseArgs() { int error = 0; if ((error = parseFileSystem(_args, kFileSystem, fileSystem))) { } if ((error = parseString(_args, kFullPath, fullPath))) { } if ((error = parseString(_args, kUrl, url))) { } return 0; } int GitClone::runCommand() { // mount the folder as a filesystem. ChromefsInit(); git_threads_init(); std::string message = "clone successful"; if (!url.length()) { git_repository_open(&repo, "/chromefs"); message = "repository load successful"; } else { git_clone(&repo, url.c_str(), "/chromefs", NULL); } const git_error *a = giterr_last(); if (a != NULL) { printf("giterror: %s\n", a->message); } pp::VarDictionary arg; arg.Set(kMessage, message); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); return 0; } void GitClone::ChromefsInit() { int32_t r = (int32_t) fileSystem.pp_resource(); char fs_resource[100] = "filesystem_resource="; sprintf(&fs_resource[20], "%d", r); mount(fullPath.c_str(), /* source */ "/chromefs", /* target */ "html5fs", /* filesystemtype */ 0, /* mountflags */ fs_resource); /* data */ } int GitCommit::runCommand() { //TODO(grv): implement. char message[100]; sprintf(message, "%s", subject.c_str()); _gitSalt->PostMessage(pp::Var(message)); printf("GitCommit: to be implemented"); return 0; } int GitCurrentBranch::parseArgs() { return 0; } int GitCurrentBranch::runCommand() { git_reference* ref = NULL; char *branch = NULL; int r= git_repository_head(&ref, repo); if (r == 0) { git_branch_name((const char**)&branch, ref); } const git_error *a = giterr_last(); if (a != NULL) { printf("giterror: %s\n", a->message); } pp::VarDictionary arg; arg.Set(kBranch, branch); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); git_reference_free(ref); return 0; } int GitGetBranches::parseArgs() { int error = 0; if ((error = parseInt(_args, kFlags, &flags))) { } return 0; } int GitGetBranches::runCommand() { git_branch_iterator* iter = NULL; git_branch_t type = (git_branch_t) flags; int r = git_branch_iterator_new(&iter, repo, type); pp::VarDictionary arg; pp::VarArray branches; int index = 0; char* branch = NULL; if (r == 0) { while (r == 0) { git_reference* ref; r = git_branch_next(&ref, &type, iter); if (r == 0) { git_branch_name((const char**)&branch, ref); branches.Set(index, branch); index++; git_reference_free(ref); } } } arg.Set(kBranches, branches); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); git_branch_iterator_free(iter); return 0; } int StatusCb(const char* path, unsigned int status, void* payload) { pp::VarDictionary* statuses = (pp::VarDictionary*) payload; statuses->Set(path, (int)status); return 0; } int GitStatus::runCommand() { git_status_cb cb = StatusCb; pp::VarDictionary statuses; int r = git_status_foreach(repo, cb, &statuses); const git_error *a = giterr_last(); if (a != NULL) { printf("giterror: %s\n", a->message); } pp::VarDictionary arg; arg.Set(kStatuses, statuses); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); return 0; } <commit_msg>Fix a warning.<commit_after>// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "git_command.h" int GitCommand::parseFileSystem(pp::VarDictionary message, std::string name, pp::FileSystem& system) { pp::Var var_filesystem = message.Get(name); if (!var_filesystem.is_resource()) { //TODO(grv): return error code; return 1; } pp::Resource resource_filesystem = var_filesystem.AsResource(); fileSystem = pp::FileSystem(resource_filesystem); return 0; } int GitCommand::parseArgs() { int error = 0; if ((error = parseFileSystem(_args, kFileSystem, fileSystem))) { } if ((error = parseString(_args, kFullPath, fullPath))) { } if ((error = parseString(_args, kUrl, url))) { } return 0; } int GitClone::runCommand() { // mount the folder as a filesystem. ChromefsInit(); git_threads_init(); std::string message = "clone successful"; if (!url.length()) { git_repository_open(&repo, "/chromefs"); message = "repository load successful"; } else { git_clone(&repo, url.c_str(), "/chromefs", NULL); } const git_error *a = giterr_last(); if (a != NULL) { printf("giterror: %s\n", a->message); } pp::VarDictionary arg; arg.Set(kMessage, message); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); return 0; } void GitClone::ChromefsInit() { int32_t r = (int32_t) fileSystem.pp_resource(); char fs_resource[100] = "filesystem_resource="; sprintf(&fs_resource[20], "%d", r); mount(fullPath.c_str(), /* source */ "/chromefs", /* target */ "html5fs", /* filesystemtype */ 0, /* mountflags */ fs_resource); /* data */ } int GitCommit::runCommand() { //TODO(grv): implement. char message[100]; sprintf(message, "%s", subject.c_str()); _gitSalt->PostMessage(pp::Var(message)); printf("GitCommit: to be implemented"); return 0; } int GitCurrentBranch::parseArgs() { return 0; } int GitCurrentBranch::runCommand() { git_reference* ref = NULL; char *branch = NULL; int r= git_repository_head(&ref, repo); if (r == 0) { git_branch_name((const char**)&branch, ref); } const git_error *a = giterr_last(); if (a != NULL) { printf("giterror: %s\n", a->message); } pp::VarDictionary arg; arg.Set(kBranch, branch); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); git_reference_free(ref); return 0; } int GitGetBranches::parseArgs() { int error = 0; if ((error = parseInt(_args, kFlags, &flags))) { } return 0; } int GitGetBranches::runCommand() { git_branch_iterator* iter = NULL; git_branch_t type = (git_branch_t) flags; int r = git_branch_iterator_new(&iter, repo, type); pp::VarDictionary arg; pp::VarArray branches; int index = 0; char* branch = NULL; if (r == 0) { while (r == 0) { git_reference* ref; r = git_branch_next(&ref, &type, iter); if (r == 0) { git_branch_name((const char**)&branch, ref); branches.Set(index, branch); index++; git_reference_free(ref); } } } arg.Set(kBranches, branches); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); git_branch_iterator_free(iter); return 0; } int StatusCb(const char* path, unsigned int status, void* payload) { pp::VarDictionary* statuses = (pp::VarDictionary*) payload; statuses->Set(path, (int)status); return 0; } int GitStatus::runCommand() { git_status_cb cb = StatusCb; pp::VarDictionary statuses; git_status_foreach(repo, cb, &statuses); const git_error *a = giterr_last(); if (a != NULL) { printf("giterror: %s\n", a->message); } pp::VarDictionary arg; arg.Set(kStatuses, statuses); pp::VarDictionary response; response.Set(kRegarding, subject); response.Set(kArg, arg); response.Set(kName, kResult); _gitSalt->PostMessage(response); return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_INV_CLOGLOG_HPP #define STAN_MATH_PRIM_FUN_INV_CLOGLOG_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/exp.hpp> #include <cmath> namespace stan { namespace math { /** * The inverse complementary log-log function. * * The function is defined by * * <code>inv_cloglog(x) = 1 - exp(-exp(x))</code>. * * This function can be used to implement the inverse link * function for complementary-log-log regression. * * \f[ \mbox{inv\_cloglog}(y) = \begin{cases} \mbox{cloglog}^{-1}(y) & \mbox{if } -\infty\leq y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{inv\_cloglog}(y)}{\partial y} = \begin{cases} \frac{\partial\, \mbox{cloglog}^{-1}(y)}{\partial y} & \mbox{if } -\infty\leq y\leq \infty \\[6pt] \textrm{NaN} & \mbox{if } y = \textrm{NaN} \end{cases} \f] \f[ \mbox{cloglog}^{-1}(y) = 1 - \exp \left( - \exp(y) \right) \f] \f[ \frac{\partial \, \mbox{cloglog}^{-1}(y)}{\partial y} = \exp(y-\exp(y)) \f] * * @param x Argument. * @return Inverse complementary log-log of the argument. */ inline double inv_cloglog(double x) { using std::exp; return 1 - exp(-exp(x)); } /** * Structure to wrap inv_cloglog() so that it can be vectorized. * * @tparam T type of variable * @param x variable * @return 1 - exp(-exp(x)). */ struct inv_cloglog_fun { template <typename T> static inline T fun(const T& x) { return inv_cloglog(x); } }; /** * Vectorized version of inv_cloglog(). * * @tparam Container type of container * @param x container * @return 1 - exp(-exp()) applied to each value in x. */ template <typename Container, require_not_container_st<std::is_arithmetic, Container>* = nullptr> inline auto inv_cloglog(const Container& x) { return apply_scalar_unary<inv_cloglog_fun, Container>::apply(x); } /** * Version of inv_cloglog() that accepts std::vectors, Eigen Matrix/Array * objects or expressions, and containers of these. * * @tparam Container Type of x * @param x Container * @return 1 - exp(-exp()) applied to each value in x. */ template <typename Container, require_container_st<std::is_arithmetic, Container>* = nullptr> inline auto inv_cloglog(const Container& x) { return apply_vector_unary<Container>::apply( x, [](const auto& v) { return 1 - (-v.array().exp()).exp(); }); } } // namespace math } // namespace stan #endif <commit_msg>Fixed merge conflicts<commit_after>#ifndef STAN_MATH_PRIM_FUN_INV_CLOGLOG_HPP #define STAN_MATH_PRIM_FUN_INV_CLOGLOG_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/exp.hpp> #include <cmath> namespace stan { namespace math { /** * The inverse complementary log-log function. * * The function is defined by * * <code>inv_cloglog(x) = 1 - exp(-exp(x))</code>. * * This function can be used to implement the inverse link * function for complementary-log-log regression. * * \f[ \mbox{inv\_cloglog}(y) = \begin{cases} \mbox{cloglog}^{-1}(y) & \mbox{if } -\infty\leq y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{inv\_cloglog}(y)}{\partial y} = \begin{cases} \frac{\partial\, \mbox{cloglog}^{-1}(y)}{\partial y} & \mbox{if } -\infty\leq y\leq \infty \\[6pt] \textrm{NaN} & \mbox{if } y = \textrm{NaN} \end{cases} \f] \f[ \mbox{cloglog}^{-1}(y) = 1 - \exp \left( - \exp(y) \right) \f] \f[ \frac{\partial \, \mbox{cloglog}^{-1}(y)}{\partial y} = \exp(y-\exp(y)) \f] * * @param x Argument. * @return Inverse complementary log-log of the argument. */ inline double inv_cloglog(double x) { using std::exp; return 1 - exp(-exp(x)); } /** * Structure to wrap inv_cloglog() so that it can be vectorized. * * @tparam T type of variable * @param x variable * @return 1 - exp(-exp(x)). */ struct inv_cloglog_fun { template <typename T> static inline T fun(const T& x) { return inv_cloglog(x); } }; /** * Vectorized version of inv_cloglog(). * * @tparam Container type of container * @param x container * @return 1 - exp(-exp()) applied to each value in x. */ template <typename Container, require_not_container_st<std::is_arithmetic, Container>* = nullptr> inline auto inv_cloglog(const Container& x) { return apply_scalar_unary<inv_cloglog_fun, Container>::apply(x); } /** * Version of inv_cloglog() that accepts std::vectors, Eigen Matrix/Array * objects or expressions, and containers of these. * * @tparam Container Type of x * @param x Container * @return 1 - exp(-exp()) applied to each value in x. */ template <typename Container, require_container_st<std::is_arithmetic, Container>* = nullptr> inline auto inv_cloglog(const Container& x) { return apply_vector_unary<Container>::apply( x, [](const auto& v) { return 1 - (-v.array().exp()).exp(); }); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include <iostream> #include <string> using namespace std::string_literals; #include "acmacs-base/argc-argv.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/quicklook.hh" // #include "acmacs-base/enumerate.hh" #include "acmacs-chart/ace.hh" #include "acmacs-map-draw/draw.hh" #include "settings.hh" #include "mod-applicator.hh" // ---------------------------------------------------------------------- constexpr const char* sUsage = " [options] <chart.ace> [<map.pdf>]\n"; int main(int argc, char* const argv[]) { try { argc_argv args(argc, argv, { {"-h", false}, {"--help", false}, {"-s", ""}, {"--settings", ""}, {"--projection", 0L}, {"--seqdb", ""}, {"--hidb-dir", ""}, {"--locdb", ""}, {"-v", false}, {"--verbose", false}, }); if (args["-h"] || args["--help"] || args.number_of_arguments() < 1 || args.number_of_arguments() > 2) { throw std::runtime_error("Usage: "s + args.program() + sUsage + args.usage_options()); } const bool verbose = args["-v"] || args["--verbose"]; auto settings = default_settings(); std::unique_ptr<Chart> chart{import_chart(args[0], verbose ? report_time::Yes : report_time::No)}; ChartDraw chart_draw(*chart, args["--projection"]); chart_draw.prepare(); // auto mods = rjson::parse_string(R"(["all_grey", {"N": "clades", "seqdb_file": "/Users/eu/AD/data/seqdb.json.xz", "report": false}])"); // auto mods = rjson::parse_string(R"([{"N": "clades", "seqdb_file": "/Users/eu/AD/data/seqdb.json.xz", "report": false}])"); auto mods = rjson::parse_string(R"(["all_red"])"); apply_mods(chart_draw, mods, settings); chart_draw.calculate_viewport(); const auto temp_file = acmacs_base::TempFile(".pdf"); chart_draw.draw(temp_file, 800, report_time::Yes); acmacs::quicklook(temp_file, 2); return 0; } catch (std::exception& err) { std::cerr << "ERROR: " << err.what() << '\n'; return 1; } } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>map-draw --init-settings<commit_after>#include <iostream> #include <string> using namespace std::string_literals; #include "acmacs-base/argc-argv.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/quicklook.hh" // #include "acmacs-base/enumerate.hh" #include "acmacs-chart/ace.hh" #include "acmacs-map-draw/draw.hh" #include "settings.hh" #include "mod-applicator.hh" // ---------------------------------------------------------------------- constexpr const char* sUsage = " [options] <chart.ace> [<map.pdf>]\n"; int main(int argc, char* const argv[]) { try { argc_argv args(argc, argv, { {"-h", false}, {"--help", false}, {"-s", ""}, {"--settings", ""}, {"--init-settings", ""}, {"--projection", 0L}, {"--seqdb", ""}, {"--hidb-dir", ""}, {"--locdb", ""}, {"-v", false}, {"--verbose", false}, }); if (args["-h"] || args["--help"] || args.number_of_arguments() < 1 || args.number_of_arguments() > 2) { throw std::runtime_error("Usage: "s + args.program() + sUsage + args.usage_options()); } const bool verbose = args["-v"] || args["--verbose"]; auto settings = default_settings(); std::unique_ptr<Chart> chart{import_chart(args[0], verbose ? report_time::Yes : report_time::No)}; ChartDraw chart_draw(*chart, args["--projection"]); chart_draw.prepare(); // auto mods = rjson::parse_string(R"(["all_grey", {"N": "clades", "seqdb_file": "/Users/eu/AD/data/seqdb.json.xz", "report": false}])"); // auto mods = rjson::parse_string(R"([{"N": "clades", "seqdb_file": "/Users/eu/AD/data/seqdb.json.xz", "report": false}])"); auto mods = rjson::parse_string(R"(["all_red"])"); apply_mods(chart_draw, mods, settings); chart_draw.calculate_viewport(); const auto temp_file = acmacs_base::TempFile(".pdf"); chart_draw.draw(temp_file, 800, report_time::Yes); if (const std::string save_settings = args["--init-settings"]; !save_settings.empty()) acmacs_base::write_file(save_settings, settings.to_json_pp()); acmacs::quicklook(temp_file, 2); return 0; } catch (std::exception& err) { std::cerr << "ERROR: " << err.what() << '\n'; return 1; } } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#ifndef ALEPH_GEOMETRY_COVER_TREE_HH__ #define ALEPH_GEOMETRY_COVER_TREE_HH__ #include <iterator> #include <limits> #include <memory> #include <ostream> #include <queue> #include <stdexcept> #include <vector> // FIXME: remove after debugging #include <iostream> #include <cassert> #include <cmath> namespace aleph { namespace geometry { /** @class CoverTree @brief Generic cover tree data structure This class models a cover tree data structure, as described in the paper "Cover trees for nearest neighbor" by Beygelzimer et al.; an implementation is given at: http://hunch.net/~jl/projects/cover_tree/cover_tree.html This implementation attempts to be as generic as possible. It uses the simplified description of the cover tree, as given by Izbicki, Shelton in "Faster Cover Trees". */ template <class Point, class Metric> class CoverTree { public: /** Covering constant of the cover tree. It might make sense to change this later on in order to improve performance. Some papers set the constant to `1.3`. */ constexpr static const double coveringConstant = 2.0; class Node { public: /** Creates a new node that stores a point */ Node( const Point& point, unsigned level ) : _point( point ) , _level( level ) { assert( level >= 1 ); } /** Calculates current covering distance of the node */ double coveringDistance() const noexcept { return std::pow( coveringConstant, static_cast<double>( _level ) ); } void addChild( const Point& p ) { _children.push_back( std::unique_ptr<Node>( new Node( p, _level - 1 ) ) ); } void insert( const Point& p ) { auto d = Metric()( _point, p ); std::cerr << __PRETTY_FUNCTION__ << ": Distance from point to root = " << d << "\n"; if( d > this->coveringDistance() ) { std::cerr << __PRETTY_FUNCTION__ << ": Distance is bigger than covering distance; need to raise level of tree\n"; throw std::runtime_error( "Not yet implemented" ); } return insert_( p ); } /** Auxiliary function for performing the recursive insertion of a new node into the tree. */ void insert_( const Point& p ) { for( auto&& child : _children ) { auto d = Metric()( child->_point, p ); if( d <= child->coveringDistance() ) { std::cerr << __PRETTY_FUNCTION__ << ": Recursive enumeration of the tree\n"; // We found a node in which the new point can be inserted // *without* violating the covering invariant. child->insert_( p ); return; } } // Add the new point as a child of the current root node. This // might require updating levels. if( _children.empty() ) _level += 1; this->addChild( p ); } Point _point; //< The point stored in the node unsigned _level; //< The level of the node (>= 1) /** All children of the node. Their order depends on the insertion order into the data set. */ std::vector< std::unique_ptr<Node> > _children; }; /** Inserts a new point into the cover tree. If the tree is empty, the new point will become the root of the tree. Else, it shall be inserted according to the covering invariant. */ void insert( const Point& p ) { if( !_root ) _root = std::unique_ptr<Node>( new Node(p,1) ); else _root->insert( p ); } // Pretty-printing function for the tree; this is only meant for // debugging purposes and could conceivably be implemented using // `std::ostream`. void print( std::ostream& o ) { std::queue<const Node*> nodes; nodes.push( _root.get() ); while( !nodes.empty() ) { { auto&& node = nodes.front(); o << node->_level << ": " << node->_point << "\n"; for( auto&& child : node->_children ) nodes.push( child.get() ); } nodes.pop(); } } private: /** Updates the levels of a cover tree. This function ensures that all information is being represented correctly. It is not mentioned in the original paper but appears to be necessary. */ void updateLevels() { // Forward pass ---------------------------------------------------- // // Determine depth of the tree. This is required in order to assign // levels correctly later on. unsigned depth = 1; std::queue<const Node*> nodes; nodes.push( _root.get() ); while( !nodes.empty() ) { auto n = nodes.size(); for( decltype(n) i = 0; i < n; i++ ) { auto node = nodes.front(); nodes.pop(); for( auto&& child : node->_children ) nodes.push( child.get() ); } ++level; } std::cerr << __PRETTY_FUNCTION__ << ": Maximum depth = " << level << "\n"; } /** Auxiliary function for calculating the distance between a point and a given set of nodes. */ double distanceToSet( const Point& p, const std::vector<Node*>& Q ) { Metric metric; double d = std::numeric_limits<double>::max(); for( auto&& q : Q ) d = std::min( d, double( metric(p, q->_point) ) ); return d; } bool insert( const Point& p, const std::vector<Node*>& Qi, unsigned i ) { std::cerr << "Inserting point " << p << " at level " << i << "\n"; Metric metric; // Contains all nodes that satisfy the distance criterion for this // level. std::vector<Node*> Qj; double d = std::numeric_limits<double>::max(); for( auto&& Q : Qi ) { for( auto&& child : Q->_children ) { double distance = double( metric( p, child->_point ) ); if( unsigned( std::log2( distance ) ) <= i ) { d = std::min( d, distance ); Qj.push_back( child.get() ); } } } d = std::log2( d ); if( d > i ) return false; else { auto parentFound = insert( p, Qj, i-1 ); auto distance = unsigned( std::log2( distanceToSet(p, Qi) ) ); if( !parentFound && distance < i ) return true; else return false; } } /** Root pointer of the tree */ std::unique_ptr<Node> _root; }; } // namespace geometry } // namespace aleph #endif <commit_msg>Updating levels after node insertion<commit_after>#ifndef ALEPH_GEOMETRY_COVER_TREE_HH__ #define ALEPH_GEOMETRY_COVER_TREE_HH__ #include <iterator> #include <limits> #include <memory> #include <ostream> #include <queue> #include <stdexcept> #include <vector> // FIXME: remove after debugging #include <iostream> #include <cassert> #include <cmath> namespace aleph { namespace geometry { /** @class CoverTree @brief Generic cover tree data structure This class models a cover tree data structure, as described in the paper "Cover trees for nearest neighbor" by Beygelzimer et al.; an implementation is given at: http://hunch.net/~jl/projects/cover_tree/cover_tree.html This implementation attempts to be as generic as possible. It uses the simplified description of the cover tree, as given by Izbicki, Shelton in "Faster Cover Trees". */ template <class Point, class Metric> class CoverTree { public: /** Covering constant of the cover tree. It might make sense to change this later on in order to improve performance. Some papers set the constant to `1.3`. */ constexpr static const double coveringConstant = 2.0; class Node { public: /** Creates a new node that stores a point */ Node( const Point& point, unsigned level ) : _point( point ) , _level( level ) { assert( _level >= 1 ); } /** Calculates current covering distance of the node */ double coveringDistance() const noexcept { return std::pow( coveringConstant, static_cast<double>( _level ) ); } void addChild( const Point& p ) { _children.push_back( std::unique_ptr<Node>( new Node( p, _level - 1 ) ) ); } void insert( const Point& p ) { auto d = Metric()( _point, p ); std::cerr << __PRETTY_FUNCTION__ << ": Distance from point to root = " << d << "\n"; if( d > this->coveringDistance() ) { std::cerr << __PRETTY_FUNCTION__ << ": Distance is bigger than covering distance; need to raise level of tree\n"; throw std::runtime_error( "Not yet implemented" ); } return insert_( p ); } /** Auxiliary function for performing the recursive insertion of a new node into the tree. */ void insert_( const Point& p ) { for( auto&& child : _children ) { auto d = Metric()( child->_point, p ); if( d <= child->coveringDistance() ) { std::cerr << __PRETTY_FUNCTION__ << ": Recursive enumeration of the tree\n"; // We found a node in which the new point can be inserted // *without* violating the covering invariant. child->insert_( p ); return; } } // Add the new point as a child of the current root node. This // might require updating levels. if( _children.empty() ) _level += 1; this->addChild( p ); } Point _point; //< The point stored in the node unsigned _level; //< The level of the node (>= 1) /** All children of the node. Their order depends on the insertion order into the data set. */ std::vector< std::unique_ptr<Node> > _children; }; /** Inserts a new point into the cover tree. If the tree is empty, the new point will become the root of the tree. Else, it shall be inserted according to the covering invariant. */ void insert( const Point& p ) { if( !_root ) _root = std::unique_ptr<Node>( new Node(p,1) ); else _root->insert( p ); this->updateLevels(); } // Pretty-printing function for the tree; this is only meant for // debugging purposes and could conceivably be implemented using // `std::ostream`. void print( std::ostream& o ) { std::queue<const Node*> nodes; nodes.push( _root.get() ); while( !nodes.empty() ) { { auto&& node = nodes.front(); o << node->_level << ": " << node->_point << "\n"; for( auto&& child : node->_children ) nodes.push( child.get() ); } nodes.pop(); } } private: /** Updates the levels of a cover tree. This function ensures that all information is being represented correctly. It is not mentioned in the original paper but appears to be necessary. */ void updateLevels() { // Forward pass ---------------------------------------------------- // // Determine depth of the tree. This is required in order to assign // levels correctly later on. unsigned depth = 0; std::queue<const Node*> nodes; nodes.push( _root.get() ); while( !nodes.empty() ) { auto n = nodes.size(); for( decltype(n) i = 0; i < n; i++ ) { auto node = nodes.front(); nodes.pop(); for( auto&& child : node->_children ) nodes.push( child.get() ); } ++depth; } assert( nodes.empty() ); // Backward pass --------------------------------------------------- // // Set the level of the root node and update child levels. Note that // all nodes will be traversed because this function is dumb. _root->_level = depth; nodes.push( _root.get() ); while( !nodes.empty() ) { { auto&& parent = nodes.front(); for( auto&& child : parent->_children ) { assert( parent->_level >= 1 ); child->_level = parent->_level - 1; nodes.push( child.get() ); } } nodes.pop(); } } /** Auxiliary function for calculating the distance between a point and a given set of nodes. */ double distanceToSet( const Point& p, const std::vector<Node*>& Q ) { Metric metric; double d = std::numeric_limits<double>::max(); for( auto&& q : Q ) d = std::min( d, double( metric(p, q->_point) ) ); return d; } bool insert( const Point& p, const std::vector<Node*>& Qi, unsigned i ) { std::cerr << "Inserting point " << p << " at level " << i << "\n"; Metric metric; // Contains all nodes that satisfy the distance criterion for this // level. std::vector<Node*> Qj; double d = std::numeric_limits<double>::max(); for( auto&& Q : Qi ) { for( auto&& child : Q->_children ) { double distance = double( metric( p, child->_point ) ); if( unsigned( std::log2( distance ) ) <= i ) { d = std::min( d, distance ); Qj.push_back( child.get() ); } } } d = std::log2( d ); if( d > i ) return false; else { auto parentFound = insert( p, Qj, i-1 ); auto distance = unsigned( std::log2( distanceToSet(p, Qi) ) ); if( !parentFound && distance < i ) return true; else return false; } } /** Root pointer of the tree */ std::unique_ptr<Node> _root; }; } // namespace geometry } // namespace aleph #endif <|endoftext|>
<commit_before> #include "config.h" #include "include/types.h" //#define MDS_CACHE_SIZE 4*10000 -> <20mb //#define MDS_CACHE_SIZE 80000 62mb #define AVG_PER_INODE_SIZE 450 #define MDS_CACHE_MB_TO_INODES(x) ((x)*1000000/AVG_PER_INODE_SIZE) //#define MDS_CACHE_SIZE MDS_CACHE_MB_TO_INODES( 50 ) //#define MDS_CACHE_SIZE 1500000 #define MDS_CACHE_SIZE 150000 // hack hack hack ugly FIXME #include "common/Mutex.h" long buffer_total_alloc = 0; Mutex bufferlock; FileLayout g_OSD_FileLayout( 1<<20, 1, 1<<20, 2 ); // stripe over 1M objects, 2x replication //FileLayout g_OSD_FileLayout( 1<<17, 4, 1<<20 ); // 128k stripes over sets of 4 // ?? FileLayout g_OSD_MDDirLayout( 1<<14, 1<<2, 1<<19, 3 ); // stripe mds log over 128 byte bits (see mds_log_pad_entry below to match!) FileLayout g_OSD_MDLogLayout( 1<<7, 32, 1<<20, 3 ); // new (good?) way //FileLayout g_OSD_MDLogLayout( 57, 32, 1<<20 ); // pathological case to test striping buffer mapping //FileLayout g_OSD_MDLogLayout( 1<<20, 1, 1<<20 ); // old way md_config_t g_conf = { num_mds: 1, num_osd: 4, num_client: 1, mkfs: false, // profiling and debugging log: true, log_interval: 1, log_name: (char*)0, log_messages: true, log_pins: true, fake_clock: false, fakemessenger_serialize: true, fake_osdmap_expand: 0, fake_osd_sync: false, debug: 1, debug_mds_balancer: 1, debug_mds_log: 1, debug_buffer: 0, debug_filer: 0, debug_client: 0, debug_osd: 0, debug_ebofs: 1, debug_bdev: 1, // block device // --- client --- client_cache_size: 300, client_cache_mid: .5, client_cache_stat_ttl: 10, // seconds until cached stat results become invalid client_use_random_mds: false, client_sync_writes: 0, client_bcache: 1, client_bcache_alloc_minsize: 1<<10, // 1KB client_bcache_alloc_maxsize: 1<<18, // 256KB client_bcache_ttl: 30, // seconds until dirty buffers are written to disk client_bcache_size: 2<<30, // 2GB //client_bcache_size: 5<<20, // 5MB client_bcache_lowater: 60, // % of size client_bcache_hiwater: 80, // % of size client_bcache_align: 1<<10, // 1KB splice alignment client_trace: 0, fuse_direct_io: 0, // --- mds --- mds_cache_size: MDS_CACHE_SIZE, mds_cache_mid: .7, mds_log: true, mds_log_max_len: MDS_CACHE_SIZE / 3, mds_log_max_trimming: 256, mds_log_read_inc: 1024,//1<<20, mds_log_pad_entry: 64, mds_log_before_reply: true, mds_log_flush_on_shutdown: true, mds_bal_replicate_threshold: 8000, mds_bal_unreplicate_threshold: 1000, mds_bal_interval: 30, // seconds mds_bal_idle_threshold: .1, mds_bal_max: -1, mds_bal_max_until: -1, mds_commit_on_shutdown: true, mds_verify_export_dirauth: true, // --- osd --- osd_pg_bits: 8, osd_max_rep: 4, osd_fsync: true, osd_writesync: false, osd_maxthreads: 1, // 0 == no threading! osd_mkfs: false, osd_fakestore_syncthreads: 4, // --- ebofs --- ebofs: 0, ebofs_commit_interval: 2, // seconds. 0 = no timeout (for debugging/tracing) ebofs_oc_size: 1000, ebofs_cc_size: 1000, ebofs_bc_size: (15 *256), // 4k blocks, or *256 for MB ebofs_bc_max_dirty: (10 *256), // before write() will block ebofs_abp_zero: false, ebofs_abp_max_alloc: 4096*32, // --- block device --- bdev_el_fw_max_ms: 1000, // restart elevator at least once every 1000 ms bdev_el_bw_max_ms: 300, // restart elevator at least once every 1000 ms bdev_el_bidir: true, // bidirectional elevator? // --- fakeclient (mds regression testing) (ancient history) --- num_fakeclient: 100, fakeclient_requests: 100, fakeclient_deterministic: false, fakeclient_op_statfs: false, // loosely based on Roselli workload paper numbers fakeclient_op_stat: 610, fakeclient_op_lstat: false, fakeclient_op_utime: 0, fakeclient_op_chmod: 1, fakeclient_op_chown: 1, fakeclient_op_readdir: 2, fakeclient_op_mknod: 30, fakeclient_op_link: false, fakeclient_op_unlink: 20, fakeclient_op_rename: 0,//40, fakeclient_op_mkdir: 10, fakeclient_op_rmdir: 20, fakeclient_op_symlink: 20, fakeclient_op_openrd: 200, fakeclient_op_openwr: 0, fakeclient_op_openwrc: 0, fakeclient_op_read: false, // osd! fakeclient_op_write: false, // osd! fakeclient_op_truncate: false, fakeclient_op_fsync: false, fakeclient_op_close: 200 }; #include <stdlib.h> #include <string.h> #include <iostream> using namespace std; void argv_to_vec(int argc, char **argv, vector<char*>& args) { for (int i=1; i<argc; i++) args.push_back(argv[i]); } void vec_to_argv(vector<char*>& args, int& argc, char **&argv) { argv = (char**)malloc(sizeof(char*) * argc); argc = 1; argv[0] = "asdf"; for (unsigned i=0; i<args.size(); i++) argv[argc++] = args[i]; } void parse_config_options(vector<char*>& args) { vector<char*> nargs; for (unsigned i=0; i<args.size(); i++) { if (strcmp(args[i], "--nummds") == 0) g_conf.num_mds = atoi(args[++i]); else if (strcmp(args[i], "--numclient") == 0) g_conf.num_client = atoi(args[++i]); else if (strcmp(args[i], "--numosd") == 0) g_conf.num_osd = atoi(args[++i]); else if (strcmp(args[i], "--mkfs") == 0) g_conf.osd_mkfs = g_conf.mkfs = 1; //atoi(args[++i]); else if (strcmp(args[i], "--fake_osdmap_expand") == 0) g_conf.fake_osdmap_expand = atoi(args[++i]); else if (strcmp(args[i], "--fake_osd_sync") == 0) g_conf.fake_osd_sync = atoi(args[++i]); else if (strcmp(args[i], "--debug") == 0) g_conf.debug = atoi(args[++i]); else if (strcmp(args[i], "--debug_mds_balancer") == 0) g_conf.debug_mds_balancer = atoi(args[++i]); else if (strcmp(args[i], "--debug_mds_log") == 0) g_conf.debug_mds_log = atoi(args[++i]); else if (strcmp(args[i], "--debug_buffer") == 0) g_conf.debug_buffer = atoi(args[++i]); else if (strcmp(args[i], "--debug_filer") == 0) g_conf.debug_filer = atoi(args[++i]); else if (strcmp(args[i], "--debug_client") == 0) g_conf.debug_client = atoi(args[++i]); else if (strcmp(args[i], "--debug_osd") == 0) g_conf.debug_osd = atoi(args[++i]); else if (strcmp(args[i], "--debug_ebofs") == 0) g_conf.debug_ebofs = atoi(args[++i]); else if (strcmp(args[i], "--debug_bdev") == 0) g_conf.debug_bdev = atoi(args[++i]); else if (strcmp(args[i], "--log") == 0) g_conf.log = atoi(args[++i]); else if (strcmp(args[i], "--log_name") == 0) g_conf.log_name = args[++i]; else if (strcmp(args[i], "--fakemessenger_serialize") == 0) g_conf.fakemessenger_serialize = atoi(args[++i]); else if (strcmp(args[i], "--mds_cache_size") == 0) g_conf.mds_cache_size = atoi(args[++i]); else if (strcmp(args[i], "--mds_log") == 0) g_conf.mds_log = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_before_reply") == 0) g_conf.mds_log_before_reply = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_max_len") == 0) g_conf.mds_log_max_len = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_read_inc") == 0) g_conf.mds_log_read_inc = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_max_trimming") == 0) g_conf.mds_log_max_trimming = atoi(args[++i]); else if (strcmp(args[i], "--mds_commit_on_shutdown") == 0) g_conf.mds_commit_on_shutdown = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_flush_on_shutdown") == 0) g_conf.mds_log_flush_on_shutdown = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_interval") == 0) g_conf.mds_bal_interval = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_rep") == 0) g_conf.mds_bal_replicate_threshold = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_unrep") == 0) g_conf.mds_bal_unreplicate_threshold = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_max") == 0) g_conf.mds_bal_max = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_max_until") == 0) g_conf.mds_bal_max_until = atoi(args[++i]); else if (strcmp(args[i], "--client_cache_size") == 0) g_conf.client_cache_size = atoi(args[++i]); else if (strcmp(args[i], "--client_cache_stat_ttl") == 0) g_conf.client_cache_stat_ttl = atoi(args[++i]); else if (strcmp(args[i], "--client_trace") == 0) g_conf.client_trace = atoi(args[++i]); else if (strcmp(args[i], "--fuse_direct_io") == 0) g_conf.fuse_direct_io = atoi(args[++i]); else if (strcmp(args[i], "--client_sync_writes") == 0) g_conf.client_sync_writes = atoi(args[++i]); else if (strcmp(args[i], "--client_bcache") == 0) g_conf.client_bcache = atoi(args[++i]); else if (strcmp(args[i], "--client_bcache_ttl") == 0) g_conf.client_bcache_ttl = atoi(args[++i]); else if (strcmp(args[i], "--ebofs") == 0) g_conf.ebofs = 1; else if (strcmp(args[i], "--fakestore") == 0) g_conf.ebofs = 0; else if (strcmp(args[i], "--osd_mkfs") == 0) g_conf.osd_mkfs = atoi(args[++i]); else if (strcmp(args[i], "--osd_pg_bits") == 0) g_conf.osd_pg_bits = atoi(args[++i]); else if (strcmp(args[i], "--osd_max_rep") == 0) g_conf.osd_max_rep = atoi(args[++i]); else if (strcmp(args[i], "--osd_fsync") == 0) g_conf.osd_fsync = atoi(args[++i]); else if (strcmp(args[i], "--osd_writesync") == 0) g_conf.osd_writesync = atoi(args[++i]); else if (strcmp(args[i], "--osd_maxthreads") == 0) g_conf.osd_maxthreads = atoi(args[++i]); else { nargs.push_back(args[i]); } } args = nargs; } <commit_msg>*** empty log message ***<commit_after> #include "config.h" #include "include/types.h" //#define MDS_CACHE_SIZE 4*10000 -> <20mb //#define MDS_CACHE_SIZE 80000 62mb #define AVG_PER_INODE_SIZE 450 #define MDS_CACHE_MB_TO_INODES(x) ((x)*1000000/AVG_PER_INODE_SIZE) //#define MDS_CACHE_SIZE MDS_CACHE_MB_TO_INODES( 50 ) //#define MDS_CACHE_SIZE 1500000 #define MDS_CACHE_SIZE 150000 // hack hack hack ugly FIXME #include "common/Mutex.h" long buffer_total_alloc = 0; Mutex bufferlock; FileLayout g_OSD_FileLayout( 1<<20, 1, 1<<20, 2 ); // stripe over 1M objects, 2x replication //FileLayout g_OSD_FileLayout( 1<<17, 4, 1<<20 ); // 128k stripes over sets of 4 // ?? FileLayout g_OSD_MDDirLayout( 1<<14, 1<<2, 1<<19, 3 ); // stripe mds log over 128 byte bits (see mds_log_pad_entry below to match!) FileLayout g_OSD_MDLogLayout( 1<<7, 32, 1<<20, 3 ); // new (good?) way //FileLayout g_OSD_MDLogLayout( 57, 32, 1<<20 ); // pathological case to test striping buffer mapping //FileLayout g_OSD_MDLogLayout( 1<<20, 1, 1<<20 ); // old way md_config_t g_conf = { num_mds: 1, num_osd: 4, num_client: 1, mkfs: false, // profiling and debugging log: true, log_interval: 1, log_name: (char*)0, log_messages: true, log_pins: true, fake_clock: false, fakemessenger_serialize: true, fake_osdmap_expand: 0, fake_osd_sync: false, debug: 1, debug_mds_balancer: 1, debug_mds_log: 1, debug_buffer: 0, debug_filer: 0, debug_client: 0, debug_osd: 0, debug_ebofs: 1, debug_bdev: 1, // block device // --- client --- client_cache_size: 300, client_cache_mid: .5, client_cache_stat_ttl: 10, // seconds until cached stat results become invalid client_use_random_mds: false, client_sync_writes: 0, client_bcache: 1, client_bcache_alloc_minsize: 1<<10, // 1KB client_bcache_alloc_maxsize: 1<<18, // 256KB client_bcache_ttl: 30, // seconds until dirty buffers are written to disk client_bcache_size: 2<<30, // 2GB //client_bcache_size: 5<<20, // 5MB client_bcache_lowater: 60, // % of size client_bcache_hiwater: 80, // % of size client_bcache_align: 1<<10, // 1KB splice alignment client_trace: 0, fuse_direct_io: 0, // --- mds --- mds_cache_size: MDS_CACHE_SIZE, mds_cache_mid: .7, mds_log: true, mds_log_max_len: MDS_CACHE_SIZE / 3, mds_log_max_trimming: 256, mds_log_read_inc: 1024,//1<<20, mds_log_pad_entry: 64, mds_log_before_reply: true, mds_log_flush_on_shutdown: true, mds_bal_replicate_threshold: 8000, mds_bal_unreplicate_threshold: 1000, mds_bal_interval: 30, // seconds mds_bal_idle_threshold: .1, mds_bal_max: -1, mds_bal_max_until: -1, mds_commit_on_shutdown: true, mds_verify_export_dirauth: true, // --- osd --- osd_pg_bits: 8, osd_max_rep: 4, osd_fsync: true, osd_writesync: false, osd_maxthreads: 10, // 0 == no threading! osd_mkfs: false, osd_fakestore_syncthreads: 4, // --- ebofs --- ebofs: 0, ebofs_commit_interval: 2, // seconds. 0 = no timeout (for debugging/tracing) ebofs_oc_size: 1000, ebofs_cc_size: 1000, ebofs_bc_size: (15 *256), // 4k blocks, or *256 for MB ebofs_bc_max_dirty: (10 *256), // before write() will block ebofs_abp_zero: false, ebofs_abp_max_alloc: 4096*32, // --- block device --- bdev_el_fw_max_ms: 1000, // restart elevator at least once every 1000 ms bdev_el_bw_max_ms: 300, // restart elevator at least once every 1000 ms bdev_el_bidir: true, // bidirectional elevator? // --- fakeclient (mds regression testing) (ancient history) --- num_fakeclient: 100, fakeclient_requests: 100, fakeclient_deterministic: false, fakeclient_op_statfs: false, // loosely based on Roselli workload paper numbers fakeclient_op_stat: 610, fakeclient_op_lstat: false, fakeclient_op_utime: 0, fakeclient_op_chmod: 1, fakeclient_op_chown: 1, fakeclient_op_readdir: 2, fakeclient_op_mknod: 30, fakeclient_op_link: false, fakeclient_op_unlink: 20, fakeclient_op_rename: 0,//40, fakeclient_op_mkdir: 10, fakeclient_op_rmdir: 20, fakeclient_op_symlink: 20, fakeclient_op_openrd: 200, fakeclient_op_openwr: 0, fakeclient_op_openwrc: 0, fakeclient_op_read: false, // osd! fakeclient_op_write: false, // osd! fakeclient_op_truncate: false, fakeclient_op_fsync: false, fakeclient_op_close: 200 }; #include <stdlib.h> #include <string.h> #include <iostream> using namespace std; void argv_to_vec(int argc, char **argv, vector<char*>& args) { for (int i=1; i<argc; i++) args.push_back(argv[i]); } void vec_to_argv(vector<char*>& args, int& argc, char **&argv) { argv = (char**)malloc(sizeof(char*) * argc); argc = 1; argv[0] = "asdf"; for (unsigned i=0; i<args.size(); i++) argv[argc++] = args[i]; } void parse_config_options(vector<char*>& args) { vector<char*> nargs; for (unsigned i=0; i<args.size(); i++) { if (strcmp(args[i], "--nummds") == 0) g_conf.num_mds = atoi(args[++i]); else if (strcmp(args[i], "--numclient") == 0) g_conf.num_client = atoi(args[++i]); else if (strcmp(args[i], "--numosd") == 0) g_conf.num_osd = atoi(args[++i]); else if (strcmp(args[i], "--mkfs") == 0) g_conf.osd_mkfs = g_conf.mkfs = 1; //atoi(args[++i]); else if (strcmp(args[i], "--fake_osdmap_expand") == 0) g_conf.fake_osdmap_expand = atoi(args[++i]); else if (strcmp(args[i], "--fake_osd_sync") == 0) g_conf.fake_osd_sync = atoi(args[++i]); else if (strcmp(args[i], "--debug") == 0) g_conf.debug = atoi(args[++i]); else if (strcmp(args[i], "--debug_mds_balancer") == 0) g_conf.debug_mds_balancer = atoi(args[++i]); else if (strcmp(args[i], "--debug_mds_log") == 0) g_conf.debug_mds_log = atoi(args[++i]); else if (strcmp(args[i], "--debug_buffer") == 0) g_conf.debug_buffer = atoi(args[++i]); else if (strcmp(args[i], "--debug_filer") == 0) g_conf.debug_filer = atoi(args[++i]); else if (strcmp(args[i], "--debug_client") == 0) g_conf.debug_client = atoi(args[++i]); else if (strcmp(args[i], "--debug_osd") == 0) g_conf.debug_osd = atoi(args[++i]); else if (strcmp(args[i], "--debug_ebofs") == 0) g_conf.debug_ebofs = atoi(args[++i]); else if (strcmp(args[i], "--debug_bdev") == 0) g_conf.debug_bdev = atoi(args[++i]); else if (strcmp(args[i], "--log") == 0) g_conf.log = atoi(args[++i]); else if (strcmp(args[i], "--log_name") == 0) g_conf.log_name = args[++i]; else if (strcmp(args[i], "--fakemessenger_serialize") == 0) g_conf.fakemessenger_serialize = atoi(args[++i]); else if (strcmp(args[i], "--mds_cache_size") == 0) g_conf.mds_cache_size = atoi(args[++i]); else if (strcmp(args[i], "--mds_log") == 0) g_conf.mds_log = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_before_reply") == 0) g_conf.mds_log_before_reply = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_max_len") == 0) g_conf.mds_log_max_len = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_read_inc") == 0) g_conf.mds_log_read_inc = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_max_trimming") == 0) g_conf.mds_log_max_trimming = atoi(args[++i]); else if (strcmp(args[i], "--mds_commit_on_shutdown") == 0) g_conf.mds_commit_on_shutdown = atoi(args[++i]); else if (strcmp(args[i], "--mds_log_flush_on_shutdown") == 0) g_conf.mds_log_flush_on_shutdown = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_interval") == 0) g_conf.mds_bal_interval = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_rep") == 0) g_conf.mds_bal_replicate_threshold = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_unrep") == 0) g_conf.mds_bal_unreplicate_threshold = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_max") == 0) g_conf.mds_bal_max = atoi(args[++i]); else if (strcmp(args[i], "--mds_bal_max_until") == 0) g_conf.mds_bal_max_until = atoi(args[++i]); else if (strcmp(args[i], "--client_cache_size") == 0) g_conf.client_cache_size = atoi(args[++i]); else if (strcmp(args[i], "--client_cache_stat_ttl") == 0) g_conf.client_cache_stat_ttl = atoi(args[++i]); else if (strcmp(args[i], "--client_trace") == 0) g_conf.client_trace = atoi(args[++i]); else if (strcmp(args[i], "--fuse_direct_io") == 0) g_conf.fuse_direct_io = atoi(args[++i]); else if (strcmp(args[i], "--client_sync_writes") == 0) g_conf.client_sync_writes = atoi(args[++i]); else if (strcmp(args[i], "--client_bcache") == 0) g_conf.client_bcache = atoi(args[++i]); else if (strcmp(args[i], "--client_bcache_ttl") == 0) g_conf.client_bcache_ttl = atoi(args[++i]); else if (strcmp(args[i], "--ebofs") == 0) g_conf.ebofs = 1; else if (strcmp(args[i], "--fakestore") == 0) g_conf.ebofs = 0; else if (strcmp(args[i], "--osd_mkfs") == 0) g_conf.osd_mkfs = atoi(args[++i]); else if (strcmp(args[i], "--osd_pg_bits") == 0) g_conf.osd_pg_bits = atoi(args[++i]); else if (strcmp(args[i], "--osd_max_rep") == 0) g_conf.osd_max_rep = atoi(args[++i]); else if (strcmp(args[i], "--osd_fsync") == 0) g_conf.osd_fsync = atoi(args[++i]); else if (strcmp(args[i], "--osd_writesync") == 0) g_conf.osd_writesync = atoi(args[++i]); else if (strcmp(args[i], "--osd_maxthreads") == 0) g_conf.osd_maxthreads = atoi(args[++i]); else { nargs.push_back(args[i]); } } args = nargs; } <|endoftext|>
<commit_before>// xiva (acronym for HTTP Extended EVent Automata) is a simple HTTP server. // Copyright (C) 2009 Yandex <[email protected]> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef XIVA_DETAILS_REQUEST_CHECKER_HPP_INCLUDED #define XIVA_DETAILS_REQUEST_CHECKER_HPP_INCLUDED #include <utility> #include <iterator> #include <algorithm> #include <boost/type_traits.hpp> #include <boost/static_assert.hpp> #include "details/asio.hpp" #include "details/functors.hpp" #include "details/line_reader.hpp" #include "details/range.hpp" #include "details/string_utils.hpp" #include "details/http_constants.hpp" #include "details/iterator_checker.hpp" #include "details/request_helper.hpp" namespace xiva { namespace details { struct http_request_checker { template <typename Iter> std::pair<Iter, bool> operator () (Iter first, Iter second) const; }; struct request_policy_checker { template <typename Iter> std::pair<Iter, bool> operator () (Iter first, Iter second) const; }; template <typename Iter> inline std::pair<Iter, bool> http_request_checker::operator () (Iter first, Iter last) const { typedef typename std::iterator_traits<Iter>::value_type char_type; BOOST_STATIC_ASSERT(sizeof(char_type) == sizeof(char)); range<Iter> line, end_line; line_reader<Iter> reader(first, last); if (reader.read_line(line, end_line) && !end_line.empty()) { int read_body_ahead = 0; request_helper<Iter> helper; helper.parse_request_line(line); while (reader.read_line(line, end_line)) { int res = helper.check_read_body_ahead(line); if (res > 0) { read_body_ahead = res; } Iter break_ptr; if (helper.find_headers_break(end_line, break_ptr)) { if (!read_body_ahead) { return std::make_pair(end_line.begin(), true); } if (std::distance(break_ptr, last) >= read_body_ahead) { return std::make_pair(last, true); } } } } return std::make_pair(last, false); } template <typename Iter> inline std::pair<Iter, bool> request_policy_checker::operator () (Iter first, Iter last) const { typedef std::reverse_iterator<Iter> iterator_type; typedef typename std::iterator_traits<Iter>::value_type char_type; BOOST_STATIC_ASSERT(sizeof(char_type) == sizeof(char)); iterator_checker<Iter> iter_check; (void) iter_check; iterator_type begin(last), end(first); if (static_cast<char_type>('<') == *first) { return std::make_pair(last, (static_cast<char_type>(0) == *begin)); } return std::make_pair(last, false); } class request_checker { public: explicit request_checker(int max_size); template <typename Iter> std::pair<Iter, bool> operator () (Iter first, Iter second) const; private: http_request_checker http_checker_; request_policy_checker policy_checker_; int max_size_; }; request_checker::request_checker(int max_size) : max_size_(max_size) { } template <typename Iter> inline std::pair<Iter, bool> request_checker::operator () (Iter first, Iter last) const { typedef typename std::iterator_traits<Iter>::difference_type diff_type; diff_type size = std::distance(first, last); enum { min_size = sizeof("get / http/1.1\n\n") - 1 }; // sizeof ("<policy-file-request/>\0") - 1 > min_size if (size < min_size) { return std::make_pair(last, false); } if (size > (diff_type)max_size_) { return std::make_pair(last, true); // will be handled in connection_impl } try { std::pair<Iter, bool> result = policy_checker_(first, last); return (result.second) ? result : http_checker_(first, last); } catch (...) { return std::make_pair(last, true); // will be handled in request_impl } } }} // namespaces XIVA_BEGIN_ASIO_NAMESPACE template <> struct is_match_condition<xiva::details::request_checker> : public boost::true_type {}; XIVA_END_ASIO_NAMESPACE #endif // XIVA_DETAILS_REQUEST_CHECKER_HPP_INCLUDED <commit_msg>fixed checking big requests (size above 512b)<commit_after>// xiva (acronym for HTTP Extended EVent Automata) is a simple HTTP server. // Copyright (C) 2009 Yandex <[email protected]> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef XIVA_DETAILS_REQUEST_CHECKER_HPP_INCLUDED #define XIVA_DETAILS_REQUEST_CHECKER_HPP_INCLUDED #include <utility> #include <iterator> #include <algorithm> #include <boost/type_traits.hpp> #include <boost/static_assert.hpp> #include "details/asio.hpp" #include "details/functors.hpp" #include "details/line_reader.hpp" #include "details/range.hpp" #include "details/string_utils.hpp" #include "details/http_constants.hpp" #include "details/iterator_checker.hpp" #include "details/request_helper.hpp" namespace xiva { namespace details { struct http_request_checker { template <typename Iter> std::pair<Iter, bool> operator () (Iter first, Iter second) const; }; struct request_policy_checker { template <typename Iter> std::pair<Iter, bool> operator () (Iter first, Iter second) const; }; template <typename Iter> inline std::pair<Iter, bool> http_request_checker::operator () (Iter first, Iter last) const { typedef typename std::iterator_traits<Iter>::value_type char_type; BOOST_STATIC_ASSERT(sizeof(char_type) == sizeof(char)); range<Iter> line, end_line; line_reader<Iter> reader(first, last); if (reader.read_line(line, end_line) && !end_line.empty()) { int read_body_ahead = 0; request_helper<Iter> helper; helper.parse_request_line(line); while (reader.read_line(line, end_line)) { int res = helper.check_read_body_ahead(line); if (res > 0) { read_body_ahead = res; } Iter break_ptr; if (helper.find_headers_break(end_line, break_ptr)) { if (!read_body_ahead) { return std::make_pair(end_line.begin(), true); // ok, without body } if (std::distance(break_ptr, last) >= read_body_ahead) { return std::make_pair(last, true); // ok, with ahead body } } } } return std::make_pair(first, false); // continue, cannot find end of headers or ahead body } template <typename Iter> inline std::pair<Iter, bool> request_policy_checker::operator () (Iter first, Iter last) const { typedef std::reverse_iterator<Iter> iterator_type; typedef typename std::iterator_traits<Iter>::value_type char_type; BOOST_STATIC_ASSERT(sizeof(char_type) == sizeof(char)); iterator_checker<Iter> iter_check; (void) iter_check; iterator_type begin(last), end(first); if (static_cast<char_type>('<') == *first) { return std::make_pair(last, (static_cast<char_type>(0) == *begin)); } return std::make_pair(last, false); } class request_checker { public: explicit request_checker(int max_size); template <typename Iter> std::pair<Iter, bool> operator () (Iter first, Iter second) const; private: http_request_checker http_checker_; request_policy_checker policy_checker_; int max_size_; }; request_checker::request_checker(int max_size) : max_size_(max_size) { } template <typename Iter> inline std::pair<Iter, bool> request_checker::operator () (Iter first, Iter last) const { typedef typename std::iterator_traits<Iter>::difference_type diff_type; diff_type size = std::distance(first, last); enum { min_size = sizeof("get / http/1.1\n\n") - 1 }; // sizeof ("<policy-file-request/>\0") - 1 > min_size if (size < min_size) { return std::make_pair(first, false); // continue, too little data } if (size > (diff_type)max_size_) { return std::make_pair(last, true); // will be handled in connection_impl } try { std::pair<Iter, bool> result = policy_checker_(first, last); return (result.second) ? result : http_checker_(first, last); } catch (...) { return std::make_pair(last, true); // will be handled in request_impl } } }} // namespaces XIVA_BEGIN_ASIO_NAMESPACE template <> struct is_match_condition<xiva::details::request_checker> : public boost::true_type {}; XIVA_END_ASIO_NAMESPACE #endif // XIVA_DETAILS_REQUEST_CHECKER_HPP_INCLUDED <|endoftext|>
<commit_before>#include <cmdstan/command.hpp> #include <test/test-models/proper.hpp> #include <stan/math/prim/core/init_threadpool_tbb.hpp> #include <tbb/task_scheduler_init.h> #include <gtest/gtest.h> TEST(StanUiCommand, threadpool_init) { tbb::task_scheduler_init &scheduler_init = stan::math::init_threadpool_tbb(); EXPECT_TRUE(scheduler_init.is_active()); scheduler_init.terminate(); EXPECT_FALSE(scheduler_init.is_active()); } <commit_msg>use auto for threadpool init so we can update tbb<commit_after>#include <cmdstan/command.hpp> #include <test/test-models/proper.hpp> #include <stan/math/prim/core/init_threadpool_tbb.hpp> #include <tbb/task_scheduler_init.h> #include <gtest/gtest.h> TEST(StanUiCommand, threadpool_init) { auto& scheduler_init = stan::math::init_threadpool_tbb(); EXPECT_TRUE(scheduler_init.is_active()); scheduler_init.terminate(); EXPECT_FALSE(scheduler_init.is_active()); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file sgd_context.hpp * \brief Stochastic Gradient Descent (SGD) context Implementation. */ #pragma once #include "etl/etl.hpp" #include "dll/layer_traits.hpp" #include "dll/dbn_traits.hpp" namespace dll { /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto num_visible = layer_t::num_visible; static constexpr const auto num_hidden = layer_t::num_hidden; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, num_visible, num_hidden> w_grad; etl::fast_matrix<weight, num_hidden> b_grad; etl::fast_matrix<weight, num_visible, num_hidden> w_inc; etl::fast_matrix<weight, num_hidden> b_inc; etl::fast_matrix<weight, batch_size, num_visible> input; etl::fast_matrix<weight, batch_size, num_hidden> output; etl::fast_matrix<weight, batch_size, num_hidden> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 2> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 2> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 2> input; etl::dyn_matrix<weight, 2> output; etl::dyn_matrix<weight, 2> errors; sgd_context(std::size_t num_visible, std::size_t num_hidden) : w_grad(num_visible, num_hidden), b_grad(num_hidden), w_inc(num_visible, num_hidden, 0.0), b_inc(num_hidden, 0.0), input(batch_size, num_visible, 0.0), output(batch_size, num_hidden, 0.0), errors(batch_size, num_hidden, 0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation"); static constexpr const std::size_t NV1 = layer_t::NV1; static constexpr const std::size_t NV2 = layer_t::NV2; static constexpr const std::size_t NH1 = layer_t::NH1; static constexpr const std::size_t NH2 = layer_t::NH2; static constexpr const std::size_t NW1 = layer_t::NW1; static constexpr const std::size_t NW2 = layer_t::NW2; static constexpr const std::size_t NC = layer_t::NC; static constexpr const std::size_t K = layer_t::K; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, K, NC, NW1, NW2> w_grad; etl::fast_matrix<weight, K> b_grad; etl::fast_matrix<weight, K, NC, NW1, NW2> w_inc; etl::fast_matrix<weight, K> b_inc; etl::fast_matrix<weight, batch_size, NC, NV1, NV2> input; etl::fast_matrix<weight, batch_size, K, NH1, NH2> output; etl::fast_matrix<weight, batch_size, K, NH1, NH2> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation"); static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 4> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2) : w_grad(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_grad(k), w_inc(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_inc(k), input(batch_size, nc, nv1, nv2), output(batch_size, k, nh1, nh2), errors(batch_size, k, nh1, nh2) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const std::size_t I1 = layer_t::I1; static constexpr const std::size_t I2 = layer_t::I2; static constexpr const std::size_t I3 = layer_t::I3; static constexpr const std::size_t O1 = layer_t::O1; static constexpr const std::size_t O2 = layer_t::O2; static constexpr const std::size_t O3 = layer_t::O3; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, I1, I2, I3> input; etl::fast_matrix<weight, batch_size, O1, O2, O3> output; etl::fast_matrix<weight, batch_size, O1, O2, O3> errors; }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3) : input(batch_size, i1, i2, i3), output(batch_size, i1 / c1, i2 / c2, i3 / c3), errors(batch_size, i1 / c1, i2 / c2, i3 / c3) {} }; template <typename DBN, typename Layer> struct transform_output_type { static constexpr const auto dimensions = dbn_traits<DBN>::is_convolutional() ? 4 : 2; using weight = typename DBN::weight; using type = etl::dyn_matrix<weight, dimensions>; }; template <typename DBN, typename Layer> using transform_output_type_t = typename transform_output_type<DBN, Layer>::type; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_transform_layer()>> { using layer_t = Layer; using weight = typename DBN::weight; using inputs_t = transform_output_type_t<DBN, Layer>; inputs_t input; inputs_t output; inputs_t errors; }; } //end of dll namespace <commit_msg>SGD context support<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file sgd_context.hpp * \brief Stochastic Gradient Descent (SGD) context Implementation. */ #pragma once #include "etl/etl.hpp" #include "dll/layer_traits.hpp" #include "dll/dbn_traits.hpp" namespace dll { /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto num_visible = layer_t::num_visible; static constexpr const auto num_hidden = layer_t::num_hidden; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, num_visible, num_hidden> w_grad; etl::fast_matrix<weight, num_hidden> b_grad; etl::fast_matrix<weight, num_visible, num_hidden> w_inc; etl::fast_matrix<weight, num_hidden> b_inc; etl::fast_matrix<weight, batch_size, num_visible> input; etl::fast_matrix<weight, batch_size, num_hidden> output; etl::fast_matrix<weight, batch_size, num_hidden> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 2> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 2> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 2> input; etl::dyn_matrix<weight, 2> output; etl::dyn_matrix<weight, 2> errors; sgd_context(std::size_t num_visible, std::size_t num_hidden) : w_grad(num_visible, num_hidden), b_grad(num_hidden), w_inc(num_visible, num_hidden, 0.0), b_inc(num_hidden, 0.0), input(batch_size, num_visible, 0.0), output(batch_size, num_hidden, 0.0), errors(batch_size, num_hidden, 0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<(layer_traits<Layer>::is_convolutional_layer() || layer_traits<Layer>::is_deconvolutional_layer()) && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation"); static constexpr const std::size_t NV1 = layer_t::NV1; static constexpr const std::size_t NV2 = layer_t::NV2; static constexpr const std::size_t NH1 = layer_t::NH1; static constexpr const std::size_t NH2 = layer_t::NH2; static constexpr const std::size_t NW1 = layer_t::NW1; static constexpr const std::size_t NW2 = layer_t::NW2; static constexpr const std::size_t NC = layer_t::NC; static constexpr const std::size_t K = layer_t::K; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, K, NC, NW1, NW2> w_grad; etl::fast_matrix<weight, K> b_grad; etl::fast_matrix<weight, K, NC, NW1, NW2> w_inc; etl::fast_matrix<weight, K> b_inc; etl::fast_matrix<weight, batch_size, NC, NV1, NV2> input; etl::fast_matrix<weight, batch_size, K, NH1, NH2> output; etl::fast_matrix<weight, batch_size, K, NH1, NH2> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<(layer_traits<Layer>::is_convolutional_layer() || layer_traits<Layer>::is_deconvolutional_layer()) && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation"); static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 4> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2) : w_grad(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_grad(k), w_inc(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_inc(k), input(batch_size, nc, nv1, nv2), output(batch_size, k, nh1, nh2), errors(batch_size, k, nh1, nh2) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const std::size_t I1 = layer_t::I1; static constexpr const std::size_t I2 = layer_t::I2; static constexpr const std::size_t I3 = layer_t::I3; static constexpr const std::size_t O1 = layer_t::O1; static constexpr const std::size_t O2 = layer_t::O2; static constexpr const std::size_t O3 = layer_t::O3; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, I1, I2, I3> input; etl::fast_matrix<weight, batch_size, O1, O2, O3> output; etl::fast_matrix<weight, batch_size, O1, O2, O3> errors; }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3) : input(batch_size, i1, i2, i3), output(batch_size, i1 / c1, i2 / c2, i3 / c3), errors(batch_size, i1 / c1, i2 / c2, i3 / c3) {} }; template <typename DBN, typename Layer> struct transform_output_type { static constexpr const auto dimensions = dbn_traits<DBN>::is_convolutional() ? 4 : 2; using weight = typename DBN::weight; using type = etl::dyn_matrix<weight, dimensions>; }; template <typename DBN, typename Layer> using transform_output_type_t = typename transform_output_type<DBN, Layer>::type; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_transform_layer()>> { using layer_t = Layer; using weight = typename DBN::weight; using inputs_t = transform_output_type_t<DBN, Layer>; inputs_t input; inputs_t output; inputs_t errors; }; } //end of dll namespace <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/core/LandmarkMapper.hpp * * Copyright 2014-2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef LANDMARKMAPPER_HPP_ #define LANDMARKMAPPER_HPP_ #include <string> #include <map> #include <fstream> #include <sstream> #include <stdexcept> #include <algorithm> #include <optional> namespace eos { namespace core { /** * @brief Represents a mapping from one kind of landmarks * to a different format (e.g. model vertices). * * When fitting the 3D model to an image, a correspondence must * be known from the 2D image landmarks to 3D vertex points in * the Morphable Model. The 3D model defines all its points in * the form of vertex ids. * These mappings are stored in a file, see the \c share/ folder for * an example for mapping 2D ibug landmarks to 3D model vertex indices. * * The LandmarkMapper thus has two main use cases: * - Mapping 2D landmark points to 3D vertices * - Converting one set of 2D landmarks into another set of 2D * landmarks with different identifiers. */ class LandmarkMapper { public: /** * @brief Constructs a new landmark mapper that performs an identity * mapping, that is, its output is the same as the input. */ LandmarkMapper() = default; /** * @brief Constructs a new landmark mapper from a file containing * mappings from one set of landmark identifiers to another. * * In case the file contains no mappings, a landmark mapper * that performs an identity mapping is constructed. * * @param[in] filename A file with landmark mappings. * @throws runtime_error if there is an error loading the mappings from the file. */ LandmarkMapper(std::string filename) { using std::string; using std::getline; std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error(string("LandmarkMapper: Could not open landmark mappings file: " + filename)); } // We'll need these helper functions for the parsing: auto starts_with = [](const std::string& input, const std::string& match) { return input.size() >= match.size() && std::equal(match.begin(), match.end(), input.begin()); }; auto trim_left = [](const std::string& input, std::string pattern = " \t") { auto first = input.find_first_not_of(pattern); if (first == std::string::npos) { return input; } return input.substr(first, input.size()); }; // Read the actual file: string line; // Skip any comments (";") or empty lines at the beginning: while (getline(file, line)) { if (!starts_with(line, ";") && line != "") { // not a commented or not an empty line break; } } // First actual line should be "landmarkMappings" if (!starts_with(line, "landmarkMappings")) { throw std::runtime_error("LandmarkMapper error: First non-comment line should be \"landmarkMappings\"."); } getline(file, line); // The next line has to be "{": if (line != "{") { throw std::runtime_error("LandmarkMapper error: Expected a \"{\" on the line following the \"landmarkMappings\" statement."); } while (getline(file, line)) { if (line == "}") { // end of the landmarkMappings block break; } // on comment, continue: if (starts_with(trim_left(line), ";")) { continue; } std::stringstream line_stream(line); string lhs, rhs; if (!(line_stream >> lhs >> rhs)) { throw std::runtime_error(string("Landmark mappings format error while parsing the line: " + line)); } landmark_mappings.insert(std::make_pair(lhs, rhs)); } // We're at the end of the "landmarkMappings { ... }" block. Something else may follow, but we don't care. }; /** * @brief Converts the given landmark name to the mapped name. * * @param[in] landmark_name A landmark name to convert. * @return The mapped landmark name if a mapping exists, an empty optional otherwise. * @throws out_of_range exception if there is no mapping * for the given landmarkName. */ std::optional<std::string> convert(std::string landmark_name) const { if (landmark_mappings.empty()) { // perform identity mapping, i.e. return the input return landmark_name; } auto&& converted_landmark = landmark_mappings.find(landmark_name); if (converted_landmark != std::end(landmark_mappings)) { // landmark mapping found, return it return converted_landmark->second; } else { // landmark_name does not match the key of any element in the map return std::nullopt; } }; /** * @brief Returns the number of loaded landmark mappings. * * @return The number of landmark mappings. */ auto num_mappings() const { return landmark_mappings.size(); }; private: std::map<std::string, std::string> landmark_mappings; ///< Mapping from one landmark name to a name in a different format. }; } /* namespace core */ } /* namespace eos */ #endif /* LANDMARKMAPPER_HPP_ */ <commit_msg>Removed old comment<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/core/LandmarkMapper.hpp * * Copyright 2014-2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef LANDMARKMAPPER_HPP_ #define LANDMARKMAPPER_HPP_ #include <string> #include <map> #include <fstream> #include <sstream> #include <stdexcept> #include <algorithm> #include <optional> namespace eos { namespace core { /** * @brief Represents a mapping from one kind of landmarks * to a different format (e.g. model vertices). * * When fitting the 3D model to an image, a correspondence must * be known from the 2D image landmarks to 3D vertex points in * the Morphable Model. The 3D model defines all its points in * the form of vertex ids. * These mappings are stored in a file, see the \c share/ folder for * an example for mapping 2D ibug landmarks to 3D model vertex indices. * * The LandmarkMapper thus has two main use cases: * - Mapping 2D landmark points to 3D vertices * - Converting one set of 2D landmarks into another set of 2D * landmarks with different identifiers. */ class LandmarkMapper { public: /** * @brief Constructs a new landmark mapper that performs an identity * mapping, that is, its output is the same as the input. */ LandmarkMapper() = default; /** * @brief Constructs a new landmark mapper from a file containing * mappings from one set of landmark identifiers to another. * * In case the file contains no mappings, a landmark mapper * that performs an identity mapping is constructed. * * @param[in] filename A file with landmark mappings. * @throws runtime_error if there is an error loading the mappings from the file. */ LandmarkMapper(std::string filename) { using std::string; using std::getline; std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error(string("LandmarkMapper: Could not open landmark mappings file: " + filename)); } // We'll need these helper functions for the parsing: auto starts_with = [](const std::string& input, const std::string& match) { return input.size() >= match.size() && std::equal(match.begin(), match.end(), input.begin()); }; auto trim_left = [](const std::string& input, std::string pattern = " \t") { auto first = input.find_first_not_of(pattern); if (first == std::string::npos) { return input; } return input.substr(first, input.size()); }; // Read the actual file: string line; // Skip any comments (";") or empty lines at the beginning: while (getline(file, line)) { if (!starts_with(line, ";") && line != "") { // not a commented or not an empty line break; } } // First actual line should be "landmarkMappings" if (!starts_with(line, "landmarkMappings")) { throw std::runtime_error("LandmarkMapper error: First non-comment line should be \"landmarkMappings\"."); } getline(file, line); // The next line has to be "{": if (line != "{") { throw std::runtime_error("LandmarkMapper error: Expected a \"{\" on the line following the \"landmarkMappings\" statement."); } while (getline(file, line)) { if (line == "}") { // end of the landmarkMappings block break; } // on comment, continue: if (starts_with(trim_left(line), ";")) { continue; } std::stringstream line_stream(line); string lhs, rhs; if (!(line_stream >> lhs >> rhs)) { throw std::runtime_error(string("Landmark mappings format error while parsing the line: " + line)); } landmark_mappings.insert(std::make_pair(lhs, rhs)); } // We're at the end of the "landmarkMappings { ... }" block. Something else may follow, but we don't care. }; /** * @brief Converts the given landmark name to the mapped name. * * @param[in] landmark_name A landmark name to convert. * @return The mapped landmark name if a mapping exists, an empty optional otherwise. */ std::optional<std::string> convert(std::string landmark_name) const { if (landmark_mappings.empty()) { // perform identity mapping, i.e. return the input return landmark_name; } auto&& converted_landmark = landmark_mappings.find(landmark_name); if (converted_landmark != std::end(landmark_mappings)) { // landmark mapping found, return it return converted_landmark->second; } else { // landmark_name does not match the key of any element in the map return std::nullopt; } }; /** * @brief Returns the number of loaded landmark mappings. * * @return The number of landmark mappings. */ auto num_mappings() const { return landmark_mappings.size(); }; private: std::map<std::string, std::string> landmark_mappings; ///< Mapping from one landmark name to a name in a different format. }; } /* namespace core */ } /* namespace eos */ #endif /* LANDMARKMAPPER_HPP_ */ <|endoftext|>
<commit_before>#include "data-id.hpp" ID::ID() { init(Department(NONE), 0, ""); } ID::ID(const ID& c) { copy(c); } ID& ID::operator= (const ID &c) { if (this == &c) return *this; copy(c); return *this; } ID::ID(string str) { string d, d1, d2, n, s; int num; long firstSpace, firstDigit, lastDigit, lastChar; // cout << "Called ID::ID() with string '" << str << "'" << endl; // Make sure everything is uppercase std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Remove extraneous spaces if (str.at(0) == ' ') str.erase(0, 1); if (str.at(str.length()-1) == ' ') str = str.substr(0, str.length()-1); firstSpace = str.find_first_of(" "); firstDigit = str.find_first_of("0123456789"); lastDigit = str.find_last_of("0123456789"); lastChar = str.find_last_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Split into Department, Number, and Section // pull out the department string if (firstSpace == string::npos) // if there is no space d = str.substr(0, firstDigit); else d = str.substr(0, firstSpace); // there is a space // check for one of those dastardly split departments if (d.find('/') != string::npos) { d1 = d.substr(0,2); d2 = d.substr(3,2); } n = str.substr(firstDigit, str.length()); if (!isdigit(n[n.length()-1])) n = str.substr(firstDigit, n.length()-1); num = stringToInt(n); if (lastChar > lastDigit) // there is a section s = str[lastChar]; // cout << "Parsed '" << str << "' to get '"; // cout << d << " "; // if (!d1.empty() && !d2.empty()) // cout << "(" << d1 << " " << d2 << ") "; // cout << n << s << "'." << endl; init(Department(d), num, s); if (!d1.empty() && !d2.empty()) { departments.clear(); departments.push_back(Department(d1)); departments.push_back(Department(d2)); } // cout << *this << endl; } ID::ID(string dn, string s) { ID(dn+s); } ID::ID(string d, string n, string s) { ID(d + n + s); } ID::ID(Department d, int n, string s) { init(d, n, s); } void ID::init(Department d, int n, string s) { departments.push_back(d); number = n; section = s; } void ID::copy(const ID& c) { departments = c.departments; number = c.number; section = c.section; } Department ID::getDepartment(int i = 0) { return departments.at(i); } const Department ID::getDepartment_const(int i = 0) { return departments.at(i); } int ID::getNumber() { return number; } string ID::getSection() { return section; } bool operator== (const ID &i1, const ID &i2) { return ((i1.departments[0] == i2.departments[0]) && (i1.number == i2.number) && (i1.section == i2.section)); } bool operator!= (ID &i1, ID &i2) { return !(i1 == i2); } bool operator< (const ID &i1, const ID &i2) { return (i1.departments.at(0) < i2.departments.at(0)); } ostream& ID::getData(ostream& os) { for (vector<Department>::iterator i = departments.begin(); i != departments.end(); ++i) { if (departments.size() == 1) os << i->getName(); else { os << i->getName(); if (i != departments.end()-1) os << "/"; } } os << " "; os << number; if (!section.empty()) os << "[" << section << "]"; return os; } ostream& operator<<(ostream& os, ID& item) { return item.getData(os); } void ID::display() { cout << *this << endl; } <commit_msg>ID::init defaults to NONE<commit_after>#include "data-id.hpp" ID::ID() { init(Department(), 0, ""); } ID::ID(const ID& c) { copy(c); } ID& ID::operator= (const ID &c) { if (this == &c) return *this; copy(c); return *this; } ID::ID(string str) { string d, d1, d2, n, s; int num; long firstSpace, firstDigit, lastDigit, lastChar; // cout << "Called ID::ID() with string '" << str << "'" << endl; // Make sure everything is uppercase std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Remove extraneous spaces if (str.at(0) == ' ') str.erase(0, 1); if (str.at(str.length()-1) == ' ') str = str.substr(0, str.length()-1); firstSpace = str.find_first_of(" "); firstDigit = str.find_first_of("0123456789"); lastDigit = str.find_last_of("0123456789"); lastChar = str.find_last_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Split into Department, Number, and Section // pull out the department string if (firstSpace == string::npos) // if there is no space d = str.substr(0, firstDigit); else d = str.substr(0, firstSpace); // there is a space // check for one of those dastardly split departments if (d.find('/') != string::npos) { d1 = d.substr(0,2); d2 = d.substr(3,2); } n = str.substr(firstDigit, str.length()); if (!isdigit(n[n.length()-1])) n = str.substr(firstDigit, n.length()-1); num = stringToInt(n); if (lastChar > lastDigit) // there is a section s = str[lastChar]; // cout << "Parsed '" << str << "' to get '"; // cout << d << " "; // if (!d1.empty() && !d2.empty()) // cout << "(" << d1 << " " << d2 << ") "; // cout << n << s << "'." << endl; init(Department(d), num, s); if (!d1.empty() && !d2.empty()) { departments.clear(); departments.push_back(Department(d1)); departments.push_back(Department(d2)); } // cout << *this << endl; } ID::ID(string dn, string s) { ID(dn+s); } ID::ID(string d, string n, string s) { ID(d + n + s); } ID::ID(Department d, int n, string s) { init(d, n, s); } void ID::init(Department d, int n, string s) { departments.push_back(d); number = n; section = s; } void ID::copy(const ID& c) { departments = c.departments; number = c.number; section = c.section; } Department ID::getDepartment(int i = 0) { return departments.at(i); } const Department ID::getDepartment_const(int i = 0) { return departments.at(i); } int ID::getNumber() { return number; } string ID::getSection() { return section; } bool operator== (const ID &i1, const ID &i2) { return ((i1.departments[0] == i2.departments[0]) && (i1.number == i2.number) && (i1.section == i2.section)); } bool operator!= (ID &i1, ID &i2) { return !(i1 == i2); } bool operator< (const ID &i1, const ID &i2) { return (i1.departments.at(0) < i2.departments.at(0)); } ostream& ID::getData(ostream& os) { for (vector<Department>::iterator i = departments.begin(); i != departments.end(); ++i) { if (departments.size() == 1) os << i->getName(); else { os << i->getName(); if (i != departments.end()-1) os << "/"; } } os << " "; os << number; if (!section.empty()) os << "[" << section << "]"; return os; } ostream& operator<<(ostream& os, ID& item) { return item.getData(os); } void ID::display() { cout << *this << endl; } <|endoftext|>
<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_MODBUS_2_INCLUDE_CUTEHMI_MODBUS_EXCEPTION_HPP #define H_EXTENSIONS_CUTEHMI_MODBUS_2_INCLUDE_CUTEHMI_MODBUS_EXCEPTION_HPP #include "internal/common.hpp" #include <cutehmi/ExceptionMixin.hpp> namespace cutehmi { namespace modbus { class Exception: public ExceptionMixin<Exception> { typedef ExceptionMixin<Exception> Parent; public: using Parent::Parent; ~Exception() override = default; }; } } #endif //(c)C: Copyright © 2019, Michał Policht <[email protected]>. All rights reserved. //(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/>. <commit_msg>Mark Exception with export API macro and remove redundant destructor entry.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_MODBUS_2_INCLUDE_CUTEHMI_MODBUS_EXCEPTION_HPP #define H_EXTENSIONS_CUTEHMI_MODBUS_2_INCLUDE_CUTEHMI_MODBUS_EXCEPTION_HPP #include "internal/common.hpp" #include <cutehmi/ExceptionMixin.hpp> namespace cutehmi { namespace modbus { class CUTEHMI_MODBUS_API Exception: public ExceptionMixin<Exception> { typedef ExceptionMixin<Exception> Parent; public: using Parent::Parent; }; } } #endif //(c)C: Copyright © 2019, Michał Policht <[email protected]>. All rights reserved. //(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/>. <|endoftext|>
<commit_before>// Copyright © 2012-2014 Inria, Written by Lénaïc Bagnères, [email protected] // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HNC_SCHEDULER_ITERATION_HPP #define HNC_SCHEDULER_ITERATION_HPP #include <chrono> #include <vector> #include <algorithm> #include <initializer_list> namespace hnc { namespace scheduler { /** * @brief Excute different versions of for loop. Split iterations, benchmark versions and select the version with the min time. No useless computing, no rollback. * * @code #include <hnc/scheduler.hpp> @endcode * * You have: * - a number of iterations (betwwen first and last with a step) * - different versions of the same computing (per iteration) * * You do not know the best version. Worse, the best version is not the same in all contexts (the best version deplasts on another computing in the computer). * * This function take the number of iterations, several versions and do this until there are no iteration anymore: * 1. execute all versions on few iterations (sample) * 2. execute the last best version on several iterations * * Example with classic function: * @code int func_value = 0; void func0(int const & first, int const & last) { for (int i = first; i < last; ++i) { ++func_value; } } void func1(int const & first, int const & last) { for (int i = first; i < last; ++i) { ++func_value; } } int main() { // Compute hnc::scheduler::iteration(0, 42, {func0, func1}); // func_value value is 42 return 0; } @endcode * * Example with functor object and lambda : * @code class fonctor { public: fonctor(std::vector<std::vector<int>> & tab2D) : r_tab2D(tab2D) { } void operator()(std::size_t const & first, std::size_t const & last) { for (std::size_t i = first; i < last; ++i) { for (std::size_t j = 0; j < r_tab2D.size(); ++j) { r_tab2D[i][j] += i * j; } } } private: std::vector<std::vector<int>> & r_tab2D; }; int main() { std::size_t const N = 200; // A 2D array [N][N] std::vector<std::vector<int>> tab2D(N, std::vector<int>(N, 0)); auto lambda = [&](std::size_t const & first, std::size_t const & last) -> void { for (j = 0; j < tab2D.size(); j += 7) { for (i = first; i < last; ++i) { tab2D[i][j] += i * j; } } }; // Compute hnc::scheduler::iteration(std::size_t(0), N, {fonctor(tab2D), lambda}); return 0; } @endcode * * @param[in] first First iteration * @param[in] last Last iteration (not included) * @param[in] versions Functions with a first and a last and with the same computing * @param[in] nb_it_sample Number of iterations for sample phases * @param[in] nb_it_compute Number of iterations for compute phases * @param[in] step Incrementation in the loop (1 by default) * * Function type (in versions) is a std::function, it can be: * - a function without parameter * - a functor object * - a lambda expression without parameter * * @pre The function type signature is (it_t const &, it_t const &) * @pre All versions do the same computing * @pre One iteration in a random version for one iteration id is the same result as another random version for the same id iteration * * @warning If the incrementation (step) have not the good value, the number of iterations computed is not correct * @warning Be carefull about versions if you need the final iterator (you can not mix loop and reverse loop for example) */ template <class it_t, class incr_t = std::size_t> inline void iteration ( it_t first, it_t const & last, std::vector<std::function<void(it_t const &, it_t const &)>> const & versions, it_t const & nb_it_sample = 2 * 4 * 6, it_t const & nb_it_compute = (2 * 4 * 6) * 10, incr_t const & step = 1 ) { while (first < last) { // Index of the best version auto best_time = std::numeric_limits<std::chrono::steady_clock::duration::rep>::max(); std::size_t best_version = 0; // Samples for (std::size_t i = 0; i < versions.size() && first < last; ++i) { // Compute auto time_first = std::chrono::steady_clock::now(); { versions[i](first, std::min(it_t(first) + it_t(nb_it_sample) * it_t(step), last)); } auto time_last = std::chrono::steady_clock::now(); // Save best version auto const time = (time_last - time_first).count(); if (time < best_time) { best_time = time; best_version = i; } // Next iterations first += it_t(nb_it_sample) * it_t(step); } // Compute if (first < last) { // Compute versions[best_version](first, std::min(it_t(first) + it_t(nb_it_compute) * it_t(step), last)); // Next iterations first += it_t(nb_it_compute) * it_t(step); } } } } } #endif <commit_msg>Fix include in hnc/scheduler/iteration.hpp<commit_after>// Copyright © 2012-2014 Inria, Written by Lénaïc Bagnères, [email protected] // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HNC_SCHEDULER_ITERATION_HPP #define HNC_SCHEDULER_ITERATION_HPP #include <chrono> #include <vector> #include <algorithm> #include <initializer_list> #include <functional> namespace hnc { namespace scheduler { /** * @brief Excute different versions of for loop. Split iterations, benchmark versions and select the version with the min time. No useless computing, no rollback. * * @code #include <hnc/scheduler.hpp> @endcode * * You have: * - a number of iterations (betwwen first and last with a step) * - different versions of the same computing (per iteration) * * You do not know the best version. Worse, the best version is not the same in all contexts (the best version deplasts on another computing in the computer). * * This function take the number of iterations, several versions and do this until there are no iteration anymore: * 1. execute all versions on few iterations (sample) * 2. execute the last best version on several iterations * * Example with classic function: * @code int func_value = 0; void func0(int const & first, int const & last) { for (int i = first; i < last; ++i) { ++func_value; } } void func1(int const & first, int const & last) { for (int i = first; i < last; ++i) { ++func_value; } } int main() { // Compute hnc::scheduler::iteration(0, 42, {func0, func1}); // func_value value is 42 return 0; } @endcode * * Example with functor object and lambda : * @code class fonctor { public: fonctor(std::vector<std::vector<int>> & tab2D) : r_tab2D(tab2D) { } void operator()(std::size_t const & first, std::size_t const & last) { for (std::size_t i = first; i < last; ++i) { for (std::size_t j = 0; j < r_tab2D.size(); ++j) { r_tab2D[i][j] += i * j; } } } private: std::vector<std::vector<int>> & r_tab2D; }; int main() { std::size_t const N = 200; // A 2D array [N][N] std::vector<std::vector<int>> tab2D(N, std::vector<int>(N, 0)); auto lambda = [&](std::size_t const & first, std::size_t const & last) -> void { for (j = 0; j < tab2D.size(); j += 7) { for (i = first; i < last; ++i) { tab2D[i][j] += i * j; } } }; // Compute hnc::scheduler::iteration(std::size_t(0), N, {fonctor(tab2D), lambda}); return 0; } @endcode * * @param[in] first First iteration * @param[in] last Last iteration (not included) * @param[in] versions Functions with a first and a last and with the same computing * @param[in] nb_it_sample Number of iterations for sample phases * @param[in] nb_it_compute Number of iterations for compute phases * @param[in] step Incrementation in the loop (1 by default) * * Function type (in versions) is a std::function, it can be: * - a function without parameter * - a functor object * - a lambda expression without parameter * * @pre The function type signature is (it_t const &, it_t const &) * @pre All versions do the same computing * @pre One iteration in a random version for one iteration id is the same result as another random version for the same id iteration * * @warning If the incrementation (step) have not the good value, the number of iterations computed is not correct * @warning Be carefull about versions if you need the final iterator (you can not mix loop and reverse loop for example) */ template <class it_t, class incr_t = std::size_t> inline void iteration ( it_t first, it_t const & last, std::vector<std::function<void(it_t const &, it_t const &)>> const & versions, it_t const & nb_it_sample = 2 * 4 * 6, it_t const & nb_it_compute = (2 * 4 * 6) * 10, incr_t const & step = 1 ) { while (first < last) { // Index of the best version auto best_time = std::numeric_limits<std::chrono::steady_clock::duration::rep>::max(); std::size_t best_version = 0; // Samples for (std::size_t i = 0; i < versions.size() && first < last; ++i) { // Compute auto time_first = std::chrono::steady_clock::now(); { versions[i](first, std::min(it_t(first) + it_t(nb_it_sample) * it_t(step), last)); } auto time_last = std::chrono::steady_clock::now(); // Save best version auto const time = (time_last - time_first).count(); if (time < best_time) { best_time = time; best_version = i; } // Next iterations first += it_t(nb_it_sample) * it_t(step); } // Compute if (first < last) { // Compute versions[best_version](first, std::min(it_t(first) + it_t(nb_it_compute) * it_t(step), last)); // Next iterations first += it_t(nb_it_compute) * it_t(step); } } } } } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2010-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BUILD_CONFIG_HPP_INCLUDED #define TORRENT_BUILD_CONFIG_HPP_INCLUDED #include "libtorrent/config.hpp" #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/stringize.hpp> #if TORRENT_USE_IPV6 #define TORRENT_CFG_IPV6 ipv6_ #else #define TORRENT_CFG_IPV6 noipv6_- #endif #ifdef TORRENT_NO_DEPRECATE #define TORRENT_CFG_DEPR nodeprecate_ #else #define TORRENT_CFG_DEPR deprecated_ #endif #define TORRENT_CFG \ BOOST_PP_CAT(TORRENT_CFG_IPV6, \ TORRENT_CFG_DEPR) #define TORRENT_CFG_STRING BOOST_PP_STRINGIZE(TORRENT_CFG) #endif <commit_msg>fix typo<commit_after>/* Copyright (c) 2010-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BUILD_CONFIG_HPP_INCLUDED #define TORRENT_BUILD_CONFIG_HPP_INCLUDED #include "libtorrent/config.hpp" #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/stringize.hpp> #if TORRENT_USE_IPV6 #define TORRENT_CFG_IPV6 ipv6_ #else #define TORRENT_CFG_IPV6 noipv6_ #endif #ifdef TORRENT_NO_DEPRECATE #define TORRENT_CFG_DEPR nodeprecate_ #else #define TORRENT_CFG_DEPR deprecated_ #endif #define TORRENT_CFG \ BOOST_PP_CAT(TORRENT_CFG_IPV6, \ TORRENT_CFG_DEPR) #define TORRENT_CFG_STRING BOOST_PP_STRINGIZE(TORRENT_CFG) #endif <|endoftext|>
<commit_before>//! \brief A collection of constants for Nova to use #pragma once #include "nova_renderer/memory/bytes.hpp" using namespace nova::mem::operators; namespace nova::renderer { constexpr const char* MODEL_MATRIX_BUFFER_NAME = "NovaModelMatrixUBO"; constexpr const char* PER_FRAME_DATA_NAME = "NovaPerFrameUBO"; constexpr uint32_t AMD_PCI_VENDOR_ID = 0x1022; constexpr uint32_t INTEL_PCI_VENDOR_ID = 8086; constexpr uint32_t NVIDIA_PCI_VENDOR_ID = 0x10DE; constexpr uint32_t NUM_IN_FLIGHT_FRAMES = 3; constexpr mem::Bytes PER_FRAME_MEMORY_SIZE = 2_mb; constexpr const char* RENDERPACK_DIRECTORY = "shaderpacks"; constexpr const char* MATERIALS_DIRECTORY = "materials"; constexpr const char* SHADERS_DIRECTORY = "shaders"; constexpr const char* RENDERPACK_DESCRIPTOR_FILE = "renderpack.json"; constexpr const char* RESOURCES_FILE = "resources.json"; constexpr const char* MATERIAL_FILE_EXTENSION = ".mat"; /*! * \brief Name of Nova's white texture * * The white texture is a 4x4 texture where each texel has the RGBA value of (1, 1, 1, 1) */ constexpr const char* WHITE_TEXTURE_NAME = "NovaWhiteTexture"; /*! * \brief Name of Nova's gray texture * * The gray texture is a 4x4 texture where each texel has the RGBA value of (0.5, 0.5, 0.5, 0.5) */ constexpr const char* GRAY_TEXTURE_NAME = "NovaGrayTexture"; /*! * \brief Name of Nova's black texture * * The black texture is a 4x4 texture where each texel has the RGBA value of (0, 0, 0, 0) */ constexpr const char* BLACK_TEXTURE_NAME = "NovaBlackTexture"; /*! * \brief Name of the builtin pass Nova uses to render UI * * This pass reads from the writes to the backbuffer. UI renderpasses are expected to use something like blending or the stencil butter * to layer the UI on top of the 3D scene. */ constexpr const char* UI_RENDER_PASS_NAME = "NovaUI"; constexpr const char* UI_MATERIAL_NAME = "BestFriendGUI"; constexpr const char* UI_MATERIAL_PASS_NAME = "BestFriendGUI"; /*! * \brief Name of the render target that renderpacks must render to */ constexpr const char* SCENE_OUTPUT_RT_NAME = "NovaSceneOutput"; /*! * \brief Name of the UI render target * * All UI renderpasses MUST will render to this render target */ constexpr const char* UI_OUTPUT_RT_NAME = "NovaUiOutput"; /*! * \brief Name of the backbuffer * * Nova presents the backbuffer to the screen every frame. The builtin UI render pass adds the UI to the backbuffer after the rest of * the rendergraph has finished */ constexpr const char* BACKBUFFER_NAME = "NovaBackbuffer"; } // namespace nova::renderer <commit_msg>[util] Remove a Best Friend constaant that snuck in<commit_after>//! \brief A collection of constants for Nova to use #pragma once #include "nova_renderer/memory/bytes.hpp" using namespace nova::mem::operators; namespace nova::renderer { constexpr const char* MODEL_MATRIX_BUFFER_NAME = "NovaModelMatrixUBO"; constexpr const char* PER_FRAME_DATA_NAME = "NovaPerFrameUBO"; constexpr uint32_t AMD_PCI_VENDOR_ID = 0x1022; constexpr uint32_t INTEL_PCI_VENDOR_ID = 8086; constexpr uint32_t NVIDIA_PCI_VENDOR_ID = 0x10DE; constexpr uint32_t NUM_IN_FLIGHT_FRAMES = 3; constexpr mem::Bytes PER_FRAME_MEMORY_SIZE = 2_mb; constexpr const char* RENDERPACK_DIRECTORY = "shaderpacks"; constexpr const char* MATERIALS_DIRECTORY = "materials"; constexpr const char* SHADERS_DIRECTORY = "shaders"; constexpr const char* RENDERPACK_DESCRIPTOR_FILE = "renderpack.json"; constexpr const char* RESOURCES_FILE = "resources.json"; constexpr const char* MATERIAL_FILE_EXTENSION = ".mat"; /*! * \brief Name of Nova's white texture * * The white texture is a 4x4 texture where each texel has the RGBA value of (1, 1, 1, 1) */ constexpr const char* WHITE_TEXTURE_NAME = "NovaWhiteTexture"; /*! * \brief Name of Nova's gray texture * * The gray texture is a 4x4 texture where each texel has the RGBA value of (0.5, 0.5, 0.5, 0.5) */ constexpr const char* GRAY_TEXTURE_NAME = "NovaGrayTexture"; /*! * \brief Name of Nova's black texture * * The black texture is a 4x4 texture where each texel has the RGBA value of (0, 0, 0, 0) */ constexpr const char* BLACK_TEXTURE_NAME = "NovaBlackTexture"; /*! * \brief Name of the builtin pass Nova uses to render UI * * This pass reads from the writes to the backbuffer. UI renderpasses are expected to use something like blending or the stencil butter * to layer the UI on top of the 3D scene. */ constexpr const char* UI_RENDER_PASS_NAME = "NovaUI"; /*! * \brief Name of the renderpass that outputs to the backbuffer */ constexpr const char* BACKBUFFER_OUTPUT_RENDER_PASS_NAME = "BackbufferOutput"; /*! * \brief Name of the render target that renderpacks must render to */ constexpr const char* SCENE_OUTPUT_RT_NAME = "NovaSceneOutput"; /*! * \brief Name of the UI render target * * All UI renderpasses MUST will render to this render target */ constexpr const char* UI_OUTPUT_RT_NAME = "NovaUiOutput"; /*! * \brief Name of the backbuffer * * Nova presents the backbuffer to the screen every frame. The builtin UI render pass adds the UI to the backbuffer after the rest of * the rendergraph has finished */ constexpr const char* BACKBUFFER_NAME = "NovaBackbuffer"; } // namespace nova::renderer <|endoftext|>
<commit_before>#pragma once #include <deque> #include <forward_list> #include <list> #include <map> #include <memory> #include <queue> #include <set> #include <stack> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #ifdef PAJLADA_SETTINGS_BOOST_OPTIONAL #include <boost/optional.hpp> #else #include <optional> #endif namespace pajlada { namespace Settings { #ifdef PAJLADA_SETTINGS_BOOST_OPTIONAL template <typename T> using OptionalType = boost::optional<T>; const boost::none_t OptionalNull = boost::none; #else template <typename T> using OptionalType = std::optional<T>; const std::nullopt_t OptionalNull = std::nullopt; #endif template <typename Type> struct ValueResult { OptionalType<Type> value; int updateIteration; }; template <typename Type> inline bool operator==(const ValueResult<Type> &lhs, const ValueResult<Type> &rhs) { return std::tie(lhs.value, lhs.updateIteration) == std::tie(rhs.value, rhs.updateIteration); } enum class SettingOption : uint32_t { DoNotWriteToJSON = (1ull << 1ull), /// A remote setting is a setting that is never saved locally, nor registered locally with any callbacks or anything Remote = (1ull << 2ull), Default = 0, }; inline SettingOption operator|(const SettingOption &lhs, const SettingOption &rhs) { return static_cast<SettingOption>( (static_cast<uint64_t>(lhs) | static_cast<uint64_t>(rhs))); } inline SettingOption operator&(const SettingOption &lhs, const SettingOption &rhs) { return static_cast<SettingOption>( (static_cast<uint64_t>(lhs) & static_cast<uint64_t>(rhs))); } } // namespace Settings // specialize a type for all of the STL containers. namespace is_stl_container_impl { template <typename T> struct is_stl_container : std::false_type { }; template <typename T, std::size_t N> struct is_stl_container<std::array<T, N>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::vector<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::deque<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::list<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::forward_list<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::set<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::multiset<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::map<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::multimap<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_set<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_multiset<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_map<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_multimap<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::stack<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::queue<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::priority_queue<Args...>> : std::true_type { }; } // namespace is_stl_container_impl // type trait to utilize the implementation type traits as well as decay the type template <typename T> struct is_stl_container { static constexpr bool const value = is_stl_container_impl::is_stl_container<std::decay_t<T>>::value; }; } // namespace pajlada <commit_msg>reformat<commit_after>#pragma once #include <deque> #include <forward_list> #include <list> #include <map> #include <memory> #include <queue> #include <set> #include <stack> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #ifdef PAJLADA_SETTINGS_BOOST_OPTIONAL #include <boost/optional.hpp> #else #include <optional> #endif namespace pajlada { namespace Settings { #ifdef PAJLADA_SETTINGS_BOOST_OPTIONAL template <typename T> using OptionalType = boost::optional<T>; const boost::none_t OptionalNull = boost::none; #else template <typename T> using OptionalType = std::optional<T>; const std::nullopt_t OptionalNull = std::nullopt; #endif template <typename Type> struct ValueResult { OptionalType<Type> value; int updateIteration; }; template <typename Type> inline bool operator==(const ValueResult<Type> &lhs, const ValueResult<Type> &rhs) { return std::tie(lhs.value, lhs.updateIteration) == std::tie(rhs.value, rhs.updateIteration); } enum class SettingOption : uint32_t { DoNotWriteToJSON = (1ull << 1ull), /// A remote setting is a setting that is never saved locally, nor registered locally with any callbacks or anything Remote = (1ull << 2ull), Default = 0, }; inline SettingOption operator|(const SettingOption &lhs, const SettingOption &rhs) { return static_cast<SettingOption>( (static_cast<uint64_t>(lhs) | static_cast<uint64_t>(rhs))); } inline SettingOption operator&(const SettingOption &lhs, const SettingOption &rhs) { return static_cast<SettingOption>( (static_cast<uint64_t>(lhs) & static_cast<uint64_t>(rhs))); } } // namespace Settings // specialize a type for all of the STL containers. namespace is_stl_container_impl { template <typename T> struct is_stl_container : std::false_type { }; template <typename T, std::size_t N> struct is_stl_container<std::array<T, N>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::vector<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::deque<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::list<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::forward_list<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::set<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::multiset<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::map<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::multimap<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_set<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_multiset<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_map<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::unordered_multimap<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::stack<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::queue<Args...>> : std::true_type { }; template <typename... Args> struct is_stl_container<std::priority_queue<Args...>> : std::true_type { }; } // namespace is_stl_container_impl // type trait to utilize the implementation type traits as well as decay the type template <typename T> struct is_stl_container { static constexpr bool const value = is_stl_container_impl::is_stl_container<std::decay_t<T>>::value; }; } // namespace pajlada <|endoftext|>
<commit_before>/** ** \file object/urbi-exception.hxx ** \brief Implementation of UrbiException */ #ifndef OBJECT_URBI_EXCEPTION_HXX # define OBJECT_URBI_EXCEPTION_HXX # include <boost/format.hpp> namespace object { inline LookupError::LookupError (libport::Symbol slot) : UrbiException ((boost::format ("lookup failed: %1%") % slot.name_get()).str()) { } inline RedefinitionError::RedefinitionError (libport::Symbol slot) : UrbiException ((boost::format ("slot redefinition: %1%") % slot.name_get()).str()) { } inline PrimitiveError::PrimitiveError (const libport::Symbol primitive, const std::string& msg) : UrbiException(msg, primitive) { } inline StackExhaustedError::StackExhaustedError(const std::string& msg) : UrbiException(msg) { } inline WrongArgumentType::WrongArgumentType(const std::string& formal, const std::string& effective, const libport::Symbol fun) : UrbiException (std::string("unexpected argument type `") + effective + "', expected `" + formal + '\'', fun) { } inline WrongArgumentType::WrongArgumentType (const libport::Symbol fun) : UrbiException("unexpected void", fun) { } inline WrongArgumentCount::WrongArgumentCount(unsigned formal, unsigned effective, const libport::Symbol fun) : UrbiException((boost::format ("expected %1% arguments, given %2%") % (formal) % (effective)).str (), fun) { } inline WrongArgumentCount::WrongArgumentCount(unsigned minformal, unsigned maxformal, unsigned effective, const libport::Symbol fun) : UrbiException((boost::format("expected between %1% and %2% arguments, " "given %3%") % (minformal-1) % (maxformal-1) % (effective-1)).str(), fun) { } inline BadInteger::BadInteger(libport::ufloat effective, const libport::Symbol fun, std::string fmt) : UrbiException((boost::format(fmt) % effective).str(), fun) { } inline ImplicitTagComponentError::ImplicitTagComponentError(const ast::loc& l) : UrbiException("illegal component for implicit tag", l) { } inline SchedulingError::SchedulingError(const std::string& msg) : UrbiException(msg) { } inline InternalError::InternalError(const std::string& msg) : UrbiException(msg) { } inline ParserError::ParserError(const ast::loc& loc, const std::string& msg) : UrbiException(msg, loc) { } inline void check_arg_count(unsigned formal, unsigned effective, const libport::Symbol fun) { if (formal != effective) throw WrongArgumentCount(formal, effective, fun); } inline void check_arg_count(unsigned minformal, unsigned maxformal, unsigned effective, const libport::Symbol fun) { if (effective < minformal || maxformal < effective) throw WrongArgumentCount(minformal, maxformal, effective, fun); } inline bool UrbiException::was_displayed() const { return displayed_; } inline void UrbiException::set_displayed() { displayed_ = true; } } // namespace object #endif //! OBJECT_URBI_EXCEPTION_HXX <commit_msg>Print the right numbers in error message.<commit_after>/** ** \file object/urbi-exception.hxx ** \brief Implementation of UrbiException */ #ifndef OBJECT_URBI_EXCEPTION_HXX # define OBJECT_URBI_EXCEPTION_HXX # include <boost/format.hpp> namespace object { inline LookupError::LookupError (libport::Symbol slot) : UrbiException ((boost::format ("lookup failed: %1%") % slot.name_get()).str()) { } inline RedefinitionError::RedefinitionError (libport::Symbol slot) : UrbiException ((boost::format ("slot redefinition: %1%") % slot.name_get()).str()) { } inline PrimitiveError::PrimitiveError (const libport::Symbol primitive, const std::string& msg) : UrbiException(msg, primitive) { } inline StackExhaustedError::StackExhaustedError(const std::string& msg) : UrbiException(msg) { } inline WrongArgumentType::WrongArgumentType(const std::string& formal, const std::string& effective, const libport::Symbol fun) : UrbiException (std::string("unexpected argument type `") + effective + "', expected `" + formal + '\'', fun) { } inline WrongArgumentType::WrongArgumentType (const libport::Symbol fun) : UrbiException("unexpected void", fun) { } inline WrongArgumentCount::WrongArgumentCount(unsigned formal, unsigned effective, const libport::Symbol fun) : UrbiException((boost::format ("expected %1% arguments, given %2%") % (formal) % (effective)).str (), fun) { } inline WrongArgumentCount::WrongArgumentCount(unsigned minformal, unsigned maxformal, unsigned effective, const libport::Symbol fun) : UrbiException((boost::format("expected between %1% and %2% arguments, " "given %3%") % minformal % maxformal % effective).str(), fun) { } inline BadInteger::BadInteger(libport::ufloat effective, const libport::Symbol fun, std::string fmt) : UrbiException((boost::format(fmt) % effective).str(), fun) { } inline ImplicitTagComponentError::ImplicitTagComponentError(const ast::loc& l) : UrbiException("illegal component for implicit tag", l) { } inline SchedulingError::SchedulingError(const std::string& msg) : UrbiException(msg) { } inline InternalError::InternalError(const std::string& msg) : UrbiException(msg) { } inline ParserError::ParserError(const ast::loc& loc, const std::string& msg) : UrbiException(msg, loc) { } inline void check_arg_count(unsigned formal, unsigned effective, const libport::Symbol fun) { if (formal != effective) throw WrongArgumentCount(formal, effective, fun); } inline void check_arg_count(unsigned minformal, unsigned maxformal, unsigned effective, const libport::Symbol fun) { if (effective < minformal || maxformal < effective) throw WrongArgumentCount(minformal, maxformal, effective, fun); } inline bool UrbiException::was_displayed() const { return displayed_; } inline void UrbiException::set_displayed() { displayed_ = true; } } // namespace object #endif //! OBJECT_URBI_EXCEPTION_HXX <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgGA/GUIEventHandler> #include <osgGA/EventVisitor> using namespace osgGA; void GUIEventHandler::operator()(osg::Node* node, osg::NodeVisitor* nv) { osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(nv); if (ev && ev->getActionAdapter() && !ev->getEvents().empty()) { for(osgGA::EventQueue::Events::iterator itr = ev->getEvents().begin(); itr != ev->getEvents().end(); ++itr) { handleWithCheckAgainstIgnoreHandledEventsMask(*(*itr), *(ev->getActionAdapter()), node, nv); } } if (node->getNumChildrenRequiringEventTraversal()>0) traverse(node,nv); } void GUIEventHandler::event(osg::NodeVisitor* nv, osg::Drawable* drawable) { osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(nv); if (ev && ev->getActionAdapter() && !ev->getEvents().empty()) { for(osgGA::EventQueue::Events::iterator itr = ev->getEvents().begin(); itr != ev->getEvents().end(); ++itr) { handleWithCheckAgainstIgnoreHandledEventsMask(*(*itr), *(ev->getActionAdapter()), drawable, nv); } } } <commit_msg>From Serge Lages, "Currently if multiple event callbacks are nested on one node, only the first will be called. The proposed fix checks if there is a nested callback."<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgGA/GUIEventHandler> #include <osgGA/EventVisitor> using namespace osgGA; void GUIEventHandler::operator()(osg::Node* node, osg::NodeVisitor* nv) { osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(nv); if (ev && ev->getActionAdapter() && !ev->getEvents().empty()) { for(osgGA::EventQueue::Events::iterator itr = ev->getEvents().begin(); itr != ev->getEvents().end(); ++itr) { handleWithCheckAgainstIgnoreHandledEventsMask(*(*itr), *(ev->getActionAdapter()), node, nv); } } if (node->getNumChildrenRequiringEventTraversal()>0 || _nestedCallback.valid()) traverse(node,nv); } void GUIEventHandler::event(osg::NodeVisitor* nv, osg::Drawable* drawable) { osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(nv); if (ev && ev->getActionAdapter() && !ev->getEvents().empty()) { for(osgGA::EventQueue::Events::iterator itr = ev->getEvents().begin(); itr != ev->getEvents().end(); ++itr) { handleWithCheckAgainstIgnoreHandledEventsMask(*(*itr), *(ev->getActionAdapter()), drawable, nv); } } } <|endoftext|>
<commit_before>#include "gvki/Logger.h" #include <cstdlib> #include <cstdio> #include <cassert> #include <errno.h> #include <iostream> #include <iomanip> #include <sstream> #include "string.h" #include "gvki/Debug.h" // For mkdir(). FIXME: Make windows compatible #include <sys/stat.h> // For opendir(). FIXME: Make windows compatible #include <dirent.h> // For getcwd() #include <unistd.h> #define FILE_SEP "/" using namespace std; using namespace gvki; // Maximum number of files or directories // that can be created static const int maxFiles = 10000; Logger& Logger::Singleton() { static Logger l; return l; } Logger::Logger() { int count = 0; bool success= false; // FIXME: Reading from the environment probably doesn't belong in here // but it makes implementing the singleton a lot easier std::string directoryPrefix; const char* envTemp = getenv("GVKI_ROOT"); if (envTemp) { DEBUG_MSG("Using GVKI_ROOT value as destination for directories"); DIR* dh = opendir(envTemp); if (dh == NULL) { ERROR_MSG(strerror(errno) << ". Directory was :" << envTemp); exit(1); } else closedir(dh); directoryPrefix = envTemp; } else { // Use the current working directory DEBUG_MSG("Using current working directory as destination for directories"); // FIXME: Hard-coding this size is gross char cwdArray[1024]; char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char)); if (!cwdResult) { ERROR_MSG(strerror(errno) << ". Could not read the current working directory"); exit(1); } else directoryPrefix = cwdResult; } directoryPrefix += FILE_SEP "gvki"; DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\""); // Keep trying a directoryPrefix name with a number as suffix // until we find an available one or we exhaust the maximum // allowed number while (count < maxFiles) { stringstream ss; ss << directoryPrefix << "-" << count; ++count; // Make the directoryPrefix if (mkdir(ss.str().c_str(), 0770) != 0) { if (errno != EEXIST) { ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix); exit(1); } // It already exists, try again continue; } this->directory = ss.str(); success = true; break; } if (!success) { ERROR_MSG("Exhausted available directory names or couldn't create any"); exit(1); } openLog(); } void Logger::openLog() { // FIXME: We should use mkstemp() or something std::stringstream ss; ss << directory << FILE_SEP << "log.json"; output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate); if (! output->good()) { ERROR_MSG("Failed to create file (" << ss.str() << ") to write log to"); exit(1); } // Start of JSON array *output << "[" << std::endl; } void Logger::closeLog() { // End of JSON array *output << std::endl << "]"; output->close(); } Logger::~Logger() { closeLog(); delete output; } void Logger::dump(cl_kernel k) { // Output JSON format defined by // http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html KernelInfo& ki = kernels[k]; static bool isFirst = true; if (!isFirst) { // Emit array element seperator // to seperate from previous dump *output << "," << endl; isFirst = false; } *output << "{" << endl << "\"language\": \"OpenCL\"," << endl; std::string kernelSourceFile = dumpKernelSource(ki); *output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl; // Not officially supported but let's emit it anyway *output << "\"global_offset\": "; printJSONArray(ki.globalWorkOffset); *output << "," << endl; *output << "\"global_size\": "; printJSONArray(ki.globalWorkSize); *output << "," << endl; *output << "\"local_size\": "; printJSONArray(ki.localWorkSize); *output << "," << endl; assert(ki.globalWorkOffset.size() == ki.globalWorkSize.size() == ki.localWorkSize.size() && "dimension mismatch"); *output << "\"entry_point\": \"" << ki.entryPointName << "\""; // entry_point might be the last entry is there were no kernel args if (ki.arguments.size() == 0) *output << endl; else { *output << "," << endl << "\"kernel_arguments\": [ " << endl; for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex) { printJSONKernelArgumentInfo(ki.arguments[argIndex]); if (argIndex != (ki.arguments.size() -1)) *output << "," << endl; } *output << endl << "]" << endl; } *output << "}"; } void Logger::printJSONArray(std::vector<size_t>& array) { *output << "[ "; for (int index=0; index < array.size(); ++index) { *output << array[index]; if (index != (array.size() -1)) *output << ", "; } *output << "]"; } void Logger::printJSONKernelArgumentInfo(ArgInfo& ai) { *output << "{"; if (ai.argValue == NULL) { // NULL was passed to clSetKernelArg() // That implies its for unallocated memory *output << "\"type\": \"array\","; // If the arg is for local memory if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler)) { // We assume this means this arguments is for local memory // where size actually means the sizeof the underlying buffer // rather than the size of the type. *output << "\"size\" : " << ai.argSize; } *output << "}"; return; } // FIXME: // Eurgh... the spec says // ``` // If the argument is a buffer object, the arg_value pointer can be NULL or // point to a NULL value in which case a NULL value will be used as the // value for the argument declared as a pointer to __global or __constant // memory in the kernel. ``` // // This makes it impossible (seeing as we don't know which address space // the arguments are in) to work out the argument type once derefencing the // pointer and finding it's equal zero because it could be a scalar constant // (of value 0) or it could be an unintialised array! DEBUG_MSG("Note sizeof(cl_mem) == " << sizeof(cl_mem)); // Hack: // It's hard to determine what type the argument is. // We can't dereference the void* to check if // it points to cl_mem we previously stored // // In some implementations cl_mem will be a pointer // which poses a risk if a scalar parameter of the same size // as the pointer type. if (ai.argSize == sizeof(cl_mem)) { cl_mem mightBecl_mem = *((cl_mem*) ai.argValue); // We might be reading invalid data now if (buffers.count(mightBecl_mem) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"array\","; BufferInfo& bi = buffers[mightBecl_mem]; *output << "\"size\": " << bi.size << "}"; return; } } // FIXME: Check for cl_sampler // // I guess it's scalar??? *output << "\"type\": \"scalar\","; *output << " \"value\": \"0x"; // Print the value as hex uint8_t* asByte = (uint8_t*) ai.argValue; for (int byteIndex=0; byteIndex < ai.argSize; ++byteIndex) { *output << setw(2) << setfill('0') << std::hex << asByte[byteIndex]; } *output << "\"" << std::dec; //std::hex is sticky so switch back to decimal *output << "}"; return; } static bool file_exists(std::string& name) { ifstream f(name.c_str()); bool result = f.good(); f.close(); return result; } std::string Logger::dumpKernelSource(KernelInfo& ki) { int count = 0; bool success = false; // FIXME: I really want a std::unique_ptr std::ofstream* kos = 0; std::string theKernelPath; while (count < maxFiles) { stringstream ss; ss << ki.entryPointName << "." << count << ".cl"; ++count; std::string withDir = (directory + FILE_SEP) + ss.str(); if (!file_exists(withDir)) { kos = new std::ofstream(withDir.c_str()); if (!kos->good()) { kos->close(); delete kos; continue; } success = true; theKernelPath = ss.str(); break; } } if (!success) { ERROR_MSG("Failed to log kernel output"); return std::string("FIXME"); } // Write kernel source ProgramInfo& pi = programs[ki.program]; for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b) { *kos << *b; } // Urgh this is bad, need RAII! kos->close(); delete kos; return theKernelPath; } <commit_msg>Only emit global_offset when its non zero. This is to work around the fact that GPUVerify does not support this right now.<commit_after>#include "gvki/Logger.h" #include <cstdlib> #include <cstdio> #include <cassert> #include <errno.h> #include <iostream> #include <iomanip> #include <sstream> #include "string.h" #include "gvki/Debug.h" // For mkdir(). FIXME: Make windows compatible #include <sys/stat.h> // For opendir(). FIXME: Make windows compatible #include <dirent.h> // For getcwd() #include <unistd.h> #define FILE_SEP "/" using namespace std; using namespace gvki; // Maximum number of files or directories // that can be created static const int maxFiles = 10000; Logger& Logger::Singleton() { static Logger l; return l; } Logger::Logger() { int count = 0; bool success= false; // FIXME: Reading from the environment probably doesn't belong in here // but it makes implementing the singleton a lot easier std::string directoryPrefix; const char* envTemp = getenv("GVKI_ROOT"); if (envTemp) { DEBUG_MSG("Using GVKI_ROOT value as destination for directories"); DIR* dh = opendir(envTemp); if (dh == NULL) { ERROR_MSG(strerror(errno) << ". Directory was :" << envTemp); exit(1); } else closedir(dh); directoryPrefix = envTemp; } else { // Use the current working directory DEBUG_MSG("Using current working directory as destination for directories"); // FIXME: Hard-coding this size is gross char cwdArray[1024]; char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char)); if (!cwdResult) { ERROR_MSG(strerror(errno) << ". Could not read the current working directory"); exit(1); } else directoryPrefix = cwdResult; } directoryPrefix += FILE_SEP "gvki"; DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\""); // Keep trying a directoryPrefix name with a number as suffix // until we find an available one or we exhaust the maximum // allowed number while (count < maxFiles) { stringstream ss; ss << directoryPrefix << "-" << count; ++count; // Make the directoryPrefix if (mkdir(ss.str().c_str(), 0770) != 0) { if (errno != EEXIST) { ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix); exit(1); } // It already exists, try again continue; } this->directory = ss.str(); success = true; break; } if (!success) { ERROR_MSG("Exhausted available directory names or couldn't create any"); exit(1); } openLog(); } void Logger::openLog() { // FIXME: We should use mkstemp() or something std::stringstream ss; ss << directory << FILE_SEP << "log.json"; output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate); if (! output->good()) { ERROR_MSG("Failed to create file (" << ss.str() << ") to write log to"); exit(1); } // Start of JSON array *output << "[" << std::endl; } void Logger::closeLog() { // End of JSON array *output << std::endl << "]"; output->close(); } Logger::~Logger() { closeLog(); delete output; } void Logger::dump(cl_kernel k) { // Output JSON format defined by // http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html KernelInfo& ki = kernels[k]; static bool isFirst = true; if (!isFirst) { // Emit array element seperator // to seperate from previous dump *output << "," << endl; isFirst = false; } *output << "{" << endl << "\"language\": \"OpenCL\"," << endl; std::string kernelSourceFile = dumpKernelSource(ki); *output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl; // FIXME: Teach GPUVerify how to handle non zero global_offset // FIXME: Document this json attribute! // Only emit global_offset if its non zero bool hasNonZeroGlobalOffset = false; for (int index=0; index < ki.globalWorkOffset.size() ; ++index) { if (ki.globalWorkOffset[index] != 0) hasNonZeroGlobalOffset = true; } if (hasNonZeroGlobalOffset) { *output << "\"global_offset\": "; printJSONArray(ki.globalWorkOffset); *output << "," << endl; } *output << "\"global_size\": "; printJSONArray(ki.globalWorkSize); *output << "," << endl; *output << "\"local_size\": "; printJSONArray(ki.localWorkSize); *output << "," << endl; assert(ki.globalWorkOffset.size() == ki.globalWorkSize.size() == ki.localWorkSize.size() && "dimension mismatch"); *output << "\"entry_point\": \"" << ki.entryPointName << "\""; // entry_point might be the last entry is there were no kernel args if (ki.arguments.size() == 0) *output << endl; else { *output << "," << endl << "\"kernel_arguments\": [ " << endl; for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex) { printJSONKernelArgumentInfo(ki.arguments[argIndex]); if (argIndex != (ki.arguments.size() -1)) *output << "," << endl; } *output << endl << "]" << endl; } *output << "}"; } void Logger::printJSONArray(std::vector<size_t>& array) { *output << "[ "; for (int index=0; index < array.size(); ++index) { *output << array[index]; if (index != (array.size() -1)) *output << ", "; } *output << "]"; } void Logger::printJSONKernelArgumentInfo(ArgInfo& ai) { *output << "{"; if (ai.argValue == NULL) { // NULL was passed to clSetKernelArg() // That implies its for unallocated memory *output << "\"type\": \"array\","; // If the arg is for local memory if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler)) { // We assume this means this arguments is for local memory // where size actually means the sizeof the underlying buffer // rather than the size of the type. *output << "\"size\" : " << ai.argSize; } *output << "}"; return; } // FIXME: // Eurgh... the spec says // ``` // If the argument is a buffer object, the arg_value pointer can be NULL or // point to a NULL value in which case a NULL value will be used as the // value for the argument declared as a pointer to __global or __constant // memory in the kernel. ``` // // This makes it impossible (seeing as we don't know which address space // the arguments are in) to work out the argument type once derefencing the // pointer and finding it's equal zero because it could be a scalar constant // (of value 0) or it could be an unintialised array! DEBUG_MSG("Note sizeof(cl_mem) == " << sizeof(cl_mem)); // Hack: // It's hard to determine what type the argument is. // We can't dereference the void* to check if // it points to cl_mem we previously stored // // In some implementations cl_mem will be a pointer // which poses a risk if a scalar parameter of the same size // as the pointer type. if (ai.argSize == sizeof(cl_mem)) { cl_mem mightBecl_mem = *((cl_mem*) ai.argValue); // We might be reading invalid data now if (buffers.count(mightBecl_mem) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"array\","; BufferInfo& bi = buffers[mightBecl_mem]; *output << "\"size\": " << bi.size << "}"; return; } } // FIXME: Check for cl_sampler // // I guess it's scalar??? *output << "\"type\": \"scalar\","; *output << " \"value\": \"0x"; // Print the value as hex uint8_t* asByte = (uint8_t*) ai.argValue; for (int byteIndex=0; byteIndex < ai.argSize; ++byteIndex) { *output << setw(2) << setfill('0') << std::hex << asByte[byteIndex]; } *output << "\"" << std::dec; //std::hex is sticky so switch back to decimal *output << "}"; return; } static bool file_exists(std::string& name) { ifstream f(name.c_str()); bool result = f.good(); f.close(); return result; } std::string Logger::dumpKernelSource(KernelInfo& ki) { int count = 0; bool success = false; // FIXME: I really want a std::unique_ptr std::ofstream* kos = 0; std::string theKernelPath; while (count < maxFiles) { stringstream ss; ss << ki.entryPointName << "." << count << ".cl"; ++count; std::string withDir = (directory + FILE_SEP) + ss.str(); if (!file_exists(withDir)) { kos = new std::ofstream(withDir.c_str()); if (!kos->good()) { kos->close(); delete kos; continue; } success = true; theKernelPath = ss.str(); break; } } if (!success) { ERROR_MSG("Failed to log kernel output"); return std::string("FIXME"); } // Write kernel source ProgramInfo& pi = programs[ki.program]; for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b) { *kos << *b; } // Urgh this is bad, need RAII! kos->close(); delete kos; return theKernelPath; } <|endoftext|>
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <GC/GC.hh> #include <Object/UpvalueObject.hh> namespace Tadpole::Object { str_t UpvalueObject::stringify() const { ss_t ss; ss << "<upvalue at `" << this << "`>"; return ss.str(); } void UpvalueObject::iter_children(ObjectVisitor&& visitor) { visitor(closed_.as_object(safe_t())); } UpvalueObject* UpvalueObject::create(Value::Value* value, UpvalueObject* next) { return GC::make_object<UpvalueObject>(value, next); } } <commit_msg>:construction: chore(upvalue-object): updated the implementation of upvalue object<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <GC/GC.hh> #include <Object/UpvalueObject.hh> namespace Tadpole::Object { str_t UpvalueObject::stringify() const { ss_t ss; ss << "<upvalue at `" << this << "`>"; return ss.str(); } void UpvalueObject::iter_children(ObjectVisitor&& visitor) { visitor(closed_.as_object(kSafePlaceholder)); } UpvalueObject* UpvalueObject::create(Value::Value* value, UpvalueObject* next) { return GC::make_object<UpvalueObject>(value, next); } } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <string> class Elem {}; class FaceInfo {}; class Variable { double _x; public: Variable(const double x) : _x(x) {} double operator()(const Elem & elem) const { return _x; } double operator()(const FaceInfo & fi) const { return _x; } double operator()(const unsigned int qp) const { return _x; } }; class MaterialProperty { public: using ElemFn = std::function<double(const Elem &)>; using FiFn = std::function<double(const FaceInfo &)>; using QpFn = std::function<double(const unsigned int &)>; template <typename PolymorphicLambda> MaterialProperty & operator=(PolymorphicLambda my_lammy) { elem_functor = my_lammy; fi_functor = my_lammy; qp_functor = my_lammy; return *this; } double operator()(const Elem & elem) const { return elem_functor(elem); } double operator()(const FaceInfo & fi) const { return fi_functor(fi); } double operator()(const unsigned int qp) const { return qp_functor(qp); } private: ElemFn elem_functor; FiFn fi_functor; QpFn qp_functor; }; class Material { public: Material() { Variable u(2); _mat_props["u2"] = [&u](const auto & geom_entity) -> double { return u(geom_entity) * u(geom_entity); }; _mat_props["u3"] = [&u](const auto & geom_entity) -> double { return u(geom_entity) * u(geom_entity) * u(geom_entity); }; } const MaterialProperty & getMatProp(const std::string & name) const { return _mat_props.at(name); } private: std::map<std::string, MaterialProperty> _mat_props; }; class ResidualObject { public: void assignMatProp(const MaterialProperty & prop) { _mat_prop = &prop; } protected: const MaterialProperty * _mat_prop; }; class Kernel : public ResidualObject { public: void computeResidual(const Elem & elem) { std::cout << (*_mat_prop)(elem) << std::endl; } }; class FVFluxKernel : public ResidualObject { public: void computeResidual(const FaceInfo & fi) { std::cout << (*_mat_prop)(fi) << std::endl; } }; int main() { Material mat; Kernel kern; kern.assignMatProp(mat.getMatProp("u2")); FVFluxKernel fv; fv.assignMatProp(mat.getMatProp("u3")); kern.computeResidual(Elem()); fv.computeResidual(FaceInfo()); } <commit_msg>eliminate dangling reference<commit_after>#include <iostream> #include <map> #include <string> #include <functional> class Elem { }; class FaceInfo { }; class Variable { double _x; public: Variable(const double x) : _x(x) {} double operator()(const Elem & elem) const { return _x; } double operator()(const FaceInfo & fi) const { return _x; } double operator()(const unsigned int qp) const { return _x; } }; class MaterialProperty { public: using ElemFn = std::function<double(const Elem &)>; using FiFn = std::function<double(const FaceInfo &)>; using QpFn = std::function<double(const unsigned int &)>; template <typename PolymorphicLambda> MaterialProperty & operator=(PolymorphicLambda my_lammy) { elem_functor = my_lammy; fi_functor = my_lammy; qp_functor = my_lammy; return *this; } double operator()(const Elem & elem) const { return elem_functor(elem); } double operator()(const FaceInfo & fi) const { return fi_functor(fi); } double operator()(const unsigned int qp) const { return qp_functor(qp); } private: ElemFn elem_functor; FiFn fi_functor; QpFn qp_functor; }; class Material { public: Material() : _u(2) { _mat_props["u2"] = [this](const auto & geom_entity) -> double { return _u(geom_entity) * _u(geom_entity); }; _mat_props["u3"] = [this](const auto & geom_entity) -> double { return _u(geom_entity) * _u(geom_entity) * _u(geom_entity); }; } const MaterialProperty & getMatProp(const std::string & name) const { return _mat_props.at(name); } private: std::map<std::string, MaterialProperty> _mat_props; Variable _u; }; class ResidualObject { public: void assignMatProp(const MaterialProperty & prop) { _mat_prop = &prop; } protected: const MaterialProperty * _mat_prop; }; class Kernel : public ResidualObject { public: void computeResidual(const Elem & elem) { std::cout << (*_mat_prop)(elem) << std::endl; } }; class FVFluxKernel : public ResidualObject { public: void computeResidual(const FaceInfo & fi) { std::cout << (*_mat_prop)(fi) << std::endl; } }; int main() { Material mat; Kernel kern; kern.assignMatProp(mat.getMatProp("u2")); FVFluxKernel fv; fv.assignMatProp(mat.getMatProp("u3")); kern.computeResidual(Elem()); fv.computeResidual(FaceInfo()); } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2020 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include <string> #include <vector> #include "tests/utils/Gmock.h" #include "tests/utils/Gtest.h" #include "joynr/BroadcastFilterParameters.h" #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/ImmutableMessage.h" #include "joynr/Message.h" #include "joynr/MessageSender.h" #include "joynr/MessagingQos.h" #include "joynr/MulticastSubscriptionQos.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/MutableMessage.h" #include "joynr/MutableMessageFactory.h" #include "joynr/OnChangeSubscriptionQos.h" #include "joynr/PeriodicSubscriptionQos.h" #include "joynr/Reply.h" #include "joynr/Request.h" #include "joynr/SingleThreadedIOService.h" #include "joynr/SubscriptionPublication.h" #include "joynr/SubscriptionReply.h" #include "joynr/SubscriptionRequest.h" #include "tests/JoynrTest.h" #include "tests/mock/MockDispatcher.h" #include "tests/mock/MockMessageRouter.h" #include "tests/mock/MockMessagingStub.h" using ::testing::_; using ::testing::A; using ::testing::AllOf; using ::testing::Eq; using ::testing::NotNull; using ::testing::Property; using namespace joynr; class MessageSenderTest : public ::testing::Test { public: MessageSenderTest() : messageFactory(), postFix(), senderID(), receiverID(), requestID(), qosSettings(), mockDispatcher(std::make_shared<MockDispatcher>()), mockMessagingStub(), callBack(), singleThreadedIOService(std::make_shared<SingleThreadedIOService>()), mockMessageRouter( std::make_shared<MockMessageRouter>(singleThreadedIOService->getIOService())), isLocalMessage(true) { singleThreadedIOService->start(); } ~MessageSenderTest() { singleThreadedIOService->stop(); } void SetUp() { postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; requestID = "requestId" + postFix; qosSettings = MessagingQos(456000); } void expectRoutedMessage(const std::string& type, const std::string& payload) { EXPECT_CALL(*(mockMessageRouter.get()), route(AllOf(MessageHasType(type), ImmutableMessageHasPayload(payload)), _)); } protected: MutableMessageFactory messageFactory; std::string postFix; std::string senderID; std::string receiverID; std::string requestID; MessagingQos qosSettings; std::shared_ptr<MockDispatcher> mockDispatcher; MockMessagingStub mockMessagingStub; std::shared_ptr<IReplyCaller> callBack; std::shared_ptr<SingleThreadedIOService> singleThreadedIOService; std::shared_ptr<MockMessageRouter> mockMessageRouter; const bool isLocalMessage; }; typedef MessageSenderTest MessageSenderDeathTest; TEST_F(MessageSenderTest, sendRequest_normal) { Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); request.setParamDatatypes(paramDatatypes); MutableMessage mutableMessage = messageFactory.createRequest( senderID, receiverID, qosSettings, request, isLocalMessage); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_REQUEST(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendRequest(senderID, receiverID, qosSettings, request, callBack, isLocalMessage); } TEST_F(MessageSenderTest, sendOneWayRequest_normal) { OneWayRequest oneWayRequest; oneWayRequest.setMethodName("methodName"); oneWayRequest.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); oneWayRequest.setParamDatatypes(paramDatatypes); MutableMessage mutableMessage = messageFactory.createOneWayRequest( senderID, receiverID, qosSettings, oneWayRequest, isLocalMessage); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_ONE_WAY(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendOneWayRequest( senderID, receiverID, qosSettings, oneWayRequest, isLocalMessage); } TEST_F(MessageSenderTest, sendReply_normal) { MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); Reply reply; reply.setRequestReplyId(util::createUuid()); reply.setResponse(std::string("response")); MutableMessage mutableMessage = messageFactory.createReply(senderID, receiverID, qosSettings, {}, reply); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_REPLY(), mutableMessage.getPayload()); messageSender.sendReply(senderID, receiverID, qosSettings, {}, reply); } TEST_F(MessageSenderTest, sendSubscriptionRequest_normal) { std::int64_t period = 2000; std::int64_t validity = 100000; std::int64_t publicationTtl = 1000; std::int64_t alert = 4000; auto qos = std::make_shared<PeriodicSubscriptionQos>(validity, publicationTtl, period, alert); SubscriptionRequest subscriptionRequest; subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("attributeName"); subscriptionRequest.setQos(qos); MutableMessage mutableMessage = messageFactory.createSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); expectRoutedMessage( Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); } TEST_F(MessageSenderTest, sendBroadcastSubscriptionRequest_normal) { std::int64_t minInterval = 2000; std::int64_t validity = 100000; std::int64_t publicationTtl = 1000; auto qos = std::make_shared<OnChangeSubscriptionQos>(validity, publicationTtl, minInterval); BroadcastSubscriptionRequest subscriptionRequest; BroadcastFilterParameters filter; filter.setFilterParameter("MyParameter", "MyValue"); subscriptionRequest.setFilterParameters(filter); subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("broadcastName"); subscriptionRequest.setQos(qos); MutableMessage mutableMessage = messageFactory.createBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); } // TODO implement sending a reply to a subscription request! TEST_F(MessageSenderTest, DISABLED_sendSubscriptionReply_normal) { std::string payload("subscriptionReply"); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY(), payload); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); // messageSender.sendSubscriptionReply(util::createUuid(), payload, senderID, receiverID, // qosSettings); } TEST_F(MessageSenderTest, removeRoutingEntry) { std::string participantId("participantId"); EXPECT_CALL(*(mockMessageRouter.get()), removeNextHop(participantId, _, _)); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.removeRoutingEntry(participantId); } TEST_F(MessageSenderTest, sendPublication_normal) { MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); SubscriptionPublication publication; publication.setSubscriptionId("ignoresubscriptionid"); publication.setResponse(std::string("publication")); MutableMessage mutableMessage = messageFactory.createSubscriptionPublication( senderID, receiverID, qosSettings, publication); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_PUBLICATION(), mutableMessage.getPayload()); messageSender.sendSubscriptionPublication( senderID, receiverID, qosSettings, std::move(publication)); } TEST_F(MessageSenderTest, sendMulticastSubscriptionRequest) { const std::string senderParticipantId("senderParticipantId"); const std::string receiverParticipantId("receiverParticipantId"); const std::string subscriptionId("subscriptionId"); MessagingQos messagingQos(1, MessagingQosEffort::Enum::BEST_EFFORT); auto subscriptionQos = std::make_shared<MulticastSubscriptionQos>(); MulticastSubscriptionRequest subscriptionRequest; subscriptionRequest.setSubscribeToName("subscribeToName"); subscriptionRequest.setSubscriptionId(subscriptionId); subscriptionRequest.setQos(subscriptionQos); subscriptionRequest.setMulticastId("multicastId"); MutableMessage mutableMessage = messageFactory.createMulticastSubscriptionRequest(senderParticipantId, receiverParticipantId, messagingQos, subscriptionRequest, isLocalMessage); SubscriptionReply subscriptionReply; subscriptionReply.setSubscriptionId("subscriptionId"); MutableMessage mutableReplyMessage = messageFactory.createSubscriptionReply( receiverParticipantId, senderParticipantId, messagingQos, subscriptionReply); expectRoutedMessage( Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY(), mutableReplyMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.sendMulticastSubscriptionRequest(senderParticipantId, receiverParticipantId, messagingQos, subscriptionRequest, isLocalMessage); } <commit_msg>[c++] Fix MessageSenderTest<commit_after>/* * #%L * %% * Copyright (C) 2020 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include <string> #include <vector> #include "tests/utils/Gmock.h" #include "tests/utils/Gtest.h" #include "joynr/BroadcastFilterParameters.h" #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/ImmutableMessage.h" #include "joynr/Message.h" #include "joynr/MessageSender.h" #include "joynr/MessagingQos.h" #include "joynr/MulticastSubscriptionQos.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/MutableMessage.h" #include "joynr/MutableMessageFactory.h" #include "joynr/OnChangeSubscriptionQos.h" #include "joynr/PeriodicSubscriptionQos.h" #include "joynr/Reply.h" #include "joynr/Request.h" #include "joynr/SingleThreadedIOService.h" #include "joynr/SubscriptionPublication.h" #include "joynr/SubscriptionReply.h" #include "joynr/SubscriptionRequest.h" #include "tests/JoynrTest.h" #include "tests/mock/MockDispatcher.h" #include "tests/mock/MockMessageRouter.h" #include "tests/mock/MockMessagingStub.h" using ::testing::_; using ::testing::A; using ::testing::AllOf; using ::testing::Eq; using ::testing::NotNull; using ::testing::Property; using namespace joynr; class MessageSenderTest : public ::testing::Test { public: MessageSenderTest() : messageFactory(), postFix(), senderID(), receiverID(), requestID(), qosSettings(), mockDispatcher(std::make_shared<MockDispatcher>()), mockMessagingStub(), callBack(), singleThreadedIOService(std::make_shared<SingleThreadedIOService>()), mockMessageRouter( std::make_shared<MockMessageRouter>(singleThreadedIOService->getIOService())), isLocalMessage(true) { singleThreadedIOService->start(); } ~MessageSenderTest() { singleThreadedIOService->stop(); } void SetUp() { postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; requestID = "requestId" + postFix; qosSettings = MessagingQos(456000); } void expectRoutedMessage(const std::string& type, const std::string& payload) { EXPECT_CALL(*(mockMessageRouter.get()), route(AllOf(MessageHasType(type), ImmutableMessageHasPayload(payload)), _)); } protected: MutableMessageFactory messageFactory; std::string postFix; std::string senderID; std::string receiverID; std::string requestID; MessagingQos qosSettings; std::shared_ptr<MockDispatcher> mockDispatcher; MockMessagingStub mockMessagingStub; std::shared_ptr<IReplyCaller> callBack; std::shared_ptr<SingleThreadedIOService> singleThreadedIOService; std::shared_ptr<MockMessageRouter> mockMessageRouter; const bool isLocalMessage; }; typedef MessageSenderTest MessageSenderDeathTest; TEST_F(MessageSenderTest, sendRequest_normal) { Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); request.setParamDatatypes(paramDatatypes); MutableMessage mutableMessage = messageFactory.createRequest( senderID, receiverID, qosSettings, request, isLocalMessage); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_REQUEST(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendRequest(senderID, receiverID, qosSettings, request, callBack, isLocalMessage); } TEST_F(MessageSenderTest, sendOneWayRequest_normal) { OneWayRequest oneWayRequest; oneWayRequest.setMethodName("methodName"); oneWayRequest.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); oneWayRequest.setParamDatatypes(paramDatatypes); MutableMessage mutableMessage = messageFactory.createOneWayRequest( senderID, receiverID, qosSettings, oneWayRequest, isLocalMessage); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_ONE_WAY(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendOneWayRequest( senderID, receiverID, qosSettings, oneWayRequest, isLocalMessage); } TEST_F(MessageSenderTest, sendReply_normal) { Reply reply; reply.setRequestReplyId(util::createUuid()); reply.setResponse(std::string("response")); MutableMessage mutableMessage = messageFactory.createReply(senderID, receiverID, qosSettings, {}, reply); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_REPLY(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendReply(senderID, receiverID, qosSettings, {}, reply); } TEST_F(MessageSenderTest, sendSubscriptionRequest_normal) { std::int64_t period = 2000; std::int64_t validity = 100000; std::int64_t publicationTtl = 1000; std::int64_t alert = 4000; auto qos = std::make_shared<PeriodicSubscriptionQos>(validity, publicationTtl, period, alert); SubscriptionRequest subscriptionRequest; subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("attributeName"); subscriptionRequest.setQos(qos); MutableMessage mutableMessage = messageFactory.createSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); expectRoutedMessage( Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); } TEST_F(MessageSenderTest, sendBroadcastSubscriptionRequest_normal) { std::int64_t minInterval = 2000; std::int64_t validity = 100000; std::int64_t publicationTtl = 1000; auto qos = std::make_shared<OnChangeSubscriptionQos>(validity, publicationTtl, minInterval); BroadcastSubscriptionRequest subscriptionRequest; BroadcastFilterParameters filter; filter.setFilterParameter("MyParameter", "MyValue"); subscriptionRequest.setFilterParameters(filter); subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("broadcastName"); subscriptionRequest.setQos(qos); MutableMessage mutableMessage = messageFactory.createBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest, isLocalMessage); } // TODO implement sending a reply to a subscription request! TEST_F(MessageSenderTest, DISABLED_sendSubscriptionReply_normal) { std::string payload("subscriptionReply"); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY(), payload); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); // messageSender.sendSubscriptionReply(util::createUuid(), payload, senderID, receiverID, // qosSettings); } TEST_F(MessageSenderTest, removeRoutingEntry) { std::string participantId("participantId"); EXPECT_CALL(*(mockMessageRouter.get()), removeNextHop(participantId, _, _)); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.removeRoutingEntry(participantId); } TEST_F(MessageSenderTest, sendPublication_normal) { SubscriptionPublication publication; publication.setSubscriptionId("ignoresubscriptionid"); publication.setResponse(std::string("publication")); MutableMessage mutableMessage = messageFactory.createSubscriptionPublication( senderID, receiverID, qosSettings, publication); expectRoutedMessage(Message::VALUE_MESSAGE_TYPE_PUBLICATION(), mutableMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.registerDispatcher(mockDispatcher); messageSender.sendSubscriptionPublication( senderID, receiverID, qosSettings, std::move(publication)); } TEST_F(MessageSenderTest, sendMulticastSubscriptionRequest) { const std::string senderParticipantId("senderParticipantId"); const std::string receiverParticipantId("receiverParticipantId"); const std::string subscriptionId("subscriptionId"); MessagingQos messagingQos(1, MessagingQosEffort::Enum::BEST_EFFORT); auto subscriptionQos = std::make_shared<MulticastSubscriptionQos>(); MulticastSubscriptionRequest subscriptionRequest; subscriptionRequest.setSubscribeToName("subscribeToName"); subscriptionRequest.setSubscriptionId(subscriptionId); subscriptionRequest.setQos(subscriptionQos); subscriptionRequest.setMulticastId("multicastId"); MutableMessage mutableMessage = messageFactory.createMulticastSubscriptionRequest(senderParticipantId, receiverParticipantId, messagingQos, subscriptionRequest, isLocalMessage); SubscriptionReply subscriptionReply; subscriptionReply.setSubscriptionId("subscriptionId"); MutableMessage mutableReplyMessage = messageFactory.createSubscriptionReply( receiverParticipantId, senderParticipantId, messagingQos, subscriptionReply); expectRoutedMessage( Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY(), mutableReplyMessage.getPayload()); MessageSender messageSender(mockMessageRouter, nullptr); messageSender.sendMulticastSubscriptionRequest(senderParticipantId, receiverParticipantId, messagingQos, subscriptionRequest, isLocalMessage); } <|endoftext|>
<commit_before>/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "saiga/image/freeimage.h" #include "saiga/util/assert.h" #ifdef SAIGA_USE_FREEIMAGE #include <FreeImagePlus.h> #include <cstring> namespace Saiga { namespace FIP { bool load(const std::string &path, Image &img, ImageMetadata *metaData) { fipImage fimg; if(!loadFIP(path,fimg)){ return false; } if(metaData){ getMetaData(fimg,*metaData); // printAllMetaData(fimg); } convert(fimg,img); return true; } bool save(const std::string &path, const Image &img) { fipImage fimg; convert(img,fimg); return saveFIP(path,fimg); } bool loadFIP(const std::string &path, fipImage &img){ auto ret = img.load(path.c_str(),JPEG_EXIFROTATE); return ret; } bool saveFIP(const std::string &path, const fipImage &img){ auto ret = img.save(path.c_str()); return ret; } void convert(const Image &_src, fipImage &dest) { auto src = _src; #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR if(src.type == UC3) { ImageView<ucvec3> img = src.getImageView<ucvec3>(); img.swapChannels(0,2); } if(src.type == UC4) { ImageView<ucvec4> img = src.getImageView<ucvec4>(); img.swapChannels(0,2); } #endif int bpp = elementSize(src.type) * 8; FREE_IMAGE_TYPE t = FIT_BITMAP; switch(_src.type) { case US1: t = FIT_UINT16; break; default: break; } auto res = dest.setSize( t, src.width,src.height, bpp ); SAIGA_ASSERT(res); for(int i =0; i < src.rows; ++i) { memcpy(dest.getScanLine(i),src.rowPtr(i), std::min<int>(dest.getScanWidth(),src.pitchBytes)); } } void convert(const fipImage &src, Image& dest){ SAIGA_ASSERT(src.isValid()); dest.width = src.getWidth(); dest.height = src.getHeight(); int channels = -1; switch(src.getColorType()){ case FIC_MINISBLACK: channels = 1; break; case FIC_RGB: channels = 3; break; case FIC_RGBALPHA: channels = 4; break; default: break; } SAIGA_ASSERT(channels != -1); if(src.getBitsPerPixel() == 32 && channels ==3) { channels = 4; } int bitDepth= src.getBitsPerPixel() / channels; ImageElementType elementType = IET_ELEMENT_UNKNOWN; switch(bitDepth) { case 8: elementType = IET_UCHAR; break; case 16: elementType = IET_USHORT; break; case 32: elementType = IET_UINT; break; } SAIGA_ASSERT(elementType != IET_ELEMENT_UNKNOWN); // cout << "Channels: " << format.getChannels() << " BitsPerPixel: " << src.getBitsPerPixel() << " Bitdepth: " << format.getBitDepth() << endl; // cout << format << endl; dest.type = getType(channels,elementType); dest.create(); for(int i =0; i < dest.rows; ++i) { memcpy(dest.rowPtr(i),src.getScanLine(i), std::min<int>(dest.pitchBytes,src.getScanWidth())); } #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR if(dest.type == UC3) { ImageView<ucvec3> img = dest.getImageView<ucvec3>(); img.swapChannels(0,2); } if(dest.type == UC4) { ImageView<ucvec4> img = dest.getImageView<ucvec4>(); img.swapChannels(0,2); } #endif } #endif static double parseFraction(const void* data){ const int* idata = reinterpret_cast<const int*>(data); return double(idata[0]) / double(idata[1]); } void getMetaData(fipImage &img, ImageMetadata& metaData){ metaData.width = img.getWidth(); metaData.height = img.getHeight(); fipTag tag; fipMetadataFind finder; if( finder.findFirstMetadata(FIMD_EXIF_MAIN, img, tag) ) { do { std::string t = tag.getKey(); if(t == "DateTime"){ metaData.DateTime = tag.toString(FIMD_EXIF_MAIN); }else if(t == "Make"){ metaData.Make = (char*)tag.getValue(); }else if(t == "Model"){ metaData.Model = (char*)tag.getValue(); }else{ // cout << "Tag: " << tag.getKey() << " Value: " << tag.toString(FIMD_EXIF_MAIN) << endl; } } while( finder.findNextMetadata(tag) ); } // the class can be called again with another metadata model if( finder.findFirstMetadata(FIMD_EXIF_EXIF, img, tag) ) { do { std::string t = tag.getKey(); if(t == "FocalLength"){ metaData.FocalLengthMM = parseFraction(tag.getValue()); }else if(t == "FocalLengthIn35mmFilm"){ metaData.FocalLengthMM35 = reinterpret_cast<const short*>(tag.getValue())[0]; }else if(t == "FocalPlaneResolutionUnit"){ metaData.FocalPlaneResolutionUnit = (ImageMetadata::ResolutionUnit) reinterpret_cast<const short*>(tag.getValue())[0]; }else if(t == "FocalPlaneXResolution"){ metaData.FocalPlaneXResolution = parseFraction(tag.getValue()); }else if(t == "FocalPlaneYResolution"){ metaData.FocalPlaneYResolution = parseFraction(tag.getValue()); }else{ // cout << "Tag: " << tag.getKey() << " Value: " << tag.toString(FIMD_EXIF_MAIN) << endl; } } while( finder.findNextMetadata(tag) ); } } void printAllMetaData(fipImage &img) { for(int i = -1; i <= 11; ++i){ FREE_IMAGE_MDMODEL model = (FREE_IMAGE_MDMODEL)i; cout << "Model: " << model << endl; fipTag tag; fipMetadataFind finder; if( finder.findFirstMetadata(model, img, tag) ) { do { std::string t = tag.getKey(); cout << tag.getKey() << " : " << tag.toString(model) << " Type: " << tag.getType() << endl; } while( finder.findNextMetadata(tag) ); } } } } } <commit_msg>no freeimage fix<commit_after>/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "saiga/image/freeimage.h" #include "saiga/util/assert.h" #ifdef SAIGA_USE_FREEIMAGE #include <FreeImagePlus.h> #include <cstring> namespace Saiga { namespace FIP { bool load(const std::string &path, Image &img, ImageMetadata *metaData) { fipImage fimg; if(!loadFIP(path,fimg)){ return false; } if(metaData){ getMetaData(fimg,*metaData); // printAllMetaData(fimg); } convert(fimg,img); return true; } bool save(const std::string &path, const Image &img) { fipImage fimg; convert(img,fimg); return saveFIP(path,fimg); } bool loadFIP(const std::string &path, fipImage &img){ auto ret = img.load(path.c_str(),JPEG_EXIFROTATE); return ret; } bool saveFIP(const std::string &path, const fipImage &img){ auto ret = img.save(path.c_str()); return ret; } void convert(const Image &_src, fipImage &dest) { auto src = _src; #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR if(src.type == UC3) { ImageView<ucvec3> img = src.getImageView<ucvec3>(); img.swapChannels(0,2); } if(src.type == UC4) { ImageView<ucvec4> img = src.getImageView<ucvec4>(); img.swapChannels(0,2); } #endif int bpp = elementSize(src.type) * 8; FREE_IMAGE_TYPE t = FIT_BITMAP; switch(_src.type) { case US1: t = FIT_UINT16; break; default: break; } auto res = dest.setSize( t, src.width,src.height, bpp ); SAIGA_ASSERT(res); for(int i =0; i < src.rows; ++i) { memcpy(dest.getScanLine(i),src.rowPtr(i), std::min<int>(dest.getScanWidth(),src.pitchBytes)); } } void convert(const fipImage &src, Image& dest){ SAIGA_ASSERT(src.isValid()); dest.width = src.getWidth(); dest.height = src.getHeight(); int channels = -1; switch(src.getColorType()){ case FIC_MINISBLACK: channels = 1; break; case FIC_RGB: channels = 3; break; case FIC_RGBALPHA: channels = 4; break; default: break; } SAIGA_ASSERT(channels != -1); if(src.getBitsPerPixel() == 32 && channels ==3) { channels = 4; } int bitDepth= src.getBitsPerPixel() / channels; ImageElementType elementType = IET_ELEMENT_UNKNOWN; switch(bitDepth) { case 8: elementType = IET_UCHAR; break; case 16: elementType = IET_USHORT; break; case 32: elementType = IET_UINT; break; } SAIGA_ASSERT(elementType != IET_ELEMENT_UNKNOWN); // cout << "Channels: " << format.getChannels() << " BitsPerPixel: " << src.getBitsPerPixel() << " Bitdepth: " << format.getBitDepth() << endl; // cout << format << endl; dest.type = getType(channels,elementType); dest.create(); for(int i =0; i < dest.rows; ++i) { memcpy(dest.rowPtr(i),src.getScanLine(i), std::min<int>(dest.pitchBytes,src.getScanWidth())); } #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR if(dest.type == UC3) { ImageView<ucvec3> img = dest.getImageView<ucvec3>(); img.swapChannels(0,2); } if(dest.type == UC4) { ImageView<ucvec4> img = dest.getImageView<ucvec4>(); img.swapChannels(0,2); } #endif } static double parseFraction(const void* data){ const int* idata = reinterpret_cast<const int*>(data); return double(idata[0]) / double(idata[1]); } void getMetaData(fipImage &img, ImageMetadata& metaData){ metaData.width = img.getWidth(); metaData.height = img.getHeight(); fipTag tag; fipMetadataFind finder; if( finder.findFirstMetadata(FIMD_EXIF_MAIN, img, tag) ) { do { std::string t = tag.getKey(); if(t == "DateTime"){ metaData.DateTime = tag.toString(FIMD_EXIF_MAIN); }else if(t == "Make"){ metaData.Make = (char*)tag.getValue(); }else if(t == "Model"){ metaData.Model = (char*)tag.getValue(); }else{ // cout << "Tag: " << tag.getKey() << " Value: " << tag.toString(FIMD_EXIF_MAIN) << endl; } } while( finder.findNextMetadata(tag) ); } // the class can be called again with another metadata model if( finder.findFirstMetadata(FIMD_EXIF_EXIF, img, tag) ) { do { std::string t = tag.getKey(); if(t == "FocalLength"){ metaData.FocalLengthMM = parseFraction(tag.getValue()); }else if(t == "FocalLengthIn35mmFilm"){ metaData.FocalLengthMM35 = reinterpret_cast<const short*>(tag.getValue())[0]; }else if(t == "FocalPlaneResolutionUnit"){ metaData.FocalPlaneResolutionUnit = (ImageMetadata::ResolutionUnit) reinterpret_cast<const short*>(tag.getValue())[0]; }else if(t == "FocalPlaneXResolution"){ metaData.FocalPlaneXResolution = parseFraction(tag.getValue()); }else if(t == "FocalPlaneYResolution"){ metaData.FocalPlaneYResolution = parseFraction(tag.getValue()); }else{ // cout << "Tag: " << tag.getKey() << " Value: " << tag.toString(FIMD_EXIF_MAIN) << endl; } } while( finder.findNextMetadata(tag) ); } } void printAllMetaData(fipImage &img) { for(int i = -1; i <= 11; ++i){ FREE_IMAGE_MDMODEL model = (FREE_IMAGE_MDMODEL)i; cout << "Model: " << model << endl; fipTag tag; fipMetadataFind finder; if( finder.findFirstMetadata(model, img, tag) ) { do { std::string t = tag.getKey(); cout << tag.getKey() << " : " << tag.toString(model) << " Type: " << tag.getType() << endl; } while( finder.findNextMetadata(tag) ); } } } } } #endif <|endoftext|>
<commit_before>#include <cmath> #include <array> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <sys/stat.h> #include "simulation.h" #include "codes/codes.h" namespace detail { inline bool file_exists(const std::string &fname) { struct stat buf; return (stat(fname.c_str(), &buf) != -1); } } static std::array<double, 131> rates{ { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872, 0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938, 0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974, 0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989, 0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 } }; static std::array<double, 131> limits = { { -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316, -1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028, -0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724, -0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394, -0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032, 0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374, 0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844, 0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412, 1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108, 2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009, 3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906, 4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841, 4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615, 5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495, 6.651, 6.837, 7.072, 7.378, 7.864 } }; static constexpr double ebno(const double rate) { if (rate <= 0.800) { const size_t index = static_cast<size_t>(rate * 100); return limits.at(index); } else if (rate >= 0.999) { return limits.back(); } else { const size_t offset = 80; const size_t index = static_cast<size_t>(std::distance( std::cbegin(rates), std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1, [=](const double r) { return r >= rate; }))); return limits.at(index); } } static std::ofstream open_file(const std::string &fname) { if (detail::file_exists(fname)) { std::ostringstream os; os << "File " << fname << " already exists."; throw std::runtime_error(os.str()); } std::ofstream log_file(fname.c_str(), std::ofstream::out); return log_file; } double awgn_simulation::sigma(const double eb_no) const { return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0))); } awgn_simulation::awgn_simulation(const class decoder &decoder_, const double step_, const uint64_t seed_) : decoder(decoder_), step(step_), seed(seed_) {} void awgn_simulation::operator()() { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "ebno" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t factor = static_cast<size_t>(1.0 / step); const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step); const double start = (tmp + (1.0 / step)) * step; const double max = std::max(8.0, start) + step / 2; /* TODO round ebno() up to next step */ for (double eb_no = start; eb_no < max; eb_no += step) { std::normal_distribution<float> distribution( 1.0, static_cast<float>(sigma(eb_no))); auto noise = std::bind(std::ref(distribution), std::ref(generator)); size_t word_errors = 0; size_t samples = 10000; std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": E_b/N_0 = " << eb_no << " with " << samples << " … "; std::cout.flush(); auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < samples; i++) { std::generate(std::begin(b), std::end(b), noise); try { auto result = decoder.correct(b); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } auto end_time = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>( end_time - start_time).count(); std::cout << seconds << " s" << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << eb_no << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << static_cast<double>(word_errors) / samples << std::endl; } } bitflip_simulation::bitflip_simulation(const class decoder &decoder, const size_t errors) : decoder(decoder), errors(errors) {} void bitflip_simulation::operator()() const { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "errors" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t length = decoder.n(); for (size_t error = 0; error <= errors; error++) { size_t patterns = 0; size_t word_errors = 0; std::vector<int> b; std::fill_n(std::back_inserter(b), length - error, 0); std::fill_n(std::back_inserter(b), error, 1); std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": errors = " << error << " … "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); do { std::vector<float> x; x.reserve(length); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x), [](const auto &bit) { return -2 * bit + 1; }); patterns++; try { auto result = decoder.correct(x); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } while (std::next_permutation(std::begin(b), std::end(b))); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s " << word_errors << " " << patterns << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << error << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / patterns << std::endl; } } std::atomic_bool thread_pool::running{ true }; std::mutex thread_pool::lock; std::condition_variable thread_pool::cv; std::list<std::function<void(void)> > thread_pool::queue; thread_pool::thread_pool() { for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) { pool.emplace_back(std::bind(&thread_pool::thread_function, this)); } } thread_pool::~thread_pool() { running = false; cv.notify_all(); for (auto &&t : pool) t.join(); } void thread_pool::thread_function() const { for (;;) { bool have_work = false; std::function<void(void)> work; { std::unique_lock<std::mutex> m(lock); /* * empty running wait * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 */ cv.wait(m, [&]() { return !(queue.empty() && running); }); if (!queue.empty()) { work = queue.front(); queue.pop_front(); have_work = true; } } if (have_work) { try { work(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else if (!running) { return; } } } <commit_msg>Remove unused variable<commit_after>#include <cmath> #include <array> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <sys/stat.h> #include "simulation.h" #include "codes/codes.h" namespace detail { inline bool file_exists(const std::string &fname) { struct stat buf; return (stat(fname.c_str(), &buf) != -1); } } static std::array<double, 131> rates{ { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872, 0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938, 0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974, 0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989, 0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 } }; static std::array<double, 131> limits = { { -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316, -1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028, -0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724, -0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394, -0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032, 0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374, 0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844, 0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412, 1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108, 2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009, 3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906, 4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841, 4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615, 5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495, 6.651, 6.837, 7.072, 7.378, 7.864 } }; static constexpr double ebno(const double rate) { if (rate <= 0.800) { const size_t index = static_cast<size_t>(rate * 100); return limits.at(index); } else if (rate >= 0.999) { return limits.back(); } else { const size_t offset = 80; const size_t index = static_cast<size_t>(std::distance( std::cbegin(rates), std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1, [=](const double r) { return r >= rate; }))); return limits.at(index); } } static std::ofstream open_file(const std::string &fname) { if (detail::file_exists(fname)) { std::ostringstream os; os << "File " << fname << " already exists."; throw std::runtime_error(os.str()); } std::ofstream log_file(fname.c_str(), std::ofstream::out); return log_file; } double awgn_simulation::sigma(const double eb_no) const { return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0))); } awgn_simulation::awgn_simulation(const class decoder &decoder_, const double step_, const uint64_t seed_) : decoder(decoder_), step(step_), seed(seed_) {} void awgn_simulation::operator()() { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "ebno" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step); const double start = (tmp + (1.0 / step)) * step; const double max = std::max(8.0, start) + step / 2; /* TODO round ebno() up to next step */ for (double eb_no = start; eb_no < max; eb_no += step) { std::normal_distribution<float> distribution( 1.0, static_cast<float>(sigma(eb_no))); auto noise = std::bind(std::ref(distribution), std::ref(generator)); size_t word_errors = 0; size_t samples = 10000; std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": E_b/N_0 = " << eb_no << " with " << samples << " … "; std::cout.flush(); auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < samples; i++) { std::generate(std::begin(b), std::end(b), noise); try { auto result = decoder.correct(b); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } auto end_time = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>( end_time - start_time).count(); std::cout << seconds << " s" << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << eb_no << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << static_cast<double>(word_errors) / samples << std::endl; } } bitflip_simulation::bitflip_simulation(const class decoder &decoder, const size_t errors) : decoder(decoder), errors(errors) {} void bitflip_simulation::operator()() const { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "errors" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t length = decoder.n(); for (size_t error = 0; error <= errors; error++) { size_t patterns = 0; size_t word_errors = 0; std::vector<int> b; std::fill_n(std::back_inserter(b), length - error, 0); std::fill_n(std::back_inserter(b), error, 1); std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": errors = " << error << " … "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); do { std::vector<float> x; x.reserve(length); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x), [](const auto &bit) { return -2 * bit + 1; }); patterns++; try { auto result = decoder.correct(x); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } while (std::next_permutation(std::begin(b), std::end(b))); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s " << word_errors << " " << patterns << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << error << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / patterns << std::endl; } } std::atomic_bool thread_pool::running{ true }; std::mutex thread_pool::lock; std::condition_variable thread_pool::cv; std::list<std::function<void(void)> > thread_pool::queue; thread_pool::thread_pool() { for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) { pool.emplace_back(std::bind(&thread_pool::thread_function, this)); } } thread_pool::~thread_pool() { running = false; cv.notify_all(); for (auto &&t : pool) t.join(); } void thread_pool::thread_function() const { for (;;) { bool have_work = false; std::function<void(void)> work; { std::unique_lock<std::mutex> m(lock); /* * empty running wait * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 */ cv.wait(m, [&]() { return !(queue.empty() && running); }); if (!queue.empty()) { work = queue.front(); queue.pop_front(); have_work = true; } } if (have_work) { try { work(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else if (!running) { return; } } } <|endoftext|>
<commit_before>#ifndef STAN_IO_VALIDATE_DIMS_HPP #define STAN_IO_VALIDATE_DIMS_HPP #include <stan/io/var_context.hpp> #include <string> #include <vector> namespace stan { namespace io { /** * Check variable dimensions against variable declaration. * * @param context The var context to check. * @param stage stan program processing stage * @param name variable name * @param base_type declared stan variable type * @param dims variable dimensions * @throw std::runtime_error if mismatch between declared * dimensions and dimensions found in context. */ void validate_dims(const stan::io::var_context& context, const std::string& stage, const std::string& name, const std::string& base_type, const std::vector<size_t>& dims_declared) { bool is_int_type = base_type == "int"; if (is_int_type) { if (!context.contains_i(name)) { std::stringstream msg; msg << (context.contains_r(name) ? "int variable contained non-int values" : "variable does not exist") << "; processing stage=" << stage << "; variable name=" << name << "; base type=" << base_type; throw std::runtime_error(msg.str()); } } else { if (!context.contains_r(name)) { std::stringstream msg; msg << "variable does not exist" << "; processing stage=" << stage << "; variable name=" << name << "; base type=" << base_type; throw std::runtime_error(msg.str()); } } std::vector<size_t> dims = context.dims_r(name); if (dims.size() != dims_declared.size()) { std::stringstream msg; msg << "mismatch in number dimensions declared and found in context" << "; processing stage=" << stage << "; variable name=" << name << "; dims declared="; context.dims_msg(msg, dims_declared); msg << "; dims found="; context.dims_msg(msg, dims); throw std::runtime_error(msg.str()); } for (size_t i = 0; i < dims.size(); ++i) { if (dims_declared[i] != dims[i]) { std::stringstream msg; msg << "mismatch in dimension declared and found in context" << "; processing stage=" << stage << "; variable name=" << name << "; position=" << i << "; dims declared="; context.dims_msg(msg, dims_declared); msg << "; dims found="; context.dims_msg(msg, dims); throw std::runtime_error(msg.str()); } } } } // namespace io } // namespace stan #endif <commit_msg>inline validate dims<commit_after>#ifndef STAN_IO_VALIDATE_DIMS_HPP #define STAN_IO_VALIDATE_DIMS_HPP #include <stan/io/var_context.hpp> #include <string> #include <vector> namespace stan { namespace io { /** * Check variable dimensions against variable declaration. * * @param context The var context to check. * @param stage stan program processing stage * @param name variable name * @param base_type declared stan variable type * @param dims variable dimensions * @throw std::runtime_error if mismatch between declared * dimensions and dimensions found in context. */ inline void validate_dims(const stan::io::var_context& context, const std::string& stage, const std::string& name, const std::string& base_type, const std::vector<size_t>& dims_declared) { bool is_int_type = base_type == "int"; if (is_int_type) { if (!context.contains_i(name)) { std::stringstream msg; msg << (context.contains_r(name) ? "int variable contained non-int values" : "variable does not exist") << "; processing stage=" << stage << "; variable name=" << name << "; base type=" << base_type; throw std::runtime_error(msg.str()); } } else { if (!context.contains_r(name)) { std::stringstream msg; msg << "variable does not exist" << "; processing stage=" << stage << "; variable name=" << name << "; base type=" << base_type; throw std::runtime_error(msg.str()); } } std::vector<size_t> dims = context.dims_r(name); if (dims.size() != dims_declared.size()) { std::stringstream msg; msg << "mismatch in number dimensions declared and found in context" << "; processing stage=" << stage << "; variable name=" << name << "; dims declared="; context.dims_msg(msg, dims_declared); msg << "; dims found="; context.dims_msg(msg, dims); throw std::runtime_error(msg.str()); } for (size_t i = 0; i < dims.size(); ++i) { if (dims_declared[i] != dims[i]) { std::stringstream msg; msg << "mismatch in dimension declared and found in context" << "; processing stage=" << stage << "; variable name=" << name << "; position=" << i << "; dims declared="; context.dims_msg(msg, dims_declared); msg << "; dims found="; context.dims_msg(msg, dims); throw std::runtime_error(msg.str()); } } } } // namespace io } // namespace stan #endif <|endoftext|>
<commit_before>// Copyright (c) 2012-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/consensus.h" #include "consensus/tx_verify.h" #include "consensus/validation.h" #include "random.h" #include "pubkey.h" #include "key.h" #include "script/script.h" #include "script/standard.h" #include "uint256.h" #include "test/test_bitcoin.h" #include <vector> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; // Helpers: static std::vector<unsigned char> Serialize(const CScript& s) { std::vector<unsigned char> sSerialized(s); return sSerialized; } BOOST_FIXTURE_TEST_SUITE(sigopcount_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(GetSigOpCount) { // Test CScript::GetSigOpCount() CScript s1; BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0U); uint160 dummy; s1 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2U); s1 << OP_IF << OP_CHECKSIG << OP_ENDIF; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21U); CScript p2sh = GetScriptForDestination(CScriptID(s1)); CScript scriptSig; scriptSig << OP_0 << Serialize(s1); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3U); std::vector<CPubKey> keys; for (int i = 0; i < 3; i++) { CKey k; k.MakeNewKey(true); keys.push_back(k.GetPubKey()); } CScript s2 = GetScriptForMultisig(1, keys); BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20U); p2sh = GetScriptForDestination(CScriptID(s2)); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0U); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0U); CScript scriptSig2; scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U); } BOOST_AUTO_TEST_CASE(test_max_sigops_per_tx) { CMutableTransaction tx; tx.nVersion = 1; tx.vin.resize(1); tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript(); tx.vout.resize(1); tx.vout[0].nValue = 1; tx.vout[0].scriptPubKey = CScript(); { CValidationState state; BOOST_CHECK(CheckTransaction(tx, state)); } // Get just before the limit. for (size_t i = 0; i < MAX_TX_SIGOPS_COUNT; i++) { tx.vout[0].scriptPubKey << OP_CHECKSIG; } { CValidationState state; BOOST_CHECK(CheckTransaction(tx, state)); } // And go over. tx.vout[0].scriptPubKey << OP_CHECKSIG; { CValidationState state; BOOST_CHECK(!CheckTransaction(tx, state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txn-sigops"); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>[qa] Add GetTransactionSigOpCost unit tests<commit_after>// Copyright (c) 2012-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/consensus.h" #include "consensus/tx_verify.h" #include "consensus/validation.h" #include "random.h" #include "pubkey.h" #include "key.h" #include "script/script.h" #include "script/standard.h" #include "uint256.h" #include "test/test_bitcoin.h" #include <vector> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; // Helpers: static std::vector<unsigned char> Serialize(const CScript& s) { std::vector<unsigned char> sSerialized(s); return sSerialized; } BOOST_FIXTURE_TEST_SUITE(sigopcount_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(GetSigOpCount) { // Test CScript::GetSigOpCount() CScript s1; BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0U); uint160 dummy; s1 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2U); s1 << OP_IF << OP_CHECKSIG << OP_ENDIF; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21U); CScript p2sh = GetScriptForDestination(CScriptID(s1)); CScript scriptSig; scriptSig << OP_0 << Serialize(s1); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3U); std::vector<CPubKey> keys; for (int i = 0; i < 3; i++) { CKey k; k.MakeNewKey(true); keys.push_back(k.GetPubKey()); } CScript s2 = GetScriptForMultisig(1, keys); BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20U); p2sh = GetScriptForDestination(CScriptID(s2)); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0U); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0U); CScript scriptSig2; scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U); } BOOST_AUTO_TEST_CASE(test_max_sigops_per_tx) { CMutableTransaction tx; tx.nVersion = 1; tx.vin.resize(1); tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript(); tx.vout.resize(1); tx.vout[0].nValue = 1; tx.vout[0].scriptPubKey = CScript(); { CValidationState state; BOOST_CHECK(CheckTransaction(tx, state)); } // Get just before the limit. for (size_t i = 0; i < MAX_TX_SIGOPS_COUNT; i++) { tx.vout[0].scriptPubKey << OP_CHECKSIG; } { CValidationState state; BOOST_CHECK(CheckTransaction(tx, state)); } // And go over. tx.vout[0].scriptPubKey << OP_CHECKSIG; { CValidationState state; BOOST_CHECK(!CheckTransaction(tx, state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txn-sigops"); } } /** * Verifies script execution of the zeroth scriptPubKey of tx output and * zeroth scriptSig of tx input. */ ScriptError VerifyWithFlag(const CTransaction& output, const CMutableTransaction& input, int flags) { ScriptError error; CTransaction inputi(input); bool ret = VerifyScript(inputi.vin[0].scriptSig, output.vout[0].scriptPubKey, flags, TransactionSignatureChecker(&inputi, 0, output.vout[0].nValue), &error); BOOST_CHECK((ret == true) == (error == SCRIPT_ERR_OK)); return error; } /** * Builds a creationTx from scriptPubKey and a spendingTx from scriptSig * such that spendingTx spends output zero of creationTx. * Also inserts creationTx's output into the coins view. */ void BuildTxs(CMutableTransaction& spendingTx, CCoinsViewCache& coins, CMutableTransaction& creationTx, const CScript& scriptPubKey, const CScript& scriptSig) { creationTx.nVersion = 1; creationTx.vin.resize(1); creationTx.vin[0].prevout.SetNull(); creationTx.vin[0].scriptSig = CScript(); creationTx.vout.resize(1); creationTx.vout[0].nValue = 1; creationTx.vout[0].scriptPubKey = scriptPubKey; spendingTx.nVersion = 1; spendingTx.vin.resize(1); spendingTx.vin[0].prevout.hash = creationTx.GetHash(); spendingTx.vin[0].prevout.n = 0; spendingTx.vin[0].scriptSig = scriptSig; spendingTx.vout.resize(1); spendingTx.vout[0].nValue = 1; spendingTx.vout[0].scriptPubKey = CScript(); AddCoins(coins, CTransaction(creationTx), 0); } BOOST_AUTO_TEST_CASE(GetTxSigOpCost) { // Transaction creates outputs CMutableTransaction creationTx; // Transaction that spends outputs and whose // sig op cost is going to be tested CMutableTransaction spendingTx; // Create utxo set CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); // Create key CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); // Default flags int flags = SCRIPT_VERIFY_P2SH; // Multisig script (legacy counting) { CScript scriptPubKey = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY; // Do not use a valid signature to avoid using wallet operations. CScript scriptSig = CScript() << OP_0 << OP_0; BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig); // Legacy counting only includes signature operations in scriptSigs and scriptPubKeys // of a transaction and does not take the actual executed sig operations into account. // spendingTx in itself does not contain a signature operation. BOOST_CHECK(GetLegacySigOpCount(CTransaction(spendingTx)) == 0); // creationTx contains two signature operations in its scriptPubKey, but legacy counting // is not accurate. BOOST_CHECK(GetLegacySigOpCount(CTransaction(creationTx)) == MAX_PUBKEYS_PER_MULTISIG); // Sanity check: script verification fails because of an invalid signature. BOOST_CHECK(VerifyWithFlag(creationTx, spendingTx, flags) == SCRIPT_ERR_CHECKMULTISIGVERIFY); } // Multisig nested in P2SH { CScript redeemScript = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY; CScript scriptPubKey = GetScriptForDestination(CScriptID(redeemScript)); CScript scriptSig = CScript() << OP_0 << OP_0 << ToByteVector(redeemScript); BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig); BOOST_CHECK(GetP2SHSigOpCount(CTransaction(spendingTx), coins) == 2); BOOST_CHECK(VerifyWithFlag(creationTx, spendingTx, flags) == SCRIPT_ERR_CHECKMULTISIGVERIFY); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>