<commit_before>// Copyright (c) 2010 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.
//
// Broker RPC Client implementation.

#include "ceee/ie/broker/broker_rpc_client.h"

#include <atlbase.h>
#include "base/lock.h"
#include "base/logging.h"
#include "base/tuple.h"
#include "base/win/scoped_comptr.h"
#include "broker_lib.h"  // NOLINT
#include "broker_rpc_lib.h"  // NOLINT
#include "ceee/common/com_utils.h"
#include "ceee/ie/broker/broker_rpc_utils.h"

namespace {

// Avoid using objects requiring unwind in functions that use __try.
void LogRpcException(const char* str, unsigned int exception_code) {
  LOG(ERROR) << str << com::LogWe(exception_code);
}

// Avoid using objects requiring unwind in functions that use __try.
void RpcDcheck(const char* message) {
  NOTREACHED() << message;
}

HRESULT BindRpc(std::wstring endpoint, RPC_BINDING_HANDLE* binding_handle) {
  DCHECK(binding_handle != NULL);
  std::wstring protocol = kRpcProtocol;
  DCHECK(!protocol.empty());
  DCHECK(!endpoint.empty());
  if (protocol.empty() || endpoint.empty() || binding_handle == NULL)
    return E_INVALIDARG;

  RPC_BINDING_HANDLE tmp_binding_handle = NULL;

  // TODO(vitalybuka@google.com): There's no guarantee (aside from name
  // uniqueness) that it will connect to an endpoint created by the same user.
  // Hint: The missing invocation is RpcBindingSetAuthInfoEx.
  VLOG(1) << "Connecting to RPC server. Endpoint: " << endpoint;
  RPC_WSTR string_binding = NULL;
  // Create binding string for given end point.
  RPC_STATUS status = ::RpcStringBindingCompose(
      NULL,
      reinterpret_cast<RPC_WSTR>(&protocol[0]),
      NULL,
      reinterpret_cast<RPC_WSTR>(&endpoint[0]),
      NULL,
      &string_binding);

  if (RPC_S_OK == status) {
    // Create binding from just generated binding string. Binding handle should
    // be used for PRC calls.
    status = ::RpcBindingFromStringBinding(string_binding, &tmp_binding_handle);
    ::RpcStringFree(&string_binding);
    if (RPC_S_OK == status) {
      VLOG(1) << "RPC client is connected. Endpoint: " << endpoint;
      *binding_handle = tmp_binding_handle;
      return S_OK;
    } else {
      LogRpcException("Failed to bind. RPC_STATUS:", status);
    }
  } else {
    LogRpcException("Failed to compose binding string. RPC_STATUS:", status);
  }
  return RPC_E_FAULT;
}

int HandleRpcException(unsigned int rpc_exception_code) {
  switch (rpc_exception_code) {
    case STATUS_ACCESS_VIOLATION:
    case STATUS_DATATYPE_MISALIGNMENT:
    case STATUS_PRIVILEGED_INSTRUCTION:
    case STATUS_BREAKPOINT:
    case STATUS_STACK_OVERFLOW:
    case STATUS_IN_PAGE_ERROR:
    case STATUS_GUARD_PAGE_VIOLATION:
      return EXCEPTION_CONTINUE_SEARCH;
    default:
      break;
  }
  return EXCEPTION_EXECUTE_HANDLER;
}

}  // namespace

BrokerRpcClient::BrokerRpcClient(bool allow_restarts)
    : context_(0),
      binding_handle_(NULL),
      allow_restarts_(allow_restarts) {
}

BrokerRpcClient::~BrokerRpcClient() {
  Disconnect();
}

void BrokerRpcClient::LockContext() {
  RpcTryExcept {
    context_ = BrokerRpcClient_Connect(binding_handle_);
  } RpcExcept(HandleRpcException(RpcExceptionCode())) {
    LogRpcException("RPC error in LockContext", RpcExceptionCode());
  } RpcEndExcept
}

void BrokerRpcClient::ReleaseContext() {
  RpcTryExcept {
    BrokerRpcClient_Disconnect(binding_handle_, &context_);
  } RpcExcept(HandleRpcException(RpcExceptionCode())) {
    LogRpcException("RPC error in ReleaseContext", RpcExceptionCode());
  } RpcEndExcept
}

HRESULT BrokerRpcClient::StartServer(IUnknown** server) {
  base::win::ScopedComPtr<IUnknown> broker;
  // TODO(vitalybuka@google.com): Start broker without COM after the last
  // COM interface is removed.
  HRESULT hr = broker.CreateInstance(CLSID_CeeeBroker);
  LOG_IF(ERROR, FAILED(hr)) << "Failed to create broker. " << com::LogHr(hr);
  if (FAILED(hr))
    return hr;
  *server = broker.Detach();
  return S_OK;
}

HRESULT BrokerRpcClient::Connect(bool start_server) {
  if (is_connected())
    return S_OK;

  // Keep alive until RPC is connected.
  base::win::ScopedComPtr<IUnknown> broker;
  if (start_server) {
    HRESULT hr = StartServer(broker.Receive());
    if (FAILED(hr))
      return hr;
  }

  if (SUCCEEDED(BindRpc(GetRpcEndpointAddress(), &binding_handle_)))
    LockContext();

  if (!is_connected()) {
    Disconnect();
    return RPC_E_FAULT;
  }
  return S_OK;
}

void BrokerRpcClient::Disconnect() {
  if (context_ != NULL)
    ReleaseContext();
  if (binding_handle_ != NULL) {
    RPC_STATUS status = ::RpcBindingFree(&binding_handle_);
    LOG_IF(WARNING, RPC_S_OK != status) <<
        "Failed to unbind. RPC_STATUS=0x" << com::LogWe(status);
  }
}

template<class Function, class Params>
HRESULT BrokerRpcClient::RunRpc(bool allow_restart,
                                Function rpc_function,
                                const Params& params) {
  if (!rpc_function) {
    RpcDcheck("rpc_function is NULL");
  }
  if (!is_connected()) {
    RpcDcheck("BrokerRpcClient is not connected");
    return RPC_E_FAULT;
  }
  RpcTryExcept {
    DispatchToFunction(rpc_function, params);
    return S_OK;
  } RpcExcept(HandleRpcException(RpcExceptionCode())) {
    LogRpcException("RPC error in RunRpc", RpcExceptionCode());

    if (allow_restart &&
        RPC_S_OK != ::RpcMgmtIsServerListening(binding_handle_)) {
      Disconnect();
      if (SUCCEEDED(Connect(true))) {
        return RunRpc(false, rpc_function, params);
      }
    }
    return RPC_E_FAULT;
  } RpcEndExcept
}

HRESULT BrokerRpcClient::FireEvent(const char* event_name,
                                   const char* event_args) {
  return RunRpc(allow_restarts_,
                &BrokerRpcClient_FireEvent,
                MakeRefTuple(binding_handle_, context_, event_name,
                             event_args));
}

HRESULT BrokerRpcClient::SendUmaHistogramTimes(const char* name, int sample) {
  return RunRpc(allow_restarts_,
                &BrokerRpcClient_SendUmaHistogramTimes,
                MakeRefTuple(binding_handle_, name, sample));
}

HRESULT BrokerRpcClient::SendUmaHistogramData(const char* name,
                                              int sample,
                                              int min,
                                              int max,
                                              int bucket_count) {
  return RunRpc(allow_restarts_,
                &BrokerRpcClient_SendUmaHistogramData,
                MakeRefTuple(binding_handle_, name, sample, min, max,
                          bucket_count));
}
<commit_msg>Revert 68291 - DCHECK to detect invalid BrokerRpcClient usage.<commit_after>// Copyright (c) 2010 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.
//
// Broker RPC Client implementation.

#include "ceee/ie/broker/broker_rpc_client.h"

#include <atlbase.h>
#include "base/lock.h"
#include "base/logging.h"
#include "base/tuple.h"
#include "base/win/scoped_comptr.h"
#include "broker_lib.h"  // NOLINT
#include "broker_rpc_lib.h"  // NOLINT
#include "ceee/common/com_utils.h"
#include "ceee/ie/broker/broker_rpc_utils.h"

