<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TaskPaneModule.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 15:55:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "TaskPaneModule.hxx"
#include "ReadOnlyModeObserver.hxx"
#include "framework/FrameworkHelper.hxx"

#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/drawing/framework/XControllerManager.hpp>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/compbase1.hxx>
#include <boost/enable_shared_from_this.hpp>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;
using ::sd::framework::FrameworkHelper;

namespace sd { namespace framework {

namespace {

typedef ::cppu::WeakComponentImplHelper1 <
      ::com::sun::star::frame::XStatusListener
    > LocalReadOnlyModeObserverInterfaceBase;

/** This local class enables or disables the ResourceManager of a
    TaskPaneModule.  It connects to a ReadOnlyModeObserver and is called
    when the state of the .uno:EditDoc command changes.  When either the
    ResourceManager or the ReadOnlyModeObserver are disposed then the
    LocalReadOnlyModeObserver disposes itself.  The link
    between the ResourceManager and the ReadOnlyModeObserver is removed and
    the ReadOnlyModeObserver typically looses its last reference and is
    destroyed.
*/
class LocalReadOnlyModeObserver
    : private MutexOwner,
      public LocalReadOnlyModeObserverInterfaceBase
{
public:
    LocalReadOnlyModeObserver (
        const Reference<frame::XController>& rxController,
        const ::rtl::Reference<ResourceManager>& rpResourceManager)
        : MutexOwner(),
          LocalReadOnlyModeObserverInterfaceBase(maMutex),
          mpResourceManager(rpResourceManager),
          mpObserver(new ReadOnlyModeObserver(rxController))
    {
        mpObserver->AddStatusListener(this);

        Reference<lang::XComponent> xComponent (
            static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);
        if (xComponent.is())
            xComponent->addEventListener(this);
    }

    ~LocalReadOnlyModeObserver (void)
    {
    }

    virtual void SAL_CALL disposing (void)
    {
        Reference<lang::XComponent> xComponent (static_cast<XWeak*>(mpObserver.get()), UNO_QUERY);
        if (xComponent.is())
            xComponent->dispose();

        xComponent = Reference<lang::XComponent>(
            static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);
        if (xComponent.is())
            xComponent->removeEventListener(this);

    }

    virtual void SAL_CALL disposing (const com::sun::star::lang::EventObject& rEvent)
        throw(RuntimeException)
    {
        if (rEvent.Source == Reference<XInterface>(static_cast<XWeak*>(mpObserver.get())))
        {
            mpObserver = NULL;
        }
        else if (rEvent.Source == Reference<XInterface>(
            static_cast<XWeak*>(mpResourceManager.get())))
        {
            mpResourceManager = NULL;
        }
        dispose();
    }

    virtual void SAL_CALL statusChanged (const com::sun::star::frame::FeatureStateEvent& rEvent)
        throw(RuntimeException)
    {
        bool bReadWrite (true);
        if (rEvent.IsEnabled)
            rEvent.State >>= bReadWrite;

        if (bReadWrite)
            mpResourceManager->Enable();
        else
            mpResourceManager->Disable();
    }

private:
    ::rtl::Reference<ResourceManager> mpResourceManager;
    ::rtl::Reference<ReadOnlyModeObserver> mpObserver;

};
}

//===== TaskPaneModule ====================================================

void TaskPaneModule::Initialize (const Reference<frame::XController>& rxController)
{
    ::rtl::Reference<ResourceManager> pResourceManager (
        new ResourceManager(
            rxController,
            FrameworkHelper::CreateResourceId(
                FrameworkHelper::msTaskPaneURL,
                FrameworkHelper::msRightPaneURL)));
    pResourceManager->AddActiveMainView(FrameworkHelper::msImpressViewURL);
    pResourceManager->AddActiveMainView(FrameworkHelper::msNotesViewURL);
    pResourceManager->AddActiveMainView(FrameworkHelper::msHandoutViewURL);
    pResourceManager->AddActiveMainView(FrameworkHelper::msSlideSorterURL);

    new LocalReadOnlyModeObserver(rxController, pResourceManager);

    try
    {
        // Create the TaskPaneService.
        Reference<lang::XMultiServiceFactory> xFactory (::comphelper::getProcessServiceFactory());
        const OUString sServiceName (::rtl::OUString::createFromAscii(
            "com.sun.star.drawing.framework.TaskPaneService"));
        Reference<XResourceController> xResourceController (
            xFactory->createInstance(sServiceName), UNO_QUERY_THROW);

        // Initialize it.
        Sequence<Any> aInitializationArguments(1);
        aInitializationArguments[0] = makeAny(rxController);
        Reference<lang::XInitialization> xInit (xResourceController, UNO_QUERY_THROW);
        xInit->initialize(aInitializationArguments);

        // Register it at the controller manager.
        Reference<XControllerManager> xControllerManager(rxController, UNO_QUERY_THROW);
        xControllerManager->registerResourceController(sServiceName, xResourceController);
    }
    catch (RuntimeException)
    {
    }
}

} } // end of namespace sd::framework
<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007/06/19 08:27:38 af 1.2.22.1: #i18486# The task pane service is not used anymore.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TaskPaneModule.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 13:40:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "TaskPaneModule.hxx"
#include "ReadOnlyModeObserver.hxx"
#include "framework/FrameworkHelper.hxx"

#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/drawing/framework/XControllerManager.hpp>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/compbase1.hxx>
#include <boost/enable_shared_from_this.hpp>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;
using ::sd::framework::FrameworkHelper;

namespace sd { namespace framework {

namespace {

typedef ::cppu::WeakComponentImplHelper1 <
      ::com::sun::star::frame::XStatusListener
    > LocalReadOnlyModeObserverInterfaceBase;

/** This local class enables or disables the ResourceManager of a
    TaskPaneModule.  It connects to a ReadOnlyModeObserver and is called
    when the state of the .uno:EditDoc command changes.  When either the
    ResourceManager or the ReadOnlyModeObserver are disposed then the
    LocalReadOnlyModeObserver disposes itself.  The link
    between the ResourceManager and the ReadOnlyModeObserver is removed and
    the ReadOnlyModeObserver typically looses its last reference and is
    destroyed.
*/
class LocalReadOnlyModeObserver
    : private MutexOwner,
      public LocalReadOnlyModeObserverInterfaceBase
{
public:
    LocalReadOnlyModeObserver (
        const Reference<frame::XController>& rxController,
        const ::rtl::Reference<ResourceManager>& rpResourceManager)
        : MutexOwner(),
          LocalReadOnlyModeObserverInterfaceBase(maMutex),
          mpResourceManager(rpResourceManager),
          mpObserver(new ReadOnlyModeObserver(rxController))
    {
        mpObserver->AddStatusListener(this);

        Reference<lang::XComponent> xComponent (
            static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);
        if (xComponent.is())
            xComponent->addEventListener(this);
    }

    ~LocalReadOnlyModeObserver (void)
    {
    }

    virtual void SAL_CALL disposing (void)
    {
        Reference<lang::XComponent> xComponent (static_cast<XWeak*>(mpObserver.get()), UNO_QUERY);
        if (xComponent.is())
            xComponent->dispose();

        xComponent = Reference<lang::XComponent>(
            static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);
        if (xComponent.is())
            xComponent->removeEventListener(this);

    }

    virtual void SAL_CALL disposing (const com::sun::star::lang::EventObject& rEvent)
        throw(RuntimeException)
    {
        if (rEvent.Source == Reference<XInterface>(static_cast<XWeak*>(mpObserver.get())))
        {
            mpObserver = NULL;
        }
        else if (rEvent.Source == Reference<XInterface>(
            static_cast<XWeak*>(mpResourceManager.get())))
        {
            mpResourceManager = NULL;
        }
        dispose();
    }

    virtual void SAL_CALL statusChanged (const com::sun::star::frame::FeatureStateEvent& rEvent)
        throw(RuntimeException)
    {
        bool bReadWrite (true);
        if (rEvent.IsEnabled)
            rEvent.State >>= bReadWrite;

        if (bReadWrite)
            mpResourceManager->Enable();
        else
            mpResourceManager->Disable();
    }

private:
    ::rtl::Reference<ResourceManager> mpResourceManager;
    ::rtl::Reference<ReadOnlyModeObserver> mpObserver;

};
}

//===== TaskPaneModule ====================================================

void TaskPaneModule::Initialize (const Reference<frame::XController>& rxController)
{
    ::rtl::Reference<ResourceManager> pResourceManager (
        new ResourceManager(
            rxController,
            FrameworkHelper::CreateResourceId(
                FrameworkHelper::msTaskPaneURL,
                FrameworkHelper::msRightPaneURL)));
    pResourceManager->AddActiveMainView(FrameworkHelper::msImpressViewURL);
    pResourceManager->AddActiveMainView(FrameworkHelper::msNotesViewURL);
    pResourceManager->AddActiveMainView(FrameworkHelper::msHandoutViewURL);
    pResourceManager->AddActiveMainView(FrameworkHelper::msSlideSorterURL);

    new LocalReadOnlyModeObserver(rxController, pResourceManager);
}

} } // end of namespace sd::framework
<|endoftext|>


<commit_before>#define ProofEventProc_cxx
// The class definition in ProofEventProc.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.

// The following methods are defined in this file:
//    Begin():        called everytime a loop on the tree starts,
//                    a convenient place to create your histograms.
//    SlaveBegin():   called after Begin(), when on PROOF called only on the
//                    slave servers.
//    Process():      called for each event, in this function you decide what
//                    to read and fill your histograms.
//    SlaveTerminate: called at the end of the loop on the tree, when on PROOF
//                    called only on the slave servers.
//    Terminate():    called at the end of the loop on the tree,
//                    a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// Root > T->Process("ProofEventProc.C")
// Root > T->Process("ProofEventProc.C","some options")
// Root > T->Process("ProofEventProc.C+")
//

#include "ProofEventProc.h"
#include <TStyle.h>
#include "TCanvas.h"
#include "TH1F.h"
#include "TH1I.h"

void ProofEventProc::Begin(TTree *)
{
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();

}

