<commit_before>#include "C45PruneableClassifierTree.h"
#include "ModelSelection.h"
#include "core/Instances.h"
#include "Distribution.h"
#include "core/Utils.h"
#include "NoSplit.h"
#include "Stats.h"

C45PruneableClassifierTree::C45PruneableClassifierTree(ModelSelection *toSelectLocModel, bool pruneTree, float cf, bool raiseTree, bool cleanup, bool collapseTree) : ClassifierTree(toSelectLocModel)
{
    mPruneTheTree = pruneTree;
    mCF = cf;
    mSubtreeRaising = raiseTree;
    mCleanup = cleanup;
    mCollapseTheTree = collapseTree;
}

void C45PruneableClassifierTree::buildClassifier(Instances &data)
{

    // remove instances with missing class
    Instances dataMissed(&data);
    dataMissed.deleteWithMissingClass();

    buildTree(dataMissed, mSubtreeRaising || !mCleanup);
    if (mCollapseTheTree)
    {
        collapse();
    }
    if (mPruneTheTree)
    {
        prune();
    }
    if (mCleanup)
    {
        ;// cleanup(new Instances(dataMissed, 0));
    }
}

void C45PruneableClassifierTree::collapse()
{

    double errorsOfSubtree;
    double errorsOfTree;
    int i;

    if (!mIsLeaf)
    {
        errorsOfSubtree = getTrainingErrors();
        errorsOfTree = localModel()->getDistribution()->numIncorrect();
        if (errorsOfSubtree >= errorsOfTree - 1E-3)
        {

            // Free adjacent trees
            //mSons = ;
            mIsLeaf = true;

            // Get NoSplit Model for tree.
            mLocalModel = new NoSplit(localModel()->getDistribution());
        }
        else
        {
            for (i = 0; i < (int)mSons.size(); i++)
            {
                son(i)->collapse();
            }
        }
    }
}

void C45PruneableClassifierTree::prune()
{

    double errorsLargestBranch;
    double errorsLeaf;
    double errorsTree;
    int indexOfLargestBranch;
    C45PruneableClassifierTree *largestBranch;
    int i;

    if (!mIsLeaf)
    {

        // Prune all subtrees.
        for (i = 0; i < (int)mSons.size(); i++)
        {
            son(i)->prune();
        }

        // Compute error for largest branch
        indexOfLargestBranch = localModel()->getDistribution()->maxBag();
        if (mSubtreeRaising)
        {
            errorsLargestBranch = son(indexOfLargestBranch)->getEstimatedErrorsForBranch(*mTrain);
        }
        else
        {
            errorsLargestBranch = std::numeric_limits<double>::max();
        }

        // Compute error if this Tree would be leaf
        errorsLeaf = getEstimatedErrorsForDistribution(localModel()->getDistribution());

        // Compute error for the whole subtree
        errorsTree = getEstimatedErrors();

        // Decide if leaf is best choice.
        if (Utils::smOrEq(errorsLeaf, errorsTree + 0.1) && Utils::smOrEq(errorsLeaf, errorsLargestBranch + 0.1))
        {

            // Free son Trees
            mSons.clear();
            mIsLeaf = true;

            // Get NoSplit Model for node.
            mLocalModel = new NoSplit(localModel()->getDistribution());
            return;
        }

        // Decide if largest branch is better choice
        // than whole subtree.
        if (Utils::smOrEq(errorsLargestBranch, errorsTree + 0.1))
        {
            largestBranch = son(indexOfLargestBranch);
            mSons = largestBranch->mSons;
            mLocalModel = largestBranch->localModel();
            mIsLeaf = largestBranch->mIsLeaf;
            newDistribution(*mTrain);
            prune();
        }
    }
}

ClassifierTree *C45PruneableClassifierTree::getNewTree(Instances &data) const
{

    C45PruneableClassifierTree *newTree = new C45PruneableClassifierTree(mToSelectModel, mPruneTheTree, mCF, mSubtreeRaising, mCleanup, mCollapseTheTree);
    newTree->buildTree(static_cast<Instances>(data), mSubtreeRaising || !mCleanup);

    return newTree;
}

double C45PruneableClassifierTree::getEstimatedErrors() const
{

    double errors = 0;
    int i;

    if (mIsLeaf)
    {
        return getEstimatedErrorsForDistribution(localModel()->getDistribution());
    }
    else
    {
        for (i = 0; i < (int)mSons.size(); i++)
        {
            errors = errors + son(i)->getEstimatedErrors();
        }
        return errors;
    }
}

double C45PruneableClassifierTree::getEstimatedErrorsForBranch(Instances &data) const
{

    std::vector<Instances*> localInstances;
    double errors = 0;
    int i;

    if (mIsLeaf)
    {
        return getEstimatedErrorsForDistribution(new Distribution(data));
    }
    else
    {
        Distribution *savedDist = localModel()->getDistribution();
        localModel()->resetDistribution(data);

        localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data));
        localModel()->setDistribution(savedDist);
        for (i = 0; i < (int)mSons.size(); i++)
        {
            errors = errors + son(i)->getEstimatedErrorsForBranch(*localInstances[i]);
        }
        return errors;
    }
}

double C45PruneableClassifierTree::getEstimatedErrorsForDistribution(Distribution *theDistribution) const
{

    if (Utils::eq(theDistribution->total(), 0))
    {
        return 0;
    }
    else
    {
        return theDistribution->numIncorrect() + Stats::addErrs(theDistribution->total(), theDistribution->numIncorrect(), mCF);
    }
}

double C45PruneableClassifierTree::getTrainingErrors() const
{

    double errors = 0;
    int i;

    if (mIsLeaf)
    {
        return localModel()->getDistribution()->numIncorrect();
    }
    else
    {
        for (i = 0; i < (int)mSons.size(); i++)
        {
            errors = errors + son(i)->getTrainingErrors();
        }
        return errors;
    }
}

ClassifierSplitModel *C45PruneableClassifierTree::localModel() const
{

    return static_cast<ClassifierSplitModel*>(mLocalModel);
}

void C45PruneableClassifierTree::newDistribution(Instances &data)
{

    std::vector<Instances*> localInstances;

    localModel()->resetDistribution(data);
    mTrain = &data;
    if (!mIsLeaf)
    {
        localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data));
        for (int i = 0; i < (int)mSons.size(); i++)
        {
            son(i)->newDistribution(*localInstances[i]);
        }
    }
    else
    {

        // Check whether there are some instances at the leaf now!
        if (!Utils::eq(data.sumOfWeights(), 0))
        {
            mIsEmpty = false;
        }
    }
}

C45PruneableClassifierTree *C45PruneableClassifierTree::son(int index) const
{

    return static_cast<C45PruneableClassifierTree*>(mSons[index]);
}
<commit_msg>Fixed RHAS compilation issue<commit_after>#include "C45PruneableClassifierTree.h"
#include "ModelSelection.h"
#include "core/Instances.h"
#include "Distribution.h"
#include "core/Utils.h"
#include "NoSplit.h"
#include "Stats.h"

C45PruneableClassifierTree::C45PruneableClassifierTree(ModelSelection *toSelectLocModel, bool pruneTree, float cf, bool raiseTree, bool cleanup, bool collapseTree) : ClassifierTree(toSelectLocModel)
{
    mPruneTheTree = pruneTree;
    mCF = cf;
    mSubtreeRaising = raiseTree;
    mCleanup = cleanup;
    mCollapseTheTree = collapseTree;
}

