<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/scenarios/side_pass/side_pass_stage.h"

#include <algorithm>
#include <vector>

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/speed_profile_generator.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {

using apollo::common::TrajectoryPoint;

constexpr double kExtraMarginforStopOnWaitPointStage = 3.0;

/*
 * @brief:
 * STAGE: SidePassApproachObstacle
 */
Stage::StageStatus SidePassApproachObstacle::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);
  if (!plan_ok) {
    AERROR << "Stage " << Name() << " error: "
           << "planning on reference line failed.";
    return Stage::ERROR;
  }
  const ReferenceLineInfo& reference_line_info =
      frame->reference_line_info().front();
  double adc_velocity = frame->vehicle_state().linear_velocity();
  double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
  const PathDecision& path_decision = reference_line_info.path_decision();

  double front_obstacle_distance = 1000;
  for (const auto* obstacle : path_decision.obstacles().Items()) {
    if (obstacle->IsVirtual()) {
      continue;
    }

    bool is_on_road = reference_line_info.reference_line().HasOverlap(
        obstacle->PerceptionBoundingBox());
    if (!is_on_road) {
      continue;
    }

    const auto& obstacle_sl = obstacle->PerceptionSLBoundary();
    if (obstacle_sl.end_s() <= reference_line_info.AdcSlBoundary().start_s()) {
      continue;
    }

    double distance = obstacle_sl.start_s() - adc_front_edge_s;
    if (distance < front_obstacle_distance) {
      front_obstacle_distance = distance;
    }
  }

  if ((front_obstacle_distance) < 0) {
    AERROR << "Stage " << Name() << " error: "
           << "front obstacle has wrong position.";
    return Stage::ERROR;
  }
  // TODO(all): stage params need to be in config file
  double max_stop_velocity = 1.0e-5;
  double min_stop_obstacle_distance = 4.0;

  if (adc_velocity < max_stop_velocity &&
      front_obstacle_distance > min_stop_obstacle_distance) {
    next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH;
    return Stage::FINISHED;
  }
  return Stage::RUNNING;
}

/*
 * @brief:
 * STAGE: SidePassGeneratePath
 */
Stage::StageStatus SidePassGeneratePath::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  if (PlanningOnReferenceLine(planning_start_point, frame)) {
    GetContext()->path_data_ = frame->reference_line_info().front().path_data();
    if (GetContext()->path_data_.discretized_path().Length() > 0.0) {
      next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT;
      return Stage::FINISHED;
    } else {
      return Stage::RUNNING;
    }
  }
  return Stage::ERROR;
}

/*
 * @brief:
 * STAGE: SidePassDetectSafety
 */

Stage::StageStatus SidePassDetectSafety::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  const auto& reference_line_info = frame->reference_line_info().front();
  bool update_success = GetContext()->path_data_.UpdateFrenetFramePath(
      &reference_line_info.reference_line());
  if (!update_success) {
    AERROR << "Fail to update path_data.";
    return Stage::ERROR;
  }

  const auto adc_frenet_frame_point_ =
      reference_line_info.reference_line().GetFrenetPoint(
          frame->PlanningStartPoint());

  bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(
      adc_frenet_frame_point_.s(), adc_frenet_frame_point_.l());
  if (!trim_success) {
    AERROR << "Fail to trim path_data. adc_frenet_frame_point: "
           << adc_frenet_frame_point_.ShortDebugString();
    return Stage::ERROR;
  }

  auto& rfl_info = frame->mutable_reference_line_info()->front();
  *(rfl_info.mutable_path_data()) = GetContext()->path_data_;

  const auto& path_points =
      rfl_info.path_data().discretized_path().path_points();
  auto* debug_path =
      rfl_info.mutable_debug()->mutable_planning_data()->add_path();

  debug_path->set_name("DpPolyPathOptimizer");
  debug_path->mutable_path_point()->CopyFrom(
      {path_points.begin(), path_points.end()});

  if (!PlanningOnReferenceLine(planning_start_point, frame)) {
    return Stage::ERROR;
  }
  bool is_safe = true;
  double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();

  const PathDecision& path_decision =
      frame->reference_line_info().front().path_decision();
  for (const auto* obstacle : path_decision.obstacles().Items()) {
    // TODO(All): check according to neighbor lane.
    if (obstacle->IsVirtual() && obstacle->Id().substr(0, 3) == "SP_" &&
        obstacle->PerceptionSLBoundary().start_s() >= adc_front_edge_s) {
      is_safe = false;
      break;
    }
  }
  if (is_safe) {
    next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE;
    return Stage::FINISHED;
  }
  return Stage::RUNNING;
}

/*
 * @brief:
 * STAGE: SidePassPassObstacle
 */
Stage::StageStatus SidePassPassObstacle::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  const auto& reference_line_info = frame->reference_line_info().front();
  bool update_success = GetContext()->path_data_.UpdateFrenetFramePath(
      &reference_line_info.reference_line());
  if (!update_success) {
    AERROR << "Fail to update path_data.";
    return Stage::ERROR;
  }

  const auto adc_frenet_frame_point_ =
      reference_line_info.reference_line().GetFrenetPoint(
          frame->PlanningStartPoint());

  bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(
      adc_frenet_frame_point_.s(), adc_frenet_frame_point_.l());
  if (!trim_success) {
    AERROR << "Fail to trim path_data. adc_frenet_frame_point: "
           << adc_frenet_frame_point_.ShortDebugString();
    return Stage::ERROR;
  }

  auto& rfl_info = frame->mutable_reference_line_info()->front();
  *(rfl_info.mutable_path_data()) = GetContext()->path_data_;

  const auto& path_points =
      rfl_info.path_data().discretized_path().path_points();
  auto* debug_path =
      rfl_info.mutable_debug()->mutable_planning_data()->add_path();

  // TODO(All):
  // Have to use DpPolyPathOptimizer to show in dreamview. Need change to
  // correct name.
  debug_path->set_name("DpPolyPathOptimizer");
  debug_path->mutable_path_point()->CopyFrom(
      {path_points.begin(), path_points.end()});

  bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);
  if (!plan_ok) {
    AERROR << "Fail to plan on reference line.";
    return Stage::ERROR;
  }

  const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary();
  const auto& end_point =
      reference_line_info.path_data().discretized_path().EndPoint();
  Vec2d last_xy_point(end_point.x(), end_point.y());
  // get s of last point on path
  common::SLPoint sl_point;
  if (!reference_line_info.reference_line().XYToSL(last_xy_point, &sl_point)) {
    AERROR << "Fail to transfer cartesian point to frenet point.";
    return Stage::ERROR;
  }

  if (adc_sl_boundary.end_s() > sl_point.s() - 1.0) {
    next_stage_ = ScenarioConfig::NO_STAGE;
    return Stage::FINISHED;
  }
  return Stage::RUNNING;
}

}  // namespace side_pass
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<commit_msg>planning: fixed side pass.<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/scenarios/side_pass/side_pass_stage.h"

#include <algorithm>
#include <vector>

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/speed_profile_generator.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {

using apollo::common::TrajectoryPoint;

constexpr double kExtraMarginforStopOnWaitPointStage = 3.0;

/*
 * @brief:
 * STAGE: SidePassApproachObstacle
 */
Stage::StageStatus SidePassApproachObstacle::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);
  if (!plan_ok) {
    AERROR << "Stage " << Name() << " error: "
           << "planning on reference line failed.";
    return Stage::ERROR;
  }
  const ReferenceLineInfo& reference_line_info =
      frame->reference_line_info().front();
  double adc_velocity = frame->vehicle_state().linear_velocity();
  double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
  const PathDecision& path_decision = reference_line_info.path_decision();

  double front_obstacle_distance = 1000;
  for (const auto* obstacle : path_decision.obstacles().Items()) {
    if (obstacle->IsVirtual()) {
      continue;
    }

    bool is_on_road = reference_line_info.reference_line().HasOverlap(
        obstacle->PerceptionBoundingBox());
    if (!is_on_road) {
      continue;
    }

    const auto& obstacle_sl = obstacle->PerceptionSLBoundary();
    if (obstacle_sl.end_s() <= reference_line_info.AdcSlBoundary().start_s()) {
      continue;
    }

    double distance = obstacle_sl.start_s() - adc_front_edge_s;
    if (distance < front_obstacle_distance) {
      front_obstacle_distance = distance;
    }
  }

  if ((front_obstacle_distance) < 0) {
    AERROR << "Stage " << Name() << " error: "
           << "front obstacle has wrong position.";
    return Stage::ERROR;
  }
  // TODO(all): stage params need to be in config file
  double max_stop_velocity = 1.0e-5;
  double min_stop_obstacle_distance = 4.0;

  if (adc_velocity < max_stop_velocity &&
      front_obstacle_distance > min_stop_obstacle_distance) {
    next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH;
    return Stage::FINISHED;
  }
  return Stage::RUNNING;
}

/*
 * @brief:
 * STAGE: SidePassGeneratePath
 */
Stage::StageStatus SidePassGeneratePath::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  if (PlanningOnReferenceLine(planning_start_point, frame)) {
    GetContext()->path_data_ = frame->reference_line_info().front().path_data();
    if (frame->reference_line_info().front().TrajectoryLength() > 0.0) {
      next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT;
      return Stage::FINISHED;
    } else {
      return Stage::RUNNING;
    }
  }
  return Stage::ERROR;
}

/*
 * @brief:
 * STAGE: SidePassDetectSafety
 */

