<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/url_request_fetch_job.h"

#include <algorithm>

#include "atom/browser/atom_browser_context.h"
#include "base/strings/string_util.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_response_writer.h"
#include "net/url_request/url_request_status.h"

namespace atom {

namespace {

// Convert string to RequestType.
net::URLFetcher::RequestType GetRequestType(const std::string& raw) {
  std::string method = StringToUpperASCII(raw);
  if (method.empty() || method == "GET")
    return net::URLFetcher::GET;
  else if (method == "POST")
    return net::URLFetcher::POST;
  else if (method == "HEAD")
    return net::URLFetcher::HEAD;
  else if (method == "DELETE")
    return net::URLFetcher::DELETE_REQUEST;
  else if (method == "PUT")
    return net::URLFetcher::PUT;
  else if (method == "PATCH")
    return net::URLFetcher::PATCH;
  else  // Use "GET" as fallback.
    return net::URLFetcher::GET;
}

// Pipe the response writer back to URLRequestFetchJob.
class ResponsePiper : public net::URLFetcherResponseWriter {
 public:
  explicit ResponsePiper(URLRequestFetchJob* job)
      : first_write_(true), job_(job) {}

  // net::URLFetcherResponseWriter:
  int Initialize(const net::CompletionCallback& callback) override {
    return net::OK;
  }
  int Write(net::IOBuffer* buffer,
            int num_bytes,
            const net::CompletionCallback& callback) override {
    if (first_write_) {
      // The URLFetcherResponseWriter doesn't have an event when headers have
      // been read, so we have to emulate by hooking to first write event.
      job_->HeadersCompleted();
      first_write_ = false;
    }
    return job_->DataAvailable(buffer, num_bytes);
  }
  int Finish(const net::CompletionCallback& callback) override {
    return net::OK;
  }

 private:
  bool first_write_;
  URLRequestFetchJob* job_;

  DISALLOW_COPY_AND_ASSIGN(ResponsePiper);
};

}  // namespace

URLRequestFetchJob::URLRequestFetchJob(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    const GURL& url,
    const std::string& method)
    : net::URLRequestJob(request, network_delegate),
      fetcher_(net::URLFetcher::Create(url, GetRequestType(method), this)),
      pending_buffer_size_(0) {
  auto context = AtomBrowserContext::Get()->url_request_context_getter();
  fetcher_->SetRequestContext(context);
  fetcher_->SaveResponseWithWriter(make_scoped_ptr(new ResponsePiper(this)));
}

void URLRequestFetchJob::HeadersCompleted() {
  response_info_.reset(new net::HttpResponseInfo);
  response_info_->headers = fetcher_->GetResponseHeaders();
  NotifyHeadersComplete();
}

int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes) {
  // Clear the IO_PENDING status.
  SetStatus(net::URLRequestStatus());
  // Do nothing if pending_buffer_ is empty, i.e. there's no ReadRawData()
  // operation waiting for IO completion.
  if (!pending_buffer_.get())
    return net::ERR_IO_PENDING;;

  // pending_buffer_ is set to the IOBuffer instance provided to ReadRawData()
  // by URLRequestJob.

  int bytes_read = std::min(num_bytes, pending_buffer_size_);
  memcpy(pending_buffer_->data(), buffer->data(), bytes_read);

  // Clear the buffers before notifying the read is complete, so that it is
  // safe for the observer to read.
  pending_buffer_ = nullptr;
  pending_buffer_size_ = 0;

  NotifyReadComplete(bytes_read);
  return bytes_read;
}

void URLRequestFetchJob::Start() {
  fetcher_->Start();
}

void URLRequestFetchJob::Kill() {
  URLRequestJob::Kill();
  fetcher_.reset();
}

bool URLRequestFetchJob::ReadRawData(net::IOBuffer* dest,
                                     int dest_size,
                                     int* bytes_read) {
  pending_buffer_ = dest;
  pending_buffer_size_ = dest_size;
  SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0));
  return false;
}

bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const {
  if (!response_info_)
    return false;

  return response_info_->headers->GetMimeType(mime_type);
}

void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) {
  if (response_info_)
    *info = *response_info_;
}

int URLRequestFetchJob::GetResponseCode() const {
  if (!response_info_)
    return -1;

  return response_info_->headers->response_code();
}

void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) {
  pending_buffer_ = nullptr;
  pending_buffer_size_ = 0;
  NotifyDone(fetcher_->GetStatus());
  if (fetcher_->GetStatus().is_success())
    NotifyReadComplete(0);
}

}  // namespace atom
<commit_msg>Use |request|'s method if |method| is not specified<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/url_request_fetch_job.h"

#include <algorithm>

#include "atom/browser/atom_browser_context.h"
#include "base/strings/string_util.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_response_writer.h"
#include "net/url_request/url_request_status.h"

namespace atom {

namespace {

// Convert string to RequestType.
net::URLFetcher::RequestType GetRequestType(const std::string& raw) {
  std::string method = StringToUpperASCII(raw);
  if (method.empty() || method == "GET")
    return net::URLFetcher::GET;
  else if (method == "POST")
    return net::URLFetcher::POST;
  else if (method == "HEAD")
    return net::URLFetcher::HEAD;
  else if (method == "DELETE")
    return net::URLFetcher::DELETE_REQUEST;
  else if (method == "PUT")
    return net::URLFetcher::PUT;
  else if (method == "PATCH")
    return net::URLFetcher::PATCH;
  else  // Use "GET" as fallback.
    return net::URLFetcher::GET;
}

// Pipe the response writer back to URLRequestFetchJob.
class ResponsePiper : public net::URLFetcherResponseWriter {
 public:
  explicit ResponsePiper(URLRequestFetchJob* job)
      : first_write_(true), job_(job) {}

  // net::URLFetcherResponseWriter:
  int Initialize(const net::CompletionCallback& callback) override {
    return net::OK;
  }
  int Write(net::IOBuffer* buffer,
            int num_bytes,
            const net::CompletionCallback& callback) override {
    if (first_write_) {
      // The URLFetcherResponseWriter doesn't have an event when headers have
      // been read, so we have to emulate by hooking to first write event.
      job_->HeadersCompleted();
      first_write_ = false;
    }
    return job_->DataAvailable(buffer, num_bytes);
  }
  int Finish(const net::CompletionCallback& callback) override {
    return net::OK;
  }

 private:
  bool first_write_;
  URLRequestFetchJob* job_;

  DISALLOW_COPY_AND_ASSIGN(ResponsePiper);
};

}  // namespace

URLRequestFetchJob::URLRequestFetchJob(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    const GURL& url,
    const std::string& method)
    : net::URLRequestJob(request, network_delegate),
      pending_buffer_size_(0) {
  // Use |request|'s method if |method| is not specified.
  net::URLFetcher::RequestType request_type;
  if (method.empty())
    request_type = GetRequestType(request->method());
  else
    request_type = GetRequestType(method);

  fetcher_.reset(net::URLFetcher::Create(url, request_type, this));
  auto context = AtomBrowserContext::Get()->url_request_context_getter();
  fetcher_->SetRequestContext(context);
  fetcher_->SaveResponseWithWriter(make_scoped_ptr(new ResponsePiper(this)));
}

void URLRequestFetchJob::HeadersCompleted() {
  response_info_.reset(new net::HttpResponseInfo);
  response_info_->headers = fetcher_->GetResponseHeaders();
  NotifyHeadersComplete();
}

int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes) {
  // Clear the IO_PENDING status.
  SetStatus(net::URLRequestStatus());
  // Do nothing if pending_buffer_ is empty, i.e. there's no ReadRawData()
  // operation waiting for IO completion.
  if (!pending_buffer_.get())
    return net::ERR_IO_PENDING;;

  // pending_buffer_ is set to the IOBuffer instance provided to ReadRawData()
  // by URLRequestJob.

  int bytes_read = std::min(num_bytes, pending_buffer_size_);
  memcpy(pending_buffer_->data(), buffer->data(), bytes_read);

  // Clear the buffers before notifying the read is complete, so that it is
  // safe for the observer to read.
  pending_buffer_ = nullptr;
  pending_buffer_size_ = 0;

  NotifyReadComplete(bytes_read);
  return bytes_read;
}

void URLRequestFetchJob::Start() {
  fetcher_->Start();
}

void URLRequestFetchJob::Kill() {
  URLRequestJob::Kill();
  fetcher_.reset();
}

bool URLRequestFetchJob::ReadRawData(net::IOBuffer* dest,
                                     int dest_size,
                                     int* bytes_read) {
  pending_buffer_ = dest;
  pending_buffer_size_ = dest_size;
  SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0));
  return false;
}

bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const {
  if (!response_info_)
    return false;

  return response_info_->headers->GetMimeType(mime_type);
}

void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) {
  if (response_info_)
    *info = *response_info_;
}

int URLRequestFetchJob::GetResponseCode() const {
  if (!response_info_)
    return -1;

  return response_info_->headers->response_code();
}

void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) {
  pending_buffer_ = nullptr;
  pending_buffer_size_ = 0;
  NotifyDone(fetcher_->GetStatus());
  if (fetcher_->GetStatus().is_success())
    NotifyReadComplete(0);
}

}  // namespace atom
<|endoftext|>


<commit_before>#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, const int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        int j;
        for(j = i; j >= 0 && data[j] < data[i]; --j);
        swap(data[i], data[j]);
    }
}

<commit_msg>Fix the logic of Insertion sort which is not working<commit_after>#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, const int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        for(int j = i; j > 0 && data[j] < data[j - 1]; --j) swap(data[j], data[j - 1]);
    }
}

<|endoftext|>


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

#include "mediatoolbox.hxx"
#include "mediaitem.hxx"
#include "mediacontrol.hxx"

#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/sfxsids.hrc>

using namespace ::com::sun::star;

namespace avmedia
{

// -----------------------
// - MediaToolboxControl -
// -----------------------

class MediaToolBoxControl_Impl : public MediaControl
{
public:

                            MediaToolBoxControl_Impl( Window& rParent, MediaToolBoxControl& rControl );
                            ~MediaToolBoxControl_Impl();

    void                    update();
    void                    execute( const MediaItem& rItem );

private:

    MediaToolBoxControl*    mpToolBoxControl;
};

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

MediaToolBoxControl_Impl::MediaToolBoxControl_Impl( Window& rParent, MediaToolBoxControl& rControl ) :
    MediaControl( &rParent, MEDIACONTROLSTYLE_SINGLELINE ),
    mpToolBoxControl( &rControl )
{
    SetSizePixel( getMinSizePixel() );
}

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

MediaToolBoxControl_Impl::~MediaToolBoxControl_Impl()
{
}

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

void MediaToolBoxControl_Impl::update()
{
    mpToolBoxControl->implUpdateMediaControl();
}

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

void MediaToolBoxControl_Impl::execute( const MediaItem& rItem )
{
    mpToolBoxControl->implExecuteMediaControl( rItem );
}

// -----------------------
// - MediaToolBoxControl -
// -----------------------

SFX_IMPL_TOOLBOX_CONTROL( ::avmedia::MediaToolBoxControl, ::avmedia::MediaItem );

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

MediaToolBoxControl::MediaToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
    SfxToolBoxControl( nSlotId, nId, rTbx )
{
        rTbx.Invalidate();
}

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

MediaToolBoxControl::~MediaToolBoxControl()
{
}

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

void MediaToolBoxControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )

{
    MediaToolBoxControl_Impl* pCtrl = static_cast< MediaToolBoxControl_Impl* >( GetToolBox().GetItemWindow( GetId() ) );

    DBG_ASSERT( pCtrl, "MediaToolBoxControl::StateChanged: media control not found" );

    if( eState == SFX_ITEM_DISABLED )
    {
        pCtrl->Enable( false, false );
        pCtrl->SetText( String() );

        const MediaItem aEmptyMediaItem( 0, AVMEDIA_SETMASK_ALL );
        pCtrl->setState( aEmptyMediaItem );
    }
    else
    {
        pCtrl->Enable( true, false );

        const MediaItem* pMediaItem = PTR_CAST( MediaItem, pState );

        if( pMediaItem && ( SFX_ITEM_AVAILABLE == eState ) )
            pCtrl->setState( *pMediaItem );
    }
}

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

Window* MediaToolBoxControl::CreateItemWindow( Window *pParent )
{
    return( pParent ? new MediaToolBoxControl_Impl( *pParent, *this ) : NULL );
}

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

void MediaToolBoxControl::implUpdateMediaControl()
{
    updateStatus( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:AVMediaToolBox" ) ) );
}

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

void MediaToolBoxControl::implExecuteMediaControl( const MediaItem& rItem )
{
    MediaItem                               aExecItem( SID_AVMEDIA_TOOLBOX );
    uno::Sequence< beans::PropertyValue >   aArgs( 1 );
    uno::Any                                aAny;

    aExecItem.merge( rItem );
    aExecItem.QueryValue( aAny );
    aArgs[ 0 ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "AVMediaToolBox" ) );
    aArgs[ 0 ].Value = aAny;

    Dispatch( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:AVMediaToolBox" ) ), aArgs );
}

}
<commit_msg>INTEGRATION: CWS warnings01 (1.3.22); FILE MERGED 2005/11/28 12:46:25 cl 1.3.22.1: warning free code fixes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mediatoolbox.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 13:58:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "mediatoolbox.hxx"
#include "mediaitem.hxx"
#include "mediacontrol.hxx"

#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/sfxsids.hrc>

using namespace ::com::sun::star;

namespace avmedia
{

// -----------------------
// - MediaToolboxControl -
// -----------------------

class MediaToolBoxControl_Impl : public MediaControl
{
public:

                            MediaToolBoxControl_Impl( Window& rParent, MediaToolBoxControl& rControl );
                            ~MediaToolBoxControl_Impl();

    void                    update();
    void                    execute( const MediaItem& rItem );

private:

    MediaToolBoxControl*    mpToolBoxControl;
};

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

MediaToolBoxControl_Impl::MediaToolBoxControl_Impl( Window& rParent, MediaToolBoxControl& rControl ) :
    MediaControl( &rParent, MEDIACONTROLSTYLE_SINGLELINE ),
    mpToolBoxControl( &rControl )
{
    SetSizePixel( getMinSizePixel() );
}

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

MediaToolBoxControl_Impl::~MediaToolBoxControl_Impl()
{
}

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

void MediaToolBoxControl_Impl::update()
{
    mpToolBoxControl->implUpdateMediaControl();
}

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

void MediaToolBoxControl_Impl::execute( const MediaItem& rItem )
{
    mpToolBoxControl->implExecuteMediaControl( rItem );
}

// -----------------------
// - MediaToolBoxControl -
// -----------------------

SFX_IMPL_TOOLBOX_CONTROL( ::avmedia::MediaToolBoxControl, ::avmedia::MediaItem );

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

MediaToolBoxControl::MediaToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
    SfxToolBoxControl( nSlotId, nId, rTbx )
{
        rTbx.Invalidate();
}

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

MediaToolBoxControl::~MediaToolBoxControl()
{
}

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

void MediaToolBoxControl::StateChanged( USHORT /* nSID */, SfxItemState eState, const SfxPoolItem* pState )

{
    MediaToolBoxControl_Impl* pCtrl = static_cast< MediaToolBoxControl_Impl* >( GetToolBox().GetItemWindow( GetId() ) );

    DBG_ASSERT( pCtrl, "MediaToolBoxControl::StateChanged: media control not found" );

    if( eState == SFX_ITEM_DISABLED )
    {
        pCtrl->Enable( false, false );
        pCtrl->SetText( String() );

        const MediaItem aEmptyMediaItem( 0, AVMEDIA_SETMASK_ALL );
        pCtrl->setState( aEmptyMediaItem );
    }
    else
    {
        pCtrl->Enable( true, false );

        const MediaItem* pMediaItem = PTR_CAST( MediaItem, pState );

        if( pMediaItem && ( SFX_ITEM_AVAILABLE == eState ) )
            pCtrl->setState( *pMediaItem );
    }
}

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

Window* MediaToolBoxControl::CreateItemWindow( Window *pParent )
{
    return( pParent ? new MediaToolBoxControl_Impl( *pParent, *this ) : NULL );
}

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

void MediaToolBoxControl::implUpdateMediaControl()
{
    updateStatus( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:AVMediaToolBox" ) ) );
}

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

void MediaToolBoxControl::implExecuteMediaControl( const MediaItem& rItem )
{
    MediaItem                               aExecItem( SID_AVMEDIA_TOOLBOX );
    uno::Sequence< beans::PropertyValue >   aArgs( 1 );
    uno::Any                                aAny;

    aExecItem.merge( rItem );
    aExecItem.QueryValue( aAny );
    aArgs[ 0 ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "AVMediaToolBox" ) );
    aArgs[ 0 ].Value = aAny;

    Dispatch( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:AVMediaToolBox" ) ), aArgs );
}

}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "localqmlprofilerrunner.h"
#include "qmlprofilerplugin.h"

using namespace QmlProfiler;
using namespace QmlProfiler::Internal;

LocalQmlProfilerRunner::LocalQmlProfilerRunner(const Configuration &configuration, QObject *parent) :
    AbstractQmlProfilerRunner(parent),
    m_configuration(configuration)
{
    connect(&m_launcher, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
            this, SIGNAL(appendMessage(QString,Utils::OutputFormat)));
}

void LocalQmlProfilerRunner::start()
{
    QString arguments = QString("-qmljsdebugger=port:%1,block").arg(
                QString::number(m_configuration.port));

    if (!m_configuration.executableArguments.isEmpty())
        arguments += QChar(' ') + m_configuration.executableArguments;

    if (QmlProfilerPlugin::debugOutput)
        qWarning("QmlProfiler: Launching %s:%d", qPrintable(m_configuration.executable),
                 m_configuration.port);

    m_launcher.setWorkingDirectory(m_configuration.workingDirectory);
    m_launcher.setEnvironment(m_configuration.environment);
    connect(&m_launcher, SIGNAL(processExited(int)), this, SLOT(spontaneousStop(int)));
    m_launcher.start(ProjectExplorer::ApplicationLauncher::Gui, m_configuration.executable,
                     arguments);

    emit started();
}

void LocalQmlProfilerRunner::spontaneousStop(int exitCode)
{
    if (QmlProfilerPlugin::debugOutput)
        qWarning() << "QmlProfiler: Application exited (exit code" << exitCode << ").";

    disconnect(&m_launcher, SIGNAL(processExited(int)), this, SLOT(spontaneousStop(int)));

    emit stopped();
}

void LocalQmlProfilerRunner::stop()
{
    if (QmlProfilerPlugin::debugOutput)
        qWarning() << "QmlProfiler: Stopping application ...";

    if (m_launcher.isRunning()) {
        m_launcher.stop();
    }
}
<commit_msg>Compile Windows.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "localqmlprofilerrunner.h"
#include "qmlprofilerplugin.h"

using namespace QmlProfiler;
using namespace QmlProfiler::Internal;

LocalQmlProfilerRunner::LocalQmlProfilerRunner(const Configuration &configuration, QObject *parent) :
    AbstractQmlProfilerRunner(parent),
    m_configuration(configuration)
{
    connect(&m_launcher, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
            this, SIGNAL(appendMessage(QString,Utils::OutputFormat)));
}

void LocalQmlProfilerRunner::start()
{
    QString arguments = QString("-qmljsdebugger=port:%1,block").arg(
                QString::number(m_configuration.port));

    if (!m_configuration.executableArguments.isEmpty())
        arguments += QChar(' ') + m_configuration.executableArguments;

    if (QmlProfilerPlugin::debugOutput)
        qWarning("QmlProfiler: Launching %s:%d", qPrintable(m_configuration.executable),
                 m_configuration.port);

    m_launcher.setWorkingDirectory(m_configuration.workingDirectory);
    m_launcher.setEnvironment(m_configuration.environment);
    connect(&m_launcher, SIGNAL(processExited(int)), this, SLOT(spontaneousStop(int)));
    m_launcher.start(ProjectExplorer::ApplicationLauncher::Gui, m_configuration.executable,
                     arguments);

    emit started();
}

void LocalQmlProfilerRunner::spontaneousStop(int exitCode)
{
    if (QmlProfilerPlugin::debugOutput)
        qWarning("QmlProfiler: Application exited (exit code %d).", exitCode);

    disconnect(&m_launcher, SIGNAL(processExited(int)), this, SLOT(spontaneousStop(int)));

    emit stopped();
}

void LocalQmlProfilerRunner::stop()
{
    if (QmlProfilerPlugin::debugOutput)
        qWarning("QmlProfiler: Stopping application ...");

    if (m_launcher.isRunning()) {
        m_launcher.stop();
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp

#include <NDK/Systems/VelocitySystem.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp>

namespace Ndk
{
	/*!
	* \ingroup NDK
	* \class Ndk::VelocitySystem
	* \brief NDK class that represents the velocity system
	*
	* \remark This system is enabled if the entity owns the trait: NodeComponent and VelocityComponent
	* but it's disabled with the trait: PhysicsComponent3D
	*/

	/*!
	* \brief Constructs an VelocitySystem object by default
	*/

	VelocitySystem::VelocitySystem()
	{
		Excludes<PhysicsComponent3D>();
		Requires<NodeComponent, VelocityComponent>();
		SetUpdateOrder(10); //< Since some systems may want to stop us
	}

	/*!
	* \brief Operation to perform when system is updated
	*
	* \param elapsedTime Delta time used for the update
	*/

	void VelocitySystem::OnUpdate(float elapsedTime)
	{
		for (const Ndk::EntityHandle& entity : GetEntities())
		{
			NodeComponent& node = entity->GetComponent<NodeComponent>();
			const VelocityComponent& velocity = entity->GetComponent<VelocityComponent>();

			node.Move(velocity.linearVelocity * elapsedTime, Nz::CoordSys_Global);
		}
	}

	SystemIndex VelocitySystem::systemIndex;
}
<commit_msg>SDK/Systems: Disable VelocitySystem if PhysicsComponent2D is present<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp

#include <NDK/Systems/VelocitySystem.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp>

namespace Ndk
{
	/*!
	* \ingroup NDK
	* \class Ndk::VelocitySystem
	* \brief NDK class that represents the velocity system
	*
	* \remark This system is enabled if the entity owns the traits NodeComponent and VelocityComponent
	* but it's disabled with the traits: PhysicsComponent2D, PhysicsComponent3D
	*/

	/*!
	* \brief Constructs an VelocitySystem object by default
	*/

	VelocitySystem::VelocitySystem()
	{
		Excludes<PhysicsComponent2D, PhysicsComponent3D>();
		Requires<NodeComponent, VelocityComponent>();
		SetUpdateOrder(10); //< Since some systems may want to stop us
	}

	/*!
	* \brief Operation to perform when system is updated
	*
	* \param elapsedTime Delta time used for the update
	*/

	void VelocitySystem::OnUpdate(float elapsedTime)
	{
		for (const Ndk::EntityHandle& entity : GetEntities())
		{
			NodeComponent& node = entity->GetComponent<NodeComponent>();
			const VelocityComponent& velocity = entity->GetComponent<VelocityComponent>();

			node.Move(velocity.linearVelocity * elapsedTime, Nz::CoordSys_Global);
		}
	}

	SystemIndex VelocitySystem::systemIndex;
}
<|endoftext|>


<commit_before>inline
opt_feat::opt_feat(const std::string in_path,
		   const std::string in_actionNames,
		   const int in_col,
		   const int in_row,
		   const int in_scale_factor,
		   const int in_shift,
		   const int in_scene, //only for kth
		   const int in_dim
)
:path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim)
{

  actions.load( actionNames );
  //dim = 14;
  //dim = 12; //Action Recognition from Video Using feature Covariance Matrices
}

inline
void
opt_feat::features_all_videos( field<string> all_people )
{
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

  field <std::string> load_save_names (n_peo*n_actions,3);
  int sc = total_scene; //Solo estoy usando 1
  int k =0;

  for (int pe = 0; pe< n_peo; ++pe)
  {
    for (int act=0; act<n_actions; ++act)
    {
      std::stringstream ss_video_name;
      ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi";

      std::stringstream save_folder;
      std::stringstream save_feat_video_i;
      std::stringstream save_labels_video_i;

      save_folder << "./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
      save_feat_video_i   << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
      save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

      load_save_names(k,0) = ss_video_name.str();
      load_save_names(k,1) = save_feat_video_i.str();
      load_save_names(k,2) = save_labels_video_i.str();
      k++;

    }
  }

  //int nProcessors=omp_get_max_threads();
  //std::cout<<nProcessors<<std::endl;
  //std::cout<< omp_get_num_threads()<<std::endl;

  wall_clock timer;
  timer.tic();
  omp_set_num_threads(5); //Use only 10 processors

  #pragma omp parallel for
  for (int i = 0; i<load_save_names.n_rows; ++i)
  {

    std::string one_video = load_save_names(i,0);
    int tid=omp_get_thread_num();

    #pragma omp critical
    cout<< "Processor " << tid <<" doing "<< one_video << endl;

    Struct_feat_lab my_Struct_feat_lab;

    feature_video( one_video, my_Struct_feat_lab );
    mat mat_features_video_i;
    vec lab_video_i;

    if (my_Struct_feat_lab.features_video_i.size()>0)
    {
      mat_features_video_i.zeros( dim,my_Struct_feat_lab.features_video_i.size() );
      lab_video_i.zeros( my_Struct_feat_lab.features_video_i.size() );
      for (uword i = 0; i < my_Struct_feat_lab.features_video_i.size(); ++i)
      {
	mat_features_video_i.col(i) = my_Struct_feat_lab.features_video_i.at(i)/norm(my_Struct_feat_lab.features_video_i.at(i),2);
	lab_video_i(i) = my_Struct_feat_lab.labels_video_i.at(i);
      }
    }
    else
    {
      mat_features_video_i.zeros(dim,0);
    }

    std::string save_feat_video_i   = load_save_names(i,1);
    std::string save_labels_video_i = load_save_names(i,2);

    mat_features_video_i.save( save_feat_video_i, hdf5_binary );
    lab_video_i.save( save_labels_video_i, hdf5_binary );
  }

  double n = timer.toc();
  cout << "number of seconds NO parallel : " << n << endl;

}

// //****************** Feature Extraction**************************************
// //***************************************************************************

inline
void
opt_feat::feature_video( std::string one_video, Struct_feat_lab &my_Struct_feat_lab )
{

  my_Struct_feat_lab.features_video_i.clear();
  my_Struct_feat_lab.labels_video_i.clear();

  int new_row = row;
  int new_col = col;

  cv::VideoCapture capVideo(one_video);
  int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT);

  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }

  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  cv::Mat flow_xy[2], mag, ang;

