text:
// This file is derivative work from Ulrich Germann's Tightly Packed Tries
// package (TPTs and related software).
//
// Original Copyright:
// Copyright 2005-2009 Ulrich Germann; all rights reserved.
// Under licence to NRC.
//
// Copyright for modifications:
// Technologies langagieres interactives / Interactive Language Technologies
// Inst. de technologie de l'information / Institute for Information Technology
// Conseil national de recherches Canada / National Research Council Canada
// Copyright 2008-2010, Sa Majeste la Reine du Chef du Canada /
// Copyright 2008-2010, Her Majesty in Right of Canada

// (c) 2007-2009 Ulrich Germann. All rights reserved.
/**
 * @author Ulrich Germann
 * @file vocab.build.cc
 * @brief Reads tokenized corpus text from stdin and writes a binary vocab
 * file and/or TokenIndex.
 *
 * First step in mmsufa generation. Normally called via build-tp-suffix-array.sh.
 */
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

#include <boost/program_options.hpp>

#include "ug_vocab.h"

using namespace std;
using namespace ugdiss;
namespace po = boost::program_options;

static char base_help_message[] = "\n\
vocab.build [options] <[--vcb] VOCAB_FILE | --tdx TOKEN_INDEX_FILE>\n\
\n\
  Read tokenized text from stdin and write the VOCAB_FILE (.vcb) and/or\n\
  TOKEN_INDEX_FILE (.tdx).\n\
\n\
  This is the first step in creating a memory mapped suffix array for a corpus.\n\
  This program is called from build-tp-suffix-array.sh.\n\
\n\
";

static stringstream options_help;       // set by interpret_args()

inline ostream& help_message(ostream& os)
{
  return os << base_help_message << options_help.str();
}

bool   alpha=false, nosort=false, quiet=false;
string oFile;
const string toksep=" \t";

string tdxFile,vcbFile;

void
interpret_args(int ac, char* av[])
{
  po::variables_map vm;
  po::options_description o("Options");
  o.add_options()
    ("help,h",    "print this message")
    ("quiet,q",   "don't print progress information")
    ("tdx", po::value<string>(&tdxFile), "name of TokenIndex file (.tdx) (output)")
    ("vcb", po::value<string>(&vcbFile), "name of Vocab file (.vcb) (output)")
    ("alpha",  "sort alphabetically instead of by frequency")
    ("nosort", "don't sort at all")
#if 0
    // UNTESTED!
    ("toksep", po::value<string>(&toksep)->default_value(" "),
     "token separator")
#endif
    ;
  options_help << o;
  po::positional_options_description a;
  a.add("vcb",1);

  try {
    po::store(po::command_line_parser(ac,av).options(o).positional(a).run(), vm);
    po::notify(vm);
  } catch(std::exception& e) {
    cerr << efatal << e.what() << endl << help_message << exit_1;
  }

  if (vm.count("help"))
    {
      cerr << help_message << endl;
      exit(0);
    }

  if (vcbFile.empty() && tdxFile.empty())
    cerr << efatal << "VOCAB_FILE or --tdx TOKEN_INDEX_FILE required." << endl
         << help_message << exit_1;

  quiet  = vm.count("quiet");
  alpha  = vm.count("alpha");
  nosort = vm.count("nosort");

  if (alpha && nosort)
    cerr << ewarn << "Only one of --alpha or --nosort may be used.\n"
         << "Sorting alphabetically and ignoring --nosort." << endl;
}

int MAIN(argc, argv)
{
  interpret_args(argc, (char **)argv);
  string lbuf;
  size_t lctr=0;
  Vocab V;

  while (getline(cin,lbuf))
    {
      //istringstream line(lbuf);
      size_t a = lbuf.find_first_not_of(toksep,0);
      if (a == string::npos)
        continue;
      while (a != string::npos)
        {
          const size_t z = lbuf.find_first_of(toksep,a);
          if (z != string::npos)
            V[lbuf.substr(a,z-a)].cnt++;
          else
            {
              V[lbuf.substr(a)].cnt++;
              break;
            }
          a = lbuf.find_first_not_of(toksep,z);
        }
      if (!quiet && ++lctr%1000==0)
	cerr << (lctr%1000) << "K sentences processed." << endl;
    }
  if (!quiet) cerr << lctr << " sentences processed in total." << endl;

  for (size_t i = 0; i < V.size(); i++)
    V.totalCount += V[i].cnt;

  if (alpha)
    {
      if (!quiet) cerr << "Sorting alphabetically..." << endl;
      V.sortAlphabetically();
    }
  else if (!nosort)
    {
      if (!quiet) cerr << "Optimizing IDs..." << endl;
      V.optimizeIDs();
    }

  if (!vcbFile.empty())
    {
      if (!quiet) cerr << "Writing vocabulary file..." << endl;
      V.pickle(vcbFile);
    }

  if (!tdxFile.empty())
    {
      if (!quiet) cerr << "Writing token index file..." << endl;
      ofstream tdx(tdxFile.c_str());
      if (tdx.fail())
        cerr << efatal << "Unable to open TokenIndex file '" << tdxFile
             << "' for writing." << exit_1;
      V.toTokenIndex(tdx);
      if (tdx.fail())
        cerr << efatal << "Writing TokenIndex file '" << tdxFile << "' failed."
             << exit_1;
      tdx.close();
    }
  if (!quiet) cerr << "Done" << endl;
}
END_MAIN

max_stars_repo_name: nrc-cnrc/Portage-SMT-TAS

max_issues_repo_name: nrc-cnrc/Portage-SMT-TAS

max_forks_repo_name: nrc-cnrc/Portage-SMT-TAS


text:
//   Copyright (c) 2012 Louis Dionne
//   Copyright (c) 2001-2012 Hartmut Kaiser
//
//   Distributed under the Boost Software License, Version 1.0. (See accompanying
//   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/spirit/include/qi.hpp>

#include <boost/core/lightweight_test.hpp>
#include <iostream>
#include <string>

struct MyInt
{
    int i_;

    template <typename Istream>
    friend Istream operator>>(Istream& is, MyInt& self)
    {
        is >> self.i_;
        return is;
    }
};

int main()
{
    using namespace boost::spirit::qi;
    typedef std::string::const_iterator Iterator;

    std::string input = "1";
    Iterator first(input.begin()), last(input.end());
    rule<Iterator, int()> my_int = stream_parser<char, MyInt>();
    BOOST_TEST(parse(first, last, my_int));
    BOOST_TEST(first == last);

    return boost::report_errors();
}

ext: cpp


text:
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 "ThetaCfaGenerator.h"
#include "gazer/Core/LiteralExpr.h"
#include "gazer/Automaton/CfaTransforms.h"

#include <llvm/ADT/Twine.h>
#include <llvm/ADT/DenseSet.h>

#include <boost/algorithm/cxx11/any_of.hpp>
#include <boost/range/join.hpp>

#include <regex>
#include <variant>
#include <llvm/Pass.h>

using namespace gazer;
using namespace gazer::theta;

using llvm::dyn_cast;

namespace
{

constexpr std::array ThetaKeywords = {
    "main", "process", "var", "loc",
    "assume", "init", "final", "error",
    "return", "havoc", "bool", "int", "rat",
    "if", "then", "else", "iff", "imply",
    "forall", "exists", "or", "and", "not",
    "mod", "rem", "true", "false"
};

struct ThetaAst
{
    virtual void print(llvm::raw_ostream& os) const = 0;

    virtual ~ThetaAst() = default;
};

struct ThetaLocDecl : ThetaAst
{
    enum Flag
    {
        Loc_State,
        Loc_Init,
        Loc_Final,
        Loc_Error,
    };

    ThetaLocDecl(std::string name, Flag flag = Loc_State)
        : mName(name), mFlag(flag)
    {}

    void print(llvm::raw_ostream& os) const override
    {
        switch (mFlag) {
            case Loc_Init:  os << "init "; break;
            case Loc_Final: os << "final "; break;
            case Loc_Error: os << "error "; break;
            default:
                break;
        }

        os << "loc " << mName;
    }

    std::string mName;
    Flag mFlag;
};

struct ThetaStmt : ThetaAst
{
    using VariantTy = std::variant<ExprPtr, std::pair<std::string, ExprPtr>, std::string>;

    /* implicit */ ThetaStmt(VariantTy content)
        : mContent(content)
    {}

    static ThetaStmt Assume(ExprPtr expr)
    {
        assert(expr->getType().isBoolType());

        return VariantTy{expr};
    }

    static ThetaStmt Assign(std::string variableName, ExprPtr value)
    {
        assert(!llvm::isa<UndefExpr>(value)
            && "Cannot assign an undef value to a variable."
            "Use ::Havoc() to represent a nondetermistic value assignment."
        );

        std::pair<std::string, ExprPtr> pair = { variableName, value };

        return VariantTy{pair};
    }

    static ThetaStmt Havoc(std::string variable)
    {
        return VariantTy{variable};
    }

    void print(llvm::raw_ostream& os) const override;

    VariantTy mContent;
};

struct ThetaEdgeDecl : ThetaAst
{
    ThetaEdgeDecl(ThetaLocDecl& source, ThetaLocDecl& target, std::vector<ThetaStmt> stmts)
        : mSource(source), mTarget(target), mStmts(std::move(stmts))
    {}

    void print(llvm::raw_ostream& os) const override;

    ThetaLocDecl& mSource;
    ThetaLocDecl& mTarget;
    std::vector<ThetaStmt> mStmts;
};

class ThetaVarDecl : ThetaAst
{
public:
    ThetaVarDecl(std::string name, std::string type)
        : mName(name), mType(type)
    {}

    llvm::StringRef getName() { return mName; }

    void print(llvm::raw_ostream& os) const override
    {
        os << "var " << mName << " : " << mType;
    }

private:
    std::string mName;
    std::string mType;
};

} // end anonymous namespace

void ThetaStmt::print(llvm::raw_ostream& os) const
{
    struct PrintVisitor
    {
        llvm::raw_ostream& mOS;
        explicit PrintVisitor(llvm::raw_ostream& os) : mOS(os) {}

        void operator()(const ExprPtr& expr) {
            mOS << "assume ";
            mOS << theta::printThetaExpr(expr);
        }

        void operator()(const std::pair<std::string, ExprPtr>& assign) {
            mOS << assign.first << " := ";
            mOS << theta::printThetaExpr(assign.second);
        }

        void operator()(const std::string& variable) {
            mOS << "havoc " << variable;
        }
    } visitor(os);

    std::visit(visitor, mContent);
}

void ThetaEdgeDecl::print(llvm::raw_ostream& os) const
{
    os << mSource.mName << " -> " << mTarget.mName << " {\n";
    for (auto& stmt : mStmts) {
        os << "    ";
        stmt.print(os);
        os << "\n";
    }
    os << "}\n";
}

static std::string typeName(Type& type)
{
    switch (type.getTypeID()) {
        case Type::IntTypeID:
            return "int";
        case Type::RealTypeID:
            return "rat";
        case Type::BoolTypeID:
            return "bool";
        case Type::ArrayTypeID: {
            auto& arrTy = llvm::cast<ArrayType>(type);
            return "[" + typeName(arrTy.getIndexType()) + "] -> " + typeName(arrTy.getElementType());
        }
        default:
            llvm_unreachable("Types which are unsupported by theta should have been eliminated earlier!");
    }
}

