text:
/***********************************************************************************************************************
*  OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
*  following conditions are met:
*
*  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
*  disclaimer.
*
*  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
*  disclaimer in the documentation and/or other materials provided with the distribution.
*
*  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
*  derived from this software without specific prior written permission from the respective party.
*
*  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
*  may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
*  written permission from Alliance for Sustainable Energy, LLC.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
*  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
*  STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
*  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/

#include <gtest/gtest.h>
#include "EnergyPlusFixture.hpp"

#include "../ErrorFile.hpp"
#include "../ForwardTranslator.hpp"
#include "../ReverseTranslator.hpp"

#include "../../model/Model.hpp"
#include "../../model/Model_Impl.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/Schedule_Impl.hpp"
#include "../../model/ScheduleTypeLimits.hpp"
#include "../../model/ScheduleTypeLimits_Impl.hpp"
#include "../../model/Building.hpp"
#include "../../model/Building_Impl.hpp"
#include "../../model/ThermalZone.hpp"
#include "../../model/FanConstantVolume.hpp"
#include "../../model/FanConstantVolume_Impl.hpp"
#include "../../model/ElectricEquipment.hpp"
#include "../../model/ElectricEquipment_Impl.hpp"
#include "../../model/ElectricEquipmentDefinition.hpp"
#include "../../model/ElectricEquipmentDefinition_Impl.hpp"

#include "../../model/ExternalInterface.hpp"
#include "../../model/ExternalInterface_Impl.hpp"
#include "../../model/ExternalInterfaceActuator.hpp"
#include "../../model/ExternalInterfaceActuator_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportFromVariable.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportFromVariable_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportToActuator.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportToActuator_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportToSchedule.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportToSchedule_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportToVariable.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitExportToVariable_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImport.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImport_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportFromVariable.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportFromVariable_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToActuator.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToActuator_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToSchedule.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToSchedule_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToVariable.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToVariable_Impl.hpp"
#include "../../model/ExternalInterfaceSchedule.hpp"
#include "../../model/ExternalInterfaceSchedule_Impl.hpp"
#include "../../model/ExternalInterfaceVariable.hpp"
#include "../../model/ExternalInterfaceVariable_Impl.hpp"

#include <utilities/idd/OS_ExternalInterface_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_Actuator_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_Actuator_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_Variable_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_Variable_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_Schedule_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_Schedule_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitImport_To_Variable_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitImport_To_Variable_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitImport_To_Schedule_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitImport_To_Schedule_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitImport_To_Actuator_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitImport_To_Actuator_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitImport_From_Variable_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitImport_From_Variable_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitImport_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitImport_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitExport_To_Variable_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitExport_To_Variable_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitExport_To_Schedule_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitExport_To_Schedule_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitExport_To_Actuator_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitExport_To_Actuator_FieldEnums.hxx>
#include <utilities/idd/OS_ExternalInterface_FunctionalMockupUnitExport_From_Variable_FieldEnums.hxx>
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitExport_From_Variable_FieldEnums.hxx>

#include "../../model/Version.hpp"
#include "../../model/Version_Impl.hpp"

#include "../../utilities/geometry/Point3d.hpp"

#include "../../utilities/core/Optional.hpp"
#include "../../utilities/core/Checksum.hpp"
#include "../../utilities/core/UUID.hpp"
#include "../../utilities/core/Logger.hpp"
#include "../../utilities/sql/SqlFile.hpp"
#include "../../utilities/idf/IdfFile.hpp"
#include "../../utilities/idf/IdfObject.hpp"

#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>

#include <boost/algorithm/string/predicate.hpp>

#include <resources.hxx>

#include <sstream>

#include <vector>

using namespace openstudio::energyplus;
using namespace openstudio::model;
using namespace openstudio;

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterface) {
  Model model;

  ExternalInterface externalinterface = model.getUniqueModelObject<ExternalInterface>();
  EXPECT_EQ("PtolemyServer", externalinterface.nameofExternalInterface());
  EXPECT_TRUE(externalinterface.setNameofExternalInterface("FunctionalMockupUnitImport"));

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface)[0];

  ASSERT_TRUE(object.getString(ExternalInterfaceFields::NameofExternalInterface, false));
  EXPECT_EQ("FunctionalMockupUnitImport", object.getString(ExternalInterfaceFields::NameofExternalInterface, false).get());

  // model.save(toPath("./ExternalInterface.osm"), true);
  // workspace.save(toPath("./ExternalInterface.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceActuator) {
  Model model;

  Building building = model.getUniqueModelObject<Building>();

  // add fan
  Schedule s = model.alwaysOnDiscreteSchedule();
  FanConstantVolume fan(model, s);

  // add actuator
  std::string fanControlType = "Fan Pressure Rise";
  std::string ComponentType = "Fan";
  ExternalInterfaceActuator fanActuator(fan, ComponentType, fanControlType);

  std::string fanName = fan.name().get() + "Press Actuator";
  fanActuator.setName(fanName);
  fanActuator.setOptionalInitialValue(1);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_Actuator).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_Actuator)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_ActuatorFields::ActuatedComponentUniqueName, false));
  EXPECT_EQ(fan.nameString(), object.getString(ExternalInterface_ActuatorFields::ActuatedComponentUniqueName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_ActuatorFields::ActuatedComponentType, false));
  EXPECT_EQ(ComponentType, object.getString(ExternalInterface_ActuatorFields::ActuatedComponentType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_ActuatorFields::ActuatedComponentControlType, false));
  EXPECT_EQ(fanControlType, object.getString(ExternalInterface_ActuatorFields::ActuatedComponentControlType, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_ActuatorFields::OptionalInitialValue, false));
  EXPECT_EQ(1.0, object.getDouble(ExternalInterface_ActuatorFields::OptionalInitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceActuator.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceActuator.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceVariable) {

  Model model;
  ExternalInterfaceVariable variable(model, "test name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_Variable).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_Variable)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_VariableFields::Name, false));
  EXPECT_EQ("test name", object.getString(ExternalInterface_VariableFields::Name, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_VariableFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_VariableFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceVariable.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceVariable.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceSchedule) {

  Model model;
  ExternalInterfaceSchedule schedule(model, 10);
  EXPECT_EQ(10.0, schedule.initialValue());
  EXPECT_EQ("External Interface Schedule 1", schedule.nameString());

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_Schedule).size());
  //EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_Schedule)[0];
  //WorkspaceObject object2 = workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_ScheduleFields::Name, false));
  EXPECT_EQ("External Interface Schedule 1", object.getString(ExternalInterface_ScheduleFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_ScheduleFields::ScheduleTypeLimitsName, false));
  //EXPECT_EQ(object2.nameString(), object.getString(ExternalInterface_ScheduleFields::ScheduleTypeLimitsName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_ScheduleFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_ScheduleFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceSchedule.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceSchedule.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitImport) {

  Model model;

  ExternalInterfaceFunctionalMockupUnitImport eifmui(model, "c:\\Program Files\\Test\\blah.fmu");

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImportFields::FMUFileName, false));
  EXPECT_EQ("c:\\Program Files\\Test\\blah.fmu", object.getString(ExternalInterface_FunctionalMockupUnitImportFields::FMUFileName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitImportFields::FMUTimeout, false));
  EXPECT_EQ(0, object.getDouble(ExternalInterface_FunctionalMockupUnitImportFields::FMUTimeout, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitImportFields::FMULoggingOn, false));
  EXPECT_EQ(0, object.getDouble(ExternalInterface_FunctionalMockupUnitImportFields::FMULoggingOn, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitImport.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitImport.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitExportFromVariable) {
  Model model;

  std::string outputVariableIndexKeyName = "outputVariableIndexKeyName";
  std::string outputVariableName = "outputVariableName";
  std::string fMUVariableName = "fMUVariableName";

  ExternalInterfaceFunctionalMockupUnitExportFromVariable variable(model, outputVariableIndexKeyName, outputVariableName, fMUVariableName);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_From_Variable).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_From_Variable)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_From_VariableFields::Output_VariableIndexKeyName, false));
  EXPECT_EQ(outputVariableIndexKeyName,
            object.getString(ExternalInterface_FunctionalMockupUnitExport_From_VariableFields::Output_VariableIndexKeyName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_From_VariableFields::Output_VariableName, false));
  EXPECT_EQ(outputVariableName, object.getString(ExternalInterface_FunctionalMockupUnitExport_From_VariableFields::Output_VariableName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_From_VariableFields::FMUVariableName, false));
  EXPECT_EQ(fMUVariableName, object.getString(ExternalInterface_FunctionalMockupUnitExport_From_VariableFields::FMUVariableName, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportFromVariable.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportFromVariable.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitExportToActuator) {
  Model model;

  Building building = model.getUniqueModelObject<Building>();

  // add fan
  Schedule s = model.alwaysOnDiscreteSchedule();
  FanConstantVolume fan(model, s);

  // add actuator
  std::string fanControlType = "Fan Pressure Rise";
  std::string ComponentType = "Fan";
  ExternalInterfaceFunctionalMockupUnitExportToActuator fanActuator(fan, ComponentType, fanControlType, "Fan FMU name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Actuator).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Actuator)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::Name, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Export To Actuator 1",
            object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentUniqueName, false));
  EXPECT_EQ(fan.nameString(),
            object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentUniqueName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentType, false));
  EXPECT_EQ(ComponentType, object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentControlType, false));
  EXPECT_EQ(fanControlType,
            object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentControlType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::FMUVariableName, false));
  EXPECT_EQ("Fan FMU name", object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToActuator.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToActuator.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitExportToVariable) {
  Model model;

  ExternalInterfaceFunctionalMockupUnitExportToVariable variable(model, "FMU name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Variable).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Variable)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_VariableFields::Name, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Export To Variable 1",
            object.getString(ExternalInterface_FunctionalMockupUnitExport_To_VariableFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_VariableFields::FMUVariableName, false));
  EXPECT_EQ("FMU name", object.getString(ExternalInterface_FunctionalMockupUnitExport_To_VariableFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_VariableFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_VariableFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToVariable.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToVariable.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitExportToSchedule) {

  Model model;
  ExternalInterfaceFunctionalMockupUnitExportToSchedule schedule(model, "FMU name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Schedule).size());
  //EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Schedule)[0];
  //WorkspaceObject object2 = workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::ScheduleName, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Export To Schedule 1",
            object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::ScheduleName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::ScheduleTypeLimitsNames, false));
  //EXPECT_EQ(object2.nameString(), object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::ScheduleTypeLimitsNames, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::FMUVariableName, false));
  EXPECT_EQ("FMU name", object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_ScheduleFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToSchedule.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToSchedule.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitImportFromVariable) {
  Model model;
  // add FMU
  ExternalInterfaceFunctionalMockupUnitImport eifmui(model, "test name");

  std::string outputVariableIndexKeyName = "outputVariableIndexKeyName";
  std::string outputVariableName = "outputVariableName";
  std::string fMUVariableName = "fMUVariableName";
  std::string fMUInstanceName = "fMUInstanceName";

  ExternalInterfaceFunctionalMockupUnitImportFromVariable variable(model, outputVariableIndexKeyName, outputVariableName, eifmui, fMUInstanceName,
                                                                   fMUVariableName);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_From_Variable).size());
  //EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_From_Variable)[0];
  //WorkspaceObject object2 = workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::Output_VariableIndexKeyName, false));
  EXPECT_EQ(outputVariableIndexKeyName,
            object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::Output_VariableIndexKeyName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::Output_VariableName, false));
  EXPECT_EQ(outputVariableName, object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::Output_VariableName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::FMUFileName, false));
  EXPECT_EQ(eifmui.fMUFileName(), object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::FMUFileName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::FMUInstanceName, false));
  EXPECT_EQ(fMUInstanceName, object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::FMUInstanceName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::FMUVariableName, false));
  EXPECT_EQ(fMUVariableName, object.getString(ExternalInterface_FunctionalMockupUnitImport_From_VariableFields::FMUVariableName, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportFromVariable.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportFromVariable.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitImportToVariable) {
  Model model;
  // add FMU
  ExternalInterfaceFunctionalMockupUnitImport eifmui(model, "test name");

  std::string fMUVariableName = "fMUVariableName";
  std::string fMUInstanceName = "fMUInstanceName";

  ExternalInterfaceFunctionalMockupUnitImportToVariable variable(model, eifmui, fMUInstanceName, fMUVariableName, 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Variable).size());
  //EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Variable)[0];
  //WorkspaceObject object2 = workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::Name, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Import To Variable 1",
            object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::FMUFileName, false));
  EXPECT_EQ(eifmui.fMUFileName(), object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::FMUFileName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::FMUInstanceName, false));
  EXPECT_EQ(fMUInstanceName, object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::FMUInstanceName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::FMUVariableName, false));
  EXPECT_EQ(fMUVariableName, object.getString(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitImport_To_VariableFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportToVariable.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportToVariable.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitImportToSchedule) {

  Model model;

  ExternalInterfaceFunctionalMockupUnitImport eifmui(model, "test name");

  ExternalInterfaceFunctionalMockupUnitImportToSchedule schedule(model, eifmui, "FMU", "FMU name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Schedule).size());
  //EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Schedule)[0];
  //WorkspaceObject object2 = workspace.getObjectsByType(IddObjectType::ScheduleTypeLimits)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::Name, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Import To Schedule 1",
            object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::ScheduleTypeLimitsNames, false));
  //EXPECT_EQ(object2.nameString(), object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::ScheduleTypeLimitsNames, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::FMUFileName, false));
  EXPECT_EQ(eifmui.fMUFileName(), object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::FMUFileName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::FMUInstanceName, false));
  EXPECT_EQ("FMU", object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::FMUInstanceName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::FMUVariableName, false));
  EXPECT_EQ("FMU name", object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitImport_To_ScheduleFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportToSchedule.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportToSchedule.idf"), true);
}

TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitImportToActuator) {
  Model model;

  Building building = model.getUniqueModelObject<Building>();

  // add fan
  Schedule s = model.alwaysOnDiscreteSchedule();
  FanConstantVolume fan(model, s);

  // add FMU
  ExternalInterfaceFunctionalMockupUnitImport eifmui(model, "test name");

  // add actuator
  std::string fanControlType = "Fan Pressure Rise";
  std::string ComponentType = "Fan";
  ExternalInterfaceFunctionalMockupUnitImportToActuator fanActuator(fan, ComponentType, fanControlType, eifmui, "FMU", "Fan FMU name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Actuator).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Actuator)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::Name, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Import To Actuator 1",
            object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentUniqueName, false));
  EXPECT_EQ(fan.nameString(),
            object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentUniqueName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentType, false));
  EXPECT_EQ(ComponentType, object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentControlType, false));
  EXPECT_EQ(fanControlType,
            object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentControlType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUFileName, false));
  EXPECT_EQ(eifmui.fMUFileName(), object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUFileName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUVariableName, false));
  EXPECT_EQ("Fan FMU name", object.getString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::InitialValue, false).get());

  // model.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportToActuator.osm"), true);
  // workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitImportToActuator.idf"), true);
}

max_stars_repo_name: muehleisen/OpenStudio

max_issues_repo_name: muehleisen/OpenStudio

max_forks_repo_name: jmarrec/OpenStudio


text: #include <boost/thread/executors/serial_executor_cont.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "DpdkCoreThread.h"

#include <boost/log/trivial.hpp>

namespace org::openkilda {

    DpdkCoreThread::DpdkCoreThread(thread_t thread_function) :
            thread(std::move(thread_function)) {
    }

    bool DpdkCoreThread::run(uint32_t used_core_id) {
        alive.store(true);
        core_id = used_core_id;

        bool ret = thread(core_id, alive);

        thread.clear();

        if (alive.load()) {
            BOOST_LOG_TRIVIAL(error) << "Thread shutdown";
        } else {
            BOOST_LOG_TRIVIAL(info) << "Thread shutdown";
        }

        return ret;
    }

    void DpdkCoreThread::stop() {
        alive.store(false);
    }

    uint32_t DpdkCoreThread::getCoreId() const {
        return core_id;
    }

}

ext: cpp

max_stars_repo_name: kawaja/Kilda

max_issues_repo_name: kawaja/Kilda

max_forks_repo_name: kawaja/Kilda


text:
// Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

#ifndef METALL_OFFSET_PTR_HPP
#define METALL_OFFSET_PTR_HPP

#include <boost/interprocess/offset_ptr.hpp>
#include <boost/interprocess/detail/utilities.hpp>

namespace metall {

/// \tparam T A type.
/// \brief Holds an offset between the address pointing at and itself.
template <typename T>
using offset_ptr = boost::interprocess::offset_ptr<T>;

/// \brief Convert a offset pointer to the corresponding raw pointer
using boost::interprocess::ipcdetail::to_raw_pointer;
}

/// \example offset_pointer.cpp
/// This is an example of how to use offset_pointer.

#endif //METALL_OFFSET_PTR_HPP

max_stars_repo_name: dice-group/metall

max_issues_repo_name: dice-group/metall

max_forks_repo_name: dice-group/metall


text:
/*
 * This file is part of the CN24 semantic segmentation software,
 * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
 *
 * For licensing information, see the LICENSE file included with this project.
 */

