<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* 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, see <http://www.gnu.org/licenses/>.              *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "stdafx.h"
#include <sofa/helper/Quater.h>

// Including component
#include <SofaBoundaryCondition/AffineMovementConstraint.h>
#include "../deformationMapping/LinearMapping.h"

#include <SofaTest/Mapping_test.h>

namespace sofa {

    using namespace defaulttype;
    using namespace component;
    using namespace component::mapping;

   /// Linear Deformation mappings test
   /**
    * Test the deformation mappings by applying a rigid transformation (translation and rotation)
    * to all rigid nodes and checks if the resulting deformation gradient is equal to rotation.
    * This screenshot explains how this test works:
    * \image html RigidDeformationMapping.png
   */

    template <typename _Mapping>
    struct RigidLinearDeformationMappings_test : public Mapping_test<_Mapping>
    {
        typedef Mapping_test<_Mapping> Inherited;
        typedef typename Inherited::In In;
        typedef typename In::CPos CPos;
        typedef typename In::Coord Coord;
        typedef typename Inherited::Out Out;
        typedef typename Inherited::Real Real;
        typedef typename Inherited::OutVecCoord OutVecCoord;
        typedef typename Inherited::InVecCoord InVecCoord;
        typedef typename Out::Frame OutFrame;
        typedef component::container::MechanicalObject<In> InDOFs;
        typedef component::container::MechanicalObject<Out> OutDOFs;
        typedef defaulttype::Quat Quat;
        typedef defaulttype::Vector3 Vec3;

        /// Tested Rotation: random rotation matrix
        defaulttype::Mat<3,3,Real> testedRotation;
        Quat testedQuaternion;
        /// Tested Translation: random translation
        Vec3 testedTranslation;

        // Constructor: call the constructor of the base class which loads the scene to test
        RigidLinearDeformationMappings_test() : Mapping_test<_Mapping>(std::string(FLEXIBLE_TEST_SCENES_DIR) + "/" + "RigidLineDeformationMapping.scn")
        {
            // rotation and translation
            this->SetRandomTestedRotationAndTranslation();
            typedef projectiveconstraintset::AffineMovementConstraint<In> AffineMovementConstraint;
            typename AffineMovementConstraint::SPtr affineConstraint  = this->root->template get<AffineMovementConstraint>(this->root->SearchDown);
            affineConstraint->m_quaternion.setValue(testedQuaternion);
            affineConstraint->m_translation.setValue(testedTranslation);
            testedQuaternion.toMatrix(testedRotation);

            static_cast<_Mapping*>(this->mapping)->d_geometricStiffness.setValue( 1 );
        }

        void SetRandomTestedRotationAndTranslation()
        {
            // Random Rotation
            SReal x,y,z,w=0;
            // Random axis
            x = SReal(helper::drand(1));
            y = SReal(helper::drand(1));
            z = SReal(helper::drand(1));
            // If the rotation axis is null
            Vec3 rotationAxis(x,y,z);
            rotationAxis.normalize( Vec3(0,0,1), 1e-7 ); // with failsafe

            // Random angle between 0 and M_PI
            while( !w )
                w = helper::drand()* M_PI;

            // Quat = (rotationAxis*sin(angle/2) , cos(angle/2)) angle = 2*w
            testedQuaternion = Quat(sin(w)*rotationAxis[0],rotationAxis[1]*sin(w),rotationAxis[2]*sin(w),cos(w));

            // to be sure
            if( !testedQuaternion.normalize() )
            {
                msg_warning("RigidLinearDeformationMappings_test")<<"testedQuaternion is too small  -  random values: "<<x<<" "<<y<<" "<<z<<" "<<w<<"   testedQuaternion="<<testedQuaternion;
                testedQuaternion.set( 0, 0, 0, 1 );
            }

            // Translation
            for(size_t i=0;i<testedTranslation.size();++i)
            {
                testedTranslation[i]=helper::drand(2);
            }

            msg_info("RigidLinearDeformationMappings_test")<<"random values: "<<x<<" "<<y<<" "<<z<<" "<<w<<"   testedQuaternion="<<testedQuaternion<<"   -   testedTranslation="<<testedTranslation;

        }

        using Inherited::runTest;
        /// After simulation compare the positions of deformation gradients to the theoretical positions.
        bool runTest(double convergenceAccuracy)
        {
            // Init simulation
            sofa::simulation::getSimulation()->init(this->root.get());

            // Get dofs positions
            typename  InDOFs::ReadVecCoord x = this->inDofs->readPositions();

            // xin
            InVecCoord xin(x.size());
            copyFromData(xin,x);

            // xout
            typename  OutDOFs::ReadVecCoord xelasticityDofs = this->outDofs->readPositions();
            OutVecCoord xout(xelasticityDofs.size());
            copyFromData(xout,xelasticityDofs);

            // Initialize parameters to test convergence
            size_t numNodes = xin.size();
            InVecCoord xPrev(numNodes);
            InVecCoord dx(numNodes);
            bool hasConverged = true;

            for (size_t i=0; i<numNodes; i++)
            {
                xPrev[i] = CPos(0,0,0);
            }

            // Animate
            do
            {
                hasConverged = true;
                sofa::simulation::getSimulation()->animate(this->root.get(),0.05);
                typename InDOFs::ReadVecCoord xCurrent = this->inDofs->readPositions();

                // Compute dx
                for (size_t i=0; i<xCurrent.size(); i++)
                {
                    // Translation
                    dx[i].getCenter() = xCurrent[i].getCenter()-xPrev[i].getCenter();
                    //Rotation
                    dx[i].getOrientation() = xCurrent[i].getOrientation().inverse()*xPrev[i].getOrientation();
                    // Test convergence
                    if(dx[i].norm()>convergenceAccuracy) hasConverged = false;
                }

                // xprev = xCurrent
                for (size_t i=0; i<numNodes; i++)
                {
                    xPrev[i]=xCurrent[i];
                }
            }
            while(!hasConverged); // not converged

            // Parent new : Get simulated positions
            typename InDOFs::WriteVecCoord xinNew = this->inDofs->writePositions();

            // New position of parents
            InVecCoord parentNew(xinNew.size());
            for(size_t i=0; i<xinNew.size();++i)
            {
                parentNew[i] = xinNew[i];
            }

            // Expected children positions: rotation from affine constraint
            typename OutDOFs::WriteVecCoord xoutNew = this->outDofs->writePositions();
            OutVecCoord expectedChildCoords(xoutNew.size());

            for(size_t i=0;i<xoutNew.size();++i)
            {
                OutFrame &f = expectedChildCoords[i].getF();
                f = testedRotation;
            }

           // run the mapping test
           return Inherited::runTest(xin,xout,parentNew,expectedChildCoords);

        }

    };

      // Define the list of DataTypes to instantiate
    using testing::Types;
    typedef Types<
        LinearMapping<Rigid3Types, F331Types>,
        LinearMapping<Rigid3Types, F332Types>
    > DataTypes; // the types to instantiate.

    // Test suite for all the instantiations
    TYPED_TEST_CASE(RigidLinearDeformationMappings_test, DataTypes);

    // test case: polarcorotationalStrainMapping
    TYPED_TEST( RigidLinearDeformationMappings_test , RigidStrainDeformationPatchTest)
    {
        ASSERT_TRUE( this->runTest(1e-15));
    }

} // namespace sofa
<commit_msg>[Flexible] trying to fix RigidDeformationMapping_test<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* 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, see <http://www.gnu.org/licenses/>.              *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "stdafx.h"
#include <sofa/helper/Quater.h>

// Including component
#include <SofaBoundaryCondition/AffineMovementConstraint.h>
#include "../deformationMapping/LinearMapping.h"

#include <SofaTest/Mapping_test.h>

namespace sofa {

    using namespace defaulttype;
    using namespace component;
    using namespace component::mapping;

   /// Linear Deformation mappings test
   /**
    * Test the deformation mappings by applying a rigid transformation (translation and rotation)
    * to all rigid nodes and checks if the resulting deformation gradient is equal to rotation.
    * This screenshot explains how this test works:
    * \image html RigidDeformationMapping.png
   */

    template <typename _Mapping>
    struct RigidLinearDeformationMappings_test : public Mapping_test<_Mapping>
    {
        typedef Mapping_test<_Mapping> Inherited;
        typedef typename Inherited::In In;
        typedef typename In::CPos CPos;
        typedef typename In::Coord Coord;
        typedef typename Inherited::Out Out;
        typedef typename Inherited::Real Real;
        typedef typename Inherited::OutVecCoord OutVecCoord;
        typedef typename Inherited::InVecCoord InVecCoord;
        typedef typename Out::Frame OutFrame;
        typedef component::container::MechanicalObject<In> InDOFs;
        typedef component::container::MechanicalObject<Out> OutDOFs;
        typedef defaulttype::Quat Quat;
        typedef defaulttype::Vector3 Vec3;

        /// Tested Rotation: random rotation matrix
        defaulttype::Mat<3,3,Real> testedRotation;

        // Constructor: call the constructor of the base class which loads the scene to test
        RigidLinearDeformationMappings_test() : Mapping_test<_Mapping>(std::string(FLEXIBLE_TEST_SCENES_DIR) + "/" + "RigidLineDeformationMapping.scn")
        {
            // random rotation and translation
            Coord randomRigid = Coord::rand(180);

            msg_info("RigidLinearDeformationMappings_test")<<"randomRigid="<<randomRigid; // to debug

            typedef projectiveconstraintset::AffineMovementConstraint<In> AffineMovementConstraint;
            typename AffineMovementConstraint::SPtr affineConstraint  = this->root->template get<AffineMovementConstraint>(this->root->SearchDown);
            affineConstraint->m_quaternion.setValue(randomRigid.getOrientation());
            affineConstraint->m_translation.setValue(randomRigid.getCenter());
            randomRigid.getOrientation().toMatrix(testedRotation);

            static_cast<_Mapping*>(this->mapping)->d_geometricStiffness.setValue( 1 );
        }