namespace {

// Avoid using objects requiring unwind in functions that use __try.
void LogRpcException(const char* str, unsigned int exception_code) {
  LOG(ERROR) << str << com::LogWe(exception_code);
}

// Avoid using objects requiring unwind in functions that use __try.
void RpcDcheck(const char* message) {
  NOTREACHED() << message;
}

HRESULT BindRpc(std::wstring endpoint, RPC_BINDING_HANDLE* binding_handle) {
  DCHECK(binding_handle != NULL);
  std::wstring protocol = kRpcProtocol;
  DCHECK(!protocol.empty());
  DCHECK(!endpoint.empty());
  if (protocol.empty() || endpoint.empty() || binding_handle == NULL)
    return E_INVALIDARG;

  RPC_BINDING_HANDLE tmp_binding_handle = NULL;

  // TODO(vitalybuka@google.com): There's no guarantee (aside from name
  // uniqueness) that it will connect to an endpoint created by the same user.
  // Hint: The missing invocation is RpcBindingSetAuthInfoEx.
  VLOG(1) << "Connecting to RPC server. Endpoint: " << endpoint;
  RPC_WSTR string_binding = NULL;
  // Create binding string for given end point.
  RPC_STATUS status = ::RpcStringBindingCompose(
      NULL,
      reinterpret_cast<RPC_WSTR>(&protocol[0]),
      NULL,
      reinterpret_cast<RPC_WSTR>(&endpoint[0]),
      NULL,
      &string_binding);

  if (RPC_S_OK == status) {
    // Create binding from just generated binding string. Binding handle should
    // be used for PRC calls.
    status = ::RpcBindingFromStringBinding(string_binding, &tmp_binding_handle);
    ::RpcStringFree(&string_binding);
    if (RPC_S_OK == status) {
      VLOG(1) << "RPC client is connected. Endpoint: " << endpoint;
      *binding_handle = tmp_binding_handle;
      return S_OK;
    } else {
      LogRpcException("Failed to bind. RPC_STATUS:", status);
    }
  } else {
    LogRpcException("Failed to compose binding string. RPC_STATUS:", status);
  }
  return RPC_E_FAULT;
}

int HandleRpcException(unsigned int rpc_exception_code) {
  switch (rpc_exception_code) {
    case STATUS_ACCESS_VIOLATION:
    case STATUS_DATATYPE_MISALIGNMENT:
    case STATUS_PRIVILEGED_INSTRUCTION:
    case STATUS_BREAKPOINT:
    case STATUS_STACK_OVERFLOW:
    case STATUS_IN_PAGE_ERROR:
    case STATUS_GUARD_PAGE_VIOLATION:
      return EXCEPTION_CONTINUE_SEARCH;
    default:
      break;
  }
  return EXCEPTION_EXECUTE_HANDLER;
}

}  // namespace

BrokerRpcClient::BrokerRpcClient(bool allow_restarts)
    : context_(0),
      binding_handle_(NULL),
      allow_restarts_(allow_restarts) {
}

BrokerRpcClient::~BrokerRpcClient() {
  Disconnect();
}

void BrokerRpcClient::LockContext() {
  RpcTryExcept {
    context_ = BrokerRpcClient_Connect(binding_handle_);
  } RpcExcept(HandleRpcException(RpcExceptionCode())) {
    LogRpcException("RPC error in LockContext", RpcExceptionCode());
  } RpcEndExcept
}

void BrokerRpcClient::ReleaseContext() {
  RpcTryExcept {
    BrokerRpcClient_Disconnect(binding_handle_, &context_);
  } RpcExcept(HandleRpcException(RpcExceptionCode())) {
    LogRpcException("RPC error in ReleaseContext", RpcExceptionCode());
  } RpcEndExcept
}

HRESULT BrokerRpcClient::StartServer(IUnknown** server) {
  base::win::ScopedComPtr<IUnknown> broker;
  // TODO(vitalybuka@google.com): Start broker without COM after the last
  // COM interface is removed.
  HRESULT hr = broker.CreateInstance(CLSID_CeeeBroker);
  LOG_IF(ERROR, FAILED(hr)) << "Failed to create broker. " << com::LogHr(hr);
  if (FAILED(hr))
    return hr;
  *server = broker.Detach();
  return S_OK;
}

HRESULT BrokerRpcClient::Connect(bool start_server) {
  if (is_connected())
    return S_OK;

  // Keep alive until RPC is connected.
  base::win::ScopedComPtr<IUnknown> broker;
  if (start_server) {
    HRESULT hr = StartServer(broker.Receive());
    if (FAILED(hr))
      return hr;
  }

  if (SUCCEEDED(BindRpc(GetRpcEndpointAddress(), &binding_handle_)))
    LockContext();

  if (!is_connected()) {
    Disconnect();
    return RPC_E_FAULT;
  }
  return S_OK;
}

void BrokerRpcClient::Disconnect() {
  if (context_ != NULL)
    ReleaseContext();
  if (binding_handle_ != NULL) {
    RPC_STATUS status = ::RpcBindingFree(&binding_handle_);
    LOG_IF(WARNING, RPC_S_OK != status) <<
        "Failed to unbind. RPC_STATUS=0x" << com::LogWe(status);
  }
}

template<class Function, class Params>
HRESULT BrokerRpcClient::RunRpc(bool allow_restart,
                                Function rpc_function,
                                const Params& params) {
  if (!rpc_function) {
    RpcDcheck("rpc_function is NULL");
  }
  if (!is_connected())
    return RPC_E_FAULT;
  RpcTryExcept {
    DispatchToFunction(rpc_function, params);
    return S_OK;
  } RpcExcept(HandleRpcException(RpcExceptionCode())) {
    LogRpcException("RPC error in RunRpc", RpcExceptionCode());

    if (allow_restart &&
        RPC_S_OK != ::RpcMgmtIsServerListening(binding_handle_)) {
      Disconnect();
      if (SUCCEEDED(Connect(true))) {
        return RunRpc(false, rpc_function, params);
      }
    }
    return RPC_E_FAULT;
  } RpcEndExcept
}

HRESULT BrokerRpcClient::FireEvent(const char* event_name,
                                   const char* event_args) {
  return RunRpc(allow_restarts_,
                &BrokerRpcClient_FireEvent,
                MakeRefTuple(binding_handle_, context_, event_name,
                             event_args));
}

HRESULT BrokerRpcClient::SendUmaHistogramTimes(const char* name, int sample) {
  return RunRpc(allow_restarts_,
                &BrokerRpcClient_SendUmaHistogramTimes,
                MakeRefTuple(binding_handle_, name, sample));
}

HRESULT BrokerRpcClient::SendUmaHistogramData(const char* name,
                                              int sample,
                                              int min,
                                              int max,
                                              int bucket_count) {
  return RunRpc(allow_restarts_,
                &BrokerRpcClient_SendUmaHistogramData,
                MakeRefTuple(binding_handle_, name, sample, min, max,
                          bucket_count));
}
<|endoftext|>


<commit_before>
RICHRunLego()
{
   TControlBar *menu = new TControlBar("vertical","RICH Lego");
   menu->AddButton("Center chamber (40 bins)","gAlice->RunLego(\"Config.C\",40,80,100,40,80,100,0,500,600)","Fast run");
   menu->AddButton("All chambers (120 bins)","gAlice->RunLego(\"Config.C\",120,60,120,120,60,120,0,500,600)","Fast run");
   menu->AddButton("Center chamber (160 bins)","gAlice->RunLego(\"Config.C\",1600,80,100,160,80,100,0,500,600)","Slow run");
   menu->AddButton("All chambers hi (200 bins)","gAlice->RunLego(\"Config.C\",200,60,120,200,60,120,0,500,600)","Very slow run");
   menu->Show();
}

<commit_msg>Corrected RunLego() calls.<commit_after>
RICHRunLego()
{
   TControlBar *menu = new TControlBar("vertical","RICH Lego");
   menu->AddButton("Center chamber (40 bins)","gAlice->RunLego(\"Config.C\",40,80,100,40,80,100,0,600,500)","Fast run");
   menu->AddButton("All chambers (120 bins)","gAlice->RunLego(\"Config.C\",120,60,120,120,60,120,0,600,500)","Fast run");
   menu->AddButton("Center chamber (80 bins)","gAlice->RunLego(\"Config.C\",80,80,100,80,80,100,0,600,500)","Slow run");
   menu->AddButton("All chambers hi (200 bins)","gAlice->RunLego(\"Config.C\",200,60,120,200,60,120,0,600,500)","Very slow run");
   menu->Show();
}

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------- //
//						                     //
//  Analysis package	  			                     //
//        					                     //
// ----------------------------------------------------------------- //
//						                     //
//  AUTHOR: Miguel Ramos Pernas		                             //
//  e-mail: miguel.ramos.pernas@cern.ch		                     //
//						                     //
//  Last update: 22/04/2016			                     //
//   						                     //
// ----------------------------------------------------------------- //
//						                     //
//  Description:				                     //
//						                     //
//  Implements the class to make one-dimensional adaptive binning    //
//  histograms. The construction can be made given a set of vectors  //
//  or a TTree object and the name of the leaves.                    //
//						                     //
// ----------------------------------------------------------------- //
///////////////////////////////////////////////////////////////////////

#include "AdaptiveBinning1D.h"

#include "TLeaf.h"

#include <algorithm>
#include <cmath>
#include <vector>

//______________________________________________________________________________

// -- CONSTRUCTORS AND DESTRUCTOR

//______________________________________________________________________________
// Main constructor
Analysis::AdaptiveBinning1D::AdaptiveBinning1D() : AdaptiveBinning() { }

