text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2006 StatPro Italia srl

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 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 license for more details.
*/

#include <ql/models/marketmodels/browniangenerators/sobolbrowniangenerator.hpp>
#include <boost/iterator/permutation_iterator.hpp>

namespace QuantLib {

    namespace {

        void fillByFactor(std::vector<std::vector<Size> >& M,
                          Size factors, Size steps) {
            Size counter = 0;
            for (Size i=0; i<factors; ++i)
                for (Size j=0; j<steps; ++j)
                    M[i][j] = counter++;
        }

        void fillByStep(std::vector<std::vector<Size> >& M,
                        Size factors, Size steps) {
            Size counter = 0;
            for (Size j=0; j<steps; ++j)
                for (Size i=0; i<factors; ++i)
                    M[i][j] = counter++;
        }

        // variate 2 is used for the second factor's full path
        void fillByDiagonal(std::vector<std::vector<Size> >& M,
                            Size factors, Size steps) {
            // starting position of the current diagonal
            Size i0 = 0, j0 = 0;
            // current position
            Size i=0, j=0;
            Size counter = 0;
            while (counter < factors*steps) {
                M[i][j] = counter++;
                if (i == 0 || j == steps-1) {
                    // we completed a diagonal and have to start a new one
                    if (i0 < factors-1) {
                        // we start the path of the next factor
                        i0 = i0+1;
                        j0 = 0;
                    } else {
                        // we move along the path of the last factor
                        i0 = factors-1;
                        j0 = j0+1;
                    }
                    i = i0;
                    j = j0;
                } else {
                    // we move along the diagonal
                    i = i-1;
                    j = j+1;
                }
            }
        }

        /*
        // variate 2 is used for the first factor's half path
        void fillByDiagonal(std::vector<std::vector<Size> >& M,
                            Size factors, Size steps) {
            // starting position of the current diagonal
            Size i0 = 0, j0 = 0;
            // current position
            Size i=0, j=0;
            Size counter = 0;
            while (counter < factors*steps) {
                M[i][j] = counter++;
                if (j == 0 || i == factors-1) {
                    // we completed a diagonal and have to start a new one
                    if (j0 < steps-1) {
                        // we move along the path of the first factor
                        i0 = 0;
                        j0 = j0+1;
                    } else {
                        // we complete the next path
                        i0 = i0+1;
                        j0 = steps-1;
                    }
                    i = i0;
                    j = j0;
                } else {
                    // we move along the diagonal
                    i = i+1;
                    j = j-1;
                }
            }
        }
        */

    }

    SobolBrownianGenerator::SobolBrownianGenerator(
                                        Size factors,
                                        Size steps,
                                        Ordering ordering,
                                        unsigned long seed,
                                        SobolRsg::DirectionIntegers integers)
    : factors_(factors), steps_(steps), ordering_(ordering),
      generator_(SobolRsg(factors*steps, seed, integers),
                 InverseCumulativeNormal()),
      bridge_(steps), lastStep_(0),
      orderedIndices_(factors, std::vector<Size>(steps)),
      bridgedVariates_(factors, std::vector<Real>(steps)) {

        switch (ordering_) {
          case Factors:
            fillByFactor(orderedIndices_, factors_, steps_);
            break;
          case Steps:
            fillByStep(orderedIndices_, factors_, steps_);
            break;
          case Diagonal:
            fillByDiagonal(orderedIndices_, factors_, steps_);
            break;
          default:
            QL_FAIL("unknown ordering");
        }
    }

    Real SobolBrownianGenerator::nextPath() {
        typedef InverseCumulativeRsg<SobolRsg,
                                     InverseCumulativeNormal>::sample_type
            sample_type;

        const sample_type& sample = generator_.nextSequence();
        // Brownian-bridge the variates according to the ordered indices
        for (Size i=0; i<factors_; ++i) {
            bridge_.transform(boost::make_permutation_iterator(
                                                  sample.value.begin(),
                                                  orderedIndices_[i].begin()),
                              boost::make_permutation_iterator(
                                                  sample.value.begin(),
                                                  orderedIndices_[i].end()),
                              bridgedVariates_[i].begin());
        }
        lastStep_ = 0;
        return sample.weight;
    }

    const std::vector<std::vector<Size> >&
    SobolBrownianGenerator::orderedIndices() const {
        return orderedIndices_;
    }

    std::vector<std::vector<Real> > SobolBrownianGenerator::transform(
                            const std::vector<std::vector<Real> >& variates) {

        QL_REQUIRE(   (variates.size() == factors_*steps_),
                   "inconsistent variate vector");

        const Size dim    = factors_*steps_;
        const Size nPaths = variates.front().size();

        std::vector<std::vector<Real> >
                       retVal(factors_, std::vector<Real>(nPaths*steps_));

        for (Size j=0; j < nPaths; ++j) {
            std::vector<Real> sample(steps_*factors_);
            for (Size k=0; k < dim; ++k) {
                sample[k] = variates[k][j];
            }
            for (Size i=0; i<factors_; ++i) {
                bridge_.transform(boost::make_permutation_iterator(
                                                  sample.begin(),
                                                  orderedIndices_[i].begin()),
                          boost::make_permutation_iterator(
                                                  sample.begin(),
                                                  orderedIndices_[i].end()),
                          retVal[i].begin()+j*steps_);
            }
        }

        return retVal;
    }

    Real SobolBrownianGenerator::nextStep(std::vector<Real>& output) {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(output.size() == factors_, "size mismatch");
        QL_REQUIRE(lastStep_<steps_, "sequence exhausted");
        #endif
        for (Size i=0; i<factors_; ++i)
            output[i] = bridgedVariates_[i][lastStep_];
        ++lastStep_;
        return 1.0;
    }

    Size SobolBrownianGenerator::numberOfFactors() const { return factors_; }

    Size SobolBrownianGenerator::numberOfSteps() const { return steps_; }

    SobolBrownianGeneratorFactory::SobolBrownianGeneratorFactory(
                                    SobolBrownianGenerator::Ordering ordering,
                                    unsigned long seed,
                                    SobolRsg::DirectionIntegers integers)
    : ordering_(ordering), seed_(seed), integers_(integers) {}

    boost::shared_ptr<BrownianGenerator>
    SobolBrownianGeneratorFactory::create(Size factors, Size steps) const {
        return boost::shared_ptr<BrownianGenerator>(
                         new SobolBrownianGenerator(factors, steps, ordering_,
                                                    seed_, integers_));
    }

}

max_stars_repo_name: sfondi/QuantLib

max_issues_repo_name: sfondi/QuantLib

max_forks_repo_name: sfondi/QuantLib


text: #include <boost/spirit/home/karma/nonterminal/debug_handler.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX 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 "rpcserver.h"

#include <map>
#include <vector>
#include <stdint.h>
#include <stdio.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>

using namespace boost;
using namespace boost::assign;
using namespace std;

void join(const set<int>& v, char c, std::string& s);

/**
 * File sync state info
 **/
