text:
// @@@LICENSE
//
//      Copyright (c) 2010-2013 LG Electronics, Inc.
//
// 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.
//
// LICENSE@@@

#include "protocol/UidSearchResponseParser.h"
#include <boost/algorithm/string/predicate.hpp>
#include <sstream>

using namespace std;

UidSearchResponseParser::UidSearchResponseParser(ImapSession& session, DoneSignal::SlotRef doneSlot, vector<UID>& uidList)
: ImapResponseParser(session, doneSlot), m_uidList(uidList)
{
}

UidSearchResponseParser::~UidSearchResponseParser()
{
}

// Fast UID list parser
bool UidSearchResponseParser::ParseUids(const std::string& line, std::vector<UID>& uids)
{
	UID uidTemp = 0;

	for(string::const_iterator it = line.begin(); it != line.end(); ++it) {
		char c = *it;

		if(c == ' ') {
			if(uidTemp > 0) { // uids can't be zero
				uids.push_back(uidTemp);
				uidTemp = 0;
			}
		} else if(c >= '0' && c <= '9') {
			UID temp = uidTemp * 10 + ((int)c - '0');

			if(temp >= uidTemp) {
				uidTemp = temp;
			} else {
				// If the number went *down*, we overflowed the unsigned int.
				// UIDs must fit in a 32-bit integer.
				return false;
			}

		} else {
			// Error -- not a number
			return false;
		}
	}

	if(uidTemp > 0) {
		uids.push_back(uidTemp);
	}

	return true;
}

bool UidSearchResponseParser::HandleUntaggedResponse(const string& line)
{
	if(boost::istarts_with(line, "SEARCH")) {
		string word; // should be search
		string rest;

		SplitOnce(line, word, rest);

		ParseUids(rest, m_uidList);
	}
	return false;
}

void UidSearchResponseParser::HandleResponse(ImapStatusCode status, const string& response)
{
	// TODO handle response
}

max_stars_repo_name: webOS-ports/mojomail

max_issues_repo_name: openwebos/app-services

max_forks_repo_name: openwebos/app-services


text:
/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2013, Autonomous Systems Laboratory, Stanford 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 Stanford 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.
*********************************************************************/

/* Authors: Ashley Clark (Stanford) and Wolfgang Pointner (AIT) */
/* Co-developers: Brice Rebsamen (Stanford), Tim Wheeler (Stanford)
                  Edward Schmerling (Stanford), and Javier V. Gómez (UC3M - Stanford)*/
/* Algorithm design: Lucas Janson (Stanford) and Marco Pavone (Stanford) */
/* Acknowledgements for insightful comments: Oren Salzman (Tel Aviv University),
 *                                           Joseph Starek (Stanford) */

#include <limits>
#include <iostream>

#include <boost/math/constants/constants.hpp>
#include <boost/math/distributions/binomial.hpp>

#include <ompl/datastructures/BinaryHeap.h>
#include <ompl/tools/config/SelfConfig.h>
#include <ompl/base/objectives/PathLengthOptimizationObjective.h>
#include <ompl/geometric/planners/fmt/FMT.h>

ompl::geometric::FMT::FMT(const base::SpaceInformationPtr &si)
    : base::Planner(si, "FMT")
    , numSamples_(1000)
    , collisionChecks_(0)
    , nearestK_(true)
    , cacheCC_(true)
    , heuristics_(false)
    , radiusMultiplier_(1.1)
    , extendedFMT_(true)
{
    // An upper bound on the free space volume is the total space volume; the free fraction is estimated in sampleFree
    freeSpaceVolume_ = si_->getStateSpace()->getMeasure();
    lastGoalMotion_ = nullptr;

    specs_.approximateSolutions = false;
    specs_.directed = false;

    ompl::base::Planner::declareParam<unsigned int>("num_samples", this, &FMT::setNumSamples, &FMT::getNumSamples, "10:10:1000000");
    ompl::base::Planner::declareParam<double>("radius_multiplier", this, &FMT::setRadiusMultiplier, &FMT::getRadiusMultiplier, "0.1:0.05:50.");
    ompl::base::Planner::declareParam<bool>("nearest_k", this, &FMT::setNearestK, &FMT::getNearestK, "0,1");
    ompl::base::Planner::declareParam<bool>("cache_cc", this, &FMT::setCacheCC, &FMT::getCacheCC, "0,1");
    ompl::base::Planner::declareParam<bool>("heuristics", this, &FMT::setHeuristics, &FMT::getHeuristics, "0,1");
    ompl::base::Planner::declareParam<bool>("extended_fmt", this, &FMT::setExtendedFMT, &FMT::getExtendedFMT, "0,1");
}

ompl::geometric::FMT::~FMT()
{
    freeMemory();
}

void ompl::geometric::FMT::setup()
{
    if (pdef_)
    {
        /* Setup the optimization objective. If no optimization objective was
        specified, then default to optimizing path length as computed by the
        distance() function in the state space */
        if (pdef_->hasOptimizationObjective())
            opt_ = pdef_->getOptimizationObjective();
        else
        {
            OMPL_INFORM("%s: No optimization objective specified. Defaulting to optimizing path length.", getName().c_str());
            opt_.reset(new base::PathLengthOptimizationObjective(si_));
            // Store the new objective in the problem def'n
            pdef_->setOptimizationObjective(opt_);
        }
        Open_.getComparisonOperator().opt_ = opt_.get();
        Open_.getComparisonOperator().heuristics_ = heuristics_;

        if (!nn_)
            nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
        nn_->setDistanceFunction(std::bind(&FMT::distanceFunction, this,
            std::placeholders::_1, std::placeholders::_2));

        if (nearestK_ && !nn_->reportsSortedResults())
        {
            OMPL_WARN("%s: NearestNeighbors datastructure does not return sorted solutions. Nearest K strategy disabled.", getName().c_str());
            nearestK_ = false;
        }
    }
    else
    {
        OMPL_INFORM("%s: problem definition is not set, deferring setup completion...", getName().c_str());
        setup_ = false;
    }
}

void ompl::geometric::FMT::freeMemory()
{
    if (nn_)
    {
        std::vector<Motion*> motions;
        motions.reserve(nn_->size());
        nn_->list(motions);
        for (unsigned int i = 0 ; i < motions.size() ; ++i)
        {
            si_->freeState(motions[i]->getState());
            delete motions[i];
        }
    }
}

void ompl::geometric::FMT::clear()
{
    Planner::clear();
    lastGoalMotion_ = nullptr;
    sampler_.reset();
    freeMemory();
    if (nn_)
        nn_->clear();
    Open_.clear();
    neighborhoods_.clear();

    collisionChecks_ = 0;
}

void ompl::geometric::FMT::getPlannerData(base::PlannerData &data) const
{
    Planner::getPlannerData(data);
    std::vector<Motion*> motions;
    nn_->list(motions);

    if (lastGoalMotion_)
        data.addGoalVertex(base::PlannerDataVertex(lastGoalMotion_->getState()));

    unsigned int size = motions.size();
    for (unsigned int i = 0; i < size; ++i)
    {
        if (motions[i]->getParent() == nullptr)
            data.addStartVertex(base::PlannerDataVertex(motions[i]->getState()));
        else
            data.addEdge(base::PlannerDataVertex(motions[i]->getParent()->getState()),
                         base::PlannerDataVertex(motions[i]->getState()));
    }
}

void ompl::geometric::FMT::saveNeighborhood(Motion *m)
{
    // Check to see if neighborhood has not been saved yet
    if (neighborhoods_.find(m) == neighborhoods_.end())
    {
        std::vector<Motion*> nbh;
        if (nearestK_)
            nn_->nearestK(m, NNk_, nbh);
        else
            nn_->nearestR(m, NNr_, nbh);
        if (!nbh.empty())
        {
            // Save the neighborhood but skip the first element, since it will be motion m
            neighborhoods_[m] = std::vector<Motion*>(nbh.size() - 1, 0);
            std::copy(nbh.begin() + 1, nbh.end(), neighborhoods_[m].begin());
        }
        else
        {
            // Save an empty neighborhood
            neighborhoods_[m] = std::vector<Motion*>(0);
        }
    } // If neighborhood hadn't been saved yet
}

// Calculate the unit ball volume for a given dimension
double ompl::geometric::FMT::calculateUnitBallVolume(const unsigned int dimension) const
{
    if (dimension == 0)
        return 1.0;
    else if (dimension == 1)
        return 2.0;
    return 2.0 * boost::math::constants::pi<double>() / dimension
            * calculateUnitBallVolume(dimension - 2);
}

double ompl::geometric::FMT::calculateRadius(const unsigned int dimension, const unsigned int n) const
{
    double a = 1.0 / (double)dimension;
    double unitBallVolume = calculateUnitBallVolume(dimension);

    return radiusMultiplier_ * 2.0 * std::pow(a, a) * std::pow(freeSpaceVolume_ / unitBallVolume, a) * std::pow(log((double)n) / (double)n, a);
}

void ompl::geometric::FMT::sampleFree(const base::PlannerTerminationCondition &ptc)
{
    unsigned int nodeCount = 0;
    unsigned int sampleAttempts = 0;
    Motion *motion = new Motion(si_);

    // Sample numSamples_ number of nodes from the free configuration space
    while (nodeCount < numSamples_ && !ptc)
    {
        sampler_->sampleUniform(motion->getState());
        sampleAttempts++;

        bool collision_free = si_->isValid(motion->getState());

        if (collision_free)
        {
            nodeCount++;
            nn_->add(motion);
            motion = new Motion(si_);
        } // If collision free
    } // While nodeCount < numSamples
    si_->freeState(motion->getState());
    delete motion;

    // 95% confidence limit for an upper bound for the true free space volume
    freeSpaceVolume_ = boost::math::binomial_distribution<>::find_upper_bound_on_p(sampleAttempts, nodeCount, 0.05) * si_->getStateSpace()->getMeasure();
}

void ompl::geometric::FMT::assureGoalIsSampled(const ompl::base::GoalSampleableRegion *goal)
{
    // Ensure that there is at least one node near each goal
    while (const base::State *goalState = pis_.nextGoal())
    {
        Motion *gMotion = new Motion(si_);
        si_->copyState(gMotion->getState(), goalState);

        std::vector<Motion*> nearGoal;
        nn_->nearestR(gMotion, goal->getThreshold(), nearGoal);

        // If there is no node in the goal region, insert one
        if (nearGoal.empty())
        {
            OMPL_DEBUG("No state inside goal region");
            if (si_->getStateValidityChecker()->isValid(gMotion->getState()))
            {
                nn_->add(gMotion);
                goalState_ = gMotion->getState();
            }
            else
            {
                si_->freeState(gMotion->getState());
                delete gMotion;
            }
        }
        else // There is already a sample in the goal region
        {
            goalState_ = nearGoal[0]->getState();
            si_->freeState(gMotion->getState());
            delete gMotion;
        }
    } // For each goal
}