#include <string>
#include <sstream>

#ifdef BUILD_BOOST
#include <boost/regex.hpp>
#else
#include <regex>
#endif

#include "ConvolutionLayer.h"
#include "NonLinearityLayer.h"
#include "MaxPoolingLayer.h"
#include "AdvancedMaxPoolingLayer.h"
#include "GradientAccumulationLayer.h"
#include "ResizeLayer.h"
#include "HMaxActivationFunction.h"
#include "LayerFactory.h"

namespace Conv {
bool LayerFactory::IsValidDescriptor(std::string descriptor) {
  const std::string valid_descriptor_regex =
    "^[a-z]+(\\("
    "("
    "[a-z]+=[a-zA-Z0-9\\.]+"
    "( [a-z]+=[a-zA-Z0-9\\.]+)*"
    ")?"
    "\\))?$";
#ifdef BUILD_BOOST
  bool valid = boost::regex_match(descriptor, boost::regex(valid_descriptor_regex,boost::regex::extended));
#else
  bool valid = std::regex_match(descriptor, std::regex(valid_descriptor_regex,std::regex::extended));
#endif
  return valid;
}

std::string LayerFactory::ExtractConfiguration(std::string descriptor) {
  const std::string config_regex = "[a-z]+\\((.+)\\)";
#ifdef BUILD_BOOST
  boost::smatch config_match;
  bool has_nonempty_configuration = boost::regex_match(descriptor, config_match, boost::regex(config_regex, boost::regex::extended));
#else
  std::smatch config_match;
  bool has_nonempty_configuration = std::regex_match(descriptor, config_match, std::regex(config_regex, std::regex::extended));
#endif
  if(has_nonempty_configuration && config_match.size() == 2) {
    return config_match[1];
  } else {
    return "";
  }
}

std::string LayerFactory::ExtractLayerType(std::string descriptor) {
  std::string layertype_regex = "([a-z]+)(\\(.*\\))?";
#ifdef BUILD_BOOST
  boost::smatch config_match;
  bool has_layertype = boost::regex_match(descriptor, config_match, boost::regex(layertype_regex, boost::regex::extended));
#else
  std::smatch config_match;
  bool has_layertype = std::regex_match(descriptor, config_match, std::regex(layertype_regex, std::regex::extended));
#endif
  if(has_layertype && config_match.size() > 1) {
    return config_match[1];
  } else {
    return "";
  }
}

#define CONV_LAYER_TYPE(ltype,lclass) else if (layertype.compare(ltype) == 0) { \
layer = new lclass (configuration) ; \
}