void ThetaCfaGenerator::write(llvm::raw_ostream& os, ThetaNameMapping& nameTrace)
{
    Cfa* main = mSystem.getMainAutomaton();
    auto recursiveToCyclicResult = TransformRecursiveToCyclic(main);

    nameTrace.errorLocation = recursiveToCyclicResult.errorLocation;
    nameTrace.errorFieldVariable = recursiveToCyclicResult.errorFieldVariable;
    nameTrace.inlinedLocations = std::move(recursiveToCyclicResult.inlinedLocations);
    nameTrace.inlinedVariables = std::move(recursiveToCyclicResult.inlinedVariables);

    llvm::DenseMap<Location*, std::unique_ptr<ThetaLocDecl>> locs;
    llvm::DenseMap<Variable*, std::unique_ptr<ThetaVarDecl>> vars;
    std::vector<std::unique_ptr<ThetaEdgeDecl>> edges;

    // Create a closure to test variable names
    auto isValidVarName = [&vars](const std::string& name) -> bool {
        // The variable name should not be present in the variable list.
        return std::find_if(vars.begin(), vars.end(), [name](auto& v1) {
            return name == v1.second->getName();
        }) == vars.end();
    };

    // Add variables
    for (auto& variable : main->locals()) {
        auto name = validName(variable.getName(), isValidVarName);
        auto type = typeName(variable.getType());

        nameTrace.variables[name] = &variable;
        vars.try_emplace(&variable, std::make_unique<ThetaVarDecl>(name, type));
    }

    for (auto& variable : main->inputs()) {
        auto name = validName(variable.getName(), isValidVarName);
        auto type = typeName(variable.getType());

        nameTrace.variables[name] = &variable;
        vars.try_emplace(&variable, std::make_unique<ThetaVarDecl>(name, type));
    }

    // Add locations
    for (Location* loc : main->nodes()) {
        ThetaLocDecl::Flag flag = ThetaLocDecl::Loc_State;
        if (loc == recursiveToCyclicResult.errorLocation) {
            flag = ThetaLocDecl::Loc_Error;
        } else if (main->getEntry() == loc) {
            flag = ThetaLocDecl::Loc_Init;
        } else if (main->getExit() == loc) {
            flag = ThetaLocDecl::Loc_Final;
        }

        auto locName = "loc" + std::to_string(loc->getId());

        nameTrace.locations[locName] = loc;
        locs.try_emplace(loc, std::make_unique<ThetaLocDecl>(locName, flag));
    }

    // Add edges
    for (Transition* edge : main->edges()) {
        ThetaLocDecl& source = *locs[edge->getSource()];
        ThetaLocDecl& target = *locs[edge->getTarget()];

        std::vector<ThetaStmt> stmts;

        if (edge->getGuard() != BoolLiteralExpr::True(edge->getGuard()->getContext())) {
            stmts.push_back(ThetaStmt::Assume(edge->getGuard()));
        }

        if (auto assignEdge = dyn_cast<AssignTransition>(edge)) {
            for (auto& assignment : *assignEdge) {
                auto lhsName = vars[assignment.getVariable()]->getName();

                if (llvm::isa<UndefExpr>(assignment.getValue())) {
                    stmts.push_back(ThetaStmt::Havoc(lhsName));
                } else {
                    stmts.push_back(ThetaStmt::Assign(lhsName, assignment.getValue()));
                }
            }
        } else if (auto callEdge = dyn_cast<CallTransition>(edge)) {
            llvm_unreachable("CallTransitions are not supported in theta CFAs!");
        }

        edges.emplace_back(std::make_unique<ThetaEdgeDecl>(source, target, std::move(stmts)));
    }

    auto INDENT  = "    ";
    auto INDENT2 = "        ";

    auto canonizeName = [&vars](Variable* variable) -> std::string {
        if (vars.count(variable) == 0) {
            return variable->getName();
        }

        return vars[variable]->getName();
    };

    os << "main process __gazer_main_process {\n";

    for (auto& variable : llvm::concat<Variable>(main->inputs(), main->locals())) {
        os << INDENT;
        vars[&variable]->print(os);
        os << "\n";
    }

    for (Location* loc : main->nodes()) {
        os << INDENT;
        locs[loc]->print(os);
        os << "\n";
    }

    for (auto& edge : edges) {
        os << INDENT << edge->mSource.mName << " -> " << edge->mTarget.mName << " {\n";
        for (auto& stmt : edge->mStmts) {
            os << INDENT2;
            struct PrintVisitor
            {
                llvm::raw_ostream& mOS;
                std::function<std::string(Variable*)> mCanonizeName;

                PrintVisitor(llvm::raw_ostream& os, std::function<std::string(Variable*)> canonizeName)
                    : mOS(os), mCanonizeName(canonizeName)
                {}

                void operator()(const ExprPtr& expr) {
                    mOS << "assume ";
                    mOS << theta::printThetaExpr(expr, mCanonizeName);
                }

                void operator()(const std::pair<std::string, ExprPtr>& assign) {
                    mOS << assign.first << " := ";
                    mOS << theta::printThetaExpr(assign.second, mCanonizeName);
                }

                void operator()(const std::string& variable) {
                    mOS << "havoc " << variable;
                }
            } visitor(os, canonizeName);

            std::visit(visitor, stmt.mContent);
            os << "\n";
        }
        os << INDENT << "}\n";
        os << "\n";
    }

    os << "}\n";
    os.flush();
}

std::string ThetaCfaGenerator::validName(std::string name, std::function<bool(const std::string&)> isUnique)
{
    name = std::regex_replace(name, std::regex("[^a-zA-Z0-9_]"), "_");

    if (std::find(ThetaKeywords.begin(), ThetaKeywords.end(), name) != ThetaKeywords.end()) {
        name += "_gazer";
    }

    while (!isUnique(name)) {
        llvm::Twine nextTry = name + llvm::Twine(mTmpCount++);
        name = nextTry.str();
    }

    return name;
}

max_stars_repo_name: ftsrg/gazer

max_issues_repo_name: FTSRG/gazer

max_forks_repo_name: ftsrg/gazer


text:
#include <ros/ros.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/Pose.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/conditional_removal.h>
#include <pcl/filters/passthrough.h>
#include <multisense_sensor_model/sensor_model.h>
#include <cylbot_mcl/pose_cloud3d.h>
#include <string>
#include <tf/transform_listener.h>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <octomap_ros/conversions.h>
#include <octomap/octomap.h>

using namespace multisense_sensor_model;
using namespace cylbot_mcl;

ros::Subscriber octomap_sub;

void laserCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_in,
				   const tf::TransformListener& tf_listener,
				   PoseCloud3D* pose_cloud)
{
	tf::StampedTransform laser_transform;
	if(!tf_listener.waitForTransform(
		   "/map",
		   "/head_hokuyo_frame",
		   cloud_in->header.stamp,
		   ros::Duration(1.0)))
	{
		ROS_WARN("Transform from /map to /head_hokuyo_frame failed");
		return;
	}
	tf_listener.lookupTransform("/map", "/head_hokuyo_frame", cloud_in->header.stamp, laser_transform);
	octomap::point3d laser_origin = octomap::pointTfToOctomap(laser_transform.getOrigin());

	pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_raw_cloud(new pcl::PointCloud<pcl::PointXYZ>);
	pcl::fromROSMsg(*cloud_in, *pcl_raw_cloud);

    // filter out the points on the robot
	pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_robot_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>);

	pcl::ConditionOr<pcl::PointXYZ>::Ptr range_cond (new pcl::ConditionOr<pcl::PointXYZ>());
	range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr (
								  new pcl::FieldComparison<pcl::PointXYZ>("x", pcl::ComparisonOps::GE, 0.25)));
	range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr (
								  new pcl::FieldComparison<pcl::PointXYZ>("x", pcl::ComparisonOps::LE, -0.25)));
	range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr (
								  new pcl::FieldComparison<pcl::PointXYZ>("y", pcl::ComparisonOps::GE, 0.25)));
	range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr (
								  new pcl::FieldComparison<pcl::PointXYZ>("y", pcl::ComparisonOps::LE, -0.25)));
	range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr (
								  new pcl::FieldComparison<pcl::PointXYZ>("z", pcl::ComparisonOps::GE, 1.2)));
	range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr (
								  new pcl::FieldComparison<pcl::PointXYZ>("z", pcl::ComparisonOps::LE, -.1)));
	pcl::ConditionalRemoval<pcl::PointXYZ> robot_filter(range_cond);
	robot_filter.setInputCloud(pcl_raw_cloud);
	robot_filter.setKeepOrganized(true);
	robot_filter.filter(*pcl_robot_filtered_cloud);

	ROS_DEBUG("pcl_robot_filtered_cloud size: %lu", pcl_robot_filtered_cloud->points.size());

	pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_map_cloud(new pcl::PointCloud<pcl::PointXYZ>);
	if(!tf_listener.waitForTransform(
		   "/map",
		   "/base_link",
		   cloud_in->header.stamp,
		   ros::Duration(1.0)))
	{
		ROS_WARN("Transform from /map to /base_link failed");
		return;
	}
	pcl_ros::transformPointCloud("/map",
								 cloud_in->header.stamp,
								 *pcl_robot_filtered_cloud,
								 "/base_link",
								 *pcl_map_cloud,
								 tf_listener);

	// filter out the ground
	pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_ground_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>);
	pcl::PassThrough<pcl::PointXYZ> ground_filter;
	ground_filter.setInputCloud(pcl_map_cloud);
	ground_filter.setFilterFieldName("z");
	ground_filter.setFilterLimits(-1, .05);
	ground_filter.setFilterLimitsNegative(true);
	ground_filter.filter(*pcl_ground_filtered_cloud);

	ROS_DEBUG("pcl_ground_filtered_cloud size: %lu", pcl_ground_filtered_cloud->points.size());

	// filter out the max range readings
	pcl::PointIndices::Ptr max_indices(new pcl::PointIndices);
	int i=0;
	for(pcl::PointCloud<pcl::PointXYZ>::const_iterator point = pcl_ground_filtered_cloud->points.begin();
		point != pcl_ground_filtered_cloud->points.end();
		point++)
	{
		// if this point is within .03 m of the max sensor reading then we want to remove it
		double x = point->x - laser_origin.x();
		double y = point->y - laser_origin.y();
		double z = point->z - laser_origin.z();
		if(fabs(sqrt(x*x + y*y + z*z) - 30.0) < .04)
			max_indices->indices.push_back(i);
		i++;
	}
	pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_max_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>);
	pcl::ExtractIndices<pcl::PointXYZ> max_filter;
	max_filter.setInputCloud(pcl_ground_filtered_cloud);
	max_filter.setNegative(true);
	max_filter.setIndices(max_indices);
	max_filter.filter(*pcl_max_filtered_cloud);

	pcl_max_filtered_cloud->header.stamp = pcl_robot_filtered_cloud->header.stamp;
	pcl_max_filtered_cloud->header.frame_id = "/map";
	pcl::PointCloud<pcl::PointXYZ>::Ptr beam_ends(new pcl::PointCloud<pcl::PointXYZ>);
	if(!tf_listener.waitForTransform(
		   "/base_link",
		   "/map",
		   cloud_in->header.stamp,
		   ros::Duration(1.0)))
	{
		ROS_WARN("Transform from /base_link to /map failed");
		return;
	}
	pcl_ros::transformPointCloud("/base_link",
								 cloud_in->header.stamp,
								 *pcl_max_filtered_cloud,
								 "/map",
								 *beam_ends,
								 tf_listener);

	tf::StampedTransform map_transform;
	tf_listener.lookupTransform("/map", "/base_link", cloud_in->header.stamp, map_transform);

	geometry_msgs::Pose true_pose;
	tf::pointTFToMsg(map_transform.getOrigin(), true_pose.position);
	true_pose.position.z = 0;
	tf::quaternionTFToMsg(map_transform.getRotation(), true_pose.orientation);
	true_pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, tf::getYaw(true_pose.orientation) + 3.14159/2.0);

	pose_cloud->sensorUpdate(true_pose, *beam_ends, laser_transform.getOrigin(), cloud_in->header.stamp.toSec());
}

void initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& initial_pose,
						 PoseCloud3D* pose_cloud,
						 const int num_particles)
{
	pose_cloud->resetCloud(*initial_pose, num_particles);
}