ompl::base::PlannerStatus ompl::geometric::FMT::solve(const base::PlannerTerminationCondition &ptc)
{
    if (lastGoalMotion_) {
        OMPL_INFORM("solve() called before clear(); returning previous solution");
        traceSolutionPathThroughTree(lastGoalMotion_);
        OMPL_DEBUG("Final path cost: %f", lastGoalMotion_->getCost().value());
        return base::PlannerStatus(true, false);
    }
    else if (Open_.size() > 0)
    {
        OMPL_INFORM("solve() called before clear(); no previous solution so starting afresh");
        clear();
    }

    checkValidity();
    base::GoalSampleableRegion *goal = dynamic_cast<base::GoalSampleableRegion*>(pdef_->getGoal().get());
    Motion *initMotion = nullptr;

    if (!goal)
    {
        OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
        return base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE;
    }

    // Add start states to V (nn_) and Open
    while (const base::State *st = pis_.nextStart())
    {
        initMotion = new Motion(si_);
        si_->copyState(initMotion->getState(), st);
        Open_.insert(initMotion);
        initMotion->setSetType(Motion::SET_OPEN);
        initMotion->setCost(opt_->initialCost(initMotion->getState()));
        nn_->add(initMotion); // V <-- {x_init}
    }

    if (!initMotion)
    {
        OMPL_ERROR("Start state undefined");
        return base::PlannerStatus::INVALID_START;
    }

    // Sample N free states in the configuration space
    if (!sampler_)
        sampler_ = si_->allocStateSampler();
    sampleFree(ptc);
    assureGoalIsSampled(goal);
    OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), nn_->size());

    // Calculate the nearest neighbor search radius
    /// \todo Create a PRM-like connection strategy
    if (nearestK_)
    {
        NNk_ = std::ceil(std::pow(2.0 * radiusMultiplier_, (double)si_->getStateDimension()) *
                        (boost::math::constants::e<double>() / (double)si_->getStateDimension()) *
                        log((double)nn_->size()));
        OMPL_DEBUG("Using nearest-neighbors k of %d", NNk_);
    }
    else
    {
        NNr_ = calculateRadius(si_->getStateDimension(), nn_->size());
        OMPL_DEBUG("Using radius of %f", NNr_);
    }

    // Execute the planner, and return early if the planner returns a failure
    bool plannerSuccess = false;
    bool successfulExpansion = false;
    Motion *z = initMotion; // z <-- xinit
    saveNeighborhood(z);

    while (!ptc)
    {
        if ((plannerSuccess = goal->isSatisfied(z->getState())))
            break;

        successfulExpansion = expandTreeFromNode(&z);

        if (!extendedFMT_ && !successfulExpansion)
            break;
        else if (extendedFMT_ && !successfulExpansion)
        {
            //Apply RRT*-like connections: sample and connect samples to tree
            std::vector<Motion*>       nbh;
            std::vector<base::Cost>    costs;
            std::vector<base::Cost>    incCosts;
            std::vector<std::size_t>   sortedCostIndices;

            // our functor for sorting nearest neighbors
            CostIndexCompare compareFn(costs, *opt_);

            Motion *m = new Motion(si_);
            while (!ptc && Open_.empty())
            {
                sampler_->sampleUniform(m->getState());

                if (!si_->isValid(m->getState()))
                    continue;

                if (nearestK_)
                    nn_->nearestK(m, NNk_, nbh);
                else
                    nn_->nearestR(m, NNr_, nbh);

                // Get neighbours in the tree.
                std::vector<Motion*> yNear;
                yNear.reserve(nbh.size());
                for (std::size_t j = 0; j < nbh.size(); ++j)
                {
                    if (nbh[j]->getSetType() == Motion::SET_CLOSED)
                    {
                        if (nearestK_)
                        {
                            // Only include neighbors that are mutually k-nearest
                            // Relies on NN datastructure returning k-nearest in sorted order
                            const base::Cost connCost = opt_->motionCost(nbh[j]->getState(), m->getState());
                            const base::Cost worstCost = opt_->motionCost(neighborhoods_[nbh[j]].back()->getState(), nbh[j]->getState());

                            if (opt_->isCostBetterThan(worstCost, connCost))
                                continue;
                            else
                                yNear.push_back(nbh[j]);
                        }
                        else
                            yNear.push_back(nbh[j]);
                    }
                }

                // Sample again if the new sample does not connect to the tree.
                if (yNear.empty())
                    continue;

                // cache for distance computations
                //
                // Our cost caches only increase in size, so they're only
                // resized if they can't fit the current neighborhood
                if (costs.size() < yNear.size())
                {
                    costs.resize(yNear.size());
                    incCosts.resize(yNear.size());
                    sortedCostIndices.resize(yNear.size());
                }

                // Finding the nearest neighbor to connect to
                // By default, neighborhood states are sorted by cost, and collision checking
                // is performed in increasing order of cost
                //
                // calculate all costs and distances
                for (std::size_t i = 0 ; i < yNear.size(); ++i)
                {
                    incCosts[i] = opt_->motionCost(yNear[i]->getState(), m->getState());
                    costs[i] = opt_->combineCosts(yNear[i]->getCost(), incCosts[i]);
                }

                // sort the nodes
                //
                // we're using index-value pairs so that we can get at
                // original, unsorted indices
                for (std::size_t i = 0; i < yNear.size(); ++i)
                    sortedCostIndices[i] = i;
                std::sort(sortedCostIndices.begin(), sortedCostIndices.begin() + yNear.size(),
                          compareFn);

               // collision check until a valid motion is found
               for (std::vector<std::size_t>::const_iterator i = sortedCostIndices.begin();
                    i != sortedCostIndices.begin() + yNear.size();
                    ++i)
               {
                   if (si_->checkMotion(yNear[*i]->getState(), m->getState()))
                   {
                       m->setParent(yNear[*i]);
                       yNear[*i]->getChildren().push_back(m);
                       const base::Cost incCost = opt_->motionCost(yNear[*i]->getState(), m->getState());
                       m->setCost(opt_->combineCosts(yNear[*i]->getCost(), incCost));
                       m->setHeuristicCost(opt_->motionCostHeuristic(m->getState(), goalState_));
                       m->setSetType(Motion::SET_OPEN);

                       nn_->add(m);
                       saveNeighborhood(m);
                       updateNeighborhood(m,nbh);

                       Open_.insert(m);
                       z = m;
                       break;
                   }
               }
            } // while (!ptc && Open_.empty())
        } // else if (extendedFMT_ && !successfulExpansion)
    } // While not at goal

    if (plannerSuccess)
    {
        // Return the path to z, since by definition of planner success, z is in the goal region
        lastGoalMotion_ = z;
        traceSolutionPathThroughTree(lastGoalMotion_);

        OMPL_DEBUG("Final path cost: %f", lastGoalMotion_->getCost().value());

        return base::PlannerStatus(true, false);
    } // if plannerSuccess
    else
    {
        // Planner terminated without accomplishing goal
        return base::PlannerStatus(false, false);
    }
}

void ompl::geometric::FMT::traceSolutionPathThroughTree(Motion *goalMotion)
{
    std::vector<Motion*> mpath;
    Motion *solution = goalMotion;

    // Construct the solution path
    while (solution != nullptr)
    {
        mpath.push_back(solution);
        solution = solution->getParent();
    }

    // Set the solution path
    PathGeometric *path = new PathGeometric(si_);
    int mPathSize = mpath.size();
    for (int i = mPathSize - 1 ; i >= 0 ; --i)
        path->append(mpath[i]->getState());
    pdef_->addSolutionPath(base::PathPtr(path), false, -1.0, getName());
}

bool ompl::geometric::FMT::expandTreeFromNode(Motion **z)
{
    // Find all nodes that are near z, and also in set Unvisited

    std::vector<Motion*> xNear;
    const std::vector<Motion*> &zNeighborhood = neighborhoods_[*z];
    const unsigned int zNeighborhoodSize = zNeighborhood.size();
    xNear.reserve(zNeighborhoodSize);

    for (unsigned int i = 0; i < zNeighborhoodSize; ++i)
    {
        Motion *x = zNeighborhood[i];
        if (x->getSetType() == Motion::SET_UNVISITED)
        {
            saveNeighborhood(x);
            if (nearestK_)
            {
                // Only include neighbors that are mutually k-nearest
                // Relies on NN datastructure returning k-nearest in sorted order
                const base::Cost connCost = opt_->motionCost((*z)->getState(), x->getState());
                const base::Cost worstCost = opt_->motionCost(neighborhoods_[x].back()->getState(), x->getState());

                if (opt_->isCostBetterThan(worstCost, connCost))
                    continue;
                else
                    xNear.push_back(x);
            }
            else
                xNear.push_back(x);
        }
    }

    // For each node near z and in set Unvisited, attempt to connect it to set Open
    std::vector<Motion*> yNear;
    std::vector<Motion*> Open_new;
    const unsigned int xNearSize = xNear.size();
    for (unsigned int i = 0 ; i < xNearSize; ++i)
    {
        Motion *x = xNear[i];

        // Find all nodes that are near x and in set Open
        const std::vector<Motion*> &xNeighborhood = neighborhoods_[x];

        const unsigned int xNeighborhoodSize = xNeighborhood.size();
        yNear.reserve(xNeighborhoodSize);
        for (unsigned int j = 0; j < xNeighborhoodSize; ++j)
        {
            if (xNeighborhood[j]->getSetType() == Motion::SET_OPEN)
                yNear.push_back(xNeighborhood[j]);
        }

        // Find the lowest cost-to-come connection from Open to x
        base::Cost cMin(std::numeric_limits<double>::infinity());
        Motion *yMin = getBestParent(x, yNear, cMin);
        yNear.clear();

        // If an optimal connection from Open to x was found
        if (yMin != nullptr)
        {
            bool collision_free = false;
            if (cacheCC_)
            {
                if (!yMin->alreadyCC(x))
                {
                    collision_free = si_->checkMotion(yMin->getState(), x->getState());
                    ++collisionChecks_;
                    // Due to FMT* design, it is only necessary to save unsuccesful
                    // connection attemps because of collision
                    if (!collision_free)
                        yMin->addCC(x);
                }
            }
            else
            {
                ++collisionChecks_;
                collision_free = si_->checkMotion(yMin->getState(), x->getState());
            }

            if (collision_free)
            {
                // Add edge from yMin to x
                x->setParent(yMin);
                x->setCost(cMin);
                x->setHeuristicCost(opt_->motionCostHeuristic(x->getState(), goalState_));
                yMin->getChildren().push_back(x);

                // Add x to Open
                Open_new.push_back(x);
                // Remove x from Unvisited
                x->setSetType(Motion::SET_CLOSED);
            }
        } // An optimal connection from Open to x was found
    } // For each node near z and in set Unvisited, try to connect it to set Open

    // Update Open
    Open_.pop();
    (*z)->setSetType(Motion::SET_CLOSED);

    // Add the nodes in Open_new to Open
    unsigned int openNewSize = Open_new.size();
    for (unsigned int i = 0; i < openNewSize; ++i)
    {
        Open_.insert(Open_new[i]);
        Open_new[i]->setSetType(Motion::SET_OPEN);
    }
    Open_new.clear();

    if (Open_.empty())
    {
        if(!extendedFMT_)
            OMPL_INFORM("Open is empty before path was found --> no feasible path exists");
        return false;
    }

    // Take the top of Open as the new z
    *z = Open_.top()->data;

    return true;
}

ompl::geometric::FMT::Motion* ompl::geometric::FMT::getBestParent(Motion *m, std::vector<Motion*> &neighbors, base::Cost &cMin)
{
    Motion *min = nullptr;
    const unsigned int neighborsSize = neighbors.size();
    for (unsigned int j = 0; j < neighborsSize; ++j)
    {
        const base::State *s = neighbors[j]->getState();
        const base::Cost dist = opt_->motionCost(s, m->getState());
        const base::Cost cNew = opt_->combineCosts(neighbors[j]->getCost(), dist);

        if (opt_->isCostBetterThan(cNew, cMin))
        {
            min = neighbors[j];
            cMin = cNew;
        }
    }
    return min;
}