//______________________________________________________________________________
// Constructor given vectors of values
Analysis::AdaptiveBinning1D::AdaptiveBinning1D( size_t  occ,
						double  vmin,
						double  vmax,
						std::vector<double> *values,
						std::vector<double> *weights ) :
  AdaptiveBinning(),
  fMax( vmax ),
  fMin( vmin ) {

  auto itv = values -> begin();
  if ( weights ) {
    if ( values -> size() != weights -> size() )
      std::cerr <<
	"ERROR: The lengths of the vectors containing the values and the weights do no match"
		<< std::endl;
    auto itw = weights -> begin();
    while( itv != values -> end() )
      if ( *itv >= vmin && *itv <= vmax )
	fData.push_back( std::make_pair( *itv++, *itw++ ) );
    fWeighted = true;
    this -> Construct( occ );
  }
  else {
    while( itv != values -> end() )
      if ( *itv >= vmin && *itv <= vmax )
	fData.push_back( std::make_pair( *itv++, 1 ) );
    fWeighted = false;
    this -> Construct( occ );
  }
}

//______________________________________________________________________________
// Constructor given a TTree object
Analysis::AdaptiveBinning1D::AdaptiveBinning1D( size_t  occ,
						double  vmin,
						double  vmax,
						TTree  *tree,
						const char *vname,
						const char *wname ) :
  AdaptiveBinning(),
  fMax( vmax ),
  fMin( vmin ) {

  TLeaf *leaf = tree -> GetLeaf( vname );
  if ( wname ) {
    TLeaf *wleaf = tree -> GetLeaf( wname );
    for ( long int ievt = 0; ievt < tree -> GetEntries(); ievt++ ) {
      tree -> GetEntry( ievt );
      if ( leaf -> GetValue() >= vmin && leaf -> GetValue() <= vmax )
	fData.push_back( std::make_pair( leaf -> GetValue(), wleaf -> GetValue() ) );
    }
    fWeighted = true;
    this -> Construct( occ );
  }
  else {
    for ( long int ievt = 0; ievt < tree -> GetEntries(); ievt++ ) {
      tree -> GetEntry( ievt );
      if ( leaf -> GetValue() >= vmin && leaf -> GetValue() <= vmax )
	fData.push_back( std::make_pair( leaf -> GetValue(), 1 ) );
    }
    fWeighted = false;
    this -> Construct( occ );
  }
}

//______________________________________________________________________________
// Destructor
Analysis::AdaptiveBinning1D::~AdaptiveBinning1D() { }

//______________________________________________________________________________

// -- PUBLIC METHODS

//______________________________________________________________________________
// Generates a new branch with name < brname > in the tree < itree >, and fills
// it with the bin corresponding to each event.
void Analysis::AdaptiveBinning1D::BinsToTree( std::string        brname,
					      TTree             *itree,
					      const std::string &datavar ) {
  int ibin;
  itree -> SetBranchStatus( "*", false );
  itree -> SetBranchStatus( datavar.c_str(), true );
  TH1     *hist   = this -> GetStruct( brname.c_str(), brname.c_str() );
  TLeaf   *leaf   = itree -> GetLeaf( datavar.c_str() );
  TBranch *branch = itree -> Branch( brname.c_str(), &ibin, ( brname + "/I" ).c_str() );
  for ( Long64_t ievt = 0; ievt < itree -> GetEntries(); ++ievt ) {
    itree -> GetEntry( ievt );
    ibin = hist -> Fill( leaf -> GetValue() );
    branch -> Fill();
  }
  itree -> AutoSave();
  itree -> SetBranchStatus( "*", true );
  delete hist;
}

//______________________________________________________________________________
// Returns an histogram with the adaptive bins and filled with the data used to
// construct it
TH1D* Analysis::AdaptiveBinning1D::GetHist( const char *name, const char *title ) {
  TH1D *hist = this -> GetStruct( name, title );
  for ( auto it = fData.begin(); it != fData.end(); it++ )
    hist -> Fill( it -> first, it -> second );
  return hist;
}

//______________________________________________________________________________
// Returns an empty histogram with the adaptive binning structure
TH1D* Analysis::AdaptiveBinning1D::GetStruct( const char *name, const char *title ) {
 double *bins = new double[ fBinList.size() + 1 ];
  for ( size_t i = 0; i < fBinList.size(); i++ )
    bins[ i ] = fBinList[ i ].fMin;
  bins[ fBinList.size() ] = fBinList.back().fMax;
  TH1D *hist = new TH1D( name, title, fBinList.size(), bins );
  delete bins;
  return hist;
}

//______________________________________________________________________________

// -- PROTECTED METHOD

//______________________________________________________________________________
// Constructs the vector of one-dimensional adaptive bins
void Analysis::AdaptiveBinning1D::Construct( const size_t &occ ) {

  std::cout << "--- Making an adaptive binning division ---" << std::endl;

  // Calculates the sum of weights
  double sw = 0;
  for ( auto it = fData.begin(); it != fData.end(); it++ )
    sw += it -> second;

  // Calculates the minimum distance between events
  double new_delta, delta = std::abs( fData.front().first - fData.back().first );
  for ( auto it1 = fData.begin(); it1 != fData.end(); it1++ )
    for ( auto it2 = it1 + 1; it2 != fData.end(); it2++ ) {
      new_delta = std::abs( it2 -> first - it1 -> first );
      if ( new_delta < delta && new_delta != 0 )
	delta = new_delta;
    }
  delta /= 2;

  // Calculates the number of bins
  size_t nbins = size_t( sw )/occ;

  // If the number of bins is zero an error is displayed
  if ( nbins == 0 )
    std::cerr << "ERROR: Occupancy requested is too big: " << occ << std::endl;

  // Creates the vector of bins
  fBinList = std::vector<Bin1D>( nbins );

  // Sorts the data and the weights
  std::sort( fData.begin(), fData.end(), [] ( std::pair<double, double> it1,
					      std::pair<double, double> it2 ) {
	       return it1.first < it2.first; } );

  // Depending if it is working with weights or with entries it fills the bins
  auto id = fData.begin();
  if ( fWeighted ) {
    double auxsw = sw, swpb = 0;
    for ( auto ib = fBinList.begin(); ib != fBinList.end(); ib++ ) {
      swpb = auxsw/nbins--;
      while ( ib -> GetSumOfWeights() < swpb && id != fData.end() ) {
	ib -> Fill( id -> first, id -> second );
	++id;
      }
      auxsw -= ib -> GetSumOfWeights();
    }
    // If the end of the data has not been reached, it fills the last bin with the rest of the events
    while ( id != fData.end() )
      fBinList.back().Fill( id -> first, id++ -> second );
  }
  else {
    size_t
      enpb = fData.size() / nbins,
      add1 = fData.size() % nbins;
    for ( auto ib = fBinList.begin(); ib != fBinList.end(); ib++ ) {
      if ( add1 ) {
	while ( ib -> GetEntries() < enpb + 1 )
	  ib -> Fill( id++ -> first );
	add1--;
      }
      else
	while ( ib -> GetEntries() < enpb )
	  ib -> Fill( id++ -> first );
    }
  }

  // Corrects the first and the last bins so the range is the specified in the constructor
  fBinList.front().fMin  = fMin;
  fBinList.front().fMax += delta;
  fBinList.back().fMax   = fMax;

  // Sets the different bin limits
  auto itlast = fBinList.end() - 1;
  for ( auto it = fBinList.begin() + 1; it != itlast; it++ )
    it -> SetBin( ( it - 1 ) -> fMax, it -> fMax + delta );
  fBinList.back().fMin = ( fBinList.end() - 2 ) -> fMax;

  //for ( auto it = fBinList.begin(); it != fBinList.end(); it++ )
  //  std::cout << it -> GetMin() << std::endl;

  // Displays the information of the process
  this -> DisplayInfo( fData.size(), sw, nbins, sw/nbins );
}
<commit_msg>Solved bugs in class AdaptiveBinning1D when working with weighted samples<commit_after>///////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------- //
//						                     //
//  Analysis package	  			                     //
//        					                     //
// ----------------------------------------------------------------- //
//						                     //
//  AUTHOR: Miguel Ramos Pernas		                             //
//  e-mail: miguel.ramos.pernas@cern.ch		                     //
//						                     //
//  Last update: 22/04/2016			                     //
//   						                     //
// ----------------------------------------------------------------- //
//						                     //
//  Description:				                     //
//						                     //
//  Implements the class to make one-dimensional adaptive binning    //
//  histograms. The construction can be made given a set of vectors  //
//  or a TTree object and the name of the leaves.                    //
//						                     //
// ----------------------------------------------------------------- //
///////////////////////////////////////////////////////////////////////

#include "AdaptiveBinning1D.h"

#include "TLeaf.h"

#include <algorithm>
#include <cmath>
#include <vector>

//______________________________________________________________________________

// -- CONSTRUCTORS AND DESTRUCTOR

//______________________________________________________________________________
// Main constructor
Analysis::AdaptiveBinning1D::AdaptiveBinning1D() : AdaptiveBinning() { }