UniValue getfilesyncstate(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
                "getfilesyncstate\n"
                "\nReturns an object containing file sync state info.\n"
                // TODO: print result struct
                "\nExamples:\n" +
                HelpExampleCli("getfilesyncstate", "") + HelpExampleRpc("getfilesyncstate", ""));

    UniValue obj(UniValue::VOBJ);

    {
        //LOCK(cs_RequiredFilesMap);

        UniValue requiredFilesList(UniValue::VARR);
        for (auto it = requiredFilesMap.begin(); it != requiredFilesMap.end(); it++) {
            UniValue item(UniValue::VOBJ);
            item.push_back(Pair("key", it->first.ToString()));
            item.push_back(Pair("requestExpirationTime", (uint64_t) it->second.requestExpirationTime));
            item.push_back(Pair("fileExpirationTime", (uint64_t) it->second.fileExpirationTime));

            requiredFilesList.push_back(item);
        }
        obj.push_back(Pair("requiredFilesMap", requiredFilesList));
    }

    {
        //LOCK(cs_FilesPendingMap);

        UniValue filePendingList(UniValue::VARR);
        for (auto it = filesPendingMap.begin(); it != filesPendingMap.end(); it++) {
            const uint256 &fileTxHash = it->first;

            UniValue item(UniValue::VOBJ);

            item.push_back(Pair("key", fileTxHash.ToString()));
            item.push_back(Pair("fileTxHash", it->second.fileTxHash.ToString()));
            std::string nodesList;
            join(it->second.nodes, ',', nodesList);
            item.push_back(Pair("nodes", nodesList));

            filePendingList.push_back(item);
        }
        obj.push_back(Pair("filesPendingMap", filePendingList));
    }

    {
        //LOCK(cs_FilesInFlightMap);

        UniValue fileInFlightList(UniValue::VARR);
        for (auto it = filesInFlightMap.begin(); it != filesInFlightMap.end(); it++) {
            const uint256 &fileTxHash = it->first;

            UniValue item(UniValue::VOBJ);

            item.push_back(Pair("key", fileTxHash.ToString()));
            item.push_back(Pair("nodeId", it->second.nodeId));
            item.push_back(Pair("fileTxHash", fileTxHash.ToString()));
            item.push_back(Pair("nTime", it->second.nTime / 1000000));

            fileInFlightList.push_back(item);
        }
        obj.push_back(Pair("fileInFlightList", fileInFlightList));
    }

    {
        //LOCK(cs_HasFileRequestedNodesMap);

        UniValue hasFileRequestedNodesList(UniValue::VARR);
        for (auto it = hasFileRequestedNodesMap.begin(); it != hasFileRequestedNodesMap.end(); it++) {
            const uint256 &fileTxHash = it->first;

            UniValue item(UniValue::VOBJ);
            item.push_back(Pair("key", fileTxHash.ToString()));

            UniValue fileRequestNodesList(UniValue::VARR);
            BOOST_FOREACH (FileRequest &fileRequest, it->second) {
                UniValue frItem(UniValue::VOBJ);
                frItem.push_back(Pair("nodeId", fileRequest.node));
                frItem.push_back(Pair("date", fileRequest.date / 1000000));
                frItem.push_back(Pair("events", fileRequest.events));

                if (fileRequest.fileHash.is_initialized()) {
                    frItem.push_back(Pair("fileHash", fileRequest.fileHash.get().ToString()));
                }

                if (fileRequest.fileTxHash.is_initialized()) {
                    frItem.push_back(Pair("fileTxHash", fileRequest.fileTxHash.get().ToString()));
                }

                fileRequestNodesList.push_back(frItem);
            }

            item.push_back(Pair("fileRequestNodesList", fileRequestNodesList));

            hasFileRequestedNodesList.push_back(item);
        }
        obj.push_back(Pair("hasFileRequestedNodesList", hasFileRequestedNodesList));
    }

    {
        //LOCK(cs_FileRequestedNodesMap);

        UniValue fileRequestMapList(UniValue::VARR);
        for (auto it = fileRequestedNodesMap.begin(); it != fileRequestedNodesMap.end(); it++) {
            const uint256 &fileTxHash = it->first;

            UniValue item(UniValue::VOBJ);
            item.push_back(Pair("key", fileTxHash.ToString()));

            UniValue fileRequestNodesMapList(UniValue::VARR);
            for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++) {
                UniValue frItem(UniValue::VOBJ);
                frItem.push_back(Pair("nodeId", it2->first));
                frItem.push_back(Pair("node", it2->second.node));
                frItem.push_back(Pair("date", it2->second.date / 1000000));
                frItem.push_back(Pair("events", it2->second.events));

                if (it2->second.fileHash.is_initialized()) {
                    frItem.push_back(Pair("fileHash", it2->second.fileHash.get().ToString()));
                }

                if (it2->second.fileTxHash.is_initialized()) {
                    frItem.push_back(Pair("fileTxHash", it2->second.fileTxHash.get().ToString()));
                }

                fileRequestNodesMapList.push_back(frItem);
            }

            item.push_back(Pair("fileRequestNodesMapList", fileRequestNodesMapList));

            fileRequestMapList.push_back(item);
        }
        obj.push_back(Pair("fileRequestMapList", fileRequestMapList));
    }

    {
        UniValue lockList(UniValue::VOBJ);

        bool isHeldRequiredFilesMap;
        bool isHeldFilesPendingMap;
        bool isHeldFilesInFlightMap;
        bool isHeldHasFileRequestedNodesMap;
        bool isHeldFileRequestedNodesMap;
        bool isHeldMain;
        bool isHeldNodes;

        {TRY_LOCK(cs_RequiredFilesMap, isRequiredFilesMap); isHeldRequiredFilesMap = isRequiredFilesMap;}
        {TRY_LOCK(cs_FilesPendingMap, isFilesPendingMap); isHeldFilesPendingMap = isFilesPendingMap;}
        {TRY_LOCK(cs_FilesInFlightMap, isFilesInFlightMap); isHeldFilesInFlightMap = isFilesInFlightMap;}
        {TRY_LOCK(cs_HasFileRequestedNodesMap, isHasFileRequestedNodesMap); isHeldHasFileRequestedNodesMap = isHasFileRequestedNodesMap;}
        {TRY_LOCK(cs_FileRequestedNodesMap, isFileRequestedNodesMap); isHeldFileRequestedNodesMap = isFileRequestedNodesMap;}
        {TRY_LOCK(cs_main, isMain); isHeldMain = isMain;}
        {TRY_LOCK(cs_vNodes, isNodes); isHeldNodes = isNodes;}

        lockList.push_back(Pair("RequiredFilesMap held", isHeldRequiredFilesMap));
        lockList.push_back(Pair("FilesPendingMap held", isHeldFilesPendingMap));
        lockList.push_back(Pair("FilesInFlightMap held", isHeldFilesInFlightMap));
        lockList.push_back(Pair("HasFileRequestedNodesMap held", isHeldHasFileRequestedNodesMap));
        lockList.push_back(Pair("FileRequestedNodesMap held", isHeldFileRequestedNodesMap));
        lockList.push_back(Pair("Main held", isHeldMain));
        lockList.push_back(Pair("vNode held", isHeldNodes));

        obj.push_back(Pair("locks", lockList));
    }

    return obj;
}

void join(const set<int>& v, char c, std::string& s) {

    s.clear();

    BOOST_FOREACH(const int item, v) {
        s += std::to_string(item);
        s += c;
    }

    if (s.length() > 0) {
        s.resize(s.length() - 1);
    }

}

ext: cpp


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

#ifndef BOOST_RANGE_DIFFERENCE_TYPE_HPP
#define BOOST_RANGE_DIFFERENCE_TYPE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/range/config.hpp>
#include <boost/range/const_iterator.hpp>
#include <boost/iterator/iterator_traits.hpp>

namespace boost
{
        template< class T >
        struct range_difference
        {
                typedef BOOST_DEDUCED_TYPENAME iterator_difference<
                        BOOST_DEDUCED_TYPENAME range_const_iterator<T>::type >::type
                                type;
        };
}

//#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
//#include <boost/range/detail/difference_type.hpp>
//#else

/*
#include <cstddef>
#include <utility>

namespace boost
{
    //////////////////////////////////////////////////////////////////////////
    // default
    //////////////////////////////////////////////////////////////////////////

    template< typename C >
    struct range_difference
    {
        typedef BOOST_DEDUCED_TYPENAME C::difference_type type;
    };

    //////////////////////////////////////////////////////////////////////////
    // pair
    //////////////////////////////////////////////////////////////////////////

    template< typename Iterator >
    struct range_difference< std::pair<Iterator,Iterator> >
    {
        typedef BOOST_DEDUCED_TYPENAME
            iterator_difference<Iterator>::type type;
    };

    template< typename Iterator >
    struct range_difference< const std::pair<Iterator,Iterator> >
    {
        typedef BOOST_DEDUCED_TYPENAME
            iterator_difference<Iterator>::type type;
    };

    //////////////////////////////////////////////////////////////////////////
    // array
    //////////////////////////////////////////////////////////////////////////

    template< typename T, std::size_t sz >
    struct range_difference< T[sz] >
    {
        typedef std::ptrdiff_t type;
    };

    template< typename T, std::size_t sz >
    struct range_difference< const T[sz] >
    {
        typedef std::ptrdiff_t type;
    };

    //////////////////////////////////////////////////////////////////////////
    // string
    //////////////////////////////////////////////////////////////////////////

    template<>
    struct range_difference< char* >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< wchar_t* >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< const char* >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< const wchar_t* >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< char* const >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< wchar_t* const >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< const char* const >
    {
        typedef std::ptrdiff_t type;
    };

    template<>
    struct range_difference< const wchar_t* const >
    {
        typedef std::ptrdiff_t type;
    };

} // namespace boost

#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
*/

#endif

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
#ifndef BOOST_CHECKED_DELETE_HPP
#define BOOST_CHECKED_DELETE_HPP

// The header file at this path is deprecated;
// use boost/core/checked_delete.hpp instead.

#include <boost/core/checked_delete.hpp>

#endif

max_stars_repo_name: awulkiew/core

max_issues_repo_name: awulkiew/core

max_forks_repo_name: awulkiew/core


text:
#include <json11.hpp>
#include <boost/program_options.hpp>
#include "picpac-cv.h"

namespace picpac {
    cv::Mat decode_buffer (const_buffer imbuf, int mode);
}

using namespace std;
using namespace json11;
using namespace picpac;

class Context {
    FileWriter db;
    int radius;
public:
    Context (fs::path const &path, int r): db(path), radius(r) {
    }
    ~Context () {
    }

    void add (Record &rec) {
        do {
            if (rec.size() <= 1) break;
            CHECK(rec.size() == 2);
            cv::Mat image = decode_buffer(rec.field(0), -1);
            string err;
            Json json = Json::parse(rec.field_string(1), err);
            int w = image.cols;
            int h = image.rows;
            bool update = false;
            Json::array shapes;
            for (auto const &shape: json["shapes"].array_items()) {
                if (shape["type"] == "point") {
                    update = true;
                    float x = shape["geometry"]["x"].number_value();
                    float y = shape["geometry"]["y"].number_value();
                    x *= w;
                    y *= h;
                    Json geo = Json::object{
                                {"x", 1.0 * (x - 1.0 * radius) / w},
                                {"y", 1.0 * (y - 1.0 * radius) / h},
                                {"width", 2.0 * radius / w},
                                {"height", 2.0 * radius / h}};
                    /*
                    Json ss = Json::object{
                            {"type", "ellipse"},
                            {"geometry", geo}};
                    shapes.push_back(ss);
                    */
                    shapes.emplace_back(Json::object{
                            {"type", "ellipse"},
                            {"geometry", geo}});
                }
                else {
                    shapes.push_back(shape);
                }
            }
            if (!update) break;
            cout << "<< " << rec.field_string(1) << endl;
            Json::object obj = json.object_items();
            obj["shapes"] = Json(shapes);
            json = Json(obj);
            string f2 = json.dump();
            cout << ">> " << f2 << endl;
            Record r(0, rec.field_string(0), f2);
            r.meta().copy(rec.meta());
            db.append(r);
            return;
        } while (false);
        db.append(rec);
    }
};

int main(int argc, char const* argv[]) {
    fs::path output_path;
    vector<fs::path> input_paths;
    int radius;

    namespace po = boost::program_options;
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "produce help message.")
        ("input", po::value(&input_paths), "")
        ("output", po::value(&output_path), "")
        ("radius,r", po::value(&radius)->default_value(3), "")
        ;

    po::positional_options_description p;
    p.add("input", 1);
    p.add("output", 1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).
                     options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help") || input_paths.empty() || output_path.empty()) {
        cout << "Usage:" << endl;
        cout << "\tpicpac-merge <output> <input> [<input> ...]" << endl;
        cout << desc;
        cout << endl;
        return 0;
    }

    Context ctx(output_path, radius);
    for (auto const &input_path: input_paths) {
        picpac::IndexedFileReader db(input_path);
        db.loop(std::bind(&Context::add, &ctx, placeholders::_1));
    }
    return 0;
}