void velocityCallback(const geometry_msgs::TwistStamped::ConstPtr& twist_msg,
					  PoseCloud3D* pose_cloud,
					  geometry_msgs::TwistStamped::ConstPtr& last_cmd)
{
	if(last_cmd == NULL)
	{
		last_cmd = twist_msg;
		return;
	}
	ros::Duration dt = twist_msg->header.stamp - last_cmd->header.stamp;
	last_cmd = twist_msg;

	pose_cloud->motionUpdate(twist_msg->twist, dt.toSec());
}

void octomapCallback(const octomap_msgs::Octomap::ConstPtr& octomap_msg,
					 PoseCloud3D* pose_cloud)
{
	boost::shared_ptr<octomap::AbstractOcTree> tree(octomap_msgs::msgToMap(*octomap_msg));
	boost::shared_ptr<octomap::OcTree> octree = boost::dynamic_pointer_cast<octomap::OcTree>(tree);
	if(octree == NULL)
	{
		ROS_ERROR("Failed to deserialize octomap");
	}

	pose_cloud->octreeUpdate(octree);

	octomap_sub.shutdown();
}

int main(int argc, char** argv)
{
	ros::init(argc, argv, "localization_2d");

	ros::NodeHandle nh;

	tf::TransformListener tf_listener;

	ros::NodeHandle priv_nh("~");
	std::string sensor_params_file = "";
	priv_nh.getParam("sensor_params_file", sensor_params_file);
	int num_global_samples;
	if(!priv_nh.getParam("num_global_samples", num_global_samples))
		num_global_samples = 10000;

	int num_local_samples;
	if(!priv_nh.getParam("num_local_samples", num_local_samples))
		num_local_samples = 1000;

	IntrinsicParams sensor_params;
	if(sensor_params_file.compare("") == 0)
	{
		ROS_WARN("Sensor params file not provided or not valid");
	}
	else
	{
		readIntrinsicParamsFromFile(sensor_params_file, &sensor_params);
	}

	RobotModel model(sensor_params);

	for(int i=0; i<model.alpha.size(); i++)
	{
		model.alpha[i] = .01;
	}

	ROS_INFO("num_global_samples: %d num_local_samples %d", num_global_samples, num_local_samples);
	PoseCloud3D pose_cloud(model, num_global_samples);

	ros::Subscriber laser_sub = nh.subscribe<sensor_msgs::PointCloud2>("/laser/points", 1,
																	   boost::bind(laserCallback,
																				   _1,
																				   boost::ref(tf_listener),
																				   &pose_cloud));
	ros::Subscriber initial_pose_sub = nh.subscribe<geometry_msgs::PoseWithCovarianceStamped>("/initialpose", 1,
																							  boost::bind(initialPoseCallback,
																										  _1,
																										  &pose_cloud,
																										  num_local_samples));

	geometry_msgs::TwistStamped::ConstPtr last_velocity;
	ros::Subscriber vel_sub = nh.subscribe<geometry_msgs::TwistStamped>("/cylbot/velocity", 1000,
																		boost::bind(velocityCallback,
																					_1,
																					&pose_cloud,
																					boost::ref(last_velocity)));

	octomap_sub = nh.subscribe<octomap_msgs::Octomap>("/octomap_binary", 1, boost::bind(octomapCallback, _1, &pose_cloud));

	ros::Publisher pose_array_pub = nh.advertise<geometry_msgs::PoseArray>("/pose_cloud", 1);

	ros::Rate loop_rate(100);
	while(ros::ok())
	{
		geometry_msgs::PoseArray pose_array = pose_cloud.getPoses();
		pose_array.header.stamp = ros::Time::now();
		pose_array.header.frame_id = "/map";
		pose_array_pub.publish(pose_array);

		ros::spinOnce();
		loop_rate.sleep();
	}
}


text:
// Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.

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

// this test is a copy from unit_test/prediction_test.cc
// it adds a noop reduction on top

#include "vw.h"
#include "reductions_fwd.h"
#include "reduction_stack.h"

// this file would live in minimal_reduction.cc
// minimal_reduction.h would define test_reduction_setup(..) fn
// see binary.h and binary.cc for contrast
//
// minimal reduction impl
namespace minimal_reduction
{
// global var eek!
// but useful for this minimal test
bool added_to_learner = false;
bool called_learn_predict = false;

// minimal predict/learn fn for test_reduction_setup
template <bool is_learn>
void predict_or_learn(char&, VW::LEARNER::single_learner& base, example& ec)
{
  called_learn_predict = true;

  if (is_learn) { base.learn(ec); }
  else
  {
    base.predict(ec);
  }
}

// minimal setup function for reduction
VW::LEARNER::base_learner* test_reduction_setup(VW::setup_base_i& stack_builder)
{
  BOOST_CHECK(added_to_learner == false);
  BOOST_CHECK(called_learn_predict == false);

  auto base = stack_builder.setup_base_learner();
  BOOST_CHECK(base->is_multiline == false);

  auto ret = VW::LEARNER::make_no_data_reduction_learner(as_singleline(base), predict_or_learn<true>,
      predict_or_learn<false>, stack_builder.get_setupfn_name(test_reduction_setup))
                 .set_learn_returns_prediction(base->learn_returns_prediction)
                 .build();

  added_to_learner = true;

  return make_base(*ret);
}

void reset_test_state()
{
  added_to_learner = false;
  called_learn_predict = false;
}
}  // namespace minimal_reduction
//
//
//
//

// minimal builder that pushes test_reduction_setup fn to the
// default stack (reduction_stack)
// inherits from the default behaviour stack builder
//
// custom_builder can be augmented to do heavier edits (reorder/remove)
// on reduction_stack
struct custom_simple_builder : VW::default_reduction_stack_setup
{
  custom_simple_builder()
  {
    BOOST_CHECK_GT(reduction_stack.size(), 77);
    reduction_stack.emplace_back("test_reduction_name", minimal_reduction::test_reduction_setup);
  }
};

// This test will push a new reduction defined in this same file.
// This reduction doesn't do anything but set a bool to true
// and assert on the enabled reductions.
// This test approximates one way users can use VW library mode
// and customize the behaviour of the stack.
//
// We can also use this as an example to craft more specific tests
// at specific parts of the stack i.e. push a test reduction that
// asserts some state right on top of cb_adf.
//
// these test reductions are useful for CI and advanced testing but are not
// important enough to pollute setup_base(..) default stack
BOOST_AUTO_TEST_CASE(minimal_reduction_test)
{
  minimal_reduction::reset_test_state();

  std::string sgd_args = "--quiet --sgd --noconstant --learning_rate 0.1";

  float prediction_one;
  {
    auto learner_builder = VW::make_unique<custom_simple_builder>();

    BOOST_CHECK(minimal_reduction::added_to_learner == false);
    BOOST_CHECK(minimal_reduction::called_learn_predict == false);
    auto& vw = *VW::initialize_with_builder(sgd_args, nullptr, false, nullptr, nullptr, std::move(learner_builder));
    BOOST_CHECK(minimal_reduction::added_to_learner);
    BOOST_CHECK(minimal_reduction::called_learn_predict == false);

    auto& pre_learn_predict_example = *VW::read_example(vw, "0.19574759682114784 | 1:1.430");
    auto& learn_example = *VW::read_example(vw, "0.19574759682114784 | 1:1.430");
    auto& predict_example = *VW::read_example(vw, "| 1:1.0");

    BOOST_CHECK(minimal_reduction::called_learn_predict == false);
    vw.predict(pre_learn_predict_example);
    BOOST_CHECK(minimal_reduction::called_learn_predict);

    vw.finish_example(pre_learn_predict_example);
    vw.learn(learn_example);
    vw.finish_example(learn_example);
    vw.predict(predict_example);
    prediction_one = predict_example.pred.scalar;
    vw.finish_example(predict_example);
    VW::finish(vw);

    BOOST_CHECK(minimal_reduction::added_to_learner);
    BOOST_CHECK(minimal_reduction::called_learn_predict);
  }

  // reset for next part of test
  minimal_reduction::reset_test_state();

  float prediction_two;
  {
    BOOST_CHECK(minimal_reduction::added_to_learner == false);
    BOOST_CHECK(minimal_reduction::called_learn_predict == false);
    auto& vw = *VW::initialize(sgd_args);

    auto& learn_example = *VW::read_example(vw, "0.19574759682114784 | 1:1.430");
    auto& predict_example = *VW::read_example(vw, "| 1:1.0");

    vw.learn(learn_example);
    vw.finish_example(learn_example);
    vw.predict(predict_example);
    prediction_two = predict_example.pred.scalar;
    vw.finish_example(predict_example);
    VW::finish(vw);

    // both should be false since it uses the default stack builder
    BOOST_CHECK(minimal_reduction::added_to_learner == false);
    BOOST_CHECK(minimal_reduction::called_learn_predict == false);
  }

  BOOST_CHECK_EQUAL(prediction_one, prediction_two);
}

ext: cc


text:
#define BOOST_TEST_MODULE registry
#include <boost/test/unit_test.hpp>

#include "odil/registry.h"
#include "odil/Tag.h"

BOOST_AUTO_TEST_CASE(PublicDictionary)
{
    auto const iterator = odil::registry::public_dictionary.find(
        odil::registry::PatientName);
    BOOST_REQUIRE(iterator != odil::registry::public_dictionary.end());
    auto const & entry = iterator->second;
    BOOST_REQUIRE_EQUAL(entry.name, "Patient's Name");
    BOOST_REQUIRE_EQUAL(entry.keyword, "PatientName");
    BOOST_REQUIRE_EQUAL(entry.vr, "PN");
    BOOST_REQUIRE_EQUAL(entry.vm, "1");
}

BOOST_AUTO_TEST_CASE(PublicDictionaryRepeatingGroup)
{
    auto const iterator = odil::registry::public_dictionary.find(
        std::string("60xx0010"));
    BOOST_REQUIRE(iterator != odil::registry::public_dictionary.end());
    auto const & entry = iterator->second;
    BOOST_REQUIRE_EQUAL(entry.name, "Overlay Rows");
    BOOST_REQUIRE_EQUAL(entry.keyword, "OverlayRows");
    BOOST_REQUIRE_EQUAL(entry.vr, "US");
    BOOST_REQUIRE_EQUAL(entry.vm, "1");
}

BOOST_AUTO_TEST_CASE(UIDsDictionary)
{
    auto const iterator = odil::registry::uids_dictionary.find(
        odil::registry::MRImageStorage);
    BOOST_REQUIRE(iterator != odil::registry::uids_dictionary.end());
    auto const & entry = iterator->second;
    BOOST_REQUIRE_EQUAL(entry.name, "MR Image Storage");
    BOOST_REQUIRE_EQUAL(entry.keyword, "MRImageStorage");
    BOOST_REQUIRE_EQUAL(entry.type, "SOP Class");
}

max_stars_repo_name: genisysram/odil

max_issues_repo_name: genisysram/odil

max_forks_repo_name: genisysram/odil


text: #include <boost/geometry/multi/core/closure.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * Copyright (c) 2019 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 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 COPYRIGHT HOLDER 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.
 */

#include <memory>

#include <Python.h>

#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/slice.hpp>
#include <boost/python/call.hpp>
#include <boost/python/enum.hpp>
#include <boost/python/scope.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include <opencv2/core/core.hpp>

#include <stdint.h>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>

#include "dbglog/dbglog.hpp"

#include "utility/enum-io.hpp"

#include "pysupport/package.hpp"
#include "pysupport/class.hpp"
#include "pysupport/enum.hpp"
#include "pysupport/string.hpp"
#include "pysupport/threads.hpp"

#include "../gdsblockwriter.hpp"
#include "../gdal.hpp"

namespace bp = boost::python;