  string text;

  for(int fr=0; fr<n_frames; fr++){

    //cout << fr << " " ;

    bool bSuccess = capVideo.read(frame); // read a new frame from video

    if (!bSuccess) //if not success, break loop
    {
      cout << "Cannot read the frame from video file" << endl;
      break;
    }

    if (scale_factor!=1)
    {
      new_row = row*scale_factor;
      new_col = col*scale_factor;
      cv::resize( frame, frame, cv::Size(new_row, new_col) );
    }

    cv::cvtColor(frame, gray, CV_BGR2GRAY);

    if( prevgray.data )
    {
      //cout << t << " " ;
      cv::calcOpticalFlowFarneback(prevgray,
				   gray,
				   flow,
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags

      //optical flow
      cv::split(flow, flow_xy);
      cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true);

      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);

      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;

      if( prevflow.data )
      {
	//cout << new_col << " " << new_row << endl;

	for (int x = 0 ; x < new_col ; ++x ){
	  for (int y = 0 ; y < new_row ; ++y ) {

	    vec features_one_pixel(dim);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];

	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);

	    // grad direction &  grad magnitude. (Edges)
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);

	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);

	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];

	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }

	    float Div = (ux + vy);
	    float Vor = (vx - uy);
	    //Adding more features
	    mat G (2,2);
	    mat S;
	    float gd_opflow = ang.at<float>(y,x);
	    float mg_opflow = mag.at<float>(y,x);
	    //Gradient Tensor
	    G   << ux << uy << endr
	    << vx << vy << endr;

	    //Rate of Stein Tensor
	    S = 0.5*(G + G.t());

	    float tr_G = trace(G);
	    float tr_G2 = trace( square(G) );
	    float tr_S = trace(S);
	    float tr_S2 = trace(square(S));

	    //Tensor Invariants  of the optical flow
	    float Gten = 0.5*( tr_G*tr_G - tr_G2 );
	    float Sten = 0.5*( tr_S*tr_S - tr_S2 );

	    if (dim ==12)
	    {
	      features_one_pixel  << x       << y       << fr   << gm  << u    << v
	      << abs(ut) << abs(vt) << Div  << Vor << Gten << Sten;
	    }

	    if (dim ==14)
	    {

	      features_one_pixel  << x << y << abs(ix) << abs(iy) << abs(ixx)
	      << abs(iyy) << gm << gd <<  u << v << abs(ut)
	      << abs(vt) << (ux + vy)  << (vx - uy);
	    }

	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar();
	    }
	    // Plotting Moving pixels
	    //cout << " " << gm;

	    double is_zero = accu(abs(features_one_pixel));

	    if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40
	    {

	      frame.at<cv::Vec3b>(y,x)[0] = 0;
	      frame.at<cv::Vec3b>(y,x)[1] = 0;
	      frame.at<cv::Vec3b>(y,x)[2] = 255;
	      my_Struct_feat_lab.features_video_i.push_back(features_one_pixel);
	      my_Struct_feat_lab.labels_video_i.push_back( fr );
	    }
	  }
	}
      }

      if(cv::waitKey(30)>=0)
	break;

    }

    std::swap(prevgray, gray);
    std::swap(prevflow, flow);

    //cv::imshow("color", frame);
    //cv::waitKey(1);

  }

}<commit_msg>No parallel<commit_after>inline
opt_feat::opt_feat(const std::string in_path,
		   const std::string in_actionNames,
		   const int in_col,
		   const int in_row,
		   const int in_scale_factor,
		   const int in_shift,
		   const int in_scene, //only for kth
		   const int in_dim
)
:path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim)
{

  actions.load( actionNames );
  //dim = 14;
  //dim = 12; //Action Recognition from Video Using feature Covariance Matrices
}