        using Inherited::runTest;
        /// After simulation compare the positions of deformation gradients to the theoretical positions.
        bool runTest(double convergenceAccuracy)
        {
            // Init simulation
            sofa::simulation::getSimulation()->init(this->root.get());

            // Get dofs positions
            typename  InDOFs::ReadVecCoord x = this->inDofs->readPositions();

            // xin
            InVecCoord xin(x.size());
            copyFromData(xin,x);

            // xout
            typename  OutDOFs::ReadVecCoord xelasticityDofs = this->outDofs->readPositions();
            OutVecCoord xout(xelasticityDofs.size());
            copyFromData(xout,xelasticityDofs);

            // Initialize parameters to test convergence
            size_t numNodes = xin.size();
            InVecCoord xPrev(numNodes);
            InVecCoord dx(numNodes);
            bool hasConverged = true;

            for (size_t i=0; i<numNodes; i++)
            {
                xPrev[i] = CPos(0,0,0);
            }

            // Animate
            do
            {
                hasConverged = true;
                sofa::simulation::getSimulation()->animate(this->root.get(),0.05);
                typename InDOFs::ReadVecCoord xCurrent = this->inDofs->readPositions();

                // Compute dx
                for (size_t i=0; i<xCurrent.size(); i++)
                {
                    // Translation
                    dx[i].getCenter() = xCurrent[i].getCenter()-xPrev[i].getCenter();
                    //Rotation
                    dx[i].getOrientation() = xCurrent[i].getOrientation().inverse()*xPrev[i].getOrientation();
                    // Test convergence
                    if(dx[i].norm()>convergenceAccuracy) hasConverged = false;
                }

                // xprev = xCurrent
                for (size_t i=0; i<numNodes; i++)
                {
                    xPrev[i]=xCurrent[i];
                }
            }
            while(!hasConverged); // not converged

            // Parent new : Get simulated positions
            typename InDOFs::WriteVecCoord xinNew = this->inDofs->writePositions();

            // New position of parents
            InVecCoord parentNew(xinNew.size());
            for(size_t i=0; i<xinNew.size();++i)
            {
                parentNew[i] = xinNew[i];
            }

            // Expected children positions: rotation from affine constraint
            typename OutDOFs::WriteVecCoord xoutNew = this->outDofs->writePositions();
            OutVecCoord expectedChildCoords(xoutNew.size());

            for(size_t i=0;i<xoutNew.size();++i)
            {
                OutFrame &f = expectedChildCoords[i].getF();
                f = testedRotation;
            }

           // run the mapping test
           return Inherited::runTest(xin,xout,parentNew,expectedChildCoords);

        }

    };

      // Define the list of DataTypes to instantiate
    using testing::Types;
    typedef Types<
        LinearMapping<Rigid3Types, F331Types>,
        LinearMapping<Rigid3Types, F332Types>
    > DataTypes; // the types to instantiate.

    // Test suite for all the instantiations
    TYPED_TEST_CASE(RigidLinearDeformationMappings_test, DataTypes);

    // test case: polarcorotationalStrainMapping
    TYPED_TEST( RigidLinearDeformationMappings_test , RigidStrainDeformationPatchTest)
    {
        ASSERT_TRUE( this->runTest(1e-15));
    }

} // namespace sofa
<|endoftext|>


<commit_before>

#include <Flexible/config.h>

#include "ComponentSpecializationsDefines.h"

#include <sofa/core/ObjectFactory.h>

#include <SofaBaseMechanics/IdentityMapping.inl>
#include <SofaMiscMapping/SubsetMultiMapping.inl>

namespace sofa
{

namespace component
{

namespace mapping
{

SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,IdentityMapping))

// Register in the Factory
int EVALUATOR(TYPEABSTRACTNAME,IdentityMappingClass) = core::RegisterObject("Special case of mapping where the child points are the same as the parent points")
#ifndef SOFA_FLOAT
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >()
#endif
#ifndef SOFA_DOUBLE
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >()
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >()
#endif
#endif
        ;

#ifndef SOFA_FLOAT
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes >;
#endif
#ifndef SOFA_DOUBLE
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes >;
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes >;
#endif
#endif

///////////////////////////////

using namespace sofa::defaulttype;

SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMapping))

int EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMappingClass) = core::RegisterObject("Compute a subset of the input MechanicalObjects according to a dof index list")
#ifndef SOFA_FLOAT
    .add< SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes > >()
#endif
#ifndef SOFA_DOUBLE
    .add< SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes > >()
#endif
        ;

#ifndef SOFA_FLOAT
    template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes >;
#endif
#ifndef SOFA_DOUBLE
    template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes >;
#endif

} // namespace mapping

} // namespace component

} // namespace sofa

#include "ComponentSpecializationsUndef.h"
<commit_msg>[Flexible] fixed debug build<commit_after>

#include <Flexible/config.h>

#include "ComponentSpecializationsDefines.h"

#include <sofa/core/ObjectFactory.h>

#include <sofa/core/Mapping.inl>
#include <SofaBaseMechanics/IdentityMapping.inl>
#include <SofaMiscMapping/SubsetMultiMapping.inl>

namespace sofa
{

namespace component
{

namespace mapping
{

SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,IdentityMapping))

// Register in the Factory
int EVALUATOR(TYPEABSTRACTNAME,IdentityMappingClass) = core::RegisterObject("Special case of mapping where the child points are the same as the parent points")
#ifndef SOFA_FLOAT
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >()
#endif
#ifndef SOFA_DOUBLE
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >()
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >()
        .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >()
#endif
#endif
        ;

#ifndef SOFA_FLOAT
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes >;
#endif
#ifndef SOFA_DOUBLE
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes >;
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes >;
    template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes >;
#endif
#endif

///////////////////////////////

using namespace sofa::defaulttype;

SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMapping))

int EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMappingClass) = core::RegisterObject("Compute a subset of the input MechanicalObjects according to a dof index list")
#ifndef SOFA_FLOAT
    .add< SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes > >()
#endif
#ifndef SOFA_DOUBLE
    .add< SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes > >()
#endif
        ;

#ifndef SOFA_FLOAT
    template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes >;
#endif
#ifndef SOFA_DOUBLE
    template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes >;
#endif

} // namespace mapping

} // namespace component

} // namespace sofa

#include "ComponentSpecializationsUndef.h"
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright RTK 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 "rtksubselect_ggo.h"
#include "rtkGgoFunctions.h"

#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkProjectionsReader.h"

#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>

