<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Benchmark test for HMMWV double lane change.
//
// =============================================================================

#include "chrono/utils/ChBenchmark.h"

#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/driver/ChPathFollowerDriver.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/utils/ChVehiclePath.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"

#include "chrono_models/vehicle/hmmwv/HMMWV.h"

using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::hmmwv;

// =============================================================================

template <typename EnumClass, EnumClass TIRE_MODEL>
class HmmwvDlcTest : public utils::ChBenchmarkTest {
  public:
    HmmwvDlcTest();
    ~HmmwvDlcTest();

    ChSystem* GetSystem() override { return m_hmmwv->GetSystem(); }
    void ExecuteStep() override;

    void SimulateVis();

    double GetTime() const { return m_hmmwv->GetSystem()->GetChTime(); }
    double GetLocation() const { return m_hmmwv->GetVehicle().GetVehiclePos().x(); }

  private:
    HMMWV_Full* m_hmmwv;
    RigidTerrain* m_terrain;
    ChPathFollowerDriver* m_driver;

    double m_step_veh;
    double m_step_tire;
};

template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::HmmwvDlcTest() : m_step_veh(2e-3), m_step_tire(1e-3) {
    PowertrainModelType powertrain_model = PowertrainModelType::SHAFTS;
    TireModelType tire_model = TireModelType::RIGID_MESH;
    DrivelineType drive_type = DrivelineType::AWD;

    // Create the HMMWV vehicle, set parameters, and initialize.
    m_hmmwv = new HMMWV_Full();
    m_hmmwv->SetContactMethod(ChMaterialSurface::SMC);
    m_hmmwv->SetChassisFixed(false);
    m_hmmwv->SetInitPosition(ChCoordsys<>(ChVector<>(-120, 0, 0.7), ChQuaternion<>(1, 0, 0, 0)));
    m_hmmwv->SetPowertrainType(powertrain_model);
    m_hmmwv->SetDriveType(drive_type);
    m_hmmwv->SetTireType(TIRE_MODEL);
    m_hmmwv->SetTireStepSize(m_step_tire);
    m_hmmwv->SetVehicleStepSize(m_step_veh);
    m_hmmwv->SetAerodynamicDrag(0.5, 5.0, 1.2);
    m_hmmwv->Initialize();

    m_hmmwv->SetChassisVisualizationType(VisualizationType::PRIMITIVES);
    m_hmmwv->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
    m_hmmwv->SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
    m_hmmwv->SetWheelVisualizationType(VisualizationType::NONE);
    m_hmmwv->SetTireVisualizationType(VisualizationType::PRIMITIVES);

    // Create the terrain
    m_terrain = new RigidTerrain(m_hmmwv->GetSystem());
    auto patch = m_terrain->AddPatch(ChCoordsys<>(ChVector<>(0, 0, -5), QUNIT), ChVector<>(300, 20, 10));
    patch->SetContactFrictionCoefficient(0.9f);
    patch->SetContactRestitutionCoefficient(0.01f);
    patch->SetContactMaterialProperties(2e7f, 0.3f);
    patch->SetColor(ChColor(0.8f, 0.8f, 0.8f));
    patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 300, 20);
    m_terrain->Initialize();

    // Parameterized NATO double lane change (to right)
    auto path = DoubleLaneChangePath(ChVector<>(-125, 0, 0.1), 28.93, 3.6105, 25.0, 50.0, false);
    m_driver = new ChPathFollowerDriver(m_hmmwv->GetVehicle(), path, "my_path", 12.0);
    m_driver->GetSteeringController().SetLookAheadDistance(5.0);
    m_driver->GetSteeringController().SetGains(0.8, 0, 0);
    m_driver->GetSpeedController().SetGains(0.4, 0, 0);
    m_driver->Initialize();
}

template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::~HmmwvDlcTest() {
    delete m_hmmwv;
    delete m_terrain;
    delete m_driver;
}

template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::ExecuteStep() {
    double time = m_hmmwv->GetSystem()->GetChTime();

    // Collect output data from modules (for inter-module communication)
    double throttle_input = m_driver->GetThrottle();
    double steering_input = m_driver->GetSteering();
    double braking_input = m_driver->GetBraking();

    // Update modules (process inputs from other modules)
    m_driver->Synchronize(time);
    m_terrain->Synchronize(time);
    m_hmmwv->Synchronize(time, steering_input, braking_input, throttle_input, *m_terrain);

    // Advance simulation for one timestep for all modules
    m_driver->Advance(m_step_veh);
    m_terrain->Advance(m_step_veh);
    m_hmmwv->Advance(m_step_veh);
}

template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::SimulateVis() {
    std::cout << "Tire model: " << static_cast<std::underlying_type<EnumClass>::type>(TIRE_MODEL) << std::endl;

    ChWheeledVehicleIrrApp app(&m_hmmwv->GetVehicle(), &m_hmmwv->GetPowertrain(), L"HMMWV acceleration test");
    app.SetSkyBox();
    app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
    app.SetChaseCamera(ChVector<>(0.0, 0.0, 1.75), 6.0, 0.5);

    // Visualization of controller points (sentinel & target)
    irr::scene::IMeshSceneNode* ballS = app.GetSceneManager()->addSphereSceneNode(0.1f);
    irr::scene::IMeshSceneNode* ballT = app.GetSceneManager()->addSphereSceneNode(0.1f);
    ballS->getMaterial(0).EmissiveColor = irr::video::SColor(0, 255, 0, 0);
    ballT->getMaterial(0).EmissiveColor = irr::video::SColor(0, 0, 255, 0);

    app.AssetBindAll();
    app.AssetUpdateAll();

    while (app.GetDevice()->run()) {
        const ChVector<>& pS = m_driver->GetSteeringController().GetSentinelLocation();
        const ChVector<>& pT = m_driver->GetSteeringController().GetTargetLocation();
        ballS->setPosition(irr::core::vector3df((irr::f32)pS.x(), (irr::f32)pS.y(), (irr::f32)pS.z()));
        ballT->setPosition(irr::core::vector3df((irr::f32)pT.x(), (irr::f32)pT.y(), (irr::f32)pT.z()));

        app.BeginScene();
        app.DrawAll();
        ExecuteStep();
        app.Synchronize("Acceleration test", m_driver->GetSteering(), m_driver->GetThrottle(), m_driver->GetBraking());
        app.Advance(m_step_veh);
        app.EndScene();
    }

    std::cout << "Time: " << GetTime() << "  location: " << GetLocation() << std::endl;
}

// =============================================================================

#define SKIP_STEPS 2500  // number of steps for hot start (2e-3 * 2500 = 5s)
#define SIM_STEPS 5000   // number of simulation steps for each benchmark (2e-3 * 5000 = 10s)
#define REPEATS 10

// TODO: error using the macro CH_BM_SIMULATION_ONCE
//CH_BM_SIMULATION_ONCE(HmmwvDLC_TMEASY, HmmwvDlcTest<TireModelType, TireModelType::TMEASY>, SKIP_STEPS, SIM_STEPS, REPEATS);

using HmmwvDLC_TMEASY = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::TMEASY>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_TMEASY, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_TMEASY, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

using HmmwvDLC_FIALA = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::FIALA>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_FIALA, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_FIALA, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

using HmmwvDLC_RIGID = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::RIGID>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_RIGID, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_RIGID, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

using HmmwvDLC_RIGIDMESH = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::RIGID_MESH>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_RIGIDMESH, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_RIGIDMESH, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

// =============================================================================

int main(int argc, char* argv[]) {
    ::benchmark::Initialize(&argc, argv);

    if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
        HmmwvDlcTest<TireModelType, TireModelType::TMEASY> test;
        test.SimulateVis();
        return 0;
    }

    ::benchmark::RunSpecifiedBenchmarks();
}
<commit_msg>Remove console output<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Benchmark test for HMMWV double lane change.
//
// =============================================================================

#include "chrono/utils/ChBenchmark.h"

#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/driver/ChPathFollowerDriver.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/utils/ChVehiclePath.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"

#include "chrono_models/vehicle/hmmwv/HMMWV.h"

using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::hmmwv;

// =============================================================================

template <typename EnumClass, EnumClass TIRE_MODEL>
class HmmwvDlcTest : public utils::ChBenchmarkTest {
  public:
    HmmwvDlcTest();
    ~HmmwvDlcTest();

    ChSystem* GetSystem() override { return m_hmmwv->GetSystem(); }
    void ExecuteStep() override;

    void SimulateVis();

    double GetTime() const { return m_hmmwv->GetSystem()->GetChTime(); }
    double GetLocation() const { return m_hmmwv->GetVehicle().GetVehiclePos().x(); }

  private:
    HMMWV_Full* m_hmmwv;
    RigidTerrain* m_terrain;
    ChPathFollowerDriver* m_driver;

    double m_step_veh;
    double m_step_tire;
};