text:
/*
 * Copyright (c) 2018-2019, Musarraf Hossain
 * All rights reservd.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    3. Neither the name of the copyright holder nor the names of 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 HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <signal.h>
#include <boost/filesystem.hpp>
#include <chrono>
#include <iostream>
#include <memory>
#include <vector>
#include "kacanopen/core/core.h"
#include "kacanopen/core/logger.h"
#include "kacanopen/master/device.h"
#include "kacanopen/master/master.h"
#include "ros/package.h"

static volatile int keepRunning = 1;

void intHandler(int dummy) {
  (void)dummy;
  keepRunning = 0;
}

int main() {
  // Signal handleing
  signal(SIGINT, intHandler);

  // ----------- //
  // Preferences //
  // ----------- //

  // A Roboteq motor driver was used to test this program //
  // The firmware version of roboteq driver: v2.0beta07032018//

  // The node ID of the slave we want to communicate with.
  const uint8_t node_id = 4;

  // Set the name of your CAN bus. "slcan0" is a common bus name
  // for the first SocketCAN device on a Linux system.
  const std::string busname = "can0";

  // Set the baudrate of your CAN bus. Most drivers support the values
  // "1M", "500K", "125K", "100K", "50K", "20K", "10K" and "5K".
  const std::string baudrate = "500K";

  // -------------- //
  // Initialization //
  // -------------- //
  // Create core.
  kaco::Core core;
  std::cout << "Starting Core (connect to the driver and start the receiver "
               "thread)..."
            << std::endl;
  if (!core.start(busname, baudrate)) {
    std::cout << "Starting core failed." << std::endl;
    return EXIT_FAILURE;
  }
  // Create device pointer
  std::shared_ptr<kaco::Device> device;
  // This will be set to true by the callback below.
  bool found_node = false;
  bool node_initialized = false;
  int channel1_speed_ref = 0;
  bool max = false;

  std::cout << "Registering a callback which is called when a device is "
               "detected via NMT..."
            << std::endl;
  core.nmt.register_device_alive_callback(
      [&](const uint8_t new_node_id) mutable {
        // Check if this is the node we are looking for.
        if (new_node_id == node_id) {
          if (!found_node) {
            found_node = true;
            // Load eds file. The eds file must be in the same folder in which
            // the binary is being executed.
            std::string path = ros::package::getPath("kacanopen");
            boost::filesystem::path full_path =
                path +
                "resources/eds_library/roboteq_motor_controllers_v80beta.eds";
            device->load_dictionary_from_eds(full_path.string());

            device->set_entry("cmd_cango/cmd_cango_1", channel1_speed_ref,
                              kaco::WriteAccessMethod::pdo);
            device->add_transmit_pdo_mapping(0x200 + node_id,
                                             {{"cmd_cango/cmd_cango_1", 0}},
                                             kaco::TransmissionType::PERIODIC,
                                             std::chrono::milliseconds(250));

            node_initialized = true;
          }
        }
      });

  while (keepRunning) {
    if (node_initialized) {
      // std::cout << " I am running." << std::endl;
      // Prepare the commands; master side tpdo1 and tpdo2
      if (3000 > channel1_speed_ref && max == false) {
        // channel1_speed_ref++;
        channel1_speed_ref = channel1_speed_ref + 100;
        if (3000 == channel1_speed_ref) {
          max = true;
        }
      }
      if (-3000 < channel1_speed_ref && max == true) {
        // channel1_speed_ref--;
        channel1_speed_ref = channel1_speed_ref - 100;
        if (-3000 == channel1_speed_ref) {
          max = false;
        }
      }
      std::cout << "Channel 1 speed command = " << std::dec
                << channel1_speed_ref << std::endl;

      device->set_entry("cmd_cango/cmd_cango_1", (channel1_speed_ref),
                        kaco::WriteAccessMethod::pdo);
      std::this_thread::sleep_for(std::chrono::milliseconds(250));
    }
  }
  std::cout << "Finished." << std::endl;
  return EXIT_SUCCESS;
}

max_stars_repo_name: grzegorzludwa/kacanopen

max_issues_repo_name: grzegorzludwa/kacanopen

max_forks_repo_name: grzegorzludwa/kacanopen


text:
/*
 * libdisassembly.cpp
 *
 *  Created on: Sep 20, 2015
 *      Author: anon
 */

#include <memory>
#include <boost/python.hpp>
#include <iostream>

#include "arm/ARMDisassembler.h"
#include "arm/ARMArch.h"

using namespace Disassembler;
using namespace boost::python;
using namespace std;

BOOST_PYTHON_MODULE(disassembler) {
	enum_<ARMMode>("ARMMode")
		.value("ARMMode_ARM", ARMMode_ARM)
		.value("ARMMode_Thumb", ARMMode_Thumb)
		.value("ARMMode_Jazelle", ARMMode_Jazelle)
		.value("ARMMode_ThumbEE", ARMMode_ThumbEE)
		.value("ARMMode_Invalid", ARMMode_Invalid)
		.value("InstrSet_ARM", ARMMode_ARM)
		.value("InstrSet_Thumb", ARMMode_Thumb)
		.value("InstrSet_Jazelle", ARMMode_Jazelle)
		.value("InstrSet_ThumbEE", ARMMode_ThumbEE);

	enum_<ARMVariants>("ARMVariants")
		.value("ARMv4", ARMv4)
		.value("ARMv4T", ARMv4T)
		.value("ARMv4All", ARMv4All)
		.value("ARMv5T", ARMv5T)
		.value("ARMv5TE", ARMv5TE)
		.value("ARMv5TEJ", ARMv5TEJ)
		.value("ARMv5TEAll", ARMv5TEAll)
		.value("ARMv5TAll", ARMv5TAll)
		.value("ARMv6", ARMv6)
		.value("ARMv6K", ARMv6K)
		.value("ARMv6T2", ARMv6T2)
		.value("ARMv6All", ARMv6All)
		.value("ARMv7", ARMv7)
		.value("ARMv7S", ARMv7S)
		.value("ARMv7VE", ARMv7VE)
		.value("ARMv7R", ARMv7R)
		.value("ARMv7All", ARMv7All)
		.value("ARMv8", ARMv8)
		.value("ARMSecurityExtension", ARMSecurityExtension)
		.value("ARMvAll", ARMvAll);

	class_<ARMInstruction>("ARMInstruction")
		.def("__str__", &ARMInstruction::toString);

	class_<ARMDisassembler>("ARMDisassembler", init<ARMVariants>())
		.def("disassemble", &ARMDisassembler::disassemble);

	// This implements the translation from std::shared_ptr<ARMInstruction> to python.
	register_ptr_to_python<shared_ptr<ARMInstruction>>();
}

max_stars_repo_name: agustingianni/retools

max_issues_repo_name: agustingianni/retools

max_forks_repo_name: agustingianni/retools


text:
/**
 * @file param_data.hpp
 * @author Ryan Curtin
 *
 * This defines the structure that holds information for each command-line
 * parameter, as well as utility functions it is used with.
 */
#ifndef MLPACK_CORE_UTIL_PARAM_DATA_HPP
#define MLPACK_CORE_UTIL_PARAM_DATA_HPP

#include <mlpack/prereqs.hpp>

#include <boost/any.hpp>

/**
 * The TYPENAME macro is used internally to convert a type into a string.
 */
#define TYPENAME(x) (std::string(typeid(x).name()))

namespace mlpack {
namespace util {

//! Metaprogramming structure for vector detection.
template<typename T>
struct IsStdVector { const static bool value = false; };

//! Metaprogramming structure for vector detection.
template<typename T, typename A>
struct IsStdVector<std::vector<T, A>> { const static bool value = true; };

// Default: HasSerialize = false.
template<bool HasSerialize, typename T>
struct ParameterTypeDeducer
{
  typedef T type;
};

// If we have a Serialize() function, then the type is a string.
template<typename T>
struct ParameterTypeDeducer<true, T>
{
  typedef std::string type;
};

/**
 * Utility struct to return the type that boost::program_options should accept
 * for a given input type.  In general, there is no change from the input type,
 * but in some cases this may be another type.
 */
template<typename T>
struct ParameterType
{
  typedef typename ParameterTypeDeducer<data::HasSerialize<T>::value, T>::type
      type;
};

/**
 * For matrix types, boost::program_options will accept a std::string, not an
 * arma::mat (since it is not clear how to specify a matrix on the
 * command-line).
 */
template<typename eT>
struct ParameterType<arma::Mat<eT>>
{
  typedef std::string type;
};

/**
 * For vector types, boost::program_options will accept a std::string, not an
 * arma::Col<eT> (since it is not clear how to specify a vector on the
 * command-line).
 */
template<typename eT>
struct ParameterType<arma::Col<eT>>
{
  typedef std::string type;
};

/**
 * For row vector types, boost::program_options will accept a std::string, not an
 * arma::Row<eT> (since it is not clear how to specify a vector on the
 * command-line).
 */
template<typename eT>
struct ParameterType<arma::Row<eT>>
{
  typedef std::string type;
};

/**
 * For matrix+dataset info types, we should accept a std::string.
 */
template<typename eT, typename PolicyType>
struct ParameterType<std::tuple<mlpack::data::DatasetMapper<PolicyType>,
                     arma::Mat<eT>>>
{
  typedef std::string type;
};

/**
 * This structure holds all of the information about a single parameter,
 * including its value (which is set when ParseCommandLine() is called).  It
 * does not hold any information about whether or not it was passed---that is
 * handled elsewhere.  A ParamData struct is only useful in order to get
 * "static" information about a parameter.  Note that some parameter types have
 * internal types but also different types that are used by
 * boost::program_options (specifically, matrix and model types map to strings).
 *
 * This structure is somewhat unwieldy and is likely to be refactored at some
 * point in the future, but for now it does the job fine.
 */
struct ParamData
{
  //! Name of this parameter.  This is the name used for HasParam() and
  //! GetParam().
  std::string name;
  //! Description of this parameter, if any.
  std::string desc;
  //! Type information of this parameter.  Note that this is TYPENAME() of the
  //! user-visible parameter type, not whatever is given by ParameterType<>.
  std::string tname;
  //! Alias for this parameter.
  char alias;
  //! True if the wasPassed value should not be ignored.
  bool isFlag;
  //! True if this is a matrix that should not be transposed.  Ignored if the
  //! parameter is not a matrix.
  bool noTranspose;
  //! True if this option is required.
  bool required;
  //! True if this option is an input option (otherwise, it is output).
  bool input;
  //! If this is an input parameter that needs extra loading, this indicates
  //! whether or not it has been loaded.
  bool loaded;
  //! If this is a matrix or model parameter, then boost::program_options will
  //! actually represent this as a string.
  bool isMappedString;
  //! The actual value that is held, as passed from the user (so the type could
  //! be different than the type of the parameter).
  boost::any value;
  //! The value that the user interacts with, if the type is different than the
  //! type of the parameter.  This is used to store matrices, for instance,
  //! because 'value' must hold the string name that the user passed.
  boost::any mappedValue;
  //! The name of the parameter, as seen by boost::program_options.
  std::string boostName;
  //! When the CLI object is destructed, output options must be output.  If
  //! 'input' is false, then this function pointer should point to a function
  //! that outputs the parameter.
  void (*outputFunction)(const ParamData&);
  //! When the CLI object is destructed, output a string representation of the
  //! parameter.
  void (*printFunction)(const ParamData&);
  //! When the CLI object is asked to print help, output the default value.
  std::string (*defaultFunction)(const ParamData&);
  //! When the CLI object is asked to print parameter types, output a string
  //! version of this parameter's type.
  std::string (*stringTypeFunction)();
};

/**
 * If needed, map the parameter name to the name that is used by boost.  This
 * is generally the same as the name, but for matrices it may be different.
 */
template<typename T>
std::string MapParameterName(
    const std::string& identifier,
    const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
    const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
    const typename boost::disable_if<std::is_same<T,
        std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* = 0);

//! This must be overloaded for matrices.
template<typename T>
std::string MapParameterName(
    const std::string& identifier,
    const typename boost::enable_if_c<
        arma::is_arma_type<T>::value ||
        std::is_same<T, std::tuple<mlpack::data::DatasetInfo,
                                   arma::mat>>::value ||
        data::HasSerialize<T>::value>::type* /* junk */ = 0);

/**
 * If needed, map 'trueValue' to the right type and return it.  This is called
 * from GetParam().
 */
template<typename T>
T& HandleParameter(
    typename util::ParameterType<T>::type& value,
    util::ParamData& d,
    const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
    const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
    const typename boost::disable_if<std::is_same<T,
        std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* = 0);

//! This must be overloaded for matrices.
template<typename T>
T& HandleParameter(
    typename util::ParameterType<T>::type& value,
    util::ParamData& d,
    const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0);

//! This must be overloaded for matrices and dataset info objects.
template<typename T>
T& HandleParameter(
    typename util::ParameterType<T>::type& value,
    util::ParamData& d,
    const typename boost::enable_if<std::is_same<T,
        std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* = 0);

//! This must be overloaded for serializable objects.
template<typename T>
T& HandleParameter(
    typename util::ParameterType<T>::type& value,
    util::ParamData& d,
    const typename boost::enable_if<data::HasSerialize<T>>::type* = 0);

//! This will just return the value.
template<typename T>
T& HandleRawParameter(
    typename util::ParameterType<T>::type& value,
    util::ParamData& /* d */,
    const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
    const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
    const typename boost::disable_if<std::is_same<T,
        std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
  return value;
}

//! This will return the mapped value.
template<typename T>
T& HandleRawParameter(
    typename util::ParameterType<T>::type& /* value */,
    util::ParamData& d,
    const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
  return *boost::any_cast<T>(&d.mappedValue);
}

//! This will return the mapped value.
template<typename T>
T& HandleRawParameter(
    typename util::ParameterType<T>::type& /* value */,
    util::ParamData& d,
    const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
  return *boost::any_cast<T>(&d.mappedValue);
}

//! This will return the mapped value.
template<typename T>
T& HandleRawParameter(
    typename util::ParameterType<T>::type& /* value */,
    util::ParamData& d,
    const typename boost::enable_if<std::is_same<T,
        std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
  return *boost::any_cast<T>(&d.mappedValue);
}

} // namespace util
} // namespace mlpack