int main(int argc, char * argv[])
{
  GGO(rtksubselect, args_info);

  // Generate file names
  itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
  names->SetDirectory(args_info.path_arg);
  names->SetNumericSort(args_info.nsort_flag);
  names->SetRegularExpression(args_info.regexp_arg);
  names->SetSubMatch(args_info.submatch_arg);

  if(args_info.verbose_flag)
    std::cout << "Regular expression matches "
              << names->GetFileNames().size()
              << " file(s)..."
              << std::endl;

  // Geometry
  if(args_info.verbose_flag)
    std::cout << "Reading geometry information from "
              << args_info.geometry_arg
              << "..."
              << std::endl;
  rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
  geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
  geometryReader->SetFilename(args_info.geometry_arg);
  TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )

  // Output RTK geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer outputGeometry = GeometryType::New();

  // Output filenames
  std::vector< std::string > outputProjectionsNames;

  // Subsection
  int n = geometryReader->GetOutputObject()->GetGantryAngles().size();
  if(args_info.list_given)
    {
    for(unsigned int i=0; i<args_info.list_given; i++)
      {
      int noProj = args_info.list_arg[i];
      outputGeometry->AddProjection(geometryReader->GetOutputObject()->GetSourceToIsocenterDistances()[noProj],
                                    geometryReader->GetOutputObject()->GetSourceToDetectorDistances()[noProj],
                                    geometryReader->GetOutputObject()->GetGantryAngles()[noProj],
                                    geometryReader->GetOutputObject()->GetProjectionOffsetsX()[noProj],
                                    geometryReader->GetOutputObject()->GetProjectionOffsetsY()[noProj],
                                    geometryReader->GetOutputObject()->GetOutOfPlaneAngles()[noProj],
                                    geometryReader->GetOutputObject()->GetInPlaneAngles()[noProj],
                                    geometryReader->GetOutputObject()->GetSourceOffsetsX()[noProj],
                                    geometryReader->GetOutputObject()->GetSourceOffsetsY()[noProj]);
      outputProjectionsNames.push_back(names->GetFileNames()[noProj]);
      }
    }
  else
    for(int noProj=args_info.first_arg; noProj<n; noProj+=args_info.step_arg)
      {
      outputGeometry->AddProjection(geometryReader->GetOutputObject()->GetSourceToIsocenterDistances()[noProj],
                                    geometryReader->GetOutputObject()->GetSourceToDetectorDistances()[noProj],
                                    geometryReader->GetOutputObject()->GetGantryAngles()[noProj],
                                    geometryReader->GetOutputObject()->GetProjectionOffsetsX()[noProj],
                                    geometryReader->GetOutputObject()->GetProjectionOffsetsY()[noProj],
                                    geometryReader->GetOutputObject()->GetOutOfPlaneAngles()[noProj],
                                    geometryReader->GetOutputObject()->GetInPlaneAngles()[noProj],
                                    geometryReader->GetOutputObject()->GetSourceOffsetsX()[noProj],
                                    geometryReader->GetOutputObject()->GetSourceOffsetsY()[noProj]);
      outputProjectionsNames.push_back(names->GetFileNames()[noProj]);
      }

  // Geometry writer
  if(args_info.verbose_flag)
    std::cout << "Writing geometry information in "
              << args_info.out_geometry_arg
              << "..."
              << std::endl;
  rtk::ThreeDCircularProjectionGeometryXMLFileWriter::Pointer xmlWriter =
    rtk::ThreeDCircularProjectionGeometryXMLFileWriter::New();
  xmlWriter->SetFilename(args_info.out_geometry_arg);
  xmlWriter->SetObject( &(*outputGeometry) );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( xmlWriter->WriteFile() )

  typedef float OutputPixelType;
  const unsigned int Dimension = 3;
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  // Projections reader
  if(args_info.verbose_flag)
    std::cout << "Reading and writing projections in "
              << args_info.out_proj_arg
              << "..."
              << std::endl;
  typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileNames( outputProjectionsNames );

  // Write
  typedef itk::ImageFileWriter<  OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( args_info.out_proj_arg );
  writer->SetInput( reader->GetOutput() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->UpdateOutputInformation() )
  writer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );

  TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() )

  return EXIT_SUCCESS;
}
<commit_msg>Modified rtksubselect : It can now take in input a single file containing several projections. It now writes its output projections in a single file too.<commit_after>/*=========================================================================
 *
 *  Copyright RTK 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 "rtksubselect_ggo.h"
#include "rtkGgoFunctions.h"

#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkProjectionsReader.h"
#include "rtkConstantImageSource.h"

#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkPasteImageFilter.h>

int main(int argc, char * argv[])
{
  GGO(rtksubselect, args_info);

  typedef float OutputPixelType;
  const unsigned int Dimension = 3;
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  // Projections reader
  typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtksubselect>(reader, args_info);
  reader->Update();

  // Geometry
  if(args_info.verbose_flag)
    std::cout << "Reading geometry information from "
              << args_info.geometry_arg
              << "..."
              << std::endl;
  rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
  geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
  geometryReader->SetFilename(args_info.geometry_arg);
  TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )

  // Compute the indices of the selected projections
  std::vector<int> indices;
  int n = geometryReader->GetOutputObject()->GetGantryAngles().size();
  if(args_info.list_given)
    for(unsigned int i=0; i<args_info.list_given; i++)
      {
        indices.push_back(args_info.list_arg[i]);
      }
  else
    for(int noProj=args_info.first_arg; noProj<n; noProj+=args_info.step_arg)
      {
        indices.push_back(noProj);
      }

  // Output RTK geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer outputGeometry = GeometryType::New();

  // Output projections object
  typedef rtk::ConstantImageSource< OutputImageType > SourceType;
  SourceType::Pointer source = SourceType::New();
  source->SetInformationFromImage(reader->GetOutput());
  OutputImageType::SizeType outputSize = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
  outputSize[Dimension - 1] = indices.size();
  source->SetSize(outputSize);
  source->SetConstant(0);
  source->Update();

  // Fill in the outputGeometry and the output projections
  typedef itk::PasteImageFilter<OutputImageType> PasteType;
  PasteType::Pointer paste = PasteType::New();
  paste->SetSourceImage(reader->GetOutput());
  paste->SetDestinationImage(source->GetOutput());

  OutputImageType::RegionType sourceRegion;
  OutputImageType::IndexType destinationIndex;
  for (unsigned int i=0; i<indices.size(); i++)
    {
    // If it is not the first projection, we need to use the output of
    // the paste filter as input
    if(i)
      {
      OutputImageType::Pointer pimg = paste->GetOutput();
      pimg->DisconnectPipeline();
      paste->SetDestinationImage(pimg);
      }

    sourceRegion = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
    sourceRegion.SetIndex(Dimension - 1, indices[i]);
    sourceRegion.SetSize(Dimension - 1, 1);
    paste->SetSourceRegion(sourceRegion);

    destinationIndex.Fill(0);
    destinationIndex[Dimension -1] = i;
    paste->SetDestinationIndex(destinationIndex);

    paste->Update();

    // Fill in the output geometry object
    outputGeometry->AddProjection(geometryReader->GetOutputObject()->GetSourceToIsocenterDistances()[indices[i]],
                                  geometryReader->GetOutputObject()->GetSourceToDetectorDistances()[indices[i]],
                                  geometryReader->GetOutputObject()->GetGantryAngles()[indices[i]],
                                  geometryReader->GetOutputObject()->GetProjectionOffsetsX()[indices[i]],
                                  geometryReader->GetOutputObject()->GetProjectionOffsetsY()[indices[i]],
                                  geometryReader->GetOutputObject()->GetOutOfPlaneAngles()[indices[i]],
                                  geometryReader->GetOutputObject()->GetInPlaneAngles()[indices[i]],
                                  geometryReader->GetOutputObject()->GetSourceOffsetsX()[indices[i]],
                                  geometryReader->GetOutputObject()->GetSourceOffsetsY()[indices[i]]);
    }

  // Geometry writer
  if(args_info.verbose_flag)
    std::cout << "Writing geometry information in "
              << args_info.out_geometry_arg
              << "..."
              << std::endl;
  rtk::ThreeDCircularProjectionGeometryXMLFileWriter::Pointer xmlWriter =
    rtk::ThreeDCircularProjectionGeometryXMLFileWriter::New();
  xmlWriter->SetFilename(args_info.out_geometry_arg);
  xmlWriter->SetObject( &(*outputGeometry) );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( xmlWriter->WriteFile() )

  // Write
  typedef itk::ImageFileWriter<  OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( args_info.out_proj_arg );
  writer->SetInput( paste->GetOutput() );
  //TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->UpdateOutputInformation() )
//  writer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );

  TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() )

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: chenone2316
 *
 * Created on June 1, 2015, 1:46 PM
 */

#include <broker/broker.hh>
#include <broker/endpoint.hh>
#include <broker/message_queue.hh>
#include <osquery/sdk.h>
#include <poll.h>
#include <iostream>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <osquery/filesystem.h>
#include <osquery/events.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/registry.h>
#include <osquery/sql.h>
//#include <pthread.h>

using namespace osquery;

broker::endpoint PC("VM");

/*
 *
 */