void ompl::geometric::FMT::updateNeighborhood(Motion *m, const std::vector<Motion*> nbh)
{
    for (std::size_t i = 0; i < nbh.size(); ++i)
    {
        // If CLOSED, the neighborhood already exists. If neighborhood already exists, we have
        // to insert the node in the corresponding place of the neighborhood of the neighbor of m.
        if (nbh[i]->getSetType() == Motion::SET_CLOSED || neighborhoods_.find(nbh[i]) != neighborhoods_.end())
        {
            const base::Cost connCost = opt_->motionCost(nbh[i]->getState(), m->getState());
            const base::Cost worstCost = opt_->motionCost(neighborhoods_[nbh[i]].back()->getState(), nbh[i]->getState());

            if (opt_->isCostBetterThan(worstCost, connCost))
                continue;
            else
            {
                // Insert the neighbor in the vector in the correct order
                std::vector<Motion*> &nbhToUpdate = neighborhoods_[nbh[i]];
                for (std::size_t j = 0; j < nbhToUpdate.size(); ++j)
                {
                    // If connection to the new state is better than the current neighbor tested, insert.
                    const base::Cost cost = opt_->motionCost(nbh[i]->getState(), nbhToUpdate[j]->getState());
                    if (opt_->isCostBetterThan(connCost, cost))
                    {
                        nbhToUpdate.insert(nbhToUpdate.begin()+j, m);
                        break;
                    }
                }
            }
        }
        else
        {
            std::vector<Motion*> nbh2;
            if (nearestK_)
                nn_->nearestK(m, NNk_, nbh2);
            else
                nn_->nearestR(m, NNr_, nbh2);

            if (!nbh2.empty())
            {
                // Save the neighborhood but skip the first element, since it will be motion m
                neighborhoods_[nbh[i]] = std::vector<Motion*>(nbh2.size() - 1, 0);
                std::copy(nbh2.begin() + 1, nbh2.end(), neighborhoods_[nbh[i]].begin());
            }
            else
            {
                // Save an empty neighborhood
                neighborhoods_[nbh[i]] = std::vector<Motion*>(0);
            }
        }
    }
}

ext: cpp

max_stars_repo_name: wzxd/project-ompl


text:
#include <NTL/GF2X.h>
#include <stdint.h>
#include <UnitTest++.h>
#include <tr1/random>
#include <sstream>
#include "xsadd.h"
#include "xsadd.c" // to check static functions

using namespace NTL;
using namespace std;

void touz(uz *r, ZZ& x)
{
    ZZ work = x;
    uz_clear(r);
    for (int i = 0; i < UZ_ARRAY_SIZE; i++) {
	for (int j = 0; j < 16; j++) {
	    uint16_t mask = 1 << j;
	    if (IsOdd(work)) {
		r->ar[i] |= mask;
	    }
	    work = work >> 1;
	}
    }
}

void uztostring16(char * str, uz * x)
{
    int p = 0;
    int first = 1;
    for (int i = UZ_ARRAY_SIZE - 1; i >= 0; i--) {
	if (first) {
	    if (x->ar[i] != 0) {
		first = 0;
		sprintf(str, "%x", x->ar[i]);
		p = strlen(str);
	    }
	} else {
	    sprintf(str + p, "%04x", x->ar[i]);
	    p = p + 4;
	}
    }
    if (first) {
	strcpy(str, "0");
    }
}

void to16string(char * buff, ZZ& x)
{
    uz tmp;
    touz(&tmp, x);
    uztostring16(buff, &tmp);
}

bool eq(xsadd_t& xs1, xsadd_t& xs2)
{
    for (int i = 0; i < 4; i++) {
	if (xs1.state[i] != xs2.state[i]) {
	    return false;
	}
    }
    return true;
}

SUITE(JUMP) {
    TEST(SMALL)
    {
	xsadd_t xs1;
	xsadd_t xs2;
	tr1::mt19937 mt(1);
	for (int i = 0; i < 200; i++) {
	    uint32_t seed = mt();
	    int step = mt() % 500;
	    xsadd_init(&xs1, seed);
	    xsadd_init(&xs2, seed);
	    xsadd_jump(&xs1, step, "1");
	    for (int j = 0; j < step; j++) {
		xsadd_uint32(&xs2);
	    }
	    CHECK(eq(xs1, xs2));
	}
    }
    TEST(LARGE)
    {
	xsadd_t xs1;
	xsadd_t xs2;
	tr1::mt19937 mt(1);
	char buff[200];
	for (int i = 0; i < 200; i++) {
	    uint32_t seed = mt();
	    int step = mt() % 500;
	    ZZ lstep;
	    RandomBits(lstep, 70);
	    to16string(buff, lstep);
	    xsadd_init(&xs1, seed);
	    xsadd_init(&xs2, seed);
	    xsadd_jump(&xs1, step, buff);
	    lstep *= step;
	    to16string(buff, lstep);
	    xsadd_jump(&xs2, 1, buff);
	    CHECK(eq(xs1, xs2));
	}
    }
}

max_stars_repo_name: mkt-matsumoto-lab/XSadd

max_issues_repo_name: mkt-matsumoto-lab/XSadd

max_forks_repo_name: mkt-matsumoto-lab/XSadd


text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pos/poswallet.h"

#include "base58.h"
#include "checkpoints.h"
#include "chain.h"
//#include "wallet/coincontrol.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "keystore.h"
#include "validation.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "ui_interface.h"
#include "utilmoneystr.h"
#include "wallet/coincontrol.h"
#include "policy/rbf.h"
#include "scheduler.h"
#include "policy/fees.h"
#include "fs.h"
#include "init.h"
#include "pos/pos.h"
#include "script/interpreter.h"
#include "wallet/wallet.h"

#include <assert.h>

#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <miner.h>
#include <iostream>
typedef std::vector<unsigned char> valtype;

using namespace std;
CAmount nReserveBalance = 0;
unsigned int GetStakeMaxCombineInputs() { return STAKE_MAX_INPUT; }

int64_t GetStakeCombineThreshold() { return 100 * COIN; }

unsigned int GetStakeSplitOutputs() { return 2; }

/**check whether wallet have utxo **/
bool HaveAvailableCoinsForStaking(CWallet *pwallet){
    std::vector<COutput> vCoins;
    AvailableCoinsForStaking(pwallet,vCoins);
    return vCoins.size() > 0;
}

/**Get a list of UTXO form wallet**/
void AvailableCoinsForStaking(CWallet *pwallet,std::vector<COutput>& vCoins){
    vCoins.clear();
    {
        LOCK2(cs_main, pwallet->cs_wallet);
        //lfmodify
        for (std::map<uint256, CWalletTx>::const_iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it){
            const uint256& wtxid = it->first;
            const CWalletTx* pcoin = &(*it).second;
            int nDepth = pcoin->GetDepthInMainChain();

            if(!IsCoinMature(chainActive.Tip()->nHeight + 1, chainActive.Tip()->nHeight - nDepth - 1)){
                continue;
            }

            //tranverse coin vout
            for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
                // We should not consider coins which aren't at least in our mempool
                // It's possible for these to be conflicted via ancestors which we may never be able to detect
                if (nDepth == 0 && !pcoin->InMempool())
                    continue;

                //should be mine
                isminetype mine = pwallet->IsMine(pcoin->tx->vout[i]);
                //lfmodify
                if (!(pwallet->IsSpent(wtxid, i)) && mine != ISMINE_NO &&
                    !pwallet->IsLockedCoin(it->first, i) && (pcoin->tx->vout[i].nValue > 0)){
                        vCoins.push_back(COutput(pcoin, i, nDepth,
                                                 ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
                                                 (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO,
                                                 (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO,true));
                }
            }
        }
    }
}

/**Get a list of UTXO form wallet**/
bool SelectCoinsForStaking(CWallet *pwallet,CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet){
    std::vector<COutput> vCoins;
    //get available coins
    AvailableCoinsForStaking(pwallet,vCoins);
    setCoinsRet.clear();
    nValueRet = 0;

    //find money to meet target
    for(const COutput& output: vCoins){
        const CWalletTx *pcoin = output.tx;
        //get vout index
        int i = output.i;
        // Stop if we've chosen enough inputs
        if (nValueRet >= nTargetValue)
            break;

        int64_t n = pcoin->tx->vout[i].nValue;

        pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));

        if (n >= nTargetValue){
            // If input value is greater or equal to target then simply insert
            // it into the current subset and exit
            setCoinsRet.insert(coin.second);
            nValueRet += coin.first;
            break;
        } else if (n < nTargetValue + CENT){
            setCoinsRet.insert(coin.second);
            nValueRet += coin.first;
        }
    }
    return true;
}

