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

#include "System.h"

#include <future>
#include <queue>
#include <thread>

using namespace omnn::math;
using namespace boost::unit_test;
using namespace std;

BOOST_AUTO_TEST_CASE(TicTacToe_X_Won_test)
{
    System ticTacToe;

    DECL_VA(i);
    ticTacToe << i.Abet({1, 2, 3});

    DECL_VA(v);
    ticTacToe << v.Equals(1); // encoded cross positions

    // The constrasint of X,Y positions to win
    DECL_VA(x);
    DECL_VA(y);
    ticTacToe << ((x.Equals(i) && y.Equals(i)) || (x.Equals(4_v - i) && y.Equals(i)));

	DECL_VA(win);
    auto winExp = (win.Equals(1) && ticTacToe.Total()) || win.Equals(0);

	struct EncodedFieldPack { // of encoded field (X only)
        bool hasXat1_1 : 1;   // bit
        bool hasXat1_2 : 1;   // bit
        bool hasXat1_3 : 1;   // bit
        bool hasXat2_1 : 1;   // bit
        bool hasXat2_2 : 1;   // bit
        bool hasXat2_3 : 1;   // bit
        bool hasXat3_1 : 1;   // bit
        bool hasXat3_2 : 1;   // bit
        bool hasXat3_3 : 1;   // bit
    };
    // Enumerating all variants and dump matched variants:
	union Variant {
        int code : 9; // bits
        EncodedFieldPack pack;
	};

    Variant fieldVariant = {};
    for (fieldVariant.code = 1 << 9; fieldVariant.code-->0; ) {

        System fieldExpression;
        fieldExpression << (x.Equals(1) && y.Equals(1) && v.Equals(fieldVariant.pack.hasXat1_1))
                        << (x.Equals(1) && y.Equals(2) && v.Equals(fieldVariant.pack.hasXat1_2))
                        << (x.Equals(1) && y.Equals(3) && v.Equals(fieldVariant.pack.hasXat1_3))
                        << (x.Equals(2) && y.Equals(1) && v.Equals(fieldVariant.pack.hasXat1_1))
                        << (x.Equals(2) && y.Equals(2) && v.Equals(fieldVariant.pack.hasXat1_2))
                        << (x.Equals(2) && y.Equals(3) && v.Equals(fieldVariant.pack.hasXat1_3))
                        << (x.Equals(3) && y.Equals(1) && v.Equals(fieldVariant.pack.hasXat1_1))
                        << (x.Equals(3) && y.Equals(2) && v.Equals(fieldVariant.pack.hasXat1_2))
                        << (x.Equals(3) && y.Equals(3) && v.Equals(fieldVariant.pack.hasXat1_3));
        fieldExpression << winExp;

		auto winSolutions = fieldExpression.Solve(win);
        if (winSolutions.size() == 1) {
            auto it = winSolutions.begin();
            if (*it == 1) {
                std::cout
					<< "Win:" << (fieldVariant.pack.hasXat1_1 ? 'X' : '0') << (fieldVariant.pack.hasXat1_2 ? 'X' : '0') << (fieldVariant.pack.hasXat1_3 ? 'X' : '0') << std::endl
					<< "    " << (fieldVariant.pack.hasXat2_1 ? 'X' : '0') << (fieldVariant.pack.hasXat2_2 ? 'X' : '0') << (fieldVariant.pack.hasXat2_3 ? 'X' : '0') << std::endl
					<< "    " << (fieldVariant.pack.hasXat3_1 ? 'X' : '0') << (fieldVariant.pack.hasXat3_2 ? 'X' : '0') << (fieldVariant.pack.hasXat3_3 ? 'X' : '0') << std::endl;
            }
        } else {
            for (auto& s : winSolutions) {
                std::cout << s << std::endl;
			}
		}
	}
}

max_stars_repo_name: ApusDT/openmind

max_issues_repo_name: ApusDT/openmind

max_forks_repo_name: ApusDT/openmind


text:
#include <vector>
#include <string>

#include "util.hpp"

#include <rw/math/Random.hpp>
#include <rwlibs/task/GraspTask.hpp>

#include <boost/program_options/parsers.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>

using namespace std;
using namespace rw::math;
using namespace rwlibs::algorithms;
using namespace rwlibs::task;
using namespace boost::filesystem;
using namespace boost::program_options;

variables_map init(int argc, char** argv){
    options_description desc("Allowed options");
    desc.add_options()
        ("help", "This script filters a grasp list by iteratively selecting the best grasp "
                 "and removing all neighboring grasps within a 6D cube arounf the selected "
                 "grasp. The 6D cube is defined by angle and dist arguments.")
        ("output,o", value<string>()->default_value("out.xml"), "the output file.")
        ("angle", value<double>()->default_value(30.0), "Angle of cone in degree.")
        ("dist", value<double>()->default_value(0.01), "Dist of square in meters.")
        ("samples", value<int>()->default_value(500), "Number of grasps to sample.")
        ("input", value<string>(), "The input grasp task file that should be filtered.")
    ;
    positional_options_description optionDesc;
    optionDesc.add("input",-1);

    variables_map vm;
    //store(parse_command_line(argc, argv, desc), vm);
    store(command_line_parser(argc, argv).
              options(desc).positional(optionDesc).run(), vm);
    notify(vm);

    // write standard welcome, status
    if (vm.count("help")) {
        cout << "Usage:\n\n"
                  << "\t" << argv[0] <<" [options] -o<outfile> <expFile1> <expFile2> <...> <expFileN> \n"
                  << "\n";
        cout << desc << "\n";
        abort();
    }

    return vm;
}

int main_jaj(int argc, char** argv);
int main_lpe(int argc, char** argv);

int main(int argc, char** argv){
    //return main_jaj(argc,argv);
    return main_lpe(argc,argv);
}

/**
 * We need to choose a number of grasps
 */