class BrokerQueryPlugin: public ConfigPlugin
{
private:
    typedef std::map<std::string, std::string>::const_iterator pt;
    QueryData bQresult;
public:
    ////////////////////////////////////////////////////////////////////////////
    //////////////////broker connection/////////////////////////////////////////
    Status brokerConnection()
    {
        std::cout<<"In the broker Connection\n";
        auto status = Status(0,"OK");
        broker::init();
        PC.peer("192.168.1.187",9999);
        auto conn_status = PC.outgoing_connection_status().need_pop();
        for(auto cs: conn_status)
        {
            if(cs.status == broker::outgoing_connection_status::tag::established)
            {
                std::cout<<"Connection Established"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"Error: Connection Failed"<<std::endl;
                status = Status(-1,"Not Connected");
            }
        }
        return status;
    }
    ////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    std::string brokerMessageExtractor(const broker::message &msg)
    {
        std::string broQuery = broker::to_string(broker::message(msg));
        broQuery = broQuery.substr(1,broQuery.size()-2);
        return broQuery;
    }

    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    Status brokerMessageQuery()
    {
        std::cout<<"In the Message Query Function\n";
        broker::message_queue mq("Testing", PC);
        pollfd pfd{mq.fd(), POLLIN, 0};
        int rv;
        std::string temp_query;
        std::string out;
        auto status = Status(0,"OK");
        QueryData test;

        while(true)
        {
            rv = poll(&pfd,1,10000);
            if(!(rv== -1) && !(rv==0))
            {
                for(auto& msg : mq.need_pop())
                {
                    temp_query = brokerMessageExtractor(msg);
                    std::cout<<"Query = "<<temp_query<<std::endl;
                    test = brokerQuery(temp_query);
                    for (auto& r : test)
                    {
                        for(pt iter = r.begin(); iter != r.end(); iter++)
                        {
                            std::cout << iter->first << ": ";
                            out += iter->first + ": ";
                            std::cout << iter->second <<std::endl ;
                            out += iter->second + "\n" ;
                        }
                        std::cout << out;
                        usleep(500000);
                        PC.send("Testing", broker::message{out});
                        usleep(500000);
                    }

                }
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////

    QueryData brokerQuery(const std::string& queryString)
    {
        QueryData qd;
        osquery::queryExternal(queryString, qd);

        return qd;
    }

    //////////////////////////////////////////////////////////////////////////
    //*************************************************************************
        Status genConfig(std::map<std::string,std::string>& config)
        {
            return Status(0,"OK");
        }
    //////////////////////////////////////////////////////////////////////
      /* Status broker_osquery_init()
        {
            std::cout<<"In the broker_init() function"<<std::endl;
            //BrokerQueryPlugin b;
            auto status = Status(0,"OK");
            status = brokerConnection();
            if(status.ok())
            {
                brokerMessageQuery();
            }
            else
            {
                std::cout<<"Could not Connect";
            }
            return Status(0,"OK");
        }*/

};
void *broker_osquery_init(void *threadid)
{
    std::cout<<"In the broker_init() function"<<std::endl;
    BrokerQueryPlugin b;
    auto status = Status(0,"OK");
    status = b.brokerConnection();
    while(!status.ok())
    {
        b.brokerConnection();
    }
    b.brokerMessageQuery();
    pthread_exit(NULL);
}

//////////////////////////////////////////////////

// Note 3: Use REGISTER_EXTERNAL to define your plugin
REGISTER_EXTERNAL(BrokerQueryPlugin, "config", "brokerQuery")

int main(int argc, char* argv[]) {

    pthread_t broker_thread;
    int rc; long t=0;
    std::cout<<"Starting the program"<<std::endl;
    BrokerQueryPlugin b;
    //b.broker_osquery_init();
    rc = pthread_create(&broker_thread, NULL, broker_osquery_init, (void*)t);
    if(rc)
    {
        std::cout<< "Error in pthread_create(): " <<rc <<std::endl;
        exit(-1);
    }

  // Note 4: Start logging, threads, etc.
  osquery::Initializer runner(argc, argv, OSQUERY_EXTENSION);
  std::cout<<"Initialized OSquery"<<std::endl;

  // Note 5: Connect to osqueryi or osqueryd.
  auto status = startExtension("brokerQuery", "0.0.1");
  if (!status.ok()) {
    LOG(ERROR) << status.getMessage();
  }

  /*BrokerQueryPlugin b;
  b.genConfig();*/

  std::cout<<"Shutting downn extension"<<std::endl;
  // Finally shutdown.
  runner.shutdown();
  return 0;
}
<commit_msg>Update bro_osquery.cpp<commit_after>/*
 * File:   main.cpp
 * Author: chenone2316
 *
 * Created on June 1, 2015, 1:46 PM
 */

#include <broker/broker.hh>
#include <broker/endpoint.hh>
#include <broker/message_queue.hh>
#include <osquery/sdk.h>
#include <poll.h>
#include <iostream>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <osquery/filesystem.h>
#include <osquery/events.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/registry.h>
#include <osquery/sql.h>
//#include <pthread.h>

using namespace osquery;

broker::endpoint PC("VM");

/*
 *
 */
class BrokerQueryPlugin: public ConfigPlugin
{
private:
    typedef std::map<std::string, std::string>::const_iterator pt;
    QueryData bQresult;
public:
    ////////////////////////////////////////////////////////////////////////////
    //////////////////broker connection/////////////////////////////////////////
    Status brokerConnection()
    {
        std::cout<<"In the broker Connection\n";
        auto status = Status(0,"OK");
        broker::init();
        PC.peer("192.168.1.187",9999);
        auto conn_status = PC.outgoing_connection_status().need_pop();
        for(auto cs: conn_status)
        {
            if(cs.status == broker::outgoing_connection_status::tag::established)
            {
                std::cout<<"Connection Established"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"Error: Connection Failed"<<std::endl;
                status = Status(-1,"Not Connected");
            }
        }
        return status;
    }
    ////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    std::string brokerMessageExtractor(const broker::message &msg)
    {
        std::string broQuery = broker::to_string(broker::message(msg));
        broQuery = broQuery.substr(1,broQuery.size()-2);
        if(broQuery.substr(0,6)!= "SELECT")
        {
            return "";
        }
        else
            return broQuery;
    }

    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    Status brokerMessageQuery()
    {
        std::cout<<"In the Message Query Function\n";
        broker::message_queue mq("Testing", PC);
        pollfd pfd{mq.fd(), POLLIN, 0};
        int rv;
        std::string temp_query;
        std::string out1;
        std::string out2;
        std::string out;
        auto status = Status(0,"OK");
        QueryData test;

        while(true)
        {
            rv = poll(&pfd,1,10000);
            if(!(rv== -1) && !(rv==0))
            {
                for(auto& msg : mq.need_pop())
                {
                    temp_query = brokerMessageExtractor(msg);
                    if(!temp_query.empty())
                    {
                        std::cout<<"Query = "<<temp_query<<std::endl;
                        test = brokerQuery(temp_query);
                        for (auto& r : test)
                        {
                            for(pt iter = r.begin(); iter != r.end(); iter++)
                            {
                               // std::cout << iter->first << ": ";
                                out1 += iter->first + " | ";
                               // std::cout << iter->second <<std::endl ;
                                out2 += iter->second + " | " ;
                            }
                            out1 += "\n"; out2 +="\n";
                            out = out1 + out2 ;
                            std::cout << out ;
                            usleep(500000);
                            PC.send("Testing", broker::message{out});
                            usleep(500000);
                            out1=out2=out="\0";
                            break;
                        }
                    }

                }
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////

    QueryData brokerQuery(const std::string& queryString)
    {
        QueryData qd;
        osquery::queryExternal(queryString, qd);

        return qd;
    }

    //////////////////////////////////////////////////////////////////////////
    //*************************************************************************
        Status genConfig(std::map<std::string,std::string>& config)
        {
            return Status(0,"OK");
        }
    //////////////////////////////////////////////////////////////////////
      /* Status broker_osquery_init()
        {
            std::cout<<"In the broker_init() function"<<std::endl;
            //BrokerQueryPlugin b;
            auto status = Status(0,"OK");
            status = brokerConnection();
            if(status.ok())
            {
                brokerMessageQuery();
            }
            else
            {
                std::cout<<"Could not Connect";
            }
            return Status(0,"OK");
        }*/

};
void *broker_osquery_init(void *threadid)
{
    std::cout<<"In the broker_init() function"<<std::endl;
    BrokerQueryPlugin b;
    auto status = Status(0,"OK");
    status = b.brokerConnection();
    while(!status.ok())
    {
        b.brokerConnection();
    }
    b.brokerMessageQuery();
    pthread_exit(NULL);
}

//////////////////////////////////////////////////

// Note 3: Use REGISTER_EXTERNAL to define your plugin
REGISTER_EXTERNAL(BrokerQueryPlugin, "config", "brokerQuery")

int main(int argc, char* argv[]) {

    pthread_t broker_thread;
    int rc; long t=0;
    std::cout<<"Starting the program"<<std::endl;
    BrokerQueryPlugin b;
    //b.broker_osquery_init();
    rc = pthread_create(&broker_thread, NULL, broker_osquery_init, (void*)t);
    if(rc)
    {
        std::cout<< "Error in pthread_create(): " <<rc <<std::endl;
        exit(-1);
    }

  // Note 4: Start logging, threads, etc.
  osquery::Initializer runner(argc, argv, OSQUERY_EXTENSION);
  std::cout<<"Initialized OSquery"<<std::endl;

  // Note 5: Connect to osqueryi or osqueryd.
  auto status = startExtension("brokerQuery", "0.0.1");
  if (!status.ok()) {
    LOG(ERROR) << status.getMessage();
  }

  /*BrokerQueryPlugin b;
  b.genConfig();*/

  std::cout<<"Shutting downn extension"<<std::endl;
  // Finally shutdown.
  runner.shutdown();
  return 0;
}

<|endoftext|>


<commit_before>// Filename: 	main.cpp
// Author: 		Christopher Goes
// Course: 		CS 404 Machine Learning and Data Mining
// Semester: 	Spring 2016
// Description:	Assignment 3 main program logic

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <cmath>
#include "matrix.h"

#define DEBUG 0
#define DEBUGINPUT 0
#define DEBUG_RESULTS 0

using namespace std;

double activate( double input ); 	// Activation Function
double sigmoid( double input );     // Sigmoid function

int main() {

	// Initialization
	int numInputs = 0;
	int numOutputs = 0;
	int rows = 0;
	int cols = 0;
	int testRows = 0;
	int testCols = 0;
	double temp = -99;
	double bias = -1; // -1 is what the book uses.
	double eta = 0.025; // 0.25 is what the book uses. open to tweaking.
	int attempts = 5; // if debugging, SET THIS TO A SMALL NUMBER!
	int num_hidden_layers = 1; // is this a thing
	int num_hidden_nodes = 0;
	double max = 1;
	double min = 1;

	//		Training Data Input 	//
	cin >> numInputs;
	cin >> num_hidden_nodes;
	cin >> rows;
	cin >> cols;
	numOutputs = cols - numInputs;

	Matrix* tinput = new Matrix(rows, numInputs + 1);
	Matrix* toutput = new Matrix(rows, numOutputs);

	if(DEBUGINPUT) {
		cout << "Inputs: " << numInputs << "\nHidden Nodes: " << num_hidden_nodes << "\nRows: " << rows << "\nCols: " << cols << endl;
	}

	// Fill the matrix
	for(int r = 0; r < rows; r++) {
		for(int c = 0; c < numInputs; c++) {
			cin >> temp;
			if( temp > max ) max = temp;
			else if( temp < min ) min = temp;
			tinput->setValue( r, c, temp);
		}

		for(int c = 0; c < numOutputs; c++ ) {
			cin >> temp;
			if( temp > max ) max = temp;
			else if( temp < min ) min = temp;
			toutput->setValue( r, c, temp);
		}
	}

	// Append the bias
	for( int r = 0; r < rows; r++ ) {
		tinput->setValue(r, numInputs, bias);
	}
	numInputs++;

	if(DEBUGINPUT) {
		cout << "\nTraining Inputs..." << endl;
		tinput->printAll();
		cout << "\nTraining Outputs..." << endl;
		toutput->printAll();
	}

	//		Test Data Input 	//
	cin >> testRows;
	cin >> testCols;
	Matrix * testInput = new Matrix(testRows, testCols + 1);

	// Fill the matrix
	for(int r = 0; r < testRows; r++) {
		for(int c = 0; c < testCols; c++) {
			cin >> temp;
			if( temp > max ) max = temp;
			else if( temp < min ) min = temp;
			testInput->setValue(r, c, temp);
		}
	}

	// Append the bias
	for( int r = 0; r < testRows; r++ ) {
		testInput->setValue(r, testCols, bias);
	}
	testCols++;

	if(DEBUGINPUT) {
		cout << "\nTest Inputs matrix" << endl;
		testInput->printAll();
	}

	// 						//
	// 		* Training * 	//

	Matrix * hw = new Matrix(numInputs, numOutputs, 2);
	Matrix * ow = new Matrix(numInputs + 1, numOutputs, 2); // +1 for the extra bias between hidden and output layers
	Matrix * tempmat;
	double tResult = -66.6; //init values are paranoia for error catching
	double aResult = -55.0;
	double fResult = -42.0;
	temp = -99;

	if(DEBUG) {
		cout << "\nInitialized Hidden Weight matrix..." << endl;
		hw->printAll();
	}

	// Normalize our input (THIS COULD BE IMPROVED) TODO
	tinput->normalize(min, max);

	Matrix * deltah; // error in hidden layer
	Matrix * deltao; // error in output layer
	Matrix * a; // hidden layer output
	Matrix * y; // output layer output
	Matrix * hVec;
	Matrix * inVec;
	Matrix * v;
	Matrix * t;
	Matrix * sumh;
	Matrix * sumo;

	// re-implementation
	for( int attempt = 0; attempt < attempts; attempt++ ) {

		for( int r = 0; r < rows; r++ ) {
			inVec = tinput->getRow(r);
			t = toutput->getRow(r);

			// hidden layer
			a = inVec->dot(hw);
			a->sigmoid();
			hVec = new Matrix(a);
			hVec->data[0].push_back(bias);
			hVec->numCols++;

			// output layer
			y = hVec->dot(hw);
			y->sigmoid();

			// output error
			t = t->sub(y);
			t = t->dot(y);
			y->scalarPreSub(1.0);
			deltao = t->dot(y);

			// hidden error
			deltah = hVec;
			hVec->scalarPreSub(1.0);
			deltah->dot(hVec);
			hVec->scalarPreSub(1.0);
			tempmat = deltao->dot(ow);
			tempmat = tempmat->transpose();
			deltah = deltah->dot(tempmat);

			// update matricies
			tempmat = hVec->transpose();
			tempmat = tempmat->dot(deltao);
			tempmat = tempmat->dot(eta);
			ow = ow->add(tempmat);

			deltah->data[0].pop_back();
			deltah->numCols--;

			tempmat = inVec->transpose();
			tempmat = inVec->dot(deltah);
			tempmat = tempmat->dot(eta);
			hw = hw->add(tempmat);

		} // rows

	} // attempts

	//							//
	//		 	Testing			//
	tResult = -66.6;
	fResult = -42.0;
	double * tempResults = new double[numOutputs];
	double * finalResults = new double[numOutputs];

	cout <<  "BEGIN TESTING" << endl;

	for( int r = 0; r < rows; r++ ) { // Each row in testing set
		for (int i = 0; i < (numInputs - 1); i++) {
			cout << fixed <<  setprecision(2) <<  testInput->getValue(r, i) <<  " ";
		}

		for( int out = 0; out < numOutputs; out++ ) { // Each output

			tResult = 0.0; // clear tempResults before we add

			for( int i = 0; i < numInputs; i++ ) { // Each input
				//tResult += test->getValue(r, i) * w->getValue(i, out);
			}

			tResult = sigmoid(tResult);
			fResult = activate(tResult);
			tempResults[out] = tResult;
			finalResults[out] = fResult;

		} // per-output loop

		for( int i = 0; i < numOutputs; i++ ) {
			cout <<  fixed <<  setprecision(0) <<  finalResults[i] << " ";
		}
		cout <<  endl; // end the row's output
	} // row in set loop

	//		Cleanup		//
	delete tempResults;
	delete finalResults;
	delete hw;
	delete ow;
	delete tinput;
	delete toutput;
	delete testInput;
	return(0);
}

double activate( double input ) {
	if( input > 0.0 )
		return 1.0;
	else
		return 0.0;
}

double sigmoid( double input ) {
	return (2 / (1 + exp(-25 * input)) - 1);
}
<commit_msg>added test output and memory management<commit_after>// Filename: 	main.cpp
// Author: 		Christopher Goes
// Course: 		CS 404 Machine Learning and Data Mining
// Semester: 	Spring 2016
// Description:	Assignment 3 main program logic

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <cmath>
#include "matrix.h"

#define DEBUG 0
#define DEBUGINPUT 0
#define DEBUG_RESULTS 0

using namespace std;

double activate( double input ); 	// Activation Function
double sigmoid( double input );     // Sigmoid function

int main() {

	// Initialization
	int numInputs = 0;
	int numOutputs = 0;
	int rows = 0;
	int cols = 0;
	int testRows = 0;
	int testCols = 0;
	double temp = -99;
	double bias = -1; // -1 is what the book uses.
	double eta = 0.025; // 0.25 is what the book uses. open to tweaking.
	int attempts = 5; // if debugging, SET THIS TO A SMALL NUMBER!
	int num_hidden_layers = 1; // is this a thing
	int num_hidden_nodes = 0;
	double max = 1;
	double min = 1;

	//		Training Data Input 	//
	cin >> numInputs;
	cin >> num_hidden_nodes;
	cin >> rows;
	cin >> cols;
	numOutputs = cols - numInputs;

	Matrix* tinput = new Matrix(rows, numInputs + 1);
	Matrix* toutput = new Matrix(rows, numOutputs);

	if(DEBUGINPUT) {
		cout << "Inputs: " << numInputs << "\nHidden Nodes: " << num_hidden_nodes << "\nRows: " << rows << "\nCols: " << cols << endl;
	}

	// Fill the matrix
	for(int r = 0; r < rows; r++) {
		for(int c = 0; c < numInputs; c++) {
			cin >> temp;
			if( temp > max ) max = temp;
			else if( temp < min ) min = temp;
			tinput->setValue( r, c, temp);
		}

		for(int c = 0; c < numOutputs; c++ ) {
			cin >> temp;
			if( temp > max ) max = temp;
			else if( temp < min ) min = temp;
			toutput->setValue( r, c, temp);
		}
	}

	// Append the bias
	for( int r = 0; r < rows; r++ ) {
		tinput->setValue(r, numInputs, bias);
	}
	numInputs++;

	if(DEBUGINPUT) {
		cout << "\nTraining Inputs..." << endl;
		tinput->printAll();
		cout << "\nTraining Outputs..." << endl;
		toutput->printAll();
	}

	//		Test Data Input 	//
	cin >> testRows;
	cin >> testCols;
	Matrix * testInput = new Matrix(testRows, testCols + 1);

	// Fill the matrix
	for(int r = 0; r < testRows; r++) {
		for(int c = 0; c < testCols; c++) {
			cin >> temp;
			if( temp > max ) max = temp;
			else if( temp < min ) min = temp;
			testInput->setValue(r, c, temp);
		}
	}

	// Append the bias
	for( int r = 0; r < testRows; r++ ) {
		testInput->setValue(r, testCols, bias);
	}
	testCols++;

	if(DEBUGINPUT) {
		cout << "\nTest Inputs matrix" << endl;
		testInput->printAll();
	}

	// 						//
	// 		* Training * 	//

	Matrix * hw = new Matrix(numInputs, numOutputs, 2);
	Matrix * ow = new Matrix(numInputs + 1, numOutputs, 2); // +1 for the extra bias between hidden and output layers
	Matrix * tempmat;
	double tResult = -66.6; //init values are paranoia for error catching
	double aResult = -55.0;
	double fResult = -42.0;
	temp = -99;

	if(DEBUG) {
		cout << "\nInitialized Hidden Weight matrix..." << endl;
		hw->printAll();
	}

	// Normalize our input (THIS COULD BE IMPROVED) TODO
	tinput->normalize(min, max);

	Matrix * deltah; // error in hidden layer
	Matrix * deltao; // error in output layer
	Matrix * a; // hidden layer output
	Matrix * y; // output layer output
	Matrix * hVec;
	Matrix * inVec;
	Matrix * t;

	// re-implementation
	for( int attempt = 0; attempt < attempts; attempt++ ) {

		for( int r = 0; r < rows; r++ ) {
			inVec = tinput->getRow(r);
			t = toutput->getRow(r);

			// hidden layer
			a = inVec->dot(hw);
			a->sigmoid();
			hVec = new Matrix(a);
			hVec->data[0].push_back(bias);
			hVec->numCols++;

			// output layer
			y = hVec->dot(hw);
			y->sigmoid();

			// output error
			t = t->sub(y);
			t = t->dot(y);
			y->scalarPreSub(1.0);
			deltao = t->dot(y);

			// hidden error
			deltah = hVec;
			hVec->scalarPreSub(1.0);
			deltah->dot(hVec);
			hVec->scalarPreSub(1.0);
			tempmat = deltao->dot(ow);
			tempmat = tempmat->transpose();
			deltah = deltah->dot(tempmat);

			// update matricies
			tempmat = hVec->transpose();
			tempmat = tempmat->dot(deltao);
			tempmat = tempmat->dot(eta);
			ow = ow->add(tempmat);

			deltah->data[0].pop_back();
			deltah->numCols--;

			tempmat = inVec->transpose();
			tempmat = inVec->dot(deltah);
			tempmat = tempmat->dot(eta);
			hw = hw->add(tempmat);

			delete deltao;
			delete deltah;
			delete a;
			delete y;
			delete hVec;
			delete inVec;
			delete t;
		} // rows

	} // attempts

	//							//
	//		 	Testing			//
	tResult = -66.6;
	fResult = -42.0;
	//double * tempResults = new double[numOutputs];
	//double * finalResults = new double[numOutputs];

	cout <<  "BEGIN TESTING" << endl;

	for( int r = 0; r < rows; r++ ) { // Each row in testing set
		inVec = testInput->getRow(r);

		for (int i = 0; i < (numInputs - 1); i++) {
			cout << fixed <<  setprecision(2) <<  testInput->getValue(r, i) <<  " ";
		}

		// hidden layer
		a = inVec->dot(hw);
		a->sigmoid();
		hVec = new Matrix(a);
		hVec->data[0].push_back(bias);
		hVec->numCols++;

		// output layer
		y = hVec->dot(hw);
		y->sigmoid();

		for( int i = 0; i < numOutputs; i++ ) {
			cout <<  fixed <<  setprecision(0) <<  y->getValue(r, i) << " ";
		}
		cout <<  endl; // end the row's output
	} // row in set loop

	//		Final Cleanup		//
	delete hw;
	delete ow;
	delete tinput;
	delete toutput;
	delete testInput;
	return(0);
}

double activate( double input ) {
	if( input > 0.0 )
		return 1.0;
	else
		return 0.0;
}

double sigmoid( double input ) {
	return (2 / (1 + exp(-25 * input)) - 1);
}
<|endoftext|>


<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

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 RESEMBLA_RESEMBLA_ENSEMBLE_HPP
#define RESEMBLA_RESEMBLA_ENSEMBLE_HPP

#include <math.h>
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include <algorithm>

#include <simstring/simstring.h>

#include "resembla_interface.hpp"
#include "eliminator.hpp"

namespace resembla {

template<typename Indexer, typename ScoreFunction>
class ResemblaEnsemble: public ResemblaInterface
{
public:
    ResemblaEnsemble(const std::string& db_path, const std::string& index_path,
            std::shared_ptr<Indexer> indexer, std::shared_ptr<ScoreFunction> score,
            const std::string& measure_name, const size_t max_candidate = 0):
        indexer(indexer), score(score),
        measure_name(measure_name), max_candidate(max_candidate),
        total_weight(0.0)
    {
        load(db_path, index_path);
    }

    void append(const std::shared_ptr<ResemblaInterface> resembla, double weight = 1.0)
    {
        children.push_back(std::make_pair(resembla, weight));
        total_weight += weight;
    }

    std::vector<output_type> find(const string_type& query,
            double threshold = 0.0, size_t max_response = 0) const
    {
        string_type search_query = indexer->index(query);

        // search from N-gram index
        std::vector<string_type> simstring_result;
        {
            std::lock_guard<std::mutex> lock(mutex_simstring);
            db.retrieve(search_query, simstring_measure, simstring_threshold, std::back_inserter(simstring_result));
        }
        if(simstring_result.empty()){
            return {};
        }
        else if(simstring_result.size() > max_candidate){
            Eliminator<string_type> eliminate(search_query);
            eliminate(simstring_result, max_candidate, true);
        }

        return eval(query, simstring_result, threshold, max_response);
    }

    std::vector<output_type> eval(const string_type& query, const std::vector<string_type>& candidates,
            double threshold = 0.0, size_t max_response = 0) const
    {
        std::unordered_map<string_type, std::vector<double>> work;
        for(const auto& child: children){
            for(const auto& r: child->eval(query, candidates, 0.0, 0)){
                auto p = work.insert(std::make_pair(r.text, r.score));
                if(!p.second){
                    p.first += r.score;
                }
            }
        }

        std::vector<output_type> results;
        for(const auto& p: work){
            double score = score_func(weights, p.second);
            if(score >= threshold){
                results.push_back({p.first, measure_name, score});
            }
        }

        if(max_response != 0 && response.size() > max_response){
            std::partial_sort(results.begin(), results.begin() + max_response, results.end());
            results.erase(results.begin() + max_response, results.end());
        }
        else{
            std::sort(results.begin(), results.end());
        }

        return response;
    }

protected:
    struct Child
    {
        std::string name;
        std::shared_ptr<ResemblaInterface> resembla;
        double weight;
    };

    // name to be used in response
    const std::string measure_name;

    const size_t max_candidate;

    double total_weight;

    std::vector<Child> children;
};

}
#endif
<commit_msg>simplify code<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

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 RESEMBLA_RESEMBLA_ENSEMBLE_HPP
#define RESEMBLA_RESEMBLA_ENSEMBLE_HPP

#include <math.h>
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include <algorithm>

#include <simstring/simstring.h>

#include "resembla_interface.hpp"
#include "eliminator.hpp"

namespace resembla {

template<typename Indexer, typename ScoreFunction>
class ResemblaEnsemble: public ResemblaInterface
{
public:
    ResemblaEnsemble(const std::string& db_path, const std::string& index_path,
            std::shared_ptr<Indexer> indexer, std::shared_ptr<ScoreFunction> score,
            const std::string& measure_name, const size_t max_candidate = 0):
        indexer(indexer), score(score),
        measure_name(measure_name), max_candidate(max_candidate),
        total_weight(0.0)
    {
        load(db_path, index_path);
    }

    void append(const std::shared_ptr<ResemblaInterface> resembla, double weight = 1.0)
    {
        children.push_back(std::make_pair(resembla, weight));
        weights.push_back(weight);
        total_weight += weight;
    }

    std::vector<output_type> find(const string_type& query,
            double threshold = 0.0, size_t max_response = 0) const
    {
        string_type search_query = indexer->index(query);

        // search from N-gram index
        std::vector<string_type> simstring_result;
        {
            std::lock_guard<std::mutex> lock(mutex_simstring);
            db.retrieve(search_query, simstring_measure, simstring_threshold, std::back_inserter(simstring_result));
        }
        if(simstring_result.empty()){
            return {};
        }
        else if(simstring_result.size() > max_candidate){
            Eliminator<string_type> eliminate(search_query);
            eliminate(simstring_result, max_candidate, true);
        }

        return eval(query, simstring_result, threshold, max_response);
    }

    std::vector<output_type> eval(const string_type& query, const std::vector<string_type>& candidates,
            double threshold = 0.0, size_t max_response = 0) const
    {
        std::unordered_map<string_type, std::vector<double>> work;
        for(const auto& resembla: children){
            for(const auto& r: resembla->eval(query, candidates, 0.0, 0)){
                auto p = work.insert(std::make_pair(r.text, {r.score}));
                if(!p.second){
                    p.first.push_back(r.score);
                }
            }
        }

        std::vector<output_type> results;
        for(const auto& p: work){
            double score = score_func(weights, p.second);
            if(score >= threshold){
                results.push_back({p.first, measure_name, score});
            }
        }

        if(max_response != 0 && response.size() > max_response){
            std::partial_sort(results.begin(), results.begin() + max_response, results.end());
            results.erase(results.begin() + max_response, results.end());
        }
        else{
            std::sort(results.begin(), results.end());
        }

        return response;
    }

protected:
    // name to be used in response
    const std::string measure_name;

    const size_t max_candidate;

    std::vector<std::shared_ptr<ResemblaInterface>> children;
    std::vector<double> weights;
    double total_weight;
};

}
#endif
<|endoftext|>


<commit_before>#include "map/place_page_info.hpp"
#include "map/reachable_by_taxi_checker.hpp"

#include "partners_api/ads_engine.hpp"
#include "partners_api/banner.hpp"

#include "indexer/feature_utils.hpp"
#include "indexer/osm_editor.hpp"

#include "platform/measurement_utils.hpp"
#include "platform/preferred_languages.hpp"
#include "platform/settings.hpp"

namespace place_page
{
char const * const Info::kSubtitleSeparator = " • ";
char const * const Info::kStarSymbol = "★";
char const * const Info::kMountainSymbol = "▲";
char const * const Info::kEmptyRatingSymbol = "-";
char const * const Info::kPricingSymbol = "$";

bool Info::IsFeature() const { return m_featureID.IsValid(); }
bool Info::IsBookmark() const { return m_bac.IsValid(); }
bool Info::IsMyPosition() const { return m_isMyPosition; }
bool Info::IsRoutePoint() const { return m_isRoutePoint; }
bool Info::IsSponsored() const { return m_sponsoredType != SponsoredType::None; }
bool Info::IsNotEditableSponsored() const
{
  return m_sponsoredType != SponsoredType::None && m_sponsoredType != SponsoredType::Opentable;
}

bool Info::ShouldShowAddPlace() const
{
  auto const isPointOrBuilding = IsPointType() || IsBuilding();
  return m_canEditOrAdd && !(IsFeature() && isPointOrBuilding);
}

bool Info::ShouldShowAddBusiness() const { return m_canEditOrAdd && IsBuilding(); }

bool Info::ShouldShowEditPlace() const
{
  return m_canEditOrAdd &&
         // TODO(mgsergio): Does IsFeature() imply !IsMyPosition()?
         !IsMyPosition() && IsFeature();
}

bool Info::HasApiUrl() const { return !m_apiUrl.empty(); }
bool Info::HasWifi() const { return GetInternet() == osm::Internet::Wlan; }

string Info::FormatNewBookmarkName() const
{
  string const title = GetTitle();
  if (title.empty())
    return GetLocalizedType();
  return title;
}

string Info::GetTitle() const
{
  if (!m_customName.empty())
    return m_customName;

  auto const mwmInfo = GetID().m_mwmId.GetInfo();

  string primaryName;
  if (mwmInfo)
  {
    auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm());
    string secondaryName;
    feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName);
  }
  return primaryName;
}

string Info::GetSecondaryTitle() const
{
  auto const mwmInfo = GetID().m_mwmId.GetInfo();

  string secondaryName;
  if (mwmInfo)
  {
    auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm());
    string primaryName;
    feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName);
  }
  return secondaryName;
}

string Info::GetSubtitle() const
{
  if (!IsFeature())
  {
    if (IsBookmark())
      return m_bookmarkCategoryName;
    return {};
  }

  vector<string> values;

  // Bookmark category.
  if (IsBookmark())
    values.push_back(m_bookmarkCategoryName);

  // Type.
  values.push_back(GetLocalizedType());

  // Flats.
  string const flats = GetFlats();
  if (!flats.empty())
    values.push_back(flats);

  // Cuisines.
  for (string const & cuisine : GetLocalizedCuisines())
    values.push_back(cuisine);

  // Stars.
  string const stars = FormatStars();
  if (!stars.empty())
    values.push_back(stars);

  // Operator.
  string const op = GetOperator();
  if (!op.empty())
    values.push_back(op);

  // Elevation.
  string const eleStr = GetElevationFormatted();
  if (!eleStr.empty())
    values.push_back(kMountainSymbol + eleStr);
  if (HasWifi())
    values.push_back(m_localizedWifiString);

  return strings::JoinStrings(values, kSubtitleSeparator);
}

string Info::FormatStars() const
{
  string stars;
  for (int i = 0; i < GetStars(); ++i)
    stars.append(kStarSymbol);
  return stars;
}

string Info::GetFormattedCoordinate(bool isDMS) const
{
  auto const & ll = GetLatLon();
  return isDMS ? measurement_utils::FormatLatLon(ll.lat, ll.lon, true)
               : measurement_utils::FormatLatLonAsDMS(ll.lat, ll.lon, 2);
}

string Info::GetCustomName() const { return m_customName; }
BookmarkAndCategory Info::GetBookmarkAndCategory() const { return m_bac; }
string Info::GetBookmarkCategoryName() const { return m_bookmarkCategoryName; }
string const & Info::GetApiUrl() const { return m_apiUrl; }
string const & Info::GetSponsoredUrl() const { return m_sponsoredUrl; }
string const & Info::GetSponsoredDescriptionUrl() const { return m_sponsoredDescriptionUrl; }
string const & Info::GetSponsoredReviewUrl() const { return m_sponsoredReviewUrl; }

string Info::GetRatingFormatted() const
{
  if (!IsSponsored())
    return string();

  auto const r = GetMetadata().Get(feature::Metadata::FMD_RATING);
  char const * rating = r.empty() ? kEmptyRatingSymbol : r.c_str();
  int const size = snprintf(nullptr, 0, m_localizedRatingString.c_str(), rating);
  if (size < 0)
  {
    LOG(LERROR, ("Incorrect size for string:", m_localizedRatingString, ", rating:", rating));
    return string();
  }

  vector<char> buf(size + 1);
  snprintf(buf.data(), buf.size(), m_localizedRatingString.c_str(), rating);
  return string(buf.begin(), buf.end());
}

string Info::GetApproximatePricing() const
{
  if (!IsSponsored())
    return string();

  int pricing;
  if (!strings::to_int(GetMetadata().Get(feature::Metadata::FMD_PRICE_RATE), pricing))
    return string();

  string result;
  for (auto i = 0; i < pricing; i++)
    result.append(kPricingSymbol);

  return result;
}

bool Info::HasBanner() const
{
  if (!m_adsEngine)
    return false;

  if (IsMyPosition())
    return false;

  return m_adsEngine->HasBanner(m_types, m_topmostCountryIds, languages::GetCurrentNorm());
}

vector<ads::Banner> Info::GetBanners() const
{
  if (!m_adsEngine)
    return {};

  return m_adsEngine->GetBanners(m_types, m_topmostCountryIds, languages::GetCurrentNorm());
}

bool Info::IsReachableByTaxi() const
{
  return IsReachableByTaxiChecker::Instance()(m_types);
}

void Info::SetMercator(m2::PointD const & mercator) { m_mercator = mercator; }
vector<string> Info::GetRawTypes() const { return m_types.ToObjectNames(); }
string const & Info::GetBookingSearchUrl() const { return m_bookingSearchUrl; }
LocalAdsStatus Info::GetLocalAdsStatus() const { return m_localAdsStatus; }
string const & Info::GetLocalAdsUrl() const { return m_localAdsUrl; }
}  // namespace place_page
<commit_msg>Added wheelchair sybmol into place page subtitle.<commit_after>#include "map/place_page_info.hpp"
#include "map/reachable_by_taxi_checker.hpp"

#include "partners_api/ads_engine.hpp"
#include "partners_api/banner.hpp"

#include "indexer/feature_utils.hpp"
#include "indexer/osm_editor.hpp"

#include "platform/measurement_utils.hpp"
#include "platform/preferred_languages.hpp"
#include "platform/settings.hpp"

namespace place_page
{
char const * const Info::kSubtitleSeparator = " • ";
char const * const Info::kStarSymbol = "★";
char const * const Info::kMountainSymbol = "▲";
char const * const Info::kEmptyRatingSymbol = "-";
char const * const Info::kPricingSymbol = "$";
char const * const kWheelchairSymbol = u8"\u267F";

bool Info::IsFeature() const { return m_featureID.IsValid(); }
bool Info::IsBookmark() const { return m_bac.IsValid(); }
bool Info::IsMyPosition() const { return m_isMyPosition; }
bool Info::IsRoutePoint() const { return m_isRoutePoint; }
bool Info::IsSponsored() const { return m_sponsoredType != SponsoredType::None; }
bool Info::IsNotEditableSponsored() const
{
  return m_sponsoredType != SponsoredType::None && m_sponsoredType != SponsoredType::Opentable;
}

bool Info::ShouldShowAddPlace() const
{
  auto const isPointOrBuilding = IsPointType() || IsBuilding();
  return m_canEditOrAdd && !(IsFeature() && isPointOrBuilding);
}

bool Info::ShouldShowAddBusiness() const { return m_canEditOrAdd && IsBuilding(); }

bool Info::ShouldShowEditPlace() const
{
  return m_canEditOrAdd &&
         // TODO(mgsergio): Does IsFeature() imply !IsMyPosition()?
         !IsMyPosition() && IsFeature();
}

bool Info::HasApiUrl() const { return !m_apiUrl.empty(); }
bool Info::HasWifi() const { return GetInternet() == osm::Internet::Wlan; }

string Info::FormatNewBookmarkName() const
{
  string const title = GetTitle();
  if (title.empty())
    return GetLocalizedType();
  return title;
}

string Info::GetTitle() const
{
  if (!m_customName.empty())
    return m_customName;

  auto const mwmInfo = GetID().m_mwmId.GetInfo();

  string primaryName;
  if (mwmInfo)
  {
    auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm());
    string secondaryName;
    feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName);
  }
  return primaryName;
}

string Info::GetSecondaryTitle() const
{
  auto const mwmInfo = GetID().m_mwmId.GetInfo();

  string secondaryName;
  if (mwmInfo)
  {
    auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm());
    string primaryName;
    feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName);
  }
  return secondaryName;
}