inline
void
opt_feat::features_all_videos( field<string> all_people )
{
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

  field <std::string> load_save_names (n_peo*n_actions,3);
  int sc = total_scene; //Solo estoy usando 1
  int k =0;

  for (int pe = 0; pe< n_peo; ++pe)
  {
    for (int act=0; act<n_actions; ++act)
    {
      std::stringstream ss_video_name;
      ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi";

      std::stringstream save_folder;
      std::stringstream save_feat_video_i;
      std::stringstream save_labels_video_i;

      save_folder << "./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
      save_feat_video_i   << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
      save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

      load_save_names(k,0) = ss_video_name.str();
      load_save_names(k,1) = save_feat_video_i.str();
      load_save_names(k,2) = save_labels_video_i.str();
      k++;

    }
  }

  //int nProcessors=omp_get_max_threads();
  //std::cout<<nProcessors<<std::endl;
  //std::cout<< omp_get_num_threads()<<std::endl;

  wall_clock timer;
  timer.tic();
  //omp_set_num_threads(5); //Use only 10 processors

  //#pragma omp parallel for
  for (int i = 0; i<load_save_names.n_rows; ++i)
  {

    std::string one_video = load_save_names(i,0);
    int tid=omp_get_thread_num();

    //#pragma omp critical
    cout<< "Processor " << tid <<" doing "<< one_video << endl;

    Struct_feat_lab my_Struct_feat_lab;

    feature_video( one_video, my_Struct_feat_lab );
    mat mat_features_video_i;
    vec lab_video_i;

    if (my_Struct_feat_lab.features_video_i.size()>0)
    {
      mat_features_video_i.zeros( dim,my_Struct_feat_lab.features_video_i.size() );
      lab_video_i.zeros( my_Struct_feat_lab.features_video_i.size() );
      for (uword i = 0; i < my_Struct_feat_lab.features_video_i.size(); ++i)
      {
	mat_features_video_i.col(i) = my_Struct_feat_lab.features_video_i.at(i)/norm(my_Struct_feat_lab.features_video_i.at(i),2);
	lab_video_i(i) = my_Struct_feat_lab.labels_video_i.at(i);
      }
    }
    else
    {
      mat_features_video_i.zeros(dim,0);
    }

    std::string save_feat_video_i   = load_save_names(i,1);
    std::string save_labels_video_i = load_save_names(i,2);

    mat_features_video_i.save( save_feat_video_i, hdf5_binary );
    lab_video_i.save( save_labels_video_i, hdf5_binary );
  }

  double n = timer.toc();
  cout << "number of seconds NO parallel : " << n << endl;

}

// //****************** Feature Extraction**************************************
// //***************************************************************************

inline
void
opt_feat::feature_video( std::string one_video, Struct_feat_lab &my_Struct_feat_lab )
{

  my_Struct_feat_lab.features_video_i.clear();
  my_Struct_feat_lab.labels_video_i.clear();

  int new_row = row;
  int new_col = col;

  cv::VideoCapture capVideo(one_video);
  int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT);

  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }

  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  cv::Mat flow_xy[2], mag, ang;

  string text;

  for(int fr=0; fr<n_frames; fr++){

    //cout << fr << " " ;

    bool bSuccess = capVideo.read(frame); // read a new frame from video

    if (!bSuccess) //if not success, break loop
    {
      cout << "Cannot read the frame from video file" << endl;
      break;
    }

    if (scale_factor!=1)
    {
      new_row = row*scale_factor;
      new_col = col*scale_factor;
      cv::resize( frame, frame, cv::Size(new_row, new_col) );
    }

    cv::cvtColor(frame, gray, CV_BGR2GRAY);

    if( prevgray.data )
    {
      //cout << t << " " ;
      cv::calcOpticalFlowFarneback(prevgray,
				   gray,
				   flow,
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags

      //optical flow
      cv::split(flow, flow_xy);
      cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true);

      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);

      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;

      if( prevflow.data )
      {
	//cout << new_col << " " << new_row << endl;

	for (int x = 0 ; x < new_col ; ++x ){
	  for (int y = 0 ; y < new_row ; ++y ) {

	    vec features_one_pixel(dim);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];

	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);

	    // grad direction &  grad magnitude. (Edges)
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);

	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);

	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];

	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }

	    float Div = (ux + vy);
	    float Vor = (vx - uy);
	    //Adding more features
	    mat G (2,2);
	    mat S;
	    float gd_opflow = ang.at<float>(y,x);
	    float mg_opflow = mag.at<float>(y,x);
	    //Gradient Tensor
	    G   << ux << uy << endr
	    << vx << vy << endr;

	    //Rate of Stein Tensor
	    S = 0.5*(G + G.t());

	    float tr_G = trace(G);
	    float tr_G2 = trace( square(G) );
	    float tr_S = trace(S);
	    float tr_S2 = trace(square(S));

	    //Tensor Invariants  of the optical flow
	    float Gten = 0.5*( tr_G*tr_G - tr_G2 );
	    float Sten = 0.5*( tr_S*tr_S - tr_S2 );

	    if (dim ==12)
	    {
	      features_one_pixel  << x       << y       << fr   << gm  << u    << v
	      << abs(ut) << abs(vt) << Div  << Vor << Gten << Sten;
	    }

	    if (dim ==14)
	    {

	      features_one_pixel  << x << y << abs(ix) << abs(iy) << abs(ixx)
	      << abs(iyy) << gm << gd <<  u << v << abs(ut)
	      << abs(vt) << (ux + vy)  << (vx - uy);
	    }

	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar();
	    }
	    // Plotting Moving pixels
	    //cout << " " << gm;

	    double is_zero = accu(abs(features_one_pixel));

	    if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40
	    {

	      frame.at<cv::Vec3b>(y,x)[0] = 0;
	      frame.at<cv::Vec3b>(y,x)[1] = 0;
	      frame.at<cv::Vec3b>(y,x)[2] = 255;
	      my_Struct_feat_lab.features_video_i.push_back(features_one_pixel);
	      my_Struct_feat_lab.labels_video_i.push_back( fr );
	    }
	  }
	}
      }

      if(cv::waitKey(30)>=0)
	break;

    }

    std::swap(prevgray, gray);
    std::swap(prevflow, flow);

    //cv::imshow("color", frame);
    //cv::waitKey(1);

  }

}<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/modelselection/ParameterCombination.h>
#include <shogun/base/Parameter.h>
#include <shogun/machine/Machine.h>

using namespace shogun;

CParameterCombination::CParameterCombination()
{
	init();
}

CParameterCombination::CParameterCombination(Parameter* param)
{
	init();

	m_param=param;
}

void CParameterCombination::init()
{
	m_param=NULL;
	m_child_nodes=new CDynamicObjectArray<CParameterCombination> ();
	SG_REF(m_child_nodes);

	m_parameters->add((CSGObject**)m_child_nodes, "child nodes",
			"children of this node");
}

CParameterCombination::~CParameterCombination()
{
	delete m_param;
	SG_UNREF(m_child_nodes);
}

void CParameterCombination::append_child(CParameterCombination* child)
{
	m_child_nodes->append_element(child);
}

void CParameterCombination::print_tree(int prefix_num) const
{
	/* prefix is enlarged */
	char* prefix=SG_MALLOC(char, prefix_num+1);
	for (index_t i=0; i<prefix_num; ++i)
		prefix[i]='\t';

	prefix[prefix_num]='\0';

	/* cases:
	 * -node with a Parameter instance and a possible children
	 * -root node with children
	 */

	if (m_param)
	{
		SG_SPRINT("%s", prefix);
		for (index_t i=0; i<m_param->get_num_parameters(); ++i)
		{
			/* distinction between sgobject and values */
			if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_SGOBJECT)
			{
				TParameter* param=m_param->get_parameter(i);
				CSGObject* current_sgobject=*((CSGObject**) param->m_parameter);
				SG_SPRINT("\"%s\":%s at %p ", param->m_name,
						current_sgobject->get_name(), current_sgobject);
			}
			else
			{
				SG_SPRINT("\"%s\"=%f ", m_param->get_parameter(i)->m_name,
						*((float64_t*)m_param->get_parameter(i)->m_parameter));
			}
		}

	}
	else
		SG_SPRINT("%sroot", prefix);

	SG_SPRINT("\n");

	for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
	{
		CParameterCombination* child=m_child_nodes->get_element(i);
		child->print_tree(prefix_num+1);
		SG_UNREF(child);
	}

	SG_FREE(prefix);
}

DynArray<Parameter*>* CParameterCombination::parameter_set_multiplication(
		const DynArray<Parameter*>& set_1, const DynArray<Parameter*>& set_2)
{
	DynArray<Parameter*>* result=new DynArray<Parameter*>();

	for (index_t i=0; i<set_1.get_num_elements(); ++i)
	{
		for (index_t j=0; j<set_2.get_num_elements(); ++j)
		{
			Parameter* p=new Parameter();
			p->add_parameters(set_1[i]);
			p->add_parameters(set_2[j]);
			result->append_element(p);
		}
	}

	return result;
}

CDynamicObjectArray<CParameterCombination>* CParameterCombination::leaf_sets_multiplication(
		const CDynamicObjectArray<CDynamicObjectArray<CParameterCombination> >& sets,
		const CParameterCombination* new_root)
{
	CDynamicObjectArray<CParameterCombination>* result=new CDynamicObjectArray<
			CParameterCombination>();

	/* check marginal cases */
	if (sets.get_num_elements()==1)
	{
		CDynamicObjectArray<CParameterCombination>* current_set=
				sets.get_element(0);

		/* just use the only element into result array.
		 * put root node before all combinations*/
		*result=*current_set;

		SG_UNREF(current_set);

		for (index_t i=0; i<result->get_num_elements(); ++i)
		{
			/* put new root as root into the tree and replace tree */
			CParameterCombination* current=result->get_element(i);
			CParameterCombination* root=new_root->copy_tree();
			root->append_child(current);
			result->set_element(root, i);
			SG_UNREF(current);
		}
	}
	else if (sets.get_num_elements()>1)
	{
		/* now the case where at least two sets are given */

		/* first, extract Parameter instances of given sets */
		DynArray<DynArray<Parameter*>*> param_sets;

		for (index_t set_nr=0; set_nr<sets.get_num_elements(); ++set_nr)
		{
			CDynamicObjectArray<CParameterCombination>* current_set=
					sets.get_element(set_nr);
			DynArray<Parameter*>* new_param_set=new DynArray<Parameter*> ();
			param_sets.append_element(new_param_set);

			for (index_t i=0; i<current_set->get_num_elements(); ++i)
			{
				CParameterCombination* current_node=current_set->get_element(i);

				if (current_node->m_child_nodes->get_num_elements())
				{
					SG_SERROR("leaf sets multiplication only possible if all "
							"trees are leafs");
				}

				Parameter* current_param=current_node->m_param;

				if (current_param)
					new_param_set->append_element(current_param);
				else
				{
					SG_SERROR("leaf sets multiplication only possible if all "
							"leafs have non-NULL Parameter instances\n");
				}

				SG_UNREF(current_node);
			}

			SG_UNREF(current_set);
		}

		/* second, build products of all parameter sets */
		DynArray<Parameter*>* param_product=parameter_set_multiplication(
				*param_sets[0], *param_sets[1]);

		delete param_sets[0];
		delete param_sets[1];

		/* build product of all remaining sets and collect results. delete all
		 * parameter instances of interim products*/
		for (index_t i=2; i<param_sets.get_num_elements(); ++i)
		{
			DynArray<Parameter*>* old_temp_result=param_product;
			param_product=parameter_set_multiplication(*param_product,
					*param_sets[i]);

			/* delete interim result parameter instances */
			for (index_t j=0; j<old_temp_result->get_num_elements(); ++j)
				delete old_temp_result->get_element(j);

			/* and dyn arrays of interim result and of param_sets */
			delete old_temp_result;
			delete param_sets[i];
		}

		/* at this point there is only one DynArray instance remaining:
		 * param_product. contains all combinations of parameters of all given
		 * sets */

		/* third, build tree sets with the given root and the parameter product
		 * elements */
		for (index_t i=0; i<param_product->get_num_elements(); ++i)
		{
			/* build parameter node from parameter product to append to root */
			CParameterCombination* param_node=new CParameterCombination(
					param_product->get_element(i));

			/* copy new root node, has to be a new one each time */
			CParameterCombination* root=new_root->copy_tree();

			/* append both and add them to result set */
			root->append_child(param_node);
			result->append_element(root);
		}

		/* this is not needed anymore, because the Parameter instances are now
		 * in the resulting tree sets */
		delete param_product;
	}

	return result;
}