Layer* LayerFactory::ConstructLayer(std::string descriptor) {
  if (!IsValidDescriptor(descriptor))
    return nullptr;
  std::string configuration = ExtractConfiguration(descriptor);
  std::string layertype = ExtractLayerType(descriptor);

  Layer* layer = nullptr;
  if(layertype.length() == 0) {
    // Leave layer a nullptr
  }
  CONV_LAYER_TYPE("convolution", ConvolutionLayer)
  CONV_LAYER_TYPE("maxpooling", MaxPoolingLayer)
  CONV_LAYER_TYPE("amaxpooling", AdvancedMaxPoolingLayer)
  CONV_LAYER_TYPE("tanh", TanhLayer)
  CONV_LAYER_TYPE("sigm", SigmoidLayer)
  CONV_LAYER_TYPE("relu", ReLULayer)
  CONV_LAYER_TYPE("gradientaccumulation", GradientAccumulationLayer)
  CONV_LAYER_TYPE("resize", ResizeLayer)
  CONV_LAYER_TYPE("hmax", HMaxActivationFunction);

  return layer;
}

std::string LayerFactory::InjectSeed(std::string descriptor, unsigned int seed) {
  if(IsValidDescriptor(descriptor)) {
    const std::string has_seed_regex = ".*seed=[0-9]+.*";
    const std::string new_seed_regex = "seed=([0-9])+";
    std::string configuration = ExtractConfiguration(descriptor);
    std::string layertype = ExtractLayerType(descriptor);

    std::stringstream seed_ss;
    seed_ss << "seed=" << seed;

#ifdef BUILD_BOOST
    bool already_has_seed = boost::regex_match(configuration, boost::regex(has_seed_regex, boost::regex::extended));
#else
    bool already_has_seed = std::regex_match(configuration, std::regex(has_seed_regex, std::regex::extended));
#endif
    if(already_has_seed) {
#ifdef BUILD_BOOST
      std::string new_descriptor = boost::regex_replace(descriptor, boost::regex(new_seed_regex, boost::regex::extended), seed_ss.str());
#else
      std::string new_descriptor = std::regex_replace(descriptor, std::regex(new_seed_regex, std::regex::extended), seed_ss.str());
#endif
      return new_descriptor;
    } else {
      std::stringstream new_descriptor_ss;
      new_descriptor_ss << layertype << "(";
      if(configuration.length() > 0) {
        new_descriptor_ss << configuration << " ";
      }
      new_descriptor_ss << seed_ss.str() << ")";
      std::string new_descriptor = new_descriptor_ss.str();
      return new_descriptor;
    }
  } else {
    return descriptor;
  }
}

}


text:
#pragma once

#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <appbase/application.hpp>
#include <golos/plugins/chain/plugin.hpp>
#include <golos/plugins/json_rpc/utility.hpp>
#include <golos/plugins/json_rpc/plugin.hpp>

namespace golos     {
namespace plugins   {
namespace raw_block {

using golos::plugins::json_rpc::msg_pack;

struct get_raw_block_r {
    golos::chain::block_id_type block_id;
    golos::chain::block_id_type previous;
    fc::time_point_sec timestamp;
    std::string raw_block;
};

DEFINE_API_ARGS ( get_raw_block, msg_pack, get_raw_block_r )

using boost::program_options::options_description;

class plugin final : public appbase::plugin<plugin> {
public:
    APPBASE_PLUGIN_REQUIRES(
        (chain::plugin)
        (json_rpc::plugin)
    )

    constexpr const static char *plugin_name = "raw_block";

    static const std::string &name() {
        static std::string name = plugin_name;
        return name;
    }

    plugin();

    ~plugin();

    void set_program_options(
        boost::program_options::options_description &cli,
        boost::program_options::options_description &cfg) override {
    }

    void plugin_initialize(const boost::program_options::variables_map &options) override;

    void plugin_startup() override;

    void plugin_shutdown() override;

    DECLARE_API (
        (get_raw_block)
    )

private:
    struct plugin_impl;

    std::unique_ptr<plugin_impl> my;
};

} } } // golos::plugins::raw_block

FC_REFLECT((golos::plugins::raw_block::get_raw_block_r),
    (block_id)(previous)(timestamp)(raw_block)
)

max_stars_repo_name: rusladder/LadderChain

max_issues_repo_name: rusladder/LadderChain

max_forks_repo_name: rusladder/LadderChain


text:
/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#ifndef _WIN32
#include <signal.h>
#endif

#include <boost/shared_ptr.hpp>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <alcommon/albrokermanager.h>

using namespace std;
using namespace AL;

#include "allaser.h"

extern "C"
{

int _createModule( boost::shared_ptr<ALBroker> pBroker )
{
  // init broker with the main broker instance
  // from the parent executable
  ALBrokerManager::setInstance(pBroker->fBrokerManager.lock());
  ALBrokerManager::getInstance()->addBroker(pBroker);
  ALModule::createModule<ALLaser>(pBroker,"ALLaser" );
  return 0;
}

} // extern "C"

max_stars_repo_name: aldebaran/allaser

max_issues_repo_name: aldebaran/allaser

max_forks_repo_name: aldebaran/allaser


text:
// -*- C++ -*-
//
// Copyright Sylvain Bougerel 2009 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file COPYING or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_DYN_LINK
#define SPATIAL_ENABLE_ASSERT // detect interal issues that should not occur

#include <boost/test/unit_test.hpp>
#include "spatial_test_fixtures.hpp"

BOOST_AUTO_TEST_CASE( test_loose_balancing )
{
  details::Dynamic_rank rank(2);
  loose_balancing test;
  // A leaf node is always balanced!
  BOOST_CHECK_EQUAL(test(rank, 0, 0), false);
  // rebalance even if no right.
  BOOST_CHECK_EQUAL(test(rank, 4, 0), true);
  // reblance even if no left.
  BOOST_CHECK_EQUAL(test(rank, 0, 4), true);
  // should fail cause we are right under loose balancing conditions
  BOOST_CHECK_EQUAL(test(rank, 7, 2), false);
  // should fail cause we are right under loose balancing conditions
  BOOST_CHECK_EQUAL(test(rank, 9, 3), false);
  // should pass cause we are above loose balancing conditions
  BOOST_CHECK_EQUAL(test(rank, 2, 8), true);
  // should pass cause we are above loose balancing conditions
  BOOST_CHECK_EQUAL(test(rank, 8, 2), true);
}

BOOST_AUTO_TEST_CASE( test_tight_balancing )
{
  {
    details::Dynamic_rank rank(2);
    tight_balancing test;
    // A leaf node is always balanced!
    BOOST_CHECK_EQUAL(test(rank, 0, 0), false);
    // rebalance even if no right.
    BOOST_CHECK_EQUAL(test(rank, 9, 0), true);
    // rebalance even if no left.
    BOOST_CHECK_EQUAL(test(rank, 0, 9), true);
    // should fail cause we are right under tight balancing conditions
    BOOST_CHECK_EQUAL(test(rank, 4, 2), false);
    // should fail cause we are right under tight balancing conditions
    BOOST_CHECK_EQUAL(test(rank, 2, 4), false);
    // should pass cause we are above tight balancing conditions
    BOOST_CHECK_EQUAL(test(rank, 3, 6), true);
    // should pass cause we are above tight balancing conditions
    BOOST_CHECK_EQUAL(test(rank, 6, 3), true);
  }
  {
    details::Dynamic_rank rank(9);
    tight_balancing test;
    // high dimension prevent rebalance.
    BOOST_CHECK_EQUAL(test(rank, 1, 8), false);
    BOOST_CHECK_EQUAL(test(rank, 8, 1), false);
  }
}

