<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/renderer_host/safe_browsing_resource_handler.h"

#include "base/logging.h"
#include "chrome/browser/renderer_host/global_request_id.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/common/resource_response.h"
#include "net/base/net_errors.h"
#include "net/base/io_buffer.h"

// Maximum time in milliseconds to wait for the safe browsing service to
// verify a URL. After this amount of time the outstanding check will be
// aborted, and the URL will be treated as if it were safe.
static const int kCheckUrlTimeoutMs = 5000;

// TODO(eroman): Downgrade these CHECK()s to DCHECKs once there is more
//               unit test coverage.

SafeBrowsingResourceHandler::SafeBrowsingResourceHandler(
    ResourceHandler* handler,
    int render_process_host_id,
    int render_view_id,
    ResourceType::Type resource_type,
    SafeBrowsingService* safe_browsing,
    ResourceDispatcherHost* resource_dispatcher_host)
    : state_(STATE_NONE),
      defer_state_(DEFERRED_NONE),
      deferred_request_id_(-1),
      next_handler_(handler),
      render_process_host_id_(render_process_host_id),
      render_view_id_(render_view_id),
      safe_browsing_(safe_browsing),
      rdh_(resource_dispatcher_host),
      resource_type_(resource_type) {
}

SafeBrowsingResourceHandler::~SafeBrowsingResourceHandler() {
}

bool SafeBrowsingResourceHandler::OnUploadProgress(int request_id,
                                                   uint64 position,
                                                   uint64 size) {
  return next_handler_->OnUploadProgress(request_id, position, size);
}

bool SafeBrowsingResourceHandler::OnRequestRedirected(
    int request_id,
    const GURL& new_url,
    ResourceResponse* response,
    bool* defer) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);

  // Save the redirect urls for possible malware detail reporting later.
  redirect_urls_.push_back(new_url);

  // We need to check the new URL before following the redirect.
  if (CheckUrl(new_url)) {
    return next_handler_->OnRequestRedirected(
        request_id, new_url, response, defer);
  }

  // If the URL couldn't be verified synchronously, defer following the
  // redirect until the SafeBrowsing check is complete. Store the redirect
  // context so we can pass it on to other handlers once we have completed
  // our check.
  defer_state_ = DEFERRED_REDIRECT;
  deferred_request_id_ = request_id;
  deferred_url_ = new_url;
  deferred_redirect_response_ = response;
  *defer = true;

  return true;
}

bool SafeBrowsingResourceHandler::OnResponseStarted(
    int request_id, ResourceResponse* response) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);
  return next_handler_->OnResponseStarted(request_id, response);
}

void SafeBrowsingResourceHandler::OnCheckUrlTimeout() {
  CHECK(state_ == STATE_CHECKING_URL);
  CHECK(defer_state_ != DEFERRED_NONE);
  safe_browsing_->CancelCheck(this);
  OnBrowseUrlCheckResult(deferred_url_, SafeBrowsingService::URL_SAFE);
}

bool SafeBrowsingResourceHandler::OnWillStart(int request_id,
                                              const GURL& url,
                                              bool* defer) {
  // We need to check the new URL before starting the request.
  if (CheckUrl(url))
    return next_handler_->OnWillStart(request_id, url, defer);

  // If the URL couldn't be verified synchronously, defer starting the
  // request until the check has completed.
  defer_state_ = DEFERRED_START;
  deferred_request_id_ = request_id;
  deferred_url_ = url;
  *defer = true;

  return true;
}

bool SafeBrowsingResourceHandler::OnWillRead(int request_id,
                                             net::IOBuffer** buf, int* buf_size,
                                             int min_size) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);
  return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}

bool SafeBrowsingResourceHandler::OnReadCompleted(int request_id,
                                                  int* bytes_read) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);
  return next_handler_->OnReadCompleted(request_id, bytes_read);
}

bool SafeBrowsingResourceHandler::OnResponseCompleted(
    int request_id, const net::URLRequestStatus& status,
    const std::string& security_info) {
  Shutdown();
  return next_handler_->OnResponseCompleted(request_id, status, security_info);
}

void SafeBrowsingResourceHandler::OnRequestClosed() {
  Shutdown();
  next_handler_->OnRequestClosed();
}

// SafeBrowsingService::Client implementation, called on the IO thread once
// the URL has been classified.
void SafeBrowsingResourceHandler::OnBrowseUrlCheckResult(
    const GURL& url, SafeBrowsingService::UrlCheckResult result) {
  CHECK(state_ == STATE_CHECKING_URL);
  CHECK(defer_state_ != DEFERRED_NONE);
  CHECK(url == deferred_url_) << "Was expecting: " << deferred_url_
                              << " but got: " << url;

  timer_.Stop();  // Cancel the timeout timer.
  safe_browsing_result_ = result;
  state_ = STATE_NONE;

  if (result == SafeBrowsingService::URL_SAFE) {
    // Log how much time the safe browsing check cost us.
    base::TimeDelta pause_delta;
    pause_delta = base::TimeTicks::Now() - url_check_start_time_;
    safe_browsing_->LogPauseDelay(pause_delta);

    // Continue the request.
    ResumeRequest();
  } else {
    StartDisplayingBlockingPage(url, result);
  }

  Release();  // Balances the AddRef() in CheckingUrl().
}

void SafeBrowsingResourceHandler::StartDisplayingBlockingPage(
    const GURL& url,
    SafeBrowsingService::UrlCheckResult result) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ != DEFERRED_NONE);
  CHECK(deferred_request_id_ != -1);

  state_ = STATE_DISPLAYING_BLOCKING_PAGE;
  AddRef();  // Balanced in OnBlockingPageComplete().

  // Grab the original url of this request as well.
  GURL original_url;
  net::URLRequest* request = rdh_->GetURLRequest(
      GlobalRequestID(render_process_host_id_, deferred_request_id_));
  if (request)
    original_url = request->original_url();
  else
    original_url = url;

  safe_browsing_->DisplayBlockingPage(
      url, original_url, redirect_urls_, resource_type_,
      result, this, render_process_host_id_, render_view_id_);
}

// SafeBrowsingService::Client implementation, called on the IO thread when
// the user has decided to proceed with the current request, or go back.
void SafeBrowsingResourceHandler::OnBlockingPageComplete(bool proceed) {
  CHECK(state_ == STATE_DISPLAYING_BLOCKING_PAGE);
  state_ = STATE_NONE;

  if (proceed) {
    safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
    ResumeRequest();
  } else {
    rdh_->CancelRequest(render_process_host_id_, deferred_request_id_, false);
  }

  Release();  // Balances the AddRef() in StartDisplayingBlockingPage().
}

void SafeBrowsingResourceHandler::Shutdown() {
  if (state_ == STATE_CHECKING_URL) {
    timer_.Stop();
    safe_browsing_->CancelCheck(this);
    state_ = STATE_NONE;
    // Balance the AddRef() from CheckUrl() which would ordinarily be
    // balanced by OnUrlCheckResult().
    Release();
  }
}

bool SafeBrowsingResourceHandler::CheckUrl(const GURL& url) {
  CHECK(state_ == STATE_NONE);
  bool succeeded_synchronously = safe_browsing_->CheckBrowseUrl(url, this);
  if (succeeded_synchronously) {
    safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
    safe_browsing_->LogPauseDelay(base::TimeDelta());  // No delay.
    return true;
  }

  AddRef();  // Balanced in OnUrlCheckResult().
  state_ = STATE_CHECKING_URL;

  // Record the start time of the check.
  url_check_start_time_ = base::TimeTicks::Now();

  // Start a timer to abort the check if it takes too long.
  timer_.Start(base::TimeDelta::FromMilliseconds(kCheckUrlTimeoutMs),
               this, &SafeBrowsingResourceHandler::OnCheckUrlTimeout);

  return false;
}

void SafeBrowsingResourceHandler::ResumeRequest() {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ != DEFERRED_NONE);

  // Resume whatever stage got paused by the safe browsing check.
  switch (defer_state_) {
    case DEFERRED_START:
      ResumeStart();
      break;
    case DEFERRED_REDIRECT:
      ResumeRedirect();
      break;
    case DEFERRED_NONE:
      NOTREACHED();
      break;
  }
}

void SafeBrowsingResourceHandler::ResumeStart() {
  CHECK(defer_state_ == DEFERRED_START);
  CHECK(deferred_request_id_ != -1);
  defer_state_ = DEFERRED_NONE;

  // Retrieve the details for the paused OnWillStart().
  int request_id = deferred_request_id_;
  GURL url = deferred_url_;

  ClearDeferredRequestInfo();

  // Give the other resource handlers a chance to defer starting.
  bool defer = false;
  // TODO(eroman): the return value is being lost here. Should
  // use it to cancel the request.
  next_handler_->OnWillStart(request_id, url, &defer);
  if (!defer)
    rdh_->StartDeferredRequest(render_process_host_id_, request_id);
}

void SafeBrowsingResourceHandler::ResumeRedirect() {
  CHECK(defer_state_ == DEFERRED_REDIRECT);
  defer_state_ = DEFERRED_NONE;

  // Retrieve the details for the paused OnReceivedRedirect().
  int request_id = deferred_request_id_;
  GURL redirect_url = deferred_url_;
  scoped_refptr<ResourceResponse> redirect_response =
      deferred_redirect_response_;

  ClearDeferredRequestInfo();

  // Give the other resource handlers a chance to handle the redirect.
  bool defer = false;
  // TODO(eroman): the return value is being lost here. Should
  // use it to cancel the request.
  next_handler_->OnRequestRedirected(request_id, redirect_url,
                                     redirect_response, &defer);
  if (!defer) {
    rdh_->FollowDeferredRedirect(render_process_host_id_, request_id,
                                 false, GURL());
  }
}

void SafeBrowsingResourceHandler::ClearDeferredRequestInfo() {
  deferred_request_id_ = -1;
  deferred_url_ = GURL();
  deferred_redirect_response_ = NULL;
}
<commit_msg>Initialize SafeBrowsingResourceHandler member.<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/renderer_host/safe_browsing_resource_handler.h"

#include "base/logging.h"
#include "chrome/browser/renderer_host/global_request_id.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/common/resource_response.h"
#include "net/base/net_errors.h"
#include "net/base/io_buffer.h"

// Maximum time in milliseconds to wait for the safe browsing service to
// verify a URL. After this amount of time the outstanding check will be
// aborted, and the URL will be treated as if it were safe.
static const int kCheckUrlTimeoutMs = 5000;

// TODO(eroman): Downgrade these CHECK()s to DCHECKs once there is more
//               unit test coverage.