/**construct a coinstake tx based on tx**/ //lfmodify Ckeystore
bool CreateCoinStake(CWallet *pwallet,unsigned int nBits, const CAmount& nTotalFees, uint32_t nTimeBlock, CMutableTransaction& tx, CKey& key){
    //edinarcoin:pos TODO chainActive
    CBlockIndex* pindexPrev = chainActive.Tip();
    arith_uint256 bnTargetPerCoinDay;
    bnTargetPerCoinDay.SetCompact(nBits);

    //int a new empty stake
    struct CMutableTransaction txNew(tx);
    txNew.vin.clear();
    txNew.vout.clear();

    // Mark coin stake transaction
    CScript scriptEmpty;
    scriptEmpty.clear();
    //first vout is empty
    txNew.vout.push_back(CTxOut(0, scriptEmpty));

    // Choose coins to use
    //get all balance
    CAmount nBalance = pwallet->GetBalance();//lfmodify
    //blance should be gt 0
    if (nBalance <= nReserveBalance)
        return false;

    std::vector<const CWalletTx*> vwtxPrev;

    std::set<pair<const CWalletTx*,unsigned int> > setCoins;
    CAmount nValueIn = 0;

    // Select coins with suitable depth
    //get target money
    CAmount nTargetValue = nBalance - nReserveBalance;
    //choose money for stake
    if (!SelectCoinsForStaking(pwallet,nTargetValue, setCoins, nValueIn))
        return false;

    if (setCoins.empty())
        return false;

    static std::map<COutPoint, CStakeCache> stakeCache;
    if(stakeCache.size() > setCoins.size() + 100){
        //Determining if the cache is still valid is harder than just clearing it when it gets too big, so instead just clear it
        //when it has more than 100 entries more than the actual setCoins.
        stakeCache.clear();
    }
    if(gArgs.GetBoolArg("-stakecache", DEFAULT_STAKE_CACHE)) {
        for(const std::pair<const CWalletTx *, unsigned int> &pcoin:setCoins){
            boost::this_thread::interruption_point();
            COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
            CacheKernel(stakeCache, prevoutStake, pindexPrev, *pcoinsTip); //this will do a 2 disk loads per op
        }
    }
    int64_t nCredit = 0;
    CScript scriptPubKeyKernel;
    //iterate eligible coin, construct the prevout(vin)
    for(const std::pair<const CWalletTx*, unsigned int>& pcoin:setCoins) {
        bool fKernelFound = false;
        boost::this_thread::interruption_point();
        // Search backward in time from the given txNew timestamp
        // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
        //get prevout Tx
        COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
        //check kernel Hash
        if (CheckKernel(pindexPrev, nBits, nTimeBlock, prevoutStake, *pcoinsTip, stakeCache)){
            // Found a kernel
            std::vector<valtype> vSolutions;
            txnouttype whichType;
            CScript scriptPubKeyOut;
            //get output pk(owner pk)
            scriptPubKeyKernel = pcoin.first->tx->vout[pcoin.second].scriptPubKey;
            //analysis pubkey
            if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
            {
                LogPrintf("coinstake CreateCoinStake : failed to parse kernel\n");
                break;
            }
            LogPrintf("coinstake CreateCoinStake : parsed kernel type=%d\n", whichType);
            //type should be p2pk,or p2pkh
            if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
            {
                LogPrintf("CreateCoinStake : no support for kernel type=%d\n", whichType);
                break;  // only support pay to public key and pay to address
            }
            //convert p2pkh to p2pk, save it into scriptPubKeyOut
            if (whichType == TX_PUBKEYHASH) // pay to address type
            {
                // convert to pay to public key type
                if (!pwallet->GetKey(uint160(vSolutions[0]), key))//lfmodify
                {
                    LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
                    break;  // unable to find corresponding public key
                }
                scriptPubKeyOut << key.GetPubKey().getvch() << OP_CHECKSIG;
            }
            //if p2pk, directly save into scriptPubKeyOut
            if (whichType == TX_PUBKEY)
            {
                valtype& vchPubKey = vSolutions[0];
                if (!pwallet->GetKey(Hash160(vchPubKey), key))//lfmodify
                {
                    LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
                    break;  // unable to find corresponding public key
                }

                if (key.GetPubKey() != vchPubKey)
                {
                    LogPrintf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
                    break; // keys mismatch
                }

                scriptPubKeyOut = scriptPubKeyKernel;
            }

            //set vin
            txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
            //get prveout amount
            nCredit += pcoin.first->tx->vout[pcoin.second].nValue;
            vwtxPrev.push_back(pcoin.first);
            //set vout
            txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));

            LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType);
            fKernelFound = true;
            break;
        }

        //success
        if (fKernelFound)
            break; // if kernel is found stop searching
    }

    //check money again
    if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
        return false;

    //put the remaint money into tx
    for(const std::pair<const CWalletTx*, unsigned int>& pcoin:setCoins){
        // Attempt to add more inputs
        // Only add coins of the same key/address as kernel
        if (txNew.vout.size() == 2 && ((pcoin.first->tx->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->tx->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
                && pcoin.first->GetHash() != txNew.vin[0].prevout.hash) {
            // Stop adding more inputs if already too many inputs
            if (txNew.vin.size() >= GetStakeMaxCombineInputs())
                break;
            // Stop adding inputs if reached reserve limit
            if (nCredit + pcoin.first->tx->vout[pcoin.second].nValue > nBalance - nReserveBalance)
                break;
            // Do not add additional significant input
            if (pcoin.first->tx->vout[pcoin.second].nValue >= GetStakeCombineThreshold())
                continue;

            txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
            nCredit += pcoin.first->tx->vout[pcoin.second].nValue;
            vwtxPrev.push_back(pcoin.first);
        }
    }

    const Consensus::Params& consensusParams = Params().GetConsensus();

    //get final money
    int64_t nReward = nTotalFees + GetBlockSubsidy(pindexPrev->nHeight + 1, consensusParams);
    if (nReward < 0) {
        return false;
    }

    nCredit += nReward;

    //put reward into vout[1]
    txNew.vout[1].nValue = nCredit;

    // Append the Refunds To Sender to the transaction outputs
    for(unsigned int i = 2; i < tx.vout.size(); i++)
    {
        txNew.vout.push_back(tx.vout[i]);
    }

    // Sign the input coins
    int nIn = 0;
    for(const CWalletTx* pcoin:vwtxPrev){
        //edinarcoin: pos-> 2way-protection required
        if (!SignSignature(*pwallet, *pcoin, txNew, nIn++, SIGHASH_ALL|SIGHASH_FORKID))
            return error("CreateCoinStake : failed to sign coinstake");
        ////
    }

    // Successfully generated coinstake
    tx = CTransaction(txNew);
     return true;
 }

max_stars_repo_name: Profitbz/EdinarcoinFork

max_issues_repo_name: Profitbz/EdinarcoinFork

max_forks_repo_name: Profitbz/EdinarcoinFork


text:
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "txmempool.h"
#include "util.h"

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

BOOST_AUTO_TEST_SUITE(mempool_tests)

BOOST_AUTO_TEST_CASE(MempoolRemoveTest)
{
    // Test CTxMemPool::remove functionality

    // Parent transaction with three children,
    // and three grand-children:
    CMutableTransaction txParent;
    txParent.vin.resize(1);
    txParent.vin[0].scriptSig = CScript() << OP_11;
    txParent.vout.resize(3);
    for (int i = 0; i < 3; i++)
    {
        txParent.vout[i].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
        txParent.vout[i].nValue = 33000LL;
    }
    CMutableTransaction txChild[3];
    for (int i = 0; i < 3; i++)
    {
        txChild[i].vin.resize(1);
        txChild[i].vin[0].scriptSig = CScript() << OP_11;
        txChild[i].vin[0].prevout.hash = txParent.GetHash();
        txChild[i].vin[0].prevout.n = i;
        txChild[i].vout.resize(1);
        txChild[i].vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
        txChild[i].vout[0].nValue = 11000LL;
    }
    CMutableTransaction txGrandChild[3];
    for (int i = 0; i < 3; i++)
    {
        txGrandChild[i].vin.resize(1);
        txGrandChild[i].vin[0].scriptSig = CScript() << OP_11;
        txGrandChild[i].vin[0].prevout.hash = txChild[i].GetHash();
        txGrandChild[i].vin[0].prevout.n = 0;
        txGrandChild[i].vout.resize(1);
        txGrandChild[i].vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
        txGrandChild[i].vout[0].nValue = 11000LL;
    }

    CTxMemPool testPool(CFeeRate(0));
    std::list<CTransaction> removed;

    // Nothing in pool, remove should do nothing:
    testPool.remove(txParent, removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 0);

    // Just the parent:
    testPool.addUnchecked(txParent.GetHash(), CTxMemPoolEntry(txParent, 0, 0, 0.0, 1));
    testPool.remove(txParent, removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 1);
    removed.clear();

    // Parent, children, grandchildren:
    testPool.addUnchecked(txParent.GetHash(), CTxMemPoolEntry(txParent, 0, 0, 0.0, 1));
    for (int i = 0; i < 3; i++)
    {
        testPool.addUnchecked(txChild[i].GetHash(), CTxMemPoolEntry(txChild[i], 0, 0, 0.0, 1));
        testPool.addUnchecked(txGrandChild[i].GetHash(), CTxMemPoolEntry(txGrandChild[i], 0, 0, 0.0, 1));
    }
    // Remove Child[0], GrandChild[0] should be removed:
    testPool.remove(txChild[0], removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 2);
    removed.clear();
    // ... make sure grandchild and child are gone:
    testPool.remove(txGrandChild[0], removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 0);
    testPool.remove(txChild[0], removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 0);
    // Remove parent, all children/grandchildren should go:
    testPool.remove(txParent, removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 5);
    BOOST_CHECK_EQUAL(testPool.size(), 0);
    removed.clear();

    // Add children and grandchildren, but NOT the parent (simulate the parent being in a block)
    for (int i = 0; i < 3; i++)
    {
        testPool.addUnchecked(txChild[i].GetHash(), CTxMemPoolEntry(txChild[i], 0, 0, 0.0, 1));
        testPool.addUnchecked(txGrandChild[i].GetHash(), CTxMemPoolEntry(txGrandChild[i], 0, 0, 0.0, 1));
    }
    // Now remove the parent, as might happen if a block-re-org occurs but the parent cannot be
    // put into the mempool (maybe because it is non-standard):
    testPool.remove(txParent, removed, true);
    BOOST_CHECK_EQUAL(removed.size(), 6);
    BOOST_CHECK_EQUAL(testPool.size(), 0);
    removed.clear();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: nashsclay/Atheneum

max_issues_repo_name: Matthelonianxl/Atheneum

max_forks_repo_name: Matthelonianxl/Atheneum


text:
//  (C) Copyright Andy Tompkins 2010. Permission to copy, use, modify, sell and
//  distribute this software is granted provided this copyright notice appears
//  in all copies. This software is provided "as is" without express or implied
//  warranty, and with no claim as to its suitability for any purpose.

// 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)

//  libs/uuid/test/test_random_generator.cpp  -------------------------------//

#include <boost/core/ignore_unused.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/predef/library/c/cloudabi.h>
#include <boost/random.hpp>
#include <boost/uuid/entropy_error.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/move/utility_core.hpp>

template <typename RandomUuidGenerator>
void check_random_generator(RandomUuidGenerator& uuid_gen)
{
    boost::uuids::uuid u1 = uuid_gen();
    boost::uuids::uuid u2 = uuid_gen();

    BOOST_TEST_NE(u1, u2);

    // check variant
    BOOST_TEST_EQ(u1.variant(), boost::uuids::uuid::variant_rfc_4122);

    // version
    BOOST_TEST_EQ(u1.version(), boost::uuids::uuid::version_random_number_based);
}

// This is the example block from the documentation - ensure it works!
void test_examples()
{
    // Depending on the platform there may be a setup cost in
    // initializing the generator so plan to reuse it if you can.
    boost::uuids::random_generator gen;
    boost::uuids::uuid id = gen();
    boost::uuids::uuid id2 = gen();
#if !BOOST_LIB_C_CLOUDABI
    std::cout << id << std::endl;
    std::cout << id2 << std::endl;
#endif
    BOOST_TEST_NE(id, id2);
    boost::ignore_unused(id);
    boost::ignore_unused(id2);

    // You can still use a PseudoRandomNumberGenerator to create
    // UUIDs, however this is not the preferred mechanism.  For
    // large numbers of UUIDs this may be more CPU efficient but
    // it comes with all the perils of a PRNG.  The test code
    // in test_bench_random identifies the transition point for
    // a given system.
    boost::uuids::random_generator_mt19937 bulkgen;
    for (size_t i = 0; i < 1000; ++i)
    {
        boost::uuids::uuid u = bulkgen();
        // do something with u
        boost::ignore_unused(u);
    }
}

int main(int, char*[])
{
    using namespace boost::uuids;

    // default random number generator
    {
        random_generator uuid_gen1;
        check_random_generator(uuid_gen1);
#if !BOOST_LIB_C_CLOUDABI
        // dump 10 of them to cout for observation
        for (size_t i = 0; i < 10; ++i)
        {
            std::cout << uuid_gen1() << std::endl;
        }
#endif
    }

    // specific random number generator
    {
        basic_random_generator<boost::rand48> uuid_gen2;
        check_random_generator(uuid_gen2);
    }

    // pass by reference
    {
        boost::ecuyer1988 ecuyer1988_gen;
        basic_random_generator<boost::ecuyer1988> uuid_gen3(ecuyer1988_gen);
        check_random_generator(uuid_gen3);
    }

    // pass by pointer
    {
        boost::lagged_fibonacci607 lagged_fibonacci607_gen;
        basic_random_generator<boost::lagged_fibonacci607> uuid_gen4(&lagged_fibonacci607_gen);
        check_random_generator(uuid_gen4);
    }

    // check move construction
    {
        random_generator uuid_gen1;
        random_generator uuid_gen2(boost::move(uuid_gen1));
        boost::ignore_unused(uuid_gen2);
    }
    {
        basic_random_generator<boost::rand48> uuid_gen1;
        basic_random_generator<boost::rand48> uuid_gen2(boost::move(uuid_gen1));
        boost::ignore_unused(uuid_gen2);
    }

    // check move assignment
    {
        random_generator uuid_gen1, uuid_gen2;
        uuid_gen2 = boost::move(uuid_gen1);
        boost::ignore_unused(uuid_gen2);
    }
    {
        basic_random_generator<boost::rand48> uuid_gen1, uuid_gen2;
        uuid_gen2 = boost::move(uuid_gen1);
        boost::ignore_unused(uuid_gen2);
    }

    // there was a bug in basic_random_generator where it did not
    // produce very random numbers.  This checks for that bug.
    {
        random_generator_mt19937 bulkgen;
        uuid u = bulkgen();
        if ((u.data[4] == u.data[12]) &&
            (u.data[5] == u.data[9] && u.data[5] == u.data[13]) &&
            (u.data[7] == u.data[11] && u.data[7] == u.data[15]) &&
            (u.data[10] == u.data[14]))
        {
            BOOST_ERROR("basic_random_generator is not producing random uuids");
        }

        // pseudo
        check_random_generator(bulkgen);
    }

    // make sure default construction seeding is happening for PRNGs
    {
        random_generator_mt19937 gen1;
        random_generator_mt19937 gen2;
        BOOST_TEST_NE(gen1(), gen2());
    }

    // The example code snippet in the documentation
    test_examples();

    return boost::report_errors();
}

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
#ifndef TEST_UTILS_HPP
#define TEST_UTILS_HPP

#include "../../base/svd.hpp"

#if SKYLARK_HAVE_BOOST
#include <boost/test/minimal.hpp>
#endif

#include <elemental.hpp>

template<typename MatrixType>
MatrixType operator-(MatrixType& A, MatrixType& B) {
    MatrixType C;
    elem::Copy(A, C);
    elem::Axpy(-1.0, B, C);
    return C;
}

template<typename MatrixType>
bool equal(MatrixType& A, MatrixType& B,  double threshold=1.e-4) {
    MatrixType C = A - B;
    double diff_norm = elem::Norm(C);
    if (diff_norm < threshold) {
        return true;
    }
    return false;
}

template<typename InputMatrixType,
         typename LeftSingularVectorsMatrixType,
         typename SingularValuesMatrixType,
         typename RightSingularVectorsMatrixType>
bool equal_svd_product(InputMatrixType& A,
    LeftSingularVectorsMatrixType& U,
    SingularValuesMatrixType& S,
    RightSingularVectorsMatrixType& V,
    double threshold=1e-4) {

    elem::DistMatrix<double> S_CIRC_CIRC = S;
    std::vector<double> values(S_CIRC_CIRC.Buffer(),
        S_CIRC_CIRC.Buffer() + S_CIRC_CIRC.Height());
    elem::Diagonal(S_CIRC_CIRC, values);
    elem::DistMatrix<double> S_MC_MR = S_CIRC_CIRC;

    elem::DistMatrix<double> A_MC_MR = A;
    elem::DistMatrix<double> U_MC_MR = U;
    elem::DistMatrix<double> V_MC_MR = V;
    elem::DistMatrix<double> US_MC_MR;
    elem::DistMatrix<double> USVt_MC_MR;

    US_MC_MR.Resize(U.Height(), S_CIRC_CIRC.Width());
    elem::Zero(US_MC_MR);
    USVt_MC_MR.Resize(U.Height(), V.Height());

    elem::Zero(USVt_MC_MR);
    elem::Gemm(elem::NORMAL, elem::NORMAL,    1.0, U_MC_MR,
        S_MC_MR, 0.0, US_MC_MR);
    elem::Gemm(elem::NORMAL, elem::TRANSPOSE, 1.0, US_MC_MR,
        V_MC_MR, 0.0, USVt_MC_MR);

    return equal(A_MC_MR, USVt_MC_MR, threshold);
}

#if SKYLARK_HAVE_BOOST

void check(elem::DistMatrix<double>& A,
    double threshold=1e-4) {
    elem::DistMatrix<double> U, V;
    elem::DistMatrix<double, elem::VR, elem::STAR> S_VR_STAR;
    skylark::base::SVD(A, U, S_VR_STAR, V);
    bool passed = equal_svd_product(A, U, S_VR_STAR, V, threshold);
    if (!passed) {
        BOOST_FAIL("Failure in [MC, MR] case");
    }

}

template<elem::Distribution ColDist>
void check(elem::DistMatrix<double, ColDist, elem::STAR>& A,
    double threshold=1e-4) {
    elem::DistMatrix<double, ColDist, elem::STAR> A_CD_STAR, U_CD_STAR;
    elem::DistMatrix<double, elem::STAR, elem::STAR> S_STAR_STAR, V_STAR_STAR;
    A_CD_STAR = A;
    skylark::base::SVD(A_CD_STAR, U_CD_STAR, S_STAR_STAR, V_STAR_STAR);
    bool passed = equal_svd_product(A_CD_STAR,
        U_CD_STAR, S_STAR_STAR, V_STAR_STAR, threshold);
    if (!passed) {
        BOOST_FAIL("Failure in [VC/VR, *] case");
    }
}

template<elem::Distribution RowDist>
void check(elem::DistMatrix<double, elem::STAR, RowDist>& A,
    double threshold=1e-4) {
    elem::DistMatrix<double, RowDist, elem::STAR> V_RD_STAR;
    elem::DistMatrix<double, elem::STAR, elem::STAR> S_STAR_STAR, U_STAR_STAR;
    skylark::base::SVD(A, U_STAR_STAR, S_STAR_STAR, V_RD_STAR);
    bool passed = equal_svd_product(A,
        U_STAR_STAR, S_STAR_STAR, V_RD_STAR, threshold);
    if (!passed) {
        BOOST_FAIL("Failure in [*, VC/VR] case");
    }

}

#endif // SKYLARK_HAVE_BOOST

#endif // TEST_UTILS_HPP

ext: hpp

max_issues_repo_name: cjiyer/libskylark

max_forks_repo_name: cjiyer/libskylark


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// 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
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//

#ifndef BOOST_COMPUTE_ALGORITHM_REVERSE_COPY_HPP
#define BOOST_COMPUTE_ALGORITHM_REVERSE_COPY_HPP

#include <iterator>

#include <boost/compute/system.hpp>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/algorithm/copy.hpp>
#include <boost/compute/algorithm/reverse.hpp>

namespace boost {
namespace compute {
namespace detail {

template<class Iterator, class OutputIterator>
struct reverse_copy_kernel : public meta_kernel
{
    reverse_copy_kernel(Iterator first, Iterator last, OutputIterator result)
        : meta_kernel("reverse_copy")
    {
        // store size of the range
        m_size = detail::iterator_range_size(first, last);
        add_set_arg<const cl_uint>("size", static_cast<const cl_uint>(m_size));

        *this <<
            decl<cl_uint>("i") << " = get_global_id(0);\n" <<
            decl<cl_uint>("j") << " = size - get_global_id(0) - 1;\n" <<
            result[var<cl_uint>("j")] << "=" << first[var<cl_uint>("i")] << ";\n";
    }

    void exec(command_queue &queue)
    {
        exec_1d(queue, 0, m_size);
    }

    size_t m_size;
};

} // end detail namespace

/// Copies the elements in the range [\p first, \p last) in reversed
/// order to the range beginning at \p result.
///
/// \see reverse()
template<class InputIterator, class OutputIterator>
inline OutputIterator
reverse_copy(InputIterator first,
             InputIterator last,
             OutputIterator result,
             command_queue &queue = system::default_queue())
{
    typedef typename std::iterator_traits<OutputIterator>::difference_type difference_type;

    difference_type count = std::distance(first, last);

    detail::reverse_copy_kernel<InputIterator, OutputIterator>
        kernel(first, last, result);

    // run kernel
    kernel.exec(queue);

    // return iterator to the end of result
    return result + count;
}

} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_ALGORITHM_REVERSE_COPY_HPP

max_stars_repo_name: EuroLine/nheqminer


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <algorithm>

#include <libdariadb/flags.h>
#include <libdariadb/storage/bloom_filter.h>
#include <libdariadb/storage/callbacks.h>
#include <libdariadb/storage/chunk.h>
#include <libdariadb/storage/engine_environment.h>
#include <libdariadb/storage/manifest.h>
#include <libdariadb/storage/pages/page.h>
#include <libdariadb/storage/pages/page_manager.h>
#include <libdariadb/storage/settings.h>
#include <libdariadb/utils/async/thread_manager.h>
#include <libdariadb/utils/fs.h>
#include <libdariadb/utils/logger.h>
#include <libdariadb/utils/utils.h>

using dariadb::storage::PageManager;
using dariadb::storage::Manifest;

BOOST_AUTO_TEST_CASE(ManifestFileTest) {
  const std::string storage_path = "emptyStorage";
  if (dariadb::utils::fs::path_exists(storage_path)) {
    dariadb::utils::fs::rm(storage_path);
  }

  std::string version = "0.1.2.3.4.5";

  {
    auto settings =
        dariadb::storage::Settings::create(storage_path);
    auto manifest = dariadb::storage::Manifest::create(settings);
    std::list<std::string> pages_names{"1", "2", "3"};
    for (auto n : pages_names) {
      manifest->page_append(n);
    }

    manifest->set_format(version);

    std::list<std::string> wal_names{"111", "222", "333"};
    for (auto n : wal_names) {
      manifest->wal_append(n);
    }

    auto page_lst = manifest->page_list();
    BOOST_CHECK_EQUAL(page_lst.size(), pages_names.size());
    BOOST_CHECK_EQUAL_COLLECTIONS(page_lst.begin(), page_lst.end(), pages_names.begin(),
                                  pages_names.end());

    auto wal_lst = manifest->wal_list();
    BOOST_CHECK_EQUAL(wal_lst.size(), wal_names.size());
    BOOST_CHECK_EQUAL_COLLECTIONS(wal_lst.begin(), wal_lst.end(), wal_names.begin(),
                                  wal_names.end());

    manifest = nullptr;
  }
  { // reopen. restore method must remove all records from manifest.
    auto settings = dariadb::storage::Settings::create(storage_path);
    auto manifest = dariadb::storage::Manifest::create(settings);
    BOOST_CHECK_EQUAL(manifest->page_list().size(), size_t(0));
    BOOST_CHECK_EQUAL(manifest->wal_list().size(), size_t(0));
    BOOST_CHECK_EQUAL(manifest->get_format(), version);
  }

  if (dariadb::utils::fs::path_exists(storage_path)) {
    dariadb::utils::fs::rm(storage_path);
  }
}

BOOST_AUTO_TEST_CASE(PageManagerReadWriteWithContinue) {
  const std::string storagePath = "testStorage";
  const size_t chunks_size = 200;
  auto t = dariadb::Time(0);

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
  dariadb::MeasList addeded;

  auto settings = dariadb::storage::Settings::create(storagePath);
  settings->chunk_size.setValue(chunks_size);

  auto manifest = dariadb::storage::Manifest::create(settings);

  auto _engine_env = dariadb::storage::EngineEnvironment::create();
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
                           settings.get());
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::MANIFEST,
                           manifest.get());

  dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());

  auto pm = dariadb::storage::PageManager::create(_engine_env);
  dariadb::Meas first;
  first.id = 1;
  first.time = t;
  {
    first.id = 1;
    first.time = t;
    auto count = chunks_size * 2;
    dariadb::MeasArray ma;
    ma.resize(count);
    for (size_t i = 0; i < count; i++, t++) {
      first.flag = dariadb::Flag(i);
      first.time = t;
      first.value = dariadb::Value(i);
      ma[i] = first;
      addeded.push_back(first);
    }
    pm->append("pagename", ma);
  }
  pm = nullptr;

  auto fname =
      dariadb::utils::fs::ls(settings->raw_path.value(), dariadb::storage::PAGE_FILE_EXT)
          .front();
  auto header = dariadb::storage::Page::readHeader(fname);
  BOOST_CHECK(header.addeded_chunks != size_t(0));

  auto iheader = dariadb::storage::Page::readIndexHeader(fname + "i");
  BOOST_CHECK(iheader.count != 0);

  pm = dariadb::storage::PageManager::create(_engine_env);

  auto mintime_chunks = pm->valuesBeforeTimePoint(
      dariadb::storage::QueryTimePoint(dariadb::IdArray{1}, 0, pm->minTime()));
  BOOST_CHECK_GE(mintime_chunks.size(), size_t(1));
  pm->fsck();

  auto index_files = dariadb::utils::fs::ls(storagePath, ".pagei");
  for (auto &f : index_files) {
    dariadb::utils::fs::rm(f);
  }

  pm->fsck();

  mintime_chunks = pm->valuesBeforeTimePoint(
      dariadb::storage::QueryTimePoint(dariadb::IdArray{1}, 0, pm->minTime()));
  BOOST_CHECK_GE(mintime_chunks.size(), size_t(1));

  pm = nullptr;
  manifest = nullptr;
  dariadb::utils::async::ThreadManager::stop();

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
}