template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::HmmwvDlcTest() : m_step_veh(2e-3), m_step_tire(1e-3) {
    PowertrainModelType powertrain_model = PowertrainModelType::SHAFTS;
    TireModelType tire_model = TireModelType::RIGID_MESH;
    DrivelineType drive_type = DrivelineType::AWD;

    // Create the HMMWV vehicle, set parameters, and initialize.
    m_hmmwv = new HMMWV_Full();
    m_hmmwv->SetContactMethod(ChMaterialSurface::SMC);
    m_hmmwv->SetChassisFixed(false);
    m_hmmwv->SetInitPosition(ChCoordsys<>(ChVector<>(-120, 0, 0.7), ChQuaternion<>(1, 0, 0, 0)));
    m_hmmwv->SetPowertrainType(powertrain_model);
    m_hmmwv->SetDriveType(drive_type);
    m_hmmwv->SetTireType(TIRE_MODEL);
    m_hmmwv->SetTireStepSize(m_step_tire);
    m_hmmwv->SetVehicleStepSize(m_step_veh);
    m_hmmwv->SetAerodynamicDrag(0.5, 5.0, 1.2);
    m_hmmwv->Initialize();

    m_hmmwv->SetChassisVisualizationType(VisualizationType::PRIMITIVES);
    m_hmmwv->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
    m_hmmwv->SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
    m_hmmwv->SetWheelVisualizationType(VisualizationType::NONE);
    m_hmmwv->SetTireVisualizationType(VisualizationType::PRIMITIVES);

    // Create the terrain
    m_terrain = new RigidTerrain(m_hmmwv->GetSystem());
    auto patch = m_terrain->AddPatch(ChCoordsys<>(ChVector<>(0, 0, -5), QUNIT), ChVector<>(300, 20, 10));
    patch->SetContactFrictionCoefficient(0.9f);
    patch->SetContactRestitutionCoefficient(0.01f);
    patch->SetContactMaterialProperties(2e7f, 0.3f);
    patch->SetColor(ChColor(0.8f, 0.8f, 0.8f));
    patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 300, 20);
    m_terrain->Initialize();

    // Parameterized NATO double lane change (to right)
    auto path = DoubleLaneChangePath(ChVector<>(-125, 0, 0.1), 28.93, 3.6105, 25.0, 50.0, false);
    m_driver = new ChPathFollowerDriver(m_hmmwv->GetVehicle(), path, "my_path", 12.0);
    m_driver->GetSteeringController().SetLookAheadDistance(5.0);
    m_driver->GetSteeringController().SetGains(0.8, 0, 0);
    m_driver->GetSpeedController().SetGains(0.4, 0, 0);
    m_driver->Initialize();
}

template <typename EnumClass, EnumClass TIRE_MODEL>
HmmwvDlcTest<EnumClass, TIRE_MODEL>::~HmmwvDlcTest() {
    delete m_hmmwv;
    delete m_terrain;
    delete m_driver;
}

template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::ExecuteStep() {
    double time = m_hmmwv->GetSystem()->GetChTime();

    // Collect output data from modules (for inter-module communication)
    double throttle_input = m_driver->GetThrottle();
    double steering_input = m_driver->GetSteering();
    double braking_input = m_driver->GetBraking();

    // Update modules (process inputs from other modules)
    m_driver->Synchronize(time);
    m_terrain->Synchronize(time);
    m_hmmwv->Synchronize(time, steering_input, braking_input, throttle_input, *m_terrain);

    // Advance simulation for one timestep for all modules
    m_driver->Advance(m_step_veh);
    m_terrain->Advance(m_step_veh);
    m_hmmwv->Advance(m_step_veh);
}

template <typename EnumClass, EnumClass TIRE_MODEL>
void HmmwvDlcTest<EnumClass, TIRE_MODEL>::SimulateVis() {
    ChWheeledVehicleIrrApp app(&m_hmmwv->GetVehicle(), &m_hmmwv->GetPowertrain(), L"HMMWV acceleration test");
    app.SetSkyBox();
    app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
    app.SetChaseCamera(ChVector<>(0.0, 0.0, 1.75), 6.0, 0.5);

    // Visualization of controller points (sentinel & target)
    irr::scene::IMeshSceneNode* ballS = app.GetSceneManager()->addSphereSceneNode(0.1f);
    irr::scene::IMeshSceneNode* ballT = app.GetSceneManager()->addSphereSceneNode(0.1f);
    ballS->getMaterial(0).EmissiveColor = irr::video::SColor(0, 255, 0, 0);
    ballT->getMaterial(0).EmissiveColor = irr::video::SColor(0, 0, 255, 0);

    app.AssetBindAll();
    app.AssetUpdateAll();

    while (app.GetDevice()->run()) {
        const ChVector<>& pS = m_driver->GetSteeringController().GetSentinelLocation();
        const ChVector<>& pT = m_driver->GetSteeringController().GetTargetLocation();
        ballS->setPosition(irr::core::vector3df((irr::f32)pS.x(), (irr::f32)pS.y(), (irr::f32)pS.z()));
        ballT->setPosition(irr::core::vector3df((irr::f32)pT.x(), (irr::f32)pT.y(), (irr::f32)pT.z()));

        app.BeginScene();
        app.DrawAll();
        ExecuteStep();
        app.Synchronize("Acceleration test", m_driver->GetSteering(), m_driver->GetThrottle(), m_driver->GetBraking());
        app.Advance(m_step_veh);
        app.EndScene();
    }

    std::cout << "Time: " << GetTime() << "  location: " << GetLocation() << std::endl;
}

// =============================================================================

#define SKIP_STEPS 2500  // number of steps for hot start (2e-3 * 2500 = 5s)
#define SIM_STEPS 5000   // number of simulation steps for each benchmark (2e-3 * 5000 = 10s)
#define REPEATS 10

// TODO: error using the macro CH_BM_SIMULATION_ONCE
//CH_BM_SIMULATION_ONCE(HmmwvDLC_TMEASY, HmmwvDlcTest<TireModelType, TireModelType::TMEASY>, SKIP_STEPS, SIM_STEPS, REPEATS);

using HmmwvDLC_TMEASY = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::TMEASY>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_TMEASY, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_TMEASY, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

using HmmwvDLC_FIALA = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::FIALA>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_FIALA, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_FIALA, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

using HmmwvDLC_RIGID = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::RIGID>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_RIGID, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_RIGID, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

using HmmwvDLC_RIGIDMESH = chrono::utils::ChBenchmarkFixture<HmmwvDlcTest<TireModelType, TireModelType::RIGID_MESH>, 0>;
BENCHMARK_DEFINE_F(HmmwvDLC_RIGIDMESH, SimulateOnce)(benchmark::State& st) {
    Reset(SKIP_STEPS);
    while (st.KeepRunning()) {
        m_test->Simulate(SIM_STEPS);
    }
    Report(st);
}
BENCHMARK_REGISTER_F(HmmwvDLC_RIGIDMESH, SimulateOnce)->Unit(benchmark::kMillisecond)->Iterations(1)->Repetitions(REPEATS);

// =============================================================================

int main(int argc, char* argv[]) {
    ::benchmark::Initialize(&argc, argv);

    if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
        HmmwvDlcTest<TireModelType, TireModelType::TMEASY> test;
        test.SimulateVis();
        return 0;
    }

    ::benchmark::RunSpecifiedBenchmarks();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fltrcfg.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVT_FLTRCFG_HXX
#define _SVT_FLTRCFG_HXX

// -----------------------------------------------------------------------

#include "svtools/svldllapi.h"
#include <unotools/configitem.hxx>

struct SvtFilterOptions_Impl;
class SVL_DLLPUBLIC SvtFilterOptions : public utl::ConfigItem
{
    SvtFilterOptions_Impl* pImp;

    const com::sun::star::uno::Sequence<rtl::OUString>& GetPropertyNames();
public:
                    SvtFilterOptions();
    virtual        ~SvtFilterOptions();

    virtual void            Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames);
    virtual void            Commit();
    void                    Load();

    void SetLoadWordBasicCode( sal_Bool bFlag );
    sal_Bool IsLoadWordBasicCode() const;
    void SetLoadWordBasicStorage( sal_Bool bFlag );
    sal_Bool IsLoadWordBasicStorage() const;

    void SetLoadExcelBasicCode( sal_Bool bFlag );
    sal_Bool IsLoadExcelBasicCode() const;
    void SetLoadExcelBasicStorage( sal_Bool bFlag );
    sal_Bool IsLoadExcelBasicStorage() const;

    void SetLoadPPointBasicCode( sal_Bool bFlag );
    sal_Bool IsLoadPPointBasicCode() const;
    void SetLoadPPointBasicStorage( sal_Bool bFlag );
    sal_Bool IsLoadPPointBasicStorage() const;

    sal_Bool IsMathType2Math() const;
    void SetMathType2Math( sal_Bool bFlag );
    sal_Bool IsMath2MathType() const;
    void SetMath2MathType( sal_Bool bFlag );

    sal_Bool IsWinWord2Writer() const;
    void SetWinWord2Writer( sal_Bool bFlag );
    sal_Bool IsWriter2WinWord() const;
    void SetWriter2WinWord( sal_Bool bFlag );

    sal_Bool IsExcel2Calc() const;
    void SetExcel2Calc( sal_Bool bFlag );
    sal_Bool IsCalc2Excel() const;
    void SetCalc2Excel( sal_Bool bFlag );

    sal_Bool IsPowerPoint2Impress() const;
    void SetPowerPoint2Impress( sal_Bool bFlag );
    sal_Bool IsImpress2PowerPoint() const;
    void SetImpress2PowerPoint( sal_Bool bFlag );

    static SvtFilterOptions* Get();
};

#endif

<commit_msg>INTEGRATION: CWS ab51 (1.6.32); FILE MERGED 2008/05/06 15:21:49 ab 1.6.32.1: #i88690# Support option to load Excel VBA code executable<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fltrcfg.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVT_FLTRCFG_HXX
#define _SVT_FLTRCFG_HXX