int main_lpe(int argc, char** argv)
{
	static const unsigned int SEED = static_cast<unsigned int>(time(NULL));
	Random::seed(SEED);
	srand(SEED);
    variables_map vm = init(argc, argv);

    std::string grasptask_file_out = vm["output"].as<std::string>();
    double angleThres = vm["angle"].as<double>()*Deg2Rad;
    double distThres = vm["dist"].as<double>();
    std::string input = vm["input"].as<string>();
    std::string output = vm["output"].as<string>();
    //Unused: int count = vm["samples"].as<int>();
    GraspTask::Ptr gtask = GraspTask::load( input );

    if( boost::filesystem::exists(output) ){
        std::cout << "Output allready exists! skipping filtering." << std::endl;
        return 0;
    }

    // first we build a search tree to efficiently search for targets in 6d
    std::vector<GTaskNNSearch::Node*> simnodes;
    std::cout << "Building tree!" << std::endl;
    GTaskNNSearch *nntree = buildKDTree_pos_eaa(gtask, simnodes);
    std::cout << "sim nodes:"  << simnodes.size() << std::endl;

    Q diff(7, distThres, distThres, distThres, angleThres, angleThres, angleThres,angleThres);
    std::cout << diff << std::endl;
    typedef std::pair<GraspSubTask*, GraspTarget*> Value;
    std::vector< Value > selGrasps;
    std::list<const GTaskNNSearch::Node*> result;

    for(std::size_t i=0;i<simnodes.size(); i++){
        if(simnodes[i]->value.second == NULL)
            continue;
        // find the node with the highest quality
        double q_max = -100;
        GTaskNNSearch::Node *n_max = simnodes[0];

        // TODO: use a priority queue instead of this brute search
        int idx = 0;
        for(GTaskNNSearch::Node* nptr : simnodes) {
            GTaskNNSearch::Node& n = *nptr;
            idx++;
            GTaskNNSearch::Value &val = n.value;
            if(val.second==NULL){
                continue;
            }
            if(val.second->result==NULL)
                continue;
            Q qual = val.second->getResult()->qualityAfterLifting;
            if(qual.size()==0)
                qual = val.second->getResult()->qualityBeforeLifting;

            if(qual.size()==0)
                continue;
            if(q_max<qual[0]){
                //std::cout << "found higher:" << qual[0] << " idx: " << idx << std::endl;
                q_max = qual[0];
                n_max = &n;
            }
        }
        // just to make sure we found a node above....
        if(q_max<-90)
            break;
        // we stop the sampling at a certain threshold 30% success
        //if(q_max<0.3)
        //    break;

        // add the max node
        GTaskNNSearch::Value &v = n_max->value;
        selGrasps.push_back( v );
        v.second = NULL;

        // use the max node as a sample point and remove all neighboring nodes
        result.clear();
        nntree->nnSearchRect( n_max->key-diff, n_max->key+diff, result);
        //std::cout << "s:" << result.size() << "\n";
        for(const GTaskNNSearch::Node* res_n : result) {
            nntree->removeNode( res_n->key );
            GTaskNNSearch::Node* r_n = (GTaskNNSearch::Node*) res_n;
            r_n->value.second = NULL;
        }
    }
    std::cout << "GENRATED: "<< selGrasps.size() << " from " << simnodes.size() << std::endl;

    // convert selectGrasps to a graspTask
    GraspTask res = *gtask;
    res.getSubTasks().clear();
    for(Value& taskpair : selGrasps) {
        GraspSubTask stask = *taskpair.first;
        stask.targets.clear();
        stask.targets.push_back( *taskpair.second );
        res.addSubTask(stask);
    }

    GraspTask::saveRWTask(&res, output);
    //std::cout << "COVERAGE: " << (((double)samples_t)/(double)samples_f)*100.0 << "%" << std::endl;
    return 0;
}

/**
 * We need to choose a number of grasps
 */
int main_jaj(int argc, char** argv)
{
	static const unsigned int SEED = static_cast<unsigned int>(time(NULL));
	Random::seed(SEED);
	srand(SEED);
    variables_map vm = init(argc, argv);

	std::string grasptask_file_out = vm["output"].as<std::string>();
	double angleThres = vm["angle"].as<double>()*Deg2Rad;
    std::string input = vm["input"].as<string>();
    std::string output = vm["output"].as<string>();
    int count = vm["samples"].as<int>();
	GraspTask::Ptr gtask = GraspTask::load( input );

	// first we build a search tree to efficiently search for targets orientet in a certain direction
	GTaskNNSearch *nntree_normal = buildKDTree_eaa(gtask);

	// now we sample the normals with random orientations
	Q diff(4, angleThres, angleThres, angleThres, angleThres);
	typedef std::pair<GraspSubTask*, GraspTarget*> Value;

	std::vector< Value > selGrasps;
	std::list<const GTaskNNSearch::Node*> result;
	int samples_f = 0, samples_t = 0;
	while((int)selGrasps.size()<count){
        result.clear();
        EAA<> eaa( Math::ranRotation3D<double>() );
        //Vector3D<> k = Math::ranRotation3D<double>()*Vector3D<>::z();
        Vector3D<> k = eaa.axis();
        Q key(3, k[0], k[1], k[2], eaa.angle());
        nntree_normal->nnSearchRect(key-diff,key+diff, result);
        samples_f++;
        if(result.size()==0)
            continue;
        samples_t++;
        int idx = Random::ranI(0,boost::numeric_cast<int>(result.size()));
        if(idx == (int)result.size())
            idx--;
        std::list<const GTaskNNSearch::Node*>::iterator i = result.begin();
        //std::cout << idx << "==" <<  result.size() << std::endl;
        if(idx>0)
            std::advance(i, idx);
        const GTaskNNSearch::Node* node = *i;
        Value v = node->value;
        selGrasps.push_back( v );
        std::cout << result.size() << "    \r" << std::flush;
	}
	// print all failures

	// convert selectGrasps to a graspTask
	GraspTask res = *gtask;
	res.getSubTasks().clear();
	for(Value& taskpair : selGrasps) {
	    GraspSubTask stask = *taskpair.first;
	    stask.targets.clear();
	    stask.targets.push_back( *taskpair.second );
	    res.addSubTask(stask);
	}

	GraspTask::saveRWTask(&res, output + ".rwtask.xml");
	std::cout << "COVERAGE: " << (((double)samples_t)/(double)samples_f)*100.0 << "%" << std::endl;
	return 0;
}