void ProofEventProc::SlaveBegin(TTree *tree)
{
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).

   Init(tree);

   // How much to read
   fFullRead = kFALSE;
   TNamed *nm = dynamic_cast<TNamed *>(fInput->FindObject("ProofEventProc_Read"));
   if (nm && !strcmp(nm->GetTitle(), "readall"))
      fFullRead = kTRUE;
   Info("SlaveBegin", "'%s' reading", (fFullRead ? "full" : "optimized"));

   TString option = GetOption();

   fPtHist = new TH1F("pt_dist","p_{T} Distribution",100,0,5);
   fPtHist->SetDirectory(0);
   fPtHist->GetXaxis()->SetTitle("p_{T}");
   fPtHist->GetYaxis()->SetTitle("dN/p_{T}dp_{T}");

   fOutput->Add(fPtHist);

   fNTracksHist = new TH1I("ntracks_dist","N_{Tracks} per Event Distribution",5,0,5);
   fNTracksHist->SetDirectory(0);
   fNTracksHist->GetXaxis()->SetTitle("N_{Tracks}");
   fNTracksHist->GetYaxis()->SetTitle("N_{Events}");

   fOutput->Add(fNTracksHist);

}

Bool_t ProofEventProc::Process(Long64_t entry)
{
   // The Process() function is called for each entry in the tree (or possibly
   // keyed object in the case of PROOF) to be processed. The entry argument
   // specifies which entry in the currently loaded tree is to be processed.
   // It can be passed to either TTree::GetEntry() or TBranch::GetEntry()
   // to read either all or the required parts of the data. When processing
   // keyed objects with PROOF, the object is already loaded and is available
   // via the fObject pointer.
   //
   // This function should contain the "body" of the analysis. It can contain
   // simple or elaborate selection criteria, run algorithms on the data
   // of the event and typically fill histograms.

   // WARNING when a selector is used with a TChain, you must use
   //  the pointer to the current TTree to call GetEntry(entry).
   //  The entry is always the local entry number in the current tree.
   //  Assuming that fChain is the pointer to the TChain being processed,
   //  use fChain->GetTree()->GetEntry(entry).

   if (fFullRead) {
      fChain->GetTree()->GetEntry(entry);
   } else {
      b_event_fNtrack->GetEntry(entry);
   }

   fNTracksHist->Fill(fNtrack);

   if (fNtrack > 0) {
      if (!fFullRead) b_fTracks->GetEntry(entry);
      for (Int_t j=0;j<fTracks->GetEntries();j++){
         Track *curtrack = dynamic_cast<Track*>(fTracks->At(j));
         fPtHist->Fill(curtrack->GetPt(),1./curtrack->GetPt());
      }
      fTracks->Clear("C");
   }

   return kTRUE;
}

void ProofEventProc::SlaveTerminate()
{
   // The SlaveTerminate() function is called after all entries or objects
   // have been processed. When running with PROOF SlaveTerminate() is called
   // on each slave server.

}

void ProofEventProc::Terminate()
{
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
   // the results graphically or save the results to file.

   TCanvas* canvas = new TCanvas("can","can",800,600);
   canvas->SetBorderMode(0);
   canvas->SetLogy();
   TH1F* h = dynamic_cast<TH1F*>(fOutput->FindObject("pt_dist"));
   if (h) h->DrawCopy();
   else Warning("Terminate", "no pt dist found");

}
<commit_msg>Add missing protections to be able to run in a non-PROOF session<commit_after>#define ProofEventProc_cxx
// The class definition in ProofEventProc.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.

// The following methods are defined in this file:
//    Begin():        called everytime a loop on the tree starts,
//                    a convenient place to create your histograms.
//    SlaveBegin():   called after Begin(), when on PROOF called only on the
//                    slave servers.
//    Process():      called for each event, in this function you decide what
//                    to read and fill your histograms.
//    SlaveTerminate: called at the end of the loop on the tree, when on PROOF
//                    called only on the slave servers.
//    Terminate():    called at the end of the loop on the tree,
//                    a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// Root > T->Process("ProofEventProc.C")
// Root > T->Process("ProofEventProc.C","some options")
// Root > T->Process("ProofEventProc.C+")
//

#include "ProofEventProc.h"
#include <TStyle.h>
#include "TCanvas.h"
#include "TH1F.h"
#include "TH1I.h"

void ProofEventProc::Begin(TTree *)
{
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();

}

void ProofEventProc::SlaveBegin(TTree *tree)
{
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).

   Init(tree);

   // How much to read
   fFullRead = kFALSE;
   TNamed *nm = 0;
   if (fInput)
      nm = dynamic_cast<TNamed *>(fInput->FindObject("ProofEventProc_Read"));
   if (nm && !strcmp(nm->GetTitle(), "readall"))
      fFullRead = kTRUE;
   Info("SlaveBegin", "'%s' reading", (fFullRead ? "full" : "optimized"));

   TString option = GetOption();

   fPtHist = new TH1F("pt_dist","p_{T} Distribution",100,0,5);
   fPtHist->SetDirectory(0);
   fPtHist->GetXaxis()->SetTitle("p_{T}");
   fPtHist->GetYaxis()->SetTitle("dN/p_{T}dp_{T}");

   fOutput->Add(fPtHist);

   fNTracksHist = new TH1I("ntracks_dist","N_{Tracks} per Event Distribution",5,0,5);
   fNTracksHist->SetDirectory(0);
   fNTracksHist->GetXaxis()->SetTitle("N_{Tracks}");
   fNTracksHist->GetYaxis()->SetTitle("N_{Events}");

   fOutput->Add(fNTracksHist);

}

Bool_t ProofEventProc::Process(Long64_t entry)
{
   // The Process() function is called for each entry in the tree (or possibly
   // keyed object in the case of PROOF) to be processed. The entry argument
   // specifies which entry in the currently loaded tree is to be processed.
   // It can be passed to either TTree::GetEntry() or TBranch::GetEntry()
   // to read either all or the required parts of the data. When processing
   // keyed objects with PROOF, the object is already loaded and is available
   // via the fObject pointer.
   //
   // This function should contain the "body" of the analysis. It can contain
   // simple or elaborate selection criteria, run algorithms on the data
   // of the event and typically fill histograms.

   // WARNING when a selector is used with a TChain, you must use
   //  the pointer to the current TTree to call GetEntry(entry).
   //  The entry is always the local entry number in the current tree.
   //  Assuming that fChain is the pointer to the TChain being processed,
   //  use fChain->GetTree()->GetEntry(entry).

   if (fFullRead) {
      fChain->GetTree()->GetEntry(entry);
   } else {
      b_event_fNtrack->GetEntry(entry);
   }

   fNTracksHist->Fill(fNtrack);

   if (fNtrack > 0) {
      if (!fFullRead) b_fTracks->GetEntry(entry);
      for (Int_t j=0;j<fTracks->GetEntries();j++){
         Track *curtrack = dynamic_cast<Track*>(fTracks->At(j));
         if (curtrack)
            fPtHist->Fill(curtrack->GetPt(),1./curtrack->GetPt());
      }
      fTracks->Clear("C");
   }

   return kTRUE;
}

void ProofEventProc::SlaveTerminate()
{
   // The SlaveTerminate() function is called after all entries or objects
   // have been processed. When running with PROOF SlaveTerminate() is called
   // on each slave server.

}

void ProofEventProc::Terminate()
{
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
   // the results graphically or save the results to file.

   TCanvas* canvas = new TCanvas("can","can",800,600);
   canvas->SetBorderMode(0);
   canvas->SetLogy();
   TH1F* h = dynamic_cast<TH1F*>(fOutput->FindObject("pt_dist"));
   if (h) h->DrawCopy();
   else Warning("Terminate", "no pt dist found");

}
<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "value.h"
#include <vespa/vespalib/util/compressor.h>
#include <xxhash.h>

using vespalib::compression::compress;
using vespalib::compression::decompress;

namespace search::docstore {

Value::Value()
    : _syncToken(0),
      _uncompressedCrc(0),
      _compressedSize(0),
      _uncompressedSize(0),
      _buf(),
      _compression(CompressionConfig::NONE)
{}

Value::Value(uint64_t syncToken)
    : _syncToken(syncToken),
      _uncompressedCrc(0),
      _compressedSize(0),
      _uncompressedSize(0),
      _buf(),
      _compression(CompressionConfig::NONE)
{}

Value::Value(const Value &rhs) = default;

Value::~Value() = default;

const void *
Value::get() const {
    return _buf ? _buf->get() : nullptr;
}

void
Value::set(vespalib::DataBuffer &&buf, ssize_t len) {
    set(std::move(buf), len, CompressionConfig());
}

namespace {

vespalib::alloc::Alloc
compact(size_t sz, vespalib::alloc::Alloc buf) {
    if (vespalib::roundUp2inN(sz) < vespalib::roundUp2inN(buf.size())) {
        vespalib::alloc::Alloc shrunk = buf.create(sz);
        memcpy(shrunk.get(), buf.get(), sz);
        return shrunk;
    }
    return buf;
}

}
void
Value::set(vespalib::DataBuffer &&buf, ssize_t len, const CompressionConfig &compression) {
    assert(len < std::numeric_limits<uint32_t>::max());
    //Underlying buffer must be identical to allow swap.
    vespalib::DataBuffer compressed(buf.getData(), 0u);
    vespalib::ConstBufferRef input(buf.getData(), len);
    CompressionConfig::Type type = compress(compression, input, compressed, true);
    _compressedSize = compressed.getDataLen();
    _compression = type;
    _uncompressedSize = len;
    _uncompressedCrc = XXH64(input.c_str(), input.size(), 0);
    _buf = std::make_shared<Alloc>(compact(_compressedSize,(buf.getData() == compressed.getData())
                                                           ? std::move(buf).stealBuffer()
                                                           : std::move(compressed).stealBuffer()));

    assert(((type == CompressionConfig::NONE) &&
            (len == ssize_t(_compressedSize))) ||
           ((type != CompressionConfig::NONE) &&
            (len > ssize_t(_compressedSize))));
}

Value::Result
Value::decompressed() const {
    vespalib::DataBuffer uncompressed(_buf.get(), (size_t) 0);
    decompress(getCompression(), getUncompressedSize(), vespalib::ConstBufferRef(*this, size()), uncompressed, true);
    uint64_t crc = XXH64(uncompressed.getData(), uncompressed.getDataLen(), 0);
    return std::make_pair<vespalib::DataBuffer, bool>(std::move(uncompressed), crc == _uncompressedCrc);
}

}
<commit_msg>Use 32M as mmap limit during decompression of documents<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "value.h"
#include <vespa/vespalib/util/compressor.h>
#include <xxhash.h>