BOOST_AUTO_TEST_CASE( test_perfect_balancing )
{
  {
    details::Dynamic_rank rank(2);
    perfect_balancing test;
    // A leaf node is always balanced!
    BOOST_CHECK_EQUAL(test(rank, 0, 0), false);
    // rebalance even if no right.
    BOOST_CHECK_EQUAL(test(rank, 4, 1), true);
    // rebalance even if no left.
    BOOST_CHECK_EQUAL(test(rank, 2, 5), true);
    // should fail cause we are right under perfect balancing conditions
    BOOST_CHECK_EQUAL(test(rank, 2, 0), false);
    // should fail cause we are right under perfect balancing conditions
    BOOST_CHECK_EQUAL(test(rank, 0, 2), false);
  }
  {
    details::Dynamic_rank rank(9);
    perfect_balancing test;
    // high dimension does not change balancing
    BOOST_CHECK_EQUAL(test(rank, 0, 2), false);
    BOOST_CHECK_EQUAL(test(rank, 2, 0), false);
    BOOST_CHECK_EQUAL(test(rank, 0, 3), true);
    BOOST_CHECK_EQUAL(test(rank, 3, 0), true);
  }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_ctor )
{
  typedef details::Relaxed_kdtree
    <details::Dynamic_rank, int2, int2, bracket_less<int2>,
     tight_balancing, std::allocator<int2> > kdtree_type;
  kdtree_type instance_one;
  kdtree_type instance_two(details::Dynamic_rank(2));
  kdtree_type instance_three(details::Dynamic_rank(2), bracket_less<int2>());
  kdtree_type instance_four(details::Dynamic_rank(2), bracket_less<int2>(),
                            tight_balancing());
  kdtree_type instance_five(details::Dynamic_rank(2), bracket_less<int2>(),
                            tight_balancing(), std::allocator<int2>());
  // Trees should be empty.
  BOOST_CHECK(instance_one.empty());
  BOOST_CHECK(instance_two.empty());
  BOOST_CHECK(instance_three.empty());
  BOOST_CHECK(instance_four.empty());
  BOOST_CHECK(instance_five.empty());
  // That also mean that beginning equal end for each of them
  BOOST_CHECK(instance_one.begin() == instance_one.end());
  BOOST_CHECK(instance_two.begin() == instance_two.end());
  BOOST_CHECK(instance_three.begin() == instance_three.end());
  BOOST_CHECK(instance_four.begin() == instance_four.end());
  BOOST_CHECK(instance_five.begin() == instance_five.end());
  // And that also mean that have a size of 0
  BOOST_CHECK_EQUAL(instance_one.size(), 0);
  BOOST_CHECK_EQUAL(instance_two.size(), 0);
  BOOST_CHECK_EQUAL(instance_three.size(), 0);
  BOOST_CHECK_EQUAL(instance_four.size(), 0);
  BOOST_CHECK_EQUAL(instance_five.size(), 0);
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_tight )
{
  typedef details::Relaxed_kdtree
    <details::Static_rank<2>, int2, int2, bracket_less<int2>,
     tight_balancing, std::allocator<int2> > kdtree_type;
  kdtree_type tree;
  kdtree_type::const_iterator it;
  BOOST_CHECK_NO_THROW(it = tree.insert(zeros));
  BOOST_CHECK(*it == zeros);
  BOOST_CHECK(!tree.empty());
  BOOST_CHECK(tree.begin() != tree.end());
  BOOST_CHECK_EQUAL(tree.size(), 1);
  BOOST_CHECK(zeros == *tree.begin());
  BOOST_CHECK(++tree.begin() == tree.end());
  BOOST_CHECK(tree.begin() == --tree.end());
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_perfect )
{
  typedef details::Relaxed_kdtree
    <details::Static_rank<2>, int2, int2, bracket_less<int2>,
     perfect_balancing, std::allocator<int2> > kdtree_type;
  kdtree_type tree;
  kdtree_type::const_iterator it;
  BOOST_CHECK_NO_THROW(it = tree.insert(zeros));
  BOOST_CHECK(*it == zeros);
  BOOST_CHECK(!tree.empty());
  BOOST_CHECK(tree.begin() != tree.end());
  BOOST_CHECK_EQUAL(tree.size(), 1);
  BOOST_CHECK(zeros == *tree.begin());
  BOOST_CHECK(++tree.begin() == tree.end());
  BOOST_CHECK(tree.begin() == --tree.end());
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_loose )
{
  typedef details::Relaxed_kdtree
    <details::Static_rank<2>, int2, int2, bracket_less<int2>,
     loose_balancing, std::allocator<int2> > kdtree_type;
  kdtree_type tree;
  kdtree_type::const_iterator it;
  BOOST_CHECK_NO_THROW(it = tree.insert(zeros));
  BOOST_CHECK(*it == zeros);
  BOOST_CHECK(!tree.empty());
  BOOST_CHECK(tree.begin() != tree.end());
  BOOST_CHECK_EQUAL(tree.size(), 1);
  BOOST_CHECK(zeros == *tree.begin());
  BOOST_CHECK(++tree.begin() == tree.end());
  BOOST_CHECK(tree.begin() == --tree.end());
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_growing )
{
  tight_pointset_fix<int2> fix(100, increase());
  // because the tree is ordered on all dimensions and nodes are all sequential
  // values, iteration should be ordered as well.
  int i = 0;
  for (tight_pointset_fix<int2>::container_type::iterator it
         = fix.container.begin(); it != fix.container.end(); ++it, ++i)
    {
      BOOST_CHECK_EQUAL((*it)[0], i);
      BOOST_CHECK_EQUAL((*it)[1], i);
    }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_same )
{
  perfect_pointset_fix<int2> fix(100, increase());
  // because the tree is ordered on all dimensions and nodes are all sequential
  // values, iteration should be ordered as well.
  int i = 0;
  for (perfect_pointset_fix<int2>::container_type::iterator it
         = fix.container.begin(); it != fix.container.end(); ++it, ++i)
    {
      BOOST_CHECK_EQUAL((*it)[0], i);
      BOOST_CHECK_EQUAL((*it)[1], i);
    }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_reduce )
{
  pointset_fix<int2> fix(100, decrease());
  // because the tree is ordered on all dimensions and nodes are all sequential
  // values, iteration should be ordered as well.
  int i = 1;
  for (pointset_fix<int2>::container_type::iterator it
         = fix.container.begin(); it != fix.container.end(); ++it, ++i)
    {
      BOOST_CHECK_EQUAL((*it)[0], i);
      BOOST_CHECK_EQUAL((*it)[1], i);
    }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_insert_lots )
{
  // build repeatitively a lot of them, should not fail.
  // This tree has multiple similar node, by construction
  for (int i=0; i<100; ++i)
    {
      pointset_fix<int2> fix(100, randomize(-4, 4));
      int count = 0;
      for (pointset_fix<int2>::container_type::iterator it
             = fix.container.begin(); it != fix.container.end(); ++it)
        {
          if ((*it)[0] >= -4 && (*it)[0] < 4
              && (*it)[1] >= -4 && (*it)[1] < 4) ++count;
        }
      BOOST_CHECK_EQUAL(count, 100);
    }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_copy )
{
  // Copy a kdtree of quad and iterate over it. Both tree should have leaf nodes
  // at the same location
  runtime_pointset_fix<quad> fix(40, randomize(-10, 10));
  runtime_pointset_fix<quad>::container_type copy(fix.container);
  BOOST_CHECK_EQUAL(fix.container.size(), copy.size());
  typedef runtime_pointset_fix<quad>::container_type::iterator iterator_type;
  iterator_type orig_begin = fix.container.begin();
  iterator_type orig_end = fix.container.end();
  iterator_type copy_begin = copy.begin();
  iterator_type copy_end = copy.end();
  for (; orig_begin != orig_end && copy_begin != copy_end;
       ++copy_begin, ++orig_begin)
    {
      BOOST_CHECK(*orig_begin == *copy_begin);
      if (orig_begin.node->left == 0) BOOST_CHECK(copy_begin.node->left == 0);
      if (orig_begin.node->right == 0) BOOST_CHECK(copy_begin.node->right == 0);
    }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_assignment )
{
  // Copy an 3d kdtree and iterate over it. Both iterators should yield same
  // results and exhibit same properties.
  runtime_pointset_fix<quad> fix(40, randomize(-10, 10));
  runtime_pointset_fix<quad> copy(40, randomize(-10, 10));
  BOOST_CHECK_EQUAL(fix.container.size(), copy.container.size());
  copy.container = fix.container;
  typedef runtime_pointset_fix<quad>::container_type::iterator iterator_type;
  iterator_type orig_begin = fix.container.begin();
  iterator_type orig_end = fix.container.end();
  iterator_type copy_begin = copy.container.begin();
  iterator_type copy_end = copy.container.end();
  for (; orig_begin != orig_end && copy_begin != copy_end;
       ++copy_begin, ++orig_begin)
    {
      BOOST_CHECK(*orig_begin == *copy_begin);
      if (orig_begin.node->left == 0) BOOST_CHECK(copy_begin.node->left == 0);
      if (orig_begin.node->right == 0) BOOST_CHECK(copy_begin.node->right == 0);
    }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_bulk_insert )
{
  // reuse test_kdtree_insert_100_iterate_forward
  typedef details::Relaxed_kdtree
    <details::Static_rank<2>, int2, int2, bracket_less<int2>,
     loose_balancing, std::allocator<int2> > kdtree_type;
  kdtree_type kdtree;
  spatial::import::array<int2, 100> points;
  for(spatial::import::array<int2, 100>::iterator i
        = points.begin(); i != points.end(); ++i)
    {
      (*i)[0] = std::rand() % 20;
      (*i)[1] = std::rand() % 20;
    }
  BOOST_REQUIRE_NO_THROW(kdtree.insert(points.begin(), points.end()));
  BOOST_CHECK(kdtree.empty() == false);
  BOOST_REQUIRE_EQUAL(kdtree.size(), 100);
  BOOST_CHECK_EQUAL(kdtree.count(), 100);
  int count = 0;
  for(kdtree_type::iterator i = kdtree.begin(); i != kdtree.end(); ++i)
    {
      spatial::import::array<int2, 100>::iterator match;
      BOOST_REQUIRE((match = std::find(points.begin(), points.end(), *i))
                    != points.end());
      (*match)[0] = -1; // Prevent the same point from being found twice.
      (*match)[1] = -1;
      BOOST_REQUIRE_LE(++count, 100);
    }
  BOOST_CHECK_EQUAL(count, 100);
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_erase_key )
{
  {
    // Erase on empty tree should return 0.
    pointset_fix<int2> fix;
    int2 some_value(0, 0);
    size_type count = fix.container.erase(some_value);
    BOOST_CHECK_EQUAL(count, 0);
    BOOST_CHECK(fix.container.end() == fix.container.begin());
    BOOST_CHECK(fix.container.empty());
  }
  {
    // Erase one value of a tree should return 1 and leave an empty tree.
    tight_pointset_fix<int2> fix;
    int2 some_value(0, 0);
    fix.container.insert(some_value);
    BOOST_CHECK(!fix.container.empty());
    size_type count = fix.container.erase(some_value);
    BOOST_CHECK_EQUAL(count, 1);
    BOOST_CHECK(fix.container.end() == fix.container.begin());
    BOOST_CHECK(fix.container.empty());
  }
  {
    // Erase a value not in the tree should leave the tree untouched.
    runtime_pointset_fix<int2> fix;
    int2 some_value(0, 0);
    int2 other_value(1, 1);
    fix.container.insert(some_value);
    runtime_pointset_fix<int2>::container_type::iterator
      begin_before = fix.container.begin();
    runtime_pointset_fix<int2>::container_type::iterator
      end_before = fix.container.end();
    size_type count = fix.container.erase(other_value);
    BOOST_CHECK_EQUAL(count, 0);
    BOOST_CHECK(!fix.container.empty());
    BOOST_CHECK(fix.container.end() != fix.container.begin());
    BOOST_CHECK(fix.container.end() == end_before);
    BOOST_CHECK(fix.container.begin() == begin_before);
  }
  {
    // Should be able to erase multiple values
    typedef details::Relaxed_kdtree
      <details::Dynamic_rank, int2, int2, bracket_less<int2>,
       tight_balancing, std::allocator<int2> >
      kdtree_type;
    // 1D tree where we store 2d objects...
    kdtree_type tree(details::Dynamic_rank(1));
    int2 one(1, 0);
    int2 two(2, 2);
    int2 four(4, 0);
    tree.insert(one);
    tree.insert(two);
    tree.insert(two);
    tree.insert(four);
    // ... And equal should take the second dimension into account.
    BOOST_REQUIRE_EQUAL(tree.count(), 4);
    size_type count = tree.erase(two);
    BOOST_CHECK_EQUAL(count, 2);
    BOOST_REQUIRE_EQUAL(tree.count(), 2);
    BOOST_CHECK(tree.find(one) != tree.end());
    BOOST_CHECK(tree.find(four) != tree.end());
    BOOST_CHECK(tree.find(two) == tree.end());
    kdtree_type::iterator iter = tree.begin();
    BOOST_REQUIRE(iter != tree.end());
    BOOST_REQUIRE_NO_THROW(++iter);
    BOOST_REQUIRE(iter != tree.end());
    BOOST_REQUIRE_NO_THROW(++iter);
    BOOST_REQUIRE(iter == tree.end());
  }
}