//______________________________________________________________________________
// Constructor given vectors of values
Analysis::AdaptiveBinning1D::AdaptiveBinning1D( size_t  occ,
						double  vmin,
						double  vmax,
						std::vector<double> *values,
						std::vector<double> *weights ) :
  AdaptiveBinning(),
  fMax( vmax ),
  fMin( vmin ) {

  auto itv = values -> begin();
  if ( weights ) {
    if ( values -> size() != weights -> size() )
      std::cerr <<
	"ERROR: The lengths of the vectors containing the values and the weights do no match"
		<< std::endl;
    auto itw = weights -> begin();
    while( itv != values -> end() )
      if ( *itv >= vmin && *itv <= vmax )
	fData.push_back( std::make_pair( *itv++, *itw++ ) );
    fWeighted = true;
    this -> Construct( occ );
  }
  else {
    while( itv != values -> end() )
      if ( *itv >= vmin && *itv <= vmax )
	fData.push_back( std::make_pair( *itv++, 1 ) );
    fWeighted = false;
    this -> Construct( occ );
  }
}

//______________________________________________________________________________
// Constructor given a TTree object
Analysis::AdaptiveBinning1D::AdaptiveBinning1D( size_t  occ,
						double  vmin,
						double  vmax,
						TTree  *tree,
						const char *vname,
						const char *wname ) :
  AdaptiveBinning(),
  fMax( vmax ),
  fMin( vmin ) {

  TLeaf *leaf = tree -> GetLeaf( vname );
  if ( wname ) {
    TLeaf *wleaf = tree -> GetLeaf( wname );
    for ( long int ievt = 0; ievt < tree -> GetEntries(); ievt++ ) {
      tree -> GetEntry( ievt );
      if ( leaf -> GetValue() >= vmin && leaf -> GetValue() < vmax )
	fData.push_back( std::make_pair( leaf -> GetValue(), wleaf -> GetValue() ) );
    }
    fWeighted = true;
    this -> Construct( occ );
  }
  else {
    for ( long int ievt = 0; ievt < tree -> GetEntries(); ievt++ ) {
      tree -> GetEntry( ievt );
      if ( leaf -> GetValue() >= vmin && leaf -> GetValue() < vmax )
	fData.push_back( std::make_pair( leaf -> GetValue(), 1 ) );
    }
    fWeighted = false;
    this -> Construct( occ );
  }
}

//______________________________________________________________________________
// Destructor
Analysis::AdaptiveBinning1D::~AdaptiveBinning1D() { }

//______________________________________________________________________________

// -- PUBLIC METHODS

//______________________________________________________________________________
// Generates a new branch with name < brname > in the tree < itree >, and fills
// it with the bin corresponding to each event.
void Analysis::AdaptiveBinning1D::BinsToTree( std::string        brname,
					      TTree             *itree,
					      const std::string &datavar ) {
  int ibin;
  itree -> SetBranchStatus( "*", false );
  itree -> SetBranchStatus( datavar.c_str(), true );
  TH1     *hist   = this -> GetStruct( brname.c_str(), brname.c_str() );
  TLeaf   *leaf   = itree -> GetLeaf( datavar.c_str() );
  TBranch *branch = itree -> Branch( brname.c_str(), &ibin, ( brname + "/I" ).c_str() );
  for ( Long64_t ievt = 0; ievt < itree -> GetEntries(); ++ievt ) {
    itree -> GetEntry( ievt );
    ibin = hist -> Fill( leaf -> GetValue() );
    branch -> Fill();
  }
  itree -> AutoSave();
  itree -> SetBranchStatus( "*", true );
  delete hist;
}

//______________________________________________________________________________
// Returns an histogram with the adaptive bins and filled with the data used to
// construct it
TH1D* Analysis::AdaptiveBinning1D::GetHist( const char *name, const char *title ) {
  TH1D *hist = this -> GetStruct( name, title );
  for ( auto it = fData.begin(); it != fData.end(); it++ )
    hist -> Fill( it -> first, it -> second );
  return hist;
}

//______________________________________________________________________________
// Returns an empty histogram with the adaptive binning structure
TH1D* Analysis::AdaptiveBinning1D::GetStruct( const char *name, const char *title ) {
 double *bins = new double[ fBinList.size() + 1 ];
  for ( size_t i = 0; i < fBinList.size(); i++ )
    bins[ i ] = fBinList[ i ].fMin;
  bins[ fBinList.size() ] = fBinList.back().fMax;
  TH1D *hist = new TH1D( name, title, fBinList.size(), bins );
  delete bins;
  return hist;
}

//______________________________________________________________________________

// -- PROTECTED METHOD

//______________________________________________________________________________
// Constructs the vector of one-dimensional adaptive bins
void Analysis::AdaptiveBinning1D::Construct( const size_t &occ ) {

  std::cout << "--- Making an adaptive binning division ---" << std::endl;

  // Calculates the sum of weights
  double sw = 0;
  for ( auto it = fData.begin(); it != fData.end(); it++ )
    sw += it -> second;

  // Calculates the minimum distance between events
  double new_delta, delta = std::abs( fData.front().first - fData.back().first );
  for ( auto it1 = fData.begin(); it1 != fData.end(); it1++ )
    for ( auto it2 = it1 + 1; it2 != fData.end(); it2++ ) {
      new_delta = std::abs( it2 -> first - it1 -> first );
      if ( new_delta < delta && new_delta != 0 )
	delta = new_delta;
    }
  delta /= 2;

  // Calculates the number of bins
  size_t nbins = size_t( sw )/occ;

  // If the number of bins is zero an error is displayed
  if ( nbins == 0 )
    std::cerr << "ERROR: Occupancy requested is too big: " << occ << std::endl;

  // Creates the vector of bins
  fBinList = std::vector<Bin1D>( nbins );

  // Sorts the data and the weights
  std::sort( fData.begin(), fData.end(), [] ( std::pair<double, double> it1,
					      std::pair<double, double> it2 ) {
	       return it1.first < it2.first; } );

  // Depending if it is working with weights or with entries it fills the bins
  auto id = fData.begin();
  if ( fWeighted ) {
    double auxsw = sw, swpb = 0;
    size_t binsout = 0;
    for ( auto ib = fBinList.begin(); ib != fBinList.end(); ib++ ) {
      swpb = auxsw/( nbins - binsout++ );
      while ( ib -> GetSumOfWeights() < swpb && id != fData.end() ) {
	ib -> Fill( id -> first, id -> second );
	++id;
      }
      auxsw -= ib -> GetSumOfWeights();
    }
    // If the end of the data has not been reached, it fills the last bin with the rest of the events
    while ( id != fData.end() )
      fBinList.back().Fill( id -> first, id++ -> second );
  }
  else {
    size_t
      enpb = fData.size() / nbins,
      add1 = fData.size() % nbins;
    for ( auto ib = fBinList.begin(); ib != fBinList.end(); ib++ ) {
      if ( add1 ) {
	while ( ib -> GetEntries() < enpb + 1 )
	  ib -> Fill( id++ -> first );
	add1--;
      }
      else
	while ( ib -> GetEntries() < enpb )
	  ib -> Fill( id++ -> first );
    }
  }

  // Corrects the first and the last bins so the range is the specified in the constructor
  fBinList.front().fMin  = fMin;
  fBinList.front().fMax += delta;
  fBinList.back().fMax   = fMax;

  // Sets the different bin limits
  auto itlast = fBinList.end() - 1;
  for ( auto it = fBinList.begin() + 1; it != itlast; it++ )
    it -> SetBin( ( it - 1 ) -> fMax, it -> fMax + delta );
  fBinList.back().fMin = ( fBinList.end() - 2 ) -> fMax;

  // Displays the information of the process
  this -> DisplayInfo( fData.size(), sw, nbins, sw/nbins );
}
<|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 "chrome/browser/automation/testing_automation_provider.h"

#include "base/values.h"
#include "chrome/browser/automation/automation_provider_json.h"
#include "chrome/browser/automation/automation_provider_observers.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/screen_lock_library.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"

using chromeos::CrosLibrary;
using chromeos::NetworkLibrary;

namespace {

DictionaryValue* GetNetworkInfoDict(const chromeos::Network* network) {
  DictionaryValue* item = new DictionaryValue;
  item->SetString("service_path", network->service_path());
  item->SetString("name", network->name());
  item->SetString("device_path", network->device_path());
  item->SetString("ip_address", network->ip_address());
  item->SetString("status", network->GetStateString());
  return item;
}

}  // namespace

void TestingAutomationProvider::LoginAsGuest(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->LoginAsGuest();
}

void TestingAutomationProvider::Login(DictionaryValue* args,
                                      IPC::Message* reply_message) {
  std::string username, password;
  if (!args->GetString("username", &username) ||
      !args->GetString("password", &password)) {
    AutomationJSONReply(this, reply_message).SendError(
        "Invalid or missing args");
    return;
  }

  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->Login(username, password);
}

