<commit_before>///////////////////////////////////////////////////////////////////
//                                                               //
// AddCaloHFEpp                                                  //
// Author: T. Suzuki Univ. of Tsukuba                            //
//                                                               //
///////////////////////////////////////////////////////////////////
class AliAnalysisDataContainer;

AliAnalysisTaskCaloHFEpp* AddTaskCaloHFEpp(TString name = "name",
		                 TString dataname = "dataname",
		                 Bool_t flagEG1,
		                 Bool_t flagEG2,
		                 Bool_t flagDG1,
		                 Bool_t flagDG2,
		                 Bool_t SetFlagClsTypeEMC,
		                 Bool_t SetFlagClsTypeDCAL,
		                 Bool_t fMC,
										 Double_t TrackEtaMin,
										 Double_t TrackEtaMax,
										 Int_t NTPCClust,
										 Int_t NITSClust,
										 Int_t NCrossedRow,
										 Double_t DCAxy,
										 Double_t DCAz,
										 Double_t NsigmaMin,
										 Double_t NsigmaMax,
										 Double_t M20Min,
										 Double_t M20Max,
										 Double_t EopMin,
										 Double_t EopMax,
										 Double_t coneR,
										 Double_t ptAsso,
										 TString  pte = "pte",
										 Double_t MassMin)
{
    // get the manager via the static access member. since it's static, you don't need
    // an instance of the class to call the function
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    // get the input event handler, again via a static method.
    // this handler is part of the managing system and feeds events
    // to your task
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }

		//-------------------------------------------
		gROOT->LoadMacro("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C");
		gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");

		AddTaskPhysicsSelection(fMC,true); // IsMC true for MC !!!, second argument is for pileup removal which is very important.
		AliMultSelectionTask * Multtask = AddTaskMultSelection(true); // argument is true if you need to run on calibration and this task should be called after the physics selection!!!!
		Multtask->SetAlternateOADBforEstimators(dataname.Data()); // for MC, if there is no calibration then you can specify here the alternate default calibration to be used.
		if(fMC)Multtask->SetUseDefaultMCCalib(kTRUE); // MC
		if(!fMC)Multtask->SetUseDefaultCalib(kTRUE); // data
		//-------------------------------------------

		// by default, a file is open for writing. here, we get the filename
		TString fileName = AliAnalysisManager::GetCommonFileName();
    fileName += ":CaloHFEpp";      // create a subfolder in the file
    // now we create an instance of your task
    AliAnalysisTaskCaloHFEpp* task = new AliAnalysisTaskCaloHFEpp(name.Data());
    task -> SetEG1(flagEG1);
    task -> SetEG2(flagEG2);
    task -> SetDG1(flagDG1);
    task -> SetDG2(flagDG2);
    task -> SetfFlagClsTypeEMC(SetFlagClsTypeEMC);
    task -> SetfFlagClsTypeDCAL(SetFlagClsTypeDCAL);

		task -> SetTrackEta(TrackEtaMin,TrackEtaMax);
		task -> SetTrackClust(NTPCClust,NITSClust,NCrossedRow);
		task -> SetDCA(DCAxy,DCAz);
		task -> SetNsigma(NsigmaMin,NsigmaMax);
		task -> SetM20(M20Min,M20Max);
		task -> SetEop(EopMin,EopMax);
		task -> SetConeR(coneR);
		task -> SetptAsso(ptAsso);
		task -> SetptCut(pte);
		task -> SetMassMin(MassMin);
    if(!task) return 0x0;

    // add your task to the manager
    mgr->AddTask(task);

    TString containerName = mgr->GetCommonFileName();
    containerName += ":PWGHF_hfeCalpp";
    TString SubcontainerName = Form("hfeCalpp");
    SubcontainerName += name;
    AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(SubcontainerName, TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutput1);

    return task;
}
<commit_msg>modify_20181102<commit_after>///////////////////////////////////////////////////////////////////
//                                                               //
// AddCaloHFEpp                                                  //
// Author: T. Suzuki Univ. of Tsukuba                            //
//                                                               //
///////////////////////////////////////////////////////////////////
class AliAnalysisDataContainer;

AliAnalysisTaskCaloHFEpp* AddTaskCaloHFEpp(TString name = "name",
		                 TString dataname = "dataname",
		                 Bool_t flagEG1,
		                 Bool_t flagEG2,
		                 Bool_t flagDG1,
		                 Bool_t flagDG2,
		                 Bool_t SetFlagClsTypeEMC,
		                 Bool_t SetFlagClsTypeDCAL,
		                 Bool_t fMC,
										 Double_t TrackEtaMin,
										 Double_t TrackEtaMax,
										 Int_t NTPCClust,
										 Int_t NITSClust,
										 Int_t NCrossedRow,
										 Double_t DCAxy,
										 Double_t DCAz,
										 Double_t NsigmaMin,
										 Double_t NsigmaMax,
										 Double_t M20Min,
										 Double_t M20Max,
										 Double_t EopMin,
										 Double_t EopMax,
										 Double_t coneR,
										 Double_t ptAsso,
										 TString  pte = "pte",
										 Double_t MassMin)
{
    // get the manager via the static access member. since it's static, you don't need
    // an instance of the class to call the function
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    // get the input event handler, again via a static method.
    // this handler is part of the managing system and feeds events
    // to your task
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }

//		//-------------------------------------------
//		gROOT->LoadMacro("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C");
//		gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
//
//		AddTaskPhysicsSelection(fMC,true); // IsMC true for MC !!!, second argument is for pileup removal which is very important.
//		AliMultSelectionTask * Multtask = AddTaskMultSelection(true); // argument is true if you need to run on calibration and this task should be called after the physics selection!!!!
//		Multtask->SetAlternateOADBforEstimators(dataname.Data()); // for MC, if there is no calibration then you can specify here the alternate default calibration to be used.
//		if(fMC)Multtask->SetUseDefaultMCCalib(kTRUE); // MC
//		if(!fMC)Multtask->SetUseDefaultCalib(kTRUE); // data
//		//-------------------------------------------

		// by default, a file is open for writing. here, we get the filename
		TString fileName = AliAnalysisManager::GetCommonFileName();
    fileName += ":CaloHFEpp";      // create a subfolder in the file
    // now we create an instance of your task
    AliAnalysisTaskCaloHFEpp* task = new AliAnalysisTaskCaloHFEpp(name.Data());
    task -> SetEG1(flagEG1);
    task -> SetEG2(flagEG2);
    task -> SetDG1(flagDG1);
    task -> SetDG2(flagDG2);
    task -> SetfFlagClsTypeEMC(SetFlagClsTypeEMC);
    task -> SetfFlagClsTypeDCAL(SetFlagClsTypeDCAL);

		task -> SetTrackEta(TrackEtaMin,TrackEtaMax);
		task -> SetTrackClust(NTPCClust,NITSClust,NCrossedRow);
		task -> SetDCA(DCAxy,DCAz);
		task -> SetNsigma(NsigmaMin,NsigmaMax);
		task -> SetM20(M20Min,M20Max);
		task -> SetEop(EopMin,EopMax);
		task -> SetConeR(coneR);
		task -> SetptAsso(ptAsso);
		task -> SetptCut(pte);
		task -> SetMassMin(MassMin);
    if(!task) return 0x0;

    // add your task to the manager
    mgr->AddTask(task);

    TString containerName = mgr->GetCommonFileName();
    containerName += ":PWGHF_hfeCalpp";
    TString SubcontainerName = Form("hfeCalpp");
    SubcontainerName += name;
    AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(SubcontainerName, TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutput1);

    return task;
}
<|endoftext|>


<commit_before>#include <string>
#include <sstream>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/python.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/utility.hpp>

#include <lemon/core.h>

#include "../include/pgmlink/hypotheses.h"

using namespace pgmlink;
using namespace boost::python;

typedef typename property_map<node_traxel, typename HypothesesGraph::base_graph>::type node_traxel_m;

node_traxel_m& addNodeTraxelMap(HypothesesGraph* g) {
  g->add(node_traxel());
  return g->get(node_traxel());
}
node_traxel_m& getNodeTraxelMap(HypothesesGraph* g) {
  return g->get(node_traxel());
}

struct HypothesesGraph_pickle_suite : pickle_suite {
  static std::string getstate( const HypothesesGraph& g ) {
    std::stringstream ss;
    boost::archive::text_oarchive oa(ss);
    oa & g;
    return ss.str();
  }

  static void setstate( HypothesesGraph& g, const std::string& state ) {
    std::stringstream ss(state);
    boost::archive::text_iarchive ia(ss);
    ia & g;
  }
};

inline object pass_through(object const& o) { return o; }
template < typename ITERABLE_VALUE_MAP >
struct IterableValueMap_ValueIterator {
  typedef ITERABLE_VALUE_MAP map_type;
  IterableValueMap_ValueIterator( const map_type& m ) {
    it_ = m.beginValue();
    end_ = m.endValue();
  }
  typename map_type::Value next() {
    if( it_ == end_) {
        PyErr_SetString(PyExc_StopIteration, "No more data.");
        boost::python::throw_error_already_set();
    }
    const typename map_type::Value& result = *it_;
    ++it_;
    return result;
  }