void C45PruneableClassifierTree::buildClassifier(Instances &data)
{

    // remove instances with missing class
    Instances dataMissed(&data);
    dataMissed.deleteWithMissingClass();

    buildTree(dataMissed, mSubtreeRaising || !mCleanup);
    if (mCollapseTheTree)
    {
        collapse();
    }
    if (mPruneTheTree)
    {
        prune();
    }
    if (mCleanup)
    {
        ;// cleanup(new Instances(dataMissed, 0));
    }
}

void C45PruneableClassifierTree::collapse()
{

    double errorsOfSubtree;
    double errorsOfTree;
    int i;

    if (!mIsLeaf)
    {
        errorsOfSubtree = getTrainingErrors();
        errorsOfTree = localModel()->getDistribution()->numIncorrect();
        if (errorsOfSubtree >= errorsOfTree - 1E-3)
        {

            // Free adjacent trees
            //mSons = ;
            mIsLeaf = true;

            // Get NoSplit Model for tree.
            mLocalModel = new NoSplit(localModel()->getDistribution());
        }
        else
        {
            for (i = 0; i < (int)mSons.size(); i++)
            {
                son(i)->collapse();
            }
        }
    }
}

void C45PruneableClassifierTree::prune()
{

    double errorsLargestBranch;
    double errorsLeaf;
    double errorsTree;
    int indexOfLargestBranch;
    C45PruneableClassifierTree *largestBranch;
    int i;

    if (!mIsLeaf)
    {

        // Prune all subtrees.
        for (i = 0; i < (int)mSons.size(); i++)
        {
            son(i)->prune();
        }

        // Compute error for largest branch
        indexOfLargestBranch = localModel()->getDistribution()->maxBag();
        if (mSubtreeRaising)
        {
            errorsLargestBranch = son(indexOfLargestBranch)->getEstimatedErrorsForBranch(*mTrain);
        }
        else
        {
            errorsLargestBranch = std::numeric_limits<double>::max();
        }

        // Compute error if this Tree would be leaf
        errorsLeaf = getEstimatedErrorsForDistribution(localModel()->getDistribution());

        // Compute error for the whole subtree
        errorsTree = getEstimatedErrors();

        // Decide if leaf is best choice.
        if (Utils::smOrEq(errorsLeaf, errorsTree + 0.1) && Utils::smOrEq(errorsLeaf, errorsLargestBranch + 0.1))
        {

            // Free son Trees
            mSons.clear();
            mIsLeaf = true;

            // Get NoSplit Model for node.
            mLocalModel = new NoSplit(localModel()->getDistribution());
            return;
        }

        // Decide if largest branch is better choice
        // than whole subtree.
        if (Utils::smOrEq(errorsLargestBranch, errorsTree + 0.1))
        {
            largestBranch = son(indexOfLargestBranch);
            mSons = largestBranch->mSons;
            mLocalModel = largestBranch->localModel();
            mIsLeaf = largestBranch->mIsLeaf;
            newDistribution(*mTrain);
            prune();
        }
    }
}

ClassifierTree *C45PruneableClassifierTree::getNewTree(Instances &data) const
{

    C45PruneableClassifierTree *newTree = new C45PruneableClassifierTree(mToSelectModel, mPruneTheTree, mCF, mSubtreeRaising, mCleanup, mCollapseTheTree);
    newTree->buildTree(data, mSubtreeRaising || !mCleanup);

    return newTree;
}

double C45PruneableClassifierTree::getEstimatedErrors() const
{

    double errors = 0;
    int i;

    if (mIsLeaf)
    {
        return getEstimatedErrorsForDistribution(localModel()->getDistribution());
    }
    else
    {
        for (i = 0; i < (int)mSons.size(); i++)
        {
            errors = errors + son(i)->getEstimatedErrors();
        }
        return errors;
    }
}

double C45PruneableClassifierTree::getEstimatedErrorsForBranch(Instances &data) const
{

    std::vector<Instances*> localInstances;
    double errors = 0;
    int i;

    if (mIsLeaf)
    {
        return getEstimatedErrorsForDistribution(new Distribution(data));
    }
    else
    {
        Distribution *savedDist = localModel()->getDistribution();
        localModel()->resetDistribution(data);

        localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data));
        localModel()->setDistribution(savedDist);
        for (i = 0; i < (int)mSons.size(); i++)
        {
            errors = errors + son(i)->getEstimatedErrorsForBranch(*localInstances[i]);
        }
        return errors;
    }
}

double C45PruneableClassifierTree::getEstimatedErrorsForDistribution(Distribution *theDistribution) const
{

    if (Utils::eq(theDistribution->total(), 0))
    {
        return 0;
    }
    else
    {
        return theDistribution->numIncorrect() + Stats::addErrs(theDistribution->total(), theDistribution->numIncorrect(), mCF);
    }
}

double C45PruneableClassifierTree::getTrainingErrors() const
{

    double errors = 0;
    int i;

    if (mIsLeaf)
    {
        return localModel()->getDistribution()->numIncorrect();
    }
    else
    {
        for (i = 0; i < (int)mSons.size(); i++)
        {
            errors = errors + son(i)->getTrainingErrors();
        }
        return errors;
    }
}

ClassifierSplitModel *C45PruneableClassifierTree::localModel() const
{

    return static_cast<ClassifierSplitModel*>(mLocalModel);
}

void C45PruneableClassifierTree::newDistribution(Instances &data)
{

    std::vector<Instances*> localInstances;

    localModel()->resetDistribution(data);
    mTrain = &data;
    if (!mIsLeaf)
    {
        localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data));
        for (int i = 0; i < (int)mSons.size(); i++)
        {
            son(i)->newDistribution(*localInstances[i]);
        }
    }
    else
    {

        // Check whether there are some instances at the leaf now!
        if (!Utils::eq(data.sumOfWeights(), 0))
        {
            mIsEmpty = false;
        }
    }
}

C45PruneableClassifierTree *C45PruneableClassifierTree::son(int index) const
{

    return static_cast<C45PruneableClassifierTree*>(mSons[index]);
}
<|endoftext|>