// Logging out could have other undesirable side effects: session_manager is
// killed, so its children, including chrome and the window manager will also
// be killed. SSH connections might be closed, the test binary might be killed.
void TestingAutomationProvider::Logout(DictionaryValue* args,
                                       IPC::Message* reply_message) {
  // Send success before stopping session because if we're a child of
  // session manager then we'll die when the session is stopped.
  AutomationJSONReply(this, reply_message).SendSuccess(NULL);
  if (chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->StopSession("");
}

void TestingAutomationProvider::ScreenLock(DictionaryValue* args,
                                           IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, true);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenLockRequested();
}

void TestingAutomationProvider::ScreenUnlock(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, false);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenUnlockRequested();
}

void TestingAutomationProvider::GetNetworkInfo(DictionaryValue* args,
                                               IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  scoped_ptr<DictionaryValue> return_value(new DictionaryValue);

  // IP address.
  return_value->SetString("ip_address", network_library->IPAddress());

  // Ethernet network.
  bool ethernet_available = network_library->ethernet_available();
  bool ethernet_enabled = network_library->ethernet_enabled();
  if (ethernet_available && ethernet_enabled) {
    const chromeos::EthernetNetwork* ethernet_network =
        network_library->ethernet_network();
    if (ethernet_network)
      return_value->Set("ethernet_network",
                        GetNetworkInfoDict(ethernet_network));
  }

  // Wi-fi networks.
  bool wifi_available = network_library->wifi_available();
  bool wifi_enabled = network_library->wifi_enabled();
  if (wifi_available && wifi_enabled) {
    const chromeos::WifiNetworkVector& wifi_networks =
        network_library->wifi_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < wifi_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(wifi_networks[i]);
      item->SetInteger("strength", wifi_networks[i]->strength());
      item->SetBoolean("encrypted", wifi_networks[i]->encrypted());
      item->SetString("encryption", wifi_networks[i]->GetEncryptionString());
      items->Append(item);
    }
    return_value->Set("wifi_networks", items);
  }

  // Cellular networks.
  bool cellular_available = network_library->cellular_available();
  bool cellular_enabled = network_library->cellular_enabled();
  if (cellular_available && cellular_enabled) {
    const chromeos::CellularNetworkVector& cellular_networks =
        network_library->cellular_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < cellular_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(cellular_networks[i]);
      item->SetInteger("strength", cellular_networks[i]->strength());
      item->SetString("operator_name", cellular_networks[i]->operator_name());
      item->SetString("operator_code", cellular_networks[i]->operator_code());
      item->SetString("payment_url", cellular_networks[i]->payment_url());
      item->SetString("usage_url", cellular_networks[i]->usage_url());
      item->SetString("network_technology",
                      cellular_networks[i]->GetNetworkTechnologyString());
      item->SetString("connectivity_state",
                      cellular_networks[i]->GetConnectivityStateString());
      item->SetString("activation_state",
                      cellular_networks[i]->GetActivationStateString());
      item->SetString("roaming_state",
                      cellular_networks[i]->GetRoamingStateString());
      items->Append(item);
    }
    return_value->Set("cellular_networks", items);
  }

  reply.SendSuccess(return_value.get());
}

void TestingAutomationProvider::ConnectToWifiNetwork(
    DictionaryValue* args, IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);
  std::string service_path, password, identity, certpath;
  if (!args->GetString("service_path", &service_path) ||
      !args->GetString("password", &password) ||
      !args->GetString("identity", &identity) ||
      !args->GetString("certpath", &certpath)) {
    reply.SendError("Invalid or missing args");
    return;
  }

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  WifiNetwork* wifi = network_library->FindWifiNetworkByPath(service_path);
  if (!wifi) {
    reply.SendError("Failed to connect");
    return;
  }
  if (!password.empty())
    wifi->SetPassphrase(password);
  if (!identity.empty())
    wifi->SetIdentity(identity);
  if (!certpath.empty())
    wifi->SetCertPath(certpath);
  network_library->ConnectToWifiNetwork(service_path);

  // TODO(stevenjb): Observe the network library and check for a successful
  // connection.

  reply.SendSuccess(NULL);
}
<commit_msg>Revert 77711 - Patch for http://codereview.chromium.org/6628023/<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 "chrome/browser/automation/testing_automation_provider.h"

#include "base/values.h"
#include "chrome/browser/automation/automation_provider_json.h"
#include "chrome/browser/automation/automation_provider_observers.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/screen_lock_library.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"

using chromeos::CrosLibrary;
using chromeos::NetworkLibrary;

namespace {

DictionaryValue* GetNetworkInfoDict(const chromeos::Network* network) {
  DictionaryValue* item = new DictionaryValue;
  item->SetString("service_path", network->service_path());
  item->SetString("name", network->name());
  item->SetString("device_path", network->device_path());
  item->SetString("ip_address", network->ip_address());
  item->SetString("status", network->GetStateString());
  return item;
}

}  // namespace

void TestingAutomationProvider::LoginAsGuest(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->LoginAsGuest();
}

void TestingAutomationProvider::Login(DictionaryValue* args,
                                      IPC::Message* reply_message) {
  std::string username, password;
  if (!args->GetString("username", &username) ||
      !args->GetString("password", &password)) {
    AutomationJSONReply(this, reply_message).SendError(
        "Invalid or missing args");
    return;
  }

  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->Login(username, password);
}

// Logging out could have other undesirable side effects: session_manager is
// killed, so its children, including chrome and the window manager will also
// be killed. SSH connections might be closed, the test binary might be killed.
void TestingAutomationProvider::Logout(DictionaryValue* args,
                                       IPC::Message* reply_message) {
  // Send success before stopping session because if we're a child of
  // session manager then we'll die when the session is stopped.
  AutomationJSONReply(this, reply_message).SendSuccess(NULL);
  if (chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->StopSession("");
}

void TestingAutomationProvider::ScreenLock(DictionaryValue* args,
                                           IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, true);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenLockRequested();
}

void TestingAutomationProvider::ScreenUnlock(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, false);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenUnlockRequested();
}

void TestingAutomationProvider::GetNetworkInfo(DictionaryValue* args,
                                               IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  scoped_ptr<DictionaryValue> return_value(new DictionaryValue);

  // IP address.
  return_value->SetString("ip_address", network_library->IPAddress());

  // Ethernet network.
  bool ethernet_available = network_library->ethernet_available();
  bool ethernet_enabled = network_library->ethernet_enabled();
  if (ethernet_available && ethernet_enabled) {
    const chromeos::EthernetNetwork* ethernet_network =
        network_library->ethernet_network();
    if (ethernet_network)
      return_value->Set("ethernet_network",
                        GetNetworkInfoDict(ethernet_network));
  }

  // Wi-fi networks.
  bool wifi_available = network_library->wifi_available();
  bool wifi_enabled = network_library->wifi_enabled();
  if (wifi_available && wifi_enabled) {
    const chromeos::WifiNetworkVector& wifi_networks =
        network_library->wifi_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < wifi_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(wifi_networks[i]);
      item->SetInteger("strength", wifi_networks[i]->strength());
      item->SetBoolean("encrypted", wifi_networks[i]->encrypted());
      item->SetString("encryption", wifi_networks[i]->GetEncryptionString());
      items->Append(item);
    }
    return_value->Set("wifi_networks", items);
  }

  // Cellular networks.
  bool cellular_available = network_library->cellular_available();
  bool cellular_enabled = network_library->cellular_enabled();
  if (cellular_available && cellular_enabled) {
    const chromeos::CellularNetworkVector& cellular_networks =
        network_library->cellular_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < cellular_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(cellular_networks[i]);
      item->SetInteger("strength", cellular_networks[i]->strength());
      item->SetString("operator_name", cellular_networks[i]->operator_name());
      item->SetString("operator_code", cellular_networks[i]->operator_code());
      item->SetString("payment_url", cellular_networks[i]->payment_url());
      item->SetString("usage_url", cellular_networks[i]->usage_url());
      item->SetString("network_technology",
                      cellular_networks[i]->GetNetworkTechnologyString());
      item->SetString("connectivity_state",
                      cellular_networks[i]->GetConnectivityStateString());
      item->SetString("activation_state",
                      cellular_networks[i]->GetActivationStateString());
      item->SetString("roaming_state",
                      cellular_networks[i]->GetRoamingStateString());
      items->Append(item);
    }
    return_value->Set("cellular_networks", items);
  }

  reply.SendSuccess(return_value.get());
}

void TestingAutomationProvider::ConnectToWifiNetwork(
    DictionaryValue* args, IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);
  std::string service_path, password, identity, certpath;
  if (!args->GetString("service_path", &service_path) ||
      !args->GetString("password", &password) ||
      !args->GetString("identity", &identity) ||
      !args->GetString("certpath", &certpath)) {
    reply.SendError("Invalid or missing args");
    return;
  }

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  if (!network_library->ConnectToWifiNetwork(
      service_path, password, identity, certpath)) {
    reply.SendError("Failed to connect");
    return;
  }

  reply.SendSuccess(NULL);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: basmodnode.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2004-10-22 14:01:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SCRIPTING_BASMODNODE_HXX