string Info::GetSubtitle() const
{
  if (!IsFeature())
  {
    if (IsBookmark())
      return m_bookmarkCategoryName;
    return {};
  }

  vector<string> values;

  // Bookmark category.
  if (IsBookmark())
    values.push_back(m_bookmarkCategoryName);

  // Type.
  values.push_back(GetLocalizedType());

  // Flats.
  string const flats = GetFlats();
  if (!flats.empty())
    values.push_back(flats);

  // Cuisines.
  for (string const & cuisine : GetLocalizedCuisines())
    values.push_back(cuisine);

  // Stars.
  string const stars = FormatStars();
  if (!stars.empty())
    values.push_back(stars);

  // Operator.
  string const op = GetOperator();
  if (!op.empty())
    values.push_back(op);

  // Elevation.
  string const eleStr = GetElevationFormatted();
  if (!eleStr.empty())
    values.push_back(kMountainSymbol + eleStr);
  if (HasWifi())
    values.push_back(m_localizedWifiString);

  // Wheelchair
  if (GetWheelchairType() == wheelchair::Type::Yes)
    values.push_back(kWheelchairSymbol);

  return strings::JoinStrings(values, kSubtitleSeparator);
}

string Info::FormatStars() const
{
  string stars;
  for (int i = 0; i < GetStars(); ++i)
    stars.append(kStarSymbol);
  return stars;
}