<commit_before>// @(#)root/win32gdk:$Id$
// Author: Valeriy Onuchin  08/08/2003

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// Proxy classes provide thread-safe interface to global objects.
//
// For example: TGWin32VirtualXProxy (to gVirtualX),
//              TGWin32InterpreterProxy (to gInterpreter).
//
// Proxy object creates callback object and posts a windows message to
// "processing thread". When windows message is received callback
// ("real method") is executed.
//
// For example:
//    gVirtualX->ClearWindow()
//
//    - callback object created containing pointer to function
//      corresponding TGWin32::ClearWindow() method
//    - message to "processing thread" (main thread) is posted
//    - TGWin32::ClearWindow() method is executed inside main thread
//    - thread containing gVirtualX proxy object waits for reply
//      from main thread that TGWin32::ClearWindow() is completed.
//
// Howto create proxy class:
//
//  1. Naming.
//       name of proxy = TGWin32 + the name of "virtual base class" + Proxy
//
//       e.g. TGWin32VirtualXProxy = TGWin32 + VirtualX + Proxy
//
//  2. Definition of global object
//       As example check definition and implementation of
//       gVirtualX, gInterpreter global objects
//
//  3. Class definition.
//       proxy class must be inherited from "virtual base class" and
//       TGWin32ProxyBase class. For example:
//
//       class TGWin32VirtualX : public TVirtualX , public  TGWin32ProxyBase
//
//  4. Constructors, destructor, extra methods.
//     - constructors and destructor of proxy class do nothing
//     - proxy class must contain two extra static methods
//       RealObject(), ProxyObject(). Each of them return pointer to object
//       of virtual base class.
//
//     For example:
//       static TInterpreter *RealObject();
//       static TInterpreter *ProxyObject();
//
//  5. Implementation
//       TGWin32ProxyDefs.h file contains a set of macros which very
//       simplify implementation.
//     - RETURN_PROXY_OBJECT macro implements ProxyObject() method, e.g.
//       RETURN_PROXY_OBJECT(Interpreter)
//     - the names of other macros say about itself.
//
//       For example:
//          VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1)
//             void TGWin32InterpreterProxy::ClearFileBusy()
//
//          RETURN_METHOD_ARG0_CONST(VirtualX,Visual_t,GetVisual)
//             Visual_t TGWin32VirtualXProxy::GetVisual() const
//
//          RETURN_METHOD_ARG2(VirtualX,Int_t,OpenPixmap,UInt_t,w,UInt_t,h)
//             Int_t TGWin32VirtualXProxy::OpenPixmap,UInt_t w,UInt_t h)
//
//     - few methods has _LOCK part in the name
//          VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl)
//
//
///////////////////////////////////////////////////////////////////////////////

#include "Windows4Root.h"
#include <windows.h>

#include "TGWin32ProxyBase.h"
#include "TRefCnt.h"
#include "TList.h"
#include "TGWin32.h"
#include "TROOT.h"

////////////////////////////////////////////////////////////////////////////////
class TGWin32CallBackObject : public TObject {
public:
   TGWin32CallBack   fCallBack;  // callback function (called by GUI thread)
   void              *fParam;    // arguments passed to/from callback function

   TGWin32CallBackObject(TGWin32CallBack cb,void *p):fCallBack(cb),fParam(p) {}
   ~TGWin32CallBackObject() { if (fParam) delete fParam; }
};

////////////////////////////////////////////////////////////////////////////////
class TGWin32ProxyBasePrivate {
public:
   HANDLE   fEvent;   // event used for syncronization
   TGWin32ProxyBasePrivate();
   ~TGWin32ProxyBasePrivate();
};

//______________________________________________________________________________
TGWin32ProxyBasePrivate::TGWin32ProxyBasePrivate()
{
   // ctor

   fEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
}

//______________________________________________________________________________
TGWin32ProxyBasePrivate::~TGWin32ProxyBasePrivate()
{
   // dtor

   if (fEvent) ::CloseHandle(fEvent);
   fEvent = 0;
}

ULong_t TGWin32ProxyBase::fgPostMessageId = 0;
ULong_t TGWin32ProxyBase::fgPingMessageId = 0;
ULong_t TGWin32ProxyBase::fgMainThreadId = 0;
Long_t  TGWin32ProxyBase::fgLock = 0;
UInt_t  TGWin32ProxyBase::fMaxResponseTime = 0;

////////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TGWin32ProxyBase::TGWin32ProxyBase()
{
   // ctor

   fCallBack = 0;
   fParam = 0;
   fListOfCallBacks = new TList();
   fBatchLimit = 100;
   fId = ::GetCurrentThreadId();
   fPimpl = new TGWin32ProxyBasePrivate();

   if (!fgPostMessageId) fgPostMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Post");
   if (!fgPingMessageId) fgPingMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Ping");
}

//______________________________________________________________________________
TGWin32ProxyBase::~TGWin32ProxyBase()
{
   // dtor

   fListOfCallBacks->Delete();
   delete fListOfCallBacks;
   fListOfCallBacks = 0;

   delete fPimpl;
}

//______________________________________________________________________________
void TGWin32ProxyBase::Lock()
{
   // enter critical section

   TGWin32::Lock();
}

//______________________________________________________________________________
void TGWin32ProxyBase::Unlock()
{
   // leave critical section

   TGWin32::Unlock();
}

//______________________________________________________________________________
void TGWin32ProxyBase::GlobalLock()
{
   // lock any proxy (client thread)

   if (IsGloballyLocked()) return;
   ::InterlockedIncrement(&fgLock);
}

//______________________________________________________________________________
void TGWin32ProxyBase::GlobalUnlock()
{
   //  unlock any proxy (client thread)

   if (!IsGloballyLocked()) return;
   ::InterlockedDecrement(&fgLock);
}

//______________________________________________________________________________
Bool_t TGWin32ProxyBase::Ping()
{
   // send ping messsage to server thread

   return ::PostThreadMessage(fgMainThreadId, fgPingMessageId, (WPARAM)0, 0L);
}

//______________________________________________________________________________
Double_t TGWin32ProxyBase::GetMilliSeconds()
{
   // returns elapsed time in milliseconds with microseconds precision

   static LARGE_INTEGER freq;
   static Bool_t first = kTRUE;
   LARGE_INTEGER count;
   static Double_t overhead = 0;

   if (first) {
      LARGE_INTEGER count0;
      ::QueryPerformanceFrequency(&freq);
      ::QueryPerformanceCounter(&count0);
      if (1) {
         Double_t dummy;
         dummy = ((Double_t)count0.QuadPart - overhead)*1000./((Double_t)freq.QuadPart);
      }
      ::QueryPerformanceCounter(&count);
      overhead = (Double_t)count.QuadPart - (Double_t)count0.QuadPart;
      first = kFALSE;
   }

   ::QueryPerformanceCounter(&count);
   return ((Double_t)count.QuadPart - overhead)*1000./((Double_t)freq.QuadPart);
}

//______________________________________________________________________________
void TGWin32ProxyBase::ExecuteCallBack(Bool_t sync)
{
   // Executes all batched callbacks and the latest callback
   // This method is executed by server thread

   // process batched callbacks
   if (fListOfCallBacks && fListOfCallBacks->GetSize()) {
      TIter next(fListOfCallBacks);
      TGWin32CallBackObject *obj;

      while ((obj = (TGWin32CallBackObject*)next())) {
         obj->fCallBack(obj->fParam);  // execute callback
      }
   }
   if (sync) {
      if (fCallBack) fCallBack(fParam);
      ::SetEvent(fPimpl->fEvent);
   }
}