ext: cpp


text:
#ifndef KOOPMAN_OPERATOR_HPP
#define KOOPMAN_OPERATOR_HPP

#include <armadillo>
#include "../system.hpp"
#include "basis_functions/basis_template.hpp"
#include <math.h>

class KoopmanOperator : public System
{

private:
    arma::mat _A;
    arma::mat _G;
    arma::mat _Ktrans;
public:
    arma::mat _K;
    arma::mat _Kx;
    arma::mat _Ku;

    int _nK;
    int _nM;
    int _nX;
    int _nU;
    int _nKU;

    Basis* basis;

    KoopmanOperator(Basis* _basis) : System(_basis->_nX, _basis->_nU) {
        basis = _basis;
        _nK = basis->_nK;
        _nX = basis->_nX;
        _nU = basis->_nU;
        _nM = basis->_nM;
        _nKU = basis->_nKU;
        _A = arma::zeros<arma::mat>(_nK, _nK);
        _G = arma::zeros<arma::mat>(_nK, _nK);
        _K = arma::zeros<arma::mat>(_nK, _nK);
        _Kx = 0.1*arma::ones<arma::mat>(_nX, _nX);
        _Ku = 0.1*arma::ones<arma::mat>(_nX, _nKU);

        _Ktrans = _K.t();
    }

    inline arma::vec f(const arma::vec& x, const arma::vec& u) {
        if (x.n_rows < _nX) {
            return _Kx * basis->fkx(x) + _Ku * basis->fku(x, u);
        } else {
            arma::vec fkx = basis->fkx(x.head_rows(_nM));
            arma::vec fku = basis->fku(x.head_rows(_nM), u);
            return _Kx * fkx + _Ku * fku;
        }
    }

    inline arma::mat fdx(const arma::vec& x, const arma::vec& u) {
        return _Kx;
    }
    inline arma::mat fdu(const arma::vec& x, const arma::vec& u) {
        return _Ku * basis->fkudu(x.head_rows(_nM), u);
    }

    void gradStep(const arma::vec& dataIn, const arma::vec& hdataIn, const arma::vec& dataOut, const arma::vec& hdataOut) {

        arma::vec phix = basis->fk(dataIn, hdataIn);
        arma::vec phixpo = basis->fk(dataOut, hdataOut);

        _G += phix * phix.t();
        _A += phix * phixpo.t();

        try {
            _K = arma::pinv(_G) * _A;
            _Ktrans = _K.t();
            _Kx = _Ktrans.submat(0, 0, _nX-1, _nX-1);
            _Ku = _Ktrans.submat(0, _nX, _nX-1, _nX + _nKU - 1);
        } catch (std::runtime_error& e) {
            std::cout << "CAUGHT ERROR" << std::endl;
        }

    }

    void computeOperator() {
      try {
            _K = arma::pinv(_G) * _A;
            _Ktrans = _K.t();
            _Kx = _Ktrans.submat(0, 0, _nX-1, _nX-1);
            _Ku = _Ktrans.submat(0, _nX, _nX-1, _nX + _nKU - 1);
        } catch (std::runtime_error& e) {
            std::cout << "CAUGHT ERROR" << std::endl;
        }
    }

    void saveOperator(std::string filePath) {
      _Ktrans.save(filePath + ".csv", arma::raw_ascii);
      _Ktrans.save(filePath + ".bin");
    }

    void loadOperator(std::string filePath) {
      _Ktrans.load(filePath);
      _K = _Ktrans.t();
      _Kx = _Ktrans.submat(0, 0 ,_nX-1, _nX-1);
      _Ku = _Ktrans.submat(0, _nX, _nX-1, _nX + _nKU-1);
      std::cout << "Loaded Koopman Operator." << std::endl;
    }

    void showOperator() {
        std::cout << _K.t() << std::endl;
    }
};

#endif

ext: hpp


text:
/*******************************************************************************
 * Copyright (c) 2014, 2015  IBM Corporation and others
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *******************************************************************************/

#include <iostream>
#include <string>
#include <algorithm>
#include <regex>

#include "Location.hpp"
#include "Beacon.hpp"
#include "BLEBeacon.hpp"
#include "Attitude.hpp"
#include "Acceleration.hpp"

#include "DataUtils.hpp"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/algorithm/string/replace.hpp>

//http://stackoverflow.com/questions/10521581/base64-encode-using-boost-throw-exception
using namespace boost::archive::iterators;
typedef
transform_width< binary_from_base64<std::string::const_iterator>, 8, 6 > it_binary_t;
//

namespace loc{

    std::list<std::string> DataUtils::splitCSV(const std::string & str){
        std::list<std::string> stringList;
        std::string delim (",");
        boost::split(stringList, str, boost::is_any_of(delim));
        return stringList;
    }