string Info::GetFormattedCoordinate(bool isDMS) const
{
  auto const & ll = GetLatLon();
  return isDMS ? measurement_utils::FormatLatLon(ll.lat, ll.lon, true)
               : measurement_utils::FormatLatLonAsDMS(ll.lat, ll.lon, 2);
}

string Info::GetCustomName() const { return m_customName; }
BookmarkAndCategory Info::GetBookmarkAndCategory() const { return m_bac; }
string Info::GetBookmarkCategoryName() const { return m_bookmarkCategoryName; }
string const & Info::GetApiUrl() const { return m_apiUrl; }
string const & Info::GetSponsoredUrl() const { return m_sponsoredUrl; }
string const & Info::GetSponsoredDescriptionUrl() const { return m_sponsoredDescriptionUrl; }
string const & Info::GetSponsoredReviewUrl() const { return m_sponsoredReviewUrl; }

string Info::GetRatingFormatted() const
{
  if (!IsSponsored())
    return string();

  auto const r = GetMetadata().Get(feature::Metadata::FMD_RATING);
  char const * rating = r.empty() ? kEmptyRatingSymbol : r.c_str();
  int const size = snprintf(nullptr, 0, m_localizedRatingString.c_str(), rating);
  if (size < 0)
  {
    LOG(LERROR, ("Incorrect size for string:", m_localizedRatingString, ", rating:", rating));
    return string();
  }

  vector<char> buf(size + 1);
  snprintf(buf.data(), buf.size(), m_localizedRatingString.c_str(), rating);
  return string(buf.begin(), buf.end());
}