  static IterableValueMap_ValueIterator<map_type>
  values ( const map_type& m ) {
    return IterableValueMap_ValueIterator<map_type>( m );
  }

  static void
  wrap( const char* python_name) {
    class_<IterableValueMap_ValueIterator<map_type> >( python_name, init<const map_type&>(args("iterable_value_map")) )
      .def("next", &IterableValueMap_ValueIterator::next)
      .def("__iter__", &pass_through)
      ;
  }

  typename map_type::ValueIt it_;
  typename map_type::ValueIt end_;
};

void export_hypotheses() {
  class_<typename HypothesesGraph::Arc>("Arc");
  class_<typename HypothesesGraph::ArcIt>("ArcIt");
  class_<typename HypothesesGraph::Node>("Node");
  class_<typename HypothesesGraph::NodeIt>("NodeIt");
  class_<typename HypothesesGraph::InArcIt>("InArcIt");
  class_<typename HypothesesGraph::OutArcIt>("OutArcIt");

  IterableValueMap_ValueIterator<node_traxel_m>::wrap("NodeTraxelMap_ValueIt");

  class_<node_traxel_m, boost::noncopyable>("NodeTraxelMap", init<const HypothesesGraph&>(args("hypotheses_graph")))
    .def("__getitem__", &node_traxel_m::operator[],
	 return_internal_reference<>())
    .def("__setitem__", &node_traxel_m::set)
    .def("values", &IterableValueMap_ValueIterator<node_traxel_m>::values)
    ;

  // handle function overloading
  void (HypothesesGraph::*erase1)(const HypothesesGraph::Node) = &HypothesesGraph::erase;
  void (HypothesesGraph::*erase2)(const HypothesesGraph::Arc) = &HypothesesGraph::erase;
  bool (HypothesesGraph::*valid1)(const HypothesesGraph::Node) const = &HypothesesGraph::valid;
  bool (HypothesesGraph::*valid2)(const HypothesesGraph::Arc) const = &HypothesesGraph::valid;
  int (*id1)(HypothesesGraph::Node) = &HypothesesGraph::id;
  int (*id2)(HypothesesGraph::Arc) = &HypothesesGraph::id;
  HypothesesGraph::Node (HypothesesGraph::*baseNode1)(const HypothesesGraph::InArcIt&) const =
    &HypothesesGraph::baseNode;
  HypothesesGraph::Node (HypothesesGraph::*baseNode2)(const HypothesesGraph::OutArcIt&) const =
    &HypothesesGraph::baseNode;
  HypothesesGraph::Node (HypothesesGraph::*runningNode1)(const HypothesesGraph::InArcIt&) const =
    &HypothesesGraph::runningNode;
  HypothesesGraph::Node (HypothesesGraph::*runningNode2)(const HypothesesGraph::OutArcIt&) const =
    &HypothesesGraph::runningNode;

  class_<HypothesesGraph, boost::noncopyable>("HypothesesGraph")
    .def("addNode", &HypothesesGraph::add_node)
    //.def("timesteps", &HypothesesGraph::timesteps,
    //   return_internal_reference<>())
    .def("earliest_timestep", &HypothesesGraph::earliest_timestep)
    .def("latest_timestep", &HypothesesGraph::latest_timestep)

    // lemon graph interface
    .def("addArc", &HypothesesGraph::addArc)
    .def("erase", erase1)
    .def("erase", erase2)
    .def("valid", valid1)
    .def("valid", valid2)
    .def("changeTarget", &HypothesesGraph::changeTarget)
    .def("changeSource", &HypothesesGraph::changeSource)
    .def("target", &HypothesesGraph::target)
    .def("source", &HypothesesGraph::source)
    .def("id", id1)
    .def("id", id2)
    .def("nodeFromId", &HypothesesGraph::nodeFromId)
    .def("arcFromId", &HypothesesGraph::arcFromId)
    .def("maxNodeId", &HypothesesGraph::maxNodeId)
    .def("maxArcId", &HypothesesGraph::maxArcId)
    .def("baseNode", baseNode1)
    .def("runningNode", runningNode1)
    .def("baseNode", baseNode2)
    .def("runningNode", runningNode2)
    .def("oppositeNode", &HypothesesGraph::oppositeNode)

    // extensions
    .def("addNodeTraxelMap", &addNodeTraxelMap,
	 return_internal_reference<>())
    .def("getNodeTraxelMap", &getNodeTraxelMap,
	 return_internal_reference<>())
    .def_pickle(HypothesesGraph_pickle_suite())
    ;

  //
  // lemon
  //
  int (*countNodes)(const HypothesesGraph&) = lemon::countNodes;
  def("countNodes", countNodes);

  int (*countArcs)(const HypothesesGraph&) = lemon::countArcs;
  def("countArcs", countArcs);
}
<commit_msg>fixed typename outside of template error<commit_after>#include <string>
#include <sstream>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/python.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/utility.hpp>

#include <lemon/core.h>

#include "../include/pgmlink/hypotheses.h"

using namespace pgmlink;
using namespace boost::python;

typedef property_map<node_traxel, typename HypothesesGraph::base_graph>::type node_traxel_m;

node_traxel_m& addNodeTraxelMap(HypothesesGraph* g) {
  g->add(node_traxel());
  return g->get(node_traxel());
}
node_traxel_m& getNodeTraxelMap(HypothesesGraph* g) {
  return g->get(node_traxel());
}

struct HypothesesGraph_pickle_suite : pickle_suite {
  static std::string getstate( const HypothesesGraph& g ) {
    std::stringstream ss;
    boost::archive::text_oarchive oa(ss);
    oa & g;
    return ss.str();
  }

  static void setstate( HypothesesGraph& g, const std::string& state ) {
    std::stringstream ss(state);
    boost::archive::text_iarchive ia(ss);
    ia & g;
  }
};

inline object pass_through(object const& o) { return o; }
template < typename ITERABLE_VALUE_MAP >
struct IterableValueMap_ValueIterator {
  typedef ITERABLE_VALUE_MAP map_type;
  IterableValueMap_ValueIterator( const map_type& m ) {
    it_ = m.beginValue();
    end_ = m.endValue();
  }
  typename map_type::Value next() {
    if( it_ == end_) {
        PyErr_SetString(PyExc_StopIteration, "No more data.");
        boost::python::throw_error_already_set();
    }
    const typename map_type::Value& result = *it_;
    ++it_;
    return result;
  }

  static IterableValueMap_ValueIterator<map_type>
  values ( const map_type& m ) {
    return IterableValueMap_ValueIterator<map_type>( m );
  }

  static void
  wrap( const char* python_name) {
    class_<IterableValueMap_ValueIterator<map_type> >( python_name, init<const map_type&>(args("iterable_value_map")) )
      .def("next", &IterableValueMap_ValueIterator::next)
      .def("__iter__", &pass_through)
      ;
  }

  typename map_type::ValueIt it_;
  typename map_type::ValueIt end_;
};

void export_hypotheses() {
  class_<typename HypothesesGraph::Arc>("Arc");
  class_<typename HypothesesGraph::ArcIt>("ArcIt");
  class_<typename HypothesesGraph::Node>("Node");
  class_<typename HypothesesGraph::NodeIt>("NodeIt");
  class_<typename HypothesesGraph::InArcIt>("InArcIt");
  class_<typename HypothesesGraph::OutArcIt>("OutArcIt");

  IterableValueMap_ValueIterator<node_traxel_m>::wrap("NodeTraxelMap_ValueIt");

  class_<node_traxel_m, boost::noncopyable>("NodeTraxelMap", init<const HypothesesGraph&>(args("hypotheses_graph")))
    .def("__getitem__", &node_traxel_m::operator[],
	 return_internal_reference<>())
    .def("__setitem__", &node_traxel_m::set)
    .def("values", &IterableValueMap_ValueIterator<node_traxel_m>::values)
    ;

  // handle function overloading
  void (HypothesesGraph::*erase1)(const HypothesesGraph::Node) = &HypothesesGraph::erase;
  void (HypothesesGraph::*erase2)(const HypothesesGraph::Arc) = &HypothesesGraph::erase;
  bool (HypothesesGraph::*valid1)(const HypothesesGraph::Node) const = &HypothesesGraph::valid;
  bool (HypothesesGraph::*valid2)(const HypothesesGraph::Arc) const = &HypothesesGraph::valid;
  int (*id1)(HypothesesGraph::Node) = &HypothesesGraph::id;
  int (*id2)(HypothesesGraph::Arc) = &HypothesesGraph::id;
  HypothesesGraph::Node (HypothesesGraph::*baseNode1)(const HypothesesGraph::InArcIt&) const =
    &HypothesesGraph::baseNode;
  HypothesesGraph::Node (HypothesesGraph::*baseNode2)(const HypothesesGraph::OutArcIt&) const =
    &HypothesesGraph::baseNode;
  HypothesesGraph::Node (HypothesesGraph::*runningNode1)(const HypothesesGraph::InArcIt&) const =
    &HypothesesGraph::runningNode;
  HypothesesGraph::Node (HypothesesGraph::*runningNode2)(const HypothesesGraph::OutArcIt&) const =
    &HypothesesGraph::runningNode;

  class_<HypothesesGraph, boost::noncopyable>("HypothesesGraph")
    .def("addNode", &HypothesesGraph::add_node)
    //.def("timesteps", &HypothesesGraph::timesteps,
    //   return_internal_reference<>())
    .def("earliest_timestep", &HypothesesGraph::earliest_timestep)
    .def("latest_timestep", &HypothesesGraph::latest_timestep)

    // lemon graph interface
    .def("addArc", &HypothesesGraph::addArc)
    .def("erase", erase1)
    .def("erase", erase2)
    .def("valid", valid1)
    .def("valid", valid2)
    .def("changeTarget", &HypothesesGraph::changeTarget)
    .def("changeSource", &HypothesesGraph::changeSource)
    .def("target", &HypothesesGraph::target)
    .def("source", &HypothesesGraph::source)
    .def("id", id1)
    .def("id", id2)
    .def("nodeFromId", &HypothesesGraph::nodeFromId)
    .def("arcFromId", &HypothesesGraph::arcFromId)
    .def("maxNodeId", &HypothesesGraph::maxNodeId)
    .def("maxArcId", &HypothesesGraph::maxArcId)
    .def("baseNode", baseNode1)
    .def("runningNode", runningNode1)
    .def("baseNode", baseNode2)
    .def("runningNode", runningNode2)
    .def("oppositeNode", &HypothesesGraph::oppositeNode)

    // extensions
    .def("addNodeTraxelMap", &addNodeTraxelMap,
	 return_internal_reference<>())
    .def("getNodeTraxelMap", &getNodeTraxelMap,
	 return_internal_reference<>())
    .def_pickle(HypothesesGraph_pickle_suite())
    ;

  //
  // lemon
  //
  int (*countNodes)(const HypothesesGraph&) = lemon::countNodes;
  def("countNodes", countNodes);

  int (*countArcs)(const HypothesesGraph&) = lemon::countArcs;
  def("countArcs", countArcs);
}
<|endoftext|>