BOOST_AUTO_TEST_CASE(PageManagerMultiPageRead) {
  const std::string storagePath = "testStorage";
  const size_t chunks_size = 200;
  auto t = dariadb::Time(0);

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
  dariadb::MeasList addeded;

  auto settings = dariadb::storage::Settings::create(storagePath);
  settings->chunk_size.setValue(chunks_size);

  auto manifest = dariadb::storage::Manifest::create(settings);

  auto _engine_env = dariadb::storage::EngineEnvironment::create();
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
                           settings.get());
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::MANIFEST,
                           manifest.get());

  dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());

  auto pm = dariadb::storage::PageManager::create(_engine_env);
  dariadb::Meas first;
  first.id = 1;
  first.time = t;
  const size_t page_count = 4;

  size_t iteration = 0;
  while (
      dariadb::utils::fs::ls(settings->raw_path.value(), dariadb::storage::PAGE_FILE_EXT)
          .size() <= page_count) {
    first.id = 1;
    first.time = t;
    auto count = chunks_size / 10;
    dariadb::MeasArray ma;
    ma.resize(count);
    for (size_t i = 0; i < count; i++, t++) {
      first.flag = dariadb::Flag(i);
      first.time = t;
      first.value = dariadb::Value(i);
      ma[i] = first;
      addeded.push_back(first);
    }
    std::stringstream ss;
    ss << std::string("pagename") << iteration++;
    pm->append(ss.str(), ma);
  }

  dariadb::storage::QueryInterval qi(dariadb::IdArray{1}, 0, addeded.front().time,
                                     addeded.back().time);

  dariadb::storage::QueryTimePoint qt(
      dariadb::IdArray{1}, 0,
      addeded.front().time + (addeded.back().time - addeded.front().time) / 2);

  auto link_list = pm->chunksByIterval(qi);

  auto clb = std::unique_ptr<dariadb::storage::MList_ReaderClb>{
      new dariadb::storage::MList_ReaderClb};
  pm->readLinks(qi, link_list, clb.get());

  size_t writed = addeded.size();
  size_t readed = clb->mlist.size();

  BOOST_CHECK_EQUAL(readed, writed);

  auto id2meas = pm->valuesBeforeTimePoint(qt);

  BOOST_CHECK_EQUAL(id2meas.size(), qt.ids.size());
  for (auto kv : id2meas) {
    BOOST_CHECK_LE(kv.second.time, qt.time_point);
  }

  dariadb::Time minTime, maxTime;
  if (pm->minMaxTime(1, &minTime, &maxTime)) {
    BOOST_CHECK_EQUAL(minTime, qi.from);
    BOOST_CHECK_EQUAL(maxTime, qi.to);
  } else {
    BOOST_ERROR("PageManager::instance()->minMaxTime error!");
  }

  auto mm = pm->loadMinMax();
  BOOST_CHECK_EQUAL(mm.size(), size_t(1));

  auto page_before_erase =
      dariadb::utils::fs::ls(settings->raw_path.value(), dariadb::storage::PAGE_FILE_EXT)
          .size();
  pm->eraseOld(addeded.back().time);
  auto page_after_erase =
      dariadb::utils::fs::ls(settings->raw_path.value(), dariadb::storage::PAGE_FILE_EXT)
          .size();

  BOOST_CHECK_LT(page_after_erase, page_before_erase);
  BOOST_CHECK_EQUAL(page_after_erase, size_t(0));

  pm = nullptr;
  manifest = nullptr;
  dariadb::utils::async::ThreadManager::stop();

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
}