#include "basmodnode.hxx"
#endif

#ifndef SCRIPTING_BASMETHNODE_HXX
#include "basmethnode.hxx"
#endif

#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#endif

#ifndef _SBXCLASS_HXX
#include <svtools/sbx.hxx>
#endif
#ifndef _SB_SBSTAR_HXX
#include <basic/sbstar.hxx>
#endif
#ifndef _SB_SBMOD_HXX
#include <basic/sbmod.hxx>
#endif
#ifndef _SB_SBMETH_HXX
#include <basic/sbmeth.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::script;

//.........................................................................
namespace basprov
{
//.........................................................................

    // =============================================================================
    // BasicModuleNodeImpl
    // =============================================================================

    BasicModuleNodeImpl::BasicModuleNodeImpl( const Reference< XComponentContext >& rxContext,
        const ::rtl::OUString& sScriptingContext, SbModule* pModule, bool isAppScript )
        :m_xContext( rxContext )
        ,m_sScriptingContext( sScriptingContext )
        ,m_pModule( pModule )
        ,m_bIsAppScript( isAppScript )
    {
    }

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

    BasicModuleNodeImpl::~BasicModuleNodeImpl()
    {
    }

    // -----------------------------------------------------------------------------
    // XBrowseNode
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicModuleNodeImpl::getName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        ::rtl::OUString sModuleName;
        if ( m_pModule )
            sModuleName = m_pModule->GetName();

        return sModuleName;
    }

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

    Sequence< Reference< browse::XBrowseNode > > BasicModuleNodeImpl::getChildNodes(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        Sequence< Reference< browse::XBrowseNode > > aChildNodes;

        if ( m_pModule )
        {
            SbxArray* pMethods = m_pModule->GetMethods();
            if ( pMethods )
            {
                sal_Int32 nCount = pMethods->Count();
                aChildNodes.realloc( nCount );
                Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();

                for ( sal_Int32 i = 0; i < nCount; ++i )
                {
                    SbMethod* pMethod = static_cast< SbMethod* >( pMethods->Get( static_cast< USHORT >( i ) ) );
                    if ( pMethod )
                        pChildNodes[i] = static_cast< browse::XBrowseNode* >( new BasicMethodNodeImpl( m_xContext, m_sScriptingContext, pMethod, m_bIsAppScript ) );
                }
            }
        }

        return aChildNodes;
    }

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

    sal_Bool BasicModuleNodeImpl::hasChildNodes(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        sal_Bool bReturn = sal_False;
        if ( m_pModule )
        {
            SbxArray* pMethods = m_pModule->GetMethods();
            if ( pMethods && pMethods->Count() > 0 )
                bReturn = sal_True;
        }

        return bReturn;
    }

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

    sal_Int16 BasicModuleNodeImpl::getType(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return browse::BrowseNodeTypes::CONTAINER;
    }

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

//.........................................................................
}   // namespace basprov
//.........................................................................
<commit_msg>INTEGRATION: CWS tbe15 (1.6.12); FILE MERGED 2004/12/03 16:23:27 tbe 1.6.12.1: #i38139# Tools/Macro/Run Macro freezes office when Basic macro is already running<commit_after>/*************************************************************************
 *
 *  $RCSfile: basmodnode.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-13 17:42:57 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SCRIPTING_BASMODNODE_HXX
#include "basmodnode.hxx"
#endif

#ifndef SCRIPTING_BASMETHNODE_HXX
#include "basmethnode.hxx"
#endif

#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SBXCLASS_HXX
#include <svtools/sbx.hxx>
#endif
#ifndef _SB_SBSTAR_HXX
#include <basic/sbstar.hxx>
#endif
#ifndef _SB_SBMOD_HXX
#include <basic/sbmod.hxx>
#endif
#ifndef _SB_SBMETH_HXX
#include <basic/sbmeth.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::script;

//.........................................................................
namespace basprov
{
//.........................................................................

    // =============================================================================
    // BasicModuleNodeImpl
    // =============================================================================

    BasicModuleNodeImpl::BasicModuleNodeImpl( const Reference< XComponentContext >& rxContext,
        const ::rtl::OUString& sScriptingContext, SbModule* pModule, bool isAppScript )
        :m_xContext( rxContext )
        ,m_sScriptingContext( sScriptingContext )
        ,m_pModule( pModule )
        ,m_bIsAppScript( isAppScript )
    {
    }

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

    BasicModuleNodeImpl::~BasicModuleNodeImpl()
    {
    }

    // -----------------------------------------------------------------------------
    // XBrowseNode
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicModuleNodeImpl::getName(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        ::rtl::OUString sModuleName;
        if ( m_pModule )
            sModuleName = m_pModule->GetName();

        return sModuleName;
    }

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

    Sequence< Reference< browse::XBrowseNode > > BasicModuleNodeImpl::getChildNodes(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        Sequence< Reference< browse::XBrowseNode > > aChildNodes;

        if ( m_pModule )
        {
            SbxArray* pMethods = m_pModule->GetMethods();
            if ( pMethods )
            {
                sal_Int32 nCount = pMethods->Count();
                aChildNodes.realloc( nCount );
                Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();

                for ( sal_Int32 i = 0; i < nCount; ++i )
                {
                    SbMethod* pMethod = static_cast< SbMethod* >( pMethods->Get( static_cast< USHORT >( i ) ) );
                    if ( pMethod )
                        pChildNodes[i] = static_cast< browse::XBrowseNode* >( new BasicMethodNodeImpl( m_xContext, m_sScriptingContext, pMethod, m_bIsAppScript ) );
                }
            }
        }

        return aChildNodes;
    }

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

    sal_Bool BasicModuleNodeImpl::hasChildNodes(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        sal_Bool bReturn = sal_False;
        if ( m_pModule )
        {
            SbxArray* pMethods = m_pModule->GetMethods();
            if ( pMethods && pMethods->Count() > 0 )
                bReturn = sal_True;
        }

        return bReturn;
    }

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

    sal_Int16 BasicModuleNodeImpl::getType(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        return browse::BrowseNodeTypes::CONTAINER;
    }

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

//.........................................................................
}   // namespace basprov
//.........................................................................
<|endoftext|>