Stage::StageStatus SidePassDetectSafety::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  const auto& reference_line_info = frame->reference_line_info().front();
  bool update_success = GetContext()->path_data_.UpdateFrenetFramePath(
      &reference_line_info.reference_line());
  if (!update_success) {
    AERROR << "Fail to update path_data.";
    return Stage::ERROR;
  }

  const auto adc_frenet_frame_point_ =
      reference_line_info.reference_line().GetFrenetPoint(
          frame->PlanningStartPoint());

  bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(
      adc_frenet_frame_point_.s(), adc_frenet_frame_point_.l());
  if (!trim_success) {
    AERROR << "Fail to trim path_data. adc_frenet_frame_point: "
           << adc_frenet_frame_point_.ShortDebugString();
    return Stage::ERROR;
  }

  auto& rfl_info = frame->mutable_reference_line_info()->front();
  *(rfl_info.mutable_path_data()) = GetContext()->path_data_;

  const auto& path_points =
      rfl_info.path_data().discretized_path().path_points();
  auto* debug_path =
      rfl_info.mutable_debug()->mutable_planning_data()->add_path();

  debug_path->set_name("DpPolyPathOptimizer");
  debug_path->mutable_path_point()->CopyFrom(
      {path_points.begin(), path_points.end()});

  if (!PlanningOnReferenceLine(planning_start_point, frame)) {
    return Stage::ERROR;
  }
  bool is_safe = true;
  double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();

  const PathDecision& path_decision =
      frame->reference_line_info().front().path_decision();
  for (const auto* obstacle : path_decision.obstacles().Items()) {
    // TODO(All): check according to neighbor lane.
    if (obstacle->IsVirtual() && obstacle->Id().substr(0, 3) == "SP_" &&
        obstacle->PerceptionSLBoundary().start_s() >= adc_front_edge_s) {
      is_safe = false;
      break;
    }
  }
  if (is_safe) {
    next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE;
    return Stage::FINISHED;
  }
  return Stage::RUNNING;
}

/*
 * @brief:
 * STAGE: SidePassPassObstacle
 */
Stage::StageStatus SidePassPassObstacle::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  const auto& reference_line_info = frame->reference_line_info().front();
  bool update_success = GetContext()->path_data_.UpdateFrenetFramePath(
      &reference_line_info.reference_line());
  if (!update_success) {
    AERROR << "Fail to update path_data.";
    return Stage::ERROR;
  }

  const auto adc_frenet_frame_point_ =
      reference_line_info.reference_line().GetFrenetPoint(
          frame->PlanningStartPoint());

  bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(
      adc_frenet_frame_point_.s(), adc_frenet_frame_point_.l());
  if (!trim_success) {
    AERROR << "Fail to trim path_data. adc_frenet_frame_point: "
           << adc_frenet_frame_point_.ShortDebugString();
    return Stage::ERROR;
  }

  auto& rfl_info = frame->mutable_reference_line_info()->front();
  *(rfl_info.mutable_path_data()) = GetContext()->path_data_;

  const auto& path_points =
      rfl_info.path_data().discretized_path().path_points();
  auto* debug_path =
      rfl_info.mutable_debug()->mutable_planning_data()->add_path();

  // TODO(All):
  // Have to use DpPolyPathOptimizer to show in dreamview. Need change to
  // correct name.
  debug_path->set_name("DpPolyPathOptimizer");
  debug_path->mutable_path_point()->CopyFrom(
      {path_points.begin(), path_points.end()});

  bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);
  if (!plan_ok) {
    AERROR << "Fail to plan on reference line.";
    return Stage::ERROR;
  }

  const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary();
  const auto& end_point =
      reference_line_info.path_data().discretized_path().EndPoint();
  Vec2d last_xy_point(end_point.x(), end_point.y());
  // get s of last point on path
  common::SLPoint sl_point;
  if (!reference_line_info.reference_line().XYToSL(last_xy_point, &sl_point)) {
    AERROR << "Fail to transfer cartesian point to frenet point.";
    return Stage::ERROR;
  }

  if (adc_sl_boundary.end_s() > sl_point.s() - 1.0) {
    next_stage_ = ScenarioConfig::NO_STAGE;
    return Stage::FINISHED;
  }
  return Stage::RUNNING;
}

}  // namespace side_pass
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unocontrolcontainer.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2001-09-28 09:52:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
#define _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_

#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XUNOCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XUnoControlContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif

#include <toolkit/controls/unocontrol.hxx>
#include <toolkit/controls/unocontrolbase.hxx>
#include <toolkit/helper/macros.hxx>
#include <toolkit/helper/servicenames.hxx>

class UnoControlHolderList;