SafeBrowsingResourceHandler::SafeBrowsingResourceHandler(
    ResourceHandler* handler,
    int render_process_host_id,
    int render_view_id,
    ResourceType::Type resource_type,
    SafeBrowsingService* safe_browsing,
    ResourceDispatcherHost* resource_dispatcher_host)
    : state_(STATE_NONE),
      defer_state_(DEFERRED_NONE),
      safe_browsing_result_(SafeBrowsingService::URL_SAFE),
      deferred_request_id_(-1),
      next_handler_(handler),
      render_process_host_id_(render_process_host_id),
      render_view_id_(render_view_id),
      safe_browsing_(safe_browsing),
      rdh_(resource_dispatcher_host),
      resource_type_(resource_type) {
}

SafeBrowsingResourceHandler::~SafeBrowsingResourceHandler() {
}

bool SafeBrowsingResourceHandler::OnUploadProgress(int request_id,
                                                   uint64 position,
                                                   uint64 size) {
  return next_handler_->OnUploadProgress(request_id, position, size);
}

bool SafeBrowsingResourceHandler::OnRequestRedirected(
    int request_id,
    const GURL& new_url,
    ResourceResponse* response,
    bool* defer) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);

  // Save the redirect urls for possible malware detail reporting later.
  redirect_urls_.push_back(new_url);

  // We need to check the new URL before following the redirect.
  if (CheckUrl(new_url)) {
    return next_handler_->OnRequestRedirected(
        request_id, new_url, response, defer);
  }

  // If the URL couldn't be verified synchronously, defer following the
  // redirect until the SafeBrowsing check is complete. Store the redirect
  // context so we can pass it on to other handlers once we have completed
  // our check.
  defer_state_ = DEFERRED_REDIRECT;
  deferred_request_id_ = request_id;
  deferred_url_ = new_url;
  deferred_redirect_response_ = response;
  *defer = true;

  return true;
}

bool SafeBrowsingResourceHandler::OnResponseStarted(
    int request_id, ResourceResponse* response) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);
  return next_handler_->OnResponseStarted(request_id, response);
}

void SafeBrowsingResourceHandler::OnCheckUrlTimeout() {
  CHECK(state_ == STATE_CHECKING_URL);
  CHECK(defer_state_ != DEFERRED_NONE);
  safe_browsing_->CancelCheck(this);
  OnBrowseUrlCheckResult(deferred_url_, SafeBrowsingService::URL_SAFE);
}

bool SafeBrowsingResourceHandler::OnWillStart(int request_id,
                                              const GURL& url,
                                              bool* defer) {
  // We need to check the new URL before starting the request.
  if (CheckUrl(url))
    return next_handler_->OnWillStart(request_id, url, defer);

  // If the URL couldn't be verified synchronously, defer starting the
  // request until the check has completed.
  defer_state_ = DEFERRED_START;
  deferred_request_id_ = request_id;
  deferred_url_ = url;
  *defer = true;

  return true;
}

bool SafeBrowsingResourceHandler::OnWillRead(int request_id,
                                             net::IOBuffer** buf, int* buf_size,
                                             int min_size) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);
  return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}

bool SafeBrowsingResourceHandler::OnReadCompleted(int request_id,
                                                  int* bytes_read) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ == DEFERRED_NONE);
  return next_handler_->OnReadCompleted(request_id, bytes_read);
}

bool SafeBrowsingResourceHandler::OnResponseCompleted(
    int request_id, const net::URLRequestStatus& status,
    const std::string& security_info) {
  Shutdown();
  return next_handler_->OnResponseCompleted(request_id, status, security_info);
}

void SafeBrowsingResourceHandler::OnRequestClosed() {
  Shutdown();
  next_handler_->OnRequestClosed();
}

// SafeBrowsingService::Client implementation, called on the IO thread once
// the URL has been classified.
void SafeBrowsingResourceHandler::OnBrowseUrlCheckResult(
    const GURL& url, SafeBrowsingService::UrlCheckResult result) {
  CHECK(state_ == STATE_CHECKING_URL);
  CHECK(defer_state_ != DEFERRED_NONE);
  CHECK(url == deferred_url_) << "Was expecting: " << deferred_url_
                              << " but got: " << url;

  timer_.Stop();  // Cancel the timeout timer.
  safe_browsing_result_ = result;
  state_ = STATE_NONE;

  if (result == SafeBrowsingService::URL_SAFE) {
    // Log how much time the safe browsing check cost us.
    base::TimeDelta pause_delta;
    pause_delta = base::TimeTicks::Now() - url_check_start_time_;
    safe_browsing_->LogPauseDelay(pause_delta);

    // Continue the request.
    ResumeRequest();
  } else {
    StartDisplayingBlockingPage(url, result);
  }

  Release();  // Balances the AddRef() in CheckingUrl().
}

void SafeBrowsingResourceHandler::StartDisplayingBlockingPage(
    const GURL& url,
    SafeBrowsingService::UrlCheckResult result) {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ != DEFERRED_NONE);
  CHECK(deferred_request_id_ != -1);

  state_ = STATE_DISPLAYING_BLOCKING_PAGE;
  AddRef();  // Balanced in OnBlockingPageComplete().

  // Grab the original url of this request as well.
  GURL original_url;
  net::URLRequest* request = rdh_->GetURLRequest(
      GlobalRequestID(render_process_host_id_, deferred_request_id_));
  if (request)
    original_url = request->original_url();
  else
    original_url = url;

  safe_browsing_->DisplayBlockingPage(
      url, original_url, redirect_urls_, resource_type_,
      result, this, render_process_host_id_, render_view_id_);
}

// SafeBrowsingService::Client implementation, called on the IO thread when
// the user has decided to proceed with the current request, or go back.
void SafeBrowsingResourceHandler::OnBlockingPageComplete(bool proceed) {
  CHECK(state_ == STATE_DISPLAYING_BLOCKING_PAGE);
  state_ = STATE_NONE;

  if (proceed) {
    safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
    ResumeRequest();
  } else {
    rdh_->CancelRequest(render_process_host_id_, deferred_request_id_, false);
  }

  Release();  // Balances the AddRef() in StartDisplayingBlockingPage().
}

void SafeBrowsingResourceHandler::Shutdown() {
  if (state_ == STATE_CHECKING_URL) {
    timer_.Stop();
    safe_browsing_->CancelCheck(this);
    state_ = STATE_NONE;
    // Balance the AddRef() from CheckUrl() which would ordinarily be
    // balanced by OnUrlCheckResult().
    Release();
  }
}

bool SafeBrowsingResourceHandler::CheckUrl(const GURL& url) {
  CHECK(state_ == STATE_NONE);
  bool succeeded_synchronously = safe_browsing_->CheckBrowseUrl(url, this);
  if (succeeded_synchronously) {
    safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
    safe_browsing_->LogPauseDelay(base::TimeDelta());  // No delay.
    return true;
  }

  AddRef();  // Balanced in OnUrlCheckResult().
  state_ = STATE_CHECKING_URL;

  // Record the start time of the check.
  url_check_start_time_ = base::TimeTicks::Now();

  // Start a timer to abort the check if it takes too long.
  timer_.Start(base::TimeDelta::FromMilliseconds(kCheckUrlTimeoutMs),
               this, &SafeBrowsingResourceHandler::OnCheckUrlTimeout);

  return false;
}

void SafeBrowsingResourceHandler::ResumeRequest() {
  CHECK(state_ == STATE_NONE);
  CHECK(defer_state_ != DEFERRED_NONE);

  // Resume whatever stage got paused by the safe browsing check.
  switch (defer_state_) {
    case DEFERRED_START:
      ResumeStart();
      break;
    case DEFERRED_REDIRECT:
      ResumeRedirect();
      break;
    case DEFERRED_NONE:
      NOTREACHED();
      break;
  }
}

void SafeBrowsingResourceHandler::ResumeStart() {
  CHECK(defer_state_ == DEFERRED_START);
  CHECK(deferred_request_id_ != -1);
  defer_state_ = DEFERRED_NONE;

  // Retrieve the details for the paused OnWillStart().
  int request_id = deferred_request_id_;
  GURL url = deferred_url_;

  ClearDeferredRequestInfo();

  // Give the other resource handlers a chance to defer starting.
  bool defer = false;
  // TODO(eroman): the return value is being lost here. Should
  // use it to cancel the request.
  next_handler_->OnWillStart(request_id, url, &defer);
  if (!defer)
    rdh_->StartDeferredRequest(render_process_host_id_, request_id);
}

void SafeBrowsingResourceHandler::ResumeRedirect() {
  CHECK(defer_state_ == DEFERRED_REDIRECT);
  defer_state_ = DEFERRED_NONE;

  // Retrieve the details for the paused OnReceivedRedirect().
  int request_id = deferred_request_id_;
  GURL redirect_url = deferred_url_;
  scoped_refptr<ResourceResponse> redirect_response =
      deferred_redirect_response_;

  ClearDeferredRequestInfo();

  // Give the other resource handlers a chance to handle the redirect.
  bool defer = false;
  // TODO(eroman): the return value is being lost here. Should
  // use it to cancel the request.
  next_handler_->OnRequestRedirected(request_id, redirect_url,
                                     redirect_response, &defer);
  if (!defer) {
    rdh_->FollowDeferredRedirect(render_process_host_id_, request_id,
                                 false, GURL());
  }
}

void SafeBrowsingResourceHandler::ClearDeferredRequestInfo() {
  deferred_request_id_ = -1;
  deferred_url_ = GURL();
  deferred_redirect_response_ = NULL;
}
<|endoftext|>


<commit_before><commit_msg>Fix validation layer warning on window minimized<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ContainerMediator.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 15:16:22 $
 *
 *  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 DBA_CONTAINERMEDIATOR_HXX