// -----------------------------------------------------------------------

#include "svtools/svldllapi.h"
#include <unotools/configitem.hxx>

struct SvtFilterOptions_Impl;
class SVL_DLLPUBLIC SvtFilterOptions : public utl::ConfigItem
{
    SvtFilterOptions_Impl* pImp;

    const com::sun::star::uno::Sequence<rtl::OUString>& GetPropertyNames();
public:
                    SvtFilterOptions();
    virtual        ~SvtFilterOptions();

    virtual void            Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames);
    virtual void            Commit();
    void                    Load();

    void SetLoadWordBasicCode( sal_Bool bFlag );
    sal_Bool IsLoadWordBasicCode() const;
    void SetLoadWordBasicStorage( sal_Bool bFlag );
    sal_Bool IsLoadWordBasicStorage() const;

    void SetLoadExcelBasicCode( sal_Bool bFlag );
    sal_Bool IsLoadExcelBasicCode() const;
    void SetLoadExcelBasicExecutable( sal_Bool bFlag );
    sal_Bool IsLoadExcelBasicExecutable() const;
    void SetLoadExcelBasicStorage( sal_Bool bFlag );
    sal_Bool IsLoadExcelBasicStorage() const;

    void SetLoadPPointBasicCode( sal_Bool bFlag );
    sal_Bool IsLoadPPointBasicCode() const;
    void SetLoadPPointBasicStorage( sal_Bool bFlag );
    sal_Bool IsLoadPPointBasicStorage() const;

    sal_Bool IsMathType2Math() const;
    void SetMathType2Math( sal_Bool bFlag );
    sal_Bool IsMath2MathType() const;
    void SetMath2MathType( sal_Bool bFlag );

    sal_Bool IsWinWord2Writer() const;
    void SetWinWord2Writer( sal_Bool bFlag );
    sal_Bool IsWriter2WinWord() const;
    void SetWriter2WinWord( sal_Bool bFlag );

    sal_Bool IsExcel2Calc() const;
    void SetExcel2Calc( sal_Bool bFlag );
    sal_Bool IsCalc2Excel() const;
    void SetCalc2Excel( sal_Bool bFlag );

    sal_Bool IsPowerPoint2Impress() const;
    void SetPowerPoint2Impress( sal_Bool bFlag );
    sal_Bool IsImpress2PowerPoint() const;
    void SetImpress2PowerPoint( sal_Bool bFlag );

    static SvtFilterOptions* Get();
};

#endif

<|endoftext|>


<commit_before>
# include <cmath>
# include <array>
# include <numeric>
# include <random>
# include "PerlinNoise.hpp"

PerlinNoise::PerlinNoise( unsigned seed )
{
	// Precondition: 0 < seed
	if(seed==0)
	{
		seed = std::mt19937::default_seed;
	}

	// "permutation" contains all numbers in [0..255] in random order
	std::array<int,256> permutation;
	std::iota(permutation.begin(),permutation.end(),0);
	std::shuffle(permutation.begin(),permutation.end(),std::mt19937(seed));

	for(int i=0; i<256; ++i)
	{
		p[256+i] = p[i] = permutation[i];
	}
}

double PerlinNoise::noise( double x ) const
{
	return noise(x,0.0,0.0);
}

double PerlinNoise::noise( double x, double y ) const
{
	return noise(x,y,0.0);
}

double PerlinNoise::noise( double x, double y, double z ) const
{
	const int X = static_cast<int>(::floor(x)) & 255;
	const int Y = static_cast<int>(::floor(y)) & 255;
	const int Z = static_cast<int>(::floor(z)) & 255;

	x -= ::floor(x);
	y -= ::floor(y);
	z -= ::floor(z);

	const double u = fade(x);
	const double v = fade(y);
	const double w = fade(z);

	const int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z;
	const int B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;

	return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),
			grad(p[BA  ], x-1, y  , z   )),
			lerp(u, grad(p[AB  ], x  , y-1, z   ),
			grad(p[BB  ], x-1, y-1, z   ))),
			lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),
			grad(p[BA+1], x-1, y  , z-1 )),
			lerp(u, grad(p[AB+1], x  , y-1, z-1 ),
			grad(p[BB+1], x-1, y-1, z-1 ))));
}

double PerlinNoise::octaveNoise( double x, int octaves ) const
{
	double result = 0.0;
	double amp = 1.0;

	for(int i=0; i<octaves; ++i)
	{
		result += noise(x) * amp;
		x   *= 2.0;
		amp *= 0.5;
	}

	return result;
}

double PerlinNoise::octaveNoise( double x, double y, int octaves ) const
{
	double result = 0.0;
	double amp = 1.0;

	for(int i=0; i<octaves; ++i)
	{
		result += noise(x,y) * amp;
		x   *= 2.0;
		y   *= 2.0;
		amp *= 0.5;
	}

	return result;
}

double PerlinNoise::octaveNoise( double x, double y, double z, int octaves ) const
{
	double result = 0.0;
	double amp = 1.0;

	for(int i=0; i<octaves; ++i)
	{
		result += noise(x,y,z) * amp;
		x   *= 2.0;
		y   *= 2.0;
		z   *= 2.0;
		amp *= 0.5;
	}

	return result;
}

double PerlinNoise::fade( double t ) const
{
	return t * t * t * (t * (t * 6 - 15) + 10);
}

double PerlinNoise::lerp( double t, double a, double b ) const
{
	return a + t * (b - a);
}

double PerlinNoise::grad( int hash, double x, double y, double z ) const
{
	const int h = hash & 15;
	const double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z;
	return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
<commit_msg>Include <algorithm> header for GCC<commit_after>
# include <cmath>
# include <array>
# include <numeric>
# include <random>
# include <algorithm>
# include "PerlinNoise.hpp"

PerlinNoise::PerlinNoise( unsigned seed )
{
	// Precondition: 0 < seed
	if(seed==0)
	{
		seed = std::mt19937::default_seed;
	}

	// "permutation" contains all numbers in [0..255] in random order
	std::array<int,256> permutation;
	std::iota(permutation.begin(),permutation.end(),0);
	std::shuffle(permutation.begin(),permutation.end(),std::mt19937(seed));

	for(int i=0; i<256; ++i)
	{
		p[256+i] = p[i] = permutation[i];
	}
}

double PerlinNoise::noise( double x ) const
{
	return noise(x,0.0,0.0);
}

double PerlinNoise::noise( double x, double y ) const
{
	return noise(x,y,0.0);
}

double PerlinNoise::noise( double x, double y, double z ) const
{
	const int X = static_cast<int>(::floor(x)) & 255;
	const int Y = static_cast<int>(::floor(y)) & 255;
	const int Z = static_cast<int>(::floor(z)) & 255;

	x -= ::floor(x);
	y -= ::floor(y);
	z -= ::floor(z);

	const double u = fade(x);
	const double v = fade(y);
	const double w = fade(z);

	const int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z;
	const int B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;

	return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),
			grad(p[BA  ], x-1, y  , z   )),
			lerp(u, grad(p[AB  ], x  , y-1, z   ),
			grad(p[BB  ], x-1, y-1, z   ))),
			lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),
			grad(p[BA+1], x-1, y  , z-1 )),
			lerp(u, grad(p[AB+1], x  , y-1, z-1 ),
			grad(p[BB+1], x-1, y-1, z-1 ))));
}

double PerlinNoise::octaveNoise( double x, int octaves ) const
{
	double result = 0.0;
	double amp = 1.0;

	for(int i=0; i<octaves; ++i)
	{
		result += noise(x) * amp;
		x   *= 2.0;
		amp *= 0.5;
	}

	return result;
}

double PerlinNoise::octaveNoise( double x, double y, int octaves ) const
{
	double result = 0.0;
	double amp = 1.0;

	for(int i=0; i<octaves; ++i)
	{
		result += noise(x,y) * amp;
		x   *= 2.0;
		y   *= 2.0;
		amp *= 0.5;
	}

	return result;
}

double PerlinNoise::octaveNoise( double x, double y, double z, int octaves ) const
{
	double result = 0.0;
	double amp = 1.0;

	for(int i=0; i<octaves; ++i)
	{
		result += noise(x,y,z) * amp;
		x   *= 2.0;
		y   *= 2.0;
		z   *= 2.0;
		amp *= 0.5;
	}

	return result;
}

double PerlinNoise::fade( double t ) const
{
	return t * t * t * (t * (t * 6 - 15) + 10);
}

double PerlinNoise::lerp( double t, double a, double b ) const
{
	return a + t * (b - a);
}