//! Include implementation of functions.
#include "param_data_impl.hpp"

#endif

max_issues_repo_name: kosmaz/Mlpack

max_forks_repo_name: kosmaz/Mlpack


text:
//
// reactive_serial_port_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.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)
//

#ifndef BOOST_ASIO_DETAIL_REACTIVE_SERIAL_PORT_SERVICE_HPP
#define BOOST_ASIO_DETAIL_REACTIVE_SERIAL_PORT_SERVICE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <cstring>
#include <string>
#include <boost/asio/detail/pop_options.hpp>

#include <boost/asio/serial_port_base.hpp>

#if defined(BOOST_ASIO_HAS_SERIAL_PORT) \
  && !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)

#include <boost/asio/error.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/descriptor_ops.hpp>
#include <boost/asio/detail/reactive_descriptor_service.hpp>

namespace boost {
namespace asio {
namespace detail {

// Extend reactive_descriptor_service to provide serial port support.
template <typename Reactor>
class reactive_serial_port_service
  : public boost::asio::detail::service_base<
      reactive_serial_port_service<Reactor> >
{
public:
  // The native type of a stream handle.
  typedef typename reactive_descriptor_service<Reactor>::native_type
    native_type;

  // The implementation type of the stream handle.
  typedef typename reactive_descriptor_service<Reactor>::implementation_type
    implementation_type;

  reactive_serial_port_service(boost::asio::io_service& io_service)
    : boost::asio::detail::service_base<
        reactive_serial_port_service>(io_service),
      descriptor_service_(boost::asio::use_service<
          reactive_descriptor_service<Reactor> >(io_service))
  {
  }

  // Destroy all user-defined handler objects owned by the service.
  void shutdown_service()
  {
  }

  // Construct a new handle implementation.
  void construct(implementation_type& impl)
  {
    descriptor_service_.construct(impl);
  }

  // Destroy a handle implementation.
  void destroy(implementation_type& impl)
  {
    descriptor_service_.destroy(impl);
  }

  // Open the serial port using the specified device name.
  boost::system::error_code open(implementation_type& impl,
      const std::string& device, boost::system::error_code& ec)
  {
    if (is_open(impl))
    {
      ec = boost::asio::error::already_open;
      return ec;
    }

    int fd = descriptor_ops::open(device.c_str(),
        O_RDWR | O_NONBLOCK | O_NOCTTY, ec);
    if (fd < 0)
      return ec;

    int s = descriptor_ops::fcntl(fd, F_GETFL, ec);
    if (s >= 0)
      s = descriptor_ops::fcntl(fd, F_SETFL, s | O_NONBLOCK, ec);
    if (s < 0)
    {
      boost::system::error_code ignored_ec;
      descriptor_ops::close(fd, ignored_ec);
      return ec;
    }

    // Set up default serial port options.
    termios ios;
    descriptor_ops::clear_error(ec);
    s = descriptor_ops::error_wrapper(::tcgetattr(fd, &ios), ec);
    if (s >= 0)
    {
#if defined(_BSD_SOURCE)
      ::cfmakeraw(&ios);
#else
      ios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK
          | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
      ios.c_oflag &= ~OPOST;
      ios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
      ios.c_cflag &= ~(CSIZE | PARENB);
      ios.c_cflag |= CS8;
#endif
      ios.c_iflag |= IGNPAR;
      ios.c_cflag |= CREAD | CLOCAL;
      descriptor_ops::clear_error(ec);
      s = descriptor_ops::error_wrapper(::tcsetattr(fd, TCSANOW, &ios), ec);
    }
    if (s < 0)
    {
      boost::system::error_code ignored_ec;
      descriptor_ops::close(fd, ignored_ec);
      return ec;
    }

    // We're done. Take ownership of the serial port descriptor.
    if (descriptor_service_.assign(impl, fd, ec))
    {
      boost::system::error_code ignored_ec;
      descriptor_ops::close(fd, ignored_ec);
    }

    return ec;
  }

  // Assign a native handle to a handle implementation.
  boost::system::error_code assign(implementation_type& impl,
      const native_type& native_descriptor, boost::system::error_code& ec)
  {
    return descriptor_service_.assign(impl, native_descriptor, ec);
  }

  // Determine whether the handle is open.
  bool is_open(const implementation_type& impl) const
  {
    return descriptor_service_.is_open(impl);
  }

  // Destroy a handle implementation.
  boost::system::error_code close(implementation_type& impl,
      boost::system::error_code& ec)
  {
    return descriptor_service_.close(impl, ec);
  }

  // Get the native handle representation.
  native_type native(implementation_type& impl)
  {
    return descriptor_service_.native(impl);
  }

  // Cancel all operations associated with the handle.
  boost::system::error_code cancel(implementation_type& impl,
      boost::system::error_code& ec)
  {
    return descriptor_service_.cancel(impl, ec);
  }

  // Set an option on the serial port.
  template <typename SettableSerialPortOption>
  boost::system::error_code set_option(implementation_type& impl,
      const SettableSerialPortOption& option, boost::system::error_code& ec)
  {
    termios ios;
    descriptor_ops::clear_error(ec);
    descriptor_ops::error_wrapper(::tcgetattr(
          descriptor_service_.native(impl), &ios), ec);
    if (ec)
      return ec;

    if (option.store(ios, ec))
      return ec;

    descriptor_ops::clear_error(ec);
    descriptor_ops::error_wrapper(::tcsetattr(
          descriptor_service_.native(impl), TCSANOW, &ios), ec);
    return ec;
  }

  // Get an option from the serial port.
  template <typename GettableSerialPortOption>
  boost::system::error_code get_option(const implementation_type& impl,
      GettableSerialPortOption& option, boost::system::error_code& ec) const
  {
    termios ios;
    descriptor_ops::clear_error(ec);
    descriptor_ops::error_wrapper(::tcgetattr(
          descriptor_service_.native(impl), &ios), ec);
    if (ec)
      return ec;

    return option.load(ios, ec);
  }

  // Send a break sequence to the serial port.
  boost::system::error_code send_break(implementation_type& impl,
      boost::system::error_code& ec)
  {
    descriptor_ops::clear_error(ec);
    descriptor_ops::error_wrapper(::tcsendbreak(
          descriptor_service_.native(impl), 0), ec);
    return ec;
  }

  // Write the given data. Returns the number of bytes sent.
  template <typename ConstBufferSequence>
  size_t write_some(implementation_type& impl,
      const ConstBufferSequence& buffers, boost::system::error_code& ec)
  {
    return descriptor_service_.write_some(impl, buffers, ec);
  }

  // Start an asynchronous write. The data being written must be valid for the
  // lifetime of the asynchronous operation.
  template <typename ConstBufferSequence, typename Handler>
  void async_write_some(implementation_type& impl,
      const ConstBufferSequence& buffers, Handler handler)
  {
    descriptor_service_.async_write_some(impl, buffers, handler);
  }

  // Read some data. Returns the number of bytes received.
  template <typename MutableBufferSequence>
  size_t read_some(implementation_type& impl,
      const MutableBufferSequence& buffers, boost::system::error_code& ec)
  {
    return descriptor_service_.read_some(impl, buffers, ec);
  }

  // Start an asynchronous read. The buffer for the data being received must be
  // valid for the lifetime of the asynchronous operation.
  template <typename MutableBufferSequence, typename Handler>
  void async_read_some(implementation_type& impl,
      const MutableBufferSequence& buffers, Handler handler)
  {
    descriptor_service_.async_read_some(impl, buffers, handler);
  }

private:
  // The handle service used for initiating asynchronous operations.
  reactive_descriptor_service<Reactor>& descriptor_service_;
};

} // namespace detail
} // namespace asio
} // namespace boost