string Info::GetApproximatePricing() const
{
  if (!IsSponsored())
    return string();

  int pricing;
  if (!strings::to_int(GetMetadata().Get(feature::Metadata::FMD_PRICE_RATE), pricing))
    return string();

  string result;
  for (auto i = 0; i < pricing; i++)
    result.append(kPricingSymbol);

  return result;
}

bool Info::HasBanner() const
{
  if (!m_adsEngine)
    return false;

  if (IsMyPosition())
    return false;

  return m_adsEngine->HasBanner(m_types, m_topmostCountryIds, languages::GetCurrentNorm());
}

vector<ads::Banner> Info::GetBanners() const
{
  if (!m_adsEngine)
    return {};

  return m_adsEngine->GetBanners(m_types, m_topmostCountryIds, languages::GetCurrentNorm());
}

bool Info::IsReachableByTaxi() const
{
  return IsReachableByTaxiChecker::Instance()(m_types);
}

void Info::SetMercator(m2::PointD const & mercator) { m_mercator = mercator; }
vector<string> Info::GetRawTypes() const { return m_types.ToObjectNames(); }
string const & Info::GetBookingSearchUrl() const { return m_bookingSearchUrl; }
LocalAdsStatus Info::GetLocalAdsStatus() const { return m_localAdsStatus; }
string const & Info::GetLocalAdsUrl() const { return m_localAdsUrl; }
}  // namespace place_page
<|endoftext|>


<commit_before>#include "utAllocore.h"

int utFile() {

	#define DELIM AL_FILE_DELIMITER_STR

	// static functions
	assert(File::exists("."));
	//assert(File::exists("." DELIM)); // fails under win32

	assert(File::isDirectory("."));
	assert(File::isDirectory(".." ));
	assert(!File::isDirectory(".." DELIM ".." DELIM "Makefile"));

	assert(
		File::conformDirectory("test")
		== "test" DELIM
	);
	assert(
		File::conformDirectory("test" DELIM)
		== "test" DELIM
	);

	assert(
		File::conformPathToOS("..\\../Makefile")
		== ".." DELIM ".." DELIM "Makefile"
	);

	assert(
		File::conformPathToOS("..\\../")
		== ".." DELIM ".." DELIM
	);

	assert(
		File::conformPathToOS("..\\..")
		== ".." DELIM ".." DELIM
	);

	// simple file/directory searching
	{
		std::string dir;

		// Search for file (that exists and probably will not be moved...)
		std::string find = "Makefile";

		bool r = File::searchBack(dir, find);
		assert(r);
		assert(File::exists(dir + find));

		find = ".." DELIM + find;	// check for a file with path
		r = File::searchBack(dir, find);
		assert(r);
		assert(File::exists(dir + find));

		assert(!File::searchBack(dir, "thisdirectorydoesnotexist" DELIM "thisfiledoesnotexist.ext"));
	}

	{
		const char * path = "utFile.txt";
		const char * text = "This is a test of AlloCore file i/o functionality. You can safely delete this file.";

		// write data
		File f(path, "w");
		assert(!f.opened());

		assert(f.open());
		assert(f.opened());
		assert(File::exists(path));

		assert(
			f.write(text, strlen(text))
		);

		assert(f.size() == (int)strlen(text));

		f.close();
		assert(!f.opened());
		assert(File::exists(path));

		// read data
		f.mode("r").open();
		assert(f.opened());

		const char * read = f.readAll();

		assert(f.size() == (int)strlen(text));

		for(int i=0; i<f.size(); ++i){
			assert(read[i] == text[i]);
//			printf("%c", read[i]);
		}

		f.close();

		f.path(
			"thisdirectroydoesnotexist" DELIM
			"neitherdoesthisone" DELIM
			"notafile.txt"
		);
		assert(!f.open());
	}

	{
		assert(Dir::make("utFileTestDir"));
		assert(Dir::remove("utFileTestDir"));

		// For now, just make sure this compiles and doesn't crash. :)
		Dir dir;
		if(dir.open("/")){
			for(int i=0; i<1; ++i){
				dir.rewind();
				while(dir.read()){
					//printf("%c %s\n", dir.entry().type() == FileInfo::DIR ? 'd':' ', dir.entry().name().c_str());
				}
			}
		}
	}

	{
		// TODO:
		SearchPaths sp;
		//printf("%s\n", sp.appPath().c_str());
	}

	{
		// TODO:
		FilePath fp("file.txt", "path");

		//printf("%s\n", fp.filepath().c_str());
	}

	#undef DELIM
	return 0;
}
<commit_msg>Fix for failing test on allocoreTests<commit_after>#include "utAllocore.h"