double PerlinNoise::grad( int hash, double x, double y, double z ) const
{
	const int h = hash & 15;
	const double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z;
	return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2017 ScyllaDB
 */

#include "test-utils.hh"

#include <core/do_with.hh>
#include <core/lowres_clock.hh>
#include <core/sleep.hh>

#include <ctime>

#include <algorithm>
#include <array>
#include <chrono>

using namespace seastar;

//
// Sanity check the accuracy of the steady low-resolution clock.
//
SEASTAR_TEST_CASE(steady_clock_sanity) {
    static constexpr auto sleep_duration = std::chrono::milliseconds(100);

    return do_with(lowres_clock::now(), [](auto &&t1) {
        return ::seastar::sleep(sleep_duration).then([&t1] {
            auto const elapsed = lowres_clock::now() - t1;
            auto const minimum_elapsed = 0.9 * sleep_duration;

            BOOST_REQUIRE(elapsed >= minimum_elapsed);

            return make_ready_future<>();
        });
    });
}

//
// At the very least, we can verify that the low-resolution system clock is within a second of the
// high-resolution system clock.
//
SEASTAR_TEST_CASE(system_clock_sanity) {
    constexpr auto check_matching = [] {
        auto const system_time = std::chrono::system_clock::now();
        auto const lowres_time = lowres_system_clock::now();

        auto const t1 = std::chrono::system_clock::to_time_t(system_time);
        auto const t2 = lowres_system_clock::to_time_t(lowres_time);

        std::tm *lt1 = std::localtime(&t1);
        std::tm *lt2 = std::localtime(&t2);

        return (lt1->tm_isdst == lt2->tm_isdst) &&
               (lt1->tm_year == lt2->tm_year) &&
               (lt1->tm_mon == lt2->tm_mon) &&
               (lt1->tm_yday == lt2->tm_yday) &&
               (lt1->tm_mday == lt2->tm_mday) &&
               (lt1->tm_wday == lt2->tm_wday) &&
               (lt1->tm_hour == lt2->tm_hour) &&
               (lt1->tm_min == lt2->tm_min) &&
               (lt1->tm_sec == lt2->tm_sec);
    };

    //
    // Check two out of three samples in order to account for the possibility that the high-resolution clock backing
    // the low-resoltuion clock was captured in the range of the 990th to 999th millisecond of the second. This would
    // make the low-resolution clock and the high-resolution clock disagree on the current second.
    //

    return do_with(0ul, 0ul, [check_matching] (std::size_t& index, std::size_t& success_count) {
        return repeat([&index, &success_count, check_matching] {
            if (index >= 3) {
                BOOST_REQUIRE_GE(success_count, 2);
                return make_ready_future<stop_iteration>(stop_iteration::yes);
            }

            return ::seastar::sleep(std::chrono::milliseconds(10)).then([&index, &success_count, check_matching] {
                if (check_matching()) {
                    ++success_count;
                }

                ++index;
                return stop_iteration::no;
            });
        });
    });
}

//
// Verify that the low-resolution clock updates its reported time point over time.
//
SEASTAR_TEST_CASE(system_clock_dynamic) {
    return do_with(lowres_system_clock::now(), [](auto &&t1) {
        return seastar::sleep(std::chrono::milliseconds(100)).then([&t1] {
            auto const t2 = lowres_system_clock::now();
            BOOST_REQUIRE_NE(t1.time_since_epoch().count(), t2.time_since_epoch().count());

            return make_ready_future<>();
        });
    });
}
<commit_msg>tests/lowres_clock_test.cc: fix compilation error for older GCC<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2017 ScyllaDB
 */

#include "test-utils.hh"

#include <core/do_with.hh>
#include <core/lowres_clock.hh>
#include <core/sleep.hh>

#include <ctime>

#include <algorithm>
#include <array>
#include <chrono>

using namespace seastar;

//
// Sanity check the accuracy of the steady low-resolution clock.
//
SEASTAR_TEST_CASE(steady_clock_sanity) {
    return do_with(lowres_clock::now(), [](auto &&t1) {
        static constexpr auto sleep_duration = std::chrono::milliseconds(100);

        return ::seastar::sleep(sleep_duration).then([&t1] {
            auto const elapsed = lowres_clock::now() - t1;
            auto const minimum_elapsed = 0.9 * sleep_duration;

            BOOST_REQUIRE(elapsed >= minimum_elapsed);

            return make_ready_future<>();
        });
    });
}

//
// At the very least, we can verify that the low-resolution system clock is within a second of the
// high-resolution system clock.
//
SEASTAR_TEST_CASE(system_clock_sanity) {
    constexpr auto check_matching = [] {
        auto const system_time = std::chrono::system_clock::now();
        auto const lowres_time = lowres_system_clock::now();

        auto const t1 = std::chrono::system_clock::to_time_t(system_time);
        auto const t2 = lowres_system_clock::to_time_t(lowres_time);

        std::tm *lt1 = std::localtime(&t1);
        std::tm *lt2 = std::localtime(&t2);

        return (lt1->tm_isdst == lt2->tm_isdst) &&
               (lt1->tm_year == lt2->tm_year) &&
               (lt1->tm_mon == lt2->tm_mon) &&
               (lt1->tm_yday == lt2->tm_yday) &&
               (lt1->tm_mday == lt2->tm_mday) &&
               (lt1->tm_wday == lt2->tm_wday) &&
               (lt1->tm_hour == lt2->tm_hour) &&
               (lt1->tm_min == lt2->tm_min) &&
               (lt1->tm_sec == lt2->tm_sec);
    };

    //
    // Check two out of three samples in order to account for the possibility that the high-resolution clock backing
    // the low-resoltuion clock was captured in the range of the 990th to 999th millisecond of the second. This would
    // make the low-resolution clock and the high-resolution clock disagree on the current second.
    //

    return do_with(0ul, 0ul, [check_matching] (std::size_t& index, std::size_t& success_count) {
        return repeat([&index, &success_count, check_matching] {
            if (index >= 3) {
                BOOST_REQUIRE_GE(success_count, 2);
                return make_ready_future<stop_iteration>(stop_iteration::yes);
            }

            return ::seastar::sleep(std::chrono::milliseconds(10)).then([&index, &success_count, check_matching] {
                if (check_matching()) {
                    ++success_count;
                }

                ++index;
                return stop_iteration::no;
            });
        });
    });
}

//
// Verify that the low-resolution clock updates its reported time point over time.
//
SEASTAR_TEST_CASE(system_clock_dynamic) {
    return do_with(lowres_system_clock::now(), [](auto &&t1) {
        return seastar::sleep(std::chrono::milliseconds(100)).then([&t1] {
            auto const t2 = lowres_system_clock::now();
            BOOST_REQUIRE_NE(t1.time_since_epoch().count(), t2.time_since_epoch().count());

            return make_ready_future<>();
        });
    });
}
<|endoftext|>


<commit_before>// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/boundary_info.h>
#include <libmesh/elem.h>
#include <libmesh/face_quad4_shell.h>
#include <libmesh/equation_systems.h>
#include <libmesh/zero_function.h>
#include <libmesh/dirichlet_boundaries.h>
#include <libmesh/dof_map.h>

#include "test_comm.h"

// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings.  These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas.  We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point.  We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>

using namespace libMesh;

class BoundaryInfoTest : public CppUnit::TestCase {
  /**
   * This test ensures various aspects of the BoundaryInfo class work as expected.
   */
public:
  CPPUNIT_TEST_SUITE( BoundaryInfoTest );

  CPPUNIT_TEST( testMesh );
  CPPUNIT_TEST( testEdgeBoundaryConditions );
  CPPUNIT_TEST( testShellFaceConstraints );

  CPPUNIT_TEST_SUITE_END();

protected:

public:
  void setUp()
  {
  }

  void tearDown()
  {
  }

  void testMesh()
  {
    Mesh mesh(*TestCommWorld);

    MeshTools::Generation::build_square(mesh,
                                        2, 2,
                                        0., 1.,
                                        0., 1.,
                                        QUAD4);

    BoundaryInfo & bi = mesh.get_boundary_info();

    // Side lists should be cleared and refilled by each call
    std::vector<dof_id_type> element_id_list;
    std::vector<unsigned short int> side_list;
    std::vector<boundary_id_type> bc_id_list;

    // build_square adds boundary_ids 0,1,2,3 for the bottom, right,
    // top, and left sides, respectively.

    // On a ReplicatedMesh, we should see all 4 ids on each processor
    if (mesh.is_serial())
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(4), bi.n_boundary_ids());

    // On any mesh, we should see each id on *some* processor
    {
      const std::set<boundary_id_type> & bc_ids = bi.get_boundary_ids();
      for (unsigned int i = 0 ; i != 4; ++i)
        {
          bool has_bcid = bc_ids.count(i);
          mesh.comm().max(has_bcid);
          CPPUNIT_ASSERT(has_bcid);
        }
    }

    // Build the side list
    bi.build_side_list (element_id_list, side_list, bc_id_list);

    // Test that the new vector-of-tuples API works equivalently.
    auto bc_triples = bi.build_side_list();

    // Check that there are exactly 8 sides in the BoundaryInfo for a
    // replicated mesh
    if (mesh.is_serial())
      {
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(8), element_id_list.size());
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(8), bc_triples.size());
      }

    // Let's test that we can remove them successfully.
    bi.remove_id(0);

    // Check that there are now only 3 boundary ids total on the Mesh.
    if (mesh.is_serial())
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(3), bi.n_boundary_ids());

    {
      const std::set<boundary_id_type> & bc_ids = bi.get_boundary_ids();
      CPPUNIT_ASSERT(!bc_ids.count(0));
      for (unsigned int i = 1 ; i != 4; ++i)
        {
          bool has_bcid = bc_ids.count(i);
          mesh.comm().max(has_bcid);
          CPPUNIT_ASSERT(has_bcid);
        }
    }

    // Build the side list again
    bi.build_side_list (element_id_list, side_list, bc_id_list);
    bc_triples = bi.build_side_list();

    // Check that there are now exactly 6 sides left in the
    // BoundaryInfo on a replicated mesh
    if (mesh.is_serial())
      {
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(6), element_id_list.size());
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(6), bc_triples.size());
      }

    // Check that the removed ID is really removed
    CPPUNIT_ASSERT(std::find(bc_id_list.begin(), bc_id_list.end(), 0) == bc_id_list.end());
    typedef std::tuple<dof_id_type, unsigned short int, boundary_id_type> Tuple;
    CPPUNIT_ASSERT(std::find_if(bc_triples.begin(), bc_triples.end(),
                                [](const Tuple & t)->bool { return std::get<2>(t) == 0; }) == bc_triples.end());

    // Remove the same id again, make sure nothing changes.
    bi.remove_id(0);
    if (mesh.is_serial())
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(3), bi.n_boundary_ids());

    // Remove the remaining IDs, verify that we have no sides left and
    // that we can safely reuse the same vectors in the
    // build_side_list() call.
    bi.remove_id(1);
    bi.remove_id(2);
    bi.remove_id(3);
    bi.build_side_list (element_id_list, side_list, bc_id_list);
    bc_triples = bi.build_side_list();

    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), bi.n_boundary_ids());
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), element_id_list.size());
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), bc_triples.size());
  }

  void testEdgeBoundaryConditions()
  {
    const unsigned int n_elem = 5;
    const std::string mesh_filename = "cube_mesh.xda";

    {
      Mesh mesh(*TestCommWorld);
      MeshTools::Generation::build_cube(mesh,
                                        n_elem, n_elem, n_elem,
                                        0., 1.,
                                        0., 1.,
                                        0., 1.,
                                        HEX8);

      BoundaryInfo & bi = mesh.get_boundary_info();

      // build_cube does not add any edge boundary IDs
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), bi.n_edge_conds());

      // Let's now add some edge boundary IDs.
      // We loop over all elements (not just local elements) so that
      // all processors know about the boundary IDs
      const boundary_id_type BOUNDARY_ID_MAX_X = 2;
      const boundary_id_type BOUNDARY_ID_MIN_Y = 1;
      const boundary_id_type EDGE_BOUNDARY_ID = 20;

      for (const auto & elem : mesh.element_ptr_range())
        {
          unsigned int side_max_x = 0, side_min_y = 0;
          bool found_side_max_x = false, found_side_min_y = false;

          for (unsigned int side=0; side<elem->n_sides(); side++)
            {
              if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_X))
                {
                  side_max_x = side;
                  found_side_max_x = true;
                }

              if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MIN_Y))
                {
                  side_min_y = side;
                  found_side_min_y = true;
                }
            }

          // If elem has sides on boundaries
          // BOUNDARY_ID_MAX_X and BOUNDARY_ID_MIN_Y
          // then let's set an edge boundary condition
          if (found_side_max_x && found_side_min_y)
            for (unsigned int e=0; e<elem->n_edges(); e++)
              if (elem->is_edge_on_side(e, side_max_x) &&
                  elem->is_edge_on_side(e, side_min_y))
                bi.add_edge(elem, e, EDGE_BOUNDARY_ID);
        }

      // Check that we have the expected number of edge boundary IDs after
      // updating bi
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(n_elem), bi.n_edge_conds());

      mesh.write(mesh_filename);
    }

    // Make sure all processors are done writing before we try to
    // start reading
    TestCommWorld->barrier();

    Mesh mesh(*TestCommWorld);
    mesh.read(mesh_filename);

    // Check that writing and reading preserves the edge boundary IDs
    BoundaryInfo & bi = mesh.get_boundary_info();
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(n_elem), bi.n_edge_conds());
  }

  void testShellFaceConstraints()
  {
    // Make a simple two element mesh that we can use to test constraints
    Mesh mesh(*TestCommWorld, 3);

    //  (0,1)           (1,1)
    //  x---------------x
    //  |               |
    //  |               |
    //  |               |
    //  |               |
    //  |               |
    //  x---------------x
    //  (0,0)           (1,0)
    //  |               |
    //  |               |
    //  |               |
    //  |               |
    //  x---------------x
    //  (0,-1)          (1,-1)

    mesh.add_point( Point(0.0,-1.0), 4 );
    mesh.add_point( Point(1.0,-1.0), 5 );
    mesh.add_point( Point(1.0, 0.0), 1 );
    mesh.add_point( Point(1.0, 1.0), 2 );
    mesh.add_point( Point(0.0, 1.0), 3 );
    mesh.add_point( Point(0.0, 0.0), 0 );

    Elem* elem_top = mesh.add_elem( new QuadShell4 );
    elem_top->set_node(0) = mesh.node_ptr(0);
    elem_top->set_node(1) = mesh.node_ptr(1);
    elem_top->set_node(2) = mesh.node_ptr(2);
    elem_top->set_node(3) = mesh.node_ptr(3);

    Elem* elem_bottom = mesh.add_elem( new QuadShell4 );
    elem_bottom->set_node(0) = mesh.node_ptr(4);
    elem_bottom->set_node(1) = mesh.node_ptr(5);
    elem_bottom->set_node(2) = mesh.node_ptr(1);
    elem_bottom->set_node(3) = mesh.node_ptr(0);

    BoundaryInfo & bi = mesh.get_boundary_info();
    bi.add_shellface(elem_top, 0, 10);
    bi.add_shellface(elem_bottom, 1, 20);

    mesh.prepare_for_use(false /*skip_renumber*/);

    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(2), bi.n_shellface_conds());

    EquationSystems es(mesh);
    System & system = es.add_system<System> ("SimpleSystem");
    system.add_variable("u", FIRST);

    // Add a Dirichlet constraint to check that we impose constraints
    // correctly on shell faces.
    std::vector<unsigned int> variables;
    variables.push_back(0);
    std::set<boundary_id_type> shellface_ids;
    shellface_ids.insert(20);
    ZeroFunction<> zf;
    DirichletBoundary dirichlet_bc(shellface_ids,
                                   variables,
                                   &zf);
    system.get_dof_map().add_dirichlet_boundary(dirichlet_bc);
    es.init();

    // Find elem_bottom again if we have it (it may have been deleted
    // in a DistributedMesh or renumbered in theory)
    elem_bottom = nullptr;
    for (unsigned int e = 0; e != mesh.max_elem_id(); ++e)
      {
        Elem *elem = mesh.query_elem_ptr(e);
        if (elem && elem->point(3) == Point(0,0))
          elem_bottom = elem;
      }

    // We expect to have a dof constraint on all four dofs of
    // elem_bottom
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(4), static_cast<std::size_t>(system.n_constrained_dofs()));

    // But we may only know the details of that
    // constraint on the processor which owns elem_bottom.
    if (elem_bottom &&
        elem_bottom->processor_id() == mesh.processor_id())
      {
        std::vector<dof_id_type> dof_indices;
        system.get_dof_map().dof_indices(elem_bottom, dof_indices);
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(4), dof_indices.size());

        for(unsigned int i=0; i<dof_indices.size(); i++)
          {
            dof_id_type dof_id = dof_indices[i];
            CPPUNIT_ASSERT( system.get_dof_map().is_constrained_dof(dof_id) );
          }
      }
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION( BoundaryInfoTest );
<commit_msg>Guard deprecated code in unit tests.<commit_after>// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/boundary_info.h>
#include <libmesh/elem.h>
#include <libmesh/face_quad4_shell.h>
#include <libmesh/equation_systems.h>
#include <libmesh/zero_function.h>
#include <libmesh/dirichlet_boundaries.h>
#include <libmesh/dof_map.h>