    std::list<std::string> DataUtils::splitAndTrimCSV(const std::string & str){
        std::list<std::string> stringList = splitCSV(str);
        std::list<std::string>::iterator iter;
        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            boost::trim(*iter);
        }
        return stringList;
    }

    bool DataUtils::csvCheckSensorType(const std::string& str, const std::string& type){
        std::list<std::string> stringList = splitAndTrimCSV(str);
        std::list<std::string>::iterator iter;
        int i=0;
        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            //std::cout << *iter << std::endl;
            if(i==1){
                if(iter->compare(type)==0){
                    return true;
                }
            }
            i++;
        }
        return false;
    }

    bool DataUtils::csvCheckAcceleration(const std::string& str){
        return csvCheckSensorType(str, "Acc");
    }

    bool DataUtils::csvCheckAttitude(const std::string& str){
        return csvCheckSensorType(str, "Motion");
    }

    bool DataUtils::csvCheckBeacons(const std::string& str){
        return csvCheckSensorType(str, "Beacon");
    }

    template<class T> T DataUtils::parseCSVSensorData(const std::string& str){
        std::list<std::string> stringList = splitAndTrimCSV(str);
        std::list<std::string>::iterator iter;
        int i=0;
        long timestamp=0L;
        double x=0 , y=0, z=0;

        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            //std::cout << *iter << std::endl;
            if(i==0) timestamp = std::stol(*iter);
            if(i==2) x = std::stod(*iter);
            if(i==3) y = std::stod(*iter);
            if(i==4) z = std::stod(*iter);
            i++;
        }

        T data(timestamp, x, y, z);
        return data;
    }

    template Acceleration DataUtils::parseCSVSensorData<Acceleration>(const std::string& str);
    template Attitude DataUtils::parseCSVSensorData<Attitude>(const std::string& str);

    Acceleration DataUtils::parseAccelerationCSV(const std::string& str){
        return parseCSVSensorData<Acceleration>(str);
    }

    Attitude DataUtils::parseAttitudeCSV(const std::string& str){
        return parseCSVSensorData<Attitude>(str);
    }

    std::string removeSpaces(const std::string& str){
        const std::string str2 = boost::algorithm::replace_all_copy(str, " ", "");
        return str2;
    }

    Beacons DataUtils::parseBeaconsCSV(const std::string& str){
        const std::string str2 = removeSpaces(str);
        Sample s = parseSampleCSV(str2);
        return s.beacons();
    }

    /*
    Beacons DataUtils::parseBeaconsCSV(const std::string& str){
        // timestamp, Beacon, x, y, height, floor, nBeacon, major, minor, rssi, ...
        Beacons beacons;

        std::list<std::string> stringList = splitAndTrimCSV(str);
        std::list<std::string>::iterator iter;
        int i=0;

        long timestamp = 0;
        int nBeacons = 0;
        int major=0;
        int minor=0;
        double rssi = -100;

        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            if(i==0) timestamp = std::stol(*iter);
            beacons.timestamp(timestamp);
            if(i==6) nBeacons = std::stoi(*iter);
            if(i>6){
                if(i%3==1) major = std::stoi(*iter);
                if(i%3==2) minor = std::stoi(*iter);
                if(i%3==0){
                    rssi = std::stod(*iter);
                    Beacon b(major, minor, rssi);
                    beacons.push_back(b);
                }
            }
            i++;
        }
        return beacons;
    }
    */

    // param (str) "uuid-major-minor"
    // return BeaconId
    BeaconId parseBeaconIdString(const std::string& str){
        std::istringstream iss(str);
        std::string newCell;
        std::vector<std::string> tokens;
        while( std::getline( iss, newCell, '-' ) ) {
            tokens.push_back(newCell);
        }

        auto n = tokens.size();
        std::string uuid;
        for(int i=0; i<n-3; i++){
            uuid += tokens[i] + "-";
        }
        uuid += tokens[n-3];

        int major = stoi(tokens.at(n-2));
        int minor = stoi(tokens.at(n-1));
        return BeaconId(uuid, major, minor);
    }

    Beacons DataUtils::parseLogBeaconsCSV(const std::string& str){
        // "Beacon",nBeacon,major,minor,rssi,....,timestamp
        // or "Beacon",nBeacon,uuid-major-minor,rssi,....,timestamp
        Beacons beacons;

        std::list<std::string> stringList = splitAndTrimCSV(str);
        std::list<std::string>::iterator iter;
        int i=0;

        long timestamp = std::stol(stringList.back());
        beacons.timestamp(timestamp);
        int nBeacons = 0;
        std::string uuid;
        int major=0;
        int minor=0;
        double rssi = -100;

        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            if(i==0){
                if(iter->compare("Beacon") != 0){
                    BOOST_THROW_EXCEPTION(LocException("Log beacon is not correctly formatted. string="+str));
                }
            }
            if(i==1) nBeacons = std::stoi(*iter);
            if(1<i){
                if( stringList.size() == 2*nBeacons + 3 ){
                    // "Beacon",nBeacon,uuid-major-minor,rssi,....,timestamp
                    if(i>1 && i-2 < 2*nBeacons){
                        if(i%2==0){
                            std::string idStr = *iter;
                            auto bId = parseBeaconIdString(idStr);
                            uuid = bId.uuid();
                            major = bId.major();
                            minor = bId.minor();
                        }
                        if(i%2==1){
                            rssi = std::stod(*iter);
                            Beacon b(uuid, major, minor, rssi);
                            beacons.push_back(b);
                        }
                    }
                }else if(stringList.size() == 3*nBeacons + 3) {
                    // "Beacon",nBeacon,major,minor,rssi,....,timestamp
                    if(i>1 && i-2 < 3*nBeacons){
                        if(i%3==2) major = std::stoi(*iter);
                        if(i%3==0) minor = std::stoi(*iter);
                        if(i%3==1){
                            rssi = std::stod(*iter);
                            Beacon b(major, minor, rssi);
                            beacons.push_back(b);
                        }
                    }
                }
            }
            i++;
        }
        return beacons;
    }

    Beacon DataUtils::jsonBeaconObjectToBeacon(picojson::object& jsonObject){
        double majorDouble = jsonObject["major"].get<double>();
        double minorDouble = jsonObject["minor"].get<double>();
        double rssi = jsonObject["rssi"].get<double>();
        if (rssi == 0) { rssi = -100; }
        Beacon beacon(majorDouble, minorDouble, rssi );
        return beacon;
    }

    Beacons DataUtils::jsonBeaconsObjectToBeacons(picojson::object& beaconsObj){
        Beacons beacons;

        std::string uuid = beaconsObj["uuid"].get<std::string>();
        double timestampDouble = beaconsObj["timestamp"].get<double>();
        long timestamp = timestampDouble;
        beacons.timestamp(timestamp);

        picojson::array dataArray = beaconsObj["data"].get<picojson::array>();
        for(picojson::array::iterator iter_data=dataArray.begin() ; iter_data!=dataArray.end() ; iter_data++){
            picojson::object beaconObj = iter_data->get<picojson::object>();
            Beacon b = jsonBeaconObjectToBeacon(beaconObj);
            beacons.push_back(b);
        }
        return beacons;
    }

    Location DataUtils::jsonInformationObjectToLocation(picojson::object& informationObject){
        double x = informationObject["absx"].get<double>();
        double y = informationObject["absy"].get<double>();
        double z = informationObject["z"].get<double>();
        double floor = informationObject["floor_num"].get<double>();
        Location location(x,y,z,floor);
        return location;
    }

    Samples DataUtils::jsonSamplesArrayToSamples(picojson::array& array){
        Samples samples;
        for(picojson::array::iterator iter=array.begin(); iter!=array.end(); iter++){
            picojson::object obj = iter->get<picojson::object>();
            picojson::object info = obj["information"].get<picojson::object>();

            loc::Location location = jsonInformationObjectToLocation(info);

            picojson::array beaconsArray = obj["beacons"].get<picojson::array>();
            for(picojson::array::iterator itb = beaconsArray.begin(); itb!=beaconsArray.end(); itb++){
                picojson::object beaconsObj = itb->get<picojson::object>();
                loc::Beacons beacons = jsonBeaconsObjectToBeacons(beaconsObj);

                Sample sample;
                sample.timestamp(beacons.timestamp())->beacons(beacons)->location(location);

                samples.push_back(sample);
            }
        }
        return samples;
    }

    Samples DataUtils::jsonSamplesStringToSamples(const std::string& str){
        picojson::value value;
        std::string err = picojson::parse(value, str);
        picojson::array& array = value.get<picojson::array>();
        return jsonSamplesArrayToSamples(array);
    }

    std::string DataUtils::fileToString(const std::string& filePath){
        std::ifstream ifs(filePath);

        if(! ifs.is_open()){
            std::cout << filePath << " is not open." << std::endl;
        }
        std::string str;
        std::stringstream stringstream;
        std::string strBuffer;
        while(std::getline(ifs, strBuffer)){
            stringstream << strBuffer;
        }
        return stringstream.str();
    }

    std::string DataUtils::stringToFile(const std::string& dataStr, const std::string& dir, const std::string& file)
    {

        std::string tempPath = dir+"/"+file;
        if (file.empty()) {
            boost::uuids::random_generator gen;
            boost::uuids::uuid u = gen();
            tempPath = dir+"/"+boost::uuids::to_string(u);
        }

        std::regex regex( "^(data:([a-z]+/[a-z]+);base64,).+$" );
        std::smatch match;

        std::string type;
        std::string data;
        std::string prefix = dataStr.substr(0,50);
        if( regex_match(prefix, match, regex) ) {
            type = match[2];
            type = std::regex_replace( type, std::regex("^[^/]+/(x-)?"), "" );
            long begin = match[1].length();

            tempPath += "."+type;
            std::ofstream ofs(tempPath);

            unsigned long paddChars = count(dataStr.end()-10, dataStr.end(), '=');
            //std::replace(data.begin(),data.end(),'=','A');
            copy(it_binary_t(dataStr.begin()+begin), it_binary_t(dataStr.end()-paddChars), std::ostream_iterator<char>(ofs));

        } else {
            tempPath += ".txt";
            std::ofstream ofs(tempPath);
            //copy(dataStr.begin(), dataStr.end(), std::ostream_iterator<char>(ofs));
            ofs << dataStr;
            ofs.close();
        }

        return tempPath;
    }

    Location DataUtils::parseLocationCSV(const std::string& csvLine){

        std::list<std::string> stringList = splitAndTrimCSV(csvLine);
        std::list<std::string>::iterator iter;

        // timestamp, type, x, y, height ,floor(z), #beacons, major, minor, rssi ,...
        std::vector<std::string> stringVector;
        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            stringVector.push_back(*iter);
        }
        double x = std::stod(stringVector.at(2));
        double y = std::stod(stringVector.at(3));
        double z = std::stod(stringVector.at(4));
        double floor = std::stod(stringVector.at(5));

        Location location(x,y,z,floor);
        return location;
    }
    Sample DataUtils::parseSampleCSV(const std::string& csvLine) throw(std::invalid_argument) {
        return DataUtils::parseSampleCSV(csvLine, false);
    }
    Sample DataUtils::parseSampleCSV(const std::string& csvLine, bool noBeacons) throw(std::invalid_argument) {
        // timestamp,"Beacon",x,y,z,floor,N,uuid1-major1-minor1,rssi1,...,uuidN-majorN-minorN,rssiN
        // or
        // timestamp,"Beacon",x,y,z,floor,N,major1,minor1,rssi1,...,majorN,minorN,rssiN
        const char *buffer = csvLine.c_str();
        long timestamp;
        double x, y, z, floor;
        int num, n = 0;
        sscanf(buffer, "%ld,Beacon,%lf,%lf,%lf,%lf,%d,%n", &timestamp, &x, &y, &z, &floor, &num, &n);

        if(n==0){
            throw std::invalid_argument("Invalid csv line was found.");
        }

        buffer += n;
        Location location(x,y,z,floor);
        Sample sample;
        sample.location(location)->timestamp(timestamp);

        if (!noBeacons) {
            int major, minor;
            double rssi;
            Beacons beacons;
            beacons.timestamp(timestamp);

            std::istringstream iss(buffer);
            std::string newCell;
            std::vector<std::string> csvTokens;
            while( std::getline( iss, newCell, ',' ) ) {
                csvTokens.push_back(newCell);
            }
            if(csvTokens.size() == 2*num ){ // "uuid-major-minor,rssi" format
                for(int i=0; i<num; i++){
                    auto beaconId = parseBeaconIdString(csvTokens[2*i]);
                    rssi = stod(csvTokens[2*i+1]);
                    Beacon b(beaconId, rssi);
                    beacons.push_back(b);
                }
            }else if(csvTokens.size() == 3*num ){ // "major,minor,rssi" format
                for(int i = 0; i < num; i++) {
                    sscanf(buffer, "%d,%d,%lf,%n", &major, &minor, &rssi, &n);
                    buffer += n;
                    beacons.push_back(Beacon(major, minor, rssi));
                }
            }else{
                throw std::invalid_argument("Invalid csv line was found.");
            }
            sample.beacons(beacons);
        }
        return sample;
    }

    void DataUtils::csvLocationsToLocations(std::istream& istream, Locations &locations){
        std::string strBuffer;
        while(std::getline(istream, strBuffer)){
            try{
                Location loc = parseLocationCSV(strBuffer);
                locations.push_back(loc);
            } catch (std::invalid_argument e){
                std::cout << "Invalid csv line was found. line=" <<strBuffer << std::endl;
            }
        }
    }

    void DataUtils::csvSamplesToSamples(std::istream& istream, Samples &samples){
        DataUtils::csvSamplesToSamples(istream, samples, false);
    }

    void DataUtils::csvSamplesToSamples(std::istream& istream, Samples &samples, bool noBeacons){
        std::string strBuffer;
        while(std::getline(istream, strBuffer)){
            try{
                Sample sample = parseSampleCSV(strBuffer, noBeacons);
                samples.push_back(sample);
            } catch (std::invalid_argument e){
                std::cout << "Invalid csv line was found. line=" <<strBuffer << std::endl;
                //std::cout << "Header line is found in csv samples." << std::endl;
            }
        }
    }

    Samples DataUtils::csvSamplesToSamples(std::istream& istream){
        return DataUtils::csvSamplesToSamples(istream, false);
    }

    Samples DataUtils::csvSamplesToSamples(std::istream& istream, bool noBeacons){
        Samples samples;
        std::string strBuffer;
        while(std::getline(istream, strBuffer)){
            try{
                Sample sample = parseSampleCSV(strBuffer, noBeacons);
                samples.push_back(sample);
            } catch (std::invalid_argument e){
                std::cout << "Invalid csv line was found. line=" <<strBuffer << std::endl;
            }
        }
        if(samples.size()==0){
            std::cout << "Samples CSV was not found." << std::endl;
        }
        return std::move(samples);
    }

    Sample DataUtils::parseShortSampleCSV(const std::string& csvLine) throw(std::invalid_argument) {
        //Location location = parseLocationCSV(csvLine);
        //Beacons beacons = parseBeaconsCSV(csvLine);

        const char *buffer = csvLine.c_str();
        long timestamp = 0;
        double x, y, z = 0, floor = 0;
        int num, n = 0;
        sscanf(buffer, "%lf,%lf,%d,%n", &x, &y, &num, &n);

        if(n==0){
            throw std::invalid_argument("Invalid csv line was found.");
        }

        buffer += n;
        Location location(x,y,z,floor);

        int major, minor;
        double rssi;
        Beacons beacons;
        beacons.timestamp(timestamp);
        for(int i = 0; i < num; i++) {
            sscanf(buffer, "%d,%d,%lf,%n", &major, &minor, &rssi, &n);
            buffer += n;
            beacons.push_back(Beacon(major, minor, rssi));
        }

        Sample sample;
        sample.timestamp(timestamp)->location(location)->beacons(beacons);
        return sample;
    }

    void DataUtils::shortCsvSamplesToSamples(std::istream& istream, Samples &samples){
        std::string strBuffer;
        while(std::getline(istream, strBuffer)){
            try{
                Sample sample = parseShortSampleCSV(strBuffer);
                samples.push_back(sample);
            } catch (std::invalid_argument e){
                std::cout << "Invalid short csv line was found. line=" <<strBuffer << std::endl;
                //std::cout << "Header line is found in csv samples." << std::endl;
            }
        }
    }

    Samples DataUtils::shortCsvSamplesToSamples(std::istream& istream){
        Samples samples;
        std::string strBuffer;
        while(std::getline(istream, strBuffer)){
            try{
                Sample sample = parseShortSampleCSV(strBuffer);
                samples.push_back(sample);
            } catch (std::invalid_argument e){
                std::cout << "Invalid short csv line was found. line=" <<strBuffer << std::endl;
            }
        }
        if(samples.size()==0){
            std::cout << "Samples CSV was not found." << std::endl;
        }
        return samples;
    }

    std::string DataUtils::samplesToCsvSamples(const Samples &samples){
        // csv format of sample
        // timestamp,"Beacon",x,y,z,floor,#beacons,major,minor,rssi,...
        std::stringstream ss;
        for(auto& s: samples){
            auto ts = s.timestamp();
            auto loc = s.location();
            auto bs = s.beacons();
            ss << ts <<",Beacon," << loc << "," << bs.size();
            for(auto& b: bs){
                ss << ",";
                ss << b;
            }
            ss << std::endl;
        }
        return ss.str();
    }

    BLEBeacon DataUtils::parseBLEBeaconCSV(const std::string& csvLine) throw(...){
        // csv format of BLEBeacon
        // uuid, major, minor, x, y, z, floor
        std::list<std::string> stringList = splitAndTrimCSV(csvLine);
        std::list<std::string>::iterator iter;
        std::vector<std::string> stringVector;
        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            stringVector.push_back(*iter);
        }

        std::string uuid = stringVector.at(0);
        int major = std::stoi(stringVector.at(1));
        int minor = std::stoi(stringVector.at(2));

        double x = std::stod(stringVector.at(3));
        double y = std::stod(stringVector.at(4));
        double z = std::stod(stringVector.at(5));
        double floor = std::stod(stringVector.at(6));

        BLEBeacon bleBeacon(uuid, major, minor, x, y, z, floor);
        return bleBeacon;

    }

    BLEBeacons DataUtils::csvBLEBeaconsToBLEBeacons(std::istream& istream){
        BLEBeacons bleBeacons;
        std::string strBuffer;
        while(std::getline(istream, strBuffer)){
            try{
                BLEBeacon bleBeacon = parseBLEBeaconCSV(strBuffer);
                bleBeacons.push_back(bleBeacon);
            }catch(std::invalid_argument e){
                std::cout << "Invalid csv line was found. line=" <<strBuffer << std::endl;
                //std::cout << "Header line is found in csv BLEBeacons." << std::endl;
            }catch(std::out_of_range& e){
                std::cout << "Invalid csv line was found. line=" <<strBuffer << std::endl;
            }
        }

        if(bleBeacons.size()==0){
            std::cout << "BLEBeacons CSV was not found." << std::endl;
        }

        return bleBeacons;
    }

    std::string DataUtils::BLEBeaconsToCSV(const BLEBeacons &bleBeacons){
        // UUID, major, minor, x,y,z,floor
        std::stringstream ss;
        for(auto& b: bleBeacons){
            ss << b.uuid() << "," << b.major() << "," << b.minor()
            << "," << b.x() << "," << b.y() << "," << b.z() << "," << b.floor();
            ss << std::endl;
        }
        return ss.str();
    }

    Pose DataUtils::parseResetPoseCSV(const std::string& csvLine){

        std::list<std::string> stringList = splitAndTrimCSV(csvLine);
        std::list<std::string>::iterator iter;

        // timestamp, "Reset", x, y, floor, orientation
        std::vector<std::string> stringVector;
        for( iter= stringList.begin(); iter!=stringList.end(); iter++){
            stringVector.push_back(*iter);
        }
        double x = std::stod(stringVector.at(2));
        double y = std::stod(stringVector.at(3));
        double z = 0.0;
        double floor = std::stod(stringVector.at(4));
        double orientation = std::stod(stringVector.at(5));

        Pose pose;
        pose.x(x).y(y).z(z).floor(floor).orientation(orientation);
        pose.velocity(0);
        pose.normalVelocity(0.0);
        return pose;
    }

    picojson::object DataUtils::locationToJSONObject(Location location){
        picojson::object obj;
        obj.insert(std::make_pair("x", picojson::value(location.x())));
        obj.insert(std::make_pair("y", picojson::value(location.y())));
        obj.insert(std::make_pair("z", picojson::value(location.z())));
        obj.insert(std::make_pair("floor", picojson::value(location.floor())));
        return obj;
    }

    picojson::object DataUtils::poseToJSONObject(Pose pose){
        picojson::object obj = locationToJSONObject(pose);
        obj.insert(std::make_pair("orientation", picojson::value(pose.orientation())));
        obj.insert(std::make_pair("velocity", picojson::value(pose.velocity())));
        obj.insert(std::make_pair("normalVelocity", picojson::value(pose.normalVelocity())));
        return obj;
    }

    picojson::object DataUtils::stateToJSONObject(State state){
        picojson::object obj = poseToJSONObject(state);
        obj.insert(std::make_pair("orientationBias", picojson::value(state.orientationBias())));
        obj.insert(std::make_pair("rssiBias", picojson::value(state.rssiBias())));
        obj.insert(std::make_pair("weight", picojson::value(state.weight())));
        return obj;
    }

    picojson::array DataUtils::statesToJSONArray(std::vector<State> states){
        picojson::array array;
        for(State s: states){
            picojson::object obj = DataUtils::stateToJSONObject(s);
            array.push_back(picojson::value(obj));
        }
        return array;
    }

    picojson::array DataUtils::statesToJSONArrayLight(std::vector<State> states){
        picojson::array array;
        for(State s: states){
            picojson::array ar;
            ar.push_back(picojson::value(s.x()));
            ar.push_back(picojson::value(s.y()));
            ar.push_back(picojson::value(s.floor()));
            array.push_back(picojson::value(ar));
        }
        return array;
    }

    picojson::object DataUtils::statusToJSONObject(Status status, bool optOutputStates){
        std::shared_ptr<Location> meanLocation = status.meanLocation();
        std::shared_ptr<Pose> meanPose = status.meanPose();
        std::shared_ptr<std::vector<State>> states = status.states();
        Location stdevLocation = Location::standardDeviation(*states);

        picojson::object json;
        if(meanPose){
            json = poseToJSONObject(*meanPose);
        }else{
            json = locationToJSONObject(*meanLocation);
        }
        json.insert(std::make_pair("stdev", picojson::value(locationToJSONObject(stdevLocation))));
        if(optOutputStates){
            picojson::array array = statesToJSONArrayLight(*states);
            json.insert(std::make_pair("states", picojson::value(array)));
        }
        return json;
    }

    picojson::array DataUtils::beaconsToJSONArray(const Beacons& beacons){
        picojson::array array;
        for(const Beacon& b: beacons){
            picojson::object obj;
            obj.insert(std::make_pair("major", picojson::value((double)b.major())));
            obj.insert(std::make_pair("minor", picojson::value((double)b.minor())));
            obj.insert(std::make_pair("rssi", picojson::value(b.rssi())));
            array.emplace_back(obj);
        }
        return array;
    }

}