using vespalib::compression::compress;
using vespalib::compression::decompress;

namespace search::docstore {

Value::Value()
    : _syncToken(0),
      _uncompressedCrc(0),
      _compressedSize(0),
      _uncompressedSize(0),
      _buf(),
      _compression(CompressionConfig::NONE)
{}

Value::Value(uint64_t syncToken)
    : _syncToken(syncToken),
      _uncompressedCrc(0),
      _compressedSize(0),
      _uncompressedSize(0),
      _buf(),
      _compression(CompressionConfig::NONE)
{}

Value::Value(const Value &rhs) = default;

Value::~Value() = default;

const void *
Value::get() const {
    return _buf ? _buf->get() : nullptr;
}

void
Value::set(vespalib::DataBuffer &&buf, ssize_t len) {
    set(std::move(buf), len, CompressionConfig());
}

namespace {

vespalib::alloc::Alloc
compact(size_t sz, vespalib::alloc::Alloc buf) {
    if (vespalib::roundUp2inN(sz) < vespalib::roundUp2inN(buf.size())) {
        vespalib::alloc::Alloc shrunk = buf.create(sz);
        memcpy(shrunk.get(), buf.get(), sz);
        return shrunk;
    }
    return buf;
}

}
void
Value::set(vespalib::DataBuffer &&buf, ssize_t len, const CompressionConfig &compression) {
    assert(len < std::numeric_limits<uint32_t>::max());
    //Underlying buffer must be identical to allow swap.
    vespalib::DataBuffer compressed(buf.getData(), 0u);
    vespalib::ConstBufferRef input(buf.getData(), len);
    CompressionConfig::Type type = compress(compression, input, compressed, true);
    _compressedSize = compressed.getDataLen();
    _compression = type;
    _uncompressedSize = len;
    _uncompressedCrc = XXH64(input.c_str(), input.size(), 0);
    _buf = std::make_shared<Alloc>(compact(_compressedSize,(buf.getData() == compressed.getData())
                                                           ? std::move(buf).stealBuffer()
                                                           : std::move(compressed).stealBuffer()));

    assert(((type == CompressionConfig::NONE) &&
            (len == ssize_t(_compressedSize))) ||
           ((type != CompressionConfig::NONE) &&
            (len > ssize_t(_compressedSize))));
}

Value::Result
Value::decompressed() const {
    vespalib::DataBuffer uncompressed(0, 1, Alloc::alloc(0, 16 * vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE));
    decompress(getCompression(), getUncompressedSize(), vespalib::ConstBufferRef(*this, size()), uncompressed, true);
    uint64_t crc = XXH64(uncompressed.getData(), uncompressed.getDataLen(), 0);
    return std::make_pair<vespalib::DataBuffer, bool>(std::move(uncompressed), crc == _uncompressedCrc);
}

}
<|endoftext|>


<commit_before>// Example of analysis class for the H1 data using code generated by MakeProxy.
// ===========================================================================
//
// This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.
// One can access these data sets (277 MBytes) from the standard Root web site
// at:       ftp://root.cern.ch/root/h1analysis/
// The Physics plots below generated by this example cannot be produced when
// using smaller data sets.
//
// There are several ways to analyze data stored in a Root Tree
//   -Using TTree::Draw: This is very convenient and efficient for small tasks.
//     A TTree::Draw call produces one histogram at the time. The histogram
//     is automatically generated. The selection expression may be specified
//     in the command line.
//
//   -Using the TTreeViewer: This is a graphical interface to TTree::Draw
//      with the same functionality.
//
//   -Using the code generated by TTree::MakeClass: In this case, the user
//      creates an instance of the analysis class. He has the control over
//      the event loop and he can generate an unlimited number of histograms.
//
//   -Using the code generated by TTree::MakeSelector. Like for the code
//      generated by TTree::MakeClass, the user can do complex analysis.
//      However, he cannot control the event loop. The event loop is controlled
//      by TTree::Process called by the user. This solution is illustrated
//      by the current code. The advantage of this method is that it can be run
//      in a parallel environment using PROOF (the Parallel Root Facility).
//
// A chain of 4 files (originally converted from PAW ntuples) is used
// to illustrate the various ways to loop on Root data sets.
// Each data set contains a Root Tree named "h42"
//
// h1analysProxy.C can be used either via TTree::Draw:
//       h42->Draw("h1analysisProxy.C");
// or it can be used directly with TTree::MakeProxy, for example to generate a
// shared library.   TTree::MakeProxy will generate a TSelector skeleton that
// include h1analysProxy.C:
//       h42->MakeProxy("h1sel","h1analysisProxy.C");
// This produces one file: h1sel.h which does a #include "h1analysProxy.C"
// The h1sel class is derived from the Root class TSelector and can then
// be used as:
//      h42->Process("h1sel.h+");
//
// The following members functions are called by the TTree::Process functions.
//    h1analysProxy_Begin():      called everytime a loop on the tree starts.
//                                a convenient place to create your histograms.
//    h1analysProxy_SlaveBegin():
//
//    h1analysProxy_Notify():     This function is called at the first entry of a new Tree
//                                in a chain.
//    h1analysProxy_Process():    called to analyze each entry.
//
//    h1analysProxy_SlaveTerminate():
//
//    h1analysProxy_Terminate():    called at the end of a loop on a TTree.
//                                  a convenient place to draw/fit your histograms.
//
//   To use this file, try the following session
//
// Root > gROOT->Time(); //will show RT & CPU time per command
//
//==>   A-  create a TChain with the 4 H1 data files
// The chain can be created by executed the short macro h1chain.C below:
// {
//   TChain chain("h42");
//   chain.Add("$H1/dstarmb.root");  //  21330730 bytes  21920 events
//   chain.Add("$H1/dstarp1a.root"); //  71464503 bytes  73243 events
//   chain.Add("$H1/dstarp1b.root"); //  83827959 bytes  85597 events
//   chain.Add("$H1/dstarp2.root");  // 100675234 bytes 103053 events
//   //where $H1 is a system symbol pointing to the H1 data directory.
// }
//
// Root > .x h1chain.C
//
//==>   B- loop on all events
// Root > chain.Draw("h1analysisProxy.C")
//
//==>   C- same as B, but in addition fill the event list with selected entries.
// The event list is saved to a file "elist.root" by the Terminate function.
// To see the list of selected events, you can do elist->Print("all").
// The selection function has selected 7525 events out of the 283813 events
// in the chain of files. (2.65 per cent)
// Root > chain.Draw("h1analysisProxy.C","","fillList")
//
//==>   D- Process only entries in the event list
// The event list is read from the file in elist.root generated by step C
// Root > chain.Draw("h1analysisProxy.C","","useList")
////
// The commands executed with the 3 different methods B,C and D
// produce two canvases shown below:
// begin_html the Dstar plot end_html
// begin_html the Tau D0 plot end_html
//
//Author; Philippe Canal from original h1analysis.C by Rene Brun

TEventList *elist;
Bool_t useList, fillList;
TH1F *hdmd;
TH2F *h2;

//_____________________________________________________________________
void h1analysisProxy_Begin(TTree * /* tree */ )
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (begin) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");
}

//_____________________________________________________________________
void h1analysisProxy_SlaveBegin(TTree *tree)
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //initialize the Tree branch addresses
   Init(tree);

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (slave) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");

   //create histograms
   hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17);
   h2   = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6);

   fOutput->Add(hdmd);
   fOutput->Add(h2);

   //process cases with event list
   fillList = kFALSE;
   useList  = kFALSE;
   tree->SetEventList(0);
   delete gDirectory->GetList()->FindObject("elist");

   // case when one creates/fills the event list
   if (option.Contains("fillList")) {
      fillList = kTRUE;
      elist = new TEventList("elist","selection from Cut",5000);
   } else elist = 0;

   // case when one uses the event list generated in a previous call
   if (option.Contains("useList")) {
      useList  = kTRUE;
      TFile f("elist.root");
      elist = (TEventList*)f.Get("elist");
      if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist
      tree->SetEventList(elist);
   }

}

Double_t h1analysisProxy() {
   return 0;
}

//_____________________________________________________________________
Bool_t h1analysisProxy_Process(Long64_t entry)
{
// entry is the entry number in the current Tree
// Selection function to select D* and D0.

   //in case one event list is given in input, the selection has already been done.
   if (!useList) {

      float f1 = md0_d;
      float f2 = md0_d-1.8646;
      bool test = TMath::Abs(md0_d-1.8646) >= 0.04;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;
      if (ptds_d <= 2.5) return kFALSE;
      if (TMath::Abs(etads_d) >= 1.5) return kFALSE;

      int cik = ik-1;    //original ik used f77 convention starting at 1
      int cipi = ipi-1;  //original ipi used f77 convention starting at 1

      f1 = nhitrp[cik];
      f2 = nhitrp[cipi];
      test = nhitrp[cik]*nhitrp[cipi] <= 1;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;
      if (rend[cik] -rstart[cik]  <= 22) return kFALSE;
      if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;
      if (nlhk[cik] <= 0.1)    return kFALSE;
      if (nlhpi[cipi] <= 0.1)  return kFALSE;
      // fix because read-only
      if (nlhpi[ipis-1] <= 0.1) return kFALSE;
      if (njets < 1)          return kFALSE;

   }
   // if option fillList, fill the event list
   if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));

   //fill some histograms
   hdmd->Fill(dm_d);
   h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d);

   return kTRUE;
}