#include "test_comm.h"

// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings.  These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas.  We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point.  We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>

using namespace libMesh;

class BoundaryInfoTest : public CppUnit::TestCase {
  /**
   * This test ensures various aspects of the BoundaryInfo class work as expected.
   */
public:
  CPPUNIT_TEST_SUITE( BoundaryInfoTest );

  CPPUNIT_TEST( testMesh );
  CPPUNIT_TEST( testEdgeBoundaryConditions );
  CPPUNIT_TEST( testShellFaceConstraints );

  CPPUNIT_TEST_SUITE_END();

protected:

public:
  void setUp()
  {
  }

  void tearDown()
  {
  }

  void testMesh()
  {
    Mesh mesh(*TestCommWorld);

    MeshTools::Generation::build_square(mesh,
                                        2, 2,
                                        0., 1.,
                                        0., 1.,
                                        QUAD4);

    BoundaryInfo & bi = mesh.get_boundary_info();

    // Side lists should be cleared and refilled by each call
#ifdef LIBMESH_ENABLE_DEPRECATED
    std::vector<dof_id_type> element_id_list;
    std::vector<unsigned short int> side_list;
    std::vector<boundary_id_type> bc_id_list;
#endif

    // build_square adds boundary_ids 0,1,2,3 for the bottom, right,
    // top, and left sides, respectively.

    // On a ReplicatedMesh, we should see all 4 ids on each processor
    if (mesh.is_serial())
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(4), bi.n_boundary_ids());

    // On any mesh, we should see each id on *some* processor
    {
      const std::set<boundary_id_type> & bc_ids = bi.get_boundary_ids();
      for (unsigned int i = 0 ; i != 4; ++i)
        {
          bool has_bcid = bc_ids.count(i);
          mesh.comm().max(has_bcid);
          CPPUNIT_ASSERT(has_bcid);
        }
    }

    // Build the side list
#ifdef LIBMESH_ENABLE_DEPRECATED
    bi.build_side_list (element_id_list, side_list, bc_id_list);
#endif

