<commit_before>#include <climits>
#include <cmath>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>

#include "../include/solvers/DeterministicSolver.h"
#include "../include/solvers/HDPSolver.h"
#include "../include/solvers/LAOStarSolver.h"
#include "../include/solvers/LRTDPSolver.h"
#include "../include/solvers/MLRTDPSolver.h"
#include "../include/solvers/Solver.h"
#include "../include/solvers/SSiPPSolver.h"
#include "../include/solvers/UCTSolver.h"
#include "../include/solvers/VISolver.h"

#include "../include/util/flags.h"
#include "../include/util/general.h"
#include "../include/util/graph.h"

#include "../include/domains/ctp/CTPOptimisticHeuristic.h"
#include "../include/domains/ctp/CTPProblem.h"
#include "../include/domains/ctp/CTPState.h"

#include "../include/domains/gridworld/GridWorldProblem.h"
#include "../include/domains/gridworld/GWManhattanHeuristic.h"

#include "../include/domains/racetrack/RacetrackProblem.h"
#include "../include/domains/racetrack/RTrackDetHeuristic.h"

#include "../include/domains/sailing/SailingNoWindHeuristic.h"
#include "../include/domains/sailing/SailingProblem.h"

using namespace mdplib;
using namespace mlcore;
using namespace mlsolvers;
using namespace std;

Problem* problem;
Heuristic* heuristic;
Solver* solver;

int verbosity = 0;
bool useOnline = false;

void setupRacetrack()
{
    string trackName = flag_value("track");
    if (verbosity > 100)
        cout << "Setting up racetrack " << trackName << endl;
    problem = new RacetrackProblem(trackName.c_str());
    ((RacetrackProblem*) problem)->pError(0.10);
    ((RacetrackProblem*) problem)->pSlip(0.20);
    ((RacetrackProblem*) problem)->mds(-1);
    heuristic = new RTrackDetHeuristic(trackName.c_str());
}

void setupGridWorld()
{
    string grid = flag_value("grid");
    if (verbosity > 100)
        cout << "Setting up grid world " << grid << endl;
    problem = new GridWorldProblem(grid.c_str(), 1.0);
    heuristic = new GWManhattanHeuristic((GridWorldProblem*) problem);
}

void setupSailingDomain()
{
    static vector<double> costs;
    costs.push_back(1);
    costs.push_back(2);
    costs.push_back(5);
    costs.push_back(10);
    costs.push_back(mdplib::dead_end_cost + 1);

    static double windTransition[] = {
        0.20, 0.20, 0.20, 0.00, 0.00, 0.00, 0.20, 0.20,
        0.20, 0.20, 0.20, 0.20, 0.00, 0.00, 0.00, 0.20,
        0.20, 0.20, 0.20, 0.20, 0.20, 0.00, 0.00, 0.00,
        0.00, 0.20, 0.20, 0.20, 0.20, 0.20, 0.00, 0.00,
        0.00, 0.00, 0.20, 0.20, 0.20, 0.20, 0.20, 0.00,
        0.00, 0.00, 0.00, 0.20, 0.20, 0.20, 0.20, 0.20,
        0.20, 0.00, 0.00, 0.00, 0.20, 0.20, 0.20, 0.20,
        0.20, 0.20, 0.00, 0.00, 0.00, 0.20, 0.20, 0.20};

    if (!flag_is_registered_with_value("sailing-goal")) {
        cerr << "Must specify sailing-goal argument flag" << endl;
        exit(-1);
    }

    int sizeSailing = atoi(flag_value("sailing-size").c_str());
    int goalSailing = atoi(flag_value("sailing-goal").c_str());

    if (verbosity > 100)
        cout << "Setting up sailing domain with size " << sizeSailing <<
            " with goal " << goalSailing << endl;

    problem =
        new SailingProblem(0, 0, 0,
                           goalSailing, goalSailing,
                           sizeSailing, sizeSailing,
                           costs,
                           windTransition);
    heuristic =
        new SailingNoWindHeuristic(static_cast<SailingProblem*>(problem));
    problem->setHeuristic(heuristic);
}

void setupCTP()
{
    if (verbosity > 100) {
        cout << "Setting up Canadian Traveler Problem " <<
            flag_value("ctp") << endl;
    }
    problem = new CTPProblem(flag_value("ctp").c_str());
    heuristic =
        new CTPOptimisticHeuristic(static_cast<CTPProblem*> (problem));
    problem->setHeuristic(heuristic);
}

void setupProblem()
{
    if (verbosity > 100)
        cout << "Setting up problem" << endl;
    if (flag_is_registered_with_value("track")) {
        setupRacetrack();
    } else if (flag_is_registered_with_value("grid")) {
        setupGridWorld();
    } else if (flag_is_registered_with_value("sailing-size")) {
        setupSailingDomain();
    } else if (flag_is_registered_with_value("ctp")) {
        setupCTP();
    } else {
        cerr << "Invalid problem." << endl;
        exit(-1);
    }
}

bool mustReplan(State* s, int plausTrial) {
  if (flag_is_registered("online"))
      return true;
  string algorithm = flag_value("algorithm");
  if (algorithm == "mlrtdp") {
      return !s->checkBits(mdplib::SOLVED_MLRTDP);
  }
  if (algorithm == "hdp") {
      if (flag_is_registered("i")) {
          int j = INT_MAX;
          if (flag_is_registered_with_value("j")) {
              j = stoi(flag_value("j"));
          }
          if (plausTrial >= j) {
              static_cast<HDPSolver*>(solver)->clearLabels();
              return true;
          }
      }
  }
  return false;
}

void initSolver()
{
    double tol = 1.0e-3;
    assert(flag_is_registered_with_value("algorithm"));
    string algorithm = flag_value("algorithm");

    int horizon = 0, expansions = 1, trials = 1000;
    if (flag_is_registered_with_value("horizon"))
        horizon = stoi(flag_value("horizon"));
    if (flag_is_registered_with_value("expansions"))
        expansions = stoi(flag_value("expansions"));
    if (flag_is_registered_with_value("trials"))
        trials = stoi(flag_value("trials"));

    if (algorithm == "wlao") {
        double weight = 1.0;
        if (flag_is_registered_with_value("weight"))
            weight = stof(flag_value("weight"));
        solver = new LAOStarSolver(problem, tol, 1000000, weight);
    } else if (algorithm == "lao") {
        solver = new LAOStarSolver(problem, tol, 1000000);
    } else if (algorithm == "lrtdp") {
        solver = new LRTDPSolver(problem, trials, tol);
    } else if (algorithm == "hdp") {
        int plaus;
        if (flag_is_registered_with_value("i"))
            solver = new HDPSolver(problem, tol, stoi(flag_value("i")));
        else
            solver = new HDPSolver(problem, tol);
    } else if (algorithm == "vi") {
        solver = new VISolver(problem, 1000000000, tol);
    } else if (algorithm == "ssipp") {
        solver = new SSiPPSolver(problem, tol, horizon);
    } else if (algorithm == "labeled-ssipp") {
        solver = new SSiPPSolver(problem, tol, horizon, SSiPPAlgo::Labeled);
    } else if (algorithm == "det") {
        solver = new DeterministicSolver(problem,
                                         mlsolvers::det_most_likely,
                                         heuristic);
    } else {
        cerr << "Unknown algorithm: " << algorithm << endl;
        assert(false);
    }
}

void updateStatistics(double cost, int n, double& mean, double& M2)
{
    double delta = cost - mean;
    mean += delta / n;
    M2 += delta * (cost - mean);
}

int main(int argc, char* args[])
{
    register_flags(argc, args);

    verbosity = 0;
    if (flag_is_registered_with_value("v"))
        verbosity = stoi(flag_value("v"));

    mdplib_debug = true;
    setupProblem();
    if (!flag_is_registered("dont-generate"))
        problem->generateAll();
    problem->setHeuristic(heuristic);

    if (verbosity > 100)
        cout << problem->states().size() << " states" << endl;

    initSolver();

    int nsims = 100;
    if (flag_is_registered_with_value("n"))
        nsims = stoi(flag_value("n"));

    // Running simulations to evaluate the solver's performance.
    double expectedCost = 0.0;
    double variance = 0.0;
    double expectedTime = 0.0;
    StateSet statesSeen;

    int cnt = 0;
    int numDecisions = 0;
    for (int i = 0; i < nsims; i++) {
        if (verbosity >= 100)
            cout << " ********* Simulation Starts ********* " << endl;
        clock_t startTime, endTime;
        if (i == 0 || !flag_is_registered("no-initial-plan")) {
            for (State* s : problem->states())
                s->reset();
            startTime = clock();
            solver->solve(problem->initialState());
            endTime = clock();
            expectedTime += (double(endTime - startTime) / CLOCKS_PER_SEC);
            numDecisions++;
        }
        if (verbosity >= 10) {
            cout << "Starting simulation " << i << endl;
        }
        State* tmp = problem->initialState();
        if (verbosity >= 100) {
            cout << "Estimated cost " <<
                problem->initialState()->cost() << endl << tmp << " ";
        }
        double costTrial = 0.0;
        int plausTrial = 0;
        while (!problem->goal(tmp)) {
            statesSeen.insert(tmp);
            Action* a;
            if (mustReplan(tmp, plausTrial)) {
                startTime = clock();
                a = solver->solve(tmp);
                endTime = clock();
                expectedTime += (double(endTime - startTime) / CLOCKS_PER_SEC);
                numDecisions++;
            }
            a = greedyAction(problem, tmp);
            costTrial += problem->cost(tmp, a);
            if (costTrial >= mdplib::dead_end_cost) {
                break;
            }
            double prob = 0.0;
            State* aux = randomSuccessor(problem, tmp, a, &prob);
            if (flag_value("algorithm") == "hdp") {
                double maxProb = 0.0;
                for (auto const & sccr : problem->transition(tmp, a))
                    maxProb = std::max(maxProb, sccr.su_prob);
                plausTrial +=
                    static_cast<HDPSolver*>(solver)->kappa(prob, maxProb);
            }
            tmp = aux;

            if (verbosity >= 1000) {
                cout << a << " " << endl;
                cout << tmp << " ";
            }
        }
        if (flag_is_registered("ctp")) {
            CTPState* ctps = static_cast<CTPState*>(tmp);
            if (!ctps->badWeather()) {
                cnt++;
                updateStatistics(costTrial, cnt, expectedCost, variance);
            }
        } else {
            cnt++;
            updateStatistics(costTrial, cnt, expectedCost, variance);
        }
        if (verbosity >= 100)
            cout << endl;
    }

    if (verbosity >= 1) {
        cout << "Estimated cost " << problem->initialState()->cost() << " ";
        cout << "Avg. Exec cost " << expectedCost << " ";
        cout << "Std. Dev. " << sqrt(variance / (cnt - 1)) << " ";
        cout << "Total time " << expectedTime / cnt << " " << endl;
        cout << "States seen " << statesSeen.size() << endl;
        cout << "Avg. time per decision " <<
            expectedTime / numDecisions << endl;
    } else {
        cout << problem->initialState()->cost() << " ";
        cout << expectedCost << " " << sqrt(variance / (cnt - 1)) << " " <<
            expectedTime / cnt << " " << expectedTime / numDecisions << endl;
    }

    delete problem;
    delete heuristic;
    delete solver;
}