//_____________________________________________________________________
void h1analysisProxy_SlaveTerminate()
{
   // nothing to be done
   printf("Terminate (slave) h1analysis\n");
}

//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
   printf("Terminate (final) h1analysis\n");

   // function called at the end of the event loop

   hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
   h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));

   if (hdmd == 0 || h2 == 0) {
      Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
      return;
   }

   //create the canvas for the h1analysis fit
   gStyle->SetOptFit();
   TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
   c1->SetBottomMargin(0.15);
   hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
   hdmd->GetXaxis()->SetTitleOffset(1.4);

   //fit histogram hdmd with function f5 using the loglikelihood option
   TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
   f5->SetParameters(1000000, .25, 2000, .1454, .001);
   hdmd->Fit("f5","lr");

   //create the canvas for tau d0
   gStyle->SetOptFit(0);
   gStyle->SetOptStat(1100);
   TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
   c2->SetGrid();
   c2->SetBottomMargin(0.15);

   // Project slices of 2-d histogram h2 along X , then fit each slice
   // with function f2 and make a histogram for each fit parameter
   // Note that the generated histograms are added to the list of objects
   // in the current directory.
   TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
   f2->SetParameters(10000, 10);
   h2->FitSlicesX(f2,0,0,1,"qln");
   TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
   h2_1->GetXaxis()->SetTitle("#tau[ps]");
   h2_1->SetMarkerStyle(21);
   h2_1->Draw();
   c2->Update();
   TLine *line = new TLine(0,0,0,c2->GetUymax());
   line->Draw();

   //save the event list to a Root file if one was produced
   if (fillList) {
      TFile efile("elist.root","recreate");
      elist->Write();
   }
}
<commit_msg>Fix arguments to FitSlicesX (fix #21519 to h1analysis.C)<commit_after>// Example of analysis class for the H1 data using code generated by MakeProxy.
// ===========================================================================
//
// This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.
// One can access these data sets (277 MBytes) from the standard Root web site
// at:       ftp://root.cern.ch/root/h1analysis/
// The Physics plots below generated by this example cannot be produced when
// using smaller data sets.
//
// There are several ways to analyze data stored in a Root Tree
//   -Using TTree::Draw: This is very convenient and efficient for small tasks.
//     A TTree::Draw call produces one histogram at the time. The histogram
//     is automatically generated. The selection expression may be specified
//     in the command line.
//
//   -Using the TTreeViewer: This is a graphical interface to TTree::Draw
//      with the same functionality.
//
//   -Using the code generated by TTree::MakeClass: In this case, the user
//      creates an instance of the analysis class. He has the control over
//      the event loop and he can generate an unlimited number of histograms.
//
//   -Using the code generated by TTree::MakeSelector. Like for the code
//      generated by TTree::MakeClass, the user can do complex analysis.
//      However, he cannot control the event loop. The event loop is controlled
//      by TTree::Process called by the user. This solution is illustrated
//      by the current code. The advantage of this method is that it can be run
//      in a parallel environment using PROOF (the Parallel Root Facility).
//
// A chain of 4 files (originally converted from PAW ntuples) is used
// to illustrate the various ways to loop on Root data sets.
// Each data set contains a Root Tree named "h42"
//
// h1analysProxy.C can be used either via TTree::Draw:
//       h42->Draw("h1analysisProxy.C");
// or it can be used directly with TTree::MakeProxy, for example to generate a
// shared library.   TTree::MakeProxy will generate a TSelector skeleton that
// include h1analysProxy.C:
//       h42->MakeProxy("h1sel","h1analysisProxy.C");
// This produces one file: h1sel.h which does a #include "h1analysProxy.C"
// The h1sel class is derived from the Root class TSelector and can then
// be used as:
//      h42->Process("h1sel.h+");
//
// The following members functions are called by the TTree::Process functions.
//    h1analysProxy_Begin():      called everytime a loop on the tree starts.
//                                a convenient place to create your histograms.
//    h1analysProxy_SlaveBegin():
//
//    h1analysProxy_Notify():     This function is called at the first entry of a new Tree
//                                in a chain.
//    h1analysProxy_Process():    called to analyze each entry.
//
//    h1analysProxy_SlaveTerminate():
//
//    h1analysProxy_Terminate():    called at the end of a loop on a TTree.
//                                  a convenient place to draw/fit your histograms.
//
//   To use this file, try the following session
//
// Root > gROOT->Time(); //will show RT & CPU time per command
//
//==>   A-  create a TChain with the 4 H1 data files
// The chain can be created by executed the short macro h1chain.C below:
// {
//   TChain chain("h42");
//   chain.Add("$H1/dstarmb.root");  //  21330730 bytes  21920 events
//   chain.Add("$H1/dstarp1a.root"); //  71464503 bytes  73243 events
//   chain.Add("$H1/dstarp1b.root"); //  83827959 bytes  85597 events
//   chain.Add("$H1/dstarp2.root");  // 100675234 bytes 103053 events
//   //where $H1 is a system symbol pointing to the H1 data directory.
// }
//
// Root > .x h1chain.C
//
//==>   B- loop on all events
// Root > chain.Draw("h1analysisProxy.C")
//
//==>   C- same as B, but in addition fill the event list with selected entries.
// The event list is saved to a file "elist.root" by the Terminate function.
// To see the list of selected events, you can do elist->Print("all").
// The selection function has selected 7525 events out of the 283813 events
// in the chain of files. (2.65 per cent)
// Root > chain.Draw("h1analysisProxy.C","","fillList")
//
//==>   D- Process only entries in the event list
// The event list is read from the file in elist.root generated by step C
// Root > chain.Draw("h1analysisProxy.C","","useList")
////
// The commands executed with the 3 different methods B,C and D
// produce two canvases shown below:
// begin_html the Dstar plot end_html
// begin_html the Tau D0 plot end_html
//
//Author; Philippe Canal from original h1analysis.C by Rene Brun

TEventList *elist;
Bool_t useList, fillList;
TH1F *hdmd;
TH2F *h2;

//_____________________________________________________________________
void h1analysisProxy_Begin(TTree * /* tree */ )
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (begin) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");
}

//_____________________________________________________________________
void h1analysisProxy_SlaveBegin(TTree *tree)
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //initialize the Tree branch addresses
   Init(tree);

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (slave) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");

   //create histograms
   hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17);
   h2   = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6);

   fOutput->Add(hdmd);
   fOutput->Add(h2);

   //process cases with event list
   fillList = kFALSE;
   useList  = kFALSE;
   tree->SetEventList(0);
   delete gDirectory->GetList()->FindObject("elist");

   // case when one creates/fills the event list
   if (option.Contains("fillList")) {
      fillList = kTRUE;
      elist = new TEventList("elist","selection from Cut",5000);
   } else elist = 0;

   // case when one uses the event list generated in a previous call
   if (option.Contains("useList")) {
      useList  = kTRUE;
      TFile f("elist.root");
      elist = (TEventList*)f.Get("elist");
      if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist
      tree->SetEventList(elist);
   }

}

Double_t h1analysisProxy() {
   return 0;
}

//_____________________________________________________________________
Bool_t h1analysisProxy_Process(Long64_t entry)
{
// entry is the entry number in the current Tree
// Selection function to select D* and D0.

   //in case one event list is given in input, the selection has already been done.
   if (!useList) {

      float f1 = md0_d;
      float f2 = md0_d-1.8646;
      bool test = TMath::Abs(md0_d-1.8646) >= 0.04;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;
      if (ptds_d <= 2.5) return kFALSE;
      if (TMath::Abs(etads_d) >= 1.5) return kFALSE;

      int cik = ik-1;    //original ik used f77 convention starting at 1
      int cipi = ipi-1;  //original ipi used f77 convention starting at 1

      f1 = nhitrp[cik];
      f2 = nhitrp[cipi];
      test = nhitrp[cik]*nhitrp[cipi] <= 1;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;
      if (rend[cik] -rstart[cik]  <= 22) return kFALSE;
      if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;
      if (nlhk[cik] <= 0.1)    return kFALSE;
      if (nlhpi[cipi] <= 0.1)  return kFALSE;
      // fix because read-only
      if (nlhpi[ipis-1] <= 0.1) return kFALSE;
      if (njets < 1)          return kFALSE;

   }
   // if option fillList, fill the event list
   if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));

   //fill some histograms
   hdmd->Fill(dm_d);
   h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d);

   return kTRUE;
}

//_____________________________________________________________________
void h1analysisProxy_SlaveTerminate()
{
   // nothing to be done
   printf("Terminate (slave) h1analysis\n");
}

//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
   printf("Terminate (final) h1analysis\n");

   // function called at the end of the event loop

   hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
   h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));

   if (hdmd == 0 || h2 == 0) {
      Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
      return;
   }

   //create the canvas for the h1analysis fit
   gStyle->SetOptFit();
   TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
   c1->SetBottomMargin(0.15);
   hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
   hdmd->GetXaxis()->SetTitleOffset(1.4);

   //fit histogram hdmd with function f5 using the loglikelihood option
   TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
   f5->SetParameters(1000000, .25, 2000, .1454, .001);
   hdmd->Fit("f5","lr");

   //create the canvas for tau d0
   gStyle->SetOptFit(0);
   gStyle->SetOptStat(1100);
   TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
   c2->SetGrid();
   c2->SetBottomMargin(0.15);

   // Project slices of 2-d histogram h2 along X , then fit each slice
   // with function f2 and make a histogram for each fit parameter
   // Note that the generated histograms are added to the list of objects
   // in the current directory.
   TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
   f2->SetParameters(10000, 10);
   h2->FitSlicesX(f2,0,-1,1,"qln");
   TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
   h2_1->GetXaxis()->SetTitle("#tau[ps]");
   h2_1->SetMarkerStyle(21);
   h2_1->Draw();
   c2->Update();
   TLine *line = new TLine(0,0,0,c2->GetUymax());
   line->Draw();

   //save the event list to a Root file if one was produced
   if (fillList) {
      TFile efile("elist.root","recreate");
      elist->Write();
   }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/aura/event_filter.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "ui/aura/desktop.h"