    // Test that the new vector-of-tuples API works equivalently.
    auto bc_triples = bi.build_side_list();

    // Check that there are exactly 8 sides in the BoundaryInfo for a
    // replicated mesh
    if (mesh.is_serial())
      {
#ifdef LIBMESH_ENABLE_DEPRECATED
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(8), element_id_list.size());
#endif
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(8), bc_triples.size());
      }

    // Let's test that we can remove them successfully.
    bi.remove_id(0);

    // Check that there are now only 3 boundary ids total on the Mesh.
    if (mesh.is_serial())
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(3), bi.n_boundary_ids());

    {
      const std::set<boundary_id_type> & bc_ids = bi.get_boundary_ids();
      CPPUNIT_ASSERT(!bc_ids.count(0));
      for (unsigned int i = 1 ; i != 4; ++i)
        {
          bool has_bcid = bc_ids.count(i);
          mesh.comm().max(has_bcid);
          CPPUNIT_ASSERT(has_bcid);
        }
    }

    // Build the side list again
#ifdef LIBMESH_ENABLE_DEPRECATED
    bi.build_side_list (element_id_list, side_list, bc_id_list);
#endif
    bc_triples = bi.build_side_list();

    // Check that there are now exactly 6 sides left in the
    // BoundaryInfo on a replicated mesh
    if (mesh.is_serial())
      {
#ifdef LIBMESH_ENABLE_DEPRECATED
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(6), element_id_list.size());
#endif
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(6), bc_triples.size());
      }

    // Check that the removed ID is really removed
#ifdef LIBMESH_ENABLE_DEPRECATED
    CPPUNIT_ASSERT(std::find(bc_id_list.begin(), bc_id_list.end(), 0) == bc_id_list.end());
#endif
    typedef std::tuple<dof_id_type, unsigned short int, boundary_id_type> Tuple;
    CPPUNIT_ASSERT(std::find_if(bc_triples.begin(), bc_triples.end(),
                                [](const Tuple & t)->bool { return std::get<2>(t) == 0; }) == bc_triples.end());

    // Remove the same id again, make sure nothing changes.
    bi.remove_id(0);
    if (mesh.is_serial())
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(3), bi.n_boundary_ids());

    // Remove the remaining IDs, verify that we have no sides left and
    // that we can safely reuse the same vectors in the
    // build_side_list() call.
    bi.remove_id(1);
    bi.remove_id(2);
    bi.remove_id(3);
#ifdef LIBMESH_ENABLE_DEPRECATED
    bi.build_side_list (element_id_list, side_list, bc_id_list);
#endif
    bc_triples = bi.build_side_list();

    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), bi.n_boundary_ids());
#ifdef LIBMESH_ENABLE_DEPRECATED
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), element_id_list.size());
#endif
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), bc_triples.size());
  }

  void testEdgeBoundaryConditions()
  {
    const unsigned int n_elem = 5;
    const std::string mesh_filename = "cube_mesh.xda";

    {
      Mesh mesh(*TestCommWorld);
      MeshTools::Generation::build_cube(mesh,
                                        n_elem, n_elem, n_elem,
                                        0., 1.,
                                        0., 1.,
                                        0., 1.,
                                        HEX8);

      BoundaryInfo & bi = mesh.get_boundary_info();

      // build_cube does not add any edge boundary IDs
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(0), bi.n_edge_conds());

      // Let's now add some edge boundary IDs.
      // We loop over all elements (not just local elements) so that
      // all processors know about the boundary IDs
      const boundary_id_type BOUNDARY_ID_MAX_X = 2;
      const boundary_id_type BOUNDARY_ID_MIN_Y = 1;
      const boundary_id_type EDGE_BOUNDARY_ID = 20;

      for (const auto & elem : mesh.element_ptr_range())
        {
          unsigned int side_max_x = 0, side_min_y = 0;
          bool found_side_max_x = false, found_side_min_y = false;

          for (unsigned int side=0; side<elem->n_sides(); side++)
            {
              if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_X))
                {
                  side_max_x = side;
                  found_side_max_x = true;
                }

              if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MIN_Y))
                {
                  side_min_y = side;
                  found_side_min_y = true;
                }
            }

          // If elem has sides on boundaries
          // BOUNDARY_ID_MAX_X and BOUNDARY_ID_MIN_Y
          // then let's set an edge boundary condition
          if (found_side_max_x && found_side_min_y)
            for (unsigned int e=0; e<elem->n_edges(); e++)
              if (elem->is_edge_on_side(e, side_max_x) &&
                  elem->is_edge_on_side(e, side_min_y))
                bi.add_edge(elem, e, EDGE_BOUNDARY_ID);
        }

      // Check that we have the expected number of edge boundary IDs after
      // updating bi
      CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(n_elem), bi.n_edge_conds());

      mesh.write(mesh_filename);
    }

    // Make sure all processors are done writing before we try to
    // start reading
    TestCommWorld->barrier();

    Mesh mesh(*TestCommWorld);
    mesh.read(mesh_filename);

    // Check that writing and reading preserves the edge boundary IDs
    BoundaryInfo & bi = mesh.get_boundary_info();
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(n_elem), bi.n_edge_conds());
  }

  void testShellFaceConstraints()
  {
    // Make a simple two element mesh that we can use to test constraints
    Mesh mesh(*TestCommWorld, 3);

    //  (0,1)           (1,1)
    //  x---------------x
    //  |               |
    //  |               |
    //  |               |
    //  |               |
    //  |               |
    //  x---------------x
    //  (0,0)           (1,0)
    //  |               |
    //  |               |
    //  |               |
    //  |               |
    //  x---------------x
    //  (0,-1)          (1,-1)

    mesh.add_point( Point(0.0,-1.0), 4 );
    mesh.add_point( Point(1.0,-1.0), 5 );
    mesh.add_point( Point(1.0, 0.0), 1 );
    mesh.add_point( Point(1.0, 1.0), 2 );
    mesh.add_point( Point(0.0, 1.0), 3 );
    mesh.add_point( Point(0.0, 0.0), 0 );

    Elem* elem_top = mesh.add_elem( new QuadShell4 );
    elem_top->set_node(0) = mesh.node_ptr(0);
    elem_top->set_node(1) = mesh.node_ptr(1);
    elem_top->set_node(2) = mesh.node_ptr(2);
    elem_top->set_node(3) = mesh.node_ptr(3);

    Elem* elem_bottom = mesh.add_elem( new QuadShell4 );
    elem_bottom->set_node(0) = mesh.node_ptr(4);
    elem_bottom->set_node(1) = mesh.node_ptr(5);
    elem_bottom->set_node(2) = mesh.node_ptr(1);
    elem_bottom->set_node(3) = mesh.node_ptr(0);

    BoundaryInfo & bi = mesh.get_boundary_info();
    bi.add_shellface(elem_top, 0, 10);
    bi.add_shellface(elem_bottom, 1, 20);

    mesh.prepare_for_use(false /*skip_renumber*/);

    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(2), bi.n_shellface_conds());

    EquationSystems es(mesh);
    System & system = es.add_system<System> ("SimpleSystem");
    system.add_variable("u", FIRST);

    // Add a Dirichlet constraint to check that we impose constraints
    // correctly on shell faces.
    std::vector<unsigned int> variables;
    variables.push_back(0);
    std::set<boundary_id_type> shellface_ids;
    shellface_ids.insert(20);
    ZeroFunction<> zf;
    DirichletBoundary dirichlet_bc(shellface_ids,
                                   variables,
                                   &zf);
    system.get_dof_map().add_dirichlet_boundary(dirichlet_bc);
    es.init();

    // Find elem_bottom again if we have it (it may have been deleted
    // in a DistributedMesh or renumbered in theory)
    elem_bottom = nullptr;
    for (unsigned int e = 0; e != mesh.max_elem_id(); ++e)
      {
        Elem *elem = mesh.query_elem_ptr(e);
        if (elem && elem->point(3) == Point(0,0))
          elem_bottom = elem;
      }

    // We expect to have a dof constraint on all four dofs of
    // elem_bottom
    CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(4), static_cast<std::size_t>(system.n_constrained_dofs()));

    // But we may only know the details of that
    // constraint on the processor which owns elem_bottom.
    if (elem_bottom &&
        elem_bottom->processor_id() == mesh.processor_id())
      {
        std::vector<dof_id_type> dof_indices;
        system.get_dof_map().dof_indices(elem_bottom, dof_indices);
        CPPUNIT_ASSERT_EQUAL(static_cast<std::size_t>(4), dof_indices.size());

        for(unsigned int i=0; i<dof_indices.size(); i++)
          {
            dof_id_type dof_id = dof_indices[i];
            CPPUNIT_ASSERT( system.get_dof_map().is_constrained_dof(dof_id) );
          }
      }
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION( BoundaryInfoTest );
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2007 Egon Willighagen <egonw@users.sf.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "namespaceharvestersaxanalyzer.h"
#include <strigi/strigiconfig.h>
#include "analysisresult.h"
#include "fieldtypes.h"

#include <cassert>
#include <cstring>
#include <string>
#include <iostream>
#include <set>

using namespace std;
using namespace Strigi;

void
NamespaceHarvesterSaxAnalyzerFactory::registerFields(FieldRegister &reg) {
    usesNamespaceField = reg.registerField(
        "http://freedesktop.org/standards/xesam/1.0/core#usesNamespace");
    addField(usesNamespaceField);
}