<commit_before>
#include <QDirIterator>

#include <qqmlengine.h>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

#include <private/qv4engine_p.h>
#include <private/qqmlengine_p.h>
#include <private/qv4assembler_p.h>
#include <private/qv4isel_masm_p.h>

#include "qrcloader.h"

QrcLoader::QrcLoader(QQmlEngine *engine):
    loader(new QmcLoader(engine))
{
}

QrcLoader::~QrcLoader(void)
{
    delete loader;
}

int QrcLoader::load(QString topLevelQmc)
{
    int ret;

    ret = loadDependencies(topLevelQmc);
    if(ret != 0){
        return ret;
    }

    ret = loadTopLevelQmc(topLevelQmc);
    return ret;
}

QQmlComponent *QrcLoader::getRootComponent(void)
{
    return rootComponent;
}

int QrcLoader::loadDependencies(QString topLevelQmc)
{
    int ret;

    // iterate through files in .qrc and compile the ones we support
    QDirIterator it(":", QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QDir dir = it.next();

        // skip top level .qmc
        if(QString(":/" + topLevelQmc) == dir.path()){
            continue;
        }

        ret = 0;
        if(dir.path().endsWith(".qmc") || dir.path().endsWith(".jsc")){
            //ret = compileFile(engine, "qrc" + dir.path(),
             //       outputBaseDir + dir.dirName().replace(".qml", ".qmc"));
            // remove leading :/
            QString path = dir.path().mid(2);
            QFile inputFile(path);
            if (!inputFile.open(QFile::ReadOnly)){
                qWarning() << "Couldn't open file for input" << path;
                return -1;
            }

            QDataStream in(&inputFile);

            qDebug() << "Loading.." << "qrc" + dir.path();
            bool success = loader->loadDependency(in, QUrl("qrc" + dir.path()));
            assert(success);
            inputFile.close();
            assert(success);
        }

        if(ret){
            return ret;
        }
    }
    return 0;
}

int QrcLoader::loadTopLevelQmc(QString qmcFile)
{

    QFile inputFile(qmcFile);
    if (!inputFile.open(QFile::ReadOnly)){
        qWarning() << "Couldn't open file for input" << qmcFile;
        return -2;
    }

    QDataStream in(&inputFile);

    rootComponent = loader->loadComponent(in, QUrl("qrc:/" + qmcFile));

    inputFile.close();

    if(!rootComponent){
        return -3;
    }

    return 0;
}

<commit_msg>Show clearly what fails<commit_after>
#include <QDirIterator>

#include <qqmlengine.h>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

#include <private/qv4engine_p.h>
#include <private/qqmlengine_p.h>
#include <private/qv4assembler_p.h>
#include <private/qv4isel_masm_p.h>

#include "qrcloader.h"

QrcLoader::QrcLoader(QQmlEngine *engine):
    loader(new QmcLoader(engine))
{
}

QrcLoader::~QrcLoader(void)
{
    delete loader;
}

int QrcLoader::load(QString topLevelQmc)
{
    int ret;

    ret = loadDependencies(topLevelQmc);
    if(ret != 0){
        return ret;
    }

    ret = loadTopLevelQmc(topLevelQmc);
    return ret;
}

QQmlComponent *QrcLoader::getRootComponent(void)
{
    return rootComponent;
}

int QrcLoader::loadDependencies(QString topLevelQmc)
{
    int ret;

    // iterate through files in .qrc and compile the ones we support
    QDirIterator it(":", QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QDir dir = it.next();

        // skip top level .qmc
        if(QString(":/" + topLevelQmc) == dir.path()){
            continue;
        }

        ret = 0;
        if(dir.path().endsWith(".qmc") || dir.path().endsWith(".jsc")){
            //ret = compileFile(engine, "qrc" + dir.path(),
             //       outputBaseDir + dir.dirName().replace(".qml", ".qmc"));
            // remove leading :/
            QString path = dir.path().mid(2);
            QFile inputFile(path);
            if (!inputFile.open(QFile::ReadOnly)){
                qWarning() << "Couldn't open file for input" << path;
                return -1;
            }

            QDataStream in(&inputFile);

            QString qrcPath = "qrc" + dir.path();
            qDebug() << "Loading dependency " << qrcPath;
            bool success = loader->loadDependency(in, QUrl(qrcPath));
            qDebug() << (success ? "OK" : "Failed");
            assert(success);
            inputFile.close();
            assert(success);
        }

        if(ret){
            return ret;
        }
    }
    return 0;
}

int QrcLoader::loadTopLevelQmc(QString qmcFile)
{

    QFile inputFile(qmcFile);
    if (!inputFile.open(QFile::ReadOnly)){
        qWarning() << "Couldn't open file for input" << qmcFile;
        return -2;
    }

    QDataStream in(&inputFile);
    QString qrcPath = "qrc:/" + qmcFile;

    qDebug() << "Loading component " << qrcPath;
    rootComponent = loader->loadComponent(in, QUrl(qrcPath));
    qDebug() << (rootComponent ? "OK" : "Failed");

    inputFile.close();

    if(!rootComponent){
        return -3;
    }

    return 0;
}

<|endoftext|>


<commit_before>/**
 * @file FunctionApproximatorRRRFF.hpp
 * @brief FunctionApproximatorRRRFF class header file.
 * @author Thibaut Munzer, Freek Stulp
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo 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 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo 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 DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _FUNCTION_APPROXIMATOR_RRRFF_H_
#define _FUNCTION_APPROXIMATOR_RRRFF_H_

#include "functionapproximators/FunctionApproximator.hpp"

/** @defgroup RRRFF Incremental Random Features Regularized Least Squares (RRRFF)
 *  @ingroup FunctionApproximators
 */

namespace DmpBbo {

// Forward declarations
class MetaParametersRRRFF;
class ModelParametersRRRFF;

/** \brief RRRFF (Ridge Regression with Random Fourier Features) function approximator
 * \ingroup FunctionApproximators
 * \ingroup RRRFF
 * https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3935121/
 */
class FunctionApproximatorRRRFF : public FunctionApproximator
{
public:

  /** Initialize a function approximator with meta- and model-parameters
   *  \param[in] meta_parameters  The training algorithm meta-parameters
   *  \param[in] model_parameters The parameters of the trained model. If this parameter is not
   *                              passed, the function approximator is initialized as untrained.
   *                              In this case, you must call FunctionApproximator::train() before
   *                              being able to call FunctionApproximator::predict().
   * Either meta_parameters XOR model-parameters can passed as NULL, but not both.
   */
  FunctionApproximatorRRRFF(const MetaParametersRRRFF *const meta_parameters, const ModelParametersRRRFF *const model_parameters=NULL);

  /** Initialize a function approximator with model parameters
   *  \param[in] model_parameters The parameters of the (previously) trained model.
   */
  FunctionApproximatorRRRFF(const ModelParametersRRRFF *const model_parameters);

	virtual FunctionApproximator* clone(void) const;

	void train(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets);
	void predict(const Eigen::Ref<const Eigen::MatrixXd>& inputs, Eigen::MatrixXd& outputs);