int utFile() {

	#define DELIM AL_FILE_DELIMITER_STR

	// static functions
	assert(File::exists("."));
	//assert(File::exists("." DELIM)); // fails under win32

	assert(File::isDirectory("."));
	assert(File::isDirectory(".." ));
	assert(!File::isDirectory(".." DELIM ".." DELIM "Makefile"));

	assert(
		File::conformDirectory("test")
		== "test" DELIM
	);
	assert(
		File::conformDirectory("test" DELIM)
		== "test" DELIM
	);

	assert(
		File::conformPathToOS("..\\../Makefile")
		== ".." DELIM ".." DELIM "Makefile"
	);

	assert(
		File::conformPathToOS("..\\../")
		== ".." DELIM ".." DELIM
	);

	assert(
		File::conformPathToOS("..\\..")
		== ".." DELIM ".." DELIM
	);

	// simple file/directory searching
	{
		std::string dir;

		// Search for file (that exists and probably will not be moved...)
		std::string find = "Makefile";

		bool r = File::searchBack(dir, find);
		assert(r);
		assert(File::exists(dir + find));

		find = "allocore" DELIM + find;	// check for a file with path
		r = File::searchBack(dir, find);
		assert(r);
		assert(File::exists(dir + find));

		assert(!File::searchBack(dir, "thisdirectorydoesnotexist" DELIM "thisfiledoesnotexist.ext"));
	}

	{
		const char * path = "utFile.txt";
		const char * text = "This is a test of AlloCore file i/o functionality. You can safely delete this file.";

		// write data
		File f(path, "w");
		assert(!f.opened());

		assert(f.open());
		assert(f.opened());
		assert(File::exists(path));

		assert(
			f.write(text, strlen(text))
		);

		assert(f.size() == (int)strlen(text));

		f.close();
		assert(!f.opened());
		assert(File::exists(path));

		// read data
		f.mode("r").open();
		assert(f.opened());

		const char * read = f.readAll();

		assert(f.size() == (int)strlen(text));

		for(int i=0; i<f.size(); ++i){
			assert(read[i] == text[i]);
//			printf("%c", read[i]);
		}

		f.close();

		f.path(
			"thisdirectroydoesnotexist" DELIM
			"neitherdoesthisone" DELIM
			"notafile.txt"
		);
		assert(!f.open());
	}

	{
		assert(Dir::make("utFileTestDir"));
		assert(Dir::remove("utFileTestDir"));

		// For now, just make sure this compiles and doesn't crash. :)
		Dir dir;
		if(dir.open("/")){
			for(int i=0; i<1; ++i){
				dir.rewind();
				while(dir.read()){
					//printf("%c %s\n", dir.entry().type() == FileInfo::DIR ? 'd':' ', dir.entry().name().c_str());
				}
			}
		}
	}

	{
		// TODO:
		SearchPaths sp;
		//printf("%s\n", sp.appPath().c_str());
	}

	{
		// TODO:
		FilePath fp("file.txt", "path");

		//printf("%s\n", fp.filepath().c_str());
	}

	#undef DELIM
	return 0;
}
<|endoftext|>


<commit_before>/**
 * \file drawSliceInPhi.cc
 * \example segmented/drawSliceInPhi.cc
 */
// Draw weighting potential of a segment of Siegfried (6 segments in phi)
void CalculateWeightingPotential()
{
   GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi;
   siegfried->V0=0*GeFiCa::volt;
   siegfried->V1=1*GeFiCa::volt;
   siegfried->SegmentNum=6;
   siegfried->SegmentID=1;
   siegfried->CalculatePotential(GeFiCa::kSOR2);
   siegfried->SaveField("siegfried.root");
}
//______________________________________________________________________________
//
void DrawWeightingPotential()
{
   // pick up a good default drawing style to modify
   gROOT->SetStyle("Plain");
   gStyle->SetTitleFont(132,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ");
   gStyle->SetLabelFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ");
   gStyle->SetPadRightMargin(0.12);
   gStyle->SetPadLeftMargin(0.08);
   gStyle->SetPadTopMargin(0.02);
   // create a smoother palette than the default one
   const int nRGBs = 5;
   const int nCont = 255;
   double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
   double red[nRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
   double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
   double blue[nRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };
   TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont);
   gStyle->SetNumberContours(nCont);
   // make a square canvas
   TCanvas *c = new TCanvas("c", "c", 450, 450);
   c->SetLogz();
   // load data and draw
   TChain *t = new TChain("t");
   t->Add("siegfried.root");
   t->Draw("c1*sin(c2):c1*cos(c2):v","","colz");
   // fine tune plot
   TH2F *h = (TH2F*) gPad->GetPrimitive("htemp");
   h->SetTitle(";x [cm];y [cm];weighting potential [V]");
   h->GetYaxis()->SetTitleOffset(0.7);
   h->GetZaxis()->SetTitleOffset(-0.4);
   h->GetXaxis()->CenterTitle();
   h->GetYaxis()->CenterTitle();
   h->GetZaxis()->CenterTitle();
   // widen the color palette
   gPad->Update(); // create the palette by forcely drawing the plot
   TPaletteAxis *palette =
      (TPaletteAxis*) h->GetListOfFunctions()->FindObject("palette");
   palette->SetX2NDC(0.94);
   h->Draw("colz"); // let the new setup take effect
   // draw segmentation scheme
   GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi();
   double r=siegfried->RUpperBound, x=r*cos(3.14/3), y=r*sin(3.14/3);
   TLine *l1 = new TLine(-r,0,r,0);
   l1->SetLineColor(kWhite);
   l1->SetLineStyle(kDashed);
   l1->Draw();
   TLine *l2 = new TLine(-x,-y,x,y);
   l2->SetLineColor(kWhite);
   l2->SetLineStyle(kDashed);
   l2->Draw();
   TLine *l3 = new TLine(-x,y,x,-y);
   l3->SetLineColor(kWhite);
   l3->SetLineStyle(kDashed);
   l3->Draw();
}
//______________________________________________________________________________
//
void drawSliceInPhi()
{
   if (1||gSystem->Which(".","siegfried.root")==0) CalculateWeightingPotential();
   DrawWeightingPotential();
}
<commit_msg>minor change<commit_after>// Draw weighting potential of a segment of Siegfried (6 segments in phi)
void CalculateWeightingPotential()
{
   GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi;
   siegfried->V0=0*GeFiCa::volt;
   siegfried->V1=1*GeFiCa::volt;
   siegfried->SegmentNum=6;
   siegfried->SegmentID=1;
   siegfried->CalculatePotential(GeFiCa::kSOR2);
   siegfried->SaveField("siegfried.root");
}
//______________________________________________________________________________
//
void DrawWeightingPotential()
{
   // pick up a good default drawing style to modify
   gROOT->SetStyle("Plain");
   gStyle->SetTitleFont(132,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ");
   gStyle->SetLabelFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ");
   gStyle->SetPadRightMargin(0.12);
   gStyle->SetPadLeftMargin(0.08);
   gStyle->SetPadTopMargin(0.02);
   // create a smoother palette than the default one
   const int nRGBs = 5;
   const int nCont = 255;
   double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
   double red[nRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
   double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
   double blue[nRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };
   TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont);
   gStyle->SetNumberContours(nCont);
   // make a square canvas
   TCanvas *c = new TCanvas("c", "c", 450, 450);
   c->SetLogz();
   // load data and draw
   TChain *t = new TChain("t");
   t->Add("siegfried.root");
   t->Draw("c1*sin(c2):c1*cos(c2):v","","colz");
   // fine tune plot
   TH2F *h = (TH2F*) gPad->GetPrimitive("htemp");
   h->SetTitle(";x [cm];y [cm];weighting potential [V]");
   h->GetYaxis()->SetTitleOffset(0.7);
   h->GetZaxis()->SetTitleOffset(-0.4);
   h->GetXaxis()->CenterTitle();
   h->GetYaxis()->CenterTitle();
   h->GetZaxis()->CenterTitle();
   // widen the color palette
   gPad->Update(); // create the palette by forcedly drawing the plot
   TPaletteAxis *palette =
      (TPaletteAxis*) h->GetListOfFunctions()->FindObject("palette");
   palette->SetX2NDC(0.94);
   h->Draw("colz"); // let the new setup take effect
   // draw segmentation scheme
   GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi();
   double r=siegfried->RUpperBound, x=r*cos(3.14/3), y=r*sin(3.14/3);
   TLine *l1 = new TLine(-r,0,r,0);
   l1->SetLineColor(kWhite);
   l1->SetLineStyle(kDashed);
   l1->Draw();
   TLine *l2 = new TLine(-x,-y,x,y);
   l2->SetLineColor(kWhite);
   l2->SetLineStyle(kDashed);
   l2->Draw();
   TLine *l3 = new TLine(-x,y,x,-y);
   l3->SetLineColor(kWhite);
   l3->SetLineStyle(kDashed);
   l3->Draw();
}
//______________________________________________________________________________
//
void drawSliceInPhi()
{
   if (1||gSystem->Which(".","siegfried.root")==0) CalculateWeightingPotential();
   DrawWeightingPotential();
}
<|endoftext|>