void
NamespaceHarvesterSaxAnalyzer::startAnalysis(AnalysisResult *i) {
    assert(i != 0);
    analysisResult = i;
    ready = false;

    usedNamespaces.clear();
}

void NamespaceHarvesterSaxAnalyzer::endAnalysis(bool /*complete*/) {
    set<string>::iterator i; // Iterator for looping over list elements
    for (i = usedNamespaces.begin(); i != usedNamespaces.end(); ++i) {
        analysisResult->addValue(factory->usesNamespaceField, *i);
    }

    analysisResult = 0;
    usedNamespaces.clear();
    ready = true;
}

void
NamespaceHarvesterSaxAnalyzer::startElement(const char *localname,
        const char *prefix, const char *uri, int nb_namespaces,
        const char **namespaces, int nb_attributes, int nb_defaulted,
        const char **attributes) {
    assert(analysisResult != 0);
    if (uri) {
        usedNamespaces.insert(uri);
    }
}

void
NamespaceHarvesterSaxAnalyzer::endElement(const char *localname,
        const char *prefix, const char *uri) {
}

void
NamespaceHarvesterSaxAnalyzer::characters(const char *data, uint32_t length) {
    assert(analysisResult != 0);
}

//Factory
class Factory : public AnalyzerFactoryFactory {
public:
    list<StreamSaxAnalyzerFactory*>
    streamSaxAnalyzerFactories() const {
        list<StreamSaxAnalyzerFactory*> af;
        af.push_back(new NamespaceHarvesterSaxAnalyzerFactory());
        return af;
    }
};

STRIGI_ANALYZER_FACTORY(Factory)
<commit_msg>tiny whitespace change<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2007 Egon Willighagen <egonw@users.sf.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "namespaceharvestersaxanalyzer.h"
#include <strigi/strigiconfig.h>
#include "analysisresult.h"
#include "fieldtypes.h"

#include <cassert>
#include <cstring>
#include <string>
#include <iostream>
#include <set>

using namespace std;
using namespace Strigi;

void
NamespaceHarvesterSaxAnalyzerFactory::registerFields(FieldRegister &reg) {
    usesNamespaceField = reg.registerField(
        "http://freedesktop.org/standards/xesam/1.0/core#usesNamespace");
    addField(usesNamespaceField);
}

void
NamespaceHarvesterSaxAnalyzer::startAnalysis(AnalysisResult *i) {
    assert(i != 0);
    analysisResult = i;
    ready = false;

    usedNamespaces.clear();
}

void
NamespaceHarvesterSaxAnalyzer::endAnalysis(bool /*complete*/) {
    set<string>::iterator i; // Iterator for looping over list elements
    for (i = usedNamespaces.begin(); i != usedNamespaces.end(); ++i) {
        analysisResult->addValue(factory->usesNamespaceField, *i);
    }

    analysisResult = 0;
    usedNamespaces.clear();
    ready = true;
}

void
NamespaceHarvesterSaxAnalyzer::startElement(const char *localname,
        const char *prefix, const char *uri, int nb_namespaces,
        const char **namespaces, int nb_attributes, int nb_defaulted,
        const char **attributes) {
    assert(analysisResult != 0);
    if (uri) {
        usedNamespaces.insert(uri);
    }
}

void
NamespaceHarvesterSaxAnalyzer::endElement(const char *localname,
        const char *prefix, const char *uri) {
}

void
NamespaceHarvesterSaxAnalyzer::characters(const char *data, uint32_t length) {
    assert(analysisResult != 0);
}

//Factory
class Factory : public AnalyzerFactoryFactory {
public:
    list<StreamSaxAnalyzerFactory*>
    streamSaxAnalyzerFactories() const {
        list<StreamSaxAnalyzerFactory*> af;
        af.push_back(new NamespaceHarvesterSaxAnalyzerFactory());
        return af;
    }
};

STRIGI_ANALYZER_FACTORY(Factory)
<|endoftext|>