#endif // defined(BOOST_ASIO_HAS_SERIAL_PORT)
       //   && !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_REACTIVE_SERIAL_PORT_SERVICE_HPP


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_FLAT_STATIC_BUFFER_HPP
#define BOOST_BEAST_FLAT_STATIC_BUFFER_HPP

#include <boost/beast/core/detail/config.hpp>
#include <boost/asio/buffer.hpp>
#include <algorithm>
#include <cstddef>
#include <cstring>

namespace boost {
namespace beast {

/** A dynamic buffer using a fixed size internal buffer.

    A dynamic buffer encapsulates memory storage that may be
    automatically resized as required, where the memory is
    divided into two regions: readable bytes followed by
    writable bytes. These memory regions are internal to
    the dynamic buffer, but direct access to the elements
    is provided to permit them to be efficiently used with
    I/O operations.

    Objects of this type meet the requirements of DynamicBuffer
    and have the following additional properties:

    @li A mutable buffer sequence representing the readable
    bytes is returned by @ref data when `this` is non-const.

    @li Buffer sequences representing the readable and writable
    bytes, returned by @ref data and @ref prepare, will have
    length one.

    @li Ownership of the underlying storage belongs to the
    derived class.

    @note Variables are usually declared using the template class
    @ref flat_static_buffer; however, to reduce the number of template
    instantiations, objects should be passed `flat_static_buffer_base&`.

    @see flat_static_buffer
*/
class flat_static_buffer_base
{
    char* begin_;
    char* in_;
    char* out_;
    char* last_;
    char* end_;

    flat_static_buffer_base(
        flat_static_buffer_base const& other) = delete;
    flat_static_buffer_base& operator=(
        flat_static_buffer_base const&) = delete;

public:
    /** Constructor

        This creates a dynamic buffer using the provided storage area.

        @param p A pointer to valid storage of at least `n` bytes.

        @param n The number of valid bytes pointed to by `p`.
    */
    flat_static_buffer_base(
        void* p, std::size_t n) noexcept
    {
        reset(p, n);
    }

    /** Clear the readable and writable bytes to zero.

        This function causes the readable and writable bytes
        to become empty. The capacity is not changed.

        Buffer sequences previously obtained using @ref data or
        @ref prepare become invalid.

        @esafe

        No-throw guarantee.
    */
    BOOST_BEAST_DECL
    void
    clear() noexcept;

#ifdef BOOST_BEAST_ALLOW_DEPRECATED
    /// Change the number of readable and writable bytes to zero.
    void
    reset() noexcept
    {
        clear();
    }
#elif ! BOOST_BEAST_DOXYGEN
    template<std::size_t I = 0>
    void
    reset() noexcept
    {
        static_assert(I != 0,
            BOOST_BEAST_DEPRECATION_STRING);
    }
#endif

    //--------------------------------------------------------------------------

    /// The ConstBufferSequence used to represent the readable bytes.
    using const_buffers_type = net::const_buffer;

    /// The MutableBufferSequence used to represent the readable bytes.
    using mutable_data_type = net::mutable_buffer;

    /// The MutableBufferSequence used to represent the writable bytes.
    using mutable_buffers_type = net::mutable_buffer;

    /// Returns the number of readable bytes.
    std::size_t
    size() const noexcept
    {
        return out_ - in_;
    }

    /// Return the maximum number of bytes, both readable and writable, that can ever be held.
    std::size_t
    max_size() const noexcept
    {
        return dist(begin_, end_);
    }

    /// Return the maximum number of bytes, both readable and writable, that can be held without requiring an allocation.
    std::size_t
    capacity() const noexcept
    {
        return max_size();
    }

    /// Returns a constant buffer sequence representing the readable bytes
    const_buffers_type
    data() const noexcept
    {
        return {in_, dist(in_, out_)};
    }

    /// Returns a constant buffer sequence representing the readable bytes
    const_buffers_type
    cdata() const noexcept
    {
        return data();
    }

    /// Returns a mutable buffer sequence representing the readable bytes
    mutable_data_type
    data() noexcept
    {
        return {in_, dist(in_, out_)};
    }

    /** Returns a mutable buffer sequence representing writable bytes.

        Returns a mutable buffer sequence representing the writable
        bytes containing exactly `n` bytes of storage.

        All buffers sequences previously obtained using
        @ref data or @ref prepare are invalidated.

        @param n The desired number of bytes in the returned buffer
        sequence.

        @throws std::length_error if `size() + n` exceeds `max_size()`.

        @esafe

        Strong guarantee.
    */
    BOOST_BEAST_DECL
    mutable_buffers_type
    prepare(std::size_t n);

    /** Append writable bytes to the readable bytes.

        Appends n bytes from the start of the writable bytes to the
        end of the readable bytes. The remainder of the writable bytes
        are discarded. If n is greater than the number of writable
        bytes, all writable bytes are appended to the readable bytes.

        All buffers sequences previously obtained using
        @ref data or @ref prepare are invalidated.

        @param n The number of bytes to append. If this number
        is greater than the number of writable bytes, all
        writable bytes are appended.

        @esafe

        No-throw guarantee.
    */
    void
    commit(std::size_t n) noexcept
    {
        out_ += (std::min<std::size_t>)(n, last_ - out_);
    }

    /** Remove bytes from beginning of the readable bytes.

        Removes n bytes from the beginning of the readable bytes.

        All buffers sequences previously obtained using
        @ref data or @ref prepare are invalidated.

        @param n The number of bytes to remove. If this number
        is greater than the number of readable bytes, all
        readable bytes are removed.

        @esafe

        No-throw guarantee.
    */
    BOOST_BEAST_DECL
    void
    consume(std::size_t n) noexcept;

protected:
    /** Constructor

        The buffer will be in an undefined state. It is necessary
        for the derived class to call @ref reset with a pointer
        and size in order to initialize the object.
    */
    flat_static_buffer_base() = default;

    /** Reset the pointed-to buffer.

        This function resets the internal state to the buffer provided.
        All input and output sequences are invalidated. This function
        allows the derived class to construct its members before
        initializing the static buffer.

        @param p A pointer to valid storage of at least `n` bytes.

        @param n The number of valid bytes pointed to by `p`.

        @esafe

        No-throw guarantee.
    */
    BOOST_BEAST_DECL
    void
    reset(void* p, std::size_t n) noexcept;

private:
    static
    std::size_t
    dist(char const* first, char const* last) noexcept
    {
        return static_cast<std::size_t>(last - first);
    }
};

//------------------------------------------------------------------------------

/** A DynamicBuffer with a fixed size internal buffer.

    Buffer sequences returned by @ref data and @ref prepare
    will always be of length one.
    This implements a dynamic buffer using no memory allocations.

    @tparam N The number of bytes in the internal buffer.

    @note To reduce the number of template instantiations when passing
    objects of this type in a deduced context, the signature of the
    receiving function should use @ref flat_static_buffer_base instead.

    @see flat_static_buffer_base
*/
template<std::size_t N>
class flat_static_buffer : public flat_static_buffer_base
{
    char buf_[N];

public:
    /// Constructor
    flat_static_buffer(flat_static_buffer const&);

    /// Constructor
    flat_static_buffer()
        : flat_static_buffer_base(buf_, N)
    {
    }

    /// Assignment
    flat_static_buffer& operator=(flat_static_buffer const&);

    /// Returns the @ref flat_static_buffer_base portion of this object
    flat_static_buffer_base&
    base()
    {
        return *this;
    }

    /// Returns the @ref flat_static_buffer_base portion of this object
    flat_static_buffer_base const&
    base() const
    {
        return *this;
    }

    /// Return the maximum sum of the input and output sequence sizes.
    std::size_t constexpr
    max_size() const
    {
        return N;
    }

    /// Return the maximum sum of input and output sizes that can be held without an allocation.
    std::size_t constexpr
    capacity() const
    {
        return N;
    }
};

} // beast
} // boost

#include <boost/beast/core/impl/flat_static_buffer.hpp>
#ifdef BOOST_BEAST_HEADER_ONLY
#include <boost/beast/core/impl/flat_static_buffer.ipp>
#endif

#endif

max_stars_repo_name: Netis/packet-agent

max_issues_repo_name: Netis/packet-agent

max_forks_repo_name: Netis/packet-agent


text:
/*
 * SerialPort.cpp
 *
 *  Created on: 2012-4-8
 *      Author: startar
 */

#include <basketball_base_serial/SerialPort.h>
#include <vector>
#include <boost/make_shared.hpp>

//using namespace std;
//using namespace boost;