<commit_msg>minor bug fix<commit_after>#include <climits>
#include <cmath>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>

#include "../include/solvers/DeterministicSolver.h"
#include "../include/solvers/HDPSolver.h"
#include "../include/solvers/LAOStarSolver.h"
#include "../include/solvers/LRTDPSolver.h"
#include "../include/solvers/MLRTDPSolver.h"
#include "../include/solvers/Solver.h"
#include "../include/solvers/SSiPPSolver.h"
#include "../include/solvers/UCTSolver.h"
#include "../include/solvers/VISolver.h"

#include "../include/util/flags.h"
#include "../include/util/general.h"
#include "../include/util/graph.h"

#include "../include/domains/ctp/CTPOptimisticHeuristic.h"
#include "../include/domains/ctp/CTPProblem.h"
#include "../include/domains/ctp/CTPState.h"

#include "../include/domains/gridworld/GridWorldProblem.h"
#include "../include/domains/gridworld/GWManhattanHeuristic.h"

#include "../include/domains/racetrack/RacetrackProblem.h"
#include "../include/domains/racetrack/RTrackDetHeuristic.h"

#include "../include/domains/sailing/SailingNoWindHeuristic.h"
#include "../include/domains/sailing/SailingProblem.h"

using namespace mdplib;
using namespace mlcore;
using namespace mlsolvers;
using namespace std;

Problem* problem;
Heuristic* heuristic;
Solver* solver;

int verbosity = 0;
bool useOnline = false;

void setupRacetrack()
{
    string trackName = flag_value("track");
    if (verbosity > 100)
        cout << "Setting up racetrack " << trackName << endl;
    problem = new RacetrackProblem(trackName.c_str());
    ((RacetrackProblem*) problem)->pError(0.10);
    ((RacetrackProblem*) problem)->pSlip(0.20);
    ((RacetrackProblem*) problem)->mds(-1);
    heuristic = new RTrackDetHeuristic(trackName.c_str());
}

void setupGridWorld()
{
    string grid = flag_value("grid");
    if (verbosity > 100)
        cout << "Setting up grid world " << grid << endl;
    problem = new GridWorldProblem(grid.c_str(), 1.0);
    heuristic = new GWManhattanHeuristic((GridWorldProblem*) problem);
}

void setupSailingDomain()
{
    static vector<double> costs;
    costs.push_back(1);
    costs.push_back(2);
    costs.push_back(5);
    costs.push_back(10);
    costs.push_back(mdplib::dead_end_cost + 1);

    static double windTransition[] = {
        0.20, 0.20, 0.20, 0.00, 0.00, 0.00, 0.20, 0.20,
        0.20, 0.20, 0.20, 0.20, 0.00, 0.00, 0.00, 0.20,
        0.20, 0.20, 0.20, 0.20, 0.20, 0.00, 0.00, 0.00,
        0.00, 0.20, 0.20, 0.20, 0.20, 0.20, 0.00, 0.00,
        0.00, 0.00, 0.20, 0.20, 0.20, 0.20, 0.20, 0.00,
        0.00, 0.00, 0.00, 0.20, 0.20, 0.20, 0.20, 0.20,
        0.20, 0.00, 0.00, 0.00, 0.20, 0.20, 0.20, 0.20,
        0.20, 0.20, 0.00, 0.00, 0.00, 0.20, 0.20, 0.20};

    if (!flag_is_registered_with_value("sailing-goal")) {
        cerr << "Must specify sailing-goal argument flag" << endl;
        exit(-1);
    }

    int sizeSailing = atoi(flag_value("sailing-size").c_str());
    int goalSailing = atoi(flag_value("sailing-goal").c_str());

    if (verbosity > 100)
        cout << "Setting up sailing domain with size " << sizeSailing <<
            " with goal " << goalSailing << endl;

    problem =
        new SailingProblem(0, 0, 0,
                           goalSailing, goalSailing,
                           sizeSailing, sizeSailing,
                           costs,
                           windTransition);
    heuristic =
        new SailingNoWindHeuristic(static_cast<SailingProblem*>(problem));
    problem->setHeuristic(heuristic);
}

void setupCTP()
{
    if (verbosity > 100) {
        cout << "Setting up Canadian Traveler Problem " <<
            flag_value("ctp") << endl;
    }
    problem = new CTPProblem(flag_value("ctp").c_str());
    heuristic =
        new CTPOptimisticHeuristic(static_cast<CTPProblem*> (problem));
    problem->setHeuristic(heuristic);
}

void setupProblem()
{
    if (verbosity > 100)
        cout << "Setting up problem" << endl;
    if (flag_is_registered_with_value("track")) {
        setupRacetrack();
    } else if (flag_is_registered_with_value("grid")) {
        setupGridWorld();
    } else if (flag_is_registered_with_value("sailing-size")) {
        setupSailingDomain();
    } else if (flag_is_registered_with_value("ctp")) {
        setupCTP();
    } else {
        cerr << "Invalid problem." << endl;
        exit(-1);
    }
}

bool mustReplan(State* s, int plausTrial) {
  if (flag_is_registered("online"))
      return true;
  string algorithm = flag_value("algorithm");
  if (algorithm == "mlrtdp") {
      return !s->checkBits(mdplib::SOLVED_MLRTDP);
  }
  if (algorithm == "hdp") {
      if (flag_is_registered("i")) {
          int j = INT_MAX;
          if (flag_is_registered_with_value("j")) {
              j = stoi(flag_value("j"));
          }
          if (plausTrial >= j) {
              static_cast<HDPSolver*>(solver)->clearLabels();
              return true;
          }
      }
  }
  return false;
}

void initSolver()
{
    double tol = 1.0e-3;
    assert(flag_is_registered_with_value("algorithm"));
    string algorithm = flag_value("algorithm");

    int horizon = 0, expansions = 1, trials = 1000;
    if (flag_is_registered_with_value("horizon"))
        horizon = stoi(flag_value("horizon"));
    if (flag_is_registered_with_value("expansions"))
        expansions = stoi(flag_value("expansions"));
    if (flag_is_registered_with_value("trials"))
        trials = stoi(flag_value("trials"));

    if (algorithm == "wlao") {
        double weight = 1.0;
        if (flag_is_registered_with_value("weight"))
            weight = stof(flag_value("weight"));
        solver = new LAOStarSolver(problem, tol, 1000000, weight);
    } else if (algorithm == "lao") {
        solver = new LAOStarSolver(problem, tol, 1000000);
    } else if (algorithm == "lrtdp") {
        solver = new LRTDPSolver(problem, trials, tol);
    } else if (algorithm == "mlrtdp") {
        bool optimal = flag_is_registered("optimal");
        solver = new MLRTDPSolver(problem, trials, tol, horizon, optimal);
    } else if (algorithm == "hdp") {
        int plaus;
        if (flag_is_registered_with_value("i"))
            solver = new HDPSolver(problem, tol, stoi(flag_value("i")));
        else
            solver = new HDPSolver(problem, tol);
    } else if (algorithm == "vi") {
        solver = new VISolver(problem, 1000000000, tol);
    } else if (algorithm == "ssipp") {
        solver = new SSiPPSolver(problem, tol, horizon);
    } else if (algorithm == "labeled-ssipp") {
        solver = new SSiPPSolver(problem, tol, horizon, SSiPPAlgo::Labeled);
    } else if (algorithm == "det") {
        solver = new DeterministicSolver(problem,
                                         mlsolvers::det_most_likely,
                                         heuristic);
    } else {
        cerr << "Unknown algorithm: " << algorithm << endl;
        assert(false);
    }
}

void updateStatistics(double cost, int n, double& mean, double& M2)
{
    double delta = cost - mean;
    mean += delta / n;
    M2 += delta * (cost - mean);
}