CParameterCombination* CParameterCombination::copy_tree() const
{
	CParameterCombination* copy=new CParameterCombination();

	/* but build new Parameter instance */

	/* only call add_parameters() argument is non-null */
	if (m_param)
	{
		copy->m_param=new Parameter();
		copy->m_param->add_parameters(m_param);
	} else
		copy->m_param=NULL;

	/* recursively copy all children */
	for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
	{
		CParameterCombination* child=m_child_nodes->get_element(i);
		copy->m_child_nodes->append_element(child->copy_tree());
		SG_UNREF(child);
	}

	return copy;
}

void CParameterCombination::apply_to_machine(CMachine* machine) const
{
	apply_to_parameter(machine->m_parameters);
}

void CParameterCombination::apply_to_parameter(Parameter* parameter) const
{
	/* case root node or name node */
	if (!m_param)
	{
		/* iterate over all children and recursively set parameters from
		 * their values to the current parameter input (its just handed one
		 * recursion level downwards) */
		for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
		{
			CParameterCombination* child=m_child_nodes->get_element(i);
			child->apply_to_parameter(parameter);
			SG_UNREF(child);
		}
	}
	/* case parameter node */
	else if (m_param)
	{
		/* does this node has sub parameters? */
		if (has_children())
		{
			/* if a parameter node has children, it has to have ONE CSGObject as
			 * parameter */
			if (m_param->get_num_parameters()>1 ||
					m_param->get_parameter(0)->m_datatype.m_ptype!=PT_SGOBJECT)
			{
				SG_SERROR("invalid CParameterCombination node type, has children"
						" and more than one parameter or is not a "
						"CSGObject.\n");
			}

			/* cast is now safe */
			CSGObject* current_sgobject=
					*((CSGObject**)(m_param->get_parameter(0)->m_parameter));

			/* set parameters */
			parameter->set_from_parameters(m_param);

			/* iterate over all children and recursively set parameters from
			 * their values */
			for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
			{
				CParameterCombination* child=m_child_nodes->get_element(i);
				child->apply_to_parameter(current_sgobject->m_parameters);
				SG_UNREF(child);
			}
		}
		else
			parameter->set_from_parameters(m_param);
	}
	else
		SG_SERROR("CParameterCombination node has illegal type.\n");

}
<commit_msg>print method now handles different data types<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/modelselection/ParameterCombination.h>
#include <shogun/base/Parameter.h>
#include <shogun/machine/Machine.h>

using namespace shogun;

CParameterCombination::CParameterCombination()
{
	init();
}

CParameterCombination::CParameterCombination(Parameter* param)
{
	init();

	m_param=param;
}

void CParameterCombination::init()
{
	m_param=NULL;
	m_child_nodes=new CDynamicObjectArray<CParameterCombination> ();
	SG_REF(m_child_nodes);

	m_parameters->add((CSGObject**)m_child_nodes, "child nodes",
			"children of this node");
}

CParameterCombination::~CParameterCombination()
{
	delete m_param;
	SG_UNREF(m_child_nodes);
}

void CParameterCombination::append_child(CParameterCombination* child)
{
	m_child_nodes->append_element(child);
}

void CParameterCombination::print_tree(int prefix_num) const
{
	/* prefix is enlarged */
	char* prefix=SG_MALLOC(char, prefix_num+1);
	for (index_t i=0; i<prefix_num; ++i)
		prefix[i]='\t';

	prefix[prefix_num]='\0';

	/* cases:
	 * -node with a Parameter instance and a possible children
	 * -root node with children
	 */

	if (m_param)
	{
		SG_SPRINT("%s", prefix);
		for (index_t i=0; i<m_param->get_num_parameters(); ++i)
		{
			/* distinction between sgobject and values */
			if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_SGOBJECT)
			{
				TParameter* param=m_param->get_parameter(i);
				CSGObject* current_sgobject=*((CSGObject**) param->m_parameter);
				SG_SPRINT("\"%s\":%s at %p ", param->m_name,
						current_sgobject->get_name(), current_sgobject);
			}
			else
			{
				SG_SPRINT("\"%s\"=", m_param->get_parameter(i)->m_name);
				void* param=m_param->get_parameter(i)->m_parameter;

				if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_FLOAT64)
					SG_SPRINT("%f ", *((float64_t*)param));
				else if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_INT32)
					SG_SPRINT("%i ", *((int32_t*)param));
				else if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_BOOL)
					SG_SPRINT("%s ", *((bool*)param ? "true" : "false"));
				else
					SG_NOTIMPLEMENTED;
			}

		}

	}
	else
		SG_SPRINT("%sroot", prefix);

	SG_SPRINT("\n");

	for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
	{
		CParameterCombination* child=m_child_nodes->get_element(i);
		child->print_tree(prefix_num+1);
		SG_UNREF(child);
	}

	SG_FREE(prefix);
}

DynArray<Parameter*>* CParameterCombination::parameter_set_multiplication(
		const DynArray<Parameter*>& set_1, const DynArray<Parameter*>& set_2)
{
	DynArray<Parameter*>* result=new DynArray<Parameter*>();

	for (index_t i=0; i<set_1.get_num_elements(); ++i)
	{
		for (index_t j=0; j<set_2.get_num_elements(); ++j)
		{
			Parameter* p=new Parameter();
			p->add_parameters(set_1[i]);
			p->add_parameters(set_2[j]);
			result->append_element(p);
		}
	}

	return result;
}

CDynamicObjectArray<CParameterCombination>* CParameterCombination::leaf_sets_multiplication(
		const CDynamicObjectArray<CDynamicObjectArray<CParameterCombination> >& sets,
		const CParameterCombination* new_root)
{
	CDynamicObjectArray<CParameterCombination>* result=new CDynamicObjectArray<
			CParameterCombination>();

	/* check marginal cases */
	if (sets.get_num_elements()==1)
	{
		CDynamicObjectArray<CParameterCombination>* current_set=
				sets.get_element(0);

		/* just use the only element into result array.
		 * put root node before all combinations*/
		*result=*current_set;

		SG_UNREF(current_set);

		for (index_t i=0; i<result->get_num_elements(); ++i)
		{
			/* put new root as root into the tree and replace tree */
			CParameterCombination* current=result->get_element(i);
			CParameterCombination* root=new_root->copy_tree();
			root->append_child(current);
			result->set_element(root, i);
			SG_UNREF(current);
		}
	}
	else if (sets.get_num_elements()>1)
	{
		/* now the case where at least two sets are given */

		/* first, extract Parameter instances of given sets */
		DynArray<DynArray<Parameter*>*> param_sets;

		for (index_t set_nr=0; set_nr<sets.get_num_elements(); ++set_nr)
		{
			CDynamicObjectArray<CParameterCombination>* current_set=
					sets.get_element(set_nr);
			DynArray<Parameter*>* new_param_set=new DynArray<Parameter*> ();
			param_sets.append_element(new_param_set);

			for (index_t i=0; i<current_set->get_num_elements(); ++i)
			{
				CParameterCombination* current_node=current_set->get_element(i);

				if (current_node->m_child_nodes->get_num_elements())
				{
					SG_SERROR("leaf sets multiplication only possible if all "
							"trees are leafs");
				}

				Parameter* current_param=current_node->m_param;

				if (current_param)
					new_param_set->append_element(current_param);
				else
				{
					SG_SERROR("leaf sets multiplication only possible if all "
							"leafs have non-NULL Parameter instances\n");
				}

				SG_UNREF(current_node);
			}

			SG_UNREF(current_set);
		}

		/* second, build products of all parameter sets */
		DynArray<Parameter*>* param_product=parameter_set_multiplication(
				*param_sets[0], *param_sets[1]);

		delete param_sets[0];
		delete param_sets[1];

		/* build product of all remaining sets and collect results. delete all
		 * parameter instances of interim products*/
		for (index_t i=2; i<param_sets.get_num_elements(); ++i)
		{
			DynArray<Parameter*>* old_temp_result=param_product;
			param_product=parameter_set_multiplication(*param_product,
					*param_sets[i]);

			/* delete interim result parameter instances */
			for (index_t j=0; j<old_temp_result->get_num_elements(); ++j)
				delete old_temp_result->get_element(j);

			/* and dyn arrays of interim result and of param_sets */
			delete old_temp_result;
			delete param_sets[i];
		}

		/* at this point there is only one DynArray instance remaining:
		 * param_product. contains all combinations of parameters of all given
		 * sets */

		/* third, build tree sets with the given root and the parameter product
		 * elements */
		for (index_t i=0; i<param_product->get_num_elements(); ++i)
		{
			/* build parameter node from parameter product to append to root */
			CParameterCombination* param_node=new CParameterCombination(
					param_product->get_element(i));

			/* copy new root node, has to be a new one each time */
			CParameterCombination* root=new_root->copy_tree();

			/* append both and add them to result set */
			root->append_child(param_node);
			result->append_element(root);
		}

		/* this is not needed anymore, because the Parameter instances are now
		 * in the resulting tree sets */
		delete param_product;
	}

	return result;
}

CParameterCombination* CParameterCombination::copy_tree() const
{
	CParameterCombination* copy=new CParameterCombination();

	/* but build new Parameter instance */

	/* only call add_parameters() argument is non-null */
	if (m_param)
	{
		copy->m_param=new Parameter();
		copy->m_param->add_parameters(m_param);
	} else
		copy->m_param=NULL;

	/* recursively copy all children */
	for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
	{
		CParameterCombination* child=m_child_nodes->get_element(i);
		copy->m_child_nodes->append_element(child->copy_tree());
		SG_UNREF(child);
	}

	return copy;
}