//______________________________________________________________________________
Bool_t TGWin32ProxyBase::ForwardCallBack(Bool_t sync)
{
   // if sync is kTRUE:
   //    - post message to main thread.
   //    - execute callbacks from fListOfCallBacks
   //    - wait for response
   // else
   //    -  add callback to fListOfCallBacks
   //
   // returns kTRUE if callback execution is delayed (batched)

   Int_t wait = 0;

   if (!fgMainThreadId) return kFALSE;

   while (IsGloballyLocked()) {
      Ping();
      if (GetCurrentThreadId() == fgMainThreadId)
         break;
      ::SleepEx(10, 1); // take a rest
      if (!fgMainThreadId) return kFALSE; // server thread terminated
   }

   Bool_t batch = !sync &&  (fListOfCallBacks->GetSize()<fBatchLimit);

   if (batch) {
      fListOfCallBacks->Add(new TGWin32CallBackObject(fCallBack, fParam));
      return kTRUE;
   }

   while (!::PostThreadMessage(fgMainThreadId, fgPostMessageId, (WPARAM)this, 0L)) {
      // wait because there is a chance that message queue does not exist yet
      ::SleepEx(50, 1);
      if (wait++ > 5) return kFALSE; // failed to post
   }

   // limiting wait time
   DWORD res = WAIT_TIMEOUT;
   while (res ==  WAIT_TIMEOUT) {
      res = ::WaitForSingleObject(fPimpl->fEvent, 100);
      if ((GetCurrentThreadId() == fgMainThreadId) ||
         (!gROOT->IsLineProcessing() && IsGloballyLocked())) {
         break;
      }
   }
   ::ResetEvent(fPimpl->fEvent);

//   DWORD res = ::WaitForSingleObject(fPimpl->fEvent, INFINITE);
//   ::ResetEvent(fPimpl->fEvent);

   if (res == WAIT_TIMEOUT) { // server thread is blocked
      GlobalLock();
      return kTRUE;
   }

   fListOfCallBacks->Delete();
   return kFALSE;
}

//______________________________________________________________________________
void TGWin32ProxyBase::SendExitMessage()
{
   // send exit message to server thread

   ::PostThreadMessage(fgMainThreadId, WM_QUIT, 0, 0L);
}
<commit_msg>From Valeriy Onuchin: - Avoid potential deadlock in TGWin32ProxyBase.cxx<commit_after>// @(#)root/win32gdk:$Id$
// Author: Valeriy Onuchin  08/08/2003

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// Proxy classes provide thread-safe interface to global objects.
//
// For example: TGWin32VirtualXProxy (to gVirtualX),
//              TGWin32InterpreterProxy (to gInterpreter).
//
// Proxy object creates callback object and posts a windows message to
// "processing thread". When windows message is received callback
// ("real method") is executed.
//
// For example:
//    gVirtualX->ClearWindow()
//
//    - callback object created containing pointer to function
//      corresponding TGWin32::ClearWindow() method
//    - message to "processing thread" (main thread) is posted
//    - TGWin32::ClearWindow() method is executed inside main thread
//    - thread containing gVirtualX proxy object waits for reply
//      from main thread that TGWin32::ClearWindow() is completed.
//
// Howto create proxy class:
//
//  1. Naming.
//       name of proxy = TGWin32 + the name of "virtual base class" + Proxy
//
//       e.g. TGWin32VirtualXProxy = TGWin32 + VirtualX + Proxy
//
//  2. Definition of global object
//       As example check definition and implementation of
//       gVirtualX, gInterpreter global objects
//
//  3. Class definition.
//       proxy class must be inherited from "virtual base class" and
//       TGWin32ProxyBase class. For example:
//
//       class TGWin32VirtualX : public TVirtualX , public  TGWin32ProxyBase
//
//  4. Constructors, destructor, extra methods.
//     - constructors and destructor of proxy class do nothing
//     - proxy class must contain two extra static methods
//       RealObject(), ProxyObject(). Each of them return pointer to object
//       of virtual base class.
//
//     For example:
//       static TInterpreter *RealObject();
//       static TInterpreter *ProxyObject();
//
//  5. Implementation
//       TGWin32ProxyDefs.h file contains a set of macros which very
//       simplify implementation.
//     - RETURN_PROXY_OBJECT macro implements ProxyObject() method, e.g.
//       RETURN_PROXY_OBJECT(Interpreter)
//     - the names of other macros say about itself.
//
//       For example:
//          VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1)
//             void TGWin32InterpreterProxy::ClearFileBusy()
//
//          RETURN_METHOD_ARG0_CONST(VirtualX,Visual_t,GetVisual)
//             Visual_t TGWin32VirtualXProxy::GetVisual() const
//
//          RETURN_METHOD_ARG2(VirtualX,Int_t,OpenPixmap,UInt_t,w,UInt_t,h)
//             Int_t TGWin32VirtualXProxy::OpenPixmap,UInt_t w,UInt_t h)
//
//     - few methods has _LOCK part in the name
//          VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl)
//
//
///////////////////////////////////////////////////////////////////////////////

#include "Windows4Root.h"
#include <windows.h>

#include "TGWin32ProxyBase.h"
#include "TRefCnt.h"
#include "TList.h"
#include "TGWin32.h"
#include "TROOT.h"

////////////////////////////////////////////////////////////////////////////////
class TGWin32CallBackObject : public TObject {
public:
   TGWin32CallBack   fCallBack;  // callback function (called by GUI thread)
   void              *fParam;    // arguments passed to/from callback function

   TGWin32CallBackObject(TGWin32CallBack cb,void *p):fCallBack(cb),fParam(p) {}
   ~TGWin32CallBackObject() { if (fParam) delete fParam; }
};

////////////////////////////////////////////////////////////////////////////////
class TGWin32ProxyBasePrivate {
public:
   HANDLE   fEvent;   // event used for syncronization
   TGWin32ProxyBasePrivate();
   ~TGWin32ProxyBasePrivate();
};

//______________________________________________________________________________
TGWin32ProxyBasePrivate::TGWin32ProxyBasePrivate()
{
   // ctor

   fEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
}

//______________________________________________________________________________
TGWin32ProxyBasePrivate::~TGWin32ProxyBasePrivate()
{
   // dtor

   if (fEvent) ::CloseHandle(fEvent);
   fEvent = 0;
}

ULong_t TGWin32ProxyBase::fgPostMessageId = 0;
ULong_t TGWin32ProxyBase::fgPingMessageId = 0;
ULong_t TGWin32ProxyBase::fgMainThreadId = 0;
Long_t  TGWin32ProxyBase::fgLock = 0;
UInt_t  TGWin32ProxyBase::fMaxResponseTime = 0;

////////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TGWin32ProxyBase::TGWin32ProxyBase()
{
   // ctor

   fCallBack = 0;
   fParam = 0;
   fListOfCallBacks = new TList();
   fBatchLimit = 100;
   fId = ::GetCurrentThreadId();
   fPimpl = new TGWin32ProxyBasePrivate();

   if (!fgPostMessageId) fgPostMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Post");
   if (!fgPingMessageId) fgPingMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Ping");
}

//______________________________________________________________________________
TGWin32ProxyBase::~TGWin32ProxyBase()
{
   // dtor

   fListOfCallBacks->Delete();
   delete fListOfCallBacks;
   fListOfCallBacks = 0;

   delete fPimpl;
}

//______________________________________________________________________________
void TGWin32ProxyBase::Lock()
{
   // enter critical section

   TGWin32::Lock();
}

//______________________________________________________________________________
void TGWin32ProxyBase::Unlock()
{
   // leave critical section

   TGWin32::Unlock();
}

//______________________________________________________________________________
void TGWin32ProxyBase::GlobalLock()
{
   // lock any proxy (client thread)

   if (IsGloballyLocked()) return;
   ::InterlockedIncrement(&fgLock);
}

//______________________________________________________________________________
void TGWin32ProxyBase::GlobalUnlock()
{
   //  unlock any proxy (client thread)

   if (!IsGloballyLocked()) return;
   ::InterlockedDecrement(&fgLock);
}