BOOST_AUTO_TEST_CASE(PageManagerBulkWrite) {
  const std::string storagePath = "testStorage";
  const size_t chunks_size = 256;

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
  auto settings = dariadb::storage::Settings::create(storagePath);
  settings->chunk_size.setValue(chunks_size);

  auto manifest = dariadb::storage::Manifest::create(settings);

  auto _engine_env = dariadb::storage::EngineEnvironment::create();
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
                           settings.get());
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::MANIFEST,
                           manifest.get());

  dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());

  auto pm = dariadb::storage::PageManager::create(_engine_env);

  auto start_time = dariadb::Time(0);
  dariadb::MeasList addeded;
  const dariadb::Id id_count(5);
  dariadb::IdSet all_id_set;
  size_t count = 5000;
  dariadb::MeasArray a(count);
  auto e = dariadb::Meas::empty();
  for (size_t i = 0; i < count; i++) {
    e.id = i % id_count;
    e.time++;
    e.value = dariadb::Value(i);
    a[i] = e;
    all_id_set.insert(e.id);
    addeded.push_back(e);
  }
  std::string page_file_prefix = "page_prefix";
  pm->append(page_file_prefix, a);

  dariadb::IdArray all_id_array{all_id_set.begin(), all_id_set.end()};
  { // Chunks load
    // must return all of appended chunks;

    pm->flush();
    dariadb::storage::QueryInterval qi_all(all_id_array, 0, 0, e.time);
    auto links_list = pm->chunksByIterval(qi_all);

    auto clb1 = std::unique_ptr<dariadb::storage::MList_ReaderClb>{
        new dariadb::storage::MList_ReaderClb};

    pm->readLinks(qi_all, links_list, clb1.get());

    BOOST_CHECK_EQUAL(addeded.size(), clb1->mlist.size());
    dariadb::Time minT = dariadb::MAX_TIME, maxT = dariadb::MIN_TIME;
    BOOST_CHECK(pm->minMaxTime(dariadb::Id(0), &minT, &maxT));
    BOOST_CHECK_EQUAL(minT, dariadb::Time(1));
    BOOST_CHECK_GE(maxT, minT);

    {
      dariadb::Time end_time(e.time / 2);
      dariadb::storage::ChunksList chunk_list;
      dariadb::storage::QueryInterval qi(all_id_array, 0, start_time, end_time);
      auto link_list = pm->chunksByIterval(qi);

      auto clb2 = std::unique_ptr<dariadb::storage::MList_ReaderClb>{
          new dariadb::storage::MList_ReaderClb};

      pm->readLinks(qi, links_list, clb2.get());

      BOOST_CHECK_GT(clb2->mlist.size(), size_t(0));

      for (auto &m : clb2->mlist) {
        BOOST_CHECK(m.time <= end_time);
      }

      auto id2meas_res = pm->valuesBeforeTimePoint(
          dariadb::storage::QueryTimePoint(all_id_array, 0, end_time));
      BOOST_CHECK_EQUAL(id2meas_res.size(), all_id_array.size());

      for (auto &kv : id2meas_res) {
        BOOST_CHECK(kv.second.time <= end_time);
      }
    }
    pm = nullptr;
  }
  BOOST_CHECK(dariadb::utils::fs::path_exists(storagePath));
  BOOST_CHECK_EQUAL(dariadb::utils::fs::ls(storagePath).size(),
                    size_t(4)); // page +index+manifest+settings

  manifest = nullptr;
  dariadb::utils::async::ThreadManager::stop();

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
}

BOOST_AUTO_TEST_CASE(PageManagerCompaction) {
  const std::string storagePath = "testStorage";
  const size_t chunks_size = 256;

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
  auto settings = dariadb::storage::Settings::create(storagePath);
  settings->chunk_size.setValue(chunks_size);

  auto manifest =  dariadb::storage::Manifest::create(settings);

  auto _engine_env = dariadb::storage::EngineEnvironment::create();
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
                           settings.get());
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::MANIFEST,
                           manifest.get());

  dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());

  auto pm = dariadb::storage::PageManager::create(_engine_env);

  size_t count = 100;
  dariadb::MeasArray a(count);
  /**
  Id=0 =>  0, count
  Id=1 =>  0, count
  Id=0 =>  0, count/2
  Id=1 =>  count/2, count
  */
  auto e = dariadb::Meas::empty();
  for (size_t i = 0; i < count; i++) {
    e.id = 0;
    e.time++;
    e.value = dariadb::Value(i);
    a[i] = e;
  }
  std::string page_file_prefix1 = "page_prefix1";
  std::string page_file1 = page_file_prefix1 + ".page";
  pm->append(page_file_prefix1, a);

  e.time = 0;
  for (size_t i = 0; i < count; i++) {
    e.id = 1;
    e.time++;
    e.value = dariadb::Value(i);
    a[i] = e;
  }
  std::string page_file_prefix2 = "page_prefix2";
  std::string page_file2 = page_file_prefix2 + ".page";
  pm->append(page_file_prefix2, a);

  e.time = 0;
  for (size_t i = 0; i < count / 2; i++) {
    e.id = 0;
    e.time++;
    e.value = dariadb::Value(i) * 3;
    a[i] = e;
  }
  std::string page_file_prefix3 = "page_prefix3";
  std::string page_file3 = page_file_prefix3 + ".page";
  pm->append(page_file_prefix3, a);

  BOOST_CHECK(dariadb::utils::fs::path_exists(storagePath));
  BOOST_CHECK_EQUAL(dariadb::utils::fs::ls(settings->raw_path.value(), ".page").size(),
                    size_t(3));

  { // id==0
    dariadb::storage::QueryInterval qi({0}, 0, 0, dariadb::MAX_TIME);
    auto link_list = pm->chunksByIterval(qi);

    auto clb = std::unique_ptr<dariadb::storage::MList_ReaderClb>{
        new dariadb::storage::MList_ReaderClb};

    pm->readLinks(qi, link_list, clb.get());

    BOOST_CHECK_GT(clb->mlist.size(), size_t(100));
  }

  pm->compactTo(1);
  BOOST_CHECK_EQUAL(dariadb::utils::fs::ls(settings->raw_path.value(), ".page").size(),
                    size_t(1));
  { // id==0
    dariadb::storage::QueryInterval qi({0}, 0, 0, dariadb::MAX_TIME);
    auto link_list = pm->chunksByIterval(qi);

    auto clb = std::unique_ptr<dariadb::storage::MList_ReaderClb>{
        new dariadb::storage::MList_ReaderClb};

    pm->readLinks(qi, link_list, clb.get());

    BOOST_CHECK_EQUAL(clb->mlist.size(), size_t(100));
  }
  { // id==1
    dariadb::storage::QueryInterval qi({1}, 0, 0, dariadb::MAX_TIME);
    auto link_list = pm->chunksByIterval(qi);

    auto clb = std::unique_ptr<dariadb::storage::MList_ReaderClb>{
        new dariadb::storage::MList_ReaderClb};

    pm->readLinks(qi, link_list, clb.get());

    BOOST_CHECK_EQUAL(clb->mlist.size(), size_t(100));
  }
  pm = nullptr;
  manifest = nullptr;
  dariadb::utils::async::ThreadManager::stop();

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
}