void CParameterCombination::apply_to_machine(CMachine* machine) const
{
	apply_to_parameter(machine->m_parameters);
}

void CParameterCombination::apply_to_parameter(Parameter* parameter) const
{
	/* case root node or name node */
	if (!m_param)
	{
		/* iterate over all children and recursively set parameters from
		 * their values to the current parameter input (its just handed one
		 * recursion level downwards) */
		for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
		{
			CParameterCombination* child=m_child_nodes->get_element(i);
			child->apply_to_parameter(parameter);
			SG_UNREF(child);
		}
	}
	/* case parameter node */
	else if (m_param)
	{
		/* does this node has sub parameters? */
		if (has_children())
		{
			/* if a parameter node has children, it has to have ONE CSGObject as
			 * parameter */
			if (m_param->get_num_parameters()>1 ||
					m_param->get_parameter(0)->m_datatype.m_ptype!=PT_SGOBJECT)
			{
				SG_SERROR("invalid CParameterCombination node type, has children"
						" and more than one parameter or is not a "
						"CSGObject.\n");
			}

			/* cast is now safe */
			CSGObject* current_sgobject=
					*((CSGObject**)(m_param->get_parameter(0)->m_parameter));

			/* set parameters */
			parameter->set_from_parameters(m_param);

			/* iterate over all children and recursively set parameters from
			 * their values */
			for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
			{
				CParameterCombination* child=m_child_nodes->get_element(i);
				child->apply_to_parameter(current_sgobject->m_parameters);
				SG_UNREF(child);
			}
		}
		else
			parameter->set_from_parameters(m_param);
	}
	else
		SG_SERROR("CParameterCombination node has illegal type.\n");

}
<|endoftext|>


<commit_before>#include "html.h"
#include "el_text.h"
#include "document.h"
#include "render_item.h"

litehtml::el_text::el_text(const tchar_t* text, const std::shared_ptr<litehtml::document>& doc) : element(doc)
{
	if(text)
	{
		m_text = text;
	}
	m_use_transformed	= false;
	m_draw_spaces		= true;
    css_w().set_display(display_inline_text);
}

void litehtml::el_text::get_content_size( size& sz, int max_width )
{
	sz = m_size;
}

void litehtml::el_text::get_text( tstring& text )
{
	text += m_text;
}

const litehtml::tchar_t* litehtml::el_text::get_style_property( const tchar_t* name, bool inherited, const tchar_t* def /*= 0*/ ) const
{
	if(inherited)
	{
		element::ptr el_parent = parent();
		if (el_parent)
		{
			return el_parent->get_style_property(name, inherited, def);
		}
	}
	return def;
}

void litehtml::el_text::parse_styles(bool is_reparse)
{
    element::ptr el_parent = parent();
    if (el_parent)
    {
        css_w().set_line_height(el_parent->css().get_line_height());
        css_w().set_font(el_parent->css().get_font());
        css_w().set_font_metrics(el_parent->css().get_font_metrics());
        css_w().set_white_space(el_parent->css().get_white_space());
    }
    css_w().set_display(display_inline_text);
    css_w().set_float(float_none);

	if(m_css.get_text_transform() != text_transform_none)
	{
		m_transformed_text	= m_text;
		m_use_transformed = true;
		get_document()->container()->transform_text(m_transformed_text, m_css.get_text_transform());
	}

    element::ptr p = parent();
    while(p && p->css().get_display() == display_inline)
    {
        if(p->css().get_position() == element_position_relative)
        {
            css_w().set_offsets(p->css().get_offsets());
            css_w().set_position(element_position_relative);
            break;
        }
        p = p->parent();
    }
    if(p)
    {
        css_w().set_position(element_position_static);
    }

	if(is_white_space())
	{
		m_transformed_text = _t(" ");
		m_use_transformed = true;
	} else
	{
		if(m_text == _t("\t"))
		{
			m_transformed_text = _t("    ");
			m_use_transformed = true;
		}
		if(m_text == _t("\n") || m_text == _t("\r"))
		{
			m_transformed_text = _t("");
			m_use_transformed = true;
		}
	}

	font_metrics fm;
	uint_ptr font = 0;
	if (el_parent)
	{
		font = el_parent->css().get_font();
        fm = el_parent->css().get_font_metrics();
	}
	if(is_break())
	{
		m_size.height	= 0;
		m_size.width	= 0;
	} else
	{
		m_size.height	= fm.height;
		m_size.width	= get_document()->container()->text_width(m_use_transformed ? m_transformed_text.c_str() : m_text.c_str(), font);
	}
	m_draw_spaces = fm.draw_spaces;
}

void litehtml::el_text::draw(uint_ptr hdc, int x, int y, const position *clip, const std::shared_ptr<render_item> &ri)
{
	if(is_white_space() && !m_draw_spaces)
	{
		return;
	}

	position pos = ri->pos();
	pos.x	+= x;
	pos.y	+= y;

	if(pos.does_intersect(clip))
	{
		element::ptr el_parent = parent();
		if (el_parent)
		{
			document::ptr doc = get_document();

			uint_ptr font = el_parent->css().get_font();
			litehtml::web_color color = el_parent->get_color(_t("color"), true, doc->get_def_color());
			doc->container()->draw_text(hdc, m_use_transformed ? m_transformed_text.c_str() : m_text.c_str(), font, color, pos);
		}
	}
}

litehtml::tstring litehtml::el_text::dump_get_name()
{
    return _t("text: \"") + get_escaped_string(m_text) + _t("\"");
}

std::vector<std::tuple<litehtml::tstring, litehtml::tstring>> litehtml::el_text::dump_get_attrs()
{
    return std::vector<std::tuple<litehtml::tstring, litehtml::tstring>>();
}
<commit_msg>fix missing text-transform<commit_after>#include "html.h"
#include "el_text.h"
#include "document.h"
#include "render_item.h"

litehtml::el_text::el_text(const tchar_t* text, const std::shared_ptr<litehtml::document>& doc) : element(doc)
{
	if(text)
	{
		m_text = text;
	}
	m_use_transformed	= false;
	m_draw_spaces		= true;
    css_w().set_display(display_inline_text);
}

void litehtml::el_text::get_content_size( size& sz, int max_width )
{
	sz = m_size;
}

void litehtml::el_text::get_text( tstring& text )
{
	text += m_text;
}

const litehtml::tchar_t* litehtml::el_text::get_style_property( const tchar_t* name, bool inherited, const tchar_t* def /*= 0*/ ) const
{
	if(inherited)
	{
		element::ptr el_parent = parent();
		if (el_parent)
		{
			return el_parent->get_style_property(name, inherited, def);
		}
	}
	return def;
}

void litehtml::el_text::parse_styles(bool is_reparse)
{
    element::ptr el_parent = parent();
    if (el_parent)
    {
        css_w().set_line_height(el_parent->css().get_line_height());
        css_w().set_font(el_parent->css().get_font());
        css_w().set_font_metrics(el_parent->css().get_font_metrics());
        css_w().set_white_space(el_parent->css().get_white_space());
		css_w().set_text_transform(el_parent->css().get_text_transform());
    }
    css_w().set_display(display_inline_text);
    css_w().set_float(float_none);

	if(m_css.get_text_transform() != text_transform_none)
	{
		m_transformed_text	= m_text;
		m_use_transformed = true;
		get_document()->container()->transform_text(m_transformed_text, m_css.get_text_transform());
	} else
	{
		m_use_transformed = false;
	}

    element::ptr p = parent();
    while(p && p->css().get_display() == display_inline)
    {
        if(p->css().get_position() == element_position_relative)
        {
            css_w().set_offsets(p->css().get_offsets());
            css_w().set_position(element_position_relative);
            break;
        }
        p = p->parent();
    }
    if(p)
    {
        css_w().set_position(element_position_static);
    }

	if(is_white_space())
	{
		m_transformed_text = _t(" ");
		m_use_transformed = true;
	} else
	{
		if(m_text == _t("\t"))
		{
			m_transformed_text = _t("    ");
			m_use_transformed = true;
		}
		if(m_text == _t("\n") || m_text == _t("\r"))
		{
			m_transformed_text = _t("");
			m_use_transformed = true;
		}
	}

	font_metrics fm;
	uint_ptr font = 0;
	if (el_parent)
	{
		font = el_parent->css().get_font();
        fm = el_parent->css().get_font_metrics();
	}
	if(is_break())
	{
		m_size.height	= 0;
		m_size.width	= 0;
	} else
	{
		m_size.height	= fm.height;
		m_size.width	= get_document()->container()->text_width(m_use_transformed ? m_transformed_text.c_str() : m_text.c_str(), font);
	}
	m_draw_spaces = fm.draw_spaces;
}

void litehtml::el_text::draw(uint_ptr hdc, int x, int y, const position *clip, const std::shared_ptr<render_item> &ri)
{
	if(is_white_space() && !m_draw_spaces)
	{
		return;
	}

	position pos = ri->pos();
	pos.x	+= x;
	pos.y	+= y;

	if(pos.does_intersect(clip))
	{
		element::ptr el_parent = parent();
		if (el_parent)
		{
			document::ptr doc = get_document();

			uint_ptr font = el_parent->css().get_font();
			litehtml::web_color color = el_parent->get_color(_t("color"), true, doc->get_def_color());
			doc->container()->draw_text(hdc, m_use_transformed ? m_transformed_text.c_str() : m_text.c_str(), font, color, pos);
		}
	}
}

litehtml::tstring litehtml::el_text::dump_get_name()
{
    return _t("text: \"") + get_escaped_string(m_text) + _t("\"");
}

std::vector<std::tuple<litehtml::tstring, litehtml::tstring>> litehtml::el_text::dump_get_attrs()
{
    return std::vector<std::tuple<litehtml::tstring, litehtml::tstring>>();
}
<|endoftext|>


<commit_before>#include "renderer.hpp"

#include "random.hpp"

#include <glm/gtc/constants.hpp>
#include <glm/gtx/rotate_vector.hpp>

#include <iostream>