//______________________________________________________________________________
Bool_t TGWin32ProxyBase::Ping()
{
   // send ping messsage to server thread

   return ::PostThreadMessage(fgMainThreadId, fgPingMessageId, (WPARAM)0, 0L);
}

//______________________________________________________________________________
Double_t TGWin32ProxyBase::GetMilliSeconds()
{
   // returns elapsed time in milliseconds with microseconds precision

   static LARGE_INTEGER freq;
   static Bool_t first = kTRUE;
   LARGE_INTEGER count;
   static Double_t overhead = 0;

   if (first) {
      LARGE_INTEGER count0;
      ::QueryPerformanceFrequency(&freq);
      ::QueryPerformanceCounter(&count0);
      if (1) {
         Double_t dummy;
         dummy = ((Double_t)count0.QuadPart - overhead)*1000./((Double_t)freq.QuadPart);
      }
      ::QueryPerformanceCounter(&count);
      overhead = (Double_t)count.QuadPart - (Double_t)count0.QuadPart;
      first = kFALSE;
   }

   ::QueryPerformanceCounter(&count);
   return ((Double_t)count.QuadPart - overhead)*1000./((Double_t)freq.QuadPart);
}

//______________________________________________________________________________
void TGWin32ProxyBase::ExecuteCallBack(Bool_t sync)
{
   // Executes all batched callbacks and the latest callback
   // This method is executed by server thread

   // process batched callbacks
   if (fListOfCallBacks && fListOfCallBacks->GetSize()) {
      TIter next(fListOfCallBacks);
      TGWin32CallBackObject *obj;

      while ((obj = (TGWin32CallBackObject*)next())) {
         obj->fCallBack(obj->fParam);  // execute callback
      }
   }
   if (sync) {
      if (fCallBack) fCallBack(fParam);
      ::SetEvent(fPimpl->fEvent);
   }
}

//______________________________________________________________________________
Bool_t TGWin32ProxyBase::ForwardCallBack(Bool_t sync)
{
   // if sync is kTRUE:
   //    - post message to main thread.
   //    - execute callbacks from fListOfCallBacks
   //    - wait for response
   // else
   //    -  add callback to fListOfCallBacks
   //
   // returns kTRUE if callback execution is delayed (batched)

   Int_t wait = 0;

   if (!fgMainThreadId) return kFALSE;

   while (IsGloballyLocked()) {
      Ping();
      if (GetCurrentThreadId() == fgMainThreadId)
         break;
      ::SleepEx(10, 1); // take a rest
      if (!fgMainThreadId) return kFALSE; // server thread terminated
   }

   Bool_t batch = !sync &&  (fListOfCallBacks->GetSize()<fBatchLimit);

   if (batch) {
      fListOfCallBacks->Add(new TGWin32CallBackObject(fCallBack, fParam));
      return kTRUE;
   }

   while (!::PostThreadMessage(fgMainThreadId, fgPostMessageId, (WPARAM)this, 0L)) {
      // wait because there is a chance that message queue does not exist yet
      ::SleepEx(50, 1);
      if (wait++ > 5) return kFALSE; // failed to post
   }

   Int_t cnt = 0; //VO attempt counters
   // limiting wait time
   DWORD res = WAIT_TIMEOUT;
   while (res ==  WAIT_TIMEOUT) {
      res = ::WaitForSingleObject(fPimpl->fEvent, 100);
      if ((GetCurrentThreadId() == fgMainThreadId) ||
         (!gROOT->IsLineProcessing() && IsGloballyLocked())) {
         break;
      }
      if (cnt++ > 20) break; // VO after some efforts go out from loop
   }
   ::ResetEvent(fPimpl->fEvent);

//   DWORD res = ::WaitForSingleObject(fPimpl->fEvent, INFINITE);
//   ::ResetEvent(fPimpl->fEvent);

   if (res == WAIT_TIMEOUT) { // server thread is blocked
      GlobalLock();
      return kTRUE;
   }

   fListOfCallBacks->Delete();
   return kFALSE;
}

//______________________________________________________________________________
void TGWin32ProxyBase::SendExitMessage()
{
   // send exit message to server thread

   ::PostThreadMessage(fgMainThreadId, WM_QUIT, 0, 0L);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_int_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] 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                                                     */
#include "p9_int_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0x0070000072040140 = 0x0070000072040140;
constexpr uint64_t literal_0x0000004000028000 = 0x0000004000028000;
constexpr uint64_t literal_0x00000000040101C3 = 0x00000000040101C3;
constexpr uint64_t literal_0x9554021F80100E0C = 0x9554021F80100E0C;
constexpr uint64_t literal_0b00 = 0b00;
constexpr uint64_t literal_0x010003FF00100020 = 0x010003FF00100020;
constexpr uint64_t literal_0xD8DFB200FFAFFFD7 = 0xD8DFB200FFAFFFD7;
constexpr uint64_t literal_0x0008002000002002 = 0x0008002000002002;
constexpr uint64_t literal_0xEF6437D2DE7DD3FD = 0xEF6437D2DE7DD3FD;
constexpr uint64_t literal_0x0002000410000000 = 0x0002000410000000;
constexpr uint64_t literal_0x7710CCC3E0000701 = 0x7710CCC3E0000701;
constexpr uint64_t literal_0x00001003000002 = 0x00001003000002;
constexpr uint64_t literal_0xFFFFEFFCFFFFFC = 0xFFFFEFFCFFFFFC;
constexpr uint64_t literal_0x0003C018006 = 0x0003C018006;
constexpr uint64_t literal_0xFFFDFFEFFFA = 0xFFFDFFEFFFA;

fapi2::ReturnCode p9_int_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE_Type l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE));
        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501300aull, l_scom_buffer ));

            if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_SMALL_SYSTEM))
            {
                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_1 );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_LARGE_SYSTEM))
            {
                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0 );
            }

            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_1 );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_0 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x501300aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013022ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0070000072040140 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013022ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013033ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000004000028000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013033ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013036ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x00000000040101C3 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013036ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013037ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x9554021F80100E0C );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013037ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013124ull, l_scom_buffer ));

            l_scom_buffer.insert<28, 2, 62, uint64_t>(literal_0b00 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013124ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013140ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x010003FF00100020 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013140ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013141ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xD8DFB200FFAFFFD7 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013141ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013148ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0008002000002002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013148ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013149ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xEF6437D2DE7DD3FD );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013149ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013178ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0002000410000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013178ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013179ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x7710CCC3E0000701 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013179ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501322dull, l_scom_buffer ));

            constexpr auto l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF = 0x0;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x501322dull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013270ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0x00001003000002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013270ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013271ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0xFFFFEFFCFFFFFC );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013271ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013272ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0x0003C018006 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013272ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013273ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0xFFFDFFEFFFA );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013273ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>INT FIR updates<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_int_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] 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                                                     */