max_stars_repo_name: harsh-agarwal/blelocpp

max_issues_repo_name: harsh-agarwal/blelocpp

max_forks_repo_name: harsh-agarwal/blelocpp


text:
#ifndef SKUI_CSS_GRAMMAR_AS_H
#define SKUI_CSS_GRAMMAR_AS_H

#include <boost/spirit/home/x3.hpp>

namespace skui::css::grammar
{
  namespace x3 = boost::spirit::x3;

  template<typename AttributeType>
  inline auto as = [](auto&& parser) { return x3::rule<struct _, AttributeType>{} %= as_parser(parser); };
}
#endif

max_issues_repo_name: qdtroy/skui

max_forks_repo_name: qdtroy/skui


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef INCLUDED_CANVAS_ISURFACEPROXY_HXX
#define INCLUDED_CANVAS_ISURFACEPROXY_HXX

#include <canvas/rendering/irendermodule.hxx>

#include <boost/shared_ptr.hpp>

namespace basegfx
{
    class B2DRange;
    class B2DPoint;
    class B2DPolyPolygon;
    class B2DHomMatrix;
}

namespace canvas
{
    struct ISurfaceProxy
    {
        virtual ~ISurfaceProxy() {}

        /** Notify the proxy that the color buffer has changed
         */
        virtual void setColorBufferDirty() = 0;