namespace geo { namespace py {

void* importNumpy()
{
    if (!PyArray_API) {
        import_array();
        if (!PyArray_API) {
            throw bp::error_already_set();
        }
    }
    return nullptr;
}

struct Tile {
    bp::object data;
    math::Point2i index;
};

::GDALDataType gdalType(char type)
{
    switch (type) {
    case 'b': return GDT_Byte;
    case 'B': return GDT_Byte;
    case 'h': return GDT_Int16;
    case 'H': return GDT_UInt16;
    case 'i': return GDT_Int32;
    case 'u': return GDT_Int32;
    case 'f': return GDT_Float32;
    case 'd': return GDT_Float64;
    }

    LOGTHROW(err1, std::logic_error)
        << "Unsupported array data type '" << type << "'.";
    throw;
}

void add(GdsBlockWriter::Batch &batch, const math::Point2i &index
         , PyArrayObject *array)
{
    if (PyArray_NDIM(array) != 3) {
        LOGTHROW(err1, std::logic_error)
            << "Block must be a 3D array; provided array has "
            << PyArray_NDIM(array) << " dimension.";
    }

    const auto dtype(PyArray_DTYPE(array));

    batch.blocks.emplace_back(index, gdalType(dtype->type)
                              , PyArray_DATA(array));
    auto &block(batch.blocks.back());

    block.size.width = PyArray_DIM(array, 1);
    block.size.height = PyArray_DIM(array, 0);
    block.channels = PyArray_DIM(array, 2);

    const auto *strides(PyArray_STRIDES(array));
    block.lineSpace = strides[0];
    block.pixelSpace = strides[1];
    block.bandSpace = strides[2];

    switch (dtype->byteorder) {
    case '=': case '|': break;
    default:
        LOGTHROW(err1, std::logic_error)
            << "Only native byte order is supported.";
    }
}

void add(GdsBlockWriter::Batch &batch, const math::Point2i &index
         , const bp::object &data)
{
    // TODO: add opencv support
    if (PyArray_Check(data.ptr())) {
        add(batch, index
            , reinterpret_cast<PyArrayObject*>(data.ptr()));
    } else {
        LOGTHROW(err1, std::logic_error)
            << "GdsBlockWriter supports only numpy array, not "
            << data.ptr()->ob_type->tp_name << ".";
    }
}

void GdsBlockWriter_write(GdsBlockWriter &writer, const bp::object &data)
{
    GdsBlockWriter::Batch batch;

    for (bp::stl_input_iterator<bp::object> idata(data), edata;
         idata != edata; ++idata)
    {
        const auto &item(*idata);

        add(batch, math::Point2i(bp::extract<int>(item[0])
                                 , bp::extract<int>(item[1]))
            , item[2]);
    }

    auto obj(data.ptr());

    batch.acquire = [obj] { Py_INCREF(obj); };

    batch.release = [obj]() {
        pysupport::EnablePython guard;
        Py_DECREF(obj);
    };

    writer.write(batch);
}

void GdsBlockWriter_finish(GdsBlockWriter &writer)
{
    pysupport::EnableThreads guard;
    writer.finish();
}

bp::object GdsBlockWriter_enter(const bp::object &self)
{
    return self;
}

void GdsBlockWriter_exit(GdsBlockWriter &writer, const bp::object&
                         , const bp::object&, const bp::object&)
{
    // close in any case
    GdsBlockWriter_finish(writer);
}

template <typename T>
std::shared_ptr<std::vector<T>> vectorFromSequence(const bp::object& sequence)
{
    auto v(std::make_shared<std::vector<T>>());
    for (bp::stl_input_iterator<T> isequence(sequence), esequence;
         isequence != esequence; ++isequence)
    {
        v->push_back(*isequence);
    }
    return v;
}

template <typename T>
void addVector(const char *type)
{
    using namespace bp;

    class_<std::vector<T>>(type)
        .def(init<>())
        .def(vector_indexing_suite<std::vector<T>>())
        .def("__init__", make_constructor(&vectorFromSequence<T>))
        ;
}

Options dictToOptions(const bp::dict &dict)
{
    Options opt;
    for (bp::stl_input_iterator<bp::str> idict(dict), edict;
         idict != edict; ++idict)
    {
        // TODO: convert value from number/boolean
        opt(pysupport::py2utf8(*idict), pysupport::py2utf8(dict[*idict]));
    }
    return opt;
}

struct from_python_options
{
    typedef bp::converter::rvalue_from_python_stage1_data Data;
    typedef bp::converter::rvalue_from_python_storage<
        Options> Storage;

    from_python_options() {
        bp::converter::registry::push_back
            (&convertible, &construct, bp::type_id<Options>());
    }

    // Determine if ptr can be converted in an Optional
    static void* convertible(::PyObject *ptr) {
        return PyDict_Check(ptr) ? ptr : nullptr;
    }

    // Convert ptr into a Options
    static void construct(::PyObject *ptr, Data *data) {
        // get memory
        void *storage(((Storage*) data)->storage.bytes);

        new (storage) Options(dictToOptions(bp::dict(bp::handle<>(ptr))));

        // Stash the memory chunk pointer for later use by boost.python
        data->convertible = storage;
    }
};

void registerGdsBlockWriter() {
    importNumpy();

    using namespace bp;

    auto GdsBlockWriter_class = class_<GdsBlockWriter, boost::noncopyable>
        ("GdsBlockWriter"
         , init<const boost::filesystem::path&, const math::Size2&
         , const GeoDataset::Format&, const math::Size2&
         , const NodataValue&, const Options&>())
        .def("write", &GdsBlockWriter_write)
        .def("finish", &GdsBlockWriter_finish)
        .def("__del__", &GdsBlockWriter_finish)
        .def("__enter__", &GdsBlockWriter_enter)
        .def("__exit__", &GdsBlockWriter_exit)
        ;

    pysupport::fillEnum< ::GDALDataType>
        ("GDALDataType", "GDAL data type.");
    addVector< ::GDALDataType>("GDALDataTypes");
    pysupport::fillEnum< ::GDALColorInterp>
        ("GDALColorInterp", "GDAL color interpretation.");
    addVector< ::GDALColorInterp>("GDALColorInterps");

    auto Format_class = class_<GeoDataset::Format>
        ("Format", init<>())
        .def(init< ::GDALDataType
             , const std::vector< ::GDALColorInterp>&>())
        .def(init< ::GDALDataType
             , const std::vector< ::GDALColorInterp>&
             , GeoDataset::Format::Storage>())
            .def_readwrite("channelType", &GeoDataset::Format::channelType)
        .def_readwrite("channels", &GeoDataset::Format::channels)
        .def_readwrite("driver", &GeoDataset::Format::driver)

        .def("gtiffRGBPhoto", &GeoDataset::Format::gtiffRGBPhoto)
        .staticmethod("gtiffRGBPhoto")
        .def("pngRGBPhoto", &GeoDataset::Format::pngRGBPhoto)
        .staticmethod("pngRGBPhoto")
        .def("pngRGBAPhoto", &GeoDataset::Format::pngRGBAPhoto)
        .staticmethod("pngRGBAPhoto")
        .def("jpegRGBPhoto", &GeoDataset::Format::jpegRGBPhoto)
        .staticmethod("jpegRGBPhoto")
            .def("coverage", &GeoDataset::Format::coverage)
        .staticmethod("coverage")
        .def("dsm", &GeoDataset::Format::dsm)
        .staticmethod("dsm")
        ;

    // inject GeoDataset::Format::Storage enum
    {
        bp::scope scope(Format_class);
        pysupport::fillEnum<GeoDataset::Format::Storage>
            ("Storage", "Storage type.");
    }

    from_python_options();

    // make sure we have thread support
    ::PyEval_InitThreads();

    dbglog::log_thread(true);
}

} } // namespace geo::py

max_stars_repo_name: ExploreWilder/libgeo

max_issues_repo_name: HanochZhu/vts-browser-unity-plugin

max_forks_repo_name: HanochZhu/vts-browser-unity-plugin


text:
#ifndef MSRP_DEMULTIPLEX_HXX
#define MSRP_DEMULTIPLEX_HXX

#include <map>
#include <string>

#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>

#include "msrp/Exception.hxx"
#include "msrp/Message.hxx"
#include "msrp/Uri.hxx"

namespace msrp
{

class IncomingMessage;
class OutgoingMessage;
class Session;

class Demultiplex : private boost::noncopyable
{
   public:
      struct Exception : public msrp::Exception
      {
         Exception(const std::string& s, const ExceptionContext& context) :
            msrp::Exception(s, context)
         {}
      };

      Demultiplex();

      // !cb! This class will not take a shared_ptr to your object, only a
      // weak_ptr, so there is no dependency.  If you don't remove your
      // object from the Demultiplex when it is destructed, it will be
      // removed when dereferencing the weak_ptr fails.

      // routes based on To-Path URIs the Session accepts
      void insert(boost::shared_ptr<Session>);
      void remove(boost::shared_ptr<Session>);

      void remove(const std::vector<Uri>&);

      // route based on Message-ID
      void insert(boost::shared_ptr<IncomingMessage>);
      void remove(boost::shared_ptr<IncomingMessage>);

      // report responses for outgoing messages
      void insert(boost::shared_ptr<OutgoingMessage>);
      void remove(boost::shared_ptr<OutgoingMessage>);

      bool process(boost::shared_ptr<const Message>);

      bool process(const asio::const_buffer&, const Message::MsgStatus);

      bool streaming() const
      {
         return mContext != mMessages.end();
      }

   private:
      typedef std::map<Uri, boost::weak_ptr<Session> > TargetMap;
      TargetMap mTargets;

      typedef std::map<std::string, boost::weak_ptr<IncomingMessage> > MessageMap;
      MessageMap mMessages;

      typedef std::map<std::string, boost::weak_ptr<OutgoingMessage> > ReportMap;
      ReportMap mReports;

      MessageMap::iterator mContext;
};

}

#endif

// Copyright 2007 Chris Bond
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

ext: hxx

max_stars_repo_name: cbond/msrp

max_issues_repo_name: cbond/msrp

max_forks_repo_name: cbond/msrp


text:
///
/// Copyright(c) 2018 Aimin Huang
/// Distributed under the MIT License (http://opensource.org/licenses/MIT)
///
#include <iostream>
#include <boost/predef.h>

#include "local_time_helper.h"
#include "trading_time_helper.h"

#if BOOST_OS_WINDOWS
#include <windows.h>
#else
#include <sys/time.h>
#endif

#if BOOST_OS_UNIX || BOOST_OS_LINUX || BOOST_OS_MACOS
#include <time.h>   // Needed for struct timespec on linux and unix and macos
//nanosleep((const struct timespec[]){{0, milli * 1000000L}},  NULL);
inline void UnifiedSleep(int milli){ const struct timespec tim = { milli/1000, (milli%1000) * 1000000L };   nanosleep(&tim, NULL); }
#elif BOOST_OS_WINDOWS	////on windows
#include <Windows.h>
inline void UnifiedSleep(int milli){ Sleep(milli); }
#elif __cplusplus >= 199711L
#include <thread>         // include std::this_thread::sleep_for and std::chrono::seconds
inline void UnifiedSleep(int milli){ std::this_thread::sleep_for(std::chrono::milliseconds(milli)); }
#endif

using Galois::Utilities::LocalTimeHelper;
using Galois::Utilities::TradingTimeHelper;

void local_time_helper_test(){
	LocalTimeHelper & local_time_helper = LocalTimeHelper::create();

	char observer_time[9], observer_time2[9];
	int update_milli = 0;
	for (int i = 0; i < 10; ++i){
#if BOOST_OS_WINDOWS
		SYSTEMTIME tp;
		GetLocalTime(&tp);
		/// LONG time_ms = (tp.wSecond * 1000) + tp.wMilliseconds;
		update_milli = tp.wMilliseconds;
		//// const tm info = local_time_helper.local_time(tp.wHour * 3600 + tp.wMinute * 60 + tp.wSecond);
		const tm info ={tp.wSecond, tp.wMinute, tp.wHour, tp.wDay, tp.wMonth, tp.wYear, tp.wDayOfWeek, 0, 0};
#else
		struct timeval tp;
		gettimeofday(&tp, NULL);
		///	long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
		update_milli = tp.tv_usec / 1000;
		const tm info = local_time_helper.local_time(tp.tv_sec);
#endif

		LocalTimeHelper::to_update_time(info, observer_time);

		const tm info2 = local_time_helper.local_time();
		LocalTimeHelper::to_update_time(info2, observer_time2);

		std::cout << observer_time << " " << observer_time2 <<" "<< update_milli<< std::endl;
		UnifiedSleep(1000 * 2);
	}
}