namespace serial {

SerialPort::SerialPort()
{
    std::cout << "SerialPort Object created!" << std::endl;

    m_state=WAITING_FF ;

    m_tempBuf.resize(1024, 0);

}

SerialPort::~SerialPort()
{
    m_pios->stop();
    m_thread.join();
}

void SerialPort::start_a_read()
{

    boost::mutex::scoped_lock lock(m_serialMutex);

    // 启动一次异步读
    m_pSerial->async_read_some(boost::asio::buffer(m_tempBuf), boost::bind(&SerialPort::readHandler,
            this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred
            ));
}

void SerialPort::start_a_write()
{
    boost::mutex::scoped_lock lock(m_serialMutex);

    // 启动一次异步写
    boost::asio::async_write(*m_pSerial, boost::asio::buffer(*(m_writeQueue.front())),
            bind(&SerialPort::writeHandler, this, boost::asio::placeholders::error));
}

void SerialPort::mainRun()
{
    std::cout << "SerialPort mainThread STARTED!" << std::endl;

    // 初始化工作状态
    m_state = WAITING_FF;

    // 设置Header存储区的大小为4字节
    m_currentHeader.resize(4, 0);

    // 启动一次异步读
    start_a_read();

    // 开始跑io_service::run()
    m_pios->run();

    std::cout << "SerialPort mainThread EXITED!" << std::endl;
}

void SerialPort::readHandler(const boost::system::error_code &ec, size_t bytesTransferred)
{
    if (ec)
    {
        // TODO: 报错
        std::cout << "SerialPort read error !!" << std::endl;
        return;
    }

//    unsigned int checksum = 0;
    // 处理每个读到的字符
    for (size_t i=0; i<bytesTransferred; i++)
    {
        // 新拿一个字节出来
        uint8_t byte = m_tempBuf.at(i);
        //printf("State=%d, Processing byte: 0x%X \n", m_state, byte);

        // 状态机...
        switch (m_state) {
        case WAITING_FF:
            // 如果新读到的字节是0xFF, 则转移状态至WAITING_FF2
            checksum = 0;
            if (byte==(uint8_t)0xFF)
            {
                 m_state = WAITING_FF2;
                 //std::cout << "Reading" << std::endl;

                    // 启动超时定时器
                    m_ptimer.reset(new boost::asio::deadline_timer(*m_pios,
                            boost::posix_time::milliseconds(m_timeOut)));
                    m_ptimer->async_wait(bind(
                            &SerialPort::timeoutHandler,
                            this,
                            boost::asio::placeholders::error));
            }
            break;
        case WAITING_FF2:
            // 如果新读到的字节的0xFF, 则转移状态至READING_HEAD, 否则回到WAITING_FF
            if (byte==(uint8_t)0xFF)
            {
                //std::cout << "Get a new datagram header !!" << std::endl;

                m_HeaderBytesRead = 0;
                m_state = READING_HEAD;
                //std::cout << "Reading" << std::endl;
            }
            else {
                m_state = WAITING_FF;
                //std::cout << "waiting" << std::endl;
            }
            break;
        case READING_HEAD:
            // 将新字节存入m_currentHeader
            m_currentHeader[m_HeaderBytesRead] = byte;
            checksum += byte;
            m_HeaderBytesRead++;
            //std::cout << "header:" << (int)byte << std::endl;

            if (HEADER_LEN == m_HeaderBytesRead)	// 如果4个字节都已经读出
            {
                // 读出数据报文的长度, 并将m_currentData的大小重设为该长度
                uint16_t dataLen =
                        ((uint16_t)(m_currentHeader[1]) << 8) + m_currentHeader[2];
                //std::cout << dataLen << std::endl ;
                //std::cout << "ok" << std::endl;
                if (dataLen>0&&dataLen<14)
                {
                    m_currentData.resize(dataLen-1, 0);
                    if(dataLen == 2)
                    {
                        ROS_WARN("Recv a detect msg\n") ;
                    }
                    m_DataBytesRead = 0;
                    m_state = READING_DATA;
                }
                else {
                    m_state = WAITING_FF;
                    //std::cout << "READING_HEAD ERROR" << std::endl;
                }
            }
            break;
        case READING_DATA:
            // 将新字节存入m_currentData

            //ROS_WARN("Reading Data");
            m_currentData[m_DataBytesRead++] = byte ;
            checksum += byte;
            //std::cout << "checksum is now :" << checksum << std::endl;
           // cout<<m_currentData.size()<<endl ;
//            std::cout << "data" << (int)byte << std::endl;
            if (m_currentData.size() == m_DataBytesRead)	// 如果所有字节都已经读出
            {
//                ROS_WARN("Reading Data");
                m_state = READING_CHECKSUM;
            }
            break;
        case READING_CHECKSUM:
            m_ptimer->cancel();
            m_ptimer.reset();
            // 计算校验和
            //for (size_t k=0; k<m_currentHeader.size(); k++)
                //byteSum += m_currentHeader.at(k);
            //for (size_t k=0; k<m_currentData.size(); k++)
            //    checksum += m_currentData.at(k);

            if ( (uint8_t)checksum == byte)
            {
                //std::cout << "A new datagram received !!" << std::endl;
                m_dataCallbackFunc(m_currentData,m_currentHeader[3]);
            }
            else {
                /*cout << "checksum is :" << (unsigned int)checksum << endl;
                cout << checksum%255 << endl;
                cout << (int)byte << endl;
                cout << "checksum error !!" << endl;*/
            }

            m_state = WAITING_FF;
            break;
        }
    }
    //std::cout << "Finish a read operation !!" << std::endl;
    start_a_read();
}

void SerialPort::writeHandler(const boost::system::error_code &ec)
{
    if (ec)
    {
        // TODO: 报错
    }

    {
        boost::mutex::scoped_lock lock(m_writeQueueMutex);
        m_writeQueue.pop();

        if (m_writeQueue.empty()==false)
        {
            start_a_write();
        }
    }
}

void SerialPort::timeoutHandler(const boost::system::error_code &ec)
{
    if (!ec)
    {
        std::cout << "Time Out !" << std::endl;
        m_state = WAITING_FF;
    }
}

void SerialPort::setSerialParams(const SerialParams &params)
{
    m_serialParams = params;
}

void SerialPort::setTimeOut(int timeout)
{
    m_timeOut = timeout;
}

bool SerialPort::startThread()
{
    std::cout << "SerialPort::startThread() called!" << std::endl;

    // 创建io_service对象
    m_pios = boost::make_shared<boost::asio::io_service>();

    try {
        // 创建一个serial_port对象, 替换掉原来的
        m_pSerial = boost::make_shared<boost::asio::serial_port>(boost::ref(*m_pios), m_serialParams.serialPort);

        // 设置串口通信参数
        // PS: 这里的强制转换不是什么好习惯... 我只是图省事
        m_pSerial->set_option(
                boost::asio::serial_port::baud_rate(m_serialParams.baudRate));
        m_pSerial->set_option(
                boost::asio::serial_port::flow_control((boost::asio::serial_port::flow_control::type)m_serialParams.flowControl));
        m_pSerial->set_option(
                boost::asio::serial_port::parity((boost::asio::serial_port::parity::type)m_serialParams.parity));
        m_pSerial->set_option(
                boost::asio::serial_port::stop_bits((boost::asio::serial_port::stop_bits::type)m_serialParams.stopBits));
        m_pSerial->set_option(boost::asio::serial_port::character_size(8));
    }
    catch (std::exception &e) {
        std::cout << "Failed to open serial port !" << std::endl;
        std::cout << "Error Info: " << e.what() << std::endl;
        return false;
    }

    try {
        // 创建线程
        m_thread = boost::thread(boost::bind(&SerialPort::mainRun, this));
    }
    catch (std::exception &e) {
        std::cout << "Failed to create thread !" << std::endl;
        std::cout << "Error Info: " << e.what() << std::endl;
        return false;
    }
    return true;
}

bool SerialPort::stopThread()
{
    m_pios->stop();
    return true;
}

void SerialPort::setCallbackFunc(const boost::function<void(ByteVector,int)> &func)
{
    m_dataCallbackFunc = func;
}

/*
bool SerialPort::writeDatagram(const XM_msgs::XM_Datagram &datagram)
{
    const size_t dataLen = datagram.data.size();

    // 准备数据
    ByteVector bufToSend(2 + HEADER_LEN + dataLen + 1, 0);
    bufToSend[0] = bufToSend[1] = (uint8_t)0xFF;
    bufToSend[2] = datagram.sender;
    bufToSend[3] = datagram.receiver;
    bufToSend[4] = (uint8_t)(dataLen >> 8);
    bufToSend[5] = (uint8_t)(dataLen & 0xFF);
    for (size_t i=0; i<dataLen; i++)
        bufToSend[6+i] = datagram.data.at(i);

/*
    // 准备数据
    ByteVector bufToSend(2 + HEADER_LEN-1 + dataLen + 1, 0);
    bufToSend[0] = bufToSend[1] = (uint8_t)0xFF;
    bufToSend[2] = datagram.sender;
    bufToSend[3] = datagram.receiver;
    bufToSend[4] = (uint8_t)(dataLen & 0xFF);
    for (size_t i=0; i<dataLen; i++)
        bufToSend[5+i] = datagram.data.at(i);

    // 计算校验和
    uint32_t byteSum = 0;
    for (size_t i=2; i<bufToSend.size()-1; i++)
        byteSum += bufToSend.at(i);
    bufToSend[bufToSend.size()-1] = (uint8_t)(byteSum % 255);

    cout << "Sending Bytes: " << endl;
    for (size_t i=0; i<bufToSend.size(); i++)
    {
        printf("%02X ", bufToSend.at(i));
    }
    cout << endl;

    // 调用writeRaw
    return writeRaw(bufToSend);
}
*/

bool SerialPort::writeRaw(const ByteVector &rawData)
{
    boost::mutex::scoped_lock lock(m_writeQueueMutex);	// 上锁

    bool writeIdle = m_writeQueue.empty();			// 检测当前队列是否为空
    pByteVector data(new ByteVector(rawData));
    m_writeQueue.push(data);						// 将数据拷贝一份, 并加入队列里去

    if (writeIdle) start_a_write();					// 如果没有在写数据, 则启动一次异步写过程

    return true;
}

} /* namespace XM_SerialNode */


text:
// Luaponte library

// Copyright (c) 2012 Peter Colberg

// Luaponte is based on Luabind, a library, inspired by and similar to
// Boost.Python, that helps you create bindings between C++ and Lua,
// Copyright (c) 2003-2010 Daniel Wallin and Arvid Norberg.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef LUAPONTE_DETAIL_CONVERSION_STORAGE_HPP
#define LUAPONTE_DETAIL_CONVERSION_STORAGE_HPP

#include <luaponte/config.hpp>
#include <boost/aligned_storage.hpp>

namespace luaponte {
namespace detail {

typedef void(*destruction_function)(void*);

// This is used by the converters in policy.hpp, and
// class_rep::convert_to as temporary storage when constructing
// holders.

struct conversion_storage
{
    conversion_storage()
      : destructor(0)
    {}

    ~conversion_storage()
    {
        if (destructor)
            destructor(&data);
    }

    // Unfortunately the converters currently doesn't have access to
    // the actual type being converted when this is instantiated, so
    // we have to guess a max size.
    boost::aligned_storage<128> data;
    destruction_function destructor;
};

} // namespace detail
} // namespace luaponte

#endif // LUAPONTE_DETAIL_CONVERSION_STORAGE_HPP

max_stars_repo_name: jb--/luaponte

max_issues_repo_name: halmd-org/luaponte

max_forks_repo_name: halmd-org/luaponte


text:
#include "BeerScorer.h"

#include <algorithm>
#include <cmath>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <cstdio>
#include <string>
#include <vector>