int main(int argc, char* args[])
{
    register_flags(argc, args);

    verbosity = 0;
    if (flag_is_registered_with_value("v"))
        verbosity = stoi(flag_value("v"));

    mdplib_debug = true;
    setupProblem();
    if (!flag_is_registered("dont-generate"))
        problem->generateAll();
    problem->setHeuristic(heuristic);

    if (verbosity > 100)
        cout << problem->states().size() << " states" << endl;

    initSolver();

    int nsims = 100;
    if (flag_is_registered_with_value("n"))
        nsims = stoi(flag_value("n"));

    // Running simulations to evaluate the solver's performance.
    double expectedCost = 0.0;
    double variance = 0.0;
    double expectedTime = 0.0;
    StateSet statesSeen;

    int cnt = 0;
    int numDecisions = 0;
    for (int i = 0; i < nsims; i++) {
        if (verbosity >= 100)
            cout << " ********* Simulation Starts ********* " << endl;
        clock_t startTime, endTime;
        if (i == 0 || !flag_is_registered("no-initial-plan")) {
            for (State* s : problem->states())
                s->reset();
            startTime = clock();
            solver->solve(problem->initialState());
            endTime = clock();
            expectedTime += (double(endTime - startTime) / CLOCKS_PER_SEC);
            numDecisions++;
        }
        if (verbosity >= 10) {
            cout << "Starting simulation " << i << endl;
        }
        State* tmp = problem->initialState();
        if (verbosity >= 100) {
            cout << "Estimated cost " <<
                problem->initialState()->cost() << endl << tmp << " ";
        }
        double costTrial = 0.0;
        int plausTrial = 0;
        while (!problem->goal(tmp)) {
            statesSeen.insert(tmp);
            Action* a;
            if (mustReplan(tmp, plausTrial)) {
                startTime = clock();
                a = solver->solve(tmp);
                endTime = clock();
                expectedTime += (double(endTime - startTime) / CLOCKS_PER_SEC);
                numDecisions++;
            }
            a = greedyAction(problem, tmp);
            costTrial += problem->cost(tmp, a);
            if (costTrial >= mdplib::dead_end_cost) {
                break;
            }
            double prob = 0.0;
            State* aux = randomSuccessor(problem, tmp, a, &prob);
            if (flag_value("algorithm") == "hdp") {
                double maxProb = 0.0;
                for (auto const & sccr : problem->transition(tmp, a))
                    maxProb = std::max(maxProb, sccr.su_prob);
                plausTrial +=
                    static_cast<HDPSolver*>(solver)->kappa(prob, maxProb);
            }
            tmp = aux;

            if (verbosity >= 1000) {
                cout << a << " " << endl;
                cout << tmp << " ";
            }
        }
        if (flag_is_registered("ctp")) {
            CTPState* ctps = static_cast<CTPState*>(tmp);
            if (!ctps->badWeather()) {
                cnt++;
                updateStatistics(costTrial, cnt, expectedCost, variance);
            }
        } else {
            cnt++;
            updateStatistics(costTrial, cnt, expectedCost, variance);
        }
        if (verbosity >= 100)
            cout << endl;
    }

    if (verbosity >= 1) {
        cout << "Estimated cost " << problem->initialState()->cost() << " ";
        cout << "Avg. Exec cost " << expectedCost << " ";
        cout << "Std. Dev. " << sqrt(variance / (cnt - 1)) << " ";
        cout << "Total time " << expectedTime / cnt << " " << endl;
        cout << "States seen " << statesSeen.size() << endl;
        cout << "Avg. time per decision " <<
            expectedTime / numDecisions << endl;
    } else {
        cout << problem->initialState()->cost() << " ";
        cout << expectedCost << " " << sqrt(variance / (cnt - 1)) << " " <<
            expectedTime / cnt << " " << expectedTime / numDecisions << endl;
    }

    delete problem;
    delete heuristic;
    delete solver;
}

<|endoftext|>


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