#include "ui/aura/event.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/aura/test/test_desktop_delegate.h"
#include "ui/aura/test/test_window_delegate.h"

#if defined(OS_WIN)
// Windows headers define macros for these function names which screw with us.
#if defined(CreateWindow)
#undef CreateWindow
#endif
#endif

namespace aura {
namespace test {

typedef AuraTestBase EventFilterTest;

class TestEventFilterWindowDelegate : public TestWindowDelegate {
 public:
  TestEventFilterWindowDelegate()
      : key_event_count_(0),
        mouse_event_count_(0),
        touch_event_count_(0) {}
  virtual ~TestEventFilterWindowDelegate() {}

  void ResetCounts() {
    key_event_count_ = 0;
    mouse_event_count_ = 0;
    touch_event_count_ = 0;
  }

  int key_event_count() const { return key_event_count_; }
  int mouse_event_count() const { return mouse_event_count_; }
  int touch_event_count() const { return touch_event_count_; }

  // Overridden from TestWindowDelegate:
  virtual bool OnKeyEvent(KeyEvent* event) OVERRIDE {
    ++key_event_count_;
    return true;
  }
  virtual bool OnMouseEvent(MouseEvent* event) OVERRIDE {
    ++mouse_event_count_;
    return true;
  }
  virtual ui::TouchStatus OnTouchEvent(TouchEvent* event) OVERRIDE {
    ++touch_event_count_;
    return ui::TOUCH_STATUS_UNKNOWN;
  }

 private:
  int key_event_count_;
  int mouse_event_count_;
  int touch_event_count_;

  DISALLOW_COPY_AND_ASSIGN(TestEventFilterWindowDelegate);
};

Window* CreateWindow(int id, Window* parent, WindowDelegate* delegate) {
  Window* window = new Window(delegate ? delegate : new TestWindowDelegate);
  window->set_id(id);
  window->Init();
  window->SetParent(parent);
  window->SetBounds(gfx::Rect(0, 0, 100, 100));
  window->Show();
  return window;
}

class TestEventFilter : public EventFilter {
 public:
  explicit TestEventFilter(Window* owner)
      : EventFilter(owner),
        key_event_count_(0),
        mouse_event_count_(0),
        touch_event_count_(0),
        consumes_key_events_(false),
        consumes_mouse_events_(false),
        consumes_touch_events_(false) {
  }
  virtual ~TestEventFilter() {}

  void ResetCounts() {
    key_event_count_ = 0;
    mouse_event_count_ = 0;
    touch_event_count_ = 0;
  }

  int key_event_count() const { return key_event_count_; }
  int mouse_event_count() const { return mouse_event_count_; }
  int touch_event_count() const { return touch_event_count_; }

  void set_consumes_key_events(bool consumes_key_events) {
    consumes_key_events_ = consumes_key_events;
  }
  void set_consumes_mouse_events(bool consumes_mouse_events) {
    consumes_mouse_events_ = consumes_mouse_events;
  }
  void set_consumes_touch_events(bool consumes_touch_events) {
    consumes_touch_events_ = consumes_touch_events;
  }

  // Overridden from EventFilter:
  virtual bool PreHandleKeyEvent(Window* target, KeyEvent* event) OVERRIDE {
    ++key_event_count_;
    return consumes_key_events_;
  }
  virtual bool PreHandleMouseEvent(Window* target, MouseEvent* event) OVERRIDE {
    ++mouse_event_count_;
    return consumes_mouse_events_;
  }
  virtual ui::TouchStatus PreHandleTouchEvent(Window* target,
                                              TouchEvent* event) OVERRIDE {
    ++touch_event_count_;
    // TODO(sadrul): !
    return ui::TOUCH_STATUS_UNKNOWN;
  }

 private:
  int key_event_count_;
  int mouse_event_count_;
  int touch_event_count_;

  bool consumes_key_events_;
  bool consumes_mouse_events_;
  bool consumes_touch_events_;

  DISALLOW_COPY_AND_ASSIGN(TestEventFilter);
};

// Creates this hierarchy:
//
// Desktop Window (EF)
//  +- w1 (EF)
//    +- w11
//      +- w111 (EF)
//        +- w1111 <-- target window
TEST_F(EventFilterTest, Basic) {
  scoped_ptr<Window> w1(CreateWindow(1, Desktop::GetInstance(), NULL));
  scoped_ptr<Window> w11(CreateWindow(11, w1.get(), NULL));
  scoped_ptr<Window> w111(CreateWindow(111, w11.get(), NULL));
  TestEventFilterWindowDelegate* d1111 = new TestEventFilterWindowDelegate;
  scoped_ptr<Window> w1111(CreateWindow(1111, w111.get(), d1111));

  TestEventFilter* desktop_filter = new TestEventFilter(Desktop::GetInstance());
  TestEventFilter* w1_filter = new TestEventFilter(w1.get());
  TestEventFilter* w111_filter = new TestEventFilter(w111.get());
  Desktop::GetInstance()->SetEventFilter(desktop_filter);
  w1->SetEventFilter(w1_filter);
  w111->SetEventFilter(w111_filter);

  w1111->GetFocusManager()->SetFocusedWindow(w1111.get());

  // To start with, no one is going to consume any events. All three filters
  // and the w1111's delegate should receive the event.
  EventGenerator generator(w1111.get());
  generator.PressLeftButton();
  KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0);
  Desktop::GetInstance()->DispatchKeyEvent(&key_event);

  // TODO(sadrul): TouchEvent!
  EXPECT_EQ(1, desktop_filter->key_event_count());
  EXPECT_EQ(1, w1_filter->key_event_count());
  EXPECT_EQ(1, w111_filter->key_event_count());
  EXPECT_EQ(1, d1111->key_event_count());
  EXPECT_EQ(1, desktop_filter->mouse_event_count());
  EXPECT_EQ(1, w1_filter->mouse_event_count());
  EXPECT_EQ(1, w111_filter->mouse_event_count());
  EXPECT_EQ(1, d1111->mouse_event_count());
  EXPECT_EQ(0, desktop_filter->touch_event_count());
  EXPECT_EQ(0, w1_filter->touch_event_count());
  EXPECT_EQ(0, w111_filter->touch_event_count());
  EXPECT_EQ(0, d1111->touch_event_count());

  d1111->ResetCounts();
  desktop_filter->ResetCounts();
  w1_filter->ResetCounts();
  w111_filter->ResetCounts();

  // Now make w1's EF consume the event.
  w1_filter->set_consumes_key_events(true);
  w1_filter->set_consumes_mouse_events(true);

  generator.ReleaseLeftButton();
  Desktop::GetInstance()->DispatchKeyEvent(&key_event);

  // TODO(sadrul): TouchEvent!
  EXPECT_EQ(1, desktop_filter->key_event_count());
  EXPECT_EQ(1, w1_filter->key_event_count());
  EXPECT_EQ(0, w111_filter->key_event_count());
  EXPECT_EQ(0, d1111->key_event_count());
  EXPECT_EQ(1, desktop_filter->mouse_event_count());
  EXPECT_EQ(1, w1_filter->mouse_event_count());
  EXPECT_EQ(0, w111_filter->mouse_event_count());
  EXPECT_EQ(0, d1111->mouse_event_count());
  EXPECT_EQ(0, desktop_filter->touch_event_count());
  EXPECT_EQ(0, w1_filter->touch_event_count());
  EXPECT_EQ(0, w111_filter->touch_event_count());
  EXPECT_EQ(0, d1111->touch_event_count());
}

}  // namespace test
}  // namespace aura

<commit_msg>Fix aura bustage.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/aura/event_filter.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "ui/aura/desktop.h"
#include "ui/aura/event.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/aura/test/test_desktop_delegate.h"
#include "ui/aura/test/test_window_delegate.h"

#if defined(OS_WIN)
// Windows headers define macros for these function names which screw with us.
#if defined(CreateWindow)
#undef CreateWindow
#endif
#endif

namespace aura {
namespace test {

typedef AuraTestBase EventFilterTest;

class TestEventFilterWindowDelegate : public TestWindowDelegate {
 public:
  TestEventFilterWindowDelegate()
      : key_event_count_(0),
        mouse_event_count_(0),
        touch_event_count_(0) {}
  virtual ~TestEventFilterWindowDelegate() {}

  void ResetCounts() {
    key_event_count_ = 0;
    mouse_event_count_ = 0;
    touch_event_count_ = 0;
  }

  int key_event_count() const { return key_event_count_; }
  int mouse_event_count() const { return mouse_event_count_; }
  int touch_event_count() const { return touch_event_count_; }

  // Overridden from TestWindowDelegate:
  virtual bool OnKeyEvent(KeyEvent* event) OVERRIDE {
    ++key_event_count_;
    return true;
  }
  virtual bool OnMouseEvent(MouseEvent* event) OVERRIDE {
    ++mouse_event_count_;
    return true;
  }
  virtual ui::TouchStatus OnTouchEvent(TouchEvent* event) OVERRIDE {
    ++touch_event_count_;
    return ui::TOUCH_STATUS_UNKNOWN;
  }

 private:
  int key_event_count_;
  int mouse_event_count_;
  int touch_event_count_;

  DISALLOW_COPY_AND_ASSIGN(TestEventFilterWindowDelegate);
};

Window* CreateWindow(int id, Window* parent, WindowDelegate* delegate) {
  Window* window = new Window(delegate ? delegate : new TestWindowDelegate);
  window->set_id(id);
  window->Init(ui::Layer::LAYER_HAS_TEXTURE);
  window->SetParent(parent);
  window->SetBounds(gfx::Rect(0, 0, 100, 100));
  window->Show();
  return window;
}

class TestEventFilter : public EventFilter {
 public:
  explicit TestEventFilter(Window* owner)
      : EventFilter(owner),
        key_event_count_(0),
        mouse_event_count_(0),
        touch_event_count_(0),
        consumes_key_events_(false),
        consumes_mouse_events_(false),
        consumes_touch_events_(false) {
  }
  virtual ~TestEventFilter() {}

