<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef OPENCV_CORE_PRIVATE_CUDA_HPP
#define OPENCV_CORE_PRIVATE_CUDA_HPP

#ifndef __OPENCV_BUILD
#  error this is a private header which should not be used from outside of the OpenCV library
#endif

#include "cvconfig.h"

#include "opencv2/core/cvdef.h"
#include "opencv2/core/base.hpp"

#include "opencv2/core/cuda.hpp"

#ifdef HAVE_CUDA
#  include <cuda.h>
#  include <cuda_runtime.h>
#  if defined(__CUDACC_VER_MAJOR__) && (8 <= __CUDACC_VER_MAJOR__)
#    if defined (__GNUC__) && !defined(__CUDACC__)
#     pragma GCC diagnostic push
#     pragma GCC diagnostic ignored "-Wstrict-aliasing"
#     include <cuda_fp16.h>
#     pragma GCC diagnostic pop
#    else
#     include <cuda_fp16.h>
#    endif
#  endif // defined(__CUDACC_VER_MAJOR__) && (8 <= __CUDACC_VER_MAJOR__)
#  include <npp.h>
#  include "opencv2/core/cuda_stream_accessor.hpp"
#  include "opencv2/core/cuda/common.hpp"

#  define NPP_VERSION (NPP_VERSION_MAJOR * 1000 + NPP_VERSION_MINOR * 100 + NPP_VERSION_BUILD)

#  define CUDART_MINIMUM_REQUIRED_VERSION 6050

#  if (CUDART_VERSION < CUDART_MINIMUM_REQUIRED_VERSION)
#    error "Insufficient Cuda Runtime library version, please update it."
#  endif

#  if defined(CUDA_ARCH_BIN_OR_PTX_10)
#    error "OpenCV CUDA module doesn't support NVIDIA compute capability 1.0"
#  endif
#endif

//! @cond IGNORED

namespace cv { namespace cuda {
    CV_EXPORTS cv::String getNppErrorMessage(int code);
    CV_EXPORTS cv::String getCudaDriverApiErrorMessage(int code);

    CV_EXPORTS GpuMat getInputMat(InputArray _src, Stream& stream);

    CV_EXPORTS GpuMat getOutputMat(OutputArray _dst, int rows, int cols, int type, Stream& stream);
    static inline GpuMat getOutputMat(OutputArray _dst, Size size, int type, Stream& stream)
    {
        return getOutputMat(_dst, size.height, size.width, type, stream);
    }

    CV_EXPORTS void syncOutput(const GpuMat& dst, OutputArray _dst, Stream& stream);
}}

#ifndef HAVE_CUDA

static inline CV_NORETURN void throw_no_cuda() { CV_Error(cv::Error::GpuNotSupported, "The library is compiled without CUDA support"); }

#else // HAVE_CUDA

#define nppSafeSetStream(oldStream, newStream) { if(oldStream != newStream) { cudaStreamSynchronize(oldStream); nppSetStream(newStream); } }

static inline CV_NORETURN void throw_no_cuda() { CV_Error(cv::Error::StsNotImplemented, "The called functionality is disabled for current build or platform"); }

namespace cv { namespace cuda
{
    static inline void checkNppError(int code, const char* file, const int line, const char* func)
    {
        if (code < 0)
            cv::error(cv::Error::GpuApiCallError, getNppErrorMessage(code), func, file, line);
    }

    static inline void checkCudaDriverApiError(int code, const char* file, const int line, const char* func)
    {
        if (code != CUDA_SUCCESS)
            cv::error(cv::Error::GpuApiCallError, getCudaDriverApiErrorMessage(code), func, file, line);
    }

    template<int n> struct NPPTypeTraits;
    template<> struct NPPTypeTraits<CV_8U>  { typedef Npp8u npp_type; };
    template<> struct NPPTypeTraits<CV_8S>  { typedef Npp8s npp_type; };
    template<> struct NPPTypeTraits<CV_16U> { typedef Npp16u npp_type; };
    template<> struct NPPTypeTraits<CV_16S> { typedef Npp16s npp_type; };
    template<> struct NPPTypeTraits<CV_32S> { typedef Npp32s npp_type; };
    template<> struct NPPTypeTraits<CV_32F> { typedef Npp32f npp_type; };
    template<> struct NPPTypeTraits<CV_64F> { typedef Npp64f npp_type; };

    class NppStreamHandler
    {
    public:
        inline explicit NppStreamHandler(Stream& newStream)
        {
            oldStream = nppGetStream();
            nppSafeSetStream(oldStream, StreamAccessor::getStream(newStream));
        }

        inline explicit NppStreamHandler(cudaStream_t newStream)
        {
            oldStream = nppGetStream();
            nppSafeSetStream(oldStream, newStream);
        }

        inline ~NppStreamHandler()
        {
            nppSafeSetStream(nppGetStream(), oldStream);
        }

    private:
        cudaStream_t oldStream;
    };
}}

#define nppSafeCall(expr)  cv::cuda::checkNppError(expr, __FILE__, __LINE__, CV_Func)
#define cuSafeCall(expr)  cv::cuda::checkCudaDriverApiError(expr, __FILE__, __LINE__, CV_Func)

#endif // HAVE_CUDA

//! @endcond