//  ----------------------------------------------------
//  class UnoControlContainer
//  ----------------------------------------------------
class UnoControlContainer : public ::com::sun::star::awt::XUnoControlContainer,
                            public ::com::sun::star::awt::XControlContainer,
                            public ::com::sun::star::container::XContainer,
                            public UnoControlBase
{
private:
    UnoControlHolderList*                   mpControls;
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > >    maTabControllers;
    ContainerListenerMultiplexer            maCListeners;

protected:
    void                                    ImplActivateTabControllers();

public:
                UnoControlContainer();
                UnoControlContainer( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >  xPeer );
                ~UnoControlContainer();

    ::com::sun::star::uno::Any  SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return UnoControl::queryInterface(rType); }
    void                        SAL_CALL acquire() throw()  { OWeakAggObject::acquire(); }
    void                        SAL_CALL release() throw()  { OWeakAggObject::release(); }

    ::com::sun::star::uno::Any  SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XTypeProvider
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type >  SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< sal_Int8 >                     SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XComponent
    void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XEventListener
    void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::container::XContainer
    void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XControlContainer
    void SAL_CALL setStatusText( const ::rtl::OUString& StatusText ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > > SAL_CALL getControls(  ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > SAL_CALL getControl( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL addControl( const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XUnoControlContainer
    void SAL_CALL setTabControllers( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > >& TabControllers ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > > SAL_CALL getTabControllers(  ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL addTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XControl
    void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& Toolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& Parent ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XWindow
    void SAL_CALL setVisible( sal_Bool Visible ) throw(::com::sun::star::uno::RuntimeException);

    DECLIMPL_SERVICEINFO( UnoControlContainer, ::rtl::OUString::createFromAscii( szServiceName2_UnoControlContainer ) )
};

#endif // _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_

<commit_msg>#96008# +removingControl/addingControl<commit_after>/*************************************************************************
 *
 *  $RCSfile: unocontrolcontainer.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: fs $ $Date: 2002-01-08 13:24:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
#define _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_

#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XUNOCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XUnoControlContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif

#include <toolkit/controls/unocontrol.hxx>
#include <toolkit/controls/unocontrolbase.hxx>
#include <toolkit/helper/macros.hxx>
#include <toolkit/helper/servicenames.hxx>

class UnoControlHolderList;

//  ----------------------------------------------------
//  class UnoControlContainer
//  ----------------------------------------------------
class UnoControlContainer : public ::com::sun::star::awt::XUnoControlContainer,
                            public ::com::sun::star::awt::XControlContainer,
                            public ::com::sun::star::container::XContainer,
                            public UnoControlBase
{
private:
    UnoControlHolderList*                   mpControls;
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > >    maTabControllers;
    ContainerListenerMultiplexer            maCListeners;

protected:
    void                                    ImplActivateTabControllers();

public:
                UnoControlContainer();
                UnoControlContainer( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >  xPeer );
                ~UnoControlContainer();

    ::com::sun::star::uno::Any  SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return UnoControl::queryInterface(rType); }
    void                        SAL_CALL acquire() throw()  { OWeakAggObject::acquire(); }
    void                        SAL_CALL release() throw()  { OWeakAggObject::release(); }

    ::com::sun::star::uno::Any  SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XTypeProvider
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type >  SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< sal_Int8 >                     SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XComponent
    void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XEventListener
    void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::container::XContainer
    void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XControlContainer
    void SAL_CALL setStatusText( const ::rtl::OUString& StatusText ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > > SAL_CALL getControls(  ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > SAL_CALL getControl( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL addControl( const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XUnoControlContainer
    void SAL_CALL setTabControllers( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > >& TabControllers ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > > SAL_CALL getTabControllers(  ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL addTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XControl
    void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& Toolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& Parent ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XWindow
    void SAL_CALL setVisible( sal_Bool Visible ) throw(::com::sun::star::uno::RuntimeException);

    DECLIMPL_SERVICEINFO( UnoControlContainer, ::rtl::OUString::createFromAscii( szServiceName2_UnoControlContainer ) )

protected:
    virtual void removingControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl );
    virtual void addingControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl );
};

#endif // _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_

<|endoftext|>


<commit_before>#include "condor_common.h"

#include "job.h"
#include "parse.h"
#include "util.h"
#include "debug.h"
#include "list.h"

static const char   COMMENT    = '#';
static const char * DELIMITERS = " \t";
static const int    MAX_LENGTH = 255;

//-----------------------------------------------------------------------------
void exampleSyntax (const char * example) {
    debug_println (DEBUG_QUIET, "Example syntax is: %s", example);
}

//-----------------------------------------------------------------------------
bool isKeyWord (char *token) {
    const unsigned int numKeyWords = 6;
    const char * keywords[numKeyWords] = {
        "JOB", "PARENT", "CHILD", "PRE", "POST", "DONE"
    };
    for (unsigned int i = 0 ; i < numKeyWords ; i++) {
        if (!strcasecmp (token, keywords[i])) return true;
    }
    return false;
}

//-----------------------------------------------------------------------------
bool parse (char *filename, Dag *dag) {

    assert (dag != NULL);

    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        if (DEBUG_LEVEL(DEBUG_QUIET)) {
            debug_println (DEBUG_QUIET, "Could not open file %s for input",
                           filename);
            return false;
        }
    }

    char line [MAX_LENGTH + 1];

    int lineNumber = 0;

    //
    // This loop will read every line of the input file
    //
    int len;
    bool done = false;

    while (!done && (len = util_getline(fp, line, MAX_LENGTH)) >= 0) {
        lineNumber++;

        //
        // Find the terminating '\0'
        //
        char * endline = line;
        while (*endline != '\0') endline++;

        if (len == 0) continue;            // Ignore blank lines
        if (line[0] == COMMENT) continue;  // Ignore comments

        char *token = strtok(line, DELIMITERS);

        //
        // Handle a Job token
        //
        // Example Syntax is:  JOB j1 j1.condor [DONE]
        //
        if (strcasecmp(token, "JOB") == 0) {
            const char * example = "JOB j1 j1.condor";

            char *jobName = strtok(NULL, DELIMITERS);
            if (jobName == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing job name",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            // The JobName cannot be a keyword
            //
            if (isKeyWord(jobName)) {
                debug_println (DEBUG_QUIET,
                               "%s(%d): JobName cannot be a keyword.",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            // Next token is the condor command file
            //
            char *cmd = strtok(NULL, DELIMITERS);
            if (cmd == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing condor cmd file",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            Job * job = new Job (jobName, cmd);
            if (job == NULL) debug_error (1, DEBUG_QUIET, "Out of Memory");

            // Check if the user has pre-definied a Job as being done
            //
            char *done = strtok(0, DELIMITERS);
            if (done != NULL && strcasecmp(done, "DONE") == 0) {
                job->_Status = Job::STATUS_DONE;
            }

            if (!dag->Add (*job)) {
                if (DEBUG_LEVEL(DEBUG_QUIET)) {
                    printf ("ERROR adding JOB ");
                    job->Print();
                    printf (" to Dag\n");
                }
                fclose(fp);
                return false;
            } else if (DEBUG_LEVEL(DEBUG_DEBUG_3)) {
                printf ("%s: Added JOB: ", __FUNCTION__);
                job->Print();
                putchar('\n');
            }
        }

        //
        // Handle a SCRIPT token
        //
        // Example Syntax is:  SCRIPT (PRE|POST) JobName ScriptName Args ...
        //
        else if ( strcasecmp(token, "SCRIPT") == 0 ) {
            const char * example = "SCRIPT (PRE|POST) JobName Script Args ...";
            Job * job = NULL;

            //
            // Second keyword is either PRE or POST
            //
            bool   post;
            char * prepost = strtok (NULL, DELIMITERS);
            if (prepost == NULL) goto MISSING_PREPOST;
            else if (!strcasecmp (prepost, "PRE" )) post = false;
            else if (!strcasecmp (prepost, "POST")) post = true;
            else {
              MISSING_PREPOST:
                debug_println (DEBUG_QUIET, "%s(%d): Expected PRE or POST",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            //
            // Third token is the JobName
            //
            char *jobName = strtok(NULL, DELIMITERS);
            if (jobName == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing job name",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            } else if (isKeyWord(jobName)) {
                debug_println (DEBUG_QUIET,
                               "%s(%d): JobName cannot be a keyword.",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            } else {
                job = dag->GetJob(jobName);
                if (job == NULL) {
                    debug_println (DEBUG_QUIET, "%s(%d): Unknown Job %s",
                                   filename, lineNumber, jobName);
                    fclose(fp);
                    return false;
                }
            }

            //
            // Make sure this job doesn't already have a script
            //
            if (post ? job->_scriptPost != NULL : job->_scriptPre  != NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Job previously assigned "
                               "a %s script.", filename, lineNumber,
                               post ? "POST" : "PRE");
                fclose(fp);
                return false;
            }

            //
            // The rest of the line is the script and args
            //
            char * rest = jobName;
            while (*rest != '\0') rest++;
            if (rest < endline)   rest++;

            if (post) job->_scriptPost = new Script (post, rest, job);
            else      job->_scriptPre  = new Script (post, rest, job);
        }

        //
        // Handle a Dependency token
        //
        // Example Syntax is:  PARENT p1 p2 p3 ... CHILD c1 c2 c3 ...
        //
        else if (strcasecmp(token, "PARENT") == 0) {
            const char * example = "PARENT p1 p2 p3 CHILD c1 c2 c3";

            List<Job> parents;

            char *jobName;

            while ((jobName = strtok (NULL, DELIMITERS)) != NULL &&
                   strcasecmp (jobName, "CHILD") != 0) {
                Job * job = dag->GetJob(jobName);
                if (job == NULL) {
                    debug_println (DEBUG_QUIET, "%s(%d): Unknown Job %s",
                                   filename, lineNumber, jobName);
                    fclose(fp);
                    return false;
                }
                parents.Append (job);
            }

            // There must be one or more parent job names before
            // the CHILD token
            if (parents.Number() < 1) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing Parent Job names",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            if (jobName == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Expected CHILD token",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            List<Job> children;

            while ((jobName = strtok (NULL, DELIMITERS)) != NULL) {
                Job * job = dag->GetJob(jobName);
                if (job == NULL) {
                    debug_println (DEBUG_QUIET, "%s(%d): Unknown Job %s",
                                   filename, lineNumber, jobName);
                    fclose(fp);
                    return false;
                }
                children.Append (job);
            }

            if (children.Number() < 1) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing Child Job names",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            //
            // Now add all the dependencies
            //

            Job *parent;
            parents.Rewind();
            while ((parent = parents.Next()) != NULL) {
                Job *child;
                children.Rewind();
                while ((child = children.Next()) != NULL) {
                    if (!dag->AddDependency (parent, child)) {
                        debug_println (DEBUG_QUIET,
                                       "Failed to add dependency to dag");
                        fclose(fp);
                        return false;
                    }
                    if (DEBUG_LEVEL(DEBUG_DEBUG_3)) {
                        printf ("%s: Added Dependency PARENT: ", __FUNCTION__);
                        parent->Print();
                        printf ("  CHILD: ");
                        child->Print();
                        putchar ('\n');
                    }
                }
            }

        } else {
            //
            // Bad token in the input file
            //
            debug_println( DEBUG_QUIET,
                           "%s(%d): Expected JOB, SCRIPT, or PARENT token",
                           filename, lineNumber );
            fclose(fp);
            return false;
        }

    }
    return true;
}
<commit_msg>changed so we pre-process the lines of the DAG file with the same routine in the util_lib used to process condor_config.  this allows the DAG file to have a backslash character as a line continuation symbol.<commit_after>#include "condor_common.h"

#include "job.h"
#include "parse.h"
#include "util.h"
#include "debug.h"
#include "list.h"
#include "util_lib_proto.h"

static const char   COMMENT    = '#';
static const char * DELIMITERS = " \t";
static const int    MAX_LENGTH = 255;

//-----------------------------------------------------------------------------
void exampleSyntax (const char * example) {
    debug_println (DEBUG_QUIET, "Example syntax is: %s", example);
}

//-----------------------------------------------------------------------------
bool isKeyWord (char *token) {
    const unsigned int numKeyWords = 6;
    const char * keywords[numKeyWords] = {
        "JOB", "PARENT", "CHILD", "PRE", "POST", "DONE"
    };
    for (unsigned int i = 0 ; i < numKeyWords ; i++) {
        if (!strcasecmp (token, keywords[i])) return true;
    }
    return false;
}

//-----------------------------------------------------------------------------
bool parse (char *filename, Dag *dag) {

    assert (dag != NULL);

    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        if (DEBUG_LEVEL(DEBUG_QUIET)) {
            debug_println (DEBUG_QUIET, "Could not open file %s for input",
                           filename);
            return false;
        }
    }

    char *line;

    int lineNumber = 0;

    //
    // This loop will read every line of the input file
    //
    int len;
    bool done = false;

    while ( !done && ((line=getline(fp)) != NULL) ) {
        lineNumber++;
		if ( line ) {
			len = strlen(line);
		}

        //
        // Find the terminating '\0'
        //
        char * endline = line;
        while (*endline != '\0') endline++;

        if (len == 0) continue;            // Ignore blank lines
        if (line[0] == COMMENT) continue;  // Ignore comments

        char *token = strtok(line, DELIMITERS);

        //
        // Handle a Job token
        //
        // Example Syntax is:  JOB j1 j1.condor [DONE]
        //
        if (strcasecmp(token, "JOB") == 0) {
            const char * example = "JOB j1 j1.condor";

            char *jobName = strtok(NULL, DELIMITERS);
            if (jobName == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing job name",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            // The JobName cannot be a keyword
            //
            if (isKeyWord(jobName)) {
                debug_println (DEBUG_QUIET,
                               "%s(%d): JobName cannot be a keyword.",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            // Next token is the condor command file
            //
            char *cmd = strtok(NULL, DELIMITERS);
            if (cmd == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing condor cmd file",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            Job * job = new Job (jobName, cmd);
            if (job == NULL) debug_error (1, DEBUG_QUIET, "Out of Memory");

            // Check if the user has pre-definied a Job as being done
            //
            char *done = strtok(0, DELIMITERS);
            if (done != NULL && strcasecmp(done, "DONE") == 0) {
                job->_Status = Job::STATUS_DONE;
            }

            if (!dag->Add (*job)) {
                if (DEBUG_LEVEL(DEBUG_QUIET)) {
                    printf ("ERROR adding JOB ");
                    job->Print();
                    printf (" to Dag\n");
                }
                fclose(fp);
                return false;
            } else if (DEBUG_LEVEL(DEBUG_DEBUG_3)) {
                printf ("%s: Added JOB: ", __FUNCTION__);
                job->Print();
                putchar('\n');
            }
        }

        //
        // Handle a SCRIPT token
        //
        // Example Syntax is:  SCRIPT (PRE|POST) JobName ScriptName Args ...
        //
        else if ( strcasecmp(token, "SCRIPT") == 0 ) {
            const char * example = "SCRIPT (PRE|POST) JobName Script Args ...";
            Job * job = NULL;

            //
            // Second keyword is either PRE or POST
            //
            bool   post;
            char * prepost = strtok (NULL, DELIMITERS);
            if (prepost == NULL) goto MISSING_PREPOST;
            else if (!strcasecmp (prepost, "PRE" )) post = false;
            else if (!strcasecmp (prepost, "POST")) post = true;
            else {
              MISSING_PREPOST:
                debug_println (DEBUG_QUIET, "%s(%d): Expected PRE or POST",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            //
            // Third token is the JobName
            //
            char *jobName = strtok(NULL, DELIMITERS);
            if (jobName == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing job name",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            } else if (isKeyWord(jobName)) {
                debug_println (DEBUG_QUIET,
                               "%s(%d): JobName cannot be a keyword.",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            } else {
                job = dag->GetJob(jobName);
                if (job == NULL) {
                    debug_println (DEBUG_QUIET, "%s(%d): Unknown Job %s",
                                   filename, lineNumber, jobName);
                    fclose(fp);
                    return false;
                }
            }

            //
            // Make sure this job doesn't already have a script
            //
            if (post ? job->_scriptPost != NULL : job->_scriptPre  != NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Job previously assigned "
                               "a %s script.", filename, lineNumber,
                               post ? "POST" : "PRE");
                fclose(fp);
                return false;
            }

            //
            // The rest of the line is the script and args
            //
            char * rest = jobName;
            while (*rest != '\0') rest++;
            if (rest < endline)   rest++;

            if (post) job->_scriptPost = new Script (post, rest, job);
            else      job->_scriptPre  = new Script (post, rest, job);
        }

        //
        // Handle a Dependency token
        //
        // Example Syntax is:  PARENT p1 p2 p3 ... CHILD c1 c2 c3 ...
        //
        else if (strcasecmp(token, "PARENT") == 0) {
            const char * example = "PARENT p1 p2 p3 CHILD c1 c2 c3";

            List<Job> parents;

            char *jobName;

            while ((jobName = strtok (NULL, DELIMITERS)) != NULL &&
                   strcasecmp (jobName, "CHILD") != 0) {
                Job * job = dag->GetJob(jobName);
                if (job == NULL) {
                    debug_println (DEBUG_QUIET, "%s(%d): Unknown Job %s",
                                   filename, lineNumber, jobName);
                    fclose(fp);
                    return false;
                }
                parents.Append (job);
            }

            // There must be one or more parent job names before
            // the CHILD token
            if (parents.Number() < 1) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing Parent Job names",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            if (jobName == NULL) {
                debug_println (DEBUG_QUIET, "%s(%d): Expected CHILD token",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            List<Job> children;

            while ((jobName = strtok (NULL, DELIMITERS)) != NULL) {
                Job * job = dag->GetJob(jobName);
                if (job == NULL) {
                    debug_println (DEBUG_QUIET, "%s(%d): Unknown Job %s",
                                   filename, lineNumber, jobName);
                    fclose(fp);
                    return false;
                }
                children.Append (job);
            }

            if (children.Number() < 1) {
                debug_println (DEBUG_QUIET, "%s(%d): Missing Child Job names",
                               filename, lineNumber);
                exampleSyntax (example);
                fclose(fp);
                return false;
            }

            //
            // Now add all the dependencies
            //

            Job *parent;
            parents.Rewind();
            while ((parent = parents.Next()) != NULL) {
                Job *child;
                children.Rewind();
                while ((child = children.Next()) != NULL) {
                    if (!dag->AddDependency (parent, child)) {
                        debug_println (DEBUG_QUIET,
                                       "Failed to add dependency to dag");
                        fclose(fp);
                        return false;
                    }
                    if (DEBUG_LEVEL(DEBUG_DEBUG_3)) {
                        printf ("%s: Added Dependency PARENT: ", __FUNCTION__);
                        parent->Print();
                        printf ("  CHILD: ");
                        child->Print();
                        putchar ('\n');
                    }
                }
            }

        } else {
            //
            // Bad token in the input file
            //
            debug_println( DEBUG_QUIET,
                           "%s(%d): Expected JOB, SCRIPT, or PARENT token",
                           filename, lineNumber );
            fclose(fp);
            return false;
        }

    }
    return true;
}
<|endoftext|>


<commit_before>/*
** Copyright 1993 by Miron Livny, Mike Litzkow, and Emmanuel Ackaouy.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author:  Emmanuel Ackaouy
**
*/

#define _POSIX_SOURCE

#include "condor_common.h"
#include "condor_constants.h"
#include "condor_io.h"
#include "condor_debug.h"
#include "internet.h"

ReliSock::ReliSock(					/* listen on port		*/
	int		port
	)
	: Sock()
{
	if (!listen(port))
		dprintf(D_ALWAYS, "failed to listen on port %d!\n", port);
}

ReliSock::ReliSock(					/* listen on serv		*/
	char	*serv
	)
	: Sock()
{
	if (!listen(serv))
		dprintf(D_ALWAYS, "failed to listen on serv %s!\n", serv);
}

ReliSock::ReliSock(
	char	*host,
	int		port,
	int		timeout_val
	)
	: Sock()
{
	timeout(timeout_val);
	if (!connect(host, port))
		dprintf(D_ALWAYS, "failed to connect to %s:%d!\n", host, port);
}

ReliSock::ReliSock(
	char	*host,
	char	*serv,
	int		timeout_val
	)
	: Sock()
{
	timeout(timeout_val);
	if (!Sock::connect(host, serv))
		dprintf(D_ALWAYS, "failed to connect to %s:%s!\n", host, serv);
}

ReliSock::~ReliSock()
{
	close();
}

int ReliSock::listen()
{
	if (!valid()) return FALSE;

	if (_state != sock_bound) return FALSE;
	if (::listen(_sock, 5) < 0) return FALSE;

	_state = sock_special;
	_special_state = relisock_listen;

	return TRUE;
}

int ReliSock::accept(
	ReliSock	&c
	)
{
	int			c_sock;
	sockaddr_in	addr;
	int			addr_sz;

	if (!valid()) return FALSE;
	if (_state != sock_special || _special_state != relisock_listen ||
													c._state != sock_virgin)
		return FALSE;

	if (_timeout > 0) {
		struct timeval	timer;
		fd_set			readfds;
		int				nfds=0, nfound;
		timer.tv_sec = _timeout;
		timer.tv_usec = 0;
#if !defined(WIN32) // nfds is ignored on WIN32
		nfds = _sock + 1;
#endif
		FD_ZERO( &readfds );
		FD_SET( _sock, &readfds );

		nfound = select( nfds, &readfds, 0, 0, &timer );

		switch(nfound) {
		case 0:
			return FALSE;
			break;
		case 1:
			break;
		default:
			dprintf( D_ALWAYS, "select returns %d, connect failed\n",
				nfound );
			return FALSE;
			break;
		}
	}

	addr_sz = sizeof(addr);
	if ((c_sock = ::accept(_sock, (sockaddr *)&addr, &addr_sz)) < 0)
		return FALSE;

	c._sock = c_sock;
	c._state = sock_connect;
	c.decode();

	return TRUE;
}

int ReliSock::accept(
	ReliSock	*c
	)
{
	if (!c) return FALSE;

	return accept(*c);
}

ReliSock *ReliSock::accept()
{
	ReliSock	*c_rs;
	int			c_sock;

	if (!(c_rs = new ReliSock())) return (ReliSock *)0;

	if ((c_sock = accept(*c_rs)) < 0) {
		delete c_rs;
		return (ReliSock *)0;
	}

	return c_rs;
}

int ReliSock::handle_incoming_packet()
{
	/* if socket is listening, and packet is there, it is ready for accept */
	if (_state == sock_special && _special_state == relisock_listen)
		return TRUE;

	/* do not queue up more than one message at a time on reliable sockets */
	/* but return 1, because old message can still be read.	               */
	if (rcv_msg.ready) return TRUE;

	if (!rcv_msg.rcv_packet(_sock, _timeout)) return FALSE;

	return TRUE;
}

int ReliSock::end_of_message()
{
	int ret_val = FALSE;

	switch(_coding){
		case stream_encode:
			if (!snd_msg.buf.empty()){
				return snd_msg.snd_packet(_sock, TRUE, _timeout);
			}
			break;

		case stream_decode:
			if ( rcv_msg.ready ) {
				if ( rcv_msg.buf.consumed() )
					ret_val = TRUE;
				rcv_msg.ready = FALSE;
				rcv_msg.buf.reset();
			}
			break;

		default:
			assert(0);
	}

	return ret_val;
}

int ReliSock::connect(
	char	*host,
	int		port
	)
{
	return do_connect(host, port);
}

int ReliSock::put_bytes(
	const void	*dta,
	int			sz
	)
{
	int		tw;
	int		nw;

	if (!valid()) return -1;

	for(nw=0;;){

		if (snd_msg.buf.full()){
			if (!snd_msg.snd_packet(_sock, FALSE, _timeout)) return FALSE;
		}
		if (snd_msg.buf.empty()){
			snd_msg.buf.seek(5);
		}

		if ((tw = snd_msg.buf.put_max(&((char *)dta)[nw], sz-nw)) < 0)
			return -1;
		nw += tw;
		if (nw == sz) break;
	}

	return nw;
}

int ReliSock::get_bytes(
	void		*dta,
	int			max_sz
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()){
			return FALSE;
		}
	}

	return rcv_msg.buf.get(dta, max_sz);
}

int ReliSock::get_ptr(
	void		*&ptr,
	char		delim
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready){
		if (!handle_incoming_packet()) return FALSE;
	}

	return rcv_msg.buf.get_tmp(ptr, delim);
}

int ReliSock::peek(
	char		&c
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()) return FALSE;
	}

	return rcv_msg.buf.peek(c);
}

int ReliSock::RcvMsg::rcv_packet(
	SOCKET _sock,
	int _timeout
	)
{
	Buf		*tmp;
	char	hdr[5];
	int		end;
	int		len, len_t;
	int		tmp_len;

    len = 0;
    while (len < 5) {
		if (_timeout > 0) {
			struct timeval	timer;
			fd_set			readfds;
			int				nfds=0, nfound;
			timer.tv_sec = _timeout;
			timer.tv_usec = 0;
#if !defined(WIN32) // nfds is ignored on WIN32
			nfds = _sock + 1;
#endif
			FD_ZERO( &readfds );
			FD_SET( _sock, &readfds );

			nfound = select( nfds, &readfds, 0, 0, &timer );

			switch(nfound) {
			case 0:
				return -1;
				break;
			case 1:
				break;
			default:
				dprintf( D_ALWAYS, "select returns %d, recv failed\n",
					nfound );
				return -1;
				break;
			}
		}
        tmp_len = recv(_sock, hdr+len, 5-len, 0);
        if (tmp_len <= 0)
            return FALSE;
        len += tmp_len;
    }
	end = (int) ((char *)hdr)[0];
	memcpy(&len_t,  &hdr[1], 4);
	len = (int) ntohl(len_t);

	if (!(tmp = new Buf)){
		dprintf(D_ALWAYS, "IO: Out of memory\n");
		return FALSE;
	}
	if (len > tmp->max_size()){
		delete tmp;
		dprintf(D_ALWAYS, "IO: Incoming packet is too big\n");
		return FALSE;
	}
	if ((tmp_len = tmp->read(_sock, len, _timeout)) != len){
		delete tmp;
		dprintf(D_ALWAYS, "IO: Packet read failed: read %d of %d\n",
				tmp_len, len);
		return FALSE;
	}
	if (!buf.put(tmp)) {
		delete tmp;
		dprintf(D_ALWAYS, "IO: Packet storing failed\n");
		return FALSE;
	}

	if (end) ready = TRUE;

	return TRUE;
}

int ReliSock::SndMsg::snd_packet(
	int		_sock,
	int		end,
	int		_timeout
	)
{
	char	hdr[5];
	int		len;
	int		ns;

	hdr[0] = (char) end;
	ns = buf.num_used()-5;
	len = (int) htonl(ns);

	memcpy(&hdr[1], &len, 4);
	if (buf.flush(_sock, hdr, 5, _timeout) != (ns+5)){
		return FALSE;
	}

	return TRUE;
}

struct sockaddr_in * ReliSock::endpoint()
{
	int addr_len;

	addr_len = sizeof(sockaddr_in);

	if (getpeername(_sock, (struct sockaddr *) &_who, &addr_len) < 0)
		return NULL;	// socket not connected

	return &_who;
}

int ReliSock::get_port()
{
	sockaddr_in	addr;
	int			addr_len;

	addr_len = sizeof(sockaddr_in);

	if (getsockname(_sock, (sockaddr *)&addr, &addr_len) < 0) return -1;

	return (int) ntohs(addr.sin_port);
}

int ReliSock::get_file_desc()
{
	return _sock;
}

#ifndef WIN32
	// interface no longer supported
int ReliSock::attach_to_file_desc(
	int		fd
	)
{
	if (_state != sock_virgin) return FALSE;

	_sock = fd;
	_state = sock_connect;
	return TRUE;
}
#endif

char * ReliSock::serialize(char *buf)
{
	char sinful_string[28];
	char *ptmp;

	if ( buf == NULL ) {
		// here we want to save our state into a buffer

		// first, get the state from our parent class
		char * parent_state = Sock::do_serialize();
		// now concatenate our state
		char * outbuf = new char[50];
		sprintf(outbuf,"*%d*%s",_special_state,sin_to_string(&_who));
		strcat(parent_state,outbuf);
		delete []outbuf;
		return( parent_state );
	}

	// here we want to restore our state from the incoming buffer

	// first, let our parent class restore its state
	ptmp = Sock::do_serialize(buf);
	assert( ptmp );
	sscanf(ptmp,"%d*%s",&_special_state,sinful_string);
	string_to_sin(sinful_string, &_who);

	return NULL;
}
<commit_msg>fixed bug: rcv_packet() needs to return FALSE on error, _not_ a -1<commit_after>/*
** Copyright 1993 by Miron Livny, Mike Litzkow, and Emmanuel Ackaouy.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author:  Emmanuel Ackaouy
**
*/

#define _POSIX_SOURCE

#include "condor_common.h"
#include "condor_constants.h"
#include "condor_io.h"
#include "condor_debug.h"
#include "internet.h"

ReliSock::ReliSock(					/* listen on port		*/
	int		port
	)
	: Sock()
{
	if (!listen(port))
		dprintf(D_ALWAYS, "failed to listen on port %d!\n", port);
}

ReliSock::ReliSock(					/* listen on serv		*/
	char	*serv
	)
	: Sock()
{
	if (!listen(serv))
		dprintf(D_ALWAYS, "failed to listen on serv %s!\n", serv);
}

ReliSock::ReliSock(
	char	*host,
	int		port,
	int		timeout_val
	)
	: Sock()
{
	timeout(timeout_val);
	if (!connect(host, port))
		dprintf(D_ALWAYS, "failed to connect to %s:%d!\n", host, port);
}

ReliSock::ReliSock(
	char	*host,
	char	*serv,
	int		timeout_val
	)
	: Sock()
{
	timeout(timeout_val);
	if (!Sock::connect(host, serv))
		dprintf(D_ALWAYS, "failed to connect to %s:%s!\n", host, serv);
}

ReliSock::~ReliSock()
{
	close();
}

int ReliSock::listen()
{
	if (!valid()) return FALSE;

	if (_state != sock_bound) return FALSE;
	if (::listen(_sock, 5) < 0) return FALSE;

	_state = sock_special;
	_special_state = relisock_listen;

	return TRUE;
}

int ReliSock::accept(
	ReliSock	&c
	)
{
	int			c_sock;
	sockaddr_in	addr;
	int			addr_sz;

	if (!valid()) return FALSE;
	if (_state != sock_special || _special_state != relisock_listen ||
													c._state != sock_virgin)
		return FALSE;

	if (_timeout > 0) {
		struct timeval	timer;
		fd_set			readfds;
		int				nfds=0, nfound;
		timer.tv_sec = _timeout;
		timer.tv_usec = 0;
#if !defined(WIN32) // nfds is ignored on WIN32
		nfds = _sock + 1;
#endif
		FD_ZERO( &readfds );
		FD_SET( _sock, &readfds );

		nfound = select( nfds, &readfds, 0, 0, &timer );

		switch(nfound) {
		case 0:
			return FALSE;
			break;
		case 1:
			break;
		default:
			dprintf( D_ALWAYS, "select returns %d, connect failed\n",
				nfound );
			return FALSE;
			break;
		}
	}

	addr_sz = sizeof(addr);
	if ((c_sock = ::accept(_sock, (sockaddr *)&addr, &addr_sz)) < 0)
		return FALSE;

	c._sock = c_sock;
	c._state = sock_connect;
	c.decode();

	return TRUE;
}

int ReliSock::accept(
	ReliSock	*c
	)
{
	if (!c) return FALSE;

	return accept(*c);
}

ReliSock *ReliSock::accept()
{
	ReliSock	*c_rs;
	int			c_sock;

	if (!(c_rs = new ReliSock())) return (ReliSock *)0;

	if ((c_sock = accept(*c_rs)) < 0) {
		delete c_rs;
		return (ReliSock *)0;
	}

	return c_rs;
}

int ReliSock::handle_incoming_packet()
{
	/* if socket is listening, and packet is there, it is ready for accept */
	if (_state == sock_special && _special_state == relisock_listen)
		return TRUE;

	/* do not queue up more than one message at a time on reliable sockets */
	/* but return 1, because old message can still be read.	               */
	if (rcv_msg.ready) return TRUE;

	if (!rcv_msg.rcv_packet(_sock, _timeout)) return FALSE;

	return TRUE;
}

int ReliSock::end_of_message()
{
	int ret_val = FALSE;

	switch(_coding){
		case stream_encode:
			if (!snd_msg.buf.empty()){
				return snd_msg.snd_packet(_sock, TRUE, _timeout);
			}
			break;

		case stream_decode:
			if ( rcv_msg.ready ) {
				if ( rcv_msg.buf.consumed() )
					ret_val = TRUE;
				rcv_msg.ready = FALSE;
				rcv_msg.buf.reset();
			}
			break;

		default:
			assert(0);
	}

	return ret_val;
}

int ReliSock::connect(
	char	*host,
	int		port
	)
{
	return do_connect(host, port);
}

int ReliSock::put_bytes(
	const void	*dta,
	int			sz
	)
{
	int		tw;
	int		nw;

	if (!valid()) return -1;

	for(nw=0;;){

		if (snd_msg.buf.full()){
			if (!snd_msg.snd_packet(_sock, FALSE, _timeout)) return FALSE;
		}
		if (snd_msg.buf.empty()){
			snd_msg.buf.seek(5);
		}

		if ((tw = snd_msg.buf.put_max(&((char *)dta)[nw], sz-nw)) < 0)
			return -1;
		nw += tw;
		if (nw == sz) break;
	}

	return nw;
}

int ReliSock::get_bytes(
	void		*dta,
	int			max_sz
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()){
			return FALSE;
		}
	}

	return rcv_msg.buf.get(dta, max_sz);
}

int ReliSock::get_ptr(
	void		*&ptr,
	char		delim
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready){
		if (!handle_incoming_packet()) return FALSE;
	}

	return rcv_msg.buf.get_tmp(ptr, delim);
}

int ReliSock::peek(
	char		&c
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()) return FALSE;
	}

	return rcv_msg.buf.peek(c);
}

int ReliSock::RcvMsg::rcv_packet(
	SOCKET _sock,
	int _timeout
	)
{
	Buf		*tmp;
	char	hdr[5];
	int		end;
	int		len, len_t;
	int		tmp_len;

    len = 0;
    while (len < 5) {
		if (_timeout > 0) {
			struct timeval	timer;
			fd_set			readfds;
			int				nfds=0, nfound;
			timer.tv_sec = _timeout;
			timer.tv_usec = 0;
#if !defined(WIN32) // nfds is ignored on WIN32
			nfds = _sock + 1;
#endif
			FD_ZERO( &readfds );
			FD_SET( _sock, &readfds );

			nfound = select( nfds, &readfds, 0, 0, &timer );

			switch(nfound) {
			case 0:
				return FALSE;
				break;
			case 1:
				break;
			default:
				dprintf( D_ALWAYS, "select returns %d, recv failed\n",
					nfound );
				return FALSE;
				break;
			}
		}
        tmp_len = recv(_sock, hdr+len, 5-len, 0);
        if (tmp_len <= 0)
            return FALSE;
        len += tmp_len;
    }
	end = (int) ((char *)hdr)[0];
	memcpy(&len_t,  &hdr[1], 4);
	len = (int) ntohl(len_t);

	if (!(tmp = new Buf)){
		dprintf(D_ALWAYS, "IO: Out of memory\n");
		return FALSE;
	}
	if (len > tmp->max_size()){
		delete tmp;
		dprintf(D_ALWAYS, "IO: Incoming packet is too big\n");
		return FALSE;
	}
	if ((tmp_len = tmp->read(_sock, len, _timeout)) != len){
		delete tmp;
		dprintf(D_ALWAYS, "IO: Packet read failed: read %d of %d\n",
				tmp_len, len);
		return FALSE;
	}
	if (!buf.put(tmp)) {
		delete tmp;
		dprintf(D_ALWAYS, "IO: Packet storing failed\n");
		return FALSE;
	}

	if (end) ready = TRUE;

	return TRUE;
}

int ReliSock::SndMsg::snd_packet(
	int		_sock,
	int		end,
	int		_timeout
	)
{
	char	hdr[5];
	int		len;
	int		ns;

	hdr[0] = (char) end;
	ns = buf.num_used()-5;
	len = (int) htonl(ns);

	memcpy(&hdr[1], &len, 4);
	if (buf.flush(_sock, hdr, 5, _timeout) != (ns+5)){
		return FALSE;
	}

	return TRUE;
}

struct sockaddr_in * ReliSock::endpoint()
{
	int addr_len;

	addr_len = sizeof(sockaddr_in);

	if (getpeername(_sock, (struct sockaddr *) &_who, &addr_len) < 0)
		return NULL;	// socket not connected

	return &_who;
}

int ReliSock::get_port()
{
	sockaddr_in	addr;
	int			addr_len;

	addr_len = sizeof(sockaddr_in);

	if (getsockname(_sock, (sockaddr *)&addr, &addr_len) < 0) return -1;

	return (int) ntohs(addr.sin_port);
}

int ReliSock::get_file_desc()
{
	return _sock;
}

#ifndef WIN32
	// interface no longer supported
int ReliSock::attach_to_file_desc(
	int		fd
	)
{
	if (_state != sock_virgin) return FALSE;

	_sock = fd;
	_state = sock_connect;
	return TRUE;
}
#endif

char * ReliSock::serialize(char *buf)
{
	char sinful_string[28];
	char *ptmp;

	if ( buf == NULL ) {
		// here we want to save our state into a buffer

		// first, get the state from our parent class
		char * parent_state = Sock::do_serialize();
		// now concatenate our state
		char * outbuf = new char[50];
		sprintf(outbuf,"*%d*%s",_special_state,sin_to_string(&_who));
		strcat(parent_state,outbuf);
		delete []outbuf;
		return( parent_state );
	}

	// here we want to restore our state from the incoming buffer

	// first, let our parent class restore its state
	ptmp = Sock::do_serialize(buf);
	assert( ptmp );
	sscanf(ptmp,"%d*%s",&_special_state,sinful_string);
	string_to_sin(sinful_string, &_who);

	return NULL;
}
<|endoftext|>


<commit_before>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file	    g_network_def.cpp
* @version
* @brief
* @author   duye
* @date     2014-05-13
* @note
*
*  2. 2014-06-21 duye move to gohoop
*  1. 2014-05-13 duye Created this file
*
*/
#include <g_function.h>
#include <g_network_def.h>

namespace gcom {

NetWorkConv::NetWorkConv() {}
NetWorkConv::~NetWorkConv() {}

GResult NetWorkConv::ipToInteger(const std::string& str_ip, GUint32& int_ip)
{
    std::list<std::string> split_list;
    IS_NO_R(Convert::splitString(str_ip, '.', split_list));
    IS_NO_RR(split_list.size() == 4, G_ERROR_INVALID_PARAMETERS);

    GUint32 ip_array[4] = {0};
    GUint16 i = 0;
    std::list<std::string>::iterator iter = split_list.begin();
    for (; iter != split_list.end(); ++iter)
    {
        ip_array[i] = std::stoul(*iter);
    }

    int_ip = (ip_array[0] << 24) + (ip_array[1] << 16) + (ip_array[2] << 8) + ip_array[3];

    return G_YES;
}

GResult NetWorkConv::ipToString(const GUint32 int_ip, std::string& str_ip)
{
    GInt8 tmp_buf[16] = {0};
    sprintf(tmp_buf, "%u.%u.%u.%u",
        (int_ip & 0xff000000) >> 24,
        (int_ip & 0x00ff0000) >> 16,
        (int_ip & 0x0000ff00) >> 8,
        (int_ip & 0x000000ff));

    str_ip.assign(tmp_buf);

    return G_YES;
}

GResult NetWorkConv::macToInteger(const std::string& str_mac, GUint64& int_mac)
{
    std::list<std::string> split_list;
    IS_NO_R(Convert::splitString(str_mac, ':', split_list));
    IS_NO_RR(split_list.size() == 6, G_ERROR_INVALID_PARAMETERS);

    GUint32 ip_array[6] = {0};
    GUint16 i = 0;
    std::list<std::string>::iterator iter = split_list.begin();
    for (; iter != split_list.end(); ++iter)
    {
        ip_array[i] = std::stoul(*iter);
    }

    int_mac = (ip_array[0] << 40) + (ip_array[1] << 32) + (ip_array[2] << 24)
        + (ip_array[3] << 16) + (ip_array[4] << 8) + ip_array[5];

    return G_YES;
}

GResult NetWorkConv::macToInteger(const GInt8 bytes_mac[6], GUint64& int_mac)
{
    int_mac = (bytes_mac[0] << 40) + (bytes_mac[1] << 32) + (bytes_mac[2] << 24)
        + (bytes_mac[3] << 16) + (bytes_mac[4] << 8) + bytes_mac[5];

    return G_YES;
}

GResult NetWorkConv::macToBytes(const std::string& str_mac, GInt8 bytes_mac[6])
{
    std::list<std::string> split_list;
    IS_NO_R(Convert::splitString(str_mac, ':', split_list));
    IS_NO_RR(split_list.size() == 6, G_ERROR_INVALID_PARAMETERS);

    GUint16 i = 0;
    std::list<std::string>::iterator iter = split_list.begin();
    for (; iter != split_list.end(); ++iter)
    {
        bytes_mac[i] = std::stoul(*iter);
    }

    return G_YES;
}

GResult NetWorkConv::macToBytes(const GUint64 int_mac, GInt8 bytes_mac[6])
{
    bytes_mac[0] = (int_mac & 0xff000000) >> 40;
    bytes_mac[1] = (int_mac & 0xff000000) >> 32;
    bytes_mac[2] = (int_mac & 0xff000000) >> 24;
    bytes_mac[3] = (int_mac & 0xff000000) >> 16;
    bytes_mac[4] = (int_mac & 0xff000000) >> 8;
    bytes_mac[5] = (int_mac & 0xff000000);

    return G_YES;
}

GResult NetWorkConv::macToString(const GUint64 int_mac, std::string& str_mac)
{
    GInt8 tmp_buf[18] = {0};
    sprintf(tmp_buf, "%0x:%0x:%0x:%0x:%0x:%0x",
        (int_mac & 0xff000000) >> 24,
        (int_mac & 0x00ff0000) >> 16,
        (int_mac & 0x0000ff00) >> 8,
        (int_mac & 0x000000ff));

    Convert::toupper(tmp_buf);
    str_mac.assign(tmp_buf);

    return G_YES;
}

GResult NetWorkConv::macToString(GInt8 bytes_mac[6], std::string& str_mac)
{
    GInt8 tmp_buf[18] = {0};
    sprintf(tmp_buf, "%0x:%0x:%0x:%0x:%0x:%0x",
        bytes_mac[5], bytes_mac[4], bytes_mac[3], bytes_mac[2], bytes_mac[1], bytes_mac[0]);

    Convert::toupper(tmp_buf);
    str_mac.assign(tmp_buf);

    return G_YES;
}

IPAddr::IPAddr() : m_ip(0) {}

IPAddr::IPAddr(const GUint32 ip) : m_ip(ip)
{
    if (m_ip != 0)
    {
    	NetWorkConv::ipToString(m_ip, m_ipStr);
    }
}

IPAddr::IPAddr(const std::string& ip) : m_ip(0), m_ipStr(ip)
{
    if (!m_ipStr.empty())
    {
    	NetWorkConv::ipToInteger(m_ipStr, m_ip);
    }
}

IPAddr::~IPAddr() {}

void IPAddr::setIP(const GUint32 ip)
{
    m_ip = 0;
    m_ipStr.clear();

    if (ip != 0)
    {
    	m_ip = ip;
    	NetWorkConv::ipToString(m_ip, m_ipStr);
    }
}

void IPAddr::setIP(const std::string& ip)
{
    m_ip = 0;
    m_ipStr.clear();

    if (!ip.empty())
    {
    	m_ipStr = ip;
    	NetWorkConv::ipToInteger(m_ipStr, m_ip);
    }
}

GUint32 IPAddr::getIP() const
{
    return m_ip;
}

const std::string& IPAddr::getIPStr() const
{
    return m_ipStr;
}

MacAddr::MacAddr() : m_mac(0) {}

MacAddr::MacAddr(const GUint64 mac) : m_mac(mac)
{
    if (m_mac != 0)
    {
    	NetWorkConv::macToString(m_mac, m_macStr);
    }
}

MacAddr::MacAddr(const std::string& mac) : m_mac(0), m_macStr(mac)
{
    if (!m_macStr.empty())
    {
    	NetWorkConv::macToInteger(m_macStr, m_mac);
    }
}

void MacAddr::setMac(GUint64 mac)
{
    m_mac = 0;
    m_macStr.clear();

    if (mac != 0)
    {
    	m_mac = mac;
    	NetWorkConv::macToString(m_mac, m_macStr);
    }
}

void MacAddr::setMac(const std::string& mac)
{
    m_mac = 0;
    m_macStr.clear();

    if (!mac.empty())
    {
    	m_macStr = mac;
    	NetWorkConv::macToInteger(m_macStr, m_mac);
    }
}

GUint64 MacAddr::getMac() const
{
    return m_mac;
}

const std::string& MacAddr::getMacStr() const
{
    return m_macStr;
}

IPPortPair::IPPortPair() : m_port(0) {}

IPPortPair::IPPortPair(const IPAddr& ip_addr, const GUint16 port)
    : m_ipAddr(ip_addr), m_port(port) {}

IPPortPair::~IPPortPair() {}

void IPPortPair::setIPAddr(const IPAddr& ip_addr)
{
    m_ipAddr = ip_addr;
}

const IPAddr& IPPortPair::getIPAddr() const
{
    return m_ipAddr;
}

void IPPortPair::setPort(const GUint16 port)
{
    m_port = port;
}

GUint16 IPPortPair::getPort() const
{
    return m_port;
}

NetAddr::NetAddr() {}

NetAddr::NetAddr(const MacAddr mac_addr, const IPAddr& ip_addr, const GUint16 port)
    : m_macAddr(mac_addr), m_ip(ip_addr), m_port(port) {}

NetAddr::~NetAddr() {}

void NetAddr::setMacAddr(const MacAddr& mac_addr)
{
    m_macAddr = mac_addr;
}

const MacAddr& NetAddr::getMacAddr() const
{
    return m_macAddr;
}

void NetAddr::setIPAddr(const IPAddr& ip_addr)
{
    m_ip = ip_addr;
}

const IPAddr& NetAddr::getIPAddr() const
{
    return m_ip;
}

void NetAddr::setPort(const GUint16 port)
{
    m_port = port;
}

GUint16 NetAddr::getPort() const
{
    return m_port;
}

SocketAddr::SocketAddr() {}

SocketAddr::SocketAddr(const NetAddr& src_addr, const NetAddr& dst_addr)
    : m_srcAddr(src_addr), m_dstAddr(dst_addr) {}

SocketAddr::~SocketAddr() {}

void SocketAddr::setSrcAddr(const NetAddr& src_addr)
{
    m_srcAddr = src_addr;
}

const NetAddr& SocketAddr::getSrcAddr() const
{
    return m_srcAddr;
}

void SocketAddr::setDstAddr(const NetAddr& dst_addr)
{
    m_dstAddr = dst_addr;
}

const NetAddr& SocketAddr::getDstAddr() const
{
    return m_dstAddr;
}

}
<commit_msg>Update g_network_def.cpp<commit_after>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file     g_network_def.cpp
* @version
* @brief
* @author   duye
* @date     2014-05-13
* @note
*
*  2. 2014-06-21 duye move to gohoop
*  1. 2014-05-13 duye Created this file
*
*/
#include <g_function.h>
#include <g_network_def.h>

namespace gcom {

NetWorkConv::NetWorkConv() {}
NetWorkConv::~NetWorkConv() {}

GResult NetWorkConv::ipToInteger(const std::string& str_ip, GUint32& int_ip)
{
    std::list<std::string> split_list;
    IS_NO_R(Convert::splitString(str_ip, '.', split_list));
    IS_NO_RR(split_list.size() == 4, G_ERROR_INVALID_PARAMETERS);

    GUint32 ip_array[4] = {0};
    GUint16 i = 0;
    std::list<std::string>::iterator iter = split_list.begin();
    for (; iter != split_list.end(); ++iter)
    {
        ip_array[i] = std::stoul(*iter);
    }

    int_ip = (ip_array[0] << 24) + (ip_array[1] << 16) + (ip_array[2] << 8) + ip_array[3];

    return G_YES;
}

GResult NetWorkConv::ipToString(const GUint32 int_ip, std::string& str_ip)
{
    GInt8 tmp_buf[16] = {0};
    sprintf(tmp_buf, "%u.%u.%u.%u",
        (int_ip & 0xff000000) >> 24,
        (int_ip & 0x00ff0000) >> 16,
        (int_ip & 0x0000ff00) >> 8,
        (int_ip & 0x000000ff));

    str_ip.assign(tmp_buf);

    return G_YES;
}

GResult NetWorkConv::macToInteger(const std::string& str_mac, GUint64& int_mac)
{
    std::list<std::string> split_list;
    IS_NO_R(Convert::splitString(str_mac, ':', split_list));
    IS_NO_RR(split_list.size() == 6, G_ERROR_INVALID_PARAMETERS);

    GUint32 ip_array[6] = {0};
    GUint16 i = 0;
    std::list<std::string>::iterator iter = split_list.begin();
    for (; iter != split_list.end(); ++iter)
    {
        ip_array[i] = std::stoul(*iter);
    }

    int_mac = (ip_array[0] << 40) + (ip_array[1] << 32) + (ip_array[2] << 24)
        + (ip_array[3] << 16) + (ip_array[4] << 8) + ip_array[5];

    return G_YES;
}

GResult NetWorkConv::macToInteger(const GInt8 bytes_mac[6], GUint64& int_mac)
{
    int_mac = (bytes_mac[0] << 40) + (bytes_mac[1] << 32) + (bytes_mac[2] << 24)
        + (bytes_mac[3] << 16) + (bytes_mac[4] << 8) + bytes_mac[5];

    return G_YES;
}

GResult NetWorkConv::macToBytes(const std::string& str_mac, GInt8 bytes_mac[6])
{
    std::list<std::string> split_list;
    IS_NO_R(Convert::splitString(str_mac, ':', split_list));
    IS_NO_RR(split_list.size() == 6, G_ERROR_INVALID_PARAMETERS);

    GUint16 i = 0;
    std::list<std::string>::iterator iter = split_list.begin();
    for (; iter != split_list.end(); ++iter)
    {
        bytes_mac[i] = std::stoul(*iter);
    }

    return G_YES;
}

GResult NetWorkConv::macToBytes(const GUint64 int_mac, GInt8 bytes_mac[6])
{
    bytes_mac[0] = (int_mac & 0xff000000) >> 40;
    bytes_mac[1] = (int_mac & 0xff000000) >> 32;
    bytes_mac[2] = (int_mac & 0xff000000) >> 24;
    bytes_mac[3] = (int_mac & 0xff000000) >> 16;
    bytes_mac[4] = (int_mac & 0xff000000) >> 8;
    bytes_mac[5] = (int_mac & 0xff000000);

    return G_YES;
}

GResult NetWorkConv::macToString(const GUint64 int_mac, std::string& str_mac)
{
    GInt8 tmp_buf[18] = {0};
    sprintf(tmp_buf, "%0x:%0x:%0x:%0x:%0x:%0x",
        (int_mac & 0xff000000) >> 24,
        (int_mac & 0x00ff0000) >> 16,
        (int_mac & 0x0000ff00) >> 8,
        (int_mac & 0x000000ff));

    Convert::toupper(tmp_buf);
    str_mac.assign(tmp_buf);

    return G_YES;
}

GResult NetWorkConv::macToString(GInt8 bytes_mac[6], std::string& str_mac)
{
    GInt8 tmp_buf[18] = {0};
    sprintf(tmp_buf, "%0x:%0x:%0x:%0x:%0x:%0x",
        bytes_mac[5], bytes_mac[4], bytes_mac[3], bytes_mac[2], bytes_mac[1], bytes_mac[0]);

    Convert::toupper(tmp_buf);
    str_mac.assign(tmp_buf);

    return G_YES;
}

IPAddr::IPAddr() : m_ip(0) {}

IPAddr::IPAddr(const GUint32 ip) : m_ip(ip)
{
    if (m_ip != 0)
    {
    	NetWorkConv::ipToString(m_ip, m_ipStr);
    }
}

IPAddr::IPAddr(const std::string& ip) : m_ip(0), m_ipStr(ip)
{
    if (!m_ipStr.empty())
    {
    	NetWorkConv::ipToInteger(m_ipStr, m_ip);
    }
}

IPAddr::~IPAddr() {}

void IPAddr::setIP(const GUint32 ip)
{
    m_ip = 0;
    m_ipStr.clear();

    if (ip != 0)
    {
    	m_ip = ip;
    	NetWorkConv::ipToString(m_ip, m_ipStr);
    }
}

void IPAddr::setIP(const std::string& ip)
{
    m_ip = 0;
    m_ipStr.clear();

    if (!ip.empty())
    {
    	m_ipStr = ip;
    	NetWorkConv::ipToInteger(m_ipStr, m_ip);
    }
}

GUint32 IPAddr::ip() const
{
    return m_ip;
}

const std::string& IPAddr::ipStr() const
{
    return m_ipStr;
}

MacAddr::MacAddr() : m_mac(0) {}

MacAddr::MacAddr(const GUint64 mac) : m_mac(mac)
{
    if (m_mac != 0)
    {
    	NetWorkConv::macToString(m_mac, m_macStr);
    }
}

MacAddr::MacAddr(const std::string& mac) : m_mac(0), m_macStr(mac)
{
    if (!m_macStr.empty())
    {
    	NetWorkConv::macToInteger(m_macStr, m_mac);
    }
}

void MacAddr::setMac(GUint64 mac)
{
    m_mac = 0;
    m_macStr.clear();

    if (mac != 0)
    {
    	m_mac = mac;
    	NetWorkConv::macToString(m_mac, m_macStr);
    }
}

void MacAddr::setMac(const std::string& mac)
{
    m_mac = 0;
    m_macStr.clear();

    if (!mac.empty())
    {
    	m_macStr = mac;
    	NetWorkConv::macToInteger(m_macStr, m_mac);
    }
}

GUint64 MacAddr::mac() const
{
    return m_mac;
}

const std::string& MacAddr::macStr() const
{
    return m_macStr;
}

IPPortPair::IPPortPair() : m_port(0) {}

IPPortPair::IPPortPair(const IPAddr& ip_addr, const GUint16 port)
    : m_ipAddr(ip_addr), m_port(port) {}

IPPortPair::~IPPortPair() {}

void IPPortPair::setIPAddr(const IPAddr& ip_addr)
{
    m_ipAddr = ip_addr;
}

const IPAddr& IPPortPair::ipAddr() const
{
    return m_ipAddr;
}

void IPPortPair::setPort(const GUint16 port)
{
    m_port = port;
}

GUint16 IPPortPair::port() const
{
    return m_port;
}

NetAddr::NetAddr() {}

NetAddr::NetAddr(const MacAddr mac_addr, const IPAddr& ip_addr, const GUint16 port)
    : m_macAddr(mac_addr), m_ip(ip_addr), m_port(port) {}

NetAddr::~NetAddr() {}

void NetAddr::setMacAddr(const MacAddr& mac_addr)
{
    m_macAddr = mac_addr;
}

const MacAddr& NetAddr::macAddr() const
{
    return m_macAddr;
}

void NetAddr::setIPAddr(const IPAddr& ip_addr)
{
    m_ip = ip_addr;
}

const IPAddr& NetAddr::ipAddr() const
{
    return m_ip;
}

void NetAddr::setPort(const GUint16 port)
{
    m_port = port;
}

GUint16 NetAddr::port() const
{
    return m_port;
}

SocketAddr::SocketAddr() {}

SocketAddr::SocketAddr(const NetAddr& src_addr, const NetAddr& dst_addr)
    : m_srcAddr(src_addr), m_dstAddr(dst_addr) {}

SocketAddr::~SocketAddr() {}

void SocketAddr::setSrcAddr(const NetAddr& src_addr)
{
    m_srcAddr = src_addr;
}

const NetAddr& SocketAddr::srcAddr() const
{
    return m_srcAddr;
}

void SocketAddr::setDstAddr(const NetAddr& dst_addr)
{
    m_dstAddr = dst_addr;
}

const NetAddr& SocketAddr::dstAddr() const
{
    return m_dstAddr;
}

}
<|endoftext|>


<commit_before>#include <iostream>

// legion stuff
#include "legion.h"
using namespace LegionRuntime::HighLevel;

#include "matrix.hpp"  // for Matrix  class
#include "hmatrix.hpp" // for HMatrix class

enum {
  TOP_LEVEL_TASK_ID = 0,
};

void top_level_task(const Task *task,
		    const std::vector<PhysicalRegion> &regions,
		    Context ctx, HighLevelRuntime *runtime) {

  Matrix b;
  Matrix U, V, D;

  // number of processes, or number of ranks as in MPI
  int nProc = 2;
  b.rand( nProc );
  U.rand( nProc );
  V.rand( nProc );
  D.rand( nProc );

  // fast solver
  HMatrix Ah( nProc );
  Ah.init( Rhs, U, V, D );
  Ah.solve();

  /*
  // direct solve
  Matrix A = U*V.transpose() + D;
  Vector x = A/Rhs;
  */
}

int main(int argc, char *argv[]) {
  // register top level task
  HighLevelRuntime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
  HighLevelRuntime::register_legion_task<top_level_task>(
    TOP_LEVEL_TASK_ID,   /* task id */
    Processor::LOC_PROC, /* cpu */
    true,  /* single */
    false, /* index  */
    AUTO_GENERATE_ID,
    TaskConfigOptions(false /*leaf task*/),
    "master-task"
  );

  // start legion master task
  return HighLevelRuntime::start(argc, argv);
}
<commit_msg>current solver interface<commit_after>#include <iostream>

// legion stuff
#include "legion.h"
using namespace LegionRuntime::HighLevel;

#include "matrix.hpp"  // for Matrix  class
#include "hmatrix.hpp" // for HMatrix class

enum {
  TOP_LEVEL_TASK_ID = 0,
};

void top_level_task(const Task *task,
		    const std::vector<PhysicalRegion> &regions,
		    Context ctx, HighLevelRuntime *runtime) {

  // ======= Problem configuration =======
  // solve: A x = b where A = U * V' + D
  // =====================================
  int N = 1<<10;
  int r = 30;
  Vector b(N);
  Matrix U(N, r);
  Matrix V(N, r);
  Vector D(N);

  // ================================================
  // generate random matrices, which could
  //  potentially be done in parallel
  // ================================================
  // number of processes, or number of ranks as in MPI
  int nProc = 2;
  b.rand( nProc );
  U.rand( nProc );
  V.rand( nProc );
  D.rand( nProc );

  // ========================================================
  // fast solver for a simple matrix U * V' + D
  //  where the off-diagonal blocks are exactly low rank,
  //  so the solve should be accurate (with round-off errors)
  // ========================================================
  // number of cores on each machine
  int nCore = 8;
  // number of levels for the (balanced) binary tree
  int level = 4;
  // assume one leaf every core for now
  assert( pow(2,level) == nProc*nCore );
  HMatrix Ah( nProc, nCore, level );
  Ah.init( Rhs, U, V, D );
  Ah.solve();

  /*
  // direct solve
  Matrix A = U*V.transpose() + D;
  Vector x = A/Rhs;
  */
}

int main(int argc, char *argv[]) {
  // register top level task
  HighLevelRuntime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
  HighLevelRuntime::register_legion_task<top_level_task>(
    TOP_LEVEL_TASK_ID,   /* task id */
    Processor::LOC_PROC, /* cpu */
    true,  /* single */
    false, /* index  */
    AUTO_GENERATE_ID,
    TaskConfigOptions(false /*leaf task*/),
    "master-task"
  );

  // start legion master task
  return HighLevelRuntime::start(argc, argv);
}
<|endoftext|>


<commit_before>/*This class takes joystick inputs and converts them to velocity in R3. */

JoyReader::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){
    ros::Rate loop_rate(rate);
    subscriber = n.subscribe("/joy", 1000, &ThrusterTortugaNode::thrusterCallBack, this);
    publisher = n.advertise<std_msgs::Float64MultiArray>("/g500/thrusters_input", 1000); //change /g500/thrusters_input to wherever it publishes to
}

JoyReader::~ThrusterTortugaNode(){}

void JoyReader::update(){
    ros::spinOnce();
}

void JoyReader::joyPub(const std_msgs::Float64MultiArray joyInput){

	float x = joyInput.data.axes[0]; /* Side-to-side, between -1 and +1 */
	float y = joyInput.data.axes[1]; /* Forward-Backward, between -1 and +1 */
	float z = -1*joyInput.data.axes[5]; /* -1,0, or +1, defining down as positive z-values */
	float mag = (joyInput.data.axes[3]+1)/2; /* Magnitude, from 0 to +1 */

	msg.layout.dim[0].label = "Input";
    msg.layout.dim[0].size = 4;
    msg.layout.dim[0].stride = 4;
	msg.data[0] = x;
	msg.data[1] = y;
    msg.data[2] = z;
    msg.data[3] = mag;

    publisher.publish(msg);
}

<commit_msg>Update JoyReader.cpp<commit_after>/*This class takes joystick inputs and converts them to velocity in R3. */

JoyReader::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){
    ros::Rate loop_rate(rate);
    subscriber = n.subscribe("/joy", 1000, &ThrusterTortugaNode::thrusterCallBack, this);
    publisher = n.advertise<std_msgs::Float64MultiArray>("/g500/thrusters_input", 1000); //change /g500/thrusters_input to wherever it publishes to
}

JoyReader::~ThrusterTortugaNode(){}

void JoyReader::update(){
    ros::spinOnce();
}

void JoyReader::joyPub(const std_msgs::Float64MultiArray joyInput){

	float x = joyInput.data.axes[0]; /* Side-to-side, between -1 and +1 */
	float y = joyInput.data.axes[1]; /* Forward-Backward, between -1 and +1 */
	float z = -1*joyInput.data.axes[5]; /* -1,0, or +1, defining down as positive z-values */
	float mag = (joyInput.data.axes[3]+1)/2; /* Magnitude, from 0 to +1 */

	msg.layout.dim[0].label = "Input";
	msg.layout.dim[0].size = 4;
   	msg.layout.dim[0].stride = 4;
	msg.data[0] = x;
	msg.data[1] = y;
    	msg.data[2] = z;
    	msg.data[3] = mag;

    publisher.publish(msg);
}

<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_manager_test
#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>

#include "kraken/data_manager.h"
#include <atomic>

//mock of navitia::type::Data class
class Data{
    public:
        bool load(const std::string&,
                  const boost::optional<std::string>&) {
            return load_status;
        }
        mutable std::atomic<bool> is_connected_to_rabbitmq;
        static bool load_status;
        static bool destructor_called;

        Data(){is_connected_to_rabbitmq = false;}

        ~Data(){Data::destructor_called = true;}
};
bool Data::load_status = true;
bool Data::destructor_called = false;

struct fixture{
    fixture(){
        Data::load_status = true;
        Data::destructor_called = false;
    }
};

BOOST_FIXTURE_TEST_SUITE(s, fixture)

BOOST_AUTO_TEST_CASE(get_data){
    DataManager<Data> data_manager;
    auto data = data_manager.get_data();
    BOOST_REQUIRE(data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_success){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    BOOST_CHECK(data_manager.load("",  {{""}}));
    auto second_data = data_manager.get_data();
    BOOST_CHECK_NE(first_data, second_data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_fail){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    Data::load_status = false;
    BOOST_CHECK(! data_manager.load("", {{""}}));
    Data::load_status = true;
    auto second_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, second_data);
}

BOOST_AUTO_TEST_CASE(destructor_called){
    DataManager<Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
        BOOST_CHECK(data_manager.load("", {{""}}));
        auto second_data = data_manager.get_data();
        BOOST_CHECK_NE(first_data, second_data);
        BOOST_CHECK_EQUAL(Data::destructor_called, false);
        first_data = boost::shared_ptr<Data>();
    }
    BOOST_CHECK_EQUAL(Data::destructor_called, true);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Kraken: fix init of chaos_database<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_manager_test
#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>

#include "kraken/data_manager.h"
#include <atomic>

//mock of navitia::type::Data class
class Data{
    public:
        bool load(const std::string&,
                  const boost::optional<std::string>&) {
            return load_status;
        }
        mutable std::atomic<bool> is_connected_to_rabbitmq;
        static bool load_status;
        static bool destructor_called;

        Data(){is_connected_to_rabbitmq = false;}

        ~Data(){Data::destructor_called = true;}
};
bool Data::load_status = true;
bool Data::destructor_called = false;

struct fixture{
    fixture(){
        Data::load_status = true;
        Data::destructor_called = false;
    }
};

BOOST_FIXTURE_TEST_SUITE(s, fixture)

BOOST_AUTO_TEST_CASE(get_data){
    DataManager<Data> data_manager;
    auto data = data_manager.get_data();
    BOOST_REQUIRE(data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_success){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    BOOST_CHECK(data_manager.load("",  {}));
    auto second_data = data_manager.get_data();
    BOOST_CHECK_NE(first_data, second_data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_fail){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    Data::load_status = false;
    BOOST_CHECK(! data_manager.load("", {}));
    Data::load_status = true;
    auto second_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, second_data);
}

BOOST_AUTO_TEST_CASE(destructor_called){
    DataManager<Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
        BOOST_CHECK(data_manager.load("", {}));
        auto second_data = data_manager.get_data();
        BOOST_CHECK_NE(first_data, second_data);
        BOOST_CHECK_EQUAL(Data::destructor_called, false);
        first_data = boost::shared_ptr<Data>();
    }
    BOOST_CHECK_EQUAL(Data::destructor_called, true);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before><commit_msg>Remove parse.cpp; no longer needed.<commit_after><|endoftext|>


<commit_before><commit_msg>pe212 finalized (very slow)<commit_after><|endoftext|>