  void ResetCounts() {
    key_event_count_ = 0;
    mouse_event_count_ = 0;
    touch_event_count_ = 0;
  }

  int key_event_count() const { return key_event_count_; }
  int mouse_event_count() const { return mouse_event_count_; }
  int touch_event_count() const { return touch_event_count_; }

  void set_consumes_key_events(bool consumes_key_events) {
    consumes_key_events_ = consumes_key_events;
  }
  void set_consumes_mouse_events(bool consumes_mouse_events) {
    consumes_mouse_events_ = consumes_mouse_events;
  }
  void set_consumes_touch_events(bool consumes_touch_events) {
    consumes_touch_events_ = consumes_touch_events;
  }

  // Overridden from EventFilter:
  virtual bool PreHandleKeyEvent(Window* target, KeyEvent* event) OVERRIDE {
    ++key_event_count_;
    return consumes_key_events_;
  }
  virtual bool PreHandleMouseEvent(Window* target, MouseEvent* event) OVERRIDE {
    ++mouse_event_count_;
    return consumes_mouse_events_;
  }
  virtual ui::TouchStatus PreHandleTouchEvent(Window* target,
                                              TouchEvent* event) OVERRIDE {
    ++touch_event_count_;
    // TODO(sadrul): !
    return ui::TOUCH_STATUS_UNKNOWN;
  }

 private:
  int key_event_count_;
  int mouse_event_count_;
  int touch_event_count_;

  bool consumes_key_events_;
  bool consumes_mouse_events_;
  bool consumes_touch_events_;

  DISALLOW_COPY_AND_ASSIGN(TestEventFilter);
};

// Creates this hierarchy:
//
// Desktop Window (EF)
//  +- w1 (EF)
//    +- w11
//      +- w111 (EF)
//        +- w1111 <-- target window
TEST_F(EventFilterTest, Basic) {
  scoped_ptr<Window> w1(CreateWindow(1, Desktop::GetInstance(), NULL));
  scoped_ptr<Window> w11(CreateWindow(11, w1.get(), NULL));
  scoped_ptr<Window> w111(CreateWindow(111, w11.get(), NULL));
  TestEventFilterWindowDelegate* d1111 = new TestEventFilterWindowDelegate;
  scoped_ptr<Window> w1111(CreateWindow(1111, w111.get(), d1111));

  TestEventFilter* desktop_filter = new TestEventFilter(Desktop::GetInstance());
  TestEventFilter* w1_filter = new TestEventFilter(w1.get());
  TestEventFilter* w111_filter = new TestEventFilter(w111.get());
  Desktop::GetInstance()->SetEventFilter(desktop_filter);
  w1->SetEventFilter(w1_filter);
  w111->SetEventFilter(w111_filter);

  w1111->GetFocusManager()->SetFocusedWindow(w1111.get());

  // To start with, no one is going to consume any events. All three filters
  // and the w1111's delegate should receive the event.
  EventGenerator generator(w1111.get());
  generator.PressLeftButton();
  KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0);
  Desktop::GetInstance()->DispatchKeyEvent(&key_event);

  // TODO(sadrul): TouchEvent!
  EXPECT_EQ(1, desktop_filter->key_event_count());
  EXPECT_EQ(1, w1_filter->key_event_count());
  EXPECT_EQ(1, w111_filter->key_event_count());
  EXPECT_EQ(1, d1111->key_event_count());
  EXPECT_EQ(1, desktop_filter->mouse_event_count());
  EXPECT_EQ(1, w1_filter->mouse_event_count());
  EXPECT_EQ(1, w111_filter->mouse_event_count());
  EXPECT_EQ(1, d1111->mouse_event_count());
  EXPECT_EQ(0, desktop_filter->touch_event_count());
  EXPECT_EQ(0, w1_filter->touch_event_count());
  EXPECT_EQ(0, w111_filter->touch_event_count());
  EXPECT_EQ(0, d1111->touch_event_count());

  d1111->ResetCounts();
  desktop_filter->ResetCounts();
  w1_filter->ResetCounts();
  w111_filter->ResetCounts();

  // Now make w1's EF consume the event.
  w1_filter->set_consumes_key_events(true);
  w1_filter->set_consumes_mouse_events(true);

  generator.ReleaseLeftButton();
  Desktop::GetInstance()->DispatchKeyEvent(&key_event);

  // TODO(sadrul): TouchEvent!
  EXPECT_EQ(1, desktop_filter->key_event_count());
  EXPECT_EQ(1, w1_filter->key_event_count());
  EXPECT_EQ(0, w111_filter->key_event_count());
  EXPECT_EQ(0, d1111->key_event_count());
  EXPECT_EQ(1, desktop_filter->mouse_event_count());
  EXPECT_EQ(1, w1_filter->mouse_event_count());
  EXPECT_EQ(0, w111_filter->mouse_event_count());
  EXPECT_EQ(0, d1111->mouse_event_count());
  EXPECT_EQ(0, desktop_filter->touch_event_count());
  EXPECT_EQ(0, w1_filter->touch_event_count());
  EXPECT_EQ(0, w111_filter->touch_event_count());
  EXPECT_EQ(0, d1111->touch_event_count());
}

}  // namespace test
}  // namespace aura

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xpathapi.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "xpathapi.hxx"
#include "nodelist.hxx"
#include "xpathobject.hxx"
#include "../dom/node.hxx"

#include <rtl/ustrbuf.hxx>

#include <libxml/xmlerror.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

#include <stdarg.h>
#include <string.h>