<commit_before>/*
    yahoocontact.cpp - Yahoo Contact

    Copyright (c) 2003-2004 by Matt Rogers <matt.rogers@kdemail.net>
    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Portions based on code by Bruno Rodrigues <bruno.rodrigues@litux.org>

    Copyright (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/
#include "kopetegroup.h"
#include "kopetemessagemanager.h"
#include "kopeteonlinestatus.h"
#include "kopetemetacontact.h"
#include "kopetemessagemanagerfactory.h"
#include "kopetemetacontact.h"

// Local Includes
#include "yahoocontact.h"
#include "yahooaccount.h"

// QT Includes
#include <qregexp.h>

// KDE Includes
#include <kdebug.h>
#include <kapplication.h>
#include <kmessagebox.h>

YahooContact::YahooContact( YahooAccount *account, const QString &userId, const QString &fullName, KopeteMetaContact *metaContact )
	: KopeteContact( account, userId, metaContact )
{
	kdDebug(14180) << k_funcinfo << endl;

	m_userId = userId;
	if ( metaContact )
		m_groupName = metaContact->groups().getFirst()->displayName();
	m_manager = 0L;
	m_account = account;

	// Update ContactList
	setDisplayName( fullName );
	setOnlineStatus( static_cast<YahooProtocol*>( m_account->protocol() )->Offline );

	if ( m_account->haveContactList() )
		syncToServer();
}

YahooContact::~YahooContact()
{
}

void YahooContact::serialize(QMap<QString, QString> &serializedData, QMap<QString, QString> &addressBookData)
{
	//kdDebug(14180) << k_funcinfo << endl;

	KopeteContact::serialize(serializedData, addressBookData);
}

void YahooContact::syncToServer()
{
	kdDebug(14180) << k_funcinfo  << endl;
	if(!m_account->isConnected()) return;

	if ( !m_account->isOnServer(m_userId) && !metaContact()->isTemporary() )
	{	kdDebug(14180) << "Contact " << m_userId << " doesn't exist on server-side. Adding..." << endl;

		KopeteGroupList groupList = metaContact()->groups();
		for( KopeteGroup *g = groupList.first(); g; g = groupList.next() )
			m_account->yahooSession()->addBuddy(m_userId, g->displayName() );
	}
}

void YahooContact::syncGroups()
{
	if ( !m_account->isConnected() )
		return;

	if ( !m_account->isOnServer( contactId() ) )
	{
		//TODO: Share this code with the above function
		kdDebug(14180) << k_funcinfo << "Contact isn't on the server. Adding..." << endl;
		KopeteGroupList groupList = metaContact()->groups();
		for ( KopeteGroup *g = groupList.first(); g; g = groupList.next() )
			m_account->yahooSession()->addBuddy(m_userId, g->displayName() );
	}
	else
	{
		QString newGroup = metaContact()->groups().first()->displayName();
		m_account->yahooSession()->changeBuddyGroup( contactId(), m_groupName, newGroup );
		m_groupName = newGroup;
	}
}

bool YahooContact::isOnline() const
{
	//kdDebug(14180) << k_funcinfo << endl;
	return onlineStatus().status() != KopeteOnlineStatus::Offline && onlineStatus().status() != KopeteOnlineStatus::Unknown;
}

bool YahooContact::isReachable()
{
	//kdDebug(14180) << k_funcinfo << endl;
	if ( m_account->isConnected() )
		return true;
	else
		return false;
}

KopeteMessageManager *YahooContact::manager( bool )
{
	if( !m_manager )
	{
		KopeteContactPtrList m_them;
		m_them.append( this );
		m_manager = KopeteMessageManagerFactory::factory()->create( m_account->myself(), m_them, protocol() );
		connect( m_manager, SIGNAL( destroyed() ), this, SLOT( slotMessageManagerDestroyed() ) );
		connect( m_manager, SIGNAL( messageSent ( KopeteMessage&, KopeteMessageManager* ) ), this, SLOT( slotSendMessage( KopeteMessage& ) ) );
		connect( m_manager, SIGNAL( typingMsg( bool) ), this, SLOT( slotTyping( bool ) ) );
		connect( m_account, SIGNAL( receivedTypingMsg( const QString &, bool ) ), m_manager, SLOT( receivedTypingMsg( const QString&, bool ) ) );
	}

	return m_manager;
}

void YahooContact::slotSendMessage( KopeteMessage &message )
{
	kdDebug(14180) << k_funcinfo << endl;

	// Yahoo does not understand XML/HTML message data, so send plain text
	// instead.  (Yahoo has its own format for "rich text".)
	QString messageText = message.plainBody();
	kdDebug(14180) << "Sending message: " << messageText << endl;

	KopeteContactPtrList m_them = manager()->members();
	KopeteContact *target = m_them.first();

	m_account->yahooSession()->sendIm( static_cast<YahooContact*>(m_account->myself())->m_userId,
		static_cast<YahooContact *>(target)->m_userId, messageText );

	// append message to window
	manager()->appendMessage(message);
	manager()->messageSucceeded();
}

void YahooContact::slotTyping(bool isTyping_ )
{
	KopeteContactPtrList m_them = manager()->members();
	KopeteContact *target = m_them.first();

	m_account->yahooSession()->sendTyping( static_cast<YahooContact*>(m_account->myself())->m_userId,
		static_cast<YahooContact*>(target)->m_userId, isTyping_ );
}

void YahooContact::slotMessageManagerDestroyed()
{
	m_manager = 0L;
}

QPtrList<KAction> *YahooContact::customContextMenuActions()
{
	//kdDebug(14180) << k_funcinfo << endl;
	return 0L;
}

void YahooContact::slotUserInfo()
{
	//kdDebug(14180) << k_funcinfo << endl;

	QString profileSiteString = "http://profiles.yahoo.com/" + m_userId;
	//kdDebug(14180) << "Yahoo profile site string: " << profileSiteString << endl;
	kapp->invokeBrowser(profileSiteString);
}

void YahooContact::slotSendFile()
{
	kdDebug(14180) << k_funcinfo << endl;
}

void YahooContact::slotDeleteContact()
{
	kdDebug(14180) << k_funcinfo << endl;
	//my ugliest hack yet. how many levels of indirection do I want? ;)
	if ( m_account->isConnected() )
		m_account->yahooSession()->removeBuddy(m_userId, m_groupName);

	KopeteContact::slotDeleteContact();
}
#include "yahoocontact.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>Use KRun::runURL instead of KApplication::invokeBrowser so that the KDE settings for the default browser get used.<commit_after>/*
    yahoocontact.cpp - Yahoo Contact

    Copyright (c) 2003-2004 by Matt Rogers <matt.rogers@kdemail.net>
    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Portions based on code by Bruno Rodrigues <bruno.rodrigues@litux.org>

    Copyright (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/
#include "kopetegroup.h"
#include "kopetemessagemanager.h"
#include "kopeteonlinestatus.h"
#include "kopetemetacontact.h"
#include "kopetemessagemanagerfactory.h"
#include "kopetemetacontact.h"

// Local Includes
#include "yahoocontact.h"
#include "yahooaccount.h"

// QT Includes
#include <qregexp.h>

// KDE Includes
#include <kdebug.h>
#include <kapplication.h>
#include <krun.h>
#include <kmessagebox.h>

YahooContact::YahooContact( YahooAccount *account, const QString &userId, const QString &fullName, KopeteMetaContact *metaContact )
	: KopeteContact( account, userId, metaContact )
{
	kdDebug(14180) << k_funcinfo << endl;

	m_userId = userId;
	if ( metaContact )
		m_groupName = metaContact->groups().getFirst()->displayName();
	m_manager = 0L;
	m_account = account;

	// Update ContactList
	setDisplayName( fullName );
	setOnlineStatus( static_cast<YahooProtocol*>( m_account->protocol() )->Offline );

	if ( m_account->haveContactList() )
		syncToServer();
}

YahooContact::~YahooContact()
{
}

void YahooContact::serialize(QMap<QString, QString> &serializedData, QMap<QString, QString> &addressBookData)
{
	//kdDebug(14180) << k_funcinfo << endl;

	KopeteContact::serialize(serializedData, addressBookData);
}

void YahooContact::syncToServer()
{
	kdDebug(14180) << k_funcinfo  << endl;
	if(!m_account->isConnected()) return;

	if ( !m_account->isOnServer(m_userId) && !metaContact()->isTemporary() )
	{	kdDebug(14180) << "Contact " << m_userId << " doesn't exist on server-side. Adding..." << endl;

		KopeteGroupList groupList = metaContact()->groups();
		for( KopeteGroup *g = groupList.first(); g; g = groupList.next() )
			m_account->yahooSession()->addBuddy(m_userId, g->displayName() );
	}
}

void YahooContact::syncGroups()
{
	if ( !m_account->isConnected() )
		return;

	if ( !m_account->isOnServer( contactId() ) )
	{
		//TODO: Share this code with the above function
		kdDebug(14180) << k_funcinfo << "Contact isn't on the server. Adding..." << endl;
		KopeteGroupList groupList = metaContact()->groups();
		for ( KopeteGroup *g = groupList.first(); g; g = groupList.next() )
			m_account->yahooSession()->addBuddy(m_userId, g->displayName() );
	}
	else
	{
		QString newGroup = metaContact()->groups().first()->displayName();
		m_account->yahooSession()->changeBuddyGroup( contactId(), m_groupName, newGroup );
		m_groupName = newGroup;
	}
}

bool YahooContact::isOnline() const
{
	//kdDebug(14180) << k_funcinfo << endl;
	return onlineStatus().status() != KopeteOnlineStatus::Offline && onlineStatus().status() != KopeteOnlineStatus::Unknown;
}

bool YahooContact::isReachable()
{
	//kdDebug(14180) << k_funcinfo << endl;
	if ( m_account->isConnected() )
		return true;
	else
		return false;
}

KopeteMessageManager *YahooContact::manager( bool )
{
	if( !m_manager )
	{
		KopeteContactPtrList m_them;
		m_them.append( this );
		m_manager = KopeteMessageManagerFactory::factory()->create( m_account->myself(), m_them, protocol() );
		connect( m_manager, SIGNAL( destroyed() ), this, SLOT( slotMessageManagerDestroyed() ) );
		connect( m_manager, SIGNAL( messageSent ( KopeteMessage&, KopeteMessageManager* ) ), this, SLOT( slotSendMessage( KopeteMessage& ) ) );
		connect( m_manager, SIGNAL( typingMsg( bool) ), this, SLOT( slotTyping( bool ) ) );
		connect( m_account, SIGNAL( receivedTypingMsg( const QString &, bool ) ), m_manager, SLOT( receivedTypingMsg( const QString&, bool ) ) );
	}

	return m_manager;
}

void YahooContact::slotSendMessage( KopeteMessage &message )
{
	kdDebug(14180) << k_funcinfo << endl;

	// Yahoo does not understand XML/HTML message data, so send plain text
	// instead.  (Yahoo has its own format for "rich text".)
	QString messageText = message.plainBody();
	kdDebug(14180) << "Sending message: " << messageText << endl;

	KopeteContactPtrList m_them = manager()->members();
	KopeteContact *target = m_them.first();

	m_account->yahooSession()->sendIm( static_cast<YahooContact*>(m_account->myself())->m_userId,
		static_cast<YahooContact *>(target)->m_userId, messageText );

	// append message to window
	manager()->appendMessage(message);
	manager()->messageSucceeded();
}

void YahooContact::slotTyping(bool isTyping_ )
{
	KopeteContactPtrList m_them = manager()->members();
	KopeteContact *target = m_them.first();

	m_account->yahooSession()->sendTyping( static_cast<YahooContact*>(m_account->myself())->m_userId,
		static_cast<YahooContact*>(target)->m_userId, isTyping_ );
}

void YahooContact::slotMessageManagerDestroyed()
{
	m_manager = 0L;
}

QPtrList<KAction> *YahooContact::customContextMenuActions()
{
	//kdDebug(14180) << k_funcinfo << endl;
	return 0L;
}

void YahooContact::slotUserInfo()
{
	//kdDebug(14180) << k_funcinfo << endl;

	QString profileSiteString = QString::fromLatin1("http://profiles.yahoo.com/") + m_userId;
	KRun::runURL( KURL( profileSiteString ) , "text/html" );
}

void YahooContact::slotSendFile()
{
	kdDebug(14180) << k_funcinfo << endl;
}

void YahooContact::slotDeleteContact()
{
	kdDebug(14180) << k_funcinfo << endl;
	//my ugliest hack yet. how many levels of indirection do I want? ;)
	if ( m_account->isConnected() )
		m_account->yahooSession()->removeBuddy(m_userId, m_groupName);

	KopeteContact::slotDeleteContact();
}
#include "yahoocontact.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ServiceMacros.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: bm $ $Date: 2003-10-06 09:58:29 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _APPHELPER_SERVICEMACROS_HXX
#define _APPHELPER_SERVICEMACROS_HXX

/*
to use these macros the supported services and the implementation name needs to be static
especially you need to implement (declaration is contained in macro already):

static com::sun::star::uno::Sequence< rtl::OUString >
    Class::getSupportedServiceNames_Static();
*/