#include "p9_int_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0x0070000072040140 = 0x0070000072040140;
constexpr uint64_t literal_0x0000004004028000 = 0x0000004004028000;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0x9554021F80110FCF = 0x9554021F80110FCF;
constexpr uint64_t literal_0b00 = 0b00;
constexpr uint64_t literal_0x010003FF00100020 = 0x010003FF00100020;
constexpr uint64_t literal_0xD8DFB200DFAFFFD7 = 0xD8DFB200DFAFFFD7;
constexpr uint64_t literal_0x0008002000002002 = 0x0008002000002002;
constexpr uint64_t literal_0xEF6437D2DE7DD3FD = 0xEF6437D2DE7DD3FD;
constexpr uint64_t literal_0x0002000410000000 = 0x0002000410000000;
constexpr uint64_t literal_0x7710CCC3E0000701 = 0x7710CCC3E0000701;
constexpr uint64_t literal_0x00001003000002 = 0x00001003000002;
constexpr uint64_t literal_0xFFFFEFFCFFFFFC = 0xFFFFEFFCFFFFFC;
constexpr uint64_t literal_0x0003C018006 = 0x0003C018006;
constexpr uint64_t literal_0xFFFDFFEFFFA = 0xFFFDFFEFFFA;

fapi2::ReturnCode p9_int_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE_Type l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE));
        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501300aull, l_scom_buffer ));

            if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_SMALL_SYSTEM))
            {
                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_1 );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_LARGE_SYSTEM))
            {
                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0 );
            }

            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_1 );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_0 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x501300aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013022ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0070000072040140 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013022ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013033ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000004004028000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013033ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013036ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013036ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013037ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x9554021F80110FCF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013037ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013124ull, l_scom_buffer ));

            l_scom_buffer.insert<28, 2, 62, uint64_t>(literal_0b00 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013124ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013140ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x010003FF00100020 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013140ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013141ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xD8DFB200DFAFFFD7 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013141ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013148ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0008002000002002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013148ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013149ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xEF6437D2DE7DD3FD );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013149ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013178ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0002000410000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013178ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013179ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x7710CCC3E0000701 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013179ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501322dull, l_scom_buffer ));

            constexpr auto l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF = 0x0;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x501322dull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013270ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0x00001003000002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013270ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013271ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0xFFFFEFFCFFFFFC );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013271ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013272ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0x0003C018006 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013272ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013273ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0xFFFDFFEFFFA );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013273ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.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_pcie_scominit.H
/// @brief Apply scom inits to PCIE chiplets
///
// *HWP HWP Owner: Christina Graves clgraves@us.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 1
// *HWP Consumed by:
//-----------------------------------------------------------------------------------
//
// *! ADDITIONAL COMMENTS :
//-----------------------------------------------------------------------------------

#ifndef _P9_PCIE_SCOMINIT_H_
#define _P9_PCIE_SCOMINIT_H_

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------

#include <fapi2.H>

//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------

//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode
(*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//-----------------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------------

extern "C" {

//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------

/// @brief Apply scom inits to PCIE chiplets
/// @param[in] i_target => P9 chip target
/// @return FAPI_RC_SUCCESS if the setup completes successfully,
//
    fapi2::ReturnCode p9_pcie_scominit(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
} //extern"C"

#endif //_P9_PCIE_SCOMINIT_H_
<commit_msg>PCIE Level 1 procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.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_pcie_scominit.H
/// @brief Perform PCIE Phase1 init sequence (FAPI2)
///
// *HWP HWP Owner: Christina Graves clgraves@us.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 1
// *HWP Consumed by: HB

#ifndef _P9_PCIE_SCOMINIT_H_
#define _P9_PCIE_SCOMINIT_H_

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

//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------

//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//-----------------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------------

extern "C" {

//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------

/// @brief Perform PCIE Phase1 init sequence
/// @param[in] i_target => P9 chip target
/// @return FAPI_RC_SUCCESS if the setup completes successfully,
//
    fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
} //extern"C"

#endif //_P9_PCIE_SCOMINIT_H_
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 7837 $

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

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

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

#include "mitkNDITrackingDevice.h"
#include "mitkNDIPassiveTool.h"
//#include "mitkSerialCommunication.h"
//#include "mitkNDIPassiveToolTest.cpp"
#include "mitkTestingMacros.h"
#include "mitkTrackingTypes.h"
#include "mitkTrackingTool.h"
#include "mitkStandardFileLocations.h"

/**Documentation
* NDIPassiveTool has a protected constructor and a protected itkNewMacro
* so that only it's friend class NDITrackingDevice is able to instantiate
* tool objects. Therefore, we derive from NDIPassiveTool and add a
* public itkNewMacro, so that we can instantiate and test the class
*/
class NDIPassiveToolTestClass : public mitk::NDIPassiveTool
{
public:
  mitkClassMacro(NDIPassiveToolTestClass, NDIPassiveTool);

  /** make a public constructor, so that the test is able
  *   to instantiate NDIPassiveTool
  */
  itkNewMacro(Self);

protected:
  NDIPassiveToolTestClass() : mitk::NDIPassiveTool()
  {
  }
};

int mitkNDITrackingDeviceTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("NDITrackingDevice ");

  // let's create an object of our class
  mitk::NDITrackingDevice::Pointer myNDITrackingDevice = mitk::NDITrackingDevice::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice.IsNotNull(),"Testing instantiation\n");

  MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice->GetMode() == mitk::TrackingDevice::Setup ,"Checking tracking device state == setup.\n");

  //OpenConnection
  MITK_TEST_CONDITION( (!myNDITrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because Tracking Device is not activated).");

  //CloseConnection
  MITK_TEST_CONDITION( (myNDITrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection().");

  //StartTracking
  MITK_TEST_CONDITION( (!myNDITrackingDevice->StartTracking()), "Testing behavior of method StartTracking().");

  //Beep(unsigned char count)
  MITK_TEST_CONDITION( (myNDITrackingDevice->Beep(3)== false), "Testing behavior of method Beep(). No Tracking device initialized!");

  //AddTool( const char* toolName, const char* fileName, TrackingPriority p /*= NDIPassiveTool::Dynamic*/ )
  std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data");
  const char *name = file.c_str();

  MITK_TEST_CONDITION( (myNDITrackingDevice->AddTool("Tool0", name))!=NULL, "Testing AddTool() for tool 0.");

  //GetToolCount()
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetToolCount())==1, "Testing GetToolCount() for one tool.");

  //GetTool(unsigned int toolNumber)
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetTool(0))!=NULL, "Testing GetTool() for tool 0.");

  mitk::TrackingTool::Pointer testtool = myNDITrackingDevice->GetTool(0);

  //UpdateTool(mitk::TrackingTool* tool)
  MITK_TEST_CONDITION( (!myNDITrackingDevice->UpdateTool(testtool)), "Testing behavior of method UpdateTool().\n");

  //RemoveTool(mitk::TrackingTool* tool)
  MITK_TEST_CONDITION( (myNDITrackingDevice->RemoveTool(testtool)), "Testing RemoveTool()for tool 0.");

  //SetOperationMode(OperationMode mode)
  MITK_TEST_CONDITION( (myNDITrackingDevice->SetOperationMode( mitk::MarkerTracking3D )== true ), "Testing behavior of method SetOperationMode().\n");

  //GetOperationMode()
  myNDITrackingDevice->SetOperationMode(mitk::MarkerTracking3D);
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==2),"" );

  myNDITrackingDevice->SetOperationMode(mitk::ToolTracking5D);
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==1),"" );

  myNDITrackingDevice->SetOperationMode(mitk::HybridTracking);
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==3), "Testing behavior of method GetOperationMode().\n");

  //GetMarkerPositions(MarkerPointContainerType* markerpositions)
  mitk::MarkerPointContainerType* markerpositions = new mitk::MarkerPointContainerType();
  MITK_TEST_CONDITION( (!myNDITrackingDevice->GetMarkerPositions(markerpositions)), "Testing behavior of method GetMarkerPositions().\n");
  delete markerpositions;

  // always end with this!
  MITK_TEST_END();
}<commit_msg>FIX (1773): deactivate test case that works only, if no tracking device is attached to test computer<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 7837 $

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

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

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