#include "ContainerMediator.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//........................................................................
namespace dbaccess
{
//........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
DBG_NAME(OContainerMediator)
OContainerMediator::OContainerMediator( const Reference< XContainer >& _xContainer
                                       ,const Reference< XNameAccess >& _xSettings
                                       ,sal_Bool _bTables)
    : m_xSettings(_xSettings)
    , m_xContainer(_xContainer)
    , m_bTables(_bTables)
{
    DBG_CTOR(OContainerMediator,NULL);
    osl_incrementInterlockedCount(&m_refCount);
    try
    {
        m_xContainer->addContainerListener(this);
        Reference< XContainer > xContainer(m_xSettings, UNO_QUERY);
        if ( xContainer.is() )
            xContainer->addContainerListener(this);
    }
    catch(Exception&)
    {
        OSL_ENSURE(sal_False, "OContainerMediator::OContainerMediator: caught an exception!");
    }
    osl_decrementInterlockedCount( &m_refCount );
}
// -----------------------------------------------------------------------------
OContainerMediator::~OContainerMediator()
{
    DBG_DTOR(OContainerMediator,NULL);
    osl_incrementInterlockedCount(&m_refCount);
    try
    {
        if ( m_xContainer.is() )
            m_xContainer->removeContainerListener(this);
        Reference< XContainer > xContainer(m_xSettings, UNO_QUERY);
        if ( xContainer.is() )
            xContainer->removeContainerListener(this);
    }
    catch(Exception&)
    {
        OSL_ENSURE(sal_False, "OContainerMediator::~OContainerMediator: caught an exception!");
    }
    osl_decrementInterlockedCount( &m_refCount );
}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::elementInserted( const ContainerEvent& _rEvent ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    if ( _rEvent.Source == m_xSettings && m_xSettings.is() )
    {
        ::rtl::OUString sElementName;
        _rEvent.Accessor >>= sElementName;
        PropertyForwardList::iterator aFind = m_aForwardList.find(sElementName);
        if ( aFind != m_aForwardList.end() )
        {
            Reference< XPropertySet> xDest(_rEvent.Element,UNO_QUERY);
            aFind->second.first->setDefinition(xDest);
        }
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::elementRemoved( const ContainerEvent& _rEvent ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    if ( _rEvent.Source == m_xContainer && m_xSettings.is() )
    {
        ::rtl::OUString sElementName;
        _rEvent.Accessor >>= sElementName;
        m_aForwardList.erase(sElementName);
        Reference<XNameContainer> xNameContainer(m_xSettings,UNO_QUERY);
        if ( xNameContainer.is() && m_xSettings->hasByName(sElementName) )
            xNameContainer->removeByName(sElementName);
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::elementReplaced( const ContainerEvent& /*_rEvent*/ ) throw(RuntimeException)
{

}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::disposing( const EventObject& Source ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);

    if ( Source.Source == m_xContainer || Source.Source == m_xSettings )
    {
        Reference< XContainer > xContainer(m_xSettings, UNO_QUERY);
        if ( xContainer.is() )
        {
            xContainer->removeContainerListener(this);
        }
        m_xSettings = NULL;

        if ( m_xContainer.is() )
        {
            m_xContainer->removeContainerListener(this);
            m_xContainer = NULL;
        }
    }
}
// -----------------------------------------------------------------------------
void OContainerMediator::notifyElementCreated(const ::rtl::OUString& _sName,const Reference<XPropertySet>& _xDest)
{
    PropertyForwardList::iterator aFind = m_aForwardList.find(_sName);
    if ( aFind == m_aForwardList.end() && m_xSettings.is() )
    {
        if ( m_xSettings->hasByName(_sName) )
        {
            Reference<XPropertySet> xSetting(m_xSettings->getByName(_sName),UNO_QUERY);
            if ( xSetting.is() )
                ::comphelper::copyProperties(xSetting,_xDest);
        }

        ::std::vector< ::rtl::OUString> aPropertyList;
        if ( m_bTables )
        {
            aPropertyList.reserve(26);
            aPropertyList.push_back(PROPERTY_FILTER);
            aPropertyList.push_back(PROPERTY_ORDER);
            aPropertyList.push_back(PROPERTY_APPLYFILTER);
            aPropertyList.push_back(PROPERTY_FONT);
            aPropertyList.push_back(PROPERTY_ROW_HEIGHT);
            aPropertyList.push_back(PROPERTY_TEXTCOLOR);
            aPropertyList.push_back(PROPERTY_TEXTLINECOLOR);
            aPropertyList.push_back(PROPERTY_TEXTEMPHASIS);
            aPropertyList.push_back(PROPERTY_TEXTRELIEF);
            aPropertyList.push_back(PROPERTY_FONTNAME);
            aPropertyList.push_back(PROPERTY_FONTHEIGHT);
            aPropertyList.push_back(PROPERTY_FONTWIDTH);
            aPropertyList.push_back(PROPERTY_FONTSTYLENAME);
            aPropertyList.push_back(PROPERTY_FONTFAMILY);
            aPropertyList.push_back(PROPERTY_FONTCHARSET);
            aPropertyList.push_back(PROPERTY_FONTPITCH);
            aPropertyList.push_back(PROPERTY_FONTCHARWIDTH);
            aPropertyList.push_back(PROPERTY_FONTWEIGHT);
            aPropertyList.push_back(PROPERTY_FONTSLANT);
            aPropertyList.push_back(PROPERTY_FONTUNDERLINE);
            aPropertyList.push_back(PROPERTY_FONTSTRIKEOUT);
            aPropertyList.push_back(PROPERTY_FONTORIENTATION);
            aPropertyList.push_back(PROPERTY_FONTKERNING);
            aPropertyList.push_back(PROPERTY_FONTWORDLINEMODE);
            aPropertyList.push_back(PROPERTY_FONTTYPE);
        }
        else
        {
            aPropertyList.reserve(9);
            aPropertyList.push_back(PROPERTY_ALIGN);
            aPropertyList.push_back(PROPERTY_NUMBERFORMAT);
            aPropertyList.push_back(PROPERTY_RELATIVEPOSITION);
            aPropertyList.push_back(PROPERTY_WIDTH);
            aPropertyList.push_back(PROPERTY_HIDDEN);
            aPropertyList.push_back(PROPERTY_CONTROLMODEL);
            aPropertyList.push_back(PROPERTY_HELPTEXT);
            aPropertyList.push_back(PROPERTY_CONTROLDEFAULT);
        }

        OPropertyForward* pForward = new OPropertyForward(_xDest,m_xSettings,_sName,aPropertyList);
        Reference<XInterface> xTemp = *pForward;
        m_aForwardList.insert( PropertyForwardList::value_type(_sName,TPropertyForward(pForward,xTemp)));
    }
}
// -----------------------------------------------------------------------------
//........................................................................
}   // namespace dbaccess
//........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.36); FILE MERGED 2006/09/01 17:24:10 kaib 1.6.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ContainerMediator.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 06:41:34 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBA_CONTAINERMEDIATOR_HXX
#include "ContainerMediator.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//........................................................................
namespace dbaccess
{
//........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
DBG_NAME(OContainerMediator)
OContainerMediator::OContainerMediator( const Reference< XContainer >& _xContainer
                                       ,const Reference< XNameAccess >& _xSettings
                                       ,sal_Bool _bTables)
    : m_xSettings(_xSettings)
    , m_xContainer(_xContainer)
    , m_bTables(_bTables)
{
    DBG_CTOR(OContainerMediator,NULL);
    osl_incrementInterlockedCount(&m_refCount);
    try
    {
        m_xContainer->addContainerListener(this);
        Reference< XContainer > xContainer(m_xSettings, UNO_QUERY);
        if ( xContainer.is() )
            xContainer->addContainerListener(this);
    }
    catch(Exception&)
    {
        OSL_ENSURE(sal_False, "OContainerMediator::OContainerMediator: caught an exception!");
    }
    osl_decrementInterlockedCount( &m_refCount );
}
// -----------------------------------------------------------------------------
OContainerMediator::~OContainerMediator()
{
    DBG_DTOR(OContainerMediator,NULL);
    osl_incrementInterlockedCount(&m_refCount);
    try
    {
        if ( m_xContainer.is() )
            m_xContainer->removeContainerListener(this);
        Reference< XContainer > xContainer(m_xSettings, UNO_QUERY);
        if ( xContainer.is() )
            xContainer->removeContainerListener(this);
    }
    catch(Exception&)
    {
        OSL_ENSURE(sal_False, "OContainerMediator::~OContainerMediator: caught an exception!");
    }
    osl_decrementInterlockedCount( &m_refCount );
}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::elementInserted( const ContainerEvent& _rEvent ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    if ( _rEvent.Source == m_xSettings && m_xSettings.is() )
    {
        ::rtl::OUString sElementName;
        _rEvent.Accessor >>= sElementName;
        PropertyForwardList::iterator aFind = m_aForwardList.find(sElementName);
        if ( aFind != m_aForwardList.end() )
        {
            Reference< XPropertySet> xDest(_rEvent.Element,UNO_QUERY);
            aFind->second.first->setDefinition(xDest);
        }
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::elementRemoved( const ContainerEvent& _rEvent ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    if ( _rEvent.Source == m_xContainer && m_xSettings.is() )
    {
        ::rtl::OUString sElementName;
        _rEvent.Accessor >>= sElementName;
        m_aForwardList.erase(sElementName);
        Reference<XNameContainer> xNameContainer(m_xSettings,UNO_QUERY);
        if ( xNameContainer.is() && m_xSettings->hasByName(sElementName) )
            xNameContainer->removeByName(sElementName);
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::elementReplaced( const ContainerEvent& /*_rEvent*/ ) throw(RuntimeException)
{

}
// -----------------------------------------------------------------------------
void SAL_CALL OContainerMediator::disposing( const EventObject& Source ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);

    if ( Source.Source == m_xContainer || Source.Source == m_xSettings )
    {
        Reference< XContainer > xContainer(m_xSettings, UNO_QUERY);
        if ( xContainer.is() )
        {
            xContainer->removeContainerListener(this);
        }
        m_xSettings = NULL;

        if ( m_xContainer.is() )
        {
            m_xContainer->removeContainerListener(this);
            m_xContainer = NULL;
        }
    }
}
// -----------------------------------------------------------------------------
void OContainerMediator::notifyElementCreated(const ::rtl::OUString& _sName,const Reference<XPropertySet>& _xDest)
{
    PropertyForwardList::iterator aFind = m_aForwardList.find(_sName);
    if ( aFind == m_aForwardList.end() && m_xSettings.is() )
    {
        if ( m_xSettings->hasByName(_sName) )
        {
            Reference<XPropertySet> xSetting(m_xSettings->getByName(_sName),UNO_QUERY);
            if ( xSetting.is() )
                ::comphelper::copyProperties(xSetting,_xDest);
        }

        ::std::vector< ::rtl::OUString> aPropertyList;
        if ( m_bTables )
        {
            aPropertyList.reserve(26);
            aPropertyList.push_back(PROPERTY_FILTER);
            aPropertyList.push_back(PROPERTY_ORDER);
            aPropertyList.push_back(PROPERTY_APPLYFILTER);
            aPropertyList.push_back(PROPERTY_FONT);
            aPropertyList.push_back(PROPERTY_ROW_HEIGHT);
            aPropertyList.push_back(PROPERTY_TEXTCOLOR);
            aPropertyList.push_back(PROPERTY_TEXTLINECOLOR);
            aPropertyList.push_back(PROPERTY_TEXTEMPHASIS);
            aPropertyList.push_back(PROPERTY_TEXTRELIEF);
            aPropertyList.push_back(PROPERTY_FONTNAME);
            aPropertyList.push_back(PROPERTY_FONTHEIGHT);
            aPropertyList.push_back(PROPERTY_FONTWIDTH);
            aPropertyList.push_back(PROPERTY_FONTSTYLENAME);
            aPropertyList.push_back(PROPERTY_FONTFAMILY);
            aPropertyList.push_back(PROPERTY_FONTCHARSET);
            aPropertyList.push_back(PROPERTY_FONTPITCH);
            aPropertyList.push_back(PROPERTY_FONTCHARWIDTH);
            aPropertyList.push_back(PROPERTY_FONTWEIGHT);
            aPropertyList.push_back(PROPERTY_FONTSLANT);
            aPropertyList.push_back(PROPERTY_FONTUNDERLINE);
            aPropertyList.push_back(PROPERTY_FONTSTRIKEOUT);
            aPropertyList.push_back(PROPERTY_FONTORIENTATION);
            aPropertyList.push_back(PROPERTY_FONTKERNING);
            aPropertyList.push_back(PROPERTY_FONTWORDLINEMODE);
            aPropertyList.push_back(PROPERTY_FONTTYPE);
        }
        else
        {
            aPropertyList.reserve(9);
            aPropertyList.push_back(PROPERTY_ALIGN);
            aPropertyList.push_back(PROPERTY_NUMBERFORMAT);
            aPropertyList.push_back(PROPERTY_RELATIVEPOSITION);
            aPropertyList.push_back(PROPERTY_WIDTH);
            aPropertyList.push_back(PROPERTY_HIDDEN);
            aPropertyList.push_back(PROPERTY_CONTROLMODEL);
            aPropertyList.push_back(PROPERTY_HELPTEXT);
            aPropertyList.push_back(PROPERTY_CONTROLDEFAULT);
        }

        OPropertyForward* pForward = new OPropertyForward(_xDest,m_xSettings,_sName,aPropertyList);
        Reference<XInterface> xTemp = *pForward;
        m_aForwardList.insert( PropertyForwardList::value_type(_sName,TPropertyForward(pForward,xTemp)));
    }
}
// -----------------------------------------------------------------------------
//........................................................................
}   // namespace dbaccess
//........................................................................
<|endoftext|>


<commit_before>#include "descartes_trajectory/axial_symmetric_pt.h"

using descartes_trajectory::TolerancedFrame;
using descartes_trajectory::AxialSymmetricPt;
using namespace descartes_core::utils;

static TolerancedFrame makeRotationalAxis(AxialSymmetricPt::FreeAxis axis)
{
  using namespace descartes_trajectory;

  Eigen::Affine3d rot = Eigen::Affine3d::Identity();
  PositionTolerance pos_tol = ToleranceBase::zeroTolerance<PositionTolerance>(0,0,0);
  OrientationTolerance orient_tol = ToleranceBase::createSymmetric<OrientationTolerance>(0.0, 0.0, 0.0,
                                    ((axis == AxialSymmetricPt::X_AXIS) ? 2*M_PI : 0.0),
                                    ((axis == AxialSymmetricPt::Y_AXIS) ? 2*M_PI : 0.0),
                                    ((axis == AxialSymmetricPt::Z_AXIS) ? 2*M_PI : 0.0));
  return TolerancedFrame(rot, pos_tol, orient_tol);
}

namespace descartes_trajectory
{

AxialSymmetricPt::AxialSymmetricPt(double x, double y, double z, double rx, double ry, double rz,
                                   double orient_increment, FreeAxis axis) :
  CartTrajectoryPt(toFrame(x, y, z, rx, ry, rz, EulerConventions::XYZ),
                   makeRotationalAxis(axis),
                   Eigen::Affine3d::Identity(),
                   Eigen::Affine3d::Identity(),
                   0.0, // The position discretization
                   orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}

AxialSymmetricPt::AxialSymmetricPt(const Eigen::Affine3d& pose, double orient_increment, FreeAxis axis) :
  CartTrajectoryPt(pose,
                   makeRotationalAxis(axis),
                   Eigen::Affine3d::Identity(),
                   Eigen::Affine3d::Identity(),
                   0.0, // The position discretization
                   orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}

} // end of namespace descartes_trajectory
<commit_msg>initializes the wobj_pt tolerance frame member with a fully defined nominal pose<commit_after>#include "descartes_trajectory/axial_symmetric_pt.h"

using descartes_trajectory::TolerancedFrame;
using descartes_trajectory::AxialSymmetricPt;
using namespace descartes_core::utils;

static TolerancedFrame makeUnconstrainedRotation(double x, double y, double z, double rx, double ry, double rz,
                                          AxialSymmetricPt::FreeAxis axis)
{
  using namespace descartes_trajectory;

  Eigen::Affine3d pose = toFrame(x, y, z, rx, ry, rz, EulerConventions::XYZ);
  PositionTolerance pos_tol = ToleranceBase::zeroTolerance<PositionTolerance>(x,y,z);
  OrientationTolerance orient_tol = ToleranceBase::createSymmetric<OrientationTolerance>(
      ((axis == AxialSymmetricPt::X_AXIS) ? 0.0 : rx),
      ((axis == AxialSymmetricPt::Y_AXIS) ? 0.0 : ry),
      ((axis == AxialSymmetricPt::Z_AXIS) ? 0.0 : rz),
      ((axis == AxialSymmetricPt::X_AXIS) ? 2*M_PI : 0.0),
      ((axis == AxialSymmetricPt::Y_AXIS) ? 2*M_PI : 0.0),
      ((axis == AxialSymmetricPt::Z_AXIS) ? 2*M_PI : 0.0));
  return TolerancedFrame(pose, pos_tol, orient_tol);
}

static TolerancedFrame makeUnconstrainedRotation(const Eigen::Affine3d& pose,
                                          AxialSymmetricPt::FreeAxis axis)
{
  using namespace descartes_trajectory;

  Eigen::Vector3d rpy = pose.rotation().eulerAngles(0,1,2);
  double rx = rpy(0);
  double ry = rpy(1);
  double rz = rpy(2);
  double x = pose.translation()(0);
  double y = pose.translation()(1);
  double z = pose.translation()(2);

  PositionTolerance pos_tol = ToleranceBase::zeroTolerance<PositionTolerance>(x,y,z);
  OrientationTolerance orient_tol = ToleranceBase::createSymmetric<OrientationTolerance>(
      ((axis == AxialSymmetricPt::X_AXIS) ? 0.0 : rx),
      ((axis == AxialSymmetricPt::Y_AXIS) ? 0.0 : ry),
      ((axis == AxialSymmetricPt::Z_AXIS) ? 0.0 : rz),
      ((axis == AxialSymmetricPt::X_AXIS) ? 2*M_PI : 0.0),
      ((axis == AxialSymmetricPt::Y_AXIS) ? 2*M_PI : 0.0),
      ((axis == AxialSymmetricPt::Z_AXIS) ? 2*M_PI : 0.0));
  return TolerancedFrame(pose, pos_tol, orient_tol);
}

namespace descartes_trajectory
{

AxialSymmetricPt::AxialSymmetricPt(double x, double y, double z, double rx, double ry, double rz,
                                   double orient_increment, FreeAxis axis) :
  CartTrajectoryPt(makeUnconstrainedRotation(x, y, z, rx, ry, rz,axis),
                   0.0, // The position discretization
                   orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}

AxialSymmetricPt::AxialSymmetricPt(const Eigen::Affine3d& pose, double orient_increment, FreeAxis axis) :
  CartTrajectoryPt(makeUnconstrainedRotation(pose,axis),
                   0.0, // The position discretization
                   orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}

} // end of namespace descartes_trajectory
<|endoftext|>


<commit_before>/*
   Copyright 2017 Thomas Krause <thomaskrause@posteo.de>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "simdindexjoin.h"

#include <annis/operators/operator.h>     // for Operator
#include <annis/util/comparefunctions.h>  // for checkAnnotationEqual
#include <algorithm>                      // for move
#include <future>                         // for future, async, launch, laun...
#include <list>                           // for list
#include "annis/iterators.h"              // for AnnoIt, Iterator
#include "annis/types.h"                  // for Match, Annotation, nodeid_t
#include "annis/util/threadpool.h"        // for ThreadPool

#include <Vc/Memory>

using namespace annis;

SIMDIndexJoin::SIMDIndexJoin(std::shared_ptr<Iterator> lhs, size_t lhsIdx,
                             std::shared_ptr<Operator> op,
                             const AnnoStorage<nodeid_t>& annos,
                             Annotation rhsAnnoToFind)
  : lhs(lhs), lhsIdx(lhsIdx), op(op), annos(annos), rhsAnnoToFind(rhsAnnoToFind)
{
}

bool SIMDIndexJoin::next(std::vector<Match> &tuple)
{
  tuple.clear();

  do
  {
    while(!matchBuffer.empty())
    {
      const MatchPair& m = matchBuffer.front();

      tuple.reserve(m.lhs.size()+1);
      tuple.insert(tuple.begin(), m.lhs.begin(), m.lhs.end());
      tuple.push_back({m.rhs, rhsAnnoToFind});

      matchBuffer.pop_front();
      return true;

    }
  } while (nextMatchBuffer());

  return false;
}

void SIMDIndexJoin::reset()
{
  if(lhs)
  {
    lhs->reset();
  }

  matchBuffer.clear();
}

bool SIMDIndexJoin::nextMatchBuffer()
{
  std::vector<Match> currentLHS;

  Vc::uint32_v valueTemplate(rhsAnnoToFind.val);

  while(matchBuffer.empty() && lhs->next(currentLHS))
  {
    std::unique_ptr<AnnoIt> reachableNodesIt = op->retrieveMatches(currentLHS[lhsIdx]);
    if(reachableNodesIt)
    {
      std::vector<nodeid_t> reachableNodes;

      {
        Match n;
        while(reachableNodesIt->next(n))
        {
          reachableNodes.push_back(n.node);
        }
      }

      Vc::Memory<Vc::uint32_v> vAnnoVals(reachableNodes.size());

      for(size_t i=0; i < vAnnoVals.entriesCount(); i++)
      {
        std::vector<Annotation> foundAnnos = annos.getAnnotations(reachableNodes[i], rhsAnnoToFind.ns, rhsAnnoToFind.name);
        vAnnoVals[i] = foundAnnos.empty() ? 0 : foundAnnos[0].val;
      }

      for(size_t i=0; i < vAnnoVals.vectorsCount(); i++)
      {
        Vc::Mask<uint32_t> maskFoundAnnos = (vAnnoVals.vector(i) == valueTemplate);

        if(!maskFoundAnnos.isEmpty())
        {
          for(int i=maskFoundAnnos.firstOne(); i < maskFoundAnnos.size(); i++)
          {
            if(maskFoundAnnos[i])
            {
              if((op->isReflexive() || currentLHS[lhsIdx].node != reachableNodes[i]))
              {
                matchBuffer.push_back({currentLHS, reachableNodes[i]});
              }
            }
          }
        }
      } // end for each vector of values
    }
  } // end while LHS valid and nothing found yet

  return !matchBuffer.empty();
}

SIMDIndexJoin::~SIMDIndexJoin()
{
}
<commit_msg>Do not attempt to create an Vc::Memory object with size zero.<commit_after>/*
   Copyright 2017 Thomas Krause <thomaskrause@posteo.de>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "simdindexjoin.h"

#include <annis/operators/operator.h>     // for Operator
#include <annis/util/comparefunctions.h>  // for checkAnnotationEqual
#include <algorithm>                      // for move
#include <future>                         // for future, async, launch, laun...
#include <list>                           // for list
#include "annis/iterators.h"              // for AnnoIt, Iterator
#include "annis/types.h"                  // for Match, Annotation, nodeid_t
#include "annis/util/threadpool.h"        // for ThreadPool

#include <Vc/Memory>

using namespace annis;

SIMDIndexJoin::SIMDIndexJoin(std::shared_ptr<Iterator> lhs, size_t lhsIdx,
                             std::shared_ptr<Operator> op,
                             const AnnoStorage<nodeid_t>& annos,
                             Annotation rhsAnnoToFind)
  : lhs(lhs), lhsIdx(lhsIdx), op(op), annos(annos), rhsAnnoToFind(rhsAnnoToFind)
{
}

bool SIMDIndexJoin::next(std::vector<Match> &tuple)
{
  tuple.clear();

  do
  {
    while(!matchBuffer.empty())
    {
      const MatchPair& m = matchBuffer.front();

      tuple.reserve(m.lhs.size()+1);
      tuple.insert(tuple.begin(), m.lhs.begin(), m.lhs.end());
      tuple.push_back({m.rhs, rhsAnnoToFind});

      matchBuffer.pop_front();
      return true;

    }
  } while (nextMatchBuffer());

  return false;
}

void SIMDIndexJoin::reset()
{
  if(lhs)
  {
    lhs->reset();
  }

  matchBuffer.clear();
}

bool SIMDIndexJoin::nextMatchBuffer()
{
  std::vector<Match> currentLHS;

  Vc::uint32_v valueTemplate(rhsAnnoToFind.val);

  while(matchBuffer.empty() && lhs->next(currentLHS))
  {
    std::unique_ptr<AnnoIt> reachableNodesIt = op->retrieveMatches(currentLHS[lhsIdx]);
    if(reachableNodesIt)
    {
      std::vector<nodeid_t> reachableNodes;

      {
        Match n;
        while(reachableNodesIt->next(n))
        {
          reachableNodes.push_back(n.node);
        }
      }

      if(!reachableNodes.empty())
      {
        // do not allocate a Vc::Memory object with an empty size (this will produce an invalid pointer)
        Vc::Memory<Vc::uint32_v> vAnnoVals(reachableNodes.size());

        for(size_t i=0; i < vAnnoVals.entriesCount(); i++)
        {
          std::vector<Annotation> foundAnnos = annos.getAnnotations(reachableNodes[i], rhsAnnoToFind.ns, rhsAnnoToFind.name);
          vAnnoVals[i] = foundAnnos.empty() ? 0 : foundAnnos[0].val;
        }

        for(size_t i=0; i < vAnnoVals.vectorsCount(); i++)
        {
          Vc::Mask<uint32_t> maskFoundAnnos = (vAnnoVals.vector(i) == valueTemplate);

          if(!maskFoundAnnos.isEmpty())
          {
            for(int i=maskFoundAnnos.firstOne(); i < maskFoundAnnos.size(); i++)
            {
              if(maskFoundAnnos[i])
              {
                if((op->isReflexive() || currentLHS[lhsIdx].node != reachableNodes[i]))
                {
                  matchBuffer.push_back({currentLHS, reachableNodes[i]});
                }
              }
            }
          }
        } // end for each vector of values
      } // end if reachable nodes not empty
    } // end if reachable nodes iterator valide
  } // end while LHS valid and nothing found yet

  return !matchBuffer.empty();
}

SIMDIndexJoin::~SIMDIndexJoin()
{
}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    vector<int> singleNumberIII(vector<int> &A) {
        // Xor all the elements to get x ^ y.
        int x_xor_y = accumulate(A.cbegin(), A.cend(), 0, bit_xor<int>());

        // Get the last bit where 1 occurs.
        x_xor_y &= -x_xor_y;

        // Get the subset of A where the number has the bit.
        // The subset only contains one of the two integers, call it x.
        // Xor all the elemets in the subset to get x.
        vector<int> result(2, 0);
        for (const auto& i : A) {
            result[!(i & x_xor_y)] ^= i;
        }
        return result;
    }
};

class Solution2 {
public:
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    vector<int> singleNumberIII(vector<int> &A) {
        // Xor all the elements to get x ^ y.
        int x_xor_y = 0;
        for (const auto& i : A) {
            x_xor_y ^= i;
        }

        // Get the last bit where 1 occurs.
        const auto bit = x_xor_y & ~(x_xor_y - 1);

        // Get the subset of A where the number has the bit.
        // The subset only contains one of the two integers, call it x.
        // Xor all the elemets in the subset to get x.
        int x = 0;
        for (const auto& i : A) {
            if (i & bit) {
                x ^= i;
            }
        }

        return {x, x_xor_y ^ x};
    }
};
<commit_msg>Update single-number-iii.cpp<commit_after>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    vector<int> singleNumberIII(vector<int> &A) {
        // Xor all the elements to get x ^ y.
        int x_xor_y = accumulate(A.cbegin(), A.cend(), 0, bit_xor<int>());

        // Get the last bit where 1 occurs.
        x_xor_y &= -x_xor_y;

        // Get the subset of A where the number has the bit.
        // The subset only contains one of the two integers, call it x.
        // Xor all the elemets in the subset to get x.
        vector<int> result(2, 0);
        for (const auto& i : A) {
            result[static_cast<bool>(i & x_xor_y)] ^= i;
        }
        return result;
    }
};

class Solution2 {
public:
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    vector<int> singleNumberIII(vector<int> &A) {
        // Xor all the elements to get x ^ y.
        int x_xor_y = 0;
        for (const auto& i : A) {
            x_xor_y ^= i;
        }

        // Get the last bit where 1 occurs.
        const auto bit = x_xor_y & ~(x_xor_y - 1);

        // Get the subset of A where the number has the bit.
        // The subset only contains one of the two integers, call it x.
        // Xor all the elemets in the subset to get x.
        int x = 0;
        for (const auto& i : A) {
            if (i & bit) {
                x ^= i;
            }
        }

        return {x, x_xor_y ^ x};
    }
};
<|endoftext|>


<commit_before>/*
* OpenSSL RC4
* (C) 1999-2007,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/stream_cipher.h>

#if defined(BOTAN_HAS_OPENSSL) && defined(BOTAN_HAS_RC4)

#include <botan/internal/openssl.h>
#include <botan/parsing.h>
#include <botan/exceptn.h>
#include <openssl/rc4.h>

namespace Botan {

namespace {

class OpenSSL_RC4 final : public StreamCipher
   {
   public:
      void clear() override { clear_mem(&m_rc4, 1); m_key_set = false; }

      std::string provider() const override { return "openssl"; }

      std::string name() const override
         {
         switch(m_skip)
            {
            case 0:
               return "RC4";
            case 256:
               return "MARK-4";
            default:
               return "RC4_skip(" + std::to_string(m_skip) + ")";
            }
         }

      StreamCipher* clone() const override { return new OpenSSL_RC4(m_skip); }

      Key_Length_Specification key_spec() const override
         {
         return Key_Length_Specification(1, 32);
         }

      explicit OpenSSL_RC4(size_t skip = 0) : m_skip(skip) { clear(); }
      ~OpenSSL_RC4() { clear(); }

      void set_iv(const uint8_t*, size_t len) override
         {
         if(len > 0)
            throw Exception("RC4 does not support an IV");
         }

      void seek(uint64_t) override
         {
         throw Not_Implemented("RC4 does not support seeking");
         }
   private:
      void cipher(const uint8_t in[], uint8_t out[], size_t length) override
         {
         verify_key_set(m_key_set);
         ::RC4(&m_rc4, length, in, out);
         }

      void key_schedule(const uint8_t key[], size_t length) override
         {
         ::RC4_set_key(&m_rc4, length, key);
         uint8_t d = 0;
         for(size_t i = 0; i != m_skip; ++i)
            ::RC4(&m_rc4, 1, &d, &d);
         m_key_set = true;
         }

      size_t m_skip;
      RC4_KEY m_rc4;
      bool m_key_set;
   };

}

std::unique_ptr<StreamCipher>
make_openssl_rc4(size_t skip)
   {
   return std::unique_ptr<StreamCipher>(new OpenSSL_RC4(skip));
   }

}

#endif
<commit_msg>Correct OpenSSL RC4 naming<commit_after>/*
* OpenSSL RC4
* (C) 1999-2007,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/stream_cipher.h>

#if defined(BOTAN_HAS_OPENSSL) && defined(BOTAN_HAS_RC4)

#include <botan/internal/openssl.h>
#include <botan/parsing.h>
#include <botan/exceptn.h>
#include <openssl/rc4.h>

namespace Botan {

namespace {

class OpenSSL_RC4 final : public StreamCipher
   {
   public:
      void clear() override { clear_mem(&m_rc4, 1); m_key_set = false; }

      std::string provider() const override { return "openssl"; }

      std::string name() const override
         {
         switch(m_skip)
            {
            case 0:
               return "RC4";
            case 256:
               return "MARK-4";
            default:
               return "RC4(" + std::to_string(m_skip) + ")";
            }
         }

      StreamCipher* clone() const override { return new OpenSSL_RC4(m_skip); }

      Key_Length_Specification key_spec() const override
         {
         return Key_Length_Specification(1, 32);
         }

      explicit OpenSSL_RC4(size_t skip = 0) : m_skip(skip) { clear(); }
      ~OpenSSL_RC4() { clear(); }

      void set_iv(const uint8_t*, size_t len) override
         {
         if(len > 0)
            throw Exception("RC4 does not support an IV");
         }

      void seek(uint64_t) override
         {
         throw Not_Implemented("RC4 does not support seeking");
         }
   private:
      void cipher(const uint8_t in[], uint8_t out[], size_t length) override
         {
         verify_key_set(m_key_set);
         ::RC4(&m_rc4, length, in, out);
         }

      void key_schedule(const uint8_t key[], size_t length) override
         {
         ::RC4_set_key(&m_rc4, length, key);
         uint8_t d = 0;
         for(size_t i = 0; i != m_skip; ++i)
            ::RC4(&m_rc4, 1, &d, &d);
         m_key_set = true;
         }

      size_t m_skip;
      RC4_KEY m_rc4;
      bool m_key_set;
   };

}

std::unique_ptr<StreamCipher>
make_openssl_rc4(size_t skip)
   {
   return std::unique_ptr<StreamCipher>(new OpenSSL_RC4(skip));
   }

}

#endif
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {StereoFixed.png}, {StereoMoving.png}
//    OUTPUTS: {fcDeformationFieldOutput-horizontal.png}, {fcDeformationFieldOutput-vertical.png}, {fcCorrelFieldOutput.png}, {fcDResampledOutput2.png}
//    1.0 5 3 0.1
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {StereoFixed.png}, {StereoMoving.png}
//    OUTPUTS: {fcMRSDDeformationFieldOutput-horizontal.png}, {fcMRSDDeformationFieldOutput-vertical.png}, {fcMRSDCorrelFieldOutput.png}, {fcMRSDDResampledOutput2.png}
//    1.0 5 3 0.1 mrsd
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the \doxygen{otb}{FineRegistrationImageFilter}. This filter performs deformation estimation
// using the classical extrema of image-to-image metric look-up in a search window.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex

#include "otbImage.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileReader.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h"

// Software Guide : BeginCodeSnippet
#include "otbFineRegistrationImageFilter.h"
// Software Guide : EndCodeSnippet

#include "otbImageOfVectorsToMonoChannelExtractROI.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkCastImageFilter.h"

#include <iostream>

int main(int argc, char** argv)
{

  if (argc < 11)
    {
    std::cerr << "Usage: " << argv[0];
    std::cerr <<
    " fixedFileName movingFileName fieldOutNameHorizontal fieldOutNameVertical fieldCorrelation warped ";
    std::cerr << "smoothingSigma correlationRadius explorationRadius subpixelPrecision";

    return EXIT_FAILURE;
    }

  const unsigned int ImageDimension = 2;

  typedef double                              PixelType;
  typedef itk::Vector<double, ImageDimension> DeformationPixelType;

  typedef double CoordinateRepresentationType;

  typedef unsigned char                               OutputPixelType;
  typedef otb::Image<OutputPixelType, ImageDimension> OutputImageType;

  // Software Guide : BeginLatex
  //
  // Several type of \doxygen{otb}{Image} are required to represent the input image, the correlation field,
  // and the deformation field.
  //
  // Software Guide : EndLatex

  //Allocate Images
  // Software Guide : BeginCodeSnippet
  typedef otb::Image<PixelType, ImageDimension> InputImageType;
  typedef otb::Image<PixelType, ImageDimension> CorrelationImageType;
  typedef otb::Image<DeformationPixelType,
      ImageDimension>                           DeformationFieldType;
  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileReader<InputImageType> InputReaderType;
  InputReaderType::Pointer fReader = InputReaderType::New();
  fReader->SetFileName(argv[1]);

  InputReaderType::Pointer mReader = InputReaderType::New();
  mReader->SetFileName(argv[2]);

  // Software Guide : BeginLatex
  //
  // To make the correlation estimation more robust, the first
  // required step is to blur the input images. This is done using the
  // \doxygen{itk}{RecursiveGaussianImageFilter}:
  //
  // Software Guide : EndLatex

  //Blur input images
  // Software Guide : BeginCodeSnippet
  typedef itk::RecursiveGaussianImageFilter<InputImageType,
      InputImageType> InputBlurType;

  InputBlurType::Pointer fBlur = InputBlurType::New();
  fBlur->SetInput(fReader->GetOutput());
  fBlur->SetSigma(atof(argv[7]));

  InputBlurType::Pointer mBlur = InputBlurType::New();
  mBlur->SetInput(mReader->GetOutput());
  mBlur->SetSigma(atof(argv[7]));
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Now, we declare and instantiate the \doxygen{otb}{FineCorrelationImageFilter} which is going to perform the registration:
  //
  // Software Guide : EndLatex

  //Create the filter
  // Software Guide : BeginCodeSnippet
  typedef otb::FineRegistrationImageFilter<InputImageType,
      CorrelationImageType,
      DeformationFieldType>
  RegistrationFilterType;

  RegistrationFilterType::Pointer registrator = RegistrationFilterType::New();

  registrator->SetMovingInput(mBlur->GetOutput());
  registrator->SetFixedInput(fBlur->GetOutput());
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Some parameters need to be specified to the filter:
  // \begin{itemize}
  // \item The area where the search is performed. This area is defined by its radius:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef RegistrationFilterType::SizeType RadiusType;

  RadiusType searchRadius;

  searchRadius[0] = atoi(argv[8]);
  searchRadius[1] = atoi(argv[8]);

  registrator->SetSearchRadius(searchRadius);
// Software Guide : EndCodeSnippet

  std::cout << "Exploration radius " << registrator->GetSearchRadius() << std::endl;

  // Software Guide : BeginLatex
  //
  // \item The window used to compute the local metric. This window is also defined by its radius:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  RadiusType correlationRadius;
  correlationRadius[0] = atoi(argv[9]);
  correlationRadius[1] = atoi(argv[9]);

  registrator->SetRadius(correlationRadius);
// Software Guide : EndCodeSnippet

  std::cout << "Correlation radius " << registrator->GetRadius() << std::endl;

  // Software Guide : BeginLatex
  //
  // We need to set the sub-pixel accuracy we want to obtain:
  //
  // Software Guide : EndLatex
  registrator->SetSubPixelAccuracy(atof(argv[10]));

  // Software Guide : BeginLatex
  //
  // The default matching metric used by the \doxygen{FineRegistrationImageFilter} is standard correlation.
  // However, we may also use any other image-to-image metric provided by ITK. For instance, here is how we
  // would use the \doxygen{itk}{MutualInformationImageToImageMetric} (do not forget to include the proper header).
  //
  // Software Guide : EndLatex

  if(argc > 11)
      {
  // Software Guide : BeginCodeSnippet
      typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<InputImageType,InputImageType> MRSDMetricType;
      MRSDMetricType::Pointer mrsdMetric = MRSDMetricType::New();
      registrator->SetMetric(mrsdMetric);
  // Software Guide : EndCodeSnippet
      }

  // Software Guide : BeginLatex
  //
  // \end{itemize}
  // The execution of the \doxygen{otb}{FineRegistrationImageFilter} will be triggered by
  // the \code{Update()} call on the writer at the end of the
  // pipeline. Make sure to use a
  // \doxygen{otb}{StreamingImageFileWriter} if you want to benefit
  // from the streaming features.
  //
  // Software Guide : EndLatex

  typedef otb::ImageOfVectorsToMonoChannelExtractROI<DeformationFieldType,
      InputImageType>
  ChannelExtractionFilterType;
  ChannelExtractionFilterType::Pointer channelExtractor =
    ChannelExtractionFilterType::New();

  channelExtractor->SetInput(registrator->GetOutputDeformationField());
  channelExtractor->SetChannel(1);

  typedef itk::RescaleIntensityImageFilter<InputImageType,
      OutputImageType> RescalerType;
  RescalerType::Pointer fieldRescaler = RescalerType::New();

  fieldRescaler->SetInput(channelExtractor->GetOutput());
  fieldRescaler->SetOutputMaximum(255);
  fieldRescaler->SetOutputMinimum(0);

  typedef otb::StreamingImageFileWriter<OutputImageType> DFWriterType;

  DFWriterType::Pointer dfWriter = DFWriterType::New();
  dfWriter->SetFileName(argv[3]);
  dfWriter->SetInput(fieldRescaler->GetOutput());
  dfWriter->Update();

  channelExtractor->SetChannel(2);
  dfWriter->SetFileName(argv[4]);
  dfWriter->Update();

  typedef itk::WarpImageFilter<InputImageType, InputImageType,
      DeformationFieldType> WarperType;
  WarperType::Pointer warper = WarperType::New();

  InputImageType::PixelType padValue = 4.0;

  warper->SetInput(mReader->GetOutput());
  warper->SetDeformationField(registrator->GetOutputDeformationField());
  warper->SetEdgePaddingValue(padValue);

  typedef itk::RescaleIntensityImageFilter<CorrelationImageType,
        OutputImageType> CorrelationRescalerType;

  CorrelationRescalerType::Pointer correlationRescaler = CorrelationRescalerType::New();
  correlationRescaler->SetInput(registrator->GetOutput());
  correlationRescaler->SetOutputMinimum(0);
  correlationRescaler->SetOutputMaximum(255);

  typedef otb::StreamingImageFileWriter<OutputImageType> WriterType;

  WriterType::Pointer writer1 = WriterType::New();
  writer1->SetInput(correlationRescaler->GetOutput());
  writer1->SetFileName(argv[5]);
  writer1->Update();

  typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType;
  CastFilterType::Pointer caster =  CastFilterType::New();
  caster->SetInput(warper->GetOutput());

  WriterType::Pointer writer2 = WriterType::New();
  writer2->SetFileName(argv[6]);
  writer2->SetInput(caster->GetOutput());
  writer2->Update();

  // Software Guide : BeginLatex
  //
  // Figure~\ref{fig:FineCorrelationImageFilterOUTPUT} shows the result of
  // applying the \doxygen{otb}{FineCorrelationImageFilter}.
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{StereoFixed.eps}
  // \includegraphics[width=0.40\textwidth]{StereoMoving.eps}
  // \includegraphics[width=0.40\textwidth]{fcDeformationFieldOutput-horizontal.eps}
  // \includegraphics[width=0.40\textwidth]{fcDeformationFieldOutput-vertical.eps}
  // \includegraphics[width=0.40\textwidth]{fcCorrelFieldOutput.eps}
  // \includegraphics[width=0.40\textwidth]{fcDResampledOutput2.eps}
  // \includegraphics[width=0.40\textwidth]{fcMRSDDeformationFieldOutput-horizontal.eps}
  // \includegraphics[width=0.40\textwidth]{fcMRSDDeformationFieldOutput-vertical.eps}
  // \includegraphics[width=0.40\textwidth]{fcMRSDCorrelFieldOutput.eps}
  // \includegraphics[width=0.40\textwidth]{fcMRSDDResampledOutput2.eps}
  // \itkcaption[Deformation field and resampling from fine correlation registration]{From left
  // to right and top to bottom: fixed input image, moving image with a low stereo angle,
  //  estimated deformation fields in both direction using correlation,
  // local correlation field, resampled image based on correlation,
  // estimated deformation fields in both direction using mean reciprocal square difference,
  // local mean reciprocal square difference field, resampled image based on mean reciprocal square difference.
  // }
  // \label{fig:FineCorrelationImageFilterOUTPUT}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;

}
<commit_msg>BUG: In example, the MRSD metric has to be maximized<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {StereoFixed.png}, {StereoMoving.png}
//    OUTPUTS: {fcDeformationFieldOutput-horizontal.png}, {fcDeformationFieldOutput-vertical.png}, {fcCorrelFieldOutput.png}, {fcDResampledOutput2.png}
//    1.0 5 3 0.1
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {StereoFixed.png}, {StereoMoving.png}
//    OUTPUTS: {fcMRSDDeformationFieldOutput-horizontal.png}, {fcMRSDDeformationFieldOutput-vertical.png}, {fcMRSDCorrelFieldOutput.png}, {fcMRSDDResampledOutput2.png}
//    1.0 5 3 0.1 mrsd
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the \doxygen{otb}{FineRegistrationImageFilter}. This filter performs deformation estimation
// using the classical extrema of image-to-image metric look-up in a search window.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex

#include "otbImage.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileReader.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h"

// Software Guide : BeginCodeSnippet
#include "otbFineRegistrationImageFilter.h"
// Software Guide : EndCodeSnippet

#include "otbImageOfVectorsToMonoChannelExtractROI.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkCastImageFilter.h"

#include <iostream>

int main(int argc, char** argv)
{

  if (argc < 11)
    {
    std::cerr << "Usage: " << argv[0];
    std::cerr <<
    " fixedFileName movingFileName fieldOutNameHorizontal fieldOutNameVertical fieldCorrelation warped ";
    std::cerr << "smoothingSigma correlationRadius explorationRadius subpixelPrecision";

    return EXIT_FAILURE;
    }

  const unsigned int ImageDimension = 2;

  typedef double                              PixelType;
  typedef itk::Vector<double, ImageDimension> DeformationPixelType;

  typedef double CoordinateRepresentationType;

  typedef unsigned char                               OutputPixelType;
  typedef otb::Image<OutputPixelType, ImageDimension> OutputImageType;

  // Software Guide : BeginLatex
  //
  // Several type of \doxygen{otb}{Image} are required to represent the input image, the correlation field,
  // and the deformation field.
  //
  // Software Guide : EndLatex

  //Allocate Images
  // Software Guide : BeginCodeSnippet
  typedef otb::Image<PixelType, ImageDimension> InputImageType;
  typedef otb::Image<PixelType, ImageDimension> CorrelationImageType;
  typedef otb::Image<DeformationPixelType,
      ImageDimension>                           DeformationFieldType;
  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileReader<InputImageType> InputReaderType;
  InputReaderType::Pointer fReader = InputReaderType::New();
  fReader->SetFileName(argv[1]);

  InputReaderType::Pointer mReader = InputReaderType::New();
  mReader->SetFileName(argv[2]);

  // Software Guide : BeginLatex
  //
  // To make the correlation estimation more robust, the first
  // required step is to blur the input images. This is done using the
  // \doxygen{itk}{RecursiveGaussianImageFilter}:
  //
  // Software Guide : EndLatex

  //Blur input images
  // Software Guide : BeginCodeSnippet
  typedef itk::RecursiveGaussianImageFilter<InputImageType,
      InputImageType> InputBlurType;

  InputBlurType::Pointer fBlur = InputBlurType::New();
  fBlur->SetInput(fReader->GetOutput());
  fBlur->SetSigma(atof(argv[7]));

  InputBlurType::Pointer mBlur = InputBlurType::New();
  mBlur->SetInput(mReader->GetOutput());
  mBlur->SetSigma(atof(argv[7]));
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Now, we declare and instantiate the \doxygen{otb}{FineCorrelationImageFilter} which is going to perform the registration:
  //
  // Software Guide : EndLatex

  //Create the filter
  // Software Guide : BeginCodeSnippet
  typedef otb::FineRegistrationImageFilter<InputImageType,
      CorrelationImageType,
      DeformationFieldType>
  RegistrationFilterType;

  RegistrationFilterType::Pointer registrator = RegistrationFilterType::New();

  registrator->SetMovingInput(mBlur->GetOutput());
  registrator->SetFixedInput(fBlur->GetOutput());
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Some parameters need to be specified to the filter:
  // \begin{itemize}
  // \item The area where the search is performed. This area is defined by its radius:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef RegistrationFilterType::SizeType RadiusType;

  RadiusType searchRadius;

  searchRadius[0] = atoi(argv[8]);
  searchRadius[1] = atoi(argv[8]);

  registrator->SetSearchRadius(searchRadius);
// Software Guide : EndCodeSnippet

  std::cout << "Exploration radius " << registrator->GetSearchRadius() << std::endl;

  // Software Guide : BeginLatex
  //
  // \item The window used to compute the local metric. This window is also defined by its radius:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  RadiusType correlationRadius;
  correlationRadius[0] = atoi(argv[9]);
  correlationRadius[1] = atoi(argv[9]);

  registrator->SetRadius(correlationRadius);
// Software Guide : EndCodeSnippet

  std::cout << "Correlation radius " << registrator->GetRadius() << std::endl;

  // Software Guide : BeginLatex
  //
  // We need to set the sub-pixel accuracy we want to obtain:
  //
  // Software Guide : EndLatex
  registrator->SetSubPixelAccuracy(atof(argv[10]));

  // Software Guide : BeginLatex
  //
  // The default matching metric used by the \doxygen{FineRegistrationImageFilter} is standard correlation.
  // However, we may also use any other image-to-image metric provided by ITK. For instance, here is how we
  // would use the \doxygen{itk}{MutualInformationImageToImageMetric} (do not forget to include the proper header).
  //
  // Software Guide : EndLatex

  if(argc > 11)
      {
      // Software Guide : BeginCodeSnippet
      typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<InputImageType,InputImageType> MRSDMetricType;
      MRSDMetricType::Pointer mrsdMetric = MRSDMetricType::New();
      registrator->SetMetric(mrsdMetric);
      // Software Guide : EndCodeSnippet

      // Software Guide : BeginLatex
      //
      // The \doxygen{itk}{MutualInformationImageToImageMetric} produces low value for poor matches, therefore, the filter has
      // to maximize the metric :
      //
      // Software Guide : EndLatex

      // Software Guide : BeginCodeSnippet
      registrator->MinimizeOff();
      // Software Guide : EndCodeSnippet
      }

  // Software Guide : BeginLatex
  //
  // \end{itemize}
  // The execution of the \doxygen{otb}{FineRegistrationImageFilter} will be triggered by
  // the \code{Update()} call on the writer at the end of the
  // pipeline. Make sure to use a
  // \doxygen{otb}{StreamingImageFileWriter} if you want to benefit
  // from the streaming features.
  //
  // Software Guide : EndLatex

  typedef otb::ImageOfVectorsToMonoChannelExtractROI<DeformationFieldType,
      InputImageType>
  ChannelExtractionFilterType;
  ChannelExtractionFilterType::Pointer channelExtractor =
    ChannelExtractionFilterType::New();

  channelExtractor->SetInput(registrator->GetOutputDeformationField());
  channelExtractor->SetChannel(1);

  typedef itk::RescaleIntensityImageFilter<InputImageType,
      OutputImageType> RescalerType;
  RescalerType::Pointer fieldRescaler = RescalerType::New();

  fieldRescaler->SetInput(channelExtractor->GetOutput());
  fieldRescaler->SetOutputMaximum(255);
  fieldRescaler->SetOutputMinimum(0);

  typedef otb::StreamingImageFileWriter<OutputImageType> DFWriterType;

  DFWriterType::Pointer dfWriter = DFWriterType::New();
  dfWriter->SetFileName(argv[3]);
  dfWriter->SetInput(fieldRescaler->GetOutput());
  dfWriter->Update();

  channelExtractor->SetChannel(2);
  dfWriter->SetFileName(argv[4]);
  dfWriter->Update();

  typedef itk::WarpImageFilter<InputImageType, InputImageType,
      DeformationFieldType> WarperType;
  WarperType::Pointer warper = WarperType::New();

  InputImageType::PixelType padValue = 4.0;

  warper->SetInput(mReader->GetOutput());
  warper->SetDeformationField(registrator->GetOutputDeformationField());
  warper->SetEdgePaddingValue(padValue);

  typedef itk::RescaleIntensityImageFilter<CorrelationImageType,
        OutputImageType> CorrelationRescalerType;

  CorrelationRescalerType::Pointer correlationRescaler = CorrelationRescalerType::New();
  correlationRescaler->SetInput(registrator->GetOutput());
  correlationRescaler->SetOutputMinimum(0);
  correlationRescaler->SetOutputMaximum(255);

  typedef otb::StreamingImageFileWriter<OutputImageType> WriterType;

  WriterType::Pointer writer1 = WriterType::New();
  writer1->SetInput(correlationRescaler->GetOutput());
  writer1->SetFileName(argv[5]);
  writer1->Update();

  typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType;
  CastFilterType::Pointer caster =  CastFilterType::New();
  caster->SetInput(warper->GetOutput());

  WriterType::Pointer writer2 = WriterType::New();
  writer2->SetFileName(argv[6]);
  writer2->SetInput(caster->GetOutput());
  writer2->Update();

  // Software Guide : BeginLatex
  //
  // Figure~\ref{fig:FineCorrelationImageFilterOUTPUT} shows the result of
  // applying the \doxygen{otb}{FineCorrelationImageFilter}.
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.30\textwidth]{StereoFixed.eps}
  // \includegraphics[width=0.30\textwidth]{StereoMoving.eps}\\
  // \includegraphics[width=0.30\textwidth]{fcDeformationFieldOutput-horizontal.eps}
  // \includegraphics[width=0.30\textwidth]{fcDeformationFieldOutput-vertical.eps}\\
  // \includegraphics[width=0.30\textwidth]{fcCorrelFieldOutput.eps}
  // \includegraphics[width=0.30\textwidth]{fcDResampledOutput2.eps}\\
  // \includegraphics[width=0.30\textwidth]{fcMRSDDeformationFieldOutput-horizontal.eps}
  // \includegraphics[width=0.30\textwidth]{fcMRSDDeformationFieldOutput-vertical.eps}\\
  // \includegraphics[width=0.30\textwidth]{fcMRSDCorrelFieldOutput.eps}
  // \includegraphics[width=0.30\textwidth]{fcMRSDDResampledOutput2.eps}
  // \itkcaption[Deformation field and resampling from fine correlation registration]{From left
  // to right and top to bottom: fixed input image, moving image with a low stereo angle,
  //  estimated deformation fields in both direction using correlation,
  // local correlation field, resampled image based on correlation,
  // estimated deformation fields in both direction using mean reciprocal square difference,
  // local mean reciprocal square difference field, resampled image based on mean reciprocal square difference.
  // }
  // \label{fig:FineCorrelationImageFilterOUTPUT}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*
 * File:   compare-01.cpp
 * Author: CarlosVRL
 *
 * Created on April 16, 2017, 1:32 PM
 */

#include <iostream>     // std::cout, cin
#include <algorithm>    // std::sort
#include <vector>       // std::vector

using namespace std;

int main()
{
    // Task 3: Augment the program so that it writes the line
    // the numbers are almost equal after (only) if they are equal

    // Initialize empty array
    vector<int> numbers;

    // Temporary integer container (from input)
    int temp;

    // While loop conditional variable
    string go = "";

    // Reads input until "|" is entered at repeat prompt
    while (go != "|")
    {
        // Read integer to vector
        cout << "Give me an int: ";
        cin >> temp;
        numbers.push_back(temp);

        // Read another integer to vector
        cout << "Give me another int: ";
        cin >> temp;
        numbers.push_back(temp);

        // Print both input integers to screen
        cout << "You gave me: " << numbers[0] << " and " << numbers[1] << endl;

        // Sort the vector and print sorted
        sort(numbers.begin(),numbers.end());

        // Case: Values are relative
        if (numbers[0] == numbers[1])
        {
            cout << "the numbers are equal" << endl;
        } else
        {
            cout << "the smaller value us: " << numbers[0] << endl;
            cout << "the larger value is: " << numbers[1] << endl;
        }

        // Clear vector for next loop
        numbers.clear();

        // Recursion
        cout << "Enter '|' to exit, or enter any other character to continue: ";
        cin >> go;
    }

    return 0;
}<commit_msg>Step 4<commit_after>/*
 * File:   compare-01.cpp
 * Author: CarlosVRL
 *
 * Created on April 16, 2017, 1:32 PM
 */

#include <iostream>     // std::cout, cin
#include <algorithm>    // std::sort
#include <vector>       // std::vector

using namespace std;

int main()
{
    /*
     * Step 4: Change the program so that it uses doubles instead
     * of ints
     */

    // Initialize empty array
    vector<double> numbers;

    // Temporary integer container (from input)
    double temp;

    // While loop conditional variable
    string go = "";

    // Reads input until "|" is entered at repeat prompt
    while (go != "|")
    {
        // Read integer to vector
        cout << "Give me a double: ";
        cin >> temp;
        numbers.push_back(temp);

        // Read another integer to vector
        cout << "Give me another double: ";
        cin >> temp;
        numbers.push_back(temp);

        // Print both input integers to screen
        cout << "You gave me: " << numbers[0] << " and " << numbers[1] << endl;

        // Sort the vector and print sorted
        sort(numbers.begin(),numbers.end());

        if (numbers[0] == numbers[1]) // values are relative
        {
            cout << "the numbers are equal" << endl;
        }
        else // values are equal
        {
            cout << "the smaller value us: " << numbers[0] << endl;
            cout << "the larger value is: " << numbers[1] << endl;
        }

        // Clear vector for next loop
        numbers.clear();

        // Recursion
        cout << "Enter '|' to exit, or enter any other character to continue: ";
        cin >> go;
    }

    return 0;
}<|endoftext|>


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

#include "DefaultVisualizer.h"

#include "ModelBase/src/nodes/Node.h"

#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/overlays/ArrowOverlay.h"
#include "VisualizationBase/src/overlays/SelectionOverlay.h"

#include "../graph/Graph.h"
#include "../graph/InformationEdge.h"
#include "../graph/InformationNode.h"

namespace InformationScripting {

const QString DefaultVisualizer::HIGHLIGHT_OVERLAY_GROUP = {"default graph highlight"};
const QString DefaultVisualizer::ARROW_OVERLAY_GROUP = {"default arrow"};

DefaultVisualizer& DefaultVisualizer::instance()
{
	static DefaultVisualizer instance;
	return instance;
}

void DefaultVisualizer::visualize(Graph* g)
{
	QList<InformationEdge*> edges = g->edges();
	if (!edges.empty())
	{
		// First check if all edges are of the same type
		QString edgeName = edges[0]->name();
		bool isSame = std::all_of(edges.begin(), edges.end(),
										  [edgeName](InformationEdge *e) {return e->name() == edgeName;});
		if (isSame)
		{
			// TODO for now we assume directed
			for (auto edge : edges)
			{
				auto from = edge->from();
				auto to = edge->to();
				// TODO for now we just support nodes that have AST property
				Q_ASSERT(from->contains("ast"));
				Q_ASSERT(to->contains("ast"));

				Model::Node* fromNode = (*from)["ast"];
				Model::Node* toNode = (*to)["ast"];
				auto fromVisualization = Visualization::Item::nodeItemsMap().find(fromNode);
				Q_ASSERT(fromVisualization != Visualization::Item::nodeItemsMap().end());
				auto toVisualization = Visualization::Item::nodeItemsMap().find(toNode);
				Q_ASSERT(toVisualization != Visualization::Item::nodeItemsMap().end());
				auto fromVisualizationItem = *fromVisualization;

				auto overlay = new Visualization::ArrowOverlay(
							fromVisualizationItem, *toVisualization, Visualization::ArrowOverlay::itemStyles().get());
				fromVisualizationItem->addOverlay(overlay, ARROW_OVERLAY_GROUP);
			}
		}
		else
		{
			// TODO
		}
	}
	else
	{
		auto condition = [](const InformationNode* node) {
			return node->contains("ast");
		};
		auto nodes = g->nodes(condition);

		for (auto informationNode : nodes)
		{
			Model::Node* node = (*informationNode)["ast"];
			auto nodeVisualization = Visualization::Item::nodeItemsMap().find(node);
			Q_ASSERT(nodeVisualization != Visualization::Item::nodeItemsMap().end());
			auto item = *nodeVisualization;

			QString styleArg;
			auto colorIt = informationNode->find("color");
			if (colorIt != informationNode->end()) styleArg = colorIt->second.operator QString();

			auto overlay = new Visualization::SelectionOverlay(
						item, Visualization::SelectionOverlay::itemStyles().get(styleArg));
			item->addOverlay(overlay, HIGHLIGHT_OVERLAY_GROUP);
		}
	}
}

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

#include "DefaultVisualizer.h"

#include "ModelBase/src/nodes/Node.h"

#include "VisualizationBase/src/Scene.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/overlays/ArrowOverlay.h"
#include "VisualizationBase/src/overlays/SelectionOverlay.h"

#include "../graph/Graph.h"
#include "../graph/InformationEdge.h"
#include "../graph/InformationNode.h"

namespace InformationScripting {

const QString DefaultVisualizer::HIGHLIGHT_OVERLAY_GROUP = {"default graph highlight"};
const QString DefaultVisualizer::ARROW_OVERLAY_GROUP = {"default arrow"};

DefaultVisualizer& DefaultVisualizer::instance()
{
	static DefaultVisualizer instance;
	return instance;
}

void DefaultVisualizer::visualize(Graph* g)
{
	// First remove all existing overlays:
	for (auto scene : Visualization::Scene::allScenes())
	{
		scene->removeOverlayGroup(HIGHLIGHT_OVERLAY_GROUP);
		scene->removeOverlayGroup(ARROW_OVERLAY_GROUP);
	}
	// Now draw the new stuff
	QList<InformationEdge*> edges = g->edges();
	if (!edges.empty())
	{
		// First check if all edges are of the same type
		QString edgeName = edges[0]->name();
		bool isSame = std::all_of(edges.begin(), edges.end(),
										  [edgeName](InformationEdge *e) {return e->name() == edgeName;});
		if (isSame)
		{
			// TODO for now we assume directed
			for (auto edge : edges)
			{
				auto from = edge->from();
				auto to = edge->to();
				// TODO for now we just support nodes that have AST property
				Q_ASSERT(from->contains("ast"));
				Q_ASSERT(to->contains("ast"));

				Model::Node* fromNode = (*from)["ast"];
				Model::Node* toNode = (*to)["ast"];
				auto fromVisualization = Visualization::Item::nodeItemsMap().find(fromNode);
				Q_ASSERT(fromVisualization != Visualization::Item::nodeItemsMap().end());
				auto toVisualization = Visualization::Item::nodeItemsMap().find(toNode);
				Q_ASSERT(toVisualization != Visualization::Item::nodeItemsMap().end());
				auto fromVisualizationItem = *fromVisualization;

				auto overlay = new Visualization::ArrowOverlay(
							fromVisualizationItem, *toVisualization, Visualization::ArrowOverlay::itemStyles().get());
				fromVisualizationItem->addOverlay(overlay, ARROW_OVERLAY_GROUP);
			}
		}
		else
		{
			// TODO
		}
	}
	else
	{
		auto condition = [](const InformationNode* node) {
			return node->contains("ast");
		};
		auto nodes = g->nodes(condition);

		for (auto informationNode : nodes)
		{
			Model::Node* node = (*informationNode)["ast"];
			auto nodeVisualization = Visualization::Item::nodeItemsMap().find(node);
			Q_ASSERT(nodeVisualization != Visualization::Item::nodeItemsMap().end());
			auto item = *nodeVisualization;

			QString styleArg;
			auto colorIt = informationNode->find("color");
			if (colorIt != informationNode->end()) styleArg = colorIt->second.operator QString();

			auto overlay = new Visualization::SelectionOverlay(
						item, Visualization::SelectionOverlay::itemStyles().get(styleArg));
			item->addOverlay(overlay, HIGHLIGHT_OVERLAY_GROUP);
		}
	}
}

} /* namespace InformationScripting */
<|endoftext|>