#endif // OPENCV_CORE_PRIVATE_CUDA_HPP
<commit_msg>Fix compiler warnings for latest cuda npp which defines this itself as: ``` #define NPP_VER_MAJOR 10 #define NPP_VER_MINOR 2 #define NPP_VER_PATCH 0 #define NPP_VER_BUILD 243<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef OPENCV_CORE_PRIVATE_CUDA_HPP
#define OPENCV_CORE_PRIVATE_CUDA_HPP

#ifndef __OPENCV_BUILD
#  error this is a private header which should not be used from outside of the OpenCV library
#endif

#include "cvconfig.h"

#include "opencv2/core/cvdef.h"
#include "opencv2/core/base.hpp"

#include "opencv2/core/cuda.hpp"

#ifdef HAVE_CUDA
#  include <cuda.h>
#  include <cuda_runtime.h>
#  if defined(__CUDACC_VER_MAJOR__) && (8 <= __CUDACC_VER_MAJOR__)
#    if defined (__GNUC__) && !defined(__CUDACC__)
#     pragma GCC diagnostic push
#     pragma GCC diagnostic ignored "-Wstrict-aliasing"
#     include <cuda_fp16.h>
#     pragma GCC diagnostic pop
#    else
#     include <cuda_fp16.h>
#    endif
#  endif // defined(__CUDACC_VER_MAJOR__) && (8 <= __CUDACC_VER_MAJOR__)
#  include <npp.h>
#  include "opencv2/core/cuda_stream_accessor.hpp"
#  include "opencv2/core/cuda/common.hpp"

# ifndef NPP_VERSION
#  define NPP_VERSION (NPP_VERSION_MAJOR * 1000 + NPP_VERSION_MINOR * 100 + NPP_VERSION_BUILD)
# endif

#  define CUDART_MINIMUM_REQUIRED_VERSION 6050

#  if (CUDART_VERSION < CUDART_MINIMUM_REQUIRED_VERSION)
#    error "Insufficient Cuda Runtime library version, please update it."
#  endif

#  if defined(CUDA_ARCH_BIN_OR_PTX_10)
#    error "OpenCV CUDA module doesn't support NVIDIA compute capability 1.0"
#  endif
#endif

//! @cond IGNORED

namespace cv { namespace cuda {
    CV_EXPORTS cv::String getNppErrorMessage(int code);
    CV_EXPORTS cv::String getCudaDriverApiErrorMessage(int code);

    CV_EXPORTS GpuMat getInputMat(InputArray _src, Stream& stream);

    CV_EXPORTS GpuMat getOutputMat(OutputArray _dst, int rows, int cols, int type, Stream& stream);
    static inline GpuMat getOutputMat(OutputArray _dst, Size size, int type, Stream& stream)
    {
        return getOutputMat(_dst, size.height, size.width, type, stream);
    }

    CV_EXPORTS void syncOutput(const GpuMat& dst, OutputArray _dst, Stream& stream);
}}

#ifndef HAVE_CUDA

static inline CV_NORETURN void throw_no_cuda() { CV_Error(cv::Error::GpuNotSupported, "The library is compiled without CUDA support"); }

#else // HAVE_CUDA

#define nppSafeSetStream(oldStream, newStream) { if(oldStream != newStream) { cudaStreamSynchronize(oldStream); nppSetStream(newStream); } }

static inline CV_NORETURN void throw_no_cuda() { CV_Error(cv::Error::StsNotImplemented, "The called functionality is disabled for current build or platform"); }

namespace cv { namespace cuda
{
    static inline void checkNppError(int code, const char* file, const int line, const char* func)
    {
        if (code < 0)
            cv::error(cv::Error::GpuApiCallError, getNppErrorMessage(code), func, file, line);
    }

    static inline void checkCudaDriverApiError(int code, const char* file, const int line, const char* func)
    {
        if (code != CUDA_SUCCESS)
            cv::error(cv::Error::GpuApiCallError, getCudaDriverApiErrorMessage(code), func, file, line);
    }

    template<int n> struct NPPTypeTraits;
    template<> struct NPPTypeTraits<CV_8U>  { typedef Npp8u npp_type; };
    template<> struct NPPTypeTraits<CV_8S>  { typedef Npp8s npp_type; };
    template<> struct NPPTypeTraits<CV_16U> { typedef Npp16u npp_type; };
    template<> struct NPPTypeTraits<CV_16S> { typedef Npp16s npp_type; };
    template<> struct NPPTypeTraits<CV_32S> { typedef Npp32s npp_type; };
    template<> struct NPPTypeTraits<CV_32F> { typedef Npp32f npp_type; };
    template<> struct NPPTypeTraits<CV_64F> { typedef Npp64f npp_type; };

    class NppStreamHandler
    {
    public:
        inline explicit NppStreamHandler(Stream& newStream)
        {
            oldStream = nppGetStream();
            nppSafeSetStream(oldStream, StreamAccessor::getStream(newStream));
        }

        inline explicit NppStreamHandler(cudaStream_t newStream)
        {
            oldStream = nppGetStream();
            nppSafeSetStream(oldStream, newStream);
        }

        inline ~NppStreamHandler()
        {
            nppSafeSetStream(nppGetStream(), oldStream);
        }

    private:
        cudaStream_t oldStream;
    };
}}

#define nppSafeCall(expr)  cv::cuda::checkNppError(expr, __FILE__, __LINE__, CV_Func)
#define cuSafeCall(expr)  cv::cuda::checkCudaDriverApiError(expr, __FILE__, __LINE__, CV_Func)

#endif // HAVE_CUDA

//! @endcond

#endif // OPENCV_CORE_PRIVATE_CUDA_HPP
<|endoftext|>


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

#include "modules/planning/planner/rtk/rtk_replay_planner.h"

#include <fstream>

#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::ErrorCode;
using apollo::common::Status;

RTKReplayPlanner::RTKReplayPlanner() {
  ReadTrajectoryFile(FLAGS_rtk_trajectory_filename);
}

Status RTKReplayPlanner::Init(const PlanningConfig& config) {
  return Status::OK();
}

Status RTKReplayPlanner::MakePlan(const TrajectoryPoint& start_point,
                                  ADCTrajectory* trajectory_pb) {
  if (complete_rtk_trajectory_.empty() || complete_rtk_trajectory_.size() < 2) {
    std::string msg(
        "RTKReplayPlanner doesn't have a recorded trajectory or "
        "the recorded trajectory doesn't have enough valid trajectory "
        "points.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  std::uint32_t matched_index =
      QueryPositionMatchedPoint(start_point, complete_rtk_trajectory_);

  std::uint32_t forward_buffer = FLAGS_rtk_trajectory_forward;
  std::uint32_t end_index =
      matched_index + forward_buffer >= complete_rtk_trajectory_.size()
          ? complete_rtk_trajectory_.size() - 1
          : matched_index + forward_buffer - 1;

  auto* trajectory_points = trajectory_pb->mutable_trajectory_point();
  *trajectory_points = {complete_rtk_trajectory_.begin() + matched_index,
                        complete_rtk_trajectory_.begin() + end_index + 1};

  // reset relative time
  double zero_time = complete_rtk_trajectory_[matched_index].relative_time();
  for (auto& trajectory : *trajectory_points) {
    trajectory.set_relative_time(trajectory.relative_time() - zero_time);
  }

  // check if the trajectory has enough points;
  // if not, append the last points multiple times and
  // adjust their corresponding time stamps.
  while (trajectory_points->size() < FLAGS_rtk_trajectory_forward) {
    const auto& last_point = *trajectory_points->rbegin();
    auto* new_point = trajectory_points->Add();
    *new_point = last_point;
    new_point->set_relative_time(new_point->relative_time() +
                                 FLAGS_trajectory_resolution);
  }
  return Status::OK();
}

void RTKReplayPlanner::ReadTrajectoryFile(const std::string& filename) {
  if (!complete_rtk_trajectory_.empty()) {
    complete_rtk_trajectory_.clear();
  }

  std::ifstream file_in(filename.c_str());
  if (!file_in.is_open()) {
    AERROR << "RTKReplayPlanner cannot open trajectory file: " << filename;
    return;
  }

  std::string line;
  // skip the header line.
  getline(file_in, line);

  while (true) {
    getline(file_in, line);
    if (line == "") {
      break;
    }

    auto tokens = apollo::common::util::StringTokenizer::Split(line, "\t ");
    if (tokens.size() < 11) {
      AERROR << "RTKReplayPlanner parse line failed; the data dimension does "
                "not match.";
      AERROR << line;
      continue;
    }

    TrajectoryPoint point;
    point.mutable_path_point()->set_x(std::stod(tokens[0]));
    point.mutable_path_point()->set_y(std::stod(tokens[1]));
    point.mutable_path_point()->set_z(std::stod(tokens[2]));

    point.set_v(std::stod(tokens[3]));
    point.set_a(std::stod(tokens[4]));

    point.mutable_path_point()->set_kappa(std::stod(tokens[5]));
    point.mutable_path_point()->set_dkappa(std::stod(tokens[6]));

    point.set_relative_time(std::stod(tokens[7]));

    point.mutable_path_point()->set_theta(std::stod(tokens[8]));

    point.mutable_path_point()->set_s(std::stod(tokens[10]));
    complete_rtk_trajectory_.push_back(point);
  }

  file_in.close();
}

std::uint32_t RTKReplayPlanner::QueryPositionMatchedPoint(
    const TrajectoryPoint& start_point,
    const std::vector<TrajectoryPoint>& trajectory) const {
  auto func_distance_square = [](const TrajectoryPoint& point, const double x,
                                 const double y) {
    double dx = point.path_point().x() - x;
    double dy = point.path_point().y() - y;
    return dx * dx + dy * dy;
  };
  double d_min =
      func_distance_square(trajectory.front(), start_point.path_point().x(),
                           start_point.path_point().y());
  std::uint32_t index_min = 0;
  for (std::uint32_t i = 1; i < trajectory.size(); ++i) {
    double d_temp =
        func_distance_square(trajectory[i], start_point.path_point().x(),
                             start_point.path_point().y());
    if (d_temp < d_min) {
      d_min = d_temp;
      index_min = i;
    }
  }
  return index_min;
}

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

#include "modules/planning/planner/rtk/rtk_replay_planner.h"

#include <fstream>

#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::ErrorCode;
using apollo::common::Status;

RTKReplayPlanner::RTKReplayPlanner() {
  ReadTrajectoryFile(FLAGS_rtk_trajectory_filename);
}

Status RTKReplayPlanner::Init(const PlanningConfig& config) {
  return Status::OK();
}

Status RTKReplayPlanner::MakePlan(const TrajectoryPoint& start_point,
                                  ADCTrajectory* trajectory_pb) {
  if (complete_rtk_trajectory_.empty() || complete_rtk_trajectory_.size() < 2) {
    std::string msg(
        "RTKReplayPlanner doesn't have a recorded trajectory or "
        "the recorded trajectory doesn't have enough valid trajectory "
        "points.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  std::uint32_t matched_index =
      QueryPositionMatchedPoint(start_point, complete_rtk_trajectory_);

  std::uint32_t forward_buffer = FLAGS_rtk_trajectory_forward;
  std::uint32_t end_index =
      matched_index + forward_buffer >= complete_rtk_trajectory_.size()
          ? complete_rtk_trajectory_.size() - 1
          : matched_index + forward_buffer - 1;

  auto* trajectory_points = trajectory_pb->mutable_trajectory_point();
  *trajectory_points = {complete_rtk_trajectory_.begin() + matched_index,
                        complete_rtk_trajectory_.begin() + end_index + 1};

  // reset relative time
  double zero_time = complete_rtk_trajectory_[matched_index].relative_time();
  for (auto& trajectory : *trajectory_points) {
    trajectory.set_relative_time(trajectory.relative_time() - zero_time);
  }

  // check if the trajectory has enough points;
  // if not, append the last points multiple times and
  // adjust their corresponding time stamps.
  while (trajectory_points->size() <
         static_cast<int64_t>(FLAGS_rtk_trajectory_forward)) {
    const auto& last_point = *trajectory_points->rbegin();
    auto* new_point = trajectory_points->Add();
    *new_point = last_point;
    new_point->set_relative_time(new_point->relative_time() +
                                 FLAGS_trajectory_resolution);
  }
  return Status::OK();
}

void RTKReplayPlanner::ReadTrajectoryFile(const std::string& filename) {
  if (!complete_rtk_trajectory_.empty()) {
    complete_rtk_trajectory_.clear();
  }

  std::ifstream file_in(filename.c_str());
  if (!file_in.is_open()) {
    AERROR << "RTKReplayPlanner cannot open trajectory file: " << filename;
    return;
  }

  std::string line;
  // skip the header line.
  getline(file_in, line);

  while (true) {
    getline(file_in, line);
    if (line == "") {
      break;
    }

    auto tokens = apollo::common::util::StringTokenizer::Split(line, "\t ");
    if (tokens.size() < 11) {
      AERROR << "RTKReplayPlanner parse line failed; the data dimension does "
                "not match.";
      AERROR << line;
      continue;
    }

    TrajectoryPoint point;
    point.mutable_path_point()->set_x(std::stod(tokens[0]));
    point.mutable_path_point()->set_y(std::stod(tokens[1]));
    point.mutable_path_point()->set_z(std::stod(tokens[2]));

    point.set_v(std::stod(tokens[3]));
    point.set_a(std::stod(tokens[4]));

    point.mutable_path_point()->set_kappa(std::stod(tokens[5]));
    point.mutable_path_point()->set_dkappa(std::stod(tokens[6]));

    point.set_relative_time(std::stod(tokens[7]));

    point.mutable_path_point()->set_theta(std::stod(tokens[8]));

    point.mutable_path_point()->set_s(std::stod(tokens[10]));
    complete_rtk_trajectory_.push_back(point);
  }

  file_in.close();
}

std::uint32_t RTKReplayPlanner::QueryPositionMatchedPoint(
    const TrajectoryPoint& start_point,
    const std::vector<TrajectoryPoint>& trajectory) const {
  auto func_distance_square = [](const TrajectoryPoint& point, const double x,
                                 const double y) {
    double dx = point.path_point().x() - x;
    double dy = point.path_point().y() - y;
    return dx * dx + dy * dy;
  };
  double d_min =
      func_distance_square(trajectory.front(), start_point.path_point().x(),
                           start_point.path_point().y());
  std::uint32_t index_min = 0;
  for (std::uint32_t i = 1; i < trajectory.size(); ++i) {
    double d_temp =
        func_distance_square(trajectory[i], start_point.path_point().x(),
                             start_point.path_point().y());
    if (d_temp < d_min) {
      d_min = d_temp;
      index_min = i;
    }
  }
  return index_min;
}

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


<commit_before><commit_msg>Changed mind: not binding Allegro, it's C already - moving to extras<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2016 Intel Corporation
 *
 * 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "bitWriter.h"
#include "common/log.h"
#include <assert.h>

namespace YamiParser {

const uint32_t CACHEBYTES = sizeof(unsigned long int);
const uint32_t CACHEBITS = sizeof(unsigned long int) * 8;

// clip to keep lowest n bits
#define CLIPBITS(value, n) ((value) & ((1 << (n)) - 1));

BitWriter::BitWriter(uint32_t size)
    : m_cache(0)
    , m_bitsInCache(0)
{
    m_bs.reserve(size);
}

uint8_t* BitWriter::getBitWriterData()
{
    uint8_t* buf;
    flushCache();

    buf = m_bs.size() ? static_cast<uint8_t*>(&m_bs[0]) : NULL;
    return buf;
}

void BitWriter::flushCache()
{
    uint8_t tmp, i, bytesInCache;

    // make sure m_bitsInCache is byte aligned, else trailing bits should be
    // padded
    if (m_bitsInCache % 8)
        writeToBytesAligned();

    assert(!(m_bitsInCache % 8));

    bytesInCache = m_bitsInCache / 8;

    for (i = 0; i < bytesInCache; i++) {
        tmp = static_cast<uint8_t>(m_cache >> (m_bitsInCache - (i + 1) * 8));
        m_bs.push_back(tmp);
    }

    m_cache = 0;
    m_bitsInCache = 0;
}

bool BitWriter::writeBits(uint32_t value, uint32_t numBits)
{
    if (value >= (uint64_t)1 << numBits) {
        ERROR("Write Bits Error: value overflow");
        return false;
    }

    ASSERT((m_bitsInCache <= CACHEBITS) && (numBits <= CACHEBITS));

    uint32_t bitLeft = CACHEBITS - m_bitsInCache;

    if (bitLeft > numBits) {
        m_cache = (m_cache << numBits | value);
        m_bitsInCache += numBits;
    } else {
        m_cache = ((m_cache << bitLeft) | (value >> (numBits - bitLeft)));
        m_bitsInCache = CACHEBITS;
        flushCache();
        m_cache = value;
        m_bitsInCache = numBits - bitLeft;
    }

    return true;
}

bool BitWriter::writeBytes(uint8_t* data, uint32_t numBytes)
{
    if (!data || !numBytes)
        return false;

    if ((m_bitsInCache % 8) == 0) {
        flushCache();
        m_bs.insert(m_bs.end(), data, data + numBytes);
    } else {
        for (uint32_t i = 0; i < numBytes; i++)
            writeBits(data[i], 8);
    }

    return true;
}

void BitWriter::writeToBytesAligned(bool bit)
{
    uint8_t padBits = m_bitsInCache & 0x7;
    uint32_t value;
    if (padBits) {
        if (bit)
            value = (1 << (8 - padBits)) - 1;
        else
            value = 0;
        writeBits(value, 8 - padBits);
    }
}

} /*namespace YamiParser*/
<commit_msg>bitWriter: don't return false when overflow<commit_after>/*
 * Copyright 2016 Intel Corporation
 *
 * 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "bitWriter.h"
#include "common/log.h"
#include <assert.h>

namespace YamiParser {

const uint32_t CACHEBYTES = sizeof(unsigned long int);
const uint32_t CACHEBITS = sizeof(unsigned long int) * 8;

// clip to keep lowest n bits
#define CLIPBITS(value, n) ((value) & ((1 << (n)) - 1));

BitWriter::BitWriter(uint32_t size)
    : m_cache(0)
    , m_bitsInCache(0)
{
    m_bs.reserve(size);
}

uint8_t* BitWriter::getBitWriterData()
{
    uint8_t* buf;
    flushCache();

    buf = m_bs.size() ? static_cast<uint8_t*>(&m_bs[0]) : NULL;
    return buf;
}

void BitWriter::flushCache()
{
    uint8_t tmp, i, bytesInCache;

    // make sure m_bitsInCache is byte aligned, else trailing bits should be
    // padded
    if (m_bitsInCache % 8)
        writeToBytesAligned();

    assert(!(m_bitsInCache % 8));

    bytesInCache = m_bitsInCache / 8;

    for (i = 0; i < bytesInCache; i++) {
        tmp = static_cast<uint8_t>(m_cache >> (m_bitsInCache - (i + 1) * 8));
        m_bs.push_back(tmp);
    }

    m_cache = 0;
    m_bitsInCache = 0;
}

bool BitWriter::writeBits(uint32_t value, uint32_t numBits)
{
    if (value >= (uint64_t)1 << numBits) {
        WARNING("Write Bits: value overflow");
    }

    ASSERT((m_bitsInCache <= CACHEBITS) && (numBits <= CACHEBITS));

    uint32_t bitLeft = CACHEBITS - m_bitsInCache;

    if (bitLeft > numBits) {
        m_cache = (m_cache << numBits | value);
        m_bitsInCache += numBits;
    } else {
        m_cache = ((m_cache << bitLeft) | (value >> (numBits - bitLeft)));
        m_bitsInCache = CACHEBITS;
        flushCache();
        m_cache = value;
        m_bitsInCache = numBits - bitLeft;
    }

    return true;
}

bool BitWriter::writeBytes(uint8_t* data, uint32_t numBytes)
{
    if (!data || !numBytes)
        return false;

    if ((m_bitsInCache % 8) == 0) {
        flushCache();
        m_bs.insert(m_bs.end(), data, data + numBytes);
    } else {
        for (uint32_t i = 0; i < numBytes; i++)
            writeBits(data[i], 8);
    }

    return true;
}

void BitWriter::writeToBytesAligned(bool bit)
{
    uint8_t padBits = m_bitsInCache & 0x7;
    uint32_t value;
    if (padBits) {
        if (bit)
            value = (1 << (8 - padBits)) - 1;
        else
            value = 0;
        writeBits(value, 8 - padBits);
    }
}

} /*namespace YamiParser*/
<|endoftext|>


<commit_before>#include "clay.hpp"

namespace two {

PValuePtr staticPValue(ObjectPtr x);
PValuePtr kernelPValue(const string &name);

MultiPValuePtr analyzeMulti(const vector<ExprPtr> &exprs, EnvPtr env);
PValuePtr analyzeOne(ExprPtr expr, EnvPtr env);
MultiPValuePtr analyzeExpr(ExprPtr expr, EnvPtr env);
MultiPValuePtr analyzeStaticObject(ObjectPtr x);
PValuePtr analyzeGlobalVariable(GlobalVariablePtr x);
PValuePtr analyzeExternalVariable(ExternalVariablePtr x);
void analyzeExternalProcedure(ExternalProcedurePtr x);
MultiPValuePtr analyzeIndexingExpr(ExprPtr indexable,
                                   const vector<ExprPtr> &args,
                                   EnvPtr env);
MultiPValuePtr analyzeFieldRefExpr(ExprPtr base,
                                   IdentifierPtr name,
                                   EnvPtr env);
MultiPValuePtr analyzeCallExpr(ExprPtr callable,
                               const vector<ExprPtr> &args,
                               EnvPtr env);

MultiPValuePtr analyzeCallValue(PValuePtr callable,
                                MultiPValuePtr args);

//
// staticPValue, kernelPValue
//

PValuePtr staticPValue(ObjectPtr x)
{
    TypePtr t = staticType(x);
    return new PValue(t, true);
}

PValuePtr kernelPValue(const string &name)
{
    return staticPValue(kernelName(name));
}

//
// analyzeMulti
//

MultiPValuePtr analyzeMulti(const vector<ExprPtr> &exprs, EnvPtr env)
{
    MultiPValuePtr out = new MultiPValue();
    for (unsigned i = 0; i < exprs.size(); ++i) {
        ExprPtr x = exprs[i];
        if (x->exprKind == VAR_ARGS_REF) {
            MultiPValuePtr y = analyzeExpr(x, env);
            if (!y)
                return NULL;
            out->values.insert(out->values.end(),
                               y->values.begin(),
                               y->values.end());
        }
        else {
            PValuePtr y = two::analyzeOne(x, env);
            if (!y)
                return NULL;
            out->values.push_back(y);
        }
    }
    return out;
}

//
// analyzeOne
//

PValuePtr analyzeOne(ExprPtr expr, EnvPtr env)
{
    MultiPValuePtr x = analyzeExpr(expr, env);
    if (!x)
        return NULL;
    if (x->size() != 1)
        arityError(expr, 1, x->size());
    return x->values[0];
}

//
// analyzeExpr
//

MultiPValuePtr analyzeExpr(ExprPtr expr, EnvPtr env)
{
    switch (expr->exprKind) {

    case BOOL_LITERAL : {
        return new MultiPValue(new PValue(boolType, true));
    }

    case INT_LITERAL : {
        IntLiteral *x = (IntLiteral *)expr.ptr();
        ValueHolderPtr v = parseIntLiteral(x);
        return new MultiPValue(new PValue(v->type, true));
    }

    case FLOAT_LITERAL : {
        FloatLiteral *x = (FloatLiteral *)expr.ptr();
        ValueHolderPtr v = parseFloatLiteral(x);
        return new MultiPValue(new PValue(v->type, true));
    }

    case CHAR_LITERAL : {
        CharLiteral *x = (CharLiteral *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarCharLiteral(x->value);
        return analyzeExpr(x->desugared, env);
    }

    case STRING_LITERAL : {
        StringLiteral *x = (StringLiteral *)expr.ptr();
        PValuePtr pv = new PValue(arrayType(int8Type, x->value.size()), true);
        MultiPValuePtr args = new MultiPValue(pv);
        return analyzeCallValue(kernelPValue("stringRef"), args);
    }

    case NAME_REF : {
        NameRef *x = (NameRef *)expr.ptr();
        ObjectPtr y = lookupEnv(env, x->name);
        if (y->objKind == EXPRESSION)
            return analyzeExpr((Expr *)y.ptr(), env);
        return two::analyzeStaticObject(y);
    }

    case TUPLE : {
        Tuple *x = (Tuple *)expr.ptr();
        if ((x->args.size() == 1) &&
            (x->args[0]->exprKind != VAR_ARGS_REF))
        {
            return analyzeExpr(x->args[0], env);
        }
        return analyzeCallExpr(primNameRef("tuple"), x->args, env);
    }

    case ARRAY : {
        Array *x = (Array *)expr.ptr();
        return analyzeCallExpr(primNameRef("array"), x->args, env);
    }

    case INDEXING : {
        Indexing *x = (Indexing *)expr.ptr();
        return analyzeIndexingExpr(x->expr, x->args, env);
    }

    case CALL : {
        Call *x = (Call *)expr.ptr();
        return analyzeCallExpr(x->expr, x->args, env);
    }

    case FIELD_REF : {
        FieldRef *x = (FieldRef *)expr.ptr();
        return analyzeFieldRefExpr(x->expr, x->name, env);
    }

    case TUPLE_REF : {
        TupleRef *x = (TupleRef *)expr.ptr();
        PValuePtr pv = two::analyzeOne(x->expr, env);
        if (!pv)
            return NULL;
        MultiPValuePtr args = new MultiPValue(pv);
        ValueHolderPtr vh = sizeTToValueHolder(x->index);
        args->values.push_back(staticPValue(vh.ptr()));
        return analyzeCallValue(kernelPValue("tupleRef"), args);
    }

    case UNARY_OP : {
        UnaryOp *x = (UnaryOp *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarUnaryOp(x);
        return analyzeExpr(x->desugared, env);
    }

    case BINARY_OP : {
        BinaryOp *x = (BinaryOp *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarBinaryOp(x);
        return analyzeExpr(x->desugared, env);
    }

    case AND : {
        And *x = (And *)expr.ptr();
        PValuePtr a = two::analyzeOne(x->expr1, env);
        if (!a)
            return NULL;
        if (a->isTemp)
            return new MultiPValue(new PValue(a->type, true));
        PValuePtr b = two::analyzeOne(x->expr2, env);
        if (!b)
            return NULL;
        if (a->type != b->type)
            error("type mismatch in 'and' expression");
        PValuePtr pv = new PValue(a->type, a->isTemp || b->isTemp);
        return new MultiPValue(pv);
    }

    case OR : {
        Or *x = (Or *)expr.ptr();
        PValuePtr a = two::analyzeOne(x->expr1, env);
        if (!a)
            return NULL;
        if (a->isTemp)
            return new MultiPValue(new PValue(a->type, true));
        PValuePtr b = two::analyzeOne(x->expr2, env);
        if (!b)
            return NULL;
        if (a->type != b->type)
            error("type mismatch in 'and' expression");
        PValuePtr pv = new PValue(a->type, a->isTemp || b->isTemp);
        return new MultiPValue(pv);
    }

    case LAMBDA : {
        Lambda *x = (Lambda *)expr.ptr();
        if (!x->initialized)
            initializeLambda(x, env);
        return analyzeExpr(x->converted, env);
    }

    case VAR_ARGS_REF : {
        ObjectPtr y = lookupEnv(env, new Identifier("%varArgs"));
        VarArgsInfo *vaInfo = (VarArgsInfo *)y.ptr();
        if (!vaInfo->hasVarArgs)
            error("varargs unavailable");
        return analyzeMulti(vaInfo->varArgs, env);
    }

    case NEW : {
        New *x = (New *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarNew(x);
        return analyzeExpr(x->desugared, env);
    }

    case STATIC_EXPR : {
        StaticExpr *x = (StaticExpr *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarStaticExpr(x);
        return analyzeExpr(x->desugared, env);
    }

    case FOREIGN_EXPR : {
        ForeignExpr *x = (ForeignExpr *)expr.ptr();
        return analyzeExpr(x->expr, x->getEnv());
    }

    case OBJECT_EXPR : {
        error("ObjectExpr deprecated");
    }

    default :
        assert(false);
        return NULL;

    }
}

//
// analyzeStaticObject
//

MultiPValuePtr analyzeStaticObject(ObjectPtr x)
{
    switch (x->objKind) {

    case ENUM_MEMBER : {
        EnumMember *y = (EnumMember *)x.ptr();
        PValuePtr pv = new PValue(y->type, true);
        return new MultiPValue(pv);
    }

    case GLOBAL_VARIABLE : {
        GlobalVariable *y = (GlobalVariable *)x.ptr();
        PValuePtr pv = analyzeGlobalVariable(y);
        return new MultiPValue(pv);
    }

    case EXTERNAL_VARIABLE : {
        ExternalVariable *y = (ExternalVariable *)x.ptr();
        PValuePtr pv = analyzeExternalVariable(y);
        return new MultiPValue(pv);
    }

    case EXTERNAL_PROCEDURE : {
        ExternalProcedure *y = (ExternalProcedure *)x.ptr();
        analyzeExternalProcedure(y);
        PValuePtr pv = new PValue(y->ptrType, true);
        return new MultiPValue(pv);
    }

    case STATIC_GLOBAL : {
        StaticGlobal *y = (StaticGlobal *)x.ptr();
        return analyzeExpr(y->expr, y->env);
    }

    case EVALUE : {
        EValue *y = (EValue *)x.ptr();
        PValuePtr pv = new PValue(y->type, false);
        return new MultiPValue(pv);
    }

    case MULTI_EVALUE : {
        MultiEValue *y = (MultiEValue *)x.ptr();
        MultiPValuePtr z = new MultiPValue();
        for (unsigned i = 0; i < y->values.size(); ++i)
            z->values.push_back(new PValue(y->values[i]->type, false));
        return z;
    }

    case CVALUE : {
        CValue *y = (CValue *)x.ptr();
        PValuePtr pv = new PValue(y->type, false);
        return new MultiPValue(pv);
    }

    case MULTI_CVALUE : {
        MultiCValue *y = (MultiCValue *)x.ptr();
        MultiPValuePtr z = new MultiPValue();
        for (unsigned i = 0; i < y->values.size(); ++i)
            z->values.push_back(new PValue(y->values[i]->type, false));
        return z;
    }

    case PVALUE : {
        PValue *y = (PValue *)x.ptr();
        return new MultiPValue(y);
    }

    case MULTI_PVALUE : {
        MultiPValue *y = (MultiPValue *)x.ptr();
        return y;
    }

    case VALUE_HOLDER : {
        ValueHolder *y = (ValueHolder *)x.ptr();
        PValuePtr pv = new PValue(y->type, true);
        return new MultiPValue(pv);
    }

    case MULTI_STATIC : {
        MultiStatic *y = (MultiStatic *)x.ptr();
        MultiPValuePtr mpv = new MultiPValue();
        for (unsigned i = 0; i < y->size(); ++i) {
            TypePtr t = objectType(y->values[i]);
            mpv->values.push_back(new PValue(t, true));
        }
        return mpv;
    }

    case TYPE :
    case PRIM_OP :
    case PROCEDURE :
    case RECORD :
    case MODULE_HOLDER :
    case IDENTIFIER : {
        TypePtr t = staticType(x);
        PValuePtr pv = new PValue(t, true);
        return new MultiPValue(pv);
    }

    case PATTERN :
        error("pattern cannot be used as value");
        return NULL;

    default :
        error("invalid static object");
        return NULL;

    }
}

//
// analyzeGlobalVariable
//

PValuePtr analyzeGlobalVariable(GlobalVariablePtr x)
{
    if (!x->type) {
        if (x->analyzing)
            return NULL;
        x->analyzing = true;
        PValuePtr pv = two::analyzeOne(x->expr, x->env);
        x->analyzing = false;
        if (!pv)
            return NULL;
        x->type = pv->type;
    }
    return new PValue(x->type, false);
}

//
// analyzeExternalVariable
//

PValuePtr analyzeExternalVariable(ExternalVariablePtr x)
{
    if (!x->type2)
        x->type2 = evaluateType(x->type, x->env);
    return new PValue(x->type2, false);
}

//
// analyzeExternalProcedure
//

void analyzeExternalProcedure(ExternalProcedurePtr x)
{
    if (x->analyzed)
        return;
    if (!x->attributesVerified)
        verifyAttributes(x);
    vector<TypePtr> argTypes;
    for (unsigned i = 0; i < x->args.size(); ++i) {
        ExternalArgPtr y = x->args[i];
        y->type2 = evaluateType(y->type, x->env);
        argTypes.push_back(y->type2);
    }
    if (!x->returnType)
        x->returnType2 = NULL;
    else
        x->returnType2 = evaluateType(x->returnType, x->env);
    CallingConv callingConv = CC_DEFAULT;
    if (x->attrStdCall)
        callingConv = CC_STDCALL;
    else if (x->attrFastCall)
        callingConv = CC_FASTCALL;
    x->ptrType = cCodePointerType(callingConv, argTypes,
                                  x->hasVarArgs, x->returnType2);
    x->analyzed = true;
}

//
// analyzeIndexingExpr
//

MultiPValuePtr analyzeIndexingExpr(ExprPtr indexable,
                                   const vector<ExprPtr> &args,
                                   EnvPtr env)
{
    return NULL;
}

//
// analyzeFieldRefExpr
//

MultiPValuePtr analyzeFieldRefExpr(ExprPtr base,
                                   IdentifierPtr name,
                                   EnvPtr env)
{
    return NULL;
}

//
// analyzeCallExpr
//

MultiPValuePtr analyzeCallExpr(ExprPtr callable,
                               const vector<ExprPtr> &args,
                               EnvPtr env)
{
    return NULL;
}

//
// analyzeCallValue
//

MultiPValuePtr analyzeCallValue(PValuePtr callable,
                                MultiPValuePtr args)
{
    return NULL;
}

}
<commit_msg>minor change in new analyzer.<commit_after>#include "clay.hpp"

namespace two {

MultiPValuePtr analyzeMulti(const vector<ExprPtr> &exprs, EnvPtr env);
PValuePtr analyzeOne(ExprPtr expr, EnvPtr env);
MultiPValuePtr analyzeExpr(ExprPtr expr, EnvPtr env);
MultiPValuePtr analyzeStaticObject(ObjectPtr x);
PValuePtr analyzeGlobalVariable(GlobalVariablePtr x);
PValuePtr analyzeExternalVariable(ExternalVariablePtr x);
void analyzeExternalProcedure(ExternalProcedurePtr x);
MultiPValuePtr analyzeIndexingExpr(ExprPtr indexable,
                                   const vector<ExprPtr> &args,
                                   EnvPtr env);
MultiPValuePtr analyzeFieldRefExpr(ExprPtr base,
                                   IdentifierPtr name,
                                   EnvPtr env);
MultiPValuePtr analyzeCallExpr(ExprPtr callable,
                               const vector<ExprPtr> &args,
                               EnvPtr env);

MultiPValuePtr analyzeCallValue(PValuePtr callable,
                                MultiPValuePtr args);

//
// staticPValue, kernelPValue
//

static PValuePtr staticPValue(ObjectPtr x)
{
    TypePtr t = staticType(x);
    return new PValue(t, true);
}

static PValuePtr kernelPValue(const string &name)
{
    return staticPValue(kernelName(name));
}

//
// analyzeMulti
//

MultiPValuePtr analyzeMulti(const vector<ExprPtr> &exprs, EnvPtr env)
{
    MultiPValuePtr out = new MultiPValue();
    for (unsigned i = 0; i < exprs.size(); ++i) {
        ExprPtr x = exprs[i];
        if (x->exprKind == VAR_ARGS_REF) {
            MultiPValuePtr y = analyzeExpr(x, env);
            if (!y)
                return NULL;
            out->values.insert(out->values.end(),
                               y->values.begin(),
                               y->values.end());
        }
        else {
            PValuePtr y = two::analyzeOne(x, env);
            if (!y)
                return NULL;
            out->values.push_back(y);
        }
    }
    return out;
}

//
// analyzeOne
//

PValuePtr analyzeOne(ExprPtr expr, EnvPtr env)
{
    MultiPValuePtr x = analyzeExpr(expr, env);
    if (!x)
        return NULL;
    if (x->size() != 1)
        arityError(expr, 1, x->size());
    return x->values[0];
}

//
// analyzeExpr
//

MultiPValuePtr analyzeExpr(ExprPtr expr, EnvPtr env)
{
    switch (expr->exprKind) {

    case BOOL_LITERAL : {
        return new MultiPValue(new PValue(boolType, true));
    }

    case INT_LITERAL : {
        IntLiteral *x = (IntLiteral *)expr.ptr();
        ValueHolderPtr v = parseIntLiteral(x);
        return new MultiPValue(new PValue(v->type, true));
    }

    case FLOAT_LITERAL : {
        FloatLiteral *x = (FloatLiteral *)expr.ptr();
        ValueHolderPtr v = parseFloatLiteral(x);
        return new MultiPValue(new PValue(v->type, true));
    }

    case CHAR_LITERAL : {
        CharLiteral *x = (CharLiteral *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarCharLiteral(x->value);
        return analyzeExpr(x->desugared, env);
    }

    case STRING_LITERAL : {
        StringLiteral *x = (StringLiteral *)expr.ptr();
        PValuePtr pv = new PValue(arrayType(int8Type, x->value.size()), true);
        MultiPValuePtr args = new MultiPValue(pv);
        return analyzeCallValue(kernelPValue("stringRef"), args);
    }

    case NAME_REF : {
        NameRef *x = (NameRef *)expr.ptr();
        ObjectPtr y = lookupEnv(env, x->name);
        if (y->objKind == EXPRESSION)
            return analyzeExpr((Expr *)y.ptr(), env);
        return two::analyzeStaticObject(y);
    }

    case TUPLE : {
        Tuple *x = (Tuple *)expr.ptr();
        if ((x->args.size() == 1) &&
            (x->args[0]->exprKind != VAR_ARGS_REF))
        {
            return analyzeExpr(x->args[0], env);
        }
        return analyzeCallExpr(primNameRef("tuple"), x->args, env);
    }

    case ARRAY : {
        Array *x = (Array *)expr.ptr();
        return analyzeCallExpr(primNameRef("array"), x->args, env);
    }

    case INDEXING : {
        Indexing *x = (Indexing *)expr.ptr();
        return analyzeIndexingExpr(x->expr, x->args, env);
    }

    case CALL : {
        Call *x = (Call *)expr.ptr();
        return analyzeCallExpr(x->expr, x->args, env);
    }

    case FIELD_REF : {
        FieldRef *x = (FieldRef *)expr.ptr();
        return analyzeFieldRefExpr(x->expr, x->name, env);
    }

    case TUPLE_REF : {
        TupleRef *x = (TupleRef *)expr.ptr();
        PValuePtr pv = two::analyzeOne(x->expr, env);
        if (!pv)
            return NULL;
        MultiPValuePtr args = new MultiPValue(pv);
        ValueHolderPtr vh = sizeTToValueHolder(x->index);
        args->values.push_back(staticPValue(vh.ptr()));
        return analyzeCallValue(kernelPValue("tupleRef"), args);
    }

    case UNARY_OP : {
        UnaryOp *x = (UnaryOp *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarUnaryOp(x);
        return analyzeExpr(x->desugared, env);
    }

    case BINARY_OP : {
        BinaryOp *x = (BinaryOp *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarBinaryOp(x);
        return analyzeExpr(x->desugared, env);
    }

    case AND : {
        And *x = (And *)expr.ptr();
        PValuePtr a = two::analyzeOne(x->expr1, env);
        if (!a)
            return NULL;
        if (a->isTemp)
            return new MultiPValue(new PValue(a->type, true));
        PValuePtr b = two::analyzeOne(x->expr2, env);
        if (!b)
            return NULL;
        if (a->type != b->type)
            error("type mismatch in 'and' expression");
        PValuePtr pv = new PValue(a->type, a->isTemp || b->isTemp);
        return new MultiPValue(pv);
    }

    case OR : {
        Or *x = (Or *)expr.ptr();
        PValuePtr a = two::analyzeOne(x->expr1, env);
        if (!a)
            return NULL;
        if (a->isTemp)
            return new MultiPValue(new PValue(a->type, true));
        PValuePtr b = two::analyzeOne(x->expr2, env);
        if (!b)
            return NULL;
        if (a->type != b->type)
            error("type mismatch in 'and' expression");
        PValuePtr pv = new PValue(a->type, a->isTemp || b->isTemp);
        return new MultiPValue(pv);
    }

    case LAMBDA : {
        Lambda *x = (Lambda *)expr.ptr();
        if (!x->initialized)
            initializeLambda(x, env);
        return analyzeExpr(x->converted, env);
    }

    case VAR_ARGS_REF : {
        ObjectPtr y = lookupEnv(env, new Identifier("%varArgs"));
        VarArgsInfo *vaInfo = (VarArgsInfo *)y.ptr();
        if (!vaInfo->hasVarArgs)
            error("varargs unavailable");
        return analyzeMulti(vaInfo->varArgs, env);
    }

    case NEW : {
        New *x = (New *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarNew(x);
        return analyzeExpr(x->desugared, env);
    }

    case STATIC_EXPR : {
        StaticExpr *x = (StaticExpr *)expr.ptr();
        if (!x->desugared)
            x->desugared = desugarStaticExpr(x);
        return analyzeExpr(x->desugared, env);
    }

    case FOREIGN_EXPR : {
        ForeignExpr *x = (ForeignExpr *)expr.ptr();
        return analyzeExpr(x->expr, x->getEnv());
    }

    case OBJECT_EXPR : {
        error("ObjectExpr deprecated");
    }

    default :
        assert(false);
        return NULL;

    }
}

//
// analyzeStaticObject
//

MultiPValuePtr analyzeStaticObject(ObjectPtr x)
{
    switch (x->objKind) {

    case ENUM_MEMBER : {
        EnumMember *y = (EnumMember *)x.ptr();
        PValuePtr pv = new PValue(y->type, true);
        return new MultiPValue(pv);
    }

    case GLOBAL_VARIABLE : {
        GlobalVariable *y = (GlobalVariable *)x.ptr();
        PValuePtr pv = analyzeGlobalVariable(y);
        return new MultiPValue(pv);
    }

    case EXTERNAL_VARIABLE : {
        ExternalVariable *y = (ExternalVariable *)x.ptr();
        PValuePtr pv = analyzeExternalVariable(y);
        return new MultiPValue(pv);
    }

    case EXTERNAL_PROCEDURE : {
        ExternalProcedure *y = (ExternalProcedure *)x.ptr();
        analyzeExternalProcedure(y);
        PValuePtr pv = new PValue(y->ptrType, true);
        return new MultiPValue(pv);
    }

    case STATIC_GLOBAL : {
        StaticGlobal *y = (StaticGlobal *)x.ptr();
        return analyzeExpr(y->expr, y->env);
    }

    case EVALUE : {
        EValue *y = (EValue *)x.ptr();
        PValuePtr pv = new PValue(y->type, false);
        return new MultiPValue(pv);
    }

    case MULTI_EVALUE : {
        MultiEValue *y = (MultiEValue *)x.ptr();
        MultiPValuePtr z = new MultiPValue();
        for (unsigned i = 0; i < y->values.size(); ++i)
            z->values.push_back(new PValue(y->values[i]->type, false));
        return z;
    }

    case CVALUE : {
        CValue *y = (CValue *)x.ptr();
        PValuePtr pv = new PValue(y->type, false);
        return new MultiPValue(pv);
    }

    case MULTI_CVALUE : {
        MultiCValue *y = (MultiCValue *)x.ptr();
        MultiPValuePtr z = new MultiPValue();
        for (unsigned i = 0; i < y->values.size(); ++i)
            z->values.push_back(new PValue(y->values[i]->type, false));
        return z;
    }

    case PVALUE : {
        PValue *y = (PValue *)x.ptr();
        return new MultiPValue(y);
    }

    case MULTI_PVALUE : {
        MultiPValue *y = (MultiPValue *)x.ptr();
        return y;
    }

    case VALUE_HOLDER : {
        ValueHolder *y = (ValueHolder *)x.ptr();
        PValuePtr pv = new PValue(y->type, true);
        return new MultiPValue(pv);
    }

    case MULTI_STATIC : {
        MultiStatic *y = (MultiStatic *)x.ptr();
        MultiPValuePtr mpv = new MultiPValue();
        for (unsigned i = 0; i < y->size(); ++i) {
            TypePtr t = objectType(y->values[i]);
            mpv->values.push_back(new PValue(t, true));
        }
        return mpv;
    }

    case TYPE :
    case PRIM_OP :
    case PROCEDURE :
    case RECORD :
    case MODULE_HOLDER :
    case IDENTIFIER : {
        TypePtr t = staticType(x);
        PValuePtr pv = new PValue(t, true);
        return new MultiPValue(pv);
    }

    case PATTERN :
        error("pattern cannot be used as value");
        return NULL;

    default :
        error("invalid static object");
        return NULL;

    }
}

//
// analyzeGlobalVariable
//

PValuePtr analyzeGlobalVariable(GlobalVariablePtr x)
{
    if (!x->type) {
        if (x->analyzing)
            return NULL;
        x->analyzing = true;
        PValuePtr pv = two::analyzeOne(x->expr, x->env);
        x->analyzing = false;
        if (!pv)
            return NULL;
        x->type = pv->type;
    }
    return new PValue(x->type, false);
}

//
// analyzeExternalVariable
//

PValuePtr analyzeExternalVariable(ExternalVariablePtr x)
{
    if (!x->type2)
        x->type2 = evaluateType(x->type, x->env);
    return new PValue(x->type2, false);
}

//
// analyzeExternalProcedure
//

void analyzeExternalProcedure(ExternalProcedurePtr x)
{
    if (x->analyzed)
        return;
    if (!x->attributesVerified)
        verifyAttributes(x);
    vector<TypePtr> argTypes;
    for (unsigned i = 0; i < x->args.size(); ++i) {
        ExternalArgPtr y = x->args[i];
        y->type2 = evaluateType(y->type, x->env);
        argTypes.push_back(y->type2);
    }
    if (!x->returnType)
        x->returnType2 = NULL;
    else
        x->returnType2 = evaluateType(x->returnType, x->env);
    CallingConv callingConv = CC_DEFAULT;
    if (x->attrStdCall)
        callingConv = CC_STDCALL;
    else if (x->attrFastCall)
        callingConv = CC_FASTCALL;
    x->ptrType = cCodePointerType(callingConv, argTypes,
                                  x->hasVarArgs, x->returnType2);
    x->analyzed = true;
}

//
// analyzeIndexingExpr
//

MultiPValuePtr analyzeIndexingExpr(ExprPtr indexable,
                                   const vector<ExprPtr> &args,
                                   EnvPtr env)
{
    return NULL;
}

//
// analyzeFieldRefExpr
//

MultiPValuePtr analyzeFieldRefExpr(ExprPtr base,
                                   IdentifierPtr name,
                                   EnvPtr env)
{
    return NULL;
}

//
// analyzeCallExpr
//

MultiPValuePtr analyzeCallExpr(ExprPtr callable,
                               const vector<ExprPtr> &args,
                               EnvPtr env)
{
    return NULL;
}

//
// analyzeCallValue
//

MultiPValuePtr analyzeCallValue(PValuePtr callable,
                                MultiPValuePtr args)
{
    return NULL;
}

}
<|endoftext|>


<commit_before>#ifndef GENERIC_SWAP_HPP
# define GENERIC_SWAP_HPP

#include <cstdint>

#if defined(_MSC_VER)
# include <stdlib.h>
#endif // _MSC_VER

namespace generic
{

#if defined(__GNUC__)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int64_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return __builtin_bswap64(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int32_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return __builtin_bswap32(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int16_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return __builtin_bswap16(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int8_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return v;
}

#elif defined(_MSC_VER)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(__int64) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return _byteswap_uint64(i);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(unsigned long) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return _byteswap_ulong(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(unsigned short) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return _byteswap_ushort(v)
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int8_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return v;
}

#else

namespace
{

template<class T, ::std::size_t ...I>
constexpr inline T swap_impl(T v, ::std::index_sequence<I...> const) noexcept
{
  return (
    (
      ((v >> (I * ::std::numeric_limits<char>::digits)) & ::std::uint8_t(~0))
      <<
      ((sizeof(T) - 1 - I) * ::std::numeric_limits<char>::digits)
    ) | ...
  );
};

}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap(T const v) noexcept
{
  return swap_impl<T>(v, ::std::make_index_sequence<sizeof(T)>{});
}

#endif

#if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || \
    defined(__BIG_ENDIAN__) || \
    defined(__ARMEB__) || \
    defined(__THUMBEB__) || \
    defined(__AARCH64EB__) || \
    defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_le(T const i) noexcept
{
  return i;
}

template <typename T>
inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_be(T const i) noexcept
{
  return swap(i);
}

#elif defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \
    defined(__LITTLE_ENDIAN__) || \
    defined(__ARMEL__) || \
    defined(__THUMBEL__) || \
    defined(__AARCH64EL__) || \
    defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_be(T const i) noexcept
{
  return i;
}

template <typename T>
inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_le(T const i) noexcept
{
  return swap(i);
}

#else
#error "I don't know what architecture this is!"
#endif

}

#endif // GENERIC_SWAP_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_SWAP_HPP
# define GENERIC_SWAP_HPP

#include <cstdint>

#include <type_traits>

#if defined(_MSC_VER)
# include <stdlib.h>
#endif // _MSC_VER

namespace generic
{

#if defined(__GNUC__)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int64_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return __builtin_bswap64(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int32_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return __builtin_bswap32(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int16_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return __builtin_bswap16(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int8_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return v;
}

#elif defined(_MSC_VER)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(__int64) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return _byteswap_uint64(i);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(unsigned long) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return _byteswap_ulong(v);
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(unsigned short) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return _byteswap_ushort(v)
}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{} &&
  (sizeof(::std::int8_t) == sizeof(T)),
  T
>
swap(T const v) noexcept
{
  return v;
}

#else

namespace
{

template<class T, ::std::size_t ...I>
constexpr inline T swap_impl(T v, ::std::index_sequence<I...> const) noexcept
{
  return (
    (
      ((v >> (I * ::std::numeric_limits<char>::digits)) & ::std::uint8_t(~0))
      <<
      ((sizeof(T) - 1 - I) * ::std::numeric_limits<char>::digits)
    ) | ...
  );
};

}

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap(T const v) noexcept
{
  return swap_impl<T>(v, ::std::make_index_sequence<sizeof(T)>{});
}

#endif

#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ || \
    defined(__BIG_ENDIAN__) || \
    defined(__ARMEB__) || \
    defined(__THUMBEB__) || \
    defined(__AARCH64EB__) || \
    defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_le(T const i) noexcept
{
  return i;
}

template <typename T>
inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_be(T const i) noexcept
{
  return swap(i);
}

#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ || \
    defined(__LITTLE_ENDIAN__) || \
    defined(__ARMEL__) || \
    defined(__THUMBEL__) || \
    defined(__AARCH64EL__) || \
    defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)

template <typename T>
constexpr inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_be(T const i) noexcept
{
  return i;
}

template <typename T>
inline ::std::enable_if_t<
  ::std::is_integral<T>{},
  T
>
swap_if_le(T const i) noexcept
{
  return swap(i);
}

#else
#error "I don't know what architecture this is!"
#endif

}

#endif // GENERIC_SWAP_HPP
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

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

#include "timsort.hpp"

BOOST_AUTO_TEST_CASE( simple10 ) {
    std::vector<int> a;
    a.push_back(60);
    a.push_back(50);
    a.push_back( 1);
    a.push_back(40);
    a.push_back(80);
    a.push_back(20);
    a.push_back(30);
    a.push_back(70);
    a.push_back(10);
    a.push_back(90);

    timsort(a.begin(), a.end(), std::less<int>());

    BOOST_CHECK_EQUAL( a[0],  1 );
    BOOST_CHECK_EQUAL( a[1], 10 );
    BOOST_CHECK_EQUAL( a[2], 20 );
    BOOST_CHECK_EQUAL( a[3], 30 );
    BOOST_CHECK_EQUAL( a[4], 40 );
    BOOST_CHECK_EQUAL( a[5], 50 );
    BOOST_CHECK_EQUAL( a[6], 60 );
    BOOST_CHECK_EQUAL( a[7], 70 );
    BOOST_CHECK_EQUAL( a[8], 80 );
    BOOST_CHECK_EQUAL( a[9], 90 );

    std::reverse(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    BOOST_CHECK_EQUAL( a[0],  1 );
    BOOST_CHECK_EQUAL( a[1], 10 );
    BOOST_CHECK_EQUAL( a[2], 20 );
    BOOST_CHECK_EQUAL( a[3], 30 );
    BOOST_CHECK_EQUAL( a[4], 40 );
    BOOST_CHECK_EQUAL( a[5], 50 );
    BOOST_CHECK_EQUAL( a[6], 60 );
    BOOST_CHECK_EQUAL( a[7], 70 );
    BOOST_CHECK_EQUAL( a[8], 80 );
    BOOST_CHECK_EQUAL( a[9], 90 );
}

BOOST_AUTO_TEST_CASE( shuffle30 ) {
    const int size = 30;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle31 ) {
    const int size = 31;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle32 ) {
    const int size = 32;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle128 ) {
    const int size = 128;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle1024 ) {
    const int size = 1024;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }

    for(int n = 0; n < 100; ++n) {
        std::random_shuffle(a.begin(), a.end());

        timsort(a.begin(), a.end(), std::less<int>());

        for(int i = 0; i < size; ++i) {
            BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
        }
    }
}

BOOST_AUTO_TEST_CASE( c_array ) {
    int a[] = { 7, 1, 5, 3, 9 };

    timsort(a, a + sizeof(a) / sizeof(int), std::less<int>());

    BOOST_CHECK_EQUAL(a[0], 1);
    BOOST_CHECK_EQUAL(a[1], 3);
    BOOST_CHECK_EQUAL(a[2], 5);
    BOOST_CHECK_EQUAL(a[3], 7);
    BOOST_CHECK_EQUAL(a[4], 9);
}

enum id { foo, bar, baz };
typedef std::pair<int, id> pair_t;
bool less_in_first(pair_t x, pair_t y) {
    return x.first < y.first;
}

BOOST_AUTO_TEST_CASE( stability ) {
    std::vector< pair_t > a;

    for(int i = 100; i >= 0; --i) {
        a.push_back( std::make_pair(i, foo) );
        a.push_back( std::make_pair(i, bar) );
        a.push_back( std::make_pair(i, baz) );
    }

    timsort(a.begin(), a.end(), &less_in_first);

    BOOST_CHECK_EQUAL(a[0].first,  0);
    BOOST_CHECK_EQUAL(a[0].second, foo);
    BOOST_CHECK_EQUAL(a[1].first,  0);
    BOOST_CHECK_EQUAL(a[1].second, bar);
    BOOST_CHECK_EQUAL(a[2].first,  0);
    BOOST_CHECK_EQUAL(a[2].second, baz);

    BOOST_CHECK_EQUAL(a[3].first,  1);
    BOOST_CHECK_EQUAL(a[3].second, foo);
    BOOST_CHECK_EQUAL(a[4].first,  1);
    BOOST_CHECK_EQUAL(a[4].second, bar);
    BOOST_CHECK_EQUAL(a[5].first,  1);
    BOOST_CHECK_EQUAL(a[5].second, baz);

    BOOST_CHECK_EQUAL(a[6].first,  2);
    BOOST_CHECK_EQUAL(a[6].second, foo);
    BOOST_CHECK_EQUAL(a[7].first,  2);
    BOOST_CHECK_EQUAL(a[7].second, bar);
    BOOST_CHECK_EQUAL(a[8].first,  2);
    BOOST_CHECK_EQUAL(a[8].second, baz);

    BOOST_CHECK_EQUAL(a[9].first,   3);
    BOOST_CHECK_EQUAL(a[9].second, foo);
    BOOST_CHECK_EQUAL(a[10].first,  3);
    BOOST_CHECK_EQUAL(a[10].second, bar);
    BOOST_CHECK_EQUAL(a[11].first,  3);
    BOOST_CHECK_EQUAL(a[11].second, baz);
}
<commit_msg>Added testsuite for non-default-constructible type<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

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

#include "timsort.hpp"

BOOST_AUTO_TEST_CASE( simple10 ) {
    std::vector<int> a;
    a.push_back(60);
    a.push_back(50);
    a.push_back( 1);
    a.push_back(40);
    a.push_back(80);
    a.push_back(20);
    a.push_back(30);
    a.push_back(70);
    a.push_back(10);
    a.push_back(90);

    timsort(a.begin(), a.end(), std::less<int>());

    BOOST_CHECK_EQUAL( a[0],  1 );
    BOOST_CHECK_EQUAL( a[1], 10 );
    BOOST_CHECK_EQUAL( a[2], 20 );
    BOOST_CHECK_EQUAL( a[3], 30 );
    BOOST_CHECK_EQUAL( a[4], 40 );
    BOOST_CHECK_EQUAL( a[5], 50 );
    BOOST_CHECK_EQUAL( a[6], 60 );
    BOOST_CHECK_EQUAL( a[7], 70 );
    BOOST_CHECK_EQUAL( a[8], 80 );
    BOOST_CHECK_EQUAL( a[9], 90 );

    std::reverse(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    BOOST_CHECK_EQUAL( a[0],  1 );
    BOOST_CHECK_EQUAL( a[1], 10 );
    BOOST_CHECK_EQUAL( a[2], 20 );
    BOOST_CHECK_EQUAL( a[3], 30 );
    BOOST_CHECK_EQUAL( a[4], 40 );
    BOOST_CHECK_EQUAL( a[5], 50 );
    BOOST_CHECK_EQUAL( a[6], 60 );
    BOOST_CHECK_EQUAL( a[7], 70 );
    BOOST_CHECK_EQUAL( a[8], 80 );
    BOOST_CHECK_EQUAL( a[9], 90 );
}

BOOST_AUTO_TEST_CASE( shuffle30 ) {
    const int size = 30;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle31 ) {
    const int size = 31;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle32 ) {
    const int size = 32;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle128 ) {
    const int size = 128;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }
    std::random_shuffle(a.begin(), a.end());

    timsort(a.begin(), a.end(), std::less<int>());

    for(int i = 0; i < size; ++i) {
        BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
    }
}

BOOST_AUTO_TEST_CASE( shuffle1024 ) {
    const int size = 1024;

    std::vector<int> a;
    for(int i = 0; i < size; ++i) {
        a.push_back((i+1) * 10);
    }

    for(int n = 0; n < 100; ++n) {
        std::random_shuffle(a.begin(), a.end());

        timsort(a.begin(), a.end(), std::less<int>());

        for(int i = 0; i < size; ++i) {
            BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
        }
    }
}

BOOST_AUTO_TEST_CASE( c_array ) {
    int a[] = { 7, 1, 5, 3, 9 };

    timsort(a, a + sizeof(a) / sizeof(int), std::less<int>());

    BOOST_CHECK_EQUAL(a[0], 1);
    BOOST_CHECK_EQUAL(a[1], 3);
    BOOST_CHECK_EQUAL(a[2], 5);
    BOOST_CHECK_EQUAL(a[3], 7);
    BOOST_CHECK_EQUAL(a[4], 9);
}

struct NonDefaultConstructible
{
    int i;

    NonDefaultConstructible( int i_ )
        : i( i_ ) {}

    friend bool operator<( NonDefaultConstructible const& x, NonDefaultConstructible const& y ) {
        return x.i < y.i;
    }

};

BOOST_AUTO_TEST_CASE( non_default_constructible ) {
    NonDefaultConstructible a[] = { 7, 1, 5, 3, 9 };

    timsort(a, a + sizeof(a) / sizeof(a[0]), std::less<NonDefaultConstructible>());

    BOOST_CHECK_EQUAL(a[0].i, 1);
    BOOST_CHECK_EQUAL(a[1].i, 3);
    BOOST_CHECK_EQUAL(a[2].i, 5);
    BOOST_CHECK_EQUAL(a[3].i, 7);
    BOOST_CHECK_EQUAL(a[4].i, 9);
}

enum id { foo, bar, baz };
typedef std::pair<int, id> pair_t;
bool less_in_first(pair_t x, pair_t y) {
    return x.first < y.first;
}

BOOST_AUTO_TEST_CASE( stability ) {
    std::vector< pair_t > a;

    for(int i = 100; i >= 0; --i) {
        a.push_back( std::make_pair(i, foo) );
        a.push_back( std::make_pair(i, bar) );
        a.push_back( std::make_pair(i, baz) );
    }

    timsort(a.begin(), a.end(), &less_in_first);

    BOOST_CHECK_EQUAL(a[0].first,  0);
    BOOST_CHECK_EQUAL(a[0].second, foo);
    BOOST_CHECK_EQUAL(a[1].first,  0);
    BOOST_CHECK_EQUAL(a[1].second, bar);
    BOOST_CHECK_EQUAL(a[2].first,  0);
    BOOST_CHECK_EQUAL(a[2].second, baz);

    BOOST_CHECK_EQUAL(a[3].first,  1);
    BOOST_CHECK_EQUAL(a[3].second, foo);
    BOOST_CHECK_EQUAL(a[4].first,  1);
    BOOST_CHECK_EQUAL(a[4].second, bar);
    BOOST_CHECK_EQUAL(a[5].first,  1);
    BOOST_CHECK_EQUAL(a[5].second, baz);

    BOOST_CHECK_EQUAL(a[6].first,  2);
    BOOST_CHECK_EQUAL(a[6].second, foo);
    BOOST_CHECK_EQUAL(a[7].first,  2);
    BOOST_CHECK_EQUAL(a[7].second, bar);
    BOOST_CHECK_EQUAL(a[8].first,  2);
    BOOST_CHECK_EQUAL(a[8].second, baz);

    BOOST_CHECK_EQUAL(a[9].first,   3);
    BOOST_CHECK_EQUAL(a[9].second, foo);
    BOOST_CHECK_EQUAL(a[10].first,  3);
    BOOST_CHECK_EQUAL(a[10].second, bar);
    BOOST_CHECK_EQUAL(a[11].first,  3);
    BOOST_CHECK_EQUAL(a[11].second, baz);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "todotxt.h"

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

#include "greatest.h"

SUITE(suite);

TEST simple_task_parse(void) {
    TodotxtTask task = todotxt_parse_task("this is an important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "this is an important task");
    PASS();
}

TEST simple_task_parse_with_priority(void) {
    TodotxtTask task = todotxt_parse_task("(A) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(A) this is a very important task");
    ASSERT_EQ(task.priority, 'A');
    PASS();
}

SUITE(suite) {
    RUN_TEST(simple_task_parse);
    RUN_TEST(simple_task_parse_with_priority);
}

GREATEST_MAIN_DEFS();

int main(int argc, char** argv)
{
    GREATEST_MAIN_BEGIN();
    RUN_SUITE(suite);
    GREATEST_MAIN_END();
}
<commit_msg>added test<commit_after>#include <stdio.h>
#include "todotxt.h"

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

#include "greatest.h"

SUITE(suite);

TEST simple_task_parse(void) {
    TodotxtTask task = todotxt_parse_task("this is an important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "this is an important task");
    PASS();
}

TEST simple_task_parse_with_priority(void) {
    TodotxtTask task = todotxt_parse_task("(A) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(A) this is a very important task");
    ASSERT_EQ(task.priority, 'A');
    PASS();
}

TEST simple_task_parse_with_wrong_priority(void) {
    TodotxtTask task = todotxt_parse_task("(a) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(a) this is a very important task");
    ASSERT_FALSE(task.priority == 'a');
    PASS();
}

SUITE(suite) {
    RUN_TEST(simple_task_parse);
    RUN_TEST(simple_task_parse_with_priority);
    RUN_TEST(simple_task_parse_with_wrong_priority);
}

GREATEST_MAIN_DEFS();

int main(int argc, char** argv)
{
    GREATEST_MAIN_BEGIN();
    RUN_SUITE(suite);
    GREATEST_MAIN_END();
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "todotxt.h"

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

#include "greatest.h"

SUITE(suite);

TEST simple_task_parse(void) {
    TodotxtTask task = todotxt_parse_task("this is an important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "this is an important task");
    ASSERT_STR_EQ(task.todo, "this is an important task");

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_finished_task_parse(void) {
    TodotxtTask task = todotxt_parse_task("x this is an important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, true);
    ASSERT_STR_EQ(task.raw_todo, "x this is an important task");
    ASSERT_STR_EQ(task.todo, "this is an important task");

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_with_priority(void) {
    TodotxtTask task = todotxt_parse_task("(A) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(A) this is a very important task");
    ASSERT_STR_EQ(task.todo, "this is a very important task");
    ASSERT_EQ(task.priority, 'A');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_with_priority_and_create_date(void) {
    TodotxtTask task = todotxt_parse_task("(A) 2014-01-02 this is a task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(A) 2014-01-02 this is a task");
    ASSERT_STR_EQ(task.todo, "this is a task");
    ASSERT_EQ(task.priority, 'A');
    ASSERT_EQ(task.create_date, 1388617200);

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_finished_task_parse_with_priority(void) {
    TodotxtTask task = todotxt_parse_task("x (A) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, true);
    ASSERT_STR_EQ(task.raw_todo, "x (A) this is a very important task");
    ASSERT_STR_EQ(task.todo, "this is a very important task");
    ASSERT_EQ(task.priority, 'A');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_with_wrong_priority(void) {
    TodotxtTask task = todotxt_parse_task("(a) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(a) this is a very important task");
    ASSERT_STR_EQ(task.todo, "(a) this is a very important task");
    ASSERT_FALSE(task.priority == 'a');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_without_priority(void) {
    TodotxtTask task = todotxt_parse_task("(a)task without a priority", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(a)task without a priority");
    ASSERT_STR_EQ(task.todo, "(a)task without a priority");
    ASSERT_EQ(task.priority, '^');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST todotxt_build_time_test(void) {
    char time[] = "2013-12-30";
    time_t t = todotxt_build_time(time);

    ASSERT_EQ(t, 1388358000);

    char another_time[] = "something";
    t = todotxt_build_time(another_time);

    ASSERT_EQ(t, -1);

    PASS();
}

SUITE(suite) {
    RUN_TEST(simple_task_parse);
    RUN_TEST(simple_finished_task_parse);
    RUN_TEST(simple_task_parse_with_priority);
    RUN_TEST(simple_finished_task_parse_with_priority);
    RUN_TEST(simple_task_parse_with_priority_and_create_date);
    RUN_TEST(simple_task_parse_with_wrong_priority);
    RUN_TEST(simple_task_parse_without_priority);
    RUN_TEST(todotxt_build_time_test);
}

GREATEST_MAIN_DEFS();

int main(int argc, char** argv)
{
    GREATEST_MAIN_BEGIN();
    RUN_SUITE(suite);
    GREATEST_MAIN_END();
}
<commit_msg>added priority to other tests<commit_after>#include <stdio.h>
#include "todotxt.h"

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

#include "greatest.h"

SUITE(suite);

TEST simple_task_parse(void) {
    TodotxtTask task = todotxt_parse_task("this is an important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "this is an important task");
    ASSERT_STR_EQ(task.todo, "this is an important task");

    ASSERT_EQ(task.priority, '^');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_finished_task_parse(void) {
    TodotxtTask task = todotxt_parse_task("x this is an important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, true);
    ASSERT_STR_EQ(task.raw_todo, "x this is an important task");
    ASSERT_STR_EQ(task.todo, "this is an important task");

    ASSERT_EQ(task.priority, '^');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_with_priority(void) {
    TodotxtTask task = todotxt_parse_task("(A) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(A) this is a very important task");
    ASSERT_STR_EQ(task.todo, "this is a very important task");
    ASSERT_EQ(task.priority, 'A');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_with_priority_and_create_date(void) {
    TodotxtTask task = todotxt_parse_task("(A) 2014-01-02 this is a task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(A) 2014-01-02 this is a task");
    ASSERT_STR_EQ(task.todo, "this is a task");
    ASSERT_EQ(task.priority, 'A');
    ASSERT_EQ(task.create_date, 1388617200);

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_finished_task_parse_with_priority(void) {
    TodotxtTask task = todotxt_parse_task("x (A) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, true);
    ASSERT_STR_EQ(task.raw_todo, "x (A) this is a very important task");
    ASSERT_STR_EQ(task.todo, "this is a very important task");
    ASSERT_EQ(task.priority, 'A');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_with_wrong_priority(void) {
    TodotxtTask task = todotxt_parse_task("(a) this is a very important task", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(a) this is a very important task");
    ASSERT_STR_EQ(task.todo, "(a) this is a very important task");
    ASSERT_FALSE(task.priority == 'a');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST simple_task_parse_without_priority(void) {
    TodotxtTask task = todotxt_parse_task("(a)task without a priority", 1);
    ASSERT_EQ(task.id, 1);
    ASSERT_EQ(task.finished, false);
    ASSERT_STR_EQ(task.raw_todo, "(a)task without a priority");
    ASSERT_STR_EQ(task.todo, "(a)task without a priority");
    ASSERT_EQ(task.priority, '^');

    delete task.raw_todo;
    delete task.todo;

    PASS();
}

TEST todotxt_build_time_test(void) {
    char time[] = "2013-12-30";
    time_t t = todotxt_build_time(time);

    ASSERT_EQ(t, 1388358000);

    char another_time[] = "something";
    t = todotxt_build_time(another_time);

    ASSERT_EQ(t, -1);

    PASS();
}

SUITE(suite) {
    RUN_TEST(simple_task_parse);
    RUN_TEST(simple_finished_task_parse);
    RUN_TEST(simple_task_parse_with_priority);
    RUN_TEST(simple_finished_task_parse_with_priority);
    RUN_TEST(simple_task_parse_with_priority_and_create_date);
    RUN_TEST(simple_task_parse_with_wrong_priority);
    RUN_TEST(simple_task_parse_without_priority);
    RUN_TEST(todotxt_build_time_test);
}

GREATEST_MAIN_DEFS();

int main(int argc, char** argv)
{
    GREATEST_MAIN_BEGIN();
    RUN_SUITE(suite);
    GREATEST_MAIN_END();
}
<|endoftext|>


<commit_before><commit_msg>Add empty test file.<commit_after><|endoftext|>


<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int distCode=0;

int main(int argc, char ** argv){
	VideoCapture in;
	VideoWriter out;

	if(argc >1){
		int num =1;

		while(num < argc){
			string input = argv[num];

			if(input == "-l2" || input == "-L2")
				distCode = 0;
			else if(input == "-l12" || input == "L12")
				distCode = 1;
			else if(input == "-fair" || input == "-FAIR")
				distCode =2;
			else if(input == "-welsch" || input == "-WELSCH")
				distCode =3;
			else if(input == "-huber" || input == "-HUBER")
				distCode = 4;
			else{
				in.open(argv[num]);
				const string source = argv[num];
				string::size_type pAt = source.find_last_of('.');
				string NAME = source.substr(0, pAt);

				if(distCode == 0)
					NAME = NAME + "_L2.avi";
				else if(distCode == 1)
					NAME = NAME + "_L12.avi";
				else if(distCode == 2)
					NAME = NAME + "_FAIR.avi";
				else if(distCode == 3)
					NAME = NAME + "_WELSCH.avi";
				else if(distCode == 4)
					NAME = NAME + "_HUBER.avi";
				else
					NAME = NAME + "_EDITED.avi";

				cerr<<NAME<<endl;
				out.open(NAME, CV_FOURCC('D', 'I', 'V', 'X') , in.get(CV_CAP_PROP_FPS),
					Size( (int) in.get(CV_CAP_PROP_FRAME_WIDTH), (int) in.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
			}
			num++;
		}
	}

	else
		exit(1);

	if(!in.isOpened()){
		cerr<<"Was unable to open video input."<<endl;
		exit(1);
	}

	if(!out.isOpened()){
		cerr<<"Was unable to open video output."<<endl;
		exit(1);
	}

	int frameNum=0;
	while(true){
		Mat frame(in.get(CV_CAP_PROP_FRAME_HEIGHT), in.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3);
		Mat color(frame.rows, frame.cols, CV_8UC3);

		if(!in.read(frame)){
			cerr<<"CANNOT READ FRAME.  VIDEO STREAM OVER."<<endl;
			break;
		}

		cvtColor(frame, color, CV_BGR2HSV, 3);

		Vec3b pixel;
		Vec4f outLineC, outLineE;
		vector<Point> pointsC;
		vector<Point> pointsE;

		for(int i=0; i<color.rows; i++){
			for(int j=0; j<color.cols; j++){
				pixel = color.at<Vec3b>(Point(j,i));
				if( (pixel[0] > 9 && pixel[0] < 25) && (pixel[1] > 0 && pixel[1] < 169) && (pixel[2] > 169 && pixel[2] < 255)){
					pointsC.push_back(Point(j, i));
				}
				if( (pixel[0] > 36 && pixel[0] < 85) && (pixel[1] > 5 && pixel[1] < 255) && (pixel[2] >208 && pixel[2] <255)){
					pointsE.push_back(Point(j, i));
				}
			}
		}

                for(int k=0; k < pointsC.size(); k++){
                        circle(frame, pointsC[k], 1, Scalar(255, 0, 0), -1,CV_AA, 0);
                }

		for(int k=0; k<pointsE.size(); k++){
			circle(frame, pointsE[k], 1, Scalar(0, 0, 255), -1, CV_AA, 0);
		}

		double m = max(color.rows, color.cols);
		Point Cp1, Cp2, Ep1, Ep2;

		if(pointsC.size() >0){

			//Simplest, least squares method (RED).
			if(distCode == 0){
				fitLine(pointsC, outLineC, CV_DIST_L2, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_L2, 0, 0.01, 0.01);
				putText(frame, "DIST L2 - Least Squares", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 1){
				fitLine(pointsC, outLineC, CV_DIST_L12, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_L12, 0, 0.01, 0.01);
				putText(frame, "DIST L12", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 2){
				fitLine(pointsC, outLineC, CV_DIST_FAIR, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_FAIR, 0, 0.01, 0.01);
				putText(frame, "DIST FAIR", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 3){
				fitLine(pointsC, outLineC, CV_DIST_WELSCH, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_WELSCH, 0, 0.01, 0.01);
				putText(frame, "DIST WELSCH", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX,2,  Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 4){
				fitLine(pointsC, outLineC, CV_DIST_HUBER, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_HUBER, 0, 0.01, 0.01);
				putText(frame, "DIST HUBER", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
		}

		Cp1.x = outLineC[2] - m*outLineC[0];
		Cp1.y = outLineC[3] - m*outLineC[1];
		Cp2.x = outLineC[2] + m*outLineC[0];
		Cp2.y = outLineC[3] + m*outLineC[1];

		Ep1.x = outLineE[2] - m*outLineE[0];
		Ep1.y = outLineE[2] - m*outLineE[1];
		Ep1.x = outLineE[2] - m*outLineE[0];
		Ep1.y = outLineE[2] - m*outLineE[1];

		line(frame, Cp1, Cp2, Scalar(0, 255, 0), 3, CV_AA, 0);
		line(frame, Ep1, Ep2, Scalar(255, 0, 255), 3, CV_AA,0);

		out.write(frame);

		if(frameNum % 100 == 0)
			cout<<"FRAME "<<frameNum<<endl;

		frameNum++;

	}

	out.release();

}
<commit_msg>tuned thresholds & limited areas of interest<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int distCode=0;

int main(int argc, char ** argv){
	VideoCapture in;
	VideoWriter out;

	if(argc >1){
		int num =1;

		while(num < argc){
			string input = argv[num];

			if(input == "-l2" || input == "-L2")
				distCode = 0;
			else if(input == "-l12" || input == "L12")
				distCode = 1;
			else if(input == "-fair" || input == "-FAIR")
				distCode =2;
			else if(input == "-welsch" || input == "-WELSCH")
				distCode =3;
			else if(input == "-huber" || input == "-HUBER")
				distCode = 4;
			else{
				in.open(argv[num]);
				const string source = argv[num];
				string::size_type pAt = source.find_last_of('.');
				string NAME = source.substr(0, pAt);

				if(distCode == 0)
					NAME = NAME + "_L2.avi";
				else if(distCode == 1)
					NAME = NAME + "_L12.avi";
				else if(distCode == 2)
					NAME = NAME + "_FAIR.avi";
				else if(distCode == 3)
					NAME = NAME + "_WELSCH.avi";
				else if(distCode == 4)
					NAME = NAME + "_HUBER.avi";
				else
					NAME = NAME + "_EDITED.avi";

				cerr<<NAME<<endl;
				out.open(NAME, CV_FOURCC('D', 'I', 'V', 'X') , in.get(CV_CAP_PROP_FPS),
					Size( (int) in.get(CV_CAP_PROP_FRAME_WIDTH), (int) in.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
			}
			num++;
		}
	}

	else
		exit(1);

	if(!in.isOpened()){
		cerr<<"Was unable to open video input."<<endl;
		exit(1);
	}

	if(!out.isOpened()){
		cerr<<"Was unable to open video output."<<endl;
		exit(1);
	}

	int frameNum=0;
	while(true){
		Mat frame(in.get(CV_CAP_PROP_FRAME_HEIGHT), in.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3);
		Mat color(frame.rows, frame.cols, CV_8UC3);

		if(!in.read(frame)){
			cerr<<"CANNOT READ FRAME.  VIDEO STREAM OVER."<<endl;
			break;
		}

		cvtColor(frame, color, CV_BGR2HSV, 3);

		Vec3b pixel;
		Vec4f outLineC, outLineE;
		vector<Point> pointsC;
		vector<Point> pointsE;

		for(int i=0; i<color.rows; i++){
			for(int j=0; j<color.cols; j++){
				pixel = color.at<Vec3b>(Point(j,i));
				if( j < color.cols && i > color.rows /3 && (pixel[0] > 9 && pixel[0] < 25) && (pixel[1] > 0 && pixel[1] < 169) && (pixel[2] > 169 && pixel[2] < 255)){
					pointsC.push_back(Point(j, i));
				}
				if( j > color.cols / 2 && i > color.rows/3 && (pixel[0] > 28 && pixel[0] < 109) && (pixel[1] > 1 && pixel[1] < 23) && (pixel[2] >200 && pixel[2] <255)){
					pointsE.push_back(Point(j, i));
				}
			}
		}

                for(int k=0; k < pointsC.size(); k++){
                        circle(frame, pointsC[k], 1, Scalar(255, 0, 0), -1,CV_AA, 0);
                }

		for(int k=0; k<pointsE.size(); k++){
			circle(frame, pointsE[k], 1, Scalar(255, 0, 255), -1, CV_AA, 0);
		}

		double m = max(color.rows, color.cols);
		Point Cp1, Cp2, Ep1, Ep2;

		if(pointsC.size() >0){

			//Simplest, least squares method (RED).
			if(distCode == 0){
				fitLine(pointsC, outLineC, CV_DIST_L2, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_L2, 0, 0.01, 0.01);
				putText(frame, "DIST L2 - Least Squares", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 1){
				fitLine(pointsC, outLineC, CV_DIST_L12, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_L12, 0, 0.01, 0.01);
				putText(frame, "DIST L12", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 2){
				fitLine(pointsC, outLineC, CV_DIST_FAIR, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_FAIR, 0, 0.01, 0.01);
				putText(frame, "DIST FAIR", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 3){
				fitLine(pointsC, outLineC, CV_DIST_WELSCH, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_WELSCH, 0, 0.01, 0.01);
				putText(frame, "DIST WELSCH", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX,2,  Scalar(255, 255, 255), 1, CV_AA, false);
			}
			else if(distCode == 4){
				fitLine(pointsC, outLineC, CV_DIST_HUBER, 0, 0.01, 0.01);
				fitLine(pointsE, outLineE, CV_DIST_HUBER, 0, 0.01, 0.01);
				putText(frame, "DIST HUBER", Point(0, frame.rows-100), FONT_HERSHEY_SIMPLEX, 2, Scalar(255, 255, 255), 1, CV_AA, false);
			}
		}

		Cp1.x = outLineC[2] - m*outLineC[0];
		Cp1.y = outLineC[3] - m*outLineC[1];
		Cp2.x = outLineC[2] + m*outLineC[0];
		Cp2.y = outLineC[3] + m*outLineC[1];

		Ep1.x = outLineE[2] - m*outLineE[0];
		Ep1.y = outLineE[3] - m*outLineE[1];
		Ep2.x = outLineE[2] + m*outLineE[0];
		Ep2.y = outLineE[3] + m*outLineE[1];

		line(frame, Cp1, Cp2, Scalar(0, 0, 255), 3, CV_AA, 0);
		line(frame, Ep1, Ep2, Scalar( 0, 255,0 ), 3, CV_AA,0);

		out.write(frame);

		if(frameNum % 100 == 0)
			cout<<"FRAME "<<frameNum<<endl;

		frameNum++;

	}

	out.release();

}
<|endoftext|>