#include <boost/thread/mutex.hpp>

#if defined(__GLIBCXX__) || defined(__GLIBCPP__)
#include "Fdstream.h"
#endif

#include "ScoreStats.h"
#include "Util.h"

using namespace std;

namespace MosesTuning
{

// Beer supported
#if (defined(__GLIBCXX__) || defined(__GLIBCPP__)) && !defined(_WIN32)

// for clarity
#define CHILD_STDIN_READ pipefds_input[0]
#define CHILD_STDIN_WRITE pipefds_input[1]
#define CHILD_STDOUT_READ pipefds_output[0]
#define CHILD_STDOUT_WRITE pipefds_output[1]

BeerScorer::BeerScorer(const string& config)
  : StatisticsBasedScorer("BEER",config)
{
  beer_dir = getConfig("beerDir", "");
  beer_threads = getConfig("beerThreads", "1");
  beer_model = getConfig("beerModel", "");
  if (beer_dir == "") {
    throw runtime_error("BEER dir is required, see BeerScorer.h for full list of options: --scconfig beerDir:/path/to/beerDir");
  }
  int pipe_status;
  int pipefds_input[2];
  int pipefds_output[2];
  // Create pipes for process communication
  pipe_status = pipe(pipefds_input);
  if (pipe_status == -1) {
    throw runtime_error("Error creating pipe");
  }
  pipe_status = pipe(pipefds_output);
  if (pipe_status == -1) {
    throw runtime_error("Error creating pipe");
  }
  // Fork
  pid_t pid;
  pid = fork();
  if (pid == pid_t(0)) {
    // Child's IO
    dup2(CHILD_STDIN_READ, 0);
    dup2(CHILD_STDOUT_WRITE, 1);
    close(CHILD_STDIN_WRITE);
    close(CHILD_STDOUT_READ);
    // Call BEER
    stringstream beer_cmd;
    beer_cmd << beer_dir << "/scripts/interactive --threads " << beer_threads;
    if(beer_model != ""){
	    beer_cmd << " --model " << beer_model;
    }
    TRACE_ERR("Executing: " + beer_cmd.str() + "\n");
    execl("/bin/bash", "bash", "-c", beer_cmd.str().c_str(), (char*)NULL);
    throw runtime_error("Continued after execl");
  }
  // Parent's IO
  close(CHILD_STDIN_READ);
  close(CHILD_STDOUT_WRITE);
  m_to_beer = new ofdstream(CHILD_STDIN_WRITE);
  m_from_beer = new ifdstream(CHILD_STDOUT_READ);
}

BeerScorer::~BeerScorer()
{
  // Cleanup IO
  // delete m_to_beer;
  // delete m_from_beer;
}

void BeerScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
  // Just store strings since we're sending lines to an external process
  for (int incRefs = 0; incRefs < (int)referenceFiles.size(); incRefs++) {
    m_references.clear();
    ifstream in(referenceFiles.at(incRefs).c_str());
    if (!in) {
      throw runtime_error("Unable to open " + referenceFiles.at(incRefs));
    }
    string line;
    while (getline(in, line)) {
      line = this->preprocessSentence(line);
      m_references.push_back(line);
    }
    m_multi_references.push_back(m_references);
  }
  m_references=m_multi_references.at(0);
}

void BeerScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry)
{
  string sentence = this->preprocessSentence(text);
  string stats_str;
  stringstream input;
  // SCORE ||| ref1 ||| ref2 ||| ... ||| text
  input << "EVAL BEST";
  input << " ||| " << text;
  for (int incRefs = 0; incRefs < (int)m_multi_references.size(); incRefs++) {
    if (sid >= m_multi_references.at(incRefs).size()) {
      stringstream msg;
      msg << "Sentence id (" << sid << ") not found in reference set";
      throw runtime_error(msg.str());
    }
    string ref = m_multi_references.at(incRefs).at(sid);
    input << " ||| " << ref;
  }
  input << "\n";
  // Threadsafe IO
#ifdef WITH_THREADS
  mtx.lock();
#endif
  //TRACE_ERR ( "in: " + input.str() );
  *m_to_beer << input.str();
  m_from_beer->getline(stats_str);
  //TRACE_ERR ( "out: " + stats_str + "\n" );
#ifdef WITH_THREADS
  mtx.unlock();
#endif
  float score = atof(stats_str.c_str());
  entry.reset();
  entry.add(score);
  entry.add(1.0);
  //entry.set(stats_str);
}

float BeerScorer::calculateScore(const vector<ScoreStatsType>& comps) const
{
  double result = comps[0]/comps[1];
  return result;
}

#else

// Beer unsupported, throw error if used

BeerScorer::BeerScorer(const string& config)
  : StatisticsBasedScorer("BEER",config)
{
  throw runtime_error("BEER unsupported, requires GLIBCXX");
}

BeerScorer::~BeerScorer() {}

void BeerScorer::setReferenceFiles(const vector<string>& referenceFiles) {}

void BeerScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry) {}

float BeerScorer::calculateScore(const vector<ScoreStatsType>& comps) const
{
  // Should never be reached
  return 0.0;
}

#endif

}

max_stars_repo_name: stanojevic/beer

max_issues_repo_name: neural-dialogue-metrics/beer

max_forks_repo_name: stanojevic/beer


text:
#include "ScoliosisQueryNN.h"
#include <boost/asio.hpp>
#include <iostream>

using boost::asio::ip::tcp;

NeuralNetworkSocketConnection::NeuralNetworkSocketConnection():
  m_socket(io_context),
  connected(false)
{
  Connect();
}

bool NeuralNetworkSocketConnection::Connect()
{
  if (connected) return true;
  try
  {
    tcp::resolver resolver(io_context);
    boost::asio::connect(m_socket, resolver.resolve("localhost", "9999"));
    connected = true;
    return true;
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
    return false;
  }
}

NetworkResponse NeuralNetworkSocketConnection::QueryNN(unsigned char * image)
{
  boost::asio::write(this->m_socket, boost::asio::buffer(image, 512 * 512));
  unsigned char reply[8];
  size_t reply_length = boost::asio::read(this->m_socket, boost::asio::buffer(reply, 8));
  float * reply_cast = reinterpret_cast<float *>(&reply[0]);
  return NetworkResponse{ reply_cast[0], reply_cast[1] };
}

ext: cxx

max_stars_repo_name: HastingsGreer/UltrasoundScoliosis

max_issues_repo_name: HastingsGreer/UltrasoundScoliosis

max_forks_repo_name: HastingsGreer/UltrasoundScoliosis


text:
//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "armnnTfLiteParser/ITfLiteParser.hpp"
#include "ParserFlatbuffersFixture.hpp"

#include <string>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(TensorflowLiteParser)

struct LoadScopeDynamicTensorFixture : public ParserFlatbuffersFixture
{
    explicit LoadScopeDynamicTensorFixture(const std::string& shape0,
                                           const std::string& shape1,
                                           const std::string& shape2)
    {
        m_JsonString = R"(
        {
            "version": 3,
            "operator_codes": [
                {
                    "builtin_code": "AVERAGE_POOL_2D",
                    "version": 1
                },
                {
                    "builtin_code": "SOFTMAX",
                    "version": 1
                }
            ],
            "subgraphs": [
                {
                    "tensors": [
                        {
                            "shape": )" + shape0 + R"(,
                            "type": "FLOAT32",
                            "buffer": 1,
                            "name": "input0",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },
                        {
                            "shape": )" + shape1 + R"(,
                            "type": "FLOAT32",
                            "buffer": 3,
                            "name": "output",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },
                        {
                            "shape": )" + shape2 + R"(,
                            "type": "FLOAT32",
                            "buffer": 2,
                            "name": "model/average_pooling2d/AvgPool",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        }
                    ],
                    "inputs": [
                        0
                    ],
                    "outputs": [
                        1
                    ],
                    "operators": [
                        {
                            "opcode_index": 1,
                            "inputs": [
                                2
                            ],
                            "outputs": [
                                1
                            ],
                            "builtin_options_type": "SoftmaxOptions",
                            "builtin_options": {
                                "beta": 1.0
                            },
                            "custom_options_format": "FLEXBUFFERS"
                        },
                        {
                            "opcode_index": 0,
                            "inputs": [
                                0
                            ],
                            "outputs": [
                                2
                            ],
                            "builtin_options_type": "Pool2DOptions",
                            "builtin_options": {
                                "padding": "VALID",
                                "stride_w": 2,
                                "stride_h": 2,
                                "filter_width": 2,
                                "filter_height": 2,
                                "fused_activation_function": "NONE"
                            },
                            "custom_options_format": "FLEXBUFFERS"
                        }
                    ],
                    "name": "main"
                }
            ],
            "description": "MLIR Converted.",
            "buffers": [
                {
                },
                {
                },
                {
                },
                {
                }
            ]
        }
        )";
        Setup();
    }
};

struct LoadScopeDynamicTensor0Fixture : LoadScopeDynamicTensorFixture
{
    LoadScopeDynamicTensor0Fixture() : LoadScopeDynamicTensorFixture("[ 1, 2, 3, 2 ]", "[]", "[]") {}
};

struct LoadScopeDynamicTensor1Fixture : LoadScopeDynamicTensorFixture
{
    LoadScopeDynamicTensor1Fixture() : LoadScopeDynamicTensorFixture("[ 1, 2, 4, 1 ]", "[ 1, 1, 2, 1 ]", "[]") {}
};

struct LoadScopeDynamicTensor2Fixture : LoadScopeDynamicTensorFixture
{
    LoadScopeDynamicTensor2Fixture() : LoadScopeDynamicTensorFixture("[ 1, 3, 3, 2 ]", "[ ]", "[ 1, 1, 1, 2 ]") {}
};

BOOST_FIXTURE_TEST_CASE(LoadScopeDynamicTensor0, LoadScopeDynamicTensor0Fixture)
{
    RunTest<4, armnn::DataType::Float32, armnn::DataType::Float32>(
        0,
        { {"input0", { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f }} },
        { {"output", { 0.26894143f, 0.7310586f }} },
        true);
}

BOOST_FIXTURE_TEST_CASE(LoadScopeDynamicTensor1, LoadScopeDynamicTensor1Fixture)
{
    RunTest<4, armnn::DataType::Float32, armnn::DataType::Float32>(
        0,
        { {"input0", { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f }} },
        { {"output", { 1.f, 1.f }} },
        true);
}