//=========================================================================
//
// XServiceInfo decl
//
//=========================================================================
namespace apphelper
{

#define APPHELPER_XSERVICEINFO_DECL()                                                   \
    virtual ::rtl::OUString SAL_CALL                                        \
        getImplementationName()                                             \
            throw( ::com::sun::star::uno::RuntimeException );               \
    virtual sal_Bool SAL_CALL                                               \
        supportsService( const ::rtl::OUString& ServiceName )               \
            throw( ::com::sun::star::uno::RuntimeException );               \
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL     \
        getSupportedServiceNames()                                          \
            throw( ::com::sun::star::uno::RuntimeException );               \
                                                                            \
    static ::rtl::OUString getImplementationName_Static();                  \
    static ::com::sun::star::uno::Sequence< ::rtl::OUString >               \
        getSupportedServiceNames_Static();

//=========================================================================
//
// XServiceInfo impl
//
//=========================================================================

#define APPHELPER_XSERVICEINFO_IMPL( Class, ImplName )                              \
::rtl::OUString SAL_CALL Class::getImplementationName()                     \
    throw( ::com::sun::star::uno::RuntimeException )                        \
{                                                                           \
    return getImplementationName_Static();                                  \
}                                                                           \
                                                                            \
::rtl::OUString Class::getImplementationName_Static()                       \
{                                                                           \
    return ImplName;                                                        \
}                                                                           \
                                                                            \
sal_Bool SAL_CALL                                                           \
Class::supportsService( const ::rtl::OUString& ServiceName )                \
    throw( ::com::sun::star::uno::RuntimeException )                        \
{                                                                           \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSNL =               \
                                        getSupportedServiceNames();         \
    const ::rtl::OUString* pArray = aSNL.getArray();                        \
    for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )                       \
    {                                                                       \
        if( pArray[ i ] == ServiceName )                                    \
            return sal_True;                                                \
    }                                                                       \
                                                                            \
    return sal_False;                                                       \
}                                                                           \
                                                                            \
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL                 \
Class::getSupportedServiceNames()                                           \
    throw( ::com::sun::star::uno::RuntimeException )                        \
{                                                                           \
    return getSupportedServiceNames_Static();                               \
}

//=========================================================================
//
// Service factory helper decl+impl
//
//to use this macro you need to provide a constructor:
//class( Reference< XComponentContext > const & xContext )
//and implement OWeakObject
//=========================================================================

#define APPHELPER_SERVICE_FACTORY_HELPER(Class)                                     \
static ::com::sun::star::uno::Reference<                                    \
                            ::com::sun::star::uno::XInterface > SAL_CALL    \
    create( ::com::sun::star::uno::Reference<                               \
               ::com::sun::star::uno::XComponentContext > const & xContext) \
    throw(::com::sun::star::uno::Exception)                                 \
{                                                                           \
    return (::cppu::OWeakObject *)new Class( xContext );                    \
}

/** This macro contains the default implementation for getImplementationId().
    Note, that you have to include the header necessary for rtl_createUuid.
    Insert the following into your file:

#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif

    @param Class the Class-Name for which getImplementationId() should be
    implemented
 */
#define APPHELPER_GETIMPLEMENTATIONID_IMPL(Class) \
::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL Class::getImplementationId() \
    throw (::com::sun::star::uno::RuntimeException) \
{ \
    static ::com::sun::star::uno::Sequence< sal_Int8 > aId; \
    if( aId.getLength() == 0 ) \
    { \
        aId.realloc( 16 ); \
        rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True ); \
    } \
    return aId; \
}

}//end namespace apphelper
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.110); FILE MERGED 2005/09/05 18:42:54 rt 1.1.1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ServiceMacros.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:46:28 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _APPHELPER_SERVICEMACROS_HXX
#define _APPHELPER_SERVICEMACROS_HXX

/*
to use these macros the supported services and the implementation name needs to be static
especially you need to implement (declaration is contained in macro already):

static com::sun::star::uno::Sequence< rtl::OUString >
    Class::getSupportedServiceNames_Static();
*/

//=========================================================================
//
// XServiceInfo decl
//
//=========================================================================
namespace apphelper
{

#define APPHELPER_XSERVICEINFO_DECL()                                                   \
    virtual ::rtl::OUString SAL_CALL                                        \
        getImplementationName()                                             \
            throw( ::com::sun::star::uno::RuntimeException );               \
    virtual sal_Bool SAL_CALL                                               \
        supportsService( const ::rtl::OUString& ServiceName )               \
            throw( ::com::sun::star::uno::RuntimeException );               \
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL     \
        getSupportedServiceNames()                                          \
            throw( ::com::sun::star::uno::RuntimeException );               \
                                                                            \
    static ::rtl::OUString getImplementationName_Static();                  \
    static ::com::sun::star::uno::Sequence< ::rtl::OUString >               \
        getSupportedServiceNames_Static();

//=========================================================================
//
// XServiceInfo impl
//
//=========================================================================

#define APPHELPER_XSERVICEINFO_IMPL( Class, ImplName )                              \
::rtl::OUString SAL_CALL Class::getImplementationName()                     \
    throw( ::com::sun::star::uno::RuntimeException )                        \
{                                                                           \
    return getImplementationName_Static();                                  \
}                                                                           \
                                                                            \
::rtl::OUString Class::getImplementationName_Static()                       \
{                                                                           \
    return ImplName;                                                        \
}                                                                           \
                                                                            \
sal_Bool SAL_CALL                                                           \
Class::supportsService( const ::rtl::OUString& ServiceName )                \
    throw( ::com::sun::star::uno::RuntimeException )                        \
{                                                                           \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSNL =               \
                                        getSupportedServiceNames();         \
    const ::rtl::OUString* pArray = aSNL.getArray();                        \
    for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )                       \
    {                                                                       \
        if( pArray[ i ] == ServiceName )                                    \
            return sal_True;                                                \
    }                                                                       \
                                                                            \
    return sal_False;                                                       \
}                                                                           \
                                                                            \
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL                 \
Class::getSupportedServiceNames()                                           \
    throw( ::com::sun::star::uno::RuntimeException )                        \
{                                                                           \
    return getSupportedServiceNames_Static();                               \
}

//=========================================================================
//
// Service factory helper decl+impl
//
//to use this macro you need to provide a constructor:
//class( Reference< XComponentContext > const & xContext )
//and implement OWeakObject
//=========================================================================

#define APPHELPER_SERVICE_FACTORY_HELPER(Class)                                     \
static ::com::sun::star::uno::Reference<                                    \
                            ::com::sun::star::uno::XInterface > SAL_CALL    \
    create( ::com::sun::star::uno::Reference<                               \
               ::com::sun::star::uno::XComponentContext > const & xContext) \
    throw(::com::sun::star::uno::Exception)                                 \
{                                                                           \
    return (::cppu::OWeakObject *)new Class( xContext );                    \
}

/** This macro contains the default implementation for getImplementationId().
    Note, that you have to include the header necessary for rtl_createUuid.
    Insert the following into your file:

#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif

    @param Class the Class-Name for which getImplementationId() should be
    implemented
 */
#define APPHELPER_GETIMPLEMENTATIONID_IMPL(Class) \
::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL Class::getImplementationId() \
    throw (::com::sun::star::uno::RuntimeException) \
{ \
    static ::com::sun::star::uno::Sequence< sal_Int8 > aId; \
    if( aId.getLength() == 0 ) \
    { \
        aId.realloc( 16 ); \
        rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True ); \
    } \
    return aId; \
}

}//end namespace apphelper
#endif
<|endoftext|>