        /** Render the surface content to screen.

            @param fAlpha
            Overall alpha for content

            @param rPos
            Output position

            @param rTransform
            Output transformation (does not affect output position)
         */
        virtual bool draw( double                         fAlpha,
                           const ::basegfx::B2DPoint&     rPos,
                           const ::basegfx::B2DHomMatrix& rTransform ) = 0;

        /** Render the surface content to screen.

            @param fAlpha
            Overall alpha for content

            @param rPos
            Output position

            @param rArea
            Subset of the surface to render. Coordinate system are
            surface area pixel, given area will be clipped to the
            surface bounds.

            @param rTransform
            Output transformation (does not affect output position)
         */
        virtual bool draw( double                         fAlpha,
                           const ::basegfx::B2DPoint&     rPos,
                           const ::basegfx::B2DRange&     rArea,
                           const ::basegfx::B2DHomMatrix& rTransform ) = 0;

        /** Render the surface content to screen.

            @param fAlpha
            Overall alpha for content

            @param rPos
            Output position

            @param rClipPoly
            Clip polygon for the surface. The clip polygon is also
            subject to the output transformation.

            @param rTransform
            Output transformation (does not affect output position)
         */
        virtual bool draw( double                           fAlpha,
                           const ::basegfx::B2DPoint&       rPos,
                           const ::basegfx::B2DPolyPolygon& rClipPoly,
                           const ::basegfx::B2DHomMatrix&   rTransform ) = 0;
    };