#include "mitkNDITrackingDevice.h"
#include "mitkNDIPassiveTool.h"
//#include "mitkSerialCommunication.h"
//#include "mitkNDIPassiveToolTest.cpp"
#include "mitkTestingMacros.h"
#include "mitkTrackingTypes.h"
#include "mitkTrackingTool.h"
#include "mitkStandardFileLocations.h"

/**Documentation
* NDIPassiveTool has a protected constructor and a protected itkNewMacro
* so that only it's friend class NDITrackingDevice is able to instantiate
* tool objects. Therefore, we derive from NDIPassiveTool and add a
* public itkNewMacro, so that we can instantiate and test the class
*/
class NDIPassiveToolTestClass : public mitk::NDIPassiveTool
{
public:
  mitkClassMacro(NDIPassiveToolTestClass, NDIPassiveTool);

  /** make a public constructor, so that the test is able
  *   to instantiate NDIPassiveTool
  */
  itkNewMacro(Self);

protected:
  NDIPassiveToolTestClass() : mitk::NDIPassiveTool()
  {
  }
};

int mitkNDITrackingDeviceTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("NDITrackingDevice ");

  // let's create an object of our class
  mitk::NDITrackingDevice::Pointer myNDITrackingDevice = mitk::NDITrackingDevice::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice.IsNotNull(),"Testing instantiation\n");

  MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice->GetMode() == mitk::TrackingDevice::Setup ,"Checking tracking device state == setup.\n");

  //OpenConnection
  //MITK_TEST_CONDITION( (!myNDITrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because Tracking Device is not activated).");
  // <-- this test is dangerous. It implies that no tracking device is connected to the dartclient pc, which could be wrong.

  //CloseConnection
  MITK_TEST_CONDITION( (myNDITrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection().");

  //StartTracking
  MITK_TEST_CONDITION( (!myNDITrackingDevice->StartTracking()), "Testing behavior of method StartTracking().");

  //Beep(unsigned char count)
  MITK_TEST_CONDITION( (myNDITrackingDevice->Beep(3)== false), "Testing behavior of method Beep(). No Tracking device initialized!");

  //AddTool( const char* toolName, const char* fileName, TrackingPriority p /*= NDIPassiveTool::Dynamic*/ )
  std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data");
  const char *name = file.c_str();

  MITK_TEST_CONDITION( (myNDITrackingDevice->AddTool("Tool0", name))!=NULL, "Testing AddTool() for tool 0.");

  //GetToolCount()
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetToolCount())==1, "Testing GetToolCount() for one tool.");

  //GetTool(unsigned int toolNumber)
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetTool(0))!=NULL, "Testing GetTool() for tool 0.");

  mitk::TrackingTool::Pointer testtool = myNDITrackingDevice->GetTool(0);

  //UpdateTool(mitk::TrackingTool* tool)
  MITK_TEST_CONDITION( (!myNDITrackingDevice->UpdateTool(testtool)), "Testing behavior of method UpdateTool().\n");

  //RemoveTool(mitk::TrackingTool* tool)
  MITK_TEST_CONDITION( (myNDITrackingDevice->RemoveTool(testtool)), "Testing RemoveTool()for tool 0.");

  //SetOperationMode(OperationMode mode)
  MITK_TEST_CONDITION( (myNDITrackingDevice->SetOperationMode( mitk::MarkerTracking3D )== true ), "Testing behavior of method SetOperationMode().\n");

  //GetOperationMode()
  myNDITrackingDevice->SetOperationMode(mitk::MarkerTracking3D);
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==2),"" );

  myNDITrackingDevice->SetOperationMode(mitk::ToolTracking5D);
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==1),"" );

  myNDITrackingDevice->SetOperationMode(mitk::HybridTracking);
  MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==3), "Testing behavior of method GetOperationMode().\n");

  //GetMarkerPositions(MarkerPointContainerType* markerpositions)
  mitk::MarkerPointContainerType* markerpositions = new mitk::MarkerPointContainerType();
  MITK_TEST_CONDITION( (!myNDITrackingDevice->GetMarkerPositions(markerpositions)), "Testing behavior of method GetMarkerPositions().\n");
  delete markerpositions;

  // always end with this!
  MITK_TEST_END();
}<|endoftext|>


<commit_before>//
//  Copyright (c) 2016 Terry Seyler
//
//  Distributed under the MIT License
//  See accompanying file LICENSE.md
//

#include <core/protocol/c4soap/c4soap_message.hpp>
#include <core/protocol/c4soap/c4soap_director.hpp>

namespace proto_net
{
    namespace protocol
    {
        namespace c4soap
        {
            std::string
            authenticate_password(unsigned long& seq, const params_array& /*params*/)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "AuthenticatePassword", seq);
                c4soap_message::param(ss, "password", "string", "root");
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_version_info(unsigned long& seq, const params_array& /*params*/)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetVersionInfo", seq);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_director_info(unsigned long& seq, const params_array& /*params*/)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetDirectorInfo", seq);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_devices_by_interface(unsigned long& seq, const params_array& params)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetDevicesByInterface", seq);
                c4soap_message::param(ss, "GUID", "string", params[0]);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_devices_by_c4i(unsigned long& seq, const params_array& params)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetDevicesByC4i", seq);
                c4soap_message::param(ss, "c4i_name", "string", params[0]);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            send_to_device(unsigned long& seq, const params_array& params)
            {
                std::stringstream ss;

                if (params.size() > 1)
                {
                    std::string id = params[0];
                    std::string cmd = params[1];

                    c4soap_message::begin_c4soap_message(ss, "SendToDevice", seq);
                    c4soap_message::param(ss, "iddevice", "number", id);
                    cmd = "<command>" + cmd + "<command>";
                    if (params.size() > 2)
                    {
                        std::string param = "";
                        for (size_t i = 2; i < params.size(); i++)
                        {
                            size_t j = i + 1;
                            if (j < params.size())
                            {
                                param += c4soap_message::get_param_value(params[i], params[j]);
                            }
                            else
                                break;
                        }
                        std::string params = "<params>" + param + "</params>";
                        cmd += params;
                    }
                    std::string device_command = "<devicecommand>" + cmd + "</devicecommand>";
                    c4soap_message::param(ss, "data", "xml", device_command);
                    c4soap_message::end_c4soap_message(ss);
                }

                return ss.str();
            }
        }
    }
}
<commit_msg>Changed type from xml to string.<commit_after>//
//  Copyright (c) 2016 Terry Seyler
//
//  Distributed under the MIT License
//  See accompanying file LICENSE.md
//

#include <core/protocol/c4soap/c4soap_message.hpp>
#include <core/protocol/c4soap/c4soap_director.hpp>