BOOST_AUTO_TEST_CASE( test_relaxed_kdtree_erase_iterator )
{
  // check that erase at edge preserve basic iterators
  {
    point_multimap_fix<quad, std::string> fix(20, randomize(0, 1));
    typedef point_multimap_fix<quad, std::string>::container_type
      ::iterator iter_type;
    size_type track_size = fix.container.size();
    while (fix.container.size() != 0)
      {
        iter_type iter = fix.container.begin();
        BOOST_REQUIRE_NO_THROW(fix.container.erase(iter));
        BOOST_CHECK_EQUAL(fix.container.size(), --track_size);
        BOOST_CHECK(iter != fix.container.begin());
        int count = 0;
        for(iter_type i = fix.container.begin();
            i != fix.container.end(); ++i, ++count);
        BOOST_CHECK_EQUAL(count, track_size);
      }
  }
  {
    point_multimap_fix<quad, std::string> fix(20, randomize(0, 1));
    typedef point_multimap_fix<quad, std::string>::container_type
      ::iterator iter_type;
    typedef point_multimap_fix<quad, std::string>::container_type
      ::reverse_iterator riter_type;
    size_type track_size = fix.container.size();
    while (fix.container.size() != 0)
      {
        iter_type iter = --fix.container.end();
        BOOST_REQUIRE_NO_THROW(fix.container.erase(iter));
        BOOST_CHECK_EQUAL(fix.container.size(), --track_size);
        BOOST_CHECK(iter != (--fix.container.end()));
        int count = 0;
        for(riter_type i = fix.container.rbegin();
            i != fix.container.rend(); ++i, ++count);
        BOOST_CHECK_EQUAL(count, track_size);
      }
  }
  // erase all and check that total ordering is preserved.
  {
    typedef pointset_fix<double6>::container_type::iterator iterator;
    typedef ordered_iterator<pointset_fix<double6>::container_type>
      ordered_iterator;
    pointset_fix<double6> fix(100, randomize(0, 1));
    size_type track_size = fix.container.size();
    while (fix.container.size() != 0)
      {
        iterator eraser = fix.container.begin();
        std::advance(eraser, static_cast<ptrdiff_t>
                     (static_cast<size_t>(rand()) % fix.container.size()));
        ordered_iterator begin = ordered_begin(fix.container);
        ordered_iterator end = ordered_end(fix.container);
        size_type count = 0;
        for(ordered_iterator i = begin; i != end; ++i, ++count);
        BOOST_REQUIRE_EQUAL(count, track_size);
        count = 0;
        for(ordered_iterator i = end; i != begin; --i, ++count);
        BOOST_REQUIRE_EQUAL(count, track_size);
        BOOST_REQUIRE_NO_THROW(fix.container.erase(eraser));
        BOOST_CHECK_EQUAL(fix.container.size(), --track_size);
      }
  }
}

BOOST_AUTO_TEST_CASE (test_relaxed_kdtree_equal)
{
  {
    // These 2 trees should be equal (contents are equivalent)
    boxmap_fix<quad, std::string> one;
    one.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    boxmap_fix<quad, std::string> two;
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    BOOST_CHECK(one.container == two.container);
  }
  {
    // These 2 trees should be different.
    boxmap_fix<quad, std::string> one;
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    boxmap_fix<quad, std::string> two;
    two.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    BOOST_CHECK(one.container != two.container);
  }
}

BOOST_AUTO_TEST_CASE (test_relaxed_kdtree_lexicographic)
{
  {
    // These 2 trees should be equal (contents are equivalent)
    boxmap_fix<quad, std::string> one;
    one.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    boxmap_fix<quad, std::string> two;
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    BOOST_CHECK(!(one.container < two.container
                  || one.container > two.container));
  }
  {
    // These one is a "prefix" of two lexicographically
    boxmap_fix<quad, std::string> one;
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    one.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    boxmap_fix<quad, std::string> two;
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(1, 2, 1, 1), ""));
    two.container.insert(std::make_pair(quad(2, 2, 1, 1), ""));
    BOOST_CHECK(one.container < two.container);
  }
}

max_stars_repo_name: Roboauto/spatial

max_issues_repo_name: Roboauto/spatial

max_forks_repo_name: Roboauto/spatial


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */
#include <cmn/agent_cmn.h>

#include <boost/property_tree/xml_parser.hpp>
#include <db/db_graph.h>

#include <cmn/agent.h>
#include <cmn/agent_db.h>

#include <bgp_schema_types.h>

#include <cfg/cfg_init.h>
#include <cfg/cfg_filter.h>
#include <cfg/cfg_mirror.h>

#include <oper/vn.h>
#include <oper/sg.h>
#include <oper/vm.h>
#include <oper/vrf.h>
#include <oper/nexthop.h>
#include <oper/interface_common.h>
#include <oper/mirror_table.h>
#include <oper/route_common.h>
#include <oper/operdb_init.h>
#include <oper/global_vrouter.h>
#include <oper/service_instance.h>
#include <oper/physical_device.h>

#include <vgw/cfg_vgw.h>
#include <vgw/vgw.h>
#include <filter/acl.h>

using namespace std;
using namespace autogen;
using namespace boost::property_tree;
using namespace boost::uuids;
using boost::optional;

void IFMapAgentSandeshInit(DB *, IFMapAgentParser *);

SandeshTraceBufferPtr CfgTraceBuf(SandeshTraceBufferCreate("Config", 2000));

AgentConfig::AgentConfig(Agent *agent)
        : agent_(agent) {
    cfg_filter_ = std::auto_ptr<CfgFilter>(new CfgFilter(this));

    cfg_graph_ = std::auto_ptr<DBGraph>(new DBGraph());
    cfg_mirror_table_ = std::auto_ptr<MirrorCfgTable>(new MirrorCfgTable(this));
    agent_->set_mirror_cfg_table(cfg_mirror_table_.get());

    cfg_intf_mirror_table_ = std::auto_ptr<IntfMirrorCfgTable>
       (new IntfMirrorCfgTable(this));
    agent_->set_interface_mirror_cfg_table(cfg_intf_mirror_table_.get());
}

AgentConfig::~AgentConfig() {
    cfg_filter_.reset();
    cfg_parser_.reset();
    cfg_graph_.reset();
    cfg_mirror_table_.reset();
    cfg_intf_mirror_table_.reset();
}

void AgentConfig::CreateDBTables(DB *db) {
    // Create parser once we know the db
    cfg_parser_ = std::auto_ptr<IFMapAgentParser>(new IFMapAgentParser(db));
    vnc_cfg_Agent_ModuleInit(db, cfg_graph_.get());
    vnc_cfg_Agent_ParserInit(db, cfg_parser_.get());
    bgp_schema_Agent_ModuleInit(db, cfg_graph_.get());
    bgp_schema_Agent_ParserInit(db, cfg_parser_.get());
    IFMapAgentLinkTable_Init(db, cfg_graph_.get());
    agent_->set_ifmap_parser(cfg_parser_.get());
    IFMapAgentStaleCleaner *cl =
        new IFMapAgentStaleCleaner(db, cfg_graph_.get());
    agent_->set_ifmap_stale_cleaner(cl);

    IFMapAgentSandeshInit(db, cfg_parser_.get());
}

void AgentConfig::Register(const char *node_name, AgentDBTable *table,
                           int need_property_id) {
}