	std::string getName(void) const {
    return std::string("RRRFF");
  };

	bool saveGridData(const Eigen::VectorXd& min, const Eigen::VectorXd& max, const Eigen::VectorXi& n_samples_per_dim, std::string directory, bool overwrite=false) const;

private:

  /**
   * Default constructor.
   * \remarks This default constuctor is required for boost::serialization to work. Since this
   * constructor should not be called by other classes, it is private (boost::serialization is a
   * friend)
   */
  FunctionApproximatorRRRFF(void) {};

  /** Give boost serialization access to private members. */
  friend class boost::serialization::access;

  /** Serialize class data members to boost archive.
   * \param[in] ar Boost archive
   * \param[in] version Version of the class
   * See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase
   */
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version);

};

}

#include <boost/serialization/export.hpp>
/** Register this derived class. */
BOOST_CLASS_EXPORT_KEY2(DmpBbo::FunctionApproximatorRRRFF, "FunctionApproximatorRRRFF")

/** Don't add version information to archives. */
BOOST_CLASS_IMPLEMENTATION(DmpBbo::FunctionApproximatorRRRFF,boost::serialization::object_serializable);

#endif // !_FUNCTION_APPROXIMATOR_RRRFF_H_
<commit_msg>Wrong name<commit_after>/**
 * @file FunctionApproximatorRRRFF.hpp
 * @brief FunctionApproximatorRRRFF class header file.
 * @author Thibaut Munzer, Freek Stulp
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo 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 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo 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 DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _FUNCTION_APPROXIMATOR_RRRFF_H_
#define _FUNCTION_APPROXIMATOR_RRRFF_H_

#include "functionapproximators/FunctionApproximator.hpp"

/** @defgroup RRRFF Ridge Regression with Random Fourier Features (RRRFF)
 *  @ingroup FunctionApproximators
 */

namespace DmpBbo {

// Forward declarations
class MetaParametersRRRFF;
class ModelParametersRRRFF;

/** \brief RRRFF (Ridge Regression with Random Fourier Features) function approximator
 * \ingroup FunctionApproximators
 * \ingroup RRRFF
 * https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3935121/
 */
class FunctionApproximatorRRRFF : public FunctionApproximator
{
public:

  /** Initialize a function approximator with meta- and model-parameters
   *  \param[in] meta_parameters  The training algorithm meta-parameters
   *  \param[in] model_parameters The parameters of the trained model. If this parameter is not
   *                              passed, the function approximator is initialized as untrained.
   *                              In this case, you must call FunctionApproximator::train() before
   *                              being able to call FunctionApproximator::predict().
   * Either meta_parameters XOR model-parameters can passed as NULL, but not both.
   */
  FunctionApproximatorRRRFF(const MetaParametersRRRFF *const meta_parameters, const ModelParametersRRRFF *const model_parameters=NULL);

  /** Initialize a function approximator with model parameters
   *  \param[in] model_parameters The parameters of the (previously) trained model.
   */
  FunctionApproximatorRRRFF(const ModelParametersRRRFF *const model_parameters);

	virtual FunctionApproximator* clone(void) const;

	void train(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets);
	void predict(const Eigen::Ref<const Eigen::MatrixXd>& inputs, Eigen::MatrixXd& outputs);

	std::string getName(void) const {
    return std::string("RRRFF");
  };

	bool saveGridData(const Eigen::VectorXd& min, const Eigen::VectorXd& max, const Eigen::VectorXi& n_samples_per_dim, std::string directory, bool overwrite=false) const;

private:

  /**
   * Default constructor.
   * \remarks This default constuctor is required for boost::serialization to work. Since this
   * constructor should not be called by other classes, it is private (boost::serialization is a
   * friend)
   */
  FunctionApproximatorRRRFF(void) {};

  /** Give boost serialization access to private members. */
  friend class boost::serialization::access;

  /** Serialize class data members to boost archive.
   * \param[in] ar Boost archive
   * \param[in] version Version of the class
   * See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase
   */
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version);

};

}

#include <boost/serialization/export.hpp>
/** Register this derived class. */
BOOST_CLASS_EXPORT_KEY2(DmpBbo::FunctionApproximatorRRRFF, "FunctionApproximatorRRRFF")

/** Don't add version information to archives. */
BOOST_CLASS_IMPLEMENTATION(DmpBbo::FunctionApproximatorRRRFF,boost::serialization::object_serializable);

#endif // !_FUNCTION_APPROXIMATOR_RRRFF_H_
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_dmi_dccal.H $     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_dmi_dccal.H
/// @brief Run Dccal on the link.
///-----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 1
/// *HWP Consumed by      : FSP:HB
///-----------------------------------------------------------------------------

#ifndef _P9_IO_DMI_DCCAL_H
#define _P9_IO_DMI_DCCAL_H

//-----------------------------------------------------------------------------
//  fapi2 Includes
//-----------------------------------------------------------------------------
#include <fapi2.H>