namespace proto_net
{
    namespace protocol
    {
        namespace c4soap
        {
            std::string
            authenticate_password(unsigned long& seq, const params_array& /*params*/)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "AuthenticatePassword", seq);
                c4soap_message::param(ss, "password", "string", "root");
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_version_info(unsigned long& seq, const params_array& /*params*/)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetVersionInfo", seq);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_director_info(unsigned long& seq, const params_array& /*params*/)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetDirectorInfo", seq);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_devices_by_interface(unsigned long& seq, const params_array& params)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetDevicesByInterface", seq);
                c4soap_message::param(ss, "GUID", "string", params[0]);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            get_devices_by_c4i(unsigned long& seq, const params_array& params)
            {
                std::stringstream ss;
                c4soap_message::begin_c4soap_message(ss, "GetDevicesByC4i", seq);
                c4soap_message::param(ss, "c4i_name", "string", params[0]);
                c4soap_message::end_c4soap_message(ss);

                return ss.str();
            }

            std::string
            send_to_device(unsigned long& seq, const params_array& params)
            {
                std::stringstream ss;

                if (params.size() > 1)
                {
                    std::string id = params[0];
                    std::string cmd = params[1];

                    c4soap_message::begin_c4soap_message(ss, "SendToDevice", seq);
                    c4soap_message::param(ss, "iddevice", "number", id);
                    cmd = "<command>" + cmd + "<command>";
                    if (params.size() > 2)
                    {
                        std::string param = "";
                        for (size_t i = 2; i < params.size(); i++)
                        {
                            size_t j = i + 1;
                            if (j < params.size())
                            {
                                param += c4soap_message::get_param_value(params[i], params[j]);
                            }
                            else
                                break;
                        }
                        std::string params = "<params>" + param + "</params>";
                        cmd += params;
                    }
                    std::string device_command = "<devicecommand>" + cmd + "</devicecommand>";
                    c4soap_message::param(ss, "data", "string", device_command);
                    c4soap_message::end_c4soap_message(ss);
                }

                return ss.str();
            }
        }
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "selectionindicator.h"

#include <QPen>
#include <cmath>
#include <QGraphicsScene>
#include <formeditorview.h>
#include <formeditorwidget.h>
#include <zoomaction.h>

namespace QmlDesigner {

SelectionIndicator::SelectionIndicator(LayerItem *layerItem)
    : m_layerItem(layerItem)
{
}

SelectionIndicator::~SelectionIndicator()
{
    clear();
}

void SelectionIndicator::show()
{
    foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values())
        item->show();
}

void SelectionIndicator::hide()
{
    foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values())
        item->hide();
}

void SelectionIndicator::clear()
{
    if (m_layerItem) {
        foreach (QGraphicsItem *item, m_indicatorShapeHash.values())
            m_layerItem->scene()->removeItem(item);
    }
    m_indicatorShapeHash.clear();
}

//static void alignVertices(QPolygonF &polygon, double factor)
//{
//    QMutableVectorIterator<QPointF> iterator(polygon);
//    while (iterator.hasNext()) {
//        QPointF &vertex = iterator.next();
//        vertex.setX(std::floor(vertex.x()) + factor);
//        vertex.setY(std::floor(vertex.y()) + factor);
//    }
//
//}

void SelectionIndicator::setItems(const QList<FormEditorItem*> &itemList)
{
    clear();

    foreach (FormEditorItem *item, itemList) {
        if (!item->qmlItemNode().isValid())
            continue;

        QGraphicsPolygonItem *newSelectionIndicatorGraphicsItem = new QGraphicsPolygonItem(m_layerItem.data());
        m_indicatorShapeHash.insert(item, newSelectionIndicatorGraphicsItem);
        QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect()));
        //        alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel());
        QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace);
        newSelectionIndicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace);
        newSelectionIndicatorGraphicsItem->setFlag(QGraphicsItem::ItemIsSelectable, false);

        QPen pen;
        pen.setColor(QColor(108, 141, 221));
        newSelectionIndicatorGraphicsItem->setPen(pen);
        newSelectionIndicatorGraphicsItem->setCursor(m_cursor);
    }
}

void SelectionIndicator::updateItems(const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem *item, itemList) {
        if (m_indicatorShapeHash.contains(item)) {
            QGraphicsPolygonItem *indicatorGraphicsItem =  m_indicatorShapeHash.value(item);
            QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect()));
//            alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel());
            QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace);
            indicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace);
        }
    }
}

void SelectionIndicator::setCursor(const QCursor &cursor)
{
    m_cursor = cursor;

    foreach (QGraphicsItem  *item, m_indicatorShapeHash.values())
        item->setCursor(cursor);
}

}

<commit_msg>QmlDesigner: fixing memory leak<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "selectionindicator.h"

#include <QPen>
#include <cmath>
#include <QGraphicsScene>
#include <formeditorview.h>
#include <formeditorwidget.h>
#include <zoomaction.h>

namespace QmlDesigner {

SelectionIndicator::SelectionIndicator(LayerItem *layerItem)
    : m_layerItem(layerItem)
{
}

SelectionIndicator::~SelectionIndicator()
{
    clear();
}

void SelectionIndicator::show()
{
    foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values())
        item->show();
}

void SelectionIndicator::hide()
{
    foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values())
        item->hide();
}

void SelectionIndicator::clear()
{
    if (m_layerItem) {
        foreach (QGraphicsItem *item, m_indicatorShapeHash.values()) {
            m_layerItem->scene()->removeItem(item);
            delete item;
        }
    }
    m_indicatorShapeHash.clear();
}

//static void alignVertices(QPolygonF &polygon, double factor)
//{
//    QMutableVectorIterator<QPointF> iterator(polygon);
//    while (iterator.hasNext()) {
//        QPointF &vertex = iterator.next();
//        vertex.setX(std::floor(vertex.x()) + factor);
//        vertex.setY(std::floor(vertex.y()) + factor);
//    }
//
//}

void SelectionIndicator::setItems(const QList<FormEditorItem*> &itemList)
{
    clear();

    foreach (FormEditorItem *item, itemList) {
        if (!item->qmlItemNode().isValid())
            continue;

        QGraphicsPolygonItem *newSelectionIndicatorGraphicsItem = new QGraphicsPolygonItem(m_layerItem.data());
        m_indicatorShapeHash.insert(item, newSelectionIndicatorGraphicsItem);
        QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect()));
        //        alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel());
        QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace);
        newSelectionIndicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace);
        newSelectionIndicatorGraphicsItem->setFlag(QGraphicsItem::ItemIsSelectable, false);

        QPen pen;
        pen.setColor(QColor(108, 141, 221));
        newSelectionIndicatorGraphicsItem->setPen(pen);
        newSelectionIndicatorGraphicsItem->setCursor(m_cursor);
    }
}

void SelectionIndicator::updateItems(const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem *item, itemList) {
        if (m_indicatorShapeHash.contains(item)) {
            QGraphicsPolygonItem *indicatorGraphicsItem =  m_indicatorShapeHash.value(item);
            QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect()));
//            alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel());
            QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace);
            indicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace);
        }
    }
}

void SelectionIndicator::setCursor(const QCursor &cursor)
{
    m_cursor = cursor;

    foreach (QGraphicsItem  *item, m_indicatorShapeHash.values())
        item->setCursor(cursor);
}

}

<|endoftext|>