namespace XPath
{
    // factory
    Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)
    {
        return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));
    }

    // ctor
    CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)
        : m_aFactory(rSMgr)
    {
    }

    const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI";
    const char* CXPathAPI::aSupportedServiceNames[] = {
        "com.sun.star.xml.xpath.XPathAPI",
        NULL
    };

    OUString CXPathAPI::_getImplementationName()
    {
        return OUString::createFromAscii(aImplementationName);
    }

    Sequence<OUString> CXPathAPI::_getSupportedServiceNames()
    {
        Sequence<OUString> aSequence;
        for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {
            aSequence.realloc(i+1);
            aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));
        }
        return aSequence;
    }

    Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()
        throw (RuntimeException)
    {
        return CXPathAPI::_getSupportedServiceNames();
    }

    OUString SAL_CALL CXPathAPI::getImplementationName()
        throw (RuntimeException)
    {
        return CXPathAPI::_getImplementationName();
    }

    sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)
        throw (RuntimeException)
    {
        Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();
        for (sal_Int32 i=0; i<supported.getLength(); i++)
        {
            if (supported[i] == aServiceName) return sal_True;
        }
        return sal_False;
    }

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

    void SAL_CALL CXPathAPI::registerNS(
            const OUString& aPrefix,
            const OUString& aURI)
        throw (RuntimeException)
    {
        m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));
    }

    void SAL_CALL CXPathAPI::unregisterNS(
            const OUString& aPrefix,
            const OUString& aURI)
        throw (RuntimeException)
    {
        if ((m_nsmap.find(aPrefix))->second.equals(aURI))
            m_nsmap.erase(aPrefix);
    }

    // register all namespaces stored in the namespace list for this object
    // with the current xpath evaluation context
    static void _registerNamespaces(
            xmlXPathContextPtr ctx,
            const nsmap_t& nsmap)
    {
        nsmap_t::const_iterator i = nsmap.begin();
        OString oprefix, ouri;
        xmlChar *p, *u;
        while (i != nsmap.end())
        {
            oprefix = OUStringToOString(i->first,  RTL_TEXTENCODING_UTF8);
            ouri    = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);
            p = (xmlChar*)oprefix.getStr();
            u = (xmlChar*)ouri.getStr();
            xmlXPathRegisterNs(ctx, p, u);
            i++;
        }
    }

    // get all ns decls on a node (and parent nodes, if any) and register them
    static void _collectNamespaces(
            CXPathAPI* pAPI,
            const Reference< XNode >&  namespaceNode)
    {
        // get namespace decls from node...
        xmlNodePtr pNode = DOM::CNode::getNodePtr(namespaceNode);
        while (pNode != 0) {
            xmlNsPtr curDef = pNode->nsDef;
            while (curDef != 0) {
                const xmlChar* xHref = curDef->href;
                OUString aURI((sal_Char*)xHref, strlen((char*)xHref), RTL_TEXTENCODING_UTF8);
                const xmlChar* xPre = curDef->prefix;
                OUString aPrefix((sal_Char*)xPre, strlen((char*)xPre), RTL_TEXTENCODING_UTF8);
                pAPI->registerNS(aPrefix, aURI);
                curDef = curDef->next;
            }
            pNode = pNode->parent;
        }
    }

    // register function and variable lookup functions with the current
    // xpath evaluation context
    static void _registerExtensions(
            xmlXPathContextPtr ctx,
            const extensions_t& extensions)
    {
        extensions_t::const_iterator i = extensions.begin();
        while (i != extensions.end())
        {
            Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();
            if ( aHandle.functionLookupFunction != 0 )
            {
                xmlXPathRegisterFuncLookup(ctx,
                    reinterpret_cast<xmlXPathFuncLookupFunc>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)),
                    reinterpret_cast<void*>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.functionData)));
            }
            if ( aHandle.variableLookupFunction != 0 )
            {
                xmlXPathRegisterVariableLookup(ctx,
                    reinterpret_cast<xmlXPathVariableLookupFunc>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)),
                    reinterpret_cast<void*>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.variableData)));
            }
            i++;
        }
    }

    /**
     * Use an XPath string to select a nodelist.
     */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(
            const Reference< XNode >& contextNode,
            const OUString& expr)
        throw (RuntimeException, XPathException)
    {
        Reference< XXPathObject > xobj = eval(contextNode, expr);
        return xobj->getNodeList();
    }

    /**
     * same as selectNodeList but registers all name space decalratiosn found on namespaceNode
     */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(
            const Reference< XNode >&  contextNode,
            const OUString& expr,
            const Reference< XNode >&  namespaceNode)
        throw (RuntimeException, XPathException)
    {
        _collectNamespaces(this, namespaceNode);
        return selectNodeList(contextNode, expr);
    }

    /**
     * Same as selectNodeList but returns the first node (if any)
     */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(
            const Reference< XNode >& contextNode,
            const OUString& expr)
        throw (RuntimeException, XPathException)
    {
        Reference< XNodeList > aList = selectNodeList(contextNode, expr);
        Reference< XNode > aNode = aList->item(0);
        return aNode;
    }

    /**
     * Same as selectSingleNode but registers all namespaces declared on
     * namespaceNode
     */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(
            const Reference< XNode >& contextNode,
            const OUString& expr,
            const Reference< XNode >&  namespaceNode )
        throw (RuntimeException, XPathException)
    {
        _collectNamespaces(this, namespaceNode);
        return selectSingleNode(contextNode, expr);
    }

    static OUString make_error_message(xmlErrorPtr pError)
    {
        ::rtl::OUStringBuffer buf;
        if (pError->message) {
            buf.appendAscii(pError->message);
        }
        int line = pError->line;
        if (line) {
            buf.appendAscii("Line: ");
            buf.append(static_cast<sal_Int32>(line));
            buf.appendAscii("\n");
        }
        int column = pError->int2;
        if (column) {
            buf.appendAscii("Column: ");
            buf.append(static_cast<sal_Int32>(column));
            buf.appendAscii("\n");
        }
        OUString msg = buf.makeStringAndClear();
        return msg;
    }

    extern "C" {

        static void generic_error_func(void *userData, const char *format, ...)
        {
            (void) userData;
            char str[1000];
            va_list args;

            va_start(args, format);
            vsnprintf(str, sizeof(str), format, args);
            va_end(args);

            ::rtl::OUStringBuffer buf(
                OUString::createFromAscii("libxml2 error:\n"));
            buf.appendAscii(str);
            OString msg = OUStringToOString(buf.makeStringAndClear(),
                RTL_TEXTENCODING_ASCII_US);
            OSL_ENSURE(sal_False, msg.getStr());
        }

        static void structured_error_func(void * userData, xmlErrorPtr error)
        {
            (void) userData;
            ::rtl::OUStringBuffer buf(
                OUString::createFromAscii("libxml2 error:\n"));
            if (error) {
                buf.append(make_error_message(error));
            } else {
                buf.append(OUString::createFromAscii("no error argument!"));
            }
            OString msg = OUStringToOString(buf.makeStringAndClear(),
                RTL_TEXTENCODING_ASCII_US);
            OSL_ENSURE(sal_False, msg.getStr());
        }

    } // extern "C"

    /**
     * evaluates an XPath string. relative XPath expressions are evaluated relative to
     * the context Node
     */
    Reference< XXPathObject > SAL_CALL CXPathAPI::eval(
            const Reference< XNode >& contextNode,
            const OUString& expr)
        throw (RuntimeException, XPathException)
    {
        xmlXPathContextPtr xpathCtx;
        xmlXPathObjectPtr xpathObj;

        // get the node and document
        xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode);
        xmlDocPtr pDoc = pNode->doc;

        /* NB: workaround for #i87252#:
           libxml < 2.6.17 considers it an error if the context
           node is the empty document (i.e. its xpathCtx->doc has no
           children). libxml 2.6.17 does not consider it an error.
           Unfortunately, old libxml prints an error message to stderr,
           which (afaik) cannot be turned off in this case, so we handle it.
        */
        if (!pDoc->children) {
            throw XPathException();
        }

        /* Create xpath evaluation context */
        xpathCtx = xmlXPathNewContext(pDoc);
        if (xpathCtx == NULL) throw XPathException();

        // set context node
        xpathCtx->node = pNode;
        // error handling
        xpathCtx->error = structured_error_func;
        xmlSetGenericErrorFunc(NULL, generic_error_func);

        // register namespaces and extension
        _registerNamespaces(xpathCtx, m_nsmap);
        _registerExtensions(xpathCtx, m_extensions);

        /* run the query */
        OString o1 = OUStringToOString(expr, RTL_TEXTENCODING_UTF8);
        xmlChar *xStr = (xmlChar*)o1.getStr();
        if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) {
            // OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);
            xmlXPathFreeContext(xpathCtx);
            throw XPathException();
        }
        xmlXPathFreeContext(xpathCtx);
        Reference< XXPathObject > aObj(new CXPathObject(xpathObj));
        return aObj;
    }

    /**
     * same as eval but registers all namespace declarations found on namespaceNode
     */
    Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(
            const Reference< XNode >& contextNode,
            const OUString& expr,
            const Reference< XNode >& namespaceNode)
        throw (RuntimeException, XPathException)
    {
        _collectNamespaces(this, namespaceNode);
        return eval(contextNode, expr);
    }

    /**
     * uses the service manager to create an instance of the service denoted by aName.
     * If the returned object implements the XXPathExtension interface, it is added to the list
     * of extensions that are used when evaluating XPath strings with this XPathAPI instance
     */
    void SAL_CALL CXPathAPI::registerExtension(
            const OUString& aName)
        throw (RuntimeException)
    {
        // get extension from service manager
        Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW);
        m_extensions.push_back( aExtension );
    }

    /**
     * registers the given extension instance to be used by XPath evaluations performed through this
     * XPathAPI instance
     */
    void SAL_CALL CXPathAPI::registerExtensionInstance(
            const Reference< XXPathExtension>& aExtension)
        throw (RuntimeException)
    {
        if (aExtension.is()) {
            m_extensions.push_back( aExtension );
        } else {
            throw RuntimeException();
        }
    }
}
<commit_msg>#i90484# Patch by pjanik for .Net2003 compiler<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xpathapi.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "xpathapi.hxx"
#include "nodelist.hxx"
#include "xpathobject.hxx"
#include "../dom/node.hxx"

#include <rtl/ustrbuf.hxx>

#include <libxml/xmlerror.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

#include <stdarg.h>
#include <string.h>