void AgentConfig::RegisterDBClients(DB *db) {

    cfg_vm_interface_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "virtual-machine-interface")));
    assert(cfg_vm_interface_table_);

    cfg_acl_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "access-control-list")));
    assert(cfg_acl_table_);

    cfg_vm_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "virtual-machine")));
    assert(cfg_vm_table_);

    cfg_vn_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "virtual-network")));
    assert(cfg_vn_table_);

    cfg_sg_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "security-group")));
    assert(cfg_sg_table_);

    cfg_vrf_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "routing-instance")));
    assert(cfg_vrf_table_);

    cfg_instanceip_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "instance-ip")));
    assert(cfg_instanceip_table_);

    cfg_floatingip_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "floating-ip")));
    assert(cfg_floatingip_table_);

    cfg_aliasip_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "alias-ip")));
    assert(cfg_aliasip_table_);

    cfg_floatingip_pool_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "floating-ip-pool")));
    assert(cfg_floatingip_pool_table_);

    cfg_aliasip_pool_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "alias-ip-pool")));
    assert(cfg_aliasip_pool_table_);

    cfg_network_ipam_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(), "network-ipam")));
    assert(cfg_network_ipam_table_);

    cfg_vn_network_ipam_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(),
                               "virtual-network-network-ipam")));
    assert(cfg_vn_network_ipam_table_);

    cfg_vm_port_vrf_table_ = (static_cast<IFMapAgentTable *>
        (IFMapTable::FindTable(agent_->db(),
                               "virtual-machine-interface-routing-instance")));
    assert(cfg_vm_port_vrf_table_);

    cfg_route_table_ = (static_cast<IFMapAgentTable *>
         (IFMapTable::FindTable(agent_->db(),
                               "interface-route-table")));
    assert(cfg_route_table_);

    cfg_service_instance_table_ = (static_cast<IFMapAgentTable *>
         (IFMapTable::FindTable(agent_->db(),
                               "service_instance")));
    assert(cfg_service_instance_table_);

    cfg_service_template_table_ = (static_cast<IFMapAgentTable *>
         (IFMapTable::FindTable(agent_->db(),
                               "service-template")));
    assert(cfg_service_template_table_);

    cfg_security_group_table_ = (static_cast<IFMapAgentTable *>
         (IFMapTable::FindTable(agent_->db(),
                               "security_group")));
    assert(cfg_security_group_table_);

    cfg_subnet_table_ = (static_cast<IFMapAgentTable *>
                    (IFMapTable::FindTable(agent_->db(),
                      "subnet")));
    assert(cfg_route_table_);

    cfg_logical_port_table_ = (static_cast<IFMapAgentTable *>
                                (IFMapTable::FindTable(agent_->db(),
                                                       "logical-interface")));
    assert(cfg_logical_port_table_);

    cfg_physical_device_table_ = (static_cast<IFMapAgentTable *>
                                (IFMapTable::FindTable(agent_->db(),
                                                       "physical-router")));
    assert(cfg_physical_device_table_);

    cfg_health_check_table_ = (static_cast<IFMapAgentTable *>
                                (IFMapTable::FindTable(agent_->db(),
                                                       "service-health-check")));
    assert(cfg_health_check_table_);

    cfg_qos_table_ = (static_cast<IFMapAgentTable *>
                      (IFMapTable::FindTable(agent_->db(),
                                             "qos-config")));
    assert(cfg_qos_table_);

    cfg_global_qos_table_ = (static_cast<IFMapAgentTable *>
                            (IFMapTable::FindTable(agent_->db(),
                                                   "global-qos-config")));
    assert(cfg_global_qos_table_);

    cfg_qos_queue_table_ = (static_cast<IFMapAgentTable *>
                            (IFMapTable::FindTable(agent_->db(),
                                                   "qos-queue")));
    assert(cfg_qos_queue_table_);

    cfg_forwarding_class_table_ = (static_cast<IFMapAgentTable *>
                            (IFMapTable::FindTable(agent_->db(),
                                                   "forwarding-class")));
    assert(cfg_forwarding_class_table_);

    cfg_bridge_domain_table_ = (static_cast<IFMapAgentTable *>
                               (IFMapTable::FindTable(agent_->db(),
                                                      "bridge-domain")));
    assert(cfg_bridge_domain_table_);

    cfg_vm_port_bridge_domain_table_ = (static_cast<IFMapAgentTable *>
                             (IFMapTable::FindTable(agent_->db(),
                                   "virtual-machine-interface-bridge-domain")));
    assert(cfg_vm_port_bridge_domain_table_);

    cfg_policy_set_table_ = (static_cast<IFMapAgentTable *>
                            (IFMapTable::FindTable(agent_->db(),
                                                   "application-policy-set")));
    assert(cfg_policy_set_table_);

    cfg_firewall_policy_table_ = (static_cast<IFMapAgentTable *>
                                 (IFMapTable::FindTable(agent_->db(),
                                                        "firewall-policy")));
    assert(cfg_firewall_policy_table_);

    cfg_firewall_rule_table_ = (static_cast<IFMapAgentTable *>
                               (IFMapTable::FindTable(agent_->db(),
                                                      "firewall-rule")));
    assert(cfg_firewall_rule_table_);

    cfg_service_group_table_ = (static_cast<IFMapAgentTable *>
                               (IFMapTable::FindTable(agent_->db(),
                                                      "service-group")));
    assert(cfg_service_group_table_);

    cfg_address_group_table_ = (static_cast<IFMapAgentTable *>
                               (IFMapTable::FindTable(agent_->db(),
                                                      "address-group")));
    assert(cfg_address_group_table_);

    cfg_firewall_policy_firewall_rule_table_ =
        (static_cast<IFMapAgentTable *>(IFMapTable::FindTable(agent_->db(),
                                        "firewall-policy-firewall-rule")));
    assert(cfg_firewall_policy_firewall_rule_table_);

    cfg_tag_table_ =
        (static_cast<IFMapAgentTable *>(IFMapTable::FindTable(agent_->db(),
                                                              "tag")));
    assert(cfg_tag_table_);

    cfg_policy_set_firewall_policy_table_ =
        (static_cast<IFMapAgentTable *>(IFMapTable::FindTable(agent_->db(),
                                  "application-policy-set-firewall-policy")));
    assert(cfg_policy_set_firewall_policy_table_);

    cfg_policy_management_table_ = (static_cast<IFMapAgentTable *>(
                IFMapTable::FindTable(agent_->db(), "policy-management")));
    assert(cfg_policy_management_table_);

    cfg_project_table_ =
        (static_cast<IFMapAgentTable *>(IFMapTable::FindTable(agent_->db(),
                                                              "project")));
    assert(cfg_project_table_);

    cfg_slo_table_ = (static_cast<IFMapAgentTable *>
                            (IFMapTable::FindTable(agent_->db(),
                                                   "security-logging-object")));
    assert(cfg_slo_table_);

    cfg_port_tuple_table_ = (static_cast<IFMapAgentTable *>
                            (IFMapTable::FindTable(agent_->db(),
                                                   "port-tuple")));
    assert(cfg_port_tuple_table_);
}

void AgentConfig::Init() {
    cfg_filter_->Init();
    cfg_mirror_table_->Init();
    cfg_intf_mirror_table_->Init();
}

void AgentConfig::InitDone() {
}

void AgentConfig::Shutdown() {
    cfg_filter_->Shutdown();

    cfg_mirror_table_->Shutdown();
    cfg_intf_mirror_table_->Shutdown();

    agent_->set_ifmap_parser(NULL);

    agent_->ifmap_stale_cleaner()->Clear();
    delete agent_->ifmap_stale_cleaner();
    agent_->set_ifmap_stale_cleaner(NULL);
}

ext: cc

max_stars_repo_name: kaweue/contrail-controller

max_issues_repo_name: kaweue/contrail-controller

max_forks_repo_name: kaweue/contrail-controller


text:
/*! \file
    \brief A storage.

    Copyright (C) 2019-2022 kaoru  https://www.tetengo.org/
*/

#include <any>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <functional>
#include <limits>
#include <memory>
#include <stdexcept>
#include <utility>
#include <vector>

#include <stdint.h>

#include <boost/interprocess/exceptions.hpp>
#include <boost/interprocess/file_mapping.hpp>

#include <tetengo/trie/double_array.hpp>
#include <tetengo/trie/memory_storage.hpp>
#include <tetengo/trie/mmap_storage.hpp>
#include <tetengo/trie/shared_storage.hpp>
#include <tetengo/trie/storage.h>
#include <tetengo/trie/storage.hpp>
#include <tetengo/trie/trie.hpp>
#include <tetengo/trie/value_serializer.hpp>

#include "tetengo_trie_storage.hpp"
#include "tetengo_trie_trie.hpp"

uint8_t tetengo_trie_storage_vacantCheckValue()
{
    return tetengo::trie::double_array::vacant_check_value();
}

tetengo_trie_storage_t* tetengo_trie_storage_createStorage(const tetengo_trie_trie_t* const p_trie)
{
    try
    {
        if (!p_trie)
        {
            throw std::invalid_argument{ "p_trie is NULL." };
        }

        auto p_instance = std::make_unique<tetengo_trie_storage_t>(&p_trie->p_cpp_trie->get_storage());
        return p_instance.release();
    }
    catch (...)
    {
        return nullptr;
    }
}

tetengo_trie_storage_t* tetengo_trie_storage_createMemoryStorage(const path_character_type* const path)
{
    try
    {
        if (!path)
        {
            throw std::invalid_argument{ "path is NULL." };
        }

        std::ifstream                           stream{ path, std::ios_base::binary };
        const tetengo::trie::value_deserializer deserializer{ [](const std::vector<char>& serialized) {
            return serialized;
        } };
        auto p_storage = std::make_unique<tetengo::trie::memory_storage>(stream, deserializer);
        auto p_instance = std::make_unique<tetengo_trie_storage_t>(std::move(p_storage));
        return p_instance.release();
    }
    catch (...)
    {
        return nullptr;
    }
}

tetengo_trie_storage_t* tetengo_trie_storage_createSharedStorage(const path_character_type* const path)
{
    try
    {
        if (!path)
        {
            throw std::invalid_argument{ "path is NULL." };
        }

        std::ifstream                           stream{ path, std::ios_base::binary };
        const tetengo::trie::value_deserializer deserializer{ [](const std::vector<char>& serialized) {
            return serialized;
        } };
        auto p_storage = std::make_unique<tetengo::trie::shared_storage>(stream, deserializer);
        auto p_instance = std::make_unique<tetengo_trie_storage_t>(std::move(p_storage));
        return p_instance.release();
    }
    catch (...)
    {
        return nullptr;
    }
}