namespace trac0r {
// #pragma omp declare simd // TODO make this work
glm::vec4 Renderer::trace_pixel_color(const unsigned x, const unsigned y, const unsigned max_depth,
                                      const Camera &camera, const Scene &scene) {
    glm::vec2 rel_pos = Camera::screenspace_to_camspace(camera, x, y);

    // Subpixel sampling / antialiasing
    glm::vec2 pixel_size = Camera::pixel_size(camera);
    glm::vec2 jitter = {rand_range(-pixel_size.x / 2.f, pixel_size.x / 2.f),
                        rand_range(-pixel_size.y / 2.f, pixel_size.y / 2.f)};
    rel_pos += jitter;

    glm::vec3 world_pos = Camera::camspace_to_worldspace(camera, rel_pos);
    glm::vec3 ray_dir = glm::normalize(world_pos - Camera::pos(camera));

    Ray next_ray{world_pos, ray_dir};
    glm::vec3 return_color{0};
    glm::vec3 albedo{1};

    // Russian Roulette
    size_t depth = 0;

    // We'll run until terminated by Russian Roulette
    while (true) {
        // Russian Roulette
        float continuation_probability = 1.f - (1.f / (max_depth - depth));
        // float continuation_probability = (albedo.x + albedo.y + albedo.z) / 3.f;
        if (rand_range(0.f, 1.0f) >= continuation_probability) {
            break;
        }
        depth++;

        auto intersect_info = Scene::intersect(scene, next_ray);
        if (intersect_info.m_has_intersected) {
            // Emitter Material
            if (intersect_info.m_material.m_type == 1) {
                return_color = albedo * intersect_info.m_material.m_color *
                               intersect_info.m_material.m_emittance / continuation_probability;
            }

            // Diffuse Material
            else if (intersect_info.m_material.m_type == 2) {
                // Find normal in correct direction
                intersect_info.m_normal =
                    intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between);
                intersect_info.m_angle_between =
                    intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between);

                // Find new random direction for diffuse reflection
                glm::vec3 new_ray_dir = oriented_uniform_hemisphere_sample(intersect_info.m_normal);

                // Get angle between new random ray direction and the surface's normal
                float cos_theta = glm::dot(new_ray_dir, intersect_info.m_normal);

                albedo *= 2.f * intersect_info.m_material.m_color * cos_theta;

                // Make a new ray
                next_ray = Ray{intersect_info.m_pos, new_ray_dir};
            }

            // Glass Material
            if (intersect_info.m_material.m_type == 3) {
                float n1, n2;

                if (intersect_info.m_angle_between > 0) {
                    // Ray in inside the object
                    n1 = intersect_info.m_material.m_ior;
                    n2 = 1.0003f;

                    intersect_info.m_normal = -intersect_info.m_normal;
                } else {
                    // Ray is outside the object
                    n1 = 1.0003f;
                    n2 = intersect_info.m_material.m_ior;

                    intersect_info.m_angle_between = -intersect_info.m_angle_between;
                }

                float n = n1 / n2;

                float cos_t =
                    1.f - glm::pow(n, 2) * (1.f - glm::pow(intersect_info.m_angle_between, 2));

                glm::vec3 new_ray_dir;
                // Handle total internal reflection
                if (cos_t < 0.f) {
                    new_ray_dir = intersect_info.m_incoming_ray.m_dir -
                                  (2.f * intersect_info.m_angle_between * intersect_info.m_normal);
                    next_ray = Ray{intersect_info.m_pos, new_ray_dir};
                    break;
                }

                cos_t = glm::sqrt(cos_t);

                // Fresnel coefficients
                float r1 = n1 * intersect_info.m_angle_between - n2 * cos_t;
                float r2 = n1 * intersect_info.m_angle_between + n2 * cos_t;
                float r3 = n2 * intersect_info.m_angle_between - n1 * cos_t;
                float r4 = n2 * intersect_info.m_angle_between + n1 * cos_t;
                float r = glm::pow(r1 / r2, 2) + glm::pow(r3 / r4, 2) * 0.5f;

                if (rand_range(0.f, 1.f) < r) {
                    // Reflection
                    new_ray_dir = intersect_info.m_incoming_ray.m_dir -
                                  (2.f * intersect_info.m_angle_between * intersect_info.m_normal);
                    albedo *= intersect_info.m_material.m_color;
                } else {
                    // Refraction
                    new_ray_dir = intersect_info.m_incoming_ray.m_dir * (n1 / n2) +
                                  intersect_info.m_normal *
                                      ((n1 / n2) * intersect_info.m_angle_between - cos_t);
                    albedo *= 1.f;
                }

                // Make a new ray
                next_ray = Ray{intersect_info.m_pos, new_ray_dir};
            }

            // Glossy Material
            else if (intersect_info.m_material.m_type == 4) {
                // Find normal in correct direction
                intersect_info.m_normal =
                    intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between);
                intersect_info.m_angle_between =
                    intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between);

                float real_roughness =
                    intersect_info.m_material.m_roughness * glm::half_pi<float>();

                // Find new direction for reflection
                glm::vec3 reflected_dir =
                    intersect_info.m_incoming_ray.m_dir -
                    (2.f * intersect_info.m_angle_between * intersect_info.m_normal);

                // Find new random direction on cone for glossy reflection
                glm::vec3 new_ray_dir = oriented_uniform_cone_sample(reflected_dir, real_roughness);

                albedo *= intersect_info.m_material.m_color;

                // Make a new ray
                next_ray = Ray{intersect_info.m_pos, new_ray_dir};
            }
        } else {
            break;
        }
    }

    return glm::vec4(return_color, 1.f);
}
}
<commit_msg>Rename albedo to luminance to be physically accurate in terminology terms<commit_after>#include "renderer.hpp"

#include "random.hpp"

#include <glm/gtc/constants.hpp>
#include <glm/gtx/rotate_vector.hpp>

#include <iostream>

namespace trac0r {
// #pragma omp declare simd // TODO make this work
glm::vec4 Renderer::trace_pixel_color(const unsigned x, const unsigned y, const unsigned max_depth,
                                      const Camera &camera, const Scene &scene) {
    glm::vec2 rel_pos = Camera::screenspace_to_camspace(camera, x, y);

    // Subpixel sampling / antialiasing
    glm::vec2 pixel_size = Camera::pixel_size(camera);
    glm::vec2 jitter = {rand_range(-pixel_size.x / 2.f, pixel_size.x / 2.f),
                        rand_range(-pixel_size.y / 2.f, pixel_size.y / 2.f)};
    rel_pos += jitter;

    glm::vec3 world_pos = Camera::camspace_to_worldspace(camera, rel_pos);
    glm::vec3 ray_dir = glm::normalize(world_pos - Camera::pos(camera));

    Ray next_ray{world_pos, ray_dir};
    glm::vec3 return_color{0};
    glm::vec3 luminance{1};

    // Russian Roulette
    size_t depth = 0;

    // We'll run until terminated by Russian Roulette
    while (true) {
        // Russian Roulette
        float continuation_probability = 1.f - (1.f / (max_depth - depth));
        // float continuation_probability = (luminance.x + luminance.y + luminance.z) / 3.f;
        if (rand_range(0.f, 1.0f) >= continuation_probability) {
            break;
        }
        depth++;

        auto intersect_info = Scene::intersect(scene, next_ray);
        if (intersect_info.m_has_intersected) {
            // Emitter Material
            if (intersect_info.m_material.m_type == 1) {
                return_color = luminance * intersect_info.m_material.m_color *
                               intersect_info.m_material.m_emittance / continuation_probability;
            }

            // Diffuse Material
            else if (intersect_info.m_material.m_type == 2) {
                // Find normal in correct direction
                intersect_info.m_normal =
                    intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between);
                intersect_info.m_angle_between =
                    intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between);

                // Find new random direction for diffuse reflection
                glm::vec3 new_ray_dir = oriented_uniform_hemisphere_sample(intersect_info.m_normal);

                // Get angle between new random ray direction and the surface's normal
                float cos_theta = glm::dot(new_ray_dir, intersect_info.m_normal);

                luminance *= 2.f * intersect_info.m_material.m_color * cos_theta;

                // Make a new ray
                next_ray = Ray{intersect_info.m_pos, new_ray_dir};
            }

            // Glass Material
            if (intersect_info.m_material.m_type == 3) {
                float n1, n2;

                if (intersect_info.m_angle_between > 0) {
                    // Ray in inside the object
                    n1 = intersect_info.m_material.m_ior;
                    n2 = 1.0003f;

                    intersect_info.m_normal = -intersect_info.m_normal;
                } else {
                    // Ray is outside the object
                    n1 = 1.0003f;
                    n2 = intersect_info.m_material.m_ior;

                    intersect_info.m_angle_between = -intersect_info.m_angle_between;
                }

                float n = n1 / n2;

                float cos_t =
                    1.f - glm::pow(n, 2) * (1.f - glm::pow(intersect_info.m_angle_between, 2));

                glm::vec3 new_ray_dir;
                // Handle total internal reflection
                if (cos_t < 0.f) {
                    new_ray_dir = intersect_info.m_incoming_ray.m_dir -
                                  (2.f * intersect_info.m_angle_between * intersect_info.m_normal);
                    next_ray = Ray{intersect_info.m_pos, new_ray_dir};
                    break;
                }

                cos_t = glm::sqrt(cos_t);

                // Fresnel coefficients
                float r1 = n1 * intersect_info.m_angle_between - n2 * cos_t;
                float r2 = n1 * intersect_info.m_angle_between + n2 * cos_t;
                float r3 = n2 * intersect_info.m_angle_between - n1 * cos_t;
                float r4 = n2 * intersect_info.m_angle_between + n1 * cos_t;
                float r = glm::pow(r1 / r2, 2) + glm::pow(r3 / r4, 2) * 0.5f;

                if (rand_range(0.f, 1.f) < r) {
                    // Reflection
                    new_ray_dir = intersect_info.m_incoming_ray.m_dir -
                                  (2.f * intersect_info.m_angle_between * intersect_info.m_normal);
                    luminance *= intersect_info.m_material.m_color;
                } else {
                    // Refraction
                    new_ray_dir = intersect_info.m_incoming_ray.m_dir * (n1 / n2) +
                                  intersect_info.m_normal *
                                      ((n1 / n2) * intersect_info.m_angle_between - cos_t);
                    luminance *= 1.f;
                }

                // Make a new ray
                next_ray = Ray{intersect_info.m_pos, new_ray_dir};
            }

            // Glossy Material
            else if (intersect_info.m_material.m_type == 4) {
                // Find normal in correct direction
                intersect_info.m_normal =
                    intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between);
                intersect_info.m_angle_between =
                    intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between);

                float real_roughness =
                    intersect_info.m_material.m_roughness * glm::half_pi<float>();

                // Find new direction for reflection
                glm::vec3 reflected_dir =
                    intersect_info.m_incoming_ray.m_dir -
                    (2.f * intersect_info.m_angle_between * intersect_info.m_normal);

                // Find new random direction on cone for glossy reflection
                glm::vec3 new_ray_dir = oriented_uniform_cone_sample(reflected_dir, real_roughness);

                luminance *= intersect_info.m_material.m_color;