void TradingTimeHelper_test(){
	TradingTimeHelper timer_helper("[09:30:00, 15:00:00]");
	char observer_time[9], observer_time2[9];
	int update_milli = 0;

	for (int i = 0; i < 10; ++i){
		timer_helper.RtnObservingTime(0, 0, observer_time);
		timer_helper.RtnObservingTime(update_milli, observer_time2);

		std::cout << observer_time << " " << observer_time2 << " " << update_milli << std::endl;
		UnifiedSleep(1000 * 2);
	}
}

int main(){
///	local_time_helper_test();

	TradingTimeHelper_test();
}


text:
// Boost.Range library
//
//  Copyright Thorsten Ottosen 2003-2004. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/range/
//

#include <boost/detail/workaround.hpp>

#if BOOST_WORKAROUND(BOOST_BORLANDC, BOOST_TESTED_AT(0x564))
#  pragma warn -8091 // suppress warning in Boost.Test
#  pragma warn -8057 // unused argument argc/argv in Boost.Test
#endif

#include <boost/range.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include <string>

template< class T >
const T& as_const( const T& r )
{
    return r;
}

void check_const_ranges()
{
    std::string       foo( "foo" );
    const std::string bar( "bar" );

    BOOST_CHECK( boost::const_begin( foo )  == boost::begin( as_const( foo ) ) );
    BOOST_CHECK( boost::const_end( foo )    == boost::end( as_const( foo ) ) );
    BOOST_CHECK( boost::const_rbegin( foo ) == boost::rbegin( as_const( foo ) ) );
    BOOST_CHECK( boost::const_rend( foo )   == boost::rend( as_const( foo ) ) );

    BOOST_CHECK( boost::const_begin( bar )  == boost::begin( as_const( bar ) ) );
    BOOST_CHECK( boost::const_end( bar )    == boost::end( as_const( bar ) ) );
    BOOST_CHECK( boost::const_rbegin( bar ) == boost::rbegin( as_const( bar ) ) );
    BOOST_CHECK( boost::const_rend( bar )   == boost::rend( as_const( bar ) ) );

}

boost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    boost::unit_test::test_suite* test = BOOST_TEST_SUITE( "Range Test Suite" );

    test->add( BOOST_TEST_CASE( &check_const_ranges ) );

    return test;
}


text:
/*
 * Copyright (c) 2014 CodiLime, Inc. All rights reserved.
 */

#include "bfd/bfd_server.h"
#include "bfd/bfd_session.h"
#include "bfd/bfd_udp_connection.h"
#include "bfd/test/bfd_test_utils.h"

#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <testing/gunit.h>
#include "base/test/task_test_util.h"

using namespace BFD;

#if 1
// Test with external system

class BFDExternalTest : public ::testing::Test {
 protected:
};

TEST_F(BFDExternalTest, Test1) {
    EventManager evm;
    UDPConnectionManager cm(&evm);

    const boost::asio::ip::address addr = boost::asio::ip::address::from_string("10.5.3.165");

        BFDServer server(&evm, &cm);
        BFDSessionConfig config1;
        config1.desiredMinTxInterval = boost::posix_time::milliseconds(1000);
        config1.requiredMinRxInterval = boost::posix_time::milliseconds(1000);
        config1.detectionTimeMultiplier = 3;
        Discriminator disc1;
        server.createSession(addr, &config1, &disc1);

        cm.RegisterCallback(boost::bind(&BFDServer::processControlPacket, &server, _1));

        EventManagerThread emt(&evm);
        for (;;) {
            boost::this_thread::sleep(boost::posix_time::milliseconds(100));
        }
}

#endif