BOOST_AUTO_TEST_CASE(PageManagerCompactionByTime) {
  const std::string storagePath = "testStorage";
  const size_t chunks_size = 256;

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
  auto settings = dariadb::storage::Settings::create(storagePath);
  settings->chunk_size.setValue(chunks_size);

  auto manifest = dariadb::storage::Manifest::create(settings);

  auto _engine_env = dariadb::storage::EngineEnvironment::create();
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
                           settings.get());
  _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::MANIFEST,
                           manifest.get());

  dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());

  auto pm = dariadb::storage::PageManager::create(_engine_env);

  auto e = dariadb::Meas::empty();
  for (int pnum = 0; pnum < 10; ++pnum) {
    size_t count = 100;
    dariadb::MeasArray a(count);

    for (size_t i = 0; i < count; i++) {
      e.id = pnum;
      e.time++;
      e.value = dariadb::Value(i);
      a[i] = e;
    }
    std::string page_file_prefix1 = "page_prefix" + std::to_string(pnum);
    std::string page_file1 = page_file_prefix1 + ".page";
    pm->append(page_file_prefix1, a);
  }
  BOOST_CHECK_GE(dariadb::utils::fs::ls(settings->raw_path.value(), ".page").size(),
                 size_t(10));
  pm->compactbyTime(dariadb::Time(0), e.time);
  BOOST_CHECK_GE(dariadb::utils::fs::ls(settings->raw_path.value(), ".page").size(),
                 size_t(1));
  pm = nullptr;
  manifest = nullptr;
  dariadb::utils::async::ThreadManager::stop();

  if (dariadb::utils::fs::path_exists(storagePath)) {
    dariadb::utils::fs::rm(storagePath);
  }
}

max_stars_repo_name: dariadb/dariadb

max_issues_repo_name: dariadb/dariadb

max_forks_repo_name: dariadb/dariadb


text:
#pragma once

#include <Tanker/Trustchain/Actions/KeyPublish/ToProvisionalUser.hpp>
#include <Tanker/Trustchain/Actions/KeyPublish/ToUser.hpp>
#include <Tanker/Trustchain/Actions/KeyPublish/ToUserGroup.hpp>
#include <Tanker/Trustchain/Actions/Nature.hpp>

#include <boost/variant2/variant.hpp>
#include <gsl/gsl-lite.hpp>
#include <nlohmann/json_fwd.hpp>

#include <cstddef>
#include <cstdint>
#include <type_traits>

namespace Tanker::Trustchain
{
using KeyPublishAction =
    boost::variant2::variant<Actions::KeyPublishToUser,
                             Actions::KeyPublishToUserGroup,
                             Actions::KeyPublishToProvisionalUser>;

Crypto::Hash getHash(KeyPublishAction const& action);
Actions::Nature getNature(KeyPublishAction const& action);
Crypto::Hash const& getAuthor(KeyPublishAction const& action);
Crypto::Signature const& getSignature(KeyPublishAction const& action);

KeyPublishAction deserializeKeyPublishAction(gsl::span<std::uint8_t const>);
}

max_stars_repo_name: TankerHQ/sdk-native

max_issues_repo_name: TankerHQ/sdk-native

max_forks_repo_name: TankerHQ/sdk-native


text:
#include "TimeIntegration.h"
#include "LagrangianState.h"
#include "Inputfile.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <istream>
#include <random>
#include <cmath>
#include <boost/program_options.hpp>
#include <iostream>
#include <iterator>
#include <omp.h>
#include <sys/time.h>

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

TimeIntegration::TimeIntegration(Options& options, ParticlePhysics& physics, LagrangianState& state)
  : options_(options), physics_(&physics), state_(&state)
{
}

TimeIntegration::TimeIntegration(Options& options, ParticlePhysics& physics, LagrangianState& state, LagrangianState& boundary)
  : options_(options), physics_(&physics), state_(&state), boundary_(&boundary)
{
}

TimeIntegration::~TimeIntegration() {

}

void TimeIntegration::euler() {
  MatrixXd DUV, DXY;
  for (int i=0; i<options_.tsteps; i++) {
    // Calculate particle interactions: x_tt = RHS
    const MatrixXd& rhs = physics_->RHS();
    DUV = rhs*options_.dt;
    state_->incrementUV(DUV);
    const MatrixXd& UV = state_->getUV();
    DXY = UV*options_.dt;
    state_->updateXY(DXY);
    if ( (i+1)%options_.tsave == 0) {
      state_->writeXY(options_.outputfile+"_"+std::to_string(i+1)+".csv");
    }

  }

}

max_stars_repo_name: adegenna/HardSphereDynamics

max_issues_repo_name: adegenna/HardSphereDynamics

max_forks_repo_name: adegenna/HardSphereDynamics


text:
/*

    Connection struct for holding all the required information for processing and responding
	to requests

    Author: Jarod Graygo

    Special thanks to GitHub user beached for his barebones ASIO server
    His base code may be found here: https://gist.github.com/beached/d2383f9b14dafcc0f585

*/

#ifndef CONNECTION_HPP
#define CONNECTION_HPP

#include <boost/asio.hpp>
#include <boost/bind.hpp>

using std::string;

// Connection structure that tracks the socket, streambuf, and request in string form
struct Connection {
	Connection(boost::asio::io_service& io_service) : socket(io_service), read_buffer() { }
	Connection(boost::asio::io_service& io_service, size_t max_buffer_size) : socket(io_service), read_buffer(max_buffer_size) { }
	boost::asio::ip::tcp::socket socket;
	boost::asio::streambuf read_buffer;
	string request;
};

#endif // CONNECTION_HPP