#include "PoolObjectSQL.h"
#include "PoolObjectAuth.h"
#include "SSLTools.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::to_xml64(string &xml64)
{
    string *str64;

    to_xml(xml64);

    str64 = SSLTools::base64_encode(xml64);

    xml64 = *str64;

    delete str64;

    return xml64;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db)
{
    ostringstream   oss;
    int             rc;
    int             boid;

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE oid = " << oid;

    boid = oid;
    oid  = -1;

    rc = db->exec(oss, this);

    unset_callback();

    if ((rc != 0) || (oid != boid ))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db, const string& _name, int _uid)
{
    ostringstream oss;

    int rc;
    char * sql_name;

    sql_name = db->escape_str(_name.c_str());

    if ( sql_name == 0 )
    {
        return -1;
    }

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE name = '" << sql_name << "'";

    if ( _uid != -1 )
    {
        oss << " AND uid = " << _uid;
    }

    name  = "";
    uid   = -1;

    rc = db->exec(oss, this);

    unset_callback();

    db->free_str(sql_name);

    if ((rc != 0) || (_name != name) || (_uid != -1 && _uid != uid))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::drop(SqlDB *db)
{
    ostringstream oss;
    int rc;

    oss << "DELETE FROM " << table << " WHERE oid=" << oid;

    rc = db->exec(oss);

    if ( rc == 0 )
    {
        set_valid(false);
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char * PoolObjectSQL::error_attribute_name = "ERROR";

void PoolObjectSQL::set_template_error_message(const string& message)
{
    VectorAttribute *  attr;
    map<string,string> error_value;

    char   str[26];
    time_t the_time;

    the_time = time(NULL);

#ifdef SOLARIS
    ctime_r(&(the_time),str,sizeof(char)*26);
#else
    ctime_r(&(the_time),str);
#endif

    str[24] = '\0'; // Get rid of final enter character

    error_value.insert(make_pair("TIMESTAMP",str));
    error_value.insert(make_pair("MESSAGE",message));

    //Replace previous error message and insert the new one

    attr = new VectorAttribute(error_attribute_name,error_value);

    obj_template->erase(error_attribute_name);
    obj_template->set(attr);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::replace_template(const string& tmpl_str, string& error)
{
    Template * new_tmpl  = get_new_template();

    if ( new_tmpl == 0 )
    {
        error = "Cannot allocate a new template";
        return -1;
    }

    if ( new_tmpl->parse_str_or_xml(tmpl_str, error) != 0 )
    {
        return -1;
    }

    delete obj_template;

    obj_template = new_tmpl;

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::perms_to_xml(string& xml) const
{
    ostringstream   oss;

    oss <<
        "<PERMISSIONS>" <<
            "<OWNER_U>" << owner_u << "</OWNER_U>"  <<
            "<OWNER_M>" << owner_m << "</OWNER_M>"  <<
            "<OWNER_A>" << owner_a << "</OWNER_A>"  <<
            "<GROUP_U>" << group_u << "</GROUP_U>"  <<
            "<GROUP_M>" << group_m << "</GROUP_M>"  <<
            "<GROUP_A>" << group_a << "</GROUP_A>"  <<
            "<OTHER_U>" << other_u << "</OTHER_U>"  <<
            "<OTHER_M>" << other_m << "</OTHER_M>"  <<
            "<OTHER_A>" << other_a << "</OTHER_A>"  <<
        "</PERMISSIONS>";

    xml = oss.str();
    return xml;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::perms_from_xml()
{
    int rc = 0;

    rc += xpath(owner_u, "/*/PERMISSIONS/OWNER_U", 0);
    rc += xpath(owner_m, "/*/PERMISSIONS/OWNER_M", 0);
    rc += xpath(owner_a, "/*/PERMISSIONS/OWNER_A", 0);

    rc += xpath(group_u, "/*/PERMISSIONS/GROUP_U", 0);
    rc += xpath(group_m, "/*/PERMISSIONS/GROUP_M", 0);
    rc += xpath(group_a, "/*/PERMISSIONS/GROUP_A", 0);

    rc += xpath(other_u, "/*/PERMISSIONS/OTHER_U", 0);
    rc += xpath(other_m, "/*/PERMISSIONS/OTHER_M", 0);
    rc += xpath(other_a, "/*/PERMISSIONS/OTHER_A", 0);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void PoolObjectSQL::get_permissions(PoolObjectAuth& auth)
{
    auth.obj_type = obj_type;

    auth.oid = oid;
    auth.uid = uid;
    auth.gid = gid;

    auth.owner_u = owner_u;
    auth.owner_m = owner_m;
    auth.owner_a = owner_a;

    auth.group_u = group_u;
    auth.group_m = group_m;
    auth.group_a = group_a;

    auth.other_u = other_u;
    auth.other_m = other_m;
    auth.other_a = other_a;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::set_permissions( int _owner_u,
                                    int _owner_m,
                                    int _owner_a,
                                    int _group_u,
                                    int _group_m,
                                    int _group_a,
                                    int _other_u,
                                    int _other_m,
                                    int _other_a,
                                    string& error_str)
{
    if ( _owner_u < -1 || _owner_u > 1 ) goto error_value;
    if ( _owner_m < -1 || _owner_m > 1 ) goto error_value;
    if ( _owner_a < -1 || _owner_a > 1 ) goto error_value;
    if ( _group_u < -1 || _group_u > 1 ) goto error_value;
    if ( _group_m < -1 || _group_m > 1 ) goto error_value;
    if ( _group_a < -1 || _group_a > 1 ) goto error_value;
    if ( _other_u < -1 || _other_u > 1 ) goto error_value;
    if ( _other_m < -1 || _other_m > 1 ) goto error_value;
    if ( _other_a < -1 || _other_a > 1 ) goto error_value;

    set_perm(owner_u, _owner_u);
    set_perm(owner_m, _owner_m);
    set_perm(owner_a, _owner_a);
    set_perm(group_u, _group_u);
    set_perm(group_m, _group_m);
    set_perm(group_a, _group_a);
    set_perm(other_u, _other_u);
    set_perm(other_m, _other_m);
    set_perm(other_a, _other_a);

    return 0;

error_value:
    error_str = "New permission values must be -1, 0 or 1";
    return -1;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<commit_msg>bug #1694: Fix memory leak when updating templates with syntax errors<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "PoolObjectSQL.h"
#include "PoolObjectAuth.h"
#include "SSLTools.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::to_xml64(string &xml64)
{
    string *str64;

    to_xml(xml64);

    str64 = SSLTools::base64_encode(xml64);

    xml64 = *str64;

    delete str64;

    return xml64;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db)
{
    ostringstream   oss;
    int             rc;
    int             boid;

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE oid = " << oid;

    boid = oid;
    oid  = -1;

    rc = db->exec(oss, this);

    unset_callback();

    if ((rc != 0) || (oid != boid ))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db, const string& _name, int _uid)
{
    ostringstream oss;

    int rc;
    char * sql_name;

    sql_name = db->escape_str(_name.c_str());

    if ( sql_name == 0 )
    {
        return -1;
    }

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE name = '" << sql_name << "'";

    if ( _uid != -1 )
    {
        oss << " AND uid = " << _uid;
    }

    name  = "";
    uid   = -1;

    rc = db->exec(oss, this);

    unset_callback();

    db->free_str(sql_name);

    if ((rc != 0) || (_name != name) || (_uid != -1 && _uid != uid))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::drop(SqlDB *db)
{
    ostringstream oss;
    int rc;

    oss << "DELETE FROM " << table << " WHERE oid=" << oid;

    rc = db->exec(oss);

    if ( rc == 0 )
    {
        set_valid(false);
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char * PoolObjectSQL::error_attribute_name = "ERROR";

void PoolObjectSQL::set_template_error_message(const string& message)
{
    VectorAttribute *  attr;
    map<string,string> error_value;

    char   str[26];
    time_t the_time;

    the_time = time(NULL);

#ifdef SOLARIS
    ctime_r(&(the_time),str,sizeof(char)*26);
#else
    ctime_r(&(the_time),str);
#endif

    str[24] = '\0'; // Get rid of final enter character

    error_value.insert(make_pair("TIMESTAMP",str));
    error_value.insert(make_pair("MESSAGE",message));

    //Replace previous error message and insert the new one

    attr = new VectorAttribute(error_attribute_name,error_value);

    obj_template->erase(error_attribute_name);
    obj_template->set(attr);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::replace_template(const string& tmpl_str, string& error)
{
    Template * new_tmpl  = get_new_template();

    if ( new_tmpl == 0 )
    {
        error = "Cannot allocate a new template";
        return -1;
    }

    if ( new_tmpl->parse_str_or_xml(tmpl_str, error) != 0 )
    {
        delete new_tmpl;
        return -1;
    }

    delete obj_template;

    obj_template = new_tmpl;

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::perms_to_xml(string& xml) const
{
    ostringstream   oss;

    oss <<
        "<PERMISSIONS>" <<
            "<OWNER_U>" << owner_u << "</OWNER_U>"  <<
            "<OWNER_M>" << owner_m << "</OWNER_M>"  <<
            "<OWNER_A>" << owner_a << "</OWNER_A>"  <<
            "<GROUP_U>" << group_u << "</GROUP_U>"  <<
            "<GROUP_M>" << group_m << "</GROUP_M>"  <<
            "<GROUP_A>" << group_a << "</GROUP_A>"  <<
            "<OTHER_U>" << other_u << "</OTHER_U>"  <<
            "<OTHER_M>" << other_m << "</OTHER_M>"  <<
            "<OTHER_A>" << other_a << "</OTHER_A>"  <<
        "</PERMISSIONS>";

    xml = oss.str();
    return xml;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::perms_from_xml()
{
    int rc = 0;

    rc += xpath(owner_u, "/*/PERMISSIONS/OWNER_U", 0);
    rc += xpath(owner_m, "/*/PERMISSIONS/OWNER_M", 0);
    rc += xpath(owner_a, "/*/PERMISSIONS/OWNER_A", 0);

    rc += xpath(group_u, "/*/PERMISSIONS/GROUP_U", 0);
    rc += xpath(group_m, "/*/PERMISSIONS/GROUP_M", 0);
    rc += xpath(group_a, "/*/PERMISSIONS/GROUP_A", 0);

    rc += xpath(other_u, "/*/PERMISSIONS/OTHER_U", 0);
    rc += xpath(other_m, "/*/PERMISSIONS/OTHER_M", 0);
    rc += xpath(other_a, "/*/PERMISSIONS/OTHER_A", 0);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void PoolObjectSQL::get_permissions(PoolObjectAuth& auth)
{
    auth.obj_type = obj_type;

    auth.oid = oid;
    auth.uid = uid;
    auth.gid = gid;

    auth.owner_u = owner_u;
    auth.owner_m = owner_m;
    auth.owner_a = owner_a;

    auth.group_u = group_u;
    auth.group_m = group_m;
    auth.group_a = group_a;

    auth.other_u = other_u;
    auth.other_m = other_m;
    auth.other_a = other_a;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::set_permissions( int _owner_u,
                                    int _owner_m,
                                    int _owner_a,
                                    int _group_u,
                                    int _group_m,
                                    int _group_a,
                                    int _other_u,
                                    int _other_m,
                                    int _other_a,
                                    string& error_str)
{
    if ( _owner_u < -1 || _owner_u > 1 ) goto error_value;
    if ( _owner_m < -1 || _owner_m > 1 ) goto error_value;
    if ( _owner_a < -1 || _owner_a > 1 ) goto error_value;
    if ( _group_u < -1 || _group_u > 1 ) goto error_value;
    if ( _group_m < -1 || _group_m > 1 ) goto error_value;
    if ( _group_a < -1 || _group_a > 1 ) goto error_value;
    if ( _other_u < -1 || _other_u > 1 ) goto error_value;
    if ( _other_m < -1 || _other_m > 1 ) goto error_value;
    if ( _other_a < -1 || _other_a > 1 ) goto error_value;

    set_perm(owner_u, _owner_u);
    set_perm(owner_m, _owner_m);
    set_perm(owner_a, _owner_a);
    set_perm(group_u, _group_u);
    set_perm(group_m, _group_m);
    set_perm(group_a, _group_a);
    set_perm(other_u, _other_u);
    set_perm(other_m, _other_m);
    set_perm(other_a, _other_a);

    return 0;

error_value:
    error_str = "New permission values must be -1, 0 or 1";
    return -1;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $
Version:   $Revision: 13129 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationDataRecorder.h"
#include <fstream>

#include <mitkTimeStamp.h>
#include <tinyxml.h>

#include <itksys/SystemTools.hxx>
mitk::NavigationDataRecorder::NavigationDataRecorder()
{
  m_NumberOfInputs = 0;
  m_RecordingMode = NormalFile;
  m_Recording = false;
  m_NumberOfRecordedFiles = 0;
  m_Stream = NULL;
  m_FileName = "";

  //To get a start time
  mitk::TimeStamp::GetInstance()->Start(this);

}

mitk::NavigationDataRecorder::~NavigationDataRecorder()
{
}

void mitk::NavigationDataRecorder::GenerateData()
{

}

void mitk::NavigationDataRecorder::AddNavigationData( const NavigationData* nd )
{
  // Process object is not const-correct so the const_cast is required here
  this->SetNthInput(m_NumberOfInputs,
    const_cast< mitk::NavigationData * >( nd ) );

  m_NumberOfInputs++;

  this->Modified();
}

void mitk::NavigationDataRecorder::SetRecordingMode( RecordingMode mode )
{
  m_RecordingMode = mode;
  this->Modified();
}

void mitk::NavigationDataRecorder::Update()
{
  if (m_Recording)
  {
    DataObjectPointerArray inputs = this->GetInputs(); //get all inputs
    mitk::NavigationData::TimeStampType timestamp=0.0;
    timestamp = mitk::TimeStamp::GetInstance()->GetElapsed();

    for (unsigned int index = 0; index < inputs.size(); index++)
    {
      mitk::NavigationData* nd = dynamic_cast<mitk::NavigationData*>(inputs[index].GetPointer());
      nd->Update();

      mitk::NavigationData::PositionType position;
      mitk::NavigationData::OrientationType orientation(0.0, 0.0, 0.0, 0.0);
      mitk::NavigationData::CovarianceMatrixType matrix;

      bool hasPosition = true;
      bool hasOrientation = true;
      bool dataValid = false;

      position.Fill(0.0);
      matrix.SetIdentity();

      position = nd->GetPosition();
      orientation = nd->GetOrientation();
      matrix = nd->GetCovErrorMatrix();

      hasPosition = nd->GetHasPosition();
      hasOrientation = nd->GetHasOrientation();
      dataValid = nd->IsDataValid();

      //use this one if you want the timestamps of the source
      //timestamp = nd->GetTimeStamp();

      //a timestamp is never < 0! this case happens only if you are using the timestamp of the nd object instead of getting a new one
      if (timestamp >= 0)
      {
        TiXmlElement* elem = new TiXmlElement("ND");

        elem->SetDoubleAttribute("Time", timestamp);
        elem->SetDoubleAttribute("Tool", index);
        elem->SetDoubleAttribute("X", position[0]);
        elem->SetDoubleAttribute("Y", position[1]);
        elem->SetDoubleAttribute("Z", position[2]);

        elem->SetDoubleAttribute("QX", orientation[0]);
        elem->SetDoubleAttribute("QY", orientation[1]);
        elem->SetDoubleAttribute("QZ", orientation[2]);
        elem->SetDoubleAttribute("QR", orientation[3]);

        elem->SetDoubleAttribute("C00", matrix[0][0]);
        elem->SetDoubleAttribute("C01", matrix[0][1]);
        elem->SetDoubleAttribute("C02", matrix[0][2]);
        elem->SetDoubleAttribute("C03", matrix[0][3]);
        elem->SetDoubleAttribute("C04", matrix[0][4]);
        elem->SetDoubleAttribute("C05", matrix[0][5]);
        elem->SetDoubleAttribute("C10", matrix[1][0]);
        elem->SetDoubleAttribute("C11", matrix[1][1]);
        elem->SetDoubleAttribute("C12", matrix[1][2]);
        elem->SetDoubleAttribute("C13", matrix[1][3]);
        elem->SetDoubleAttribute("C14", matrix[1][4]);
        elem->SetDoubleAttribute("C15", matrix[1][5]);

        if (dataValid)
          elem->SetAttribute("Valid",1);
        else
          elem->SetAttribute("Valid",0);

        if (hasOrientation)
          elem->SetAttribute("hO",1);
        else
          elem->SetAttribute("hO",0);

        if (hasPosition)
          elem->SetAttribute("hP",1);
        else
          elem->SetAttribute("hP",0);

        *m_Stream << "        " << *elem << std::endl;

        delete elem;
      }
    }
  }
}

void mitk::NavigationDataRecorder::StartRecording()
{
  if (m_Recording)
  {
    std::cout << "Already recording please stop before start new recording session" << std::endl;
    return;
  }
  if (m_Stream == NULL)
  {
    std::stringstream ss;
    std::ostream* stream;

    //An existing extension will be cut and replaced with .xml
    std::string tmpPath = itksys::SystemTools::GetFilenamePath(m_FileName);
    m_FileName = itksys::SystemTools::GetFilenameWithoutExtension(m_FileName);
    ss << tmpPath << "/" <<  m_FileName << "-" << m_NumberOfRecordedFiles << ".xml";
    switch(m_RecordingMode)
    {
      case Console:
        stream = &std::cout;
        break;
      case NormalFile:

        //Check if there is a file name and path
        if (m_FileName == "")
        {
          stream = &std::cout;
          std::cout << "No file name or file path set the output is redirected to the console";
        }
        else
        {
          stream = new std::ofstream(ss.str().c_str());
        }

        break;
      case ZipFile:
        stream = &std::cout;
        std::cout << "Sorry no ZipFile support yet";
        break;
      default:
        stream = &std::cout;
        break;
    }
    StartRecording(stream);
  }

}
void mitk::NavigationDataRecorder::StartRecording(std::ostream* stream)
{
  if (m_Recording)
  {
    std::cout << "Already recording please stop before start new recording session" << std::endl;
    return;
  }

  m_Stream = stream;
  m_Stream->precision(10);

  //TODO store date and GMT time
  if (m_Stream)
  {
    *m_Stream << "<?xml version=\"1.0\" ?>" << std::endl;
    *m_Stream << "<Version Ver=\"1\" />" << std::endl;
    *m_Stream << "    " << "<Data ToolCount=\"" << (m_NumberOfInputs) << "\">" << std::endl;

    m_Recording = true;
  }
}
void mitk::NavigationDataRecorder::StopRecording()
{
  if (!m_Recording)
  {
    std::cout << "You have to start a recording first" << std::endl;
    return;
  }
  if (m_Stream)
  {
    *m_Stream << "</Data>" << std::endl;
  }

  m_NumberOfRecordedFiles++;
  m_Stream = NULL;
  m_Recording = false;
}<commit_msg>DOC: added a line of documentation as even Hannes had to rethink why he did it like that without a comment<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $
Version:   $Revision: 13129 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationDataRecorder.h"
#include <fstream>

#include <mitkTimeStamp.h>
#include <tinyxml.h>

#include <itksys/SystemTools.hxx>
mitk::NavigationDataRecorder::NavigationDataRecorder()
{
  m_NumberOfInputs = 0;
  m_RecordingMode = NormalFile;
  m_Recording = false;
  m_NumberOfRecordedFiles = 0;
  m_Stream = NULL;
  m_FileName = "";

  //To get a start time
  mitk::TimeStamp::GetInstance()->Start(this);

}

mitk::NavigationDataRecorder::~NavigationDataRecorder()
{
}

void mitk::NavigationDataRecorder::GenerateData()
{

}

void mitk::NavigationDataRecorder::AddNavigationData( const NavigationData* nd )
{
  // Process object is not const-correct so the const_cast is required here
  this->SetNthInput(m_NumberOfInputs,
    const_cast< mitk::NavigationData * >( nd ) );

  m_NumberOfInputs++;

  this->Modified();
}

void mitk::NavigationDataRecorder::SetRecordingMode( RecordingMode mode )
{
  m_RecordingMode = mode;
  this->Modified();
}

void mitk::NavigationDataRecorder::Update()
{
  if (m_Recording)
  {
    DataObjectPointerArray inputs = this->GetInputs(); //get all inputs
    mitk::NavigationData::TimeStampType timestamp=0.0;
    timestamp = mitk::TimeStamp::GetInstance()->GetElapsed();

    for (unsigned int index = 0; index < inputs.size(); index++)
    {
      mitk::NavigationData* nd = dynamic_cast<mitk::NavigationData*>(inputs[index].GetPointer());
      nd->Update(); // call update to propagate update to previous filters

      mitk::NavigationData::PositionType position;
      mitk::NavigationData::OrientationType orientation(0.0, 0.0, 0.0, 0.0);
      mitk::NavigationData::CovarianceMatrixType matrix;

      bool hasPosition = true;
      bool hasOrientation = true;
      bool dataValid = false;

      position.Fill(0.0);
      matrix.SetIdentity();

      position = nd->GetPosition();
      orientation = nd->GetOrientation();
      matrix = nd->GetCovErrorMatrix();

      hasPosition = nd->GetHasPosition();
      hasOrientation = nd->GetHasOrientation();
      dataValid = nd->IsDataValid();

      //use this one if you want the timestamps of the source
      //timestamp = nd->GetTimeStamp();

      //a timestamp is never < 0! this case happens only if you are using the timestamp of the nd object instead of getting a new one
      if (timestamp >= 0)
      {
        TiXmlElement* elem = new TiXmlElement("ND");

        elem->SetDoubleAttribute("Time", timestamp);
        elem->SetDoubleAttribute("Tool", index);
        elem->SetDoubleAttribute("X", position[0]);
        elem->SetDoubleAttribute("Y", position[1]);
        elem->SetDoubleAttribute("Z", position[2]);

        elem->SetDoubleAttribute("QX", orientation[0]);
        elem->SetDoubleAttribute("QY", orientation[1]);
        elem->SetDoubleAttribute("QZ", orientation[2]);
        elem->SetDoubleAttribute("QR", orientation[3]);

        elem->SetDoubleAttribute("C00", matrix[0][0]);
        elem->SetDoubleAttribute("C01", matrix[0][1]);
        elem->SetDoubleAttribute("C02", matrix[0][2]);
        elem->SetDoubleAttribute("C03", matrix[0][3]);
        elem->SetDoubleAttribute("C04", matrix[0][4]);
        elem->SetDoubleAttribute("C05", matrix[0][5]);
        elem->SetDoubleAttribute("C10", matrix[1][0]);
        elem->SetDoubleAttribute("C11", matrix[1][1]);
        elem->SetDoubleAttribute("C12", matrix[1][2]);
        elem->SetDoubleAttribute("C13", matrix[1][3]);
        elem->SetDoubleAttribute("C14", matrix[1][4]);
        elem->SetDoubleAttribute("C15", matrix[1][5]);

        if (dataValid)
          elem->SetAttribute("Valid",1);
        else
          elem->SetAttribute("Valid",0);

        if (hasOrientation)
          elem->SetAttribute("hO",1);
        else
          elem->SetAttribute("hO",0);

        if (hasPosition)
          elem->SetAttribute("hP",1);
        else
          elem->SetAttribute("hP",0);

        *m_Stream << "        " << *elem << std::endl;

        delete elem;
      }
    }
  }
}

void mitk::NavigationDataRecorder::StartRecording()
{
  if (m_Recording)
  {
    std::cout << "Already recording please stop before start new recording session" << std::endl;
    return;
  }
  if (m_Stream == NULL)
  {
    std::stringstream ss;
    std::ostream* stream;

    //An existing extension will be cut and replaced with .xml
    std::string tmpPath = itksys::SystemTools::GetFilenamePath(m_FileName);
    m_FileName = itksys::SystemTools::GetFilenameWithoutExtension(m_FileName);
    ss << tmpPath << "/" <<  m_FileName << "-" << m_NumberOfRecordedFiles << ".xml";
    switch(m_RecordingMode)
    {
      case Console:
        stream = &std::cout;
        break;
      case NormalFile:

        //Check if there is a file name and path
        if (m_FileName == "")
        {
          stream = &std::cout;
          std::cout << "No file name or file path set the output is redirected to the console";
        }
        else
        {
          stream = new std::ofstream(ss.str().c_str());
        }

        break;
      case ZipFile:
        stream = &std::cout;
        std::cout << "Sorry no ZipFile support yet";
        break;
      default:
        stream = &std::cout;
        break;
    }
    StartRecording(stream);
  }

}
void mitk::NavigationDataRecorder::StartRecording(std::ostream* stream)
{
  if (m_Recording)
  {
    std::cout << "Already recording please stop before start new recording session" << std::endl;
    return;
  }

  m_Stream = stream;
  m_Stream->precision(10);

  //TODO store date and GMT time
  if (m_Stream)
  {
    *m_Stream << "<?xml version=\"1.0\" ?>" << std::endl;
    *m_Stream << "<Version Ver=\"1\" />" << std::endl;
    *m_Stream << "    " << "<Data ToolCount=\"" << (m_NumberOfInputs) << "\">" << std::endl;

    m_Recording = true;
  }
}
void mitk::NavigationDataRecorder::StopRecording()
{
  if (!m_Recording)
  {
    std::cout << "You have to start a recording first" << std::endl;
    return;
  }
  if (m_Stream)
  {
    *m_Stream << "</Data>" << std::endl;
  }

  m_NumberOfRecordedFiles++;
  m_Stream = NULL;
  m_Recording = false;
}<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationToolStorage.h"
#include "mitkNavigationTool.h"
#include "mitkCommon.h"
#include "mitkTestingMacros.h"

class mitkNavigationToolStorageTestClass
  {
  public:

    static void TestInstantiation()
    {
    // let's create an object of our class
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    MITK_TEST_CONDITION_REQUIRED(myStorage.IsNotNull(),"Testing instantiation")
    }

    static void TestAddAndDelete()
    {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //first tool
    mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
    myTool1->SetIdentifier("001");
    MITK_TEST_CONDITION_REQUIRED(myStorage->AddTool(myTool1),"Testing: Add 1st tool.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==1,"Testing: Is first tool in storage?");

    //second tool
    mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
    myTool2->SetIdentifier("002");
    MITK_TEST_CONDITION_REQUIRED(myStorage->AddTool(myTool2),"Testing: Add 2nd tool.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==2,"Testing: Is second tool in storage?");

    //third tool (same identifier => not valid!)
    mitk::NavigationTool::Pointer myTool3 = mitk::NavigationTool::New();
    myTool3->SetIdentifier("002");
    MITK_TEST_CONDITION_REQUIRED(!myStorage->AddTool(myTool3),"Testing: Add 3rd tool, which is not valid.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==2,"Testing: 3rd tool should NOT be in the storage!");

    //delete second tool
    myStorage->DeleteTool(1);
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==1,"Testing: Delete 2nd tool.");

    //delete first tool
    myStorage->DeleteTool(0);
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==0,"Testing: Delete 1st tool.");

    //delete tool with wrong tool number
    MITK_TEST_CONDITION_REQUIRED(!myStorage->DeleteTool(412),"Testing: Delete non-existing tool. No error should occur!");
    }

    static void TestAddAndDelete100Tools()
    {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    for(int i=0; i<100; i++)
      {
      mitk::NavigationTool::Pointer myTool = mitk::NavigationTool::New();
      std::stringstream str;
      str << i;
      myTool->SetIdentifier(str.str());
      myStorage->AddTool(myTool);
      }
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==100,"Testing: Adding 100 tools.");
    for(int i=99; i>-1; i--)
      {
      myStorage->DeleteTool(i);
      }
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==0,"Testing: Delete 100 tools.");
    }

    static void TestGetTool()
    {
    //let's create an object of our class
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //let's add two different tools
    //first tool
    mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
    myTool1->SetSerialNumber("0815");
    myTool1->SetIdentifier("001");
    myStorage->AddTool(myTool1);

    //second tool
    mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
    myTool2->SetSerialNumber("0816");
    myTool2->SetIdentifier("002");
    myStorage->AddTool(myTool2);

    //let's try to get the first tool in different ways.
    mitk::NavigationTool::Pointer myToolGet = myStorage->GetTool(0);
    MITK_TEST_CONDITION_REQUIRED(myToolGet==myTool1,"Testing GetTool() by number.");
    myToolGet = myStorage->GetTool("001");
    MITK_TEST_CONDITION_REQUIRED(myToolGet==myTool1,"Testing GetTool() by identifier.");
    }
  };

/** This function is testing the TrackingVolume class. */
int mitkNavigationToolStorageTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("NavigationToolStorage")

  mitkNavigationToolStorageTestClass::TestInstantiation();
  mitkNavigationToolStorageTestClass::TestAddAndDelete();
  mitkNavigationToolStorageTestClass::TestAddAndDelete100Tools();
  mitkNavigationToolStorageTestClass::TestGetTool();

  MITK_TEST_END()
}

<commit_msg>improved test, test coverage should be 100% now<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationToolStorage.h"
#include "mitkNavigationTool.h"
#include "mitkCommon.h"
#include "mitkTestingMacros.h"

class mitkNavigationToolStorageTestClass
  {
  public:

    static void TestInstantiation()
    {
    // let's create an object of our class
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    MITK_TEST_CONDITION_REQUIRED(myStorage.IsNotNull(),"Testing instantiation")
    }

    static void TestAddAndDelete()
    {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //first tool
    mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
    myTool1->SetIdentifier("001");
    MITK_TEST_CONDITION_REQUIRED(myStorage->AddTool(myTool1),"Testing: Add 1st tool.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==1,"Testing: Is first tool in storage?");

    //second tool
    mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
    myTool2->SetIdentifier("002");
    MITK_TEST_CONDITION_REQUIRED(myStorage->AddTool(myTool2),"Testing: Add 2nd tool.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==2,"Testing: Is second tool in storage?");

    //third tool (same identifier => not valid!)
    mitk::NavigationTool::Pointer myTool3 = mitk::NavigationTool::New();
    myTool3->SetIdentifier("002");
    MITK_TEST_CONDITION_REQUIRED(!myStorage->AddTool(myTool3),"Testing: Add 3rd tool, which is not valid.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==2,"Testing: 3rd tool should NOT be in the storage!");

    //delete second tool
    myStorage->DeleteTool(1);
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==1,"Testing: Delete 2nd tool.");

    //delete first tool
    myStorage->DeleteTool(0);
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==0,"Testing: Delete 1st tool.");

    //delete tool with wrong tool number
    MITK_TEST_CONDITION_REQUIRED(!myStorage->DeleteTool(412),"Testing: Delete non-existing tool. No error should occur!");
    }

    static void TestAddAndDelete100Tools()
    {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    for(int i=0; i<100; i++)
      {
      mitk::NavigationTool::Pointer myTool = mitk::NavigationTool::New();
      std::stringstream str;
      str << i;
      myTool->SetIdentifier(str.str());
      myStorage->AddTool(myTool);
      }
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==100,"Testing: Adding 100 tools.");
    for(int i=99; i>-1; i--)
      {
      myStorage->DeleteTool(i);
      }
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==0,"Testing: Delete 100 tools.");
    }

    static void TestAddAndDelete100ToolsAtOnce()
    {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    for(int i=0; i<100; i++)
      {
      mitk::NavigationTool::Pointer myTool = mitk::NavigationTool::New();
      std::stringstream str;
      str << i;
      myTool->SetIdentifier(str.str());
      myStorage->AddTool(myTool);
      }
    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==100,"Testing: Adding 100 tools.");
    MITK_TEST_CONDITION_REQUIRED(!myStorage->isEmpty(),"Testing: method isEmpty() with non empty storage.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->DeleteAllTools(),"Testing: Delete method.");
    MITK_TEST_CONDITION_REQUIRED(myStorage->isEmpty(),"Testing: method isEmpty() with empty storage.");

    MITK_TEST_CONDITION_REQUIRED(myStorage->GetToolCount()==0,"Testing: Delete 100 tools at once.");
    }

    static void TestGetTool()
    {
    //let's create an object of our class
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //let's add two different tools
    //first tool
    mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
    myTool1->SetSerialNumber("0815");
    myTool1->SetIdentifier("001");
    mitk::DataNode::Pointer toolNode = mitk::DataNode::New();
    toolNode->SetName("Tool1");
    myTool1->SetDataNode(toolNode);
    myStorage->AddTool(myTool1);

    //second tool
    mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
    myTool2->SetSerialNumber("0816");
    myTool2->SetIdentifier("002");
    myStorage->AddTool(myTool2);

    //let's try to get the first tool in different ways.
    mitk::NavigationTool::Pointer myToolGet = myStorage->GetTool(0);
    MITK_TEST_CONDITION_REQUIRED(myToolGet==myTool1,"Testing GetTool() by number.");
    myToolGet = myStorage->GetTool("001");
    MITK_TEST_CONDITION_REQUIRED(myToolGet==myTool1,"Testing GetTool() by identifier.");
    myToolGet = myStorage->GetToolByName("Tool1");
    MITK_TEST_CONDITION_REQUIRED(myToolGet==myTool1,"Testing GetTool() by name.");

    //let's try to get a tool which doesn't exist
    myToolGet = myStorage->GetToolByName("quatsch");
    MITK_TEST_CONDITION_REQUIRED(myToolGet.IsNull(),"Testing GetTool() with wrong name.");
    }
  };

/** This function is testing the TrackingVolume class. */
int mitkNavigationToolStorageTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("NavigationToolStorage")

  mitkNavigationToolStorageTestClass::TestInstantiation();
  mitkNavigationToolStorageTestClass::TestAddAndDelete();
  mitkNavigationToolStorageTestClass::TestAddAndDelete100Tools();
  mitkNavigationToolStorageTestClass::TestAddAndDelete100ToolsAtOnce();
  mitkNavigationToolStorageTestClass::TestGetTool();

  MITK_TEST_END()
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2006-2007 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include <cstring>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include "printer.hh"
#include "tracechild.hh"

using namespace std;

void printUsage(const char * execName)
{
    cout << execName << " -h | -r -- <command> <arguments>" << endl;
}

int main(int argc, char * argv[], char * envp[])
{
    TraceChild * child = genTraceChild();
    string args;
    int startProgramArgs;

    //Parse the command line arguments
    bool printInitial = false;
    bool printTrace = true;
    for(int x = 1; x < argc; x++)
    {
        if(!strcmp(argv[x], "-h"))
        {
            printUsage(argv[0]);
            return 0;
        }
        else if(!strcmp(argv[x], "-r"))
        {
            cout << "Legal register names:" << endl;
            int numRegs = child->getNumRegs();
            for(unsigned int x = 0; x < numRegs; x++)
            {
                cout << "\t" << child->getRegName(x) << endl;
            }
            return 0;
        }
        else if(!strcmp(argv[x], "-i"))
        {
            printInitial = true;
        }
        else if(!strcmp(argv[x], "-nt"))
        {
            printTrace = false;
        }
        else if(!strcmp(argv[x], "--"))
        {
            x++;
            if(x >= argc)
            {
                cerr << "Incorrect usage.\n" << endl;
                printUsage(argv[0]);
                return 1;
            }
            startProgramArgs = x;
            break;
        }
        else
        {
            cerr << "Incorrect usage.\n" << endl;
            printUsage(argv[0]);
            return 1;
        }
    }
    if(!child->startTracing(argv[startProgramArgs],
                argv + startProgramArgs))
    {
        cerr << "Couldn't start target program" << endl;
        return 1;
    }
    if(printInitial)
    {
        child->outputStartState(cout);
    }
    if(printTrace)
    {
        // Connect to m5
        bool portSet = false;
        int port;
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            cerr << "Error opening socket! " << strerror(errno) << endl;
            return 1;
        }
        struct hostent *server;
        server = gethostbyname("localhost");
        if(!server)
        {
            cerr << "Couldn't get host ip! " << strerror(errno) << endl;
            return 1;
        }
        struct sockaddr_in serv_addr;
        bzero((char *)&serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        bcopy((char *)server->h_addr,
                (char *)&serv_addr.sin_addr.s_addr,
                server->h_length);
        serv_addr.sin_port = htons(8000);
        if(connect(sock, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        {
            cerr << "Couldn't connect to server! " << strerror(errno) << endl;
            return 1;
        }
        child->step();
        while(child->isTracing())
        {
                if(!child->sendState(sock))
                    break;
                child->step();
        }
    }
    if(!child->stopTracing())
    {
            cerr << "Couldn't stop child" << endl;
            return 1;
    }
    return 0;
}

<commit_msg>imported patch statetracehost.patch<commit_after>/*
 * Copyright (c) 2006-2007 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include <cstring>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include "printer.hh"
#include "tracechild.hh"

using namespace std;

void printUsage(const char * execName)
{
    cout << execName << " -h | -r -- <command> <arguments>" << endl;
}

int main(int argc, char * argv[], char * envp[])
{
    TraceChild * child = genTraceChild();
    string args;
    int startProgramArgs;

    //Parse the command line arguments
    bool printInitial = false;
    bool printTrace = true;
    string host = "localhost";
    for(int x = 1; x < argc; x++)
    {
        if(!strcmp(argv[x], "-h"))
        {
            printUsage(argv[0]);
            return 0;
        }
        if(!strcmp(argv[x], "--host"))
        {
            x++;
            if(x >= argc)
            {
                cerr << "Incorrect usage.\n" << endl;
                printUsage(argv[0]);
                return 1;
            }
            host = argv[x];
        }
        else if(!strcmp(argv[x], "-r"))
        {
            cout << "Legal register names:" << endl;
            int numRegs = child->getNumRegs();
            for(unsigned int x = 0; x < numRegs; x++)
            {
                cout << "\t" << child->getRegName(x) << endl;
            }
            return 0;
        }
        else if(!strcmp(argv[x], "-i"))
        {
            printInitial = true;
        }
        else if(!strcmp(argv[x], "-nt"))
        {
            printTrace = false;
        }
        else if(!strcmp(argv[x], "--"))
        {
            x++;
            if(x >= argc)
            {
                cerr << "Incorrect usage.\n" << endl;
                printUsage(argv[0]);
                return 1;
            }
            startProgramArgs = x;
            break;
        }
        else
        {
            cerr << "Incorrect usage.\n" << endl;
            printUsage(argv[0]);
            return 1;
        }
    }
    if(!child->startTracing(argv[startProgramArgs],
                argv + startProgramArgs))
    {
        cerr << "Couldn't start target program" << endl;
        return 1;
    }
    if(printInitial)
    {
        child->outputStartState(cout);
    }
    if(printTrace)
    {
        // Connect to m5
        bool portSet = false;
        int port;
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            cerr << "Error opening socket! " << strerror(errno) << endl;
            return 1;
        }
        struct hostent *server;
        server = gethostbyname(host.c_str());
        if(!server)
        {
            cerr << "Couldn't get host ip! " << strerror(errno) << endl;
            return 1;
        }
        struct sockaddr_in serv_addr;
        bzero((char *)&serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        bcopy((char *)server->h_addr,
                (char *)&serv_addr.sin_addr.s_addr,
                server->h_length);
        serv_addr.sin_port = htons(8000);
        if(connect(sock, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        {
            cerr << "Couldn't connect to server! " << strerror(errno) << endl;
            return 1;
        }
        child->step();
        while(child->isTracing())
        {
                if(!child->sendState(sock))
                    break;
                child->step();
        }
    }
    if(!child->stopTracing())
    {
            cerr << "Couldn't stop child" << endl;
            return 1;
    }
    return 0;
}

<|endoftext|>


<commit_before><commit_msg>cosPAV0 -> cpaV0Min<commit_after><|endoftext|>


<commit_before>// coding: utf-8
/* Copyright (c) 2009, Roboterclub Aachen e.V.
 * All Rights Reserved.
 *
 * The file is part of the xpcc library and is released under the 3-clause BSD
 * license. See the file `LICENSE` for the full license governing this code.
 */
// ----------------------------------------------------------------------------

#ifndef	XPCC_TIMESTAMP_HPP
#define	XPCC_TIMESTAMP_HPP

#include <stdint.h>

#include <xpcc/io/iostream.hpp>
#include <xpcc/utils/arithmetic_traits.hpp>

namespace xpcc
{

/**
 * Generic timestamp for 16bit and 32bit timestamps of variable timebase.
 *
 * @author	Fabian Greif
 * @author	Niklas Hauser
 * @ingroup	processing
 */
template< typename T >
class GenericTimestamp
{
public:
	typedef T Type;
	typedef typename xpcc::ArithmeticTraits<T>::SignedType SignedType;

public:
	/// @param time in ms
	GenericTimestamp(const Type time = 0) :
		time(time)
	{
	}

	GenericTimestamp(const GenericTimestamp<T> &other) :
		time(other.time)
	{
	}

	inline Type
	getTime() const
	{
		return time;
	}

	inline GenericTimestamp<T>
	operator + (const GenericTimestamp<T>& other) const
	{
		return GenericTimestamp<T>(time + other.time);
	}

	inline GenericTimestamp<T>
	operator - (const GenericTimestamp<T>& other) const
	{
		return GenericTimestamp<T>(time - other.time);
	}

	inline bool
	operator == (const GenericTimestamp<T>& other) const
	{
		return (time == other.time);
	}

	inline bool
	operator != (const GenericTimestamp<T>& other) const
	{
		return (time != other.time);
	}

	inline bool
	operator < (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) < 0;
	}

	inline bool
	operator > (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) > 0;
	}

	inline bool
	operator <= (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) <= 0;
	}

	inline bool
	operator >= (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) >= 0;
	}

private:
	Type time;
};

/// 16bit timestamp, which can hold up to 65 seconds at millisecond resolution.
using ShortTimestamp = GenericTimestamp<uint_fast16_t>;

/// 32bit timestamp, which can hold up to 49 days at millisecond resolution.
using Timestamp      = GenericTimestamp<uint32_t>;

// ------------------------------------------------------------------------
template< typename T >
inline IOStream&
operator << (IOStream& os, const GenericTimestamp<T>& t)
{
	os << t.getTime();
	return os;
}

}	// namespace xpcc

#endif	// XPCC_TIMESTAMP_HPP
<commit_msg>Processing: Use uint16_t for ShortTimestamp.<commit_after>// coding: utf-8
/* Copyright (c) 2009, Roboterclub Aachen e.V.
 * All Rights Reserved.
 *
 * The file is part of the xpcc library and is released under the 3-clause BSD
 * license. See the file `LICENSE` for the full license governing this code.
 */
// ----------------------------------------------------------------------------

#ifndef	XPCC_TIMESTAMP_HPP
#define	XPCC_TIMESTAMP_HPP

#include <stdint.h>

#include <xpcc/io/iostream.hpp>
#include <xpcc/utils/arithmetic_traits.hpp>

namespace xpcc
{

/**
 * Generic timestamp for 16bit and 32bit timestamps of variable timebase.
 *
 * @author	Fabian Greif
 * @author	Niklas Hauser
 * @ingroup	processing
 */
template< typename T >
class GenericTimestamp
{
public:
	typedef T Type;
	typedef typename xpcc::ArithmeticTraits<T>::SignedType SignedType;

public:
	/// @param time in ms
	GenericTimestamp(const Type time = 0) :
		time(time)
	{
	}

	GenericTimestamp(const GenericTimestamp<T> &other) :
		time(other.time)
	{
	}

	inline Type
	getTime() const
	{
		return time;
	}

	inline GenericTimestamp<T>
	operator + (const GenericTimestamp<T>& other) const
	{
		return GenericTimestamp<T>(time + other.time);
	}

	inline GenericTimestamp<T>
	operator - (const GenericTimestamp<T>& other) const
	{
		return GenericTimestamp<T>(time - other.time);
	}

	inline bool
	operator == (const GenericTimestamp<T>& other) const
	{
		return (time == other.time);
	}

	inline bool
	operator != (const GenericTimestamp<T>& other) const
	{
		return (time != other.time);
	}

	inline bool
	operator < (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) < 0;
	}

	inline bool
	operator > (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) > 0;
	}

	inline bool
	operator <= (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) <= 0;
	}

	inline bool
	operator >= (const GenericTimestamp<T>& other) const
	{
		return SignedType(time - other.time) >= 0;
	}

private:
	Type time;
};

/// 16bit timestamp, which can hold up to 65 seconds at millisecond resolution.
using ShortTimestamp = GenericTimestamp<uint16_t>;

/// 32bit timestamp, which can hold up to 49 days at millisecond resolution.
using Timestamp      = GenericTimestamp<uint32_t>;

// ------------------------------------------------------------------------
template< typename T >
inline IOStream&
operator << (IOStream& os, const GenericTimestamp<T>& t)
{
	os << t.getTime();
	return os;
}

}	// namespace xpcc

#endif	// XPCC_TIMESTAMP_HPP
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: quadtree.hh 17 2005-03-08 23:58:43Z pavlenko $

#ifndef QUADTREE_HPP
#define QUADTREE_HPP
// stl
#include <vector>
#include <fstream>
// mapnik
#include <mapnik/envelope.hpp>

using mapnik::Envelope;
using mapnik::coord2d;

template <typename T>
struct quadtree_node
{
      Envelope<double> ext_;
      std::vector<T> data_;
      quadtree_node<T>* children_[4];
      quadtree_node(const Envelope<double>& ext)
         : ext_(ext),data_()
      {
         memset(children_,0,sizeof(quadtree_node<T>*)*4);
      }

      ~quadtree_node()
      {
         for (int i=0;i<4;++i)
         {
            if (children_[i])
            {
               delete children_[i],children_[i]=0;
            }
         }
      }

      int num_subnodes() const
      {
         int count=0;
         for (int i=0;i<4;++i)
         {
            if (children_[i])
            {
               ++count;
            }
         }
         return count;
      }
};

template <typename T>
class quadtree
{
private:
    quadtree_node<T>* root_;
    const int maxdepth_;
    const double ratio_;
public:
    quadtree(const Envelope<double>& extent,int maxdepth,double ratio)
        : root_(new quadtree_node<T>(extent)),
          maxdepth_(maxdepth),
          ratio_(ratio) {}

    ~quadtree()
    {
        if (root_) delete root_;
    }

    void insert(const T& data,const Envelope<double>& item_ext)
    {
        insert(data,item_ext,root_,maxdepth_);
    }

    int count() const
    {
        return count_nodes(root_);
    }

    int count_items() const
    {
        int count=0;
        count_items(root_,count);
        return count;
    }

    void print() const
    {
        print(root_);
    }

    void trim()
    {
        trim_tree(root_);
    }

    void write(std::ostream& out)
    {
        char header[16];
        memset(header,0,16);
        header[0]='m';
        header[1]='a';
        header[2]='p';
        header[4]='n';
        header[5]='i';
        header[6]='k';
        out.write(header,16);
        write_node(out,root_);
    }

private:

    void trim_tree(quadtree_node<T>*&  node)
    {
        if (node)
        {
            for (int i=0;i<4;++i)
            {
                trim_tree(node->children_[i]);
            }

            if (node->num_subnodes()==1 && node->data_.size()==0)
            {
                for (int i=0;i<4;++i)
                {
                    if (node->children_[i])
                    {
                        node=node->children_[i];
                        break;
                    }
                }
            }
        }
    }

    int count_nodes(const quadtree_node<T>*  node) const
    {
        if (!node)
        {
            return 0;
        }
        else
        {
            int count = 1;
            for (int i=0;i<4;++i)
            {
                count += count_nodes(node->children_[i]);
            }
            return count;
        }
    }

    void count_items(const quadtree_node<T>* node,int& count) const
    {
        if (node)
        {
            count += node->data_.size();
            for (int i=0;i<4;++i)
            {
                count_items(node->children_[i],count);
            }
        }
    }

    int subnode_offset(const quadtree_node<T>* node) const
    {
        int offset=0;
        for (int i=0;i<4;i++)
        {
            if (node->children_[i])
            {
                offset +=sizeof(Envelope<double>)+(node->children_[i]->data_.size()*sizeof(T))+3*sizeof(int);
                offset +=subnode_offset(node->children_[i]);
            }
        }
        return offset;
    }

    void write_node(std::ostream& out,const quadtree_node<T>* node) const
    {
        if (node)
        {
            int offset=subnode_offset(node);
            int shape_count=node->data_.size();
            int recsize=sizeof(Envelope<double>) + 3 * sizeof(int) + shape_count * sizeof(T);
            char* node_record=new char[recsize];
            memset(node_record,0,recsize);
            memcpy(node_record,&offset,4);
            memcpy(node_record+4,&node->ext_,sizeof(Envelope<double>));
            memcpy(node_record+36,&shape_count,4);
            for (int i=0;i<shape_count;++i)
            {
                memcpy(node_record + 40 + i * sizeof(T),&(node->data_[i]),sizeof(T));
            }
            int num_subnodes=0;
            for (int i=0;i<4;++i)
            {
                if (node->children_[i])
                {
                    ++num_subnodes;
                }
            }
            memcpy(node_record + 40 + shape_count * sizeof(T),&num_subnodes,4);
            out.write(node_record,recsize);
            delete [] node_record;

            for (int i=0;i<4;++i)
            {
                write_node(out,node->children_[i]);
            }
        }
    }

    void print(const quadtree_node<T>* node,int level=0) const
    {
        if (node)
        {
            typename std::vector<T>::const_iterator itr=node->data_.begin();
            std::string pad;
            for (int i=0;i<level;++i)
            {
                pad+=" ";
            }
            std::clog<<pad<<"node "<<node<<" extent:"<<node->ext_<<std::endl;
            std::clog<<pad;
            while(itr!=node->data_.end())
            {
                std::clog<<*itr<<" ";
                ++itr;
            }
            std::clog<<std::endl;
            for (int i=0;i<4;++i)
            {
                print(node->children_[i],level+4);
            }
        }
    }

    void insert(const T& data,const Envelope<double>& item_ext,quadtree_node<T>*  node,int maxdepth)
    {
        if (node && node->ext_.contains(item_ext))
        {
            coord2d c=node->ext_.center();

            double width=node->ext_.width();
            double height=node->ext_.height();

            double lox=node->ext_.minx();
            double loy=node->ext_.miny();
            double hix=node->ext_.maxx();
            double hiy=node->ext_.maxy();

            Envelope<double> ext[4];
            ext[0]=Envelope<double>(lox,loy,lox + width * ratio_,loy + height * ratio_);
            ext[1]=Envelope<double>(hix - width * ratio_,loy,hix,loy + height * ratio_);
            ext[2]=Envelope<double>(lox,hiy - height*ratio_,lox + width * ratio_,hiy);
            ext[3]=Envelope<double>(hix - width * ratio_,hiy - height*ratio_,hix,hiy);

            if (maxdepth > 1)
            {
                for (int i=0;i<4;++i)
                {
                    if (ext[i].contains(item_ext))
                    {
                        if (!node->children_[i])
                        {
                            node->children_[i]=new quadtree_node<T>(ext[i]);
                        }
                        insert(data,item_ext,node->children_[i],maxdepth-1);
                        return;
                    }
                }
            }
            node->data_.push_back(data);
        }
    }
};
#endif //QUADTREE_HPP
<commit_msg>small fix<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: quadtree.hh 17 2005-03-08 23:58:43Z pavlenko $

#ifndef QUADTREE_HPP
#define QUADTREE_HPP
// stl
#include <vector>
#include <fstream>
// mapnik
#include <mapnik/envelope.hpp>

using mapnik::Envelope;
using mapnik::coord2d;

template <typename T>
struct quadtree_node
{
      Envelope<double> ext_;
      std::vector<T> data_;
      quadtree_node<T>* children_[4];
      quadtree_node(const Envelope<double>& ext)
         : ext_(ext),data_()
      {
         memset(children_,0,sizeof(quadtree_node<T>*)*4);
      }

      ~quadtree_node()
      {
         for (int i=0;i<4;++i)
         {
            if (children_[i])
            {
               delete children_[i],children_[i]=0;
            }
         }
      }

      int num_subnodes() const
      {
         int count=0;
         for (int i=0;i<4;++i)
         {
            if (children_[i])
            {
               ++count;
            }
         }
         return count;
      }
};

template <typename T>
class quadtree
{
private:
    quadtree_node<T>* root_;
    const int maxdepth_;
    const double ratio_;
public:
    quadtree(const Envelope<double>& extent,int maxdepth,double ratio)
        : root_(new quadtree_node<T>(extent)),
          maxdepth_(maxdepth),
          ratio_(ratio) {}

    ~quadtree()
    {
        if (root_) delete root_;
    }

    void insert(const T& data,const Envelope<double>& item_ext)
    {
        insert(data,item_ext,root_,maxdepth_);
    }

    int count() const
    {
        return count_nodes(root_);
    }

    int count_items() const
    {
        int count=0;
        count_items(root_,count);
        return count;
    }

    void print() const
    {
        print(root_);
    }

    void trim()
    {
        trim_tree(root_);
    }

    void write(std::ostream& out)
    {
        char header[16];
        memset(header,0,16);
        header[0]='m';
        header[1]='a';
        header[2]='p';
        header[3]='n';
        header[4]='i';
        header[5]='k';
        out.write(header,16);
        write_node(out,root_);
    }

private:

    void trim_tree(quadtree_node<T>*&  node)
    {
        if (node)
        {
            for (int i=0;i<4;++i)
            {
                trim_tree(node->children_[i]);
            }

            if (node->num_subnodes()==1 && node->data_.size()==0)
            {
                for (int i=0;i<4;++i)
                {
                    if (node->children_[i])
                    {
                        node=node->children_[i];
                        break;
                    }
                }
            }
        }
    }

    int count_nodes(const quadtree_node<T>*  node) const
    {
        if (!node)
        {
            return 0;
        }
        else
        {
            int count = 1;
            for (int i=0;i<4;++i)
            {
                count += count_nodes(node->children_[i]);
            }
            return count;
        }
    }

    void count_items(const quadtree_node<T>* node,int& count) const
    {
        if (node)
        {
            count += node->data_.size();
            for (int i=0;i<4;++i)
            {
                count_items(node->children_[i],count);
            }
        }
    }

    int subnode_offset(const quadtree_node<T>* node) const
    {
        int offset=0;
        for (int i=0;i<4;i++)
        {
            if (node->children_[i])
            {
                offset +=sizeof(Envelope<double>)+(node->children_[i]->data_.size()*sizeof(T))+3*sizeof(int);
                offset +=subnode_offset(node->children_[i]);
            }
        }
        return offset;
    }

    void write_node(std::ostream& out,const quadtree_node<T>* node) const
    {
        if (node)
        {
            int offset=subnode_offset(node);
            int shape_count=node->data_.size();
            int recsize=sizeof(Envelope<double>) + 3 * sizeof(int) + shape_count * sizeof(T);
            char* node_record=new char[recsize];
            memset(node_record,0,recsize);
            memcpy(node_record,&offset,4);
            memcpy(node_record+4,&node->ext_,sizeof(Envelope<double>));
            memcpy(node_record+36,&shape_count,4);
            for (int i=0;i<shape_count;++i)
            {
                memcpy(node_record + 40 + i * sizeof(T),&(node->data_[i]),sizeof(T));
            }
            int num_subnodes=0;
            for (int i=0;i<4;++i)
            {
                if (node->children_[i])
                {
                    ++num_subnodes;
                }
            }
            memcpy(node_record + 40 + shape_count * sizeof(T),&num_subnodes,4);
            out.write(node_record,recsize);
            delete [] node_record;

            for (int i=0;i<4;++i)
            {
                write_node(out,node->children_[i]);
            }
        }
    }

    void print(const quadtree_node<T>* node,int level=0) const
    {
        if (node)
        {
            typename std::vector<T>::const_iterator itr=node->data_.begin();
            std::string pad;
            for (int i=0;i<level;++i)
            {
                pad+=" ";
            }
            std::clog<<pad<<"node "<<node<<" extent:"<<node->ext_<<std::endl;
            std::clog<<pad;
            while(itr!=node->data_.end())
            {
                std::clog<<*itr<<" ";
                ++itr;
            }
            std::clog<<std::endl;
            for (int i=0;i<4;++i)
            {
                print(node->children_[i],level+4);
            }
        }
    }

    void insert(const T& data,const Envelope<double>& item_ext,quadtree_node<T>*  node,int maxdepth)
    {
        if (node && node->ext_.contains(item_ext))
        {
            coord2d c=node->ext_.center();

            double width=node->ext_.width();
            double height=node->ext_.height();

            double lox=node->ext_.minx();
            double loy=node->ext_.miny();
            double hix=node->ext_.maxx();
            double hiy=node->ext_.maxy();

            Envelope<double> ext[4];
            ext[0]=Envelope<double>(lox,loy,lox + width * ratio_,loy + height * ratio_);
            ext[1]=Envelope<double>(hix - width * ratio_,loy,hix,loy + height * ratio_);
            ext[2]=Envelope<double>(lox,hiy - height*ratio_,lox + width * ratio_,hiy);
            ext[3]=Envelope<double>(hix - width * ratio_,hiy - height*ratio_,hix,hiy);

            if (maxdepth > 1)
            {
                for (int i=0;i<4;++i)
                {
                    if (ext[i].contains(item_ext))
                    {
                        if (!node->children_[i])
                        {
                            node->children_[i]=new quadtree_node<T>(ext[i]);
                        }
                        insert(data,item_ext,node->children_[i],maxdepth-1);
                        return;
                    }
                }
            }
            node->data_.push_back(data);
        }
    }
};
#endif //QUADTREE_HPP
<|endoftext|>


<commit_before><commit_msg>ditch last XubString in starmath<commit_after><|endoftext|>