namespace
{
    std::unique_ptr<boost::interprocess::file_mapping> create_file_mapping(const path_character_type* const path)
    {
        try
        {
            return std::make_unique<boost::interprocess::file_mapping>(path, boost::interprocess::read_only);
        }
        catch (const boost::interprocess::interprocess_exception&)
        {
            return nullptr;
        }
    }

}

tetengo_trie_storage_t*
tetengo_trie_storage_createMmapStorage(const path_character_type* const path, const size_t content_offset)
{
    try
    {
        if (!path)
        {
            throw std::invalid_argument{ "path is NULL." };
        }

        auto                              p_file_mapping = create_file_mapping(path);
        const auto                        file_size = static_cast<std::size_t>(std::filesystem::file_size(path));
        tetengo::trie::value_deserializer deserializer{ [](const std::vector<char>& serialized) {
            return serialized;
        } };
        auto p_storage = std::make_unique<tetengo::trie::mmap_storage>(
            *p_file_mapping, content_offset, file_size, std::move(deserializer));
        auto p_instance = std::make_unique<tetengo_trie_storage_t>(std::move(p_file_mapping), std::move(p_storage));
        return p_instance.release();
    }
    catch (...)
    {
        return nullptr;
    }
}

void tetengo_trie_storage_destroy(const tetengo_trie_storage_t* const p_storage)
{
    try
    {
        const std::unique_ptr<const tetengo_trie_storage_t> p_instance{ p_storage };
    }
    catch (...)
    {}
}

size_t tetengo_trie_storage_baseCheckSize(const tetengo_trie_storage_t* const p_storage)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        return p_storage->p_cpp_storage()->base_check_size();
    }
    catch (...)
    {
        return static_cast<size_t>(-1);
    }
}

int32_t tetengo_trie_storage_baseAt(const tetengo_trie_storage_t* const p_storage, const size_t base_check_index)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        return p_storage->p_cpp_storage()->base_at(base_check_index);
    }
    catch (...)
    {
        return INT32_MAX;
    }
}

bool tetengo_trie_storage_setBaseAt(
    tetengo_trie_storage_t* const p_storage,
    const size_t                  base_check_index,
    const int32_t                 base)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        p_storage->p_cpp_storage()->set_base_at(base_check_index, base);

        return true;
    }
    catch (...)
    {
        return false;
    }
}

uint8_t tetengo_trie_storage_checkAt(const tetengo_trie_storage_t* const p_storage, const size_t base_check_index)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        return p_storage->p_cpp_storage()->check_at(base_check_index);
    }
    catch (...)
    {
        return UINT8_MAX;
    }
}

bool tetengo_trie_storage_setCheckAt(
    tetengo_trie_storage_t* const p_storage,
    const size_t                  base_check_index,
    const uint8_t                 check)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        p_storage->p_cpp_storage()->set_check_at(base_check_index, check);

        return true;
    }
    catch (...)
    {
        return false;
    }
}

size_t tetengo_trie_storage_valueCount(const tetengo_trie_storage_t* const p_storage)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        return p_storage->p_cpp_storage()->value_count();
    }
    catch (...)
    {
        return static_cast<size_t>(-1);
    }
}

const void* tetengo_trie_storage_valueAt(const tetengo_trie_storage_t* const p_storage, const size_t value_index)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        const auto* const cpp_value = p_storage->p_cpp_storage()->value_at(value_index);
        if (!cpp_value)
        {
            return NULL;
        }
        return std::any_cast<std::vector<char>>(cpp_value);
    }
    catch (...)
    {
        return NULL;
    }
}

bool tetengo_trie_storage_addValueAt(
    tetengo_trie_storage_t* const p_storage,
    const size_t                  value_index,
    const void* const             p_value,
    const size_t                  value_size)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }
        if (!p_value)
        {
            throw std::invalid_argument{ "p_value is NULL." };
        }

        auto value_bytes = std::make_any<std::vector<char>>(
            static_cast<const char*>(p_value), static_cast<const char*>(p_value) + value_size);
        p_storage->p_cpp_storage()->add_value_at(value_index, std::move(value_bytes));

        return true;
    }
    catch (...)
    {
        return false;
    }
}

double tetengo_trie_storage_fillingRate(const tetengo_trie_storage_t* const p_storage)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }

        return p_storage->p_cpp_storage()->filling_rate();
    }
    catch (...)
    {
        return std::numeric_limits<double>::signaling_NaN();
    }
}

bool tetengo_trie_storage_serialize(
    const tetengo_trie_storage_t* const p_storage,
    const path_character_type* const    path,
    const size_t                        fixed_value_size)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }
        if (!path)
        {
            throw std::invalid_argument{ "path is NULL." };
        }

        std::ofstream                         stream{ path, std::ios_base::binary };
        const tetengo::trie::value_serializer serializer{
            [](const std::any& value) { return *std::any_cast<std::vector<char>>(&value); }, fixed_value_size
        };
        p_storage->p_cpp_storage()->serialize(stream, serializer);

        return true;
    }
    catch (...)
    {
        return false;
    }
}

tetengo_trie_storage_t* tetengo_trie_storage_clone(const tetengo_trie_storage_t* const p_storage)
{
    try
    {
        if (!p_storage)
        {
            throw std::invalid_argument{ "p_storage is NULL." };
        }
        auto p_clone = p_storage->p_cpp_storage()->clone();

        auto p_instance = std::make_unique<tetengo_trie_storage_t>(std::move(p_clone));
        return p_instance.release();
    }
    catch (...)
    {
        return nullptr;
    }
}

max_stars_repo_name: tetengo/tetengo

max_issues_repo_name: tetengo/tetengo

max_forks_repo_name: tetengo/tetengo


text:
#define BOOST_TEST_MODULE Gpufit

#include "Gpufit/gpufit.h"

#include <boost/test/included/unit_test.hpp>

#include <array>

// TODO this doesn't fail anymore as expected, we do not really throw an error anymore and therefore cannot reliably check for an error

BOOST_AUTO_TEST_CASE( Error_Handling )
{
    std::size_t const n_fits{ 1 } ;
    std::size_t const n_points{ 2 } ;
    std::array< REAL, n_points > data{ { 0, 1 } } ;
    std::array< REAL, n_points > weights{ { 1, 1 } } ;
    std::array< REAL, 2 > initial_parameters{ { 0, 0 } } ;
    REAL tolerance{ 0.001f } ;
    int max_n_iterations{ 10 } ;
    std::array< int, 2 > parameters_to_fit{ { 0, 0 } } ;
    std::array< int, 2 > user_info{ { 0, 1 } } ;
    std::array< REAL, 2 > output_parameters ;
    int output_states ;
    REAL output_chi_square ;
    int output_n_iterations ;

    int const status
            = gpufit
            (
                n_fits,
                n_points,
                data.data(),
                weights.data(),
                LINEAR_1D,
                initial_parameters.data(),
                tolerance,
                max_n_iterations,
                parameters_to_fit.data(),
                LSE,
                n_points * sizeof( int ),
                reinterpret_cast< char * >( user_info.data() ),
                output_parameters.data(),
                & output_states,
                & output_chi_square,
                & output_n_iterations
            ) ;

    BOOST_CHECK( status == - 1 ) ;

    std::string const error = gpufit_get_last_error() ;

    BOOST_CHECK( error == "invalid configuration argument" ) ;
}


text:
//
// Created by samarth on 2/28/19.
//

#ifndef DART_REMAP_HAND_HPP
#define DART_REMAP_HAND_HPP

#include <pangolin/pangolin.h>
#include <pangolin/gl/glcuda.h>

#include <atomic>
#include <string>
#include <thread>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <boost/filesystem.hpp>

// DART includes
#include "tracker_no_obs.h"
#include "util/gl_dart.h"
#include "optimization/priors.h"

class HandMapper {
 public:
  HandMapper(const std::string &src_model_filename,
      const std::string &dst_model_filename,
      bool graspit=false,
      const std::string &data_dir=std::string("grasps"));

  ~HandMapper() {
    if (!pango_thread) return;
    if (pango_thread->joinable()) pango_thread->join();
  }

  void show_axes(bool show) { _show_axes = show; }
  void close() { pangolin::Quit(); }

  // set the pose of the src hand from a file
  void set_src_pose(const std::string &pose_filename);
  // map the src pose to dst pose
  float do_mapping();
  // save result
  void save_result(const std::string &src_filename);

  void set_max_iterations(int m);
  void set_attract_weight(float w);
  void set_attract_dist_cm(float d);
  void set_inter_model_intersection(float w);
  void set_intra_model_intersection(float w);
  void set_lm_damping(float w);
  void set_log10_regularization(float w);
  void set_params(float aw, float ad, float iw, float lmd, float reg) {
    set_attract_weight(aw);
    set_attract_dist_cm(ad);
    set_inter_model_intersection(iw);
    set_intra_model_intersection(iw);
    set_lm_damping(lmd);
    set_log10_regularization(reg);
  }

 private:
  std::string src_model_filename, dst_model_filename;

  // pangolin variables
  bool _iterate, _init, _show_axes, _calc_error, _save_result, _reset_joints,
      _show_priors, _show_src_hand, _show_dst_hand, _show_object;
  bool graspit;
  bool quit_pangolin_loop;
  int _max_iterations;
  float _attract_weight;
  float _inter_model_intersection, _intra_model_intersection;
  float _lm_damping, _log10_regularization;
  std::shared_ptr<std::thread> pango_thread;

  // holds the dof values of the src hand
  std::vector<pangolin::Var<float> > sliders;