BOOST_FIXTURE_TEST_CASE(LoadScopeDynamicTensor2, LoadScopeDynamicTensor2Fixture)
{
  RunTest<4, armnn::DataType::Float32, armnn::DataType::Float32>(
        0,
        { {"input0", { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f }} },
        { {"output", { 0.7772999f, 0.22270015f }} },
        true);
}

struct LoadScopeDynamicTensorBroadcastingFixture : public ParserFlatbuffersFixture
{
    explicit LoadScopeDynamicTensorBroadcastingFixture(const std::string& inputShape0,
                                                       const std::string& inputShape1,
                                                       const std::string& inputShape2,
                                                       const std::string& addShape,
                                                       const std::string& outputShape)
    {
        m_JsonString = R"(
        {
            "version": 3,
            "operator_codes": [
                {
                    "builtin_code": "ADD",
                    "version": 1
                },
                {
                    "builtin_code": "SUB",
                    "version": 1
                }
            ],
            "subgraphs": [
                {
                    "tensors": [
                        {
                            "shape": )" + inputShape0 + R"(,
                            "type": "FLOAT32",
                            "buffer": 1,
                            "name": "input0",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },
                        {
                            "shape": )" + inputShape1 + R"(,
                            "type": "FLOAT32",
                            "buffer": 2,
                            "name": "input1",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },
                        {
                            "shape": )" + outputShape + R"(,
                            "type": "FLOAT32",
                            "buffer": 5,
                            "name": "output",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },

                        {
                            "shape": )" + addShape + R"(,
                            "type": "FLOAT32",
                            "buffer": 4,
                            "name": "model/add/add",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },
                        {
                            "shape": )" + inputShape2 + R"(,
                            "type": "FLOAT32",
                            "buffer": 3,
                            "name": "input2",
                            "quantization": {
                                "details_type": 0,
                                "quantized_dimension": 0
                            },
                            "is_variable": false
                        },
                    ],
                    "inputs": [
                        0,
                        1,
                        4
                    ],
                    "outputs": [
                        2
                    ],
                    "operators": [
                        {
                            "opcode_index": 0,
                            "inputs": [
                                0,
                                1
                            ],
                            "outputs": [
                                3
                            ],
                            "builtin_options_type": "AddOptions",
                            "builtin_options": {
                                "fused_activation_function": "NONE"
                            },
                            "custom_options_format": "FLEXBUFFERS"
                        },
                        {
                            "opcode_index": 1,
                            "inputs": [
                                3,
                                4
                            ],
                            "outputs": [
                                2
                            ],
                            "builtin_options_type": "SubOptions",
                            "builtin_options": {
                                "fused_activation_function": "NONE"
                            },
                            "custom_options_format": "FLEXBUFFERS"
                        }
                    ],
                    "name": "main"
                }
            ],
            "buffers": [
                {
                },
                {
                },
                {
                },
                {
                },
                {
                },
                {
                }
            ]
        }
        )";
        Setup();
    }
};

struct LoadScopeDynamicTensorBroadcasting3DFixture : LoadScopeDynamicTensorBroadcastingFixture
{
    LoadScopeDynamicTensorBroadcasting3DFixture() : LoadScopeDynamicTensorBroadcastingFixture("[ 1, 2, 3, 2 ]",
                                                                                "[ 2, 3, 2 ]",
                                                                                "[ 2, 3, 2 ]",
                                                                                "[ 1, 2, 3, 2 ]", "[]") {}
};

struct LoadScopeDynamicTensorBroadcasting2DFixture : LoadScopeDynamicTensorBroadcastingFixture
{
    LoadScopeDynamicTensorBroadcasting2DFixture() : LoadScopeDynamicTensorBroadcastingFixture("[ 1, 2, 3, 2 ]",
                                                                                "[ 3, 2 ]",
                                                                                "[ 3, 2 ]",
                                                                                "[]", "[]") {}
};

struct LoadScopeDynamicTensorBroadcasting1DFixture : LoadScopeDynamicTensorBroadcastingFixture
{
    LoadScopeDynamicTensorBroadcasting1DFixture() : LoadScopeDynamicTensorBroadcastingFixture("[ 1, 2, 3, 2 ]",
                                                                                "[ 1 ]",
                                                                                "[ 1 ]",
                                                                                "[]",
                                                                                "[ 1, 2, 3, 2 ]") {}
};

BOOST_FIXTURE_TEST_CASE(LoadScopeDynamicTensorBroadcasting3D, LoadScopeDynamicTensorBroadcasting3DFixture)
{
    RunTest<4, armnn::DataType::Float32, armnn::DataType::Float32>(
        0,
        { {"input0", { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f }},
          {"input1", { 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f }},
          {"input2", { 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f }}
        },
        { {"output", { 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f }} },
        true);
}

BOOST_FIXTURE_TEST_CASE(LoadScopeDynamicTensorBroadcasting2D, LoadScopeDynamicTensorBroadcasting2DFixture)
{
    RunTest<4, armnn::DataType::Float32, armnn::DataType::Float32>(
        0,
        { {"input0", { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f }},
          {"input1", { 3.f, 4.f, 5.f, 6.f, 7.f, 8.f }},
          {"input2", { -1.f, -2.f, 3.f, 4.f, 5.f, 6.f }}
        },
        { {"output", { 4.f, 7.f, 4.f, 5.f, 6.f, 7.f, 10.f, 13.f, 10.f, 11.f, 12.f, 13.f }} },
        true);
}

BOOST_FIXTURE_TEST_CASE(LoadScopeDynamicTensorBroadcasting1D, LoadScopeDynamicTensorBroadcasting1DFixture)
{
    RunTest<4, armnn::DataType::Float32, armnn::DataType::Float32>(
        0,
        { {"input0", { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f }},
          {"input1", { 5.f }},
          {"input2", { 1.f }}
        },
        { {"output", { 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f }} },
        true);
}

BOOST_AUTO_TEST_SUITE_END()


text:
//  Copyright (c) 2008, 2009 João Abecasis
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <saga/saga/adaptors/utils/is_local_address.hpp>

#include <boost/assert.hpp>

#include <iostream>
#include <string>

bool test_address(std::string const & addr)
{
    using saga::adaptors::utils::is_local_address;

    bool is_alias;

    std::cout << " * " << addr << ((is_alias = is_local_address(addr))
            ? ": resolves to localhost.\n"
            : ": does NOT resolve to localhost.\n");

    return is_alias;
}

int main(int argc, char ** argv)
{
    if (argc >= 2)
        for (int i = 1; i < argc; ++i)
            test_address(argv[i]);
    else
    {
        std::cout << "No arguments specified. Entering self-test mode.\n"
            "  Usage: " << argv[0] << " [list of addresses]\n\n"
            << std::flush;

        BOOST_ASSERT(test_address("localhost"));
        BOOST_ASSERT(test_address("127.0.0.1"));

        BOOST_ASSERT(!test_address("example.com"));
    }
}

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
// Copyright (C) 2013 Vicente J. Botet Escriba
//
//  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)
//
// 2013/09 Vicente J. Botet Escriba
//    Adapt to boost from CCIA C++11 implementation
//    first implementation of a simple pool thread using a vector of threads and a sync_queue.

#ifndef BOOST_THREAD_THREAD_POOL_HPP
#define BOOST_THREAD_THREAD_POOL_HPP

#include <boost/thread/executors/basic_thread_pool.hpp>

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#pragma once

#include "../Colour/colour.hh"
#include "../geometry/LineSegment/LineSegment2/linesegment2.hh"
#include "../geometry/Polygon2.hh"

#include <memory>
#include <vector>
#include <Eigen/Core>

namespace bold
{
  enum class DrawingItemType
  {
    Line = 1,
    Circle = 2,
    Polygon = 3,
  };

  enum class Frame
  {
    Camera = 1,
    Agent = 2,
    World = 3
  };

  struct DrawingItem
  {
    Frame frame;
    DrawingItemType type;
  };

  struct LineDrawing : public DrawingItem
  {
    Eigen::Vector2d p1;
    Eigen::Vector2d p2;
    Colour::bgr colour;
    double lineWidth;
    double alpha;
  };

  struct CircleDrawing : public DrawingItem
  {
    Eigen::Vector2d centre;
    double radius;
    Colour::bgr fillColour;
    Colour::bgr strokeColour;
    double fillAlpha;
    double strokeAlpha;
    double lineWidth;
  };

  struct PolygonDrawing : public DrawingItem
  {
    PolygonDrawing(Polygon2d const& polygon)
      : polygon(polygon)
    {}

    Polygon2d polygon;
    Colour::bgr fillColour;
    Colour::bgr strokeColour;
    double fillAlpha;
    double strokeAlpha;
    double lineWidth;
  };

  class Draw
  {
  public:
    static void initialise();

    static void circle(Frame frame, Eigen::Vector2d const& centre, double radius, Colour::bgr const& colour, double alpha = 1.0, double lineWidth = 1.0);
    static void fillCircle(Frame frame, Eigen::Vector2d const& centre, double radius, Colour::bgr const& fillColour, double fillAlpha, Colour::bgr const& strokeColour, double strokeAlpha, double lineWidth = 1.0);

    static void polygon(Frame frame, Polygon2d const& polygon, Colour::bgr const& strokeColour, double strokeAlpha, double lineWidth = 1.0);
    static void fillPolygon(Frame frame, Polygon2d const& polygon, Colour::bgr const& fillColour, double fillAlpha, Colour::bgr const& strokeColour, double strokeAlpha, double lineWidth = 1.0);

    static void line(Frame frame, Eigen::Vector2d const& p1, Eigen::Vector2d const& p2, Colour::bgr const& colour, double alpha = 1.0, double lineWidth = 1.0);
    static void line(Frame frame, LineSegment2d const& line, Colour::bgr const& colour, double alpha = 1.0, double lineWidth = 1.0);
    static void lineAtAngle(Frame frame, Eigen::Vector2d const& p1, double angle, double length, Colour::bgr const& colour, double alpha = 1.0, double lineWidth = 1.0);

    static void flushToStateObject();

  private:
    static std::unique_ptr<std::vector<std::unique_ptr<DrawingItem const>>> d_drawingItems;
  };
}

ext: hh

max_stars_repo_name: drewnoakes/bold-humanoid

max_issues_repo_name: drewnoakes/bold-humanoid

max_forks_repo_name: drewnoakes/bold-humanoid