<commit_before>/*
    Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include "server.hpp"

#include <boost/asio/placeholders.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <iostream>

#include "client.hpp"
#include "config.hpp"

using namespace std;

namespace asio = boost::asio;
namespace fs = boost::filesystem;

using namespace bithorded;

Server::Server(asio::io_service& ioSvc, Config& cfg) :
	_cfg(cfg),
	_ioSvc(ioSvc),
	_tcpListener(ioSvc),
	_localListener(ioSvc)
{
	for (auto iter=_cfg.sources.begin(); iter != _cfg.sources.end(); iter++) {
		_assetStores.push_back( unique_ptr<LinkedAssetStore>(new LinkedAssetStore(ioSvc, iter->root)) );
	}

	if (_cfg.tcpPort) {
		auto tcpPort = asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), _cfg.tcpPort);
		_tcpListener.open(tcpPort.protocol());
		_tcpListener.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
		_tcpListener.bind(tcpPort);
		_tcpListener.listen();

		waitForTCPConnection();
	}

	if (!_cfg.unixSocket.empty()) {
		if (fs::exists(_cfg.unixSocket))
			fs::remove(_cfg.unixSocket);
		auto localPort = asio::local::stream_protocol::endpoint(_cfg.unixSocket);
		_localListener.open(localPort.protocol());
		_localListener.set_option(boost::asio::local::stream_protocol::acceptor::reuse_address(true));
		_localListener.bind(localPort);
		_localListener.listen(4);

		waitForLocalConnection();
	}
}

asio::io_service& Server::ioService()
{
	return _ioSvc;
}

void Server::waitForTCPConnection()
{
	boost::shared_ptr<asio::ip::tcp::socket> sock = boost::make_shared<asio::ip::tcp::socket>(_ioSvc);
	_tcpListener.async_accept(*sock, boost::bind(&Server::onTCPConnected, this, sock, asio::placeholders::error));
}

void Server::onTCPConnected(boost::shared_ptr< asio::ip::tcp::socket >& socket, const boost::system::error_code& ec)
{
	if (!ec) {
		bithorded::Client::Pointer c = bithorded::Client::create(*this, "testserver");
		c->connect(bithorde::Connection::create(_ioSvc, socket));
		clientConnected(c);
		waitForTCPConnection();
	}
}

void Server::waitForLocalConnection()
{
	boost::shared_ptr<asio::local::stream_protocol::socket> sock = boost::make_shared<asio::local::stream_protocol::socket>(_ioSvc);
	_localListener.async_accept(*sock, boost::bind(&Server::onLocalConnected, this, sock, asio::placeholders::error));
}

void Server::onLocalConnected(boost::shared_ptr< boost::asio::local::stream_protocol::socket >& socket, const boost::system::error_code& ec)
{
	if (!ec) {
		bithorded::Client::Pointer c = bithorded::Client::create(*this, "testserver");
		c->connect(bithorde::Connection::create(_ioSvc, socket));
		clientConnected(c);
		waitForLocalConnection();
	}
}

void Server::clientConnected(const bithorde::Client::Pointer& client)
{
	// When storing a client-copy in the bound reference, we make sure the Client isn't
	// destroyed until the disconnected signal calls clientDisconnected, which releases
	// the reference
	client->disconnected.connect(boost::bind(&Server::clientDisconnected, this, client));
}

void Server::clientDisconnected(bithorde::Client::Pointer& client)
{
	cerr << "Disconnected: " << client->peerName() << endl;
	// Will destroy the client, unless others are holding references.
	client.reset();
}

bool Server::linkAsset(const boost::filesystem3::path& filePath, LinkedAssetStore::ResultHandler resultHandler)
{
	for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
		bool res = (*iter)->addAsset(filePath, resultHandler);
		if (res)
			return res;
	}
	return false;
}

Asset::Ptr Server::findAsset(const BitHordeIds& ids)
{
	for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
		Asset::Ptr asset((*iter)->findAsset(ids));
		if (asset)
			return asset;
	}

	return Asset::Ptr();
}
<commit_msg>[server/server]Use actual node-name, not hardcoded "testserver".<commit_after>/*
    Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include "server.hpp"

#include <boost/asio/placeholders.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <iostream>

#include "client.hpp"
#include "config.hpp"

using namespace std;

namespace asio = boost::asio;
namespace fs = boost::filesystem;

using namespace bithorded;

Server::Server(asio::io_service& ioSvc, Config& cfg) :
	_cfg(cfg),
	_ioSvc(ioSvc),
	_tcpListener(ioSvc),
	_localListener(ioSvc)
{
	for (auto iter=_cfg.sources.begin(); iter != _cfg.sources.end(); iter++) {
		_assetStores.push_back( unique_ptr<LinkedAssetStore>(new LinkedAssetStore(ioSvc, iter->root)) );
	}

	if (_cfg.tcpPort) {
		auto tcpPort = asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), _cfg.tcpPort);
		_tcpListener.open(tcpPort.protocol());
		_tcpListener.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
		_tcpListener.bind(tcpPort);
		_tcpListener.listen();

		waitForTCPConnection();
	}

	if (!_cfg.unixSocket.empty()) {
		if (fs::exists(_cfg.unixSocket))
			fs::remove(_cfg.unixSocket);
		auto localPort = asio::local::stream_protocol::endpoint(_cfg.unixSocket);
		_localListener.open(localPort.protocol());
		_localListener.set_option(boost::asio::local::stream_protocol::acceptor::reuse_address(true));
		_localListener.bind(localPort);
		_localListener.listen(4);

		waitForLocalConnection();
	}
}

asio::io_service& Server::ioService()
{
	return _ioSvc;
}

void Server::waitForTCPConnection()
{
	boost::shared_ptr<asio::ip::tcp::socket> sock = boost::make_shared<asio::ip::tcp::socket>(_ioSvc);
	_tcpListener.async_accept(*sock, boost::bind(&Server::onTCPConnected, this, sock, asio::placeholders::error));
}

void Server::onTCPConnected(boost::shared_ptr< asio::ip::tcp::socket >& socket, const boost::system::error_code& ec)
{
	if (!ec) {
		bithorded::Client::Pointer c = bithorded::Client::create(*this, _cfg.nodeName);
		c->connect(bithorde::Connection::create(_ioSvc, socket));
		clientConnected(c);
		waitForTCPConnection();
	}
}

void Server::waitForLocalConnection()
{
	boost::shared_ptr<asio::local::stream_protocol::socket> sock = boost::make_shared<asio::local::stream_protocol::socket>(_ioSvc);
	_localListener.async_accept(*sock, boost::bind(&Server::onLocalConnected, this, sock, asio::placeholders::error));
}

void Server::onLocalConnected(boost::shared_ptr< boost::asio::local::stream_protocol::socket >& socket, const boost::system::error_code& ec)
{
	if (!ec) {
		bithorded::Client::Pointer c = bithorded::Client::create(*this, _cfg.nodeName);
		c->connect(bithorde::Connection::create(_ioSvc, socket));
		clientConnected(c);
		waitForLocalConnection();
	}
}

void Server::clientConnected(const bithorde::Client::Pointer& client)
{
	// When storing a client-copy in the bound reference, we make sure the Client isn't
	// destroyed until the disconnected signal calls clientDisconnected, which releases
	// the reference
	client->disconnected.connect(boost::bind(&Server::clientDisconnected, this, client));
}

void Server::clientDisconnected(bithorde::Client::Pointer& client)
{
	cerr << "Disconnected: " << client->peerName() << endl;
	// Will destroy the client, unless others are holding references.
	client.reset();
}

bool Server::linkAsset(const boost::filesystem3::path& filePath, LinkedAssetStore::ResultHandler resultHandler)
{
	for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
		bool res = (*iter)->addAsset(filePath, resultHandler);
		if (res)
			return res;
	}
	return false;
}

Asset::Ptr Server::findAsset(const BitHordeIds& ids)
{
	for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
		Asset::Ptr asset((*iter)->findAsset(ids));
		if (asset)
			return asset;
	}

	return Asset::Ptr();
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  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 "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "itkQuadEdgeMesh.h"
#include "itkTestingMacros.h"

int
itkMeshFileReaderWriterTest(int argc, char * argv[])
{
  if (argc < 3)
  {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFileName outputFileName" << std::endl;
    return EXIT_FAILURE;
  }

  using coord = double;
  constexpr unsigned int Dimension = 3;

  using MeshType = itk::QuadEdgeMesh<coord, Dimension>;

  using ReaderType = itk::MeshFileReader<MeshType>;
  auto reader = ReaderType::New();

  ITK_EXERCISE_BASIC_OBJECT_METHODS(reader, MeshFileReader, MeshSource);

  // Test exceptions
  std::string inputFileName = "";
  reader->SetFileName(inputFileName);

  inputFileName = argv[1];
  reader->SetFileName(inputFileName);

  ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update());

  MeshType::Pointer readMesh = nullptr;
  ITK_TRY_EXPECT_NO_EXCEPTION(readMesh = itk::ReadMesh<MeshType>(inputFileName));

  ITK_TRY_EXPECT_NO_EXCEPTION(itk::WriteMesh(readMesh.GetPointer(), inputFileName));
  ITK_TRY_EXPECT_NO_EXCEPTION(itk::WriteMesh(readMesh, inputFileName));

  std::cout << "Test finished" << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>ENH: Add checks to itkMeshFileReaderWriterTest<commit_after>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  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 "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "itkQuadEdgeMesh.h"
#include "itkTestingMacros.h"
#include "itkMeshFileTestHelper.h"

int
itkMeshFileReaderWriterTest(int argc, char * argv[])
{
  if (argc < 3)
  {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputFileName outputFileName" << std::endl;
    return EXIT_FAILURE;
  }

  using coord = double;
  constexpr unsigned int Dimension = 3;

  using MeshType = itk::QuadEdgeMesh<coord, Dimension>;

  using ReaderType = itk::MeshFileReader<MeshType>;
  auto reader = ReaderType::New();

  ITK_EXERCISE_BASIC_OBJECT_METHODS(reader, MeshFileReader, MeshSource);

  // Test exceptions
  std::string inputFileName = "";
  reader->SetFileName(inputFileName);
  ITK_TRY_EXPECT_EXCEPTION(reader->Update());

  inputFileName = argv[1];
  reader->SetFileName(inputFileName);

  ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update());

  MeshType::Pointer readMesh = nullptr;
  ITK_TRY_EXPECT_NO_EXCEPTION(readMesh = itk::ReadMesh<MeshType>(inputFileName));

  const std::string outputFileName = argv[2];
  ITK_TRY_EXPECT_NO_EXCEPTION(itk::WriteMesh(readMesh.GetPointer(), outputFileName));
  ITK_TRY_EXPECT_NO_EXCEPTION(itk::WriteMesh(readMesh, outputFileName));

  MeshType::Pointer writeReadMesh = nullptr;
  ITK_TRY_EXPECT_NO_EXCEPTION(writeReadMesh = itk::ReadMesh<MeshType>(outputFileName));

  ITK_TEST_EXPECT_EQUAL(TestPointsContainer<MeshType>(readMesh->GetPoints(), writeReadMesh->GetPoints()), EXIT_SUCCESS);
  ITK_TEST_EXPECT_EQUAL(TestCellsContainer<MeshType>(readMesh->GetCells(), writeReadMesh->GetCells()), EXIT_SUCCESS);
  ITK_TEST_EXPECT_EQUAL(TestPointDataContainer<MeshType>(readMesh->GetPointData(), writeReadMesh->GetPointData()),
                        EXIT_SUCCESS);
  ITK_TEST_EXPECT_EQUAL(TestCellDataContainer<MeshType>(readMesh->GetCellData(), writeReadMesh->GetCellData()),
                        EXIT_SUCCESS);

  std::cout << "Test finished" << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE Test_BasicPhysic
#include <boost/test/unit_test.hpp>

#include <SFML/System/Vector2.hpp>
/* make everything public for testing */
#define private public
#define protected public
#include "../src/BasicPhysic.hpp"

/*
 * USER DEFINED CLASSES
 */

class BodyTester : virtual public PhysicBody {
public:
    BodyTester (float x = 0, float y = 0) : PhysicBody (x, y) {}
};

/*
 * FIXTURE
 * BodyTester o1 : no initial movement, no acceleration
 * BodyTester o2 : (10,10) initial movement, (-20,-20) acceleration
 */

struct PhysicFixture {
    BodyTester o1;
    BodyTester o2;
    PhysicFixture () : o2(10, 10) {}
};

/*
 * TESTS
 */

BOOST_AUTO_TEST_SUITE( BodyTester_Initializer )

BOOST_FIXTURE_TEST_CASE ( BodyTester_constructor, PhysicFixture ) {

    BOOST_REQUIRE ( o1.force == sf::Vector2f(0, 0) );
    BOOST_REQUIRE ( o2.force == sf::Vector2f(10, 10) );

}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test++<commit_after>#define BOOST_TEST_MODULE Test_BasicPhysic
#include <boost/test/unit_test.hpp>

#include <SFML/System/Vector2.hpp>
/* make everything public for testing */
#define private public
#define protected public
#include "../src/BasicPhysic.hpp"

/*
 * USER DEFINED CLASSES
 */

class BodyTester : virtual public PhysicBody {
public:
    BodyTester (float x = 0, float y = 0) : PhysicBody (x, y) {}
};

/*
 * FIXTURE
 * BodyTester o1 : no initial movement, no acceleration
 * BodyTester o2 : (10,10) initial movement, (-20,-20) acceleration
 */

struct PhysicFixture {
    BasicPhysic physic;
    BodyTester o1;
    BodyTester o2;
    PhysicFixture () : o2(10, 10) {}
};

/*
 * TESTS
 */

BOOST_AUTO_TEST_SUITE( BodyTester_Initializer )

BOOST_FIXTURE_TEST_CASE ( BodyTester_constructor, PhysicFixture ) {

    BOOST_REQUIRE ( o1.force == sf::Vector2f(0, 0) );
    BOOST_REQUIRE ( o2.force == sf::Vector2f(10, 10) );

}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( PhysicBody_test )

BOOST_FIXTURE_TEST_CASE ( applyForce, PhysicFixture ) {

    sf::Vector2f f(10, 10);

    o1.applyForce(f);
    o2.applyForce(f);

    BOOST_CHECK ( o1.force == sf::Vector2f(10, 10) );
    BOOST_CHECK ( o2.force == sf::Vector2f(20, 20) );

}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( BasicPhysic_test )

BOOST_FIXTURE_TEST_CASE ( reaction1, PhysicFixture ) {

    physic.reaction(&o1, &o2);

    BOOST_CHECK ( o1.force == sf::Vector2f(10, 10) );
    BOOST_CHECK ( o2.force == sf::Vector2f(0, 0) );

}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>