  std::shared_ptr<dart::TrackerNoObs> tracker;
  int src_hand_id, dst_hand_id;
  std::mutex tracker_mutex;
  std::condition_variable tracker_cv;
  bool tracker_ready;
  bool analyze_from_pango_thread;
  std::vector<int> graspit2dartdofs;

  std::vector<std::shared_ptr<dart::Point3D3DPrior> > priors;
  size_t n_priors;

  boost::filesystem::path data_dir, src_hand_model_filename,
      dst_hand_model_filename;

  // pose of dst w.r.t. src
  dart::SE3 T_s_d;

  void pangolin_loop();
  void create_pangolin_vars_callbacks();
  void create_tracker();
  void create_priors();
  void show_3d_3d_prior(const std::shared_ptr<dart::Point3D3DPrior> &p,
      float size=10.f);
  float3 frame_point_in_camera(const float3 &frame_pt, int frame_id);
};

#endif //DART_REMAP_HAND_HPP

max_stars_repo_name: contactgrasp/dart

max_issues_repo_name: contactgrasp/dart

max_forks_repo_name: contactgrasp/dart


text:
#include "CharacterSet.h"

#include <boost/assign/list_of.hpp>
#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>

namespace opendnp3 {

    template <typename Enumeration>
    constexpr auto EnumAsInt(const Enumeration value)
        -> typename std::underlying_type<Enumeration>::type
    {
        static_assert(std::is_enum<Enumeration>::value, "EnumAsInt(): argument should be type of: enum or enum class");
        return static_cast<typename std::underlying_type<Enumeration>::type>(value);
    }

    using Relation_t = boost::bimap<
        boost::bimaps::unordered_set_of<std::string>,
        boost::bimaps::unordered_set_of<CharacterSet>
    >;

    static const Relation_t Relation = boost::assign::list_of<Relation_t::relation>
        ("UTF8", CharacterSet::UTF8)
        ("CP1251", CharacterSet::CP1251)
    ;

    CharacterSet FromString(const std::string& value, CharacterSet defaultValue) {
        const auto it = Relation.left.find(value);
        return it != Relation.left.end() ? it->second : defaultValue;
    }

    std::string ToString(CharacterSet value) {
        const auto it = Relation.right.find(value);
        if (it != Relation.right.end()) {
            return it->second;
        }
        return std::to_string(EnumAsInt(value));
    }

    std::ostream& operator<<(std::ostream& out, CharacterSet rhs) {
        out << ToString(rhs);
        return out;
    }

}


text:
#pragma once

#include <iostream>
#include <memory>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>

#include <boost/algorithm/string.hpp>
#include <range/v3/view/enumerate.hpp>
#include <spdlog/spdlog.h>
#include "index_types.hpp"
#include "query/queries.hpp"
#include "term_processor.hpp"
#include "tokenizer.hpp"
#include "topk_queue.hpp"
#include "util/util.hpp"
#include "wand_data.hpp"
#include "wand_data_compressed.hpp"
#include "wand_data_raw.hpp"

namespace pisa {

using term_id_type = uint32_t;
using term_id_vec = std::vector<term_id_type>;

struct Query {
    std::optional<std::string> id;
    std::vector<term_id_type> terms;
    std::vector<float> term_weights;
};

[[nodiscard]] auto split_query_at_colon(std::string const &query_string)
    -> std::pair<std::optional<std::string>, std::string_view>
{
    // query id : terms (or ids)
    auto colon = std::find(query_string.begin(), query_string.end(), ':');
    std::optional<std::string> id;
    if (colon != query_string.end()) {
        id = std::string(query_string.begin(), colon);
    }
    auto pos = colon == query_string.end() ? query_string.begin() : std::next(colon);
    auto raw_query = std::string_view(&*pos, std::distance(pos, query_string.end()));
    return {std::move(id), std::move(raw_query)};
}

[[nodiscard]] auto parse_query_terms(std::string const &query_string, TermProcessor term_processor)
    -> Query
{
    auto [id, raw_query] = split_query_at_colon(query_string);
    TermTokenizer tokenizer(raw_query);
    std::vector<term_id_type> parsed_query;
    for (auto term_iter = tokenizer.begin(); term_iter != tokenizer.end(); ++term_iter) {
        auto raw_term = *term_iter;
        auto term = term_processor(raw_term);
        if (term) {
            if (!term_processor.is_stopword(*term)) {
                parsed_query.push_back(std::move(*term));
            } else {
                spdlog::warn("Term `{}` is a stopword and will be ignored", raw_term);
            }
        } else {
            spdlog::warn("Term `{}` not found and will be ignored", raw_term);
        }
    }
    return {std::move(id), std::move(parsed_query), {}};
}

[[nodiscard]] auto parse_query_ids(std::string const &query_string) -> Query
{
    auto [id, raw_query] = split_query_at_colon(query_string);
    std::vector<term_id_type> parsed_query;
    std::vector<std::string> term_ids;
    boost::split(term_ids, raw_query, boost::is_any_of("\t, ,\v,\f,\r,\n"));

    auto is_empty = [](const std::string &val) { return val.empty(); };
    // remove_if move matching elements to the end, preparing them for erase.
    term_ids.erase(std::remove_if(term_ids.begin(), term_ids.end(), is_empty), term_ids.end());

    try {
        auto to_int = [](const std::string &val) { return std::stoi(val); };
        std::transform(term_ids.begin(), term_ids.end(), std::back_inserter(parsed_query), to_int);
    } catch (std::invalid_argument &err) {
        spdlog::error("Could not parse term identifiers of query `{}`", raw_query);
        exit(1);
    }
    return {std::move(id), std::move(parsed_query), {}};
}

[[nodiscard]] std::function<void(const std::string)> resolve_query_parser(
    std::vector<Query> &queries,
    std::optional<std::string> const &terms_file,
    std::optional<std::string> const &stopwords_filename,
    std::optional<std::string> const &stemmer_type)
{
    if (terms_file) {
        auto term_processor = TermProcessor(terms_file, stopwords_filename, stemmer_type);
        return [&queries, term_processor = std::move(term_processor)](
                   std::string const &query_line) {
            queries.push_back(parse_query_terms(query_line, term_processor));
        };
    } else {
        return [&queries](std::string const &query_line) {
            queries.push_back(parse_query_ids(query_line));
        };
    }
}

bool read_query(term_id_vec &ret, std::istream &is = std::cin)
{
    ret.clear();
    std::string line;
    if (!std::getline(is, line)) {
        return false;
    }
    ret = parse_query_ids(line).terms;
    return true;
}

void remove_duplicate_terms(term_id_vec &terms)
{
    std::sort(terms.begin(), terms.end());
    terms.erase(std::unique(terms.begin(), terms.end()), terms.end());
}

typedef std::pair<uint64_t, uint64_t> term_freq_pair;
typedef std::vector<term_freq_pair> term_freq_vec;

term_freq_vec query_freqs(term_id_vec terms)
{
    term_freq_vec query_term_freqs;
    std::sort(terms.begin(), terms.end());
    // count query term frequencies
    for (size_t i = 0; i < terms.size(); ++i) {
        if (i == 0 || terms[i] != terms[i - 1]) {
            query_term_freqs.emplace_back(terms[i], 1);
        } else {
            query_term_freqs.back().second += 1;
        }
    }
    return query_term_freqs;
}

using multi_query = std::vector<Query>;
// Consume a vector of queries, and convert to multi-queries
std::vector<multi_query> generate_multi_queries (std::vector<Query> queries)
{
    std::vector<multi_query> multi_queries;

    std::map<std::string, multi_query> mapped_queries;
    for (auto &q : queries) {
        std::string id = q.id.value_or("");
        if (id == "") {
            spdlog::error("Error: Multi Queries must have IDs");
            exit(1);
        }
        remove_duplicate_terms(q.terms); // Ensure queries are unique terms only
        mapped_queries[id].push_back(q);
    }

    for (const auto &elem : mapped_queries)
        multi_queries.push_back(elem.second);

    spdlog::info("Read {} multi queries.", multi_queries.size());
    return multi_queries;

}

// Convert a multi-query into the SP-CS format
std::vector<Query> multi_query_to_spcs (std::vector<multi_query> queries)
{
    std::vector<Query> spcs_queries;

    std::map<std::string, Query> q_map;
    size_t count = 0;
    for (const auto & multi : queries) {
        for (const auto & query : multi) {
            ++count;
            std::string id = query.id.value_or("");
            if (id == "") {
                spdlog::error("Error: Multi Queries must have IDs");
                exit(1);
            }
            q_map[id].id = id;
            for (const auto & term : query.terms) {
                q_map[id].terms.push_back(term);
            }
        }
    }

    for (const auto &elem : q_map) {
      spcs_queries.push_back(elem.second);
    }

    spdlog::info("Converted {} queries into {} SP-CS queries.", count, spcs_queries.size());
    return spcs_queries;
}

} // namespace pisa

#include "algorithm/and_query.hpp"
#include "algorithm/block_max_maxscore_query.hpp"
#include "algorithm/block_max_ranked_and_query.hpp"
#include "algorithm/block_max_wand_query.hpp"
#include "algorithm/maxscore_query.hpp"
#include "algorithm/or_query.hpp"
#include "algorithm/range_query.hpp"
#include "algorithm/range_taat_query.hpp"
#include "algorithm/ranked_and_query.hpp"
#include "algorithm/ranked_or_query.hpp"
#include "algorithm/ranked_or_taat_query.hpp"
#include "algorithm/wand_query.hpp"

max_stars_repo_name: JMMackenzie/pisa-multi-query

max_issues_repo_name: JMMackenzie/pisa-multi-query

max_forks_repo_name: JMMackenzie/pisa-multi-query


text: #include <boost/fusion/include/insert_range.hpp>