                // Make a new ray
                next_ray = Ray{intersect_info.m_pos, new_ray_dir};
            }
        } else {
            break;
        }
    }

    return glm::vec4(return_color, 1.f);
}
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DLL_WATCHER_HPP
#define DLL_WATCHER_HPP

#include <fstream>

#include <sys/stat.h>

#include "stop_watch.hpp"
#include "rbm_traits.hpp"
#include "dbn_traits.hpp"

namespace dll {

template<typename R>
struct default_rbm_watcher {
    stop_watch<std::chrono::seconds> watch;

    template<typename RBM = R>
    void training_begin(const RBM& rbm){
        std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM>::name() << "\"" << std::endl;
        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << rbm.learning_rate << std::endl;

        if(rbm_traits<RBM>::has_momentum()){
            std::cout << "   momentum=" << rbm.momentum << std::endl;
        }

        if(rbm_traits<RBM>::decay() == decay_type::L1 || rbm_traits<RBM>::decay() == decay_type::L1_FULL){
            std::cout << "   weight_cost(L1)=" << rbm.weight_cost << std::endl;
        }

        if(rbm_traits<RBM>::decay() == decay_type::L2 || rbm_traits<RBM>::decay() == decay_type::L2_FULL){
            std::cout << "   weight_cost(L2)=" << rbm.weight_cost << std::endl;
        }

        if(rbm_traits<RBM>::has_sparsity()){
            std::cout << "   sparsity_target=" << rbm.sparsity_target << std::endl;
        }
    }

    template<typename RBM = R>
    void epoch_end(std::size_t epoch, double error, double free_energy, const RBM& /*rbm*/){
        printf("epoch %ld - Reconstruction error average: %.5f - Free energy average: %.3f\n", epoch, error, free_energy);
    }

    template<typename RBM = R>
    void training_end(const RBM&){
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template<typename DBN>
struct default_dbn_watcher {
    static constexpr const bool ignore_sub = false;
    static constexpr const bool replace_sub = false;

    stop_watch<std::chrono::seconds> watch;

    void pretraining_begin(const DBN& /*dbn*/){
        std::cout << "DBN: Pretraining begin" << std::endl;
    }

    template<typename RBM>
    void pretrain_layer(const DBN& /*dbn*/, std::size_t I, std::size_t input_size){
        using rbm_t = RBM;
        static constexpr const auto num_visible = rbm_t::num_visible;
        static constexpr const auto num_hidden = rbm_t::num_hidden;

        std::cout << "DBN: Train layer " << I << " (" << num_visible << "->" << num_hidden << ") with " << input_size << " entries" << std::endl;
    }

    void pretraining_end(const DBN& /*dbn*/){
        std::cout << "DBN: Pretraining end" << std::endl;
    }

    void fine_tuning_begin(const DBN& dbn){
        std::cout << "Train DBN with \"" << DBN::desc::template trainer_t<DBN>::name() << "\"" << std::endl;
        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << dbn.learning_rate << std::endl;

        if(dbn_traits<DBN>::has_momentum()){
            std::cout << "   momentum=" << dbn.momentum << std::endl;
        }
    }

    void ft_epoch_end(std::size_t epoch, double error, const DBN&){
        printf("epoch %ld - Classification error: %.5f \n", epoch, error);
    }

    void fine_tuning_end(const DBN&){
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template<typename DBN>
struct silent_dbn_watcher : default_dbn_watcher<DBN> {
    static constexpr const bool ignore_sub = true;
    static constexpr const bool replace_sub = false;
};

template<typename DBN>
struct complete_dbn_watcher : default_dbn_watcher<DBN> {
    static constexpr const bool ignore_sub = false;
    static constexpr const bool replace_sub = true;
};

//TODO This is currently useless

template<typename R>
struct histogram_watcher {
    default_rbm_watcher<R> parent;

    template<typename RBM = R>
    void training_begin(const RBM& rbm){
        parent.training_begin(rbm);
    }

    template<typename RBM = R>
    void epoch_end(std::size_t epoch, double error, double /*free_energy*/, const RBM& rbm){
        parent.epoch_end(epoch, error, rbm);
    }

    template<typename RBM = R>
    void training_end(const RBM& rbm){
        parent.training_end(rbm);
    }

    void generate_hidden_images(size_t epoch, const R& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        for(size_t j = 0; j < R::num_hidden; ++j){
            auto path = folder + "/h_" + std::to_string(j) + ".dat";
            std::ofstream file(path, std::ios::out);

            if(!file){
                std::cout << "Could not open file " << path << std::endl;
            } else {
                size_t i = R::num_visible;
                while(i > 0){
                    --i;

                    auto value = rbm.w(i,j);
                    file << static_cast<size_t>(value > 0 ? static_cast<size_t>(value * 255.0) << 8 : static_cast<size_t>(-value * 255.0) << 16) << " ";
                }

                file << std::endl;
                file.close();
            }
        }
    }

    void generate_histograms(size_t epoch, const R& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        generate_histogram(folder + "/weights.dat", rbm.w);
        generate_histogram(folder + "/visibles.dat", rbm.a);
        generate_histogram(folder + "/hiddens.dat", rbm.b);
    }

    template<typename Container>
    void generate_histogram(const std::string& path, const Container& weights){
        std::ofstream file(path, std::ios::out);

        if(!file){
            std::cout << "Could not open file " << path << std::endl;
        } else {
            for(auto& weight : weights){
                file << weight << std::endl;
            }

            file << std::endl;
            file.close();
        }
    }
};

} //end of dbn namespace

#endif<commit_msg>Remove test structures<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DLL_WATCHER_HPP
#define DLL_WATCHER_HPP

#include <fstream>

#include <sys/stat.h>

#include "stop_watch.hpp"
#include "rbm_traits.hpp"
#include "dbn_traits.hpp"

namespace dll {

template<typename R>
struct default_rbm_watcher {
    stop_watch<std::chrono::seconds> watch;

    template<typename RBM = R>
    void training_begin(const RBM& rbm){
        std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM>::name() << "\"" << std::endl;
        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << rbm.learning_rate << std::endl;

        if(rbm_traits<RBM>::has_momentum()){
            std::cout << "   momentum=" << rbm.momentum << std::endl;
        }

        if(rbm_traits<RBM>::decay() == decay_type::L1 || rbm_traits<RBM>::decay() == decay_type::L1_FULL){
            std::cout << "   weight_cost(L1)=" << rbm.weight_cost << std::endl;
        }

        if(rbm_traits<RBM>::decay() == decay_type::L2 || rbm_traits<RBM>::decay() == decay_type::L2_FULL){
            std::cout << "   weight_cost(L2)=" << rbm.weight_cost << std::endl;
        }

        if(rbm_traits<RBM>::has_sparsity()){
            std::cout << "   sparsity_target=" << rbm.sparsity_target << std::endl;
        }
    }

    template<typename RBM = R>
    void epoch_end(std::size_t epoch, double error, double free_energy, const RBM& /*rbm*/){
        printf("epoch %ld - Reconstruction error average: %.5f - Free energy average: %.3f\n", epoch, error, free_energy);
    }

    template<typename RBM = R>
    void training_end(const RBM&){
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template<typename DBN>
struct default_dbn_watcher {
    static constexpr const bool ignore_sub = false;
    static constexpr const bool replace_sub = false;

    stop_watch<std::chrono::seconds> watch;

    void pretraining_begin(const DBN& /*dbn*/){
        std::cout << "DBN: Pretraining begin" << std::endl;
    }

    template<typename RBM>
    void pretrain_layer(const DBN& /*dbn*/, std::size_t I, std::size_t input_size){
        using rbm_t = RBM;
        static constexpr const auto num_visible = rbm_t::num_visible;
        static constexpr const auto num_hidden = rbm_t::num_hidden;

        std::cout << "DBN: Train layer " << I << " (" << num_visible << "->" << num_hidden << ") with " << input_size << " entries" << std::endl;
    }

    void pretraining_end(const DBN& /*dbn*/){
        std::cout << "DBN: Pretraining end" << std::endl;
    }

    void fine_tuning_begin(const DBN& dbn){
        std::cout << "Train DBN with \"" << DBN::desc::template trainer_t<DBN>::name() << "\"" << std::endl;
        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << dbn.learning_rate << std::endl;

        if(dbn_traits<DBN>::has_momentum()){
            std::cout << "   momentum=" << dbn.momentum << std::endl;
        }
    }

    void ft_epoch_end(std::size_t epoch, double error, const DBN&){
        printf("epoch %ld - Classification error: %.5f \n", epoch, error);
    }

    void fine_tuning_end(const DBN&){
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template<typename DBN>
struct silent_dbn_watcher : default_dbn_watcher<DBN> {
    static constexpr const bool ignore_sub = true;
    static constexpr const bool replace_sub = false;
};

//TODO This is currently useless

template<typename R>
struct histogram_watcher {
    default_rbm_watcher<R> parent;

    template<typename RBM = R>
    void training_begin(const RBM& rbm){
        parent.training_begin(rbm);
    }

    template<typename RBM = R>
    void epoch_end(std::size_t epoch, double error, double /*free_energy*/, const RBM& rbm){
        parent.epoch_end(epoch, error, rbm);
    }

    template<typename RBM = R>
    void training_end(const RBM& rbm){
        parent.training_end(rbm);
    }

    void generate_hidden_images(size_t epoch, const R& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        for(size_t j = 0; j < R::num_hidden; ++j){
            auto path = folder + "/h_" + std::to_string(j) + ".dat";
            std::ofstream file(path, std::ios::out);

            if(!file){
                std::cout << "Could not open file " << path << std::endl;
            } else {
                size_t i = R::num_visible;
                while(i > 0){
                    --i;

                    auto value = rbm.w(i,j);
                    file << static_cast<size_t>(value > 0 ? static_cast<size_t>(value * 255.0) << 8 : static_cast<size_t>(-value * 255.0) << 16) << " ";
                }

                file << std::endl;
                file.close();
            }
        }
    }

    void generate_histograms(size_t epoch, const R& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        generate_histogram(folder + "/weights.dat", rbm.w);
        generate_histogram(folder + "/visibles.dat", rbm.a);
        generate_histogram(folder + "/hiddens.dat", rbm.b);
    }

    template<typename Container>
    void generate_histogram(const std::string& path, const Container& weights){
        std::ofstream file(path, std::ios::out);

        if(!file){
            std::cout << "Could not open file " << path << std::endl;
        } else {
            for(auto& weight : weights){
                file << weight << std::endl;
            }

            file << std::endl;
            file.close();
        }
    }
};

} //end of dbn namespace

#endif<|endoftext|>