int main(int argc, char **argv) {
    LoggingInit();
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

max_stars_repo_name: safchain/contrail-controller

max_issues_repo_name: safchain/contrail-controller

max_forks_repo_name: safchain/contrail-controller


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


text:
#include <stdint.h>
#include "../../include/lsl_cpp.h"
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <map>
#include <time.h>
#include <stdlib.h>
using namespace std;

// set to true by the main program when we're ready to quit
bool stop_inlet = false, stop_outlet = false, start_outlet = false;

// get the current time
double now() { return lsl::local_clock(); }

// initialize a sample with data
template<class T>
vector<T> init_sample(int numchan) {
	vector<T> sample(numchan);
	for (int c=0;c<numchan;c++)
		sample[c] = 17.3;
	return sample;
}

// initialize a sample with data
template<class T>
void init_sample(int numchan, vector<T> &sample) {
	sample.resize(numchan);
	for (int c=0;c<numchan;c++)
		sample[c] = 17.3f;
}

// run an outlet
template<class T>
void run_outlet(string name, string type, int numchan, lsl::channel_format_t fmt, double srate, int chunk_len, int max_samples) {
	try {
		// create a new streaminfo and outlet
		std::ostringstream uid; uid << name << type << numchan << fmt;
		lsl::stream_info info(name,type,numchan,srate,fmt,uid.str());
		lsl::stream_outlet outlet(info);
		cout << "outlet started." << endl;

		while (!start_outlet)
			lslboost::this_thread::sleep(lslboost::posix_time::milliseconds(1));

		// initialize data to send
		vector<T> sample,chunk;
		init_sample(numchan,sample);
		init_sample((int)(numchan*(chunk_len*srate/1000*5)),chunk);

		// send in bursts
		double start_time = lsl::local_clock();
		for (int target,diff,written=0;written<max_samples && !stop_outlet;written+=diff) {
			lslboost::this_thread::sleep(lslboost::posix_time::milliseconds(chunk_len));
			target = (int)floor((lsl::local_clock()-start_time)*srate);
			int num_elements = std::min((std::size_t)((target-written)*numchan),chunk.size());
			outlet.push_chunk_multiplexed(&chunk[0],num_elements);
			diff = num_elements/numchan;
		}
		cout << "outlet finished." << endl;
	}
	catch(lslboost::thread_interrupted &) {}
	catch(std::exception &e) {
		std::cerr << "ERROR during run_outlet() Stress-test function: " <<	e.what() << std::endl;
	}
}

// run an inlet for some time (optionally with sporadic interruptions in between)
template<class T>
void run_inlet(string type, bool in_chunks, int buffer_len) {
	try {
		vector<vector<T> > chunk;
		vector<T> sample;

		// resolve by type and create inlet
		vector<lsl::stream_info> results = lsl::resolve_stream("type",type);
		lsl::stream_inlet inlet(results[0],buffer_len);
		cout << "inlet started." << endl;
		start_outlet = true;

		// variables for data rate testing
		double starttime = lsl::local_clock(), next_display = starttime+1;
		double ts, last_ts;

		// run
		for (int k=0,num_samples=0;!stop_inlet;k++) {
			lslboost::this_thread::sleep(lslboost::posix_time::milliseconds(10));
			if (in_chunks) {
				inlet.pull_chunk(chunk);
				num_samples += chunk.size();
			} else {
				while (ts = inlet.pull_sample(sample,0.0)) {
					last_ts = ts;
					num_samples++;
				}
			}
			// display code
			if (k % 50 == 0) {
				double now = lsl::local_clock();
				if (now>next_display) {
					cout << num_samples/(now-starttime) << " samples/sec" << endl; // " samples/sec; latency = " << 1000*(now-last_ts) << " ms." << endl; // NOTE: testing latency requires that data is sent with a burst length of 0
					next_display = now+1;
				}
			}
		}
		cout << "inlet finished." << endl;
	}
	catch(lslboost::thread_interrupted &) {}
	catch(std::exception &e) {
		std::cerr << "ERROR during run_inlet() Stress-test function: " <<	e.what() << std::endl;
	}
}

int main(int argc, char* argv[]) {
	double srate = 500000;
	int numchans = 1;
	lsl::channel_format_t format = lsl::cf_int8;
	int burstlen = 10;
	int maxsamples = 10000000;
	int bufferlen = 10;
	if (argc > 1)
		srate = lslboost::lexical_cast<double>(argv[1]);
	if (argc > 2)
		numchans = lslboost::lexical_cast<int>(argv[2]);
	if (argc > 3) {
		std::map<std::string,lsl::channel_format_t> m; m["int8"]=lsl::cf_int8;m["int16"]=lsl::cf_int16;m["int32"]=lsl::cf_int32;m["int64"]=lsl::cf_int64;m["float"]=lsl::cf_float32;m["double"]=lsl::cf_double64;m["float32"]=lsl::cf_float32;m["double64"]=lsl::cf_double64; m["string"]=lsl::cf_string;
		format = m[argv[3]];
	}
	if (argc > 4)
		burstlen = lslboost::lexical_cast<int>(argv[4]);
	if (argc > 5)
		maxsamples = lslboost::lexical_cast<int>(argv[5]);
	if (argc > 6)
		bufferlen = lslboost::lexical_cast<int>(argv[6]);

	{
		// fast serial transmission (1-channel char)
		lslboost::thread outlet(lslboost::bind(&run_outlet<float>,"FastSerial","Serial",numchans,format,srate,burstlen,maxsamples));
		lslboost::thread inlet(lslboost::bind(&run_inlet<float>,"Serial",false,bufferlen));

		// typical audio transmission (44KHz, 2-ch, 16-bit, 512-sample chunks)
		//boost::thread a(boost::bind(&run_outlet<char>,"TypicalAudio","Audio",2,lsl::cf_int16,44100,512,1000000));
		//boost::thread b(boost::bind(&run_inlet<char>,"Audio",true,10));

		// HD video transmission (30Hz, 2-ch, 16-bit, 512-sample chunks)
		//boost::thread outlet(boost::bind(&run_outlet<char>,"HDVideo","Video",640*480*3,lsl::cf_int8,10,0,1000000));
		//boost::thread inlet(boost::bind(&run_inlet<char>,"Video",false,1));

		//boost::thread highchan_outlet_thread(boost::bind(&run_outlet,1000000,"HighChanStream","Video",1920*1080*3,lsl::cf_int8,60,1000000,-1));
		//boost::thread highchan_inlet_thread(boost::bind(&run_inlet,1000000,"HighChanStream","Video",false,false,false,1000000));
		//cout << "Press [Enter] to exit: " << endl; cin.get();

		// take'em down
		outlet.join();
		stop_inlet = true;
		inlet.join();
	}
	cout << "exiting..." << endl;
	return 0;
}

max_stars_repo_name: mvidaldp/liblsl-android-builder

max_issues_repo_name: mvidaldp/liblsl-android-builder

max_forks_repo_name: mvidaldp/liblsl-android-builder


text:
/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Rice University nor the names of its
*     contributors may 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
*  COPYRIGHT OWNER 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.
*********************************************************************/

/* Author: Mark Moll */

#include <ompl/base/spaces/DubinsStateSpace.h>
#include <ompl/base/spaces/ReedsSheppStateSpace.h>
#include <ompl/base/ScopedState.h>
#include <ompl/geometric/SimpleSetup.h>
#include <boost/program_options.hpp>

namespace ob = ompl::base;
namespace og = ompl::geometric;
namespace po = boost::program_options;

// The easy problem is the standard narrow passage problem: two big open
// spaces connected by a narrow passage. The hard problem is essentially
// one long narrow passage with the robot facing towards the long walls
// in both the start and goal configurations.

bool isStateValidEasy(const ob::SpaceInformation *si, const ob::State *state)
{
    const ob::SE2StateSpace::StateType *s = state->as<ob::SE2StateSpace::StateType>();
    double x=s->getX(), y=s->getY();
    return si->satisfiesBounds(s) && (x<5 || x>13 || (y>8.5 && y<9.5));
}

bool isStateValidHard(const ob::SpaceInformation *si, const ob::State *state)
{
    return si->satisfiesBounds(state);
}

void plan(ob::StateSpacePtr space, bool easy)
{
    ob::ScopedState<> start(space), goal(space);
    ob::RealVectorBounds bounds(2);
    bounds.setLow(0);
    if (easy)
        bounds.setHigh(18);
    else
    {
        bounds.high[0] = 6;
        bounds.high[1] = .6;
    }
    space->as<ob::SE2StateSpace>()->setBounds(bounds);

    // define a simple setup class
    og::SimpleSetup ss(space);

    // set state validity checking for this space
    ob::SpaceInformationPtr si(ss.getSpaceInformation());
    ss.setStateValidityChecker(boost::bind(
        easy ? &isStateValidEasy : &isStateValidHard, si.get(), _1));

    // set the start and goal states
    if (easy)
    {
        start[0] = start[1] = 1.; start[2] = 0.;
        goal[0] = goal[1] = 17; goal[2] = -.99*boost::math::constants::pi<double>();
    }
    else
    {
        start[0] = start[1] = .5; start[2] = .5*boost::math::constants::pi<double>();;
        goal[0] = 5.5; goal[1] = .5; goal[2] = .5*boost::math::constants::pi<double>();
    }
    ss.setStartAndGoalStates(start, goal);

    // this call is optional, but we put it in to get more output information
    ss.getSpaceInformation()->setStateValidityCheckingResolution(0.005);
    ss.setup();
    ss.print();

    // attempt to solve the problem within 30 seconds of planning time
    ob::PlannerStatus solved = ss.solve(30.0);

    if (solved)
    {
        std::vector<double> reals;

        std::cout << "Found solution:" << std::endl;
        ss.simplifySolution();
        og::PathGeometric path = ss.getSolutionPath();
        path.interpolate(1000);
        path.printAsMatrix(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
}

void printTrajectory(ob::StateSpacePtr space, const std::vector<double>& pt)
{
    if (pt.size()!=3) throw ompl::Exception("3 arguments required for trajectory option");
    const unsigned int num_pts = 50;
    ob::ScopedState<> from(space), to(space), s(space);
    std::vector<double> reals;

    from[0] = from[1] = from[2] = 0.;

    to[0] = pt[0];
    to[1] = pt[1];
    to[2] = pt[2];

    std::cout << "distance: " << space->distance(from(), to()) << "\npath:\n";
    for (unsigned int i=0; i<=num_pts; ++i)
    {
        space->interpolate(from(), to(), (double)i/num_pts, s());
        reals = s.reals();
        std::cout << "path " << reals[0] << ' ' << reals[1] << ' ' << reals[2] << ' ' << std::endl;
    }
}

void printDistanceGrid(ob::StateSpacePtr space)
{
    // print the distance for (x,y,theta) for all points in a 3D grid in SE(2)
    // over [-5,5) x [-5, 5) x [-pi,pi).
    //
    // The output should be redirected to a file, say, distance.txt. This
    // can then be read and plotted in Matlab like so:
    //     x = reshape(load('distance.txt'),200,200,200);
    //     for i=1:200,
    //         contourf(squeeze(x(i,:,:)),30);
    //         axis equal; axis tight; colorbar; pause;
    //     end;
    const unsigned int num_pts = 200;
    ob::ScopedState<> from(space), to(space);
    from[0] = from[1] = from[2] = 0.;

    for (unsigned int i=0; i<num_pts; ++i)
        for (unsigned int j=0; j<num_pts; ++j)
            for (unsigned int k=0; k<num_pts; ++k)
            {
                to[0] = 5. * (2. * (double)i/num_pts - 1.);
                to[1] = 5. * (2. * (double)j/num_pts - 1.);
                to[2] = boost::math::constants::pi<double>() * (2. * (double)k/num_pts - 1.);
                std::cout << space->distance(from(), to()) << '\n';
            }

}

int main(int argc, char* argv[])
{
    try
    {
        po::options_description desc("Options");
        desc.add_options()
            ("help", "show help message")
            ("dubins", "use Dubins state space")
            ("dubinssym", "use symmetrized Dubins state space")
            ("reedsshepp", "use Reeds-Shepp state space (default)")
            ("easyplan", "solve easy planning problem and print path")
            ("hardplan", "solve hard planning problem and print path")
            ("trajectory", po::value<std::vector<double > >()->multitoken(),
                "print trajectory from (0,0,0) to a user-specified x, y, and theta")
            ("distance", "print distance grid")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc,
            po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);
        po::notify(vm);

        if (vm.count("help") || argc==1)
        {
            std::cout << desc << "\n";
            return 1;
        }

        ob::StateSpacePtr space(new ob::ReedsSheppStateSpace);

        if (vm.count("dubins"))
            space = ob::StateSpacePtr(new ob::DubinsStateSpace);
        if (vm.count("dubinssym"))
            space = ob::StateSpacePtr(new ob::DubinsStateSpace(1., true));
        if (vm.count("easyplan"))
            plan(space, true);
        if (vm.count("hardplan"))
            plan(space, false);
        if (vm.count("trajectory"))
            printTrajectory(space, vm["trajectory"].as<std::vector<double> >());
        if (vm.count("distance"))
            printDistanceGrid(space);
    }
    catch(std::exception& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        std::cerr << "Exception of unknown type!\n";
    }

    return 0;
}

max_stars_repo_name: ivaROS/ivaOmplCore

max_issues_repo_name: ivaROS/ivaOmplCore

max_forks_repo_name: ivaROS/ivaOmplCore


text:
#ifndef BOOST_RANGE_RANGE_SINGLE_IMPL_HPP
#define BOOST_RANGE_RANGE_SINGLE_IMPL_HPP

// Boost.Range 2.0 Extension library
// via PStade Oven Library
//
// Copyright Akira Takahashi 2011.
// Copyright Shunsuke Sogame 2005-2007.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/utility/addressof.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>

namespace boost {

namespace range {
    template <class T>
    inline iterator_range<const T*> single(const T& x)
    {
        return make_iterator_range(boost::addressof(x), boost::addressof(x) + 1);
    }

    template <class T>
    inline iterator_range<T*> single(T& x)
    {
        return make_iterator_range(boost::addressof(x), boost::addressof(x) + 1);
    }
} // namespace range

} // namespace boost

#endif // BOOST_RANGE_RANGE_SINGLE_IMPL_HPP

max_stars_repo_name: Flast/OvenToBoost

max_issues_repo_name: Flast/OvenToBoost

max_forks_repo_name: Flast/OvenToBoost


text:
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// Warning! This file is autogenerated.
#include <boost/text/data_versions.hpp>

namespace boost { namespace text {

    library_version unicode_version() { return { 11, 0, 0 }; }

    library_version cldr_version() { return { 33, 1, 0 }; }

}}


text:
/**
   @file infocommand.cpp
   @brief This file is part of Kalinka mediaserver.
   @author Ivan Murashko <ivan.murashko@gmail.com>

   Copyright (c) 2007-2012 Kalinka Team

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   CHANGE HISTORY

   @date
   - 2009/01/17 created by ipp (Ivan Murashko)
   - 2009/08/02 header was changed by header.py script
   - 2010/01/06 header was changed by header.py script
   - 2011/01/01 header was changed by header.py script
   - 2012/02/03 header was changed by header.py script
*/

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

#include <boost/bind.hpp>

#include "infocommand.h"
#include "defines.h"
#include "dvbdev.h"
#include "utils.h"
#include "dvb.h"
#include "utils/utils.h"

using namespace klk;
using namespace klk::dvb;

//
// InfoCommand class
//

const std::string INFOSUMMARY = "Lists all dvb cards and status information. when adapter name is given, the selected adapter is shown. all lists all available adapters.";
const std::string INFOUSAGE = "Usage: " + MODNAME +
    +" " + INFONAME + " [resource_name] | [all]\n";

// Constructor
InfoCommand::InfoCommand() :
    BaseCommand(INFONAME, INFOSUMMARY, INFOUSAGE)
{
}

// Process the command
// @param[in] params - the parameters
const std::string InfoCommand::process(const cli::ParameterVector& params)

{
    StringList list = getDevNames();

    if (list.empty())
    {
        return "There is no any DVB cards\n";
    }

    if (params.empty() || params.size() > 1)
    {
        return INFOUSAGE;
    }

    BOOST_ASSERT(params.size() == 1);
    std::string result;
    if (params[0] == cli::ALL)
    {
        std::for_each(list.begin(), list.end(),
                      boost::bind(&InfoCommand::getInfo,
                                  this, _1, &result));
    }
    else
    {
        StringList::iterator i = std::find(
            list.begin(), list.end(),
            params[0]);
        if (i == list.end())
        {
            result = "Unknown device name: " + params[0] + "\n";
        }
        else
        {
            getInfo(*i, &result);
        }
    }

    return result;
}

// Retrives specified param info for a dev
const std::string
InfoCommand::getParamInfo(const std::string& param, const IDevPtr& dev) const
{
    if (dev->hasParam(param))
    {
        return dev->getStringParam(param);
    }

    return NOTAVAILABLE;
}

// Retrives info about the specified dev
void InfoCommand::getInfo(const std::string& name,
                          std::string* result)
{
    BOOST_ASSERT(result);
    const std::string NAME = "name: ";
    const std::string ADAPTER = "adapter: ";
    const std::string FRONTEND = "frontend: ";
    const std::string TYPE = "type: ";
    const std::string SIGNAL_SOURCE = "signal source: ";
    const std::string FREQUENCY = "frequency: ";
    const std::string STATUS = "status: ";
    const std::string SIGNAL = "signal: ";
    const std::string SNR = "snr: ";
    const std::string BER = "ber: ";
    const std::string UNC = "unc: ";
    const std::string BANDWIDTH = "bandwidth: ";
    const std::string ACTIVITY = "activity: ";
    const std::string TUNED_CHANNELS = "tuned channels: ";

    // FIXME!!! add check all lengths
    size_t max_size = TUNED_CHANNELS.size();

    IDevPtr dev = getDev(name);
    *result += "\n\n";
    *result += base::Utils::align(NAME, max_size) +
        dev->getStringParam(dev::NAME) + "\n";
    *result += base::Utils::align(ADAPTER, max_size) +
        dev->getStringParam(dev::ADAPTER) + "\n";
    *result += base::Utils::align(FRONTEND, max_size) +
        dev->getStringParam(dev::FRONTEND) + "\n";

    *result += base::Utils::align(TYPE, max_size);
    if (dev->getStringParam(dev::TYPE) == dev::DVB_S)
    {
        *result += DVB_S_NAME;
    }
    else if (dev->getStringParam(dev::TYPE) == dev::DVB_T)
    {
        *result += DVB_T_NAME;
    }
    else if (dev->getStringParam(dev::TYPE) == dev::DVB_C)
    {
        *result += DVB_C_NAME;
    }
    else
    {
        BOOST_ASSERT(false);
    }
    *result += "\n";

    *result += base::Utils::align(FREQUENCY, max_size) +
        getParamInfo(dev::FREQUENCY, dev) + " Hz\n";

    std::string source_name;
    try
    {
        source_name = Utils::getSourceName(getFactory(),
                                           dev->getStringParam(dev::SOURCE));
    }
    catch(...)
    {
        source_name = NOTAVAILABLE;
    }

    *result += base::Utils::align(SIGNAL_SOURCE, max_size) +
        source_name + "\n";

    *result += base::Utils::align(STATUS, max_size);
    if (dev->hasParam(dev::HASLOCK))
    {
        if (dev->getStringParam(dev::HASLOCK) == "0")
        {
            *result += "does not have lock";
        }
        else
        {
            *result += "has lock";
        }
    }
    *result += "\n";

    *result += base::Utils::align(SIGNAL, max_size) +
        getParamInfo(dev::SIGNAL, dev) + "\n";
    *result += base::Utils::align(SNR, max_size) +
        getParamInfo(dev::SNR, dev) + "\n";
    *result += base::Utils::align(BER, max_size) +
        getParamInfo(dev::BER, dev) + "\n";
    *result += base::Utils::align(UNC, max_size) +
        getParamInfo(dev::UNC, dev) + "\n";
    *result += base::Utils::align(BANDWIDTH, max_size) +
        getParamInfo(dev::BANDWIDTH, dev) + " kHz\n";

    if (dev->getState() == dev::IDLE)
    {
        *result += base::Utils::align(ACTIVITY, max_size) +
            "idle\n";
    }
    else if (dev->getStringParam(dev::DVBACTIVITY) == dev::STREAMING)
    {
        *result += base::Utils::align(ACTIVITY, max_size) +
            "in use\n";

        *result += base::Utils::align(TUNED_CHANNELS, max_size);
        StringList list =
            getModule<DVB>()->getProcessor()->getChannelNames(dev);
        for (StringList::iterator i = list.begin(); i !=list.end(); i++)
        {
            if (i != list.begin())
                *result += ", ";
            *result += *i;
        }

        *result += "\n";
    }
    else if (dev->getStringParam(dev::DVBACTIVITY) == dev::SCANING)
    {
        *result += base::Utils::align(ACTIVITY, max_size) +
            "in use\n";
    }
}

// Retrives list of possible completions for a n's parameter
const cli::ParameterVector
InfoCommand::getCompletion(const cli::ParameterVector& setparams)
{
    cli::ParameterVector result;

    if (setparams.empty())
    {
        result.push_back(cli::ALL);
        StringList list = getDevNames();
        std::copy(list.begin(), list.end(),
                  std::back_inserter(result));
    }

    return result;
}

max_stars_repo_name: ivanmurashko/kalinka

max_issues_repo_name: ivanmurashko/kalinka

max_forks_repo_name: ivanmurashko/kalinka


text:
#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <libfr.h>

#include <QApplication>
#include <QWidget>

#include <gtest/gtest.h>

namespace fr {
	namespace app {
        class AppDemo : public BaseApp
		{
        public:
            static const unsigned short DEFAULT_WINDOW_WIDTH = 250;
            static const unsigned short DEFAULT_WINDOW_HEIGHT = 150;
            static const char* DEFAULT_WINDOW_TITLE;

        public:
            /* virtual */ void InitOptions()
            {
                // Init parent options
                BaseApp::InitOptions();

                // Specify program options
                Opts.add_options()
                    ("gui,g", "show gui")
                    ("test,t", "run test")
                    ;
            }

            /* virtual */ int Run(int argc, const char** argv)
            {
                // You are right. This is overriden just for educational purposes.
                return BaseApp::Run(argc, argv);
            }

            /* virtual */ int ProcessOptions()
            {
                // GUI
                if(Args.count("gui"))
                {
                    QApplication app(Argc, const_cast<char**>(Argv));

                    QWidget window;

                    window.resize(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT);
                    window.setWindowTitle("Demo");
                    window.show();

                    return app.exec();
                }

                // Test app if requested
                if(Args.count("test"))
                {
                    std::cout << "Running the test." << std::endl;
                    // Tests that the Foo::Bar() method does Abc.

                    Test();

                    return EXIT_SUCCESS;
                }

                // If no arguments were specified print help and exit
                if(Argc < 1)
                {
                    PrintHelpMessage();
                    return EXIT_FAILURE;
                }

                // Print help and exit if needed
                if (Args.size() < 1)
                {
                    std::cout << Opts << std::endl;
                    return EXIT_SUCCESS;
                }

                // Let base process it ...
                return BaseApp::ProcessOptions();
            }

        private:
            void Test()
            {
                // ASSERT_TRUE(true);
            }
		}; // AppDemo
    } // namespace app
} // namespace fr

int main(int argc, const char** argv)
{
    // See http://www.zetcode.com/gui/qt4/firstprograms/
    return fr::app::AppDemo().Run(argc, argv);
}

max_stars_repo_name: mdqyy/libfr

max_issues_repo_name: mdqyy/libfr

max_forks_repo_name: mdqyy/libfr


text:
#include <Storages/ColumnsDescription.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ExpressionElementParsers.h>
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/parseQuery.h>
#include <Parsers/queryToString.h>
#include <IO/WriteBuffer.h>
#include <IO/WriteHelpers.h>
#include <IO/ReadBuffer.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteBufferFromString.h>
#include <IO/ReadBufferFromString.h>
#include <DataTypes/DataTypeFactory.h>
#include <Common/Exception.h>
#include <Common/typeid_cast.h>

#include <ext/collection_cast.h>
#include <ext/map.h>

#include <boost/range/join.hpp>

#include <optional>

namespace DB
{

namespace ErrorCodes
{
    extern const int NO_SUCH_COLUMN_IN_TABLE;
    extern const int CANNOT_PARSE_TEXT;
}

NamesAndTypesList ColumnsDescription::getAllPhysical() const
{
    return ext::collection_cast<NamesAndTypesList>(boost::join(ordinary, materialized));
}

NamesAndTypesList ColumnsDescription::getAll() const
{
    return ext::collection_cast<NamesAndTypesList>(boost::join(ordinary, boost::join(materialized, aliases)));
}

Names ColumnsDescription::getNamesOfPhysical() const
{
    return ext::map<Names>(boost::join(ordinary, materialized), [] (const auto & it) { return it.name; });
}

NameAndTypePair ColumnsDescription::getPhysical(const String & column_name) const
{
    for (auto & it : boost::join(ordinary, materialized))
        if (it.name == column_name)
            return it;
    throw Exception("There is no column " + column_name + " in table.", ErrorCodes::NO_SUCH_COLUMN_IN_TABLE);
}

bool ColumnsDescription::hasPhysical(const String & column_name) const
{
    for (auto & it : boost::join(ordinary, materialized))
        if (it.name == column_name)
            return true;
    return false;
}

String ColumnsDescription::toString() const
{
    WriteBufferFromOwnString buf;

    writeCString("columns format version: 1\n", buf);
    writeText(ordinary.size() + materialized.size() + aliases.size(), buf);
    writeCString(" columns:\n", buf);

    const auto write_columns = [this, &buf] (const NamesAndTypesList & columns)
    {
        for (const auto & column : columns)
        {
            const auto defaults_it = defaults.find(column.name);
            const auto comments_it = comments.find(column.name);

            writeBackQuotedString(column.name, buf);
            writeChar(' ', buf);
            writeText(column.type->getName(), buf);

            const bool exist_comment = comments_it != std::end(comments);
            if (defaults_it != std::end(defaults))
            {
                writeChar('\t', buf);
                writeText(DB::toString(defaults_it->second.kind), buf);
                writeChar('\t', buf);
                writeText(queryToString(defaults_it->second.expression), buf);
            }
            else if (exist_comment)
            {
                writeChar('\t', buf);
            }

            if (exist_comment)
            {
                writeChar('\t', buf);
                writeText(queryToString(ASTLiteral(Field(comments_it->second))), buf);
            }

            writeChar('\n', buf);
        }
    };

    write_columns(ordinary);
    write_columns(materialized);
    write_columns(aliases);
    return buf.str();
}

std::optional<ColumnDefault> parseDefaultInfo(ReadBufferFromString & buf)
{
    if (*buf.position() == '\n')
        return {};

    assertChar('\t', buf);
    if (*buf.position() == '\t')
        return {};

    String default_kind_str;
    readText(default_kind_str, buf);
    const auto default_kind = columnDefaultKindFromString(default_kind_str);
    assertChar('\t', buf);

    ParserExpression expr_parser;
    String default_expr_str;
    readText(default_expr_str, buf);
    ASTPtr default_expr = parseQuery(expr_parser, default_expr_str, "default_expression", 0);
    return ColumnDefault{default_kind, std::move(default_expr)};
}

String parseComment(ReadBufferFromString& buf)
{
    if (*buf.position() == '\n')
        return {};

    assertChar('\t', buf);
    ParserStringLiteral string_literal_parser;
    String comment_expr_str;
    readText(comment_expr_str, buf);
    ASTPtr comment_expr = parseQuery(string_literal_parser, comment_expr_str, "comment expression", 0);
    return typeid_cast<ASTLiteral &>(*comment_expr).value.get<String>();
}

void parseColumn(ReadBufferFromString & buf, ColumnsDescription & result, const DataTypeFactory & data_type_factory)
{
    String column_name;
    readBackQuotedStringWithSQLStyle(column_name, buf);
    assertChar(' ', buf);

    String type_name;
    readText(type_name, buf);
    auto type = data_type_factory.get(type_name);
    if (*buf.position() == '\n')
    {
        assertChar('\n', buf);
        result.ordinary.emplace_back(column_name, std::move(type));
        return;
    }

    auto column_default = parseDefaultInfo(buf);
    if (column_default)
    {
        switch (column_default->kind)
        {
            case ColumnDefaultKind::Default:
                result.ordinary.emplace_back(column_name, std::move(type));
                break;
            case ColumnDefaultKind::Materialized:
                result.materialized.emplace_back(column_name, std::move(type));
                break;
            case ColumnDefaultKind::Alias:
                result.aliases.emplace_back(column_name, std::move(type));
        }

        result.defaults.emplace(column_name, std::move(*column_default));
    }

    auto comment = parseComment(buf);
    if (!comment.empty())
    {
        result.comments.emplace(column_name, std::move(comment));
    }

    assertChar('\n', buf);
}

ColumnsDescription ColumnsDescription::parse(const String & str)
{
    ReadBufferFromString buf{str};

    assertString("columns format version: 1\n", buf);
    size_t count{};
    readText(count, buf);
    assertString(" columns:\n", buf);

    ParserExpression expr_parser;
    const DataTypeFactory & data_type_factory = DataTypeFactory::instance();

    ColumnsDescription result;
    for (size_t i = 0; i < count; ++i)
    {
        parseColumn(buf, result, data_type_factory);
    }

    assertEOF(buf);
    return result;
}

}

max_stars_repo_name: viongpanzi/ClickHouse

max_issues_repo_name: viongpanzi/ClickHouse

max_forks_repo_name: viongpanzi/ClickHouse


text:
 /**
 * @file
 *
 *   Unless noted otherwise, the portions of Isis written by the USGS are public
 *   domain. See individual third-party library and package descriptions for
 *   intellectual property information,user agreements, and related information.
 *
 *   Although Isis has been used by the USGS, no warranty, expressed or implied,
 *   is made by the USGS as to the accuracy and functioning of such software
 *   and related material nor shall the fact of distribution constitute any such
 *   warranty, and no responsibility is assumed by the USGS in connection
 *   therewith.
 *
 *   For additional information, launch
 *   $ISISROOT/doc//documents/Disclaimers/Disclaimers.html in a browser or see
 *   the Privacy & Disclaimers page on the Isis website,
 *   http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
 *   http://www.usgs.gov/privacy.html.
 */
#include <cmath>
#include <iostream>

#include <boost/math/special_functions/legendre.hpp>

#include "Camera.h"
#include "CameraFocalPlaneMap.h"
#include "Constants.h"
#include "FunctionTools.h"
#include "IString.h"
#include "LineScanCameraDetectorMap.h"
#include "NewHorizonsMvicTdiCameraDistortionMap.h"

#include <QDebug>

using namespace boost::math;
using namespace std;
using namespace Isis;

namespace Isis {
  /** Camera distortion map constructor
   *
   * Create a camera distortion map.  This class maps between distorted
   * and undistorted focal plane x/y's.  The default mapping is the
   * identity, that is, the focal plane x/y and undistorted focal plane
   * x/y will be identical.
   *
   * @param parent                 the parent camera that will use this distortion map
   * @param zDirection             the direction of the focal plane Z-axis
   *                               (either 1 or -1)
   *
   * @param xDistortionCoeffs      distortion coefficients in x
   * @param yDistortionCoeffs      distortion coefficients in y
   * @param residualColDistCoeffs
   * @param residualRowDistCoeffs
   *
   */
  NewHorizonsMvicTdiCameraDistortionMap::NewHorizonsMvicTdiCameraDistortionMap(
      Camera *parent,
      vector<double> xDistortionCoeffs,
      vector<double> yDistortionCoeffs,
      vector<double> residualColDistCoeffs,
      vector<double> residualRowDistCoeffs) :
    CameraDistortionMap(parent, 1.0) {

    m_xDistortionCoeffs = xDistortionCoeffs;
    m_yDistortionCoeffs = yDistortionCoeffs;

    m_residualColDistCoeffs = residualColDistCoeffs;
    m_residualRowDistCoeffs = residualRowDistCoeffs;

    // half of detector in x is 32.5 mm
    m_focalPlaneHalf_x = 0.5 * p_camera->Samples() * p_camera->PixelPitch();
  }

  /** Destructor
   */
  NewHorizonsMvicTdiCameraDistortionMap::~NewHorizonsMvicTdiCameraDistortionMap() {
  }

  /** Compute undistorted focal plane x/y
   *
   * Compute undistorted focal plane x given a distorted focal plane x
   *
   * TODO: Modify this - Distortion in line direction currently not considered (MVIC TDI is treated as line scan sensor)
   *
   * In the event of any failure, undistorted focal plane values are set equal to the raw
   * (distorted) values
   *
   * @param dx distorted focal plane x in millimeters
   * @param dy distorted focal plane y in millimeters
   *
   * @return success/failure
   *
   * @see SetDistortion
   */
  // TODO: Don't really like this - we always return true, even in event of failures
  bool NewHorizonsMvicTdiCameraDistortionMap::SetFocalPlane(const double dx, const double dy) {

    p_focalPlaneX = dx;
    p_focalPlaneY = dy;

    // initialize undistorted focal plane coordinates to the distorted
    // coordinate values
    p_undistortedFocalPlaneX = dx;
    p_undistortedFocalPlaneY = dy;

    // if x lies outside of the detector, do NOT apply distortion
    // set undistorted focal plane values to be identical to raw values
    if ((fabs(dx) > m_focalPlaneHalf_x)) {
      return true;
    }

    // scale x to lie in the range -1.0 to +1.0
    // this is required for Legendre Polynomials, man
    double xscaled = -dx / m_focalPlaneHalf_x;

    // compute distortion corrections in x using Legendre Polynomials
    // these corrections are also in the -1.0 to +1.0 range
    double deltax1 = 0.0;
    if (!computeDistortionCorrections(xscaled, 0.0, deltax1)) {
      return true;
    }

    // now compute residual distortion corrections (per Jason Cook)
    // TODO: implementation not complete
    double deltax2 = 0.0;
    double deltay2 = 0.0;
    computeResidualDistortionCorrections(dx, deltax2, deltay2);

    // apply the corrections
    xscaled += deltax1;

    // scale back from range of '-1.0 to +1.0' to the detector, '-32.5 to 32.5 mm'
//    p_undistortedFocalPlaneX = -xscaled * m_focalPlaneHalf_x;
//    p_undistortedFocalPlaneY = p_focalPlaneY;
    p_undistortedFocalPlaneX = -xscaled * m_focalPlaneHalf_x + deltax2;
    p_undistortedFocalPlaneY = p_focalPlaneY + deltay2;

    return true;
  }

  /** Compute distorted focal plane x/y
   *
   * Compute distorted focal plane x/y given an undistorted focal plane x/y.
   *
   * This is an iterative procedure as computing the inverse of the distortion equations used by New
   * Horizons MVIC is difficult.
   *
   * @param ux undistorted focal plane x in millimeters
   * @param uy undistorted focal plane y in millimeters
   *
   * @return if the conversion was successful
   * @see SetDistortion
   */
  bool NewHorizonsMvicTdiCameraDistortionMap::SetUndistortedFocalPlane(const double ux, const double uy) {

    // image coordinates prior to introducing distortion
    p_undistortedFocalPlaneX = ux;
    p_undistortedFocalPlaneY = uy;

    double xt = ux;
    double yt = uy;

//    p_focalPlaneX = p_undistortedFocalPlaneX;
//    p_focalPlaneY = p_undistortedFocalPlaneY;
//    return true;

    // scale undistorted coordinates to range of -1.0 to +1.0
    double uxScaled = -ux/m_focalPlaneHalf_x;
    double xtScaled;
    double xprevious, yprevious;
    double scaledDeltax;
    double deltax2 = 0.0;
    double deltay2 = 0.0;

    xprevious = 1000000.0;
    yprevious = 1000000.0;

    double tolerance = 0.000001;

    bool bConverged = false;

    // iterating to introduce distortion...
    // we stop when the difference between distorted coordinates
    // in successive iterations is at or below the given tolerance
    for ( int i = 0; i < 50; i++ ) {

      xtScaled = -xt / m_focalPlaneHalf_x;

      // Changed this failure mode from a throw to return false.  These functions should never
      // throw, the callers are not catching, so bad things happen.  The callers should be checking
      // the return status
      if (fabs(xtScaled) > 1.0) {
        return bConverged;
      }

      // compute scaled distortion in x (scaled to -1.0 - +1.0) using Legendre Polynomials
      computeDistortionCorrections(xtScaled, 0.0, scaledDeltax);

      // compute residual distortion in unscaled focal plane coordinates
      computeResidualDistortionCorrections(xt, deltax2, deltay2);

      // update unscaled coordinates
      xt = -(uxScaled-scaledDeltax) * m_focalPlaneHalf_x - deltax2;
      yt = uy - deltay2;

      // check for convergenceyScaledDistortion
      if ((fabs(xt - xprevious) <= tolerance) && (fabs(yt - yprevious) <= tolerance)) {
        bConverged = true;
        break;
      }

      xprevious = xt;
      yprevious = yt;
    }

    if (bConverged) {
      // scale x coord inate back to detector (-32.5 to +32.5)
      // xtScaled *= -m_focalPlaneHalf_x;

      // set distorted coordinates
      p_focalPlaneX = xt;
      p_focalPlaneY = yt;
    }

    return bConverged;
  }

  /** Compute distortion corrections in x and y direction
   *
   * For Legendre Polynomials, see ...
   *
   * http://mathworld.wolfram.com/LegendrePolynomial.html
   * http://www.boost.org/doc/libs/1_36_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_poly/legendre.html
   *
   * @param xscaled focal plane x scaled to range of 1- to 1 for Legendre Polynomials
   * @param yscaled focal plane y scaled to range of 1- to 1 for Legendre Polynomials
   * @param deltax focal plane distortion correction to x in millimeters
   * @param deltay focal plane distortion correction to y in millimeters
   *
   * @return success/failure
   */
  bool NewHorizonsMvicTdiCameraDistortionMap::computeDistortionCorrections(
      const double xscaled,
      const double yscaled,
      double &deltax) {

    double lpx0, lpx1, lpx2, lpx3, lpx4, lpx5;
    double lpy0, lpy1, lpy2, lpy3, lpy4, lpy5;

    // Legendre polynomials
    try {
      lpx0 = legendre_p(0,xscaled);
      lpx1 = legendre_p(1,xscaled);
      lpx2 = legendre_p(2,xscaled);
      lpx3 = legendre_p(3,xscaled);
      lpx4 = legendre_p(4,xscaled);
      lpx5 = legendre_p(5,xscaled);
      lpy0 = legendre_p(0,yscaled);
      lpy1 = legendre_p(1,yscaled);
      lpy2 = legendre_p(2,yscaled);
      lpy3 = legendre_p(3,yscaled);
      lpy4 = legendre_p(4,yscaled);
      lpy5 = legendre_p(5,yscaled);
    }
    catch (const std::exception& e) {
      return false;
    }

    deltax =
       m_xDistortionCoeffs[0] * lpx0  * lpy1 +
       m_xDistortionCoeffs[1] * lpx1 * lpy0 +
       m_xDistortionCoeffs[2] * lpx0 * lpy2 +
       m_xDistortionCoeffs[3] * lpx1 * lpy1 +
       m_xDistortionCoeffs[4] * lpx2 * lpy0 +
       m_xDistortionCoeffs[5] * lpx0 * lpy3 +
       m_xDistortionCoeffs[6] * lpx1 * lpy2 +
       m_xDistortionCoeffs[7] * lpx2 * lpy1 +
       m_xDistortionCoeffs[8] * lpx3 * lpy0 +
       m_xDistortionCoeffs[9] * lpx0 * lpy4 +
      m_xDistortionCoeffs[10] * lpx1 * lpy3 +
      m_xDistortionCoeffs[11] * lpx2 * lpy2 +
      m_xDistortionCoeffs[12] * lpx3 * lpy1 +
      m_xDistortionCoeffs[13] * lpx4 * lpy0 +
      m_xDistortionCoeffs[14] * lpx0 * lpy5 +
      m_xDistortionCoeffs[15] * lpx1 * lpy4 +
      m_xDistortionCoeffs[16] * lpx2 * lpy3 +
      m_xDistortionCoeffs[17] * lpx3 * lpy2 +
      m_xDistortionCoeffs[18] * lpx4 * lpy1 +
      m_xDistortionCoeffs[19] * lpx5 * lpy0;

    return true;
  }

  /** Compute residual distortion corrections in row and column direction
   *  TODO: Implementati plete
   *
   * @param dx
   * @param dy
   * @param residualDeltax
   * @param residualDeltay
   *
   * @return success/failure
   */
  void NewHorizonsMvicTdiCameraDistortionMap::computeResidualDistortionCorrections(const double dx,
                                                             double &residualDeltax,
                                                             double &residualDeltay) {

    double s = 2500.5 - dx/0.013;

    residualDeltax = s * m_residualColDistCoeffs[1] +
                       pow(s,2) * m_residualColDistCoeffs[2] +
                       pow(s,3) * m_residualColDistCoeffs[3] +
                       pow(s,4) * m_residualColDistCoeffs[4] +
                       pow(s,5) * m_residualColDistCoeffs[5];

    residualDeltay = s * m_residualRowDistCoeffs[1] +
                       pow(s,2) * m_residualRowDistCoeffs[2] +
                       pow(s,3) * m_residualRowDistCoeffs[3] +
                       pow(s,4) * m_residualRowDistCoeffs[4] +
                       pow(s,5) * m_residualRowDistCoeffs[5];

    // convert to mm (correction for negative x to the left)
    residualDeltax *= -p_camera->PixelPitch();
    residualDeltay *= p_camera->PixelPitch();
  }

///**
// * Testing method to output corrections in x and y at pixel centers for entire focal plane.
// * Output in csv format for viewing/plotting in Excel.
// */
//bool NewHorizonsMvicTdiCameraDistortionMap::outputResidualDeltas() {
//
//  QString ofname("mvic_tdi_residual_deltas.csv");
//  std::ofstream fp_out(ofname.toLatin1().data(), std::ios::out);
//  if (!fp_out)
//    return false;
//
//  char buf[1056];
//
//  double residualColDelta;
//
//  for (int s=0; s <= 5000; s++) {  // loop in sample direction
//    residualColDelta =            m_residualColDistCoeffs[0] +
//                              s * m_residualColDistCoeffs[1] +
//                       pow(double(s),2) * m_residualColDistCoeffs[2] +
//                       pow(double(s),3) * m_residualColDistCoeffs[3] +
//                       pow(double(s),4) * m_residualColDistCoeffs[4] +
//                       pow(double(s),5) * m_residualColDistCoeffs[5];
//    sprintf(buf, "%d,%lf\n", s, residualColDelta);
//    fp_out << buf;
//  }
//
//  fp_out.close();
//
//  return true;
//}

}