text:
/**
*    Copyright (C) 2008 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "mongo/pch.h"

#include "mongo/db/initialize_server_global_state.h"

#include <boost/filesystem/operations.hpp>

#ifndef _WIN32
#include <sys/types.h>
#include <sys/wait.h>
#endif

#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/security_key.h"
#include "mongo/db/cmdline.h"
#include "mongo/util/log.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/processinfo.h"

namespace fs = boost::filesystem;

namespace mongo {

#ifndef _WIN32
    // support for exit value propagation with fork
    void launchSignal( int sig ) {
        if ( sig == SIGUSR2 ) {
            pid_t cur = getpid();

            if ( cur == cmdLine.parentProc || cur == cmdLine.leaderProc ) {
                // signal indicates successful start allowing us to exit
                _exit(0);
            }
        }
    }

    static void setupLaunchSignals() {
        verify( signal(SIGUSR2 , launchSignal ) != SIG_ERR );
    }

    void CmdLine::launchOk() {
        if ( cmdLine.doFork ) {
            // killing leader will propagate to parent
            verify( kill( cmdLine.leaderProc, SIGUSR2 ) == 0 );
        }
    }
#endif

    bool initializeServerGlobalState(bool isMongodShutdownSpecialCase) {

        Listener::globalTicketHolder.resize( cmdLine.maxConns );

#ifndef _WIN32
        if (!fs::is_directory(cmdLine.socket)) {
            cout << cmdLine.socket << " must be a directory" << endl;
            return false;
        }

        if (cmdLine.doFork) {
            fassert(16447, !cmdLine.logpath.empty() || cmdLine.logWithSyslog);

            cout.flush();
            cerr.flush();

            cmdLine.parentProc = getpid();

            // facilitate clean exit when child starts successfully
            setupLaunchSignals();

            cout << "about to fork child process, waiting until server is ready for connections."
                 << endl;

            pid_t child1 = fork();
            if (child1 == -1) {
                cout << "ERROR: stage 1 fork() failed: " << errnoWithDescription();
                _exit(EXIT_ABRUPT);
            }
            else if (child1) {
                // this is run in the original parent process
                int pstat;
                waitpid(child1, &pstat, 0);

                if (WIFEXITED(pstat)) {
                    if (WEXITSTATUS(pstat)) {
                        cout << "ERROR: child process failed, exited with error number "
                             << WEXITSTATUS(pstat) << endl;
                    }
                    else {
                        cout << "child process started successfully, parent exiting" << endl;
                    }

                    _exit(WEXITSTATUS(pstat));
                }

                _exit(50);
            }

            if ( chdir("/") < 0 ) {
                cout << "Cant chdir() while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }
            setsid();

            cmdLine.leaderProc = getpid();

            pid_t child2 = fork();
            if (child2 == -1) {
                cout << "ERROR: stage 2 fork() failed: " << errnoWithDescription();
                _exit(EXIT_ABRUPT);
            }
            else if (child2) {
                // this is run in the middle process
                int pstat;
                cout << "forked process: " << child2 << endl;
                waitpid(child2, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(51);
            }

            // this is run in the final child process (the server)

            // stdout handled in initLogging
            //fclose(stdout);
            //freopen("/dev/null", "w", stdout);

            fclose(stderr);
            fclose(stdin);

            FILE* f = freopen("/dev/null", "w", stderr);
            if ( f == NULL ) {
                cout << "Cant reassign stderr while forking server process: " << strerror(errno) << endl;
                return false;
            }

            f = freopen("/dev/null", "r", stdin);
            if ( f == NULL ) {
                cout << "Cant reassign stdin while forking server process: " << strerror(errno) << endl;
                return false;
            }
        }

        if (cmdLine.logWithSyslog) {
            StringBuilder sb;
            sb << cmdLine.binaryName << "." << cmdLine.port;
            Logstream::useSyslog( sb.str().c_str() );
        }
#endif
        if (!cmdLine.logpath.empty() && !isMongodShutdownSpecialCase) {
            fassert(16448, !cmdLine.logWithSyslog);
            string absoluteLogpath = boost::filesystem::absolute(
                    cmdLine.logpath, cmdLine.cwd).string();
            if (!initLogging(absoluteLogpath, cmdLine.logAppend)) {
                cout << "Bad logpath value: \"" << absoluteLogpath << "\"; terminating." << endl;
                return false;
            }
        }

        if (!cmdLine.pidFile.empty()) {
            writePidFile(cmdLine.pidFile);
        }

        if (!cmdLine.keyFile.empty()) {

            if (!setUpSecurityKey(cmdLine.keyFile)) {
                // error message printed in setUpPrivateKey
                return false;
            }

            AuthorizationManager::setAuthEnabled(true);
        }

        return true;
    }

    static void ignoreSignal( int sig ) {}

    void setupCoreSignals() {
#if !defined(_WIN32)
        verify( signal(SIGHUP , ignoreSignal ) != SIG_ERR );
        verify( signal(SIGUSR2, ignoreSignal ) != SIG_ERR );
#endif
    }

}  // namespace mongo

max_issues_repo_name: qunb/mongo

max_forks_repo_name: qunb/mongo


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2016.
// 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)

#define BOOST_METAPARSE_LIMIT_STRING_SIZE 4
#include <boost/metaparse/string.hpp>

namespace
{
  typedef BOOST_METAPARSE_STRING("abcde") too_long;
}


text:
// This file is part of comma, a generic and flexible library
// Copyright (c) 2011 The University of Sydney
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the University of Sydney nor the
//    names of its contributors may be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE.  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 vsevolod vlaskine

#include <Eigen/Core>
#include <comma/application/command_line_options.h>
#include <comma/base/exception.h>
#include <comma/csv/stream.h>
#include <comma/name_value/serialize.h>
#include <comma/string/string.h>
#include <comma/visiting/traits.h>
#include "../../../../visiting/eigen.h"
#include "../packets.h"
#include "../traits.h"

static void usage( bool verbose = false )
{
    std::cerr << std::endl;
    std::cerr << "convert las (laser exchange format) to csv" << std::endl;
    std::cerr << std::endl;
    std::cerr << "cat points.las | las-to-csv <what> [<options>]" << std::endl;
    std::cerr << std::endl;
    std::cerr << "what" << std::endl;
    std::cerr << "    points: output points" << std::endl;
    std::cerr << "    header: output header as json and exit" << std::endl;
    std::cerr << std::endl;
    std::cerr << "options" << std::endl;
    std::cerr << "    --help,-h: help; --help --verbose: more help" << std::endl;
    std::cerr << "    --no-offset; do not apply cartesian offset to points" << std::endl;
    std::cerr << "    --output-fields: output fields for a given point format (0-5) and exit; if --type not given, las data on stdin used" << std::endl;
    std::cerr << "    --output-format: output format for a given point format (0-5) and exit; if --type not given, las data on stdin used" << std::endl;
    std::cerr << "    --type,--point-format=<point format>: enforce point format" << std::endl;
    std::cerr << "    --verbose,-v: more output" << std::endl;
    if( verbose ) { std::cerr << comma::csv::options::usage() << std::endl; }
    std::cerr << std::endl;
    exit( 0 );
}

struct colour
{
    comma::uint16 red;
    comma::uint16 green;
    comma::uint16 blue;
    colour() : red( 0 ), green( 0 ), blue( 0 ) {};
    colour( comma::uint16 red, comma::uint16 green, comma::uint16 blue ) : red( red ), green( green ), blue( blue ) {};
};

template < unsigned int I > struct point;

template <> struct point< 0 >
{
    Eigen::Vector3d coordinates;
    comma::uint16 intensity;
    unsigned char return_number;
    unsigned char number_of_returns;
    bool scan_direction;
    bool edge_of_flight_line;
    unsigned char classification;
    char scan_angle;
    unsigned char user_data;
    comma::uint16 point_source_id;

    point< 0 >() {}
    template < typename P >
    point< 0 >( const P& p, const Eigen::Vector3d& factor, const Eigen::Vector3d& offset )
        : coordinates( Eigen::Vector3d( factor.x() * p.coordinates.x()
                                      , factor.y() * p.coordinates.y()
                                      , factor.z() * p.coordinates.z() ) + offset )
        , intensity( p.intensity() )
        , return_number( p.returns().number )
        , number_of_returns( p.returns().size )
        , scan_direction( p.returns().scan_direction )
        , edge_of_flight_line( p.returns().edge_of_flight_line )
        , classification( p.classification() )
        , scan_angle( p.scan_angle() )
        , user_data( p.user_data() )
        , point_source_id( p.point_source_id() )
    {
    }
};

template <> struct point< 1 > : public point< 0 >
{
    double gps_time;

    point() {}
    point( const snark::las::point< 1 >& p, const Eigen::Vector3d& factor, const Eigen::Vector3d& offset ) : point< 0 >( p, factor, offset ), gps_time( p.gps_time() ) {}
};

template <> struct point< 2 > : public point< 0 >
{
    ::colour colour;

    point() {}
    point( const snark::las::point< 2 >& p, const Eigen::Vector3d& factor, const Eigen::Vector3d& offset ) : point< 0 >( p, factor, offset ), colour( p.colour.red(), p.colour.green(), p.colour.blue() ) {}
};

template <> struct point< 3 > : public point< 0 >
{
    double gps_time;
    ::colour colour;

    point() {}
    point( const snark::las::point< 3 >& p, const Eigen::Vector3d& factor, const Eigen::Vector3d& offset ) : point< 0 >( p, factor, offset ), gps_time( p.gps_time() ), colour( p.colour.red(), p.colour.green(), p.colour.blue() ) {}
};

namespace comma { namespace visiting {

template <> struct traits< point< 0 > >
{
    template< typename K, typename V > static void visit( const K&, const point< 0 >& t, V& v ) // todo
    {
        v.apply( "coordinates", t.coordinates );
        v.apply( "intensity", t.intensity );
        v.apply( "return_number", t.return_number );
        v.apply( "number_of_returns", t.number_of_returns );
        v.apply( "scan_direction", t.scan_direction );
        v.apply( "edge_of_flight_line", t.edge_of_flight_line );
        v.apply( "classification", t.classification );
        v.apply( "scan_angle", t.scan_angle );
        v.apply( "user_data", t.user_data );
        v.apply( "point_source_id", t.point_source_id );
    }
};

template <> struct traits< colour >
{
    template< typename K, typename V > static void visit( const K&, const colour& t, V& v ) // todo
    {
        v.apply( "red", t.red );
        v.apply( "green", t.green );
        v.apply( "blue", t.blue );
    }
};

template <> struct traits< point< 1 > >
{
    template< typename K, typename V > static void visit( const K& k, const point< 1 >& t, V& v ) // todo
    {
        traits< point< 0 > >::visit( k, t, v );
        v.apply( "gps_time", t.gps_time );
    }
};

template <> struct traits< point< 2 > >
{
    template< typename K, typename V > static void visit( const K& k, const point< 2 >& t, V& v ) // todo
    {
        traits< point< 0 > >::visit( k, t, v );
        v.apply( "colour", t.colour );
    }
};

template <> struct traits< point< 3 > >
{
    template< typename K, typename V > static void visit( const K& k, const point< 3 >& t, V& v ) // todo
    {
        traits< point< 0 > >::visit( k, t, v );
        v.apply( "gps_time", t.gps_time );
        v.apply( "colour", t.colour );
    }
};

} } // namespace comma { namespace visiting {

template < unsigned int I >
static int read_points( const snark::las::header& header, const comma::command_line_options& options )
{
    comma::csv::options csv( options );
    csv.full_xpath = false;
    Eigen::Vector3d factor( header.scale_factor.x(), header.scale_factor.y(), header.scale_factor.z() );
    auto offset = options.exists( "--no-offset" ) ? Eigen::Vector3d::Zero()
                                                  : Eigen::Vector3d( header.offset.x(), header.offset.y(), header.offset.z() );
    comma::csv::output_stream< point< I > > os( std::cout, csv );
    while( std::cin.good() && !std::cin.eof() )
    {
        snark::las::point< I > p;
        std::cin.read( reinterpret_cast< char* >( &p ), snark::las::point< I >::size ); // todo: watch performance
        int count = std::cin.gcount();
        if( count == 0 ) { break; }
        if( count < snark::las::point< I >::size ) { std::cerr << "las-to-csv: expected las point record format " << I << " of " << snark::las::point< I >::size << " bytes, got only: " << count << std::endl; return 1; }
        os.write( point< I >( p, factor, offset ) );
    }
    return 0;
}

static snark::las::header read_header( std::istream& is )
{
    snark::las::header header;
    is.read( reinterpret_cast< char* >( &header ), snark::las::header::size );
    int count = std::cin.gcount();
    if( count < snark::las::header::size ) { COMMA_THROW( comma::exception, "las-to-csv: expected las header of " << snark::las::header::size << " bytes, got only: " << count << std::endl ); }
    return header;
}

int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av, usage );
        boost::optional< unsigned int > point_format = options.optional< unsigned int >( "--type,--point-format" );
        if( ac < 2 ) { usage(); }
        if( options.exists( "--output-fields" ) )
        {
            if( !point_format ) { point_format = read_header( std::cin ).point_data_format(); }
            switch( *point_format )
            {
                case 0: std::cout << comma::join( comma::csv::names< point< 0 > >( false ), ',' ) << std::endl; return 0;
                case 1: std::cout << comma::join( comma::csv::names< point< 1 > >( false ), ',' ) << std::endl; return 0;
                case 2: std::cout << comma::join( comma::csv::names< point< 2 > >( false ), ',' ) << std::endl; return 0;
                case 3: std::cout << comma::join( comma::csv::names< point< 3 > >( false ), ',' ) << std::endl; return 0;
                case 4:
                case 5:
                    std::cerr << "las-to-csv: output fields for point data format " << *point_format << ": todo" << std::endl;
                    return 1;
                default:
                    std::cerr << "las-to-csv: expected point data format between 0 and 5, got: " << *point_format << std::endl;
                    return 1;
            }
            return 0;
        }
        if( options.exists( "--output-format" ) )
        {
            if( !point_format ) { point_format = read_header( std::cin ).point_data_format(); }
            switch( *point_format )
            {
                case 0: std::cout << comma::csv::format::value< point< 0 > >() << std::endl; return 0;
                case 1: std::cout << comma::csv::format::value< point< 1 > >() << std::endl; return 0;
                case 2: std::cout << comma::csv::format::value< point< 2 > >() << std::endl; return 0;
                case 3: std::cout << comma::csv::format::value< point< 3 > >() << std::endl; return 0;
                case 4:
                case 5:
                    std::cerr << "las-to-csv: output fields for point data format " << *point_format << ": todo" << std::endl;
                    return 1;
                default:
                    std::cerr << "las-to-csv: expected point data format between 0 and 5, got: " << *point_format << std::endl;
                    return 1;
            }
            return 0;
        }
        std::string what = av[1];
        snark::las::header header = read_header( std::cin );
        if( !point_format ) { point_format = header.point_data_format(); }
        if( what == "header" ) { comma::write_json( header, std::cout ); return 0; }
        if( what == "points" )
        {
            std::vector< char > offset( header.offset_to_point_data() - snark::las::header::size );
            std::cin.read( &offset[0], offset.size() );
            int count = std::cin.gcount();
            if( count < int( offset.size() ) ) { std::cerr << "las-to-csv: expected " << offset.size() << " bytes, got only: " << count << std::endl; return 1; }
            switch( *point_format )
            {
                case 0: return read_points< 0 >( header, options );
                case 1: return read_points< 1 >( header, options );
                case 2: return read_points< 2 >( header, options );
                case 3: return read_points< 3 >( header, options );
                case 4:
                case 5:
                    std::cerr << "las-to-csv: point data format " << point_format << ": todo" << std::endl;
                    return 1;
                default:
                    std::cerr << "las-to-csv: expected point data format between 0 and 5, got: " << point_format << std::endl;
                    return 1;
            }
            return 0;
        }
        std::cerr << "las-to-csv: expected operation, got: \"" << what << "\"" << std::endl;
        return 1;
    }
    catch( std::exception& ex ) { std::cerr << "las-to-csv: " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << "las-to-csv: unknown exception" << std::endl; }
    return 1;
}

max_stars_repo_name: mission-systems-pty-ltd/snark

max_issues_repo_name: NEU-LC/snark

max_forks_repo_name: NEU-LC/snark