    typedef ::boost::shared_ptr< ISurfaceProxy > ISurfaceProxySharedPtr;
}

#endif /* INCLUDED_CANVAS_ISURFACEPROXY_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#include "Cache.hpp"
#include "Sha256.hpp"

#include <fstream>
#include <streambuf>

#include <boost/filesystem/operations.hpp>

SourceCache::SourceCache(std::string const & path, std::string const & targetName)
  : m_cacheFileName(path + "/" + targetName + ".gen_cache")
{
}

SourceCache::~SourceCache()
{
}

void SourceCache::Load()
{
  std::ifstream input(m_cacheFileName);
  std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());

  size_t pos = str.find("\n");
  while (pos != std::string::npos)
  {
    std::string const line = str.substr(0, pos);

    size_t delimPos = line.find("|");
    if (delimPos != std::string::npos)
    {
      std::string key = line.substr(0, delimPos);
      std::string value = line.substr(delimPos + 1);

      if (!key.empty() && !value.empty())
        m_cache[key] = value;
    }

    str = str.substr(pos + 1);
    pos = str.find("\n");
  }
}

void SourceCache::Save()
{
  std::ofstream out(m_cacheFileName, std::fstream::out);
  CacheMap::const_iterator it = m_cache.begin();
  for (; it != m_cache.end(); ++it)
  {
    out << it->first << "|" << it->second << std::endl;
  }
  out.flush();
  out.close();
}