namespace XPath
{
    // factory
    Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)
    {
        return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));
    }

    // ctor
    CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)
        : m_aFactory(rSMgr)
    {
    }

    const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI";
    const char* CXPathAPI::aSupportedServiceNames[] = {
        "com.sun.star.xml.xpath.XPathAPI",
        NULL
    };

    OUString CXPathAPI::_getImplementationName()
    {
        return OUString::createFromAscii(aImplementationName);
    }

    Sequence<OUString> CXPathAPI::_getSupportedServiceNames()
    {
        Sequence<OUString> aSequence;
        for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {
            aSequence.realloc(i+1);
            aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));
        }
        return aSequence;
    }

    Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()
        throw (RuntimeException)
    {
        return CXPathAPI::_getSupportedServiceNames();
    }

    OUString SAL_CALL CXPathAPI::getImplementationName()
        throw (RuntimeException)
    {
        return CXPathAPI::_getImplementationName();
    }

    sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)
        throw (RuntimeException)
    {
        Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();
        for (sal_Int32 i=0; i<supported.getLength(); i++)
        {
            if (supported[i] == aServiceName) return sal_True;
        }
        return sal_False;
    }

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

    void SAL_CALL CXPathAPI::registerNS(
            const OUString& aPrefix,
            const OUString& aURI)
        throw (RuntimeException)
    {
        m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));
    }

    void SAL_CALL CXPathAPI::unregisterNS(
            const OUString& aPrefix,
            const OUString& aURI)
        throw (RuntimeException)
    {
        if ((m_nsmap.find(aPrefix))->second.equals(aURI))
            m_nsmap.erase(aPrefix);
    }

    // register all namespaces stored in the namespace list for this object
    // with the current xpath evaluation context
    static void _registerNamespaces(
            xmlXPathContextPtr ctx,
            const nsmap_t& nsmap)
    {
        nsmap_t::const_iterator i = nsmap.begin();
        OString oprefix, ouri;
        xmlChar *p, *u;
        while (i != nsmap.end())
        {
            oprefix = OUStringToOString(i->first,  RTL_TEXTENCODING_UTF8);
            ouri    = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);
            p = (xmlChar*)oprefix.getStr();
            u = (xmlChar*)ouri.getStr();
            xmlXPathRegisterNs(ctx, p, u);
            i++;
        }
    }

    // get all ns decls on a node (and parent nodes, if any) and register them
    static void _collectNamespaces(
            CXPathAPI* pAPI,
            const Reference< XNode >&  namespaceNode)
    {
        // get namespace decls from node...
        xmlNodePtr pNode = DOM::CNode::getNodePtr(namespaceNode);
        while (pNode != 0) {
            xmlNsPtr curDef = pNode->nsDef;
            while (curDef != 0) {
                const xmlChar* xHref = curDef->href;
                OUString aURI((sal_Char*)xHref, strlen((char*)xHref), RTL_TEXTENCODING_UTF8);
                const xmlChar* xPre = curDef->prefix;
                OUString aPrefix((sal_Char*)xPre, strlen((char*)xPre), RTL_TEXTENCODING_UTF8);
                pAPI->registerNS(aPrefix, aURI);
                curDef = curDef->next;
            }
            pNode = pNode->parent;
        }
    }

    // register function and variable lookup functions with the current
    // xpath evaluation context
    static void _registerExtensions(
            xmlXPathContextPtr ctx,
            const extensions_t& extensions)
    {
        extensions_t::const_iterator i = extensions.begin();
        while (i != extensions.end())
        {
            Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();
            if ( aHandle.functionLookupFunction != 0 )
            {
                xmlXPathRegisterFuncLookup(ctx,
                    reinterpret_cast<xmlXPathFuncLookupFunc>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)),
                    reinterpret_cast<void*>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.functionData)));
            }
            if ( aHandle.variableLookupFunction != 0 )
            {
                xmlXPathRegisterVariableLookup(ctx,
                    reinterpret_cast<xmlXPathVariableLookupFunc>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)),
                    reinterpret_cast<void*>(
                        sal::static_int_cast<sal_IntPtr>(aHandle.variableData)));
            }
            i++;
        }
    }

    /**
     * Use an XPath string to select a nodelist.
     */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(
            const Reference< XNode >& contextNode,
            const OUString& expr)
        throw (RuntimeException, XPathException)
    {
        Reference< XXPathObject > xobj = eval(contextNode, expr);
        return xobj->getNodeList();
    }

    /**
     * same as selectNodeList but registers all name space decalratiosn found on namespaceNode
     */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(
            const Reference< XNode >&  contextNode,
            const OUString& expr,
            const Reference< XNode >&  namespaceNode)
        throw (RuntimeException, XPathException)
    {
        _collectNamespaces(this, namespaceNode);
        return selectNodeList(contextNode, expr);
    }

    /**
     * Same as selectNodeList but returns the first node (if any)
     */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(
            const Reference< XNode >& contextNode,
            const OUString& expr)
        throw (RuntimeException, XPathException)
    {
        Reference< XNodeList > aList = selectNodeList(contextNode, expr);
        Reference< XNode > aNode = aList->item(0);
        return aNode;
    }

    /**
     * Same as selectSingleNode but registers all namespaces declared on
     * namespaceNode
     */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(
            const Reference< XNode >& contextNode,
            const OUString& expr,
            const Reference< XNode >&  namespaceNode )
        throw (RuntimeException, XPathException)
    {
        _collectNamespaces(this, namespaceNode);
        return selectSingleNode(contextNode, expr);
    }

    static OUString make_error_message(xmlErrorPtr pError)
    {
        ::rtl::OUStringBuffer buf;
        if (pError->message) {
            buf.appendAscii(pError->message);
        }
        int line = pError->line;
        if (line) {
            buf.appendAscii("Line: ");
            buf.append(static_cast<sal_Int32>(line));
            buf.appendAscii("\n");
        }
        int column = pError->int2;
        if (column) {
            buf.appendAscii("Column: ");
            buf.append(static_cast<sal_Int32>(column));
            buf.appendAscii("\n");
        }
        OUString msg = buf.makeStringAndClear();
        return msg;
    }

    extern "C" {

        static void generic_error_func(void *userData, const char *format, ...)
        {
            (void) userData;
            char str[1000];
            va_list args;

            va_start(args, format);
#ifdef _WIN32
#define vsnprintf _vsnprintf
#endif
            vsnprintf(str, sizeof(str), format, args);
            va_end(args);

            ::rtl::OUStringBuffer buf(
                OUString::createFromAscii("libxml2 error:\n"));
            buf.appendAscii(str);
            OString msg = OUStringToOString(buf.makeStringAndClear(),
                RTL_TEXTENCODING_ASCII_US);
            OSL_ENSURE(sal_False, msg.getStr());
        }

        static void structured_error_func(void * userData, xmlErrorPtr error)
        {
            (void) userData;
            ::rtl::OUStringBuffer buf(
                OUString::createFromAscii("libxml2 error:\n"));
            if (error) {
                buf.append(make_error_message(error));
            } else {
                buf.append(OUString::createFromAscii("no error argument!"));
            }
            OString msg = OUStringToOString(buf.makeStringAndClear(),
                RTL_TEXTENCODING_ASCII_US);
            OSL_ENSURE(sal_False, msg.getStr());
        }

    } // extern "C"

    /**
     * evaluates an XPath string. relative XPath expressions are evaluated relative to
     * the context Node
     */
    Reference< XXPathObject > SAL_CALL CXPathAPI::eval(
            const Reference< XNode >& contextNode,
            const OUString& expr)
        throw (RuntimeException, XPathException)
    {
        xmlXPathContextPtr xpathCtx;
        xmlXPathObjectPtr xpathObj;

        // get the node and document
        xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode);
        xmlDocPtr pDoc = pNode->doc;

        /* NB: workaround for #i87252#:
           libxml < 2.6.17 considers it an error if the context
           node is the empty document (i.e. its xpathCtx->doc has no
           children). libxml 2.6.17 does not consider it an error.
           Unfortunately, old libxml prints an error message to stderr,
           which (afaik) cannot be turned off in this case, so we handle it.
        */
        if (!pDoc->children) {
            throw XPathException();
        }

        /* Create xpath evaluation context */
        xpathCtx = xmlXPathNewContext(pDoc);
        if (xpathCtx == NULL) throw XPathException();

        // set context node
        xpathCtx->node = pNode;
        // error handling
        xpathCtx->error = structured_error_func;
        xmlSetGenericErrorFunc(NULL, generic_error_func);

        // register namespaces and extension
        _registerNamespaces(xpathCtx, m_nsmap);
        _registerExtensions(xpathCtx, m_extensions);

        /* run the query */
        OString o1 = OUStringToOString(expr, RTL_TEXTENCODING_UTF8);
        xmlChar *xStr = (xmlChar*)o1.getStr();
        if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) {
            // OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);
            xmlXPathFreeContext(xpathCtx);
            throw XPathException();
        }
        xmlXPathFreeContext(xpathCtx);
        Reference< XXPathObject > aObj(new CXPathObject(xpathObj));
        return aObj;
    }

    /**
     * same as eval but registers all namespace declarations found on namespaceNode
     */
    Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(
            const Reference< XNode >& contextNode,
            const OUString& expr,
            const Reference< XNode >& namespaceNode)
        throw (RuntimeException, XPathException)
    {
        _collectNamespaces(this, namespaceNode);
        return eval(contextNode, expr);
    }

    /**
     * uses the service manager to create an instance of the service denoted by aName.
     * If the returned object implements the XXPathExtension interface, it is added to the list
     * of extensions that are used when evaluating XPath strings with this XPathAPI instance
     */
    void SAL_CALL CXPathAPI::registerExtension(
            const OUString& aName)
        throw (RuntimeException)
    {
        // get extension from service manager
        Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW);
        m_extensions.push_back( aExtension );
    }

    /**
     * registers the given extension instance to be used by XPath evaluations performed through this
     * XPathAPI instance
     */
    void SAL_CALL CXPathAPI::registerExtensionInstance(
            const Reference< XXPathExtension>& aExtension)
        throw (RuntimeException)
    {
        if (aExtension.is()) {
            m_extensions.push_back( aExtension );
        } else {
            throw RuntimeException();
        }
    }
}
<|endoftext|>


<commit_before>/*
By Vivek Dhiman
*/

#include <cstdlib>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <utility>   // for pairs
#include <algorithm> // for swap
using namespace std;

int main (int argc, char const *argv[]){
    //************* make sure args are present:
    if (argc != 3){
        cout << "ERROR: something wrong with the inputs" << endl;
        cout << "usage:\n    " << argv[0] << " networkEdgeIdMap.csv network.clusters newnetwork.clusters" << endl;
        exit(1);
    }
    //************* got the args
    clock_t begin = clock();

    //************* start load edgelist
    ifstream inFile;
    inFile.open( argv[1] );
    if (!inFile) {
        cout << "ERROR: unable to open input file" << endl;
        exit(1); // terminate with error
    }
    // index should be iterator not integer????
    long long edgeId = 0;
    map<long long, pair<long long, long long> > edgeIdMap; // O(log n) access too slow?
    long long ni, nj;
    while (inFile >> ni >> nj >> edgeId){ // scan edgelist to populate
        edgeIdMap[edgeId] = make_pair(ni,nj);
    }
    inFile.close(); inFile.clear();
    //************* end load edgelist

    //************* loop over jaccards file and do the clustering

    ifstream jaccFile;
    jaccFile.open( argv[2] );
    if (!jaccFile) {
        cout << "ERROR: unable to open jaccards file" << endl;
        exit(1); // terminate with error
    }
    FILE * nwClusterFile  = fopen( argv[3], "w" );
    string line;
    while (std::getline(jaccFile, line)){
      std::stringstream ss(line);
      while(ss >> edgeId){
        fprintf( nwClusterFile, "%ld,%ld ", edgeIdMap[edgeId].first, edgeIdMap[edgeId].second);
      }
      fprintf( nwClusterFile, "\n");
    }
    fclose(nwClusterFile);
    //************* done looping over jaccards file
    jaccFile.close(); jaccFile.clear();
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC  << " seconds. "<< endl;
    return 0;
}
<commit_msg>Update replaceEdgeIdByEdgNodes.cpp<commit_after>/*
By Vivek Dhiman
*/

#include <cstdlib>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <utility>   // for pairs
#include <algorithm> // for swap
using namespace std;

int main (int argc, char const *argv[]){
    //************* make sure args are present:
    if (argc != 4){
        cout << "ERROR: something wrong with the inputs" << endl;
        cout << "usage:\n    " << argv[0] << " networkEdgeIdMap.csv network.clusters newnetwork.clusters" << endl;
        exit(1);
    }
    //************* got the args
    clock_t begin = clock();

    //************* start load edgelist
    ifstream inFile;
    inFile.open( argv[1] );
    if (!inFile) {
        cout << "ERROR: unable to open input file" << endl;
        exit(1); // terminate with error
    }
    // index should be iterator not integer????
    long long edgeId = 0;
    map<long long, pair<long long, long long> > edgeIdMap; // O(log n) access too slow?
    long long ni, nj;
    while (inFile >> ni >> nj >> edgeId){ // scan edgelist to populate
        edgeIdMap[edgeId] = make_pair(ni,nj);
    }
    inFile.close(); inFile.clear();
    //************* end load edgelist

    //************* loop over jaccards file and do the clustering

    ifstream jaccFile;
    jaccFile.open( argv[2] );
    if (!jaccFile) {
        cout << "ERROR: unable to open jaccards file" << endl;
        exit(1); // terminate with error
    }
    FILE * nwClusterFile  = fopen( argv[3], "w" );
    string line;
    while (std::getline(jaccFile, line)){
      std::stringstream ss(line);
      while(ss >> edgeId){
        fprintf( nwClusterFile, "%ld,%ld ", edgeIdMap[edgeId].first, edgeIdMap[edgeId].second);
      }
      fprintf( nwClusterFile, "\n");
    }
    fclose(nwClusterFile);
    //************* done looping over jaccards file
    jaccFile.close(); jaccFile.clear();
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC  << " seconds. "<< endl;
    return 0;
}
<|endoftext|>