typedef fapi2::Target<fapi2::TARGET_TYPE_DMI> DMI_TGT;
typedef fapi2::ReturnCode (*p9_io_dmi_dccal_FP_t)(fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

extern "C"
{

    /**
     * @brief A I/O EDI+ Procedure that runs Rx Dccal and Tx Z Impedance calibration
     * on every EDI+ DMI chiplet.
     *
     * @param[in] i_target_chip   Chip target
     *
     * @return FAPI2_RC_SUCCESS on success, error otherwise
     */
    fapi2::ReturnCode p9_io_dmi_dccal(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);

} // extern "C"

#endif // _P9_IO_DMI_DCCAL_H
<commit_msg>I/O Metadata Cleanup<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_dmi_dccal.H $     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_dmi_dccal.H
/// @brief Run Dccal on the link.
///-----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 3
/// *HWP Consumed by      : FSP:HB
///-----------------------------------------------------------------------------

#ifndef _P9_IO_DMI_DCCAL_H
#define _P9_IO_DMI_DCCAL_H

//-----------------------------------------------------------------------------
//  fapi2 Includes
//-----------------------------------------------------------------------------
#include <fapi2.H>

typedef fapi2::Target<fapi2::TARGET_TYPE_DMI> DMI_TGT;
typedef fapi2::ReturnCode (*p9_io_dmi_dccal_FP_t)(fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

extern "C"
{

    /**
     * @brief A I/O EDI+ Procedure that runs Rx Dccal and Tx Z Impedance calibration
     * on every EDI+ DMI chiplet.
     *
     * @param[in] i_target_chip   Chip target
     *
     * @return FAPI2_RC_SUCCESS on success, error otherwise
     */
    fapi2::ReturnCode p9_io_dmi_dccal(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);

} // extern "C"

#endif // _P9_IO_DMI_DCCAL_H
<|endoftext|>


<commit_before>#include "Stdafx.h"
#include "Karo.h"

namespace Karo {
    namespace Core {
        Karo::Karo() {
            _tiles = gcnew array<Tile^>(20);
            for (int i = 0; i < 20; i++) {
                _tiles[i] = gcnew Tile(i % 5, i / 5);
            }
        }
        bool Karo::IsFinished::get()
        {
            //todo: Implement
            return false;
        }
        IEnumerable<Piece^>^ Karo::Pieces::get() {
            return _pieces;
        }
        IEnumerable<Tile^>^ Karo::Tiles::get() {
            return _tiles;
        }
        IEnumerable<Move^>^ Karo::GetAvailableMoves(Player player) {
			array<Move^>^ moves = gcnew array<Move^>(48); // 6 pieces * 8 directions

			int i = 0;

			if (PieceCount() < 12) // we're still in the first phase
			{
				for each (Tile^ tile in Tiles)
				{
					if (!tile->HasPiece)
					{
						moves[i++] = gcnew Move(tile->X, tile->Y, 0, 0, 0, 0);
					}
				}
			}

			return moves;
        }

        bool Karo::IsValidMove(Move^ move) {
            //todo: Implement
            return true;
        }
        Karo^ Karo::WithMoveApplied(Move^ move) {
            //todo: Implement
            return nullptr;
        }
		int Karo::PieceCount()
		{
			if (Pieces == nullptr)
				return 0;

			int i = 0;

			for each (Piece^ piece in Pieces)
			{
				if (piece != nullptr)
					i++;
			}

			return i;
		}
    }
}<commit_msg>Code cleanup<commit_after>#include "Stdafx.h"
#include "Karo.h"

namespace Karo {
    namespace Core {
        Karo::Karo() {
            _tiles = gcnew array<Tile^>(20);
            for (int i = 0; i < 20; i++) {
                _tiles[i] = gcnew Tile(i % 5, i / 5);
            }
        }
        bool Karo::IsFinished::get()
        {
            //todo: Implement
            return false;
        }
        IEnumerable<Piece^>^ Karo::Pieces::get() {
            return _pieces;
        }
        IEnumerable<Tile^>^ Karo::Tiles::get() {
            return _tiles;
        }
        IEnumerable<Move^>^ Karo::GetAvailableMoves(Player player) {
			array<Move^>^ moves = gcnew array<Move^>(48); // 6 pieces * 8 directions

			int i = 0;

			if (PieceCount() < 12) // we're still in the first phase
			{
				for each (Tile^ tile in Tiles)
				{
					if (!tile->HasPiece)
					{
						moves[i++] = gcnew Move(tile->X, tile->Y, 0, 0, 0, 0);
					}
				}
			}

			return moves;
        }

        bool Karo::IsValidMove(Move^ move) {
            //todo: Implement
            return true;
        }
        Karo^ Karo::WithMoveApplied(Move^ move) {
            //todo: Implement
            return nullptr;
        }
		int Karo::PieceCount()
		{
			if (Pieces == nullptr)
				return 0;

			int i = 0;

			for each (Piece^ piece in Pieces)
				if (piece != nullptr)
					i++;

			return i;
		}
    }
}<|endoftext|>


<commit_before>/*
    Copyright (C) 2008 Nikolas Zimmermann <zimmermann@kde.org>

    This file is part of the KDE project

    This library is free software you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "DgmlVisibleTagHandler.h"

#include "DgmlElementDictionary.h"
#include "DgmlAuxillaryDictionary.h"
#include "GeoParser.h"
#include "GeoSceneHead.h"

namespace Marble
{
namespace dgml
{
DGML_DEFINE_TAG_HANDLER(Visible)

GeoNode* DgmlVisibleTagHandler::parse(GeoParser& parser) const
{
    // Check whether the tag is valid
    Q_ASSERT(parser.isStartElement() && parser.isValidElement(dgmlTag_Visible));

    // Checking for parent item
    GeoStackItem parentItem = parser.parentElement();
    if (parentItem.represents(dgmlTag_Head)) {
        QString parsedText = parser.readElementText().toLower().trimmed();
        parentItem.nodeAs<GeoSceneHead>()->setVisible(parsedText == dgmlValue_true || dgmlValue_on);
    }

    return 0;
}

}
}
<commit_msg>Fix value interpretation, previously always true.<commit_after>/*
    Copyright (C) 2008 Nikolas Zimmermann <zimmermann@kde.org>

    This file is part of the KDE project

    This library is free software you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "DgmlVisibleTagHandler.h"

#include "DgmlElementDictionary.h"
#include "DgmlAuxillaryDictionary.h"
#include "GeoParser.h"
#include "GeoSceneHead.h"

namespace Marble
{
namespace dgml
{
DGML_DEFINE_TAG_HANDLER(Visible)

GeoNode* DgmlVisibleTagHandler::parse(GeoParser& parser) const
{
    // Check whether the tag is valid
    Q_ASSERT(parser.isStartElement() && parser.isValidElement(dgmlTag_Visible));

    // Checking for parent item
    GeoStackItem parentItem = parser.parentElement();
    if (parentItem.represents(dgmlTag_Head)) {
        QString parsedText = parser.readElementText().toLower().trimmed();
        parentItem.nodeAs<GeoSceneHead>()->setVisible(parsedText == dgmlValue_true || parsedText == dgmlValue_on);
    }

    return 0;
}

}
}
<|endoftext|>


<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#ifdef TRITON_PYTHON_BINDINGS

#include <api.hpp>
#include <pythonObjects.hpp>
#include <pythonUtils.hpp>
#include <pythonXFunctions.hpp>
#include <solverModel.hpp>

/*! \page py_SolverModel_page SolverModel
    \brief [**python api**] All information about the SolverModel python object.

\tableofcontents

\section py_SolverModel_description Description

This object is used to represent a model from a SMT solver.

~~~~~~~~~~~~~{.py}
>>> from triton import *
>>> from ast import *

>>> setArchitecture(ARCH.X86_64)
>>> inst = Instruction()
>>> inst.setOpcodes("\x48\x35\x44\x33\x22\x11") # xor rax, 0x11223344

>>> symvar = convertRegisterToSymbolicVariable(REG.RAX)
>>> print symvar
SymVar_0:64

>>> processing(inst)
>>> print inst
0: xor rax, 0x11223344

>>> raxAst = getFullAstFromId(getSymbolicRegisterId(REG.RAX))
>>> print raxAst
(bvxor ((_ extract 63 0) SymVar_0) (_ bv287454020 64))

>>> constraint = assert_(equal(raxAst, bv(0, raxAst.getBitvectorSize())))
>>> print constraint
(assert (= (bvxor ((_ extract 63 0) SymVar_0) (_ bv287454020 64)) (_ bv0 64)))

>>> model = getModel(constraint)
>>> print model
{0L: <SolverModel object at 0x7f30ac870b58>}

>>> symvarModel =  model[symvar.getId()] # Model from the symvar's id
>>> print symvarModel
SymVar_0 = 287454020
>>> hex(symvarModel.getValue())
'0x11223344L'
~~~~~~~~~~~~~

\section SolverModel_py_api Python API - Methods of the SolverModel class

- **getId(void)**

Returns the if of the model as integer. This id is the same that the variable id.

- **getName(void)**

Returns the name of the model as string. This name is the same that the variable name.

- **getValue(void)**

Returns the value of the model as integer.

*/

namespace triton {
  namespace bindings {
    namespace python {

      //! SolverModel destructor.
      void SolverModel_dealloc(PyObject* self) {
        std::cout << std::flush;
        delete PySolverModel_AsSolverModel(self);
        Py_DECREF(self);
      }

      static PyObject* SolverModel_getId(PyObject* self, PyObject* noarg) {
        try {
          return PyLong_FromUint32(PySolverModel_AsSolverModel(self)->getId());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      static PyObject* SolverModel_getName(PyObject* self, PyObject* noarg) {
        try {
          return Py_BuildValue("s", PySolverModel_AsSolverModel(self)->getName().c_str());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      static PyObject* SolverModel_getValue(PyObject* self, PyObject* noarg) {
        try {
          return PyLong_FromUint512(PySolverModel_AsSolverModel(self)->getValue());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      static int SolverModel_print(PyObject* self) {
        std::cout << PySolverModel_AsSolverModel(self);
        return 0;
      }

      static PyObject* SolverModel_str(PyObject* self) {
        try {
          std::stringstream str;
          str << PySolverModel_AsSolverModel(self);
          return PyString_FromFormat("%s", str.str().c_str());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      //! SolverModel methods.
      PyMethodDef SolverModel_callbacks[] = {
        {"getId",     SolverModel_getId,      METH_NOARGS,    ""},
        {"getName",   SolverModel_getName,    METH_NOARGS,    ""},
        {"getValue",  SolverModel_getValue,   METH_NOARGS,    ""},
        {nullptr,     nullptr,                0,              nullptr}
      };

      PyTypeObject SolverModel_Type = {
        PyObject_HEAD_INIT(&PyType_Type)
        0,                                          /* ob_size*/
        "SolverModel",                              /* tp_name*/
        sizeof(SolverModel_Object),                 /* tp_basicsize*/
        0,                                          /* tp_itemsize*/
        (destructor)SolverModel_dealloc,            /* tp_dealloc*/
        (printfunc)SolverModel_print,               /* tp_print*/
        0,                                          /* tp_getattr*/
        0,                                          /* tp_setattr*/
        0,                                          /* tp_compare*/
        0,                                          /* tp_repr*/
        0,                                          /* tp_as_number*/
        0,                                          /* tp_as_sequence*/
        0,                                          /* tp_as_mapping*/
        0,                                          /* tp_hash */
        0,                                          /* tp_call*/
        (reprfunc)SolverModel_str,                  /* tp_str*/
        0,                                          /* tp_getattro*/
        0,                                          /* tp_setattro*/
        0,                                          /* tp_as_buffer*/
        Py_TPFLAGS_DEFAULT,                         /* tp_flags*/
        "SolverModel objects",                      /* tp_doc */
        0,                                          /* tp_traverse */
        0,                                          /* tp_clear */
        0,                                          /* tp_richcompare */
        0,                                          /* tp_weaklistoffset */
        0,                                          /* tp_iter */
        0,                                          /* tp_iternext */
        SolverModel_callbacks,                      /* tp_methods */
        0,                                          /* tp_members */
        0,                                          /* tp_getset */
        0,                                          /* tp_base */
        0,                                          /* tp_dict */
        0,                                          /* tp_descr_get */
        0,                                          /* tp_descr_set */
        0,                                          /* tp_dictoffset */
        0,                                          /* tp_init */
        0,                                          /* tp_alloc */
        0,                                          /* tp_new */
        0,                                          /* tp_free */
        0,                                          /* tp_is_gc */
        0,                                          /* tp_bases */
        0,                                          /* tp_mro */
        0,                                          /* tp_cache */
        0,                                          /* tp_subclasses */
        0,                                          /* tp_weaklist */
        0,                                          /* tp_del */
        0                                           /* tp_version_tag */
      };

      PyObject* PySolverModel(const triton::engines::solver::SolverModel& model) {
        SolverModel_Object* object;

        PyType_Ready(&SolverModel_Type);
        object = PyObject_NEW(SolverModel_Object, &SolverModel_Type);
        if (object != NULL)
          object->model = new triton::engines::solver::SolverModel(model);

        return (PyObject*)object;
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */

#endif /* TRITON_PYTHON_BINDINGS */
<commit_msg>Fix a doxygen typo<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#ifdef TRITON_PYTHON_BINDINGS

#include <api.hpp>
#include <pythonObjects.hpp>
#include <pythonUtils.hpp>
#include <pythonXFunctions.hpp>
#include <solverModel.hpp>

/*! \page py_SolverModel_page SolverModel
    \brief [**python api**] All information about the SolverModel python object.

\tableofcontents

\section py_SolverModel_description Description

This object is used to represent a model from a SMT solver.

~~~~~~~~~~~~~{.py}
>>> from triton import *
>>> from ast import *

>>> setArchitecture(ARCH.X86_64)
>>> inst = Instruction()
>>> inst.setOpcodes("\x48\x35\x44\x33\x22\x11") # xor rax, 0x11223344

>>> symvar = convertRegisterToSymbolicVariable(REG.RAX)
>>> print symvar
SymVar_0:64

>>> processing(inst)
>>> print inst
0: xor rax, 0x11223344

>>> raxAst = getFullAstFromId(getSymbolicRegisterId(REG.RAX))
>>> print raxAst
(bvxor ((_ extract 63 0) SymVar_0) (_ bv287454020 64))

>>> constraint = assert_(equal(raxAst, bv(0, raxAst.getBitvectorSize())))
>>> print constraint
(assert (= (bvxor ((_ extract 63 0) SymVar_0) (_ bv287454020 64)) (_ bv0 64)))

>>> model = getModel(constraint)
>>> print model
{0L: <SolverModel object at 0x7f30ac870b58>}

>>> symvarModel =  model[symvar.getId()] # Model from the symvar's id
>>> print symvarModel
SymVar_0 = 287454020
>>> hex(symvarModel.getValue())
'0x11223344L'
~~~~~~~~~~~~~

\section SolverModel_py_api Python API - Methods of the SolverModel class

- **getId(void)**

Returns the id of the model as integer. This id is the same that the variable id.

- **getName(void)**

Returns the name of the model as string. This name is the same that the variable name.

- **getValue(void)**

Returns the value of the model as integer.

*/

namespace triton {
  namespace bindings {
    namespace python {

      //! SolverModel destructor.
      void SolverModel_dealloc(PyObject* self) {
        std::cout << std::flush;
        delete PySolverModel_AsSolverModel(self);
        Py_DECREF(self);
      }

      static PyObject* SolverModel_getId(PyObject* self, PyObject* noarg) {
        try {
          return PyLong_FromUint32(PySolverModel_AsSolverModel(self)->getId());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      static PyObject* SolverModel_getName(PyObject* self, PyObject* noarg) {
        try {
          return Py_BuildValue("s", PySolverModel_AsSolverModel(self)->getName().c_str());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      static PyObject* SolverModel_getValue(PyObject* self, PyObject* noarg) {
        try {
          return PyLong_FromUint512(PySolverModel_AsSolverModel(self)->getValue());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      static int SolverModel_print(PyObject* self) {
        std::cout << PySolverModel_AsSolverModel(self);
        return 0;
      }

      static PyObject* SolverModel_str(PyObject* self) {
        try {
          std::stringstream str;
          str << PySolverModel_AsSolverModel(self);
          return PyString_FromFormat("%s", str.str().c_str());
        }
        catch (const std::exception& e) {
          return PyErr_Format(PyExc_TypeError, "%s", e.what());
        }
      }

      //! SolverModel methods.
      PyMethodDef SolverModel_callbacks[] = {
        {"getId",     SolverModel_getId,      METH_NOARGS,    ""},
        {"getName",   SolverModel_getName,    METH_NOARGS,    ""},
        {"getValue",  SolverModel_getValue,   METH_NOARGS,    ""},
        {nullptr,     nullptr,                0,              nullptr}
      };

      PyTypeObject SolverModel_Type = {
        PyObject_HEAD_INIT(&PyType_Type)
        0,                                          /* ob_size*/
        "SolverModel",                              /* tp_name*/
        sizeof(SolverModel_Object),                 /* tp_basicsize*/
        0,                                          /* tp_itemsize*/
        (destructor)SolverModel_dealloc,            /* tp_dealloc*/
        (printfunc)SolverModel_print,               /* tp_print*/
        0,                                          /* tp_getattr*/
        0,                                          /* tp_setattr*/
        0,                                          /* tp_compare*/
        0,                                          /* tp_repr*/
        0,                                          /* tp_as_number*/
        0,                                          /* tp_as_sequence*/
        0,                                          /* tp_as_mapping*/
        0,                                          /* tp_hash */
        0,                                          /* tp_call*/
        (reprfunc)SolverModel_str,                  /* tp_str*/
        0,                                          /* tp_getattro*/
        0,                                          /* tp_setattro*/
        0,                                          /* tp_as_buffer*/
        Py_TPFLAGS_DEFAULT,                         /* tp_flags*/
        "SolverModel objects",                      /* tp_doc */
        0,                                          /* tp_traverse */
        0,                                          /* tp_clear */
        0,                                          /* tp_richcompare */
        0,                                          /* tp_weaklistoffset */
        0,                                          /* tp_iter */
        0,                                          /* tp_iternext */
        SolverModel_callbacks,                      /* tp_methods */
        0,                                          /* tp_members */
        0,                                          /* tp_getset */
        0,                                          /* tp_base */
        0,                                          /* tp_dict */
        0,                                          /* tp_descr_get */
        0,                                          /* tp_descr_set */
        0,                                          /* tp_dictoffset */
        0,                                          /* tp_init */
        0,                                          /* tp_alloc */
        0,                                          /* tp_new */
        0,                                          /* tp_free */
        0,                                          /* tp_is_gc */
        0,                                          /* tp_bases */
        0,                                          /* tp_mro */
        0,                                          /* tp_cache */
        0,                                          /* tp_subclasses */
        0,                                          /* tp_weaklist */
        0,                                          /* tp_del */
        0                                           /* tp_version_tag */
      };

      PyObject* PySolverModel(const triton::engines::solver::SolverModel& model) {
        SolverModel_Object* object;

        PyType_Ready(&SolverModel_Type);
        object = PyObject_NEW(SolverModel_Object, &SolverModel_Type);
        if (object != NULL)
          object->model = new triton::engines::solver::SolverModel(model);

        return (PyObject*)object;
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */

#endif /* TRITON_PYTHON_BINDINGS */
<|endoftext|>


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

#include "OpenWireFormat.h"

#include <activemq/util/Boolean.h>
#include <activemq/util/Integer.h>
#include <activemq/util/Long.h>
#include <activemq/util/Guid.h>
#include <activemq/util/Math.h>
#include <activemq/io/ByteArrayOutputStream.h>
#include <activemq/connector/openwire/utils/BooleanStream.h>
#include <activemq/connector/openwire/commands/WireFormatInfo.h>
#include <activemq/connector/openwire/commands/DataStructure.h>
#include <activemq/connector/openwire/marshal/MarshalAware.h>
#include <activemq/connector/openwire/marshal/DataStreamMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MarshallerFactory.h>

using namespace std;
using namespace activemq;
using namespace activemq::wireformat;
using namespace activemq::io;
using namespace activemq::util;
using namespace activemq::connector;
using namespace activemq::transport;
using namespace activemq::exceptions;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::commands;
using namespace activemq::connector::openwire::marshal;
using namespace activemq::connector::openwire::marshal::v2;
using namespace activemq::connector::openwire::utils;

////////////////////////////////////////////////////////////////////////////////
const unsigned char OpenWireFormat::NULL_TYPE = 0;

////////////////////////////////////////////////////////////////////////////////
OpenWireFormat::OpenWireFormat( const activemq::util::Properties& properties ) {

    // Copy config data
    this->properties.copy( &properties );
    this->preferedWireFormatInfo = NULL;

    // Fill in that DataStreamMarshallers collection
    dataMarshallers.resize( 256 );
    MarshallerFactory().configure( this );

    // Generate an ID
    this->id = Guid::createGUIDString();

    // Set defaults for initial WireFormat negotiation
    this->stackTraceEnabled = false;
    this->cacheEnabled = false;
    this->tcpNoDelayEnabled = false;
    this->tightEncodingEnabled = false;
    this->sizePrefixDisabled = false;
}

////////////////////////////////////////////////////////////////////////////////
OpenWireFormat::~OpenWireFormat()
{
    try {

        for( size_t i = 0; i < dataMarshallers.size(); ++i )
        {
            delete dataMarshallers[i];
        }

        delete preferedWireFormatInfo;
    }
    AMQ_CATCH_NOTHROW( ActiveMQException )
    AMQ_CATCHALL_NOTHROW( )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::addMarshaller( DataStreamMarshaller* marshaller )
{
    unsigned char type = marshaller->getDataStructureType();
    dataMarshallers[type & 0xFF] = marshaller;
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::setPreferedWireFormatInfo(
    commands::WireFormatInfo* info ) throw ( IllegalStateException ) {

    delete preferedWireFormatInfo;
    this->preferedWireFormatInfo = info;
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::marshal( transport::Command* command,
                              io::DataOutputStream* dataOut )
    throw ( io::IOException ) {

    try {

        int size = 1;

        if( command != NULL ) {

            DataStructure* dataStructure =
                dynamic_cast< DataStructure* >( command );

            unsigned char type = dataStructure->getDataStructureType();

            DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF];

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( type ) ).c_str() );
            }

            if( tightEncodingEnabled ) {
                BooleanStream bs;
                size += dsm->tightMarshal1( this, dataStructure, &bs );
                size += bs.marshalledSize();

                if( !sizePrefixDisabled ) {
                    dataOut->writeInt( size );
                }

                dataOut->writeByte( type );
                bs.marshal( dataOut );
                dsm->tightMarshal2( this, dataStructure, dataOut, &bs );

            } else {
                DataOutputStream* looseOut = dataOut;
                ByteArrayOutputStream* baos = NULL;

                if( !sizePrefixDisabled ) {
                    baos = new ByteArrayOutputStream();
                    looseOut = new DataOutputStream( baos );
                }

                looseOut->writeByte( type );
                dsm->looseMarshal( this, dataStructure, looseOut );

                if( !sizePrefixDisabled ) {
                    looseOut->close();
                    dataOut->writeInt( (int)baos->getByteArraySize() );
                    dataOut->write( baos->getByteArray(),
                                    baos->getByteArraySize() );

                    // Delete allocated resource
                    delete baos;
                    delete looseOut;
                }
            }
        } else {
            dataOut->writeInt( size );
            dataOut->writeByte( NULL_TYPE );
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
transport::Command* OpenWireFormat::unmarshal( io::DataInputStream* dis )
    throw ( io::IOException ) {

    try{

        if( !sizePrefixDisabled ) {
            dis->readInt();
        }

        // Get the unmarshalled DataStructure
        DataStructure* data = doUnmarshal( dis );

        if( data == NULL ) {
            throw IOException(
                __FILE__, __LINE__,
                "OpenWireFormat::doUnmarshal - "
                "Failed to unmarshal an Object" );
        }

        // Now all unmarshals from this level should result in an object
        // that is a transport::Command type, if its not then we throw an
        // exception.
        transport::Command* command =
            dynamic_cast< transport::Command* >( data );

        if( command == NULL ) {
            delete data;

            throw IOException(
                __FILE__, __LINE__,
                "OpenWireFormat::doUnmarshal - "
                "Unmarshalled a non Command Type" );
        }

        return command;
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
commands::DataStructure* OpenWireFormat::doUnmarshal( DataInputStream* dis )
    throw ( IOException ) {

    try {

        unsigned char dataType = dis->readByte();

        if( dataType != NULL_TYPE ) {

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            // Ask the DataStreamMarshaller to create a new instance of its
            // command so that we can fill in its data.
            DataStructure* data = dsm->createObject();

            if( this->tightEncodingEnabled ) {
                BooleanStream bs;
                bs.unmarshal( dis );
                dsm->tightUnmarshal( this, data, dis, &bs );
            } else {
                dsm->looseUnmarshal( this, data, dis );
            }

            return data;
        }

        return NULL;
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
int OpenWireFormat::tightMarshalNestedObject1( commands::DataStructure* object,
                                               utils::BooleanStream* bs )
    throw ( io::IOException ) {

    try {

        bs->writeBoolean( object != NULL );
        if( object == NULL ) {
            return 0;
        }

        if( object->isMarshalAware() ) {

            std::vector<unsigned char> sequence =
                object->getMarshaledForm(this);
            bs->writeBoolean( !sequence.empty() );
            if( !sequence.empty() ) {
                return (int)(1 + sequence.size());
            }
        }

        unsigned char type = object->getDataStructureType();
        if( type == 0 ) {
            throw IOException(
                __FILE__, __LINE__,
                "No valid data structure type for object of this type");
        }

        DataStreamMarshaller* dsm =
            dynamic_cast< DataStreamMarshaller* >( dataMarshallers[type & 0xFF] );

        if( dsm == NULL ) {
            throw IOException(
                __FILE__, __LINE__,
                ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                Integer::toString( type ) ).c_str() );
        }

        return 1 + dsm->tightMarshal1( this, object, bs );
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::tightMarshalNestedObject2( DataStructure* o,
                                                DataOutputStream* ds,
                                                BooleanStream* bs )
                                                    throw ( IOException ) {

    try {

        if( !bs->readBoolean() ) {
            return;
        }

        unsigned char type = o->getDataStructureType();

        ds->writeByte(type);

        if( o->isMarshalAware() && bs->readBoolean() ) {

            MarshalAware* ma = dynamic_cast< MarshalAware* >( o );
            vector<unsigned char> sequence = ma->getMarshaledForm( this );
            ds->write( &sequence[0], sequence.size() );

        } else {

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >( dataMarshallers[type & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( type ) ).c_str() );
            }

            dsm->tightMarshal2( this, o, ds, bs );

        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
DataStructure* OpenWireFormat::tightUnmarshalNestedObject( DataInputStream* dis,
                                                           BooleanStream* bs)
    throw ( io::IOException ) {

    try {

        if( bs->readBoolean() ) {

            const unsigned char dataType = dis->readByte();

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            DataStructure* data = dsm->createObject();

            if( data->isMarshalAware() && bs->readBoolean() ) {

                dis->readInt();
                dis->readByte();

                BooleanStream bs2;
                bs2.unmarshal( dis );
                dsm->tightUnmarshal( this, data, dis, &bs2 );

            } else {
                dsm->tightUnmarshal( this, data, dis, bs );
            }

            return data;
        } else {
            return NULL;
        }

    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
DataStructure* OpenWireFormat::looseUnmarshalNestedObject( io::DataInputStream* dis )
    throw ( IOException ) {

    try{

        if( dis->readBoolean() ) {

            unsigned char dataType = dis->readByte();

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            DataStructure* data = dsm->createObject();
            dsm->looseUnmarshal( this, data, dis );

            return data;

        } else {
            return NULL;
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::looseMarshalNestedObject( commands::DataStructure* o,
                                               io::DataOutputStream* dataOut )
    throw ( io::IOException ) {

    try{

        dataOut->writeBoolean( o != NULL );
        if( o != NULL ) {

            unsigned char dataType = o->getDataStructureType();

            dataOut->writeByte( dataType );

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            dsm->looseMarshal( this, o, dataOut );
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::renegotiateWireFormat( WireFormatInfo* info )
    throw ( exceptions::IllegalStateException ) {

    if( preferedWireFormatInfo == NULL ) {
        throw IllegalStateException(
            __FILE__, __LINE__,
            "OpenWireFormat::renegotiateWireFormat - "
            "Wireformat cannot not be renegotiated." );
    }

    this->setVersion( Math::min( preferedWireFormatInfo->getVersion(),
                                 info->getVersion() ) );
    this->stackTraceEnabled = info->isStackTraceEnabled() &&
                              preferedWireFormatInfo->isStackTraceEnabled();
    this->tcpNoDelayEnabled = info->isTcpNoDelayEnabled() &&
                              preferedWireFormatInfo->isTcpNoDelayEnabled();
    this->cacheEnabled = info->isCacheEnabled() &&
                         preferedWireFormatInfo->isCacheEnabled();
    this->tightEncodingEnabled = info->isTightEncodingEnabled() &&
                                 preferedWireFormatInfo->isTightEncodingEnabled();
    this->sizePrefixDisabled = info->isSizePrefixDisabled() &&
                               preferedWireFormatInfo->isSizePrefixDisabled();

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

#include "OpenWireFormat.h"

#include <activemq/util/Boolean.h>
#include <activemq/util/Integer.h>
#include <activemq/util/Long.h>
#include <activemq/util/Guid.h>
#include <activemq/util/Math.h>
#include <activemq/io/ByteArrayOutputStream.h>
#include <activemq/connector/openwire/utils/BooleanStream.h>
#include <activemq/connector/openwire/commands/WireFormatInfo.h>
#include <activemq/connector/openwire/commands/DataStructure.h>
#include <activemq/connector/openwire/marshal/MarshalAware.h>
#include <activemq/connector/openwire/marshal/DataStreamMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MarshallerFactory.h>

using namespace std;
using namespace activemq;
using namespace activemq::wireformat;
using namespace activemq::io;
using namespace activemq::util;
using namespace activemq::connector;
using namespace activemq::transport;
using namespace activemq::exceptions;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::commands;
using namespace activemq::connector::openwire::marshal;
using namespace activemq::connector::openwire::marshal::v2;
using namespace activemq::connector::openwire::utils;

////////////////////////////////////////////////////////////////////////////////
const unsigned char OpenWireFormat::NULL_TYPE = 0;

////////////////////////////////////////////////////////////////////////////////
OpenWireFormat::OpenWireFormat( const activemq::util::Properties& properties ) {

    // Copy config data
    this->properties.copy( &properties );
    this->preferedWireFormatInfo = NULL;

    // Fill in that DataStreamMarshallers collection
    dataMarshallers.resize( 256 );
    MarshallerFactory().configure( this );

    // Generate an ID
    this->id = Guid::createGUIDString();

    // Set defaults for initial WireFormat negotiation
    this->stackTraceEnabled = false;
    this->cacheEnabled = false;
    this->tcpNoDelayEnabled = false;
    this->tightEncodingEnabled = false;
    this->sizePrefixDisabled = false;
}

////////////////////////////////////////////////////////////////////////////////
OpenWireFormat::~OpenWireFormat()
{
    try {

        for( size_t i = 0; i < dataMarshallers.size(); ++i )
        {
            delete dataMarshallers[i];
        }

        delete preferedWireFormatInfo;
    }
    AMQ_CATCH_NOTHROW( ActiveMQException )
    AMQ_CATCHALL_NOTHROW()
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::addMarshaller( DataStreamMarshaller* marshaller )
{
    unsigned char type = marshaller->getDataStructureType();
    dataMarshallers[type & 0xFF] = marshaller;
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::setPreferedWireFormatInfo(
    commands::WireFormatInfo* info ) throw ( IllegalStateException ) {

    delete preferedWireFormatInfo;
    this->preferedWireFormatInfo = info;
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::marshal( transport::Command* command,
                              io::DataOutputStream* dataOut )
    throw ( io::IOException ) {

    try {

        int size = 1;

        if( command != NULL ) {

            DataStructure* dataStructure =
                dynamic_cast< DataStructure* >( command );

            unsigned char type = dataStructure->getDataStructureType();

            DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF];

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( type ) ).c_str() );
            }

            if( tightEncodingEnabled ) {
                BooleanStream bs;
                size += dsm->tightMarshal1( this, dataStructure, &bs );
                size += bs.marshalledSize();

                if( !sizePrefixDisabled ) {
                    dataOut->writeInt( size );
                }

                dataOut->writeByte( type );
                bs.marshal( dataOut );
                dsm->tightMarshal2( this, dataStructure, dataOut, &bs );

            } else {
                DataOutputStream* looseOut = dataOut;
                ByteArrayOutputStream* baos = NULL;

                if( !sizePrefixDisabled ) {
                    baos = new ByteArrayOutputStream();
                    looseOut = new DataOutputStream( baos );
                }

                looseOut->writeByte( type );
                dsm->looseMarshal( this, dataStructure, looseOut );

                if( !sizePrefixDisabled ) {
                    looseOut->close();
                    dataOut->writeInt( (int)baos->getByteArraySize() );
                    dataOut->write( baos->getByteArray(),
                                    baos->getByteArraySize() );

                    // Delete allocated resource
                    delete baos;
                    delete looseOut;
                }
            }
        } else {
            dataOut->writeInt( size );
            dataOut->writeByte( NULL_TYPE );
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
transport::Command* OpenWireFormat::unmarshal( io::DataInputStream* dis )
    throw ( io::IOException ) {

    try{

        if( !sizePrefixDisabled ) {
            dis->readInt();
        }

        // Get the unmarshalled DataStructure
        DataStructure* data = doUnmarshal( dis );

        if( data == NULL ) {
            throw IOException(
                __FILE__, __LINE__,
                "OpenWireFormat::doUnmarshal - "
                "Failed to unmarshal an Object" );
        }

        // Now all unmarshals from this level should result in an object
        // that is a transport::Command type, if its not then we throw an
        // exception.
        transport::Command* command =
            dynamic_cast< transport::Command* >( data );

        if( command == NULL ) {
            delete data;

            throw IOException(
                __FILE__, __LINE__,
                "OpenWireFormat::doUnmarshal - "
                "Unmarshalled a non Command Type" );
        }

        return command;
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
commands::DataStructure* OpenWireFormat::doUnmarshal( DataInputStream* dis )
    throw ( IOException ) {

    try {

        unsigned char dataType = dis->readByte();

        if( dataType != NULL_TYPE ) {

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            // Ask the DataStreamMarshaller to create a new instance of its
            // command so that we can fill in its data.
            DataStructure* data = dsm->createObject();

            if( this->tightEncodingEnabled ) {
                BooleanStream bs;
                bs.unmarshal( dis );
                dsm->tightUnmarshal( this, data, dis, &bs );
            } else {
                dsm->looseUnmarshal( this, data, dis );
            }

            return data;
        }

        return NULL;
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
int OpenWireFormat::tightMarshalNestedObject1( commands::DataStructure* object,
                                               utils::BooleanStream* bs )
    throw ( io::IOException ) {

    try {

        bs->writeBoolean( object != NULL );
        if( object == NULL ) {
            return 0;
        }

        if( object->isMarshalAware() ) {

            std::vector<unsigned char> sequence =
                object->getMarshaledForm(this);
            bs->writeBoolean( !sequence.empty() );
            if( !sequence.empty() ) {
                return (int)(1 + sequence.size());
            }
        }

        unsigned char type = object->getDataStructureType();
        if( type == 0 ) {
            throw IOException(
                __FILE__, __LINE__,
                "No valid data structure type for object of this type");
        }

        DataStreamMarshaller* dsm =
            dynamic_cast< DataStreamMarshaller* >( dataMarshallers[type & 0xFF] );

        if( dsm == NULL ) {
            throw IOException(
                __FILE__, __LINE__,
                ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                Integer::toString( type ) ).c_str() );
        }

        return 1 + dsm->tightMarshal1( this, object, bs );
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::tightMarshalNestedObject2( DataStructure* o,
                                                DataOutputStream* ds,
                                                BooleanStream* bs )
                                                    throw ( IOException ) {

    try {

        if( !bs->readBoolean() ) {
            return;
        }

        unsigned char type = o->getDataStructureType();

        ds->writeByte(type);

        if( o->isMarshalAware() && bs->readBoolean() ) {

            MarshalAware* ma = dynamic_cast< MarshalAware* >( o );
            vector<unsigned char> sequence = ma->getMarshaledForm( this );
            ds->write( &sequence[0], sequence.size() );

        } else {

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >( dataMarshallers[type & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( type ) ).c_str() );
            }

            dsm->tightMarshal2( this, o, ds, bs );

        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
DataStructure* OpenWireFormat::tightUnmarshalNestedObject( DataInputStream* dis,
                                                           BooleanStream* bs )
    throw ( io::IOException ) {

    try {

        if( bs->readBoolean() ) {

            const unsigned char dataType = dis->readByte();

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            DataStructure* data = dsm->createObject();

            if( data->isMarshalAware() && bs->readBoolean() ) {

                dis->readInt();
                dis->readByte();

                BooleanStream bs2;
                bs2.unmarshal( dis );
                dsm->tightUnmarshal( this, data, dis, &bs2 );

            } else {
                dsm->tightUnmarshal( this, data, dis, bs );
            }

            return data;
        } else {
            return NULL;
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
DataStructure* OpenWireFormat::looseUnmarshalNestedObject( io::DataInputStream* dis )
    throw ( IOException ) {

    try{

        if( dis->readBoolean() ) {

            unsigned char dataType = dis->readByte();

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            DataStructure* data = dsm->createObject();
            dsm->looseUnmarshal( this, data, dis );

            return data;

        } else {
            return NULL;
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::looseMarshalNestedObject( commands::DataStructure* o,
                                               io::DataOutputStream* dataOut )
    throw ( io::IOException ) {

    try{

        dataOut->writeBoolean( o != NULL );
        if( o != NULL ) {

            unsigned char dataType = o->getDataStructureType();

            dataOut->writeByte( dataType );

            DataStreamMarshaller* dsm =
                dynamic_cast< DataStreamMarshaller* >(
                    dataMarshallers[dataType & 0xFF] );

            if( dsm == NULL ) {
                throw IOException(
                    __FILE__, __LINE__,
                    ( string( "OpenWireFormat::marshal - Unknown data type: " ) +
                    Integer::toString( dataType ) ).c_str() );
            }

            dsm->looseMarshal( this, o, dataOut );
        }
    }
    AMQ_CATCH_RETHROW( IOException )
    AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException )
    AMQ_CATCHALL_THROW( IOException )
}

////////////////////////////////////////////////////////////////////////////////
void OpenWireFormat::renegotiateWireFormat( WireFormatInfo* info )
    throw ( exceptions::IllegalStateException ) {

    if( preferedWireFormatInfo == NULL ) {
        throw IllegalStateException(
            __FILE__, __LINE__,
            "OpenWireFormat::renegotiateWireFormat - "
            "Wireformat cannot not be renegotiated." );
    }

    this->setVersion( Math::min( preferedWireFormatInfo->getVersion(),
                                 info->getVersion() ) );
    this->stackTraceEnabled = info->isStackTraceEnabled() &&
                              preferedWireFormatInfo->isStackTraceEnabled();
    this->tcpNoDelayEnabled = info->isTcpNoDelayEnabled() &&
                              preferedWireFormatInfo->isTcpNoDelayEnabled();
    this->cacheEnabled = info->isCacheEnabled() &&
                         preferedWireFormatInfo->isCacheEnabled();
    this->tightEncodingEnabled = info->isTightEncodingEnabled() &&
                                 preferedWireFormatInfo->isTightEncodingEnabled();
    this->sizePrefixDisabled = info->isSizePrefixDisabled() &&
                               preferedWireFormatInfo->isSizePrefixDisabled();
}
<|endoftext|>