void SourceCache::CheckGenerator(std::string const & fileName)
{
  std::string absPath = boost::filesystem::canonical(boost::filesystem::path(fileName)).string();
  std::string checksum = FileChecksum(absPath);

  CacheMap::iterator it = m_cache.find(absPath);
  if (it != m_cache.end())
  {
    if (it->second == checksum)
      return; // generator doesn't changed
  }

  // clear cache, because of new generator
  m_cache.clear();
  m_cache[absPath] = checksum;
}

bool SourceCache::RequestGenerate(std::string const & fileName)
{
  std::string absPath = boost::filesystem::canonical(boost::filesystem::path(fileName)).string();
  std::string checksum = FileChecksum(absPath);

  CacheMap::iterator it = m_cache.find(absPath);
  if (it != m_cache.end())
  {
    if (it->second == checksum)
      return false;
  }

  m_cache[absPath] = checksum;

  return true;
}

std::string SourceCache::FileChecksum(std::string const & fileName)
{
  boost::filesystem::path p(fileName);
  if (boost::filesystem::exists(p))
  {
    std::ifstream input(fileName);
    std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());

    std::time_t t = boost::filesystem::last_write_time(p);

    return sha256(str + std::ctime(&t));
  }

  return std::string();
}

max_stars_repo_name: RuslanKorshunov/sc-machine

max_issues_repo_name: RuslanKorshunov/sc-machine

max_forks_repo_name: RuslanKorshunov/sc-machine