text
stringlengths 54
60.6k
|
---|
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
refreshkeyscommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "refreshkeyscommand.h"
#include "command_p.h"
#include <models/keycache.h>
#include <gpgme++/key.h>
#include <gpgme++/keylistresult.h>
#include <kleo/cryptobackendfactory.h>
#include <kleo/keylistjob.h>
#include <QStringList>
#include <cassert>
using namespace Kleo;
class RefreshKeysCommand::Private : public Command::Private {
friend class ::Kleo::RefreshKeysCommand;
public:
Private( RefreshKeysCommand * qq, Mode mode, KeyListController* controller );
~Private();
enum KeyType {
PublicKeys,
SecretKeys
};
void startKeyListing( const char* backend, KeyType type );
void publicKeyListingDone( const GpgME::KeyListResult& result );
void secretKeyListingDone( const GpgME::KeyListResult& result );
void addKey( const GpgME::Key& key );
private:
const Mode mode;
uint m_pubKeysJobs;
uint m_secKeysJobs;
};
RefreshKeysCommand::Private * RefreshKeysCommand::d_func() { return static_cast<Private*>( d.get() ); }
const RefreshKeysCommand::Private * RefreshKeysCommand::d_func() const { return static_cast<const Private*>( d.get() ); }
RefreshKeysCommand::RefreshKeysCommand( Mode mode, KeyListController * p )
: Command( p, new Private( this, mode, p ) )
{
}
RefreshKeysCommand::RefreshKeysCommand( Mode mode, QAbstractItemView * v, KeyListController * p )
: Command( v, p, new Private( this, mode, p ) )
{
}
RefreshKeysCommand::~RefreshKeysCommand() {}
RefreshKeysCommand::Private::Private( RefreshKeysCommand * qq, Mode m, KeyListController * controller )
: Command::Private( qq, controller ),
mode( m ),
m_pubKeysJobs( 0 ),
m_secKeysJobs( 0 )
{
}
RefreshKeysCommand::Private::~Private() {}
void RefreshKeysCommand::Private::startKeyListing( const char* backend, KeyType type )
{
const Kleo::CryptoBackend::Protocol * const protocol = Kleo::CryptoBackendFactory::instance()->protocol( backend );
if ( !protocol )
return;
Kleo::KeyListJob * const job = protocol->keyListJob( /*remote*/false, /*includeSigs*/false, mode == Validate );
if ( !job )
return;
if ( type == PublicKeys ) {
connect( job, SIGNAL(result(GpgME::KeyListResult)),
q, SLOT(publicKeyListingDone(GpgME::KeyListResult)) );
} else {
connect( job, SIGNAL(result(GpgME::KeyListResult)),
q, SLOT(secretKeyListingDone(GpgME::KeyListResult)) );
}
connect( job, SIGNAL(progress(QString,int,int)),
q, SIGNAL(progress(QString,int,int)) );
connect( job, SIGNAL(nextKey(GpgME::Key)),
q, SLOT(addKey(GpgME::Key)) );
job->start( QStringList(), type == SecretKeys );
++( type == PublicKeys ? m_pubKeysJobs : m_secKeysJobs );
}
void RefreshKeysCommand::Private::publicKeyListingDone( const GpgME::KeyListResult & )
{
assert( m_pubKeysJobs > 0 );
--m_pubKeysJobs;
if ( m_pubKeysJobs == 0 ) {
startKeyListing( "openpgp", Private::SecretKeys );
startKeyListing( "smime", Private::SecretKeys );
}
}
void RefreshKeysCommand::Private::secretKeyListingDone( const GpgME::KeyListResult & )
{
assert( m_secKeysJobs > 0 );
--m_secKeysJobs;
if ( m_secKeysJobs == 0 )
finished();
}
void RefreshKeysCommand::Private::addKey( const GpgME::Key& key )
{
if ( key.hasSecret() ) // ### hope this is ok. It is, after all, why we need the split in the first place...
SecretKeyCache::mutableInstance()->insert( key );
else
PublicKeyCache::mutableInstance()->insert( key );
}
#define d d_func()
void RefreshKeysCommand::doStart() {
/* NOTE: first fetch public keys. when done, fetch secret keys. hasSecret() works only
correctly when the key was retrieved with --list-secret-keys (secretOnly flag
in gpgme keylist operations) so we overwrite the key from --list-keys (secret
not set) with the one from --list-secret-keys (with secret set).
*/
d->startKeyListing( "openpgp", Private::PublicKeys );
d->startKeyListing( "smime", Private::PublicKeys );
}
void RefreshKeysCommand::doCancel() {
}
#undef d
#include "moc_refreshkeyscommand.cpp"
<commit_msg>Implement cancel properly<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
refreshkeyscommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "refreshkeyscommand.h"
#include "command_p.h"
#include <models/keycache.h>
#include <gpgme++/key.h>
#include <gpgme++/keylistresult.h>
#include <kleo/cryptobackendfactory.h>
#include <kleo/keylistjob.h>
#include <QStringList>
#include <cassert>
using namespace Kleo;
class RefreshKeysCommand::Private : public Command::Private {
friend class ::Kleo::RefreshKeysCommand;
public:
Private( RefreshKeysCommand * qq, Mode mode, KeyListController* controller );
~Private();
enum KeyType {
PublicKeys,
SecretKeys
};
void startKeyListing( const char* backend, KeyType type );
void publicKeyListingDone( const GpgME::KeyListResult& result );
void secretKeyListingDone( const GpgME::KeyListResult& result );
void addKey( const GpgME::Key& key );
private:
const Mode mode;
uint m_pubKeysJobs;
uint m_secKeysJobs;
};
RefreshKeysCommand::Private * RefreshKeysCommand::d_func() { return static_cast<Private*>( d.get() ); }
const RefreshKeysCommand::Private * RefreshKeysCommand::d_func() const { return static_cast<const Private*>( d.get() ); }
RefreshKeysCommand::RefreshKeysCommand( Mode mode, KeyListController * p )
: Command( p, new Private( this, mode, p ) )
{
}
RefreshKeysCommand::RefreshKeysCommand( Mode mode, QAbstractItemView * v, KeyListController * p )
: Command( v, p, new Private( this, mode, p ) )
{
}
RefreshKeysCommand::~RefreshKeysCommand() {}
RefreshKeysCommand::Private::Private( RefreshKeysCommand * qq, Mode m, KeyListController * controller )
: Command::Private( qq, controller ),
mode( m ),
m_pubKeysJobs( 0 ),
m_secKeysJobs( 0 )
{
}
RefreshKeysCommand::Private::~Private() {}
void RefreshKeysCommand::Private::startKeyListing( const char* backend, KeyType type )
{
const Kleo::CryptoBackend::Protocol * const protocol = Kleo::CryptoBackendFactory::instance()->protocol( backend );
if ( !protocol )
return;
Kleo::KeyListJob * const job = protocol->keyListJob( /*remote*/false, /*includeSigs*/false, mode == Validate );
if ( !job )
return;
if ( type == PublicKeys ) {
connect( job, SIGNAL(result(GpgME::KeyListResult)),
q, SLOT(publicKeyListingDone(GpgME::KeyListResult)) );
} else {
connect( job, SIGNAL(result(GpgME::KeyListResult)),
q, SLOT(secretKeyListingDone(GpgME::KeyListResult)) );
}
connect( job, SIGNAL(progress(QString,int,int)),
q, SIGNAL(progress(QString,int,int)) );
connect( job, SIGNAL(nextKey(GpgME::Key)),
q, SLOT(addKey(GpgME::Key)) );
connect( q, SIGNAL(canceled()),
job, SLOT(slotCancel()) );
job->start( QStringList(), type == SecretKeys );
++( type == PublicKeys ? m_pubKeysJobs : m_secKeysJobs );
}
void RefreshKeysCommand::Private::publicKeyListingDone( const GpgME::KeyListResult & result )
{
assert( m_pubKeysJobs > 0 );
--m_pubKeysJobs;
if ( result.error().isCanceled() )
finished();
else if ( m_pubKeysJobs == 0 ) {
startKeyListing( "openpgp", Private::SecretKeys );
startKeyListing( "smime", Private::SecretKeys );
}
}
void RefreshKeysCommand::Private::secretKeyListingDone( const GpgME::KeyListResult & result )
{
assert( m_secKeysJobs > 0 );
--m_secKeysJobs;
if ( result.error().isCanceled() || m_secKeysJobs == 0 )
finished();
}
void RefreshKeysCommand::Private::addKey( const GpgME::Key& key )
{
// ### collect them and replace them at the end in the key cache. This
// is waaaay to slow:
if ( key.hasSecret() )
SecretKeyCache::mutableInstance()->insert( key );
else
PublicKeyCache::mutableInstance()->insert( key );
}
#define d d_func()
void RefreshKeysCommand::doStart() {
/* NOTE: first fetch public keys. when done, fetch secret keys. hasSecret() works only
correctly when the key was retrieved with --list-secret-keys (secretOnly flag
in gpgme keylist operations) so we overwrite the key from --list-keys (secret
not set) with the one from --list-secret-keys (with secret set).
*/
d->startKeyListing( "openpgp", Private::PublicKeys );
d->startKeyListing( "smime", Private::PublicKeys );
}
void RefreshKeysCommand::doCancel() {
// empty implementation, as canceled(), emitted from
// Command::cancel(), is connected to Kleo::Job::slotCanceled()
// for all our jobs.
}
#undef d
#include "moc_refreshkeyscommand.cpp"
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
crypto/gui/resultitemwidget.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "resultitemwidget.h"
#include <ui/messagebox.h>
#include <KDebug>
#include <KLocalizedString>
#include <KPushButton>
#include <KStandardGuiItem>
#include <QHBoxLayout>
#include <QLabel>
#include <QStringList>
#include <QUrl>
#include <QVBoxLayout>
using namespace Kleo;
using namespace Kleo::Crypto;
using namespace Kleo::Crypto::Gui;
using namespace boost;
namespace {
//### TODO move outta here, make colors configurable
static QColor colorForVisualCode( Task::Result::VisualCode code ) {
switch ( code ) {
case Task::Result::AllGood:
return Qt::green;
case Task::Result::NeutralError:
case Task::Result::Warning:
return Qt::yellow;
case Task::Result::Danger:
return Qt::red;
case Task::Result::NeutralSuccess:
default:
return Qt::blue;
}
}
}
class ResultItemWidget::Private {
ResultItemWidget* const q;
public:
explicit Private( const shared_ptr<const Task::Result> result, ResultItemWidget* qq ) : q( qq ), m_result( result ), m_detailsLabel( 0 ), m_showDetailsLabel( 0 ) { assert( m_result ); }
void slotLinkActivated( const QString & );
void updateShowDetailsLabel();
const shared_ptr<const Task::Result> m_result;
QLabel * m_detailsLabel;
QLabel * m_showDetailsLabel;
KPushButton * m_closeButton;
};
void ResultItemWidget::Private::updateShowDetailsLabel()
{
if ( !m_showDetailsLabel || !m_detailsLabel )
return;
const bool detailsVisible = m_detailsLabel->isVisible();
const bool hasAuditLog = !m_result->auditLogAsHtml().isEmpty();
if ( detailsVisible )
m_showDetailsLabel->setText( QString("<a href=\"kleoresultitem://toggledetails/\">%1</a><br/>%2").arg( i18n( "Hide Details" ), hasAuditLog ? QString( "<a href=\"kleoresultitem://showauditlog/\">%1</a>" ).arg( i18n( "Show Audit Log" ) ) : i18n( "No Audit Log available" ) ) );
else
m_showDetailsLabel->setText( QString("<a href=\"kleoresultitem://toggledetails/\">%1</a>").arg( i18n( "Show Details" ) ) );
}
ResultItemWidget::ResultItemWidget( const shared_ptr<const Task::Result> & result, QWidget * parent, Qt::WindowFlags flags ) : QWidget( parent, flags ), d( new Private( result, this ) )
{
const QColor color = colorForVisualCode( d->m_result->code() );
setStyleSheet( QString( "* { background-color: %1; margin: 0px; } QFrame#resultFrame{ border-color: %2; border-style: solid; border-radius: 3px; border-width: 2px } QLabel { padding: 5px; border-radius: 3px }" ).arg( color.lighter( 150 ).name(), color.name() ) );
QVBoxLayout* topLayout = new QVBoxLayout( this );
topLayout->setMargin( 0 );
topLayout->setSpacing( 0 );
QFrame* frame = new QFrame;
frame->setObjectName( "resultFrame" );
topLayout->addWidget( frame );
QVBoxLayout* layout = new QVBoxLayout( frame );
layout->setMargin( 0 );
layout->setSpacing( 0 );
QWidget* hbox = new QWidget;
QHBoxLayout* hlay = new QHBoxLayout( hbox );
hlay->setMargin( 0 );
hlay->setSpacing( 0 );
QLabel* overview = new QLabel;
overview->setWordWrap( true );
overview->setTextFormat( Qt::RichText );
overview->setText( d->m_result->overview() );
connect( overview, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)) );
hlay->addWidget( overview, 1, Qt::AlignTop );
layout->addWidget( hbox );
const QString details = d->m_result->details();
d->m_showDetailsLabel = new QLabel;
connect( d->m_showDetailsLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)) );
hlay->addWidget( d->m_showDetailsLabel );
d->m_showDetailsLabel->setVisible( !details.isEmpty() );
d->m_detailsLabel = new QLabel;
d->m_detailsLabel->setWordWrap( true );
d->m_detailsLabel->setTextFormat( Qt::RichText );
d->m_detailsLabel->setText( details );
connect( d->m_detailsLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)) );
layout->addWidget( d->m_detailsLabel );
d->m_detailsLabel->setVisible( false );
d->m_closeButton = new KPushButton;
d->m_closeButton->setGuiItem( KStandardGuiItem::close() );
d->m_closeButton->setFixedSize( d->m_closeButton->sizeHint() );
connect( d->m_closeButton, SIGNAL(clicked()), this, SIGNAL(closeButtonClicked()) );
layout->addWidget( d->m_closeButton, 0, Qt::AlignRight );
d->m_closeButton->setVisible( false );
d->updateShowDetailsLabel();
}
ResultItemWidget::~ResultItemWidget()
{
}
void ResultItemWidget::showCloseButton( bool show )
{
d->m_closeButton->setVisible( show );
}
bool ResultItemWidget::detailsVisible() const
{
return d->m_detailsLabel && d->m_detailsLabel->isVisible();
}
bool ResultItemWidget::hasErrorResult() const
{
return d->m_result->hasError();
}
void ResultItemWidget::Private::slotLinkActivated( const QString & link )
{
assert( m_result );
if ( link.startsWith( "key:" ) ) {
const QStringList split = link.split( ':' );
if ( split.size() == 3 || m_result->nonce() != split.value( 1 ) )
emit q->linkActivated( "key://" + split.value( 2 ) );
else
kWarning() << "key link invalid, or nonce not matching! link=" << link << " nonce" << m_result->nonce();
}
const QUrl url( link );
if ( url.host() == "toggledetails" ) {
q->showDetails( !q->detailsVisible() );
return;
}
if ( url.host() == "showauditlog" ) {
q->showAuditLog();
return;
}
kWarning() << "Unexpected link scheme: " << link;
}
void ResultItemWidget::showAuditLog() {
MessageBox::auditLog( this, d->m_result->auditLogAsHtml() );
}
void ResultItemWidget::showDetails( bool show )
{
if ( show == d->m_detailsLabel->isVisible() )
return;
d->m_detailsLabel->setVisible( show );
d->updateShowDetailsLabel();
emit detailsToggled( show );
}
#include "resultitemwidget.moc"
<commit_msg>add missing return <commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
crypto/gui/resultitemwidget.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "resultitemwidget.h"
#include <ui/messagebox.h>
#include <KDebug>
#include <KLocalizedString>
#include <KPushButton>
#include <KStandardGuiItem>
#include <QHBoxLayout>
#include <QLabel>
#include <QStringList>
#include <QUrl>
#include <QVBoxLayout>
using namespace Kleo;
using namespace Kleo::Crypto;
using namespace Kleo::Crypto::Gui;
using namespace boost;
namespace {
//### TODO move outta here, make colors configurable
static QColor colorForVisualCode( Task::Result::VisualCode code ) {
switch ( code ) {
case Task::Result::AllGood:
return Qt::green;
case Task::Result::NeutralError:
case Task::Result::Warning:
return Qt::yellow;
case Task::Result::Danger:
return Qt::red;
case Task::Result::NeutralSuccess:
default:
return Qt::blue;
}
}
}
class ResultItemWidget::Private {
ResultItemWidget* const q;
public:
explicit Private( const shared_ptr<const Task::Result> result, ResultItemWidget* qq ) : q( qq ), m_result( result ), m_detailsLabel( 0 ), m_showDetailsLabel( 0 ) { assert( m_result ); }
void slotLinkActivated( const QString & );
void updateShowDetailsLabel();
const shared_ptr<const Task::Result> m_result;
QLabel * m_detailsLabel;
QLabel * m_showDetailsLabel;
KPushButton * m_closeButton;
};
void ResultItemWidget::Private::updateShowDetailsLabel()
{
if ( !m_showDetailsLabel || !m_detailsLabel )
return;
const bool detailsVisible = m_detailsLabel->isVisible();
const bool hasAuditLog = !m_result->auditLogAsHtml().isEmpty();
if ( detailsVisible )
m_showDetailsLabel->setText( QString("<a href=\"kleoresultitem://toggledetails/\">%1</a><br/>%2").arg( i18n( "Hide Details" ), hasAuditLog ? QString( "<a href=\"kleoresultitem://showauditlog/\">%1</a>" ).arg( i18n( "Show Audit Log" ) ) : i18n( "No Audit Log available" ) ) );
else
m_showDetailsLabel->setText( QString("<a href=\"kleoresultitem://toggledetails/\">%1</a>").arg( i18n( "Show Details" ) ) );
}
ResultItemWidget::ResultItemWidget( const shared_ptr<const Task::Result> & result, QWidget * parent, Qt::WindowFlags flags ) : QWidget( parent, flags ), d( new Private( result, this ) )
{
const QColor color = colorForVisualCode( d->m_result->code() );
setStyleSheet( QString( "* { background-color: %1; margin: 0px; } QFrame#resultFrame{ border-color: %2; border-style: solid; border-radius: 3px; border-width: 2px } QLabel { padding: 5px; border-radius: 3px }" ).arg( color.lighter( 150 ).name(), color.name() ) );
QVBoxLayout* topLayout = new QVBoxLayout( this );
topLayout->setMargin( 0 );
topLayout->setSpacing( 0 );
QFrame* frame = new QFrame;
frame->setObjectName( "resultFrame" );
topLayout->addWidget( frame );
QVBoxLayout* layout = new QVBoxLayout( frame );
layout->setMargin( 0 );
layout->setSpacing( 0 );
QWidget* hbox = new QWidget;
QHBoxLayout* hlay = new QHBoxLayout( hbox );
hlay->setMargin( 0 );
hlay->setSpacing( 0 );
QLabel* overview = new QLabel;
overview->setWordWrap( true );
overview->setTextFormat( Qt::RichText );
overview->setText( d->m_result->overview() );
connect( overview, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)) );
hlay->addWidget( overview, 1, Qt::AlignTop );
layout->addWidget( hbox );
const QString details = d->m_result->details();
d->m_showDetailsLabel = new QLabel;
connect( d->m_showDetailsLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)) );
hlay->addWidget( d->m_showDetailsLabel );
d->m_showDetailsLabel->setVisible( !details.isEmpty() );
d->m_detailsLabel = new QLabel;
d->m_detailsLabel->setWordWrap( true );
d->m_detailsLabel->setTextFormat( Qt::RichText );
d->m_detailsLabel->setText( details );
connect( d->m_detailsLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)) );
layout->addWidget( d->m_detailsLabel );
d->m_detailsLabel->setVisible( false );
d->m_closeButton = new KPushButton;
d->m_closeButton->setGuiItem( KStandardGuiItem::close() );
d->m_closeButton->setFixedSize( d->m_closeButton->sizeHint() );
connect( d->m_closeButton, SIGNAL(clicked()), this, SIGNAL(closeButtonClicked()) );
layout->addWidget( d->m_closeButton, 0, Qt::AlignRight );
d->m_closeButton->setVisible( false );
d->updateShowDetailsLabel();
}
ResultItemWidget::~ResultItemWidget()
{
}
void ResultItemWidget::showCloseButton( bool show )
{
d->m_closeButton->setVisible( show );
}
bool ResultItemWidget::detailsVisible() const
{
return d->m_detailsLabel && d->m_detailsLabel->isVisible();
}
bool ResultItemWidget::hasErrorResult() const
{
return d->m_result->hasError();
}
void ResultItemWidget::Private::slotLinkActivated( const QString & link )
{
assert( m_result );
if ( link.startsWith( "key:" ) ) {
const QStringList split = link.split( ':' );
if ( split.size() == 3 || m_result->nonce() != split.value( 1 ) )
emit q->linkActivated( "key://" + split.value( 2 ) );
else
kWarning() << "key link invalid, or nonce not matching! link=" << link << " nonce" << m_result->nonce();
return;
}
const QUrl url( link );
if ( url.host() == "toggledetails" ) {
q->showDetails( !q->detailsVisible() );
return;
}
if ( url.host() == "showauditlog" ) {
q->showAuditLog();
return;
}
kWarning() << "Unexpected link scheme: " << link;
}
void ResultItemWidget::showAuditLog() {
MessageBox::auditLog( this, d->m_result->auditLogAsHtml() );
}
void ResultItemWidget::showDetails( bool show )
{
if ( show == d->m_detailsLabel->isVisible() )
return;
d->m_detailsLabel->setVisible( show );
d->updateShowDetailsLabel();
emit detailsToggled( show );
}
#include "resultitemwidget.moc"
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2009 Kevin Krammer <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "itemsavejob.h"
#include "itemsavecontext.h"
#include <akonadi/itemcreatejob.h>
#include <akonadi/itemdeletejob.h>
#include <akonadi/itemmodifyjob.h>
using namespace Akonadi;
ItemSaveJob::ItemSaveJob( const ItemSaveContext &saveContext )
{
foreach ( const ItemAddContext &addContext, saveContext.addedItems ) {
(void)new ItemCreateJob( addContext.item, addContext.collection, this );
}
foreach ( const Item &item, saveContext.changedItems ) {
(void)new ItemModifyJob( item, this );
}
foreach ( const Item &item, saveContext.removedItems ) {
(void)new ItemDeleteJob( item, this );
}
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Add debug output to ItemSaveJob so we can check if the correct jobs is being used<commit_after>/*
This file is part of kdepim.
Copyright (c) 2009 Kevin Krammer <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "itemsavejob.h"
#include "itemsavecontext.h"
#include <akonadi/itemcreatejob.h>
#include <akonadi/itemdeletejob.h>
#include <akonadi/itemmodifyjob.h>
#include <KDebug>
using namespace Akonadi;
ItemSaveJob::ItemSaveJob( const ItemSaveContext &saveContext )
{
foreach ( const ItemAddContext &addContext, saveContext.addedItems ) {
kDebug( 5650 ) << "CreateJob for Item (mimeType=" << addContext.item.mimeType()
<< "), collection (id=" << addContext.collection.id()
<< ", remoteId=" << addContext.collection.remoteId()
<< ")";
(void)new ItemCreateJob( addContext.item, addContext.collection, this );
}
foreach ( const Item &item, saveContext.changedItems ) {
kDebug( 5650 ) << "ModifyJob for Item (id=" << item.id()
<< ", remoteId=" << item.remoteId()
<< ", mimeType=" << item.mimeType()
<< ")";
(void)new ItemModifyJob( item, this );
}
foreach ( const Item &item, saveContext.removedItems ) {
kDebug( 5650 ) << "DeleteJob for Item (id=" << item.id()
<< ", remoteId=" << item.remoteId()
<< ", mimeType=" << item.mimeType()
<< ")";
(void)new ItemDeleteJob( item, this );
}
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>#ifndef BFC_AST_VISITOR_HPP
#define BFC_AST_VISITOR_HPP
#include <memory>
namespace bfc {
namespace ast {
class program;
class set;
class add;
class sub;
class mul;
class mov;
class read;
class write;
class loop;
class visitor {
public:
enum status {
BREAK = 0,
CONTINUE
};
virtual ~visitor(void) = default;
virtual status visit(program &node) { return CONTINUE; }
virtual status visit(const program &node) { return CONTINUE; }
virtual status visit(set &node) { return CONTINUE; }
virtual status visit(const set &node) { return CONTINUE; }
virtual status visit(add &node) { return CONTINUE; }
virtual status visit(const add &node) { return CONTINUE; }
virtual status visit(sub &node) { return CONTINUE; }
virtual status visit(const sub &node) { return CONTINUE; }
virtual status visit(mov &node) { return CONTINUE; }
virtual status visit(const mov &node) { return CONTINUE; }
virtual status visit(mul &node) { return CONTINUE; }
virtual status visit(const mul &node) { return CONTINUE; }
virtual status visit(loop &node) { return CONTINUE; }
virtual status visit(const loop &node) { return CONTINUE; }
virtual status visit(read &node) { return CONTINUE; }
virtual status visit(const read &node) { return CONTINUE; }
virtual status visit(write &node) { return CONTINUE; }
virtual status visit(const write &node) { return CONTINUE; }
};
}
}
#endif /* !BFC_AST_VISITOR_HPP */
<commit_msg>Added enum to visitor to be able to store types of nodes visited<commit_after>#ifndef BFC_AST_VISITOR_HPP
#define BFC_AST_VISITOR_HPP
#include <memory>
namespace bfc {
namespace ast {
class program;
class set;
class add;
class sub;
class mul;
class mov;
class read;
class write;
class loop;
class visitor {
public:
enum status {
BREAK = 0,
CONTINUE
};
enum node_type {
PROGRAM = 0,
ADD,
SUB,
MUL,
MOV,
READ,
WRITE,
LOOP
}
virtual ~visitor(void) = default;
virtual status visit(program &node) { return CONTINUE; }
virtual status visit(const program &node) { return CONTINUE; }
virtual status visit(set &node) { return CONTINUE; }
virtual status visit(const set &node) { return CONTINUE; }
virtual status visit(add &node) { return CONTINUE; }
virtual status visit(const add &node) { return CONTINUE; }
virtual status visit(sub &node) { return CONTINUE; }
virtual status visit(const sub &node) { return CONTINUE; }
virtual status visit(mov &node) { return CONTINUE; }
virtual status visit(const mov &node) { return CONTINUE; }
virtual status visit(mul &node) { return CONTINUE; }
virtual status visit(const mul &node) { return CONTINUE; }
virtual status visit(loop &node) { return CONTINUE; }
virtual status visit(const loop &node) { return CONTINUE; }
virtual status visit(read &node) { return CONTINUE; }
virtual status visit(const read &node) { return CONTINUE; }
virtual status visit(write &node) { return CONTINUE; }
virtual status visit(const write &node) { return CONTINUE; }
};
}
}
#endif /* !BFC_AST_VISITOR_HPP */
<|endoftext|> |
<commit_before>/*
Copyright 2011 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "state_assignment_statement.hpp"
#include <cassert>
#include <memory>
#include <string>
#include <utility>
#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/expressions/cast_expression.hpp>
#include <joelang/state.hpp>
#include <joelang/state_assignment.hpp>
namespace JoeLang
{
namespace Compiler
{
//------------------------------------------------------------------------------
// StateAssignmentStatement
//------------------------------------------------------------------------------
StateAssignmentStatement::StateAssignmentStatement(
std::string identifier,
Expression_up expression )
:PassStatement( TokenTy::StateAssignmentStatement )
,m_Identifier( std::move(identifier) )
,m_Expression( std::move(expression) )
{
assert( !m_Identifier.empty() &&
"Trying to create a StateAssignmentStatement with an empty state "
"name" );
assert( m_Expression &&
"Trying to create a StateAssignmentStatement with a null "
"expression" );
}
StateAssignmentStatement::~StateAssignmentStatement()
{
}
bool StateAssignmentStatement::PerformSema( SemaAnalyzer& sema )
{
// create a scope for the enumerants
SemaAnalyzer::ScopeHolder scope( sema );
scope.Enter();
// Try and get the state to which we are assigning
m_State = sema.GetState( m_Identifier );
if( !m_State )
{
sema.Error( "Undeclared state: " + m_Identifier );
return false;
}
sema.LoadStateEnumerants( *m_State );
m_Expression = CastExpression::Create( m_State->GetType(),
std::move(m_Expression),
false );
if( !m_Expression->PerformSema( sema ) )
return false;
// best to be explicit about these things
scope.Leave();
return true;
}
std::unique_ptr<StateAssignmentBase>
StateAssignmentStatement::GenerateStateAssignment(
CodeGenerator& code_gen,
const std::string& name ) const
{
assert( m_State &&
"Trying to generate a state assignment without a state" );
Type t = m_State->GetType();
assert( m_Expression->GetType().GetType() == t &&
"Trying to create a state assignment with mismatched types" );
// If this is just a constant return a ConstStateAssignment
if( m_Expression->IsConst() )
{
GenericValue v = code_gen.EvaluateExpression( *m_Expression );
switch( t )
{
case Type::BOOL:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_bool>(
static_cast<const State<jl_bool>&>(*m_State),
v.GetBool() ) );
case Type::CHAR:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_char>(
static_cast<const State<jl_char>&>(*m_State),
v.GetChar() ) );
case Type::SHORT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_short>(
static_cast<const State<jl_short>&>(*m_State),
v.GetShort() ) );
case Type::INT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_int>(
static_cast<const State<jl_int>&>(*m_State),
v.GetInt() ) );
case Type::LONG:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_long>(
static_cast<const State<jl_long>&>(*m_State),
v.GetLong() ) );
case Type::UCHAR:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_uchar>(
static_cast<const State<jl_uchar>&>(*m_State),
v.GetUChar() ) );
case Type::USHORT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_ushort>(
static_cast<const State<jl_ushort>&>(*m_State),
v.GetUShort() ) );
case Type::UINT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_uint>(
static_cast<const State<jl_uint>&>(*m_State),
v.GetUInt() ) );
case Type::UINT2:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_uint2>(
static_cast<const State<jl_uint2>&>(*m_State),
v.GetUInt2() ) );
case Type::ULONG:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_ulong>(
static_cast<const State<jl_ulong>&>(*m_State),
v.GetULong() ) );
case Type::FLOAT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_float>(
static_cast<const State<jl_float>&>(*m_State),
v.GetFloat() ) );
case Type::FLOAT2:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_float2>(
static_cast<const State<jl_float2>&>(*m_State),
v.GetFloat2() ) );
case Type::FLOAT3:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_float3>(
static_cast<const State<jl_float3>&>(*m_State),
v.GetFloat3() ) );
case Type::FLOAT4:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_float4>(
static_cast<const State<jl_float4>&>(*m_State),
v.GetFloat4() ) );
case Type::DOUBLE:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_double>(
static_cast<const State<jl_double>&>(*m_State),
v.GetDouble() ) );
case Type::STRING:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<std::string>(
static_cast<const State<std::string>&>(*m_State),
v.GetString() ) );
default:
assert( false &&
"Trying to create a ConstStateAssignment with an unhandled type" );
return nullptr;
}
}
return code_gen.GenerateStateAssignment( *m_State,
*m_Expression,
name + "_" + m_Identifier );
}
bool StateAssignmentStatement::Parse(
Parser& parser,
std::unique_ptr<StateAssignmentStatement>& token )
{
// Read the state identifier
std::string identifier;
if( !parser.ExpectTerminal( TerminalType::IDENTIFIER, identifier ) )
return false;
// The assignment operator
if( !parser.ExpectTerminal( TerminalType::EQUALS ) )
return false;
// And the expression
Expression_up expression;
if( !parser.Expect< Expression >( expression ) )
return false;
// Closing semicolon
if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
return false;
token.reset( new StateAssignmentStatement( std::move(identifier),
std::move(expression) ) );
return true;
}
bool StateAssignmentStatement::classof( const Token* t )
{
return t->GetSubClassID() == TokenTy::StateAssignmentStatement;
}
bool StateAssignmentStatement::classof( const StateAssignmentStatement* t )
{
return true;
}
} // namespace Compiler
} // namespace JoeLang
<commit_msg>[+] Types for const state assignments<commit_after>/*
Copyright 2011 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "state_assignment_statement.hpp"
#include <cassert>
#include <memory>
#include <string>
#include <utility>
#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/expressions/cast_expression.hpp>
#include <joelang/state.hpp>
#include <joelang/state_assignment.hpp>
#include <joelang/types.hpp>
namespace JoeLang
{
namespace Compiler
{
//------------------------------------------------------------------------------
// StateAssignmentStatement
//------------------------------------------------------------------------------
StateAssignmentStatement::StateAssignmentStatement(
std::string identifier,
Expression_up expression )
:PassStatement( TokenTy::StateAssignmentStatement )
,m_Identifier( std::move(identifier) )
,m_Expression( std::move(expression) )
{
assert( !m_Identifier.empty() &&
"Trying to create a StateAssignmentStatement with an empty state "
"name" );
assert( m_Expression &&
"Trying to create a StateAssignmentStatement with a null "
"expression" );
}
StateAssignmentStatement::~StateAssignmentStatement()
{
}
bool StateAssignmentStatement::PerformSema( SemaAnalyzer& sema )
{
// create a scope for the enumerants
SemaAnalyzer::ScopeHolder scope( sema );
scope.Enter();
// Try and get the state to which we are assigning
m_State = sema.GetState( m_Identifier );
if( !m_State )
{
sema.Error( "Undeclared state: " + m_Identifier );
return false;
}
sema.LoadStateEnumerants( *m_State );
m_Expression = CastExpression::Create( m_State->GetType(),
std::move(m_Expression),
false );
if( !m_Expression->PerformSema( sema ) )
return false;
// best to be explicit about these things
scope.Leave();
return true;
}
std::unique_ptr<StateAssignmentBase>
StateAssignmentStatement::GenerateStateAssignment(
CodeGenerator& code_gen,
const std::string& name ) const
{
assert( m_State &&
"Trying to generate a state assignment without a state" );
Type t = m_State->GetType();
assert( m_Expression->GetType().GetType() == t &&
"Trying to create a state assignment with mismatched types" );
#define CREATE_CONST_STATE_ASSIGNMENT( type, Type ) \
case JoeLangType<type>::value: \
return std::unique_ptr<StateAssignmentBase>( \
new ConstStateAssignment<type>( \
static_cast<const State<type>&>(*m_State), \
v.Get##Type() ) );
#define CREATE_CONST_STATE_ASSIGNMENT_N( type, Type ) \
CREATE_CONST_STATE_ASSIGNMENT( type, Type ) \
CREATE_CONST_STATE_ASSIGNMENT( type##2, Type##2 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##3, Type##3 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##4, Type##4 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##2x2, Type##2x2 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##2x3, Type##2x3 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##2x4, Type##2x4 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##3x2, Type##3x2 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##3x3, Type##3x3 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##3x4, Type##3x4 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##4x2, Type##4x2 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##4x3, Type##4x3 ) \
CREATE_CONST_STATE_ASSIGNMENT( type##4x4, Type##4x4 )
// If this is just a constant return a ConstStateAssignment
if( m_Expression->IsConst() )
{
GenericValue v = code_gen.EvaluateExpression( *m_Expression );
switch( t )
{
CREATE_CONST_STATE_ASSIGNMENT_N( jl_bool, Bool )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_char, Char )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_short, Short )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_int, Int )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_long, Long )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_uchar, UChar )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_ushort, UShort )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_uint, UInt )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_ulong, ULong )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_float, Float )
CREATE_CONST_STATE_ASSIGNMENT_N( jl_double, Double )
CREATE_CONST_STATE_ASSIGNMENT( std::string, String )
default:
assert( false &&
"Trying to create a ConstStateAssignment with an unhandled type" );
return nullptr;
}
}
#undef CREATE_CONST_STATE_ASSIGNMENT_N
#undef CREATE_CONST_STATE_ASSIGNMENT
return code_gen.GenerateStateAssignment( *m_State,
*m_Expression,
name + "_" + m_Identifier );
}
bool StateAssignmentStatement::Parse(
Parser& parser,
std::unique_ptr<StateAssignmentStatement>& token )
{
// Read the state identifier
std::string identifier;
if( !parser.ExpectTerminal( TerminalType::IDENTIFIER, identifier ) )
return false;
// The assignment operator
if( !parser.ExpectTerminal( TerminalType::EQUALS ) )
return false;
// And the expression
Expression_up expression;
if( !parser.Expect< Expression >( expression ) )
return false;
// Closing semicolon
if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
return false;
token.reset( new StateAssignmentStatement( std::move(identifier),
std::move(expression) ) );
return true;
}
bool StateAssignmentStatement::classof( const Token* t )
{
return t->GetSubClassID() == TokenTy::StateAssignmentStatement;
}
bool StateAssignmentStatement::classof( const StateAssignmentStatement* t )
{
return true;
}
} // namespace Compiler
} // namespace JoeLang
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmlplatform_p.h"
QT_BEGIN_NAMESPACE
/*
This object and its properties are documented as part of the Qt object,
in qqmlengine.cpp
*/
QQmlPlatform::QQmlPlatform(QObject *parent)
: QObject(parent)
{
}
QQmlPlatform::~QQmlPlatform()
{
}
QString QQmlPlatform::os()
{
#if defined(Q_OS_ANDROID)
return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
return QLatin1String("ios");
#elif defined(Q_OS_MAC)
return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
return QLatin1String("wince");
#elif defined(Q_OS_WIN)
return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
return QLatin1String("unix");
#else
return QLatin1String("unknown");
#endif
}
QT_END_NAMESPACE
<commit_msg>Return "winphone" and "winrt" for Qt.platform.os when appropriate<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmlplatform_p.h"
QT_BEGIN_NAMESPACE
/*
This object and its properties are documented as part of the Qt object,
in qqmlengine.cpp
*/
QQmlPlatform::QQmlPlatform(QObject *parent)
: QObject(parent)
{
}
QQmlPlatform::~QQmlPlatform()
{
}
QString QQmlPlatform::os()
{
#if defined(Q_OS_ANDROID)
return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
return QLatin1String("ios");
#elif defined(Q_OS_MAC)
return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
return QLatin1String("wince");
#elif defined(Q_OS_WINPHONE)
return QStringLiteral("winphone");
#elif defined(Q_OS_WINRT)
return QStringLiteral("winrt");
#elif defined(Q_OS_WIN)
return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
return QLatin1String("unix");
#else
return QLatin1String("unknown");
#endif
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/mcbist/gen_mss_mcbist_traits.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file gen_mss_mcbist_traits.H
/// @brief Run and manage the MCBIST engine
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Stephen Glancy <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _GEN_MSS_MCBIST_TRAITS_H_
#define _GEN_MSS_MCBIST_TRAITS_H_
#include <fapi2.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mcbist/gen_address.H>
namespace mss
{
///
/// @class mcbistMCTraits
/// @tparam MC the mc type
/// @brief A MC to MC_TARGET_TYPE mapping
///
template< mss::mc_type MC = DEFAULT_MC_TYPE >
class mcbistMCTraits;
///
/// @class mcbistTraits
/// @tparam MC the mc type of the T
/// @tparam T the fapi2::TargetType - derived
/// @brief a collection of traits associated with the MCBIST engine or hardware
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T = mss::mcbistMCTraits<MC>::MC_TARGET_TYPE>
class mcbistTraits;
}// mss
#endif
<commit_msg>Add snapshot of ocmb/explorer for master-p10 branch<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/mcbist/gen_mss_mcbist_traits.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file gen_mss_mcbist_traits.H
/// @brief Run and manage the MCBIST engine
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Stephen Glancy <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _GEN_MSS_MCBIST_TRAITS_H_
#define _GEN_MSS_MCBIST_TRAITS_H_
#include <fapi2.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mcbist/gen_mss_mcbist_address.H>
namespace mss
{
///
/// @class mcbistMCTraits
/// @tparam MC the mc type
/// @brief A MC to MC_TARGET_TYPE mapping
///
template< mss::mc_type MC = DEFAULT_MC_TYPE >
class mcbistMCTraits;
///
/// @class mcbistTraits
/// @tparam MC the mc type of the T
/// @tparam T the fapi2::TargetType - derived
/// @brief a collection of traits associated with the MCBIST engine or hardware
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T = mss::mcbistMCTraits<MC>::MC_TARGET_TYPE>
class mcbistTraits;
}// mss
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <openssl/rand.h>
#include "Crypto.h"
#include "Identity.h"
#include "common/key.hpp"
#include <thread>
#include <unistd.h>
#include <vector>
#include <mutex>
static std::mutex thread_mutex;
static i2p::data::SigningKeyType type;
static i2p::data::PrivateKeys keys;
static bool finded=false;
static size_t padding_size;
static uint8_t * KeyBuf;
static uint8_t * PaddingBuf;
static unsigned long long hash;
#define CPU_ONLY
#ifdef CPU_ONLY
// XXX: make this faster
static inline bool NotThat(const char * a, const char *b){
while(*b)
if(*a++!=*b++) return true;
return false;
}
inline void twist_cpu(uint8_t * buf,size_t * l0){
//TODO: NORMAL IMPLEMENTATION
RAND_bytes(buf,padding_size);
}
// XXX: make this faster
static inline void mutate_keys_cpu(
uint8_t * buf,
uint8_t * padding,
size_t * l0)
{
twist_cpu(padding,l0);
thread_mutex.lock();
keys.RecalculateIdentHash(buf);
thread_mutex.unlock();
}
void thread_find(const char * prefix){
while(NotThat(keys.GetPublic()->GetIdentHash().ToBase32().c_str(),prefix) and !finded)
{
size_t l0 = 0;
mutate_keys_cpu(KeyBuf,PaddingBuf, (size_t*)&l0);
hash++;
}
}
#endif
int main (int argc, char * argv[])
{
if ( argc < 3 )
{
std::cout << "Usage: " << argv[0] << " filename generatestring <signature type>" << std::endl;
return 0;
}
i2p::crypto::InitCrypto (false);
type = i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519;
if ( argc > 3 )
type = NameToSigType(std::string(argv[3]));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
keys = i2p::data::PrivateKeys::CreateRandomKeys (type);
switch(type){
case i2p::data::SIGNING_KEY_TYPE_DSA_SHA1:
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512:
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512_TEST:
std::cout << "Sorry, i don't can generate adress for this signature type" << std::endl;
return 0;
break;
}
switch(type){
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
padding_size=64;
break;
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
padding_size=32;
break;
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
padding_size=4;
break;
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
padding_size=128;
break;
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
padding_size=256;
break;
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
padding_size=384;
break;
case i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
padding_size=96;
break;
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256:
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256_TEST:
padding_size=64;
break;
}
// TODO: multi threading
KeyBuf = new uint8_t[keys.GetFullLen()];
PaddingBuf = keys.GetPadding();
unsigned int count_cpu = sysconf(_SC_NPROCESSORS_ONLN);
std::vector<std::thread> threads(count_cpu);
std::cout << "Start vanity generator in " << count_cpu << " threads" << std::endl;
for ( unsigned int j = count_cpu;j--;){
threads[j] = std::thread(thread_find,argv[2]);
sched_param sch;
int policy;
pthread_getschedparam(threads[j].native_handle(), &policy, &sch);
sch.sched_priority = 10;
if (pthread_setschedparam(threads[j].native_handle(), SCHED_FIFO, &sch)) {
std::cout << "Failed to setschedparam" << std::endl;
return 1;
}
}
for(unsigned int j = 0; j < count_cpu;j++)
threads[j].join();
std::cout << "Hashes: " << hash << std::endl;
std::ofstream f (argv[1], std::ofstream::binary | std::ofstream::out);
if (f)
{
size_t len = keys.GetFullLen ();
len = keys.ToBuffer (KeyBuf, len);
f.write ((char *)KeyBuf, len);
delete [] KeyBuf;
std::cout << "Destination " << keys.GetPublic ()->GetIdentHash ().ToBase32 () << " created" << std::endl;
}
else
std::cout << "Can't create file " << argv[1] << std::endl;
i2p::crypto::TerminateCrypto ();
return 0;
}
<commit_msg>notes<commit_after>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <openssl/rand.h>
#include "Crypto.h"
#include "Identity.h"
#include "common/key.hpp"
#include <thread>
#include <unistd.h>
#include <vector>
#include <mutex>
static std::mutex thread_mutex;
static i2p::data::SigningKeyType type;
static i2p::data::PrivateKeys keys;
static bool finded=false;
static size_t padding_size;
static uint8_t * KeyBuf;
static uint8_t * PaddingBuf;
static unsigned long long hash;
#define CPU_ONLY
#ifdef CPU_ONLY
static inline bool NotThat(const char * a, const char *b){
while(*b)
if(*a++!=*b++) return true;
return false;
}
inline void twist_cpu(uint8_t * buf,size_t * l0){
//TODO: NORMAL IMPLEMENTATION,\
As in miner...
RAND_bytes(buf,padding_size);
}
// XXX: make this faster
static inline void mutate_keys_cpu(
uint8_t * buf,
uint8_t * padding,
size_t * l0)
{
twist_cpu(padding,l0);
thread_mutex.lock();
keys.RecalculateIdentHash(buf);
thread_mutex.unlock();
}
void thread_find(const char * prefix){
while(NotThat(keys.GetPublic()->GetIdentHash().ToBase32().c_str(),prefix) and !finded)
{
size_t l0 = 0;
mutate_keys_cpu(KeyBuf,PaddingBuf, (size_t*)&l0);
hash++;
}
}
#endif
int main (int argc, char * argv[])
{
if ( argc < 3 )
{
std::cout << "Usage: " << argv[0] << " filename generatestring <signature type>" << std::endl;
return 0;
}
i2p::crypto::InitCrypto (false);
type = i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519;
if ( argc > 3 )
type = NameToSigType(std::string(argv[3]));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
keys = i2p::data::PrivateKeys::CreateRandomKeys (type);
switch(type){
case i2p::data::SIGNING_KEY_TYPE_DSA_SHA1:
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512:
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512_TEST:
std::cout << "Sorry, i don't can generate adress for this signature type" << std::endl;
return 0;
break;
}
switch(type){
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
padding_size=64;
break;
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
padding_size=32;
break;
case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
padding_size=4;
break;
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
padding_size=128;
break;
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
padding_size=256;
break;
case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
padding_size=384;
break;
case i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
padding_size=96;
break;
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256:
case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256_TEST:
padding_size=64;
break;
}
// TODO: multi threading
/*
TODO:
<orignal> Francezgy переделай пожалуйста треды
<orignal> без всех это pthread
* orignal has quit (Quit: Leaving)
*/
KeyBuf = new uint8_t[keys.GetFullLen()];
PaddingBuf = keys.GetPadding();
unsigned int count_cpu = sysconf(_SC_NPROCESSORS_ONLN);
std::vector<std::thread> threads(count_cpu);
std::cout << "Start vanity generator in " << count_cpu << " threads" << std::endl;
for ( unsigned int j = count_cpu;j--;){
threads[j] = std::thread(thread_find,argv[2]);
sched_param sch;
int policy;
pthread_getschedparam(threads[j].native_handle(), &policy, &sch);
sch.sched_priority = 10;
if (pthread_setschedparam(threads[j].native_handle(), SCHED_FIFO, &sch)) {
std::cout << "Failed to setschedparam" << std::endl;
return 1;
}
}
for(unsigned int j = 0; j < count_cpu;j++)
threads[j].join();
std::cout << "Hashes: " << hash << std::endl;
std::ofstream f (argv[1], std::ofstream::binary | std::ofstream::out);
if (f)
{
size_t len = keys.GetFullLen ();
len = keys.ToBuffer (KeyBuf, len);
f.write ((char *)KeyBuf, len);
delete [] KeyBuf;
std::cout << "Destination " << keys.GetPublic ()->GetIdentHash ().ToBase32 () << " created" << std::endl;
}
else
std::cout << "Can't create file " << argv[1] << std::endl;
i2p::crypto::TerminateCrypto ();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Delay deletion of view in View::DoRemoveChildView<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2009 Sacha Schutz <[email protected]>
* Copyright (C) 2009-2011 Guillaume Martres <[email protected]>
* Copyright (C) 2011 Laszlo Papp <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "sound.h"
#include "engine.h"
#include <core/debughelper.h>
#include <alure.h>
using namespace GluonAudio;
class Sound::SoundPrivate
{
public:
SoundPrivate()
: isValid(false)
, isStreamed(false)
, isLooping(false)
, status(STOPPED)
, stream(0)
, source(0)
, position(QVector3D( 0, 0, 0 ))
, volume(1.0f)
, pitch(1.0f)
, radius(10000.0f)
, duration(0)
{
}
~SoundPrivate()
{
}
bool newError( const QString& str )
{
QLatin1String error = QLatin1String( alureGetErrorString() );
if( error != QLatin1String( "No error" ) )
{
DEBUG_BLOCK
DEBUG_TEXT2( "Alure error: %1", error )
DEBUG_TEXT2( "%1", str )
isValid = false;
return true;
}
return false;
}
bool setupSource()
{
if( path.isEmpty() )
{
return false;
}
alGenSources( 1, &source );
if( source == 0 )
{
DEBUG_BLOCK
DEBUG_TEXT2( "Empty source, OpenAL error: %1", alGetError() )
return false;
}
ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
alSourcefv( source, AL_POSITION, sourcePosition );
alSourcef( source, AL_GAIN, volume );
alSourcef( source, AL_PITCH, pitch );
alSourcef( source, AL_REFERENCE_DISTANCE, radius );
return true;
}
void _k_deleteSource()
{
if( source != 0 )
{
alureStopSource( source, false );
alDeleteSources( 1, &source );
source = 0;
}
isValid = false;
status = STOPPED;
if( isStreamed )
{
alureDestroyStream( stream, 0, 0 );
}
stream = 0;
}
QString path;
bool isValid;
bool isStreamed;
bool isLooping;
Status status;
alureStream* stream;
ALuint source;
QVector3D position;
ALfloat volume;
ALfloat pitch;
ALfloat radius;
double duration;
};
Sound::Sound(QObject *parent)
: QObject( parent )
, d( new SoundPrivate )
{
d->isValid = false;
}
Sound::Sound( const QString& fileName )
: QObject( Engine::instance() )
, d( new SoundPrivate )
{
load( fileName );
}
Sound::~Sound()
{
d->_k_deleteSource();
delete d;
}
bool Sound::isValid() const
{
return d->isValid;
}
bool Sound::load( const QString& fileName )
{
if( fileName.isEmpty() )
{
d->isValid = false;
return false;
}
if( !d->path.isEmpty() )
{
d->_k_deleteSource();
}
d->path = fileName;
if( !d->setupSource() )
return false;
alureStreamSizeIsMicroSec(true);
alureStream *stream = alureCreateStreamFromFile(fileName.toLocal8Bit().data(), Engine::instance()->bufferLength(), 0, NULL);
if( stream )
d->duration = (double)alureGetStreamLength(stream) / alureGetStreamFrequency(stream);
d->isStreamed = (d->duration >= Engine::instance()->bufferLength()*Engine::instance()->buffersPerStream() / 1e6);
if( d->isStreamed )
d->stream = stream;
else
{
alureDestroyStream(stream, 0, NULL);
stream = NULL;
ALuint buffer = Engine::instance()->genBuffer( d->path );
if( d->newError( "Loading " + d->path + " failed" ) )
{
d->isValid = false;
return false;
}
alSourcei( d->source, AL_BUFFER, buffer );
}
d->isValid = !d->newError( "Loading " + d->path + " failed" );
return d->isValid;
}
ALfloat Sound::elapsedTime() const
{
ALfloat seconds = 0.f;
alGetSourcef( d->source, AL_SEC_OFFSET, &seconds );
return seconds;
}
ALint Sound::status() const
{
ALint status;
alGetSourcei( d->source, AL_SOURCE_STATE, &status );
return status;
}
bool Sound::isLooping() const
{
return d->isLooping;
}
bool Sound::isPlaying() const
{
return d->status == PLAYING;
}
bool Sound::isPaused() const
{
return d->status == PAUSED;
}
bool Sound::isStopped() const
{
return d->status == STOPPED;
}
void Sound::setLoop( bool enabled )
{
d->isLooping = enabled;
if( !d->isStreamed )
{
alSourcei( d->source, AL_LOOPING, enabled );
}
}
void Sound::clear()
{
d->_k_deleteSource();
}
QVector3D Sound::position() const
{
return d->position;
}
ALfloat Sound::x() const
{
return d->position.x();
}
ALfloat Sound::y() const
{
return d->position.y();
}
ALfloat Sound::z() const
{
return d->position.z();
}
ALfloat Sound::volume() const
{
return d->volume;
}
ALfloat Sound::pitch() const
{
return d->pitch;
}
ALfloat Sound::radius() const
{
return d->radius;
}
double Sound::duration() const
{
if( !d->isValid )
{
return 0;
}
return d->duration;
}
void Sound::setPosition( ALfloat x, ALfloat y, ALfloat z )
{
setPosition( QVector3D( x, y, z ) );
}
void Sound::setPosition( QVector3D position )
{
d->position = position;
ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
alSourcefv( d->source, AL_POSITION, sourcePosition );
}
void Sound::setVolume( ALfloat volume )
{
d->volume = volume;
alSourcef( d->source, AL_GAIN, volume );
}
void Sound::setPitch( ALfloat pitch )
{
d->pitch = pitch;
alSourcef( d->source, AL_PITCH, pitch );
}
void Sound::setRadius( ALfloat radius )
{
d->radius = radius;
alSourcef( d->source, AL_REFERENCE_DISTANCE, radius );
}
void Sound::callbackStopped( void* object, ALuint source )
{
static_cast<GluonAudio::Sound*>( object )->cbStop();
}
void Sound::cbStop()
{
d->status = STOPPED;
if( d->isLooping )
{
play();
}
else
{
emit stopped();
}
}
void Sound::play()
{
if( isPaused() )
{
alureResumeSource( d->source );
}
else if( isPlaying() )
{
stop();
}
if( d->isStreamed )
{
int loopCount = ( d->isLooping ? -1 : 0 );
alurePlaySourceStream( d->source, d->stream, Engine::instance()->buffersPerStream(), loopCount, Sound::callbackStopped, this );
}
else
{
alurePlaySource( d->source, callbackStopped, this );
}
d->status = PLAYING;
d->newError( "Playing " + d->path + " failed" );
emit played();
}
void Sound::pause()
{
alurePauseSource( d->source );
d->status = PAUSED;
d->newError( "Pausing " + d->path + " failed" );
emit paused();
}
void Sound::stop()
{
alureStopSource( d->source, false );
d->status = STOPPED;
d->newError( "Stopping " + d->path + " failed" );
}
void Sound::rewind()
{
if( d->isStreamed )
{
alureRewindStream( d->stream );
}
else
{
alSourceRewind( d->source );
}
d->newError( "Rewinding " + d->path + " failed" );
}
void Sound::setMinVolume( ALfloat min )
{
alSourcef( d->source, AL_MIN_GAIN, min );
}
void Sound::setMaxVolume( ALfloat max )
{
alSourcef( d->source, AL_MAX_GAIN, max );
}
void Sound::setVelocity( ALfloat vx, ALfloat vy, ALfloat vz )
{
ALfloat velocity[] = { vx, vy, vz };
alSourcefv( d->source, AL_VELOCITY, velocity );
}
void Sound::setDirection( ALfloat dx, ALfloat dy, ALfloat dz )
{
ALfloat direction[] = { dx, dy, dz };
alSourcefv( d->source, AL_POSITION, direction );
}
void Sound::setTimePosition( ALfloat time )
{
alSourcef( d->source, AL_SEC_OFFSET, time );
}
#include "sound.moc"
<commit_msg>Do not stop playing when Sound::play is called while already playing.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2009 Sacha Schutz <[email protected]>
* Copyright (C) 2009-2011 Guillaume Martres <[email protected]>
* Copyright (C) 2011 Laszlo Papp <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "sound.h"
#include "engine.h"
#include <core/debughelper.h>
#include <alure.h>
using namespace GluonAudio;
class Sound::SoundPrivate
{
public:
SoundPrivate()
: isValid(false)
, isStreamed(false)
, isLooping(false)
, status(STOPPED)
, stream(0)
, source(0)
, position(QVector3D( 0, 0, 0 ))
, volume(1.0f)
, pitch(1.0f)
, radius(10000.0f)
, duration(0)
{
}
~SoundPrivate()
{
}
bool newError( const QString& str )
{
QLatin1String error = QLatin1String( alureGetErrorString() );
if( error != QLatin1String( "No error" ) )
{
DEBUG_BLOCK
DEBUG_TEXT2( "Alure error: %1", error )
DEBUG_TEXT2( "%1", str )
isValid = false;
return true;
}
return false;
}
bool setupSource()
{
if( path.isEmpty() )
{
return false;
}
alGenSources( 1, &source );
if( source == 0 )
{
DEBUG_BLOCK
DEBUG_TEXT2( "Empty source, OpenAL error: %1", alGetError() )
return false;
}
ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
alSourcefv( source, AL_POSITION, sourcePosition );
alSourcef( source, AL_GAIN, volume );
alSourcef( source, AL_PITCH, pitch );
alSourcef( source, AL_REFERENCE_DISTANCE, radius );
return true;
}
void _k_deleteSource()
{
if( source != 0 )
{
alureStopSource( source, false );
alDeleteSources( 1, &source );
source = 0;
}
isValid = false;
status = STOPPED;
if( isStreamed )
{
alureDestroyStream( stream, 0, 0 );
}
stream = 0;
}
QString path;
bool isValid;
bool isStreamed;
bool isLooping;
Status status;
alureStream* stream;
ALuint source;
QVector3D position;
ALfloat volume;
ALfloat pitch;
ALfloat radius;
double duration;
};
Sound::Sound(QObject *parent)
: QObject( parent )
, d( new SoundPrivate )
{
d->isValid = false;
}
Sound::Sound( const QString& fileName )
: QObject( Engine::instance() )
, d( new SoundPrivate )
{
load( fileName );
}
Sound::~Sound()
{
d->_k_deleteSource();
delete d;
}
bool Sound::isValid() const
{
return d->isValid;
}
bool Sound::load( const QString& fileName )
{
if( fileName.isEmpty() )
{
d->isValid = false;
return false;
}
if( !d->path.isEmpty() )
{
d->_k_deleteSource();
}
d->path = fileName;
if( !d->setupSource() )
return false;
alureStreamSizeIsMicroSec(true);
alureStream *stream = alureCreateStreamFromFile(fileName.toLocal8Bit().data(), Engine::instance()->bufferLength(), 0, NULL);
if( stream )
d->duration = (double)alureGetStreamLength(stream) / alureGetStreamFrequency(stream);
d->isStreamed = (d->duration >= Engine::instance()->bufferLength()*Engine::instance()->buffersPerStream() / 1e6);
if( d->isStreamed )
d->stream = stream;
else
{
alureDestroyStream(stream, 0, NULL);
stream = NULL;
ALuint buffer = Engine::instance()->genBuffer( d->path );
if( d->newError( "Loading " + d->path + " failed" ) )
{
d->isValid = false;
return false;
}
alSourcei( d->source, AL_BUFFER, buffer );
}
d->isValid = !d->newError( "Loading " + d->path + " failed" );
return d->isValid;
}
ALfloat Sound::elapsedTime() const
{
ALfloat seconds = 0.f;
alGetSourcef( d->source, AL_SEC_OFFSET, &seconds );
return seconds;
}
ALint Sound::status() const
{
ALint status;
alGetSourcei( d->source, AL_SOURCE_STATE, &status );
return status;
}
bool Sound::isLooping() const
{
return d->isLooping;
}
bool Sound::isPlaying() const
{
return d->status == PLAYING;
}
bool Sound::isPaused() const
{
return d->status == PAUSED;
}
bool Sound::isStopped() const
{
return d->status == STOPPED;
}
void Sound::setLoop( bool enabled )
{
d->isLooping = enabled;
if( !d->isStreamed )
{
alSourcei( d->source, AL_LOOPING, enabled );
}
}
void Sound::clear()
{
d->_k_deleteSource();
}
QVector3D Sound::position() const
{
return d->position;
}
ALfloat Sound::x() const
{
return d->position.x();
}
ALfloat Sound::y() const
{
return d->position.y();
}
ALfloat Sound::z() const
{
return d->position.z();
}
ALfloat Sound::volume() const
{
return d->volume;
}
ALfloat Sound::pitch() const
{
return d->pitch;
}
ALfloat Sound::radius() const
{
return d->radius;
}
double Sound::duration() const
{
if( !d->isValid )
{
return 0;
}
return d->duration;
}
void Sound::setPosition( ALfloat x, ALfloat y, ALfloat z )
{
setPosition( QVector3D( x, y, z ) );
}
void Sound::setPosition( QVector3D position )
{
d->position = position;
ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
alSourcefv( d->source, AL_POSITION, sourcePosition );
}
void Sound::setVolume( ALfloat volume )
{
d->volume = volume;
alSourcef( d->source, AL_GAIN, volume );
}
void Sound::setPitch( ALfloat pitch )
{
d->pitch = pitch;
alSourcef( d->source, AL_PITCH, pitch );
}
void Sound::setRadius( ALfloat radius )
{
d->radius = radius;
alSourcef( d->source, AL_REFERENCE_DISTANCE, radius );
}
void Sound::callbackStopped( void* object, ALuint source )
{
static_cast<GluonAudio::Sound*>( object )->cbStop();
}
void Sound::cbStop()
{
d->status = STOPPED;
if( d->isLooping )
{
play();
}
else
{
emit stopped();
}
}
void Sound::play()
{
if( isPaused() )
{
alureResumeSource( d->source );
}
else if( isPlaying() )
{
return;
}
if( d->isStreamed )
{
int loopCount = ( d->isLooping ? -1 : 0 );
alurePlaySourceStream( d->source, d->stream, Engine::instance()->buffersPerStream(), loopCount, Sound::callbackStopped, this );
}
else
{
alurePlaySource( d->source, callbackStopped, this );
}
d->status = PLAYING;
d->newError( "Playing " + d->path + " failed" );
emit played();
}
void Sound::pause()
{
alurePauseSource( d->source );
d->status = PAUSED;
d->newError( "Pausing " + d->path + " failed" );
emit paused();
}
void Sound::stop()
{
alureStopSource( d->source, false );
d->status = STOPPED;
d->newError( "Stopping " + d->path + " failed" );
}
void Sound::rewind()
{
if( d->isStreamed )
{
alureRewindStream( d->stream );
}
else
{
alSourceRewind( d->source );
}
d->newError( "Rewinding " + d->path + " failed" );
}
void Sound::setMinVolume( ALfloat min )
{
alSourcef( d->source, AL_MIN_GAIN, min );
}
void Sound::setMaxVolume( ALfloat max )
{
alSourcef( d->source, AL_MAX_GAIN, max );
}
void Sound::setVelocity( ALfloat vx, ALfloat vy, ALfloat vz )
{
ALfloat velocity[] = { vx, vy, vz };
alSourcefv( d->source, AL_VELOCITY, velocity );
}
void Sound::setDirection( ALfloat dx, ALfloat dy, ALfloat dz )
{
ALfloat direction[] = { dx, dy, dz };
alSourcefv( d->source, AL_POSITION, direction );
}
void Sound::setTimePosition( ALfloat time )
{
alSourcef( d->source, AL_SEC_OFFSET, time );
}
#include "sound.moc"
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "common/errdbg/exceptions.h"
#include "ugnames.h"
/* {% globals */
static UGlobalNamesRegistryItem *registry = NULL;
static UGlobalNamesRegistrySearchProc searchProc = NULL;
/* }% */
#ifdef _WIN32
#define IPC_PRIVATE 0
#ifndef snprintf
#define snprintf _snprintf
#endif
#else
#include <sys/types.h>
#include <sys/ipc.h>
#endif
void
UReleaseGlobalNamesRegistry()
{
registry = NULL;
searchProc = NULL;
}
static
const UGlobalNamesRegistryItem *
SearchGlobalNamesRegistry(const UGlobalNamesRegistryItem *registry,
const char *basename)
{
assert(registry);
while (registry->basename && 0!=strcmp(registry->basename,basename)) ++registry;
return registry->basename ? registry : NULL;
}
static void ThrowSystemException(const char *msg)
{
throw SYSTEM_EXCEPTION(msg);
}
static int ValidateBaseName(const char *baseName)
{
/* TODO: implement validation */
return 1;
}
static int ValidateGlobalName(const char *globalName)
{
/* TODO: implement validation */
return 1;
}
static int ValidateCompoundName(const char *compoundName)
{
/* TODO: implement validation */
return 1;
}
void
UInitGlobalNamesRegistry(UGlobalNamesRegistryItem *registryParam,
UGlobalNamesRegistrySearchProc searchProcParam,
int rangeBegin,
int rangeEnd)
{
int rangeSizeMin = 0;
UGlobalNamesRegistryItem *i = NULL;
char errorBuf[128];
assert(registryParam);
/* first let's estimate the required range size */
for (i = registryParam; i->basename; ++i)
{
if (!ValidateBaseName(i->basename) || i->nObjectsMax<1 || (i->prefix==NULL && i->nObjectsMax > 1))
{
snprintf(errorBuf, sizeof errorBuf,
"UInitGlobalNamesRegistry: bad item '%s'", i->basename);
errorBuf[(sizeof errorBuf)-1]=0;
ThrowSystemException(errorBuf);
}
rangeSizeMin+=i->nObjectsMax;
}
registry = registryParam;
/* check if the passed range is ok */
if (rangeEnd - rangeBegin < rangeSizeMin)
ThrowSystemException("InitGlobalNamesRegistry: range too small");
/* now initialize per-entry ranges */
for (i = registry; i->basename; ++i)
{
i->rangeBegin = rangeBegin;
rangeBegin = i->rangeEnd = rangeBegin + i->nObjectsMax;
}
/* complete initialization */
searchProc = (searchProcParam ? searchProcParam : SearchGlobalNamesRegistry);
}
const char *
UCreateGlobalName(const char *basename,
int objectId,
char *buf,
size_t bufSize)
{
char prefix[32] = "", errorBuf[128];
int ordinal = 0;
const UGlobalNamesRegistryItem *item = NULL;
int stored = 0;
assert (basename);
item = searchProc(registry, basename);
if (!item)
{
snprintf(errorBuf, sizeof errorBuf, "CreateGlobalName: '%s' not found", basename);
errorBuf[(sizeof errorBuf)-1]=0;
ThrowSystemException(errorBuf);
}
ordinal = item->rangeBegin + objectId;
if (item->prefix)
{
stored = snprintf(prefix, sizeof prefix, "%s%d.", item->prefix, objectId);
if (stored<0 || (size_t)stored>=(sizeof prefix))
ThrowSystemException("UCreateGlobalName: prefix too long");
}
if (ordinal >= item->rangeEnd || ordinal < item->rangeBegin)
ThrowSystemException("CreateGlobalName: generated ordinal out of range");
stored = snprintf(buf, bufSize, "Global\\SEDNA%d.%s%s@%d", registry->rangeBegin, prefix, basename, ordinal);
if (stored<0 || (size_t)stored>=bufSize)
ThrowSystemException("CreateGlobalName: buffer too small");
return buf;
}
struct GlobalNameComponents
{
const char *strNameBegin, *strNameEnd;
int base, ordinal;
};
static
void ParseGlobalName(GlobalNameComponents *components,
const char *globalName)
{
assert(components);
if (globalName==NULL)
{
components->strNameBegin = NULL;
components->strNameEnd = NULL;
components->base = 0;
components->ordinal = 0;
}
else
{
const char *sep = NULL;
char *tail = NULL;
int ordinal = 0, base = 0;
sep = strchr(globalName,'@');
if (sep==NULL || (ordinal=strtol(sep+1,&tail,10), *tail!='\0'))
{
ThrowSystemException("ParseGlobalName: bad global name syntax");
}
components->strNameBegin = globalName;
components->strNameEnd = sep;
components->base = base;
components->ordinal = ordinal;
}
}
static
const char *StrNameFromGlobalName(const char *globalName,
size_t limit,
const char *prefix,
char *buf,
size_t bufSize)
{
char bufjr[16];
int partSz = 0, stored = 0;
GlobalNameComponents components = {NULL};
assert(prefix);
ParseGlobalName(&components,globalName);
if (globalName == NULL)
{
buf = NULL;
}
else
{
partSz = (int)(components.strNameEnd - components.strNameBegin);
stored = snprintf(buf, bufSize, "%s%.*s", prefix, partSz, components.strNameBegin);
if (stored<0 || (size_t)stored>=bufSize)
ThrowSystemException("StrNameFromGlobalName: buffer too small");
if (limit>0 && (size_t)stored>limit)
{
stored = snprintf(bufjr, sizeof bufjr, "~%d", components.ordinal);
if (stored<0 || (size_t)stored>=sizeof bufjr) ThrowSystemException("StrNameFromGlobalName: internal error");
if ((size_t)stored>limit) ThrowSystemException("StrNameFromGlobalName: impossible limit");
strcpy(buf+limit-stored, bufjr);
}
}
return buf;
}
const char *UWinIPCNameFromGlobalName(const char *globalName,
char *buf,
size_t bufSize)
{
return StrNameFromGlobalName(globalName, 0, "", buf, bufSize);
}
const char *UPosixIPCNameFromGlobalName(const char *globalName,
char *buf,
size_t bufSize)
{
const char *prefix = "/";
size_t limit = 0;
#if (defined(FreeBSD) || defined(DARWIN))
prefix = "/tmp/";
#endif
#if defined(DARWIN)
limit = 30;
#endif
return StrNameFromGlobalName(globalName, limit, prefix, buf, bufSize);
}
int USys5IPCKeyFromGlobalName(const char *globalName)
{
int key = 0;
GlobalNameComponents components = {NULL};
ParseGlobalName(&components,globalName);
if (globalName == NULL)
{
key = IPC_PRIVATE;
}
else
{
key = components.ordinal;
if (key==IPC_PRIVATE)
ThrowSystemException("USys5IPCKeyFromGlobalName: bad key");
}
return key;
}
const char *
UCreateCompoundName(const char **namesVec,
size_t namesCount,
char *buf,
size_t bufSize)
{
size_t nameLen = 0;
const char **nameCur = namesVec, **namesEnd = namesVec+namesCount;
char *bufpos = buf;
assert(buf && bufSize>0);
strcpy(bufpos,"");
while(nameCur != namesEnd)
{
if (nameCur!=namesVec)
{
/* checked there is enough room in buf on previous iteration */
strcpy(bufpos,",");
++bufpos; bufSize-=1;
}
if (!ValidateGlobalName(*nameCur))
ThrowSystemException("UCreateCompoundName: bad global name syntax");
nameLen = (*nameCur?strlen(*nameCur):0);
if (bufSize < nameLen + 2)
ThrowSystemException("UCreateCompoundName: buffer too small");
if (*nameCur)
{
strcpy(bufpos, *nameCur);
bufpos+=nameLen;
bufSize-=nameLen;
}
++nameCur;
}
return buf;
}
const char *
UGlobalNameFromCompoundName(const char *compoundName,
int index,
char *buf,
size_t bufSize)
{
const char *pos = NULL, *epos=NULL;
assert(buf && compoundName);
if (!ValidateCompoundName(compoundName))
{
ThrowSystemException("UGlobalNameFromCompoundName: bad compound name syntax");
}
else
{
pos = compoundName;
while(index > 0 && pos)
{
pos = strchr(pos,',');
if (pos) pos+=1;
--index;
}
if (!pos || index<0)
{
ThrowSystemException("UGlobalNameFromCompoundName: index out of range");
}
epos = strchr(pos,',');
if (!epos) epos=pos+strlen(pos);
if (bufSize < (unsigned int) (epos-pos+1))
{
ThrowSystemException("UGlobalNameFromCompoundName: buffer too small");
}
if (pos == epos)
{
buf = NULL;
}
else
{
memcpy(buf,pos,epos-pos);
buf[epos-pos]=0;
}
}
return buf;
}
<commit_msg>revert unintended patch from the previous commit<commit_after>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "common/errdbg/exceptions.h"
#include "ugnames.h"
/* {% globals */
static UGlobalNamesRegistryItem *registry = NULL;
static UGlobalNamesRegistrySearchProc searchProc = NULL;
/* }% */
#ifdef _WIN32
#define IPC_PRIVATE 0
#ifndef snprintf
#define snprintf _snprintf
#endif
#else
#include <sys/types.h>
#include <sys/ipc.h>
#endif
void
UReleaseGlobalNamesRegistry()
{
registry = NULL;
searchProc = NULL;
}
static
const UGlobalNamesRegistryItem *
SearchGlobalNamesRegistry(const UGlobalNamesRegistryItem *registry,
const char *basename)
{
assert(registry);
while (registry->basename && 0!=strcmp(registry->basename,basename)) ++registry;
return registry->basename ? registry : NULL;
}
static void ThrowSystemException(const char *msg)
{
throw SYSTEM_EXCEPTION(msg);
}
static int ValidateBaseName(const char *baseName)
{
/* TODO: implement validation */
return 1;
}
static int ValidateGlobalName(const char *globalName)
{
/* TODO: implement validation */
return 1;
}
static int ValidateCompoundName(const char *compoundName)
{
/* TODO: implement validation */
return 1;
}
void
UInitGlobalNamesRegistry(UGlobalNamesRegistryItem *registryParam,
UGlobalNamesRegistrySearchProc searchProcParam,
int rangeBegin,
int rangeEnd)
{
int rangeSizeMin = 0;
UGlobalNamesRegistryItem *i = NULL;
char errorBuf[128];
assert(registryParam);
/* first let's estimate the required range size */
for (i = registryParam; i->basename; ++i)
{
if (!ValidateBaseName(i->basename) || i->nObjectsMax<1 || (i->prefix==NULL && i->nObjectsMax > 1))
{
snprintf(errorBuf, sizeof errorBuf,
"UInitGlobalNamesRegistry: bad item '%s'", i->basename);
errorBuf[(sizeof errorBuf)-1]=0;
ThrowSystemException(errorBuf);
}
rangeSizeMin+=i->nObjectsMax;
}
registry = registryParam;
/* check if the passed range is ok */
if (rangeEnd - rangeBegin < rangeSizeMin)
ThrowSystemException("InitGlobalNamesRegistry: range too small");
/* now initialize per-entry ranges */
for (i = registry; i->basename; ++i)
{
i->rangeBegin = rangeBegin;
rangeBegin = i->rangeEnd = rangeBegin + i->nObjectsMax;
}
/* complete initialization */
searchProc = (searchProcParam ? searchProcParam : SearchGlobalNamesRegistry);
}
const char *
UCreateGlobalName(const char *basename,
int objectId,
char *buf,
size_t bufSize)
{
char prefix[32] = "", errorBuf[128];
int ordinal = 0;
const UGlobalNamesRegistryItem *item = NULL;
int stored = 0;
assert (basename);
item = searchProc(registry, basename);
if (!item)
{
snprintf(errorBuf, sizeof errorBuf, "CreateGlobalName: '%s' not found", basename);
errorBuf[(sizeof errorBuf)-1]=0;
ThrowSystemException(errorBuf);
}
ordinal = item->rangeBegin + objectId;
if (item->prefix)
{
stored = snprintf(prefix, sizeof prefix, "%s%d.", item->prefix, objectId);
if (stored<0 || (size_t)stored>=(sizeof prefix))
ThrowSystemException("UCreateGlobalName: prefix too long");
}
if (ordinal >= item->rangeEnd || ordinal < item->rangeBegin)
ThrowSystemException("CreateGlobalName: generated ordinal out of range");
stored = snprintf(buf, bufSize, "SEDNA%d.%s%s@%d", registry->rangeBegin, prefix, basename, ordinal);
if (stored<0 || (size_t)stored>=bufSize)
ThrowSystemException("CreateGlobalName: buffer too small");
return buf;
}
struct GlobalNameComponents
{
const char *strNameBegin, *strNameEnd;
int base, ordinal;
};
static
void ParseGlobalName(GlobalNameComponents *components,
const char *globalName)
{
assert(components);
if (globalName==NULL)
{
components->strNameBegin = NULL;
components->strNameEnd = NULL;
components->base = 0;
components->ordinal = 0;
}
else
{
const char *sep = NULL;
char *tail = NULL;
int ordinal = 0, base = 0;
sep = strchr(globalName,'@');
if (sep==NULL || (ordinal=strtol(sep+1,&tail,10), *tail!='\0'))
{
ThrowSystemException("ParseGlobalName: bad global name syntax");
}
components->strNameBegin = globalName;
components->strNameEnd = sep;
components->base = base;
components->ordinal = ordinal;
}
}
static
const char *StrNameFromGlobalName(const char *globalName,
size_t limit,
const char *prefix,
char *buf,
size_t bufSize)
{
char bufjr[16];
int partSz = 0, stored = 0;
GlobalNameComponents components = {NULL};
assert(prefix);
ParseGlobalName(&components,globalName);
if (globalName == NULL)
{
buf = NULL;
}
else
{
partSz = (int)(components.strNameEnd - components.strNameBegin);
stored = snprintf(buf, bufSize, "%s%.*s", prefix, partSz, components.strNameBegin);
if (stored<0 || (size_t)stored>=bufSize)
ThrowSystemException("StrNameFromGlobalName: buffer too small");
if (limit>0 && (size_t)stored>limit)
{
stored = snprintf(bufjr, sizeof bufjr, "~%d", components.ordinal);
if (stored<0 || (size_t)stored>=sizeof bufjr) ThrowSystemException("StrNameFromGlobalName: internal error");
if ((size_t)stored>limit) ThrowSystemException("StrNameFromGlobalName: impossible limit");
strcpy(buf+limit-stored, bufjr);
}
}
return buf;
}
const char *UWinIPCNameFromGlobalName(const char *globalName,
char *buf,
size_t bufSize)
{
return StrNameFromGlobalName(globalName, 0, "", buf, bufSize);
}
const char *UPosixIPCNameFromGlobalName(const char *globalName,
char *buf,
size_t bufSize)
{
const char *prefix = "/";
size_t limit = 0;
#if (defined(FreeBSD) || defined(DARWIN))
prefix = "/tmp/";
#endif
#if defined(DARWIN)
limit = 30;
#endif
return StrNameFromGlobalName(globalName, limit, prefix, buf, bufSize);
}
int USys5IPCKeyFromGlobalName(const char *globalName)
{
int key = 0;
GlobalNameComponents components = {NULL};
ParseGlobalName(&components,globalName);
if (globalName == NULL)
{
key = IPC_PRIVATE;
}
else
{
key = components.ordinal;
if (key==IPC_PRIVATE)
ThrowSystemException("USys5IPCKeyFromGlobalName: bad key");
}
return key;
}
const char *
UCreateCompoundName(const char **namesVec,
size_t namesCount,
char *buf,
size_t bufSize)
{
size_t nameLen = 0;
const char **nameCur = namesVec, **namesEnd = namesVec+namesCount;
char *bufpos = buf;
assert(buf && bufSize>0);
strcpy(bufpos,"");
while(nameCur != namesEnd)
{
if (nameCur!=namesVec)
{
/* checked there is enough room in buf on previous iteration */
strcpy(bufpos,",");
++bufpos; bufSize-=1;
}
if (!ValidateGlobalName(*nameCur))
ThrowSystemException("UCreateCompoundName: bad global name syntax");
nameLen = (*nameCur?strlen(*nameCur):0);
if (bufSize < nameLen + 2)
ThrowSystemException("UCreateCompoundName: buffer too small");
if (*nameCur)
{
strcpy(bufpos, *nameCur);
bufpos+=nameLen;
bufSize-=nameLen;
}
++nameCur;
}
return buf;
}
const char *
UGlobalNameFromCompoundName(const char *compoundName,
int index,
char *buf,
size_t bufSize)
{
const char *pos = NULL, *epos=NULL;
assert(buf && compoundName);
if (!ValidateCompoundName(compoundName))
{
ThrowSystemException("UGlobalNameFromCompoundName: bad compound name syntax");
}
else
{
pos = compoundName;
while(index > 0 && pos)
{
pos = strchr(pos,',');
if (pos) pos+=1;
--index;
}
if (!pos || index<0)
{
ThrowSystemException("UGlobalNameFromCompoundName: index out of range");
}
epos = strchr(pos,',');
if (!epos) epos=pos+strlen(pos);
if (bufSize < (unsigned int) (epos-pos+1))
{
ThrowSystemException("UGlobalNameFromCompoundName: buffer too small");
}
if (pos == epos)
{
buf = NULL;
}
else
{
memcpy(buf,pos,epos-pos);
buf[epos-pos]=0;
}
}
return buf;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#include <iostream>
#include <sstream>
#ifdef __APPLE__
#include <dlfcn.h>
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#ifdef __ANDROID__
#include <android/log.h>
#endif
#include <realm/util/terminate.hpp>
namespace {
// extern "C" and noinline so that a readable message shows up in the stack trace
// of the crash
// prototype here to silence warning
extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io();
extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io() {
std::abort();
}
#ifdef __APPLE__
void nslog(const char *message) {
CFStringRef str = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull);
CFShow(str);
// Log the message to Crashlytics if it's loaded into the process
void* addr = dlsym(RTLD_DEFAULT, "CLSLog");
if (addr) {
auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr));
fn(CFSTR("%@"), str);
}
CFRelease(str);
}
#endif
} // unnamed namespace
namespace realm {
namespace util {
REALM_NORETURN void terminate_internal(std::stringstream& ss) noexcept
{
#if defined(__APPLE__)
void* callstack[128];
int frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (int i = 0; i < frames; ++i) {
ss << strs[i] << '\n';
}
free(strs);
#endif
ss << "IMPORTANT: if you see this error, please send this log to [email protected].";
#ifdef REALM_DEBUG
std::cerr << ss.rdbuf() << '\n';
#endif
#if defined(__APPLE__)
nslog(ss.str().c_str());
#elif defined(__ANDROID__)
__android_log_print(ANDROID_LOG_ERROR, "REALM", ss.str().c_str());
#endif
please_report_this_error_to_help_at_realm_dot_io();
}
REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept
{
std::stringstream ss;
ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n';
terminate_internal(ss);
}
} // namespace util
} // namespace realm
<commit_msg>Erroneously placed `please_report_this_error_to_help_at_realm_dot_io` in an unnamed namespace.<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#include <iostream>
#include <sstream>
#ifdef __APPLE__
#include <dlfcn.h>
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#ifdef __ANDROID__
#include <android/log.h>
#endif
#include <realm/util/terminate.hpp>
// extern "C" and noinline so that a readable message shows up in the stack trace
// of the crash
// prototype here to silence warning
extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io();
extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io() {
std::abort();
}
namespace {
#ifdef __APPLE__
void nslog(const char *message) {
CFStringRef str = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull);
CFShow(str);
// Log the message to Crashlytics if it's loaded into the process
void* addr = dlsym(RTLD_DEFAULT, "CLSLog");
if (addr) {
auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr));
fn(CFSTR("%@"), str);
}
CFRelease(str);
}
#endif
} // unnamed namespace
namespace realm {
namespace util {
REALM_NORETURN void terminate_internal(std::stringstream& ss) noexcept
{
#if defined(__APPLE__)
void* callstack[128];
int frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (int i = 0; i < frames; ++i) {
ss << strs[i] << '\n';
}
free(strs);
#endif
ss << "IMPORTANT: if you see this error, please send this log to [email protected].";
#ifdef REALM_DEBUG
std::cerr << ss.rdbuf() << '\n';
#endif
#if defined(__APPLE__)
nslog(ss.str().c_str());
#elif defined(__ANDROID__)
__android_log_print(ANDROID_LOG_ERROR, "REALM", ss.str().c_str());
#endif
please_report_this_error_to_help_at_realm_dot_io();
}
REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept
{
std::stringstream ss;
ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n';
terminate_internal(ss);
}
} // namespace util
} // namespace realm
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY, TITLE, NONINFRINGEMENT or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
#include "winsock.h"
#include <objbase.h>
#include <initguid.h>
#include <connmgr.h>
#include <wininet.h>
#include "http/GPRSConnection.h"
#include "base/Log.h"
/*
* Method to test if connection is alive. If no one is found, it tries to establish
* default connection.
*/
BOOL EstablishConnection() {
HANDLE phWebConnection = NULL;
// First we check if we might have a connection
DWORD pdwStatus = 0;
LOG.info("Establish connection: test internet connection status...");
ConnMgrConnectionStatus(phWebConnection, &pdwStatus);
if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
LOG.info("Arleady connected");
//We are already connected!
return TRUE;
}
#if _WIN32_WCE > 0x500
else if (pdwStatus == CONNMGR_STATUS_PHONEOFF) {
LOG.info("phone off");
//We are already connected!
return FALSE;
}
#endif
else {
LOG.debug("Not connected: try to connect...");
//We are not connected, so lets try:
//The CONNECTIONINFO is the structure that
//tells Connection Manager how we want
//to connect
CONNMGR_CONNECTIONINFO sConInfo;
memset(&sConInfo,0, sizeof(CONNMGR_CONNECTIONINFO));
sConInfo.cbSize = sizeof(CONNMGR_CONNECTIONINFO);
// We want to use the "guidDestNet" parameter
sConInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
// This is the highest data priority.
sConInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
// sConInfo.dwFlags = 0;
sConInfo.dwFlags=CONNMGR_FLAG_PROXY_HTTP;
// Lets be nice and share the connection with
// other applications
sConInfo.bExclusive = FALSE;
sConInfo.bDisabled = FALSE;
sConInfo.guidDestNet = IID_DestNetInternet;
LOG.debug("Try to establish connection...");
if (ConnMgrEstablishConnection(&sConInfo,&phWebConnection) == S_OK) {
LOG.debug("Start internet connection process...");
//We start successfully process!
for (unsigned int k = 0; k < 6; k++) {
ConnMgrConnectionStatus(phWebConnection,&pdwStatus);
if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
LOG.info("Internet connection succesfully completed.");
return TRUE;
}
else {
if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
LOG.debug("Internet connection not succeded.");
return FALSE;
}
Sleep(2000);
ConnMgrConnectionStatus(phWebConnection,&pdwStatus);
if (pdwStatus == CONNMGR_STATUS_WAITINGCONNECTION) {
// it is possible to do something...
}
if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
LOG.debug("Internet connection not succeded");
return FALSE;
}
}
}
LOG.debug("Internet connection not succeded after connection process");
return FALSE;
}
else {
//Connection failed!
LOG.info("Internet connection failed.");
return FALSE;
}
}
}
<commit_msg>use winsock2 lib<commit_after>/*
* Copyright (C) 2003-2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY, TITLE, NONINFRINGEMENT or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
#include "winsock2.h"
#include <objbase.h>
#include <initguid.h>
#include <connmgr.h>
#include <wininet.h>
#include "http/GPRSConnection.h"
#include "base/Log.h"
/*
* Method to test if connection is alive. If no one is found, it tries to establish
* default connection.
*/
BOOL EstablishConnection() {
HANDLE phWebConnection = NULL;
// First we check if we might have a connection
DWORD pdwStatus = 0;
LOG.info("Establish connection: test internet connection status...");
ConnMgrConnectionStatus(phWebConnection, &pdwStatus);
if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
LOG.info("Arleady connected");
//We are already connected!
return TRUE;
}
#if _WIN32_WCE > 0x500
else if (pdwStatus == CONNMGR_STATUS_PHONEOFF) {
LOG.info("phone off");
//We are already connected!
return FALSE;
}
#endif
else {
LOG.debug("Not connected: try to connect...");
//We are not connected, so lets try:
//The CONNECTIONINFO is the structure that
//tells Connection Manager how we want
//to connect
CONNMGR_CONNECTIONINFO sConInfo;
memset(&sConInfo,0, sizeof(CONNMGR_CONNECTIONINFO));
sConInfo.cbSize = sizeof(CONNMGR_CONNECTIONINFO);
// We want to use the "guidDestNet" parameter
sConInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
// This is the highest data priority.
sConInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
// sConInfo.dwFlags = 0;
sConInfo.dwFlags=CONNMGR_FLAG_PROXY_HTTP;
// Lets be nice and share the connection with
// other applications
sConInfo.bExclusive = FALSE;
sConInfo.bDisabled = FALSE;
sConInfo.guidDestNet = IID_DestNetInternet;
LOG.debug("Try to establish connection...");
if (ConnMgrEstablishConnection(&sConInfo,&phWebConnection) == S_OK) {
LOG.debug("Start internet connection process...");
//We start successfully process!
for (unsigned int k = 0; k < 6; k++) {
ConnMgrConnectionStatus(phWebConnection,&pdwStatus);
if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
LOG.info("Internet connection succesfully completed.");
return TRUE;
}
else {
if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
LOG.debug("Internet connection not succeded.");
return FALSE;
}
Sleep(2000);
ConnMgrConnectionStatus(phWebConnection,&pdwStatus);
if (pdwStatus == CONNMGR_STATUS_WAITINGCONNECTION) {
// it is possible to do something...
}
if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
LOG.debug("Internet connection not succeded");
return FALSE;
}
}
}
LOG.debug("Internet connection not succeded after connection process");
return FALSE;
}
else {
//Connection failed!
LOG.info("Internet connection failed.");
return FALSE;
}
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/rendering/renderable.h>
#include <openspace/camera/camera.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/events/event.h>
#include <openspace/events/eventengine.h>
#include <openspace/navigation/navigationhandler.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/memorymanager.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/misc/profiling.h>
#include <ghoul/opengl/programobject.h>
#include <optional>
namespace {
constexpr std::string_view KeyType = "Type";
constexpr openspace::properties::Property::PropertyInfo EnabledInfo = {
"Enabled",
"Is Enabled",
"This setting determines whether this object will be visible or not"
};
constexpr openspace::properties::Property::PropertyInfo OpacityInfo = {
"Opacity",
"Opacity",
"This value determines the opacity of this renderable. A value of 0 means "
"completely transparent"
};
constexpr openspace::properties::Property::PropertyInfo FadeInfo = {
"Fade",
"Fade",
"This value is used by the system to be able to fade out renderables "
"independently from the Opacity value selected by the user. This value should "
"not be directly manipulated through a user interface, but instead used by other "
"components of the system programmatically",
// The Developer mode should be used once the properties in the UI listen to this
// openspace::properties::Property::Visibility::Developer
openspace::properties::Property::Visibility::Hidden
};
constexpr openspace::properties::Property::PropertyInfo RenderableTypeInfo = {
"Type",
"Renderable Type",
"This tells the type of the renderable",
openspace::properties::Property::Visibility::Hidden
};
constexpr openspace::properties::Property::PropertyInfo RenderableRenderBinModeInfo =
{
"RenderBinMode",
"Render Bin Mode",
"This value specifies if the renderable should be rendered in the Background,"
"Opaque, Pre/PostDeferredTransparency, or Overlay rendering step",
openspace::properties::Property::Visibility::Developer
};
constexpr openspace::properties::Property::PropertyInfo DimInAtmosphereInfo = {
"DimInAtmosphere",
"Dim In Atmosphere",
"Enables/Disables if the object should be dimmed if the camera is in an "
"atmosphere",
openspace::properties::Property::Visibility::Developer
};
struct [[codegen::Dictionary(Renderable)]] Parameters {
// [[codegen::verbatim(EnabledInfo.description)]]
std::optional<bool> enabled;
// [[codegen::verbatim(OpacityInfo.description)]]
std::optional<float> opacity [[codegen::inrange(0.0, 1.0)]];
// A single tag or a list of tags that this renderable will respond to when
// setting properties
std::optional<std::variant<std::vector<std::string>, std::string>> tag;
// [[codegen::verbatim(RenderableTypeInfo.description)]]
std::optional<std::string> type;
// Fragile! Keep in sync with documentation
enum class [[codegen::map(openspace::Renderable::RenderBin)]] RenderBinMode {
Background,
Opaque,
PreDeferredTransparent,
PostDeferredTransparent,
Overlay
};
// [[codegen::verbatim(RenderableRenderBinModeInfo.description)]]
std::optional<RenderBinMode> renderBinMode;
// [[codegen::verbatim(DimInAtmosphereInfo.description)]]
std::optional<bool> dimInAtmosphere;
};
#include "renderable_codegen.cpp"
} // namespace
namespace openspace {
documentation::Documentation Renderable::Documentation() {
return codegen::doc<Parameters>("renderable");
}
ghoul::mm_unique_ptr<Renderable> Renderable::createFromDictionary(
ghoul::Dictionary dictionary)
{
if (!dictionary.hasKey(KeyType)) {
throw ghoul::RuntimeError("Tried to create Renderable but no 'Type' was found");
}
// This should be done in the constructor instead with noexhaustive
documentation::testSpecificationAndThrow(Documentation(), dictionary, "Renderable");
std::string renderableType = dictionary.value<std::string>(KeyType);
ghoul::TemplateFactory<Renderable>* factory =
FactoryManager::ref().factory<Renderable>();
ghoul_assert(factory, "Renderable factory did not exist");
Renderable* result = factory->create(
renderableType,
dictionary,
&global::memoryManager->PersistentMemory
);
return ghoul::mm_unique_ptr<Renderable>(result);
}
Renderable::Renderable(const ghoul::Dictionary& dictionary)
: properties::PropertyOwner({ "Renderable" })
, _enabled(EnabledInfo, true)
, _opacity(OpacityInfo, 1.f, 0.f, 1.f)
, _fade(FadeInfo, 1.f, 0.f, 1.f)
, _renderableType(RenderableTypeInfo, "Renderable")
, _dimInAtmosphere(DimInAtmosphereInfo, false)
{
ZoneScoped
// I can't come up with a good reason not to do this for all renderables
registerUpdateRenderBinFromOpacity();
const Parameters p = codegen::bake<Parameters>(dictionary);
if (p.tag.has_value()) {
if (std::holds_alternative<std::string>(*p.tag)) {
if (!std::get<std::string>(*p.tag).empty()) {
addTag(std::get<std::string>(*p.tag));
}
}
else {
ghoul_assert(std::holds_alternative<std::vector<std::string>>(*p.tag), "");
for (std::string tag : std::get<std::vector<std::string>>(*p.tag)) {
addTag(std::move(tag));
}
}
}
_enabled = p.enabled.value_or(_enabled);
addProperty(_enabled);
_enabled.onChange([this]() {
if (isEnabled()) {
global::eventEngine->publishEvent<events::EventRenderableEnabled>(_parent);
}
else {
global::eventEngine->publishEvent<events::EventRenderableDisabled>(_parent);
}
});
_opacity = p.opacity.value_or(_opacity);
// We don't add the property here as subclasses should decide on their own whether
// they to expose the opacity or not
addProperty(_fade);
// set type for UI
_renderableType = p.type.value_or(_renderableType);
addProperty(_renderableType);
// only used by a few classes such as RenderableTrail and RenderableSphere
if (p.renderBinMode.has_value()) {
setRenderBin(codegen::map<Renderable::RenderBin>(*p.renderBinMode));
}
_dimInAtmosphere = p.dimInAtmosphere.value_or(_dimInAtmosphere);
addProperty(_dimInAtmosphere);
}
void Renderable::initialize() {}
void Renderable::initializeGL() {}
void Renderable::deinitialize() {}
void Renderable::deinitializeGL() {}
void Renderable::update(const UpdateData&) {}
void Renderable::render(const RenderData&, RendererTasks&) {}
void Renderable::setBoundingSphere(double boundingSphere) {
_boundingSphere = boundingSphere;
}
double Renderable::boundingSphere() const {
return _boundingSphere;
}
void Renderable::setInteractionSphere(double interactionSphere) {
_interactionSphere = interactionSphere;
}
double Renderable::interactionSphere() const {
return _interactionSphere;
}
SurfacePositionHandle Renderable::calculateSurfacePositionHandle(
const glm::dvec3& targetModelSpace) const
{
const glm::dvec3 directionFromCenterToTarget = glm::normalize(targetModelSpace);
return {
directionFromCenterToTarget * _parent->interactionSphere(),
directionFromCenterToTarget,
0.0
};
}
bool Renderable::renderedWithDesiredData() const {
return true;
}
Renderable::RenderBin Renderable::renderBin() const {
return _renderBin;
}
void Renderable::setRenderBin(RenderBin bin) {
_renderBin = bin;
}
bool Renderable::matchesRenderBinMask(int binMask) {
return binMask & static_cast<int>(renderBin());
}
bool Renderable::isVisible() const {
return _enabled && _opacity > 0.f && _fade > 0.f;
}
bool Renderable::isReady() const {
return true;
}
bool Renderable::isEnabled() const {
return _enabled;
}
bool Renderable::shouldUpdateIfDisabled() const {
return _shouldUpdateIfDisabled;
}
void Renderable::onEnabledChange(std::function<void(bool)> callback) {
_enabled.onChange([this, c = std::move(callback)]() {
c(isEnabled());
});
}
void Renderable::setRenderBinFromOpacity() {
if ((_renderBin != Renderable::RenderBin::PostDeferredTransparent) &&
(_renderBin != Renderable::RenderBin::Overlay))
{
const float v = opacity();
if (v >= 0.f && v < 1.f) {
setRenderBin(Renderable::RenderBin::PreDeferredTransparent);
}
else {
setRenderBin(Renderable::RenderBin::Opaque);
}
}
}
void Renderable::registerUpdateRenderBinFromOpacity() {
_opacity.onChange([this]() { setRenderBinFromOpacity(); });
_fade.onChange([this]() { setRenderBinFromOpacity(); });
}
float Renderable::opacity() const {
// Rendering should depend on if camera is in the atmosphere and if camera is at the
// dark part of the globe
return _dimInAtmosphere ?
_opacity * _fade * global::navigationHandler->camera()->atmosphereDimmingFactor() :
_opacity * _fade;
}
} // namespace openspace
<commit_msg>Clarify info for the the Dim In Atmosphere property<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/rendering/renderable.h>
#include <openspace/camera/camera.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/events/event.h>
#include <openspace/events/eventengine.h>
#include <openspace/navigation/navigationhandler.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/memorymanager.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/misc/profiling.h>
#include <ghoul/opengl/programobject.h>
#include <optional>
namespace {
constexpr std::string_view KeyType = "Type";
constexpr openspace::properties::Property::PropertyInfo EnabledInfo = {
"Enabled",
"Is Enabled",
"This setting determines whether this object will be visible or not"
};
constexpr openspace::properties::Property::PropertyInfo OpacityInfo = {
"Opacity",
"Opacity",
"This value determines the opacity of this renderable. A value of 0 means "
"completely transparent"
};
constexpr openspace::properties::Property::PropertyInfo FadeInfo = {
"Fade",
"Fade",
"This value is used by the system to be able to fade out renderables "
"independently from the Opacity value selected by the user. This value should "
"not be directly manipulated through a user interface, but instead used by other "
"components of the system programmatically",
// The Developer mode should be used once the properties in the UI listen to this
// openspace::properties::Property::Visibility::Developer
openspace::properties::Property::Visibility::Hidden
};
constexpr openspace::properties::Property::PropertyInfo RenderableTypeInfo = {
"Type",
"Renderable Type",
"This tells the type of the renderable",
openspace::properties::Property::Visibility::Hidden
};
constexpr openspace::properties::Property::PropertyInfo RenderableRenderBinModeInfo =
{
"RenderBinMode",
"Render Bin Mode",
"This value specifies if the renderable should be rendered in the Background,"
"Opaque, Pre/PostDeferredTransparency, or Overlay rendering step",
openspace::properties::Property::Visibility::Developer
};
constexpr openspace::properties::Property::PropertyInfo DimInAtmosphereInfo = {
"DimInAtmosphere",
"Dim In Atmosphere",
"Enables/Disables if the object should be dimmed when the camera is in the "
"sunny part of an atmosphere",
openspace::properties::Property::Visibility::Developer
};
struct [[codegen::Dictionary(Renderable)]] Parameters {
// [[codegen::verbatim(EnabledInfo.description)]]
std::optional<bool> enabled;
// [[codegen::verbatim(OpacityInfo.description)]]
std::optional<float> opacity [[codegen::inrange(0.0, 1.0)]];
// A single tag or a list of tags that this renderable will respond to when
// setting properties
std::optional<std::variant<std::vector<std::string>, std::string>> tag;
// [[codegen::verbatim(RenderableTypeInfo.description)]]
std::optional<std::string> type;
// Fragile! Keep in sync with documentation
enum class [[codegen::map(openspace::Renderable::RenderBin)]] RenderBinMode {
Background,
Opaque,
PreDeferredTransparent,
PostDeferredTransparent,
Overlay
};
// [[codegen::verbatim(RenderableRenderBinModeInfo.description)]]
std::optional<RenderBinMode> renderBinMode;
// [[codegen::verbatim(DimInAtmosphereInfo.description)]]
std::optional<bool> dimInAtmosphere;
};
#include "renderable_codegen.cpp"
} // namespace
namespace openspace {
documentation::Documentation Renderable::Documentation() {
return codegen::doc<Parameters>("renderable");
}
ghoul::mm_unique_ptr<Renderable> Renderable::createFromDictionary(
ghoul::Dictionary dictionary)
{
if (!dictionary.hasKey(KeyType)) {
throw ghoul::RuntimeError("Tried to create Renderable but no 'Type' was found");
}
// This should be done in the constructor instead with noexhaustive
documentation::testSpecificationAndThrow(Documentation(), dictionary, "Renderable");
std::string renderableType = dictionary.value<std::string>(KeyType);
ghoul::TemplateFactory<Renderable>* factory =
FactoryManager::ref().factory<Renderable>();
ghoul_assert(factory, "Renderable factory did not exist");
Renderable* result = factory->create(
renderableType,
dictionary,
&global::memoryManager->PersistentMemory
);
return ghoul::mm_unique_ptr<Renderable>(result);
}
Renderable::Renderable(const ghoul::Dictionary& dictionary)
: properties::PropertyOwner({ "Renderable" })
, _enabled(EnabledInfo, true)
, _opacity(OpacityInfo, 1.f, 0.f, 1.f)
, _fade(FadeInfo, 1.f, 0.f, 1.f)
, _renderableType(RenderableTypeInfo, "Renderable")
, _dimInAtmosphere(DimInAtmosphereInfo, false)
{
ZoneScoped
// I can't come up with a good reason not to do this for all renderables
registerUpdateRenderBinFromOpacity();
const Parameters p = codegen::bake<Parameters>(dictionary);
if (p.tag.has_value()) {
if (std::holds_alternative<std::string>(*p.tag)) {
if (!std::get<std::string>(*p.tag).empty()) {
addTag(std::get<std::string>(*p.tag));
}
}
else {
ghoul_assert(std::holds_alternative<std::vector<std::string>>(*p.tag), "");
for (std::string tag : std::get<std::vector<std::string>>(*p.tag)) {
addTag(std::move(tag));
}
}
}
_enabled = p.enabled.value_or(_enabled);
addProperty(_enabled);
_enabled.onChange([this]() {
if (isEnabled()) {
global::eventEngine->publishEvent<events::EventRenderableEnabled>(_parent);
}
else {
global::eventEngine->publishEvent<events::EventRenderableDisabled>(_parent);
}
});
_opacity = p.opacity.value_or(_opacity);
// We don't add the property here as subclasses should decide on their own whether
// they to expose the opacity or not
addProperty(_fade);
// set type for UI
_renderableType = p.type.value_or(_renderableType);
addProperty(_renderableType);
// only used by a few classes such as RenderableTrail and RenderableSphere
if (p.renderBinMode.has_value()) {
setRenderBin(codegen::map<Renderable::RenderBin>(*p.renderBinMode));
}
_dimInAtmosphere = p.dimInAtmosphere.value_or(_dimInAtmosphere);
addProperty(_dimInAtmosphere);
}
void Renderable::initialize() {}
void Renderable::initializeGL() {}
void Renderable::deinitialize() {}
void Renderable::deinitializeGL() {}
void Renderable::update(const UpdateData&) {}
void Renderable::render(const RenderData&, RendererTasks&) {}
void Renderable::setBoundingSphere(double boundingSphere) {
_boundingSphere = boundingSphere;
}
double Renderable::boundingSphere() const {
return _boundingSphere;
}
void Renderable::setInteractionSphere(double interactionSphere) {
_interactionSphere = interactionSphere;
}
double Renderable::interactionSphere() const {
return _interactionSphere;
}
SurfacePositionHandle Renderable::calculateSurfacePositionHandle(
const glm::dvec3& targetModelSpace) const
{
const glm::dvec3 directionFromCenterToTarget = glm::normalize(targetModelSpace);
return {
directionFromCenterToTarget * _parent->interactionSphere(),
directionFromCenterToTarget,
0.0
};
}
bool Renderable::renderedWithDesiredData() const {
return true;
}
Renderable::RenderBin Renderable::renderBin() const {
return _renderBin;
}
void Renderable::setRenderBin(RenderBin bin) {
_renderBin = bin;
}
bool Renderable::matchesRenderBinMask(int binMask) {
return binMask & static_cast<int>(renderBin());
}
bool Renderable::isVisible() const {
return _enabled && _opacity > 0.f && _fade > 0.f;
}
bool Renderable::isReady() const {
return true;
}
bool Renderable::isEnabled() const {
return _enabled;
}
bool Renderable::shouldUpdateIfDisabled() const {
return _shouldUpdateIfDisabled;
}
void Renderable::onEnabledChange(std::function<void(bool)> callback) {
_enabled.onChange([this, c = std::move(callback)]() {
c(isEnabled());
});
}
void Renderable::setRenderBinFromOpacity() {
if ((_renderBin != Renderable::RenderBin::PostDeferredTransparent) &&
(_renderBin != Renderable::RenderBin::Overlay))
{
const float v = opacity();
if (v >= 0.f && v < 1.f) {
setRenderBin(Renderable::RenderBin::PreDeferredTransparent);
}
else {
setRenderBin(Renderable::RenderBin::Opaque);
}
}
}
void Renderable::registerUpdateRenderBinFromOpacity() {
_opacity.onChange([this]() { setRenderBinFromOpacity(); });
_fade.onChange([this]() { setRenderBinFromOpacity(); });
}
float Renderable::opacity() const {
// Rendering should depend on if camera is in the atmosphere and if camera is at the
// dark part of the globe
return _dimInAtmosphere ?
_opacity * _fade * global::navigationHandler->camera()->atmosphereDimmingFactor() :
_opacity * _fade;
}
} // namespace openspace
<|endoftext|> |
<commit_before>#include <rendering/texture_2d.h>
#include <unordered_map>
namespace rendering {
namespace {
struct texture_format_traits {
GLint internalformat;
GLenum format;
GLenum type;
};
std::unordered_map<texture_2d::texture_format, texture_format_traits> format_traits = {
{ texture_2d::TEXTURE_FORMAT_RGBA8, {GL_RGBA8, GL_RGBA, GL_BYTE}},
{ texture_2d::TEXTURE_FORMAT_RG16F, {GL_RG16F, GL_RG, GL_HALF_FLOAT}},
};
} // unnamed namespace
texture_2d::texture_2d(const util::extent& extent, texture_format format, const void *data)
{
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
auto traits = format_traits[format];
glTexImage2D(GL_TEXTURE_2D, 0, format, GLsizei(extent.width), GLsizei(extent.height), 0, traits.format, traits.type, data);
GL_CHECK();
}
} // namespace rendering
<commit_msg>workaround texture state destruction caused by texture_2d ctor<commit_after>#include <rendering/texture_2d.h>
#include <unordered_map>
namespace rendering {
namespace {
struct texture_format_traits {
GLint internalformat;
GLenum format;
GLenum type;
};
std::unordered_map<texture_2d::texture_format, texture_format_traits> format_traits = {
{ texture_2d::TEXTURE_FORMAT_RGBA8, {GL_RGBA8, GL_RGBA, GL_BYTE}},
{ texture_2d::TEXTURE_FORMAT_RG16F, {GL_RG16F, GL_RG, GL_HALF_FLOAT}},
};
} // unnamed namespace
texture_2d::texture_2d(const util::extent& extent, texture_format format, const void *data)
{
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_2D, tex);
auto traits = format_traits[format];
glTexImage2D(GL_TEXTURE_2D, 0, format, GLsizei(extent.width), GLsizei(extent.height), 0, traits.format, traits.type, data);
GL_CHECK();
glActiveTexture(GL_TEXTURE0);
}
} // namespace rendering
<|endoftext|> |
<commit_before>#ifndef __REPLICATION_PROTOCOL_HPP__
#define __REPLICATION_PROTOCOL_HPP__
#include "errors.hpp"
#include <boost/function.hpp>
#include "arch/arch.hpp"
#include "concurrency/fifo_checker.hpp"
#include "concurrency/drain_semaphore.hpp"
#include "concurrency/mutex.hpp"
#include "containers/scoped_malloc.hpp"
#include "data_provider.hpp"
#include "replication/multistream.hpp"
#include "replication/net_structs.hpp"
#include "replication/heartbeat_manager.hpp"
namespace replication {
template <class T>
struct stream_pair {
boost::shared_ptr<buffered_data_provider_t> stream;
unique_malloc_t<T> data;
/* The `stream_pair()` constructor takes a buffer that contains the beginning of a multipart
message. It's guaranteed to contain the entire header and the entire key and probably part of
the value, but it's not guaranteed to contain the entire value. The network logic will later
fill in the rest of the value. */
// This uses key_size, which is completely crap.
stream_pair(const char *beg, const char *end, ssize_t size = 0) : stream(), data() {
void *p;
size_t m = sizeof(T) + reinterpret_cast<const T *>(beg)->key_size;
const char *cutpoint = beg + m;
{
unique_malloc_t<T> tmp(beg, cutpoint);
data = tmp;
}
stream.reset(new buffered_data_provider_t(size == 0 ? end - cutpoint : size, &p));
memcpy(p, cutpoint, end - cutpoint);
}
T *operator->() { return data.get(); }
};
class message_callback_t {
public:
// These could call .swap on their parameter, taking ownership of the pointee.
virtual void hello(net_hello_t message) = 0;
virtual void send(scoped_malloc<net_introduce_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_complete_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_delete_everything_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_delete_t>& message) = 0;
virtual void send(stream_pair<net_backfill_set_t>& message) = 0;
virtual void send(scoped_malloc<net_get_cas_t>& message) = 0;
virtual void send(stream_pair<net_sarc_t>& message) = 0;
virtual void send(scoped_malloc<net_incr_t>& message) = 0;
virtual void send(scoped_malloc<net_decr_t>& message) = 0;
virtual void send(stream_pair<net_append_t>& message) = 0;
virtual void send(stream_pair<net_prepend_t>& message) = 0;
virtual void send(scoped_malloc<net_delete_t>& message) = 0;
virtual void send(scoped_malloc<net_timebarrier_t>& message) = 0;
virtual void send(scoped_malloc<net_heartbeat_t>& message) = 0;
virtual void conn_closed() = 0;
virtual ~message_callback_t() {}
};
struct tracker_obj_t {
boost::function<void ()> function;
char *buf;
size_t bufsize;
tracker_obj_t(const boost::function<void ()>& _function, char * _buf, size_t _bufsize)
: function(_function), buf(_buf), bufsize(_bufsize) { }
};
namespace internal {
struct replication_stream_handler_t : public stream_handler_t {
replication_stream_handler_t(message_callback_t *receiver, heartbeat_receiver_t *hb_receiver) :
receiver_(receiver), hb_receiver_(hb_receiver), saw_first_part_(false), tracker_obj_(NULL) { }
~replication_stream_handler_t() { if(tracker_obj_) delete tracker_obj_; }
void stream_part(const char *buf, size_t size);
void end_of_stream();
private:
message_callback_t *const receiver_;
heartbeat_receiver_t *hb_receiver_;
bool saw_first_part_;
tracker_obj_t *tracker_obj_;
};
struct replication_connection_handler_t : public connection_handler_t {
void process_hello_message(net_hello_t msg);
stream_handler_t *new_stream_handler() { return new replication_stream_handler_t(receiver_, hb_receiver_); }
replication_connection_handler_t(message_callback_t *receiver, heartbeat_receiver_t *hb_receiver) :
receiver_(receiver), hb_receiver_(hb_receiver) { }
void conn_closed() { receiver_->conn_closed(); }
private:
message_callback_t *receiver_;
heartbeat_receiver_t *hb_receiver_;
};
} // namespace internal
class repli_stream_t : public heartbeat_sender_t, public heartbeat_receiver_t, public home_thread_mixin_t {
public:
repli_stream_t(boost::scoped_ptr<tcp_conn_t>& conn, message_callback_t *recv_callback, int heartbeat_timeout);
~repli_stream_t();
// Call shutdown() when you want the repli_stream to stop. shutdown() causes
// the connection to be closed and conn_closed() to be called.
void shutdown() {
unwatch_heartbeat();
stop_sending_heartbeats();
try {
mutex_acquisition_t ak(&outgoing_mutex_); // flush_buffer() would interfere with active writes
conn_->flush_buffer();
} catch (tcp_conn_t::write_closed_exc_t &e) {
(void)e;
// Ignore
}
conn_->shutdown_read();
}
void send(net_introduce_t *msg);
void send(net_backfill_t *msg);
void send(net_backfill_complete_t *msg);
void send(net_backfill_delete_everything_t msg);
void send(net_backfill_delete_t *msg);
void send(net_backfill_set_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_get_cas_t *msg);
void send(net_sarc_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_incr_t *msg);
void send(net_decr_t *msg);
void send(net_append_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_prepend_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_delete_t *msg);
void send(net_timebarrier_t msg);
void send(net_heartbeat_t msg);
void flush();
protected:
void send_heartbeat() {
net_heartbeat_t msg;
msg.padding = 0;
send(msg);
}
void on_heartbeat_timeout() {
logINF("Terminating connection due to heartbeat timeout.\n");
shutdown();
}
private:
template <class net_struct_type>
void sendobj(uint8_t msgcode, net_struct_type *msg);
template <class net_struct_type>
void sendobj(uint8_t msgcode, net_struct_type *msg, const char *key, boost::shared_ptr<data_provider_t> data);
void send_hello(const mutex_acquisition_t& proof_of_acquisition);
void try_write(const void *data, size_t size);
internal::replication_connection_handler_t conn_handler_;
/* outgoing_mutex_ is used to prevent messages from being interlaced on the wire */
mutex_t outgoing_mutex_;
/* drain_semaphore_ is used to prevent the repli_stream_t from being destroyed while there
are active calls to send(). */
drain_semaphore_t drain_semaphore_;
boost::scoped_ptr<tcp_conn_t> conn_;
};
} // namespace replication
#endif // __REPLICATION_PROTOCOL_HPP__
<commit_msg>Don't try to close a closed connection.<commit_after>#ifndef __REPLICATION_PROTOCOL_HPP__
#define __REPLICATION_PROTOCOL_HPP__
#include "errors.hpp"
#include <boost/function.hpp>
#include "arch/arch.hpp"
#include "concurrency/fifo_checker.hpp"
#include "concurrency/drain_semaphore.hpp"
#include "concurrency/mutex.hpp"
#include "containers/scoped_malloc.hpp"
#include "data_provider.hpp"
#include "replication/multistream.hpp"
#include "replication/net_structs.hpp"
#include "replication/heartbeat_manager.hpp"
namespace replication {
template <class T>
struct stream_pair {
boost::shared_ptr<buffered_data_provider_t> stream;
unique_malloc_t<T> data;
/* The `stream_pair()` constructor takes a buffer that contains the beginning of a multipart
message. It's guaranteed to contain the entire header and the entire key and probably part of
the value, but it's not guaranteed to contain the entire value. The network logic will later
fill in the rest of the value. */
// This uses key_size, which is completely crap.
stream_pair(const char *beg, const char *end, ssize_t size = 0) : stream(), data() {
void *p;
size_t m = sizeof(T) + reinterpret_cast<const T *>(beg)->key_size;
const char *cutpoint = beg + m;
{
unique_malloc_t<T> tmp(beg, cutpoint);
data = tmp;
}
stream.reset(new buffered_data_provider_t(size == 0 ? end - cutpoint : size, &p));
memcpy(p, cutpoint, end - cutpoint);
}
T *operator->() { return data.get(); }
};
class message_callback_t {
public:
// These could call .swap on their parameter, taking ownership of the pointee.
virtual void hello(net_hello_t message) = 0;
virtual void send(scoped_malloc<net_introduce_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_complete_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_delete_everything_t>& message) = 0;
virtual void send(scoped_malloc<net_backfill_delete_t>& message) = 0;
virtual void send(stream_pair<net_backfill_set_t>& message) = 0;
virtual void send(scoped_malloc<net_get_cas_t>& message) = 0;
virtual void send(stream_pair<net_sarc_t>& message) = 0;
virtual void send(scoped_malloc<net_incr_t>& message) = 0;
virtual void send(scoped_malloc<net_decr_t>& message) = 0;
virtual void send(stream_pair<net_append_t>& message) = 0;
virtual void send(stream_pair<net_prepend_t>& message) = 0;
virtual void send(scoped_malloc<net_delete_t>& message) = 0;
virtual void send(scoped_malloc<net_timebarrier_t>& message) = 0;
virtual void send(scoped_malloc<net_heartbeat_t>& message) = 0;
virtual void conn_closed() = 0;
virtual ~message_callback_t() {}
};
struct tracker_obj_t {
boost::function<void ()> function;
char *buf;
size_t bufsize;
tracker_obj_t(const boost::function<void ()>& _function, char * _buf, size_t _bufsize)
: function(_function), buf(_buf), bufsize(_bufsize) { }
};
namespace internal {
struct replication_stream_handler_t : public stream_handler_t {
replication_stream_handler_t(message_callback_t *receiver, heartbeat_receiver_t *hb_receiver) :
receiver_(receiver), hb_receiver_(hb_receiver), saw_first_part_(false), tracker_obj_(NULL) { }
~replication_stream_handler_t() { if(tracker_obj_) delete tracker_obj_; }
void stream_part(const char *buf, size_t size);
void end_of_stream();
private:
message_callback_t *const receiver_;
heartbeat_receiver_t *hb_receiver_;
bool saw_first_part_;
tracker_obj_t *tracker_obj_;
};
struct replication_connection_handler_t : public connection_handler_t {
void process_hello_message(net_hello_t msg);
stream_handler_t *new_stream_handler() { return new replication_stream_handler_t(receiver_, hb_receiver_); }
replication_connection_handler_t(message_callback_t *receiver, heartbeat_receiver_t *hb_receiver) :
receiver_(receiver), hb_receiver_(hb_receiver) { }
void conn_closed() { receiver_->conn_closed(); }
private:
message_callback_t *receiver_;
heartbeat_receiver_t *hb_receiver_;
};
} // namespace internal
class repli_stream_t : public heartbeat_sender_t, public heartbeat_receiver_t, public home_thread_mixin_t {
public:
repli_stream_t(boost::scoped_ptr<tcp_conn_t>& conn, message_callback_t *recv_callback, int heartbeat_timeout);
~repli_stream_t();
// Call shutdown() when you want the repli_stream to stop. shutdown() causes
// the connection to be closed and conn_closed() to be called.
void shutdown() {
unwatch_heartbeat();
stop_sending_heartbeats();
try {
mutex_acquisition_t ak(&outgoing_mutex_); // flush_buffer() would interfere with active writes
conn_->flush_buffer();
} catch (tcp_conn_t::write_closed_exc_t &e) {
(void)e;
// Ignore
}
if (conn_->is_read_open()) {
conn_->shutdown_read();
}
}
void send(net_introduce_t *msg);
void send(net_backfill_t *msg);
void send(net_backfill_complete_t *msg);
void send(net_backfill_delete_everything_t msg);
void send(net_backfill_delete_t *msg);
void send(net_backfill_set_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_get_cas_t *msg);
void send(net_sarc_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_incr_t *msg);
void send(net_decr_t *msg);
void send(net_append_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_prepend_t *msg, const char *key, boost::shared_ptr<data_provider_t> value);
void send(net_delete_t *msg);
void send(net_timebarrier_t msg);
void send(net_heartbeat_t msg);
void flush();
protected:
void send_heartbeat() {
net_heartbeat_t msg;
msg.padding = 0;
send(msg);
}
void on_heartbeat_timeout() {
logINF("Terminating connection due to heartbeat timeout.\n");
shutdown();
}
private:
template <class net_struct_type>
void sendobj(uint8_t msgcode, net_struct_type *msg);
template <class net_struct_type>
void sendobj(uint8_t msgcode, net_struct_type *msg, const char *key, boost::shared_ptr<data_provider_t> data);
void send_hello(const mutex_acquisition_t& proof_of_acquisition);
void try_write(const void *data, size_t size);
internal::replication_connection_handler_t conn_handler_;
/* outgoing_mutex_ is used to prevent messages from being interlaced on the wire */
mutex_t outgoing_mutex_;
/* drain_semaphore_ is used to prevent the repli_stream_t from being destroyed while there
are active calls to send(). */
drain_semaphore_t drain_semaphore_;
boost::scoped_ptr<tcp_conn_t> conn_;
};
} // namespace replication
#endif // __REPLICATION_PROTOCOL_HPP__
<|endoftext|> |
<commit_before>/*
This file is part of KDE Kontact.
Copyright (c) 2003 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "aboutdialog.h"
#include "aboutdialog.moc"
#include "core.h"
#include "plugin.h"
#include <klocale.h>
#include <kiconloader.h>
#include <kaboutdata.h>
#include <kactivelabel.h>
#include <ktextbrowser.h>
#include <qlayout.h>
#include <qlabel.h>
#include <kdebug.h>
using namespace Kontact;
AboutDialog::AboutDialog( Kontact::Core *core, const char *name )
: KDialogBase( IconList, i18n("About Kontact"), Ok, Ok, core, name, false,
true ),
mCore( core )
{
addAboutData( i18n("Kontact Container Application"), QString( "kontact" ),
KGlobal::instance()->aboutData() );
QPtrList<Plugin> plugins = mCore->pluginList();
uint i;
for( i = 0; i < plugins.count(); ++i ) {
addAboutPlugin( plugins.at( i ) );
}
addLicenseText( KGlobal::instance()->aboutData() );
}
void AboutDialog::addAboutPlugin( Kontact::Plugin *plugin )
{
addAboutData( plugin->title(), plugin->icon(), plugin->aboutData() );
}
void AboutDialog::addAboutData( const QString &title, const QString &icon,
const KAboutData *about )
{
QPixmap pixmap = KGlobal::iconLoader()->loadIcon( icon,
KIcon::Desktop, 48 );
QFrame *topFrame = addPage( title, QString::null, pixmap );
QBoxLayout *topLayout = new QVBoxLayout( topFrame );
if ( !about ) {
QLabel *label = new QLabel( i18n("No about information available."),
topFrame );
topLayout->addWidget( label );
} else {
QString text;
text += "<p><b>" + about->programName() + "</b><br>";
text += i18n("Version %1</p>").arg( about->version() );
if (!about->shortDescription().isEmpty()) {
text += "<p>" + about->shortDescription() + "<br>" +
about->copyrightStatement() + "</p>";
}
QString home = about->homepage();
if ( !home.isEmpty() ) {
text += "<a href=\"" + home + "\">" + home + "</a><br>";
}
text.replace( "\n", "<br>" );
KActiveLabel *label = new KActiveLabel( text, topFrame );
label->setAlignment( AlignTop );
topLayout->addWidget( label );
QTextEdit *personView = new QTextEdit( topFrame );
personView->setReadOnly( true );
topLayout->addWidget( personView, 1 );
text = "";
QValueList<KAboutPerson> authors = about->authors();
if ( !authors.isEmpty() ) {
text += i18n("<p><b>Authors:</b></p>");
QValueList<KAboutPerson>::ConstIterator it;
for( it = authors.begin(); it != authors.end(); ++it ) {
text += formatPerson( (*it).name(), (*it).emailAddress() );
if (!(*it).task().isEmpty()) text += "<i>" + (*it).task() + "</i><br>";
}
}
QValueList<KAboutPerson> credits = about->credits();
if ( !credits.isEmpty() ) {
text += i18n("<p><b>Thanks to:</b></p>");
QValueList<KAboutPerson>::ConstIterator it;
for( it = credits.begin(); it != credits.end(); ++it ) {
text += formatPerson( (*it).name(), (*it).emailAddress() );
if (!(*it).task().isEmpty()) text += "<i>" + (*it).task() + "</i><br>";
}
}
QValueList<KAboutTranslator> translators = about->translators();
if ( !translators.isEmpty() ) {
text += i18n("<p><b>Translators:</b></p>");
QValueList<KAboutTranslator>::ConstIterator it;
for( it = translators.begin(); it != translators.end(); ++it ) {
text += formatPerson( (*it).name(), (*it).emailAddress() );
}
}
personView->setText( text );
}
}
QString AboutDialog::formatPerson( const QString &name, const QString &email )
{
QString text = name;
if ( !email.isEmpty() ) {
text += " <<a href=\"mailto:" + email + "\">" + email + "</a>>";
}
text += "<br>";
return text;
}
void AboutDialog::addLicenseText(const KAboutData *about)
{
if ( !about || about->license().isEmpty() ) return;
QPixmap pixmap = KGlobal::iconLoader()->loadIcon( "scripting",
KIcon::Desktop, 48 );
QString title = i18n("%1 license").arg(about->programName());
QFrame *topFrame = addPage( title, QString::null, pixmap );
QBoxLayout *topLayout = new QVBoxLayout( topFrame );
KTextBrowser *textBrowser = new KTextBrowser( topFrame );
textBrowser->setText( QString("<pre>%1</pre>").arg(about->license()) );
topLayout->addWidget(textBrowser);
}
<commit_msg>Less wide string<commit_after>/*
This file is part of KDE Kontact.
Copyright (c) 2003 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "aboutdialog.h"
#include "aboutdialog.moc"
#include "core.h"
#include "plugin.h"
#include <klocale.h>
#include <kiconloader.h>
#include <kaboutdata.h>
#include <kactivelabel.h>
#include <ktextbrowser.h>
#include <qlayout.h>
#include <qlabel.h>
#include <kdebug.h>
using namespace Kontact;
AboutDialog::AboutDialog( Kontact::Core *core, const char *name )
: KDialogBase( IconList, i18n("About Kontact"), Ok, Ok, core, name, false,
true ),
mCore( core )
{
addAboutData( i18n("Kontact Container"), QString( "kontact" ),
KGlobal::instance()->aboutData() );
QPtrList<Plugin> plugins = mCore->pluginList();
uint i;
for( i = 0; i < plugins.count(); ++i ) {
addAboutPlugin( plugins.at( i ) );
}
addLicenseText( KGlobal::instance()->aboutData() );
}
void AboutDialog::addAboutPlugin( Kontact::Plugin *plugin )
{
addAboutData( plugin->title(), plugin->icon(), plugin->aboutData() );
}
void AboutDialog::addAboutData( const QString &title, const QString &icon,
const KAboutData *about )
{
QPixmap pixmap = KGlobal::iconLoader()->loadIcon( icon,
KIcon::Desktop, 48 );
QFrame *topFrame = addPage( title, QString::null, pixmap );
QBoxLayout *topLayout = new QVBoxLayout( topFrame );
if ( !about ) {
QLabel *label = new QLabel( i18n("No about information available."),
topFrame );
topLayout->addWidget( label );
} else {
QString text;
text += "<p><b>" + about->programName() + "</b><br>";
text += i18n("Version %1</p>").arg( about->version() );
if (!about->shortDescription().isEmpty()) {
text += "<p>" + about->shortDescription() + "<br>" +
about->copyrightStatement() + "</p>";
}
QString home = about->homepage();
if ( !home.isEmpty() ) {
text += "<a href=\"" + home + "\">" + home + "</a><br>";
}
text.replace( "\n", "<br>" );
KActiveLabel *label = new KActiveLabel( text, topFrame );
label->setAlignment( AlignTop );
topLayout->addWidget( label );
QTextEdit *personView = new QTextEdit( topFrame );
personView->setReadOnly( true );
topLayout->addWidget( personView, 1 );
text = "";
QValueList<KAboutPerson> authors = about->authors();
if ( !authors.isEmpty() ) {
text += i18n("<p><b>Authors:</b></p>");
QValueList<KAboutPerson>::ConstIterator it;
for( it = authors.begin(); it != authors.end(); ++it ) {
text += formatPerson( (*it).name(), (*it).emailAddress() );
if (!(*it).task().isEmpty()) text += "<i>" + (*it).task() + "</i><br>";
}
}
QValueList<KAboutPerson> credits = about->credits();
if ( !credits.isEmpty() ) {
text += i18n("<p><b>Thanks to:</b></p>");
QValueList<KAboutPerson>::ConstIterator it;
for( it = credits.begin(); it != credits.end(); ++it ) {
text += formatPerson( (*it).name(), (*it).emailAddress() );
if (!(*it).task().isEmpty()) text += "<i>" + (*it).task() + "</i><br>";
}
}
QValueList<KAboutTranslator> translators = about->translators();
if ( !translators.isEmpty() ) {
text += i18n("<p><b>Translators:</b></p>");
QValueList<KAboutTranslator>::ConstIterator it;
for( it = translators.begin(); it != translators.end(); ++it ) {
text += formatPerson( (*it).name(), (*it).emailAddress() );
}
}
personView->setText( text );
}
}
QString AboutDialog::formatPerson( const QString &name, const QString &email )
{
QString text = name;
if ( !email.isEmpty() ) {
text += " <<a href=\"mailto:" + email + "\">" + email + "</a>>";
}
text += "<br>";
return text;
}
void AboutDialog::addLicenseText(const KAboutData *about)
{
if ( !about || about->license().isEmpty() ) return;
QPixmap pixmap = KGlobal::iconLoader()->loadIcon( "scripting",
KIcon::Desktop, 48 );
QString title = i18n("%1 license").arg(about->programName());
QFrame *topFrame = addPage( title, QString::null, pixmap );
QBoxLayout *topLayout = new QVBoxLayout( topFrame );
KTextBrowser *textBrowser = new KTextBrowser( topFrame );
textBrowser->setText( QString("<pre>%1</pre>").arg(about->license()) );
topLayout->addWidget(textBrowser);
}
<|endoftext|> |
<commit_before>/**
* @file rectifier_function.hpp
* @author Marcus Edel
*
* Definition and implementation of the rectifier function as described by
* V. Nair and G. E. Hinton.
*
* For more information, see the following paper.
*
* @code
* @misc{NairHinton2010,
* author = {Vinod Nair, Geoffrey E. Hinton},
* title = {Rectified Linear Units Improve Restricted Boltzmann Machines},
* year = {2010}
* }
* @endcode
*/
#ifndef __MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_RECTIFIER_FUNCTION_HPP
#define __MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_RECTIFIER_FUNCTION_HPP
#include <mlpack/core.hpp>
#include <algorithm>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The rectifier function, defined by
*
* @f[
* f(x) &=& \max(0, x) \\
* f'(x) &=& \left\{
* \begin{array}{lr}
* 1 & : x > 0 \\
* 0 & : x \le 0
* \end{array}
* \right
* @f]
*/
class RectifierFunction
{
public:
/**
* Computes the rectifier function.
*
* @param x Input data.
* @return f(x).
*/
static double fn(const double x)
{
return std::max(0.0, x);
}
/**
* Computes the rectifier function.
*
* @param x Input data.
* @param y The resulting output activation.
*/
template<typename InputVecType, typename OutputVecType>
static void fn(const InputVecType& x, OutputVecType& y)
{
y = x;
y = arma::max(arma::zeros<OutputVecType>(x.n_elem), x);
}
/**
* Computes the first derivative of the rectifier function.
*
* @param x Input data.
* @return f'(x)
*/
static double deriv(const double y)
{
return y > 0 ? 1 : 0;
}
/**
* Computes the first derivatives of the rectifier function.
*
* @param y Input activations.
* @param x The resulting derivatives.
*/
template<typename InputVecType, typename OutputVecType>
static void deriv(const InputVecType& y, OutputVecType& x)
{
x = y;
x.transform( [](double y) { return deriv(y); } );
}
}; // class RectifierFunction
}; // namespace ann
}; // namespace mlpack
#endif
<commit_msg>Refactor to support 3rd-order tensors.<commit_after>/**
* @file rectifier_function.hpp
* @author Marcus Edel
*
* Definition and implementation of the rectifier function as described by
* V. Nair and G. E. Hinton.
*
* For more information, see the following paper.
*
* @code
* @misc{NairHinton2010,
* author = {Vinod Nair, Geoffrey E. Hinton},
* title = {Rectified Linear Units Improve Restricted Boltzmann Machines},
* year = {2010}
* }
* @endcode
*/
#ifndef __MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_RECTIFIER_FUNCTION_HPP
#define __MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_RECTIFIER_FUNCTION_HPP
#include <mlpack/core.hpp>
#include <algorithm>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The rectifier function, defined by
*
* @f[
* f(x) &=& \max(0, x) \\
* f'(x) &=& \left\{
* \begin{array}{lr}
* 1 & : x > 0 \\
* 0 & : x \le 0
* \end{array}
* \right
* @f]
*/
class RectifierFunction
{
public:
/**
* Computes the rectifier function.
*
* @param x Input data.
* @return f(x).
*/
static double fn(const double x)
{
return std::max(0.0, x);
}
/**
* Computes the rectifier function using a dense matrix as input.
*
* @param x Input data.
* @param y The resulting output activation.
*/
template<typename eT>
static void fn(const arma::Mat<eT>& x, arma::Mat<eT>& y)
{
y = arma::max(arma::zeros<arma::Mat<eT> >(x.n_rows, x.n_cols), x);
}
/**
* Computes the rectifier function using a 3rd-order tensor as input.
*
* @param x Input data.
* @param y The resulting output activation.
*/
template<typename eT>
static void fn(const arma::Cube<eT>& x, arma::Cube<eT>& y)
{
y = x;
for (size_t s = 0; s < x.n_slices; s++)
fn(x.slice(s), y.slice(s));
}
/**
* Computes the first derivative of the rectifier function.
*
* @param x Input data.
* @return f'(x)
*/
static double deriv(const double y)
{
return y > 0;
}
/**
* Computes the first derivatives of the rectifier function.
*
* @param y Input activations.
* @param x The resulting derivatives.
*/
template<typename InputType, typename OutputType>
static void deriv(const InputType& y, OutputType& x)
{
x = y;
x.transform( [](double y) { return deriv(y); } );
}
}; // class RectifierFunction
}; // namespace ann
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>#include "model.h"
Model::Model(const Data& data){
//initiate the tumour with a homogenous population with the type_p=1 and type_i=1
int i;
double n=data.return_initial_cellnumber();
//define a matrix whose entries is initialized with 0
double max_num_row=data.return_max_prolif_types();
double max_num_column=data.return_max_immun_types();
for(i=0;i<max_num_row;i++)
{
std::vector<double> row(max_num_column,0);
_cells.push_back(row);
}
//define the first phenotype: type_p=1 and type_i=1 with an initial size of n
_cell[0][0]=n;
}
double Model::return_Ccell_number(int type_p, int type_i) const
{
return _cells[type_p][type_i];
}
void Model::set_Ccell_number(int type_p, int type_i, double number){
double max_num_row=data.return_max_prolif_types();
double max_num_column=data.return_max_immun_types();
if((type_p>=max_num_row)||(type_i>=max_num_column)) exit(1);
_cells[type_p][type_i]=number;
}
void output(double dt, std::ostream & os){
}<commit_msg>corret small errors, Weini.<commit_after>#include "model.h"
Model::Model(const Data& data){
//initiate the tumour with a homogenous population with the type_p=1 and type_i=1
int i;
double n=data.return_initial_cellnumber();
//define a matrix whose entries is initialized with 0
double max_num_row=data.return_max_prolif_types();
double max_num_column=data.return_max_immune_types();
for(i=0;i<max_num_row;i++)
{
std::vector<double> row(max_num_column,0);
_cells.push_back(row);
}
//define the first phenotype: type_p=1 and type_i=1 with an initial size of n
_cells[0][0]=n;
}
double Model::return_Ccell_number(int type_p, int type_i) const
{
return _cells[type_p][type_i];
}
void Model::set_Ccell_number(int type_p, int type_i, double number){
double max_num_row=_cells.size();
double max_num_column=_cells[0].size();
if((type_p>=max_num_row)||(type_i>=max_num_column)) exit(1);
_cells[type_p][type_i]=number;
}
void output(double dt, std::ostream & os){
}<|endoftext|> |
<commit_before>/*
Copyright (C) <2011> Michael Zanetti <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "remotecontrolmanager.h"
#include "remotecontrolmanager_p.h"
#include "ifaces/remotecontrolmanagerinterface.h"
#include "ifaces/remotecontrolinterface.h"
#include <kglobal.h>
#include <kservicetypetrader.h>
#include <kservice.h>
#include <kdebug.h>
K_GLOBAL_STATIC(RemoteControlManagerPrivate, globalRemoteControlManager)
bool RemoteControlManager::connected()
{
return globalRemoteControlManager->connected();
}
RemoteControlManager::Notifier* RemoteControlManager::notifier()
{
return globalRemoteControlManager;
}
/***********************************************************************
RemoteControlManagerPrivate
***********************************************************************/
RemoteControlManagerPrivate::RemoteControlManagerPrivate()
{
loadBackends("KRemoteControlManager");
}
RemoteControlManagerPrivate::~RemoteControlManagerPrivate()
{
while(!m_backendList.isEmpty()) {
delete m_backendList.takeFirst();
}
}
void RemoteControlManagerPrivate::loadBackends(const char *serviceName)
{
QStringList error_msg;
KService::List offers = KServiceTypeTrader::self()->query(serviceName, "(Type == 'Service')");
foreach (const KService::Ptr &ptr, offers) {
QString error_string;
QObject *backend = ptr->createInstance<QObject>(0, QVariantList(), &error_string);
if(backend!=0) {
if(backend->inherits("Iface::RemoteControlManager")) {
kDebug() << "Backend loaded: " << ptr->name();
m_backendList.append(qobject_cast<Iface::RemoteControlManager*>(backend));
break;
} else {
kDebug() << "Failed loading:" << error_string;
QString error_string = i18n("Backend loaded but wrong type obtained, expected %1",
"Iface::RemoteControlManager");
kDebug() << "Error loading '" << ptr->name() << "': " << error_string;
error_msg.append(error_string);
delete backend;
backend = 0;
}
} else {
kDebug() << "Error loading '" << ptr->name() << "', KService said: " << error_string;
error_msg.append(error_string);
}
}
if (m_backendList.isEmpty()) {
if (offers.size() == 0) {
kDebug() << "No Backend found";
} else {
kDebug() << "could not load any of the backends";
}
}
}
bool RemoteControlManagerPrivate::connected()
{
return m_connected;
}
RemoteControlList RemoteControlManagerPrivate::buildDeviceList(const QStringList &remoteList)
{
RemoteControlList list;
foreach (const QString &remote, remoteList) {
QPair<RemoteControl *, Iface::RemoteControl *> pair = findRegisteredRemoteControl(remote);
if (pair.first!= 0) {
list.append(pair.first);
}
}
return list;
}
void RemoteControlManagerPrivate::_k_remoteControlAdded(const QString &name)
{
Iface::RemoteControlManager *backendManager = qobject_cast<Iface::RemoteControlManager*>(sender());
if(backendManager == 0) {
return;
}
RemoteControl *rc = new RemoteControl(name);
Iface::RemoteControl *rcBackend = backendManager->createRemoteControl(name);
rc->d_ptr->setBackendObject(rcBackend);
m_remoteControlMap.insert(name, QPair<RemoteControl*, Iface::RemoteControl*>(rc, rcBackend));
emit remoteControlAdded(name);
}
void RemoteControlManagerPrivate::_k_remoteControlRemoved(const QString &name)
{
delete m_remoteControlMap[name].first;
delete m_remoteControlMap[name].second;
m_remoteControlMap.remove(name);
emit remoteControlRemoved(name);
}
void RemoteControlManagerPrivate::_k_statusChanged(bool connected)
{
if(connected == m_connected) {
return;
}
if(!connected) {
// Is there still another backend connected?
foreach(Iface::RemoteControlManager* backend, m_backendList) {
if(backend->connected()) {
return;
}
}
}
m_connected = connected;
emit statusChanged(connected);
kDebug() << "Remotecontrol backend status has changed to" << connected;
}
RemoteControlList RemoteControlManagerPrivate::allRemotes()
{
QStringList remoteList;
foreach(Iface::RemoteControlManager *backend, m_backendList) {
remoteList.append(backend->remoteNames());
}
if (!m_backendList.isEmpty()) {
return buildDeviceList(remoteList);
} else {
return RemoteControlList();
}
}
RemoteControl* RemoteControlManagerPrivate::findRemoteControl(const QString &name)
{
return m_remoteControlMap.value(name).first;
}
RemoteControl::RemoteControl(const QString &name): QObject(), d_ptr(new RemoteControlPrivate(this))
{
Q_D(RemoteControl);
RemoteControl *other = globalRemoteControlManager->findRemoteControl(name);
if(other) {
d->setBackendObject(other->d_ptr->backendObject());
}
}
QList<RemoteControl*> RemoteControl::allRemotes()
{
return globalRemoteControlManager->allRemotes();
}
QPair<RemoteControl *, Iface::RemoteControl *>
RemoteControlManagerPrivate::findRegisteredRemoteControl(const QString &remote)
{
if (m_remoteControlMap.contains(remote)) {
return m_remoteControlMap[remote];
} else {
foreach(Iface::RemoteControlManager *backend, m_backendList) {
Iface::RemoteControl * iface = backend->createRemoteControl(remote);
RemoteControl *device = 0;
if(iface != 0) {
device = new RemoteControl(iface);
} else {
kDebug() << "Unknown Remote: " << remote;
}
if (device != 0) {
QPair<RemoteControl *, Iface::RemoteControl *> pair(device, iface);
connect(dynamic_cast<QObject*>(iface), SIGNAL(destroyed(QObject *)),
this, SLOT(_k_destroyed(QObject *)));
m_remoteControlMap[remote] = pair;
return pair;
} else {
return QPair<RemoteControl *, Iface::RemoteControl *>(0, 0);
}
}
}
return QPair<RemoteControl *, Iface::RemoteControl *>(0, 0);
}
void RemoteControlManagerPrivate::_k_destroyed(QObject *object)
{
Iface::RemoteControl *remote = qobject_cast<Iface::RemoteControl*>(object);
if(remote) {
QString name = remote->name();
QPair<RemoteControl*, Iface::RemoteControl*> pair = m_remoteControlMap.take(name);
delete pair.first;
}
}
<commit_msg>SVN_SILENT compile<commit_after>/*
Copyright (C) <2011> Michael Zanetti <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "remotecontrolmanager.h"
#include "remotecontrolmanager_p.h"
#include "ifaces/remotecontrolmanagerinterface.h"
#include "ifaces/remotecontrolinterface.h"
#include <kglobal.h>
#include <kservicetypetrader.h>
#include <kservice.h>
#include <kdebug.h>
K_GLOBAL_STATIC(RemoteControlManagerPrivate, globalRemoteControlManager)
bool RemoteControlManager::connected()
{
return globalRemoteControlManager->connected();
}
RemoteControlManager::Notifier* RemoteControlManager::notifier()
{
return globalRemoteControlManager;
}
/***********************************************************************
RemoteControlManagerPrivate
***********************************************************************/
RemoteControlManagerPrivate::RemoteControlManagerPrivate()
{
loadBackends("KRemoteControlManager");
}
RemoteControlManagerPrivate::~RemoteControlManagerPrivate()
{
while(!m_backendList.isEmpty()) {
delete m_backendList.takeFirst();
}
}
void RemoteControlManagerPrivate::loadBackends(const char *serviceName)
{
QStringList error_msg;
KService::List offers = KServiceTypeTrader::self()->query(serviceName, "(Type == 'Service')");
foreach (const KService::Ptr &ptr, offers) {
QString error_string;
QObject *backend = ptr->createInstance<QObject>(0, QVariantList(), &error_string);
if(backend!=0) {
if(backend->inherits("Iface::RemoteControlManager")) {
kDebug() << "Backend loaded: " << ptr->name();
m_backendList.append(qobject_cast<Iface::RemoteControlManager*>(backend));
break;
} else {
kDebug() << "Failed loading:" << error_string;
QString error_string = i18n("Backend loaded but wrong type obtained, expected %1",
QLatin1String("Iface::RemoteControlManager"));
kDebug() << "Error loading '" << ptr->name() << "': " << error_string;
error_msg.append(error_string);
delete backend;
backend = 0;
}
} else {
kDebug() << "Error loading '" << ptr->name() << "', KService said: " << error_string;
error_msg.append(error_string);
}
}
if (m_backendList.isEmpty()) {
if (offers.size() == 0) {
kDebug() << "No Backend found";
} else {
kDebug() << "could not load any of the backends";
}
}
}
bool RemoteControlManagerPrivate::connected()
{
return m_connected;
}
RemoteControlList RemoteControlManagerPrivate::buildDeviceList(const QStringList &remoteList)
{
RemoteControlList list;
foreach (const QString &remote, remoteList) {
QPair<RemoteControl *, Iface::RemoteControl *> pair = findRegisteredRemoteControl(remote);
if (pair.first!= 0) {
list.append(pair.first);
}
}
return list;
}
void RemoteControlManagerPrivate::_k_remoteControlAdded(const QString &name)
{
Iface::RemoteControlManager *backendManager = qobject_cast<Iface::RemoteControlManager*>(sender());
if(backendManager == 0) {
return;
}
RemoteControl *rc = new RemoteControl(name);
Iface::RemoteControl *rcBackend = backendManager->createRemoteControl(name);
rc->d_ptr->setBackendObject(rcBackend);
m_remoteControlMap.insert(name, QPair<RemoteControl*, Iface::RemoteControl*>(rc, rcBackend));
emit remoteControlAdded(name);
}
void RemoteControlManagerPrivate::_k_remoteControlRemoved(const QString &name)
{
delete m_remoteControlMap[name].first;
delete m_remoteControlMap[name].second;
m_remoteControlMap.remove(name);
emit remoteControlRemoved(name);
}
void RemoteControlManagerPrivate::_k_statusChanged(bool connected)
{
if(connected == m_connected) {
return;
}
if(!connected) {
// Is there still another backend connected?
foreach(Iface::RemoteControlManager* backend, m_backendList) {
if(backend->connected()) {
return;
}
}
}
m_connected = connected;
emit statusChanged(connected);
kDebug() << "Remotecontrol backend status has changed to" << connected;
}
RemoteControlList RemoteControlManagerPrivate::allRemotes()
{
QStringList remoteList;
foreach(Iface::RemoteControlManager *backend, m_backendList) {
remoteList.append(backend->remoteNames());
}
if (!m_backendList.isEmpty()) {
return buildDeviceList(remoteList);
} else {
return RemoteControlList();
}
}
RemoteControl* RemoteControlManagerPrivate::findRemoteControl(const QString &name)
{
return m_remoteControlMap.value(name).first;
}
RemoteControl::RemoteControl(const QString &name): QObject(), d_ptr(new RemoteControlPrivate(this))
{
Q_D(RemoteControl);
RemoteControl *other = globalRemoteControlManager->findRemoteControl(name);
if(other) {
d->setBackendObject(other->d_ptr->backendObject());
}
}
QList<RemoteControl*> RemoteControl::allRemotes()
{
return globalRemoteControlManager->allRemotes();
}
QPair<RemoteControl *, Iface::RemoteControl *>
RemoteControlManagerPrivate::findRegisteredRemoteControl(const QString &remote)
{
if (m_remoteControlMap.contains(remote)) {
return m_remoteControlMap[remote];
} else {
foreach(Iface::RemoteControlManager *backend, m_backendList) {
Iface::RemoteControl * iface = backend->createRemoteControl(remote);
RemoteControl *device = 0;
if(iface != 0) {
device = new RemoteControl(iface);
} else {
kDebug() << "Unknown Remote: " << remote;
}
if (device != 0) {
QPair<RemoteControl *, Iface::RemoteControl *> pair(device, iface);
connect(dynamic_cast<QObject*>(iface), SIGNAL(destroyed(QObject *)),
this, SLOT(_k_destroyed(QObject *)));
m_remoteControlMap[remote] = pair;
return pair;
} else {
return QPair<RemoteControl *, Iface::RemoteControl *>(0, 0);
}
}
}
return QPair<RemoteControl *, Iface::RemoteControl *>(0, 0);
}
void RemoteControlManagerPrivate::_k_destroyed(QObject *object)
{
Iface::RemoteControl *remote = qobject_cast<Iface::RemoteControl*>(object);
if(remote) {
QString name = remote->name();
QPair<RemoteControl*, Iface::RemoteControl*> pair = m_remoteControlMap.take(name);
delete pair.first;
}
}
<|endoftext|> |
<commit_before><commit_msg>Avoid recursive DisplayDebugMessageInDialog call when an assert is hit on the IO thread<commit_after><|endoftext|> |
<commit_before>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "stdio.h"
#include "time.h"
#include "base/logging.h"
namespace operations_research {
DateLogger::DateLogger() {
#if defined(_MSC_VER)
_tzset();
#endif
}
char* const DateLogger::HumanDate() {
#if defined(_MSC_VER)
strtime_s(buffer_, 9);
#else
time_t time_value = time(NULL);
struct tm* const now = localtime(&time_value);
sprintf(buffer_, "%02d:%02d:%02d\0", now->tm_hour, now->tm_min, now->tm_sec);
#endif
return buffer_;
}
} // namespace operations_research
<commit_msg>fix visual studio compilation<commit_after>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "stdio.h"
#include "time.h"
#include "base/logging.h"
namespace operations_research {
DateLogger::DateLogger() {
#if defined(_MSC_VER)
_tzset();
#endif
}
char* const DateLogger::HumanDate() {
#if defined(_MSC_VER)
_strtime_s(buffer_, 9);
#else
time_t time_value = time(NULL);
struct tm* const now = localtime(&time_value);
sprintf(buffer_, "%02d:%02d:%02d\0", now->tm_hour, now->tm_min, now->tm_sec);
#endif
return buffer_;
}
} // namespace operations_research
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* This file is the implementation of the RemoteResource class. */
#include "condor_common.h"
#include "remoteresource.h"
#include "exit.h" // for JOB_BLAH_BLAH exit reasons
#include "condor_debug.h" // for D_debuglevel #defines
#include "condor_string.h" // for strnewp()
// for remote syscalls, this is currently in NTreceivers.C.
extern int do_REMOTE_syscall();
// for remote syscalls...
ReliSock *syscall_sock;
RemoteResource *thisRemoteResource;
// 90 seconds to wait for a socket timeout:
const int RemoteResource::SHADOW_SOCK_TIMEOUT = 90;
RemoteResource::RemoteResource( BaseShadow *shad )
{
executingHost = NULL;
capability = NULL;
init( shad );
}
RemoteResource::RemoteResource( BaseShadow * shad,
const char * eHost,
const char * cbility )
{
executingHost = strnewp( eHost );
capability = strnewp( cbility );
init( shad );
}
void RemoteResource::init( BaseShadow *shad ) {
shadow = shad;
machineName = NULL;
starterAddress = NULL;
jobAd = NULL;
fs_domain = NULL;
uid_domain = NULL;
claimSock = new ReliSock();
exitReason = exitStatus = -1;
}
RemoteResource::~RemoteResource() {
if ( executingHost ) delete [] executingHost;
if ( machineName ) delete [] machineName;
if ( capability ) delete [] capability;
if ( starterAddress) delete [] starterAddress;
if ( uid_domain ) delete [] uid_domain;
if ( fs_domain ) delete [] fs_domain;
if ( claimSock ) delete claimSock;
if ( jobAd ) delete jobAd;
}
int RemoteResource::requestIt( int starterVersion ) {
/* starterVersion is a default to 2. */
int reply;
if ( !executingHost || !capability ) {
shadow->dprintf ( D_ALWAYS, "executingHost or capability not defined"
"in requestIt.\n" );
setExitReason(JOB_SHADOW_USAGE); // no better exit reason available
return -1;
}
if ( !jobAd ) {
shadow->dprintf( D_ALWAYS, "JobAd not defined in RemoteResource\n" );
return -1;
}
claimSock->close(); // make sure ClaimSock is a virgin socket
claimSock->timeout(SHADOW_SOCK_TIMEOUT);
if (!claimSock->connect(executingHost, 0)) {
shadow->dprintf(D_ALWAYS, "failed to connect to execute host %s\n",
executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
claimSock->encode();
if (!claimSock->put(ACTIVATE_CLAIM) ||
!claimSock->code(capability) ||
!claimSock->code(starterVersion) ||
!jobAd->put(*claimSock) ||
!claimSock->end_of_message())
{
shadow->dprintf(D_ALWAYS, "failed to send ACTIVATE_CLAIM "
"request to %s\n", executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
claimSock->decode();
if (!claimSock->code(reply) || !claimSock->end_of_message()) {
shadow->dprintf(D_ALWAYS, "failed to receive ACTIVATE_CLAIM "
"reply from %s\n", executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
if (reply != OK) {
shadow->dprintf(D_ALWAYS, "Request to run on %s was REFUSED.\n",
executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
shadow->dprintf(D_ALWAYS, "Request to run on %s was ACCEPTED.\n",
executingHost);
return 0;
}
int RemoteResource::killStarter() {
ReliSock sock;
if ( !executingHost ) {
shadow->dprintf ( D_ALWAYS, "In killStarter, "
"executingHost not defined.\n");
return -1;
}
shadow->dprintf( D_ALWAYS, "Removing machine \"%s\".\n",
machineName ? machineName : executingHost );
sock.timeout(SHADOW_SOCK_TIMEOUT);
if (!sock.connect(executingHost, 0)) {
shadow->dprintf(D_ALWAYS, "failed to connect to executing host %s\n",
executingHost );
return -1;
}
sock.encode();
if (!sock.put(KILL_FRGN_JOB) ||
!sock.put(capability) ||
!sock.end_of_message())
{
shadow->dprintf(D_ALWAYS, "failed to send KILL_FRGN_JOB "
"to startd %s\n", executingHost );
return -1;
}
return 0;
}
void RemoteResource::dprintfSelf( int debugLevel ) {
shadow->dprintf ( debugLevel, "RemoteResource::dprintSelf printing "
"host info:\n");
if ( executingHost )
shadow->dprintf ( debugLevel, "\texecutingHost: %s\n", executingHost);
if ( capability )
shadow->dprintf ( debugLevel, "\tcapability: %s\n", capability);
if ( machineName )
shadow->dprintf ( debugLevel, "\tmachineName: %s\n", machineName);
if ( starterAddress )
shadow->dprintf ( debugLevel, "\tstarterAddr: %s\n", starterAddress);
shadow->dprintf ( debugLevel, "\texitReason: %d\n", exitReason);
shadow->dprintf ( debugLevel, "\texitStatus: %d\n", exitStatus);
}
void RemoteResource::printExit( FILE *fp ) {
/* Add more cases to the switch as they develop... */
switch ( exitReason ) {
case JOB_EXITED: {
if ( WIFSIGNALED(exitStatus) ) {
fprintf ( fp, "died on signal %d.\n",
WTERMSIG(exitStatus) );
}
else {
if ( WEXITSTATUS(exitStatus) == ENOEXEC ) {
/* What has happened here is this: The starter
forked, but the exec failed with ENOEXEC and
called exit(ENOEXEC). The exit appears normal,
however, and the status is ENOEXEC - or 8. If
the user job can exit with a status of 8, we're
hosed. A better solution should be found. */
fprintf( fp, "exited because of an invalid binary.\n" );
} else {
fprintf ( fp, "exited normally with status %d.\n",
WEXITSTATUS(exitStatus) );
}
}
break;
}
case JOB_KILLED: {
fprintf ( fp, "was forceably removed by condor.\n" );
break;
}
case JOB_NOT_CKPTED: {
fprintf ( fp, "was removed by condor, without a checkpoint.\n" );
break;
}
case JOB_NOT_STARTED: {
fprintf ( fp, "was never started.\n" );
break;
}
case JOB_SHADOW_USAGE: {
fprintf ( fp, "had incorrect arguments to the condor_shadow.\n" );
fprintf ( fp, " "
"This is an internal problem...\n" );
break;
}
default: {
fprintf ( fp, "has a strange exit reason of %d.\n", exitReason );
}
} // switch()
}
int RemoteResource::handleSysCalls( Stream *sock ) {
// change value of the syscall_sock to correspond with that of
// this claim sock right before do_REMOTE_syscall().
syscall_sock = claimSock;
thisRemoteResource = this;
if (do_REMOTE_syscall() < 0) {
shadow->dprintf(D_SYSCALLS,"Shadow: do_REMOTE_syscall returned < 0\n");
// we call our shadow's shutdown method:
shadow->shutDown(exitReason, exitStatus);
// close sock on this end...the starter has gone away.
return TRUE;
}
return KEEP_STREAM;
}
void RemoteResource::getExecutingHost( char *& eHost ) {
if (!eHost) {
eHost = strnewp ( executingHost );
} else {
if ( executingHost ) {
strcpy ( eHost, executingHost );
} else {
eHost[0] = '\0';
}
}
}
void RemoteResource::getMachineName( char *& mName ) {
if ( !mName ) {
mName = strnewp( machineName );
} else {
if ( machineName ) {
strcpy( mName, machineName );
} else {
mName[0] = '\0';
}
}
}
void RemoteResource::getUidDomain( char *& uidDomain ) {
if ( !uidDomain ) {
uidDomain = strnewp( uid_domain );
} else {
if ( uid_domain ) {
strcpy( uidDomain, uid_domain );
} else {
uidDomain[0] = '\0';
}
}
}
void RemoteResource::getFilesystemDomain( char *& filesystemDomain ) {
if ( !filesystemDomain ) {
filesystemDomain = strnewp( fs_domain );
} else {
if ( fs_domain ) {
strcpy( filesystemDomain, fs_domain );
} else {
filesystemDomain[0] = '\0';
}
}
}
void RemoteResource::getCapability( char *& cbility ) {
if (!cbility) {
cbility = strnewp( capability );
} else {
if ( capability ) {
strcpy( cbility, capability );
} else {
cbility[0] = '\0';
}
}
}
void RemoteResource::getStarterAddress( char *& starterAddr ) {
if (!starterAddr) {
starterAddr = strnewp( starterAddress );
} else {
if ( starterAddress ) {
strcpy( starterAddr, starterAddress );
} else {
starterAddr[0] = '\0';
}
}
}
ReliSock* RemoteResource::getClaimSock() {
return claimSock;
}
int RemoteResource::getExitReason() {
return exitReason;
}
int RemoteResource::getExitStatus() {
return exitStatus;
}
void RemoteResource::setExecutingHost( const char * eHost ) {
if ( executingHost )
delete [] executingHost;
executingHost = strnewp( eHost );
}
void RemoteResource::setMachineName( const char * mName ) {
if ( machineName )
delete [] machineName;
machineName = strnewp ( mName );
}
void RemoteResource::setUidDomain( const char * uidDomain ) {
if ( uid_domain )
delete [] uid_domain;
uid_domain = strnewp ( uidDomain );
}
void RemoteResource::setFilesystemDomain( const char * filesystemDomain ) {
if ( fs_domain )
delete [] fs_domain;
fs_domain = strnewp ( filesystemDomain );
}
void RemoteResource::setCapability( const char * cbility ) {
if ( capability )
delete [] capability;
capability = strnewp ( cbility );
}
void RemoteResource::setStarterAddress( const char * starterAddr ) {
if ( starterAddress )
delete [] starterAddress;
starterAddress = strnewp( starterAddr );
}
void RemoteResource::setClaimSock( ReliSock * cSock ) {
claimSock = cSock;
}
void RemoteResource::setExitReason( int reason ) {
// Set the exitReason, but not if the reason is JOB_KILLED.
// This prevents exitReason being reset from JOB_KILLED to
// JOB_NOT_CKPTED or some such when the starter gets killed
// and the syscall sock goes away.
shadow->dprintf ( D_FULLDEBUG, "setting exit reason on %s to %d\n",
machineName ? machineName : executingHost, reason );
if ( exitReason != JOB_KILLED ) {
exitReason = reason;
}
}
void RemoteResource::setExitStatus( int status ) {
shadow->dprintf ( D_FULLDEBUG, "setting exit status on %s to %d\n",
machineName ? machineName : "???", status );
exitStatus = status;
}
<commit_msg>+ clarified and/or made some sense on NT of some of the termination messages + added implementations for bytesSent() and bytesRecvd() methods<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* This file is the implementation of the RemoteResource class. */
#include "condor_common.h"
#include "remoteresource.h"
#include "exit.h" // for JOB_BLAH_BLAH exit reasons
#include "condor_debug.h" // for D_debuglevel #defines
#include "condor_string.h" // for strnewp()
// for remote syscalls, this is currently in NTreceivers.C.
extern int do_REMOTE_syscall();
// for remote syscalls...
ReliSock *syscall_sock;
RemoteResource *thisRemoteResource;
// 90 seconds to wait for a socket timeout:
const int RemoteResource::SHADOW_SOCK_TIMEOUT = 90;
RemoteResource::RemoteResource( BaseShadow *shad )
{
executingHost = NULL;
capability = NULL;
init( shad );
}
RemoteResource::RemoteResource( BaseShadow * shad,
const char * eHost,
const char * cbility )
{
executingHost = strnewp( eHost );
capability = strnewp( cbility );
init( shad );
}
void RemoteResource::init( BaseShadow *shad ) {
shadow = shad;
machineName = NULL;
starterAddress = NULL;
jobAd = NULL;
fs_domain = NULL;
uid_domain = NULL;
claimSock = new ReliSock();
exitReason = exitStatus = -1;
}
RemoteResource::~RemoteResource() {
if ( executingHost ) delete [] executingHost;
if ( machineName ) delete [] machineName;
if ( capability ) delete [] capability;
if ( starterAddress) delete [] starterAddress;
if ( uid_domain ) delete [] uid_domain;
if ( fs_domain ) delete [] fs_domain;
if ( claimSock ) delete claimSock;
if ( jobAd ) delete jobAd;
}
int RemoteResource::requestIt( int starterVersion ) {
/* starterVersion is a default to 2. */
int reply;
if ( !executingHost || !capability ) {
shadow->dprintf ( D_ALWAYS, "executingHost or capability not defined"
"in requestIt.\n" );
setExitReason(JOB_SHADOW_USAGE); // no better exit reason available
return -1;
}
if ( !jobAd ) {
shadow->dprintf( D_ALWAYS, "JobAd not defined in RemoteResource\n" );
return -1;
}
claimSock->close(); // make sure ClaimSock is a virgin socket
claimSock->timeout(SHADOW_SOCK_TIMEOUT);
if (!claimSock->connect(executingHost, 0)) {
shadow->dprintf(D_ALWAYS, "failed to connect to execute host %s\n",
executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
claimSock->encode();
if (!claimSock->put(ACTIVATE_CLAIM) ||
!claimSock->code(capability) ||
!claimSock->code(starterVersion) ||
!jobAd->put(*claimSock) ||
!claimSock->end_of_message())
{
shadow->dprintf(D_ALWAYS, "failed to send ACTIVATE_CLAIM "
"request to %s\n", executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
claimSock->decode();
if (!claimSock->code(reply) || !claimSock->end_of_message()) {
shadow->dprintf(D_ALWAYS, "failed to receive ACTIVATE_CLAIM "
"reply from %s\n", executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
if (reply != OK) {
shadow->dprintf(D_ALWAYS, "Request to run on %s was REFUSED.\n",
executingHost);
setExitReason(JOB_NOT_STARTED);
return -1;
}
shadow->dprintf(D_ALWAYS, "Request to run on %s was ACCEPTED.\n",
executingHost);
return 0;
}
int RemoteResource::killStarter() {
ReliSock sock;
if ( !executingHost ) {
shadow->dprintf ( D_ALWAYS, "In killStarter, "
"executingHost not defined.\n");
return -1;
}
shadow->dprintf( D_ALWAYS, "Removing machine \"%s\".\n",
machineName ? machineName : executingHost );
sock.timeout(SHADOW_SOCK_TIMEOUT);
if (!sock.connect(executingHost, 0)) {
shadow->dprintf(D_ALWAYS, "failed to connect to executing host %s\n",
executingHost );
return -1;
}
sock.encode();
if (!sock.put(KILL_FRGN_JOB) ||
!sock.put(capability) ||
!sock.end_of_message())
{
shadow->dprintf(D_ALWAYS, "failed to send KILL_FRGN_JOB "
"to startd %s\n", executingHost );
return -1;
}
return 0;
}
void RemoteResource::dprintfSelf( int debugLevel ) {
shadow->dprintf ( debugLevel, "RemoteResource::dprintSelf printing "
"host info:\n");
if ( executingHost )
shadow->dprintf ( debugLevel, "\texecutingHost: %s\n", executingHost);
if ( capability )
shadow->dprintf ( debugLevel, "\tcapability: %s\n", capability);
if ( machineName )
shadow->dprintf ( debugLevel, "\tmachineName: %s\n", machineName);
if ( starterAddress )
shadow->dprintf ( debugLevel, "\tstarterAddr: %s\n", starterAddress);
shadow->dprintf ( debugLevel, "\texitReason: %d\n", exitReason);
shadow->dprintf ( debugLevel, "\texitStatus: %d\n", exitStatus);
}
void RemoteResource::printExit( FILE *fp ) {
/* Add more cases to the switch as they develop... */
switch ( exitReason ) {
case JOB_EXITED: {
if ( WIFSIGNALED(exitStatus) ) {
fprintf ( fp, "died on %s.\n",
daemonCore->GetExceptionString(WTERMSIG(exitStatus)) );
}
else {
#ifndef WIN32
if ( WEXITSTATUS(exitStatus) == ENOEXEC ) {
/* What has happened here is this: The starter
forked, but the exec failed with ENOEXEC and
called exit(ENOEXEC). The exit appears normal,
however, and the status is ENOEXEC - or 8. If
the user job can exit with a status of 8, we're
hosed. A better solution should be found. */
fprintf( fp, "exited because of an invalid binary.\n" );
} else
#endif // of ifndef WIN32
{
fprintf ( fp, "exited normally with status %d.\n",
WEXITSTATUS(exitStatus) );
}
}
break;
}
case JOB_KILLED: {
fprintf ( fp, "was forceably removed with condor_rm.\n" );
break;
}
case JOB_NOT_CKPTED: {
fprintf ( fp, "was removed by condor, without a checkpoint.\n" );
break;
}
case JOB_NOT_STARTED: {
fprintf ( fp, "was never started.\n" );
break;
}
case JOB_SHADOW_USAGE: {
fprintf ( fp, "had incorrect arguments to the condor_shadow.\n" );
fprintf ( fp, " "
"This is an internal problem...\n" );
break;
}
default: {
fprintf ( fp, "has a strange exit reason of %d.\n", exitReason );
}
} // switch()
}
int RemoteResource::handleSysCalls( Stream *sock ) {
// change value of the syscall_sock to correspond with that of
// this claim sock right before do_REMOTE_syscall().
syscall_sock = claimSock;
thisRemoteResource = this;
if (do_REMOTE_syscall() < 0) {
shadow->dprintf(D_SYSCALLS,"Shadow: do_REMOTE_syscall returned < 0\n");
// we call our shadow's shutdown method:
shadow->shutDown(exitReason, exitStatus);
// close sock on this end...the starter has gone away.
return TRUE;
}
return KEEP_STREAM;
}
void RemoteResource::getExecutingHost( char *& eHost ) {
if (!eHost) {
eHost = strnewp ( executingHost );
} else {
if ( executingHost ) {
strcpy ( eHost, executingHost );
} else {
eHost[0] = '\0';
}
}
}
void RemoteResource::getMachineName( char *& mName ) {
if ( !mName ) {
mName = strnewp( machineName );
} else {
if ( machineName ) {
strcpy( mName, machineName );
} else {
mName[0] = '\0';
}
}
}
void RemoteResource::getUidDomain( char *& uidDomain ) {
if ( !uidDomain ) {
uidDomain = strnewp( uid_domain );
} else {
if ( uid_domain ) {
strcpy( uidDomain, uid_domain );
} else {
uidDomain[0] = '\0';
}
}
}
void RemoteResource::getFilesystemDomain( char *& filesystemDomain ) {
if ( !filesystemDomain ) {
filesystemDomain = strnewp( fs_domain );
} else {
if ( fs_domain ) {
strcpy( filesystemDomain, fs_domain );
} else {
filesystemDomain[0] = '\0';
}
}
}
void RemoteResource::getCapability( char *& cbility ) {
if (!cbility) {
cbility = strnewp( capability );
} else {
if ( capability ) {
strcpy( cbility, capability );
} else {
cbility[0] = '\0';
}
}
}
void RemoteResource::getStarterAddress( char *& starterAddr ) {
if (!starterAddr) {
starterAddr = strnewp( starterAddress );
} else {
if ( starterAddress ) {
strcpy( starterAddr, starterAddress );
} else {
starterAddr[0] = '\0';
}
}
}
ReliSock* RemoteResource::getClaimSock() {
return claimSock;
}
int RemoteResource::getExitReason() {
return exitReason;
}
int RemoteResource::getExitStatus() {
return exitStatus;
}
void RemoteResource::setExecutingHost( const char * eHost ) {
if ( executingHost )
delete [] executingHost;
executingHost = strnewp( eHost );
}
void RemoteResource::setMachineName( const char * mName ) {
if ( machineName )
delete [] machineName;
machineName = strnewp ( mName );
}
void RemoteResource::setUidDomain( const char * uidDomain ) {
if ( uid_domain )
delete [] uid_domain;
uid_domain = strnewp ( uidDomain );
}
void RemoteResource::setFilesystemDomain( const char * filesystemDomain ) {
if ( fs_domain )
delete [] fs_domain;
fs_domain = strnewp ( filesystemDomain );
}
void RemoteResource::setCapability( const char * cbility ) {
if ( capability )
delete [] capability;
capability = strnewp ( cbility );
}
void RemoteResource::setStarterAddress( const char * starterAddr ) {
if ( starterAddress )
delete [] starterAddress;
starterAddress = strnewp( starterAddr );
}
void RemoteResource::setClaimSock( ReliSock * cSock ) {
claimSock = cSock;
}
void RemoteResource::setExitReason( int reason ) {
// Set the exitReason, but not if the reason is JOB_KILLED.
// This prevents exitReason being reset from JOB_KILLED to
// JOB_NOT_CKPTED or some such when the starter gets killed
// and the syscall sock goes away.
shadow->dprintf ( D_FULLDEBUG, "setting exit reason on %s to %d\n",
machineName ? machineName : executingHost, reason );
if ( exitReason != JOB_KILLED ) {
exitReason = reason;
}
}
void RemoteResource::setExitStatus( int status ) {
shadow->dprintf ( D_FULLDEBUG, "setting exit status on %s to %d\n",
machineName ? machineName : "???", status );
exitStatus = status;
}
float RemoteResource::bytesSent()
{
float bytes = 0.0;
// add in bytes sent by transferring files
bytes += filetrans.TotalBytesSent();
// add in bytes sent via remote system calls
/*** until the day we support syscalls in the new shadow
if (syscall_sock) {
bytes += syscall_sock->get_bytes_sent();
}
****/
return bytes;
}
float RemoteResource::bytesRecvd()
{
float bytes = 0.0;
// add in bytes sent by transferring files
bytes += filetrans.TotalBytesReceived();
// add in bytes sent via remote system calls
/*** until the day we support syscalls in the new shadow
if (syscall_sock) {
bytes += syscall_sock->get_bytes_recvd();
}
****/
return bytes;
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
#include "ofxPS3EyeGrabber.h"
#define WIDTH 640
#define HEIGHT 480
//--------------------------------------------------------------
void ofApp::setup(){
// Set the video grabber to the ofxPS3EyeGrabber.
vidGrabber.setGrabber(std::make_shared<ofxPS3EyeGrabber>());
vidGrabber.setup(WIDTH, HEIGHT);
colorImg.allocate(WIDTH, HEIGHT);
grayImage.allocate(WIDTH, HEIGHT);
grayBg.allocate(WIDTH, HEIGHT);
grayDiff.allocate(WIDTH, HEIGHT);
bLearnBakground = true;
threshold = 80;
}
//--------------------------------------------------------------
void ofApp::update(){
vidGrabber.update();
if(vidGrabber.isFrameNew())
{
colorImg.setFromPixels(vidGrabber.getPixels());
grayImage = colorImg;
if (bLearnBakground == true)
{
// the = sign copys the pixels from grayImage into grayBg (operator overloading)
grayBg = grayImage;
bLearnBakground = false;
}
// take the abs value of the difference between background and incoming and then threshold:
grayDiff.absDiff(grayBg, grayImage);
grayDiff.threshold(threshold);
// find contours which are between the size of 20 pixels and 1/3 the w*h pixels.
// also, find holes is set to true so we will get interior contours as well....
contourFinder.findContours(grayDiff, 20, (WIDTH*HEIGHT)/3, 10, true); // find holes
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0);
ofSetColor(255);
//vidGrabber.draw(0, 0);
colorImg.draw(0,0);
//grayDiff.draw(0,0);
for(int i = 0; i < contourFinder.nBlobs; i++)
{
contourFinder.blobs[i].draw(0,0);
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key){
case ' ':
bLearnBakground = true;
break;
case '+':
threshold ++;
if (threshold > 255) threshold = 255;
break;
case '-':
threshold --;
if (threshold < 0) threshold = 0;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>actual frame subtraction, don't bother with the abs()<commit_after>#include "ofApp.h"
#include "ofxPS3EyeGrabber.h"
#define WIDTH 640
#define HEIGHT 480
//--------------------------------------------------------------
void ofApp::setup(){
// Set the video grabber to the ofxPS3EyeGrabber.
vidGrabber.setGrabber(std::make_shared<ofxPS3EyeGrabber>());
vidGrabber.setPixelFormat(OF_PIXELS_RGB);
vidGrabber.setDesiredFrameRate(60);
vidGrabber.setup(WIDTH, HEIGHT);
//PS3 Eye specific settings
vidGrabber.getGrabber<ofxPS3EyeGrabber>()->setAutogain(false);
vidGrabber.getGrabber<ofxPS3EyeGrabber>()->setAutoWhiteBalance(false);
colorImg.allocate(WIDTH, HEIGHT);
grayImage.allocate(WIDTH, HEIGHT);
grayBg.allocate(WIDTH, HEIGHT);
grayDiff.allocate(WIDTH, HEIGHT);
bLearnBakground = true;
threshold = 80;
}
//--------------------------------------------------------------
void ofApp::update(){
vidGrabber.update();
if(vidGrabber.isFrameNew())
{
colorImg.setFromPixels(vidGrabber.getPixels());
grayImage = colorImg;
if (bLearnBakground == true)
{
// the = sign copys the pixels from grayImage into grayBg (operator overloading)
grayBg = grayImage;
bLearnBakground = false;
}
// take the abs value of the difference between background and incoming and then threshold:
//grayDiff.absDiff(grayBg, grayImage);
cvSub(grayImage.getCvImage(), grayBg.getCvImage(), grayDiff.getCvImage());
grayDiff.flagImageChanged();
grayDiff.threshold(threshold);
// find contours which are between the size of 20 pixels and 1/3 the w*h pixels.
// also, find holes is set to true so we will get interior contours as well....
contourFinder.findContours(grayDiff, 20, (WIDTH*HEIGHT)/3, 10, true); // find holes
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0);
ofSetColor(255);
colorImg.draw(0, 0);
grayDiff.draw(WIDTH, 0);
for(int i = 0; i < contourFinder.nBlobs; i++)
{
contourFinder.blobs[i].draw(0, 0);
contourFinder.blobs[i].draw(WIDTH, 0);
}
ofSetHexColor(0xffffff);
stringstream t;
t << "Threshold: " << threshold << std::endl
<< "Blobs: " << contourFinder.nBlobs << std::endl
<< "FPS: " << ofGetFrameRate();
ofDrawBitmapString(t.str(), 20, 20);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key)
{
case ' ':
bLearnBakground = true;
break;
case OF_KEY_UP:
threshold++;
if (threshold > 255) threshold = 255;
break;
case OF_KEY_DOWN:
threshold--;
if (threshold < 0) threshold = 0;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2015 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <gtest/gtest.h>
#include <repo/core/handler/repo_database_handler_mongo.h>
#include "../../../repo_test_database_info.h"
using namespace repo::core::handler;
MongoDatabaseHandler* getHandler()
{
std::string errMsg;
return MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, REPO_GTEST_DBPORT,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
}
TEST(MongoDatabaseHandlerTest, GetHandlerDisconnectHandler)
{
std::string errMsg;
MongoDatabaseHandler* handler =
MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, REPO_GTEST_DBPORT,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
EXPECT_TRUE(handler);
EXPECT_TRUE(errMsg.empty());
EXPECT_TRUE(MongoDatabaseHandler::getHandler(REPO_GTEST_DBADDRESS));
MongoDatabaseHandler::disconnectHandler();
EXPECT_FALSE(MongoDatabaseHandler::getHandler(REPO_GTEST_DBADDRESS));
MongoDatabaseHandler *wrongAdd = MongoDatabaseHandler::getHandler(errMsg, "blah", REPO_GTEST_DBPORT,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
EXPECT_FALSE(wrongAdd);
MongoDatabaseHandler *wrongPort = MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, 0001,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
EXPECT_FALSE(wrongPort);
//Check can connect without authentication
MongoDatabaseHandler *noauth = MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, REPO_GTEST_DBPORT,
1);
EXPECT_TRUE(noauth);
MongoDatabaseHandler::disconnectHandler();
}
TEST(MongoDatabaseHandlerTest, CreateBSONCredentials)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
EXPECT_TRUE(handler->createBSONCredentials("testdb" , "username", "password"));
EXPECT_TRUE(handler->createBSONCredentials("testdb" , "username", "password", true));
EXPECT_FALSE(handler->createBSONCredentials("" , "username", "password"));
EXPECT_FALSE(handler->createBSONCredentials("testdb", "" , "password"));
EXPECT_FALSE(handler->createBSONCredentials("testdb", "username", ""));
}
TEST(MongoDatabaseHandlerTest, CountItemsInCollection)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
auto goldenData = getCollectionCounts(REPO_GTEST_DBNAME1);
for (const auto &pair : goldenData)
{
std::string message;
EXPECT_EQ(pair.second, handler->countItemsInCollection(REPO_GTEST_DBNAME1, pair.first, message));
EXPECT_TRUE(message.empty());
}
goldenData = getCollectionCounts(REPO_GTEST_DBNAME2);
for (const auto &pair : goldenData)
{
std::string message;
EXPECT_EQ(pair.second, handler->countItemsInCollection(REPO_GTEST_DBNAME2, pair.first, message));
EXPECT_TRUE(message.empty());
}
std::string message;
EXPECT_EQ(0, handler->countItemsInCollection("", "", message));
EXPECT_FALSE(message.empty());
message.clear();
EXPECT_EQ(0, handler->countItemsInCollection("", "blah", message));
EXPECT_FALSE(message.empty());
message.clear();
EXPECT_EQ(0, handler->countItemsInCollection("blah", "", message));
EXPECT_FALSE(message.empty());
message.clear();
EXPECT_EQ(0, handler->countItemsInCollection("blah", "blah", message));
EXPECT_TRUE(message.empty());
}
TEST(MongoDatabaseHandlerTest, GetAllFromCollectionTailable)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
auto goldenData = getGoldenForGetAllFromCollectionTailable();
std::vector<repo::core::model::RepoBSON> bsons = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second);
ASSERT_EQ(bsons.size(), goldenData.second.size());
auto goldenDataDisposable = goldenData.second;
for (int i = 0; i < bsons.size(); ++i)
{
bool foundMatch = false;
for (int j = 0; j< goldenDataDisposable.size(); ++j)
{
if (foundMatch = bsons[i].toString() == goldenDataDisposable[j])
{
goldenDataDisposable.erase(goldenDataDisposable.begin() + j);
break;
}
}
EXPECT_TRUE(foundMatch);
}
//Test limit and skip
std::vector<repo::core::model::RepoBSON> bsonsLimitSkip = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 1, 1);
ASSERT_EQ(bsonsLimitSkip.size(), 1);
EXPECT_EQ(bsonsLimitSkip[0].toString(), goldenData.second[1]);
//test projection
auto bsonsProjected = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 0, 0, { "_id", "shared_id" });
std::vector<repoUUID> ids;
ASSERT_EQ(bsonsProjected.size(), bsons.size());
for (int i = 0; i < bsons.size(); ++i)
{
ids.push_back(bsons[i].getUUIDField("_id"));
EXPECT_EQ(bsons[i].getUUIDField("_id"), bsonsProjected[i].getUUIDField("_id"));
EXPECT_EQ(bsons[i].getUUIDField("shared_id"), bsonsProjected[i].getUUIDField("shared_id"));
}
//test sort
auto bsonsSorted = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 0, 0, {}, "_id", -1);
std::sort(ids.begin(), ids.end());
ASSERT_EQ(bsonsSorted.size(), ids.size());
for (int i = 0; i < bsons.size(); ++i)
{
EXPECT_EQ(bsonsSorted[i].getUUIDField("_id"), ids[bsons.size() - i - 1]);
}
bsonsSorted = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 0, 0, {}, "_id", 1);
ASSERT_EQ(bsonsSorted.size(), ids.size());
for (int i = 0; i < bsons.size(); ++i)
{
EXPECT_EQ(bsonsSorted[i].getUUIDField("_id"), ids[i]);
}
//check error handling - make sure it doesn't crash
EXPECT_EQ(0, handler->getAllFromCollectionTailable("", "").size());
EXPECT_EQ(0, handler->getAllFromCollectionTailable("", "blah").size());
EXPECT_EQ(0, handler->getAllFromCollectionTailable("blah", "").size());
EXPECT_EQ(0, handler->getAllFromCollectionTailable("blah", "blah").size());
}
TEST(MongoDatabaseHandlerTest, GetCollections)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
auto goldenData = getCollectionList(REPO_GTEST_DBNAME1);
auto collections = handler->getCollections(REPO_GTEST_DBNAME1);
ASSERT_EQ(goldenData.size(), collections.size());
std::sort(goldenData.begin(), goldenData.end());
collections.sort();
auto colIt = collections.begin();
auto gdIt = goldenData.begin();
for (;colIt != collections.end(); ++colIt, ++gdIt)
{
EXPECT_EQ(*colIt, *gdIt);
}
goldenData = getCollectionList(REPO_GTEST_DBNAME2);
collections = handler->getCollections(REPO_GTEST_DBNAME2);
ASSERT_EQ(goldenData.size(), collections.size());
std::sort(goldenData.begin(), goldenData.end());
collections.sort();
colIt = collections.begin();
gdIt = goldenData.begin();
for (; colIt != collections.end(); ++colIt, ++gdIt)
{
EXPECT_EQ(*colIt, *gdIt);
}
//check error handling - make sure it doesn't crash
EXPECT_EQ(0, handler->getCollections("").size());
EXPECT_EQ(0, handler->getCollections("blahblah").size());
}<commit_msg>#13 skip content check as it is too non deterministic<commit_after>/**
* Copyright (C) 2015 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <gtest/gtest.h>
#include <repo/core/handler/repo_database_handler_mongo.h>
#include "../../../repo_test_database_info.h"
using namespace repo::core::handler;
MongoDatabaseHandler* getHandler()
{
std::string errMsg;
return MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, REPO_GTEST_DBPORT,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
}
TEST(MongoDatabaseHandlerTest, GetHandlerDisconnectHandler)
{
std::string errMsg;
MongoDatabaseHandler* handler =
MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, REPO_GTEST_DBPORT,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
EXPECT_TRUE(handler);
EXPECT_TRUE(errMsg.empty());
EXPECT_TRUE(MongoDatabaseHandler::getHandler(REPO_GTEST_DBADDRESS));
MongoDatabaseHandler::disconnectHandler();
EXPECT_FALSE(MongoDatabaseHandler::getHandler(REPO_GTEST_DBADDRESS));
MongoDatabaseHandler *wrongAdd = MongoDatabaseHandler::getHandler(errMsg, "blah", REPO_GTEST_DBPORT,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
EXPECT_FALSE(wrongAdd);
MongoDatabaseHandler *wrongPort = MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, 0001,
1,
REPO_GTEST_AUTH_DATABASE,
REPO_GTEST_DBUSER, REPO_GTEST_DBPW);
EXPECT_FALSE(wrongPort);
//Check can connect without authentication
MongoDatabaseHandler *noauth = MongoDatabaseHandler::getHandler(errMsg, REPO_GTEST_DBADDRESS, REPO_GTEST_DBPORT,
1);
EXPECT_TRUE(noauth);
MongoDatabaseHandler::disconnectHandler();
}
TEST(MongoDatabaseHandlerTest, CreateBSONCredentials)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
EXPECT_TRUE(handler->createBSONCredentials("testdb" , "username", "password"));
EXPECT_TRUE(handler->createBSONCredentials("testdb" , "username", "password", true));
EXPECT_FALSE(handler->createBSONCredentials("" , "username", "password"));
EXPECT_FALSE(handler->createBSONCredentials("testdb", "" , "password"));
EXPECT_FALSE(handler->createBSONCredentials("testdb", "username", ""));
}
TEST(MongoDatabaseHandlerTest, CountItemsInCollection)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
auto goldenData = getCollectionCounts(REPO_GTEST_DBNAME1);
for (const auto &pair : goldenData)
{
std::string message;
EXPECT_EQ(pair.second, handler->countItemsInCollection(REPO_GTEST_DBNAME1, pair.first, message));
EXPECT_TRUE(message.empty());
}
goldenData = getCollectionCounts(REPO_GTEST_DBNAME2);
for (const auto &pair : goldenData)
{
std::string message;
EXPECT_EQ(pair.second, handler->countItemsInCollection(REPO_GTEST_DBNAME2, pair.first, message));
EXPECT_TRUE(message.empty());
}
std::string message;
EXPECT_EQ(0, handler->countItemsInCollection("", "", message));
EXPECT_FALSE(message.empty());
message.clear();
EXPECT_EQ(0, handler->countItemsInCollection("", "blah", message));
EXPECT_FALSE(message.empty());
message.clear();
EXPECT_EQ(0, handler->countItemsInCollection("blah", "", message));
EXPECT_FALSE(message.empty());
message.clear();
EXPECT_EQ(0, handler->countItemsInCollection("blah", "blah", message));
EXPECT_TRUE(message.empty());
}
TEST(MongoDatabaseHandlerTest, GetAllFromCollectionTailable)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
auto goldenData = getGoldenForGetAllFromCollectionTailable();
std::vector<repo::core::model::RepoBSON> bsons = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second);
ASSERT_EQ(bsons.size(), goldenData.second.size());
/*auto goldenDataDisposable = goldenData.second;
for (int i = 0; i < bsons.size(); ++i)
{
bool foundMatch = false;
for (int j = 0; j< goldenDataDisposable.size(); ++j)
{
if (foundMatch = bsons[i].toString() == goldenDataDisposable[j])
{
goldenDataDisposable.erase(goldenDataDisposable.begin() + j);
break;
}
}
EXPECT_TRUE(foundMatch);
}*/
//Test limit and skip
std::vector<repo::core::model::RepoBSON> bsonsLimitSkip = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 1, 1);
ASSERT_EQ(bsonsLimitSkip.size(), 1);
//EXPECT_EQ(bsonsLimitSkip[0].toString(), goldenData.second[1]);
//test projection
auto bsonsProjected = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 0, 0, { "_id", "shared_id" });
std::vector<repoUUID> ids;
ASSERT_EQ(bsonsProjected.size(), bsons.size());
for (int i = 0; i < bsons.size(); ++i)
{
ids.push_back(bsons[i].getUUIDField("_id"));
EXPECT_EQ(bsons[i].getUUIDField("_id"), bsonsProjected[i].getUUIDField("_id"));
EXPECT_EQ(bsons[i].getUUIDField("shared_id"), bsonsProjected[i].getUUIDField("shared_id"));
}
//test sort
auto bsonsSorted = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 0, 0, {}, "_id", -1);
std::sort(ids.begin(), ids.end());
ASSERT_EQ(bsonsSorted.size(), ids.size());
for (int i = 0; i < bsons.size(); ++i)
{
EXPECT_EQ(bsonsSorted[i].getUUIDField("_id"), ids[bsons.size() - i - 1]);
}
bsonsSorted = handler->getAllFromCollectionTailable(
goldenData.first.first, goldenData.first.second, 0, 0, {}, "_id", 1);
ASSERT_EQ(bsonsSorted.size(), ids.size());
for (int i = 0; i < bsons.size(); ++i)
{
EXPECT_EQ(bsonsSorted[i].getUUIDField("_id"), ids[i]);
}
//check error handling - make sure it doesn't crash
EXPECT_EQ(0, handler->getAllFromCollectionTailable("", "").size());
EXPECT_EQ(0, handler->getAllFromCollectionTailable("", "blah").size());
EXPECT_EQ(0, handler->getAllFromCollectionTailable("blah", "").size());
EXPECT_EQ(0, handler->getAllFromCollectionTailable("blah", "blah").size());
}
TEST(MongoDatabaseHandlerTest, GetCollections)
{
auto handler = getHandler();
ASSERT_TRUE(handler);
auto goldenData = getCollectionList(REPO_GTEST_DBNAME1);
auto collections = handler->getCollections(REPO_GTEST_DBNAME1);
ASSERT_EQ(goldenData.size(), collections.size());
std::sort(goldenData.begin(), goldenData.end());
collections.sort();
auto colIt = collections.begin();
auto gdIt = goldenData.begin();
for (;colIt != collections.end(); ++colIt, ++gdIt)
{
EXPECT_EQ(*colIt, *gdIt);
}
goldenData = getCollectionList(REPO_GTEST_DBNAME2);
collections = handler->getCollections(REPO_GTEST_DBNAME2);
ASSERT_EQ(goldenData.size(), collections.size());
std::sort(goldenData.begin(), goldenData.end());
collections.sort();
colIt = collections.begin();
gdIt = goldenData.begin();
for (; colIt != collections.end(); ++colIt, ++gdIt)
{
EXPECT_EQ(*colIt, *gdIt);
}
//check error handling - make sure it doesn't crash
EXPECT_EQ(0, handler->getCollections("").size());
EXPECT_EQ(0, handler->getCollections("blahblah").size());
}<|endoftext|> |
<commit_before>// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//===- non_blocking_work_queue.cc -------------------------------*- C++ -*-===//
//
// Concurrent Work Queue implementation composed from a blocking and
// non-blocking work queues.
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <thread>
#include "blocking_work_queue.h"
#include "environment.h"
#include "llvm/ADT/ArrayRef.h"
#include "non_blocking_work_queue.h"
#include "tfrt/host_context/async_value.h"
#include "tfrt/host_context/concurrent_work_queue.h"
#include "tfrt/host_context/task_function.h"
#include "tfrt/support/latch.h"
#include "tfrt/support/ref_count.h"
#include "tfrt/support/string_util.h"
namespace tfrt {
class MultiThreadedWorkQueue : public ConcurrentWorkQueue {
using ThreadingEnvironment = ::tfrt::internal::StdThreadingEnvironment;
public:
MultiThreadedWorkQueue(int num_threads, int max_blocking_work_queue_threads);
~MultiThreadedWorkQueue() override;
std::string name() const override {
return StrCat("Multi-threaded C++ work queue (", num_threads_, " threads)");
}
int GetParallelismLevel() const final { return num_threads_; }
void AddTask(TaskFunction task) final;
Optional<TaskFunction> AddBlockingTask(TaskFunction task,
bool allow_queuing) final;
void Quiesce() final;
void Await(ArrayRef<RCReference<AsyncValue>> values) final;
bool IsInWorkerThread() const final;
private:
const int num_threads_;
std::unique_ptr<internal::QuiescingState> quiescing_state_;
internal::NonBlockingWorkQueue<ThreadingEnvironment> non_blocking_work_queue_;
internal::BlockingWorkQueue<ThreadingEnvironment> blocking_work_queue_;
};
MultiThreadedWorkQueue::MultiThreadedWorkQueue(
int num_threads, int max_blocking_work_queue_threads)
: num_threads_(num_threads),
quiescing_state_(std::make_unique<internal::QuiescingState>()),
non_blocking_work_queue_(quiescing_state_.get(), num_threads),
blocking_work_queue_(quiescing_state_.get(),
max_blocking_work_queue_threads) {}
MultiThreadedWorkQueue::~MultiThreadedWorkQueue() {
// Pending tasks in the underlying queues might submit new tasks to each other
// during destruction.
Quiesce();
}
void MultiThreadedWorkQueue::AddTask(TaskFunction task) {
non_blocking_work_queue_.AddTask(std::move(task));
}
Optional<TaskFunction> MultiThreadedWorkQueue::AddBlockingTask(
TaskFunction task, bool allow_queuing) {
if (allow_queuing) {
return blocking_work_queue_.EnqueueBlockingTask(std::move(task));
} else {
return blocking_work_queue_.RunBlockingTask(std::move(task));
}
}
void MultiThreadedWorkQueue::Quiesce() {
// Turn on pending tasks counter inside both work queues.
auto quiescing = internal::Quiescing::Start(quiescing_state_.get());
// We call NonBlockingWorkQueue::Quiesce() first because we prefer to keep
// caller thread busy with compute intensive tasks.
non_blocking_work_queue_.Quiesce();
// Wait for completion of all blocking tasks.
blocking_work_queue_.Quiesce();
// At this point we might still have tasks in the work queues, but because we
// enabled quiescing mode earlier, we can rely on empty check as a loop
// condition.
while (quiescing.HasPendingTasks()) {
non_blocking_work_queue_.Quiesce();
blocking_work_queue_.Quiesce();
}
}
void MultiThreadedWorkQueue::Await(ArrayRef<RCReference<AsyncValue>> values) {
// We might block on a latch waiting for the completion of all tasks, and
// this is not allowed to do inside non blocking work queue.
non_blocking_work_queue_.CheckCallerThread("MultiThreadedWorkQueue::Await");
// We are done when values_remaining drops to zero.
tfrt::latch values_remaining(values.size());
// As each value becomes available, we decrement the count.
for (auto& value : values) {
value->AndThen([&values_remaining]() { values_remaining.count_down(); });
}
// Keep stealing tasks from non-blocking workers until we reach a point when
// all async values are resolved or we could not steal any task.
//
// We steal pending tasks globally and potentially can steal a very expensive
// task, that will unnecessarily delay the completion of this function.
// Alternative is to immediately block on the latch.
llvm::Optional<TaskFunction> task = non_blocking_work_queue_.Steal();
while (task.hasValue() || !values_remaining.try_wait()) {
if (task.hasValue()) (*task)();
task = non_blocking_work_queue_.Steal();
}
// Wait until all values are resolved.
values_remaining.wait();
}
bool MultiThreadedWorkQueue::IsInWorkerThread() const {
return non_blocking_work_queue_.IsInWorkerThread();
}
std::unique_ptr<ConcurrentWorkQueue> CreateMultiThreadedWorkQueue(
int num_threads, int num_blocking_threads) {
assert(num_threads > 0 && num_blocking_threads > 0);
return std::make_unique<MultiThreadedWorkQueue>(num_threads,
num_blocking_threads);
}
} // namespace tfrt
<commit_msg>[TFRT] Don't do work stealing in MultiThreadedWorkQueue::Await.<commit_after>// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//===- non_blocking_work_queue.cc -------------------------------*- C++ -*-===//
//
// Concurrent Work Queue implementation composed from a blocking and
// non-blocking work queues.
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <thread>
#include "blocking_work_queue.h"
#include "environment.h"
#include "llvm/ADT/ArrayRef.h"
#include "non_blocking_work_queue.h"
#include "tfrt/host_context/async_value.h"
#include "tfrt/host_context/concurrent_work_queue.h"
#include "tfrt/host_context/task_function.h"
#include "tfrt/support/latch.h"
#include "tfrt/support/ref_count.h"
#include "tfrt/support/string_util.h"
namespace tfrt {
class MultiThreadedWorkQueue : public ConcurrentWorkQueue {
using ThreadingEnvironment = ::tfrt::internal::StdThreadingEnvironment;
public:
MultiThreadedWorkQueue(int num_threads, int max_blocking_work_queue_threads);
~MultiThreadedWorkQueue() override;
std::string name() const override {
return StrCat("Multi-threaded C++ work queue (", num_threads_, " threads)");
}
int GetParallelismLevel() const final { return num_threads_; }
void AddTask(TaskFunction task) final;
Optional<TaskFunction> AddBlockingTask(TaskFunction task,
bool allow_queuing) final;
void Quiesce() final;
void Await(ArrayRef<RCReference<AsyncValue>> values) final;
bool IsInWorkerThread() const final;
private:
const int num_threads_;
std::unique_ptr<internal::QuiescingState> quiescing_state_;
internal::NonBlockingWorkQueue<ThreadingEnvironment> non_blocking_work_queue_;
internal::BlockingWorkQueue<ThreadingEnvironment> blocking_work_queue_;
};
MultiThreadedWorkQueue::MultiThreadedWorkQueue(
int num_threads, int max_blocking_work_queue_threads)
: num_threads_(num_threads),
quiescing_state_(std::make_unique<internal::QuiescingState>()),
non_blocking_work_queue_(quiescing_state_.get(), num_threads),
blocking_work_queue_(quiescing_state_.get(),
max_blocking_work_queue_threads) {}
MultiThreadedWorkQueue::~MultiThreadedWorkQueue() {
// Pending tasks in the underlying queues might submit new tasks to each other
// during destruction.
Quiesce();
}
void MultiThreadedWorkQueue::AddTask(TaskFunction task) {
non_blocking_work_queue_.AddTask(std::move(task));
}
Optional<TaskFunction> MultiThreadedWorkQueue::AddBlockingTask(
TaskFunction task, bool allow_queuing) {
if (allow_queuing) {
return blocking_work_queue_.EnqueueBlockingTask(std::move(task));
} else {
return blocking_work_queue_.RunBlockingTask(std::move(task));
}
}
void MultiThreadedWorkQueue::Quiesce() {
// Turn on pending tasks counter inside both work queues.
auto quiescing = internal::Quiescing::Start(quiescing_state_.get());
// We call NonBlockingWorkQueue::Quiesce() first because we prefer to keep
// caller thread busy with compute intensive tasks.
non_blocking_work_queue_.Quiesce();
// Wait for completion of all blocking tasks.
blocking_work_queue_.Quiesce();
// At this point we might still have tasks in the work queues, but because we
// enabled quiescing mode earlier, we can rely on empty check as a loop
// condition.
while (quiescing.HasPendingTasks()) {
non_blocking_work_queue_.Quiesce();
blocking_work_queue_.Quiesce();
}
}
void MultiThreadedWorkQueue::Await(ArrayRef<RCReference<AsyncValue>> values) {
// We might block on a latch waiting for the completion of all tasks, and
// this is not allowed to do inside non blocking work queue.
non_blocking_work_queue_.CheckCallerThread("MultiThreadedWorkQueue::Await");
// We are done when values_remaining drops to zero.
tfrt::latch values_remaining(values.size());
// As each value becomes available, we decrement the count.
for (auto& value : values) {
value->AndThen([&values_remaining]() { values_remaining.count_down(); });
}
// Wait until all values are resolved.
values_remaining.wait();
}
bool MultiThreadedWorkQueue::IsInWorkerThread() const {
return non_blocking_work_queue_.IsInWorkerThread();
}
std::unique_ptr<ConcurrentWorkQueue> CreateMultiThreadedWorkQueue(
int num_threads, int num_blocking_threads) {
assert(num_threads > 0 && num_blocking_threads > 0);
return std::make_unique<MultiThreadedWorkQueue>(num_threads,
num_blocking_threads);
}
} // namespace tfrt
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "ClientSocket.h"
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
#include <folly/Conv.h>
#include <folly/FileUtil.h>
#include <folly/ScopeGuard.h>
#include <folly/String.h>
#include <chrono>
#include <thread>
#include "mcrouter/lib/fbi/cpp/util.h"
namespace facebook { namespace memcache {
ClientSocket::ClientSocket(uint16_t port) {
struct addrinfo hints;
struct addrinfo* res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
auto portStr = folly::to<std::string>(port);
auto ret = ::getaddrinfo("localhost", portStr.data(), &hints, &res);
checkRuntime(!ret, "Failed to find a local IP: {}", ::gai_strerror(ret));
SCOPE_EXIT {
::freeaddrinfo(res);
};
socketFd_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (socketFd_ < 0) {
throwRuntime("Failed to create a socket: {}", folly::errnoStr(errno));
}
if (::connect(socketFd_, res->ai_addr, res->ai_addrlen) != 0) {
::close(socketFd_);
throwRuntime("Failed to connect: {}", folly::errnoStr(errno));
}
}
ClientSocket::ClientSocket(ClientSocket&& other) noexcept
: socketFd_(other.socketFd_) {
other.socketFd_ = -1;
}
ClientSocket& ClientSocket::operator=(ClientSocket&& other) noexcept {
if (this != &other) {
if (socketFd_ >= 0) {
::close(socketFd_);
}
socketFd_ = other.socketFd_;
other.socketFd_ = -1;
}
return *this;
}
ClientSocket::~ClientSocket() {
if (socketFd_ >= 0) {
::close(socketFd_);
}
}
void ClientSocket::write(folly::StringPiece data,
std::chrono::milliseconds timeout) {
size_t written = 0;
auto timeoutMs = static_cast<size_t>(timeout.count());
for (size_t i = 0; written < data.size() && i <= timeoutMs; ++i) {
ssize_t n = ::send(socketFd_,
data.data() + written, data.size() - written,
MSG_DONTWAIT);
if (n == -1) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
throwRuntime("failed to write to socket: {}", folly::errnoStr(errno));
}
written += n;
}
checkRuntime(written == data.size(),
"failed to write to socket. Written {}, expected {}",
written, data.size());
}
std::string ClientSocket::sendRequest(folly::StringPiece request,
std::chrono::milliseconds timeout) {
write(request, timeout);
// wait for some data to arrive
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(socketFd_, &rfds);
auto tvTimeout = to<timeval_t>(timeout);
auto ret = ::select(socketFd_ + 1, &rfds, nullptr, nullptr, &tvTimeout);
if (ret == -1) {
throwRuntime("select() failed on socket: {}", folly::errnoStr(errno));
} if (ret > 0) {
char replyBuf[kMaxReplySize + 1];
ssize_t n = ::recv(socketFd_, replyBuf, kMaxReplySize, MSG_DONTWAIT);
if (n == -1) {
throwRuntime("failed to read from socket: {}", folly::errnoStr(errno));
}
return std::string(replyBuf, n);
} else {
throwRuntime("No data available within {}ms", timeout.count());
}
}
}} // facebook::memcache
<commit_msg>Fix ClientSocket<commit_after>/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "ClientSocket.h"
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <folly/Conv.h>
#include <folly/FileUtil.h>
#include <folly/ScopeGuard.h>
#include <folly/String.h>
#include <chrono>
#include <thread>
#include "mcrouter/lib/fbi/cpp/util.h"
namespace facebook { namespace memcache {
ClientSocket::ClientSocket(uint16_t port) {
struct addrinfo hints;
struct addrinfo* res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
auto portStr = folly::to<std::string>(port);
auto ret = ::getaddrinfo("localhost", portStr.data(), &hints, &res);
checkRuntime(!ret, "Failed to find a local IP: {}", ::gai_strerror(ret));
SCOPE_EXIT {
::freeaddrinfo(res);
};
socketFd_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (socketFd_ < 0) {
throwRuntime("Failed to create a socket: {}", folly::errnoStr(errno));
}
if (::connect(socketFd_, res->ai_addr, res->ai_addrlen) != 0) {
::close(socketFd_);
throwRuntime("Failed to connect: {}", folly::errnoStr(errno));
}
}
ClientSocket::ClientSocket(ClientSocket&& other) noexcept
: socketFd_(other.socketFd_) {
other.socketFd_ = -1;
}
ClientSocket& ClientSocket::operator=(ClientSocket&& other) noexcept {
if (this != &other) {
if (socketFd_ >= 0) {
::close(socketFd_);
}
socketFd_ = other.socketFd_;
other.socketFd_ = -1;
}
return *this;
}
ClientSocket::~ClientSocket() {
if (socketFd_ >= 0) {
::close(socketFd_);
}
}
void ClientSocket::write(folly::StringPiece data,
std::chrono::milliseconds timeout) {
size_t written = 0;
auto timeoutMs = static_cast<size_t>(timeout.count());
for (size_t i = 0; written < data.size() && i <= timeoutMs; ++i) {
ssize_t n = ::send(socketFd_,
data.data() + written, data.size() - written,
MSG_DONTWAIT);
if (n == -1) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
throwRuntime("failed to write to socket: {}", folly::errnoStr(errno));
}
written += n;
}
checkRuntime(written == data.size(),
"failed to write to socket. Written {}, expected {}",
written, data.size());
}
std::string ClientSocket::sendRequest(folly::StringPiece request,
std::chrono::milliseconds timeout) {
write(request, timeout);
// wait for some data to arrive
auto timeoutMs = static_cast<size_t>(timeout.count());
for (size_t i = 0; i <= timeoutMs; ++i) {
char replyBuf[kMaxReplySize + 1];
ssize_t n = ::recv(socketFd_, replyBuf, kMaxReplySize, MSG_DONTWAIT);
if (n == -1) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
throwRuntime("failed to read from socket: {}", folly::errnoStr(errno));
} else if (n == 0) {
throwRuntime("peer closed the socket");
}
return std::string(replyBuf, n);
}
throwRuntime("timeout reading from socket");
}
}} // facebook::memcache
<|endoftext|> |
<commit_before>#ifndef slic3r_MainFrame_hpp_
#define slic3r_MainFrame_hpp_
#include "libslic3r/PrintConfig.hpp"
#include <wx/frame.h>
#include <wx/string.h>
#include <string>
#include <map>
#include "GUI_Utils.hpp"
#include "Plater.hpp"
#include "Event.hpp"
class wxNotebook;
class wxProgressDialog;
namespace Slic3r {
class ProgressStatusBar;
namespace GUI
{
class Tab;
class PrintHostQueueDialog;
enum QuickSlice
{
qsUndef = 0,
qsReslice = 1,
qsSaveAs = 2,
qsExportSVG = 4,
qsExportPNG = 8
};
struct PresetTab {
std::string name;
Tab* panel;
PrinterTechnology technology;
};
class MainFrame : public DPIFrame
{
bool m_loaded {false};
wxString m_qs_last_input_file = wxEmptyString;
wxString m_qs_last_output_file = wxEmptyString;
wxString m_last_config = wxEmptyString;
wxMenuItem* m_menu_item_repeat { nullptr };
wxMenuItem* m_menu_item_reslice_now { nullptr };
PrintHostQueueDialog *m_printhost_queue_dlg;
std::string get_base_name(const wxString &full_name, const char *extension = nullptr) const;
std::string get_dir_name(const wxString &full_name) const;
void on_presets_changed(SimpleEvent&);
void on_value_changed(wxCommandEvent&);
bool can_save() const;
bool can_export_model() const;
bool can_export_gcode() const;
bool can_slice() const;
bool can_change_view() const;
bool can_select() const;
bool can_delete() const;
bool can_delete_all() const;
protected:
virtual void on_dpi_changed(const wxRect &suggested_rect);
public:
MainFrame();
~MainFrame() {}
Plater* plater() { return m_plater; }
void init_tabpanel();
void create_preset_tabs();
void add_created_tab(Tab* panel);
void init_menubar();
void update_ui_from_settings();
bool is_loaded() const { return m_loaded; }
bool is_last_input_file() const { return !m_qs_last_input_file.IsEmpty(); }
void quick_slice(const int qs = qsUndef);
void reslice_now();
void repair_stl();
void export_config();
// Query user for the config file and open it.
void load_config_file();
// Open a config file. Return true if loaded.
bool load_config_file(const std::string &path);
void export_configbundle();
void load_configbundle(wxString file = wxEmptyString);
void load_config(const DynamicPrintConfig& config);
void select_tab(size_t tab) const;
void select_view(const std::string& direction);
// Propagate changed configuration from the Tab to the Platter and save changes to the AppConfig
void on_config_changed(DynamicPrintConfig* cfg) const ;
PrintHostQueueDialog* printhost_queue_dlg() { return m_printhost_queue_dlg; }
Plater* m_plater { nullptr };
wxNotebook* m_tabpanel { nullptr };
wxProgressDialog* m_progress_dialog { nullptr };
ProgressStatusBar* m_statusbar { nullptr };
};
} // GUI
} //Slic3r
#endif // slic3r_MainFrame_hpp_
<commit_msg>Fixed missing header (clang is picky)<commit_after>#ifndef slic3r_MainFrame_hpp_
#define slic3r_MainFrame_hpp_
#include "libslic3r/PrintConfig.hpp"
#include <wx/frame.h>
#include <wx/settings.h>
#include <wx/string.h>
#include <string>
#include <map>
#include "GUI_Utils.hpp"
#include "Plater.hpp"
#include "Event.hpp"
class wxNotebook;
class wxProgressDialog;
namespace Slic3r {
class ProgressStatusBar;
namespace GUI
{
class Tab;
class PrintHostQueueDialog;
enum QuickSlice
{
qsUndef = 0,
qsReslice = 1,
qsSaveAs = 2,
qsExportSVG = 4,
qsExportPNG = 8
};
struct PresetTab {
std::string name;
Tab* panel;
PrinterTechnology technology;
};
class MainFrame : public DPIFrame
{
bool m_loaded {false};
wxString m_qs_last_input_file = wxEmptyString;
wxString m_qs_last_output_file = wxEmptyString;
wxString m_last_config = wxEmptyString;
wxMenuItem* m_menu_item_repeat { nullptr };
wxMenuItem* m_menu_item_reslice_now { nullptr };
PrintHostQueueDialog *m_printhost_queue_dlg;
std::string get_base_name(const wxString &full_name, const char *extension = nullptr) const;
std::string get_dir_name(const wxString &full_name) const;
void on_presets_changed(SimpleEvent&);
void on_value_changed(wxCommandEvent&);
bool can_save() const;
bool can_export_model() const;
bool can_export_gcode() const;
bool can_slice() const;
bool can_change_view() const;
bool can_select() const;
bool can_delete() const;
bool can_delete_all() const;
protected:
virtual void on_dpi_changed(const wxRect &suggested_rect);
public:
MainFrame();
~MainFrame() {}
Plater* plater() { return m_plater; }
void init_tabpanel();
void create_preset_tabs();
void add_created_tab(Tab* panel);
void init_menubar();
void update_ui_from_settings();
bool is_loaded() const { return m_loaded; }
bool is_last_input_file() const { return !m_qs_last_input_file.IsEmpty(); }
void quick_slice(const int qs = qsUndef);
void reslice_now();
void repair_stl();
void export_config();
// Query user for the config file and open it.
void load_config_file();
// Open a config file. Return true if loaded.
bool load_config_file(const std::string &path);
void export_configbundle();
void load_configbundle(wxString file = wxEmptyString);
void load_config(const DynamicPrintConfig& config);
void select_tab(size_t tab) const;
void select_view(const std::string& direction);
// Propagate changed configuration from the Tab to the Platter and save changes to the AppConfig
void on_config_changed(DynamicPrintConfig* cfg) const ;
PrintHostQueueDialog* printhost_queue_dlg() { return m_printhost_queue_dlg; }
Plater* m_plater { nullptr };
wxNotebook* m_tabpanel { nullptr };
wxProgressDialog* m_progress_dialog { nullptr };
ProgressStatusBar* m_statusbar { nullptr };
};
} // GUI
} //Slic3r
#endif // slic3r_MainFrame_hpp_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "output.h"
#include "xact.h"
#include "post.h"
#include "account.h"
#include "session.h"
#include "report.h"
namespace ledger {
format_posts::format_posts(report_t& _report,
const string& format,
bool _print_raw)
: report(_report), last_xact(NULL), last_post(NULL),
print_raw(_print_raw)
{
TRACE_CTOR(format_posts, "report&, const string&");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
first_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
next_lines_format.parse(string(n, 0, p - n));
between_format.parse(string(p + 2));
} else {
next_lines_format.parse(n);
}
} else {
first_line_format.parse(format);
next_lines_format.parse(format);
}
}
void format_posts::flush()
{
report.output_stream.flush();
}
void format_posts::operator()(post_t& post)
{
std::ostream& out(report.output_stream);
if (print_raw) {
if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
print_item(out, *post.xact);
out << '\n';
last_xact = post.xact;
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
else if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
bind_scope_t bound_scope(report, post);
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
first_line_format.format(out, bound_scope);
last_xact = post.xact;
}
else if (last_post && last_post->date() != post.date()) {
first_line_format.format(out, bound_scope);
}
else {
next_lines_format.format(out, bound_scope);
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
format_accounts::format_accounts(report_t& _report,
const string& format)
: report(_report), disp_pred()
{
TRACE_CTOR(format_accounts, "report&, const string&");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
account_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
total_line_format.parse(string(n, 0, p - n));
separator_format.parse(string(p + 2));
} else {
total_line_format.parse(n);
}
} else {
account_line_format.parse(format);
total_line_format.parse(format);
}
}
void format_accounts::post_account(account_t& account)
{
if (account.xdata().has_flags(ACCOUNT_EXT_TO_DISPLAY)) {
account.xdata().add_flags(ACCOUNT_EXT_DISPLAYED);
bind_scope_t bound_scope(report, account);
account_line_format.format(report.output_stream, bound_scope);
}
}
std::pair<std::size_t, std::size_t>
format_accounts::mark_accounts(account_t& account, const bool flat)
{
std::size_t visited = 0;
std::size_t to_display = 0;
foreach (accounts_map::value_type& pair, account.accounts) {
std::pair<std::size_t, std::size_t> i = mark_accounts(*pair.second, flat);
visited += i.first;
to_display += i.second;
}
#if defined(DEBUG_ON)
DEBUG("account.display", "Considering account: " << account.fullname());
if (account.has_flags(ACCOUNT_EXT_VISITED))
DEBUG("account.display", " it was visited itself");
DEBUG("account.display", " it has " << visited << " visited children");
DEBUG("account.display",
" it has " << to_display << " children to display");
#endif
if (account.has_flags(ACCOUNT_EXT_VISITED) || (! flat && visited > 0)) {
bind_scope_t bound_scope(report, account);
if (disp_pred(bound_scope) && (flat || to_display != 1)) {
account.xdata().add_flags(ACCOUNT_EXT_TO_DISPLAY);
DEBUG("account.display", "Marking account as TO_DISPLAY");
to_display = 1;
}
visited = 1;
}
return std::pair<std::size_t, std::size_t>(visited, to_display);
}
void format_accounts::flush()
{
std::ostream& out(report.output_stream);
if (report.HANDLED(display_)) {
DEBUG("account.display",
"Account display predicate: " << report.HANDLER(display_).str());
disp_pred.predicate.parse(report.HANDLER(display_).str());
}
std::size_t top_displayed = 0;
mark_accounts(*report.session.master, report.HANDLED(flat));
foreach (account_t * account, posted_accounts) {
post_account(*account);
if (report.HANDLED(flat) && account->has_flags(ACCOUNT_EXT_DISPLAYED))
top_displayed++;
}
if (! report.HANDLED(flat)) {
foreach (accounts_map::value_type pair, report.session.master->accounts) {
if (pair.second->has_flags(ACCOUNT_EXT_DISPLAYED) ||
pair.second->children_with_flags(ACCOUNT_EXT_DISPLAYED)) {
top_displayed++;
}
}
}
if (! report.HANDLED(no_total) && top_displayed > 1 &&
report.session.master->family_total()) {
bind_scope_t bound_scope(report, *report.session.master);
separator_format.format(out, bound_scope);
total_line_format.format(out, bound_scope);
}
out.flush();
}
void format_accounts::operator()(account_t& account)
{
posted_accounts.push_back(&account);
}
} // namespace ledger
<commit_msg>Moved a variable initialization<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "output.h"
#include "xact.h"
#include "post.h"
#include "account.h"
#include "session.h"
#include "report.h"
namespace ledger {
format_posts::format_posts(report_t& _report,
const string& format,
bool _print_raw)
: report(_report), last_xact(NULL), last_post(NULL),
print_raw(_print_raw)
{
TRACE_CTOR(format_posts, "report&, const string&");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
first_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
next_lines_format.parse(string(n, 0, p - n));
between_format.parse(string(p + 2));
} else {
next_lines_format.parse(n);
}
} else {
first_line_format.parse(format);
next_lines_format.parse(format);
}
}
void format_posts::flush()
{
report.output_stream.flush();
}
void format_posts::operator()(post_t& post)
{
std::ostream& out(report.output_stream);
if (print_raw) {
if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
print_item(out, *post.xact);
out << '\n';
last_xact = post.xact;
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
else if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
bind_scope_t bound_scope(report, post);
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
first_line_format.format(out, bound_scope);
last_xact = post.xact;
}
else if (last_post && last_post->date() != post.date()) {
first_line_format.format(out, bound_scope);
}
else {
next_lines_format.format(out, bound_scope);
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
format_accounts::format_accounts(report_t& _report,
const string& format)
: report(_report), disp_pred()
{
TRACE_CTOR(format_accounts, "report&, const string&");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
account_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
total_line_format.parse(string(n, 0, p - n));
separator_format.parse(string(p + 2));
} else {
total_line_format.parse(n);
}
} else {
account_line_format.parse(format);
total_line_format.parse(format);
}
}
void format_accounts::post_account(account_t& account)
{
if (account.xdata().has_flags(ACCOUNT_EXT_TO_DISPLAY)) {
account.xdata().add_flags(ACCOUNT_EXT_DISPLAYED);
bind_scope_t bound_scope(report, account);
account_line_format.format(report.output_stream, bound_scope);
}
}
std::pair<std::size_t, std::size_t>
format_accounts::mark_accounts(account_t& account, const bool flat)
{
std::size_t visited = 0;
std::size_t to_display = 0;
foreach (accounts_map::value_type& pair, account.accounts) {
std::pair<std::size_t, std::size_t> i = mark_accounts(*pair.second, flat);
visited += i.first;
to_display += i.second;
}
#if defined(DEBUG_ON)
DEBUG("account.display", "Considering account: " << account.fullname());
if (account.has_flags(ACCOUNT_EXT_VISITED))
DEBUG("account.display", " it was visited itself");
DEBUG("account.display", " it has " << visited << " visited children");
DEBUG("account.display",
" it has " << to_display << " children to display");
#endif
if (account.has_flags(ACCOUNT_EXT_VISITED) || (! flat && visited > 0)) {
bind_scope_t bound_scope(report, account);
if (disp_pred(bound_scope) && (flat || to_display != 1)) {
account.xdata().add_flags(ACCOUNT_EXT_TO_DISPLAY);
DEBUG("account.display", "Marking account as TO_DISPLAY");
to_display = 1;
}
visited = 1;
}
return std::pair<std::size_t, std::size_t>(visited, to_display);
}
void format_accounts::flush()
{
std::ostream& out(report.output_stream);
if (report.HANDLED(display_)) {
DEBUG("account.display",
"Account display predicate: " << report.HANDLER(display_).str());
disp_pred.predicate.parse(report.HANDLER(display_).str());
}
mark_accounts(*report.session.master, report.HANDLED(flat));
std::size_t top_displayed = 0;
foreach (account_t * account, posted_accounts) {
post_account(*account);
if (report.HANDLED(flat) && account->has_flags(ACCOUNT_EXT_DISPLAYED))
top_displayed++;
}
if (! report.HANDLED(flat)) {
foreach (accounts_map::value_type pair, report.session.master->accounts) {
if (pair.second->has_flags(ACCOUNT_EXT_DISPLAYED) ||
pair.second->children_with_flags(ACCOUNT_EXT_DISPLAYED)) {
top_displayed++;
}
}
}
if (! report.HANDLED(no_total) && top_displayed > 1 &&
report.session.master->family_total()) {
bind_scope_t bound_scope(report, *report.session.master);
separator_format.format(out, bound_scope);
total_line_format.format(out, bound_scope);
}
out.flush();
}
void format_accounts::operator()(account_t& account)
{
posted_accounts.push_back(&account);
}
} // namespace ledger
<|endoftext|> |
<commit_before>#include "lsearch_init.h"
using namespace nano;
scalar_t lsearch_unit_init_t::get(const solver_state_t&, const int)
{
return 1;
}
scalar_t lsearch_linear_init_t::get(const solver_state_t& state, const int iteration)
{
scalar_t t0;
const auto dg = state.d.dot(state.g);
switch (iteration)
{
case 0:
t0 = 1;
break;
default:
// NB: the line-search length is from the previous iteration!
t0 = state.t * m_prevdg / dg;
break;
}
m_prevdg = dg;
return t0;
}
scalar_t lsearch_quadratic_init_t::get(const solver_state_t& state, const int iteration)
{
scalar_t t0;
switch (iteration)
{
case 0:
t0 = 1;
break;
default:
t0 = scalar_t(1.01) * 2 * (state.f - m_prevf) / state.d.dot(state.g);
break;
}
m_prevf = state.f;
return t0;
}
scalar_t lsearch_cgdescent_init_t::get(const solver_state_t& state, const int iteration)
{
scalar_t t0;
const auto phi0 = scalar_t(0.01);
const auto phi2 = scalar_t(2.0);
switch (iteration)
{
case 0:
{
const auto xnorm = state.x.lpNorm<Eigen::Infinity>();
const auto fnorm = std::fabs(state.f);
if (xnorm > 0)
{
t0 = phi0 * xnorm / state.g.lpNorm<Eigen::Infinity>();
}
else if (fnorm > 0)
{
t0 = phi0 * fnorm / state.g.squaredNorm();
}
else
{
t0 = 1;
}
}
break;
default:
// NB: the line-search length is from the previous iteration!
t0 = state.t * phi2;
break;
}
return t0;
}
<commit_msg>cg_descent lsearch initial step with quadratic interpolation (to finish)<commit_after>#include "lsearch_init.h"
using namespace nano;
scalar_t lsearch_unit_init_t::get(const solver_state_t&, const int)
{
return 1;
}
scalar_t lsearch_linear_init_t::get(const solver_state_t& state, const int iteration)
{
scalar_t t0;
const auto dg = state.d.dot(state.g);
switch (iteration)
{
case 0:
t0 = 1;
break;
default:
// NB: the line-search length is from the previous iteration!
t0 = state.t * m_prevdg / dg;
break;
}
m_prevdg = dg;
return t0;
}
scalar_t lsearch_quadratic_init_t::get(const solver_state_t& state, const int iteration)
{
scalar_t t0;
switch (iteration)
{
case 0:
t0 = 1;
break;
default:
t0 = scalar_t(1.01) * 2 * (state.f - m_prevf) / state.d.dot(state.g);
break;
}
m_prevf = state.f;
return t0;
}
scalar_t lsearch_cgdescent_init_t::get(const solver_state_t& state, const int iteration)
{
scalar_t t0;
const auto phi0 = scalar_t(0.01);
const auto phi1 = scalar_t(0.1);
const auto phi2 = scalar_t(2.0);
switch (iteration)
{
case 0:
{
const auto xnorm = state.x.lpNorm<Eigen::Infinity>();
const auto fnorm = std::fabs(state.f);
if (xnorm > 0)
{
t0 = phi0 * xnorm / state.g.lpNorm<Eigen::Infinity>();
}
else if (fnorm > 0)
{
t0 = phi0 * fnorm / state.g.squaredNorm();
}
else
{
t0 = 1;
}
}
break;
default:
{
// NB: the line-search length is from the previous iteration!
lsearch_strategy_t::step_t step0 = state;
lsearch_strategy_t::step_t stepx;
stepx.t = state.t * phi1;
stepx.f = state.function->vgrad(state.x + stepx.t * state.d);
stepx.g = 0;
const auto tq = lsearch_strategy_t::quadratic(step0, stepx);
if (stepx.f < step0.f && tq > 0 && tq < stepx.t)
{
// todo: check here if the quadratic interpolant is convex!!!
t0 = tq;
}
else
{
t0 = state.t * phi2;
}
}
break;
}
return t0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <ostream>
#include <cstdint>
#include <tuple>
#include <type_traits>
namespace stub
{
/// Specialization chosen for empty tuples or when Index reaches the
/// sizeof the tuple (i.e. the number of values in the tuple), see
/// description below.
template
<
uint32_t Index = 0,
class... Args,
typename std::enable_if<Index == sizeof...(Args), uint8_t>::type = 0
>
inline void print_arguments(std::ostream& out, const std::tuple<Args...>& t)
{
(void) out;
(void) t;
}
/// Prints the content of a tuple to the specified std::ostream.
///
/// The two functions print_arguments use SFINAE (Substitution Failure
/// Is Not An Error) to select which overload to call.
///
/// The overloading works like this:
///
/// 1. If print_arguments is called with an empty tuple then
/// Index==sizeof...(Args) will be true and the empty overload
/// will be chosen.
///
/// 2. If print_argument is called with a non-empty tuple the
/// Index!=sizeof(Args) is true and the overload writing to the
/// std::ostream will be called. This will then recursively call
/// print_arguments incrementing the Index. A some point
/// Index==sizeof(Args) and the empty overload gets chosen and we
/// are done.
///
///Note that if called with an empty tuple then
/// Index != sizeof...(Args) will be false and the empty
/// print_arguments will be called
template
<
uint32_t Index = 0,
class... Args,
typename std::enable_if<Index != sizeof...(Args), uint8_t>::type = 0
>
inline void print_arguments(std::ostream& out, const std::tuple<Args...>& t)
{
out << "Arg " << Index << ": " << std::get<Index>(t) << "\n";
print_arguments<Index + 1>(out, t);
}
}
<commit_msg>Make win32 happy<commit_after>// Copyright (c) 2015 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <ostream>
#include <cstdint>
#include <tuple>
#include <type_traits>
namespace stub
{
inline void print_arguments(std::ostream& out, const std::tuple<>& t)
{
(void) out;
(void) t;
}
/// Specialization chosen for empty tuples or when Index reaches the
/// sizeof the tuple (i.e. the number of values in the tuple), see
/// description below.
template
<
uint32_t Index = 0,
class... Args,
typename std::enable_if<Index == sizeof...(Args), uint8_t>::type = 0
>
inline void print_arguments(std::ostream& out, const std::tuple<Args...>& t)
{
(void) out;
(void) t;
}
/// Prints the content of a tuple to the specified std::ostream.
///
/// The two functions print_arguments use SFINAE (Substitution Failure
/// Is Not An Error) to select which overload to call.
///
/// The overloading works like this:
///
/// 1. If print_arguments is called with an empty tuple then
/// Index==sizeof...(Args) will be true and the empty overload
/// will be chosen.
///
/// 2. If print_argument is called with a non-empty tuple the
/// Index!=sizeof(Args) is true and the overload writing to the
/// std::ostream will be called. This will then recursively call
/// print_arguments incrementing the Index. A some point
/// Index==sizeof(Args) and the empty overload gets chosen and we
/// are done.
///
///Note that if called with an empty tuple then
/// Index != sizeof...(Args) will be false and the empty
/// print_arguments will be called
template
<
uint32_t Index = 0,
class... Args,
typename std::enable_if<Index != sizeof...(Args), uint8_t>::type = 0
>
inline void print_arguments(std::ostream& out, const std::tuple<Args...>& t)
{
out << "Arg " << Index << ": " << std::get<Index>(t) << "\n";
print_arguments<Index + 1>(out, t);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "type.hpp"
#include "error.hpp"
#define BOOST_PP_VARIADICS 1
#include <boost/preprocessor.hpp>
namespace spn {
template <class... Ts>
struct ValueHolder {
template <class T2>
void ref(T2*) {}
template <class T2>
void cref(T2*) const {}
};
template <class T, class... Ts>
struct ValueHolder<T, Ts...> : ValueHolder<Ts...> {
using base = ValueHolder<Ts...>;
using value_type = typename T::value_type;
value_type value;
value_type& ref(T*) { return value; }
const value_type& cref(T*) const { return value; }
template <class T2>
auto ref(T2* p) -> decltype(base::ref(p)) {
return base::ref(p); }
template <class T2>
auto cref(T2* p) const -> decltype(base::cref(p)) {
return base::cref(p); }
};
//! キャッシュ変数の自動管理クラス
template <class Class, class... Ts>
class RFlag : public ValueHolder<Ts...> {
public:
using FlagValue = uint32_t;
private:
using base = ValueHolder<Ts...>;
using ct_base = spn::CType<Ts...>;
template <class T>
static T* _GetNull() { return reinterpret_cast<T*>(0); }
mutable FlagValue _rflag = All();
//! integral_constantの値がtrueなら引数テンプレートのOr()を返す
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,false>) { return 0; }
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,true>) { return OrLH<T0>(); }
template <class T, int N>
static constexpr FlagValue _IterateLH(std::integral_constant<int,N>) {
using T0 = typename ct_base::template At<N>::type;
using T0Has = typename T0::template Has<T>;
return _Add_If<T0>(T0Has()) |
_IterateLH<T>(std::integral_constant<int,N+1>());
}
template <class T>
static constexpr FlagValue _IterateLH(std::integral_constant<int,ct_base::size>) { return 0; }
template <class T, int N>
static constexpr FlagValue _IterateHL(std::integral_constant<int,N>) {
using T0 = typename T::template At<N>::type;
return OrHL<T0>() | _IterateHL<T>(std::integral_constant<int,N-1>());
}
template <class T>
static constexpr FlagValue _IterateHL(std::integral_constant<int,-1>) { return 0; }
template <class T>
auto _refresh(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
const base* ptrC = this;
base* ptr = const_cast<base*>(ptrC);
_rflag &= ~(self->_refresh(ptr->ref(_GetNull<T>()), _GetNull<T>()));
_rflag &= ~Get<T>();
AssertP(Trap, !(_rflag & OrHL<T>()), "refresh flag was not cleared correctly")
return ptrC->cref(_GetNull<T>());
}
template <class TA>
static constexpr FlagValue _GetSingle() {
return 1 << ct_base::template Find<TA>::result;
}
template <class... TsA>
static constexpr FlagValue _Sum(std::integral_constant<int,0>) { return 0; }
template <class TA, class... TsA, int N>
static constexpr FlagValue _Sum(std::integral_constant<int,N>) {
return _GetSingle<TA>() | _Sum<TsA...>(std::integral_constant<int,N-1>());
}
template <class... TsA>
void _setFlag(std::integral_constant<int,0>) {}
template <class T, class... TsA, int N>
void _setFlag(std::integral_constant<int,N>) {
_rflag |= OrLH<T>();
_setFlag<TsA...>(std::integral_constant<int,N-1>());
}
public:
template <class... TsA>
static constexpr FlagValue Get() {
return _Sum<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
static constexpr FlagValue All() {
return (1 << (sizeof...(Ts)+1)) -1;
}
FlagValue GetFlag() const {
return _rflag;
}
template <class... TsA>
FlagValue Test() const {
return GetFlag() & Get<TsA...>();
}
template <class T>
static constexpr FlagValue OrLH() {
// TypeListを巡回、A::Has<T>ならOr<A>()をたす
return Get<T>() | _IterateLH<T>(std::integral_constant<int,0>());
}
template <class T>
static constexpr FlagValue OrHL() {
return Get<T>() | _IterateHL<T>(std::integral_constant<int,T::size-1>());
}
//! 更新フラグだけを立てる
template <class... TsA>
void setFlag() {
_setFlag<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
template <class T>
auto get(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
if(!(_rflag & Get<T>()))
return base::cref(_GetNull<T>());
return _refresh<T>(self);
}
template <class T>
auto ref() const -> typename std::decay<decltype(base::cref(_GetNull<T>()))>::type& {
// 更新チェックなしで参照を返す
const auto& ret = base::cref(_GetNull<T>());
return const_cast<typename std::decay<decltype(ret)>::type&>(ret);
}
template <class T>
auto refF() -> decltype(ref<T>()) {
// 更新フラグありで参照を返す
setFlag<T>();
return ref<T>();
}
//! キャッシュ機能付きの値を変更する際に使用
template <class T, class TA>
void set(TA&& t) {
refF<T>() = std::forward<TA>(t);
}
};
#define RFLAG(clazz, seq) \
using RFlag_t = spn::RFlag<clazz, BOOST_PP_SEQ_ENUM(seq)>; \
RFlag_t _rflag; \
template <class T, class... Ts> \
friend class spn::RFlag;
#define RFLAG_RVALUE_BASE(name, valueT, ...) \
struct name : spn::CType<__VA_ARGS__> { \
using value_type = valueT; \
value_type value; };
#define RFLAG_RVALUE(name, ...) \
RFLAG_RVALUE_BASE(name, __VA_ARGS__) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
1 \
), \
RFLAG_RVALUE_, \
RFLAG_RVALUE_D_ \
)(name, __VA_ARGS__)
#define RFLAG_RVALUE_D_(name, valueT, ...) \
uint32_t _refresh(valueT&, name*) const;
#define RFLAG_RVALUE_(name, valueT) \
uint32_t _refresh(valueT&, name*) const { return 0; }
#define RFLAG_GETMETHOD(name) auto get##name() const -> decltype(_rflag.get<name>(this)) { return _rflag.get<name>(this); }
#define PASS_THROUGH(func, ...) func(__VA_ARGS__)
#define RFLAG_FUNC(z, data, elem) PASS_THROUGH(RFLAG_RVALUE, BOOST_PP_SEQ_ENUM(elem))
#define SEQ_GETFIRST(z, data, elem) (BOOST_PP_SEQ_ELEM(0,elem))
#define RFLAG_S(clazz, seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC, \
BOOST_PP_NIL, \
seq \
) \
RFLAG( \
clazz, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_FUNC2(z, data, elem) RFLAG_GETMETHOD(elem)
#define RFLAG_GETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC2, \
BOOST_PP_NIL, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
/* class MyClass {
RFLAG_RVALUE(Value0, Type0)
RFLAG_RVALUE(Value0, Type0, Depends....) をクラス内に変数分だけ書く
更新関数を uint32_t _refresh(Type0&, Value0*) const; の形で記述
RFLAG(MyClass, Value0, Value0...)
public:
// 参照用の関数
RFLAG_GETMETHOD(Value0)
RFLAG_GETMETHOD(Value1)
参照する時は _rflag.get<Value0>(this) とやるか、
getValue0()とすると依存変数の自動更新
_rfvalue.ref<Value0>(this)とすれば依存関係を無視して取り出せる
--- 上記の簡略系 ---
#define SEQ ((Value0)(Type0))((Value1)(Type1)(Depend))
private:
RFLAG_S(MyClass, SEQ)
public:
RFLAG_GETMETHOD_S(SEQ) */
#define VARIADIC_FOR_EACH_FUNC(z, n, data) BOOST_PP_TUPLE_ELEM(0, data)(1, BOOST_PP_TUPLE_ELEM(1,data), BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n,2),data))
#define VARIADIC_FOR_EACH(macro, data, ...) BOOST_PP_REPEAT(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), VARIADIC_FOR_EACH_FUNC, BOOST_PP_VARIADIC_TO_TUPLE(macro, data, __VA_ARGS__))
}
<commit_msg>rflag: 中間層への値セット setMethodの自動定義マクロ<commit_after>#pragma once
#include "type.hpp"
#include "error.hpp"
#define BOOST_PP_VARIADICS 1
#include <boost/preprocessor.hpp>
namespace spn {
template <class... Ts>
struct ValueHolder {
template <class T2>
void ref(T2*) {}
template <class T2>
void cref(T2*) const {}
};
template <class T, class... Ts>
struct ValueHolder<T, Ts...> : ValueHolder<Ts...> {
using base = ValueHolder<Ts...>;
using value_type = typename T::value_type;
value_type value;
value_type& ref(T*) { return value; }
const value_type& cref(T*) const { return value; }
template <class T2>
auto ref(T2* p) -> decltype(base::ref(p)) {
return base::ref(p); }
template <class T2>
auto cref(T2* p) const -> decltype(base::cref(p)) {
return base::cref(p); }
};
//! キャッシュ変数の自動管理クラス
template <class Class, class... Ts>
class RFlag : public ValueHolder<Ts...> {
public:
using FlagValue = uint32_t;
private:
using base = ValueHolder<Ts...>;
using ct_base = spn::CType<Ts...>;
template <class T>
static T* _GetNull() { return reinterpret_cast<T*>(0); }
mutable FlagValue _rflag = All();
//! integral_constantの値がtrueなら引数テンプレートのOr()を返す
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,false>) { return 0; }
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,true>) { return OrLH<T0>(); }
template <class T, int N>
static constexpr FlagValue _IterateLH(std::integral_constant<int,N>) {
using T0 = typename ct_base::template At<N>::type;
using T0Has = typename T0::template Has<T>;
return _Add_If<T0>(T0Has()) |
_IterateLH<T>(std::integral_constant<int,N+1>());
}
template <class T>
static constexpr FlagValue _IterateLH(std::integral_constant<int,ct_base::size>) { return 0; }
template <class T, int N>
static constexpr FlagValue _IterateHL(std::integral_constant<int,N>) {
using T0 = typename T::template At<N>::type;
return OrHL<T0>() | _IterateHL<T>(std::integral_constant<int,N-1>());
}
template <class T>
static constexpr FlagValue _IterateHL(std::integral_constant<int,-1>) { return 0; }
template <class T>
auto _refresh(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
const base* ptrC = this;
base* ptr = const_cast<base*>(ptrC);
_rflag &= ~(self->_refresh(ptr->ref(_GetNull<T>()), _GetNull<T>()));
_rflag &= ~Get<T>();
AssertP(Trap, !(_rflag & OrHL<T>()), "refresh flag was not cleared correctly")
return ptrC->cref(_GetNull<T>());
}
template <class TA>
static constexpr FlagValue _GetSingle() {
return 1 << ct_base::template Find<TA>::result;
}
template <class... TsA>
static constexpr FlagValue _Sum(std::integral_constant<int,0>) { return 0; }
template <class TA, class... TsA, int N>
static constexpr FlagValue _Sum(std::integral_constant<int,N>) {
return _GetSingle<TA>() | _Sum<TsA...>(std::integral_constant<int,N-1>());
}
template <class... TsA>
void _setFlag(std::integral_constant<int,0>) {}
template <class T, class... TsA, int N>
void _setFlag(std::integral_constant<int,N>) {
// 自分より下の階層はフラグを下ろす
_rflag &= ~OrHL<T>();
// 自分の階層より上の変数は全てフラグを立てる
_rflag |= OrLH<T>();
_setFlag<TsA...>(std::integral_constant<int,N-1>());
}
public:
template <class... TsA>
static constexpr FlagValue Get() {
return _Sum<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
static constexpr FlagValue All() {
return (1 << (sizeof...(Ts)+1)) -1;
}
FlagValue GetFlag() const {
return _rflag;
}
template <class... TsA>
FlagValue Test() const {
return GetFlag() & Get<TsA...>();
}
template <class T>
static constexpr FlagValue OrLH() {
// TypeListを巡回、A::Has<T>ならOr<A>()をたす
return Get<T>() | _IterateLH<T>(std::integral_constant<int,0>());
}
template <class T>
static constexpr FlagValue OrHL() {
return Get<T>() | _IterateHL<T>(std::integral_constant<int,T::size-1>());
}
//! 更新フラグだけを立てる
template <class... TsA>
void setFlag() {
_setFlag<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
template <class T>
auto get(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
if(!(_rflag & Get<T>()))
return base::cref(_GetNull<T>());
return _refresh<T>(self);
}
template <class T>
auto ref() const -> typename std::decay<decltype(base::cref(_GetNull<T>()))>::type& {
// 更新チェックなしで参照を返す
const auto& ret = base::cref(_GetNull<T>());
return const_cast<typename std::decay<decltype(ret)>::type&>(ret);
}
template <class T>
auto refF() -> decltype(ref<T>()) {
// 更新フラグありで参照を返す
setFlag<T>();
return ref<T>();
}
//! キャッシュ機能付きの値を変更する際に使用
template <class T, class TA>
void set(TA&& t) {
refF<T>() = std::forward<TA>(t);
}
};
#define RFLAG(clazz, seq) \
using RFlag_t = spn::RFlag<clazz, BOOST_PP_SEQ_ENUM(seq)>; \
RFlag_t _rflag; \
template <class T, class... Ts> \
friend class spn::RFlag;
#define RFLAG_RVALUE_BASE(name, valueT, ...) \
struct name : spn::CType<__VA_ARGS__> { \
using value_type = valueT; \
value_type value; };
#define RFLAG_RVALUE(name, ...) \
RFLAG_RVALUE_BASE(name, __VA_ARGS__) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
1 \
), \
RFLAG_RVALUE_, \
RFLAG_RVALUE_D_ \
)(name, __VA_ARGS__)
#define RFLAG_RVALUE_D_(name, valueT, ...) \
uint32_t _refresh(valueT&, name*) const;
#define RFLAG_RVALUE_(name, valueT) \
uint32_t _refresh(valueT&, name*) const { return 0; }
#define RFLAG_GETMETHOD(name) auto get##name() const -> decltype(_rflag.get<name>(this)) { return _rflag.get<name>(this); }
#define PASS_THROUGH(func, ...) func(__VA_ARGS__)
#define RFLAG_FUNC(z, data, elem) PASS_THROUGH(RFLAG_RVALUE, BOOST_PP_SEQ_ENUM(elem))
#define SEQ_GETFIRST(z, data, elem) (BOOST_PP_SEQ_ELEM(0,elem))
#define RFLAG_S(clazz, seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC, \
BOOST_PP_NIL, \
seq \
) \
RFLAG( \
clazz, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_FUNC2(z, data, elem) RFLAG_GETMETHOD(elem)
#define RFLAG_GETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC2, \
BOOST_PP_NIL, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_SETMETHOD(name) \
template <class TArg> \
void BOOST_PP_CAT(set, name(TArg&& t)) { _rflag.set<name>(std::forward<TArg>(t)); }
#define RFLAG_FUNC3(z, dummy, seq) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_SEQ_SIZE(seq), \
2 \
), \
RFLAG_SETMETHOD, \
NOTHING_ARG \
)(BOOST_PP_SEQ_ELEM(0, seq))
#define RFLAG_SETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC3, \
BOOST_PP_NIL, \
seq \
)
/* class MyClass {
RFLAG_RVALUE(Value0, Type0)
RFLAG_RVALUE(Value0, Type0, Depends....) をクラス内に変数分だけ書く
更新関数を uint32_t _refresh(Type0&, Value0*) const; の形で記述
RFLAG(MyClass, Value0, Value0...)
public:
// 参照用の関数
RFLAG_GETMETHOD(Value0)
RFLAG_GETMETHOD(Value1)
参照する時は _rflag.get<Value0>(this) とやるか、
getValue0()とすると依存変数の自動更新
_rfvalue.ref<Value0>(this)とすれば依存関係を無視して取り出せる
--- 上記の簡略系 ---
#define SEQ ((Value0)(Type0))((Value1)(Type1)(Depend))
private:
RFLAG_S(MyClass, SEQ)
public:
RFLAG_GETMETHOD_S(SEQ) */
#define VARIADIC_FOR_EACH_FUNC(z, n, data) BOOST_PP_TUPLE_ELEM(0, data)(1, BOOST_PP_TUPLE_ELEM(1,data), BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n,2),data))
#define VARIADIC_FOR_EACH(macro, data, ...) BOOST_PP_REPEAT(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), VARIADIC_FOR_EACH_FUNC, BOOST_PP_VARIADIC_TO_TUPLE(macro, data, __VA_ARGS__))
}
<|endoftext|> |
<commit_before>
#include "RFM02.h"
uint8_t _pinFSK;
uint8_t _pinNIRQ;
uint8_t _pinSOMI;
uint8_t _pinSIMO;
uint8_t _pinChipSelect;
uint8_t _pinSerialClock;
// Booster Pack Pins FR5969
// 7 - P2.2 for SPI_CLK mode
// 15 - P1.6 for SPI_SIMO mode
// 14 - P1.7 for SPI_SOMI mode
// 5 - P2.5 output pin for SPI_CS
// 18 - P3.0 nIRQ for sending data
// 3 - P2.6 as FSK input data
// Set display's VCC and DISP pins to high
static const uint8_t P_CS = 4;
static const uint8_t P_FSK = 3;
static const uint8_t P_NIRQ = 18;
// empty constructor
RFM02::RFM02() {
RFM02(P_CS, P_FSK, P_NIRQ);
}
// constructor with variables
RFM02::RFM02(uint8_t pinChipSelect, uint8_t pinFSK, uint8_t pinNIRQ){
_pinChipSelect = pinChipSelect;
_pinFSK = pinFSK;
_pinNIRQ = pinNIRQ;
}
void RFM02::begin() {
digitalWrite(_pinChipSelect, HIGH); // set chip select high
pinMode(_pinChipSelect, OUTPUT); // set chip select pin as output
digitalWrite(_pinFSK, LOW); // set FSK to low
pinMode(_pinFSK, OUTPUT); // set FSK pin as output
pinMode(P_NIRQ, INPUT); // set nIRQ pin as input
configureDeviceSettings(); // configure RFM01 to correct settings
pinMode(RED_LED, OUTPUT); // set pin with red led as output
digitalWrite(RED_LED, HIGH); // blink red led 50 ms to indicate setup ready
delay(50);
digitalWrite(RED_LED, LOW);
}
void RFM02::writeRegister(uint8_t HighByte, uint8_t LowByte) {
digitalWrite(_pinChipSelect,LOW);
SPI.transfer(HighByte);
SPI.transfer(LowByte);
digitalWrite(_pinChipSelect,HIGH);
}
void RFM02::configureDeviceSettings() {
writeRegister(0xCC,0x00); // read status
writeRegister(0x93,0x82); // 868MHz Band +/- 90kHz Bandbreite
writeRegister(0xA6,0x86); // 868.35 MHz
writeRegister(0xD0,0x40); // RATE/2
writeRegister(0xC8,0x23); // 4.8kbps
writeRegister(0xC2,0x20); // Bit Sync active
writeRegister(0xC0,0x01); // disable TX
writeRegister(0xD2,0x40); // PLL 25%
writeRegister(0xB0,0x00); // -9 db
writeRegister(0xE0,0x00); // 'disable wakeup timer
}
// Data via FSK
/******************************************************************************/
/* Sending data via the FSK-Pin as Input-Pin */
/* */
/* After the PowerAmplifier has turned on ( ea=1 ) from rfm02-module */
/* comes a clock corresponding to the data-rate set before on nIRQ. */
/* The data to be transmitted is bitwise set on the FSK-Pin of the */
/* module, after the falling edge of nIRQ. With the following edge */
/* of nIRQ this bit is read in and sent out. */
/* nSEL must be high, SCK low, both all the time */
/* */
/* */
/* TESTED: 28.09.2014 with Deviation +/- 90kHz and 435.000 MHz */
/* up to 115.000BPS */
/* */
/* Support & Copyright: [email protected] */
/******************************************************************************/
void RFM02::RFM02_TX_DataByte_FSK(uint8_t DataByte){
uint8_t i=8;
// PowerAmplifier is here already enabled, impulses on nIRQ corresponding to the
// set data-rate, nSEL is high, SCK is low
digitalWrite(_pinChipSelect,HIGH);
while(i){ // do 8 times..., (any number of bit's will do, also 9 or 121)
i=i-1;
while(!(digitalRead(_pinNIRQ))); // wait for the 0-1-edge of nIRQ, reading in the data
while((digitalRead(_pinNIRQ))); // wait for 1-0-edge to send the last bit
if( DataByte & BIT7 ) // if not '0' write over with '1'
digitalWrite(_pinFSK, HIGH); // ...write '1' if most significant bit is '1'
else
digitalWrite(_pinFSK, LOW); //OUT_PORT_REG &= ~FSK; // first set Bitx as '0'
DataByte <<= 1; // shift DataByte one bit left to write the next bit
}
}
void RFM02::sendMessage(uint8_t *txData, uint8_t size)
{
//digitalWrite(_pinChipSelect, LOW); // CS LOW
writeRegister(0xC0,0x39); // enable TX
//digitalWrite(_pinChipSelect, HIGH); // CS HIGH
//delay(1000);
RFM02_TX_DataByte_FSK(0xAA); // preamble
RFM02_TX_DataByte_FSK(0xAA); // preamble
RFM02_TX_DataByte_FSK(0xAA); // preamble
RFM02_TX_DataByte_FSK(0x2D); // sync word high
RFM02_TX_DataByte_FSK(0xD4); // sync word low
for(int myLoop=0;myLoop<MESSAGELENGTH;myLoop++)
{
RFM02_TX_DataByte_FSK(txData[myLoop]); // sync word lowtxData[myLoop] = myLoop;
}
/*
RFM02_TX_DataByte_FSK('H'); // data
RFM02_TX_DataByte_FSK('E'); // data
RFM02_TX_DataByte_FSK('L'); // data
RFM02_TX_DataByte_FSK('L'); // data
RFM02_TX_DataByte_FSK('O'); // data
RFM02_TX_DataByte_FSK(1); // data
RFM02_TX_DataByte_FSK(2); // data
RFM02_TX_DataByte_FSK(3); // data
RFM02_TX_DataByte_FSK(4); // data
RFM02_TX_DataByte_FSK(0xA5); // ende zeichen
*/
delay(1); // delay until carrier turn off
//digitalWrite(_pinChipSelect, LOW); // CS LOW
writeRegister(0xC0,0x01); // disable TX
//digitalWrite(_pinChipSelect, HIGH); // CS HIGH
}
<commit_msg>corrected upper-case letter error in include for rfm02.h to make linux compatible<commit_after>
#include "rfm02.h"
uint8_t _pinFSK;
uint8_t _pinNIRQ;
uint8_t _pinSOMI;
uint8_t _pinSIMO;
uint8_t _pinChipSelect;
uint8_t _pinSerialClock;
// Booster Pack Pins FR5969
// 7 - P2.2 for SPI_CLK mode
// 15 - P1.6 for SPI_SIMO mode
// 14 - P1.7 for SPI_SOMI mode
// 5 - P2.5 output pin for SPI_CS
// 18 - P3.0 nIRQ for sending data
// 3 - P2.6 as FSK input data
// Set display's VCC and DISP pins to high
static const uint8_t P_CS = 4;
static const uint8_t P_FSK = 3;
static const uint8_t P_NIRQ = 18;
// empty constructor
RFM02::RFM02() {
RFM02(P_CS, P_FSK, P_NIRQ);
}
// constructor with variables
RFM02::RFM02(uint8_t pinChipSelect, uint8_t pinFSK, uint8_t pinNIRQ)
{
_pinChipSelect = pinChipSelect;
_pinFSK = pinFSK;
_pinNIRQ = pinNIRQ;
}
void RFM02::begin() {
digitalWrite(_pinChipSelect, HIGH); // set chip select high
pinMode(_pinChipSelect, OUTPUT); // set chip select as output
digitalWrite(_pinFSK, LOW); // set FSK to low
pinMode(_pinFSK, OUTPUT); // set FSK pin as output
pinMode(P_NIRQ, INPUT); // set nIRQ pin as input
configureDeviceSettings(); // configure RFM01
pinMode(RED_LED, OUTPUT); // set red led as output
digitalWrite(RED_LED, HIGH); // blink red led 50 ms
// to indicate setup ready
delay(50);
digitalWrite(RED_LED, LOW);
}
void RFM02::writeRegister(uint8_t HighByte, uint8_t LowByte) {
digitalWrite(_pinChipSelect,LOW);
SPI.transfer(HighByte);
SPI.transfer(LowByte);
digitalWrite(_pinChipSelect,HIGH);
}
void RFM02::configureDeviceSettings() {
writeRegister(0xCC,0x00); // read status
writeRegister(0x93,0x82); // 868MHz Band +/- 90kHz Bandbreite
writeRegister(0xA6,0x86); // 868.35 MHz
writeRegister(0xD0,0x40); // RATE/2
writeRegister(0xC8,0x23); // 4.8kbps
writeRegister(0xC2,0x20); // Bit Sync active
writeRegister(0xC0,0x01); // disable TX
writeRegister(0xD2,0x40); // PLL 25%
writeRegister(0xB0,0x00); // -9 db
writeRegister(0xE0,0x00); // 'disable wakeup timer
}
// Data via FSK
/******************************************************************************/
/* Sending data via the FSK-Pin as Input-Pin */
/* */
/* After the PowerAmplifier has turned on ( ea=1 ) from rfm02-module */
/* comes a clock corresponding to the data-rate set before on nIRQ. */
/* The data to be transmitted is bitwise set on the FSK-Pin of the */
/* module, after the falling edge of nIRQ. With the following edge */
/* of nIRQ this bit is read in and sent out. */
/* nSEL must be high, SCK low, both all the time */
/* */
/* */
/* TESTED: 28.09.2014 with Deviation +/- 90kHz and 435.000 MHz */
/* up to 115.000BPS */
/* */
/* Support & Copyright: [email protected] */
/******************************************************************************/
void RFM02::RFM02_TX_DataByte_FSK(uint8_t DataByte){
uint8_t i=8;
// PowerAmplifier is here already enabled, impulses on nIRQ corresponding to the
// set data-rate, nSEL is high, SCK is low
digitalWrite(_pinChipSelect,HIGH);
while(i){ // do 8 times..., (any number of bit's will do, also 9 or 121)
i=i-1;
while(!(digitalRead(_pinNIRQ))); // wait for the 0-1-edge of nIRQ, reading in the data
while((digitalRead(_pinNIRQ))); // wait for 1-0-edge to send the last bit
if( DataByte & BIT7 ) // if not '0' write over with '1'
digitalWrite(_pinFSK, HIGH); // ...write '1' if most significant bit is '1'
else
digitalWrite(_pinFSK, LOW); //OUT_PORT_REG &= ~FSK; // first set Bitx as '0'
DataByte <<= 1; // shift DataByte one bit left to write the next bit
}
}
void RFM02::sendMessage(uint8_t *txData, uint8_t size)
{
//digitalWrite(_pinChipSelect, LOW); // CS LOW
writeRegister(0xC0,0x39); // enable TX
//digitalWrite(_pinChipSelect, HIGH); // CS HIGH
//delay(1000);
RFM02_TX_DataByte_FSK(0xAA); // preamble
RFM02_TX_DataByte_FSK(0xAA); // preamble
RFM02_TX_DataByte_FSK(0xAA); // preamble
RFM02_TX_DataByte_FSK(0x2D); // sync word high
RFM02_TX_DataByte_FSK(0xD4); // sync word low
for(int myLoop=0;myLoop<MESSAGELENGTH;myLoop++)
{
RFM02_TX_DataByte_FSK(txData[myLoop]); // sync word lowtxData[myLoop] = myLoop;
}
/*
RFM02_TX_DataByte_FSK('H'); // data
RFM02_TX_DataByte_FSK('E'); // data
RFM02_TX_DataByte_FSK('L'); // data
RFM02_TX_DataByte_FSK('L'); // data
RFM02_TX_DataByte_FSK('O'); // data
RFM02_TX_DataByte_FSK(1); // data
RFM02_TX_DataByte_FSK(2); // data
RFM02_TX_DataByte_FSK(3); // data
RFM02_TX_DataByte_FSK(4); // data
RFM02_TX_DataByte_FSK(0xA5); // ende zeichen
*/
delay(1); // delay until carrier turn off
//digitalWrite(_pinChipSelect, LOW); // CS LOW
writeRegister(0xC0,0x01); // disable TX
//digitalWrite(_pinChipSelect, HIGH); // CS HIGH
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <vector>
#include <random>
#include <numeric>
#include <fstream>
#include <iomanip>
#include <iterator>
#include <iostream>
#include <iterator>
#include <algorithm>
#include "caf/all.hpp"
#if defined __APPLE__ || defined(MACOSX)
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
using namespace std;
using namespace caf;
namespace {
constexpr const char* kernel_name = "kernel_wah_index";
constexpr const char* kernel_file = "kernel_wah_bitindex.cl";
class config : public actor_system_config {
public:
string filename = "";
uint32_t bound = 0;
string device_name = "GeForce GT 650M";
uint32_t batch_size = 1023;
uint32_t jobs = 1;
uint32_t work_groups = 1;
bool print_results;
config() {
opt_group{custom_options_, "global"}
.add(filename, "data-file,f", "file with test data (one value per line)")
.add(bound, "bound,b", "maximum value (0 will scan values)")
.add(device_name, "device,d", "device for computation (GeForce GTX 780M)")
.add(batch_size, "batch-size,b", "values indexed in one batch (1023)")
.add(print_results, "print,p", "print resulting bitmap index")
.add(work_groups, "work-groups,w", "Use work-groups")
.add(jobs, "jobs,j", "jobs sent to GPU (1)");
}
};
void eval_err(cl_int err, string msg = "") {
if (err != CL_SUCCESS)
cout << "[!!!] " << msg << err << endl;
else
cout << "DONE" << endl;
}
} // namespace <anonymous>
void caf_main(actor_system&, const config& cfg) {
vector<uint32_t> values;
if (cfg.filename.empty()) {
values = {10, 7, 22, 6, 7, 1, 9, 42, 2, 5,
13, 3, 2, 1, 0, 1, 18, 18, 3, 13,
5, 9, 0, 3, 2, 19, 5, 23, 22, 10,
6, 22};
} else {
cout << "Reading data from '" << cfg.filename << "' ... " << flush;
ifstream source{cfg.filename, std::ios::in};
uint32_t next;
while (source >> next) {
values.push_back(next);
}
}
cout << "'" << values.size() << "' values." << endl;
auto bound = cfg.bound;
if (bound == 0 && !values.empty()) {
auto itr = max_element(values.begin(), values.end());
bound = *itr;
}
cout << "Maximum value is '" << bound << "'." << endl;
// read cl kernel file
auto filename = string("./include/") + kernel_file;
cout << "Reading source from '" << filename << "' ... " << flush;
ifstream read_source{filename, std::ios::in};
string source_contents;
if (read_source) {
read_source.seekg(0, std::ios::end);
source_contents.resize(read_source.tellg());
read_source.seekg(0, std::ios::beg);
read_source.read(&source_contents[0], source_contents.size());
read_source.close();
} else {
cout << strerror(errno) << "[!!!] " << endl;
return;
}
cout << "DONE" << endl;
// #### OLD PROGRAM ####
cl_int err{0};
// find up to two available platforms
cout << "Getting platform id(s) ..." << flush;
uint32_t num_platforms;
err = clGetPlatformIDs(0, nullptr, &num_platforms);
vector<cl_platform_id> platform_ids(num_platforms);
err = clGetPlatformIDs(platform_ids.size(), platform_ids.data(),
&num_platforms);
eval_err(err);
// find gpu devices on our platform
int platform_used = 0;
uint32_t num_gpu_devices = 0;
err = clGetDeviceIDs(platform_ids[platform_used], CL_DEVICE_TYPE_GPU, 0,
nullptr, &num_gpu_devices);
if (err != CL_SUCCESS) {
cout << "[!!!] Error getting number of gpu devices for platform '"
<< platform_ids[platform_used] << "'." << endl;
return;
}
vector<cl_device_id> gpu_devices(num_gpu_devices);
err = clGetDeviceIDs(platform_ids[platform_used], CL_DEVICE_TYPE_GPU,
num_gpu_devices, gpu_devices.data(), nullptr);
if (err != CL_SUCCESS) {
cout << "[!!!] Error getting CL_DEVICE_TYPE_GPU for platform '"
<< platform_ids[platform_used] << "'." << endl;
return;
}
// choose device
int device_used{0};
bool found = false;
if (!cfg.device_name.empty()) {
for (uint32_t i = 0; i < num_gpu_devices; ++i) {
size_t return_size;
err = clGetDeviceInfo(gpu_devices[i], CL_DEVICE_NAME, 0, nullptr,
&return_size);
vector<char> name(return_size);
err = clGetDeviceInfo(gpu_devices[i], CL_DEVICE_NAME, return_size,
name.data(), &return_size);
string as_string(name.data());
if (as_string == cfg.device_name) {
cout << "Using '" << as_string << "'" << endl;
device_used = i;
found = true;
break;
}
}
if (!found) {
cout << "Device " << cfg.device_name << " not found." << endl;
return;
}
} else {
size_t return_size;
err = clGetDeviceInfo(gpu_devices[device_used], CL_DEVICE_NAME, 0, nullptr,
&return_size);
vector<char> name(return_size);
err = clGetDeviceInfo(gpu_devices[device_used], CL_DEVICE_NAME, return_size,
name.data(), &return_size);
cout << "Using '" << string(name.data()) << "'" << endl;
}
cl_device_id device_id_used = gpu_devices[device_used];
size_t max_work_group_size;
err = clGetDeviceInfo(device_id_used, CL_DEVICE_MAX_WORK_GROUP_SIZE,
sizeof(size_t), &max_work_group_size, NULL);
// create a context
auto pfn_notify = [](const char *errinfo, const void *, size_t, void *) {
std::cerr << "\n##### Error message via pfn_notify #####\n"
<< string(errinfo)
<< "\n########################################";
};
cout << "Creating context ... " << flush;
cl_context context = clCreateContext(0, 1, &device_id_used, pfn_notify,
nullptr, &err);
eval_err(err);
// create a command queue
cout << "Creating command queue ... " << flush;
cl_command_queue cmd_queue = clCreateCommandQueue(context, device_id_used,
CL_QUEUE_PROFILING_ENABLE,
&err);
eval_err(err);
// create program object from kernel source
cout << "Creating program object from source ... " << flush;
const char* strings = source_contents.c_str();
size_t lengths = source_contents.size();
cl_program program = clCreateProgramWithSource(context, 1, &strings,
&lengths, &err);
eval_err(err);
// build programm from program object
cout << "Building program from program object ... " << flush;
err = clBuildProgram(program, 0, nullptr, "", nullptr,
nullptr);
eval_err(err);
// create kernel
cout << "Creating kernel object ... " << flush;
cl_kernel kernel = clCreateKernel(program, kernel_name, &err);
eval_err(err);
auto batch_size = min(cfg.batch_size, static_cast<uint32_t>(values.size()));
auto wg_size = min(batch_size, static_cast<uint32_t>(max_work_group_size));
auto wg_num = cfg.work_groups;
auto gl_size = wg_size * wg_num; // must be multiple of wg_size
auto processed = 0;
auto remaining = static_cast<uint32_t>(values.size());
auto in_out_flags = CL_MEM_READ_WRITE;
auto out_flags = CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY;
auto buf_flags = CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS;
auto blocking = CL_FALSE;
while (remaining > 0) {
auto arg_size = min(remaining, wg_num * wg_size);
auto arg_bytes = arg_size * sizeof(uint32_t);
vector<uint32_t> input{
make_move_iterator(begin(values) + processed),
make_move_iterator(begin(values) + processed + arg_size)
};
processed += arg_size;
remaining -= arg_size;
auto full = arg_size / wg_size;
auto partial = arg_size - (full * wg_size);
vector<uint32_t> config(2 + (full * 2));
config[0] = arg_size;
config[1] = full;
for (uint32_t i = 0; i < full; ++i) {
config[2 * i + 2] = wg_size;
config[2 * i + 3] = wg_size * 2;
}
if (partial > 0) {
config[1] += 1;
config.emplace_back(partial);
config.emplace_back(partial * 2);
}
auto cfg_bytes = config.size() * sizeof(uint32_t);
cout << "Config for " << arg_size << " values:" << endl;
for (size_t i = 0; i < config.size(); ++i)
cout << "> config[" << i << "]: " << config[i] << endl;
vector<cl_event> eq_events;
// create input buffers
cout << "Creating buffer 'config' ... " << flush;
cl_mem buf_config = clCreateBuffer(context, in_out_flags, cfg_bytes,
nullptr, &err);
eval_err(err);
cout << "Creating buffer 'input' ... " << flush;
cl_mem buf_input = clCreateBuffer(context, in_out_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cout << "Creating buffer 'index' ... " << flush;
cl_mem buf_index = clCreateBuffer(context, out_flags, arg_bytes * 2,
nullptr, &err);
eval_err(err);
cout << "Creating buffer 'offsets' ... " << flush;
cl_mem buf_offsets = clCreateBuffer(context, out_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cout << "Creating buffer 'rids' ... " << flush;
cl_mem buf_rids = clCreateBuffer(context, buf_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cout << "Creating buffer 'chids' ... " << flush;
cl_mem buf_chids = clCreateBuffer(context, buf_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cout << "Creating buffer 'lits' ... " << flush;
cl_mem buf_lits = clCreateBuffer(context, buf_flags, arg_bytes,
nullptr, &err);
eval_err(err);
// copy data to GPU
cl_event config_cpy;
cout << "Writing 'config' ... " << flush;
err = clEnqueueWriteBuffer(cmd_queue, buf_config, blocking, 0,
cfg_bytes, config.data(), 0,
nullptr, &config_cpy);
eval_err(err);
eq_events.push_back(config_cpy);
cl_event input_copy;
cout << "Writing 'input' ... " << flush;
err = clEnqueueWriteBuffer(cmd_queue, buf_input, blocking, 0,
arg_bytes, input.data(), 0,
nullptr, &input_copy);
eval_err(err);
eq_events.push_back(input_copy);
// set arguments
cout << "Setting kernel argument 0 ... " << flush;
err = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void*) &buf_config);
eval_err(err);
cout << "Setting kernel argument 1 ... " << flush;
err = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*) &buf_input);
eval_err(err);
cout << "Setting kernel argument 2 ... " << flush;
err = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*) &buf_index);
eval_err(err);
cout << "Setting kernel argument 3 ... " << flush;
err = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void*) &buf_offsets);
eval_err(err);
cout << "Setting kernel argument 4 ... " << flush;
err = clSetKernelArg(kernel, 4, sizeof(cl_mem), (void*) &buf_rids);
eval_err(err);
cout << "Setting kernel argument 5 ... " << flush;
err = clSetKernelArg(kernel, 5, sizeof(cl_mem), (void*) &buf_chids);
eval_err(err);
cout << "Setting kernel argument 6 ... " << flush;
err = clSetKernelArg(kernel, 6, sizeof(cl_mem), (void*) &buf_lits);
eval_err(err);
// enqueue kernel
cout << "Enqueueing kernel to command queue ... " << flush;
vector<size_t> global_work{gl_size};
vector<size_t> local_work{wg_size};
cl_event kernel_exec;
err = clEnqueueNDRangeKernel(cmd_queue, kernel, 1, nullptr,
global_work.data(), local_work.data(),
eq_events.size(), eq_events.data(),
&kernel_exec);
eval_err(err);
// get results from gpu
vector<uint32_t> keys(arg_size);
vector<uint32_t> index(arg_size * 2);
vector<uint32_t> offsets(arg_size);
cout << "Reading 'config' ... " << flush;
err = clEnqueueReadBuffer(cmd_queue, buf_config, blocking, 0,
cfg_bytes, config.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
cout << "Reading 'keys' ... " << flush;
err = clEnqueueReadBuffer(cmd_queue, buf_input, blocking, 0,
arg_bytes, keys.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
cout << "Reading 'index' ... " << flush;
err = clEnqueueReadBuffer(cmd_queue, buf_index, blocking, 0,
arg_bytes * 2, index.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
cout << "Reading 'offsets' ... " << flush;
err = clEnqueueReadBuffer(cmd_queue, buf_offsets, blocking, 0,
arg_bytes, offsets.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
clFinish(cmd_queue);
for (auto& ev : eq_events)
clReleaseEvent(ev);
clReleaseEvent(kernel_exec);
clReleaseMemObject(buf_config);
clReleaseMemObject(buf_input);
clReleaseMemObject(buf_index);
clReleaseMemObject(buf_offsets);
clReleaseMemObject(buf_rids);
clReleaseMemObject(buf_chids);
clReleaseMemObject(buf_lits);
}
// clean up
cout << "Releasing memory ... " << flush;
clReleaseKernel(kernel);
clReleaseProgram(program);
clReleaseCommandQueue(cmd_queue);
clReleaseContext(context);
cout << "DONE" << endl;
}
CAF_MAIN()
<commit_msg>Slim down output of plain opencl program<commit_after>#include <cmath>
#include <vector>
#include <chrono>
#include <random>
#include <numeric>
#include <fstream>
#include <iomanip>
#include <iterator>
#include <iostream>
#include <iterator>
#include <algorithm>
#include "caf/all.hpp"
#if defined __APPLE__ || defined(MACOSX)
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
using namespace std;
using namespace caf;
namespace {
constexpr const char* kernel_name = "kernel_wah_index";
constexpr const char* kernel_file = "kernel_wah_bitindex.cl";
class config : public actor_system_config {
public:
string filename = "";
uint32_t bound = 0;
string device_name = "GeForce GT 650M";
uint32_t batch_size = 1023;
uint32_t jobs = 1;
uint32_t work_groups = 1;
bool print_results;
config() {
opt_group{custom_options_, "global"}
.add(filename, "data-file,f", "file with test data (one value per line)")
.add(bound, "bound,b", "maximum value (0 will scan values)")
.add(device_name, "device,d", "device for computation (GeForce GTX 780M)")
.add(batch_size, "batch-size,b", "values indexed in one batch (1023)")
.add(print_results, "print,p", "print resulting bitmap index")
.add(work_groups, "work-groups,w", "Use work-groups")
.add(jobs, "jobs,j", "jobs sent to GPU (1)");
}
};
void eval_err(cl_int err, string msg = "") {
if (err != CL_SUCCESS) {
cout << "[!!!] " << msg << err << endl;
exit(err);
}
}
} // namespace <anonymous>
void caf_main(actor_system&, const config& cfg) {
vector<uint32_t> values;
if (cfg.filename.empty()) {
values = {10, 7, 22, 6, 7, 1, 9, 42, 2, 5,
13, 3, 2, 1, 0, 1, 18, 18, 3, 13,
5, 9, 0, 3, 2, 19, 5, 23, 22, 10,
6, 22};
} else {
ifstream source{cfg.filename, std::ios::in};
uint32_t next;
while (source >> next) {
values.push_back(next);
}
}
auto bound = cfg.bound;
if (bound == 0 && !values.empty()) {
auto itr = max_element(values.begin(), values.end());
bound = *itr;
}
// read cl kernel file
auto filename = string("./include/") + kernel_file;
ifstream read_source{filename, std::ios::in};
string source_contents;
if (read_source) {
read_source.seekg(0, std::ios::end);
source_contents.resize(read_source.tellg());
read_source.seekg(0, std::ios::beg);
read_source.read(&source_contents[0], source_contents.size());
read_source.close();
} else {
cout << strerror(errno) << "[!!!] " << endl;
return;
}
cl_int err{0};
// find up to two available platforms
uint32_t num_platforms;
err = clGetPlatformIDs(0, nullptr, &num_platforms);
vector<cl_platform_id> platform_ids(num_platforms);
err = clGetPlatformIDs(platform_ids.size(), platform_ids.data(),
&num_platforms);
eval_err(err);
// find gpu devices on our platform
int platform_used = 0;
uint32_t num_gpu_devices = 0;
err = clGetDeviceIDs(platform_ids[platform_used], CL_DEVICE_TYPE_GPU, 0,
nullptr, &num_gpu_devices);
eval_err(err);
vector<cl_device_id> gpu_devices(num_gpu_devices);
err = clGetDeviceIDs(platform_ids[platform_used], CL_DEVICE_TYPE_GPU,
num_gpu_devices, gpu_devices.data(), nullptr);
eval_err(err);
// choose device
int device_used{0};
bool found = false;
if (!cfg.device_name.empty()) {
for (uint32_t i = 0; i < num_gpu_devices; ++i) {
size_t return_size;
err = clGetDeviceInfo(gpu_devices[i], CL_DEVICE_NAME, 0, nullptr,
&return_size);
vector<char> name(return_size);
err = clGetDeviceInfo(gpu_devices[i], CL_DEVICE_NAME, return_size,
name.data(), &return_size);
string as_string(name.data());
if (as_string == cfg.device_name) {
device_used = i;
found = true;
break;
}
}
if (!found) {
cout << "Device " << cfg.device_name << " not found." << endl;
return;
}
} else {
size_t return_size;
err = clGetDeviceInfo(gpu_devices[device_used], CL_DEVICE_NAME, 0, nullptr,
&return_size);
vector<char> name(return_size);
err = clGetDeviceInfo(gpu_devices[device_used], CL_DEVICE_NAME, return_size,
name.data(), &return_size);
cout << "Using '" << string(name.data()) << "'" << endl;
}
cl_device_id device_id_used = gpu_devices[device_used];
size_t max_work_group_size;
err = clGetDeviceInfo(device_id_used, CL_DEVICE_MAX_WORK_GROUP_SIZE,
sizeof(size_t), &max_work_group_size, NULL);
// create a context
auto pfn_notify = [](const char *errinfo, const void *, size_t, void *) {
std::cerr << "\n##### Error message via pfn_notify #####\n"
<< string(errinfo)
<< "\n########################################";
};
cl_context context = clCreateContext(0, 1, &device_id_used, pfn_notify,
nullptr, &err);
eval_err(err);
// create a command queue
cl_command_queue cmd_queue = clCreateCommandQueue(context, device_id_used,
CL_QUEUE_PROFILING_ENABLE,
&err);
eval_err(err);
// create program object from kernel source
const char* strings = source_contents.c_str();
size_t lengths = source_contents.size();
cl_program program = clCreateProgramWithSource(context, 1, &strings,
&lengths, &err);
eval_err(err);
// build programm from program object
err = clBuildProgram(program, 0, nullptr, "", nullptr,
nullptr);
eval_err(err);
// create kernel
cl_kernel kernel = clCreateKernel(program, kernel_name, &err);
eval_err(err);
auto batch_size = min(cfg.batch_size, static_cast<uint32_t>(values.size()));
auto wg_size = min(batch_size, static_cast<uint32_t>(max_work_group_size));
auto wg_num = cfg.work_groups;
auto gl_size = wg_size * wg_num; // must be multiple of wg_size
auto processed = 0;
auto remaining = static_cast<uint32_t>(values.size());
auto in_out_flags = CL_MEM_READ_WRITE;
auto out_flags = CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY;
auto buf_flags = CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS;
auto blocking = CL_FALSE;
auto start = chrono::high_resolution_clock::now();
while (remaining > 0) {
auto arg_size = min(remaining, wg_num * wg_size);
auto arg_bytes = arg_size * sizeof(uint32_t);
vector<uint32_t> input{
begin(values) + processed,
begin(values) + processed + arg_size
//make_move_iterator(begin(values) + processed),
//make_move_iterator(begin(values) + processed + arg_size)
};
processed += arg_size;
remaining -= arg_size;
auto full = arg_size / wg_size;
auto partial = arg_size - (full * wg_size);
vector<uint32_t> config(2 + (full * 2));
config[0] = arg_size;
config[1] = full;
for (uint32_t i = 0; i < full; ++i) {
config[2 * i + 2] = wg_size;
config[2 * i + 3] = wg_size * 2;
}
if (partial > 0) {
config[1] += 1;
config.emplace_back(partial);
config.emplace_back(partial * 2);
}
auto cfg_bytes = config.size() * sizeof(uint32_t);
vector<cl_event> eq_events;
// create input buffers
cl_mem buf_config = clCreateBuffer(context, in_out_flags, cfg_bytes,
nullptr, &err);
eval_err(err);
cl_mem buf_input = clCreateBuffer(context, in_out_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cl_mem buf_index = clCreateBuffer(context, out_flags, arg_bytes * 2,
nullptr, &err);
eval_err(err);
cl_mem buf_offsets = clCreateBuffer(context, out_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cl_mem buf_rids = clCreateBuffer(context, buf_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cl_mem buf_chids = clCreateBuffer(context, buf_flags, arg_bytes,
nullptr, &err);
eval_err(err);
cl_mem buf_lits = clCreateBuffer(context, buf_flags, arg_bytes,
nullptr, &err);
eval_err(err);
// copy data to GPU
cl_event config_cpy;
err = clEnqueueWriteBuffer(cmd_queue, buf_config, blocking, 0,
cfg_bytes, config.data(), 0,
nullptr, &config_cpy);
eval_err(err);
eq_events.push_back(config_cpy);
cl_event input_copy;
err = clEnqueueWriteBuffer(cmd_queue, buf_input, blocking, 0,
arg_bytes, input.data(), 0,
nullptr, &input_copy);
eval_err(err);
eq_events.push_back(input_copy);
// set arguments
err = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void*) &buf_config);
eval_err(err);
err = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*) &buf_input);
eval_err(err);
err = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*) &buf_index);
eval_err(err);
err = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void*) &buf_offsets);
eval_err(err);
err = clSetKernelArg(kernel, 4, sizeof(cl_mem), (void*) &buf_rids);
eval_err(err);
err = clSetKernelArg(kernel, 5, sizeof(cl_mem), (void*) &buf_chids);
eval_err(err);
err = clSetKernelArg(kernel, 6, sizeof(cl_mem), (void*) &buf_lits);
eval_err(err);
// enqueue kernel
vector<size_t> global_work{gl_size};
vector<size_t> local_work{wg_size};
cl_event kernel_exec;
err = clEnqueueNDRangeKernel(cmd_queue, kernel, 1, nullptr,
global_work.data(), local_work.data(),
eq_events.size(), eq_events.data(),
&kernel_exec);
eval_err(err);
// get results from gpu
vector<uint32_t> keys(arg_size);
vector<uint32_t> index(arg_size * 2);
vector<uint32_t> offsets(arg_size);
err = clEnqueueReadBuffer(cmd_queue, buf_config, blocking, 0,
cfg_bytes, config.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
err = clEnqueueReadBuffer(cmd_queue, buf_input, blocking, 0,
arg_bytes, keys.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
err = clEnqueueReadBuffer(cmd_queue, buf_index, blocking, 0,
arg_bytes * 2, index.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
err = clEnqueueReadBuffer(cmd_queue, buf_offsets, blocking, 0,
arg_bytes, offsets.data(), 1,
&kernel_exec, nullptr);
eval_err(err);
clFinish(cmd_queue);
for (auto& ev : eq_events)
clReleaseEvent(ev);
clReleaseEvent(kernel_exec);
clReleaseMemObject(buf_config);
clReleaseMemObject(buf_input);
clReleaseMemObject(buf_index);
clReleaseMemObject(buf_offsets);
clReleaseMemObject(buf_rids);
clReleaseMemObject(buf_chids);
clReleaseMemObject(buf_lits);
}
auto stop = chrono::high_resolution_clock::now();
// clean up
clReleaseKernel(kernel);
clReleaseProgram(program);
clReleaseCommandQueue(cmd_queue);
clReleaseContext(context);
cout << "Time: '"
<< chrono::duration_cast<chrono::milliseconds>(stop - start).count()
<< "' ms" << endl;
}
CAF_MAIN()
<|endoftext|> |
<commit_before>/**
* po n c i
* poor mans cgroups interface
*
* Copyright 2016 by LRR-TUM
* Jens Breitbart <[email protected]>
*
* Licensed under GNU Lesser General Public License 2.1 or later.
* Some rights reserved. See LICENSE
*/
#include "ponci/ponci.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <errno.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
// default mount path
static std::string path_prefix("/sys/fs/cgroup/");
// TODO function to change prefix?
/////////////////////////////////////////////////////////////////
// PROTOTYPES
/////////////////////////////////////////////////////////////////
static inline std::string cgroup_path(const char *name);
template <typename T> static inline void write_vector_to_file(const std::string &filename, const std::vector<T> &vec);
template <typename T> static inline void write_array_to_file(const std::string &filename, T *arr, size_t size);
template <typename T> static inline void write_value_to_file(const std::string &filename, T val);
template <> inline void write_value_to_file<const char *>(const std::string &filename, const char *val);
template <typename T> static inline void append_value_to_file(const std::string &filename, T val);
static inline std::string read_line_from_file(const std::string &filename);
template <typename T> static inline std::vector<T> read_lines_from_file(const std::string &filename);
template <typename T> static inline T string_to_T(const std::string &s, std::size_t &done);
// template <> inline unsigned long string_to_T<unsigned long>(const std::string &s, std::size_t &done);
template <> inline int string_to_T<int>(const std::string &s, std::size_t &done);
static std::vector<int> get_tids_from_pid(const int pid);
/////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS
/////////////////////////////////////////////////////////////////
void cgroup_create(const char *name) {
const int err = mkdir(cgroup_path(name).c_str(), S_IRWXU | S_IRWXG);
if (err != 0 && errno != EEXIST) throw std::runtime_error(strerror(errno));
errno = 0;
}
void cgroup_delete(const char *name) {
const int err = rmdir(cgroup_path(name).c_str());
if (err != 0) throw std::runtime_error(strerror(errno));
}
void cgroup_add_me(const char *name) {
pid_t me = static_cast<pid_t>(syscall(SYS_gettid));
cgroup_add_task(name, me);
}
void cgroup_add_task(const char *name, const pid_t tid) {
std::string filename = cgroup_path(name) + std::string("tasks");
append_value_to_file(filename, tid);
}
void cgroup_set_cpus(const char *name, const size_t *cpus, size_t size) {
std::string filename = cgroup_path(name) + std::string("cpuset.cpus");
write_array_to_file(filename, cpus, size);
}
void cgroup_set_cpus(const std::string &name, const std::vector<unsigned char> &cpus) {
std::string filename = cgroup_path(name.c_str()) + std::string("cpuset.cpus");
write_vector_to_file(filename, cpus);
}
void cgroup_set_mems(const char *name, const size_t *mems, size_t size) {
std::string filename = cgroup_path(name) + std::string("cpuset.mems");
write_array_to_file(filename, mems, size);
}
void cgroup_set_mems(const std::string &name, const std::vector<unsigned char> &mems) {
std::string filename = cgroup_path(name.c_str()) + std::string("cpuset.mems");
write_vector_to_file(filename, mems);
}
void cgroup_set_memory_migrate(const char *name, size_t flag) {
assert(flag == 0 || flag == 1);
std::string filename = cgroup_path(name) + std::string("cpuset.memory_migrate");
write_value_to_file(filename, flag);
}
void cgroup_set_cpus_exclusive(const char *name, size_t flag) {
assert(flag == 0 || flag == 1);
std::string filename = cgroup_path(name) + std::string("cpuset.cpu_exclusive");
write_value_to_file(filename, flag);
}
void cgroup_set_mem_hardwall(const char *name, size_t flag) {
assert(flag == 0 || flag == 1);
std::string filename = cgroup_path(name) + std::string("cpuset.mem_hardwall");
write_value_to_file(filename, flag);
}
void cgroup_set_scheduling_domain(const char *name, int flag) {
assert(flag >= -1 && flag <= 5);
std::string filename = cgroup_path(name) + std::string("cpuset.sched_relax_domain_level");
write_value_to_file(filename, flag);
}
void cgroup_freeze(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
write_value_to_file(filename, "FROZEN");
}
void cgroup_thaw(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
write_value_to_file(filename, "THAWED");
}
void cgroup_wait_frozen(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
std::string temp;
while (temp != "FROZEN\n") {
temp = read_line_from_file(filename);
}
}
void cgroup_wait_thawed(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
std::string temp;
while (temp != "THAWED\n") {
temp = read_line_from_file(filename);
}
}
void cgroup_kill(const char *name) {
auto tids = get_tids_from_pid(getpid());
// get all pids
std::vector<int> pids = read_lines_from_file<int>(cgroup_path(name) + std::string("tasks"));
// send kill
for (__pid_t pid : pids) {
if (std::find(tids.begin(), tids.end(), pid) != tids.end()) {
// pid in tids
} else {
// pid not in tids
if (kill(pid, SIGTERM) != 0) {
throw std::runtime_error(strerror(errno));
}
}
}
// wait until tasks empty
while (pids.size() != 0) {
pids = read_lines_from_file<int>(cgroup_path(name) + std::string("tasks"));
}
cgroup_delete(name);
}
/////////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
/////////////////////////////////////////////////////////////////
static inline std::string cgroup_path(const char *name) {
std::string res(path_prefix);
if (strcmp(name, "") != 0) {
res.append(name);
res.append("/");
}
return res;
}
template <typename T> static inline void write_vector_to_file(const std::string &filename, const std::vector<T> &vec) {
write_array_to_file(filename, &vec[0], vec.size());
}
template <typename T> static inline void write_array_to_file(const std::string &filename, T *arr, size_t size) {
assert(size > 0);
assert(filename.compare("") != 0);
std::string str;
for (size_t i = 0; i < size; ++i) {
str.append(std::to_string(arr[i]));
str.append(",");
}
write_value_to_file(filename, str.c_str());
}
template <typename T> static inline void append_value_to_file(const std::string &filename, T val) {
assert(filename.compare("") != 0);
FILE *f = fopen(filename.c_str(), "a+");
if (f == nullptr) {
throw std::runtime_error(strerror(errno));
}
std::string str = std::to_string(val);
if (fputs(str.c_str(), f) == EOF && ferror(f) != 0) {
throw std::runtime_error(strerror(errno));
}
if (fclose(f) != 0) {
throw std::runtime_error(strerror(errno));
}
}
template <typename T> static inline void write_value_to_file(const std::string &filename, T val) {
write_value_to_file(filename, std::to_string(val).c_str());
}
template <> void write_value_to_file<const char *>(const std::string &filename, const char *val) {
assert(filename.compare("") != 0);
FILE *file = fopen(filename.c_str(), "w+");
if (file == nullptr) {
throw std::runtime_error(strerror(errno));
}
int status = fputs(val, file);
if (status <= 0 || ferror(file) != 0) {
throw std::runtime_error(strerror(errno));
}
if (fclose(file) != 0) {
throw std::runtime_error(strerror(errno));
}
}
static inline std::string read_line_from_file(const std::string &filename) {
assert(filename.compare("") != 0);
FILE *file = fopen(filename.c_str(), "r");
if (file == nullptr) {
throw std::runtime_error(strerror(errno));
}
char temp[255];
if (fgets(temp, 255, file) == nullptr && !feof(file)) {
throw std::runtime_error("Error while reading file in libponci. Buffer to small?");
}
if (feof(file)) return std::string();
if (fclose(file) != 0) {
throw std::runtime_error(strerror(errno));
}
return std::string(temp);
}
template <typename T> static inline std::vector<T> read_lines_from_file(const std::string &filename) {
assert(filename.compare("") != 0);
FILE *file = fopen(filename.c_str(), "r");
if (file == nullptr) {
throw std::runtime_error(strerror(errno));
}
std::vector<T> ret;
char temp[255];
while (true) {
if (fgets(temp, 255, file) == nullptr && !feof(file)) {
throw std::runtime_error("Error while reading file in libponci. Buffer to small?");
}
if (feof(file)) break;
std::size_t done = 0;
T i = string_to_T<T>(std::string(temp), done);
if (done != 0) ret.push_back(i);
}
if (fclose(file) != 0) {
throw std::runtime_error(strerror(errno));
}
return ret;
}
template <> int string_to_T<int>(const std::string &s, std::size_t &done) { return stoi(s, &done); }
#if 0
template <> unsigned long string_to_T<unsigned long>(const std::string &s, std::size_t &done) {
return stoul(s, &done);
}
#endif
static std::vector<int> get_tids_from_pid(const int pid) {
std::string path("/proc/" + std::to_string(pid) + "/task/");
dirent *dent;
DIR *srcdir = opendir(path.c_str());
if (srcdir == nullptr) {
throw std::runtime_error(strerror(errno));
}
std::vector<int> ret;
while ((dent = readdir(srcdir)) != nullptr) {
struct stat st;
if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue;
if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0) {
continue;
}
if (S_ISDIR(st.st_mode)) {
std::size_t i;
ret.push_back(string_to_T<int>(std::string(dent->d_name), i));
}
}
closedir(srcdir);
return ret;
}
<commit_msg>Added support for PONCI_PATH env variable.<commit_after>/**
* po n c i
* poor mans cgroups interface
*
* Copyright 2016 by LRR-TUM
* Jens Breitbart <[email protected]>
*
* Licensed under GNU Lesser General Public License 2.1 or later.
* Some rights reserved. See LICENSE
*/
#include "ponci/ponci.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <errno.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
// default mount path
static std::string path_prefix("/sys/fs/cgroup/");
/////////////////////////////////////////////////////////////////
// PROTOTYPES
/////////////////////////////////////////////////////////////////
static inline std::string cgroup_path(const char *name);
template <typename T> static inline void write_vector_to_file(const std::string &filename, const std::vector<T> &vec);
template <typename T> static inline void write_array_to_file(const std::string &filename, T *arr, size_t size);
template <typename T> static inline void write_value_to_file(const std::string &filename, T val);
template <> inline void write_value_to_file<const char *>(const std::string &filename, const char *val);
template <typename T> static inline void append_value_to_file(const std::string &filename, T val);
static inline std::string read_line_from_file(const std::string &filename);
template <typename T> static inline std::vector<T> read_lines_from_file(const std::string &filename);
template <typename T> static inline T string_to_T(const std::string &s, std::size_t &done);
// template <> inline unsigned long string_to_T<unsigned long>(const std::string &s, std::size_t &done);
template <> inline int string_to_T<int>(const std::string &s, std::size_t &done);
static std::vector<int> get_tids_from_pid(const int pid);
/////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS
/////////////////////////////////////////////////////////////////
void cgroup_create(const char *name) {
const int err = mkdir(cgroup_path(name).c_str(), S_IRWXU | S_IRWXG);
if (err != 0 && errno != EEXIST) throw std::runtime_error(strerror(errno));
errno = 0;
}
void cgroup_delete(const char *name) {
const int err = rmdir(cgroup_path(name).c_str());
if (err != 0) throw std::runtime_error(strerror(errno));
}
void cgroup_add_me(const char *name) {
pid_t me = static_cast<pid_t>(syscall(SYS_gettid));
cgroup_add_task(name, me);
}
void cgroup_add_task(const char *name, const pid_t tid) {
std::string filename = cgroup_path(name) + std::string("tasks");
append_value_to_file(filename, tid);
}
void cgroup_set_cpus(const char *name, const size_t *cpus, size_t size) {
std::string filename = cgroup_path(name) + std::string("cpuset.cpus");
write_array_to_file(filename, cpus, size);
}
void cgroup_set_cpus(const std::string &name, const std::vector<unsigned char> &cpus) {
std::string filename = cgroup_path(name.c_str()) + std::string("cpuset.cpus");
write_vector_to_file(filename, cpus);
}
void cgroup_set_mems(const char *name, const size_t *mems, size_t size) {
std::string filename = cgroup_path(name) + std::string("cpuset.mems");
write_array_to_file(filename, mems, size);
}
void cgroup_set_mems(const std::string &name, const std::vector<unsigned char> &mems) {
std::string filename = cgroup_path(name.c_str()) + std::string("cpuset.mems");
write_vector_to_file(filename, mems);
}
void cgroup_set_memory_migrate(const char *name, size_t flag) {
assert(flag == 0 || flag == 1);
std::string filename = cgroup_path(name) + std::string("cpuset.memory_migrate");
write_value_to_file(filename, flag);
}
void cgroup_set_cpus_exclusive(const char *name, size_t flag) {
assert(flag == 0 || flag == 1);
std::string filename = cgroup_path(name) + std::string("cpuset.cpu_exclusive");
write_value_to_file(filename, flag);
}
void cgroup_set_mem_hardwall(const char *name, size_t flag) {
assert(flag == 0 || flag == 1);
std::string filename = cgroup_path(name) + std::string("cpuset.mem_hardwall");
write_value_to_file(filename, flag);
}
void cgroup_set_scheduling_domain(const char *name, int flag) {
assert(flag >= -1 && flag <= 5);
std::string filename = cgroup_path(name) + std::string("cpuset.sched_relax_domain_level");
write_value_to_file(filename, flag);
}
void cgroup_freeze(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
write_value_to_file(filename, "FROZEN");
}
void cgroup_thaw(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
write_value_to_file(filename, "THAWED");
}
void cgroup_wait_frozen(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
std::string temp;
while (temp != "FROZEN\n") {
temp = read_line_from_file(filename);
}
}
void cgroup_wait_thawed(const char *name) {
assert(strcmp(name, "") != 0);
std::string filename = cgroup_path(name) + std::string("freezer.state");
std::string temp;
while (temp != "THAWED\n") {
temp = read_line_from_file(filename);
}
}
void cgroup_kill(const char *name) {
auto tids = get_tids_from_pid(getpid());
// get all pids
std::vector<int> pids = read_lines_from_file<int>(cgroup_path(name) + std::string("tasks"));
// send kill
for (__pid_t pid : pids) {
if (std::find(tids.begin(), tids.end(), pid) != tids.end()) {
// pid in tids
} else {
// pid not in tids
if (kill(pid, SIGTERM) != 0) {
throw std::runtime_error(strerror(errno));
}
}
}
// wait until tasks empty
while (pids.size() != 0) {
pids = read_lines_from_file<int>(cgroup_path(name) + std::string("tasks"));
}
cgroup_delete(name);
}
/////////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
/////////////////////////////////////////////////////////////////
static inline std::string cgroup_path(const char *name) {
const char *env = std::getenv("PONCI_PATH");
if (env != nullptr) {
path_prefix = std::string(env);
}
std::string res(path_prefix);
if (strcmp(name, "") != 0) {
res.append(name);
res.append("/");
}
return res;
}
template <typename T> static inline void write_vector_to_file(const std::string &filename, const std::vector<T> &vec) {
write_array_to_file(filename, &vec[0], vec.size());
}
template <typename T> static inline void write_array_to_file(const std::string &filename, T *arr, size_t size) {
assert(size > 0);
assert(filename.compare("") != 0);
std::string str;
for (size_t i = 0; i < size; ++i) {
str.append(std::to_string(arr[i]));
str.append(",");
}
write_value_to_file(filename, str.c_str());
}
template <typename T> static inline void append_value_to_file(const std::string &filename, T val) {
assert(filename.compare("") != 0);
FILE *f = fopen(filename.c_str(), "a+");
if (f == nullptr) {
throw std::runtime_error(strerror(errno));
}
std::string str = std::to_string(val);
if (fputs(str.c_str(), f) == EOF && ferror(f) != 0) {
throw std::runtime_error(strerror(errno));
}
if (fclose(f) != 0) {
throw std::runtime_error(strerror(errno));
}
}
template <typename T> static inline void write_value_to_file(const std::string &filename, T val) {
write_value_to_file(filename, std::to_string(val).c_str());
}
template <> void write_value_to_file<const char *>(const std::string &filename, const char *val) {
assert(filename.compare("") != 0);
FILE *file = fopen(filename.c_str(), "w+");
if (file == nullptr) {
throw std::runtime_error(strerror(errno));
}
int status = fputs(val, file);
if (status <= 0 || ferror(file) != 0) {
throw std::runtime_error(strerror(errno));
}
if (fclose(file) != 0) {
throw std::runtime_error(strerror(errno));
}
}
static inline std::string read_line_from_file(const std::string &filename) {
assert(filename.compare("") != 0);
FILE *file = fopen(filename.c_str(), "r");
if (file == nullptr) {
throw std::runtime_error(strerror(errno));
}
char temp[255];
if (fgets(temp, 255, file) == nullptr && !feof(file)) {
throw std::runtime_error("Error while reading file in libponci. Buffer to small?");
}
if (feof(file)) return std::string();
if (fclose(file) != 0) {
throw std::runtime_error(strerror(errno));
}
return std::string(temp);
}
template <typename T> static inline std::vector<T> read_lines_from_file(const std::string &filename) {
assert(filename.compare("") != 0);
FILE *file = fopen(filename.c_str(), "r");
if (file == nullptr) {
throw std::runtime_error(strerror(errno));
}
std::vector<T> ret;
char temp[255];
while (true) {
if (fgets(temp, 255, file) == nullptr && !feof(file)) {
throw std::runtime_error("Error while reading file in libponci. Buffer to small?");
}
if (feof(file)) break;
std::size_t done = 0;
T i = string_to_T<T>(std::string(temp), done);
if (done != 0) ret.push_back(i);
}
if (fclose(file) != 0) {
throw std::runtime_error(strerror(errno));
}
return ret;
}
template <> int string_to_T<int>(const std::string &s, std::size_t &done) { return stoi(s, &done); }
#if 0
template <> unsigned long string_to_T<unsigned long>(const std::string &s, std::size_t &done) {
return stoul(s, &done);
}
#endif
static std::vector<int> get_tids_from_pid(const int pid) {
std::string path("/proc/" + std::to_string(pid) + "/task/");
dirent *dent;
DIR *srcdir = opendir(path.c_str());
if (srcdir == nullptr) {
throw std::runtime_error(strerror(errno));
}
std::vector<int> ret;
while ((dent = readdir(srcdir)) != nullptr) {
struct stat st;
if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue;
if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0) {
continue;
}
if (S_ISDIR(st.st_mode)) {
std::size_t i;
ret.push_back(string_to_T<int>(std::string(dent->d_name), i));
}
}
closedir(srcdir);
return ret;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2010, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program 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 General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <time.h>
#include "Context.h"
#include "Date.h"
#include "Duration.h"
#include "text.h"
#include "util.h"
#include "main.h"
#ifdef HAVE_LIBNCURSES
#include <ncurses.h>
#endif
// Global context for use by all.
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Scans all tasks, and for any recurring tasks, determines whether any new
// child tasks need to be generated to fill gaps.
void handleRecurrence ()
{
std::vector <Task> tasks;
Filter filter;
context.tdb.loadPending (tasks, filter);
std::vector <Task> modified;
// Look at all tasks and find any recurring ones.
foreach (t, tasks)
{
if (t->getStatus () == Task::recurring)
{
// Generate a list of due dates for this recurring task, regardless of
// the mask.
std::vector <Date> due;
if (!generateDueDates (*t, due))
{
std::cout << "Task ("
<< trim (t->get ("description"))
<< ") has past its 'until' date, and has been deleted.\n";
// Determine the end date.
char endTime[16];
sprintf (endTime, "%u", (unsigned int) time (NULL));
t->set ("end", endTime);
t->setStatus (Task::deleted);
context.tdb.update (*t);
continue;
}
// Get the mask from the parent task.
std::string mask = t->get ("mask");
// Iterate over the due dates, and check each against the mask.
bool changed = false;
unsigned int i = 0;
foreach (d, due)
{
if (mask.length () <= i)
{
changed = true;
Task rec (*t); // Clone the parent.
rec.set ("uuid", uuid ()); // New UUID.
rec.set ("parent", t->get ("uuid")); // Remember mom.
char dueDate[16];
sprintf (dueDate, "%u", (unsigned int) d->toEpoch ());
rec.set ("due", dueDate); // Store generated due date.
if (t->get ("wait").size())
{
Date old_wait (atoi (t->get ("wait").c_str ()));
Date old_due (atoi (t->get ("due").c_str ()));
Date due (*d);
sprintf (dueDate, "%u", (unsigned int) (due + (old_wait - old_due)).toEpoch ());
rec.set ("wait", dueDate);
rec.setStatus (Task::waiting);
mask += 'W';
}
else
{
mask += '-';
rec.setStatus (Task::pending);
}
char indexMask[12];
sprintf (indexMask, "%u", (unsigned int) i);
rec.set ("imask", indexMask); // Store index into mask.
rec.remove ("mask"); // Remove the mask of the parent.
// Add the new task to the vector, for immediate use.
modified.push_back (rec);
// Add the new task to the DB.
context.tdb.add (rec);
}
++i;
}
// Only modify the parent if necessary.
if (changed)
{
t->set ("mask", mask);
context.tdb.update (*t);
}
}
else
modified.push_back (*t);
}
tasks = modified;
}
////////////////////////////////////////////////////////////////////////////////
// Determine a start date (due), an optional end date (until), and an increment
// period (recur). Then generate a set of corresponding dates.
//
// Returns false if the parent recurring task is depleted.
bool generateDueDates (Task& parent, std::vector <Date>& allDue)
{
// Determine due date, recur period and until date.
Date due (atoi (parent.get ("due").c_str ()));
std::string recur = parent.get ("recur");
bool specificEnd = false;
Date until;
if (parent.get ("until") != "")
{
until = Date (atoi (parent.get ("until").c_str ()));
specificEnd = true;
}
int recurrence_limit = context.config.getInteger ("recurrence.limit");
int recurrence_counter = 0;
Date now;
for (Date i = due; ; i = getNextRecurrence (i, recur))
{
allDue.push_back (i);
if (specificEnd && i > until)
{
// If i > until, it means there are no more tasks to generate, and if the
// parent mask contains all + or X, then there never will be another task
// to generate, and this parent task may be safely reaped.
std::string mask = parent.get ("mask");
if (mask.length () == allDue.size () &&
mask.find ('-') == std::string::npos)
return false;
return true;
}
if (i > now)
++recurrence_counter;
if (recurrence_counter >= recurrence_limit)
return true;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
Date getNextRecurrence (Date& current, std::string& period)
{
int m = current.month ();
int d = current.day ();
int y = current.year ();
// Some periods are difficult, because they can be vague.
if (period == "monthly")
{
if (++m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
if (period == "weekdays")
{
int dow = current.dayOfWeek ();
int days;
if (dow == 5) days = 3;
else if (dow == 6) days = 2;
else days = 1;
return current + (days * 86400);
}
if (isdigit (period[0]) && period[period.length () - 1] == 'm')
{
std::string numeric = period.substr (0, period.length () - 1);
int increment = atoi (numeric.c_str ());
m += increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "quarterly")
{
m += 3;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (isdigit (period[0]) && period[period.length () - 1] == 'q')
{
std::string numeric = period.substr (0, period.length () - 1);
int increment = atoi (numeric.c_str ());
m += 3 * increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "semiannual")
{
m += 6;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "bimonthly")
{
m += 2;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "biannual" ||
period == "biyearly")
{
y += 2;
return Date (m, d, y);
}
else if (period == "annual" ||
period == "yearly")
{
y += 1;
// If the due data just happens to be 2/29 in a leap year, then simply
// incrementing y is going to create an invalid date.
if (m == 2 && d == 29)
d = 28;
return Date (m, d, y);
}
// If the period is an 'easy' one, add it to current, and we're done.
int secs = 0;
try { Duration du (period); secs = du; }
catch (...) { secs = 0; }
return current + secs;
}
////////////////////////////////////////////////////////////////////////////////
// When the status of a recurring child task changes, the parent task must
// update it's mask.
void updateRecurrenceMask (
std::vector <Task>& all,
Task& task)
{
std::string parent = task.get ("parent");
if (parent != "")
{
std::vector <Task>::iterator it;
for (it = all.begin (); it != all.end (); ++it)
{
if (it->get ("uuid") == parent)
{
unsigned int index = atoi (task.get ("imask").c_str ());
std::string mask = it->get ("mask");
if (mask.length () > index)
{
mask[index] = (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
it->set ("mask", mask);
context.tdb.update (*it);
}
else
{
std::string mask;
for (unsigned int i = 0; i < index; ++i)
mask += "?";
mask += (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
}
return; // No point continuing the loop.
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Determines whether a task is overdue. Returns
// 0 = not due at all
// 1 = imminent
// 2 = today
// 3 = overdue
int getDueState (const std::string& due)
{
if (due.length ())
{
Date dt (::atoi (due.c_str ()));
// rightNow is the current date + time.
Date rightNow;
Date thisDay (rightNow.month (), rightNow.day (), rightNow.year ());
if (dt < rightNow)
return 3;
if (rightNow.sameDay (dt))
return 2;
int imminentperiod = context.config.getInteger ("due");
if (imminentperiod == 0)
return 1;
Date imminentDay = thisDay + imminentperiod * 86400;
if (dt < imminentDay)
return 1;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Returns a Boolean indicator as to whether a nag message was generated, so
// that commands can control the number of nag messages displayed (ie one is
// enough).
bool nag (Task& task)
{
// Special tag overrides nagging.
if (task.hasTag ("nonag"))
return false;
std::string nagMessage = context.config.get ("nag");
if (nagMessage != "")
{
// Load all pending tasks.
std::vector <Task> tasks;
Filter filter;
// Piggy-back on existing locked TDB.
context.tdb.loadPending (tasks, filter);
// Counters.
int overdue = 0;
int high = 0;
int medium = 0;
int low = 0;
bool isOverdue = false;
char pri = ' ';
// Scan all pending tasks.
foreach (t, tasks)
{
if (t->id == task.id)
{
if (getDueState (t->get ("due")) == 3)
isOverdue = true;
std::string priority = t->get ("priority");
if (priority.length ())
pri = priority[0];
}
else if (t->getStatus () == Task::pending)
{
if (getDueState (t->get ("due")) == 3)
overdue++;
std::string priority = t->get ("priority");
if (priority.length ())
{
switch (priority[0])
{
case 'H': high++; break;
case 'M': medium++; break;
case 'L': low++; break;
}
}
}
}
// General form is "if there are no more deserving tasks", suppress the nag.
if (isOverdue ) return false;
if (pri == 'H' && !overdue ) return false;
if (pri == 'M' && !overdue && !high ) return false;
if (pri == 'L' && !overdue && !high && !medium ) return false;
if (pri == ' ' && !overdue && !high && !medium && !low ) return false;
if (dependencyIsBlocking (task) && !dependencyIsBlocked (task)) return false;
// All the excuses are made, all that remains is to nag the user.
context.footnote (nagMessage);
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Code Cleanup<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2010, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program 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 General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <time.h>
#include "Context.h"
#include "Date.h"
#include "Duration.h"
#include "text.h"
#include "util.h"
#include "main.h"
#ifdef HAVE_LIBNCURSES
#include <ncurses.h>
#endif
// Global context for use by all.
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Scans all tasks, and for any recurring tasks, determines whether any new
// child tasks need to be generated to fill gaps.
void handleRecurrence ()
{
std::vector <Task> tasks;
Filter filter;
context.tdb.loadPending (tasks, filter);
std::vector <Task> modified;
// Look at all tasks and find any recurring ones.
foreach (t, tasks)
{
if (t->getStatus () == Task::recurring)
{
// Generate a list of due dates for this recurring task, regardless of
// the mask.
std::vector <Date> due;
if (!generateDueDates (*t, due))
{
std::cout << "Task ("
<< trim (t->get ("description"))
<< ") has past its 'until' date, and has been deleted.\n";
// Determine the end date.
char endTime[16];
sprintf (endTime, "%u", (unsigned int) time (NULL));
t->set ("end", endTime);
t->setStatus (Task::deleted);
context.tdb.update (*t);
continue;
}
// Get the mask from the parent task.
std::string mask = t->get ("mask");
// Iterate over the due dates, and check each against the mask.
bool changed = false;
unsigned int i = 0;
foreach (d, due)
{
if (mask.length () <= i)
{
changed = true;
Task rec (*t); // Clone the parent.
rec.set ("uuid", uuid ()); // New UUID.
rec.set ("parent", t->get ("uuid")); // Remember mom.
char dueDate[16];
sprintf (dueDate, "%u", (unsigned int) d->toEpoch ());
rec.set ("due", dueDate); // Store generated due date.
if (t->has ("wait"))
{
Date old_wait (atoi (t->get ("wait").c_str ()));
Date old_due (atoi (t->get ("due").c_str ()));
Date due (*d);
sprintf (dueDate, "%u", (unsigned int) (due + (old_wait - old_due)).toEpoch ());
rec.set ("wait", dueDate);
rec.setStatus (Task::waiting);
mask += 'W';
}
else
{
mask += '-';
rec.setStatus (Task::pending);
}
char indexMask[12];
sprintf (indexMask, "%u", (unsigned int) i);
rec.set ("imask", indexMask); // Store index into mask.
rec.remove ("mask"); // Remove the mask of the parent.
// Add the new task to the vector, for immediate use.
modified.push_back (rec);
// Add the new task to the DB.
context.tdb.add (rec);
}
++i;
}
// Only modify the parent if necessary.
if (changed)
{
t->set ("mask", mask);
context.tdb.update (*t);
}
}
else
modified.push_back (*t);
}
tasks = modified;
}
////////////////////////////////////////////////////////////////////////////////
// Determine a start date (due), an optional end date (until), and an increment
// period (recur). Then generate a set of corresponding dates.
//
// Returns false if the parent recurring task is depleted.
bool generateDueDates (Task& parent, std::vector <Date>& allDue)
{
// Determine due date, recur period and until date.
Date due (atoi (parent.get ("due").c_str ()));
std::string recur = parent.get ("recur");
bool specificEnd = false;
Date until;
if (parent.get ("until") != "")
{
until = Date (atoi (parent.get ("until").c_str ()));
specificEnd = true;
}
int recurrence_limit = context.config.getInteger ("recurrence.limit");
int recurrence_counter = 0;
Date now;
for (Date i = due; ; i = getNextRecurrence (i, recur))
{
allDue.push_back (i);
if (specificEnd && i > until)
{
// If i > until, it means there are no more tasks to generate, and if the
// parent mask contains all + or X, then there never will be another task
// to generate, and this parent task may be safely reaped.
std::string mask = parent.get ("mask");
if (mask.length () == allDue.size () &&
mask.find ('-') == std::string::npos)
return false;
return true;
}
if (i > now)
++recurrence_counter;
if (recurrence_counter >= recurrence_limit)
return true;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
Date getNextRecurrence (Date& current, std::string& period)
{
int m = current.month ();
int d = current.day ();
int y = current.year ();
// Some periods are difficult, because they can be vague.
if (period == "monthly")
{
if (++m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
if (period == "weekdays")
{
int dow = current.dayOfWeek ();
int days;
if (dow == 5) days = 3;
else if (dow == 6) days = 2;
else days = 1;
return current + (days * 86400);
}
if (isdigit (period[0]) && period[period.length () - 1] == 'm')
{
std::string numeric = period.substr (0, period.length () - 1);
int increment = atoi (numeric.c_str ());
m += increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "quarterly")
{
m += 3;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (isdigit (period[0]) && period[period.length () - 1] == 'q')
{
std::string numeric = period.substr (0, period.length () - 1);
int increment = atoi (numeric.c_str ());
m += 3 * increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "semiannual")
{
m += 6;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "bimonthly")
{
m += 2;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "biannual" ||
period == "biyearly")
{
y += 2;
return Date (m, d, y);
}
else if (period == "annual" ||
period == "yearly")
{
y += 1;
// If the due data just happens to be 2/29 in a leap year, then simply
// incrementing y is going to create an invalid date.
if (m == 2 && d == 29)
d = 28;
return Date (m, d, y);
}
// If the period is an 'easy' one, add it to current, and we're done.
int secs = 0;
try { Duration du (period); secs = du; }
catch (...) { secs = 0; }
return current + secs;
}
////////////////////////////////////////////////////////////////////////////////
// When the status of a recurring child task changes, the parent task must
// update it's mask.
void updateRecurrenceMask (
std::vector <Task>& all,
Task& task)
{
std::string parent = task.get ("parent");
if (parent != "")
{
std::vector <Task>::iterator it;
for (it = all.begin (); it != all.end (); ++it)
{
if (it->get ("uuid") == parent)
{
unsigned int index = atoi (task.get ("imask").c_str ());
std::string mask = it->get ("mask");
if (mask.length () > index)
{
mask[index] = (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
it->set ("mask", mask);
context.tdb.update (*it);
}
else
{
std::string mask;
for (unsigned int i = 0; i < index; ++i)
mask += "?";
mask += (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
}
return; // No point continuing the loop.
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Determines whether a task is overdue. Returns
// 0 = not due at all
// 1 = imminent
// 2 = today
// 3 = overdue
int getDueState (const std::string& due)
{
if (due.length ())
{
Date dt (::atoi (due.c_str ()));
// rightNow is the current date + time.
Date rightNow;
Date thisDay (rightNow.month (), rightNow.day (), rightNow.year ());
if (dt < rightNow)
return 3;
if (rightNow.sameDay (dt))
return 2;
int imminentperiod = context.config.getInteger ("due");
if (imminentperiod == 0)
return 1;
Date imminentDay = thisDay + imminentperiod * 86400;
if (dt < imminentDay)
return 1;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Returns a Boolean indicator as to whether a nag message was generated, so
// that commands can control the number of nag messages displayed (ie one is
// enough).
bool nag (Task& task)
{
// Special tag overrides nagging.
if (task.hasTag ("nonag"))
return false;
std::string nagMessage = context.config.get ("nag");
if (nagMessage != "")
{
// Load all pending tasks.
std::vector <Task> tasks;
Filter filter;
// Piggy-back on existing locked TDB.
context.tdb.loadPending (tasks, filter);
// Counters.
int overdue = 0;
int high = 0;
int medium = 0;
int low = 0;
bool isOverdue = false;
char pri = ' ';
// Scan all pending tasks.
foreach (t, tasks)
{
if (t->id == task.id)
{
if (getDueState (t->get ("due")) == 3)
isOverdue = true;
std::string priority = t->get ("priority");
if (priority.length ())
pri = priority[0];
}
else if (t->getStatus () == Task::pending)
{
if (getDueState (t->get ("due")) == 3)
overdue++;
std::string priority = t->get ("priority");
if (priority.length ())
{
switch (priority[0])
{
case 'H': high++; break;
case 'M': medium++; break;
case 'L': low++; break;
}
}
}
}
// General form is "if there are no more deserving tasks", suppress the nag.
if (isOverdue ) return false;
if (pri == 'H' && !overdue ) return false;
if (pri == 'M' && !overdue && !high ) return false;
if (pri == 'L' && !overdue && !high && !medium ) return false;
if (pri == ' ' && !overdue && !high && !medium && !low ) return false;
if (dependencyIsBlocking (task) && !dependencyIsBlocked (task)) return false;
// All the excuses are made, all that remains is to nag the user.
context.footnote (nagMessage);
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>// Copyright[2015] <[email protected]>
#include <cstdio>
#include "./runner.h"
namespace eznetpp {
runner::runner(void) {
}
runner::~runner(void) {
}
void runner::run(void) {
printf("hello test!");
}
} // namespace eznetpp
<commit_msg>updated runner class code<commit_after>// Copyright[2015] <[email protected]>
#include <cstdio>
#include "./runner.h"
namespace eznetpp {
runner::runner(void) {
}
runner::~runner(void) {
}
void runner::run(void) {
}
} // namespace eznetpp
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/stream_manager.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/actor_control_block.hpp"
#include "caf/error.hpp"
#include "caf/expected.hpp"
#include "caf/inbound_path.hpp"
#include "caf/scheduled_actor.hpp"
#include "caf/logger.hpp"
#include "caf/message.hpp"
#include "caf/outbound_path.hpp"
#include "caf/response_promise.hpp"
#include "caf/sec.hpp"
namespace caf {
stream_manager::stream_manager(scheduled_actor* selfptr, stream_priority prio)
: self_(selfptr),
pending_handshakes_(0),
priority_(prio),
continuous_(false) {
// nop
}
stream_manager::~stream_manager() {
// nop
}
void stream_manager::handle(inbound_path*, downstream_msg::batch&) {
CAF_LOG_WARNING("unimplemented base handler for batches called");
}
void stream_manager::handle(inbound_path*, downstream_msg::close&) {
// nop
}
void stream_manager::handle(inbound_path*, downstream_msg::forced_close& x) {
abort(std::move(x.reason));
}
bool stream_manager::handle(stream_slots slots, upstream_msg::ack_open& x) {
CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(x));
auto ptr = out().path(slots.receiver);
if (ptr == nullptr)
return false;
if (!ptr->pending()) {
CAF_LOG_ERROR("received repeated ack_open");
return false;
}
if (ptr->hdl != x.rebind_from) {
CAF_LOG_ERROR("received ack_open with invalid rebind_from");
return false;
}
if (x.rebind_from != x.rebind_to) {
ptr->hdl = x.rebind_to;
}
ptr->slots.receiver = slots.sender;
ptr->open_credit = x.initial_demand;
ptr->desired_batch_size = x.desired_batch_size;
--pending_handshakes_;
push();
return true;
}
void stream_manager::handle(stream_slots slots, upstream_msg::ack_batch& x) {
CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(x));
auto path = out().path(slots.receiver);
if (path != nullptr) {
path->open_credit += x.new_capacity;
path->desired_batch_size = x.desired_batch_size;
path->next_ack_id = x.acknowledged_id + 1;
push();
}
}
void stream_manager::handle(stream_slots slots, upstream_msg::drop&) {
error tmp;
out().remove_path(slots.receiver, std::move(tmp), true);
}
void stream_manager::handle(stream_slots slots, upstream_msg::forced_drop& x) {
if (out().remove_path(slots.receiver, x.reason, true))
abort(std::move(x.reason));
}
void stream_manager::stop() {
CAF_LOG_TRACE("");
out().close();
error tmp;
finalize(tmp);
self_->erase_inbound_paths_later(this);
}
void stream_manager::abort(error reason) {
CAF_LOG_TRACE(CAF_ARG(reason));
out().abort(reason);
finalize(reason);
self_->erase_inbound_paths_later(this, std::move(reason));
}
void stream_manager::push() {
CAF_LOG_TRACE("");
do {
out().emit_batches();
} while (generate_messages());
}
bool stream_manager::congested() const noexcept {
return false;
}
void stream_manager::deliver_handshake(response_promise& rp, stream_slot slot,
message handshake) {
CAF_LOG_TRACE(CAF_ARG(rp) << CAF_ARG(slot) << CAF_ARG(handshake));
CAF_ASSERT(rp.pending());
CAF_ASSERT(slot != invalid_stream_slot);
++pending_handshakes_;
auto next = rp.next();
rp.deliver(open_stream_msg{slot, std::move(handshake), self_->ctrl(), next,
priority_});
}
bool stream_manager::generate_messages() {
return false;
}
void stream_manager::cycle_timeout(size_t) {
// TODO: make pure virtual
}
void stream_manager::register_input_path(inbound_path* ptr) {
CAF_ASSERT(ptr != nullptr);
CAF_LOG_TRACE(CAF_ARG2("path", *ptr));
inbound_paths_.emplace_back(ptr);
}
void stream_manager::deregister_input_path(inbound_path* ptr) noexcept {
CAF_ASSERT(ptr != nullptr);
CAF_LOG_TRACE(CAF_ARG2("path", *ptr));
CAF_ASSERT(inbound_paths_.size() > 0);
using std::swap;
if (ptr != inbound_paths_.back()) {
auto i = std::find(inbound_paths_.begin(), inbound_paths_.end(), ptr);
CAF_ASSERT(i != inbound_paths_.end());
swap(*i, inbound_paths_.back());
}
inbound_paths_.pop_back();
CAF_LOG_DEBUG(inbound_paths_.size() << "paths remaining");
}
void stream_manager::remove_input_path(stream_slot slot, error reason,
bool silent) {
if (silent)
self_->erase_inbound_path_later(slot);
else
self_->erase_inbound_path_later(slot, std::move(reason));
}
inbound_path* stream_manager::get_inbound_path(stream_slot x) const noexcept {
auto pred = [=](inbound_path* ptr) {
return ptr->slots.receiver == x;
};
auto e = inbound_paths_.end();
auto i = std::find_if(inbound_paths_.begin(), e, pred);
return i != e ? *i : nullptr;
}
bool stream_manager::inbound_paths_up_to_date() const noexcept {
auto up_to_date = [](inbound_path* x) { return x->up_to_date(); };
return std::all_of(inbound_paths_.begin(), inbound_paths_.end(), up_to_date);
}
stream_slot stream_manager::add_unchecked_outbound_path_impl(response_promise& rp,
message handshake) {
CAF_LOG_TRACE(CAF_ARG(rp) << CAF_ARG(handshake));
CAF_ASSERT(out().terminal() == false);
if (!rp.pending()) {
CAF_LOG_WARNING("add_outbound_path called with next == nullptr");
rp.deliver(sec::no_downstream_stages_defined);
return invalid_stream_slot;
}
auto slot = self_->assign_next_pending_slot_to(this);
auto path = out().add_path(slot, rp.next());
CAF_IGNORE_UNUSED(path);
CAF_ASSERT(path != nullptr);
// Build pipeline by forwarding handshake along the path.
deliver_handshake(rp, slot, std::move(handshake));
generate_messages();
return slot;
}
stream_slot stream_manager::add_unchecked_outbound_path_impl(strong_actor_ptr next,
message handshake) {
CAF_LOG_TRACE(CAF_ARG(next) << CAF_ARG(handshake));
response_promise rp{self_->ctrl(), nullptr, {next}, make_message_id()};
return add_unchecked_outbound_path_impl(rp, std::move(handshake));
}
stream_slot stream_manager::add_unchecked_outbound_path_impl(message handshake) {
CAF_LOG_TRACE(CAF_ARG(handshake));
auto rp = self_->make_response_promise();
return add_unchecked_outbound_path_impl(rp, std::move(handshake));
}
stream_slot stream_manager::add_unchecked_inbound_path_impl() {
CAF_LOG_TRACE("");
auto x = self_->current_mailbox_element();
if (x == nullptr || !x->content().match_elements<open_stream_msg>()) {
CAF_LOG_ERROR("add_unchecked_inbound_path called, but current message "
"is not an open_stream_msg");
return invalid_stream_slot;
}
auto& osm = x->content().get_mutable_as<open_stream_msg>(0);
if (out().terminal() && !self_->current_forwarding_stack().empty()) {
// Sinks must always terminate the stream.
CAF_LOG_WARNING("add_unchecked_inbound_path called in a sink, but the "
"handshake has further stages");
stream_slots path_id{osm.slot, 0};
auto code = sec::cannot_add_downstream;
inbound_path::emit_irregular_shutdown(self_, path_id,
std::move(osm.prev_stage), code);
auto rp = self_->make_response_promise();
rp.deliver(code);
return invalid_stream_slot;
}
auto slot = assign_next_slot();
stream_slots path_id{osm.slot, slot};
auto ptr = self_->make_inbound_path(this, path_id, std::move(osm.prev_stage));
CAF_ASSERT(ptr != nullptr);
ptr->emit_ack_open(self_, actor_cast<actor_addr>(osm.original_stage));
return slot;
}
stream_slot stream_manager::assign_next_slot() {
return self_->assign_next_slot_to(this);
}
stream_slot stream_manager::assign_next_pending_slot() {
return self_->assign_next_pending_slot_to(this);
}
void stream_manager::finalize(const error&) {
// nop
}
message stream_manager::make_final_result() {
return none;
}
error stream_manager::process_batch(message&) {
CAF_LOG_ERROR("stream_manager::process_batch called");
return sec::invalid_stream_state;
}
void stream_manager::output_closed(error) {
// nop
}
void stream_manager::downstream_demand(outbound_path*, long) {
CAF_LOG_ERROR("stream_manager::downstream_demand called");
}
void stream_manager::input_closed(error) {
// nop
}
} // namespace caf
<commit_msg>Add sanity checks<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/stream_manager.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/actor_control_block.hpp"
#include "caf/error.hpp"
#include "caf/expected.hpp"
#include "caf/inbound_path.hpp"
#include "caf/scheduled_actor.hpp"
#include "caf/logger.hpp"
#include "caf/message.hpp"
#include "caf/outbound_path.hpp"
#include "caf/response_promise.hpp"
#include "caf/sec.hpp"
namespace caf {
stream_manager::stream_manager(scheduled_actor* selfptr, stream_priority prio)
: self_(selfptr),
pending_handshakes_(0),
priority_(prio),
continuous_(false) {
// nop
}
stream_manager::~stream_manager() {
// nop
}
void stream_manager::handle(inbound_path*, downstream_msg::batch&) {
CAF_LOG_WARNING("unimplemented base handler for batches called");
}
void stream_manager::handle(inbound_path*, downstream_msg::close&) {
// nop
}
void stream_manager::handle(inbound_path*, downstream_msg::forced_close& x) {
abort(std::move(x.reason));
}
bool stream_manager::handle(stream_slots slots, upstream_msg::ack_open& x) {
CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(x));
CAF_ASSERT(x.desired_batch_size > 0);
auto ptr = out().path(slots.receiver);
if (ptr == nullptr)
return false;
if (!ptr->pending()) {
CAF_LOG_ERROR("received repeated ack_open");
return false;
}
if (ptr->hdl != x.rebind_from) {
CAF_LOG_ERROR("received ack_open with invalid rebind_from");
return false;
}
if (x.rebind_from != x.rebind_to) {
ptr->hdl = x.rebind_to;
}
ptr->slots.receiver = slots.sender;
ptr->open_credit = x.initial_demand;
ptr->desired_batch_size = x.desired_batch_size;
--pending_handshakes_;
push();
return true;
}
void stream_manager::handle(stream_slots slots, upstream_msg::ack_batch& x) {
CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(x));
CAF_ASSERT(x.desired_batch_size > 0);
auto path = out().path(slots.receiver);
if (path != nullptr) {
path->open_credit += x.new_capacity;
path->desired_batch_size = x.desired_batch_size;
path->next_ack_id = x.acknowledged_id + 1;
push();
}
}
void stream_manager::handle(stream_slots slots, upstream_msg::drop&) {
error tmp;
out().remove_path(slots.receiver, std::move(tmp), true);
}
void stream_manager::handle(stream_slots slots, upstream_msg::forced_drop& x) {
if (out().remove_path(slots.receiver, x.reason, true))
abort(std::move(x.reason));
}
void stream_manager::stop() {
CAF_LOG_TRACE("");
out().close();
error tmp;
finalize(tmp);
self_->erase_inbound_paths_later(this);
}
void stream_manager::abort(error reason) {
CAF_LOG_TRACE(CAF_ARG(reason));
out().abort(reason);
finalize(reason);
self_->erase_inbound_paths_later(this, std::move(reason));
}
void stream_manager::push() {
CAF_LOG_TRACE("");
do {
out().emit_batches();
} while (generate_messages());
}
bool stream_manager::congested() const noexcept {
return false;
}
void stream_manager::deliver_handshake(response_promise& rp, stream_slot slot,
message handshake) {
CAF_LOG_TRACE(CAF_ARG(rp) << CAF_ARG(slot) << CAF_ARG(handshake));
CAF_ASSERT(rp.pending());
CAF_ASSERT(slot != invalid_stream_slot);
++pending_handshakes_;
auto next = rp.next();
rp.deliver(open_stream_msg{slot, std::move(handshake), self_->ctrl(), next,
priority_});
}
bool stream_manager::generate_messages() {
return false;
}
void stream_manager::cycle_timeout(size_t) {
// TODO: make pure virtual
}
void stream_manager::register_input_path(inbound_path* ptr) {
CAF_ASSERT(ptr != nullptr);
CAF_LOG_TRACE(CAF_ARG2("path", *ptr));
inbound_paths_.emplace_back(ptr);
}
void stream_manager::deregister_input_path(inbound_path* ptr) noexcept {
CAF_ASSERT(ptr != nullptr);
CAF_LOG_TRACE(CAF_ARG2("path", *ptr));
CAF_ASSERT(inbound_paths_.size() > 0);
using std::swap;
if (ptr != inbound_paths_.back()) {
auto i = std::find(inbound_paths_.begin(), inbound_paths_.end(), ptr);
CAF_ASSERT(i != inbound_paths_.end());
swap(*i, inbound_paths_.back());
}
inbound_paths_.pop_back();
CAF_LOG_DEBUG(inbound_paths_.size() << "paths remaining");
}
void stream_manager::remove_input_path(stream_slot slot, error reason,
bool silent) {
if (silent)
self_->erase_inbound_path_later(slot);
else
self_->erase_inbound_path_later(slot, std::move(reason));
}
inbound_path* stream_manager::get_inbound_path(stream_slot x) const noexcept {
auto pred = [=](inbound_path* ptr) {
return ptr->slots.receiver == x;
};
auto e = inbound_paths_.end();
auto i = std::find_if(inbound_paths_.begin(), e, pred);
return i != e ? *i : nullptr;
}
bool stream_manager::inbound_paths_up_to_date() const noexcept {
auto up_to_date = [](inbound_path* x) { return x->up_to_date(); };
return std::all_of(inbound_paths_.begin(), inbound_paths_.end(), up_to_date);
}
stream_slot stream_manager::add_unchecked_outbound_path_impl(response_promise& rp,
message handshake) {
CAF_LOG_TRACE(CAF_ARG(rp) << CAF_ARG(handshake));
CAF_ASSERT(out().terminal() == false);
if (!rp.pending()) {
CAF_LOG_WARNING("add_outbound_path called with next == nullptr");
rp.deliver(sec::no_downstream_stages_defined);
return invalid_stream_slot;
}
auto slot = self_->assign_next_pending_slot_to(this);
auto path = out().add_path(slot, rp.next());
CAF_IGNORE_UNUSED(path);
CAF_ASSERT(path != nullptr);
// Build pipeline by forwarding handshake along the path.
deliver_handshake(rp, slot, std::move(handshake));
generate_messages();
return slot;
}
stream_slot stream_manager::add_unchecked_outbound_path_impl(strong_actor_ptr next,
message handshake) {
CAF_LOG_TRACE(CAF_ARG(next) << CAF_ARG(handshake));
response_promise rp{self_->ctrl(), nullptr, {next}, make_message_id()};
return add_unchecked_outbound_path_impl(rp, std::move(handshake));
}
stream_slot stream_manager::add_unchecked_outbound_path_impl(message handshake) {
CAF_LOG_TRACE(CAF_ARG(handshake));
auto rp = self_->make_response_promise();
return add_unchecked_outbound_path_impl(rp, std::move(handshake));
}
stream_slot stream_manager::add_unchecked_inbound_path_impl() {
CAF_LOG_TRACE("");
auto x = self_->current_mailbox_element();
if (x == nullptr || !x->content().match_elements<open_stream_msg>()) {
CAF_LOG_ERROR("add_unchecked_inbound_path called, but current message "
"is not an open_stream_msg");
return invalid_stream_slot;
}
auto& osm = x->content().get_mutable_as<open_stream_msg>(0);
if (out().terminal() && !self_->current_forwarding_stack().empty()) {
// Sinks must always terminate the stream.
CAF_LOG_WARNING("add_unchecked_inbound_path called in a sink, but the "
"handshake has further stages");
stream_slots path_id{osm.slot, 0};
auto code = sec::cannot_add_downstream;
inbound_path::emit_irregular_shutdown(self_, path_id,
std::move(osm.prev_stage), code);
auto rp = self_->make_response_promise();
rp.deliver(code);
return invalid_stream_slot;
}
auto slot = assign_next_slot();
stream_slots path_id{osm.slot, slot};
auto ptr = self_->make_inbound_path(this, path_id, std::move(osm.prev_stage));
CAF_ASSERT(ptr != nullptr);
ptr->emit_ack_open(self_, actor_cast<actor_addr>(osm.original_stage));
return slot;
}
stream_slot stream_manager::assign_next_slot() {
return self_->assign_next_slot_to(this);
}
stream_slot stream_manager::assign_next_pending_slot() {
return self_->assign_next_pending_slot_to(this);
}
void stream_manager::finalize(const error&) {
// nop
}
message stream_manager::make_final_result() {
return none;
}
error stream_manager::process_batch(message&) {
CAF_LOG_ERROR("stream_manager::process_batch called");
return sec::invalid_stream_state;
}
void stream_manager::output_closed(error) {
// nop
}
void stream_manager::downstream_demand(outbound_path*, long) {
CAF_LOG_ERROR("stream_manager::downstream_demand called");
}
void stream_manager::input_closed(error) {
// nop
}
} // namespace caf
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
using namespace Halide::Internal;
class ValidateInterleavedPipeline: public IRMutator {
protected:
//
// This is roughly the structure that we are trying to validate in this custom pass:
//
// parallel<Renderscript> (result$2.s0.y$2.__block_id_y, 0, result$2.extent.1) {
// parallel<Renderscript> (result$2.s0.x$2.__block_id_x, 0, result$2.extent.0) {
// ...
// parallel<Renderscript> (.__thread_id_x, 0, 1) {
// for<Renderscript> (result$2.s0.c$2, 0, 4) {
// image_store("result$2",
// result$2.buffer,
// (result$2.s0.x$2.__block_id_x + result$2.min.0),
// (result$2.s0.y$2.__block_id_y + result$2.min.1),
// result$2.s0.c$2,
// image_load("input",
// input.buffer,
// ((result$2.s0.x$2.__block_id_x + result$2.min.0) - input.min.0),
// input.extent.0,
// ((result$2.s0.y$2.__block_id_y + result$2.min.1) - input.min.1),
// input.extent.1,
// result$2.s0.c$2,
// 4))
// }
// }
// ...
// }
// }
//
using IRMutator::visit;
virtual void visit(const Call *call) {
if (in_pipeline && call->call_type == Call::CallType::Intrinsic && call->name == Call::image_store) {
assert(for_nest_level == 4);
std::map<std::string, Expr> matches;
assert(expr_match(
StringImm::make("result"),
call->args[0],
matches));
assert(expr_match(
Variable::make(Handle(1), "result.buffer"),
call->args[1],
matches));
assert(expr_match(
Variable::make(Int(32), "result.s0.x.__block_id_x") + Variable::make(Int(32), "result.min.0"),
call->args[2],
matches));
assert(expr_match(
Variable::make(Int(32), "result.s0.y.__block_id_y") + Variable::make(Int(32), "result.min.1"),
call->args[3],
matches));
assert(expr_match(
Variable::make(Int(32), "result.s0.c"),
call->args[4],
matches));
assert(expr_match(
Call::make(
UInt(8),
Call::image_load,
{
StringImm::make("input"),
Variable::make(Handle(1), "input.buffer"),
(Variable::make(Int(32), "result.s0.x.__block_id_x") +
Variable::make(Int(32), "result.min.0")) -
Variable::make(Int(32), "input.min.0"),
Variable::make(Int(32), "input.extent.0"),
(Variable::make(Int(32), "result.s0.y.__block_id_y") +
Variable::make(Int(32), "result.min.1")) -
Variable::make(Int(32), "input.min.1"),
Variable::make(Int(32), "input.extent.1"),
Variable::make(Int(32), "result.s0.c"),
IntImm::make(channels)
},
Call::CallType::Intrinsic),
call->args[5],
matches));
}
IRMutator::visit(call);
}
void visit(const For *op) {
if (in_pipeline) {
assert(for_nest_level >= 0); // For-loop should show up in Pipeline.
for_nest_level++;
if (for_nest_level <= 3) {
assert(op->for_type == ForType::Parallel);
}
assert(op->device_api == DeviceAPI::Renderscript);
}
IRMutator::visit(op);
}
void visit(const ProducerConsumer *op) {
assert(!in_pipeline); // There should be only one pipeline in the test.
for_nest_level = 0;
in_pipeline = true;
assert(op->produce.defined());
assert(!op->update.defined());
assert(op->consume.defined());
IRMutator::visit(op);
stmt = Stmt();
}
int for_nest_level = -1;
bool in_pipeline = false;
int channels;
public:
ValidateInterleavedPipeline(int _channels) : channels(_channels) {}
};
class ValidateInterleavedVectorizedPipeline: public ValidateInterleavedPipeline {
using ValidateInterleavedPipeline::visit;
virtual void visit(const Call *call) {
if (in_pipeline && call->call_type == Call::CallType::Intrinsic && call->name == Call::image_store) {
assert(for_nest_level == 3); // Should be three nested for-loops before we get to the first call.
std::map<std::string, Expr> matches;
assert(expr_match(
Broadcast::make(StringImm::make("result"), channels),
call->args[0],
matches));
assert(expr_match(
Broadcast::make(Variable::make(Handle(1), "result.buffer"), channels),
call->args[1],
matches));
assert(expr_match(
Broadcast::make(Variable::make(Int(32), "result.s0.x.__block_id_x") + Variable::make(Int(32), "result.min.0"), channels),
call->args[2],
matches));
assert(expr_match(
Broadcast::make(Variable::make(Int(32), "result.s0.y.__block_id_y") + Variable::make(Int(32), "result.min.1"), channels),
call->args[3],
matches));
assert(expr_match(
Ramp::make(0, 1, channels), call->args[4], matches));
assert(expr_match(
Call::make(
UInt(8, channels),
Call::image_load,
{
Broadcast::make(StringImm::make("input"), channels),
Broadcast::make(Variable::make(Handle(1), "input.buffer"), channels),
Broadcast::make(
Add::make(
Variable::make(Int(32), "result.s0.x.__block_id_x"),
Variable::make(Int(32), "result.min.0")) -
Variable::make(Int(32), "input.min.0"),
channels),
Broadcast::make(Variable::make(Int(32), "input.extent.0"), channels),
Broadcast::make(
Add::make(
Variable::make(Int(32), "result.s0.y.__block_id_y"),
Variable::make(Int(32), "result.min.1")) -
Variable::make(Int(32), "input.min.1"),
channels),
Broadcast::make(Variable::make(Int(32), "input.extent.1"), channels),
Ramp::make(0, 1, channels),
Broadcast::make(IntImm::make(channels), channels)
},
Call::CallType::Intrinsic),
call->args[5],
matches));
}
IRMutator::visit(call);
}
public:
ValidateInterleavedVectorizedPipeline(int _channels) : ValidateInterleavedPipeline(_channels) {}
};
Image<uint8_t> make_interleaved_image(uint8_t *host, int W, int H, int channels) {
buffer_t buf = { 0 };
buf.host = host;
buf.extent[0] = W;
buf.stride[0] = channels;
buf.extent[1] = H;
buf.stride[1] = buf.stride[0] * buf.extent[0];
buf.extent[2] = channels;
buf.stride[2] = 1;
buf.elem_size = 1;
return Image<uint8_t>(&buf);
}
void copy_interleaved(bool vectorized = false, int channels = 4) {
ImageParam input8(UInt(8), 3, "input");
input8.set_stride(0, channels)
.set_stride(1, Halide::Expr())
.set_stride(2, 1)
.set_bounds(2, 0, channels); // expecting interleaved image
uint8_t *in_buf = new uint8_t[128 * 128 * channels];
uint8_t *out_buf = new uint8_t[128 * 128 * channels];
Image<uint8_t> in = make_interleaved_image(in_buf, 128, 128, channels);
Image<uint8_t> out = make_interleaved_image(out_buf, 128, 128, channels);
input8.set(in);
Var x, y, c;
Func result("result");
result(x, y, c) = input8(x, y, c);
result.output_buffer()
.set_stride(0, channels)
.set_stride(1, Halide::Expr())
.set_stride(2, 1)
.set_bounds(2, 0, channels); // expecting interleaved image
result.bound(c, 0, channels);
result.shader(x, y, c, DeviceAPI::Renderscript);
if (vectorized) result.vectorize(c);
result.add_custom_lowering_pass(
vectorized?
new ValidateInterleavedVectorizedPipeline(channels):
new ValidateInterleavedPipeline(channels));
result.realize(out);
delete[] in_buf;
delete[] out_buf;
}
int main(int argc, char **argv) {
copy_interleaved(true, 4);
copy_interleaved(false, 4);
copy_interleaved(true, 3);
copy_interleaved(false, 3);
std::cout << "Done!" << std::endl;
return 0;
}
<commit_msg>Another using directive for renderscript jit copy test<commit_after>#include "Halide.h"
using namespace Halide;
using namespace Halide::Internal;
class ValidateInterleavedPipeline: public IRMutator {
protected:
//
// This is roughly the structure that we are trying to validate in this custom pass:
//
// parallel<Renderscript> (result$2.s0.y$2.__block_id_y, 0, result$2.extent.1) {
// parallel<Renderscript> (result$2.s0.x$2.__block_id_x, 0, result$2.extent.0) {
// ...
// parallel<Renderscript> (.__thread_id_x, 0, 1) {
// for<Renderscript> (result$2.s0.c$2, 0, 4) {
// image_store("result$2",
// result$2.buffer,
// (result$2.s0.x$2.__block_id_x + result$2.min.0),
// (result$2.s0.y$2.__block_id_y + result$2.min.1),
// result$2.s0.c$2,
// image_load("input",
// input.buffer,
// ((result$2.s0.x$2.__block_id_x + result$2.min.0) - input.min.0),
// input.extent.0,
// ((result$2.s0.y$2.__block_id_y + result$2.min.1) - input.min.1),
// input.extent.1,
// result$2.s0.c$2,
// 4))
// }
// }
// ...
// }
// }
//
using IRMutator::visit;
virtual void visit(const Call *call) {
if (in_pipeline && call->call_type == Call::CallType::Intrinsic && call->name == Call::image_store) {
assert(for_nest_level == 4);
std::map<std::string, Expr> matches;
assert(expr_match(
StringImm::make("result"),
call->args[0],
matches));
assert(expr_match(
Variable::make(Handle(1), "result.buffer"),
call->args[1],
matches));
assert(expr_match(
Variable::make(Int(32), "result.s0.x.__block_id_x") + Variable::make(Int(32), "result.min.0"),
call->args[2],
matches));
assert(expr_match(
Variable::make(Int(32), "result.s0.y.__block_id_y") + Variable::make(Int(32), "result.min.1"),
call->args[3],
matches));
assert(expr_match(
Variable::make(Int(32), "result.s0.c"),
call->args[4],
matches));
assert(expr_match(
Call::make(
UInt(8),
Call::image_load,
{
StringImm::make("input"),
Variable::make(Handle(1), "input.buffer"),
(Variable::make(Int(32), "result.s0.x.__block_id_x") +
Variable::make(Int(32), "result.min.0")) -
Variable::make(Int(32), "input.min.0"),
Variable::make(Int(32), "input.extent.0"),
(Variable::make(Int(32), "result.s0.y.__block_id_y") +
Variable::make(Int(32), "result.min.1")) -
Variable::make(Int(32), "input.min.1"),
Variable::make(Int(32), "input.extent.1"),
Variable::make(Int(32), "result.s0.c"),
IntImm::make(channels)
},
Call::CallType::Intrinsic),
call->args[5],
matches));
}
IRMutator::visit(call);
}
void visit(const For *op) {
if (in_pipeline) {
assert(for_nest_level >= 0); // For-loop should show up in Pipeline.
for_nest_level++;
if (for_nest_level <= 3) {
assert(op->for_type == ForType::Parallel);
}
assert(op->device_api == DeviceAPI::Renderscript);
}
IRMutator::visit(op);
}
void visit(const ProducerConsumer *op) {
assert(!in_pipeline); // There should be only one pipeline in the test.
for_nest_level = 0;
in_pipeline = true;
assert(op->produce.defined());
assert(!op->update.defined());
assert(op->consume.defined());
IRMutator::visit(op);
stmt = Stmt();
}
int for_nest_level = -1;
bool in_pipeline = false;
int channels;
public:
ValidateInterleavedPipeline(int _channels) : channels(_channels) {}
};
class ValidateInterleavedVectorizedPipeline: public ValidateInterleavedPipeline {
using IRMutator::visit;
using ValidateInterleavedPipeline::visit;
virtual void visit(const Call *call) {
if (in_pipeline && call->call_type == Call::CallType::Intrinsic && call->name == Call::image_store) {
assert(for_nest_level == 3); // Should be three nested for-loops before we get to the first call.
std::map<std::string, Expr> matches;
assert(expr_match(
Broadcast::make(StringImm::make("result"), channels),
call->args[0],
matches));
assert(expr_match(
Broadcast::make(Variable::make(Handle(1), "result.buffer"), channels),
call->args[1],
matches));
assert(expr_match(
Broadcast::make(Variable::make(Int(32), "result.s0.x.__block_id_x") + Variable::make(Int(32), "result.min.0"), channels),
call->args[2],
matches));
assert(expr_match(
Broadcast::make(Variable::make(Int(32), "result.s0.y.__block_id_y") + Variable::make(Int(32), "result.min.1"), channels),
call->args[3],
matches));
assert(expr_match(
Ramp::make(0, 1, channels), call->args[4], matches));
assert(expr_match(
Call::make(
UInt(8, channels),
Call::image_load,
{
Broadcast::make(StringImm::make("input"), channels),
Broadcast::make(Variable::make(Handle(1), "input.buffer"), channels),
Broadcast::make(
Add::make(
Variable::make(Int(32), "result.s0.x.__block_id_x"),
Variable::make(Int(32), "result.min.0")) -
Variable::make(Int(32), "input.min.0"),
channels),
Broadcast::make(Variable::make(Int(32), "input.extent.0"), channels),
Broadcast::make(
Add::make(
Variable::make(Int(32), "result.s0.y.__block_id_y"),
Variable::make(Int(32), "result.min.1")) -
Variable::make(Int(32), "input.min.1"),
channels),
Broadcast::make(Variable::make(Int(32), "input.extent.1"), channels),
Ramp::make(0, 1, channels),
Broadcast::make(IntImm::make(channels), channels)
},
Call::CallType::Intrinsic),
call->args[5],
matches));
}
IRMutator::visit(call);
}
public:
ValidateInterleavedVectorizedPipeline(int _channels) : ValidateInterleavedPipeline(_channels) {}
};
Image<uint8_t> make_interleaved_image(uint8_t *host, int W, int H, int channels) {
buffer_t buf = { 0 };
buf.host = host;
buf.extent[0] = W;
buf.stride[0] = channels;
buf.extent[1] = H;
buf.stride[1] = buf.stride[0] * buf.extent[0];
buf.extent[2] = channels;
buf.stride[2] = 1;
buf.elem_size = 1;
return Image<uint8_t>(&buf);
}
void copy_interleaved(bool vectorized = false, int channels = 4) {
ImageParam input8(UInt(8), 3, "input");
input8.set_stride(0, channels)
.set_stride(1, Halide::Expr())
.set_stride(2, 1)
.set_bounds(2, 0, channels); // expecting interleaved image
uint8_t *in_buf = new uint8_t[128 * 128 * channels];
uint8_t *out_buf = new uint8_t[128 * 128 * channels];
Image<uint8_t> in = make_interleaved_image(in_buf, 128, 128, channels);
Image<uint8_t> out = make_interleaved_image(out_buf, 128, 128, channels);
input8.set(in);
Var x, y, c;
Func result("result");
result(x, y, c) = input8(x, y, c);
result.output_buffer()
.set_stride(0, channels)
.set_stride(1, Halide::Expr())
.set_stride(2, 1)
.set_bounds(2, 0, channels); // expecting interleaved image
result.bound(c, 0, channels);
result.shader(x, y, c, DeviceAPI::Renderscript);
if (vectorized) result.vectorize(c);
result.add_custom_lowering_pass(
vectorized?
new ValidateInterleavedVectorizedPipeline(channels):
new ValidateInterleavedPipeline(channels));
result.realize(out);
delete[] in_buf;
delete[] out_buf;
}
int main(int argc, char **argv) {
copy_interleaved(true, 4);
copy_interleaved(false, 4);
copy_interleaved(true, 3);
copy_interleaved(false, 3);
std::cout << "Done!" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBinaryMinMaxCurvatureFlowImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkBinaryMinMaxCurvatureFlowImageFilter.h"
#include "itkOutputWindow.h"
#include "itkCommand.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "vnl/vnl_math.h"
#include "vnl/vnl_sample.h"
#include "vcl_ctime.h"
// The following class is used to support callbacks
// on the filter in the pipeline that follows later
namespace
{class ShowProgressObject
{
public:
ShowProgressObject(itk::ProcessObject* o)
{m_Process = o;}
void ShowProgress()
{std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
itk::ProcessObject::Pointer m_Process;
};
}
#define MAXRUNS 5 // maximum number of runs
template<unsigned int VImageDimension>
int testBinaryMinMaxCurvatureFlow(
itk::Size<VImageDimension> & size,
double threshold,
double radius,
int numberOfRuns,
unsigned int niter[],
unsigned long radii[] );
/**
* This file tests the functionality of the BinaryMinMaxCurvatureFlowImageFilter.
* The test uses a binary image of a circle/sphere with intensity value
* of 0 (black). The background is white ( intensity = 255 ).
* X% salt and pepper noise is added to the the input image. Specifically,
* X% of the pixels is replaced with a value choosen from a uniform
* distribution between 0 and 255.
*
* We then test the ability of BinaryMinMaxCurvatureFlowImageFilter to denoise
* the binary image.
*/
int itkBinaryMinMaxCurvatureFlowImageFilterTest(int, char* [] )
{
double radius;
int numberOfRuns;
unsigned int niter[MAXRUNS];
unsigned long radii[MAXRUNS];
itk::Size<2> size2D;
size2D[0] = 64; size2D[1] = 64;
radius = 20.0;
numberOfRuns = 2;
niter[0] = 100; niter[1] = 100;
radii[0] = 1; radii[1] = 3;
int err2D = testBinaryMinMaxCurvatureFlow( size2D, 127.5, radius, numberOfRuns,
niter, radii );
if ( err2D )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
template<unsigned int VImageDimension>
int testBinaryMinMaxCurvatureFlow(
itk::Size<VImageDimension> & size, // ND image size
double threshold,
double radius, // ND-sphere radius
int numberOfRuns, // number of times to run the filter
unsigned int niter[], // number of iterations
unsigned long radii[] // stencil radius
)
{
typedef float PixelType;
enum { ImageDimension = VImageDimension };
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::ImageRegionIterator<ImageType> IteratorType;
typedef itk::BinaryMinMaxCurvatureFlowImageFilter<ImageType,ImageType> DenoiserType;
typename DenoiserType::Pointer denoiser = DenoiserType::New();
int j;
/**
* Create an image containing a circle/sphere with intensity of 0
* and background of 255 with added salt and pepper noise.
*/
double sqrRadius = vnl_math_sqr( radius ); // radius of the circle/sphere
double fractionNoise = 0.30; // salt & pepper noise fraction
PixelType foreground = 0.0; // intensity value of the foreground
PixelType background = 255.0; // intensity value of the background
std::cout << "Create an image of circle/sphere with noise" << std::endl;
typename ImageType::Pointer circleImage = ImageType::New();
typename ImageType::RegionType region;
region.SetSize( size );
circleImage->SetLargestPossibleRegion( region );
circleImage->SetBufferedRegion( region );
circleImage->Allocate();
IteratorType circleIter( circleImage, circleImage->GetBufferedRegion() );
for ( ; !circleIter.IsAtEnd() ; ++circleIter )
{
typename ImageType::IndexType index = circleIter.GetIndex();
float value;
double lhs = 0.0;
for ( j = 0; j < ImageDimension; j++ )
{
lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 );
}
if ( lhs < sqrRadius )
{
value = foreground;
}
else
{
value = background;
}
if ( vnl_sample_uniform( 0.0, 1.0 ) < fractionNoise )
{
value = vnl_sample_uniform( vnl_math_min(foreground,background),
vnl_math_max(foreground,background) );
}
circleIter.Set( value );
}
/**
* Run MinMaxCurvatureFlowImageFilter several times using the previous
* output as the input in the next run.
*/
std::cout << "Run BinaryMinMaxCurvatureFlowImageFiler.." << std::endl;
// set other denoiser parameters here
denoiser->SetTimeStep( 0.05 );
denoiser->SetThreshold( threshold );
// attach a progress watcher to the denoiser
ShowProgressObject progressWatch(denoiser);
itk::SimpleMemberCommand<ShowProgressObject>::Pointer command;
command = itk::SimpleMemberCommand<ShowProgressObject>::New();
command->SetCallbackFunction(&progressWatch,
&ShowProgressObject::ShowProgress);
denoiser->AddObserver( itk::ProgressEvent(), command);
typename ImageType::Pointer swapPointer = circleImage;
for ( int j = 0; j < numberOfRuns; j++ )
{
denoiser->SetInput( swapPointer );
// set the stencil radius and number of iterations
denoiser->SetStencilRadius( radii[j] );
denoiser->SetNumberOfIterations( niter[j] );
std::cout << " Run: " << j;
std::cout << " Radius: " << denoiser->GetStencilRadius();
std::cout << " Iter: " << denoiser->GetNumberOfIterations();
std::cout << std::endl;
// run the filter
denoiser->Update();
swapPointer = denoiser->GetOutput();
swapPointer->DisconnectPipeline();
}
/**
* Check the quality of the output by comparing it against a
* clean image of the circle/sphere.
* An output pixel is okay if it is within
* 0.1 * |foreground - background| of the true value.
* This test is considered as passed if the fraction of wrong
* pixels is less than the original noise fraction.
*/
std::cout << "Checking the output..." << std::endl;
IteratorType outIter( swapPointer,
swapPointer->GetBufferedRegion() );
PixelType tolerance = vnl_math_abs( foreground - background ) * 0.1;
unsigned long numPixelsWrong = 0;
for ( ; !outIter.IsAtEnd(); ++outIter )
{
typename ImageType::IndexType index = outIter.GetIndex();
PixelType value = outIter.Get();
double lhs = 0.0;
for ( j = 0; j < ImageDimension; j++ )
{
lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 );
}
if ( lhs < sqrRadius )
{
if ( vnl_math_abs( foreground - value ) > tolerance )
{
numPixelsWrong++;
}
}
else if ( vnl_math_abs( background - value ) > tolerance )
{
numPixelsWrong++;
}
}
double fractionWrong = (double) numPixelsWrong /
(double) region.GetNumberOfPixels();
std::cout << "Noise reduced from " << fractionNoise << " to ";
std::cout << fractionWrong << std::endl;
bool passed = true;
if ( fractionWrong > fractionNoise )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
/**
* Exercise other member functions here
*/
denoiser->Print( std::cout );
std::cout << "GetThreshold: " << denoiser->GetThreshold() << std::endl;
/**
* Exercise error handling
*/
typedef itk::CurvatureFlowFunction<ImageType> WrongFunctionType;
typename WrongFunctionType::Pointer wrongFunction = WrongFunctionType::New();
passed = false;
try
{
denoiser->SetDifferenceFunction( wrongFunction );
denoiser->Update();
}
catch( itk::ExceptionObject& err )
{
passed = true;
std::cout << "Caught expected exception." << std::endl;
std::cout << err << std::endl;
}
if ( !passed )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>BUG: If CYGWIN call vnl_sample_reseed<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBinaryMinMaxCurvatureFlowImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkBinaryMinMaxCurvatureFlowImageFilter.h"
#include "itkOutputWindow.h"
#include "itkCommand.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "vnl/vnl_math.h"
#include "vnl/vnl_sample.h"
#include "vcl_ctime.h"
// The following class is used to support callbacks
// on the filter in the pipeline that follows later
namespace
{class ShowProgressObject
{
public:
ShowProgressObject(itk::ProcessObject* o)
{m_Process = o;}
void ShowProgress()
{std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
itk::ProcessObject::Pointer m_Process;
};
}
#define MAXRUNS 5 // maximum number of runs
template<unsigned int VImageDimension>
int testBinaryMinMaxCurvatureFlow(
itk::Size<VImageDimension> & size,
double threshold,
double radius,
int numberOfRuns,
unsigned int niter[],
unsigned long radii[] );
/**
* This file tests the functionality of the BinaryMinMaxCurvatureFlowImageFilter.
* The test uses a binary image of a circle/sphere with intensity value
* of 0 (black). The background is white ( intensity = 255 ).
* X% salt and pepper noise is added to the the input image. Specifically,
* X% of the pixels is replaced with a value choosen from a uniform
* distribution between 0 and 255.
*
* We then test the ability of BinaryMinMaxCurvatureFlowImageFilter to denoise
* the binary image.
*/
int itkBinaryMinMaxCurvatureFlowImageFilterTest(int, char* [] )
{
double radius;
int numberOfRuns;
unsigned int niter[MAXRUNS];
unsigned long radii[MAXRUNS];
itk::Size<2> size2D;
size2D[0] = 64; size2D[1] = 64;
radius = 20.0;
numberOfRuns = 2;
niter[0] = 100; niter[1] = 100;
radii[0] = 1; radii[1] = 3;
#if __CYGWIN__
vnl_sample_reseed(0x1234abcd);
#endif
int err2D = testBinaryMinMaxCurvatureFlow( size2D, 127.5, radius, numberOfRuns,
niter, radii );
if ( err2D )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
template<unsigned int VImageDimension>
int testBinaryMinMaxCurvatureFlow(
itk::Size<VImageDimension> & size, // ND image size
double threshold,
double radius, // ND-sphere radius
int numberOfRuns, // number of times to run the filter
unsigned int niter[], // number of iterations
unsigned long radii[] // stencil radius
)
{
typedef float PixelType;
enum { ImageDimension = VImageDimension };
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::ImageRegionIterator<ImageType> IteratorType;
typedef itk::BinaryMinMaxCurvatureFlowImageFilter<ImageType,ImageType> DenoiserType;
typename DenoiserType::Pointer denoiser = DenoiserType::New();
int j;
/**
* Create an image containing a circle/sphere with intensity of 0
* and background of 255 with added salt and pepper noise.
*/
double sqrRadius = vnl_math_sqr( radius ); // radius of the circle/sphere
double fractionNoise = 0.30; // salt & pepper noise fraction
PixelType foreground = 0.0; // intensity value of the foreground
PixelType background = 255.0; // intensity value of the background
std::cout << "Create an image of circle/sphere with noise" << std::endl;
typename ImageType::Pointer circleImage = ImageType::New();
typename ImageType::RegionType region;
region.SetSize( size );
circleImage->SetLargestPossibleRegion( region );
circleImage->SetBufferedRegion( region );
circleImage->Allocate();
IteratorType circleIter( circleImage, circleImage->GetBufferedRegion() );
for ( ; !circleIter.IsAtEnd() ; ++circleIter )
{
typename ImageType::IndexType index = circleIter.GetIndex();
float value;
double lhs = 0.0;
for ( j = 0; j < ImageDimension; j++ )
{
lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 );
}
if ( lhs < sqrRadius )
{
value = foreground;
}
else
{
value = background;
}
if ( vnl_sample_uniform( 0.0, 1.0 ) < fractionNoise )
{
value = vnl_sample_uniform( vnl_math_min(foreground,background),
vnl_math_max(foreground,background) );
}
circleIter.Set( value );
}
/**
* Run MinMaxCurvatureFlowImageFilter several times using the previous
* output as the input in the next run.
*/
std::cout << "Run BinaryMinMaxCurvatureFlowImageFiler.." << std::endl;
// set other denoiser parameters here
denoiser->SetTimeStep( 0.05 );
denoiser->SetThreshold( threshold );
// attach a progress watcher to the denoiser
ShowProgressObject progressWatch(denoiser);
itk::SimpleMemberCommand<ShowProgressObject>::Pointer command;
command = itk::SimpleMemberCommand<ShowProgressObject>::New();
command->SetCallbackFunction(&progressWatch,
&ShowProgressObject::ShowProgress);
denoiser->AddObserver( itk::ProgressEvent(), command);
typename ImageType::Pointer swapPointer = circleImage;
for ( int j = 0; j < numberOfRuns; j++ )
{
denoiser->SetInput( swapPointer );
// set the stencil radius and number of iterations
denoiser->SetStencilRadius( radii[j] );
denoiser->SetNumberOfIterations( niter[j] );
std::cout << " Run: " << j;
std::cout << " Radius: " << denoiser->GetStencilRadius();
std::cout << " Iter: " << denoiser->GetNumberOfIterations();
std::cout << std::endl;
// run the filter
denoiser->Update();
swapPointer = denoiser->GetOutput();
swapPointer->DisconnectPipeline();
}
/**
* Check the quality of the output by comparing it against a
* clean image of the circle/sphere.
* An output pixel is okay if it is within
* 0.1 * |foreground - background| of the true value.
* This test is considered as passed if the fraction of wrong
* pixels is less than the original noise fraction.
*/
std::cout << "Checking the output..." << std::endl;
IteratorType outIter( swapPointer,
swapPointer->GetBufferedRegion() );
PixelType tolerance = vnl_math_abs( foreground - background ) * 0.1;
unsigned long numPixelsWrong = 0;
for ( ; !outIter.IsAtEnd(); ++outIter )
{
typename ImageType::IndexType index = outIter.GetIndex();
PixelType value = outIter.Get();
double lhs = 0.0;
for ( j = 0; j < ImageDimension; j++ )
{
lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 );
}
if ( lhs < sqrRadius )
{
if ( vnl_math_abs( foreground - value ) > tolerance )
{
numPixelsWrong++;
}
}
else if ( vnl_math_abs( background - value ) > tolerance )
{
numPixelsWrong++;
}
}
double fractionWrong = (double) numPixelsWrong /
(double) region.GetNumberOfPixels();
std::cout << "Noise reduced from " << fractionNoise << " to ";
std::cout << fractionWrong << std::endl;
bool passed = true;
if ( fractionWrong > fractionNoise )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
/**
* Exercise other member functions here
*/
denoiser->Print( std::cout );
std::cout << "GetThreshold: " << denoiser->GetThreshold() << std::endl;
/**
* Exercise error handling
*/
typedef itk::CurvatureFlowFunction<ImageType> WrongFunctionType;
typename WrongFunctionType::Pointer wrongFunction = WrongFunctionType::New();
passed = false;
try
{
denoiser->SetDifferenceFunction( wrongFunction );
denoiser->Update();
}
catch( itk::ExceptionObject& err )
{
passed = true;
std::cout << "Caught expected exception." << std::endl;
std::cout << err << std::endl;
}
if ( !passed )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ToolRunner.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LLVMContext.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/StandardPasses.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Valgrind.h"
#include "llvm/LinkAllVMCore.h"
using namespace llvm;
static cl::opt<bool>
FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
"on program to find bugs"), cl::init(false));
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input llvm ll/bc files>"));
static cl::opt<unsigned>
TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
cl::desc("Number of seconds program is allowed to run before it "
"is killed (default is 300s), 0 disables timeout"));
static cl::opt<int>
MemoryLimit("mlimit", cl::init(-1), cl::value_desc("MBytes"),
cl::desc("Maximum amount of memory to use. 0 disables check."
" Defaults to 100MB (800MB under valgrind)."));
static cl::opt<bool>
UseValgrind("enable-valgrind",
cl::desc("Run optimizations through valgrind"));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);
static cl::opt<bool>
StandardCompileOpts("std-compile-opts",
cl::desc("Include the standard compile time optimizations"));
static cl::opt<bool>
StandardLinkOpts("std-link-opts",
cl::desc("Include the standard link time optimizations"));
static cl::opt<std::string>
OverrideTriple("mtriple", cl::desc("Override target triple for module"));
/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
bool llvm::BugpointIsInterrupted = false;
static void BugpointInterruptFunction() {
BugpointIsInterrupted = true;
}
// Hack to capture a pass list.
namespace {
class AddToDriver : public PassManager {
BugDriver &D;
public:
AddToDriver(BugDriver &_D) : D(_D) {}
virtual void add(Pass *P) {
const void *ID = P->getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
D.addPass(PI->getPassArgument());
}
};
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize passes
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeIPA(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
cl::ParseCommandLineOptions(argc, argv,
"LLVM automatic testcase reducer. See\nhttp://"
"llvm.org/cmds/bugpoint.html"
" for more information.\n");
sys::SetInterruptFunction(BugpointInterruptFunction);
LLVMContext& Context = getGlobalContext();
// If we have an override, set it and then track the triple we want Modules
// to use.
if (!OverrideTriple.empty()) {
TargetTriple.setTriple(Triple::normalize(OverrideTriple));
outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
}
if (MemoryLimit < 0) {
// Set the default MemoryLimit. Be sure to update the flag's description if
// you change this.
if (sys::RunningOnValgrind() || UseValgrind)
MemoryLimit = 800;
else
MemoryLimit = 100;
}
BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit,
UseValgrind, Context);
if (D.addSources(InputFilenames)) return 1;
AddToDriver PM(D);
if (StandardCompileOpts) {
createStandardModulePasses(&PM, 3,
/*OptimizeSize=*/ false,
/*UnitAtATime=*/ true,
/*UnrollLoops=*/ true,
/*SimplifyLibCalls=*/ true,
/*HaveExceptions=*/ true,
createFunctionInliningPass());
}
if (StandardLinkOpts)
createStandardLTOPasses(&PM, /*Internalize=*/true,
/*RunInliner=*/true,
/*VerifyEach=*/false);
for (std::vector<const PassInfo*>::iterator I = PassList.begin(),
E = PassList.end();
I != E; ++I) {
const PassInfo* PI = *I;
D.addPass(PI->getPassArgument());
}
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, we prevent it
sys::Process::PreventCoreFiles();
std::string Error;
bool Failure = D.run(Error);
if (!Error.empty()) {
errs() << Error;
return 1;
}
return Failure;
}
<commit_msg>Little help to debug the bugpoint itself. Patch by Bob Wilson.<commit_after>//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ToolRunner.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LLVMContext.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/StandardPasses.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Valgrind.h"
#include "llvm/LinkAllVMCore.h"
// Enable this macro to debug bugpoint itself.
#define DEBUG_BUGPOINT 0
using namespace llvm;
static cl::opt<bool>
FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
"on program to find bugs"), cl::init(false));
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input llvm ll/bc files>"));
static cl::opt<unsigned>
TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
cl::desc("Number of seconds program is allowed to run before it "
"is killed (default is 300s), 0 disables timeout"));
static cl::opt<int>
MemoryLimit("mlimit", cl::init(-1), cl::value_desc("MBytes"),
cl::desc("Maximum amount of memory to use. 0 disables check."
" Defaults to 100MB (800MB under valgrind)."));
static cl::opt<bool>
UseValgrind("enable-valgrind",
cl::desc("Run optimizations through valgrind"));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);
static cl::opt<bool>
StandardCompileOpts("std-compile-opts",
cl::desc("Include the standard compile time optimizations"));
static cl::opt<bool>
StandardLinkOpts("std-link-opts",
cl::desc("Include the standard link time optimizations"));
static cl::opt<std::string>
OverrideTriple("mtriple", cl::desc("Override target triple for module"));
/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
bool llvm::BugpointIsInterrupted = false;
#ifndef DEBUG_BUGPOINT
static void BugpointInterruptFunction() {
BugpointIsInterrupted = true;
}
#endif
// Hack to capture a pass list.
namespace {
class AddToDriver : public PassManager {
BugDriver &D;
public:
AddToDriver(BugDriver &_D) : D(_D) {}
virtual void add(Pass *P) {
const void *ID = P->getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
D.addPass(PI->getPassArgument());
}
};
}
int main(int argc, char **argv) {
#ifndef DEBUG_BUGPOINT
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
#endif
// Initialize passes
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeIPA(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
cl::ParseCommandLineOptions(argc, argv,
"LLVM automatic testcase reducer. See\nhttp://"
"llvm.org/cmds/bugpoint.html"
" for more information.\n");
#ifndef DEBUG_BUGPOINT
sys::SetInterruptFunction(BugpointInterruptFunction);
#endif
LLVMContext& Context = getGlobalContext();
// If we have an override, set it and then track the triple we want Modules
// to use.
if (!OverrideTriple.empty()) {
TargetTriple.setTriple(Triple::normalize(OverrideTriple));
outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
}
if (MemoryLimit < 0) {
// Set the default MemoryLimit. Be sure to update the flag's description if
// you change this.
if (sys::RunningOnValgrind() || UseValgrind)
MemoryLimit = 800;
else
MemoryLimit = 100;
}
BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit,
UseValgrind, Context);
if (D.addSources(InputFilenames)) return 1;
AddToDriver PM(D);
if (StandardCompileOpts) {
createStandardModulePasses(&PM, 3,
/*OptimizeSize=*/ false,
/*UnitAtATime=*/ true,
/*UnrollLoops=*/ true,
/*SimplifyLibCalls=*/ true,
/*HaveExceptions=*/ true,
createFunctionInliningPass());
}
if (StandardLinkOpts)
createStandardLTOPasses(&PM, /*Internalize=*/true,
/*RunInliner=*/true,
/*VerifyEach=*/false);
for (std::vector<const PassInfo*>::iterator I = PassList.begin(),
E = PassList.end();
I != E; ++I) {
const PassInfo* PI = *I;
D.addPass(PI->getPassArgument());
}
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, we prevent it
#ifndef DEBUG_BUGPOINT
sys::Process::PreventCoreFiles();
#endif
std::string Error;
bool Failure = D.run(Error);
if (!Error.empty()) {
errs() << Error;
return 1;
}
return Failure;
}
<|endoftext|> |
<commit_before>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <bts/app/api.hpp>
#include <bts/chain/address.hpp>
#include <bts/utilities/key_conversion.hpp>
using namespace bts::app;
using namespace bts::chain;
using namespace bts::utilities;
using namespace std;
struct wallet_data
{
flat_set<account_id_type> accounts;
// map of key_id -> base58 private key
map<key_id_type, string> keys;
// map of account_name -> base58_private_key for
// incomplete account regs
map<string, string> pending_account_registrations;
string ws_server = "ws://localhost:8090";
string ws_user;
string ws_password;
};
FC_REFLECT( wallet_data, (accounts)(keys)(pending_account_registrations)(ws_server)(ws_user)(ws_password) );
/**
* This wallet assumes nothing about where the database server is
* located and performs minimal caching. This API could be provided
* locally to be used by a web interface.
*/
class wallet_api
{
public:
wallet_api( fc::api<login_api> rapi )
:_remote_api(rapi)
{
_remote_db = _remote_api->database();
_remote_net = _remote_api->network();
}
string help()const;
string suggest_brain_key()const
{
return string("dummy");
}
variant get_object( object_id_type id )
{
return _remote_db->get_objects({id});
}
account_object get_account( string account_name_or_id )
{
FC_ASSERT( account_name_or_id.size() > 0 );
vector<optional<account_object>> opt_account;
if( std::isdigit( account_name_or_id.front() ) )
opt_account = _remote_db->get_accounts( {fc::variant(account_name_or_id).as<account_id_type>()} );
else
opt_account = _remote_db->lookup_account_names( {account_name_or_id} );
FC_ASSERT( opt_account.size() && opt_account.front() );
return *opt_account.front();
}
bool import_key( string account_name_or_id, string wif_key )
{
auto opt_priv_key = wif_to_key(wif_key);
FC_ASSERT( opt_priv_key.valid() );
bts::chain::address wif_key_address = bts::chain::address(
opt_priv_key->get_public_key() );
auto acnt = get_account( account_name_or_id );
flat_set<key_id_type> keys;
for( auto item : acnt.active.auths )
{
if( item.first.type() == key_object_type )
keys.insert( item.first );
}
for( auto item : acnt.owner.auths )
{
if( item.first.type() == key_object_type )
keys.insert( item.first );
}
auto opt_keys = _remote_db->get_keys( vector<key_id_type>(keys.begin(),keys.end()) );
for( const fc::optional<key_object>& opt_key : opt_keys )
{
// the requested key ID's should all exist because they are
// keys for an account
FC_ASSERT( opt_key.valid() );
// we do this check by address because key objects on the
// blockchain may not contain a key (i.e. are simply an address)
if( opt_key->key_address() == wif_key_address )
{
_wallet.keys[ opt_key->id ] = wif_key;
return true;
}
}
ilog( "key not for account ${name}", ("name",account_name_or_id) );
return false;
}
string normalize_brain_key( string s )
{
size_t i = 0, n = s.length();
std::string result;
char c;
result.reserve( n );
bool preceded_by_whitespace = false;
bool non_empty = false;
while( i < n )
{
c = s[i++];
switch( c )
{
case ' ': case '\t': case '\r': case '\n': case '\v': case '\f':
preceded_by_whitespace = true;
continue;
case 'a': c = 'A'; break;
case 'b': c = 'B'; break;
case 'c': c = 'C'; break;
case 'd': c = 'D'; break;
case 'e': c = 'E'; break;
case 'f': c = 'F'; break;
case 'g': c = 'G'; break;
case 'h': c = 'H'; break;
case 'i': c = 'I'; break;
case 'j': c = 'J'; break;
case 'k': c = 'K'; break;
case 'l': c = 'L'; break;
case 'm': c = 'M'; break;
case 'n': c = 'N'; break;
case 'o': c = 'O'; break;
case 'p': c = 'P'; break;
case 'q': c = 'Q'; break;
case 'r': c = 'R'; break;
case 's': c = 'S'; break;
case 't': c = 'T'; break;
case 'u': c = 'U'; break;
case 'v': c = 'V'; break;
case 'w': c = 'W'; break;
case 'x': c = 'X'; break;
case 'y': c = 'Y'; break;
case 'z': c = 'Z'; break;
default:
break;
}
if( preceded_by_whitespace && non_empty )
result.push_back(' ');
result.push_back(c);
preceded_by_whitespace = false;
non_empty = true;
}
return result;
}
fc::ecc::private_key derive_private_key(
const std::string& prefix_string, int sequence_number)
{
std::string sequence_string = std::to_string(sequence_number);
fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string);
fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h));
return derived_key;
}
signed_transaction create_account_with_brain_key(
string brain_key,
string account_name,
string registrar_account,
string referrer_account,
uint8_t referrer_percent
)
{
string normalized_brain_key = normalize_brain_key( brain_key );
// TODO: scan blockchain for accounts that exist with same brain key
fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 );
fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), 0);
bts::chain::public_key_type owner_pubkey = owner_privkey.get_public_key();
bts::chain::public_key_type active_pubkey = active_privkey.get_public_key();
account_create_operation account_create_op;
// TODO: process when pay_from_account is ID
account_object registrar_account_object =
this->get_account( registrar_account );
account_id_type registrar_account_id = registrar_account_object.id;
if( referrer_percent > 0 )
{
account_object referrer_account_object =
this->get_account( referrer_account );
account_create_op.referrer = referrer_account_object.id;
account_create_op.referrer_percent = referrer_percent;
}
// get pay_from_account_id
key_create_operation owner_key_create_op;
owner_key_create_op.fee_paying_account = registrar_account_id;
owner_key_create_op.key_data = owner_pubkey;
key_create_operation active_key_create_op;
active_key_create_op.fee_paying_account = registrar_account_id;
active_key_create_op.key_data = active_pubkey;
// key_create_op.calculate_fee(db.current_fee_schedule());
// TODO: Check if keys already exist!!!
account_create_operation account_create_op;
vector<string> v_pay_from_account;
v_pay_from_account.push_back( pay_from_account );
account_create_op.registrar = pay_from_account_id;
relative_key_id_type owner_rkid(0);
relative_key_id_type active_rkid(1);
account_create_op.registrar = registrar_account_id;
account_create_op.name = account_name;
account_create_op.owner = authority(1, owner_rkid, 1);
account_create_op.active = authority(1, active_rkid, 1);
account_create_op.memo_key = active_rkid;
account_create_op.voting_key = active_rkid;
account_create_op.vote = flat_set<vote_tally_id_type>();
// current_fee_schedule()
// find_account(pay_from_account)
// account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule());
signed_transaction tx;
tx.operations.push_back( owner_key_create_op );
tx.operations.push_back( active_key_create_op );
tx.operations.push_back( account_create_op );
tx.visit( operation_set_fee( _remote_db->get_global_properties().parameters.current_fees ) );
vector<key_id_type> paying_keys = registrar_account_object.active.get_keys();
tx.validate();
for( key_id_type& key : paying_keys )
{
auto it = _wallet.keys.find(key);
if( it != _wallet.keys.end() )
{
fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second );
if( !privkey.valid() )
{
FC_ASSERT( false, "Malformed private key in _wallet.keys" );
}
tx.sign( *privkey );
}
}
// we do not insert owner_privkey here because
// it is intended to only be used for key recovery
_wallet.pending_account_registrations[ account_name ] = key_to_wif( active_privkey );
return tx;
}
signed_transaction transfer( string from,
string to,
uint64_t amount,
string asset_symbol,
string memo,
bool broadcast = false )
{
auto opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol} );
wdump( (opt_asset) );
return signed_transaction();
}
// methods that start with underscore are not incuded in API
void _resync()
{
// this method is used to update wallet_data annotations
// e.g. wallet has been restarted and was not notified
// of events while it was down
//
// everything that is done "incremental style" when a push
// notification is received, should also be done here
// "batch style" by querying the blockchain
if( _wallet.pending_account_registrations.size() > 0 )
{
std::vector<string> v_names;
v_names.reserve( _wallet.pending_account_registrations.size() );
for( auto it : _wallet.pending_account_registrations )
v_names.push_back( it.first );
std::vector< fc::optional< bts::chain::account_object >>
v_accounts = _remote_db->lookup_account_names( v_names );
for( fc::optional< bts::chain::account_object > opt_account : v_accounts )
{
if( ! opt_account.valid() )
continue;
string account_name = opt_account->name;
auto it = _wallet.pending_account_registrations.find( account_name );
FC_ASSERT( it != _wallet.pending_account_registrations.end() );
if( import_key( account_name, it->second ) )
{
// somebody else beat our pending registration, there is
// nothing we can do except log it and move on
ilog( "account ${name} registered by someone else first!",
("name", account_name) );
// might as well remove it from pending regs,
// because there is now no way this registration
// can become valid (even in the extremely rare
// possibility of migrating to a fork where the
// name is available, the user can always
// manually re-register)
}
_wallet.pending_account_registrations.erase( it );
}
}
return;
}
wallet_data _wallet;
fc::api<login_api> _remote_api;
fc::api<database_api> _remote_db;
fc::api<network_api> _remote_net;
};
FC_API( wallet_api,
(help)
(import_key)
(suggest_brain_key)
(create_account_with_brain_key)
(transfer)
(get_account)
(get_object)
(normalize_brain_key)
)
struct help_visitor
{
help_visitor( std::stringstream& s ):ss(s){}
std::stringstream& ss;
template<typename R, typename... Args>
void operator()( const char* name, std::function<R(Args...)>& memb )const {
ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "( ";
vector<string> args{ fc::get_typename<Args>::name()... };
for( uint32_t i = 0; i < args.size(); ++i )
ss << args[i] << (i==args.size()-1?" ":", ");
ss << ")\n";
}
};
string wallet_api::help()const
{
fc::api<wallet_api> tmp;
std::stringstream ss;
tmp->visit( help_visitor(ss) );
return ss.str();
}
int main( int argc, char** argv )
{
try {
FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) );
fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis")));
idump( (key_to_wif( genesis_private_key ) ) );
idump( (account_id_type()) );
wallet_data wallet;
fc::path wallet_file(argv[1]);
if( fc::exists( wallet_file ) )
wallet = fc::json::from_file( wallet_file ).as<wallet_data>();
fc::http::websocket_client client;
auto con = client.connect( wallet.ws_server );
auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);
con->closed.connect( [&](){ elog( "connection closed" ); } );
auto remote_api = apic->get_remote_api< login_api >();
FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) );
auto wapiptr = std::make_shared<wallet_api>(remote_api);
wapiptr->_wallet = wallet;
fc::api<wallet_api> wapi(wapiptr);
auto wallet_cli = std::make_shared<fc::rpc::cli>();
wallet_cli->format_result( "help", [&]( variant result, const fc::variants& a) {
return result.get_string();
});
wallet_cli->register_api( wapi );
wallet_cli->start();
wallet_cli->wait();
}
catch ( const fc::exception& e )
{
std::cout << e.to_detail_string() << "\n";
}
return -1;
}
<commit_msg>remove vestigial code, it should compile now<commit_after>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <bts/app/api.hpp>
#include <bts/chain/address.hpp>
#include <bts/utilities/key_conversion.hpp>
using namespace bts::app;
using namespace bts::chain;
using namespace bts::utilities;
using namespace std;
struct wallet_data
{
flat_set<account_id_type> accounts;
// map of key_id -> base58 private key
map<key_id_type, string> keys;
// map of account_name -> base58_private_key for
// incomplete account regs
map<string, string> pending_account_registrations;
string ws_server = "ws://localhost:8090";
string ws_user;
string ws_password;
};
FC_REFLECT( wallet_data, (accounts)(keys)(pending_account_registrations)(ws_server)(ws_user)(ws_password) );
/**
* This wallet assumes nothing about where the database server is
* located and performs minimal caching. This API could be provided
* locally to be used by a web interface.
*/
class wallet_api
{
public:
wallet_api( fc::api<login_api> rapi )
:_remote_api(rapi)
{
_remote_db = _remote_api->database();
_remote_net = _remote_api->network();
}
string help()const;
string suggest_brain_key()const
{
return string("dummy");
}
variant get_object( object_id_type id )
{
return _remote_db->get_objects({id});
}
account_object get_account( string account_name_or_id )
{
FC_ASSERT( account_name_or_id.size() > 0 );
vector<optional<account_object>> opt_account;
if( std::isdigit( account_name_or_id.front() ) )
opt_account = _remote_db->get_accounts( {fc::variant(account_name_or_id).as<account_id_type>()} );
else
opt_account = _remote_db->lookup_account_names( {account_name_or_id} );
FC_ASSERT( opt_account.size() && opt_account.front() );
return *opt_account.front();
}
bool import_key( string account_name_or_id, string wif_key )
{
auto opt_priv_key = wif_to_key(wif_key);
FC_ASSERT( opt_priv_key.valid() );
bts::chain::address wif_key_address = bts::chain::address(
opt_priv_key->get_public_key() );
auto acnt = get_account( account_name_or_id );
flat_set<key_id_type> keys;
for( auto item : acnt.active.auths )
{
if( item.first.type() == key_object_type )
keys.insert( item.first );
}
for( auto item : acnt.owner.auths )
{
if( item.first.type() == key_object_type )
keys.insert( item.first );
}
auto opt_keys = _remote_db->get_keys( vector<key_id_type>(keys.begin(),keys.end()) );
for( const fc::optional<key_object>& opt_key : opt_keys )
{
// the requested key ID's should all exist because they are
// keys for an account
FC_ASSERT( opt_key.valid() );
// we do this check by address because key objects on the
// blockchain may not contain a key (i.e. are simply an address)
if( opt_key->key_address() == wif_key_address )
{
_wallet.keys[ opt_key->id ] = wif_key;
return true;
}
}
ilog( "key not for account ${name}", ("name",account_name_or_id) );
return false;
}
string normalize_brain_key( string s )
{
size_t i = 0, n = s.length();
std::string result;
char c;
result.reserve( n );
bool preceded_by_whitespace = false;
bool non_empty = false;
while( i < n )
{
c = s[i++];
switch( c )
{
case ' ': case '\t': case '\r': case '\n': case '\v': case '\f':
preceded_by_whitespace = true;
continue;
case 'a': c = 'A'; break;
case 'b': c = 'B'; break;
case 'c': c = 'C'; break;
case 'd': c = 'D'; break;
case 'e': c = 'E'; break;
case 'f': c = 'F'; break;
case 'g': c = 'G'; break;
case 'h': c = 'H'; break;
case 'i': c = 'I'; break;
case 'j': c = 'J'; break;
case 'k': c = 'K'; break;
case 'l': c = 'L'; break;
case 'm': c = 'M'; break;
case 'n': c = 'N'; break;
case 'o': c = 'O'; break;
case 'p': c = 'P'; break;
case 'q': c = 'Q'; break;
case 'r': c = 'R'; break;
case 's': c = 'S'; break;
case 't': c = 'T'; break;
case 'u': c = 'U'; break;
case 'v': c = 'V'; break;
case 'w': c = 'W'; break;
case 'x': c = 'X'; break;
case 'y': c = 'Y'; break;
case 'z': c = 'Z'; break;
default:
break;
}
if( preceded_by_whitespace && non_empty )
result.push_back(' ');
result.push_back(c);
preceded_by_whitespace = false;
non_empty = true;
}
return result;
}
fc::ecc::private_key derive_private_key(
const std::string& prefix_string, int sequence_number)
{
std::string sequence_string = std::to_string(sequence_number);
fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string);
fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h));
return derived_key;
}
signed_transaction create_account_with_brain_key(
string brain_key,
string account_name,
string registrar_account,
string referrer_account,
uint8_t referrer_percent
)
{
string normalized_brain_key = normalize_brain_key( brain_key );
// TODO: scan blockchain for accounts that exist with same brain key
fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 );
fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), 0);
bts::chain::public_key_type owner_pubkey = owner_privkey.get_public_key();
bts::chain::public_key_type active_pubkey = active_privkey.get_public_key();
account_create_operation account_create_op;
// TODO: process when pay_from_account is ID
account_object registrar_account_object =
this->get_account( registrar_account );
account_id_type registrar_account_id = registrar_account_object.id;
if( referrer_percent > 0 )
{
account_object referrer_account_object =
this->get_account( referrer_account );
account_create_op.referrer = referrer_account_object.id;
account_create_op.referrer_percent = referrer_percent;
}
// get pay_from_account_id
key_create_operation owner_key_create_op;
owner_key_create_op.fee_paying_account = registrar_account_id;
owner_key_create_op.key_data = owner_pubkey;
key_create_operation active_key_create_op;
active_key_create_op.fee_paying_account = registrar_account_id;
active_key_create_op.key_data = active_pubkey;
// key_create_op.calculate_fee(db.current_fee_schedule());
// TODO: Check if keys already exist!!!
relative_key_id_type owner_rkid(0);
relative_key_id_type active_rkid(1);
account_create_op.registrar = registrar_account_id;
account_create_op.name = account_name;
account_create_op.owner = authority(1, owner_rkid, 1);
account_create_op.active = authority(1, active_rkid, 1);
account_create_op.memo_key = active_rkid;
account_create_op.voting_key = active_rkid;
account_create_op.vote = flat_set<vote_tally_id_type>();
// current_fee_schedule()
// find_account(pay_from_account)
// account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule());
signed_transaction tx;
tx.operations.push_back( owner_key_create_op );
tx.operations.push_back( active_key_create_op );
tx.operations.push_back( account_create_op );
tx.visit( operation_set_fee( _remote_db->get_global_properties().parameters.current_fees ) );
vector<key_id_type> paying_keys = registrar_account_object.active.get_keys();
tx.validate();
for( key_id_type& key : paying_keys )
{
auto it = _wallet.keys.find(key);
if( it != _wallet.keys.end() )
{
fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second );
if( !privkey.valid() )
{
FC_ASSERT( false, "Malformed private key in _wallet.keys" );
}
tx.sign( *privkey );
}
}
// we do not insert owner_privkey here because
// it is intended to only be used for key recovery
_wallet.pending_account_registrations[ account_name ] = key_to_wif( active_privkey );
return tx;
}
signed_transaction transfer( string from,
string to,
uint64_t amount,
string asset_symbol,
string memo,
bool broadcast = false )
{
auto opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol} );
wdump( (opt_asset) );
return signed_transaction();
}
// methods that start with underscore are not incuded in API
void _resync()
{
// this method is used to update wallet_data annotations
// e.g. wallet has been restarted and was not notified
// of events while it was down
//
// everything that is done "incremental style" when a push
// notification is received, should also be done here
// "batch style" by querying the blockchain
if( _wallet.pending_account_registrations.size() > 0 )
{
std::vector<string> v_names;
v_names.reserve( _wallet.pending_account_registrations.size() );
for( auto it : _wallet.pending_account_registrations )
v_names.push_back( it.first );
std::vector< fc::optional< bts::chain::account_object >>
v_accounts = _remote_db->lookup_account_names( v_names );
for( fc::optional< bts::chain::account_object > opt_account : v_accounts )
{
if( ! opt_account.valid() )
continue;
string account_name = opt_account->name;
auto it = _wallet.pending_account_registrations.find( account_name );
FC_ASSERT( it != _wallet.pending_account_registrations.end() );
if( import_key( account_name, it->second ) )
{
// somebody else beat our pending registration, there is
// nothing we can do except log it and move on
ilog( "account ${name} registered by someone else first!",
("name", account_name) );
// might as well remove it from pending regs,
// because there is now no way this registration
// can become valid (even in the extremely rare
// possibility of migrating to a fork where the
// name is available, the user can always
// manually re-register)
}
_wallet.pending_account_registrations.erase( it );
}
}
return;
}
wallet_data _wallet;
fc::api<login_api> _remote_api;
fc::api<database_api> _remote_db;
fc::api<network_api> _remote_net;
};
FC_API( wallet_api,
(help)
(import_key)
(suggest_brain_key)
(create_account_with_brain_key)
(transfer)
(get_account)
(get_object)
(normalize_brain_key)
)
struct help_visitor
{
help_visitor( std::stringstream& s ):ss(s){}
std::stringstream& ss;
template<typename R, typename... Args>
void operator()( const char* name, std::function<R(Args...)>& memb )const {
ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "( ";
vector<string> args{ fc::get_typename<Args>::name()... };
for( uint32_t i = 0; i < args.size(); ++i )
ss << args[i] << (i==args.size()-1?" ":", ");
ss << ")\n";
}
};
string wallet_api::help()const
{
fc::api<wallet_api> tmp;
std::stringstream ss;
tmp->visit( help_visitor(ss) );
return ss.str();
}
int main( int argc, char** argv )
{
try {
FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) );
fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis")));
idump( (key_to_wif( genesis_private_key ) ) );
idump( (account_id_type()) );
wallet_data wallet;
fc::path wallet_file(argv[1]);
if( fc::exists( wallet_file ) )
wallet = fc::json::from_file( wallet_file ).as<wallet_data>();
fc::http::websocket_client client;
auto con = client.connect( wallet.ws_server );
auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);
con->closed.connect( [&](){ elog( "connection closed" ); } );
auto remote_api = apic->get_remote_api< login_api >();
FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) );
auto wapiptr = std::make_shared<wallet_api>(remote_api);
wapiptr->_wallet = wallet;
fc::api<wallet_api> wapi(wapiptr);
auto wallet_cli = std::make_shared<fc::rpc::cli>();
wallet_cli->format_result( "help", [&]( variant result, const fc::variants& a) {
return result.get_string();
});
wallet_cli->register_api( wapi );
wallet_cli->start();
wallet_cli->wait();
}
catch ( const fc::exception& e )
{
std::cout << e.to_detail_string() << "\n";
}
return -1;
}
<|endoftext|> |
<commit_before>#include "runner/at_handler.hh"
#include <iostream>
#include <list>
#include "scheduler/tag.hh"
namespace runner
{
class AtJob
{
public:
AtJob(rObject condition, rObject clause, rObject on_leave,
scheduler::tags_type tags);
bool blocked() const;
bool frozen() const;
const rObject& condition_get() const;
const rObject& clause_get() const;
const rObject& on_leave_get() const;
bool triggered_get() const;
void triggered_set(bool);
const scheduler::tags_type& tags_get() const;
private:
rObject condition_;
rObject clause_;
rObject on_leave_;
bool triggered_;
scheduler::tags_type tags_;
};
class AtHandler : public Runner
{
public:
AtHandler(const Runner&);
virtual ~AtHandler();
virtual void work();
virtual bool frozen() const;
virtual bool blocked() const;
void add_job(AtJob*);
private:
void complete_tags(const AtJob&);
void rebuild_tags();
typedef std::vector<AtJob*> at_jobs_type;
at_jobs_type jobs_;
bool yielding;
scheduler::tags_type tags_;
};
// There is only one at job handler. It will be created if it doesn't exist
// and destroyed when it has no more jobs to handle.
static AtHandler* at_job_handler;
AtHandler::AtHandler(const Runner& model)
: Runner(model, 0),
yielding(false)
{
}
AtHandler::~AtHandler()
{
}
void
AtHandler::work()
{
bool check_for_blocked = true;
bool tags_need_rebuilding;
side_effect_free_set(true);
while (true)
{
non_interruptible_set(true);
yielding = false;
tags_need_rebuilding = false;
// We have been woken up, either because we may have something to do
// or because some tag conditions have changed.
at_jobs_type pending;
pending.reserve(jobs_.size());
// If we have to check for blocked jobs, do it at the beginning
// to make sure we do not miss a "stop" because some condition
// evaluation mistakenly reenters the scheduler. So instead of
// just swapping pending_ and jobs, we will build pending using
// the unblocked jobs.
if (check_for_blocked)
{
foreach(AtJob* job, jobs_)
if (job->blocked())
{
tags_need_rebuilding = true;
delete job;
}
else
pending.push_back(job);
}
else // Use all jobs, none has been blocked
swap(jobs_, pending);
foreach (AtJob* job, pending)
{
// If job has been frozen, we will not consider it for the moment.
if (job->frozen())
{
jobs_.push_back(job);
continue;
}
// Check the job condition and continue if it has not changed.
bool new_state;
try
{
new_state =
object::is_true(urbi_call(*this, job->condition_get(), SYMBOL(eval)));
}
catch (const kernel::exception& ke)
{
std::cerr << "at condition triggered an exception: " << ke.what()
<< std::endl;
tags_need_rebuilding = true;
delete job;
continue;
}
catch (...)
{
std::cerr << "at condition triggered an exception\n";
delete job;
continue;
}
if (new_state == job->triggered_get())
{
jobs_.push_back(job);
continue;
}
// There has been a change in the condition, act accordingly depending
// on whether we have seen a rising or a falling edge and save the
// condition evaluation result.
const rObject& to_launch =
new_state ? job->clause_get() : job->on_leave_get();
if (to_launch != object::nil_class)
{
// Temporarily install the needed tags as the current tags.
tags_set(job->tags_get());
// We do not need to check for an exception here as "detach",
// which is the function being called, will not throw and any
// exception thrown in the detached runner will not be caught
// here anyway.
urbi_call(*this, to_launch, SYMBOL(eval));
}
job->triggered_set(new_state);
jobs_.push_back(job);
}
// If we have no more jobs, we can destroy ourselves.
if (jobs_.empty())
{
at_job_handler = 0;
terminate_now();
}
non_interruptible_set(false);
check_for_blocked = false;
yielding = true;
// Rebuild tags if our list of jobs has changed.
if (tags_need_rebuilding)
rebuild_tags();
// Go to sleep
try
{
// We want to appear blocked only when explicitly yielding and
// catching the exception. If, by mistake, a condition evaluation
// yields and is blocked, we do not want it to get the bogus
// exception.
yield_until_things_changed();
}
catch (const scheduler::BlockedException& e)
{
// We have at least one "at" job which needs to be blocked.
check_for_blocked = true;
}
catch (const kernel::exception& e)
{
std::cerr << "at job handler exited with exception " << e.what()
<< std::endl;
throw;
}
catch (...)
{
std::cerr << "at job handler exited with unknown exception\n";
throw;
}
}
}
bool
AtHandler::frozen() const
{
return false;
}
bool
AtHandler::blocked() const
{
if (!yielding)
return false;
foreach (const scheduler::rTag& t, tags_)
if (t->blocked())
return true;
return false;
}
void
AtHandler::add_job(AtJob* job)
{
jobs_.push_back(job);
complete_tags(*job);
}
void
AtHandler::rebuild_tags()
{
tags_.clear();
foreach (const AtJob* job, jobs_)
complete_tags(*job);
}
void
AtHandler::complete_tags(const AtJob& job)
{
foreach (scheduler::rTag t, job.tags_get())
{
foreach (const scheduler::rTag& u, tags_)
if (t == u)
goto already_found;
tags_.push_back(t);
already_found:
;
}
}
AtJob::AtJob(rObject condition, rObject clause, rObject on_leave,
scheduler::tags_type tags)
: condition_(condition),
clause_(clause),
on_leave_(on_leave),
triggered_(false),
tags_(tags)
{
}
bool
AtJob::blocked() const
{
foreach(const scheduler::rTag& tag, tags_)
if (tag->blocked())
return true;
return false;
}
bool
AtJob::frozen() const
{
foreach(const scheduler::rTag& tag, tags_)
if (tag->frozen())
return true;
return false;
}
const rObject&
AtJob::condition_get() const
{
return condition_;
}
const rObject&
AtJob::clause_get() const
{
return clause_;
}
const rObject&
AtJob::on_leave_get() const
{
return on_leave_;
}
bool
AtJob::triggered_get() const
{
return triggered_;
}
void
AtJob::triggered_set(bool t)
{
triggered_ = t;
}
const scheduler::tags_type&
AtJob::tags_get() const
{
return tags_;
}
void
register_at_job(const runner::Runner& starter,
rObject condition,
rObject clause,
rObject on_leave)
{
if (!at_job_handler)
{
at_job_handler = new AtHandler(starter);
at_job_handler->start_job();
}
AtJob* job = new AtJob(condition,
clause,
on_leave,
starter.tags_get());
at_job_handler->add_job(job);
}
} // namespace runner
<commit_msg>Use pointer containers in at job handler.<commit_after>#include "runner/at_handler.hh"
#include <iostream>
#include <list>
#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include "scheduler/tag.hh"
namespace runner
{
class AtJob
{
public:
AtJob(rObject condition, rObject clause, rObject on_leave,
scheduler::tags_type tags);
bool blocked() const;
bool frozen() const;
const rObject& condition_get() const;
const rObject& clause_get() const;
const rObject& on_leave_get() const;
bool triggered_get() const;
void triggered_set(bool);
const scheduler::tags_type& tags_get() const;
private:
rObject condition_;
rObject clause_;
rObject on_leave_;
bool triggered_;
scheduler::tags_type tags_;
};
class AtHandler : public Runner
{
public:
AtHandler(const Runner&);
virtual ~AtHandler();
virtual void work();
virtual bool frozen() const;
virtual bool blocked() const;
void add_job(AtJob*);
private:
void complete_tags(const AtJob&);
void rebuild_tags();
typedef boost::ptr_vector<AtJob> at_jobs_type;
at_jobs_type jobs_;
bool yielding;
scheduler::tags_type tags_;
};
// There is only one at job handler. It will be created if it doesn't exist
// and destroyed when it has no more jobs to handle.
static AtHandler* at_job_handler;
AtHandler::AtHandler(const Runner& model)
: Runner(model, 0),
yielding(false)
{
}
AtHandler::~AtHandler()
{
jobs_.release();
}
void
AtHandler::work()
{
bool check_for_blocked = true;
bool tags_need_rebuilding = false;
side_effect_free_set(true);
while (true)
{
non_interruptible_set(true);
yielding = false;
// If we have to check for blocked jobs, do it at the beginning
// to make sure we do not miss a "stop" because some condition
// evaluation mistakenly reenters the scheduler. We know that we
// have to check for blocked jobs because we have had an indication
// that tags needed to be rebuilt.
if (tags_need_rebuilding)
jobs_.erase_if(boost::bind(&AtJob::blocked, _1));
for (at_jobs_type::iterator job = jobs_.begin();
job != jobs_.end();
/* Do not increment as we will also use erase() to advance */)
{
// If job has been frozen, we will not consider it for the moment.
if (job->frozen())
{
++job;
continue;
}
// Check the job condition and continue if it has not changed.
bool new_state;
try
{
new_state =
object::is_true(urbi_call(*this, job->condition_get(), SYMBOL(eval)));
}
catch (const kernel::exception& ke)
{
std::cerr << "at condition triggered an exception: " << ke.what()
<< std::endl;
tags_need_rebuilding = true;
job = jobs_.erase(job);
continue;
}
catch (...)
{
std::cerr << "at condition triggered an exception\n";
job = jobs_.erase(job);
continue;
}
if (new_state == job->triggered_get())
{
++job;
continue;
}
// There has been a change in the condition, act accordingly depending
// on whether we have seen a rising or a falling edge and save the
// condition evaluation result.
const rObject& to_launch =
new_state ? job->clause_get() : job->on_leave_get();
if (to_launch != object::nil_class)
{
// Temporarily install the needed tags as the current tags.
tags_set(job->tags_get());
// We do not need to check for an exception here as "detach",
// which is the function being called, will not throw and any
// exception thrown in the detached runner will not be caught
// here anyway.
urbi_call(*this, to_launch, SYMBOL(eval));
}
job->triggered_set(new_state);
++job;
}
// If we have no more jobs, we can destroy ourselves.
if (jobs_.empty())
{
at_job_handler = 0;
terminate_now();
}
non_interruptible_set(false);
check_for_blocked = false;
yielding = true;
// Rebuild tags if our list of jobs has changed.
if (tags_need_rebuilding)
rebuild_tags();
tags_need_rebuilding = false;
// Go to sleep
try
{
// We want to appear blocked only when explicitly yielding and
// catching the exception. If, by mistake, a condition evaluation
// yields and is blocked, we do not want it to get the bogus
// exception.
yield_until_things_changed();
}
catch (const scheduler::BlockedException& e)
{
// We have at least one "at" job which needs to be blocked.
tags_need_rebuilding = true;
}
catch (const kernel::exception& e)
{
std::cerr << "at job handler exited with exception " << e.what()
<< std::endl;
throw;
}
catch (...)
{
std::cerr << "at job handler exited with unknown exception\n";
throw;
}
}
}
bool
AtHandler::frozen() const
{
return false;
}
bool
AtHandler::blocked() const
{
if (!yielding)
return false;
foreach (const scheduler::rTag& t, tags_)
if (t->blocked())
return true;
return false;
}
void
AtHandler::add_job(AtJob* job)
{
jobs_.push_back(job);
complete_tags(*job);
}
void
AtHandler::rebuild_tags()
{
tags_.clear();
foreach (const AtJob& job, jobs_)
complete_tags(job);
}
void
AtHandler::complete_tags(const AtJob& job)
{
foreach (scheduler::rTag t, job.tags_get())
{
foreach (const scheduler::rTag& u, tags_)
if (t == u)
goto already_found;
tags_.push_back(t);
already_found:
;
}
}
AtJob::AtJob(rObject condition, rObject clause, rObject on_leave,
scheduler::tags_type tags)
: condition_(condition),
clause_(clause),
on_leave_(on_leave),
triggered_(false),
tags_(tags)
{
}
bool
AtJob::blocked() const
{
foreach(const scheduler::rTag& tag, tags_)
if (tag->blocked())
return true;
return false;
}
bool
AtJob::frozen() const
{
foreach(const scheduler::rTag& tag, tags_)
if (tag->frozen())
return true;
return false;
}
const rObject&
AtJob::condition_get() const
{
return condition_;
}
const rObject&
AtJob::clause_get() const
{
return clause_;
}
const rObject&
AtJob::on_leave_get() const
{
return on_leave_;
}
bool
AtJob::triggered_get() const
{
return triggered_;
}
void
AtJob::triggered_set(bool t)
{
triggered_ = t;
}
const scheduler::tags_type&
AtJob::tags_get() const
{
return tags_;
}
void
register_at_job(const runner::Runner& starter,
rObject condition,
rObject clause,
rObject on_leave)
{
if (!at_job_handler)
{
at_job_handler = new AtHandler(starter);
at_job_handler->start_job();
}
AtJob* job = new AtJob(condition,
clause,
on_leave,
starter.tags_get());
at_job_handler->add_job(job);
}
} // namespace runner
<|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) 2013 Evgeniy Andreev (gsomix)
*/
#include <cstdio>_
#include <shogun/io/LineReader.h>
using namespace shogun;
CLineReader::CLineReader()
: m_stream(NULL), m_max_line_length(0), m_next_line_length(-1)
{
m_buffer=new CCircularBuffer(0);
}
CLineReader::CLineReader(FILE* stream, char delimiter)
: m_stream(stream), m_max_line_length(10*1024*1024), m_next_line_length(-1)
{
m_buffer=new CCircularBuffer(m_max_line_length);
m_tokenizer=new CDelimiterTokenizer();
m_tokenizer->delimiters[delimiter]=1;
m_buffer->set_tokenizer(m_tokenizer);
}
CLineReader::CLineReader(int32_t max_line_length, FILE* stream, char delimiter)
: m_stream(stream), m_max_line_length(max_line_length), m_next_line_length(-1)
{
m_buffer=new CCircularBuffer(m_max_line_length);
m_tokenizer=new CDelimiterTokenizer();
m_tokenizer->delimiters[delimiter]=1;
m_buffer->set_tokenizer(m_tokenizer);
}
CLineReader::~CLineReader()
{
SG_UNREF(m_tokenizer);
SG_UNREF(m_buffer);
}
bool CLineReader::has_next_line()
{
if (m_stream==NULL || m_max_line_length==0)
{
SG_ERROR("Class is not initialized");
return false;
}
if (ferror(m_stream))
{
SG_ERROR("Error reading file");
return false;
}
if (feof(m_stream) && m_buffer->num_bytes_contained()<=0)
return false; // nothing to read
return true;
}
SGVector<char> CLineReader::get_next_line()
{
SGVector<char> line;
m_next_line_length=read_line();
if (m_next_line_length==-1)
line=SGVector<char>();
else
line=copy_line(m_next_line_length);
return line;
}
void CLineReader::set_delimiter(char delimiter)
{
m_tokenizer->delimiters[delimiter]=1;
}
void CLineReader::clear_delimiters()
{
m_tokenizer->clear_delimiters();
}
int32_t CLineReader::read_line()
{
int32_t line_end=0;
int32_t bytes_to_skip=0;
int32_t bytes_to_read=0;
while (1)
{
line_end+=m_buffer->next_token_idx(bytes_to_skip)-bytes_to_skip;
if (m_buffer->num_bytes_contained()!=0 && line_end<m_buffer->num_bytes_contained())
return line_end;
else if (m_buffer->available()==0)
return -1; // we need some limit in case file does not contain delimiter
// if there is no delimiter in buffer
// try get more data from stream
// and write it into buffer
if (m_buffer->available() < m_max_line_length)
bytes_to_read=m_buffer->available();
else
bytes_to_read=m_max_line_length;
if (feof(m_stream))
return line_end;
else
m_buffer->push(m_stream, bytes_to_read);
if (ferror(m_stream))
{
SG_ERROR("Error reading file");
return -1;
}
}
}
SGVector<char> CLineReader::copy_line(int32_t line_len)
{
SGVector<char> line;
if (line_len==0)
line=SGVector<char>();
else
line=m_buffer->pop(line_len);
m_buffer->skip_characters(1);
return line;
}
<commit_msg>Remove extra tokens at end of #include<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) 2013 Evgeniy Andreev (gsomix)
*/
#include <cstdio>
#include <shogun/io/LineReader.h>
using namespace shogun;
CLineReader::CLineReader()
: m_stream(NULL), m_max_line_length(0), m_next_line_length(-1)
{
m_buffer=new CCircularBuffer(0);
}
CLineReader::CLineReader(FILE* stream, char delimiter)
: m_stream(stream), m_max_line_length(10*1024*1024), m_next_line_length(-1)
{
m_buffer=new CCircularBuffer(m_max_line_length);
m_tokenizer=new CDelimiterTokenizer();
m_tokenizer->delimiters[delimiter]=1;
m_buffer->set_tokenizer(m_tokenizer);
}
CLineReader::CLineReader(int32_t max_line_length, FILE* stream, char delimiter)
: m_stream(stream), m_max_line_length(max_line_length), m_next_line_length(-1)
{
m_buffer=new CCircularBuffer(m_max_line_length);
m_tokenizer=new CDelimiterTokenizer();
m_tokenizer->delimiters[delimiter]=1;
m_buffer->set_tokenizer(m_tokenizer);
}
CLineReader::~CLineReader()
{
SG_UNREF(m_tokenizer);
SG_UNREF(m_buffer);
}
bool CLineReader::has_next_line()
{
if (m_stream==NULL || m_max_line_length==0)
{
SG_ERROR("Class is not initialized");
return false;
}
if (ferror(m_stream))
{
SG_ERROR("Error reading file");
return false;
}
if (feof(m_stream) && m_buffer->num_bytes_contained()<=0)
return false; // nothing to read
return true;
}
SGVector<char> CLineReader::get_next_line()
{
SGVector<char> line;
m_next_line_length=read_line();
if (m_next_line_length==-1)
line=SGVector<char>();
else
line=copy_line(m_next_line_length);
return line;
}
void CLineReader::set_delimiter(char delimiter)
{
m_tokenizer->delimiters[delimiter]=1;
}
void CLineReader::clear_delimiters()
{
m_tokenizer->clear_delimiters();
}
int32_t CLineReader::read_line()
{
int32_t line_end=0;
int32_t bytes_to_skip=0;
int32_t bytes_to_read=0;
while (1)
{
line_end+=m_buffer->next_token_idx(bytes_to_skip)-bytes_to_skip;
if (m_buffer->num_bytes_contained()!=0 && line_end<m_buffer->num_bytes_contained())
return line_end;
else if (m_buffer->available()==0)
return -1; // we need some limit in case file does not contain delimiter
// if there is no delimiter in buffer
// try get more data from stream
// and write it into buffer
if (m_buffer->available() < m_max_line_length)
bytes_to_read=m_buffer->available();
else
bytes_to_read=m_max_line_length;
if (feof(m_stream))
return line_end;
else
m_buffer->push(m_stream, bytes_to_read);
if (ferror(m_stream))
{
SG_ERROR("Error reading file");
return -1;
}
}
}
SGVector<char> CLineReader::copy_line(int32_t line_len)
{
SGVector<char> line;
if (line_len==0)
line=SGVector<char>();
else
line=m_buffer->pop(line_len);
m_buffer->skip_characters(1);
return line;
}
<|endoftext|> |
<commit_before>#include "runtime_internal.h"
#include "HalideRuntimeQurt.h"
#include "printer.h"
#include "mini_qurt.h"
#include "hexagon_remote/log.h"
using namespace Halide::Runtime::Internal::Qurt;
extern "C" {
enum qurt_hvx_mode_t {
QURT_HVX_MODE_64B = 0,
QURT_HVX_MODE_128B = 1,
};
extern int qurt_hvx_lock(qurt_hvx_mode_t);
extern int qurt_hvx_unlock();
WEAK int halide_qurt_hvx_lock(void *user_context, int size) {
qurt_hvx_mode_t mode;
switch (size) {
case 64: mode = QURT_HVX_MODE_64B; break;
case 128: mode = QURT_HVX_MODE_128B; break;
default:
error(user_context) << "HVX lock size must be 64 or 128.\n";
return -1;
}
debug(user_context) << "QuRT: qurt_hvx_lock(" << mode << ") ->\n";
int result = qurt_hvx_lock(mode);
debug(user_context) << " " << result << "\n";
if (result != QURT_EOK) {
error(user_context) << "qurt_hvx_lock failed\n";
return -1;
}
return 0;
}
WEAK int halide_qurt_hvx_unlock(void *user_context) {
debug(user_context) << "QuRT: qurt_hvx_unlock ->\n";
int result = qurt_hvx_unlock();
debug(user_context) << " " << result << "\n";
if (result != QURT_EOK) {
error(user_context) << "qurt_hvx_unlock failed\n";
return -1;
}
return 0;
}
WEAK void halide_qurt_hvx_unlock_as_destructor(void *user_context, void * /*obj*/) {
halide_qurt_hvx_unlock(user_context);
}
/////////////////////////////////////////////////////////////////////////////
//
// halide_hexagon_prefetch_buffer_t
//
// Prefetch a multi-dimensional box (subset) from a larger array
//
// dim number of dimensions in array
// elem_size size in bytes of one element
// num_elem total number of elements in array
// buf buffer_t describing box to prefetch
//
// Notes:
// - Prefetches can be queued up to 3 deep (MAX_PREFETCH)
// - If 3 are already pending, the oldest request is dropped
// - USR:PFA status bit is set to indicate that prefetches are in progress
// - A l2fetch with any subfield set to zero cancels all pending prefetches
// - The l2fetch starting address must be in mapped memory but the range
// prefetched can go into unmapped memory without raising an exception
//
// TODO: Opt: Generate more control code for prefetch_buffer_t directly in
// TODO Prefetch.cpp to avoid passing box info through a buffer_t
// TODO (which results in ~30 additional stores/loads)
//
#define MAX_PREFETCH 3
#define MASK16 0xFFFF
#define MIN(x,y) (((x)<(y)) ? (x) : (y))
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
//
// Prefetch debugging controls
//#define DEBUG_PREFETCH 1 // Uncomment to enable prefetch debug
#ifdef DEBUG_PREFETCH // Prefetch debug enabled
// Only produce debug info in this range
#define DBG_P_START 1 // First debug instance to display
#define DBG_P_STOP 9 // Last debug instance to display
//#define DBG_P_STOP 0xFFFFFFFF // Last debug instance to display
#define DBG_PREFETCH_V(...) log_printf(__VA_ARGS__) // Verbose debug enabled
//#define DBG_PREFETCH_V(...) {} // Verbose debug disabled
#define DBG_PREFETCH(...) if ((dbg_cnt >= DBG_P_START) && \
(dbg_cnt <= DBG_P_STOP)) { \
log_printf(__VA_ARGS__); \
} // Normal range-based debug enabled
#else // Prefetch debug disabled
#define DBG_PREFETCH_V(...) {} // Verbose debug disabled
#define DBG_PREFETCH(...) {} // Normal debug disabled
#endif
//
WEAK int halide_hexagon_prefetch_buffer_t(const uint32_t dim, const int32_t elem_size,
const uint32_t num_elem, const buffer_t *buf)
{
// Extract needed fields from buffer_t
unsigned char *addr = buf->host;
const int32_t *extent = buf->extent;
const int32_t *stride = buf->stride;
const int32_t *min = buf->min;
unsigned int boxdim = dim; // dimensions of entire box to prefetch
unsigned int iterdim = 2; // dimension to iterate over
const unsigned char *addr_beg = addr;
const unsigned char *addr_end = addr + (num_elem * elem_size);
#ifdef DEBUG_PREFETCH
static uint32_t dbg_cnt = 0; // limit how many calls debug is generated
dbg_cnt++;
DBG_PREFETCH("halide_hexagon_prefetch_buffer_t(%u, %d)\n", dim, elem_size, num_elem);
DBG_PREFETCH(" addr range 0x%p => 0x%p\n", addr_beg, addr_end);
DBG_PREFETCH(" buf host=0x%p elem_size=%d\n", addr, buf->elem_size);
for (unsigned int i = 0; i < boxdim; i++) {
DBG_PREFETCH(" buf stride[%d]=0x%-8x min[%d]=%-6d ext[%d]=%d\n",
i, stride[i], i, min[i], i, extent[i]);
}
#endif
// Compute starting position of box
int32_t startpos = 0;
for (unsigned int i = 0; i < boxdim; i++) {
startpos += min[i] * stride[i];
}
addr += startpos * elem_size;
DBG_PREFETCH(" +startpos=0x%x*%d => addr=0x%p\n", startpos, elem_size, addr);
// Range check starting address
if ((addr < addr_beg) || (addr >= addr_end)) {
DBG_PREFETCH_V(" l2fetch: 0x%p out of range [0x%p, 0x%p]\n",
addr, addr_beg, addr_end);
return 0;
}
// Compute 2-D prefetch descriptor
// l2fetch(Rs,Rtt): 48 bit descriptor
uint32_t pdir = 1; // 0 row major, 1 = column major
uint32_t pstride = stride[0] * elem_size;
uint32_t pwidth = extent[0] * elem_size;
uint32_t pheight = 1;
if (boxdim > 1) {
pheight = extent[1];
}
#if 0 // TODO: Opt: Box collapse disabled for now - needs more testing, and
// TODO collapse candidates tend to exceed the stride mask size
// For boxes with dimension > 2 try to "collapse" any unit height
// dimensions by increasing the descriptor stride
int32_t newpstride = pstride;
while (boxdim > 2) {
if (pheight == 1) { // if height is currently 1
newpstride = stride[iterdim-1] * elem_size; // update stride
} else {
break; // otherwise, we're done collapsing
}
if (newpstride == (newpstride & MASK16)) { // and if it fits in mask...
pstride = newpstride; // ...accept new stride
pheight = extent[iterdim]; // ...and height
} else {
break; // otherwise, we're done collapsing
}
boxdim--; // remaining non-collapsed dimensions
iterdim++; // update innermost iterate dimension
}
#endif
pdir = pdir & 0x1; // bit 48
pstride = MIN(pstride, MASK16); // bits 47:32
pwidth = MIN(pwidth, MASK16); // bits 31:16
pheight = MIN(pheight, MASK16); // bits 15:0
uint64_t pdir64 = pdir;
uint64_t pstride64 = pstride;
uint64_t pdesc = (pdir64<<48) | (pstride64<<32) | (pwidth<<16) | pheight;
const uint32_t pbytes = pwidth * pheight; // Bytes in prefetch descriptor
uint32_t tbytes = 0; // Total bytes prefetched
uint32_t tcnt = 0; // Total count of prefetch ops
// Hard coded descriptors for testing
// uint64_t pdesc = 0x1020002000002; // col, 512 width, 2 rows
// uint64_t pdesc = 0x1020002000001; // col, 512 width, 1 row
// uint64_t pdesc = 0x1144014400001; // col, 5184 width, 1 row
DBG_PREFETCH(" prefetch pdir:0x%x pstride:0x%x pwidth:0x%x pheight:0x%x\n",
pdir, pstride, pwidth, pheight);
DBG_PREFETCH(" prefetch addr:0x%p pdesc:0x%llx\n", addr, pdesc);
DBG_PREFETCH(" iterdim:%d\n", iterdim);
// If iterdim is not last dim && iterdim extent is 1...
while ((iterdim < dim-1) && (extent[iterdim] == 1)) {
iterdim++; // ...iterate at the next higher dimension
}
// TODO: Add support for iterating over multiple higher dimensions?
// TODO Currently just iterating over one outer (non-unity) dimension
// TODO since only MAX_PREFETCH prefetches can be queued anyway.
if ((boxdim <= 2) || // 2-D box, or
(iterdim >= dim) || // No dimension remaining to iterate over, or
(extent[iterdim] == 1)) { // >2-D box, but unity outer dimension
// Perform a single prefetch
DBG_PREFETCH(" l2fetch(0x%p, 0x%llx): %d bytes\n", addr, pdesc, pbytes);
__asm__ __volatile__ ("l2fetch(%0,%1)" : : "r"(addr), "r"(pdesc));
tbytes += pbytes;
tcnt++;
} else { // Iterate for higher dimension boxes...
// Get iteration stride and extents
int32_t iterstride = stride[iterdim] * elem_size;
int32_t iterextent = extent[iterdim];
iterextent = MIN(iterextent, MAX_PREFETCH); // Limit # of prefetches
DBG_PREFETCH(" stride[%d]*%d=0x%x ext[%d]=%d\n",
iterdim, elem_size, iterstride, iterdim, iterextent);
for (int32_t i = 0; i < iterextent; i++) {
DBG_PREFETCH(" %d: l2fetch(0x%p, 0x%llx): %d bytes\n", i, addr, pdesc, pbytes);
// Range check starting address
if ((addr >= addr_beg) && (addr < addr_end)) {
// Perform prefetch
__asm__ __volatile__ ("l2fetch(%0,%1)" : : "r"(addr), "r"(pdesc));
tbytes += pbytes;
tcnt++;
} else {
DBG_PREFETCH_V(" %d: l2fetch: +0x%x => 0x%p out of range [0x%p, 0x%p]\n",
i, iterstride, addr, addr_beg, addr_end);
}
addr += iterstride;
}
}
// TODO: Opt: Return the number of prefetch instructions (tcnt) issued?
// to not exceed MAX_PREFETCH in a sequence of prefetch ops
// TODO: Opt: Return the size in bytes (tbytes) prefetched?
// to avoid prefetching too much data in one sequence
DBG_PREFETCH(" l2fetch: %d ops, %d bytes\n", tcnt, tbytes);
return 0;
}
}
<commit_msg>Fix stride descriptor for higher dimension arrays<commit_after>#include "runtime_internal.h"
#include "HalideRuntimeQurt.h"
#include "printer.h"
#include "mini_qurt.h"
#include "hexagon_remote/log.h"
using namespace Halide::Runtime::Internal::Qurt;
extern "C" {
enum qurt_hvx_mode_t {
QURT_HVX_MODE_64B = 0,
QURT_HVX_MODE_128B = 1,
};
extern int qurt_hvx_lock(qurt_hvx_mode_t);
extern int qurt_hvx_unlock();
WEAK int halide_qurt_hvx_lock(void *user_context, int size) {
qurt_hvx_mode_t mode;
switch (size) {
case 64: mode = QURT_HVX_MODE_64B; break;
case 128: mode = QURT_HVX_MODE_128B; break;
default:
error(user_context) << "HVX lock size must be 64 or 128.\n";
return -1;
}
debug(user_context) << "QuRT: qurt_hvx_lock(" << mode << ") ->\n";
int result = qurt_hvx_lock(mode);
debug(user_context) << " " << result << "\n";
if (result != QURT_EOK) {
error(user_context) << "qurt_hvx_lock failed\n";
return -1;
}
return 0;
}
WEAK int halide_qurt_hvx_unlock(void *user_context) {
debug(user_context) << "QuRT: qurt_hvx_unlock ->\n";
int result = qurt_hvx_unlock();
debug(user_context) << " " << result << "\n";
if (result != QURT_EOK) {
error(user_context) << "qurt_hvx_unlock failed\n";
return -1;
}
return 0;
}
WEAK void halide_qurt_hvx_unlock_as_destructor(void *user_context, void * /*obj*/) {
halide_qurt_hvx_unlock(user_context);
}
/////////////////////////////////////////////////////////////////////////////
//
// halide_hexagon_prefetch_buffer_t
//
// Prefetch a multi-dimensional box (subset) from a larger array
//
// dim number of dimensions in array
// elem_size size in bytes of one element
// num_elem total number of elements in array
// buf buffer_t describing box to prefetch
//
// Notes:
// - Prefetches can be queued up to 3 deep (MAX_PREFETCH)
// - If 3 are already pending, the oldest request is dropped
// - USR:PFA status bit is set to indicate that prefetches are in progress
// - A l2fetch with any subfield set to zero cancels all pending prefetches
// - The l2fetch starting address must be in mapped memory but the range
// prefetched can go into unmapped memory without raising an exception
//
// TODO: Opt: Generate more control code for prefetch_buffer_t directly in
// TODO Prefetch.cpp to avoid passing box info through a buffer_t
// TODO (which results in ~30 additional stores/loads)
//
#define MAX_PREFETCH 3
#define MASK16 0xFFFF
#define MIN(x,y) (((x)<(y)) ? (x) : (y))
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
//
// Prefetch debugging controls
//#define DEBUG_PREFETCH 1 // Uncomment to enable prefetch debug
#ifdef DEBUG_PREFETCH // Prefetch debug enabled
// Only produce debug info in this range
#define DBG_P_START 1 // First debug instance to display
#define DBG_P_STOP 9 // Last debug instance to display
//#define DBG_P_STOP 0xFFFFFFFF // Last debug instance to display
#define DBG_PREFETCH_V(...) log_printf(__VA_ARGS__) // Verbose debug enabled
//#define DBG_PREFETCH_V(...) {} // Verbose debug disabled
#define DBG_PREFETCH(...) if ((dbg_cnt >= DBG_P_START) && \
(dbg_cnt <= DBG_P_STOP)) { \
log_printf(__VA_ARGS__); \
} // Normal range-based debug enabled
#else // Prefetch debug disabled
#define DBG_PREFETCH_V(...) {} // Verbose debug disabled
#define DBG_PREFETCH(...) {} // Normal debug disabled
#endif
//
WEAK int halide_hexagon_prefetch_buffer_t(const uint32_t dim, const int32_t elem_size,
const uint32_t num_elem, const buffer_t *buf)
{
// Extract needed fields from buffer_t
unsigned char *addr = buf->host;
const int32_t *extent = buf->extent;
const int32_t *stride = buf->stride;
const int32_t *min = buf->min;
unsigned int boxdim = dim; // dimensions of entire box to prefetch
unsigned int iterdim = 2; // dimension to iterate over
const unsigned char *addr_beg = addr;
const unsigned char *addr_end = addr + (num_elem * elem_size);
#ifdef DEBUG_PREFETCH
static uint32_t dbg_cnt = 0; // limit how many calls debug is generated
dbg_cnt++;
DBG_PREFETCH("halide_hexagon_prefetch_buffer_t(%u, %d)\n", dim, elem_size, num_elem);
DBG_PREFETCH(" addr range 0x%p => 0x%p\n", addr_beg, addr_end);
DBG_PREFETCH(" buf host=0x%p elem_size=%d\n", addr, buf->elem_size);
for (unsigned int i = 0; i < boxdim; i++) {
DBG_PREFETCH(" buf stride[%d]=0x%-8x min[%d]=%-6d ext[%d]=%d\n",
i, stride[i], i, min[i], i, extent[i]);
}
#endif
// Compute starting position of box
int32_t startpos = 0;
for (unsigned int i = 0; i < boxdim; i++) {
startpos += min[i] * stride[i];
}
addr += startpos * elem_size;
DBG_PREFETCH(" +startpos=0x%x*%d => addr=0x%p\n", startpos, elem_size, addr);
// Range check starting address
if ((addr < addr_beg) || (addr >= addr_end)) {
DBG_PREFETCH_V(" l2fetch: 0x%p out of range [0x%p, 0x%p]\n",
addr, addr_beg, addr_end);
return 0;
}
// Compute 2-D prefetch descriptor
// l2fetch(Rs,Rtt): 48 bit descriptor
uint32_t pdir = 1; // 0 row major, 1 = column major
uint32_t pstride = stride[0] * elem_size;
uint32_t pwidth = extent[0] * elem_size;
uint32_t pheight = 1;
if (boxdim > 1) {
// Note: Currently assuming this will fit within MASK16
pstride = stride[1] * elem_size;
pheight = extent[1];
}
#if 0 // TODO: Opt: Box collapse disabled for now - needs more testing, and
// TODO collapse candidates tend to exceed the stride mask size
// For boxes with dimension > 2 try to "collapse" any unit height
// dimensions by increasing the descriptor stride
int32_t newpstride = pstride;
while (boxdim > 2) {
if (pheight == 1) { // if height is currently 1
newpstride = stride[iterdim-1] * elem_size; // update stride
} else {
break; // otherwise, we're done collapsing
}
if (newpstride == (newpstride & MASK16)) { // and if it fits in mask...
pstride = newpstride; // ...accept new stride
pheight = extent[iterdim]; // ...and height
} else {
break; // otherwise, we're done collapsing
}
boxdim--; // remaining non-collapsed dimensions
iterdim++; // update innermost iterate dimension
}
#endif
pdir = pdir & 0x1; // bit 48
pstride = MIN(pstride, MASK16); // bits 47:32
pwidth = MIN(pwidth, MASK16); // bits 31:16
pheight = MIN(pheight, MASK16); // bits 15:0
uint64_t pdir64 = pdir;
uint64_t pstride64 = pstride;
uint64_t pdesc = (pdir64<<48) | (pstride64<<32) | (pwidth<<16) | pheight;
const uint32_t pbytes = pwidth * pheight; // Bytes in prefetch descriptor
uint32_t tbytes = 0; // Total bytes prefetched
uint32_t tcnt = 0; // Total count of prefetch ops
// Hard coded descriptors for testing
// uint64_t pdesc = 0x1020002000002; // col, 512 width, 2 rows
// uint64_t pdesc = 0x1020002000001; // col, 512 width, 1 row
// uint64_t pdesc = 0x1144014400001; // col, 5184 width, 1 row
DBG_PREFETCH(" prefetch pdir:0x%x pstride:0x%x pwidth:0x%x pheight:0x%x\n",
pdir, pstride, pwidth, pheight);
DBG_PREFETCH(" prefetch addr:0x%p pdesc:0x%llx\n", addr, pdesc);
DBG_PREFETCH(" iterdim:%d\n", iterdim);
// If iterdim is not last dim && iterdim extent is 1...
while ((iterdim < dim-1) && (extent[iterdim] == 1)) {
iterdim++; // ...iterate at the next higher dimension
}
// TODO: Add support for iterating over multiple higher dimensions?
// TODO Currently just iterating over one outer (non-unity) dimension
// TODO since only MAX_PREFETCH prefetches can be queued anyway.
if ((boxdim <= 2) || // 2-D box, or
(iterdim >= dim) || // No dimension remaining to iterate over, or
(extent[iterdim] == 1)) { // >2-D box, but unity outer dimension
// Perform a single prefetch
DBG_PREFETCH(" l2fetch(0x%p, 0x%llx): %d bytes\n", addr, pdesc, pbytes);
__asm__ __volatile__ ("l2fetch(%0,%1)" : : "r"(addr), "r"(pdesc));
tbytes += pbytes;
tcnt++;
} else { // Iterate for higher dimension boxes...
// Get iteration stride and extents
int32_t iterstride = stride[iterdim] * elem_size;
int32_t iterextent = extent[iterdim];
iterextent = MIN(iterextent, MAX_PREFETCH); // Limit # of prefetches
DBG_PREFETCH(" stride[%d]*%d=0x%x ext[%d]=%d\n",
iterdim, elem_size, iterstride, iterdim, iterextent);
for (int32_t i = 0; i < iterextent; i++) {
DBG_PREFETCH(" %d: l2fetch(0x%p, 0x%llx): %d bytes\n", i, addr, pdesc, pbytes);
// Range check starting address
if ((addr >= addr_beg) && (addr < addr_end)) {
// Perform prefetch
__asm__ __volatile__ ("l2fetch(%0,%1)" : : "r"(addr), "r"(pdesc));
tbytes += pbytes;
tcnt++;
} else {
DBG_PREFETCH_V(" %d: l2fetch: +0x%x => 0x%p out of range [0x%p, 0x%p]\n",
i, iterstride, addr, addr_beg, addr_end);
}
addr += iterstride;
}
}
// TODO: Opt: Return the number of prefetch instructions (tcnt) issued?
// to not exceed MAX_PREFETCH in a sequence of prefetch ops
// TODO: Opt: Return the size in bytes (tbytes) prefetched?
// to avoid prefetching too much data in one sequence
DBG_PREFETCH(" l2fetch: %d ops, %d bytes\n", tcnt, tbytes);
return 0;
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ft_mmoc.h"
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QDir>
#include <QFile>
#include <QTest>
void Ft_MMoc::initTestCase()
{
m_skipTests = false;
// check for qt moc
m_qtMocFound = QFileInfo( "/usr/bin/moc" ).exists();
// check for mmoc perl script
m_perlMmoc = "/usr/bin/mmoc.pl";
m_perlMmocFound = QFileInfo( m_perlMmoc ).exists();
// check for mmoc binary
m_binaryMmoc = "/usr/bin/mmoc";
m_binaryMmocFound = QFileInfo( m_binaryMmoc ).exists();
}
void Ft_MMoc::cleanupTestCase()
{
}
int Ft_MMoc::runProcess( const QString& process, const QStringList ¶ms )
{
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start( process, params );
if ( !p.waitForStarted() )
{
qCritical( "process start failed" );
return -1;
}
if ( !p.waitForFinished() )
{
qCritical( "process finish failed" );
return -2;
}
return p.exitCode();
}
void Ft_MMoc::doMMoc_data()
{
QTest::addColumn<QString>("mocPath");
QTest::addColumn<QString>("fileName");
// test all .h files in samples subdir.
QStringList files( QDir( "/usr/lib/libmeegotouch-tests/ft_mmoc-samples" ).
entryList( QStringList("*.h") ) );
foreach ( QString file, files )
{
if ( m_qtMocFound && m_binaryMmocFound )
{
QTest::newRow( qPrintable( file + " using " + m_binaryMmoc ) )
<< m_binaryMmoc << file;
}
if ( m_qtMocFound && m_perlMmocFound )
{
QTest::newRow( qPrintable( file + " using " + m_perlMmoc ) )
<< m_perlMmoc << file;
}
}
}
void Ft_MMoc::doMMoc()
{
QFETCH( QString, mocPath );
QFETCH( QString, fileName );
QString path = "/usr/lib/libmeegotouch-tests/ft_mmoc-samples/";
qWarning( "testing: moc: %s file: %s",
qPrintable( mocPath ),
qPrintable( fileName ) );
QString baseName = fileName;
baseName.remove( ".h" );
int result = runProcess( mocPath, QStringList()
<< path + fileName
<< "-o" << "/tmp/moc_" + baseName + ".cpp" );
// check for successful return
QVERIFY( result == 0 );
// now compare files
QVERIFY( compareFiles( "/tmp/moc_" + baseName + ".cpp",
path + "moc_" + baseName + ".cpp.correct" ) );
}
bool Ft_MMoc::compareFiles(const QString &filename, const QString &correctFilename) const
{
bool filesAreTheSame = true;
QFile newFile(filename);
if (!newFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "a Could not open" << filename;
return false;
}
QTextStream newIn(&newFile);
QFile correctFile(correctFilename);
if (!correctFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "b Could not open" << correctFilename;
return false;
}
QTextStream correctIn(&correctFile);
do {
if (newIn.atEnd() || correctIn.atEnd()) {
bool oneFileFinishedBeforeOther = (!newIn.atEnd() || !correctIn.atEnd());
if (oneFileFinishedBeforeOther) {
qDebug( "one file finished before the other" );
filesAreTheSame = false;
}
break;
}
QString newLine = newIn.readLine();
QString correctLine = correctIn.readLine();
// skip exceptional lines
QString headerGuard(QFileInfo(filename).fileName().toUpper().replace(".", "_"));
bool lineIsExceptional =
newLine.contains(headerGuard) ||
newLine.contains("** Created: ") ||
newLine.contains("** by: The Qt Meta Object Compiler version ") ||
newLine.contains("#error \"This file was generated using the moc from") ||
newLine.contains("#include ") ||
newLine.contains("** Meta object code from reading C++ file ") ||
newLine.contains("ft_mservicefwgen")
;
if (lineIsExceptional) {
continue;
}
bool linesAreIdentical = (newLine == correctLine);
if ( ! linesAreIdentical )
{
qDebug() << "got these different lines: new:\n"
<< filename
<< "\n"
<< newLine
<< "\nexpected:\n"
<< correctFilename
<< "\n"
<< correctLine;
}
filesAreTheSame = linesAreIdentical;
} while (filesAreTheSame);
correctFile.close();
newFile.close();
return filesAreTheSame;
}
QTEST_MAIN(Ft_MMoc)
<commit_msg>Changes: Skips ft_mmoc when no development environment is installed.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ft_mmoc.h"
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QDir>
#include <QFile>
#include <QTest>
void Ft_MMoc::initTestCase()
{
m_skipTests = false;
// check for qt moc
m_qtMocFound = QFileInfo( "/usr/bin/moc" ).exists();
// check for mmoc perl script
m_perlMmoc = "/usr/bin/mmoc.pl";
m_perlMmocFound = QFileInfo( m_perlMmoc ).exists();
// check for mmoc binary
m_binaryMmoc = "/usr/bin/mmoc";
m_binaryMmocFound = QFileInfo( m_binaryMmoc ).exists();
if ( !m_binaryMmocFound && !m_perlMmocFound ) {
QSKIP( "need development environment", SkipAll );
}
}
void Ft_MMoc::cleanupTestCase()
{
}
int Ft_MMoc::runProcess( const QString& process, const QStringList ¶ms )
{
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start( process, params );
if ( !p.waitForStarted() )
{
qCritical( "process start failed" );
return -1;
}
if ( !p.waitForFinished() )
{
qCritical( "process finish failed" );
return -2;
}
return p.exitCode();
}
void Ft_MMoc::doMMoc_data()
{
QTest::addColumn<QString>("mocPath");
QTest::addColumn<QString>("fileName");
// test all .h files in samples subdir.
QStringList files( QDir( "/usr/lib/libmeegotouch-tests/ft_mmoc-samples" ).
entryList( QStringList("*.h") ) );
foreach ( QString file, files )
{
if ( m_qtMocFound && m_binaryMmocFound )
{
QTest::newRow( qPrintable( file + " using " + m_binaryMmoc ) )
<< m_binaryMmoc << file;
}
if ( m_qtMocFound && m_perlMmocFound )
{
QTest::newRow( qPrintable( file + " using " + m_perlMmoc ) )
<< m_perlMmoc << file;
}
}
}
void Ft_MMoc::doMMoc()
{
QFETCH( QString, mocPath );
QFETCH( QString, fileName );
QString path = "/usr/lib/libmeegotouch-tests/ft_mmoc-samples/";
qWarning( "testing: moc: %s file: %s",
qPrintable( mocPath ),
qPrintable( fileName ) );
QString baseName = fileName;
baseName.remove( ".h" );
int result = runProcess( mocPath, QStringList()
<< path + fileName
<< "-o" << "/tmp/moc_" + baseName + ".cpp" );
// check for successful return
QVERIFY( result == 0 );
// now compare files
QVERIFY( compareFiles( "/tmp/moc_" + baseName + ".cpp",
path + "moc_" + baseName + ".cpp.correct" ) );
}
bool Ft_MMoc::compareFiles(const QString &filename, const QString &correctFilename) const
{
bool filesAreTheSame = true;
QFile newFile(filename);
if (!newFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "a Could not open" << filename;
return false;
}
QTextStream newIn(&newFile);
QFile correctFile(correctFilename);
if (!correctFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "b Could not open" << correctFilename;
return false;
}
QTextStream correctIn(&correctFile);
do {
if (newIn.atEnd() || correctIn.atEnd()) {
bool oneFileFinishedBeforeOther = (!newIn.atEnd() || !correctIn.atEnd());
if (oneFileFinishedBeforeOther) {
qDebug( "one file finished before the other" );
filesAreTheSame = false;
}
break;
}
QString newLine = newIn.readLine();
QString correctLine = correctIn.readLine();
// skip exceptional lines
QString headerGuard(QFileInfo(filename).fileName().toUpper().replace(".", "_"));
bool lineIsExceptional =
newLine.contains(headerGuard) ||
newLine.contains("** Created: ") ||
newLine.contains("** by: The Qt Meta Object Compiler version ") ||
newLine.contains("#error \"This file was generated using the moc from") ||
newLine.contains("#include ") ||
newLine.contains("** Meta object code from reading C++ file ") ||
newLine.contains("ft_mservicefwgen")
;
if (lineIsExceptional) {
continue;
}
bool linesAreIdentical = (newLine == correctLine);
if ( ! linesAreIdentical )
{
qDebug() << "got these different lines: new:\n"
<< filename
<< "\n"
<< newLine
<< "\nexpected:\n"
<< correctFilename
<< "\n"
<< correctLine;
}
filesAreTheSame = linesAreIdentical;
} while (filesAreTheSame);
correctFile.close();
newFile.close();
return filesAreTheSame;
}
QTEST_MAIN(Ft_MMoc)
<|endoftext|> |
<commit_before>/*********************************************************************/
/* Copyright (c) 2011 - 2012, The University of Texas at Austin. */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT */
/* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */
/* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */
/* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */
/* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */
/* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include "Movie.h"
#include "main.h"
#include "log.h"
Movie::Movie(std::string uri)
{
initialized_ = false;
// defaults
textureId_ = 0;
textureBound_ = false;
avFormatContext_ = NULL;
avCodecContext_ = NULL;
swsContext_ = NULL;
avFrame_ = NULL;
avFrameRGB_ = NULL;
streamIdx_ = -1;
paused_ = false;
loop_ = true;
start_time_ = 0;
duration_ = 0;
num_frames_ = 0;
frame_index_ = 0;
skipped_frames_ = false;
// assign values
uri_ = uri;
// initialize ffmpeg
av_register_all();
// open movie file
if(avformat_open_input(&avFormatContext_, uri.c_str(), NULL, NULL) != 0)
{
put_flog(LOG_ERROR, "could not open movie file %s", uri.c_str());
return;
}
// get stream information
if(avformat_find_stream_info(avFormatContext_, NULL) < 0)
{
put_flog(LOG_ERROR, "could not find stream information");
return;
}
// dump format information to stderr
av_dump_format(avFormatContext_, 0, uri.c_str(), 0);
// find the first video stream
streamIdx_ = -1;
for(unsigned int i=0; i<avFormatContext_->nb_streams; i++)
{
if(avFormatContext_->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
streamIdx_ = i;
break;
}
}
if(streamIdx_ == -1)
{
put_flog(LOG_ERROR, "could not find video stream");
return;
}
videostream_ = avFormatContext_->streams[streamIdx_];
// get a pointer to the codec context for the video stream
avCodecContext_ = videostream_->codec;
// find the decoder for the video stream
AVCodec * codec = avcodec_find_decoder(avCodecContext_->codec_id);
if(codec == NULL)
{
put_flog(LOG_ERROR, "unsupported codec");
return;
}
// open codec
int ret = avcodec_open2(avCodecContext_, codec, NULL);
if(ret < 0)
{
char errbuf[256];
av_strerror(ret, errbuf, 256);
put_flog(LOG_ERROR, "could not open codec, error code %i: %s", ret, errbuf);
return;
}
den2_ = videostream_->time_base.den * videostream_->r_frame_rate.den;
num2_ = videostream_->time_base.num * videostream_->r_frame_rate.num;
// generate seeking parameters
start_time_ = videostream_->start_time;
duration_ = videostream_->duration;
num_frames_ = av_rescale(duration_, num2_, den2_);
frameDuration_ = (double)videostream_->r_frame_rate.den / (double)videostream_->r_frame_rate.num;
put_flog(LOG_DEBUG, "seeking parameters: start_time = %i, duration_ = %i, num frames = %i", start_time_, duration_, num_frames_);
// create texture for movie
QImage image(avCodecContext_->width, avCodecContext_->height, QImage::Format_RGB32);
image.fill(0);
textureId_ = g_mainWindow->getGLWindow()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, QGLContext::LinearFilteringBindOption);
textureBound_ = true;
// allocate video frame for video decoding
avFrame_ = avcodec_alloc_frame();
// allocate video frame for RGB conversion
avFrameRGB_ = avcodec_alloc_frame();
if(avFrame_ == NULL || avFrameRGB_ == NULL)
{
put_flog(LOG_ERROR, "error allocating frames");
return;
}
// get required buffer size and allocate buffer for pFrameRGB
// this memory will be overwritten during frame conversion, but needs to be allocated ahead of time
int numBytes = avpicture_get_size(PIX_FMT_RGBA, avCodecContext_->width, avCodecContext_->height);
uint8_t * buffer = (uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
// assign buffer to pFrameRGB
avpicture_fill((AVPicture *)avFrameRGB_, buffer, PIX_FMT_RGBA, avCodecContext_->width, avCodecContext_->height);
// create sws scaler context
swsContext_ = sws_getContext(avCodecContext_->width, avCodecContext_->height, avCodecContext_->pix_fmt, avCodecContext_->width, avCodecContext_->height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
initialized_ = true;
}
Movie::~Movie()
{
if(textureBound_ == true)
{
// delete bound texture
glDeleteTextures(1, &textureId_); // it appears deleteTexture() below is not actually deleting the texture from the GPU...
g_mainWindow->getGLWindow()->deleteTexture(textureId_);
}
// close the format context
avformat_close_input(&avFormatContext_);
// free scaler context
sws_freeContext(swsContext_);
// free frames
av_free(avFrame_);
av_free(avFrameRGB_);
}
void Movie::getDimensions(int &width, int &height)
{
width = avCodecContext_->width;
height = avCodecContext_->height;
}
void Movie::render(float tX, float tY, float tW, float tH)
{
updateRenderedFrameCount();
if(initialized_ != true)
{
return;
}
// draw the texture
glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureId_);
// on zoom-out, clamp to edge (instead of showing the texture tiled / repeated)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glTexCoord2f(tX,tY);
glVertex2f(0.,0.);
glTexCoord2f(tX+tW,tY);
glVertex2f(1.,0.);
glTexCoord2f(tX+tW,tY+tH);
glVertex2f(1.,1.);
glTexCoord2f(tX,tY+tH);
glVertex2f(0.,1.);
glEnd();
glPopAttrib();
}
void Movie::nextFrame(bool skip)
{
if( !initialized_ || (paused_ && !skipped_frames_) )
return;
// rate limiting
double elapsedSeconds = 999999.;
if( !nextTimestamp_.is_not_a_date_time( ))
elapsedSeconds = (g_displayGroupManager->getTimestamp() -
nextTimestamp_).total_microseconds() / 1000000.;
if( elapsedSeconds < frameDuration_ )
return;
// update timestamp of last frame
nextTimestamp_ = g_displayGroupManager->getTimestamp();
// seeking
// where we should be after we read a frame in this function
if( !paused_ )
++frame_index_;
// if we're skipping this frame, increment the skipped frame counter and return
// otherwise, make sure we're in the correct position in the stream and decode
if( skip )
{
skipped_frames_ = true;
return;
}
// keep track of a desired timestamp if we seek in this frame
int64_t desiredTimestamp = 0;
if( skipped_frames_ )
{
// need to seek
// frame number we want
const int64_t index = (frame_index_) % (num_frames_ + 1);
// timestamp we want
desiredTimestamp = start_time_ + av_rescale(index, den2_, num2_);
// seek to the nearest keyframe before desiredTimestamp and flush buffers
if(avformat_seek_file(avFormatContext_, streamIdx_, 0, desiredTimestamp, desiredTimestamp, 0) != 0)
{
put_flog(LOG_ERROR, "seeking error");
return;
}
avcodec_flush_buffers(avCodecContext_);
skipped_frames_ = false;
}
int avReadStatus = 0;
AVPacket packet;
int frameFinished;
while((avReadStatus = av_read_frame(avFormatContext_, &packet)) >= 0)
{
// make sure packet is from video stream
if(packet.stream_index == streamIdx_)
{
// decode video frame
avcodec_decode_video2(avCodecContext_, avFrame_, &frameFinished, &packet);
// make sure we got a full video frame
if(frameFinished)
{
// note that the last packet decoded will have a DTS corresponding to this frame's PTS
// hence the use of avFrame_->pkt_dts as the timestamp. also, we'll keep reading frames
// until we get to the desired timestamp (in the case that we seeked)
if(desiredTimestamp == 0 || (avFrame_->pkt_dts >= desiredTimestamp))
{
// convert the frame from its native format to RGB
sws_scale(swsContext_, avFrame_->data, avFrame_->linesize, 0, avCodecContext_->height, avFrameRGB_->data, avFrameRGB_->linesize);
// put the RGB image to the already-created texture
// glTexSubImage2D uses the existing texture and is more efficient than other means
glBindTexture(GL_TEXTURE_2D, textureId_);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0,0, avCodecContext_->width, avCodecContext_->height, GL_RGBA, GL_UNSIGNED_BYTE, avFrameRGB_->data[0]);
// free the packet that was allocated by av_read_frame
av_free_packet(&packet);
break;
}
}
}
// free the packet that was allocated by av_read_frame
av_free_packet(&packet);
}
// see if we need to loop
if(avReadStatus < 0 && loop_)
{
av_seek_frame(avFormatContext_, streamIdx_, 0, AVSEEK_FLAG_BACKWARD);
}
}
void Movie::setPause(const bool pause)
{
paused_ = pause;
}
void Movie::setLoop(const bool loop)
{
loop_ = loop;
}
<commit_msg>Fix offset with resized movies on skipped nodes<commit_after>/*********************************************************************/
/* Copyright (c) 2011 - 2012, The University of Texas at Austin. */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT */
/* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */
/* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */
/* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */
/* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */
/* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include "Movie.h"
#include "main.h"
#include "log.h"
Movie::Movie(std::string uri)
{
initialized_ = false;
// defaults
textureId_ = 0;
textureBound_ = false;
avFormatContext_ = NULL;
avCodecContext_ = NULL;
swsContext_ = NULL;
avFrame_ = NULL;
avFrameRGB_ = NULL;
streamIdx_ = -1;
paused_ = false;
loop_ = true;
start_time_ = 0;
duration_ = 0;
num_frames_ = 0;
frame_index_ = 0;
skipped_frames_ = false;
// assign values
uri_ = uri;
// initialize ffmpeg
av_register_all();
// open movie file
if(avformat_open_input(&avFormatContext_, uri.c_str(), NULL, NULL) != 0)
{
put_flog(LOG_ERROR, "could not open movie file %s", uri.c_str());
return;
}
// get stream information
if(avformat_find_stream_info(avFormatContext_, NULL) < 0)
{
put_flog(LOG_ERROR, "could not find stream information");
return;
}
// dump format information to stderr
av_dump_format(avFormatContext_, 0, uri.c_str(), 0);
// find the first video stream
streamIdx_ = -1;
for(unsigned int i=0; i<avFormatContext_->nb_streams; i++)
{
if(avFormatContext_->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
streamIdx_ = i;
break;
}
}
if(streamIdx_ == -1)
{
put_flog(LOG_ERROR, "could not find video stream");
return;
}
videostream_ = avFormatContext_->streams[streamIdx_];
// get a pointer to the codec context for the video stream
avCodecContext_ = videostream_->codec;
// find the decoder for the video stream
AVCodec * codec = avcodec_find_decoder(avCodecContext_->codec_id);
if(codec == NULL)
{
put_flog(LOG_ERROR, "unsupported codec");
return;
}
// open codec
int ret = avcodec_open2(avCodecContext_, codec, NULL);
if(ret < 0)
{
char errbuf[256];
av_strerror(ret, errbuf, 256);
put_flog(LOG_ERROR, "could not open codec, error code %i: %s", ret, errbuf);
return;
}
den2_ = videostream_->time_base.den * videostream_->r_frame_rate.den;
num2_ = videostream_->time_base.num * videostream_->r_frame_rate.num;
// generate seeking parameters
start_time_ = videostream_->start_time;
duration_ = videostream_->duration;
num_frames_ = av_rescale(duration_, num2_, den2_);
frameDuration_ = (double)videostream_->r_frame_rate.den / (double)videostream_->r_frame_rate.num;
put_flog(LOG_DEBUG, "seeking parameters: start_time = %i, duration_ = %i, num frames = %i", start_time_, duration_, num_frames_);
// create texture for movie
QImage image(avCodecContext_->width, avCodecContext_->height, QImage::Format_RGB32);
image.fill(0);
textureId_ = g_mainWindow->getGLWindow()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, QGLContext::LinearFilteringBindOption);
textureBound_ = true;
// allocate video frame for video decoding
avFrame_ = avcodec_alloc_frame();
// allocate video frame for RGB conversion
avFrameRGB_ = avcodec_alloc_frame();
if(avFrame_ == NULL || avFrameRGB_ == NULL)
{
put_flog(LOG_ERROR, "error allocating frames");
return;
}
// get required buffer size and allocate buffer for pFrameRGB
// this memory will be overwritten during frame conversion, but needs to be allocated ahead of time
int numBytes = avpicture_get_size(PIX_FMT_RGBA, avCodecContext_->width, avCodecContext_->height);
uint8_t * buffer = (uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
// assign buffer to pFrameRGB
avpicture_fill((AVPicture *)avFrameRGB_, buffer, PIX_FMT_RGBA, avCodecContext_->width, avCodecContext_->height);
// create sws scaler context
swsContext_ = sws_getContext(avCodecContext_->width, avCodecContext_->height, avCodecContext_->pix_fmt, avCodecContext_->width, avCodecContext_->height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
initialized_ = true;
}
Movie::~Movie()
{
if(textureBound_ == true)
{
// delete bound texture
glDeleteTextures(1, &textureId_); // it appears deleteTexture() below is not actually deleting the texture from the GPU...
g_mainWindow->getGLWindow()->deleteTexture(textureId_);
}
// close the format context
avformat_close_input(&avFormatContext_);
// free scaler context
sws_freeContext(swsContext_);
// free frames
av_free(avFrame_);
av_free(avFrameRGB_);
}
void Movie::getDimensions(int &width, int &height)
{
width = avCodecContext_->width;
height = avCodecContext_->height;
}
void Movie::render(float tX, float tY, float tW, float tH)
{
updateRenderedFrameCount();
if(initialized_ != true)
{
return;
}
// draw the texture
glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureId_);
// on zoom-out, clamp to edge (instead of showing the texture tiled / repeated)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glTexCoord2f(tX,tY);
glVertex2f(0.,0.);
glTexCoord2f(tX+tW,tY);
glVertex2f(1.,0.);
glTexCoord2f(tX+tW,tY+tH);
glVertex2f(1.,1.);
glTexCoord2f(tX,tY+tH);
glVertex2f(0.,1.);
glEnd();
glPopAttrib();
}
void Movie::nextFrame(bool skip)
{
if( !initialized_ || (paused_ && !skipped_frames_) )
return;
// rate limiting
double elapsedSeconds = 999999.;
if( !nextTimestamp_.is_not_a_date_time( ))
elapsedSeconds = (g_displayGroupManager->getTimestamp() -
nextTimestamp_).total_microseconds() / 1000000.;
if( elapsedSeconds < frameDuration_ )
return;
// update timestamp of last frame
nextTimestamp_ = g_displayGroupManager->getTimestamp();
// seeking
// where we should be after we read a frame in this function
if( !paused_ )
++frame_index_;
// if we're skipping this frame, increment the skipped frame counter and return
// otherwise, make sure we're in the correct position in the stream and decode
if( skip )
{
skipped_frames_ = true;
return;
}
// keep track of a desired timestamp if we seek in this frame
int64_t desiredTimestamp = 0;
if( skipped_frames_ )
{
// need to seek
// frame number we want
const int64_t index = (frame_index_-1) % (num_frames_+1);
// timestamp we want
desiredTimestamp = start_time_ + av_rescale(index, den2_, num2_);
// seek to the nearest keyframe before desiredTimestamp and flush buffers
if(avformat_seek_file(avFormatContext_, streamIdx_, 0, desiredTimestamp, desiredTimestamp, 0) != 0)
{
put_flog(LOG_ERROR, "seeking error");
return;
}
avcodec_flush_buffers(avCodecContext_);
skipped_frames_ = false;
}
int avReadStatus = 0;
AVPacket packet;
int frameFinished;
while((avReadStatus = av_read_frame(avFormatContext_, &packet)) >= 0)
{
// make sure packet is from video stream
if(packet.stream_index == streamIdx_)
{
// decode video frame
avcodec_decode_video2(avCodecContext_, avFrame_, &frameFinished, &packet);
// make sure we got a full video frame
if(frameFinished)
{
// note that the last packet decoded will have a DTS corresponding to this frame's PTS
// hence the use of avFrame_->pkt_dts as the timestamp. also, we'll keep reading frames
// until we get to the desired timestamp (in the case that we seeked)
if(desiredTimestamp == 0 || (avFrame_->pkt_dts >= desiredTimestamp))
{
// convert the frame from its native format to RGB
sws_scale(swsContext_, avFrame_->data, avFrame_->linesize, 0, avCodecContext_->height, avFrameRGB_->data, avFrameRGB_->linesize);
// put the RGB image to the already-created texture
// glTexSubImage2D uses the existing texture and is more efficient than other means
glBindTexture(GL_TEXTURE_2D, textureId_);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0,0, avCodecContext_->width, avCodecContext_->height, GL_RGBA, GL_UNSIGNED_BYTE, avFrameRGB_->data[0]);
// free the packet that was allocated by av_read_frame
av_free_packet(&packet);
break;
}
}
}
// free the packet that was allocated by av_read_frame
av_free_packet(&packet);
}
// see if we need to loop
if(avReadStatus < 0 && loop_)
{
av_seek_frame(avFormatContext_, streamIdx_, 0, AVSEEK_FLAG_BACKWARD);
frame_index_ = 0;
}
}
void Movie::setPause(const bool pause)
{
paused_ = pause;
}
void Movie::setLoop(const bool loop)
{
loop_ = loop;
}
<|endoftext|> |
<commit_before>#include "MyTools.h"
#include "Nurse.h"
//-----------------------------------------------------------------------------
//
// S t r u c t u r e S t a t e
//
//-----------------------------------------------------------------------------
// Updates the state if a new day is worked on shift newShift
void State::updateWithNewDay(int newShift){
// Consecutives : +1 iff it is the same as the previous one
consShifts_ = (shift_==newShift) ? (consShifts_ + 1) : 1;
// Consecutive Days Worked : +1 if the new one is worked (!=0), 0 if it is a rest (==0)
consDaysWorked_ = shift_ ? (consDaysWorked_ + 1) : 0;
// Current shift worked : updated with the new one
shift_ = newShift;
}
//-----------------------------------------------------------------------------
//
// S t r u c t u r e P r e f e r e n c e
//
//-----------------------------------------------------------------------------
// Initialization with an vector or size nNurses with no wished Shift-Off
Preferences::Preferences(int nNurses){
nNurses_ = nNurses;
vector<map<int,set<int>>> wishesOff
for(int i=0; i<nNurses; i++){
map<int,set<int>> m;
wishesOff.push_back(m);
}
wishesOff_ = wishesOff;
}
// Add a wished day-shift off for a nurse
void Preferences::addShiftOff(int nurse, int day, int shift){
// If the nurse does not already have a wish for that day -> insert a new emptyset on that day
if(wishesOff_[nurse].find(day) == wishesOff_[nurse].end()){
set<int> emptyset;
wishesOff_[nurse].insert(pair<int,set<int>>(day,emptyset));
}
// Insert the wished shift in the set
wishesOff_[nurse][day].insert(shift);
}
// Returns true if the nurses wants that shift off
bool Preferences::wantsTheShiftOff(int nurse, int day, int shift){
// If the day is not in the wish-list, return false
map<int,set<int>>::iterator itM = wishesOff_[nurse].find(day);
if(itM == wishesOff_[nurse].end())
return false;
// If the shift is not in the wish-list for that day, return false
else if(itM->second.find(shift) == itM->second.end())
return false;
else
return true;
}
<commit_msg>Begin Samuel<commit_after>#include "MyTools.h"
#include "Nurse.h"
//-----------------------------------------------------------------------------
//
// S t r u c t u r e S t a t e
//
//-----------------------------------------------------------------------------
// Updates the state if a new day is worked on shift newShift
void State::updateWithNewDay(int newShift){
// Consecutives : +1 iff it is the same as the previous one
consShifts_ = (shift_==newShift) ? (consShifts_ + 1) : 1;
// Consecutive Days Worked : +1 if the new one is worked (!=0), 0 if it is a rest (==0)
consDaysWorked_ = shift_ ? (consDaysWorked_ + 1) : 0;
// Current shift worked : updated with the new one
shift_ = newShift;
}
//-----------------------------------------------------------------------------
//
// S t r u c t u r e P r e f e r e n c e
//
//-----------------------------------------------------------------------------
// Initialization with an vector or size nNurses with no wished Shift-Off.
Preferences::Preferences(int nNurses){
nNurses_ = nNurses;
vector<map<int,set<int>>> wishesOff
for(int i=0; i<nNurses; i++){
map<int,set<int>> m;
wishesOff.push_back(m);
}
wishesOff_ = wishesOff;
}
// Add a wished day-shift off for a nurse
void Preferences::addShiftOff(int nurse, int day, int shift){
// If the nurse does not already have a wish for that day -> insert a new emptyset on that day
if(wishesOff_[nurse].find(day) == wishesOff_[nurse].end()){
set<int> emptyset;
wishesOff_[nurse].insert(pair<int,set<int>>(day,emptyset));
}
// Insert the wished shift in the set
wishesOff_[nurse][day].insert(shift);
}
// Returns true if the nurses wants that shift off
bool Preferences::wantsTheShiftOff(int nurse, int day, int shift){
// If the day is not in the wish-list, return false
map<int,set<int>>::iterator itM = wishesOff_[nurse].find(day);
if(itM == wishesOff_[nurse].end())
return false;
// If the shift is not in the wish-list for that day, return false
else if(itM->second.find(shift) == itM->second.end())
return false;
else
return true;
}
<|endoftext|> |
<commit_before>#include <limits.h>
#include <gtest/gtest.h>
#include "ramdis.h"
// Global variable for coordinator locator string.
char* coordinatorLocator = NULL;
// Tests GET and SET commands.
TEST(GetSetTest, readWrite) {
Context* context = ramdis_connect(coordinatorLocator);
Object key;
key.data = (void*)"Robert Tyre Jones Jr.";
key.len = strlen((char*)key.data) + 1;
Object value;
value.data = (void*)"Birthday: 1902/03/17, Height: 5'8\", Weight: 165lb";
value.len = strlen((char*)value.data) + 1;
set(context, &key, &value);
Object* obj = get(context, &key);
EXPECT_EQ(value.len, obj->len);
EXPECT_STREQ((char*)value.data, (char*)obj->data);
freeObject(obj);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(LpushTest, pushManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = lpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
ObjectArray* objArray;
objArray = lrange(context, &key, 0, -1);
EXPECT_EQ(totalElements, objArray->len);
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", totalElements - i - 1);
EXPECT_STREQ(valBuf, (char*)objArray->array[i].data);
}
freeObjectArray(objArray);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(RpushTest, pushManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = rpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
ObjectArray* objArray;
objArray = lrange(context, &key, 0, -1);
EXPECT_EQ(totalElements, objArray->len);
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
EXPECT_STREQ(valBuf, (char*)objArray->array[i].data);
}
freeObjectArray(objArray);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(LpopTest, popManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = lpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", totalElements - i - 1);
Object* obj = lpop(context, &key);
EXPECT_STREQ(valBuf, (char*)obj->data);
freeObject(obj);
}
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
// Tests DEL command.
TEST(DelTest, deleteSingleObject) {
Context* context = ramdis_connect(coordinatorLocator);
Object key;
key.data = (void*)"Robert Tyre Jones Jr.";
key.len = strlen((char*)key.data) + 1;
Object value;
value.data = (void*)"Birthday: 1902/03/17, Height: 5'8\", Weight: 165lb";
value.len = strlen((char*)value.data) + 1;
set(context, &key, &value);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
uint64_t n = del(context, &keysArray);
EXPECT_EQ(n, 1);
Object *obj = get(context, &key);
EXPECT_TRUE(obj == NULL);
ramdis_disconnect(context);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-C") == 0) {
coordinatorLocator = argv[i+1];
break;
}
}
if (coordinatorLocator == NULL) {
printf("ERROR: Required -C argument missing for coordinator locator "
"string.\n");
return -1;
}
return RUN_ALL_TESTS();
}
<commit_msg>Added RPOP test.<commit_after>#include <limits.h>
#include <gtest/gtest.h>
#include "ramdis.h"
// Global variable for coordinator locator string.
char* coordinatorLocator = NULL;
// Tests GET and SET commands.
TEST(GetSetTest, readWrite) {
Context* context = ramdis_connect(coordinatorLocator);
Object key;
key.data = (void*)"Robert Tyre Jones Jr.";
key.len = strlen((char*)key.data) + 1;
Object value;
value.data = (void*)"Birthday: 1902/03/17, Height: 5'8\", Weight: 165lb";
value.len = strlen((char*)value.data) + 1;
set(context, &key, &value);
Object* obj = get(context, &key);
EXPECT_EQ(value.len, obj->len);
EXPECT_STREQ((char*)value.data, (char*)obj->data);
freeObject(obj);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(LpushTest, pushManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = lpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
ObjectArray* objArray;
objArray = lrange(context, &key, 0, -1);
EXPECT_EQ(totalElements, objArray->len);
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", totalElements - i - 1);
EXPECT_STREQ(valBuf, (char*)objArray->array[i].data);
}
freeObjectArray(objArray);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(RpushTest, pushManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = rpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
ObjectArray* objArray;
objArray = lrange(context, &key, 0, -1);
EXPECT_EQ(totalElements, objArray->len);
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
EXPECT_STREQ(valBuf, (char*)objArray->array[i].data);
}
freeObjectArray(objArray);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(LpopTest, popManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = lpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", totalElements - i - 1);
Object* obj = lpop(context, &key);
EXPECT_STREQ(valBuf, (char*)obj->data);
freeObject(obj);
}
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
TEST(RpopTest, popManyValues) {
Context* context = ramdis_connect(coordinatorLocator);
/* Number of elements to put in the list. */
uint32_t totalElements = (1<<13);
/* Size of each element in bytes. */
size_t elementSize = 8;
Object key;
key.data = (void*)"mylist";
key.len = strlen((char*)key.data) + 1;
Object value;
char valBuf[elementSize];
value.data = (void*)valBuf;
value.len = elementSize;
uint32_t elemCount;
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
elemCount = lpush(context, &key, &value);
EXPECT_EQ(0, context->err);
EXPECT_EQ(i + 1, elemCount);
}
for (uint32_t i = 0; i < totalElements; i++) {
sprintf(valBuf, "%07d", i);
Object* obj = rpop(context, &key);
EXPECT_STREQ(valBuf, (char*)obj->data);
freeObject(obj);
}
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
del(context, &keysArray);
ramdis_disconnect(context);
}
// Tests DEL command.
TEST(DelTest, deleteSingleObject) {
Context* context = ramdis_connect(coordinatorLocator);
Object key;
key.data = (void*)"Robert Tyre Jones Jr.";
key.len = strlen((char*)key.data) + 1;
Object value;
value.data = (void*)"Birthday: 1902/03/17, Height: 5'8\", Weight: 165lb";
value.len = strlen((char*)value.data) + 1;
set(context, &key, &value);
ObjectArray keysArray;
keysArray.array = &key;
keysArray.len = 1;
uint64_t n = del(context, &keysArray);
EXPECT_EQ(n, 1);
Object *obj = get(context, &key);
EXPECT_TRUE(obj == NULL);
ramdis_disconnect(context);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-C") == 0) {
coordinatorLocator = argv[i+1];
break;
}
}
if (coordinatorLocator == NULL) {
printf("ERROR: Required -C argument missing for coordinator locator "
"string.\n");
return -1;
}
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <bts/net/chain_downloader.hpp>
#include <bts/net/chain_server_commands.hpp>
#include <fc/network/tcp_socket.hpp>
#include <fc/io/raw_variant.hpp>
#include <fc/thread/thread.hpp>
namespace bts { namespace net {
namespace detail {
class chain_downloader_impl {
public:
chain_downloader* self;
std::unique_ptr<fc::tcp_socket> _client_socket;
std::vector<fc::ip::endpoint> _chain_servers;
void connect_to_chain_server()
{ try {
auto next_server = _chain_servers.begin();
_client_socket = std::unique_ptr<fc::tcp_socket>(new fc::tcp_socket);
while(!_client_socket->is_open() && next_server != _chain_servers.end()) {
_client_socket = std::unique_ptr<fc::tcp_socket>(new fc::tcp_socket);
try {
_client_socket->connect_to(*(next_server++));
} catch (const fc::exception& e) {
wlog("Failed to connect to chain_server: ${e}", ("e", e.to_detail_string()));
_client_socket->close();
continue;
}
uint32_t protocol_version = -1;
fc::raw::unpack(*_client_socket, protocol_version);
if (protocol_version != PROTOCOL_VERSION) {
wlog("Can't talk to chain server; he's using protocol ${srv} and I'm using ${cli}!",
("srv", protocol_version)("cli", PROTOCOL_VERSION));
fc::raw::pack(*_client_socket, finish);
_client_socket->close();
}
}
} FC_RETHROW_EXCEPTIONS(error, "") }
void get_all_blocks(std::function<void (const blockchain::full_block&)> new_block_callback,
uint32_t first_block_number)
{ try {
if (!new_block_callback)
return;
connect_to_chain_server();
FC_ASSERT(_client_socket->is_open(), "unable to connect to any chain server");
ilog("Connected to ${remote}; requesting blocks after ${num}",
("remote", _client_socket->remote_endpoint())("num", first_block_number));
ulog("Starting fast-sync of blocks from ${num}", ("num", first_block_number));
auto start_time = fc::time_point::now();
fc::raw::pack(*_client_socket, get_blocks_from_number);
fc::raw::pack(*_client_socket, first_block_number);
uint32_t blocks_to_retrieve = 0;
uint32_t blocks_in = 0;
fc::raw::unpack(*_client_socket, blocks_to_retrieve);
ilog("Server at ${remote} is sending us ${num} blocks.",
("remote", _client_socket->remote_endpoint())("num", blocks_to_retrieve));
while(blocks_to_retrieve > 0)
{
blockchain::full_block block;
fc::raw::unpack(*_client_socket, block);
new_block_callback(block);
--blocks_to_retrieve;
++blocks_in;
if(blocks_to_retrieve == 0) {
fc::raw::unpack(*_client_socket, blocks_to_retrieve);
if(blocks_to_retrieve > 0)
ilog("Server at ${remote} is sending us ${num} blocks.",
("remote", _client_socket->remote_endpoint())("num", blocks_to_retrieve));
}
}
ulog("Finished fast-syncing ${num} blocks at ${rate} blocks/sec.",
("num", blocks_in)("rate", blocks_in/((fc::time_point::now() - start_time).count() / 1000000.0)));
ilog("Finished getting ${num} blocks from ${remote}",
("num", blocks_in)("remote", _client_socket->remote_endpoint()));
fc::raw::pack(*_client_socket, finish);
} FC_RETHROW_EXCEPTIONS(error, "", ("first_block_number", first_block_number))
}
};
} //namespace detail
chain_downloader::chain_downloader(std::vector<fc::ip::endpoint> chain_servers)
: my(new detail::chain_downloader_impl)
{
my->self = this;
add_chain_servers(chain_servers);
}
chain_downloader::~chain_downloader()
{}
void chain_downloader::add_chain_server(const fc::ip::endpoint& server)
{
if(std::find(my->_chain_servers.begin(), my->_chain_servers.end(), server) == my->_chain_servers.end())
my->_chain_servers.push_back(server);
}
void chain_downloader::add_chain_servers(const std::vector<fc::ip::endpoint>& servers)
{
my->_chain_servers.reserve(my->_chain_servers.size() + servers.size());
for (auto server : servers)
add_chain_server(server);
my->_chain_servers.shrink_to_fit();
}
fc::future<void> chain_downloader::get_all_blocks(std::function<void (const blockchain::full_block&)> new_block_callback,
uint32_t first_block_number)
{
return fc::async([=]{my->get_all_blocks(new_block_callback, first_block_number);});
}
} } //namespace bts::blockchain
<commit_msg>Log chain downloader completion and rate<commit_after>#include <algorithm>
#include <bts/net/chain_downloader.hpp>
#include <bts/net/chain_server_commands.hpp>
#include <fc/network/tcp_socket.hpp>
#include <fc/io/raw_variant.hpp>
#include <fc/thread/thread.hpp>
namespace bts { namespace net {
namespace detail {
class chain_downloader_impl {
public:
chain_downloader* self;
std::unique_ptr<fc::tcp_socket> _client_socket;
std::vector<fc::ip::endpoint> _chain_servers;
void connect_to_chain_server()
{ try {
auto next_server = _chain_servers.begin();
_client_socket = std::unique_ptr<fc::tcp_socket>(new fc::tcp_socket);
while(!_client_socket->is_open() && next_server != _chain_servers.end()) {
_client_socket = std::unique_ptr<fc::tcp_socket>(new fc::tcp_socket);
try {
_client_socket->connect_to(*(next_server++));
} catch (const fc::exception& e) {
wlog("Failed to connect to chain_server: ${e}", ("e", e.to_detail_string()));
_client_socket->close();
continue;
}
uint32_t protocol_version = -1;
fc::raw::unpack(*_client_socket, protocol_version);
if (protocol_version != PROTOCOL_VERSION) {
wlog("Can't talk to chain server; he's using protocol ${srv} and I'm using ${cli}!",
("srv", protocol_version)("cli", PROTOCOL_VERSION));
fc::raw::pack(*_client_socket, finish);
_client_socket->close();
}
}
} FC_RETHROW_EXCEPTIONS(error, "") }
void get_all_blocks(std::function<void (const blockchain::full_block&)> new_block_callback,
uint32_t first_block_number)
{ try {
if (!new_block_callback)
return;
connect_to_chain_server();
FC_ASSERT(_client_socket->is_open(), "unable to connect to any chain server");
ilog("Connected to ${remote}; requesting blocks after ${num}",
("remote", _client_socket->remote_endpoint())("num", first_block_number));
ulog("Starting fast-sync of blocks from ${num}", ("num", first_block_number));
auto start_time = fc::time_point::now();
fc::raw::pack(*_client_socket, get_blocks_from_number);
fc::raw::pack(*_client_socket, first_block_number);
uint32_t blocks_to_retrieve = 0;
uint32_t blocks_in = 0;
fc::raw::unpack(*_client_socket, blocks_to_retrieve);
ilog("Server at ${remote} is sending us ${num} blocks.",
("remote", _client_socket->remote_endpoint())("num", blocks_to_retrieve));
while(blocks_to_retrieve > 0)
{
blockchain::full_block block;
fc::raw::unpack(*_client_socket, block);
new_block_callback(block);
--blocks_to_retrieve;
++blocks_in;
if(blocks_to_retrieve == 0) {
fc::raw::unpack(*_client_socket, blocks_to_retrieve);
if(blocks_to_retrieve > 0)
ilog("Server at ${remote} is sending us ${num} blocks.",
("remote", _client_socket->remote_endpoint())("num", blocks_to_retrieve));
}
}
ulog("Finished fast-syncing ${num} blocks at ${rate} blocks/sec.",
("num", blocks_in)("rate", blocks_in/((fc::time_point::now() - start_time).count() / 1000000.0)));
wlog("Finished getting ${num} blocks from ${remote} at ${rate} blocks/sec.",
("num", blocks_in)("remote", _client_socket->remote_endpoint())
("rate", blocks_in/((fc::time_point::now() - start_time).count() / 1000000.0)));
fc::raw::pack(*_client_socket, finish);
} FC_RETHROW_EXCEPTIONS(error, "", ("first_block_number", first_block_number))
}
};
} //namespace detail
chain_downloader::chain_downloader(std::vector<fc::ip::endpoint> chain_servers)
: my(new detail::chain_downloader_impl)
{
my->self = this;
add_chain_servers(chain_servers);
}
chain_downloader::~chain_downloader()
{}
void chain_downloader::add_chain_server(const fc::ip::endpoint& server)
{
if(std::find(my->_chain_servers.begin(), my->_chain_servers.end(), server) == my->_chain_servers.end())
my->_chain_servers.push_back(server);
}
void chain_downloader::add_chain_servers(const std::vector<fc::ip::endpoint>& servers)
{
my->_chain_servers.reserve(my->_chain_servers.size() + servers.size());
for (auto server : servers)
add_chain_server(server);
my->_chain_servers.shrink_to_fit();
}
fc::future<void> chain_downloader::get_all_blocks(std::function<void (const blockchain::full_block&)> new_block_callback,
uint32_t first_block_number)
{
return fc::async([=]{my->get_all_blocks(new_block_callback, first_block_number);});
}
} } //namespace bts::blockchain
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/base/processors/imagestackvolumesource.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/image/imageram.h>
#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/io/datareaderfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/stdextensions.h>
#include <inviwo/core/util/vectoroperations.h>
#include <inviwo/core/io/datareaderexception.h>
namespace inviwo {
namespace {
template <typename Format>
struct FloatOrIntMax32
: std::integral_constant<bool, Format::numtype == NumericType::Float || Format::compsize <= 4> {
};
} // namespace
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo ImageStackVolumeSource::processorInfo_{
"org.inviwo.ImageStackVolumeSource", // Class identifier
"Image Stack Volume Source", // Display name
"Data Input", // Category
CodeState::Stable, // Code state
"Layer, Image, Volume", // Tags
};
const ProcessorInfo ImageStackVolumeSource::getProcessorInfo() const { return processorInfo_; }
ImageStackVolumeSource::ImageStackVolumeSource()
: Processor()
, outport_("volume")
, filePattern_("filePattern", "File Pattern", "####.jpeg", "")
, skipUnsupportedFiles_("skipUnsupportedFiles", "Skip Unsupported Files", false)
// volume parameters
, voxelSpacing_("voxelSpacing", "Voxel Spacing", vec3(1.0f), vec3(0.1f), vec3(10.0f),
vec3(0.1f))
, basis_("Basis", "Basis and offset")
, information_("Information", "Data information") {
addPort(outport_);
addProperty(filePattern_);
addProperty(skipUnsupportedFiles_);
addProperty(voxelSpacing_);
addProperty(information_);
addProperty(basis_);
validExtensions_ =
InviwoApplication::getPtr()->getDataReaderFactory()->getExtensionsForType<Layer>();
filePattern_.onChange([this]() { load(); });
voxelSpacing_.onChange([this]() {
// update volume basis and offset
updateVolumeBasis();
invalidate(InvalidationLevel::InvalidOutput);
});
filePattern_.onChange([&]() { isReady_.update(); });
isReady_.setUpdate([this]() { return !filePattern_.getFileList().empty(); });
}
void ImageStackVolumeSource::process() {
if (isDeserializing_) return;
if (dirty_) {
load();
dirty_ = false;
}
if (volume_) {
basis_.updateEntity(*volume_);
information_.updateVolume(*volume_);
}
}
bool ImageStackVolumeSource::isValidImageFile(std::string fileName) {
std::string fileExtension = toLower(filesystem::getFileExtension(fileName));
return util::contains_if(validExtensions_,
[&](const FileExtension& e) { return e.extension_ == fileExtension; });
}
void ImageStackVolumeSource::load() { load(false); }
void ImageStackVolumeSource::load(bool deserialized) {
if (isDeserializing_) return;
std::vector<std::string> filesInDirectory = filePattern_.getFileList();
if (filesInDirectory.empty()) return;
std::vector<std::string> fileNames;
for (size_t i = 0; i < filesInDirectory.size(); i++) {
if (isValidImageFile(filesInDirectory[i])) {
fileNames.push_back(filesInDirectory[i]);
}
}
if (!fileNames.size()) {
LogWarn("No images found in '" << filePattern_.getFilePatternPath() << "'");
return;
}
using ReaderMap = std::map<std::string, std::unique_ptr<DataReaderType<Layer>>>;
ReaderMap readerMap;
size_t numSlices = 0;
// determine number of slices and file readers for all images
for (auto file : fileNames) {
std::string fileExtension = toLower(filesystem::getFileExtension(file));
if (readerMap.find(fileExtension) != readerMap.end()) {
// reader already exists for this format
++numSlices;
continue;
}
auto reader = InviwoApplication::getPtr()
->getDataReaderFactory()
->getReaderForTypeAndExtension<Layer>(fileExtension);
if (!reader && skipUnsupportedFiles_.get()) {
// ignore file entirely
continue;
}
readerMap[fileExtension] = std::move(reader);
++numSlices;
}
if (readerMap.empty()) {
// could not find any suitable data reader for the images
LogWarn("Image formats not supported");
return;
}
auto getReaderIt = [&readerMap](const std::string& filename) {
return readerMap.find(toLower(filesystem::getFileExtension(filename)));
};
// use first image to determine the volume size
size2_t layerDims{0u, 0u};
// const DataFormatBase* format = nullptr;
try {
size_t slice = 0;
// skip slices with unsupported image formats
while (getReaderIt(fileNames[slice]) == readerMap.end()) {
++slice;
}
auto imgLayer = getReaderIt(fileNames[slice])->second->readData(fileNames[slice]);
// Call getRepresentation here to force read a ram representation.
// Otherwise the default image size, i.e. 256x265, will be reported
// until you do the conversion since the LayerDisk does not provide any metadata.
auto layerRAM = imgLayer->getRepresentation<LayerRAM>();
layerDims = imgLayer->getDimensions();
if ((layerDims.x == 0) || (layerDims.y == 0)) {
LogError("Could not extract valid image dimensions from '" << fileNames[slice] << "'");
return;
}
volume_ = layerRAM->dispatch<std::shared_ptr<Volume>, FloatOrIntMax32>(
[&](auto baselayerprecision) {
using ValueType = util::PrecsionValueType<decltype(baselayerprecision)>;
using PrimitiveType = typename DataFormat<ValueType>::primitive;
const size3_t volSize(layerDims, numSlices);
// create matching volume representation
auto volumeRAM = std::make_shared<VolumeRAMPrecision<ValueType>>(volSize);
auto volume = std::make_shared<Volume>(volumeRAM);
volume->dataMap_.dataRange =
dvec2{DataFormat<PrimitiveType>::lowest(), DataFormat<PrimitiveType>::max()};
volume->dataMap_.valueRange =
dvec2{DataFormat<PrimitiveType>::lowest(), DataFormat<PrimitiveType>::max()};
auto volData = volumeRAM->getDataTyped();
const size_t sliceOffset = glm::compMul(layerDims);
// initalize volume slices before current one
std::fill(volData, volData + slice * sliceOffset, ValueType{0});
// copy first image layer into volume
auto layerDataBase = baselayerprecision->getDataTyped();
std::copy(layerDataBase, layerDataBase + sliceOffset,
volData + slice * sliceOffset);
// load remaining slices
++slice;
while (slice < numSlices) {
auto it = getReaderIt(fileNames[slice]);
if (it == readerMap.end()) {
// reader does not exist for this format
std::fill(volData + slice * sliceOffset,
volData + (slice + 1) * sliceOffset, ValueType{0});
++slice;
continue;
}
try {
auto layer = (*it).second->readData(fileNames[slice]);
if (layer->getDimensions() != layerDims) {
// rescale layer if necessary
layer->setDimensions(layerDims);
}
layer->getRepresentation<LayerRAM>()->dispatch<void, FloatOrIntMax32>(
[&](auto layerpr) {
using ValueTypeLayer = util::PrecsionValueType<decltype(layerpr)>;
if ((DataFormat<ValueType>::numtype != NumericType::Float) &&
(DataFormat<ValueType>::compsize > 4)) {
throw DataReaderException(
std::string{"Unsupported integer bit depth ("} +
std::to_string(DataFormat<ValueType>::precision()) + ")");
}
auto layerData = layerpr->getDataTyped();
std::transform(
layerData, layerData + sliceOffset,
volData + slice * sliceOffset, [](auto value) {
return util::glm_convert_normalized<typename ValueType>(
value);
});
});
} catch (DataReaderException const& e) {
LogProcessorError("Could not load image: " << fileNames[slice] << ", "
<< e.getMessage());
std::fill(volData + slice * sliceOffset,
volData + (slice + 1) * sliceOffset, ValueType{0});
}
++slice;
}
return volume;
});
} catch (DataReaderException const& e) {
LogProcessorError("Could not load image: " << fileNames.front() << ", " << e.getMessage());
return;
}
/*
if ((layerDims.x == 0) || (layerDims.y == 0) || !format) {
LogError("Invalid layer dimensions/format for volume");
return;
}
// create a volume GL representation
auto volumeRAM = createVolumeRAM(volSize, format);
volume_ = std::make_shared<Volume>(volumeRAM);
volume_->dataMap_.dataRange = dvec2{format->getLowest(), format->getMax()};
volume_->dataMap_.valueRange = dvec2{format->getLowest(), format->getMax()};
// set physical size of volume
updateVolumeBasis(deserialized);
volumeRAM->dispatch<void, FloatOrIntMax32>([&](auto volumeprecision) {
using ValueType = util::PrecsionValueType<decltype(volumeprecision)>;
using PrimitiveType = typename DataFormat<ValueType>::primitive;
auto volData = volumeprecision->getDataTyped();
const size_t sliceOffset = glm::compMul(layerDims);
size_t slice = 0;
for (auto file : fileNames) {
// load image into texture
std::string fileExtension = toLower(filesystem::getFileExtension(file));
auto it = readerMap.find(fileExtension);
if (it == readerMap.end()) {
// reader does not exist for this format
std::fill(volData + slice * sliceOffset, volData + (slice + 1) * sliceOffset,
ValueType{0});
++slice;
continue;
}
try {
auto layer = (*it).second->readData(file);
if (layer->getDimensions() != layerDims) {
// rescale layer if necessary
layer->setDimensions(layerDims);
}
layer->getRepresentation<LayerRAM>()->dispatch<void, FloatOrIntMax32>(
[&](auto layerpr) {
auto layerData = layerpr->getDataTyped();
std::transform(
layerData, layerData + sliceOffset, volData + slice * sliceOffset,
[](auto value) {
return util::glm_convert_normalized<typename ValueType>(value);
});
});
} catch (DataReaderException const& e) {
LogProcessorError("Could not load image: " << file << ", " << e.getMessage());
std::fill(volData + slice * sliceOffset, volData + (slice + 1) * sliceOffset,
ValueType{0});
}
++slice;
}
});
*/
basis_.updateForNewEntity(*volume_, deserialized);
information_.updateForNewVolume(*volume_, deserialized);
outport_.setData(volume_);
}
void ImageStackVolumeSource::deserialize(Deserializer& d) {
isDeserializing_ = true;
Processor::deserialize(d);
isDeserializing_ = false;
dirty_ = true;
}
void ImageStackVolumeSource::updateVolumeBasis(bool deserialized) {
if (!volume_) {
return;
}
size3_t layerDims{volume_->getDimensions()};
vec3 spacing{voxelSpacing_.get()};
double aspectRatio = static_cast<double>(layerDims.x) / static_cast<double>(layerDims.y);
// consider voxel spacing
aspectRatio *= spacing.x / spacing.y;
vec3 scale{2.0f};
if (aspectRatio > 1.0) {
scale.y /= static_cast<float>(aspectRatio);
scale.z = scale.x / (layerDims.x * spacing.x) * (layerDims.z * spacing.z);
} else {
scale.x *= static_cast<float>(aspectRatio);
scale.z = scale.y / (layerDims.y * spacing.y) * (layerDims.z * spacing.z);
}
mat3 basis(glm::scale(scale));
vec3 offset(-scale);
offset *= 0.5;
volume_->setBasis(basis);
volume_->setOffset(offset);
basis_.updateForNewEntity(*volume_, deserialized);
}
} // namespace inviwo
<commit_msg>Base: clang fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/base/processors/imagestackvolumesource.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>
#include <inviwo/core/datastructures/image/imageram.h>
#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/io/datareaderfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/stdextensions.h>
#include <inviwo/core/util/vectoroperations.h>
#include <inviwo/core/io/datareaderexception.h>
namespace inviwo {
namespace {
template <typename Format>
struct FloatOrIntMax32
: std::integral_constant<bool, Format::numtype == NumericType::Float || Format::compsize <= 4> {
};
} // namespace
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo ImageStackVolumeSource::processorInfo_{
"org.inviwo.ImageStackVolumeSource", // Class identifier
"Image Stack Volume Source", // Display name
"Data Input", // Category
CodeState::Stable, // Code state
"Layer, Image, Volume", // Tags
};
const ProcessorInfo ImageStackVolumeSource::getProcessorInfo() const { return processorInfo_; }
ImageStackVolumeSource::ImageStackVolumeSource()
: Processor()
, outport_("volume")
, filePattern_("filePattern", "File Pattern", "####.jpeg", "")
, skipUnsupportedFiles_("skipUnsupportedFiles", "Skip Unsupported Files", false)
// volume parameters
, voxelSpacing_("voxelSpacing", "Voxel Spacing", vec3(1.0f), vec3(0.1f), vec3(10.0f),
vec3(0.1f))
, basis_("Basis", "Basis and offset")
, information_("Information", "Data information") {
addPort(outport_);
addProperty(filePattern_);
addProperty(skipUnsupportedFiles_);
addProperty(voxelSpacing_);
addProperty(information_);
addProperty(basis_);
validExtensions_ =
InviwoApplication::getPtr()->getDataReaderFactory()->getExtensionsForType<Layer>();
filePattern_.onChange([this]() { load(); });
voxelSpacing_.onChange([this]() {
// update volume basis and offset
updateVolumeBasis();
invalidate(InvalidationLevel::InvalidOutput);
});
filePattern_.onChange([&]() { isReady_.update(); });
isReady_.setUpdate([this]() { return !filePattern_.getFileList().empty(); });
}
void ImageStackVolumeSource::process() {
if (isDeserializing_) return;
if (dirty_) {
load();
dirty_ = false;
}
if (volume_) {
basis_.updateEntity(*volume_);
information_.updateVolume(*volume_);
}
}
bool ImageStackVolumeSource::isValidImageFile(std::string fileName) {
std::string fileExtension = toLower(filesystem::getFileExtension(fileName));
return util::contains_if(validExtensions_,
[&](const FileExtension& e) { return e.extension_ == fileExtension; });
}
void ImageStackVolumeSource::load() { load(false); }
void ImageStackVolumeSource::load(bool deserialized) {
if (isDeserializing_) return;
std::vector<std::string> filesInDirectory = filePattern_.getFileList();
if (filesInDirectory.empty()) return;
std::vector<std::string> fileNames;
for (size_t i = 0; i < filesInDirectory.size(); i++) {
if (isValidImageFile(filesInDirectory[i])) {
fileNames.push_back(filesInDirectory[i]);
}
}
if (!fileNames.size()) {
LogWarn("No images found in '" << filePattern_.getFilePatternPath() << "'");
return;
}
using ReaderMap = std::map<std::string, std::unique_ptr<DataReaderType<Layer>>>;
ReaderMap readerMap;
size_t numSlices = 0;
// determine number of slices and file readers for all images
for (auto file : fileNames) {
std::string fileExtension = toLower(filesystem::getFileExtension(file));
if (readerMap.find(fileExtension) != readerMap.end()) {
// reader already exists for this format
++numSlices;
continue;
}
auto reader = InviwoApplication::getPtr()
->getDataReaderFactory()
->getReaderForTypeAndExtension<Layer>(fileExtension);
if (!reader && skipUnsupportedFiles_.get()) {
// ignore file entirely
continue;
}
readerMap[fileExtension] = std::move(reader);
++numSlices;
}
if (readerMap.empty()) {
// could not find any suitable data reader for the images
LogWarn("Image formats not supported");
return;
}
auto getReaderIt = [&readerMap](const std::string& filename) {
return readerMap.find(toLower(filesystem::getFileExtension(filename)));
};
// use first image to determine the volume size
size2_t layerDims{0u, 0u};
// const DataFormatBase* format = nullptr;
try {
size_t slice = 0;
// skip slices with unsupported image formats
while (getReaderIt(fileNames[slice]) == readerMap.end()) {
++slice;
}
auto imgLayer = getReaderIt(fileNames[slice])->second->readData(fileNames[slice]);
// Call getRepresentation here to force read a ram representation.
// Otherwise the default image size, i.e. 256x265, will be reported
// until you do the conversion since the LayerDisk does not provide any metadata.
auto layerRAM = imgLayer->getRepresentation<LayerRAM>();
layerDims = imgLayer->getDimensions();
if ((layerDims.x == 0) || (layerDims.y == 0)) {
LogError("Could not extract valid image dimensions from '" << fileNames[slice] << "'");
return;
}
volume_ = layerRAM->dispatch<std::shared_ptr<Volume>, FloatOrIntMax32>(
[&](auto baselayerprecision) {
using ValueType = util::PrecsionValueType<decltype(baselayerprecision)>;
using PrimitiveType = typename DataFormat<ValueType>::primitive;
const size3_t volSize(layerDims, numSlices);
// create matching volume representation
auto volumeRAM = std::make_shared<VolumeRAMPrecision<ValueType>>(volSize);
auto volume = std::make_shared<Volume>(volumeRAM);
volume->dataMap_.dataRange =
dvec2{DataFormat<PrimitiveType>::lowest(), DataFormat<PrimitiveType>::max()};
volume->dataMap_.valueRange =
dvec2{DataFormat<PrimitiveType>::lowest(), DataFormat<PrimitiveType>::max()};
auto volData = volumeRAM->getDataTyped();
const size_t sliceOffset = glm::compMul(layerDims);
// initalize volume slices before current one
std::fill(volData, volData + slice * sliceOffset, ValueType{0});
// copy first image layer into volume
auto layerDataBase = baselayerprecision->getDataTyped();
std::copy(layerDataBase, layerDataBase + sliceOffset,
volData + slice * sliceOffset);
// load remaining slices
++slice;
while (slice < numSlices) {
auto it = getReaderIt(fileNames[slice]);
if (it == readerMap.end()) {
// reader does not exist for this format
std::fill(volData + slice * sliceOffset,
volData + (slice + 1) * sliceOffset, ValueType{0});
++slice;
continue;
}
try {
auto layer = (*it).second->readData(fileNames[slice]);
if (layer->getDimensions() != layerDims) {
// rescale layer if necessary
layer->setDimensions(layerDims);
}
layer->getRepresentation<LayerRAM>()->dispatch<void, FloatOrIntMax32>(
[&](auto layerpr) {
using ValueTypeLayer = util::PrecsionValueType<decltype(layerpr)>;
if ((DataFormat<ValueType>::numtype != NumericType::Float) &&
(DataFormat<ValueType>::compsize > 4)) {
throw DataReaderException(
std::string{"Unsupported integer bit depth ("} +
std::to_string(DataFormat<ValueType>::precision()) + ")");
}
auto layerData = layerpr->getDataTyped();
std::transform(
layerData, layerData + sliceOffset,
volData + slice * sliceOffset, [](auto value) {
return util::glm_convert_normalized<ValueType>(value);
});
});
} catch (DataReaderException const& e) {
LogProcessorError("Could not load image: " << fileNames[slice] << ", "
<< e.getMessage());
std::fill(volData + slice * sliceOffset,
volData + (slice + 1) * sliceOffset, ValueType{0});
}
++slice;
}
return volume;
});
} catch (DataReaderException const& e) {
LogProcessorError("Could not load image: " << fileNames.front() << ", " << e.getMessage());
return;
}
/*
if ((layerDims.x == 0) || (layerDims.y == 0) || !format) {
LogError("Invalid layer dimensions/format for volume");
return;
}
// create a volume GL representation
auto volumeRAM = createVolumeRAM(volSize, format);
volume_ = std::make_shared<Volume>(volumeRAM);
volume_->dataMap_.dataRange = dvec2{format->getLowest(), format->getMax()};
volume_->dataMap_.valueRange = dvec2{format->getLowest(), format->getMax()};
// set physical size of volume
updateVolumeBasis(deserialized);
volumeRAM->dispatch<void, FloatOrIntMax32>([&](auto volumeprecision) {
using ValueType = util::PrecsionValueType<decltype(volumeprecision)>;
using PrimitiveType = typename DataFormat<ValueType>::primitive;
auto volData = volumeprecision->getDataTyped();
const size_t sliceOffset = glm::compMul(layerDims);
size_t slice = 0;
for (auto file : fileNames) {
// load image into texture
std::string fileExtension = toLower(filesystem::getFileExtension(file));
auto it = readerMap.find(fileExtension);
if (it == readerMap.end()) {
// reader does not exist for this format
std::fill(volData + slice * sliceOffset, volData + (slice + 1) * sliceOffset,
ValueType{0});
++slice;
continue;
}
try {
auto layer = (*it).second->readData(file);
if (layer->getDimensions() != layerDims) {
// rescale layer if necessary
layer->setDimensions(layerDims);
}
layer->getRepresentation<LayerRAM>()->dispatch<void, FloatOrIntMax32>(
[&](auto layerpr) {
auto layerData = layerpr->getDataTyped();
std::transform(
layerData, layerData + sliceOffset, volData + slice * sliceOffset,
[](auto value) {
return util::glm_convert_normalized<typename ValueType>(value);
});
});
} catch (DataReaderException const& e) {
LogProcessorError("Could not load image: " << file << ", " << e.getMessage());
std::fill(volData + slice * sliceOffset, volData + (slice + 1) * sliceOffset,
ValueType{0});
}
++slice;
}
});
*/
basis_.updateForNewEntity(*volume_, deserialized);
information_.updateForNewVolume(*volume_, deserialized);
outport_.setData(volume_);
}
void ImageStackVolumeSource::deserialize(Deserializer& d) {
isDeserializing_ = true;
Processor::deserialize(d);
isDeserializing_ = false;
dirty_ = true;
}
void ImageStackVolumeSource::updateVolumeBasis(bool deserialized) {
if (!volume_) {
return;
}
size3_t layerDims{volume_->getDimensions()};
vec3 spacing{voxelSpacing_.get()};
double aspectRatio = static_cast<double>(layerDims.x) / static_cast<double>(layerDims.y);
// consider voxel spacing
aspectRatio *= spacing.x / spacing.y;
vec3 scale{2.0f};
if (aspectRatio > 1.0) {
scale.y /= static_cast<float>(aspectRatio);
scale.z = scale.x / (layerDims.x * spacing.x) * (layerDims.z * spacing.z);
} else {
scale.x *= static_cast<float>(aspectRatio);
scale.z = scale.y / (layerDims.y * spacing.y) * (layerDims.z * spacing.z);
}
mat3 basis(glm::scale(scale));
vec3 offset(-scale);
offset *= 0.5;
volume_->setBasis(basis);
volume_->setOffset(offset);
basis_.updateForNewEntity(*volume_, deserialized);
}
} // namespace inviwo
<|endoftext|> |
<commit_before>#include <assert.h>
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#define SHUT_RDWR SD_BOTH
#else // WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <fcntl.h>
#endif // !WIN32
#include <unordered_map>
#include <set>
#include "connection.h"
#include "utils.h"
class GlobalNetProcess {
public:
std::mutex fd_map_mutex;
std::unordered_map<int, Connection*> fd_map;
#ifndef WIN32
int pipe_write;
#endif
static void do_net_process(GlobalNetProcess* me) {
fd_set fd_set_read, fd_set_write;
struct timeval timeout;
#ifndef WIN32
int pipefd[2];
ALWAYS_ASSERT(!pipe(pipefd));
fcntl(pipefd[1], F_SETFL, fcntl(pipefd[1], F_GETFL) | O_NONBLOCK);
fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK);
me->pipe_write = pipefd[1];
#endif
while (true) {
#ifndef WIN32
timeout.tv_sec = 86400;
timeout.tv_usec = 20 * 1000;
#else
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
#endif
FD_ZERO(&fd_set_read); FD_ZERO(&fd_set_write);
#ifndef WIN32
int max = pipefd[0];
FD_SET(pipefd[0], &fd_set_read);
#else
int max = 0;
#endif
auto now = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(me->fd_map_mutex);
for (const auto& e : me->fd_map) {
ALWAYS_ASSERT(e.first < FD_SETSIZE);
if (e.second->total_inbound_size < 65536)
FD_SET(e.first, &fd_set_read);
if (e.second->total_waiting_size > 0) {
FD_SET(e.first, &fd_set_write);
if (now < e.second->earliest_next_write) {
timeout.tv_sec = 0;
timeout.tv_usec = std::min((long unsigned)timeout.tv_usec, to_micros_lu(e.second->earliest_next_write - now));
}
}
max = std::max(e.first, max);
}
}
ALWAYS_ASSERT(select(max + 1, &fd_set_read, &fd_set_write, NULL, &timeout) >= 0);
now = std::chrono::steady_clock::now();
unsigned char buf[4096];
{
std::set<int> remove_set;
std::lock_guard<std::mutex> lock(me->fd_map_mutex);
for (const auto& e : me->fd_map) {
Connection* conn = e.second;
if (FD_ISSET(e.first, &fd_set_read)) {
ssize_t count = recv(conn->sock, (char*)buf, 4096, 0);
std::lock_guard<std::mutex> lock(conn->read_mutex);
if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
remove_set.insert(e.first);
conn->sock_errno = errno;
} else {
conn->inbound_queue.emplace_back(new std::vector<unsigned char>(buf, buf + count));
conn->total_inbound_size += count;
conn->read_cv.notify_all();
}
}
if (FD_ISSET(e.first, &fd_set_write)) {
if (now < conn->earliest_next_write)
continue;
std::lock_guard<std::mutex> lock(conn->send_mutex);
if (!conn->secondary_writepos && conn->outbound_primary_queue.size()) {
auto& msg = conn->outbound_primary_queue.front();
ssize_t count = send(conn->sock, (char*) &(*msg)[conn->primary_writepos], msg->size() - conn->primary_writepos, MSG_NOSIGNAL);
if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
remove_set.insert(e.first);
conn->sock_errno = errno;
} else {
conn->primary_writepos += count;
if (conn->primary_writepos == msg->size()) {
conn->primary_writepos = 0;
conn->total_waiting_size -= msg->size();
conn->outbound_primary_queue.pop_front();
}
}
} else {
assert(conn->outbound_secondary_queue.size() && !conn->primary_writepos);
auto& msg = conn->outbound_secondary_queue.front();
ssize_t count = send(conn->sock, (char*) &(*msg)[conn->secondary_writepos], msg->size() - conn->secondary_writepos, MSG_NOSIGNAL);
if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
remove_set.insert(e.first);
conn->sock_errno = errno;
} else {
conn->secondary_writepos += count;
if (conn->secondary_writepos == msg->size()) {
conn->secondary_writepos = 0;
conn->total_waiting_size -= msg->size();
conn->outbound_secondary_queue.pop_front();
}
}
}
if (!conn->total_waiting_size)
conn->initial_outbound_throttle = false;
else if (!conn->primary_writepos && !conn->secondary_writepos && conn->initial_outbound_throttle)
conn->earliest_next_write = std::chrono::steady_clock::now() + std::chrono::milliseconds(20); // Limit outbound to avg 5Mbps worst-case
}
}
for (const int fd : remove_set) {
Connection* conn = me->fd_map[fd];
std::lock_guard<std::mutex> lock(conn->read_mutex);
conn->inbound_queue.emplace_back((std::nullptr_t)NULL);
conn->read_cv.notify_all();
conn->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE;
me->fd_map.erase(fd);
}
}
#ifndef WIN32
if (FD_ISSET(pipefd[0], &fd_set_read))
while (read(pipefd[0], buf, 4096) > 0);
#endif
}
}
GlobalNetProcess() {
std::thread(do_net_process, this).detach();
}
};
static GlobalNetProcess processor;
Connection::~Connection() {
assert(disconnectFlags & DISCONNECT_COMPLETE);
user_thread->join();
close(sock);
delete user_thread;
}
void Connection::do_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) {
if (!send_mutex_token)
send_mutex.lock();
else
ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token);
if (initial_outbound_throttle && send_mutex_token)
initial_outbound_bytes += bytes->size();
if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) {
if (!send_mutex_token)
send_mutex.unlock();
return disconnect_from_outside("total_waiting_size blew up :(");
}
outbound_primary_queue.push_back(bytes);
total_waiting_size += bytes->size();
#ifndef WIN32
if (total_waiting_size > (ssize_t)bytes->size())
write(processor.pipe_write, "1", 1);
#endif
if (!send_mutex_token)
send_mutex.unlock();
}
void Connection::maybe_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) {
if (!send_mutex_token) {
if (!send_mutex.try_lock())
return;
} else
ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token);
if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) {
if (!send_mutex_token)
send_mutex.unlock();
return disconnect_from_outside("total_waiting_size blew up :(");
}
outbound_secondary_queue.push_back(bytes);
total_waiting_size += bytes->size();
#ifndef WIN32
if (total_waiting_size > (ssize_t)bytes->size())
write(processor.pipe_write, "1", 1);
#endif
if (!send_mutex_token)
send_mutex.unlock();
}
void Connection::disconnect_from_outside(const char* reason) {
if (disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE)
return;
printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(errno));
shutdown(sock, SHUT_RDWR);
}
void Connection::disconnect(const char* reason) {
if (disconnectFlags.fetch_or(DISCONNECT_STARTED) & DISCONNECT_STARTED)
return;
if (!(disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE)) {
printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(sock_errno));
shutdown(sock, SHUT_RDWR);
}
assert(std::this_thread::get_id() == user_thread->get_id());
std::unique_lock<std::mutex> lock(read_mutex);
while (!(disconnectFlags & DISCONNECT_GLOBAL_THREAD_DONE))
read_cv.wait(lock);
outbound_secondary_queue.clear();
outbound_primary_queue.clear();
inbound_queue.clear();
disconnectFlags |= DISCONNECT_COMPLETE;
if (on_disconnect)
std::thread(on_disconnect).detach();
}
void Connection::do_setup_and_read(Connection* me) {
#ifdef WIN32
unsigned long nonblocking = 1;
ioctlsocket(me->sock, FIONBIO, &nonblocking);
#else
fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) | O_NONBLOCK);
#endif
#ifdef X86_BSD
int nosigpipe = 1;
setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int));
#endif
int nodelay = 1;
setsockopt(me->sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay));
if (errno) {
me->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE;
return me->disconnect("error during connect");
}
{
std::lock_guard<std::mutex> lock(processor.fd_map_mutex);
processor.fd_map[me->sock] = me;
#ifndef WIN32
write(processor.pipe_write, "1", 1);
#endif
}
me->net_process([&](const char* reason) { me->disconnect(reason); });
}
ssize_t Connection::read_all(char *buf, size_t nbyte) {
size_t total = 0;
while (total < nbyte) {
std::unique_lock<std::mutex> lock(read_mutex);
while (!inbound_queue.size())
read_cv.wait(lock);
if (!inbound_queue.front())
return -1;
size_t readamt = std::min(nbyte - total, inbound_queue.front()->size() - readpos);
memcpy(buf + total, &(*inbound_queue.front())[readpos], readamt);
if (readpos + readamt == inbound_queue.front()->size()) {
#ifndef WIN32
int32_t old_size = total_inbound_size;
#endif
total_inbound_size -= inbound_queue.front()->size();
#ifndef WIN32
// If the old size is >= 64k, we may need to wakeup the select thread to get it to read more
if (old_size >= 65536)
write(processor.pipe_write, "1", 1);
#endif
readpos = 0;
inbound_queue.pop_front();
} else
readpos += readamt;
total += readamt;
}
assert(total == nbyte);
return nbyte;
}
void OutboundPersistentConnection::reconnect(std::string disconnectReason) {
OutboundConnection* old = (OutboundConnection*) connection.fetch_and(0);
if (old)
old->disconnect_from_outside(disconnectReason.c_str());
on_disconnect();
std::this_thread::sleep_for(std::chrono::seconds(1));
while (old && !(old->getDisconnectFlags() & DISCONNECT_COMPLETE)) {
printf("Disconnect of outbound connection still not complete (status is %d)\n", old->getDisconnectFlags());
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::thread(do_connect, this).detach();
delete old;
}
void OutboundPersistentConnection::do_connect(OutboundPersistentConnection* me) {
int sock = socket(AF_INET6, SOCK_STREAM, 0);
if (sock <= 0)
return me->reconnect("unable to create socket");
sockaddr_in6 addr;
if (!lookup_address(me->serverHost.c_str(), &addr)) {
close(sock);
return me->reconnect("unable to lookup host");
}
int v6only = 0;
setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only));
addr.sin6_port = htons(me->serverPort);
if (connect(sock, (struct sockaddr*)&addr, sizeof(addr))) {
close(sock);
return me->reconnect("failed to connect()");
}
OutboundConnection* new_conn = new OutboundConnection(sock, me);
#ifndef NDEBUG
unsigned long old_val =
#endif
me->connection.exchange((unsigned long)new_conn);
assert(old_val == 0);
new_conn->construction_done();
}
<commit_msg>Fix CPU usage bug on initial_outbound_throttle<commit_after>#include <assert.h>
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#define SHUT_RDWR SD_BOTH
#else // WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <fcntl.h>
#endif // !WIN32
#include <unordered_map>
#include <set>
#include "connection.h"
#include "utils.h"
class GlobalNetProcess {
public:
std::mutex fd_map_mutex;
std::unordered_map<int, Connection*> fd_map;
#ifndef WIN32
int pipe_write;
#endif
static void do_net_process(GlobalNetProcess* me) {
fd_set fd_set_read, fd_set_write;
struct timeval timeout;
#ifndef WIN32
int pipefd[2];
ALWAYS_ASSERT(!pipe(pipefd));
fcntl(pipefd[1], F_SETFL, fcntl(pipefd[1], F_GETFL) | O_NONBLOCK);
fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK);
me->pipe_write = pipefd[1];
#endif
while (true) {
#ifndef WIN32
timeout.tv_sec = 86400;
timeout.tv_usec = 20 * 1000;
#else
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
#endif
FD_ZERO(&fd_set_read); FD_ZERO(&fd_set_write);
#ifndef WIN32
int max = pipefd[0];
FD_SET(pipefd[0], &fd_set_read);
#else
int max = 0;
#endif
auto now = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(me->fd_map_mutex);
for (const auto& e : me->fd_map) {
ALWAYS_ASSERT(e.first < FD_SETSIZE);
if (e.second->total_inbound_size < 65536)
FD_SET(e.first, &fd_set_read);
if (e.second->total_waiting_size > 0) {
if (now < e.second->earliest_next_write) {
timeout.tv_sec = 0;
timeout.tv_usec = std::min((long unsigned)timeout.tv_usec, to_micros_lu(e.second->earliest_next_write - now));
} else
FD_SET(e.first, &fd_set_write);
}
max = std::max(e.first, max);
}
}
ALWAYS_ASSERT(select(max + 1, &fd_set_read, &fd_set_write, NULL, &timeout) >= 0);
now = std::chrono::steady_clock::now();
unsigned char buf[4096];
{
std::set<int> remove_set;
std::lock_guard<std::mutex> lock(me->fd_map_mutex);
for (const auto& e : me->fd_map) {
Connection* conn = e.second;
if (FD_ISSET(e.first, &fd_set_read)) {
ssize_t count = recv(conn->sock, (char*)buf, 4096, 0);
std::lock_guard<std::mutex> lock(conn->read_mutex);
if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
remove_set.insert(e.first);
conn->sock_errno = errno;
} else {
conn->inbound_queue.emplace_back(new std::vector<unsigned char>(buf, buf + count));
conn->total_inbound_size += count;
conn->read_cv.notify_all();
}
}
if (FD_ISSET(e.first, &fd_set_write)) {
if (now < conn->earliest_next_write)
continue;
std::lock_guard<std::mutex> lock(conn->send_mutex);
if (!conn->secondary_writepos && conn->outbound_primary_queue.size()) {
auto& msg = conn->outbound_primary_queue.front();
ssize_t count = send(conn->sock, (char*) &(*msg)[conn->primary_writepos], msg->size() - conn->primary_writepos, MSG_NOSIGNAL);
if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
remove_set.insert(e.first);
conn->sock_errno = errno;
} else {
conn->primary_writepos += count;
if (conn->primary_writepos == msg->size()) {
conn->primary_writepos = 0;
conn->total_waiting_size -= msg->size();
conn->outbound_primary_queue.pop_front();
}
}
} else {
assert(conn->outbound_secondary_queue.size() && !conn->primary_writepos);
auto& msg = conn->outbound_secondary_queue.front();
ssize_t count = send(conn->sock, (char*) &(*msg)[conn->secondary_writepos], msg->size() - conn->secondary_writepos, MSG_NOSIGNAL);
if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
remove_set.insert(e.first);
conn->sock_errno = errno;
} else {
conn->secondary_writepos += count;
if (conn->secondary_writepos == msg->size()) {
conn->secondary_writepos = 0;
conn->total_waiting_size -= msg->size();
conn->outbound_secondary_queue.pop_front();
}
}
}
if (!conn->total_waiting_size)
conn->initial_outbound_throttle = false;
else if (!conn->primary_writepos && !conn->secondary_writepos && conn->initial_outbound_throttle)
conn->earliest_next_write = std::chrono::steady_clock::now() + std::chrono::milliseconds(20); // Limit outbound to avg 5Mbps worst-case
}
}
for (const int fd : remove_set) {
Connection* conn = me->fd_map[fd];
std::lock_guard<std::mutex> lock(conn->read_mutex);
conn->inbound_queue.emplace_back((std::nullptr_t)NULL);
conn->read_cv.notify_all();
conn->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE;
me->fd_map.erase(fd);
}
}
#ifndef WIN32
if (FD_ISSET(pipefd[0], &fd_set_read))
while (read(pipefd[0], buf, 4096) > 0);
#endif
}
}
GlobalNetProcess() {
std::thread(do_net_process, this).detach();
}
};
static GlobalNetProcess processor;
Connection::~Connection() {
assert(disconnectFlags & DISCONNECT_COMPLETE);
user_thread->join();
close(sock);
delete user_thread;
}
void Connection::do_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) {
if (!send_mutex_token)
send_mutex.lock();
else
ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token);
if (initial_outbound_throttle && send_mutex_token)
initial_outbound_bytes += bytes->size();
if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) {
if (!send_mutex_token)
send_mutex.unlock();
return disconnect_from_outside("total_waiting_size blew up :(");
}
outbound_primary_queue.push_back(bytes);
total_waiting_size += bytes->size();
#ifndef WIN32
if (total_waiting_size > (ssize_t)bytes->size())
write(processor.pipe_write, "1", 1);
#endif
if (!send_mutex_token)
send_mutex.unlock();
}
void Connection::maybe_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) {
if (!send_mutex_token) {
if (!send_mutex.try_lock())
return;
} else
ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token);
if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) {
if (!send_mutex_token)
send_mutex.unlock();
return disconnect_from_outside("total_waiting_size blew up :(");
}
outbound_secondary_queue.push_back(bytes);
total_waiting_size += bytes->size();
#ifndef WIN32
if (total_waiting_size > (ssize_t)bytes->size())
write(processor.pipe_write, "1", 1);
#endif
if (!send_mutex_token)
send_mutex.unlock();
}
void Connection::disconnect_from_outside(const char* reason) {
if (disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE)
return;
printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(errno));
shutdown(sock, SHUT_RDWR);
}
void Connection::disconnect(const char* reason) {
if (disconnectFlags.fetch_or(DISCONNECT_STARTED) & DISCONNECT_STARTED)
return;
if (!(disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE)) {
printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(sock_errno));
shutdown(sock, SHUT_RDWR);
}
assert(std::this_thread::get_id() == user_thread->get_id());
std::unique_lock<std::mutex> lock(read_mutex);
while (!(disconnectFlags & DISCONNECT_GLOBAL_THREAD_DONE))
read_cv.wait(lock);
outbound_secondary_queue.clear();
outbound_primary_queue.clear();
inbound_queue.clear();
disconnectFlags |= DISCONNECT_COMPLETE;
if (on_disconnect)
std::thread(on_disconnect).detach();
}
void Connection::do_setup_and_read(Connection* me) {
#ifdef WIN32
unsigned long nonblocking = 1;
ioctlsocket(me->sock, FIONBIO, &nonblocking);
#else
fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) | O_NONBLOCK);
#endif
#ifdef X86_BSD
int nosigpipe = 1;
setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int));
#endif
int nodelay = 1;
setsockopt(me->sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay));
if (errno) {
me->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE;
return me->disconnect("error during connect");
}
{
std::lock_guard<std::mutex> lock(processor.fd_map_mutex);
processor.fd_map[me->sock] = me;
#ifndef WIN32
write(processor.pipe_write, "1", 1);
#endif
}
me->net_process([&](const char* reason) { me->disconnect(reason); });
}
ssize_t Connection::read_all(char *buf, size_t nbyte) {
size_t total = 0;
while (total < nbyte) {
std::unique_lock<std::mutex> lock(read_mutex);
while (!inbound_queue.size())
read_cv.wait(lock);
if (!inbound_queue.front())
return -1;
size_t readamt = std::min(nbyte - total, inbound_queue.front()->size() - readpos);
memcpy(buf + total, &(*inbound_queue.front())[readpos], readamt);
if (readpos + readamt == inbound_queue.front()->size()) {
#ifndef WIN32
int32_t old_size = total_inbound_size;
#endif
total_inbound_size -= inbound_queue.front()->size();
#ifndef WIN32
// If the old size is >= 64k, we may need to wakeup the select thread to get it to read more
if (old_size >= 65536)
write(processor.pipe_write, "1", 1);
#endif
readpos = 0;
inbound_queue.pop_front();
} else
readpos += readamt;
total += readamt;
}
assert(total == nbyte);
return nbyte;
}
void OutboundPersistentConnection::reconnect(std::string disconnectReason) {
OutboundConnection* old = (OutboundConnection*) connection.fetch_and(0);
if (old)
old->disconnect_from_outside(disconnectReason.c_str());
on_disconnect();
std::this_thread::sleep_for(std::chrono::seconds(1));
while (old && !(old->getDisconnectFlags() & DISCONNECT_COMPLETE)) {
printf("Disconnect of outbound connection still not complete (status is %d)\n", old->getDisconnectFlags());
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::thread(do_connect, this).detach();
delete old;
}
void OutboundPersistentConnection::do_connect(OutboundPersistentConnection* me) {
int sock = socket(AF_INET6, SOCK_STREAM, 0);
if (sock <= 0)
return me->reconnect("unable to create socket");
sockaddr_in6 addr;
if (!lookup_address(me->serverHost.c_str(), &addr)) {
close(sock);
return me->reconnect("unable to lookup host");
}
int v6only = 0;
setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only));
addr.sin6_port = htons(me->serverPort);
if (connect(sock, (struct sockaddr*)&addr, sizeof(addr))) {
close(sock);
return me->reconnect("failed to connect()");
}
OutboundConnection* new_conn = new OutboundConnection(sock, me);
#ifndef NDEBUG
unsigned long old_val =
#endif
me->connection.exchange((unsigned long)new_conn);
assert(old_val == 0);
new_conn->construction_done();
}
<|endoftext|> |
<commit_before>#include <common.h>
#define TITLE Quest(
#define DESC ,
#define REWARD ,(struct item_t){
#define x ,
#define END }),
const Quest QuestList[TOTAL_QUESTS]={
// Quest("Test","A test quest",(struct item_t){1,TEST_ITEM}),
// Get quest list
#include "../config/quest_list.txt"
};
Quest::Quest(const char *t,const char *d,struct item_t r){
strcpy((title=(char *)malloc(strlen(t))),t);
strcpy((desc =(char *)malloc(strlen(d))),d);
memcpy(&reward,&r,sizeof(struct item_t));
}
Quest::~Quest(){
free(title);
free(desc);
memset(&reward,0,sizeof(struct item_t));
}
int QuestHandler::assign(const char *t){
unsigned char i;
for(i=0;i<current.size();i++){ // Make sure we don't already have this quest
if(!strcmp(current[i]->title,t)){
#ifdef DEBUG
DEBUG_printf("The QuestHandler already has this quest: %s\n",t);
#endif // DEBUG
return -2;
}
}
for(i=0;i<TOTAL_QUESTS;i++){ // Add the quest (if it really exists)
if(!strcmp(QuestList[i].title,t)){
current.push_back(&QuestList[i]);
#ifdef DEBUG
DEBUG_printf("Added quest %s, now have %u active quests.\n",t,current.size());
#endif // DEBUG
return current.size();
}
#ifdef DEBUG
DEBUG_printf("Finding quest: %s != %s\n",t,QuestList[i].title);
#endif // DEBUG
}
#ifdef DEBUG
DEBUG_printf("Quest %s does not exist.\n",t);
#endif // DEBUG
return -1;
}
int QuestHandler::drop(const char *t){
unsigned char i;
for(i=0;i<current.size();i++){
if(!strcmp(current[i]->title,t)){
current.erase(current.begin()+i);
return current.size();
}
}
return -1;
}
int QuestHandler::finish(const char *t,void *completer){
unsigned char i;
unsigned int r;
for(i=0;i<current.size();i++){
if(!strcmp(current[i]->title,t)){
#ifdef DEBUG
DEBUG_printf("Completing quest %s.\n",t);
#endif // DEBUG
((Entity *)completer)->inv->addItem(current[i]->reward.id,current[i]->reward.count);
current.erase(current.begin()+i);
#ifdef DEBUG
DEBUG_printf("QuestHandler now has %u active quests.\n",current.size());
#endif // DEBUG
return 0;
}
}
#ifdef DEBUG
DEBUG_printf("QuestHandler never had quest %s.\n",t);
#endif // DEBUG
return -1;
}
bool QuestHandler::hasQuest(const char *t){
unsigned int i;
for(i=0;i<current.size();i++){
if(!strcmp(current[i]->title,t)){
return true;
}
}
return false;
}
<commit_msg>fixed malloc crash<commit_after>#include <common.h>
#define TITLE Quest(
#define DESC ,
#define REWARD ,(struct item_t){
#define x ,
#define END }),
const Quest QuestList[TOTAL_QUESTS]={
// Quest("Test","A test quest",(struct item_t){1,TEST_ITEM}),
// Get quest list
#include "../config/quest_list.txt"
};
// Trust nobody
#define STRLEN_MIN 16
unsigned int safe_strlen(const char *s){
unsigned int size=0;
while(s[size])size++;
if(size<STRLEN_MIN)return STRLEN_MIN;
else return size;
}
Quest::Quest(const char *t,const char *d,struct item_t r){
title=(char *)calloc(safe_strlen(t),sizeof(char));
desc=(char *)calloc(safe_strlen(d),sizeof(char));
strcpy(title,t);
strcpy(desc,d);
memcpy(&reward,&r,sizeof(struct item_t));
}
Quest::~Quest(){
free(title);
free(desc);
memset(&reward,0,sizeof(struct item_t));
}
int QuestHandler::assign(const char *t){
unsigned char i;
for(i=0;i<current.size();i++){ // Make sure we don't already have this quest
if(!strcmp(current[i]->title,t)){
#ifdef DEBUG
DEBUG_printf("The QuestHandler already has this quest: %s\n",t);
#endif // DEBUG
return -2;
}
}
for(i=0;i<TOTAL_QUESTS;i++){ // Add the quest (if it really exists)
if(!strcmp(QuestList[i].title,t)){
current.push_back(&QuestList[i]);
#ifdef DEBUG
DEBUG_printf("Added quest %s, now have %u active quests.\n",t,current.size());
#endif // DEBUG
return current.size();
}
#ifdef DEBUG
DEBUG_printf("Finding quest: %s != %s\n",t,QuestList[i].title);
#endif // DEBUG
}
#ifdef DEBUG
DEBUG_printf("Quest %s does not exist.\n",t);
#endif // DEBUG
return -1;
}
int QuestHandler::drop(const char *t){
unsigned char i;
for(i=0;i<current.size();i++){
if(!strcmp(current[i]->title,t)){
current.erase(current.begin()+i);
return current.size();
}
}
return -1;
}
int QuestHandler::finish(const char *t,void *completer){
unsigned char i;
unsigned int r;
for(i=0;i<current.size();i++){
if(!strcmp(current[i]->title,t)){
#ifdef DEBUG
DEBUG_printf("Completing quest %s.\n",t);
#endif // DEBUG
((Entity *)completer)->inv->addItem(current[i]->reward.id,current[i]->reward.count);
current.erase(current.begin()+i);
#ifdef DEBUG
DEBUG_printf("QuestHandler now has %u active quests.\n",current.size());
#endif // DEBUG
return 0;
}
}
#ifdef DEBUG
DEBUG_printf("QuestHandler never had quest %s.\n",t);
#endif // DEBUG
return -1;
}
bool QuestHandler::hasQuest(const char *t){
unsigned int i;
for(i=0;i<current.size();i++){
if(!strcmp(current[i]->title,t)){
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>#ifndef SPEED_CONTROL_H
#define SPEED_CONTROL_H
#include <Arduino.h>
class Servo;
class SerialMessageHandler;
class SpeedControl
{
/**
* external state transitions (initiated by the user)
* - STOPPED -> DRIVING or REVERSING
* - DRIVING -> STOPPING
* - REVERSING -> DRIVING or STOPPING
* - REVERSE_WAIT -> DRIVING or STOPPING
*
* internal transitions
* - STOPPING -> REVERSE_WAIT -> REVERSING
* - STOPPING -> STOPPED
*
*/
enum State
{
DISABLED,
STOPPED,
BRAKING,
DRIVING,
REVERSING,
REVERSE_WAIT,
STOPPING_REVERSE
};
static const unsigned long minimum_tick_micros = 50;
static const unsigned int tick_array_size = 4; // tick array size must be a power of 2
static const unsigned int tick_array_mask = tick_array_size -1;
SerialMessageHandler *message_handler;
Servo *throttle_servo;
SpeedControl::State state = DISABLED;
unsigned long last_update_millis;
unsigned long last_update_ticks;
unsigned long reverse_wait_start_millis;
unsigned long tick_array[tick_array_size];
unsigned int tick_index;
unsigned long last_tick_micros;
unsigned long tick_counter;
int target_speed;
public:
int ticks_per_metre = 30;
int brake_throttle = 40;
int throttle_offset = 0;
void set_throttle(int throttle);
int get_throttle();
float current_speed();
void set_speed(int requested_speed);
void set_throttle_offset(int amount) {throttle_offset = constrain(amount, -40, 40);}
void set_brake_force(int amount) {brake_throttle = constrain(amount, 0, 90);}
void set_ticks_per_metre(int amount) {ticks_per_metre = constrain(amount, 0, 1000);}
void init(SerialMessageHandler *message_handler, Servo *throttle_servo);
void poll();
void disable();
void interrupt();
};
#endif /* SPEED_CONTROL_H */
<commit_msg>Make interrupt-modified variables volatile.<commit_after>#ifndef SPEED_CONTROL_H
#define SPEED_CONTROL_H
#include <Arduino.h>
class Servo;
class SerialMessageHandler;
class SpeedControl
{
/**
* external state transitions (initiated by the user)
* - STOPPED -> DRIVING or REVERSING
* - DRIVING -> STOPPING
* - REVERSING -> DRIVING or STOPPING
* - REVERSE_WAIT -> DRIVING or STOPPING
*
* internal transitions
* - STOPPING -> REVERSE_WAIT -> REVERSING
* - STOPPING -> STOPPED
*
*/
enum State
{
DISABLED,
STOPPED,
BRAKING,
DRIVING,
REVERSING,
REVERSE_WAIT,
STOPPING_REVERSE
};
static const unsigned long minimum_tick_micros = 50;
static const unsigned int tick_array_size = 4; // tick array size must be a power of 2
static const unsigned int tick_array_mask = tick_array_size -1;
SerialMessageHandler *message_handler;
Servo *throttle_servo;
SpeedControl::State state = DISABLED;
unsigned long last_update_millis;
unsigned long last_update_ticks;
unsigned long reverse_wait_start_millis;
volatile unsigned long tick_array[tick_array_size];
volatile unsigned long tick_counter;
volatile unsigned long last_tick_micros;
int target_speed;
public:
int ticks_per_metre = 30;
int brake_throttle = 40;
int throttle_offset = 0;
void set_throttle(int throttle);
int get_throttle();
float current_speed();
void set_speed(int requested_speed);
void set_throttle_offset(int amount) {throttle_offset = constrain(amount, -40, 40);}
void set_brake_force(int amount) {brake_throttle = constrain(amount, 0, 90);}
void set_ticks_per_metre(int amount) {ticks_per_metre = constrain(amount, 0, 1000);}
void init(SerialMessageHandler *message_handler, Servo *throttle_servo);
void poll();
void disable();
void interrupt();
};
#endif /* SPEED_CONTROL_H */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: e3ditem.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:27:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_
#include <com/sun/star/drawing/Direction3D.hpp>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#include <svx/e3ditem.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
DBG_NAMEEX(SvxB3DVectorItem)
DBG_NAME(SvxB3DVectorItem)
// -----------------------------------------------------------------------
TYPEINIT1_FACTORY(SvxB3DVectorItem, SfxPoolItem, new SvxB3DVectorItem);
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem()
{
DBG_CTOR(SvxB3DVectorItem, 0);
}
SvxB3DVectorItem::~SvxB3DVectorItem()
{
DBG_DTOR(SvxB3DVectorItem, 0);
}
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem( USHORT _nWhich, const basegfx::B3DVector& rVal ) :
SfxPoolItem( _nWhich ),
aVal( rVal )
{
DBG_CTOR(SvxB3DVectorItem, 0);
}
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem( USHORT _nWhich, SvStream& rStream ) :
SfxPoolItem( _nWhich )
{
DBG_CTOR(SvxB3DVectorItem, 0);
double fValue;
rStream >> fValue; aVal.setX(fValue);
rStream >> fValue; aVal.setY(fValue);
rStream >> fValue; aVal.setZ(fValue);
}
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem( const SvxB3DVectorItem& rItem ) :
SfxPoolItem( rItem ),
aVal( rItem.aVal )
{
DBG_CTOR(SvxB3DVectorItem, 0);
}
// -----------------------------------------------------------------------
int SvxB3DVectorItem::operator==( const SfxPoolItem &rItem ) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
return ((SvxB3DVectorItem&)rItem).aVal == aVal;
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxB3DVectorItem::Clone( SfxItemPool* /*pPool*/ ) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
return new SvxB3DVectorItem( *this );
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxB3DVectorItem::Create(SvStream &rStream, USHORT /*nVersion*/) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
basegfx::B3DVector aStr;
double fValue;
rStream >> fValue; aStr.setX(fValue);
rStream >> fValue; aStr.setY(fValue);
rStream >> fValue; aStr.setZ(fValue);
return new SvxB3DVectorItem(Which(), aStr);
}
// -----------------------------------------------------------------------
SvStream& SvxB3DVectorItem::Store(SvStream &rStream, USHORT /*nItemVersion*/) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
// ## if (nItemVersion)
double fValue;
fValue = aVal.getX(); rStream << fValue;
fValue = aVal.getY(); rStream << fValue;
fValue = aVal.getZ(); rStream << fValue;
return rStream;
}
// -----------------------------------------------------------------------
sal_Bool SvxB3DVectorItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
drawing::Direction3D aDirection;
// Werte eintragen
aDirection.DirectionX = aVal.getX();
aDirection.DirectionY = aVal.getY();
aDirection.DirectionZ = aVal.getZ();
rVal <<= aDirection;
return( sal_True );
}
// -----------------------------------------------------------------------
sal_Bool SvxB3DVectorItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
drawing::Direction3D aDirection;
if(!(rVal >>= aDirection))
return sal_False;
aVal.setX(aDirection.DirectionX);
aVal.setY(aDirection.DirectionY);
aVal.setZ(aDirection.DirectionZ);
return sal_True;
}
// -----------------------------------------------------------------------
USHORT SvxB3DVectorItem::GetVersion (USHORT nFileFormatVersion) const
{
return (nFileFormatVersion == SOFFICE_FILEFORMAT_31) ? USHRT_MAX : 0;
}
// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.10.368); FILE MERGED 2008/04/01 15:51:16 thb 1.10.368.3: #i85898# Stripping all external header guards 2008/04/01 12:49:13 thb 1.10.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:34 rt 1.10.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: e3ditem.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <com/sun/star/drawing/Direction3D.hpp>
#include <tools/stream.hxx>
#include <svx/e3ditem.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
DBG_NAMEEX(SvxB3DVectorItem)
DBG_NAME(SvxB3DVectorItem)
// -----------------------------------------------------------------------
TYPEINIT1_FACTORY(SvxB3DVectorItem, SfxPoolItem, new SvxB3DVectorItem);
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem()
{
DBG_CTOR(SvxB3DVectorItem, 0);
}
SvxB3DVectorItem::~SvxB3DVectorItem()
{
DBG_DTOR(SvxB3DVectorItem, 0);
}
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem( USHORT _nWhich, const basegfx::B3DVector& rVal ) :
SfxPoolItem( _nWhich ),
aVal( rVal )
{
DBG_CTOR(SvxB3DVectorItem, 0);
}
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem( USHORT _nWhich, SvStream& rStream ) :
SfxPoolItem( _nWhich )
{
DBG_CTOR(SvxB3DVectorItem, 0);
double fValue;
rStream >> fValue; aVal.setX(fValue);
rStream >> fValue; aVal.setY(fValue);
rStream >> fValue; aVal.setZ(fValue);
}
// -----------------------------------------------------------------------
SvxB3DVectorItem::SvxB3DVectorItem( const SvxB3DVectorItem& rItem ) :
SfxPoolItem( rItem ),
aVal( rItem.aVal )
{
DBG_CTOR(SvxB3DVectorItem, 0);
}
// -----------------------------------------------------------------------
int SvxB3DVectorItem::operator==( const SfxPoolItem &rItem ) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
return ((SvxB3DVectorItem&)rItem).aVal == aVal;
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxB3DVectorItem::Clone( SfxItemPool* /*pPool*/ ) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
return new SvxB3DVectorItem( *this );
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxB3DVectorItem::Create(SvStream &rStream, USHORT /*nVersion*/) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
basegfx::B3DVector aStr;
double fValue;
rStream >> fValue; aStr.setX(fValue);
rStream >> fValue; aStr.setY(fValue);
rStream >> fValue; aStr.setZ(fValue);
return new SvxB3DVectorItem(Which(), aStr);
}
// -----------------------------------------------------------------------
SvStream& SvxB3DVectorItem::Store(SvStream &rStream, USHORT /*nItemVersion*/) const
{
DBG_CHKTHIS(SvxB3DVectorItem, 0);
// ## if (nItemVersion)
double fValue;
fValue = aVal.getX(); rStream << fValue;
fValue = aVal.getY(); rStream << fValue;
fValue = aVal.getZ(); rStream << fValue;
return rStream;
}
// -----------------------------------------------------------------------
sal_Bool SvxB3DVectorItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
drawing::Direction3D aDirection;
// Werte eintragen
aDirection.DirectionX = aVal.getX();
aDirection.DirectionY = aVal.getY();
aDirection.DirectionZ = aVal.getZ();
rVal <<= aDirection;
return( sal_True );
}
// -----------------------------------------------------------------------
sal_Bool SvxB3DVectorItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
drawing::Direction3D aDirection;
if(!(rVal >>= aDirection))
return sal_False;
aVal.setX(aDirection.DirectionX);
aVal.setY(aDirection.DirectionY);
aVal.setZ(aDirection.DirectionZ);
return sal_True;
}
// -----------------------------------------------------------------------
USHORT SvxB3DVectorItem::GetVersion (USHORT nFileFormatVersion) const
{
return (nFileFormatVersion == SOFFICE_FILEFORMAT_31) ? USHRT_MAX : 0;
}
// eof
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grfitem.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:28:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVX_GRFCROP_HXX
#include <svx/grfcrop.hxx>
#endif
#ifndef _SVX_ITEMTYPE_HXX //autogen
#include <svx/itemtype.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_GRAPHICCROP_HPP_
#include <com/sun/star/text/GraphicCrop.hpp>
#endif
using namespace ::com::sun::star;
#define TWIP_TO_MM100(TWIP) ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100) ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))
//TYPEINIT1_FACTORY( SvxGrfCrop, SfxPoolItem , new SvxGrfCrop(0))
/******************************************************************************
* Implementierung class SwCropGrf
******************************************************************************/
SvxGrfCrop::SvxGrfCrop( USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( 0 ), nRight( 0 ), nTop( 0 ), nBottom( 0 )
{}
SvxGrfCrop::SvxGrfCrop( sal_Int32 nL, sal_Int32 nR,
sal_Int32 nT, sal_Int32 nB, USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( nL ), nRight( nR ), nTop( nT ), nBottom( nB )
{}
SvxGrfCrop::~SvxGrfCrop()
{
}
int SvxGrfCrop::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rAttr ), "not equal attributes" );
return nLeft == ((const SvxGrfCrop&)rAttr).GetLeft() &&
nRight == ((const SvxGrfCrop&)rAttr).GetRight() &&
nTop == ((const SvxGrfCrop&)rAttr).GetTop() &&
nBottom == ((const SvxGrfCrop&)rAttr).GetBottom();
}
/*
SfxPoolItem* SvxGrfCrop::Clone( SfxItemPool* ) const
{
return new SvxGrfCrop( *this );
}
*/
/*
USHORT SvxGrfCrop::GetVersion( USHORT nFFVer ) const
{
DBG_ASSERT( SOFFICE_FILEFORMAT_31==nFFVer ||
SOFFICE_FILEFORMAT_40==nFFVer ||
SOFFICE_FILEFORMAT_NOW==nFFVer,
"SvxGrfCrop: exist a new fileformat?" );
return GRFCROP_VERSION_SWDEFAULT;
}
*/
SfxPoolItem* SvxGrfCrop::Create( SvStream& rStrm, USHORT nVersion ) const
{
INT32 top, left, right, bottom;
rStrm >> top >> left >> right >> bottom;
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
SvxGrfCrop* pNew = (SvxGrfCrop*)Clone();
pNew->SetLeft( left );
pNew->SetRight( right );
pNew->SetTop( top );
pNew->SetBottom( bottom );
return pNew;
}
SvStream& SvxGrfCrop::Store( SvStream& rStrm, USHORT nVersion ) const
{
INT32 left = GetLeft(), right = GetRight(),
top = GetTop(), bottom = GetBottom();
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
rStrm << top << left << right << bottom;
return rStrm;
}
BOOL SvxGrfCrop::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aRet;
aRet.Left = nLeft;
aRet.Right = nRight;
aRet.Top = nTop;
aRet.Bottom = nBottom;
if( bConvert )
{
aRet.Right = TWIP_TO_MM100(aRet.Right );
aRet.Top = TWIP_TO_MM100(aRet.Top );
aRet.Left = TWIP_TO_MM100(aRet.Left );
aRet.Bottom = TWIP_TO_MM100(aRet.Bottom);
}
rVal <<= aRet;
return sal_True;
}
BOOL SvxGrfCrop::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aVal;
if(!(rVal >>= aVal))
return sal_False;
if( bConvert )
{
aVal.Right = MM100_TO_TWIP(aVal.Right );
aVal.Top = MM100_TO_TWIP(aVal.Top );
aVal.Left = MM100_TO_TWIP(aVal.Left );
aVal.Bottom = MM100_TO_TWIP(aVal.Bottom);
}
nLeft = aVal.Left ;
nRight = aVal.Right ;
nTop = aVal.Top ;
nBottom = aVal.Bottom;
return sal_True;
}
SfxItemPresentation SvxGrfCrop::GetPresentation(
SfxItemPresentation ePres, SfxMapUnit eCoreUnit, SfxMapUnit /*ePresUnit*/,
String &rText, const IntlWrapper* pIntl ) const
{
rText.Erase();
switch( ePres )
{
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
if( SFX_ITEM_PRESENTATION_COMPLETE == ePres )
{
( rText.AssignAscii( "L: " )) += ::GetMetricText( GetLeft(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " R: " )) += ::GetMetricText( GetRight(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " T: " )) += ::GetMetricText( GetTop(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " B: " )) += ::GetMetricText( GetBottom(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
}
break;
default:
ePres = SFX_ITEM_PRESENTATION_NONE;
break;
}
return ePres;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.11.368); FILE MERGED 2008/04/01 15:51:17 thb 1.11.368.3: #i85898# Stripping all external header guards 2008/04/01 12:49:14 thb 1.11.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:34 rt 1.11.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grfitem.cxx,v $
* $Revision: 1.12 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <tools/stream.hxx>
#include <svx/grfcrop.hxx>
#include <svx/itemtype.hxx>
#include <com/sun/star/text/GraphicCrop.hpp>
using namespace ::com::sun::star;
#define TWIP_TO_MM100(TWIP) ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100) ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))
//TYPEINIT1_FACTORY( SvxGrfCrop, SfxPoolItem , new SvxGrfCrop(0))
/******************************************************************************
* Implementierung class SwCropGrf
******************************************************************************/
SvxGrfCrop::SvxGrfCrop( USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( 0 ), nRight( 0 ), nTop( 0 ), nBottom( 0 )
{}
SvxGrfCrop::SvxGrfCrop( sal_Int32 nL, sal_Int32 nR,
sal_Int32 nT, sal_Int32 nB, USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( nL ), nRight( nR ), nTop( nT ), nBottom( nB )
{}
SvxGrfCrop::~SvxGrfCrop()
{
}
int SvxGrfCrop::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rAttr ), "not equal attributes" );
return nLeft == ((const SvxGrfCrop&)rAttr).GetLeft() &&
nRight == ((const SvxGrfCrop&)rAttr).GetRight() &&
nTop == ((const SvxGrfCrop&)rAttr).GetTop() &&
nBottom == ((const SvxGrfCrop&)rAttr).GetBottom();
}
/*
SfxPoolItem* SvxGrfCrop::Clone( SfxItemPool* ) const
{
return new SvxGrfCrop( *this );
}
*/
/*
USHORT SvxGrfCrop::GetVersion( USHORT nFFVer ) const
{
DBG_ASSERT( SOFFICE_FILEFORMAT_31==nFFVer ||
SOFFICE_FILEFORMAT_40==nFFVer ||
SOFFICE_FILEFORMAT_NOW==nFFVer,
"SvxGrfCrop: exist a new fileformat?" );
return GRFCROP_VERSION_SWDEFAULT;
}
*/
SfxPoolItem* SvxGrfCrop::Create( SvStream& rStrm, USHORT nVersion ) const
{
INT32 top, left, right, bottom;
rStrm >> top >> left >> right >> bottom;
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
SvxGrfCrop* pNew = (SvxGrfCrop*)Clone();
pNew->SetLeft( left );
pNew->SetRight( right );
pNew->SetTop( top );
pNew->SetBottom( bottom );
return pNew;
}
SvStream& SvxGrfCrop::Store( SvStream& rStrm, USHORT nVersion ) const
{
INT32 left = GetLeft(), right = GetRight(),
top = GetTop(), bottom = GetBottom();
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
rStrm << top << left << right << bottom;
return rStrm;
}
BOOL SvxGrfCrop::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aRet;
aRet.Left = nLeft;
aRet.Right = nRight;
aRet.Top = nTop;
aRet.Bottom = nBottom;
if( bConvert )
{
aRet.Right = TWIP_TO_MM100(aRet.Right );
aRet.Top = TWIP_TO_MM100(aRet.Top );
aRet.Left = TWIP_TO_MM100(aRet.Left );
aRet.Bottom = TWIP_TO_MM100(aRet.Bottom);
}
rVal <<= aRet;
return sal_True;
}
BOOL SvxGrfCrop::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aVal;
if(!(rVal >>= aVal))
return sal_False;
if( bConvert )
{
aVal.Right = MM100_TO_TWIP(aVal.Right );
aVal.Top = MM100_TO_TWIP(aVal.Top );
aVal.Left = MM100_TO_TWIP(aVal.Left );
aVal.Bottom = MM100_TO_TWIP(aVal.Bottom);
}
nLeft = aVal.Left ;
nRight = aVal.Right ;
nTop = aVal.Top ;
nBottom = aVal.Bottom;
return sal_True;
}
SfxItemPresentation SvxGrfCrop::GetPresentation(
SfxItemPresentation ePres, SfxMapUnit eCoreUnit, SfxMapUnit /*ePresUnit*/,
String &rText, const IntlWrapper* pIntl ) const
{
rText.Erase();
switch( ePres )
{
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
if( SFX_ITEM_PRESENTATION_COMPLETE == ePres )
{
( rText.AssignAscii( "L: " )) += ::GetMetricText( GetLeft(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " R: " )) += ::GetMetricText( GetRight(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " T: " )) += ::GetMetricText( GetTop(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " B: " )) += ::GetMetricText( GetBottom(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
}
break;
default:
ePres = SFX_ITEM_PRESENTATION_NONE;
break;
}
return ePres;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmltxtimp.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:16:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmloff/xmlmetae.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif
#ifndef _SVX_EDITSOURCE_HXX
#include "editsource.hxx"
#endif
#ifndef _SVX_UNOTEXT_HXX
#include "unotext.hxx"
#endif
using namespace com::sun::star;
using namespace com::sun::star::document;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::text;
using namespace ::rtl;
using namespace cppu;
using namespace xmloff::token;
///////////////////////////////////////////////////////////////////////
class SvxXMLTextImportContext : public SvXMLImportContext
{
public:
SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText );
virtual ~SvxXMLTextImportContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );
// SvxXMLXTableImport& getImport() const { return *(SvxXMLXTableImport*)&GetImport(); }
private:
const Reference< XText > mxText;
};
///////////////////////////////////////////////////////////////////////
SvxXMLTextImportContext::SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText )
: SvXMLImportContext( rImport, nPrfx, rLName ), mxText( xText )
{
}
SvxXMLTextImportContext::~SvxXMLTextImportContext()
{
}
SvXMLImportContext *SvxXMLTextImportContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
SvXMLImportContext* pContext = NULL;
if(XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_BODY ) )
{
pContext = new SvxXMLTextImportContext( GetImport(), nPrefix, rLocalName, xAttrList, mxText );
}
else if( XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_AUTOMATIC_STYLES ) )
{
pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
GetImport().GetTextImport()->SetAutoStyles( (SvXMLStylesContext*)pContext );
}
else
{
pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList );
}
if( NULL == pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
///////////////////////////////////////////////////////////////////////
class SvxXMLXTextImportComponent : public SvXMLImport
{
public:
// #110680#
SvxXMLXTextImportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const Reference< XText > & xText );
virtual ~SvxXMLXTextImportComponent() throw ();
static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );
private:
const Reference< XText > mxText;
};
// --------------------------------------------------------------------
// #110680#
SvxXMLXTextImportComponent::SvxXMLXTextImportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const Reference< XText > & xText )
: SvXMLImport(xServiceFactory),
mxText( xText )
{
GetTextImport()->SetCursor( mxText->createTextCursor() );
}
SvxXMLXTextImportComponent::~SvxXMLXTextImportComponent() throw ()
{
}
void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel )
{
SvxEditEngineSource aEditSource( &rEditEngine );
static const SfxItemPropertyMap SvxXMLTextImportComponentPropertyMap[] =
{
SVX_UNOEDIT_CHAR_PROPERTIES,
SVX_UNOEDIT_FONT_PROPERTIES,
// SVX_UNOEDIT_OUTLINER_PROPERTIES,
SVX_UNOEDIT_PARA_PROPERTIES,
{0,0}
};
uno::Reference<text::XText > xParent;
SvxUnoText* pUnoText = new SvxUnoText( &aEditSource, SvxXMLTextImportComponentPropertyMap, xParent );
pUnoText->SetSelection( rSel );
uno::Reference<text::XText > xText( pUnoText );
try
{
do
{
uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
if( !xServiceFactory.is() )
{
DBG_ERROR( "SvxXMLXTableImport::load: got no service manager" );
break;
}
uno::Reference< xml::sax::XParser > xParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY );
if( !xParser.is() )
{
DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
break;
}
Reference<io::XInputStream> xInputStream = new utl::OInputStreamWrapper( rStream );
/* testcode
const OUString aURL( RTL_CONSTASCII_USTRINGPARAM( "file:///e:/test.xml" ) );
SfxMedium aMedium( aURL, STREAM_READ | STREAM_NOCREATE, TRUE );
aMedium.IsRemote();
uno::Reference<io::XOutputStream> xOut( new utl::OOutputStreamWrapper( *aMedium.GetOutStream() ) );
aMedium.GetInStream()->Seek( 0 );
uno::Reference< io::XActiveDataSource > xSource( aMedium.GetDataSource() );
if( !xSource.is() )
{
DBG_ERROR( "got no data source from medium" );
break;
}
Reference< XInterface > xPipe( xServiceFactory->createInstance(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe") ) ) );
if( !xPipe.is() )
{
DBG_ERROR( "XMLReader::Read: com.sun.star.io.Pipe service missing" );
break;
}
// connect pipe's output stream to the data source
xSource->setOutputStream( Reference< io::XOutputStream >::query( xPipe ) );
xml::sax::InputSource aParserInput;
aParserInput.aInputStream = uno::Reference< io::XInputStream >::query( xPipe );
aParserInput.sSystemId = aMedium.GetName();
if( xSource.is() )
{
Reference< io::XActiveDataControl > xSourceControl( xSource, UNO_QUERY );
xSourceControl->start();
}
*/
// #110680#
// Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xText ) );
Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xServiceFactory, xText ) );
xParser->setDocumentHandler( xHandler );
xml::sax::InputSource aParserInput;
aParserInput.aInputStream = xInputStream;
// aParserInput.sSystemId = aMedium.GetName();
xParser->parseStream( aParserInput );
}
while(0);
}
catch( uno::Exception& e )
{
}
}
SvXMLImportContext *SvxXMLXTextImportComponent::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
SvXMLImportContext* pContext;
if(XML_NAMESPACE_OFFICE == nPrefix && ( IsXMLToken( rLocalName, XML_DOCUMENT ) || IsXMLToken( rLocalName, XML_DOCUMENT_CONTENT ) ) )
{
pContext = new SvxXMLTextImportContext(*this, nPrefix, rLocalName, xAttrList, mxText );
}
else
{
pContext = SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
}
return pContext;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.5.222); FILE MERGED 2006/05/12 12:25:32 ab 1.5.222.1: #i53898# Removed warnings for unxlngi6/unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmltxtimp.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 17:04: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
*
************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmloff/xmlmetae.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif
#ifndef _SVX_EDITSOURCE_HXX
#include "editsource.hxx"
#endif
#ifndef _SVX_UNOTEXT_HXX
#include "unotext.hxx"
#endif
using namespace com::sun::star;
using namespace com::sun::star::document;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::text;
using namespace ::rtl;
using namespace cppu;
using namespace xmloff::token;
///////////////////////////////////////////////////////////////////////
class SvxXMLTextImportContext : public SvXMLImportContext
{
public:
SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText );
virtual ~SvxXMLTextImportContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );
// SvxXMLXTableImport& getImport() const { return *(SvxXMLXTableImport*)&GetImport(); }
private:
const Reference< XText > mxText;
};
///////////////////////////////////////////////////////////////////////
SvxXMLTextImportContext::SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >&, const Reference< XText >& xText )
: SvXMLImportContext( rImport, nPrfx, rLName ), mxText( xText )
{
}
SvxXMLTextImportContext::~SvxXMLTextImportContext()
{
}
SvXMLImportContext *SvxXMLTextImportContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
SvXMLImportContext* pContext = NULL;
if(XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_BODY ) )
{
pContext = new SvxXMLTextImportContext( GetImport(), nPrefix, rLocalName, xAttrList, mxText );
}
else if( XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_AUTOMATIC_STYLES ) )
{
pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
GetImport().GetTextImport()->SetAutoStyles( (SvXMLStylesContext*)pContext );
}
else
{
pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList );
}
if( NULL == pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
///////////////////////////////////////////////////////////////////////
class SvxXMLXTextImportComponent : public SvXMLImport
{
public:
// #110680#
SvxXMLXTextImportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const Reference< XText > & xText );
virtual ~SvxXMLXTextImportComponent() throw ();
static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );
private:
const Reference< XText > mxText;
};
// --------------------------------------------------------------------
// #110680#
SvxXMLXTextImportComponent::SvxXMLXTextImportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const Reference< XText > & xText )
: SvXMLImport(xServiceFactory),
mxText( xText )
{
GetTextImport()->SetCursor( mxText->createTextCursor() );
}
SvxXMLXTextImportComponent::~SvxXMLXTextImportComponent() throw ()
{
}
void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel )
{
SvxEditEngineSource aEditSource( &rEditEngine );
static const SfxItemPropertyMap SvxXMLTextImportComponentPropertyMap[] =
{
SVX_UNOEDIT_CHAR_PROPERTIES,
SVX_UNOEDIT_FONT_PROPERTIES,
// SVX_UNOEDIT_OUTLINER_PROPERTIES,
SVX_UNOEDIT_PARA_PROPERTIES,
{0,0,0,0,0,0}
};
uno::Reference<text::XText > xParent;
SvxUnoText* pUnoText = new SvxUnoText( &aEditSource, SvxXMLTextImportComponentPropertyMap, xParent );
pUnoText->SetSelection( rSel );
uno::Reference<text::XText > xText( pUnoText );
try
{
do
{
uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
if( !xServiceFactory.is() )
{
DBG_ERROR( "SvxXMLXTableImport::load: got no service manager" );
break;
}
uno::Reference< xml::sax::XParser > xParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY );
if( !xParser.is() )
{
DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
break;
}
Reference<io::XInputStream> xInputStream = new utl::OInputStreamWrapper( rStream );
/* testcode
const OUString aURL( RTL_CONSTASCII_USTRINGPARAM( "file:///e:/test.xml" ) );
SfxMedium aMedium( aURL, STREAM_READ | STREAM_NOCREATE, TRUE );
aMedium.IsRemote();
uno::Reference<io::XOutputStream> xOut( new utl::OOutputStreamWrapper( *aMedium.GetOutStream() ) );
aMedium.GetInStream()->Seek( 0 );
uno::Reference< io::XActiveDataSource > xSource( aMedium.GetDataSource() );
if( !xSource.is() )
{
DBG_ERROR( "got no data source from medium" );
break;
}
Reference< XInterface > xPipe( xServiceFactory->createInstance(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe") ) ) );
if( !xPipe.is() )
{
DBG_ERROR( "XMLReader::Read: com.sun.star.io.Pipe service missing" );
break;
}
// connect pipe's output stream to the data source
xSource->setOutputStream( Reference< io::XOutputStream >::query( xPipe ) );
xml::sax::InputSource aParserInput;
aParserInput.aInputStream = uno::Reference< io::XInputStream >::query( xPipe );
aParserInput.sSystemId = aMedium.GetName();
if( xSource.is() )
{
Reference< io::XActiveDataControl > xSourceControl( xSource, UNO_QUERY );
xSourceControl->start();
}
*/
// #110680#
// Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xText ) );
Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xServiceFactory, xText ) );
xParser->setDocumentHandler( xHandler );
xml::sax::InputSource aParserInput;
aParserInput.aInputStream = xInputStream;
// aParserInput.sSystemId = aMedium.GetName();
xParser->parseStream( aParserInput );
}
while(0);
}
catch( uno::Exception& e )
{
}
}
SvXMLImportContext *SvxXMLXTextImportComponent::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
SvXMLImportContext* pContext;
if(XML_NAMESPACE_OFFICE == nPrefix && ( IsXMLToken( rLocalName, XML_DOCUMENT ) || IsXMLToken( rLocalName, XML_DOCUMENT_CONTENT ) ) )
{
pContext = new SvxXMLTextImportContext(*this, nPrefix, rLocalName, xAttrList, mxText );
}
else
{
pContext = SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
}
return pContext;
}
<|endoftext|> |
<commit_before>#include "WPILib.h"
#include "Commands/Command.h"
#include "Commands/ExampleCommand.h"
#include "CommandBase.h"
#include "XboxController.h"
#include "Subsystems/Shooter.h"
#include "Subsystems/BallCollector.h"
class Robot: public IterativeRobot {
private:
std::unique_ptr<Command> autonomousCommand;
SendableChooser *chooser;
std::unique_ptr<XboxController> controller;
std::unique_ptr<RobotDrive> robot_drive;
std::unique_ptr<Shooter> shooter;
std::unique_ptr<BallCollector> picker_upper;
void RobotInit() {
CommandBase::init();
chooser = new SendableChooser();
chooser->AddDefault("Default Auto", new ExampleCommand());
//chooser->AddObject("My Auto", new MyAutoCommand());
SmartDashboard::PutData("Auto Modes", chooser);
controller = std::unique_ptr<XboxController>(new XboxController(0));
robot_drive = std::unique_ptr<RobotDrive> (new RobotDrive(1,2,3,4));
shooter = std::unique_ptr<Shooter> (new Shooter());
picker_upper = std::unique_ptr<BallCollector> (new BallCollector());
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
void DisabledInit() {
}
void DisabledPeriodic() {
Scheduler::GetInstance()->Run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the GetString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the if-else structure below with additional strings & commands.
*/
void AutonomousInit() {
/* std::string autoSelected = SmartDashboard::GetString("Auto Selector", "Default");
if(autoSelected == "My Auto") {
autonomousCommand.reset(new MyAutoCommand());
} else {
autonomousCommand.reset(new ExampleCommand());
} */
autonomousCommand.reset((Command *)chooser->GetSelected());
if (autonomousCommand != NULL)
autonomousCommand->Start();
}
void AutonomousPeriodic() {
Scheduler::GetInstance()->Run();
}
void TeleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != NULL)
autonomousCommand->Cancel();
}
void TeleopPeriodic() {
Scheduler::GetInstance()->Run();
std::unique_ptr<Vector> left_stick_vector = std::unique_ptr<Vector>(controller->GetLeftVector());
std::unique_ptr<Vector> right_stick_vector = std::unique_ptr<Vector>(controller->GetRightVector());
robot_drive->TankDrive(left_stick_vector->magnitude, right_stick_vector->magnitude, false);
if (controller->GetTrigger(controller->RightTrigger,controller->RightTriggerOffset) >= 0.5){
shooter->run_shooter();
}else{
shooter->stop_shooter();
}
if (controller->GetTrigger(controller->LeftTrigger,controller->LeftTriggerOffset) >= 0.5){
picker_upper->Start();
}else{
picker_upper->Stop();
}
}
void TestPeriodic() {
LiveWindow::GetInstance()->Run();
}
};
START_ROBOT_CLASS(Robot)
<commit_msg>Removed old command base code<commit_after>#include "WPILib.h"
#include "XboxController.h"
#include "Subsystems/Shooter.h"
#include "Subsystems/BallCollector.h"
class Robot: public IterativeRobot {
private:
std::unique_ptr<XboxController> controller;
std::unique_ptr<RobotDrive> robot_drive;
std::unique_ptr<Shooter> shooter;
std::unique_ptr<BallCollector> ball_collector;
void RobotInit() {
// Initialize Subsystems
controller = std::unique_ptr<XboxController>(new XboxController(0));
robot_drive = std::unique_ptr<RobotDrive> (new RobotDrive(1,2,3,4));
shooter = std::unique_ptr<Shooter> (new Shooter());
ball_collector = std::unique_ptr<BallCollector> (new BallCollector());
}
void DisabledInit() {
}
void DisabledPeriodic() {
Scheduler::GetInstance()->Run();
}
void AutonomousInit() {
}
void AutonomousPeriodic() {
}
void TeleopInit() {
}
void TeleopPeriodic() {
std::unique_ptr<Vector> left_stick_vector = std::unique_ptr<Vector>(controller->GetLeftVector());
std::unique_ptr<Vector> right_stick_vector = std::unique_ptr<Vector>(controller->GetRightVector());
robot_drive->TankDrive(left_stick_vector->magnitude, right_stick_vector->magnitude, false);
if (controller->GetTrigger(controller->RightTrigger,controller->RightTriggerOffset) >= 0.5){
shooter->run_shooter();
}else{
shooter->stop_shooter();
}
if (controller->GetTrigger(controller->LeftTrigger,controller->LeftTriggerOffset) >= 0.5){
ball_collector->Start();
}else{
ball_collector->Stop();
}
}
void TestPeriodic() {
}
};
START_ROBOT_CLASS(Robot)
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "gtest/gtest.h"
#include "json_document.h"
#include "json_document_write.h"
#include "platform.h"
#include "statistics.h"
#include "util/pointer.h"
using namespace std; // NOLINT
namespace perf {
TEST(T_Statistics, Counter) {
Counter counter;
EXPECT_EQ(0, counter.Get());
counter.Set(1);
EXPECT_EQ(1, counter.Get());
counter.Inc();
EXPECT_EQ(2, counter.Get());
counter.Dec();
EXPECT_EQ(1, counter.Get());
EXPECT_EQ(1, counter.Xadd(-1));
EXPECT_EQ(0, counter.Get());
counter.Dec();
EXPECT_EQ(-1, counter.Get());
counter.Set(1024*1024);
EXPECT_EQ("1048576", counter.Print());
EXPECT_EQ("1024", counter.PrintKi());
EXPECT_EQ("1048", counter.PrintK());
EXPECT_EQ("1", counter.PrintM());
EXPECT_EQ("1", counter.PrintMi());
Counter counter2;
EXPECT_EQ("inf", counter.PrintRatio(counter2));
counter2.Set(1024);
EXPECT_EQ("1024.000", counter.PrintRatio(counter2));
}
TEST(T_Statistics, Statistics) {
Statistics statistics;
Counter *counter = statistics.Register("test.counter", "a test counter");
ASSERT_TRUE(counter != NULL);
EXPECT_EQ(0, counter->Get());
ASSERT_DEATH(statistics.Register("test.counter", "Name Clash"), ".*");
EXPECT_EQ(0, statistics.Lookup("test.counter")->Get());
EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter"));
EXPECT_EQ(NULL, statistics.Lookup("test.unknown"));
EXPECT_EQ("test.counter|0|a test counter\n",
statistics.PrintList(Statistics::kPrintSimple));
}
TEST(T_Statistics, Fork) {
Statistics stat_father;
Counter *cnt_father = stat_father.Register("father", "a test counter");
perf::Inc(cnt_father);
EXPECT_EQ(1, stat_father.Lookup("father")->Get());
Statistics *stat_child = stat_father.Fork();
EXPECT_EQ(1, stat_child->Lookup("father")->Get());
perf::Inc(cnt_father);
EXPECT_EQ(2, stat_father.Lookup("father")->Get());
EXPECT_EQ(2, stat_child->Lookup("father")->Get());
Counter *cnt_fork_father = stat_father.Register("fork", "a test counter");
stat_child->Register("fork", "a test counter");
perf::Inc(cnt_fork_father);
EXPECT_EQ(1, stat_father.Lookup("fork")->Get());
EXPECT_EQ(0, stat_child->Lookup("fork")->Get());
delete stat_child;
EXPECT_EQ(2, stat_father.Lookup("father")->Get());
}
TEST(T_Statistics, StatisticsTemplate) {
Statistics statistics;
StatisticsTemplate stat_template1("template1", &statistics);
StatisticsTemplate stat_template2("template2", &statistics);
StatisticsTemplate stat_sub("sub", stat_template1);
Counter *cnt1 = stat_template1.RegisterTemplated("value", "a test counter");
Counter *cnt2 = stat_template2.RegisterTemplated("value", "a test counter");
Counter *cnt_sub = stat_sub.RegisterTemplated("value", "test");
EXPECT_EQ(cnt1, statistics.Lookup("template1.value"));
EXPECT_EQ(cnt2, statistics.Lookup("template2.value"));
EXPECT_EQ(cnt_sub, statistics.Lookup("template1.sub.value"));
}
TEST(T_Statistics, RecorderConstruct) {
Recorder recorder(5, 10);
EXPECT_EQ(10U, recorder.capacity_s());
Recorder recorder2(5, 9);
EXPECT_EQ(10U, recorder2.capacity_s());
Recorder recorder3(5, 6);
EXPECT_EQ(10U, recorder3.capacity_s());
Recorder recorder4(1, 10);
EXPECT_EQ(10U, recorder4.capacity_s());
}
TEST(T_Statistics, RecorderTick) {
Recorder recorder(1, 10);
EXPECT_EQ(0U, recorder.GetNoTicks(0));
EXPECT_EQ(0U, recorder.GetNoTicks(1));
EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));
recorder.Tick();
recorder.TickAt(platform_monotonic_time() - 5);
EXPECT_EQ(1U, recorder.GetNoTicks(1));
EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));
// Don't record tick in the distant past
recorder.TickAt(0);
EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));
// Many ticks in a past period
Recorder recorder2(1, 10);
for (unsigned i = 0; i < 10; ++i)
recorder2.TickAt(i);
EXPECT_EQ(0U, recorder2.GetNoTicks(1));
EXPECT_EQ(10U, recorder2.GetNoTicks(uint32_t(-1)));
// Long gap with no ticks
recorder2.Tick();
EXPECT_EQ(1U, recorder2.GetNoTicks(uint32_t(-1)));
// Ticks not starting at zero
Recorder recorder3(1, 10);
for (unsigned i = 2; i < 12; ++i)
recorder3.TickAt(i);
EXPECT_EQ(0U, recorder3.GetNoTicks(1));
EXPECT_EQ(10U, recorder3.GetNoTicks(uint32_t(-1)));
// More coarse-grained binning, ring buffer overflow
Recorder recorder4(2, 10);
for (unsigned i = 2; i < 22; ++i)
recorder4.TickAt(i);
EXPECT_EQ(0U, recorder4.GetNoTicks(1));
EXPECT_EQ(10U, recorder4.GetNoTicks(uint32_t(-1)));
// Clear bins
Recorder recorder5(1, 10);
for (unsigned i = 2; i < 12; ++i)
recorder5.TickAt(i);
recorder5.TickAt(14);
EXPECT_EQ(8U, recorder5.GetNoTicks(uint32_t(-1)));
}
TEST(T_Statistics, MultiRecorder) {
MultiRecorder recorder;
recorder.Tick();
EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));
recorder.AddRecorder(1, 10);
recorder.AddRecorder(2, 20);
for (unsigned i = 2; i < 22; ++i)
recorder.TickAt(i);
EXPECT_EQ(20U, recorder.GetNoTicks(uint32_t(-1)));
recorder.Tick();
EXPECT_EQ(1U, recorder.GetNoTicks(1));
EXPECT_EQ(1U, recorder.GetNoTicks(uint32_t(-1)));
}
TEST(T_Statistics, GenerateCorrectJsonEvenWithoutInput) {
Statistics stats;
std::string output = stats.PrintJSON();
UniquePtr<JsonDocument> json(JsonDocument::Create(output));
ASSERT_TRUE(json.IsValid());
}
} // namespace perf
<commit_msg>T_Statistics: add unittest for PrintJSON()<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "gtest/gtest.h"
#include "json_document.h"
#include "json_document_write.h"
#include "platform.h"
#include "statistics.h"
#include "util/pointer.h"
using namespace std; // NOLINT
namespace perf {
TEST(T_Statistics, Counter) {
Counter counter;
EXPECT_EQ(0, counter.Get());
counter.Set(1);
EXPECT_EQ(1, counter.Get());
counter.Inc();
EXPECT_EQ(2, counter.Get());
counter.Dec();
EXPECT_EQ(1, counter.Get());
EXPECT_EQ(1, counter.Xadd(-1));
EXPECT_EQ(0, counter.Get());
counter.Dec();
EXPECT_EQ(-1, counter.Get());
counter.Set(1024*1024);
EXPECT_EQ("1048576", counter.Print());
EXPECT_EQ("1024", counter.PrintKi());
EXPECT_EQ("1048", counter.PrintK());
EXPECT_EQ("1", counter.PrintM());
EXPECT_EQ("1", counter.PrintMi());
Counter counter2;
EXPECT_EQ("inf", counter.PrintRatio(counter2));
counter2.Set(1024);
EXPECT_EQ("1024.000", counter.PrintRatio(counter2));
}
TEST(T_Statistics, Statistics) {
Statistics statistics;
Counter *counter = statistics.Register("test.counter", "a test counter");
ASSERT_TRUE(counter != NULL);
EXPECT_EQ(0, counter->Get());
ASSERT_DEATH(statistics.Register("test.counter", "Name Clash"), ".*");
EXPECT_EQ(0, statistics.Lookup("test.counter")->Get());
EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter"));
EXPECT_EQ(NULL, statistics.Lookup("test.unknown"));
EXPECT_EQ("test.counter|0|a test counter\n",
statistics.PrintList(Statistics::kPrintSimple));
}
TEST(T_Statistics, Fork) {
Statistics stat_father;
Counter *cnt_father = stat_father.Register("father", "a test counter");
perf::Inc(cnt_father);
EXPECT_EQ(1, stat_father.Lookup("father")->Get());
Statistics *stat_child = stat_father.Fork();
EXPECT_EQ(1, stat_child->Lookup("father")->Get());
perf::Inc(cnt_father);
EXPECT_EQ(2, stat_father.Lookup("father")->Get());
EXPECT_EQ(2, stat_child->Lookup("father")->Get());
Counter *cnt_fork_father = stat_father.Register("fork", "a test counter");
stat_child->Register("fork", "a test counter");
perf::Inc(cnt_fork_father);
EXPECT_EQ(1, stat_father.Lookup("fork")->Get());
EXPECT_EQ(0, stat_child->Lookup("fork")->Get());
delete stat_child;
EXPECT_EQ(2, stat_father.Lookup("father")->Get());
}
TEST(T_Statistics, StatisticsTemplate) {
Statistics statistics;
StatisticsTemplate stat_template1("template1", &statistics);
StatisticsTemplate stat_template2("template2", &statistics);
StatisticsTemplate stat_sub("sub", stat_template1);
Counter *cnt1 = stat_template1.RegisterTemplated("value", "a test counter");
Counter *cnt2 = stat_template2.RegisterTemplated("value", "a test counter");
Counter *cnt_sub = stat_sub.RegisterTemplated("value", "test");
EXPECT_EQ(cnt1, statistics.Lookup("template1.value"));
EXPECT_EQ(cnt2, statistics.Lookup("template2.value"));
EXPECT_EQ(cnt_sub, statistics.Lookup("template1.sub.value"));
}
TEST(T_Statistics, RecorderConstruct) {
Recorder recorder(5, 10);
EXPECT_EQ(10U, recorder.capacity_s());
Recorder recorder2(5, 9);
EXPECT_EQ(10U, recorder2.capacity_s());
Recorder recorder3(5, 6);
EXPECT_EQ(10U, recorder3.capacity_s());
Recorder recorder4(1, 10);
EXPECT_EQ(10U, recorder4.capacity_s());
}
TEST(T_Statistics, RecorderTick) {
Recorder recorder(1, 10);
EXPECT_EQ(0U, recorder.GetNoTicks(0));
EXPECT_EQ(0U, recorder.GetNoTicks(1));
EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));
recorder.Tick();
recorder.TickAt(platform_monotonic_time() - 5);
EXPECT_EQ(1U, recorder.GetNoTicks(1));
EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));
// Don't record tick in the distant past
recorder.TickAt(0);
EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));
// Many ticks in a past period
Recorder recorder2(1, 10);
for (unsigned i = 0; i < 10; ++i)
recorder2.TickAt(i);
EXPECT_EQ(0U, recorder2.GetNoTicks(1));
EXPECT_EQ(10U, recorder2.GetNoTicks(uint32_t(-1)));
// Long gap with no ticks
recorder2.Tick();
EXPECT_EQ(1U, recorder2.GetNoTicks(uint32_t(-1)));
// Ticks not starting at zero
Recorder recorder3(1, 10);
for (unsigned i = 2; i < 12; ++i)
recorder3.TickAt(i);
EXPECT_EQ(0U, recorder3.GetNoTicks(1));
EXPECT_EQ(10U, recorder3.GetNoTicks(uint32_t(-1)));
// More coarse-grained binning, ring buffer overflow
Recorder recorder4(2, 10);
for (unsigned i = 2; i < 22; ++i)
recorder4.TickAt(i);
EXPECT_EQ(0U, recorder4.GetNoTicks(1));
EXPECT_EQ(10U, recorder4.GetNoTicks(uint32_t(-1)));
// Clear bins
Recorder recorder5(1, 10);
for (unsigned i = 2; i < 12; ++i)
recorder5.TickAt(i);
recorder5.TickAt(14);
EXPECT_EQ(8U, recorder5.GetNoTicks(uint32_t(-1)));
}
TEST(T_Statistics, MultiRecorder) {
MultiRecorder recorder;
recorder.Tick();
EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));
recorder.AddRecorder(1, 10);
recorder.AddRecorder(2, 20);
for (unsigned i = 2; i < 22; ++i)
recorder.TickAt(i);
EXPECT_EQ(20U, recorder.GetNoTicks(uint32_t(-1)));
recorder.Tick();
EXPECT_EQ(1U, recorder.GetNoTicks(1));
EXPECT_EQ(1U, recorder.GetNoTicks(uint32_t(-1)));
}
TEST(T_Statistics, GenerateCorrectJsonEvenWithoutInput) {
Statistics stats;
std::string output = stats.PrintJSON();
UniquePtr<JsonDocument> json(JsonDocument::Create(output));
ASSERT_TRUE(json.IsValid());
}
TEST(T_Statistics, GenerateJSONStatisticsTemplates) {
Statistics stats;
StatisticsTemplate stat_template1("template1", &stats);
StatisticsTemplate stat_template2("template2", &stats);
StatisticsTemplate stat_template_empty("emptytemplate", &stats);
Counter *cnt1 = stat_template1.RegisterTemplated("valueA", "test counter A");
Counter *cnt2 = stat_template1.RegisterTemplated("valueB", "test counter B");
Counter *cnt3 = stat_template2.RegisterTemplated("valueC", "test counter C");
cnt1->Set(420);
cnt2->Set(0);
cnt3->Set(-42);
std::string json_observed = stats.PrintJSON();
std::string json_expected =
"{\"template1\":{\"valueA\":420,\"valueB\":0},"
"\"template2\":{\"valueC\":-42}}";
EXPECT_EQ(json_expected, json_observed);
}
} // namespace perf
<|endoftext|> |
<commit_before>/*
Pololu Motor Driver Code for Use with Arduino Microcontroller.
Adapted from https://github.com/pololu/qik-arduino, a pololu supplied library
Author: Alex Sher, 17 Oct 2013
*/
#include "serial_interface.h"
// serial command buffer storage
char cmd[5];
// C++ serial interface stuff
using namespace LibSerial;
SerialStream serial_port;
char readBuffer[1];
int numBytesRead;
// Pololu Object, works for models 2s9v1 and 2s12v10
PololuQik::PololuQik(char serial_port_filename[])
{
// Open port for reading and writing
serial_port.Open(serial_port_filename);
if(!serial_port.good()){
printf("Error, can't open serial port ya dingwad \n");
exit(0);
}
serial_port.SetBaudRate(SerialStreamBuf::BAUD_9600);
if(!serial_port.good()){
printf("Error setting baud rate, exiting \n");
exit(0);
}
// Tell Pololu Motor Driver to autodetect Baud Rate
memset(cmd, 0, 5);
cmd[0] = 0xAA;
serial_port.write(cmd, 1);
}
/*
Will develop once Set Speed works as expected
// Return Firmware Version
char PololuQik::getFirmwareVersion()
{
write(QIK_GET_FIRMWARE_VERSION);
while (available() < 1);
memset(readBuffer, 0, 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Return Error Byte (definitions here: http://www.pololu.com/docs/0J29/5.c)
byte PololuQik::getErrors()
{
write(QIK_GET_ERROR_BYTE);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Return Configuration Parameters (see PololuQik.h for list of parameters)
byte PololuQik::getConfigurationParameter(byte parameter)
{
listen();
cmd[0] = QIK_GET_CONFIGURATION_PARAMETER;
cmd[1] = parameter;
write(cmd, 2);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Set Configuration parameters (see PololuQik.h for info on parameters)
byte PololuQik::setConfigurationParameter(byte parameter, byte value)
{
listen();
cmd[0] = QIK_SET_CONFIGURATION_PARAMETER;
cmd[1] = parameter;
cmd[2] = value;
cmd[3] = 0x55;
cmd[4] = 0x2A;
write(cmd, 5);
while (available() < 1);
return read();
return fread(readBuffer, sizeof(char), serPort);
}
*/
// Set Speed command
void PololuQik::setM0Speed(int speed)
{
// Direction value
bool reverse = 0;
// Handle negative direction speeds
if (speed < 0)
{
// make speed a positive quantity
speed = -speed;
// preserve the direction
reverse = 1;
}
// Clamp speed at Max readable speed
if (speed > 255)
{
speed = 255;
}
// Reset Command byte
memset(cmd, 0, 5);
if (speed > 127)
{
// 8-bit mode: actual speed is (speed + 128)
cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE_8_BIT : QIK_MOTOR_M0_FORWARD_8_BIT;
cmd[1] = speed - 128;
}
else
{
// lower bit mode, can physically write speed in normal mode
cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE : QIK_MOTOR_M0_FORWARD;
cmd[1] = speed;
}
serial_port.write(cmd, 2);
}
// Set Speed command for second channel, see above for explanations
void PololuQik::setM1Speed(int speed)
{
bool reverse = 0;
if (speed < 0)
{
speed = -speed;
reverse = 1;
}
if (speed > 255)
{
speed = 255;
}
memset(cmd, 0, 5);
if (speed > 127)
{
cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE_8_BIT : QIK_MOTOR_M1_FORWARD_8_BIT;
cmd[1] = speed - 128;
}
else
{
cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE : QIK_MOTOR_M1_FORWARD;
cmd[1] = speed;
}
serial_port.write(cmd, 2);
}
// Set speeds on both channels
void PololuQik::setSpeeds(int m0Speed, int m1Speed)
{
// Simply use commands written above
setM0Speed(m0Speed);
setM1Speed(m1Speed);
}
// 2s12v10 specific stuff
// Brake Command
void PololuQik2s12v10::setM0Brake(unsigned char brake)
{
// Limit to 127, the brake limit
if (brake > 127)
{
brake = 127;
}
// Reset Command buffer
memset(cmd, 0, 5);
// pack the command array
cmd[0] = QIK_2S12V10_MOTOR_M0_BRAKE;
cmd[1] = brake;
// Serial write
serial_port.write(cmd, 2);
}
// Brake command for second channel, see above for explanations
void PololuQik2s12v10::setM1Brake(unsigned char brake)
{
if (brake > 127)
{
brake = 127;
}
memset(cmd, 0, 5);
cmd[0] = QIK_2S12V10_MOTOR_M1_BRAKE;
cmd[1] = brake;
serial_port.write(cmd, 2);
}
// Dual Channel Brake Command
void PololuQik2s12v10::setBrakes(unsigned char m0Brake, unsigned char m1Brake)
{
// Utlizie pre=written Brake Functions
setM0Brake(m0Brake);
setM1Brake(m1Brake);
}
/*
Under Development once we get main functionality working
// Get Current
unsigned char PololuQik2s12v10::getM0Current()
{
// Make sure device is still there
listen();
// Write command byte
write(QIK_2S12V10_GET_MOTOR_M0_CURRENT);
// Wait for response
while (available() < 1);
// Return response
return read();
return fread(readBuffer, sizeof(char), serPort);
}
// Current command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Current()
{
listen();
write(QIK_2S12V10_GET_MOTOR_M1_CURRENT);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Current command for mA
unsigned int PololuQik2s12v10::getM0CurrentMilliamps()
{
// Use regular current call and scale
return getM0Current() * 150;
}
// Current command for second channel, see above for explanation
unsigned int PololuQik2s12v10::getM1CurrentMilliamps()
{
return getM1Current() * 150;
}
// Get speed command
unsigned char PololuQik2s12v10::getM0Speed()
{
// Make sure device is still there
listen();
// Write command byte
write(QIK_2S12V10_GET_MOTOR_M0_SPEED);
// Wait for a response
while (available() < 1);
// Return response
return fread(readBuffer, sizeof(char), serPort);
}
// Speed command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Speed()
{
listen();
write(QIK_2S12V10_GET_MOTOR_M1_SPEED);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
*/
<commit_msg>Added Base Control launch file for launching all nodes necessary to control motors from computer.<commit_after>/*
Pololu Motor Driver Code for Use with Arduino Microcontroller.
Adapted from https://github.com/pololu/qik-arduino, a pololu supplied library
Author: Alex Sher, 17 Oct 2013
*/
#include "serial_interface.h"
// serial command buffer storage
char cmd[5];
// C++ serial interface stuff
using namespace LibSerial;
SerialStream serial_port;
char readBuffer[1];
int numBytesRead;
// Pololu Object, works for models 2s9v1 and 2s12v10
PololuQik::PololuQik(char serial_port_filename[])
{
// Open port for reading and writing
serial_port.Open(serial_port_filename);
if(!serial_port.good()){
printf("Error, can't open serial port ya dingwad \n");
exit(1);
}
serial_port.SetBaudRate(SerialStreamBuf::BAUD_9600);
if(!serial_port.good()){
printf("Error setting baud rate, exiting \n");
exit(1);
}
// Tell Pololu Motor Driver to autodetect Baud Rate
memset(cmd, 0, 5);
cmd[0] = 0xAA;
serial_port.write(cmd, 1);
}
/*
Will develop once Set Speed works as expected
// Return Firmware Version
char PololuQik::getFirmwareVersion()
{
write(QIK_GET_FIRMWARE_VERSION);
while (available() < 1);
memset(readBuffer, 0, 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Return Error Byte (definitions here: http://www.pololu.com/docs/0J29/5.c)
byte PololuQik::getErrors()
{
write(QIK_GET_ERROR_BYTE);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Return Configuration Parameters (see PololuQik.h for list of parameters)
byte PololuQik::getConfigurationParameter(byte parameter)
{
listen();
cmd[0] = QIK_GET_CONFIGURATION_PARAMETER;
cmd[1] = parameter;
write(cmd, 2);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Set Configuration parameters (see PololuQik.h for info on parameters)
byte PololuQik::setConfigurationParameter(byte parameter, byte value)
{
listen();
cmd[0] = QIK_SET_CONFIGURATION_PARAMETER;
cmd[1] = parameter;
cmd[2] = value;
cmd[3] = 0x55;
cmd[4] = 0x2A;
write(cmd, 5);
while (available() < 1);
return read();
return fread(readBuffer, sizeof(char), serPort);
}
*/
// Set Speed command
void PololuQik::setM0Speed(int speed)
{
// Direction value
bool reverse = 0;
// Handle negative direction speeds
if (speed < 0)
{
// make speed a positive quantity
speed = -speed;
// preserve the direction
reverse = 1;
}
// Clamp speed at Max readable speed
if (speed > 255)
{
speed = 255;
}
// Reset Command byte
memset(cmd, 0, 5);
if (speed > 127)
{
// 8-bit mode: actual speed is (speed + 128)
cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE_8_BIT : QIK_MOTOR_M0_FORWARD_8_BIT;
cmd[1] = speed - 128;
}
else
{
// lower bit mode, can physically write speed in normal mode
cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE : QIK_MOTOR_M0_FORWARD;
cmd[1] = speed;
}
serial_port.write(cmd, 2);
}
// Set Speed command for second channel, see above for explanations
void PololuQik::setM1Speed(int speed)
{
bool reverse = 0;
if (speed < 0)
{
speed = -speed;
reverse = 1;
}
if (speed > 255)
{
speed = 255;
}
memset(cmd, 0, 5);
if (speed > 127)
{
cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE_8_BIT : QIK_MOTOR_M1_FORWARD_8_BIT;
cmd[1] = speed - 128;
}
else
{
cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE : QIK_MOTOR_M1_FORWARD;
cmd[1] = speed;
}
serial_port.write(cmd, 2);
}
// Set speeds on both channels
void PololuQik::setSpeeds(int m0Speed, int m1Speed)
{
// Simply use commands written above
setM0Speed(m0Speed);
setM1Speed(m1Speed);
}
// 2s12v10 specific stuff
// Brake Command
void PololuQik2s12v10::setM0Brake(unsigned char brake)
{
// Limit to 127, the brake limit
if (brake > 127)
{
brake = 127;
}
// Reset Command buffer
memset(cmd, 0, 5);
// pack the command array
cmd[0] = QIK_2S12V10_MOTOR_M0_BRAKE;
cmd[1] = brake;
// Serial write
serial_port.write(cmd, 2);
}
// Brake command for second channel, see above for explanations
void PololuQik2s12v10::setM1Brake(unsigned char brake)
{
if (brake > 127)
{
brake = 127;
}
memset(cmd, 0, 5);
cmd[0] = QIK_2S12V10_MOTOR_M1_BRAKE;
cmd[1] = brake;
serial_port.write(cmd, 2);
}
// Dual Channel Brake Command
void PololuQik2s12v10::setBrakes(unsigned char m0Brake, unsigned char m1Brake)
{
// Utlizie pre=written Brake Functions
setM0Brake(m0Brake);
setM1Brake(m1Brake);
}
/*
Under Development once we get main functionality working
// Get Current
unsigned char PololuQik2s12v10::getM0Current()
{
// Make sure device is still there
listen();
// Write command byte
write(QIK_2S12V10_GET_MOTOR_M0_CURRENT);
// Wait for response
while (available() < 1);
// Return response
return read();
return fread(readBuffer, sizeof(char), serPort);
}
// Current command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Current()
{
listen();
write(QIK_2S12V10_GET_MOTOR_M1_CURRENT);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
// Current command for mA
unsigned int PololuQik2s12v10::getM0CurrentMilliamps()
{
// Use regular current call and scale
return getM0Current() * 150;
}
// Current command for second channel, see above for explanation
unsigned int PololuQik2s12v10::getM1CurrentMilliamps()
{
return getM1Current() * 150;
}
// Get speed command
unsigned char PololuQik2s12v10::getM0Speed()
{
// Make sure device is still there
listen();
// Write command byte
write(QIK_2S12V10_GET_MOTOR_M0_SPEED);
// Wait for a response
while (available() < 1);
// Return response
return fread(readBuffer, sizeof(char), serPort);
}
// Speed command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Speed()
{
listen();
write(QIK_2S12V10_GET_MOTOR_M1_SPEED);
while (available() < 1);
return fread(readBuffer, sizeof(char), serPort);
}
*/
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro ([email protected]) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "ingredientmatcherdialog.h"
#include "datablocks/recipelist.h"
#include "widgets/ingredientlistview.h"
#include "datablocks/elementlist.h"
#include "backends/recipedb.h"
#include "widgets/krelistview.h"
#include "widgets/unitcombobox.h"
#include "widgets/fractioninput.h"
#include "widgets/amountunitinput.h"
#include "datablocks/mixednumber.h"
#include "recipeactionshandler.h"
#include <q3header.h>
#include <qpainter.h>
#include <qstringlist.h>
#include <qlayout.h>
#include <q3groupbox.h>
//Added by qt3to4:
#include <QHBoxLayout>
#include <Q3ValueList>
#include <QLabel>
#include <QVBoxLayout>
#include <kapplication.h>
#include <kcursor.h>
#include <kiconloader.h>
#include <klocale.h>
#include <knuminput.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kvbox.h>
#include "profiling.h"
IngredientMatcherDialog::IngredientMatcherDialog( QWidget *parent, RecipeDB *db ) : QWidget( parent )
{
// Initialize internal variables
database = db;
//Design the dialog
QVBoxLayout *dialogLayout = new QVBoxLayout( this );
dialogLayout->setMargin( 11 );
dialogLayout->setSpacing( 6 );
// Ingredient list
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->setObjectName( "layout2" );
layout2->setMargin( 0 );
layout2->setSpacing( 6 );
allIngListView = new KreListView( this, QString::null, true, 0 );
StdIngredientListView *list_view = new StdIngredientListView(allIngListView,database);
list_view->setSelectionMode( Q3ListView::Multi );
allIngListView->setListView(list_view);
layout2->addWidget( allIngListView );
QVBoxLayout *layout1 = new QVBoxLayout();
layout1->setMargin( 0 );
layout1->setSpacing( 6 );
layout1->setObjectName( "layout1" );
//KIconLoader *il = KIconLoader::global();
addButton = new KPushButton( this );
addButton->setObjectName( "addButton" );
//addButton->setIconSet( il->loadIconSet( "go-next", KIcon::Small ) );
addButton->setFixedSize( QSize( 32, 32 ) );
layout1->addWidget( addButton );
removeButton = new KPushButton( this );
removeButton->setObjectName( "removeButton" );
//removeButton->setIconSet( il->loadIconSet( "go-previous", KIcon::Small ) );
removeButton->setFixedSize( QSize( 32, 32 ) );
layout1->addWidget( removeButton );
QSpacerItem *spacer1 = new QSpacerItem( 51, 191, QSizePolicy::Minimum, QSizePolicy::Expanding );
layout1->addItem( spacer1 );
layout2->addLayout( layout1 );
ingListView = new KreListView( this, QString::null, true );
ingListView->listView() ->addColumn( i18n( "Ingredient (required?)" ) );
ingListView->listView() ->addColumn( i18n( "Amount Available" ) );
layout2->addWidget( ingListView );
dialogLayout->addLayout( layout2 );
// Box to select allowed number of missing ingredients
missingBox = new KHBox( this );
missingNumberLabel = new QLabel( missingBox );
missingNumberLabel->setText( i18n( "Missing ingredients allowed:" ) );
missingNumberSpinBox = new KIntSpinBox( missingBox );
missingNumberSpinBox->setMinimum( -1 );
missingNumberSpinBox->setSpecialValueText( i18n( "Any" ) );
dialogLayout->addWidget(missingBox);
// Found recipe list
recipeListView = new KreListView( this, i18n( "Matching Recipes" ), false, 1, missingBox );
recipeListView->listView() ->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
recipeListView->listView() ->setAllColumnsShowFocus( true );
recipeListView->listView() ->addColumn( i18n( "Title" ) );
KConfigGroup config( KGlobal::config(), "Advanced" );
bool show_id = config.readEntry( "ShowID", false );
recipeListView->listView() ->addColumn( i18n( "Id" ), show_id ? -1 : 0 );
recipeListView->listView() ->addColumn( i18n( "Missing Ingredients" ) );
recipeListView->listView() ->setSorting( -1 );
dialogLayout->addWidget(recipeListView);
RecipeActionsHandler *actionHandler = new RecipeActionsHandler( recipeListView->listView(), database, RecipeActionsHandler::Open | RecipeActionsHandler::Edit | RecipeActionsHandler::Export );
KHBox *buttonBox = new KHBox( this );
okButton = new KPushButton( buttonBox );
//okButton->setIconSet( il->loadIconSet( "dialog-ok", KIcon::Small ) );
okButton->setText( i18n( "Find matching recipes" ) );
//buttonBox->layout()->addItem( new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) );
clearButton = new KPushButton( buttonBox );
//clearButton->setIconSet( il->loadIconSet( "edit-clear", KIcon::Small ) );
clearButton->setText( i18n( "Clear" ) );
dialogLayout->addWidget(buttonBox);
// Connect signals & slots
connect ( okButton, SIGNAL( clicked() ), this, SLOT( findRecipes() ) );
connect ( clearButton, SIGNAL( clicked() ), recipeListView->listView(), SLOT( clear() ) );
connect ( clearButton, SIGNAL( clicked() ), this, SLOT( unselectIngredients() ) );
connect ( actionHandler, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
connect( addButton, SIGNAL( clicked() ), this, SLOT( addIngredient() ) );
connect( removeButton, SIGNAL( clicked() ), this, SLOT( removeIngredient() ) );
connect( ingListView->listView(), SIGNAL( doubleClicked( Q3ListViewItem*, const QPoint &, int ) ), SLOT( itemRenamed( Q3ListViewItem*, const QPoint &, int ) ) );
}
IngredientMatcherDialog::~IngredientMatcherDialog()
{
}
void IngredientMatcherDialog::itemRenamed( Q3ListViewItem* item, const QPoint &, int col )
{
if ( col == 1 ) {
KDialog amountEditDialog(this);
amountEditDialog.setCaption(i18n("Enter amount"));
amountEditDialog.setButtons(KDialog::Cancel | KDialog::Ok);
amountEditDialog.setDefaultButton(KDialog::Ok);
amountEditDialog.setModal( false );
Q3GroupBox *box = new Q3GroupBox( 1, Qt::Horizontal, i18n("Amount"), &amountEditDialog );
AmountUnitInput *amountEdit = new AmountUnitInput( box, database );
// Set the values from the item
if ( !item->text(1).isEmpty() ) {
amountEdit->setAmount( MixedNumber::fromString(item->text(2)) );
Unit u;
u.id = item->text(3).toInt();
amountEdit->setUnit( u );
} else {
amountEdit->setAmount( -1 );
Unit u;
u.id = -1;
amountEdit->setUnit( u );
}
amountEditDialog.setMainWidget(box);
if ( amountEditDialog.exec() == QDialog::Accepted ) {
MixedNumber amount = amountEdit->amount();
Unit unit = amountEdit->unit();
if ( amount.toDouble() <= 1e-5 ) {
amount = -1;
unit.id = -1;
item->setText(1,QString::null);
} else {
item->setText(1,amount.toString()+" "+((amount.toDouble()>1)?unit.plural:unit.name));
}
item->setText(2,amount.toString());
item->setText(3,QString::number(unit.id));
IngredientList::iterator ing_it = m_item_ing_map[item];
(*ing_it).amount = amount.toDouble();
(*ing_it).units = unit;
}
}
}
void IngredientMatcherDialog::addIngredient()
{
/*
QList<Q3ListViewItem> items = allIngListView->listView()->selectedItems();
if ( !items.isEmpty() ) {
for (int i = 0; i < items.size(); ++i) {
bool dup = false;
for ( Q3ListViewItem *exists_it = ingListView->listView()->firstChild(); exists_it; exists_it = exists_it->nextSibling() ) {
if ( exists_it->text( 0 ) == item->text( 0 ) ) {
dup = true;
break;
}
}
if ( !dup ) {
Q3ListViewItem * new_item = new Q3CheckListItem( ingListView->listView(), item->text( 0 ), Q3CheckListItem::CheckBox );
ingListView->listView() ->setSelected( new_item, true );
ingListView->listView() ->ensureItemVisible( new_item );
allIngListView->listView() ->setSelected( item, false );
m_item_ing_map.insert( new_item, m_ingredientList.append( Ingredient( item->text( 0 ), 0, Unit(), -1, item->text( 1 ).toInt() ) ) );
}
++it;
}
}
*/
}
void IngredientMatcherDialog::removeIngredient()
{
/*
Q3ListViewItem * item = ingListView->listView() ->selectedItem();
if ( item ) {
for ( IngredientList::iterator it = m_ingredientList.begin(); it != m_ingredientList.end(); ++it ) {
if ( *m_item_ing_map.find( item ) == it ) {
m_ingredientList.remove( it );
m_item_ing_map.remove( item );
break;
}
}
delete item;
}
*/
}
void IngredientMatcherDialog::unselectIngredients()
{
ingListView->listView()->clear();
for ( Q3ListViewItem *it = allIngListView->listView()->firstChild(); it; it = it->nextSibling() )
allIngListView->listView()->setSelected(it,false);
}
void IngredientMatcherDialog::findRecipes( void )
{
KApplication::setOverrideCursor( Qt::WaitCursor );
START_TIMER("Ingredient Matcher: loading database data");
RecipeList rlist;
database->loadRecipes( &rlist, RecipeDB::Title | RecipeDB::NamesOnly | RecipeDB::Ingredients | RecipeDB::IngredientAmounts );
END_TIMER();
START_TIMER("Ingredient Matcher: analyzing data for matching recipes");
// Clear the list
recipeListView->listView() ->clear();
// Now show the recipes with ingredients that are contained in the previous set
// of ingredients
RecipeList incompleteRecipes;
QList <int> missingNumbers;
Q3ValueList <IngredientList> missingIngredients;
RecipeList::Iterator it;
for ( it = rlist.begin();it != rlist.end();++it ) {
IngredientList il = ( *it ).ingList;
if ( il.isEmpty() )
continue;
IngredientList missing;
if ( m_ingredientList.containsSubSet( il, missing, true, database ) ) {
new CustomRecipeListItem( recipeListView->listView(), *it );
}
else {
incompleteRecipes.append( *it );
missingIngredients.append( missing );
missingNumbers.append( missing.count() );
}
}
END_TIMER();
//Check if the user wants to show missing ingredients
if ( missingNumberSpinBox->value() == 0 ) {
KApplication::restoreOverrideCursor();
return ;
} //"None"
START_TIMER("Ingredient Matcher: searching for and displaying partial matches");
IngredientList requiredIngredients;
for ( Q3ListViewItem *it = ingListView->listView()->firstChild(); it; it = it->nextSibling() ) {
if ( ((Q3CheckListItem*)it)->isOn() )
requiredIngredients << *m_item_ing_map[it];
}
// Classify recipes with missing ingredients in different lists by ammount
QList<int>::Iterator nit;
Q3ValueList<IngredientList>::Iterator ilit;
int missingNoAllowed = missingNumberSpinBox->value();
if ( missingNoAllowed == -1 ) // "Any"
{
for ( nit = missingNumbers.begin();nit != missingNumbers.end();++nit )
if ( ( *nit ) > missingNoAllowed )
missingNoAllowed = ( *nit );
}
for ( int missingNo = 1; missingNo <= missingNoAllowed; missingNo++ ) {
nit = missingNumbers.begin();
ilit = missingIngredients.begin();
bool titleShownYet = false;
for ( it = incompleteRecipes.begin();it != incompleteRecipes.end();++it, ++nit, ++ilit ) {
if ( !( *it ).ingList.containsAny( m_ingredientList ) )
continue;
if ( !( *it ).ingList.containsSubSet( requiredIngredients ) )
continue;
if ( ( *nit ) == missingNo ) {
if ( !titleShownYet ) {
new SectionItem( recipeListView->listView(), i18np( "You are missing 1 ingredient for:", "You are missing %1 ingredients for:", missingNo ) );
titleShownYet = true;
}
new CustomRecipeListItem( recipeListView->listView(), *it, *ilit );
}
}
}
END_TIMER();
KApplication::restoreOverrideCursor();
}
void IngredientMatcherDialog::reload( ReloadFlags flag )
{
( ( StdIngredientListView* ) allIngListView->listView() ) ->reload(flag);
}
void SectionItem::paintCell ( QPainter * p, const QColorGroup & /*cg*/, int column, int width, int /*align*/ )
{
// Draw the section's deco
p->setPen( KGlobalSettings::activeTitleColor() );
p->setBrush( KGlobalSettings::activeTitleColor() );
p->drawRect( 0, 0, width, height() );
// Draw the section's text
if ( column == 0 ) {
QFont titleFont = KGlobalSettings::windowTitleFont ();
p->setFont( titleFont );
p->setPen( KGlobalSettings::activeTextColor() );
p->drawText( 0, 0, width, height(), Qt::AlignLeft | Qt::AlignVCenter, mText );
}
}
#include "ingredientmatcherdialog.moc"
<commit_msg>Restored the icons for the buttons in the ingredient matcher dialog.<commit_after>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro ([email protected]) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "ingredientmatcherdialog.h"
#include "datablocks/recipelist.h"
#include "widgets/ingredientlistview.h"
#include "datablocks/elementlist.h"
#include "backends/recipedb.h"
#include "widgets/krelistview.h"
#include "widgets/unitcombobox.h"
#include "widgets/fractioninput.h"
#include "widgets/amountunitinput.h"
#include "datablocks/mixednumber.h"
#include "recipeactionshandler.h"
#include <q3header.h>
#include <qpainter.h>
#include <qstringlist.h>
#include <qlayout.h>
#include <q3groupbox.h>
//Added by qt3to4:
#include <QHBoxLayout>
#include <Q3ValueList>
#include <QLabel>
#include <QVBoxLayout>
#include <kapplication.h>
#include <kcursor.h>
#include <kiconloader.h>
#include <klocale.h>
#include <knuminput.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kvbox.h>
#include "profiling.h"
IngredientMatcherDialog::IngredientMatcherDialog( QWidget *parent, RecipeDB *db ) : QWidget( parent )
{
// Initialize internal variables
database = db;
//Design the dialog
QVBoxLayout *dialogLayout = new QVBoxLayout( this );
dialogLayout->setMargin( 11 );
dialogLayout->setSpacing( 6 );
// Ingredient list
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->setObjectName( "layout2" );
layout2->setMargin( 0 );
layout2->setSpacing( 6 );
allIngListView = new KreListView( this, QString::null, true, 0 );
StdIngredientListView *list_view = new StdIngredientListView(allIngListView,database);
list_view->setSelectionMode( Q3ListView::Multi );
allIngListView->setListView(list_view);
layout2->addWidget( allIngListView );
QVBoxLayout *layout1 = new QVBoxLayout();
layout1->setMargin( 0 );
layout1->setSpacing( 6 );
layout1->setObjectName( "layout1" );
KIconLoader *il = KIconLoader::global();
addButton = new KPushButton( this );
addButton->setObjectName( "addButton" );
il->loadIcon( "go-next", KIconLoader::Small );
addButton->setIcon( KIcon( "go-next", il ) );
addButton->setFixedSize( QSize( 32, 32 ) );
layout1->addWidget( addButton );
removeButton = new KPushButton( this );
removeButton->setObjectName( "removeButton" );
il->loadIcon( "go-previous", KIconLoader::Small );
removeButton->setIcon( KIcon( "go-previous", il ) );
removeButton->setFixedSize( QSize( 32, 32 ) );
layout1->addWidget( removeButton );
QSpacerItem *spacer1 = new QSpacerItem( 51, 191, QSizePolicy::Minimum, QSizePolicy::Expanding );
layout1->addItem( spacer1 );
layout2->addLayout( layout1 );
ingListView = new KreListView( this, QString::null, true );
ingListView->listView() ->addColumn( i18n( "Ingredient (required?)" ) );
ingListView->listView() ->addColumn( i18n( "Amount Available" ) );
layout2->addWidget( ingListView );
dialogLayout->addLayout( layout2 );
// Box to select allowed number of missing ingredients
missingBox = new KHBox( this );
missingNumberLabel = new QLabel( missingBox );
missingNumberLabel->setText( i18n( "Missing ingredients allowed:" ) );
missingNumberSpinBox = new KIntSpinBox( missingBox );
missingNumberSpinBox->setMinimum( -1 );
missingNumberSpinBox->setSpecialValueText( i18n( "Any" ) );
dialogLayout->addWidget(missingBox);
// Found recipe list
recipeListView = new KreListView( this, i18n( "Matching Recipes" ), false, 1, missingBox );
recipeListView->listView() ->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
recipeListView->listView() ->setAllColumnsShowFocus( true );
recipeListView->listView() ->addColumn( i18n( "Title" ) );
KConfigGroup config( KGlobal::config(), "Advanced" );
bool show_id = config.readEntry( "ShowID", false );
recipeListView->listView() ->addColumn( i18n( "Id" ), show_id ? -1 : 0 );
recipeListView->listView() ->addColumn( i18n( "Missing Ingredients" ) );
recipeListView->listView() ->setSorting( -1 );
dialogLayout->addWidget(recipeListView);
RecipeActionsHandler *actionHandler = new RecipeActionsHandler( recipeListView->listView(), database, RecipeActionsHandler::Open | RecipeActionsHandler::Edit | RecipeActionsHandler::Export );
KHBox *buttonBox = new KHBox( this );
okButton = new KPushButton( buttonBox );
il->loadIcon( "dialog-ok", KIconLoader::Small );
okButton->setIcon( KIcon( "dialog-ok", il ) );
okButton->setText( i18n( "Find matching recipes" ) );
//buttonBox->layout()->addItem( new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) );
clearButton = new KPushButton( buttonBox );
il->loadIcon( "edit-clear", KIconLoader::Small );
clearButton->setIcon( KIcon( "edit-clear", il ) );
clearButton->setText( i18n( "Clear" ) );
dialogLayout->addWidget(buttonBox);
// Connect signals & slots
connect ( okButton, SIGNAL( clicked() ), this, SLOT( findRecipes() ) );
connect ( clearButton, SIGNAL( clicked() ), recipeListView->listView(), SLOT( clear() ) );
connect ( clearButton, SIGNAL( clicked() ), this, SLOT( unselectIngredients() ) );
connect ( actionHandler, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
connect( addButton, SIGNAL( clicked() ), this, SLOT( addIngredient() ) );
connect( removeButton, SIGNAL( clicked() ), this, SLOT( removeIngredient() ) );
connect( ingListView->listView(), SIGNAL( doubleClicked( Q3ListViewItem*, const QPoint &, int ) ), SLOT( itemRenamed( Q3ListViewItem*, const QPoint &, int ) ) );
}
IngredientMatcherDialog::~IngredientMatcherDialog()
{
}
void IngredientMatcherDialog::itemRenamed( Q3ListViewItem* item, const QPoint &, int col )
{
if ( col == 1 ) {
KDialog amountEditDialog(this);
amountEditDialog.setCaption(i18n("Enter amount"));
amountEditDialog.setButtons(KDialog::Cancel | KDialog::Ok);
amountEditDialog.setDefaultButton(KDialog::Ok);
amountEditDialog.setModal( false );
Q3GroupBox *box = new Q3GroupBox( 1, Qt::Horizontal, i18n("Amount"), &amountEditDialog );
AmountUnitInput *amountEdit = new AmountUnitInput( box, database );
// Set the values from the item
if ( !item->text(1).isEmpty() ) {
amountEdit->setAmount( MixedNumber::fromString(item->text(2)) );
Unit u;
u.id = item->text(3).toInt();
amountEdit->setUnit( u );
} else {
amountEdit->setAmount( -1 );
Unit u;
u.id = -1;
amountEdit->setUnit( u );
}
amountEditDialog.setMainWidget(box);
if ( amountEditDialog.exec() == QDialog::Accepted ) {
MixedNumber amount = amountEdit->amount();
Unit unit = amountEdit->unit();
if ( amount.toDouble() <= 1e-5 ) {
amount = -1;
unit.id = -1;
item->setText(1,QString::null);
} else {
item->setText(1,amount.toString()+" "+((amount.toDouble()>1)?unit.plural:unit.name));
}
item->setText(2,amount.toString());
item->setText(3,QString::number(unit.id));
IngredientList::iterator ing_it = m_item_ing_map[item];
(*ing_it).amount = amount.toDouble();
(*ing_it).units = unit;
}
}
}
void IngredientMatcherDialog::addIngredient()
{
/*
QList<Q3ListViewItem> items = allIngListView->listView()->selectedItems();
if ( !items.isEmpty() ) {
for (int i = 0; i < items.size(); ++i) {
bool dup = false;
for ( Q3ListViewItem *exists_it = ingListView->listView()->firstChild(); exists_it; exists_it = exists_it->nextSibling() ) {
if ( exists_it->text( 0 ) == item->text( 0 ) ) {
dup = true;
break;
}
}
if ( !dup ) {
Q3ListViewItem * new_item = new Q3CheckListItem( ingListView->listView(), item->text( 0 ), Q3CheckListItem::CheckBox );
ingListView->listView() ->setSelected( new_item, true );
ingListView->listView() ->ensureItemVisible( new_item );
allIngListView->listView() ->setSelected( item, false );
m_item_ing_map.insert( new_item, m_ingredientList.append( Ingredient( item->text( 0 ), 0, Unit(), -1, item->text( 1 ).toInt() ) ) );
}
++it;
}
}
*/
}
void IngredientMatcherDialog::removeIngredient()
{
/*
Q3ListViewItem * item = ingListView->listView() ->selectedItem();
if ( item ) {
for ( IngredientList::iterator it = m_ingredientList.begin(); it != m_ingredientList.end(); ++it ) {
if ( *m_item_ing_map.find( item ) == it ) {
m_ingredientList.remove( it );
m_item_ing_map.remove( item );
break;
}
}
delete item;
}
*/
}
void IngredientMatcherDialog::unselectIngredients()
{
ingListView->listView()->clear();
for ( Q3ListViewItem *it = allIngListView->listView()->firstChild(); it; it = it->nextSibling() )
allIngListView->listView()->setSelected(it,false);
}
void IngredientMatcherDialog::findRecipes( void )
{
KApplication::setOverrideCursor( Qt::WaitCursor );
START_TIMER("Ingredient Matcher: loading database data");
RecipeList rlist;
database->loadRecipes( &rlist, RecipeDB::Title | RecipeDB::NamesOnly | RecipeDB::Ingredients | RecipeDB::IngredientAmounts );
END_TIMER();
START_TIMER("Ingredient Matcher: analyzing data for matching recipes");
// Clear the list
recipeListView->listView() ->clear();
// Now show the recipes with ingredients that are contained in the previous set
// of ingredients
RecipeList incompleteRecipes;
QList <int> missingNumbers;
Q3ValueList <IngredientList> missingIngredients;
RecipeList::Iterator it;
for ( it = rlist.begin();it != rlist.end();++it ) {
IngredientList il = ( *it ).ingList;
if ( il.isEmpty() )
continue;
IngredientList missing;
if ( m_ingredientList.containsSubSet( il, missing, true, database ) ) {
new CustomRecipeListItem( recipeListView->listView(), *it );
}
else {
incompleteRecipes.append( *it );
missingIngredients.append( missing );
missingNumbers.append( missing.count() );
}
}
END_TIMER();
//Check if the user wants to show missing ingredients
if ( missingNumberSpinBox->value() == 0 ) {
KApplication::restoreOverrideCursor();
return ;
} //"None"
START_TIMER("Ingredient Matcher: searching for and displaying partial matches");
IngredientList requiredIngredients;
for ( Q3ListViewItem *it = ingListView->listView()->firstChild(); it; it = it->nextSibling() ) {
if ( ((Q3CheckListItem*)it)->isOn() )
requiredIngredients << *m_item_ing_map[it];
}
// Classify recipes with missing ingredients in different lists by ammount
QList<int>::Iterator nit;
Q3ValueList<IngredientList>::Iterator ilit;
int missingNoAllowed = missingNumberSpinBox->value();
if ( missingNoAllowed == -1 ) // "Any"
{
for ( nit = missingNumbers.begin();nit != missingNumbers.end();++nit )
if ( ( *nit ) > missingNoAllowed )
missingNoAllowed = ( *nit );
}
for ( int missingNo = 1; missingNo <= missingNoAllowed; missingNo++ ) {
nit = missingNumbers.begin();
ilit = missingIngredients.begin();
bool titleShownYet = false;
for ( it = incompleteRecipes.begin();it != incompleteRecipes.end();++it, ++nit, ++ilit ) {
if ( !( *it ).ingList.containsAny( m_ingredientList ) )
continue;
if ( !( *it ).ingList.containsSubSet( requiredIngredients ) )
continue;
if ( ( *nit ) == missingNo ) {
if ( !titleShownYet ) {
new SectionItem( recipeListView->listView(), i18np( "You are missing 1 ingredient for:", "You are missing %1 ingredients for:", missingNo ) );
titleShownYet = true;
}
new CustomRecipeListItem( recipeListView->listView(), *it, *ilit );
}
}
}
END_TIMER();
KApplication::restoreOverrideCursor();
}
void IngredientMatcherDialog::reload( ReloadFlags flag )
{
( ( StdIngredientListView* ) allIngListView->listView() ) ->reload(flag);
}
void SectionItem::paintCell ( QPainter * p, const QColorGroup & /*cg*/, int column, int width, int /*align*/ )
{
// Draw the section's deco
p->setPen( KGlobalSettings::activeTitleColor() );
p->setBrush( KGlobalSettings::activeTitleColor() );
p->drawRect( 0, 0, width, height() );
// Draw the section's text
if ( column == 0 ) {
QFont titleFont = KGlobalSettings::windowTitleFont ();
p->setFont( titleFont );
p->setPen( KGlobalSettings::activeTextColor() );
p->drawText( 0, 0, width, height(), Qt::AlignLeft | Qt::AlignVCenter, mText );
}
}
#include "ingredientmatcherdialog.moc"
<|endoftext|> |
<commit_before># include "particle-functions.h"
# include <application.h>
extern WeatherData weather;
void WeatherData :: message(int data) // defined outside class definition
{
Serial.print("Timestamp: "); Serial.println(_weatherTime);
Serial.print("Temp (F): "); Serial.println(_greenhouseTemp);
Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity);
}
void WeatherData :: weatherData()
{
_weatherTime = 0;
_greenhouseTemp = 0;
_greenhouseHumidity = 0;
_backupGreenhouseTemp = 0;
_backupGreenhouseHumidity = 0;
_outsideTemp = 0;
_outsideHumidity = 0;
_solar = 0;
_high = 0;
_low = 0;
}
void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,
int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp,
int outsideHumidity, int solar, int high, int low)
{
_weatherTime = weatherTime;
_greenhouseTemp = greenhouseTemp;
_greenhouseHumidity = greenhouseHumidity;
_backupGreenhouseTemp = backupGreenhouseTemp;
_backupGreenhouseHumidity = backupGreenhouseHumidity;
_outsideTemp = outsideTemp;
_outsideHumidity = outsideHumidity;
_solar = solar;
_high = high;
_low = low;
}
void WeatherData :: init()
{
Spark.function("ghData", greenhouseData);
}
int greenhouseData(String data)
{
//Expected parameters in CSV format
// 1. Unix time stamp
// 2. current greenhouse temperature
// 3. current greenhouse humidity
// 4. backup sensor current greenhouse temperature
// 5. backup sensor current greenhouse humidity
// 6. current outside temperature
// 7. current outside humidity
// 8. solar radiation
// 9. forecast high
// 10. forecast low
char copyStr[64];
data.toCharArray(copyStr,64);
char *p = strtok(copyStr, ",");
unsigned int weatherTime = atoi(p);
p = strtok(NULL,",");
int greenhouseTemp = atoi(p);
p = strtok(NULL,",");
int greenhouseHumidity = atoi(p);
p = strtok(NULL,",");
int backupGreenhouseTemp = atoi(p);
p = strtok(NULL,",");
int backupGreenhouseHumidity = atoi(p);
p = strtok(NULL,",");
int outsideTemp = atoi(p);
p = strtok(NULL,",");
int outsideHumidity = atoi(p);
p = strtok(NULL,",");
int solar = atoi(p);
p = strtok(NULL,",");
int high = atoi(p);
p = strtok(NULL,",");
int low = atoi(p);
weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp,
backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low);
return 1;
}
<commit_msg>Update particle-functions.cpp<commit_after># include "particle-functions.h"
# include <application.h>
extern WeatherData weather;
void WeatherData :: message(int data) // defined outside class definition
{
Serial.print("Timestamp: "); Serial.println(_weatherTime);
Serial.print("Temp (F): "); Serial.println(_greenhouseTemp);
Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity);
}
void WeatherData :: weatherData()
{
_weatherTime = 0;
_greenhouseTemp = 0;
_greenhouseHumidity = 0;
_backupGreenhouseTemp = 0;
_backupGreenhouseHumidity = 0;
_outsideTemp = 0;
_outsideHumidity = 0;
_solar = 0;
_high = 0;
_low = 0;
}
void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,
int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp,
int outsideHumidity, int solar, int high, int low)
{
_weatherTime = weatherTime;
_greenhouseTemp = greenhouseTemp;
_greenhouseHumidity = greenhouseHumidity;
_backupGreenhouseTemp = backupGreenhouseTemp;
_backupGreenhouseHumidity = backupGreenhouseHumidity;
_outsideTemp = outsideTemp;
_outsideHumidity = outsideHumidity;
_solar = solar;
_high = high;
_low = low;
}
int greenhouseData(String data)
{
//Expected parameters in CSV format
// 1. Unix time stamp
// 2. current greenhouse temperature
// 3. current greenhouse humidity
// 4. backup sensor current greenhouse temperature
// 5. backup sensor current greenhouse humidity
// 6. current outside temperature
// 7. current outside humidity
// 8. solar radiation
// 9. forecast high
// 10. forecast low
char copyStr[64];
data.toCharArray(copyStr,64);
char *p = strtok(copyStr, ",");
unsigned int weatherTime = atoi(p);
p = strtok(NULL,",");
int greenhouseTemp = atoi(p);
p = strtok(NULL,",");
int greenhouseHumidity = atoi(p);
p = strtok(NULL,",");
int backupGreenhouseTemp = atoi(p);
p = strtok(NULL,",");
int backupGreenhouseHumidity = atoi(p);
p = strtok(NULL,",");
int outsideTemp = atoi(p);
p = strtok(NULL,",");
int outsideHumidity = atoi(p);
p = strtok(NULL,",");
int solar = atoi(p);
p = strtok(NULL,",");
int high = atoi(p);
p = strtok(NULL,",");
int low = atoi(p);
weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp,
backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low);
return 1;
}
void particleInit()
{
// time function setup
Time.zone(tzOffset);
Alarm.alarmRepeat(AMsetback,0,0, MorningAlarm);
Alarm.alarmRepeat(PMsetback,0,0, EveningAlarm);
// setup particle functions
Spark.function("ghData", greenhouseData);
Spark.function("test_call",call_function);
Spark.function("setSeason", setSeason);
}
<|endoftext|> |
<commit_before>/*
may need to code against htslib rather than samtools.
For each read in the BAM file:
calculate the 5' ends of the fragment:
if last 5' end seen is less than the current 5' end:
flush buffers, gathering stats on duplicates
if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out
create signature and add to buffer
on buffer flush:
for each signatures:
skip if count is 1
add number of reads in signature to histogram of duplicate fragments
sort into bins by tile
for each tile, create distance matrix
increment counts in distance histogram
clear out signatures hash
for each read we need:
read name
chromosome
position
a populated mate cigar tag (MC:Z:)
tlen
we need a method to parse out readnames
we need a method to determine how far apart two readnames are
we need a method to generate a signature
we need a method to expand the cigar strings for the signature
we need a histogram template
we need a small amount of test data
diagnose_dups -i bam_file -o dup_stats
*/
#include "common/Options.hpp"
#include "diagnose_dups/Read.hpp"
#include "diagnose_dups/Signature.hpp"
#include "diagnose_dups/SignatureBundle.hpp"
#include "io/BamRecord.hpp"
#include "io/SamReader.hpp"
#include <sam.h>
#include <boost/unordered_map.hpp>
#include <iostream>
#include <numeric>
using namespace std;
namespace {
typedef boost::unordered_map<uint64_t, uint64_t> histogram;
typedef vector<Read> read_vector;
typedef boost::unordered_map<Signature, read_vector> signature_map;
struct BundleProcessor {
histogram dup_insert_sizes;
histogram nondup_insert_sizes;
histogram distances;
histogram number_of_dups;
void process(SignatureBundle const& bundle) {
std::vector<SigRead> const& sigreads = bundle.data();
signature_map sigmap;
for (std::size_t i = 0; i < sigreads.size(); ++i) {
sigmap[sigreads[i].sig].push_back(sigreads[i].read);
}
for(signature_map::const_iterator i = sigmap.begin(); i != sigmap.end(); ++i) {
if (i->second.size() > 1) {
++number_of_dups[i->second.size()];
typedef vector<Read>::const_iterator read_vec_iter;
for(read_vec_iter cri = i->second.begin(); cri != i->second.end() - 1; ++cri) {
++dup_insert_sizes[abs(cri->insert_size)];
nondup_insert_sizes[abs(cri->insert_size)] += 0;
for(read_vec_iter dci = cri + 1; dci != i->second.end(); ++dci) {
if(is_on_same_tile(*cri, *dci)) {
uint64_t flow_cell_distance = euclidean_distance(*cri, *dci);
distances[flow_cell_distance] += 1;
}
}
}
}
}
}
};
}
int main(int argc, char** argv) {
Options opts = Options(argc, argv);
SamReader reader(opts.vm["input"].as<string>().c_str(), "r");
reader.required_flags(BAM_FPROPER_PAIR);
reader.skip_flags(BAM_FSECONDARY | BAM_FQCFAIL | BAM_FREAD2 | BAM_FSUPPLEMENTARY);
BamRecord record;
SignatureBundle bundle;
std::vector<std::size_t> sig_sizes;
std::size_t n_bundles;
std::size_t bundle_size_sum;
BundleProcessor proc;
while(reader.next(record)) {
int rv = bundle.add(record);
if (rv == -1) {
std::cerr << "Failed to parse bam record, name = " << bam_get_qname(record) << "\n";
// XXX: would you rather abort?
continue;
}
else if (rv == 0) {
bundle_size_sum += bundle.size();
++n_bundles;
proc.process(bundle);
bundle.clear();
}
}
proc.process(bundle);
bundle_size_sum += bundle.size();
++n_bundles;
cout << "Inter-tile distance\tFrequency\n";
for(histogram::iterator i = proc.distances.begin(); i != proc.distances.end(); ++i) {
cout << i->first << "\t" << i->second << "\n";
}
cout << "\n";
cout << "Number of dups at location\tFrequency\n";
for(histogram::iterator i = proc.number_of_dups.begin(); i != proc.number_of_dups.end(); ++i) {
cout << i->first << "\t" << i->second << "\n";
}
cout << "\n";
cout << "Size\tUniq frequency\tDup Frequency\n";
for(histogram::iterator i = proc.nondup_insert_sizes.begin(); i != proc.nondup_insert_sizes.end(); ++i) {
cout << i->first << "\t" << i->second << "\t" << proc.dup_insert_sizes[i->first] << "\n";
}
double mu = bundle_size_sum / double(n_bundles);
std::cerr << n_bundles << " bundles.\n";
std::cerr << "avg bundle size: " << mu << "\n";
return 0;
}
<commit_msg>fix uninitialized vars<commit_after>/*
may need to code against htslib rather than samtools.
For each read in the BAM file:
calculate the 5' ends of the fragment:
if last 5' end seen is less than the current 5' end:
flush buffers, gathering stats on duplicates
if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out
create signature and add to buffer
on buffer flush:
for each signatures:
skip if count is 1
add number of reads in signature to histogram of duplicate fragments
sort into bins by tile
for each tile, create distance matrix
increment counts in distance histogram
clear out signatures hash
for each read we need:
read name
chromosome
position
a populated mate cigar tag (MC:Z:)
tlen
we need a method to parse out readnames
we need a method to determine how far apart two readnames are
we need a method to generate a signature
we need a method to expand the cigar strings for the signature
we need a histogram template
we need a small amount of test data
diagnose_dups -i bam_file -o dup_stats
*/
#include "common/Options.hpp"
#include "diagnose_dups/Read.hpp"
#include "diagnose_dups/Signature.hpp"
#include "diagnose_dups/SignatureBundle.hpp"
#include "io/BamRecord.hpp"
#include "io/SamReader.hpp"
#include <sam.h>
#include <boost/unordered_map.hpp>
#include <iostream>
#include <numeric>
using namespace std;
namespace {
typedef boost::unordered_map<uint64_t, uint64_t> histogram;
typedef vector<Read> read_vector;
typedef boost::unordered_map<Signature, read_vector> signature_map;
struct BundleProcessor {
histogram dup_insert_sizes;
histogram nondup_insert_sizes;
histogram distances;
histogram number_of_dups;
void process(SignatureBundle const& bundle) {
std::vector<SigRead> const& sigreads = bundle.data();
signature_map sigmap;
for (std::size_t i = 0; i < sigreads.size(); ++i) {
sigmap[sigreads[i].sig].push_back(sigreads[i].read);
}
for(signature_map::const_iterator i = sigmap.begin(); i != sigmap.end(); ++i) {
if (i->second.size() > 1) {
++number_of_dups[i->second.size()];
typedef vector<Read>::const_iterator read_vec_iter;
for(read_vec_iter cri = i->second.begin(); cri != i->second.end() - 1; ++cri) {
++dup_insert_sizes[abs(cri->insert_size)];
nondup_insert_sizes[abs(cri->insert_size)] += 0;
for(read_vec_iter dci = cri + 1; dci != i->second.end(); ++dci) {
if(is_on_same_tile(*cri, *dci)) {
uint64_t flow_cell_distance = euclidean_distance(*cri, *dci);
distances[flow_cell_distance] += 1;
}
}
}
}
}
}
};
}
int main(int argc, char** argv) {
Options opts = Options(argc, argv);
SamReader reader(opts.vm["input"].as<string>().c_str(), "r");
reader.required_flags(BAM_FPROPER_PAIR);
reader.skip_flags(BAM_FSECONDARY | BAM_FQCFAIL | BAM_FREAD2 | BAM_FSUPPLEMENTARY);
BamRecord record;
SignatureBundle bundle;
std::vector<std::size_t> sig_sizes;
std::size_t n_bundles = 0;
std::size_t bundle_size_sum = 0;
BundleProcessor proc;
while(reader.next(record)) {
int rv = bundle.add(record);
if (rv == -1) {
std::cerr << "Failed to parse bam record, name = " << bam_get_qname(record) << "\n";
// XXX: would you rather abort?
continue;
}
else if (rv == 0) {
bundle_size_sum += bundle.size();
++n_bundles;
proc.process(bundle);
bundle.clear();
}
}
proc.process(bundle);
bundle_size_sum += bundle.size();
++n_bundles;
cout << "Inter-tile distance\tFrequency\n";
for(histogram::iterator i = proc.distances.begin(); i != proc.distances.end(); ++i) {
cout << i->first << "\t" << i->second << "\n";
}
cout << "\n";
cout << "Number of dups at location\tFrequency\n";
for(histogram::iterator i = proc.number_of_dups.begin(); i != proc.number_of_dups.end(); ++i) {
cout << i->first << "\t" << i->second << "\n";
}
cout << "\n";
cout << "Size\tUniq frequency\tDup Frequency\n";
for(histogram::iterator i = proc.nondup_insert_sizes.begin(); i != proc.nondup_insert_sizes.end(); ++i) {
cout << i->first << "\t" << i->second << "\t" << proc.dup_insert_sizes[i->first] << "\n";
}
double mu = bundle_size_sum / double(n_bundles);
std::cerr << n_bundles << " bundles.\n";
std::cerr << "avg bundle size: " << mu << "\n";
return 0;
}
<|endoftext|> |
<commit_before>/*
* cam_QHY5IIbase.cpp
* PHD Guiding
*
* Created by Craig Stark.
* Copyright (c) 2012 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#if defined(QHY5II) || defined(QHY5LII)
#include "cam_QHY5II.h"
static bool s_qhySdkInitDone = false;
static bool QHYSDKInit()
{
if (s_qhySdkInitDone)
return false;
int ret;
#if defined (__APPLE__)
wxFileName exeFile(wxStandardPaths::Get().GetExecutablePath());
wxString exePath(exeFile.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(exePath);
const char *temp = (const char *)tmp_buf;
size_t const len = strlen(temp) + 1;
char *destImgPath = new char[len];
memcpy(destImgPath, temp, len);
if ((ret = OSXInitQHYCCDFirmware(destImgPath)) != 0)
{
Debug.Write(wxString::Format("OSXInitQHYCCDFirmware(%s) failed: %d\n", destImgPath, ret));
delete[] destImgPath;
return true;
}
delete[] destImgPath;
#endif
if ((ret = InitQHYCCDResource()) != 0)
{
Debug.Write(wxString::Format("InitQHYCCDResource failed: %d\n", ret));
return true;
}
s_qhySdkInitDone = true;
return false;
}
static void QHYSDKUninit()
{
if (s_qhySdkInitDone)
{
ReleaseQHYCCDResource();
s_qhySdkInitDone = false;
}
}
Camera_QHY5IIBase::Camera_QHY5IIBase()
{
Connected = false;
m_hasGuideOutput = true;
HasGainControl = true;
RawBuffer = 0;
Color = false;
#if 0 // Subframes do not work yet; lzr from QHY is investigating - ag 6/24/2015
HasSubframes = true;
#endif
m_camhandle = 0;
}
Camera_QHY5IIBase::~Camera_QHY5IIBase()
{
delete[] RawBuffer;
QHYSDKUninit();
}
bool Camera_QHY5IIBase::Connect()
{
if (QHYSDKInit())
{
wxMessageBox(_("Failed to initialize QHY SDK"));
return true;
}
int num_cams = ScanQHYCCD();
if (num_cams <= 0)
{
wxMessageBox(_("No QHY cameras found"));
return true;
}
for (int i = 0; i < num_cams; i++)
{
char camid[32];
GetQHYCCDId(i, camid);
if (camid[0] == 'Q' && camid[3] == '5' && camid[5] == 'I')
{
m_camhandle = OpenQHYCCD(camid);
break;
}
}
if (!m_camhandle)
{
wxMessageBox(_("Failed to connect to camera"));
return true;
}
int ret = GetQHYCCDParamMinMaxStep(m_camhandle, CONTROL_GAIN, &m_gainMin, &m_gainMax, &m_gainStep);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Failed to get gain range"));
return true;
}
double chipw, chiph, pixelw, pixelh;
int imagew, imageh, bpp;
ret = GetQHYCCDChipInfo(m_camhandle, &chipw, &chiph, &imagew, &imageh, &pixelw, &pixelh, &bpp);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Failed to connect to camera"));
return true;
}
ret = SetQHYCCDBinMode(m_camhandle, 1, 1);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Failed to set camera binning"));
return true;
}
FullSize = wxSize(imagew, imageh);
delete[] RawBuffer;
size_t size = imagew * imageh;
RawBuffer = new unsigned char[size];
PixelSize = sqrt(pixelw * pixelh);
ret = InitQHYCCD(m_camhandle);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Init camera failed"));
return true;
}
ret = SetQHYCCDResolution(m_camhandle, 0, 0, imagew, imageh);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Init camera failed"));
return true;
}
m_curGain = -1;
m_curExposure = -1;
m_roi = wxRect(0, 0, imagew, imageh);
Connected = true;
return false;
}
bool Camera_QHY5IIBase::Disconnect()
{
StopQHYCCDLive(m_camhandle);
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
Connected = false;
delete[] RawBuffer;
RawBuffer = 0;
return false;
}
bool Camera_QHY5IIBase::ST4PulseGuideScope(int direction, int duration)
{
int qdir;
switch (direction)
{
case NORTH: qdir = 1; break;
case SOUTH: qdir = 2; break;
case EAST: qdir = 0; break;
case WEST: qdir = 3; break;
default: return true; // bad direction passed in
}
ControlQHYCCDGuide(m_camhandle, qdir, duration);
WorkerThread::MilliSleep(duration + 10);
return false;
}
static bool StopExposure()
{
Debug.AddLine("QHY5: cancel exposure");
// todo
return true;
}
bool Camera_QHY5IIBase::Capture(int duration, usImage& img, int options, const wxRect& subframe)
{
if (img.Init(FullSize))
{
DisconnectWithAlert(CAPT_FAIL_MEMORY);
return true;
}
bool useSubframe = !subframe.IsEmpty();
wxRect frame = useSubframe ? subframe : wxRect(FullSize);
if (useSubframe)
img.Clear();
int ret;
// lzr from QHY says this needs to be set for every exposure
ret = SetQHYCCDBinMode(m_camhandle, 1, 1);
if (ret != QHYCCD_SUCCESS)
{
Debug.Write(wxString::Format("SetQHYCCDBinMode failed! ret = %d\n", ret));
}
if (m_roi != frame)
{
ret = SetQHYCCDResolution(m_camhandle, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight());
if (ret == QHYCCD_SUCCESS)
{
m_roi = frame;
}
else
{
Debug.Write(wxString::Format("SetQHYCCDResolution failed! ret = %d\n", ret));
}
}
if (GuideCameraGain != m_curGain)
{
double gain = m_gainMin + GuideCameraGain * (m_gainMax - m_gainMin) / 100.0;
gain = floor(gain / m_gainStep) * m_gainStep;
Debug.Write(wxString::Format("QHY set gain %g (%g..%g incr %g)\n", gain, m_gainMin, m_gainMax, m_gainStep));
ret = SetQHYCCDParam(m_camhandle, CONTROL_GAIN, gain);
if (ret == QHYCCD_SUCCESS)
{
m_curGain = GuideCameraGain;
}
else
{
Debug.Write(wxString::Format("QHY set gain ret %d\n", ret));
pFrame->Alert(_("Failed to set camera gain"));
}
}
if (duration != m_curExposure)
{
ret = SetQHYCCDParam(m_camhandle, CONTROL_EXPOSURE, duration * 1000.0); // QHY duration is usec
if (ret == QHYCCD_SUCCESS)
{
m_curExposure = duration;
}
else
{
Debug.Write(wxString::Format("QHY set exposure ret %d\n", ret));
pFrame->Alert(_("Failed to set camera exposure"));
}
}
ret = ExpQHYCCDSingleFrame(m_camhandle);
if (ret != QHYCCD_SUCCESS)
{
Debug.Write(wxString::Format("QHY exp single frame ret %d\n", ret));
DisconnectWithAlert(_("QHY exposure failed"));
return true;
}
int w, h, bpp, channels;
ret = GetQHYCCDSingleFrame(m_camhandle, &w, &h, &bpp, &channels, RawBuffer);
if (ret != QHYCCD_SUCCESS)
{
Debug.Write(wxString::Format("QHY get single frame ret %d\n", ret));
DisconnectWithAlert(_("QHY get frame failed"));
return true;
}
if (useSubframe)
{
const unsigned char *src = RawBuffer;
unsigned short *dst = img.ImageData + frame.GetTop() * FullSize.GetWidth() + frame.GetLeft();
for (int y = 0; y < frame.GetHeight(); y++)
{
unsigned short *d = dst;
for (int x = 0; x < frame.GetWidth(); x++)
*d++ = (unsigned short) *src++;
dst += FullSize.GetWidth();
}
}
else
{
const unsigned char *src = RawBuffer;
unsigned short *dst = img.ImageData;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
*dst++ = (unsigned short) *src++;
}
}
}
img.ImageData[200 * FullSize.GetWidth() + 400 + 0] = 22000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 1] = 32000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 2] = 35000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 3] = 35000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 4] = 32000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 5] = 22000;
if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img);
if (Color && (options & CAPTURE_RECON)) QuickLRecon(img);
return false;
}
#endif
<commit_msg>disable subframe debug code<commit_after>/*
* cam_QHY5IIbase.cpp
* PHD Guiding
*
* Created by Craig Stark.
* Copyright (c) 2012 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#if defined(QHY5II) || defined(QHY5LII)
#include "cam_QHY5II.h"
static bool s_qhySdkInitDone = false;
static bool QHYSDKInit()
{
if (s_qhySdkInitDone)
return false;
int ret;
#if defined (__APPLE__)
wxFileName exeFile(wxStandardPaths::Get().GetExecutablePath());
wxString exePath(exeFile.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(exePath);
const char *temp = (const char *)tmp_buf;
size_t const len = strlen(temp) + 1;
char *destImgPath = new char[len];
memcpy(destImgPath, temp, len);
if ((ret = OSXInitQHYCCDFirmware(destImgPath)) != 0)
{
Debug.Write(wxString::Format("OSXInitQHYCCDFirmware(%s) failed: %d\n", destImgPath, ret));
delete[] destImgPath;
return true;
}
delete[] destImgPath;
#endif
if ((ret = InitQHYCCDResource()) != 0)
{
Debug.Write(wxString::Format("InitQHYCCDResource failed: %d\n", ret));
return true;
}
s_qhySdkInitDone = true;
return false;
}
static void QHYSDKUninit()
{
if (s_qhySdkInitDone)
{
ReleaseQHYCCDResource();
s_qhySdkInitDone = false;
}
}
Camera_QHY5IIBase::Camera_QHY5IIBase()
{
Connected = false;
m_hasGuideOutput = true;
HasGainControl = true;
RawBuffer = 0;
Color = false;
#if 0 // Subframes do not work yet; lzr from QHY is investigating - ag 6/24/2015
HasSubframes = true;
#endif
m_camhandle = 0;
}
Camera_QHY5IIBase::~Camera_QHY5IIBase()
{
delete[] RawBuffer;
QHYSDKUninit();
}
bool Camera_QHY5IIBase::Connect()
{
if (QHYSDKInit())
{
wxMessageBox(_("Failed to initialize QHY SDK"));
return true;
}
int num_cams = ScanQHYCCD();
if (num_cams <= 0)
{
wxMessageBox(_("No QHY cameras found"));
return true;
}
for (int i = 0; i < num_cams; i++)
{
char camid[32];
GetQHYCCDId(i, camid);
if (camid[0] == 'Q' && camid[3] == '5' && camid[5] == 'I')
{
m_camhandle = OpenQHYCCD(camid);
break;
}
}
if (!m_camhandle)
{
wxMessageBox(_("Failed to connect to camera"));
return true;
}
int ret = GetQHYCCDParamMinMaxStep(m_camhandle, CONTROL_GAIN, &m_gainMin, &m_gainMax, &m_gainStep);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Failed to get gain range"));
return true;
}
double chipw, chiph, pixelw, pixelh;
int imagew, imageh, bpp;
ret = GetQHYCCDChipInfo(m_camhandle, &chipw, &chiph, &imagew, &imageh, &pixelw, &pixelh, &bpp);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Failed to connect to camera"));
return true;
}
ret = SetQHYCCDBinMode(m_camhandle, 1, 1);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Failed to set camera binning"));
return true;
}
FullSize = wxSize(imagew, imageh);
delete[] RawBuffer;
size_t size = imagew * imageh;
RawBuffer = new unsigned char[size];
PixelSize = sqrt(pixelw * pixelh);
ret = InitQHYCCD(m_camhandle);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Init camera failed"));
return true;
}
ret = SetQHYCCDResolution(m_camhandle, 0, 0, imagew, imageh);
if (ret != QHYCCD_SUCCESS)
{
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
wxMessageBox(_("Init camera failed"));
return true;
}
m_curGain = -1;
m_curExposure = -1;
m_roi = wxRect(0, 0, imagew, imageh);
Connected = true;
return false;
}
bool Camera_QHY5IIBase::Disconnect()
{
StopQHYCCDLive(m_camhandle);
CloseQHYCCD(m_camhandle);
m_camhandle = 0;
Connected = false;
delete[] RawBuffer;
RawBuffer = 0;
return false;
}
bool Camera_QHY5IIBase::ST4PulseGuideScope(int direction, int duration)
{
int qdir;
switch (direction)
{
case NORTH: qdir = 1; break;
case SOUTH: qdir = 2; break;
case EAST: qdir = 0; break;
case WEST: qdir = 3; break;
default: return true; // bad direction passed in
}
ControlQHYCCDGuide(m_camhandle, qdir, duration);
WorkerThread::MilliSleep(duration + 10);
return false;
}
static bool StopExposure()
{
Debug.AddLine("QHY5: cancel exposure");
// todo
return true;
}
bool Camera_QHY5IIBase::Capture(int duration, usImage& img, int options, const wxRect& subframe)
{
if (img.Init(FullSize))
{
DisconnectWithAlert(CAPT_FAIL_MEMORY);
return true;
}
bool useSubframe = !subframe.IsEmpty();
wxRect frame = useSubframe ? subframe : wxRect(FullSize);
if (useSubframe)
img.Clear();
int ret;
// lzr from QHY says this needs to be set for every exposure
ret = SetQHYCCDBinMode(m_camhandle, 1, 1);
if (ret != QHYCCD_SUCCESS)
{
Debug.Write(wxString::Format("SetQHYCCDBinMode failed! ret = %d\n", ret));
}
if (m_roi != frame)
{
ret = SetQHYCCDResolution(m_camhandle, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight());
if (ret == QHYCCD_SUCCESS)
{
m_roi = frame;
}
else
{
Debug.Write(wxString::Format("SetQHYCCDResolution failed! ret = %d\n", ret));
}
}
if (GuideCameraGain != m_curGain)
{
double gain = m_gainMin + GuideCameraGain * (m_gainMax - m_gainMin) / 100.0;
gain = floor(gain / m_gainStep) * m_gainStep;
Debug.Write(wxString::Format("QHY set gain %g (%g..%g incr %g)\n", gain, m_gainMin, m_gainMax, m_gainStep));
ret = SetQHYCCDParam(m_camhandle, CONTROL_GAIN, gain);
if (ret == QHYCCD_SUCCESS)
{
m_curGain = GuideCameraGain;
}
else
{
Debug.Write(wxString::Format("QHY set gain ret %d\n", ret));
pFrame->Alert(_("Failed to set camera gain"));
}
}
if (duration != m_curExposure)
{
ret = SetQHYCCDParam(m_camhandle, CONTROL_EXPOSURE, duration * 1000.0); // QHY duration is usec
if (ret == QHYCCD_SUCCESS)
{
m_curExposure = duration;
}
else
{
Debug.Write(wxString::Format("QHY set exposure ret %d\n", ret));
pFrame->Alert(_("Failed to set camera exposure"));
}
}
ret = ExpQHYCCDSingleFrame(m_camhandle);
if (ret != QHYCCD_SUCCESS)
{
Debug.Write(wxString::Format("QHY exp single frame ret %d\n", ret));
DisconnectWithAlert(_("QHY exposure failed"));
return true;
}
int w, h, bpp, channels;
ret = GetQHYCCDSingleFrame(m_camhandle, &w, &h, &bpp, &channels, RawBuffer);
if (ret != QHYCCD_SUCCESS)
{
Debug.Write(wxString::Format("QHY get single frame ret %d\n", ret));
DisconnectWithAlert(_("QHY get frame failed"));
return true;
}
if (useSubframe)
{
const unsigned char *src = RawBuffer;
unsigned short *dst = img.ImageData + frame.GetTop() * FullSize.GetWidth() + frame.GetLeft();
for (int y = 0; y < frame.GetHeight(); y++)
{
unsigned short *d = dst;
for (int x = 0; x < frame.GetWidth(); x++)
*d++ = (unsigned short) *src++;
dst += FullSize.GetWidth();
}
}
else
{
const unsigned char *src = RawBuffer;
unsigned short *dst = img.ImageData;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
*dst++ = (unsigned short) *src++;
}
}
}
#if 0 // for testing subframes on the bench
img.ImageData[200 * FullSize.GetWidth() + 400 + 0] = 22000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 1] = 32000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 2] = 35000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 3] = 35000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 4] = 32000;
img.ImageData[200 * FullSize.GetWidth() + 400 + 5] = 22000;
#endif
if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img);
if (Color && (options & CAPTURE_RECON)) QuickLRecon(img);
return false;
}
#endif
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "fix4.2/Fix42.h"
#include "util.h"
TEST(TestFieldValue, CharFieldValue) {
EXPECT_EQ('a', fromString<Fix42::kFieldType::kkChar>("a")->getValue());
EXPECT_EQ("a\001", fromValue<Fix42::kFieldType::kkChar>('a')->toString());
}
TEST(TestFieldValue, IntFieldValue) {
EXPECT_EQ(123, fromString<Fix42::kFieldType::kInt>("123")->getValue());
EXPECT_NE(123, fromString<Fix42::kFieldType::kInt>("1234")->getValue());
EXPECT_EQ(-123, fromString<Fix42::kFieldType::kInt>("-123")->getValue());
EXPECT_EQ("123\001", fromValue<Fix42::kFieldType::kInt>(123)->toString());
}
TEST(TestFieldValue, FloatFieldValue) {
EXPECT_DOUBLE_EQ(0.1, fromString<Fix42::kFieldType::kFloat>("0.10")->getValue());
EXPECT_DOUBLE_EQ(0.1, fromString<Fix42::kFieldType::kFloat>("0.1")->getValue());
EXPECT_DOUBLE_EQ(-0.1, fromString<Fix42::kFieldType::kFloat>("-0.1")->getValue());
EXPECT_DOUBLE_EQ(1, fromString<Fix42::kFieldType::kFloat>("1")->getValue());
EXPECT_DOUBLE_EQ(1, fromString<Fix42::kFieldType::kFloat>("1.0")->getValue());
}
TEST(TestFieldValue, StringFieldValue) {
EXPECT_EQ(std::string("abc"), fromString<Fix42::kFieldType::kString>("abc")->getValue());
EXPECT_EQ("abc\001", fromValue<Fix42::kFieldType::kString>("abc")->toString());
}
TEST(TestFieldValue, DataFieldValue) {
char src[] = "0123456789";
auto data = fromString<Fix42::kFieldType::kData>(src);
EXPECT_EQ(10, data->getLength());
const char *begin = data->getValue();
for (int i = 0; i < data->getLength(); i++) {
EXPECT_EQ(src[i], begin[i]);
}
auto expect = std::string(src) + '\001';
EXPECT_EQ(expect, fromValue<Fix42::kFieldType::kData>(src, 10)->toString());
EXPECT_EQ(expect, data->toString());
}
<commit_msg>Fix typo<commit_after>#include "gtest/gtest.h"
#include "fix4.2/Fix42.h"
#include "util.h"
TEST(TestFieldValue, CharFieldValue) {
EXPECT_EQ('a', fromString<Fix42::kFieldType::kChar>("a")->getValue());
EXPECT_EQ("a\001", fromValue<Fix42::kFieldType::kChar>('a')->toString());
}
TEST(TestFieldValue, IntFieldValue) {
EXPECT_EQ(123, fromString<Fix42::kFieldType::kInt>("123")->getValue());
EXPECT_NE(123, fromString<Fix42::kFieldType::kInt>("1234")->getValue());
EXPECT_EQ(-123, fromString<Fix42::kFieldType::kInt>("-123")->getValue());
EXPECT_EQ("123\001", fromValue<Fix42::kFieldType::kInt>(123)->toString());
}
TEST(TestFieldValue, FloatFieldValue) {
EXPECT_DOUBLE_EQ(0.1, fromString<Fix42::kFieldType::kFloat>("0.10")->getValue());
EXPECT_DOUBLE_EQ(0.1, fromString<Fix42::kFieldType::kFloat>("0.1")->getValue());
EXPECT_DOUBLE_EQ(-0.1, fromString<Fix42::kFieldType::kFloat>("-0.1")->getValue());
EXPECT_DOUBLE_EQ(1, fromString<Fix42::kFieldType::kFloat>("1")->getValue());
EXPECT_DOUBLE_EQ(1, fromString<Fix42::kFieldType::kFloat>("1.0")->getValue());
}
TEST(TestFieldValue, StringFieldValue) {
EXPECT_EQ(std::string("abc"), fromString<Fix42::kFieldType::kString>("abc")->getValue());
EXPECT_EQ("abc\001", fromValue<Fix42::kFieldType::kString>("abc")->toString());
}
TEST(TestFieldValue, DataFieldValue) {
char src[] = "0123456789";
auto data = fromString<Fix42::kFieldType::kData>(src);
EXPECT_EQ(10, data->getLength());
const char *begin = data->getValue();
for (int i = 0; i < data->getLength(); i++) {
EXPECT_EQ(src[i], begin[i]);
}
auto expect = std::string(src) + '\001';
EXPECT_EQ(expect, fromValue<Fix42::kFieldType::kData>(src, 10)->toString());
EXPECT_EQ(expect, data->toString());
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010-2011 Sune Vuorela <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "qrcodebarcode.h"
#include <qrencode.h>
using namespace prison;
/**
@cond PRIVATE
*/
class QRCodeBarcode::Private {
public:
};
/**
@endcond
*/
QRCodeBarcode::QRCodeBarcode() : AbstractBarcode(), d(0){
}
QRCodeBarcode::~QRCodeBarcode() {
delete d;
}
QImage QRCodeBarcode::toImage(const QSizeF& size) {
const int width = qRound(qMin(size.width(),size.height()));
if(data().size()==0 || width==0) {
return QImage();
}
const QByteArray trimmedData(data().trimmed().toUtf8());
QRcode* code = QRcode_encodeString8bit(trimmedData.constData(), 0, QR_ECLEVEL_Q);
const int margin = 2;
/*32 bit colors, 8 bit pr byte*/
uchar* img = new uchar[4 *sizeof(char*)*(2*margin + code->width)*(2*margin* + code->width)];
uchar* p = img;
const char white = 0xff;
const char black = 0x00;
for(int row = 0 ; row < code->width+2*margin ; row++) {
for(int col = 0 ; col < code->width+2*margin ; col++) {
if(row < margin || row >= (code->width+margin) || col < margin || col >= (code->width+margin)) {
/*4 bytes for color*/
for(int i =0 ; i<4 ; i++) {
*p = white;
p++;
}
} else {
int c= (row-margin)*code->width + (col-margin);
/*it is bit 1 that is the interesting bit for us from libqrencode*/
if(code->data[c] & 1) {
/*4 bytes for color*/
for(int i =0 ; i<4 ; i++) {
*p = black;
p++;
}
} else {
/*4 bytes for color*/
for(int i =0 ; i<4 ; i++) {
*p = white;
p++;
}
}
}
}
}
QImage tmp(img,code->width+2*margin,code->width+2*margin,QImage::Format_RGB32);
setMinimumSize(QSizeF(tmp.width()*4,tmp.height()*4));
QImage ret = tmp.convertToFormat(QImage::Format_Mono).scaled(qMax(tmp.width()*4,width),qMax(tmp.height()*4,width)); //4 is determined by trial and error.
delete[] img;
QRcode_free(code);
return ret;
}
<commit_msg>QRcode_encodeString8bit can return a null pointer under some circumstances. Check for this and return a default constructed QImage in that case<commit_after>/*
Copyright (c) 2010-2011 Sune Vuorela <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "qrcodebarcode.h"
#include <qrencode.h>
using namespace prison;
/**
@cond PRIVATE
*/
class QRCodeBarcode::Private {
public:
};
/**
@endcond
*/
QRCodeBarcode::QRCodeBarcode() : AbstractBarcode(), d(0){
}
QRCodeBarcode::~QRCodeBarcode() {
delete d;
}
QImage QRCodeBarcode::toImage(const QSizeF& size) {
const int width = qRound(qMin(size.width(),size.height()));
if(data().size()==0 || width==0) {
return QImage();
}
const QByteArray trimmedData(data().trimmed().toUtf8());
QRcode* code = QRcode_encodeString8bit(trimmedData.constData(), 0, QR_ECLEVEL_Q);
if(!code) {
return QImage();
}
const int margin = 2;
/*32 bit colors, 8 bit pr byte*/
uchar* img = new uchar[4 *sizeof(char*)*(2*margin + code->width)*(2*margin* + code->width)];
uchar* p = img;
const char white = 0xff;
const char black = 0x00;
for(int row = 0 ; row < code->width+2*margin ; row++) {
for(int col = 0 ; col < code->width+2*margin ; col++) {
if(row < margin || row >= (code->width+margin) || col < margin || col >= (code->width+margin)) {
/*4 bytes for color*/
for(int i =0 ; i<4 ; i++) {
*p = white;
p++;
}
} else {
int c= (row-margin)*code->width + (col-margin);
/*it is bit 1 that is the interesting bit for us from libqrencode*/
if(code->data[c] & 1) {
/*4 bytes for color*/
for(int i =0 ; i<4 ; i++) {
*p = black;
p++;
}
} else {
/*4 bytes for color*/
for(int i =0 ; i<4 ; i++) {
*p = white;
p++;
}
}
}
}
}
QImage tmp(img,code->width+2*margin,code->width+2*margin,QImage::Format_RGB32);
setMinimumSize(QSizeF(tmp.width()*4,tmp.height()*4));
QImage ret = tmp.convertToFormat(QImage::Format_Mono).scaled(qMax(tmp.width()*4,width),qMax(tmp.height()*4,width)); //4 is determined by trial and error.
delete[] img;
QRcode_free(code);
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/HHWheelTimer.h>
#include <cassert>
#include <folly/Memory.h>
#include <folly/Optional.h>
#include <folly/ScopeGuard.h>
#include <folly/container/BitIterator.h>
#include <folly/io/async/Request.h>
#include <folly/lang/Bits.h>
using std::chrono::milliseconds;
namespace folly {
/**
* We want to select the default interval carefully.
* An interval of 10ms will give us 10ms * WHEEL_SIZE^WHEEL_BUCKETS
* for the largest timeout possible, or about 497 days.
*
* For a lower bound, we want a reasonable limit on local IO, 10ms
* seems short enough
*
* A shorter interval also has CPU implications, less than 1ms might
* start showing up in cpu perf. Also, it might not be possible to set
* tick interval less than 10ms on older kernels.
*/
int HHWheelTimer::DEFAULT_TICK_INTERVAL = 10;
HHWheelTimer::Callback::~Callback() {
if (isScheduled()) {
cancelTimeout();
}
}
void HHWheelTimer::Callback::setScheduled(
HHWheelTimer* wheel,
std::chrono::milliseconds timeout) {
assert(wheel_ == nullptr);
assert(expiration_ == decltype(expiration_){});
wheel_ = wheel;
expiration_ = getCurTime() + timeout;
}
void HHWheelTimer::Callback::cancelTimeoutImpl() {
if (--wheel_->count_ <= 0) {
assert(wheel_->count_ == 0);
wheel_->AsyncTimeout::cancelTimeout();
}
unlink();
if ((-1 != bucket_) && (wheel_->buckets_[0][bucket_].empty())) {
auto bi = makeBitIterator(wheel_->bitmap_.begin());
*(bi + bucket_) = false;
}
wheel_ = nullptr;
expiration_ = {};
}
HHWheelTimer::HHWheelTimer(
folly::TimeoutManager* timeoutMananger,
std::chrono::milliseconds intervalMS,
AsyncTimeout::InternalEnum internal,
std::chrono::milliseconds defaultTimeoutMS)
: AsyncTimeout(timeoutMananger, internal),
interval_(intervalMS),
defaultTimeout_(defaultTimeoutMS),
lastTick_(1),
expireTick_(1),
count_(0),
startTime_(getCurTime()),
processingCallbacksGuard_(nullptr) {
bitmap_.resize((WHEEL_SIZE / sizeof(std::size_t)) / 8, 0);
}
HHWheelTimer::~HHWheelTimer() {
// Ensure this gets done, but right before destruction finishes.
auto destructionPublisherGuard = folly::makeGuard([&] {
// Inform the subscriber that this instance is doomed.
if (processingCallbacksGuard_) {
*processingCallbacksGuard_ = true;
}
});
cancelAll();
}
void HHWheelTimer::scheduleTimeoutImpl(
Callback* callback,
std::chrono::milliseconds timeout,
int64_t nextTickToProcess,
int64_t nextTick) {
int64_t due = timeToWheelTicks(timeout) + nextTick;
int64_t diff = due - nextTickToProcess;
CallbackList* list;
auto bi = makeBitIterator(bitmap_.begin());
if (diff < 0) {
list = &buckets_[0][nextTick & WHEEL_MASK];
*(bi + (nextTick & WHEEL_MASK)) = true;
callback->bucket_ = nextTick & WHEEL_MASK;
} else if (diff < WHEEL_SIZE) {
list = &buckets_[0][due & WHEEL_MASK];
*(bi + (due & WHEEL_MASK)) = true;
callback->bucket_ = due & WHEEL_MASK;
} else if (diff < 1 << (2 * WHEEL_BITS)) {
list = &buckets_[1][(due >> WHEEL_BITS) & WHEEL_MASK];
} else if (diff < 1 << (3 * WHEEL_BITS)) {
list = &buckets_[2][(due >> 2 * WHEEL_BITS) & WHEEL_MASK];
} else {
/* in largest slot */
if (diff > LARGEST_SLOT) {
diff = LARGEST_SLOT;
due = diff + nextTickToProcess;
}
list = &buckets_[3][(due >> 3 * WHEEL_BITS) & WHEEL_MASK];
}
list->push_back(*callback);
}
void HHWheelTimer::scheduleTimeout(
Callback* callback,
std::chrono::milliseconds timeout) {
// Cancel the callback if it happens to be scheduled already.
callback->cancelTimeout();
callback->requestContext_ = RequestContext::saveContext();
count_++;
callback->setScheduled(this, timeout);
auto nextTick = calcNextTick();
// It's possible that the wheel timeout is already scheduled for earlier
// tick, but it didn't run yet. In such case, we must use the lowest of them
// to avoid using the wrong slot.
int64_t baseTick = nextTick;
if (isScheduled()) {
baseTick = std::min(expireTick_, nextTick);
}
scheduleTimeoutImpl(callback, timeout, baseTick, nextTick);
/* If we're calling callbacks, timer will be reset after all
* callbacks are called.
*/
if (!processingCallbacksGuard_) {
scheduleNextTimeout(nextTick);
}
}
void HHWheelTimer::scheduleTimeout(Callback* callback) {
CHECK(std::chrono::milliseconds(-1) != defaultTimeout_)
<< "Default timeout was not initialized";
scheduleTimeout(callback, defaultTimeout_);
}
bool HHWheelTimer::cascadeTimers(int bucket, int tick) {
CallbackList cbs;
cbs.swap(buckets_[bucket][tick]);
while (!cbs.empty()) {
auto* cb = &cbs.front();
cbs.pop_front();
scheduleTimeoutImpl(
cb, cb->getTimeRemaining(getCurTime()), lastTick_, calcNextTick());
}
// If tick is zero, timeoutExpired will cascade the next bucket.
return tick == 0;
}
void HHWheelTimer::timeoutExpired() noexcept {
auto nextTick = calcNextTick();
// If the last smart pointer for "this" is reset inside the callback's
// timeoutExpired(), then the guard will detect that it is time to bail from
// this method.
auto isDestroyed = false;
// If scheduleTimeout is called from a callback in this function, it may
// cause inconsistencies in the state of this object. As such, we need
// to treat these calls slightly differently.
CHECK(!processingCallbacksGuard_);
processingCallbacksGuard_ = &isDestroyed;
auto reEntryGuard = folly::makeGuard([&] {
if (!isDestroyed) {
processingCallbacksGuard_ = nullptr;
}
});
// timeoutExpired() can only be invoked directly from the event base loop.
// It should never be invoked recursively.
//
lastTick_ = expireTick_;
while (lastTick_ < nextTick) {
int idx = lastTick_ & WHEEL_MASK;
auto bi = makeBitIterator(bitmap_.begin());
*(bi + idx) = false;
lastTick_++;
CallbackList* cbs = &buckets_[0][idx];
while (!cbs->empty()) {
auto* cb = &cbs->front();
cbs->pop_front();
timeoutsToRunNow_.push_back(*cb);
}
if (idx == 0) {
// Cascade timers
if (cascadeTimers(1, (lastTick_ >> WHEEL_BITS) & WHEEL_MASK) &&
cascadeTimers(2, (lastTick_ >> (2 * WHEEL_BITS)) & WHEEL_MASK)) {
cascadeTimers(3, (lastTick_ >> (3 * WHEEL_BITS)) & WHEEL_MASK);
}
}
}
while (!timeoutsToRunNow_.empty()) {
auto* cb = &timeoutsToRunNow_.front();
timeoutsToRunNow_.pop_front();
count_--;
cb->wheel_ = nullptr;
cb->expiration_ = {};
RequestContextScopeGuard rctx(cb->requestContext_);
cb->timeoutExpired();
if (isDestroyed) {
// The HHWheelTimer itself has been destroyed. The other callbacks
// will have been cancelled from the destructor. Bail before causing
// damage.
return;
}
}
scheduleNextTimeout(calcNextTick());
}
size_t HHWheelTimer::cancelAll() {
size_t count = 0;
if (count_ != 0) {
const std::size_t numElements = WHEEL_BUCKETS * WHEEL_SIZE;
auto maxBuckets = std::min(numElements, count_);
auto buckets = std::make_unique<CallbackList[]>(maxBuckets);
size_t countBuckets = 0;
for (auto& tick : buckets_) {
for (auto& bucket : tick) {
if (bucket.empty()) {
continue;
}
count += bucket.size();
std::swap(bucket, buckets[countBuckets++]);
if (count >= count_) {
break;
}
}
}
for (size_t i = 0; i < countBuckets; ++i) {
cancelTimeoutsFromList(buckets[i]);
}
// Swap the list to prevent potential recursion if cancelAll is called by
// one of the callbacks.
CallbackList timeoutsToRunNow;
timeoutsToRunNow.swap(timeoutsToRunNow_);
count += cancelTimeoutsFromList(timeoutsToRunNow);
}
return count;
}
void HHWheelTimer::scheduleNextTimeout(int64_t nextTick) {
int64_t tick = 1;
if (nextTick & WHEEL_MASK) {
auto bi = makeBitIterator(bitmap_.begin());
auto bi_end = makeBitIterator(bitmap_.end());
auto it = folly::findFirstSet(bi + (nextTick & WHEEL_MASK), bi_end);
if (it == bi_end) {
tick = WHEEL_SIZE - ((nextTick - 1) & WHEEL_MASK);
} else {
tick = std::distance(bi + (nextTick & WHEEL_MASK), it) + 1;
}
}
if (count_ > 0) {
if (!this->AsyncTimeout::isScheduled() ||
(expireTick_ > tick + nextTick - 1)) {
this->AsyncTimeout::scheduleTimeout(interval_ * tick);
expireTick_ = tick + nextTick - 1;
}
} else {
this->AsyncTimeout::cancelTimeout();
}
}
size_t HHWheelTimer::cancelTimeoutsFromList(CallbackList& timeouts) {
size_t count = 0;
while (!timeouts.empty()) {
++count;
auto& cb = timeouts.front();
cb.cancelTimeout();
cb.callbackCanceled();
}
return count;
}
int64_t HHWheelTimer::calcNextTick() {
auto intervals = (getCurTime() - startTime_) / interval_;
// Slow eventbases will have skew between the actual time and the
// callback time. To avoid racing the next scheduleNextTimeout()
// call, always schedule new timeouts against the actual
// timeoutExpired() time.
if (!processingCallbacksGuard_) {
return intervals;
} else {
return lastTick_;
}
}
} // namespace folly
<commit_msg>Allow cascading into the current tick<commit_after>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/HHWheelTimer.h>
#include <cassert>
#include <folly/Memory.h>
#include <folly/Optional.h>
#include <folly/ScopeGuard.h>
#include <folly/container/BitIterator.h>
#include <folly/io/async/Request.h>
#include <folly/lang/Bits.h>
using std::chrono::milliseconds;
namespace folly {
/**
* We want to select the default interval carefully.
* An interval of 10ms will give us 10ms * WHEEL_SIZE^WHEEL_BUCKETS
* for the largest timeout possible, or about 497 days.
*
* For a lower bound, we want a reasonable limit on local IO, 10ms
* seems short enough
*
* A shorter interval also has CPU implications, less than 1ms might
* start showing up in cpu perf. Also, it might not be possible to set
* tick interval less than 10ms on older kernels.
*/
int HHWheelTimer::DEFAULT_TICK_INTERVAL = 10;
HHWheelTimer::Callback::~Callback() {
if (isScheduled()) {
cancelTimeout();
}
}
void HHWheelTimer::Callback::setScheduled(
HHWheelTimer* wheel,
std::chrono::milliseconds timeout) {
assert(wheel_ == nullptr);
assert(expiration_ == decltype(expiration_){});
wheel_ = wheel;
expiration_ = getCurTime() + timeout;
}
void HHWheelTimer::Callback::cancelTimeoutImpl() {
if (--wheel_->count_ <= 0) {
assert(wheel_->count_ == 0);
wheel_->AsyncTimeout::cancelTimeout();
}
unlink();
if ((-1 != bucket_) && (wheel_->buckets_[0][bucket_].empty())) {
auto bi = makeBitIterator(wheel_->bitmap_.begin());
*(bi + bucket_) = false;
}
wheel_ = nullptr;
expiration_ = {};
}
HHWheelTimer::HHWheelTimer(
folly::TimeoutManager* timeoutMananger,
std::chrono::milliseconds intervalMS,
AsyncTimeout::InternalEnum internal,
std::chrono::milliseconds defaultTimeoutMS)
: AsyncTimeout(timeoutMananger, internal),
interval_(intervalMS),
defaultTimeout_(defaultTimeoutMS),
lastTick_(1),
expireTick_(1),
count_(0),
startTime_(getCurTime()),
processingCallbacksGuard_(nullptr) {
bitmap_.resize((WHEEL_SIZE / sizeof(std::size_t)) / 8, 0);
}
HHWheelTimer::~HHWheelTimer() {
// Ensure this gets done, but right before destruction finishes.
auto destructionPublisherGuard = folly::makeGuard([&] {
// Inform the subscriber that this instance is doomed.
if (processingCallbacksGuard_) {
*processingCallbacksGuard_ = true;
}
});
cancelAll();
}
void HHWheelTimer::scheduleTimeoutImpl(
Callback* callback,
std::chrono::milliseconds timeout,
int64_t nextTickToProcess,
int64_t nextTick) {
int64_t due = timeToWheelTicks(timeout) + nextTick;
int64_t diff = due - nextTickToProcess;
CallbackList* list;
auto bi = makeBitIterator(bitmap_.begin());
if (diff < 0) {
list = &buckets_[0][nextTick & WHEEL_MASK];
*(bi + (nextTick & WHEEL_MASK)) = true;
callback->bucket_ = nextTick & WHEEL_MASK;
} else if (diff < WHEEL_SIZE) {
list = &buckets_[0][due & WHEEL_MASK];
*(bi + (due & WHEEL_MASK)) = true;
callback->bucket_ = due & WHEEL_MASK;
} else if (diff < 1 << (2 * WHEEL_BITS)) {
list = &buckets_[1][(due >> WHEEL_BITS) & WHEEL_MASK];
} else if (diff < 1 << (3 * WHEEL_BITS)) {
list = &buckets_[2][(due >> 2 * WHEEL_BITS) & WHEEL_MASK];
} else {
/* in largest slot */
if (diff > LARGEST_SLOT) {
diff = LARGEST_SLOT;
due = diff + nextTickToProcess;
}
list = &buckets_[3][(due >> 3 * WHEEL_BITS) & WHEEL_MASK];
}
list->push_back(*callback);
}
void HHWheelTimer::scheduleTimeout(
Callback* callback,
std::chrono::milliseconds timeout) {
// Cancel the callback if it happens to be scheduled already.
callback->cancelTimeout();
callback->requestContext_ = RequestContext::saveContext();
count_++;
callback->setScheduled(this, timeout);
auto nextTick = calcNextTick();
// It's possible that the wheel timeout is already scheduled for earlier
// tick, but it didn't run yet. In such case, we must use the lowest of them
// to avoid using the wrong slot.
int64_t baseTick = nextTick;
if (isScheduled()) {
baseTick = std::min(expireTick_, nextTick);
}
scheduleTimeoutImpl(callback, timeout, baseTick, nextTick);
/* If we're calling callbacks, timer will be reset after all
* callbacks are called.
*/
if (!processingCallbacksGuard_) {
scheduleNextTimeout(nextTick);
}
}
void HHWheelTimer::scheduleTimeout(Callback* callback) {
CHECK(std::chrono::milliseconds(-1) != defaultTimeout_)
<< "Default timeout was not initialized";
scheduleTimeout(callback, defaultTimeout_);
}
bool HHWheelTimer::cascadeTimers(int bucket, int tick) {
CallbackList cbs;
cbs.swap(buckets_[bucket][tick]);
while (!cbs.empty()) {
auto* cb = &cbs.front();
cbs.pop_front();
scheduleTimeoutImpl(
cb, cb->getTimeRemaining(getCurTime()), lastTick_, calcNextTick());
}
// If tick is zero, timeoutExpired will cascade the next bucket.
return tick == 0;
}
void HHWheelTimer::timeoutExpired() noexcept {
auto nextTick = calcNextTick();
// If the last smart pointer for "this" is reset inside the callback's
// timeoutExpired(), then the guard will detect that it is time to bail from
// this method.
auto isDestroyed = false;
// If scheduleTimeout is called from a callback in this function, it may
// cause inconsistencies in the state of this object. As such, we need
// to treat these calls slightly differently.
CHECK(!processingCallbacksGuard_);
processingCallbacksGuard_ = &isDestroyed;
auto reEntryGuard = folly::makeGuard([&] {
if (!isDestroyed) {
processingCallbacksGuard_ = nullptr;
}
});
// timeoutExpired() can only be invoked directly from the event base loop.
// It should never be invoked recursively.
//
lastTick_ = expireTick_;
while (lastTick_ < nextTick) {
int idx = lastTick_ & WHEEL_MASK;
if (idx == 0) {
// Cascade timers
if (cascadeTimers(1, (lastTick_ >> WHEEL_BITS) & WHEEL_MASK) &&
cascadeTimers(2, (lastTick_ >> (2 * WHEEL_BITS)) & WHEEL_MASK)) {
cascadeTimers(3, (lastTick_ >> (3 * WHEEL_BITS)) & WHEEL_MASK);
}
}
auto bi = makeBitIterator(bitmap_.begin());
*(bi + idx) = false;
lastTick_++;
CallbackList* cbs = &buckets_[0][idx];
while (!cbs->empty()) {
auto* cb = &cbs->front();
cbs->pop_front();
timeoutsToRunNow_.push_back(*cb);
}
}
while (!timeoutsToRunNow_.empty()) {
auto* cb = &timeoutsToRunNow_.front();
timeoutsToRunNow_.pop_front();
count_--;
cb->wheel_ = nullptr;
cb->expiration_ = {};
RequestContextScopeGuard rctx(cb->requestContext_);
cb->timeoutExpired();
if (isDestroyed) {
// The HHWheelTimer itself has been destroyed. The other callbacks
// will have been cancelled from the destructor. Bail before causing
// damage.
return;
}
}
scheduleNextTimeout(calcNextTick());
}
size_t HHWheelTimer::cancelAll() {
size_t count = 0;
if (count_ != 0) {
const std::size_t numElements = WHEEL_BUCKETS * WHEEL_SIZE;
auto maxBuckets = std::min(numElements, count_);
auto buckets = std::make_unique<CallbackList[]>(maxBuckets);
size_t countBuckets = 0;
for (auto& tick : buckets_) {
for (auto& bucket : tick) {
if (bucket.empty()) {
continue;
}
count += bucket.size();
std::swap(bucket, buckets[countBuckets++]);
if (count >= count_) {
break;
}
}
}
for (size_t i = 0; i < countBuckets; ++i) {
cancelTimeoutsFromList(buckets[i]);
}
// Swap the list to prevent potential recursion if cancelAll is called by
// one of the callbacks.
CallbackList timeoutsToRunNow;
timeoutsToRunNow.swap(timeoutsToRunNow_);
count += cancelTimeoutsFromList(timeoutsToRunNow);
}
return count;
}
void HHWheelTimer::scheduleNextTimeout(int64_t nextTick) {
int64_t tick = 1;
if (nextTick & WHEEL_MASK) {
auto bi = makeBitIterator(bitmap_.begin());
auto bi_end = makeBitIterator(bitmap_.end());
auto it = folly::findFirstSet(bi + (nextTick & WHEEL_MASK), bi_end);
if (it == bi_end) {
tick = WHEEL_SIZE - ((nextTick - 1) & WHEEL_MASK);
} else {
tick = std::distance(bi + (nextTick & WHEEL_MASK), it) + 1;
}
}
if (count_ > 0) {
if (!this->AsyncTimeout::isScheduled() ||
(expireTick_ > tick + nextTick - 1)) {
this->AsyncTimeout::scheduleTimeout(interval_ * tick);
expireTick_ = tick + nextTick - 1;
}
} else {
this->AsyncTimeout::cancelTimeout();
}
}
size_t HHWheelTimer::cancelTimeoutsFromList(CallbackList& timeouts) {
size_t count = 0;
while (!timeouts.empty()) {
++count;
auto& cb = timeouts.front();
cb.cancelTimeout();
cb.callbackCanceled();
}
return count;
}
int64_t HHWheelTimer::calcNextTick() {
auto intervals = (getCurTime() - startTime_) / interval_;
// Slow eventbases will have skew between the actual time and the
// callback time. To avoid racing the next scheduleNextTimeout()
// call, always schedule new timeouts against the actual
// timeoutExpired() time.
if (!processingCallbacksGuard_) {
return intervals;
} else {
return lastTick_;
}
}
} // namespace folly
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Edit.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2007-11-01 14:54:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FORMS_EDIT_HXX_
#define _FORMS_EDIT_HXX_
#include "EditBase.hxx"
#include <cppuhelper/implbase3.hxx>
namespace dbtools { class FormattedColumnValue; }
//.........................................................................
namespace frm
{
//==================================================================
//= OEditModel
//==================================================================
class OEditModel
:public OEditBaseModel
{
::rtl::OUString m_aSaveValue;
::std::auto_ptr< ::dbtools::FormattedColumnValue >
m_pValueFormatter;
sal_Bool m_bMaxTextLenModified : 1; // set to <TRUE/> when we change the MaxTextLen of the aggregate
sal_Bool m_bWritingFormattedFake : 1;
// are we writing something which should be interpreted as formatted upon reading?
protected:
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
DECLARE_DEFAULT_LEAF_XTOR( OEditModel );
void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; }
void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; }
sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; }
friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
friend class OFormattedFieldWrapper;
friend class OFormattedModel; // temporary
public:
virtual void SAL_CALL disposing();
// XPropertySet
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
// XPersistObject
virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
// XPropertySet
using OBoundControlModel::getFastPropertyValue;
// XReset
virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
IMPLEMENTATION_NAME(OEditModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// OControlModel's property handling
virtual void describeFixedProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
) const;
virtual void describeAggregateProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
// XEventListener
using OBoundControlModel::disposing;
protected:
// OControlModel overridables
virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const;
virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream );
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual void onDisconnectedDbColumn();
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType );
protected:
virtual sal_uInt16 getPersistenceFlags() const;
DECLARE_XCLONEABLE();
private:
bool implActsAsRichText( ) const;
};
//==================================================================
//= OEditControl
//==================================================================
typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,
::com::sun::star::awt::XKeyListener,
::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE;
class OEditControl : public OBoundControl
,public OEditControl_BASE
{
::cppu::OInterfaceContainerHelper
m_aChangeListeners;
::rtl::OUString m_aHtmlChangeValue;
sal_uInt32 m_nKeyEvent;
public:
OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
virtual ~OEditControl();
DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
// OComponentHelper
virtual void SAL_CALL disposing();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XServiceInfo
IMPLEMENTATION_NAME(OEditControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// ::com::sun::star::form::XChangeBroadcaster
virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XFocusListener
virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XKeyListener
virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
// XControl
virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& _rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& _rxParent ) throw ( ::com::sun::star::uno::RuntimeException );
private:
DECL_LINK( OnKeyPressed, void* );
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_EDIT_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.16.42); FILE MERGED 2008/03/31 13:11:32 rt 1.16.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Edit.hxx,v $
* $Revision: 1.17 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _FORMS_EDIT_HXX_
#define _FORMS_EDIT_HXX_
#include "EditBase.hxx"
#include <cppuhelper/implbase3.hxx>
namespace dbtools { class FormattedColumnValue; }
//.........................................................................
namespace frm
{
//==================================================================
//= OEditModel
//==================================================================
class OEditModel
:public OEditBaseModel
{
::rtl::OUString m_aSaveValue;
::std::auto_ptr< ::dbtools::FormattedColumnValue >
m_pValueFormatter;
sal_Bool m_bMaxTextLenModified : 1; // set to <TRUE/> when we change the MaxTextLen of the aggregate
sal_Bool m_bWritingFormattedFake : 1;
// are we writing something which should be interpreted as formatted upon reading?
protected:
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
DECLARE_DEFAULT_LEAF_XTOR( OEditModel );
void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; }
void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; }
sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; }
friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
friend class OFormattedFieldWrapper;
friend class OFormattedModel; // temporary
public:
virtual void SAL_CALL disposing();
// XPropertySet
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
// XPersistObject
virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
// XPropertySet
using OBoundControlModel::getFastPropertyValue;
// XReset
virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
IMPLEMENTATION_NAME(OEditModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// OControlModel's property handling
virtual void describeFixedProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
) const;
virtual void describeAggregateProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
// XEventListener
using OBoundControlModel::disposing;
protected:
// OControlModel overridables
virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const;
virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream );
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual void onDisconnectedDbColumn();
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType );
protected:
virtual sal_uInt16 getPersistenceFlags() const;
DECLARE_XCLONEABLE();
private:
bool implActsAsRichText( ) const;
};
//==================================================================
//= OEditControl
//==================================================================
typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,
::com::sun::star::awt::XKeyListener,
::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE;
class OEditControl : public OBoundControl
,public OEditControl_BASE
{
::cppu::OInterfaceContainerHelper
m_aChangeListeners;
::rtl::OUString m_aHtmlChangeValue;
sal_uInt32 m_nKeyEvent;
public:
OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
virtual ~OEditControl();
DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
// OComponentHelper
virtual void SAL_CALL disposing();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XServiceInfo
IMPLEMENTATION_NAME(OEditControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw();
// ::com::sun::star::form::XChangeBroadcaster
virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XFocusListener
virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XKeyListener
virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
// XControl
virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& _rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& _rxParent ) throw ( ::com::sun::star::uno::RuntimeException );
private:
DECL_LINK( OnKeyPressed, void* );
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_EDIT_HXX_
<|endoftext|> |
<commit_before><commit_msg>fixed a typeo<commit_after><|endoftext|> |
<commit_before>//===-- dsymutil.cpp - Debug info dumping utility for llvm ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that aims to be a dropin replacement for
// Darwin's dsymutil.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Options.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
using namespace llvm::dsymutil;
namespace {
using namespace llvm::cl;
static opt<std::string> InputFile(Positional, desc("<input file>"),
init("a.out"));
static opt<std::string> OsoPrependPath("oso-prepend-path",
desc("Specify a directory to prepend "
"to the paths of object files."),
value_desc("path"));
static opt<bool> Verbose("v", desc("Verbosity level"), init(false));
static opt<bool>
ParseOnly("parse-only",
desc("Only parse the debug map, do not actaully link "
"the DWARF."),
init(false));
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram StackPrinter(argc, argv);
llvm::llvm_shutdown_obj Shutdown;
llvm::cl::ParseCommandLineOptions(argc, argv, "llvm dsymutil\n");
auto DebugMapPtrOrErr = parseDebugMap(InputFile, OsoPrependPath, Verbose);
if (auto EC = DebugMapPtrOrErr.getError()) {
llvm::errs() << "error: cannot parse the debug map for \"" << InputFile
<< "\": " << EC.message() << '\n';
return 1;
}
if (Verbose)
(*DebugMapPtrOrErr)->print(llvm::outs());
if (ParseOnly)
return 0;
std::string OutputBasename(InputFile);
if (OutputBasename == "-")
OutputBasename = "a.out";
return !linkDwarf(OutputBasename + ".dwarf", **DebugMapPtrOrErr, Verbose);
}
<commit_msg>[dsymutil] Add -o option to select ouptut filename<commit_after>//===-- dsymutil.cpp - Debug info dumping utility for llvm ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that aims to be a dropin replacement for
// Darwin's dsymutil.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Options.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
using namespace llvm::dsymutil;
namespace {
using namespace llvm::cl;
static opt<std::string> InputFile(Positional, desc("<input file>"),
init("a.out"));
static opt<std::string> OutputFileOpt("o", desc("Specify the output file."
" default: <input file>.dwarf"),
value_desc("filename"));
static opt<std::string> OsoPrependPath("oso-prepend-path",
desc("Specify a directory to prepend "
"to the paths of object files."),
value_desc("path"));
static opt<bool> Verbose("v", desc("Verbosity level"), init(false));
static opt<bool>
ParseOnly("parse-only",
desc("Only parse the debug map, do not actaully link "
"the DWARF."),
init(false));
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram StackPrinter(argc, argv);
llvm::llvm_shutdown_obj Shutdown;
llvm::cl::ParseCommandLineOptions(argc, argv, "llvm dsymutil\n");
auto DebugMapPtrOrErr = parseDebugMap(InputFile, OsoPrependPath, Verbose);
if (auto EC = DebugMapPtrOrErr.getError()) {
llvm::errs() << "error: cannot parse the debug map for \"" << InputFile
<< "\": " << EC.message() << '\n';
return 1;
}
if (Verbose)
(*DebugMapPtrOrErr)->print(llvm::outs());
if (ParseOnly)
return 0;
std::string OutputFile;
if (OutputFileOpt.empty()) {
if (InputFile == "-")
OutputFile = "a.out.dwarf";
else
OutputFile = InputFile + ".dwarf";
} else {
OutputFile = OutputFileOpt;
}
return !linkDwarf(OutputFile, **DebugMapPtrOrErr, Verbose);
}
<|endoftext|> |
<commit_before>#include <experimental/filesystem>
#include <fstream>
#include <string>
#include <vector>
#include "glog/logging.h"
#include "google/protobuf/descriptor.h"
#include "serialization/journal.pb.h"
namespace principia {
using ::google::protobuf::Descriptor;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::FieldOptions;
using ::google::protobuf::FileDescriptor;
namespace tools {
namespace {
char const kIn[] = "In";
char const kReturn[] = "Return";
char const kOut[] = "Out";
class Generator {
public:
void ProcessMethods();
std::vector<std::string> GetCppMethodTypes() const;
private:
void ProcessRepeatedMessageField(FieldDescriptor const* descriptor);
void ProcessOptionalInt32Field(FieldDescriptor const* descriptor);
void ProcessRequiredFixed64Field(FieldDescriptor const* descriptor);
void ProcessRequiredMessageField(FieldDescriptor const* descriptor);
void ProcessRequiredBoolField(FieldDescriptor const* descriptor);
void ProcessRequiredDoubleField(FieldDescriptor const* descriptor);
void ProcessRequiredInt32Field(FieldDescriptor const* descriptor);
void ProcessSingleStringField(FieldDescriptor const* descriptor);
void ProcessOptionalField(FieldDescriptor const* descriptor);
void ProcessRepeatedField(FieldDescriptor const* descriptor);
void ProcessRequiredField(FieldDescriptor const* descriptor);
void ProcessField(FieldDescriptor const* descriptor);
void ProcessInOut(Descriptor const* descriptor,
std::vector<FieldDescriptor const*>* field_descriptors);
void ProcessReturn(Descriptor const* descriptor);
void ProcessMethodExtension(Descriptor const* descriptor);
private:
std::map<Descriptor const*, std::string> cpp_method_type_;
std::map<FieldDescriptor const*, std::string> size_field_;
std::set<FieldDescriptor const*> in_out_field_;
std::map<Descriptor const*, std::string> cpp_nested_type_;
std::map<FieldDescriptor const*, std::string> cpp_field_type_;
};
void Generator::ProcessMethods() {
// Get the file containing |Method|.
Descriptor const* method_descriptor = serialization::Method::descriptor();
FileDescriptor const* file_descriptor = method_descriptor->file();
// Process all the messages in that file.
for (int i = 0; i < file_descriptor->message_type_count(); ++i) {
Descriptor const* message_descriptor = file_descriptor->message_type(i);
switch (message_descriptor->extension_count()) {
case 0: {
// An auxiliary message that is not an extension. Nothing to do.
break;
}
case 1: {
// An extension. Check that it extends |Method|.
FieldDescriptor const* extension = message_descriptor->extension(0);
CHECK(extension->is_extension());
Descriptor const* containing_type = extension->containing_type();
CHECK_EQ(method_descriptor, containing_type)
<< message_descriptor->name() << " extends a message other than "
<< method_descriptor->name() << ": " << containing_type->name();
ProcessMethodExtension(message_descriptor);
break;
}
default: {
LOG(FATAL) << message_descriptor->name() << " has "
<< message_descriptor->extension_count() << " extensions";
}
}
}
}
std::vector<std::string> Generator::GetCppMethodTypes() const {
std::vector<std::string> result;
for (auto const& pair : cpp_method_type_) {
result.push_back(pair.second);
}
return result;
}
void Generator::ProcessRepeatedMessageField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->message_type()->name() +
" const*";
}
void Generator::ProcessOptionalInt32Field(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = "int const*";
}
void Generator::ProcessRequiredFixed64Field(FieldDescriptor const* descriptor) {
FieldOptions const& options = descriptor->options();
CHECK(options.HasExtension(serialization::pointer_to))
<< descriptor->full_name() << " is missing a pointer_to option";
std::string const& pointer_to =
options.GetExtension(serialization::pointer_to);
cpp_field_type_[descriptor] = pointer_to + "*";
}
void Generator::ProcessRequiredMessageField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->message_type()->name();
}
void Generator::ProcessRequiredBoolField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->cpp_type_name();
}
void Generator::ProcessRequiredDoubleField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->cpp_type_name();
}
void Generator::ProcessRequiredInt32Field(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = "int";
}
void Generator::ProcessSingleStringField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = "char const*";
}
void Generator::ProcessOptionalField(FieldDescriptor const* descriptor) {
switch (descriptor->type()) {
case FieldDescriptor::TYPE_INT32:
ProcessOptionalInt32Field(descriptor);
break;
case FieldDescriptor::TYPE_STRING:
ProcessSingleStringField(descriptor);
break;
default:
LOG(FATAL) << descriptor->full_name() << " has unexpected type "
<< descriptor->type_name();
}
}
void Generator::ProcessRepeatedField(FieldDescriptor const* descriptor) {
switch (descriptor->type()) {
case FieldDescriptor::TYPE_MESSAGE:
ProcessRepeatedMessageField(descriptor);
break;
default:
LOG(FATAL) << descriptor->full_name() << " has unexpected type "
<< descriptor->type_name();
}
}
void Generator::ProcessRequiredField(FieldDescriptor const* descriptor) {
switch (descriptor->type()) {
case FieldDescriptor::TYPE_BOOL:
ProcessRequiredBoolField(descriptor);
break;
case FieldDescriptor::TYPE_DOUBLE:
ProcessRequiredDoubleField(descriptor);
break;
case FieldDescriptor::TYPE_FIXED64:
ProcessRequiredFixed64Field(descriptor);
break;
case FieldDescriptor::TYPE_INT32:
ProcessRequiredInt32Field(descriptor);
break;
case FieldDescriptor::TYPE_MESSAGE:
ProcessRequiredMessageField(descriptor);
break;
case FieldDescriptor::TYPE_STRING:
ProcessSingleStringField(descriptor);
break;
default:
LOG(FATAL) << descriptor->full_name() << " has unexpected type "
<< descriptor->type_name();
}
// For in-out fields the data is actually passed with an extra level of
// indirection.
if (in_out_field_.find(descriptor) != in_out_field_.end()) {
cpp_field_type_[descriptor] += "*";
}
}
void Generator::ProcessField(FieldDescriptor const* descriptor) {
switch (descriptor->label()) {
case FieldDescriptor::LABEL_OPTIONAL:
ProcessOptionalField(descriptor);
break;
case FieldDescriptor::LABEL_REPEATED:
ProcessRepeatedField(descriptor);
break;
case FieldDescriptor::LABEL_REQUIRED:
ProcessRequiredField(descriptor);
break;
}
FieldOptions const& options = descriptor->options();
if (options.HasExtension(serialization::size)) {
size_field_[descriptor] = options.GetExtension(serialization::size);
}
}
void Generator::ProcessInOut(Descriptor const* descriptor,
std::vector<FieldDescriptor const*>* field_descriptors) {
cpp_nested_type_[descriptor] = " struct " + descriptor->name() + " {\n";
for (int i = 0; i < descriptor->field_count(); ++i) {
FieldDescriptor const* field_descriptor = descriptor->field(i);
if (field_descriptors != nullptr) {
field_descriptors->push_back(field_descriptor);
}
ProcessField(field_descriptor);
cpp_nested_type_[descriptor] += " " +
cpp_field_type_[field_descriptor] +
" const " +
field_descriptor->name() + ";\n";
// This this field has a size, generate it now.
if (size_field_.find(field_descriptor) != size_field_.end()) {
cpp_nested_type_[descriptor] += " int const " +
size_field_[field_descriptor] + ";\n";
}
}
cpp_nested_type_[descriptor] += " };\n";
}
void Generator::ProcessReturn(Descriptor const* descriptor) {
CHECK_EQ(1, descriptor->field_count())
<< descriptor->full_name() << " must have exactly one field";
FieldDescriptor const* field_descriptor = descriptor->field(0);
ProcessField(field_descriptor);
cpp_nested_type_[descriptor] =
" using Return = " + cpp_field_type_[field_descriptor] + ";\n";
}
void Generator::ProcessMethodExtension(Descriptor const* descriptor) {
bool has_in = false;
bool has_out = false;
bool has_return = false;
// Do a first pass to determine which fields are in-out. The data produced
// here will be overwritten by the next pass.
std::vector<FieldDescriptor const*> field_descriptors;
for (int i = 0; i < descriptor->nested_type_count(); ++i) {
Descriptor const* nested_descriptor = descriptor->nested_type(i);
const std::string& nested_name = nested_descriptor->name();
if (nested_name == kIn) {
has_in = true;
ProcessInOut(nested_descriptor, &field_descriptors);
} else if (nested_name == kOut) {
has_out = true;
ProcessInOut(nested_descriptor, &field_descriptors);
} else if (nested_name == kReturn) {
has_return = true;
} else {
LOG(FATAL) << "Unexpected nested message "
<< nested_descriptor->full_name();
}
}
// Now mark the fields that have the same name in In and Out as in-out.
if (has_in || has_out) {
std::sort(field_descriptors.begin(),
field_descriptors.end(),
[](FieldDescriptor const* left,
FieldDescriptor const* right) {
return left->name() < right->name();
});
for (int i = 0; i < field_descriptors.size() - 1; ++i) {
if (field_descriptors[i]->name() == field_descriptors[i + 1]->name()) {
in_out_field_.insert(field_descriptors[i]);
in_out_field_.insert(field_descriptors[i + 1]);
}
}
}
// The second pass that produces the actual output.
cpp_method_type_[descriptor] = "struct " + descriptor->name() + " {\n";
for (int i = 0; i < descriptor->nested_type_count(); ++i) {
Descriptor const* nested_descriptor = descriptor->nested_type(i);
const std::string& nested_name = nested_descriptor->name();
if (nested_name == kIn) {
ProcessInOut(nested_descriptor, /*field_descriptors=*/nullptr);
} else if (nested_name == kOut) {
ProcessInOut(nested_descriptor, /*field_descriptors=*/nullptr);
} else if (nested_name == kReturn) {
ProcessReturn(nested_descriptor);
}
cpp_method_type_[descriptor] += cpp_nested_type_[nested_descriptor];
}
if (has_in || has_out || has_return) {
cpp_method_type_[descriptor] += "\n";
}
cpp_method_type_[descriptor] +=
std::string(" using Message = serialization::") +
descriptor->name() + ";\n";
if (has_in) {
cpp_method_type_[descriptor] += " static void Generator::Fill(In const& in, "
"not_null<Message*> const message);\n";
}
if (has_out) {
cpp_method_type_[descriptor] += " static void Generator::Fill(Out const& out, "
"not_null<Message*> const message);\n";
}
if (has_return) {
cpp_method_type_[descriptor] += " static void Generator::Fill("
"Return const& result, "
"not_null<Message*> const message);\n";
}
cpp_method_type_[descriptor] += " static void Generator::Run("
"Message const& message,\n"
" not_null<"
"Player::PointerMap*> const pointer_map);"
"\n";
cpp_method_type_[descriptor] += "};\n\n";
}
} // namespace
void GenerateProfiles() {
Generator generator;
generator.ProcessMethods();
// Now write the output.
std::experimental::filesystem::path const directory =
SOLUTION_DIR / "journal";
std::ofstream profiles_hpp(directory / "profiles.hpp");
CHECK(profiles_hpp.good());
profiles_hpp << "#pragma once\n";
profiles_hpp << "\n";
profiles_hpp << "#include \"base/not_null.hpp\"\n";
profiles_hpp << "#include \"journal/player.hpp\"\n";
profiles_hpp << "#include \"ksp_plugin/interface.hpp\"\n";
profiles_hpp << "#include \"serialization/journal.pb.h\"\n";
profiles_hpp << "\n";
profiles_hpp << "namespace principia {\n";
profiles_hpp << "\n";
profiles_hpp << "using base::not_null;\n";
profiles_hpp << "using ksp_plugin::KSPPart;\n";
profiles_hpp << "using ksp_plugin::LineAndIterator;\n";
profiles_hpp << "using ksp_plugin::NavigationFrame;\n";
profiles_hpp << "using ksp_plugin::Plugin;\n";
profiles_hpp << "using ksp_plugin::QP;\n";
profiles_hpp << "using ksp_plugin::WXYZ;\n";
profiles_hpp << "using ksp_plugin::XYZ;\n";
profiles_hpp << "using ksp_plugin::XYZSegment;\n";
profiles_hpp << "\n";
profiles_hpp << "namespace journal {\n";
profiles_hpp << "\n";
for (auto const& cpp_method_type : generator.GetCppMethodTypes()) {
profiles_hpp << cpp_method_type;
}
profiles_hpp << "} // namespace journal\n";
profiles_hpp << "} // namespace principia\n";
}
} // namespace tools
} // namespace principia
<commit_msg>Cleanup.<commit_after>#include <experimental/filesystem>
#include <fstream>
#include <string>
#include <vector>
#include "glog/logging.h"
#include "google/protobuf/descriptor.h"
#include "serialization/journal.pb.h"
namespace principia {
using ::google::protobuf::Descriptor;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::FieldOptions;
using ::google::protobuf::FileDescriptor;
namespace tools {
namespace {
char const kIn[] = "In";
char const kReturn[] = "Return";
char const kOut[] = "Out";
class Generator {
public:
void ProcessMethods();
std::vector<std::string> GetCppMethodTypes() const;
private:
void ProcessRepeatedMessageField(FieldDescriptor const* descriptor);
void ProcessOptionalInt32Field(FieldDescriptor const* descriptor);
void ProcessRequiredFixed64Field(FieldDescriptor const* descriptor);
void ProcessRequiredMessageField(FieldDescriptor const* descriptor);
void ProcessRequiredBoolField(FieldDescriptor const* descriptor);
void ProcessRequiredDoubleField(FieldDescriptor const* descriptor);
void ProcessRequiredInt32Field(FieldDescriptor const* descriptor);
void ProcessSingleStringField(FieldDescriptor const* descriptor);
void ProcessOptionalField(FieldDescriptor const* descriptor);
void ProcessRepeatedField(FieldDescriptor const* descriptor);
void ProcessRequiredField(FieldDescriptor const* descriptor);
void ProcessField(FieldDescriptor const* descriptor);
void ProcessInOut(Descriptor const* descriptor,
std::vector<FieldDescriptor const*>* field_descriptors);
void ProcessReturn(Descriptor const* descriptor);
void ProcessMethodExtension(Descriptor const* descriptor);
private:
std::map<Descriptor const*, std::string> cpp_method_type_;
std::map<FieldDescriptor const*, std::string> size_field_;
std::set<FieldDescriptor const*> in_out_field_;
std::map<Descriptor const*, std::string> cpp_nested_type_;
std::map<FieldDescriptor const*, std::string> cpp_field_type_;
};
void Generator::ProcessMethods() {
// Get the file containing |Method|.
Descriptor const* method_descriptor = serialization::Method::descriptor();
FileDescriptor const* file_descriptor = method_descriptor->file();
// Process all the messages in that file.
for (int i = 0; i < file_descriptor->message_type_count(); ++i) {
Descriptor const* message_descriptor = file_descriptor->message_type(i);
switch (message_descriptor->extension_count()) {
case 0: {
// An auxiliary message that is not an extension. Nothing to do.
break;
}
case 1: {
// An extension. Check that it extends |Method|.
FieldDescriptor const* extension = message_descriptor->extension(0);
CHECK(extension->is_extension());
Descriptor const* containing_type = extension->containing_type();
CHECK_EQ(method_descriptor, containing_type)
<< message_descriptor->name() << " extends a message other than "
<< method_descriptor->name() << ": " << containing_type->name();
ProcessMethodExtension(message_descriptor);
break;
}
default: {
LOG(FATAL) << message_descriptor->name() << " has "
<< message_descriptor->extension_count() << " extensions";
}
}
}
}
std::vector<std::string> Generator::GetCppMethodTypes() const {
std::vector<std::string> result;
for (auto const& pair : cpp_method_type_) {
result.push_back(pair.second);
}
return result;
}
void Generator::ProcessRepeatedMessageField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->message_type()->name() +
" const*";
}
void Generator::ProcessOptionalInt32Field(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = "int const*";
}
void Generator::ProcessRequiredFixed64Field(FieldDescriptor const* descriptor) {
FieldOptions const& options = descriptor->options();
CHECK(options.HasExtension(serialization::pointer_to))
<< descriptor->full_name() << " is missing a pointer_to option";
std::string const& pointer_to =
options.GetExtension(serialization::pointer_to);
cpp_field_type_[descriptor] = pointer_to + "*";
}
void Generator::ProcessRequiredMessageField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->message_type()->name();
}
void Generator::ProcessRequiredBoolField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->cpp_type_name();
}
void Generator::ProcessRequiredDoubleField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = descriptor->cpp_type_name();
}
void Generator::ProcessRequiredInt32Field(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = "int";
}
void Generator::ProcessSingleStringField(FieldDescriptor const* descriptor) {
cpp_field_type_[descriptor] = "char const*";
}
void Generator::ProcessOptionalField(FieldDescriptor const* descriptor) {
switch (descriptor->type()) {
case FieldDescriptor::TYPE_INT32:
ProcessOptionalInt32Field(descriptor);
break;
case FieldDescriptor::TYPE_STRING:
ProcessSingleStringField(descriptor);
break;
default:
LOG(FATAL) << descriptor->full_name() << " has unexpected type "
<< descriptor->type_name();
}
}
void Generator::ProcessRepeatedField(FieldDescriptor const* descriptor) {
switch (descriptor->type()) {
case FieldDescriptor::TYPE_MESSAGE:
ProcessRepeatedMessageField(descriptor);
break;
default:
LOG(FATAL) << descriptor->full_name() << " has unexpected type "
<< descriptor->type_name();
}
}
void Generator::ProcessRequiredField(FieldDescriptor const* descriptor) {
switch (descriptor->type()) {
case FieldDescriptor::TYPE_BOOL:
ProcessRequiredBoolField(descriptor);
break;
case FieldDescriptor::TYPE_DOUBLE:
ProcessRequiredDoubleField(descriptor);
break;
case FieldDescriptor::TYPE_FIXED64:
ProcessRequiredFixed64Field(descriptor);
break;
case FieldDescriptor::TYPE_INT32:
ProcessRequiredInt32Field(descriptor);
break;
case FieldDescriptor::TYPE_MESSAGE:
ProcessRequiredMessageField(descriptor);
break;
case FieldDescriptor::TYPE_STRING:
ProcessSingleStringField(descriptor);
break;
default:
LOG(FATAL) << descriptor->full_name() << " has unexpected type "
<< descriptor->type_name();
}
// For in-out fields the data is actually passed with an extra level of
// indirection.
if (in_out_field_.find(descriptor) != in_out_field_.end()) {
cpp_field_type_[descriptor] += "*";
}
}
void Generator::ProcessField(FieldDescriptor const* descriptor) {
switch (descriptor->label()) {
case FieldDescriptor::LABEL_OPTIONAL:
ProcessOptionalField(descriptor);
break;
case FieldDescriptor::LABEL_REPEATED:
ProcessRepeatedField(descriptor);
break;
case FieldDescriptor::LABEL_REQUIRED:
ProcessRequiredField(descriptor);
break;
}
FieldOptions const& options = descriptor->options();
if (options.HasExtension(serialization::size)) {
size_field_[descriptor] = options.GetExtension(serialization::size);
}
}
void Generator::ProcessInOut(Descriptor const* descriptor,
std::vector<FieldDescriptor const*>* field_descriptors) {
cpp_nested_type_[descriptor] = " struct " + descriptor->name() + " {\n";
for (int i = 0; i < descriptor->field_count(); ++i) {
FieldDescriptor const* field_descriptor = descriptor->field(i);
if (field_descriptors != nullptr) {
field_descriptors->push_back(field_descriptor);
}
ProcessField(field_descriptor);
cpp_nested_type_[descriptor] += " " +
cpp_field_type_[field_descriptor] +
" const " +
field_descriptor->name() + ";\n";
// This this field has a size, generate it now.
if (size_field_.find(field_descriptor) != size_field_.end()) {
cpp_nested_type_[descriptor] += " int const " +
size_field_[field_descriptor] + ";\n";
}
}
cpp_nested_type_[descriptor] += " };\n";
}
void Generator::ProcessReturn(Descriptor const* descriptor) {
CHECK_EQ(1, descriptor->field_count())
<< descriptor->full_name() << " must have exactly one field";
FieldDescriptor const* field_descriptor = descriptor->field(0);
ProcessField(field_descriptor);
cpp_nested_type_[descriptor] =
" using Return = " + cpp_field_type_[field_descriptor] + ";\n";
}
void Generator::ProcessMethodExtension(Descriptor const* descriptor) {
bool has_in = false;
bool has_out = false;
bool has_return = false;
// Do a first pass to determine which fields are in-out. The data produced
// here will be overwritten by the next pass.
std::vector<FieldDescriptor const*> field_descriptors;
for (int i = 0; i < descriptor->nested_type_count(); ++i) {
Descriptor const* nested_descriptor = descriptor->nested_type(i);
const std::string& nested_name = nested_descriptor->name();
if (nested_name == kIn) {
has_in = true;
ProcessInOut(nested_descriptor, &field_descriptors);
} else if (nested_name == kOut) {
has_out = true;
ProcessInOut(nested_descriptor, &field_descriptors);
} else if (nested_name == kReturn) {
has_return = true;
} else {
LOG(FATAL) << "Unexpected nested message "
<< nested_descriptor->full_name();
}
}
// Now mark the fields that have the same name in In and Out as in-out.
if (has_in || has_out) {
std::sort(field_descriptors.begin(),
field_descriptors.end(),
[](FieldDescriptor const* left,
FieldDescriptor const* right) {
return left->name() < right->name();
});
for (int i = 0; i < field_descriptors.size() - 1; ++i) {
if (field_descriptors[i]->name() == field_descriptors[i + 1]->name()) {
in_out_field_.insert(field_descriptors[i]);
in_out_field_.insert(field_descriptors[i + 1]);
}
}
}
// The second pass that produces the actual output.
cpp_method_type_[descriptor] = "struct " + descriptor->name() + " {\n";
for (int i = 0; i < descriptor->nested_type_count(); ++i) {
Descriptor const* nested_descriptor = descriptor->nested_type(i);
const std::string& nested_name = nested_descriptor->name();
if (nested_name == kIn) {
ProcessInOut(nested_descriptor, /*field_descriptors=*/nullptr);
} else if (nested_name == kOut) {
ProcessInOut(nested_descriptor, /*field_descriptors=*/nullptr);
} else if (nested_name == kReturn) {
ProcessReturn(nested_descriptor);
}
cpp_method_type_[descriptor] += cpp_nested_type_[nested_descriptor];
}
if (has_in || has_out || has_return) {
cpp_method_type_[descriptor] += "\n";
}
cpp_method_type_[descriptor] +=
" using Message = serialization::" +
descriptor->name() + ";\n";
if (has_in) {
cpp_method_type_[descriptor] += " static void Fill(In const& in, "
"not_null<Message*> const message);\n";
}
if (has_out) {
cpp_method_type_[descriptor] += " static void Fill(Out const& out, "
"not_null<Message*> const message);\n";
}
if (has_return) {
cpp_method_type_[descriptor] += " static void Fill("
"Return const& result, "
"not_null<Message*> const message);\n";
}
cpp_method_type_[descriptor] += " static void Run("
"Message const& message,\n"
" not_null<"
"Player::PointerMap*> const pointer_map);"
"\n";
cpp_method_type_[descriptor] += "};\n\n";
}
} // namespace
void GenerateProfiles() {
Generator generator;
generator.ProcessMethods();
// Now write the output.
std::experimental::filesystem::path const directory =
SOLUTION_DIR / "journal";
std::ofstream profiles_hpp(directory / "profiles.hpp");
CHECK(profiles_hpp.good());
profiles_hpp << "#pragma once\n";
profiles_hpp << "\n";
profiles_hpp << "#include \"base/not_null.hpp\"\n";
profiles_hpp << "#include \"journal/player.hpp\"\n";
profiles_hpp << "#include \"ksp_plugin/interface.hpp\"\n";
profiles_hpp << "#include \"serialization/journal.pb.h\"\n";
profiles_hpp << "\n";
profiles_hpp << "namespace principia {\n";
profiles_hpp << "\n";
profiles_hpp << "using base::not_null;\n";
profiles_hpp << "using ksp_plugin::KSPPart;\n";
profiles_hpp << "using ksp_plugin::LineAndIterator;\n";
profiles_hpp << "using ksp_plugin::NavigationFrame;\n";
profiles_hpp << "using ksp_plugin::Plugin;\n";
profiles_hpp << "using ksp_plugin::QP;\n";
profiles_hpp << "using ksp_plugin::WXYZ;\n";
profiles_hpp << "using ksp_plugin::XYZ;\n";
profiles_hpp << "using ksp_plugin::XYZSegment;\n";
profiles_hpp << "\n";
profiles_hpp << "namespace journal {\n";
profiles_hpp << "\n";
for (auto const& cpp_method_type : generator.GetCppMethodTypes()) {
profiles_hpp << cpp_method_type;
}
profiles_hpp << "} // namespace journal\n";
profiles_hpp << "} // namespace principia\n";
}
} // namespace tools
} // namespace principia
<|endoftext|> |
<commit_before>#include "includes.h"
#include "spdlog/sinks/dup_filter_sink.h"
#include "test_sink.h"
using namespace spdlog;
using namespace spdlog::sinks;
TEST_CASE("dup_filter_test1", "[dup_filter_sink]")
{
dup_filter_sink_st dup_sink{std::chrono::seconds{5}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
for (int i = 0; i < 10; i++)
{
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
}
REQUIRE(test_sink->msg_counter() == 1);
}
TEST_CASE("dup_filter_test2", "[dup_filter_sink]")
{
dup_filter_sink_st dup_sink{std::chrono::seconds{0}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
for (int i = 0; i < 10; i++)
{
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
REQUIRE(test_sink->msg_counter() == 10);
}
TEST_CASE("dup_filter_test3", "[dup_filter_sink]")
{
dup_filter_sink_st dup_sink{std::chrono::seconds{0}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
for (int i = 0; i < 10; i++)
{
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message2"});
}
REQUIRE(test_sink->msg_counter() == 20);
}
TEST_CASE("dup_filter_test4", "[dup_filter_sink]")
{
dup_filter_sink_mt dup_sink{std::chrono::milliseconds{10}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message"});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message"});
REQUIRE(test_sink->msg_counter() == 2);
}
TEST_CASE("dup_filter_test5", "[dup_filter_sink]")
{
dup_filter_sink_mt dup_sink{std::chrono::seconds{5}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message2"});
REQUIRE(test_sink->msg_counter() == 3); // skip 2 messages but log the "skipped.." message before message2
}
<commit_msg>Fixed dup_filter test<commit_after>#include "includes.h"
#include "spdlog/sinks/dup_filter_sink.h"
#include "test_sink.h"
using namespace spdlog;
using namespace spdlog::sinks;
TEST_CASE("dup_filter_test1", "[dup_filter_sink]")
{
dup_filter_sink_st dup_sink{std::chrono::seconds{5}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
for (int i = 0; i < 10; i++)
{
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
}
REQUIRE(test_sink->msg_counter() == 1);
}
TEST_CASE("dup_filter_test2", "[dup_filter_sink]")
{
dup_filter_sink_st dup_sink{std::chrono::seconds{0}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
for (int i = 0; i < 10; i++)
{
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
REQUIRE(test_sink->msg_counter() == 10);
}
TEST_CASE("dup_filter_test3", "[dup_filter_sink]")
{
dup_filter_sink_st dup_sink{std::chrono::seconds{1}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
for (int i = 0; i < 10; i++)
{
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message2"});
}
REQUIRE(test_sink->msg_counter() == 20);
}
TEST_CASE("dup_filter_test4", "[dup_filter_sink]")
{
dup_filter_sink_mt dup_sink{std::chrono::milliseconds{10}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message"});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message"});
REQUIRE(test_sink->msg_counter() == 2);
}
TEST_CASE("dup_filter_test5", "[dup_filter_sink]")
{
dup_filter_sink_mt dup_sink{std::chrono::seconds{5}};
auto test_sink = std::make_shared<test_sink_mt>();
dup_sink.add_sink(test_sink);
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
dup_sink.log(spdlog::details::log_msg{"test", spdlog::level::info, "message2"});
REQUIRE(test_sink->msg_counter() == 3); // skip 2 messages but log the "skipped.." message before message2
}
<|endoftext|> |
<commit_before>#ifndef GUI_PROCESS_HPP
#define GUI_PROCESS_HPP
class wxWindow;
class wxString;
namespace Slic3r {
namespace GUI {
// Start a new slicer instance, optionally with a file to open.
void start_new_slicer(const wxString *path_to_open = nullptr, bool single_instance = false);
void start_new_slicer(const std::vector<wxString>& files, bool single_instance = false);
// Start a new G-code viewer instance, optionally with a file to open.
void start_new_gcodeviewer(const wxString *path_to_open = nullptr);
// Open a file dialog, ask the user to select a new G-code to open, start a new G-code viewer.
void start_new_gcodeviewer_open_file(wxWindow *parent = nullptr);
} // namespace GUI
} // namespace Slic3r
#endif // GUI_PROCESS_HPP
<commit_msg>Added a missing include<commit_after>#ifndef GUI_PROCESS_HPP
#define GUI_PROCESS_HPP
#include <vector>
class wxWindow;
class wxString;
namespace Slic3r {
namespace GUI {
// Start a new slicer instance, optionally with a file to open.
void start_new_slicer(const wxString *path_to_open = nullptr, bool single_instance = false);
void start_new_slicer(const std::vector<wxString>& files, bool single_instance = false);
// Start a new G-code viewer instance, optionally with a file to open.
void start_new_gcodeviewer(const wxString *path_to_open = nullptr);
// Open a file dialog, ask the user to select a new G-code to open, start a new G-code viewer.
void start_new_gcodeviewer_open_file(wxWindow *parent = nullptr);
} // namespace GUI
} // namespace Slic3r
#endif // GUI_PROCESS_HPP
<|endoftext|> |
<commit_before>// timer.cpp
// 30. April 2017
// Created by:
// Bryan Burkhardt ([email protected])
// Alexander Eckert ([email protected])
// Jeremiah Jacobson ([email protected])
// Jarye Murphy ([email protected])
// Cameron Showalter ([email protected])
//
// Source file for timer
#include <iomanip>
#include "../include/timer.hpp"
/****** Timer Functions ******/
void Timer::updateTimer() {
/****** Current Timer Stuff ******/
currentTimer = music->_music.getPlayingOffset();
currentTimeSeconds = (int)currentTimer.asSeconds();
currentTimeMinutes = convertToMinutes((int)currentTimer.asSeconds());
currentTimeHours = convertToHours((int) currentTimeSeconds);
currentTimerStreamSeconds.str("");
currentTimerStreamMinutes.str("");
currentTimerStreamHours.str("");
currentTimerStreamSeconds << std::fixed << std::setprecision(0) << (int) currentTimeSeconds % 60;
currentTimerStreamMinutes << std::fixed << std::setprecision(0) << ((int)currentTimeMinutes%60);
currentTimerStreamHours << std::fixed << std::setprecision(0) << (currentTimeHours);
/****** Total Timer Stuff ******/
totalTimer = music->_music.getDuration();
totalTimeSeconds = (int)totalTimer.asSeconds();
totalTimeMinutes = convertToMinutes((int) totalTimeSeconds);
totalTimeHours = convertToHours((int) totalTimeSeconds);
totalTimerStreamSeconds.str("");
totalTimerStreamMinutes.str("");
totalTimerStreamHours.str("");
totalTimerStreamSeconds << std::fixed << std::setprecision(0) << (int) totalTimeSeconds % 60;
totalTimerStreamMinutes << std::fixed << std::setprecision(0) << ((int)totalTimeMinutes%60);
totalTimerStreamHours << std::fixed << std::setprecision(0) << (totalTimeHours);
// Seconds
if ((int)currentTimeSeconds%60 < 10) {
currentSec = "0" + currentTimerStreamSeconds.str() + "/";
}
else {
currentSec = currentTimerStreamSeconds.str() + "/";
}
if((int)totalTimeSeconds%60 < 10) {
totalSec = "0" + totalTimerStreamSeconds.str();
}
else {
totalSec = totalTimerStreamSeconds.str();
}
// Minutes
if((int)currentTimeMinutes%60 < 10 && (int)totalTimeMinutes < 10 && (int)totalTimeHours < 1) {
currentMin = currentTimerStreamMinutes.str() + ":";
totalMin = totalTimerStreamMinutes.str() + ":";
}
else if((int)currentTimeMinutes%60 < 10 && (int)totalTimeMinutes > 9 && (int)totalTimeHours < 1) {
currentMin = "0" + currentTimerStreamMinutes.str() + ":";
totalMin = totalTimerStreamMinutes.str() + ":";
}
else if((int)currentTimeMinutes%60 < 10 && (int)totalTimeHours > 0) {
currentMin = "0" + currentTimerStreamMinutes.str() + ":";
totalMin = "0" + totalTimerStreamMinutes.str() + ":";
}
else {
currentMin = currentTimerStreamMinutes.str() + ":";
totalMin = totalTimerStreamMinutes.str() + ":";
}
// Hours
currentHour = currentTimerStreamHours.str() + ":";
totalHour = totalTimerStreamHours.str() + ":";
}
std::string Timer::selectDisplayTimer() {
std::string rv = "";
if(music->_music.getStatus() == 0) {
music->callNextSong();
}
// 0:xx
if(totalTimeMinutes < 1) {
rv = "0:";
rv += currentSec + "0:";
rv += totalSec;
return rv;
}
// xx:xx
else if(currentTimeHours < 1 && totalTimeHours < 1 && totalTimeMinutes > 1) {
return currentMin + currentSec + totalMin + totalSec;
}
// xx:xx:xx
else {
return currentHour + currentMin + currentSec + totalHour + totalMin + totalSec;
}
}
void Timer::displayTimer() {
updateTimer();
selectDisplayTimer();
}
int Timer::convertToMinutes(int seconds) {
return seconds/60;
}
int Timer::convertToHours(int seconds) {
return (seconds/(60*60));
}
Timer::Timer(std::shared_ptr<Music> music) : music(music) {
}<commit_msg>fixed timer bug<commit_after>// timer.cpp
// 30. April 2017
// Created by:
// Bryan Burkhardt ([email protected])
// Alexander Eckert ([email protected])
// Jeremiah Jacobson ([email protected])
// Jarye Murphy ([email protected])
// Cameron Showalter ([email protected])
//
// Source file for timer
#include <iomanip>
#include "../include/timer.hpp"
/****** Timer Functions ******/
void Timer::updateTimer() {
/****** Current Timer Stuff ******/
currentTimer = music->_music.getPlayingOffset();
currentTimeSeconds = (int)currentTimer.asSeconds();
currentTimeMinutes = convertToMinutes((int)currentTimer.asSeconds());
currentTimeHours = convertToHours((int) currentTimeSeconds);
currentTimerStreamSeconds.str("");
currentTimerStreamMinutes.str("");
currentTimerStreamHours.str("");
currentTimerStreamSeconds << std::fixed << std::setprecision(0) << (int) currentTimeSeconds % 60;
currentTimerStreamMinutes << std::fixed << std::setprecision(0) << ((int)currentTimeMinutes%60);
currentTimerStreamHours << std::fixed << std::setprecision(0) << (currentTimeHours);
/****** Total Timer Stuff ******/
totalTimer = music->_music.getDuration();
totalTimeSeconds = (int)totalTimer.asSeconds();
totalTimeMinutes = convertToMinutes((int) totalTimeSeconds);
totalTimeHours = convertToHours((int) totalTimeSeconds);
totalTimerStreamSeconds.str("");
totalTimerStreamMinutes.str("");
totalTimerStreamHours.str("");
totalTimerStreamSeconds << std::fixed << std::setprecision(0) << (int) totalTimeSeconds % 60;
totalTimerStreamMinutes << std::fixed << std::setprecision(0) << ((int)totalTimeMinutes%60);
totalTimerStreamHours << std::fixed << std::setprecision(0) << (totalTimeHours);
// Seconds
if ((int)currentTimeSeconds%60 < 10) {
currentSec = "0" + currentTimerStreamSeconds.str() + "/";
}
else {
currentSec = currentTimerStreamSeconds.str() + "/";
}
if((int)totalTimeSeconds%60 < 10) {
totalSec = "0" + totalTimerStreamSeconds.str();
}
else {
totalSec = totalTimerStreamSeconds.str();
}
// Minutes
if((int)currentTimeMinutes%60 < 10 && (int)totalTimeMinutes < 10 && (int)totalTimeHours < 1) {
currentMin = currentTimerStreamMinutes.str() + ":";
totalMin = totalTimerStreamMinutes.str() + ":";
}
else if((int)currentTimeMinutes%60 < 10 && (int)totalTimeMinutes > 9 && (int)totalTimeHours < 1) {
currentMin = "0" + currentTimerStreamMinutes.str() + ":";
totalMin = totalTimerStreamMinutes.str() + ":";
}
else if((int)currentTimeMinutes%60 < 10 && (int)totalTimeMinutes%60 < 10 && (int)totalTimeHours > 0) {
currentMin = "0" + currentTimerStreamMinutes.str() + ":";
totalMin = "0" + totalTimerStreamMinutes.str() + ":";
}
else {
currentMin = currentTimerStreamMinutes.str() + ":";
totalMin = totalTimerStreamMinutes.str() + ":";
}
// Hours
currentHour = currentTimerStreamHours.str() + ":";
totalHour = totalTimerStreamHours.str() + ":";
}
std::string Timer::selectDisplayTimer() {
std::string rv = "";
if(music->_music.getStatus() == 0) {
music->callNextSong();
}
// 0:xx
if(totalTimeMinutes < 1) {
rv = "0:";
rv += currentSec + "0:";
rv += totalSec;
return rv;
}
// xx:xx
else if(currentTimeHours < 1 && totalTimeHours < 1 && totalTimeMinutes > 1) {
return currentMin + currentSec + totalMin + totalSec;
}
// xx:xx:xx
else {
return currentHour + currentMin + currentSec + totalHour + totalMin + totalSec;
}
}
void Timer::displayTimer() {
updateTimer();
selectDisplayTimer();
}
int Timer::convertToMinutes(int seconds) {
return seconds/60;
}
int Timer::convertToHours(int seconds) {
return (seconds/(60*60));
}
Timer::Timer(std::shared_ptr<Music> music) : music(music) {
}<|endoftext|> |
<commit_before>
#if !defined(MAX_TIMERS)
#define MAX_TIMERS MAX_WORKER_THREADS
#endif
typedef int (*taction)(void *arg);
struct ttimer {
double time;
double period;
taction action;
void *arg;
};
struct ttimers {
pthread_t threadid; /* Timer thread ID */
pthread_mutex_t mutex; /* Protects timer lists */
struct ttimer timers[MAX_TIMERS]; /* List of timers */
unsigned timer_count; /* Current size of timer list */
};
static double
timer_getcurrenttime(void)
{
#if defined(_WIN32)
/* GetTickCount returns milliseconds since system start as
* unsigned 32 bit value. It will wrap around every 49.7 days.
* We need to use a 64 bit counter (will wrap in 500 mio. years),
* by adding the 32 bit difference since the last call to a
* 64 bit counter. This algorithm will only work, if this
* function is called at least once every 7 weeks. */
static DWORD last_tick;
static uint64_t now_tick64;
DWORD now_tick = GetTickCount();
now_tick64 += ((DWORD)(now_tick - last_tick));
last_tick = now_tick;
return (double)now_tick64 * 1.0E-3;
#else
struct timespec now_ts;
clock_gettime(CLOCK_MONOTONIC, &now);
return (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
#endif
}
static int
timer_add(struct mg_context *ctx,
double next_time,
double period,
int is_relative,
taction action,
void *arg)
{
unsigned u, v;
int error = 0;
double now;
if (ctx->stop_flag) {
return 0;
}
now = timer_getcurrenttime();
/* HCP24: if is_relative = 0 and next_time < now
* action will be called so fast as possible
* if additional period > 0
* action will be called so fast as possible
* n times until (next_time + (n * period)) > now
* then the period is working
* Solution:
* if next_time < now then we set next_time = now.
* The first callback will be so fast as possible (now)
* but the next callback on period
*/
if (is_relative) {
next_time += now;
}
/* You can not set timers into the past */
if (next_time < now) {
next_time = now;
}
pthread_mutex_lock(&ctx->timers->mutex);
if (ctx->timers->timer_count == MAX_TIMERS) {
error = 1;
} else {
/* Insert new timer into a sorted list. */
/* The linear list is still most efficient for short lists (small
* number of timers) - if there are many timers, different
* algorithms will work better. */
for (u = 0; u < ctx->timers->timer_count; u++) {
if (ctx->timers->timers[u].time > next_time) {
/* HCP24: moving all timers > next_time */
for (v = ctx->timers->timer_count; v > u; v--) {
ctx->timers->timers[v] = ctx->timers->timers[v - 1];
}
break;
}
}
ctx->timers->timers[u].time = next_time;
ctx->timers->timers[u].period = period;
ctx->timers->timers[u].action = action;
ctx->timers->timers[u].arg = arg;
ctx->timers->timer_count++;
}
pthread_mutex_unlock(&ctx->timers->mutex);
return error;
}
static void
timer_thread_run(void *thread_func_param)
{
struct mg_context *ctx = (struct mg_context *)thread_func_param;
double d;
unsigned u;
int re_schedule;
struct ttimer t;
mg_set_thread_name("timer");
if (ctx->callbacks.init_thread) {
/* Timer thread */
ctx->callbacks.init_thread(ctx, 2);
}
d = timer_getcurrenttime();
while (ctx->stop_flag == 0) {
pthread_mutex_lock(&ctx->timers->mutex);
if ((ctx->timers->timer_count > 0)
&& (d >= ctx->timers->timers[0].time)) {
t = ctx->timers->timers[0];
for (u = 1; u < ctx->timers->timer_count; u++) {
ctx->timers->timers[u - 1] = ctx->timers->timers[u];
}
ctx->timers->timer_count--;
pthread_mutex_unlock(&ctx->timers->mutex);
re_schedule = t.action(t.arg);
if (re_schedule && (t.period > 0)) {
timer_add(ctx, t.time + t.period, t.period, 0, t.action, t.arg);
}
continue;
} else {
pthread_mutex_unlock(&ctx->timers->mutex);
}
/* 10 ms seems reasonable.
* A faster loop (smaller sleep value) increases CPU load,
* a slower loop (higher sleep value) decreases timer accuracy.
*/
#ifdef _WIN32
Sleep(10);
#else
usleep(10000);
#endif
d = timer_getcurrenttime();
}
ctx->timers->timer_count = 0;
}
#ifdef _WIN32
static unsigned __stdcall timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return 0;
}
#else
static void *
timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return NULL;
}
#endif /* _WIN32 */
static int
timers_init(struct mg_context *ctx)
{
ctx->timers = (struct ttimers *)mg_calloc(sizeof(struct ttimers), 1);
(void)pthread_mutex_init(&ctx->timers->mutex, NULL);
(void)timer_getcurrenttime();
/* Start timer thread */
mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
return 0;
}
static void
timers_exit(struct mg_context *ctx)
{
if (ctx->timers) {
pthread_mutex_lock(&ctx->timers->mutex);
ctx->timers->timer_count = 0;
(void)pthread_mutex_destroy(&ctx->timers->mutex);
mg_free(ctx->timers);
}
}
<commit_msg>Fix copy/paste error for Linux<commit_after>
#if !defined(MAX_TIMERS)
#define MAX_TIMERS MAX_WORKER_THREADS
#endif
typedef int (*taction)(void *arg);
struct ttimer {
double time;
double period;
taction action;
void *arg;
};
struct ttimers {
pthread_t threadid; /* Timer thread ID */
pthread_mutex_t mutex; /* Protects timer lists */
struct ttimer timers[MAX_TIMERS]; /* List of timers */
unsigned timer_count; /* Current size of timer list */
};
static double
timer_getcurrenttime(void)
{
#if defined(_WIN32)
/* GetTickCount returns milliseconds since system start as
* unsigned 32 bit value. It will wrap around every 49.7 days.
* We need to use a 64 bit counter (will wrap in 500 mio. years),
* by adding the 32 bit difference since the last call to a
* 64 bit counter. This algorithm will only work, if this
* function is called at least once every 7 weeks. */
static DWORD last_tick;
static uint64_t now_tick64;
DWORD now_tick = GetTickCount();
now_tick64 += ((DWORD)(now_tick - last_tick));
last_tick = now_tick;
return (double)now_tick64 * 1.0E-3;
#else
struct timespec now_ts;
clock_gettime(CLOCK_MONOTONIC, &now_ts);
return (double)now_ts.tv_sec + (double)now_ts.tv_nsec * 1.0E-9;
#endif
}
static int
timer_add(struct mg_context *ctx,
double next_time,
double period,
int is_relative,
taction action,
void *arg)
{
unsigned u, v;
int error = 0;
double now;
if (ctx->stop_flag) {
return 0;
}
now = timer_getcurrenttime();
/* HCP24: if is_relative = 0 and next_time < now
* action will be called so fast as possible
* if additional period > 0
* action will be called so fast as possible
* n times until (next_time + (n * period)) > now
* then the period is working
* Solution:
* if next_time < now then we set next_time = now.
* The first callback will be so fast as possible (now)
* but the next callback on period
*/
if (is_relative) {
next_time += now;
}
/* You can not set timers into the past */
if (next_time < now) {
next_time = now;
}
pthread_mutex_lock(&ctx->timers->mutex);
if (ctx->timers->timer_count == MAX_TIMERS) {
error = 1;
} else {
/* Insert new timer into a sorted list. */
/* The linear list is still most efficient for short lists (small
* number of timers) - if there are many timers, different
* algorithms will work better. */
for (u = 0; u < ctx->timers->timer_count; u++) {
if (ctx->timers->timers[u].time > next_time) {
/* HCP24: moving all timers > next_time */
for (v = ctx->timers->timer_count; v > u; v--) {
ctx->timers->timers[v] = ctx->timers->timers[v - 1];
}
break;
}
}
ctx->timers->timers[u].time = next_time;
ctx->timers->timers[u].period = period;
ctx->timers->timers[u].action = action;
ctx->timers->timers[u].arg = arg;
ctx->timers->timer_count++;
}
pthread_mutex_unlock(&ctx->timers->mutex);
return error;
}
static void
timer_thread_run(void *thread_func_param)
{
struct mg_context *ctx = (struct mg_context *)thread_func_param;
double d;
unsigned u;
int re_schedule;
struct ttimer t;
mg_set_thread_name("timer");
if (ctx->callbacks.init_thread) {
/* Timer thread */
ctx->callbacks.init_thread(ctx, 2);
}
d = timer_getcurrenttime();
while (ctx->stop_flag == 0) {
pthread_mutex_lock(&ctx->timers->mutex);
if ((ctx->timers->timer_count > 0)
&& (d >= ctx->timers->timers[0].time)) {
t = ctx->timers->timers[0];
for (u = 1; u < ctx->timers->timer_count; u++) {
ctx->timers->timers[u - 1] = ctx->timers->timers[u];
}
ctx->timers->timer_count--;
pthread_mutex_unlock(&ctx->timers->mutex);
re_schedule = t.action(t.arg);
if (re_schedule && (t.period > 0)) {
timer_add(ctx, t.time + t.period, t.period, 0, t.action, t.arg);
}
continue;
} else {
pthread_mutex_unlock(&ctx->timers->mutex);
}
/* 10 ms seems reasonable.
* A faster loop (smaller sleep value) increases CPU load,
* a slower loop (higher sleep value) decreases timer accuracy.
*/
#ifdef _WIN32
Sleep(10);
#else
usleep(10000);
#endif
d = timer_getcurrenttime();
}
ctx->timers->timer_count = 0;
}
#ifdef _WIN32
static unsigned __stdcall timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return 0;
}
#else
static void *
timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return NULL;
}
#endif /* _WIN32 */
static int
timers_init(struct mg_context *ctx)
{
ctx->timers = (struct ttimers *)mg_calloc(sizeof(struct ttimers), 1);
(void)pthread_mutex_init(&ctx->timers->mutex, NULL);
(void)timer_getcurrenttime();
/* Start timer thread */
mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
return 0;
}
static void
timers_exit(struct mg_context *ctx)
{
if (ctx->timers) {
pthread_mutex_lock(&ctx->timers->mutex);
ctx->timers->timer_count = 0;
(void)pthread_mutex_destroy(&ctx->timers->mutex);
mg_free(ctx->timers);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "vk/GrVkPipelineStateBuilder.h"
#include "vk/GrVkDescriptorSetManager.h"
#include "vk/GrVkGpu.h"
#include "vk/GrVkRenderPass.h"
GrVkPipelineState* GrVkPipelineStateBuilder::CreatePipelineState(
GrVkGpu* gpu,
const GrPipeline& pipeline,
const GrStencilSettings& stencil,
const GrPrimitiveProcessor& primProc,
GrPrimitiveType primitiveType,
const GrVkPipelineState::Desc& desc,
const GrVkRenderPass& renderPass) {
// create a builder. This will be handed off to effects so they can use it to add
// uniforms, varyings, textures, etc
GrVkPipelineStateBuilder builder(gpu, pipeline, primProc, desc);
GrGLSLExpr4 inputColor;
GrGLSLExpr4 inputCoverage;
if (!builder.emitAndInstallProcs(&inputColor, &inputCoverage)) {
builder.cleanupFragmentProcessors();
return nullptr;
}
return builder.finalize(stencil, primitiveType, renderPass, desc);
}
GrVkPipelineStateBuilder::GrVkPipelineStateBuilder(GrVkGpu* gpu,
const GrPipeline& pipeline,
const GrPrimitiveProcessor& primProc,
const GrProgramDesc& desc)
: INHERITED(pipeline, primProc, desc)
, fGpu(gpu)
, fVaryingHandler(this)
, fUniformHandler(this) {
}
const GrCaps* GrVkPipelineStateBuilder::caps() const {
return fGpu->caps();
}
const GrGLSLCaps* GrVkPipelineStateBuilder::glslCaps() const {
return fGpu->vkCaps().glslCaps();
}
void GrVkPipelineStateBuilder::finalizeFragmentOutputColor(GrGLSLShaderVar& outputColor) {
outputColor.setLayoutQualifier("location = 0, index = 0");
}
void GrVkPipelineStateBuilder::finalizeFragmentSecondaryColor(GrGLSLShaderVar& outputColor) {
outputColor.setLayoutQualifier("location = 0, index = 1");
}
bool GrVkPipelineStateBuilder::CreateVkShaderModule(const GrVkGpu* gpu,
VkShaderStageFlagBits stage,
const GrGLSLShaderBuilder& builder,
VkShaderModule* shaderModule,
VkPipelineShaderStageCreateInfo* stageInfo) {
SkString shaderString;
for (int i = 0; i < builder.fCompilerStrings.count(); ++i) {
if (builder.fCompilerStrings[i]) {
shaderString.append(builder.fCompilerStrings[i]);
shaderString.append("\n");
}
}
return GrCompileVkShaderModule(gpu, shaderString.c_str(), stage, shaderModule, stageInfo);
}
GrVkPipelineState* GrVkPipelineStateBuilder::finalize(const GrStencilSettings& stencil,
GrPrimitiveType primitiveType,
const GrVkRenderPass& renderPass,
const GrVkPipelineState::Desc& desc) {
VkDescriptorSetLayout dsLayout[2];
VkPipelineLayout pipelineLayout;
VkShaderModule vertShaderModule;
VkShaderModule fragShaderModule;
GrVkResourceProvider& resourceProvider = fGpu->resourceProvider();
// This layout is not owned by the PipelineStateBuilder and thus should no be destroyed
dsLayout[GrVkUniformHandler::kUniformBufferDescSet] = resourceProvider.getUniformDSLayout();
GrVkDescriptorSetManager::Handle samplerDSHandle;
resourceProvider.getSamplerDescriptorSetHandle(fUniformHandler, &samplerDSHandle);
dsLayout[GrVkUniformHandler::kSamplerDescSet] =
resourceProvider.getSamplerDSLayout(samplerDSHandle);
// Create the VkPipelineLayout
VkPipelineLayoutCreateInfo layoutCreateInfo;
memset(&layoutCreateInfo, 0, sizeof(VkPipelineLayoutCreateFlags));
layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
layoutCreateInfo.pNext = 0;
layoutCreateInfo.flags = 0;
layoutCreateInfo.setLayoutCount = 2;
layoutCreateInfo.pSetLayouts = dsLayout;
layoutCreateInfo.pushConstantRangeCount = 0;
layoutCreateInfo.pPushConstantRanges = nullptr;
GR_VK_CALL_ERRCHECK(fGpu->vkInterface(), CreatePipelineLayout(fGpu->device(),
&layoutCreateInfo,
nullptr,
&pipelineLayout));
// We need to enable the following extensions so that the compiler can correctly make spir-v
// from our glsl shaders.
fVS.extensions().appendf("#extension GL_ARB_separate_shader_objects : enable\n");
fFS.extensions().appendf("#extension GL_ARB_separate_shader_objects : enable\n");
fVS.extensions().appendf("#extension GL_ARB_shading_language_420pack : enable\n");
fFS.extensions().appendf("#extension GL_ARB_shading_language_420pack : enable\n");
this->finalizeShaders();
VkPipelineShaderStageCreateInfo shaderStageInfo[2];
SkAssertResult(CreateVkShaderModule(fGpu,
VK_SHADER_STAGE_VERTEX_BIT,
fVS,
&vertShaderModule,
&shaderStageInfo[0]));
SkAssertResult(CreateVkShaderModule(fGpu,
VK_SHADER_STAGE_FRAGMENT_BIT,
fFS,
&fragShaderModule,
&shaderStageInfo[1]));
GrVkPipeline* pipeline = resourceProvider.createPipeline(fPipeline,
stencil,
fPrimProc,
shaderStageInfo,
2,
primitiveType,
renderPass,
pipelineLayout);
GR_VK_CALL(fGpu->vkInterface(), DestroyShaderModule(fGpu->device(), vertShaderModule,
nullptr));
GR_VK_CALL(fGpu->vkInterface(), DestroyShaderModule(fGpu->device(), fragShaderModule,
nullptr));
if (!pipeline) {
GR_VK_CALL(fGpu->vkInterface(), DestroyPipelineLayout(fGpu->device(), pipelineLayout,
nullptr));
GR_VK_CALL(fGpu->vkInterface(),
DestroyDescriptorSetLayout(fGpu->device(),
dsLayout[GrVkUniformHandler::kSamplerDescSet],
nullptr));
this->cleanupFragmentProcessors();
return nullptr;
}
return new GrVkPipelineState(fGpu,
desc,
pipeline,
pipelineLayout,
samplerDSHandle,
fUniformHandles,
fUniformHandler.fUniforms,
fUniformHandler.fCurrentVertexUBOOffset,
fUniformHandler.fCurrentFragmentUBOOffset,
(uint32_t)fUniformHandler.numSamplers(),
fGeometryProcessor,
fXferProcessor,
fFragmentProcessors);
}
<commit_msg>Fix double deletion of DescriptorSetLayouts<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "vk/GrVkPipelineStateBuilder.h"
#include "vk/GrVkDescriptorSetManager.h"
#include "vk/GrVkGpu.h"
#include "vk/GrVkRenderPass.h"
GrVkPipelineState* GrVkPipelineStateBuilder::CreatePipelineState(
GrVkGpu* gpu,
const GrPipeline& pipeline,
const GrStencilSettings& stencil,
const GrPrimitiveProcessor& primProc,
GrPrimitiveType primitiveType,
const GrVkPipelineState::Desc& desc,
const GrVkRenderPass& renderPass) {
// create a builder. This will be handed off to effects so they can use it to add
// uniforms, varyings, textures, etc
GrVkPipelineStateBuilder builder(gpu, pipeline, primProc, desc);
GrGLSLExpr4 inputColor;
GrGLSLExpr4 inputCoverage;
if (!builder.emitAndInstallProcs(&inputColor, &inputCoverage)) {
builder.cleanupFragmentProcessors();
return nullptr;
}
return builder.finalize(stencil, primitiveType, renderPass, desc);
}
GrVkPipelineStateBuilder::GrVkPipelineStateBuilder(GrVkGpu* gpu,
const GrPipeline& pipeline,
const GrPrimitiveProcessor& primProc,
const GrProgramDesc& desc)
: INHERITED(pipeline, primProc, desc)
, fGpu(gpu)
, fVaryingHandler(this)
, fUniformHandler(this) {
}
const GrCaps* GrVkPipelineStateBuilder::caps() const {
return fGpu->caps();
}
const GrGLSLCaps* GrVkPipelineStateBuilder::glslCaps() const {
return fGpu->vkCaps().glslCaps();
}
void GrVkPipelineStateBuilder::finalizeFragmentOutputColor(GrGLSLShaderVar& outputColor) {
outputColor.setLayoutQualifier("location = 0, index = 0");
}
void GrVkPipelineStateBuilder::finalizeFragmentSecondaryColor(GrGLSLShaderVar& outputColor) {
outputColor.setLayoutQualifier("location = 0, index = 1");
}
bool GrVkPipelineStateBuilder::CreateVkShaderModule(const GrVkGpu* gpu,
VkShaderStageFlagBits stage,
const GrGLSLShaderBuilder& builder,
VkShaderModule* shaderModule,
VkPipelineShaderStageCreateInfo* stageInfo) {
SkString shaderString;
for (int i = 0; i < builder.fCompilerStrings.count(); ++i) {
if (builder.fCompilerStrings[i]) {
shaderString.append(builder.fCompilerStrings[i]);
shaderString.append("\n");
}
}
return GrCompileVkShaderModule(gpu, shaderString.c_str(), stage, shaderModule, stageInfo);
}
GrVkPipelineState* GrVkPipelineStateBuilder::finalize(const GrStencilSettings& stencil,
GrPrimitiveType primitiveType,
const GrVkRenderPass& renderPass,
const GrVkPipelineState::Desc& desc) {
VkDescriptorSetLayout dsLayout[2];
VkPipelineLayout pipelineLayout;
VkShaderModule vertShaderModule;
VkShaderModule fragShaderModule;
GrVkResourceProvider& resourceProvider = fGpu->resourceProvider();
// These layouts are not owned by the PipelineStateBuilder and thus should not be destroyed
dsLayout[GrVkUniformHandler::kUniformBufferDescSet] = resourceProvider.getUniformDSLayout();
GrVkDescriptorSetManager::Handle samplerDSHandle;
resourceProvider.getSamplerDescriptorSetHandle(fUniformHandler, &samplerDSHandle);
dsLayout[GrVkUniformHandler::kSamplerDescSet] =
resourceProvider.getSamplerDSLayout(samplerDSHandle);
// Create the VkPipelineLayout
VkPipelineLayoutCreateInfo layoutCreateInfo;
memset(&layoutCreateInfo, 0, sizeof(VkPipelineLayoutCreateFlags));
layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
layoutCreateInfo.pNext = 0;
layoutCreateInfo.flags = 0;
layoutCreateInfo.setLayoutCount = 2;
layoutCreateInfo.pSetLayouts = dsLayout;
layoutCreateInfo.pushConstantRangeCount = 0;
layoutCreateInfo.pPushConstantRanges = nullptr;
GR_VK_CALL_ERRCHECK(fGpu->vkInterface(), CreatePipelineLayout(fGpu->device(),
&layoutCreateInfo,
nullptr,
&pipelineLayout));
// We need to enable the following extensions so that the compiler can correctly make spir-v
// from our glsl shaders.
fVS.extensions().appendf("#extension GL_ARB_separate_shader_objects : enable\n");
fFS.extensions().appendf("#extension GL_ARB_separate_shader_objects : enable\n");
fVS.extensions().appendf("#extension GL_ARB_shading_language_420pack : enable\n");
fFS.extensions().appendf("#extension GL_ARB_shading_language_420pack : enable\n");
this->finalizeShaders();
VkPipelineShaderStageCreateInfo shaderStageInfo[2];
SkAssertResult(CreateVkShaderModule(fGpu,
VK_SHADER_STAGE_VERTEX_BIT,
fVS,
&vertShaderModule,
&shaderStageInfo[0]));
SkAssertResult(CreateVkShaderModule(fGpu,
VK_SHADER_STAGE_FRAGMENT_BIT,
fFS,
&fragShaderModule,
&shaderStageInfo[1]));
GrVkPipeline* pipeline = resourceProvider.createPipeline(fPipeline,
stencil,
fPrimProc,
shaderStageInfo,
2,
primitiveType,
renderPass,
pipelineLayout);
GR_VK_CALL(fGpu->vkInterface(), DestroyShaderModule(fGpu->device(), vertShaderModule,
nullptr));
GR_VK_CALL(fGpu->vkInterface(), DestroyShaderModule(fGpu->device(), fragShaderModule,
nullptr));
if (!pipeline) {
GR_VK_CALL(fGpu->vkInterface(), DestroyPipelineLayout(fGpu->device(), pipelineLayout,
nullptr));
this->cleanupFragmentProcessors();
return nullptr;
}
return new GrVkPipelineState(fGpu,
desc,
pipeline,
pipelineLayout,
samplerDSHandle,
fUniformHandles,
fUniformHandler.fUniforms,
fUniformHandler.fCurrentVertexUBOOffset,
fUniformHandler.fCurrentFragmentUBOOffset,
(uint32_t)fUniformHandler.numSamplers(),
fGeometryProcessor,
fXferProcessor,
fFragmentProcessors);
}
<|endoftext|> |
<commit_before>#include "common.h"
#include <cmath>
using namespace std;
extern "C"
void fft_inplace_even(complexd * data, int size, int pitch);
// In principle, we can calculate 1 - (t2/r)^2 separately
// because it does not depend on w and can be reused for
// all layers, but we don't bother with caching and copying them
// over and thus recalculate them each time
void mkGCFLayer(
complexd arena[] // Full oversampled layer (padded)
, int size // linear size of the arena
, int pitch // pitch of the arena
, double t2
, double w
, int max_support
){
acc2d<complexd> center = acc2d<complexd>(arena + size * pitch / 2, pitch);
int radius = max_support / 2;
double normer = t2 / double (radius);
#pragma omp parallel for // not so much important
// Can make this slightly more optimal ...
for(int i = 0; i <= radius; i++)
for(int j = 0; i <= radius; i++) {
double x, y, ph;
x = double(i) / normer;
y = double(j) / normer;
ph = w * (1 - sqrt(1 - x*x - y*y));
double s, c;
sincos(2.0 * M_PI * ph, &s, &c);
center[-i][-j]
= center[-i][ j]
= center[ i][-j]
= center[ i][ j] = complexd(c,-s);
}
fft_inplace_even(arena, size, pitch);
// TODO:
// Transposition and extraction here.
// I believe we should combine transposition with extraction.
}
<commit_msg>Add transposition/extraction to CPU GCF (need to integrate this in the whole, thus need to decide where to do this -- in Haskell or C++ land).<commit_after>#include "common.h"
#include <cmath>
using namespace std;
extern "C"
void fft_inplace_even(complexd * data, int size, int pitch);
// In principle, we can calculate 1 - (t2/r)^2 separately
// because it does not depend on w and can be reused for
// all layers, but we don't bother with caching and copying them
// over and thus recalculate them each time
void mkGCFLayer(
complexd arena[] // Full oversampled layer (padded)
, int size // linear size of the arena
, int pitch // pitch of the arena
, double t2
, double w
, int max_support
){
acc2d<complexd> center = acc2d<complexd>(arena + size * pitch / 2, pitch);
int radius = max_support / 2;
double normer = t2 / double (radius);
#pragma omp parallel for // not so much important
// Can make this slightly more optimal ...
for(int i = 0; i <= radius; i++)
for(int j = 0; i <= radius; i++) {
double x, y, ph;
x = double(i) / normer;
y = double(j) / normer;
ph = w * (1 - sqrt(1 - x*x - y*y));
double s, c;
sincos(2.0 * M_PI * ph, &s, &c);
center[-i][-j]
= center[-i][ j]
= center[ i][-j]
= center[ i][ j] = complexd(c,-s);
}
fft_inplace_even(arena, size, pitch);
// TODO:
// Transposition and extraction here.
// I believe we should combine transposition with extraction.
}
template <int over>
void __transpose_and_extract(
complexd dst[] // [over][over][support][support]
, const complexd src[] // [max_support][over][max_support][over]
, int support
, int max_support
, int src_pad
) {
int
src_size = max_support * over
, src_pitch = src_size + src_pad
, start_loc = (max_support - support) * over * src_pitch / 2
;
const complexd * srcp = src + start_loc;
// NOTE: check this thoroughly
for (int overu = 0; overu < over; overu++, srcp+=src_pitch) {
const complexd * srcp1; srcp1 = srcp;
for (int overv = 0; overv < over; overv++, srcp1++) {
const complexd * srcp2; srcp2 = srcp1;
for (int suppu = 0; suppu < support; suppu++, srcp2+=over*src_pitch) {
const complexd * srcp3; srcp3 = srcp2;
for (int suppv = 0; suppv < support; suppv++, srcp3+=over) {
*dst++ = *srcp3;
}
}
}
}
}
// Inst
extern "C"
void transpose_and_extract(
complexd dst[]
, const complexd src[]
, int support
, int max_support
, int src_pad
) {
__transpose_and_extract<8>(dst, src, support, max_support, src_pad);
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP
#define STAN_MATH_REV_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/dot_product.hpp>
#include <stan/math/rev/fun/dot_self.hpp>
#include <stan/math/rev/fun/typedefs.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
namespace stan {
namespace math {
template <typename T, require_rev_matrix_t<T>* = nullptr>
inline plain_type_t<T> multiply_lower_tri_self_transpose(const T& L) {
using T_double = Eigen::MatrixXd;
using T_var = plain_type_t<T>;
if (L.size() == 0)
return L;
arena_t<T_var> arena_L = L;
arena_t<T_double> arena_L_val
= value_of(arena_L).template triangularView<Eigen::Lower>();
arena_t<T_var> res = arena_L_val.template triangularView<Eigen::Lower>()
* arena_L_val.transpose();
reverse_pass_callback([res, arena_L, arena_L_val]() mutable {
const auto& adj = to_ref(res.adj());
Eigen::MatrixXd adjL = (adj.transpose() + adj) * arena_L_val.template triangularView<Eigen::Lower>();
arena_L.adj() += adjL.template triangularView<Eigen::Lower>();
});
return res;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.1-14 (tags/RELEASE_601/final)<commit_after>#ifndef STAN_MATH_REV_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP
#define STAN_MATH_REV_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/dot_product.hpp>
#include <stan/math/rev/fun/dot_self.hpp>
#include <stan/math/rev/fun/typedefs.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
namespace stan {
namespace math {
template <typename T, require_rev_matrix_t<T>* = nullptr>
inline plain_type_t<T> multiply_lower_tri_self_transpose(const T& L) {
using T_double = Eigen::MatrixXd;
using T_var = plain_type_t<T>;
if (L.size() == 0)
return L;
arena_t<T_var> arena_L = L;
arena_t<T_double> arena_L_val
= value_of(arena_L).template triangularView<Eigen::Lower>();
arena_t<T_var> res = arena_L_val.template triangularView<Eigen::Lower>()
* arena_L_val.transpose();
reverse_pass_callback([res, arena_L, arena_L_val]() mutable {
const auto& adj = to_ref(res.adj());
Eigen::MatrixXd adjL
= (adj.transpose() + adj)
* arena_L_val.template triangularView<Eigen::Lower>();
arena_L.adj() += adjL.template triangularView<Eigen::Lower>();
});
return res;
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <vector>
#include <string>
#include <pcl/visualization/vtk.h>
#include <pcl/visualization/pcl_visualizer.h>
#include "boost.h"
#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
double now = pcl::getTime (); \
++count; \
if (now - last >= 1.0) \
{ \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber)
: grabber_ (grabber)
, image_mutex_ ()
, image_ ()
, depth_image_ ()
, importer_ (vtkSmartPointer<vtkImageImport>::New ())
, depth_importer_ (vtkSmartPointer<vtkImageImport>::New ())
, writer_ (vtkSmartPointer<vtkTIFFWriter>::New ())
, flipper_ (vtkSmartPointer<vtkImageFlip>::New ())
{
importer_->SetNumberOfScalarComponents (3);
importer_->SetDataScalarTypeToUnsignedChar ();
depth_importer_->SetNumberOfScalarComponents (1);
depth_importer_->SetDataScalarTypeToUnsignedShort ();
writer_->SetCompressionToPackBits ();
flipper_->SetFilteredAxes (1);
}
void
image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
{
FPS_CALC ("image callback");
boost::mutex::scoped_lock lock (image_mutex_);
image_ = image;
depth_image_ = depth_image;
}
void
run ()
{
boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
boost::signals2::connection image_connection = grabber_.registerCallback (image_cb);
grabber_.start ();
unsigned char* rgb_data = 0;
unsigned rgb_data_size = 0;
const void* data;
while (true)
{
boost::mutex::scoped_lock lock (image_mutex_);
std::string time = boost::posix_time::to_iso_string (boost::posix_time::microsec_clock::local_time ());
if (image_)
{
FPS_CALC ("writer callback");
boost::shared_ptr<openni_wrapper::Image> image;
image.swap (image_);
if (image->getEncoding() == openni_wrapper::Image::RGB)
{
data = reinterpret_cast<const void*> (image->getMetaData ().Data ());
importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0);
importer_->SetDataExtentToWholeExtent ();
}
else
{
if (rgb_data_size < image->getWidth () * image->getHeight ())
{
rgb_data_size = image->getWidth () * image->getHeight ();
rgb_data = new unsigned char [rgb_data_size * 3];
importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0);
importer_->SetDataExtentToWholeExtent ();
}
image->fillRGB (image->getWidth (), image->getHeight (), rgb_data);
data = reinterpret_cast<const void*> (rgb_data);
}
std::stringstream ss;
ss << "frame_" + time + "_rgb.tiff";
importer_->SetImportVoidPointer (const_cast<void*>(data), 1);
importer_->Update ();
flipper_->SetInputConnection (importer_->GetOutputPort ());
flipper_->Update ();
writer_->SetFileName (ss.str ().c_str ());
writer_->SetInputConnection (flipper_->GetOutputPort ());
writer_->Write ();
}
if (depth_image_)
{
boost::shared_ptr<openni_wrapper::DepthImage> depth_image;
depth_image.swap (depth_image_);
std::stringstream ss;
ss << "frame_" + time + "_depth.tiff";
depth_importer_->SetWholeExtent (0, depth_image->getWidth () - 1, 0, depth_image->getHeight () - 1, 0, 0);
depth_importer_->SetDataExtentToWholeExtent ();
depth_importer_->SetImportVoidPointer (const_cast<void*> (reinterpret_cast<const void*> (depth_image->getDepthMetaData ().Data ())), 1);
depth_importer_->Update ();
flipper_->SetInputConnection (depth_importer_->GetOutputPort ());
flipper_->Update ();
writer_->SetFileName (ss.str ().c_str ());
writer_->SetInputConnection (flipper_->GetOutputPort ());
writer_->Write ();
}
}
grabber_.stop ();
image_connection.disconnect ();
if (rgb_data)
delete[] rgb_data;
}
pcl::OpenNIGrabber& grabber_;
boost::mutex image_mutex_;
boost::shared_ptr<openni_wrapper::Image> image_;
boost::shared_ptr<openni_wrapper::DepthImage> depth_image_;
vtkSmartPointer<vtkImageImport> importer_, depth_importer_;
vtkSmartPointer<vtkTIFFWriter> writer_;
vtkSmartPointer<vtkImageFlip> flipper_;
};
void
usage (char ** argv)
{
cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl;
cout << argv[0] << " -h | --help : shows this help" << endl;
cout << argv[0] << " -l : list all available devices" << endl;
cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;
cout << " device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
<< " or" << endl
<< " bus@address for the device connected to a specific usb-bus / address combination or" << endl
<< " <serial-number>"
#endif
<< endl;
cout << endl;
cout << "examples:" << endl;
cout << argv[0] << " \"#1\"" << endl;
cout << " uses the first device." << endl;
cout << argv[0] << " \"./temp/test.oni\"" << endl;
cout << " uses the oni-player device to play back oni file given by path." << endl;
cout << argv[0] << " -l" << endl;
cout << " lists all available devices." << endl;
cout << argv[0] << " -l \"#2\"" << endl;
cout << " lists all available modes for the second device" << endl;
#ifndef _WIN32
cout << argv[0] << " A00361800903049A" << endl;
cout << " uses the device with the serial number \'A00361800903049A\'." << endl;
cout << argv[0] << " 1@16" << endl;
cout << " uses the device on address 16 at USB bus 1." << endl;
#endif
return;
}
int
main(int argc, char ** argv)
{
std::string device_id ("");
pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
if (argc >= 2)
{
device_id = argv[1];
if (device_id == "--help" || device_id == "-h")
{
usage(argv);
return 0;
}
else if (device_id == "-l")
{
if (argc >= 3)
{
pcl::OpenNIGrabber grabber (argv[2]);
boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice ();
std::vector<std::pair<int, XnMapOutputMode> > modes;
if (device->hasImageStream ())
{
cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl;
modes = grabber.getAvailableImageModes ();
for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it)
{
cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
}
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
{
for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
{
cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
<< ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
}
}
else
cout << "No devices connected." << endl;
cout <<"Virtual Devices available: ONI player" << endl;
}
return (0);
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
cout << "Device Id not set, using first device." << endl;
}
unsigned mode;
if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1)
image_mode = pcl::OpenNIGrabber::Mode (mode);
pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);
SimpleOpenNIViewer v (grabber);
v.run ();
return (0);
}
<commit_msg>Added depth_mode argument to openni_save_image.cpp<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <vector>
#include <string>
#include <pcl/visualization/vtk.h>
#include <pcl/visualization/pcl_visualizer.h>
#include "boost.h"
#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
double now = pcl::getTime (); \
++count; \
if (now - last >= 1.0) \
{ \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber)
: grabber_ (grabber)
, image_mutex_ ()
, image_ ()
, depth_image_ ()
, importer_ (vtkSmartPointer<vtkImageImport>::New ())
, depth_importer_ (vtkSmartPointer<vtkImageImport>::New ())
, writer_ (vtkSmartPointer<vtkTIFFWriter>::New ())
, flipper_ (vtkSmartPointer<vtkImageFlip>::New ())
{
importer_->SetNumberOfScalarComponents (3);
importer_->SetDataScalarTypeToUnsignedChar ();
depth_importer_->SetNumberOfScalarComponents (1);
depth_importer_->SetDataScalarTypeToUnsignedShort ();
writer_->SetCompressionToPackBits ();
flipper_->SetFilteredAxes (1);
}
void
image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
{
FPS_CALC ("image callback");
boost::mutex::scoped_lock lock (image_mutex_);
image_ = image;
depth_image_ = depth_image;
}
void
run ()
{
boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
boost::signals2::connection image_connection = grabber_.registerCallback (image_cb);
grabber_.start ();
unsigned char* rgb_data = 0;
unsigned rgb_data_size = 0;
const void* data;
while (true)
{
boost::mutex::scoped_lock lock (image_mutex_);
std::string time = boost::posix_time::to_iso_string (boost::posix_time::microsec_clock::local_time ());
if (image_)
{
FPS_CALC ("writer callback");
boost::shared_ptr<openni_wrapper::Image> image;
image.swap (image_);
if (image->getEncoding() == openni_wrapper::Image::RGB)
{
data = reinterpret_cast<const void*> (image->getMetaData ().Data ());
importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0);
importer_->SetDataExtentToWholeExtent ();
}
else
{
if (rgb_data_size < image->getWidth () * image->getHeight ())
{
rgb_data_size = image->getWidth () * image->getHeight ();
rgb_data = new unsigned char [rgb_data_size * 3];
importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0);
importer_->SetDataExtentToWholeExtent ();
}
image->fillRGB (image->getWidth (), image->getHeight (), rgb_data);
data = reinterpret_cast<const void*> (rgb_data);
}
std::stringstream ss;
ss << "frame_" + time + "_rgb.tiff";
importer_->SetImportVoidPointer (const_cast<void*>(data), 1);
importer_->Update ();
flipper_->SetInputConnection (importer_->GetOutputPort ());
flipper_->Update ();
writer_->SetFileName (ss.str ().c_str ());
writer_->SetInputConnection (flipper_->GetOutputPort ());
writer_->Write ();
}
if (depth_image_)
{
boost::shared_ptr<openni_wrapper::DepthImage> depth_image;
depth_image.swap (depth_image_);
std::stringstream ss;
ss << "frame_" + time + "_depth.tiff";
depth_importer_->SetWholeExtent (0, depth_image->getWidth () - 1, 0, depth_image->getHeight () - 1, 0, 0);
depth_importer_->SetDataExtentToWholeExtent ();
depth_importer_->SetImportVoidPointer (const_cast<void*> (reinterpret_cast<const void*> (depth_image->getDepthMetaData ().Data ())), 1);
depth_importer_->Update ();
flipper_->SetInputConnection (depth_importer_->GetOutputPort ());
flipper_->Update ();
writer_->SetFileName (ss.str ().c_str ());
writer_->SetInputConnection (flipper_->GetOutputPort ());
writer_->Write ();
}
}
grabber_.stop ();
image_connection.disconnect ();
if (rgb_data)
delete[] rgb_data;
}
pcl::OpenNIGrabber& grabber_;
boost::mutex image_mutex_;
boost::shared_ptr<openni_wrapper::Image> image_;
boost::shared_ptr<openni_wrapper::DepthImage> depth_image_;
vtkSmartPointer<vtkImageImport> importer_, depth_importer_;
vtkSmartPointer<vtkTIFFWriter> writer_;
vtkSmartPointer<vtkImageFlip> flipper_;
};
void
usage (char ** argv)
{
cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl;
cout << argv[0] << " -h | --help : shows this help" << endl;
cout << argv[0] << " -l : list all available devices" << endl;
cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;
cout << " device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
<< " or" << endl
<< " bus@address for the device connected to a specific usb-bus / address combination or" << endl
<< " <serial-number>"
#endif
<< endl;
cout << endl;
cout << "examples:" << endl;
cout << argv[0] << " \"#1\"" << endl;
cout << " uses the first device." << endl;
cout << argv[0] << " \"./temp/test.oni\"" << endl;
cout << " uses the oni-player device to play back oni file given by path." << endl;
cout << argv[0] << " -l" << endl;
cout << " lists all available devices." << endl;
cout << argv[0] << " -l \"#2\"" << endl;
cout << " lists all available modes for the second device" << endl;
#ifndef _WIN32
cout << argv[0] << " A00361800903049A" << endl;
cout << " uses the device with the serial number \'A00361800903049A\'." << endl;
cout << argv[0] << " 1@16" << endl;
cout << " uses the device on address 16 at USB bus 1." << endl;
#endif
return;
}
int
main(int argc, char ** argv)
{
std::string device_id ("");
pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
pcl::OpenNIGrabber::Mode depth_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
if (argc >= 2)
{
device_id = argv[1];
if (device_id == "--help" || device_id == "-h")
{
usage(argv);
return 0;
}
else if (device_id == "-l")
{
if (argc >= 3)
{
pcl::OpenNIGrabber grabber (argv[2]);
boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice ();
std::vector<std::pair<int, XnMapOutputMode> > modes;
if (device->hasImageStream ())
{
cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl;
modes = grabber.getAvailableImageModes ();
for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it)
{
cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
}
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
{
for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
{
cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
<< ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
}
}
else
cout << "No devices connected." << endl;
cout <<"Virtual Devices available: ONI player" << endl;
}
return (0);
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
cout << "Device Id not set, using first device." << endl;
}
unsigned imagemode;
if (pcl::console::parse (argc, argv, "-imagemode", imagemode) != -1)
image_mode = pcl::OpenNIGrabber::Mode (imagemode);
unsigned depthmode;
if (pcl::console::parse (argc, argv, "-depthmode", depthmode) != -1)
depth_mode = pcl::OpenNIGrabber::Mode (depthmode);
pcl::OpenNIGrabber grabber (device_id, depth_mode, image_mode);
SimpleOpenNIViewer v (grabber);
v.run ();
return (0);
}
<|endoftext|> |
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "dense_lambda_peek_optimizer.h"
#include "dense_lambda_peek_function.h"
#include "dense_cell_range_function.h"
#include <vespa/eval/instruction/replace_type_function.h>
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/node_tools.h>
#include <vespa/eval/eval/basic_nodes.h>
#include <vespa/eval/eval/operator_nodes.h>
#include <vespa/eval/eval/call_nodes.h>
#include <vespa/eval/eval/tensor_nodes.h>
#include <vespa/eval/eval/llvm/compile_cache.h>
#include <optional>
using namespace vespalib::eval::nodes;
namespace vespalib::eval {
namespace {
// 'simple peek': deterministic peek into a single parameter with
// compilable dimension index expressions.
const TensorPeek *find_simple_peek(const tensor_function::Lambda &lambda) {
const Function &function = lambda.lambda();
const size_t num_dims = lambda.result_type().dimensions().size();
auto peek = as<TensorPeek>(function.root());
if (peek && (function.num_params() == (num_dims + 1))) {
auto param = as<Symbol>(peek->get_child(0));
if (param && (param->id() == num_dims)) {
for (size_t i = 1; i < peek->num_children(); ++i) {
const Node &dim_expr = peek->get_child(i);
if (NodeTools::min_num_params(dim_expr) > num_dims) {
return nullptr;
}
if (CompiledFunction::detect_issues(dim_expr)) {
return nullptr;
}
}
return peek;
}
}
return nullptr;
}
Node_UP make_dim_expr(const TensorPeek::Dim &src_dim) {
if (src_dim.second.is_expr()) {
return NodeTools::copy(*src_dim.second.expr);
} else {
return std::make_unique<Number>(as_number(src_dim.second.label));
}
}
template <typename OP>
Node_UP make_op(Node_UP a, Node_UP b) {
auto res = std::make_unique<OP>();
res->bind(std::move(a), std::move(b));
return res;
}
Node_UP make_floor(Node_UP a) {
auto res = std::make_unique<Floor>();
res->bind_next(std::move(a));
return res;
}
struct PeekAnalyzer {
std::vector<size_t> dst_dim_sizes;
std::vector<size_t> src_dim_sizes;
std::vector<CompiledFunction::UP> src_dim_funs;
std::shared_ptr<Function const> src_idx_fun;
struct CellRange {
size_t offset;
size_t length;
bool is_full(size_t num_cells) const {
return ((offset == 0) && (length == num_cells));
}
};
struct Result {
bool valid;
std::optional<CellRange> cell_range;
static Result simple(CellRange range) { return Result{true, range}; }
static Result complex() { return Result{true, std::nullopt}; }
static Result invalid() { return Result{false, std::nullopt}; }
};
PeekAnalyzer(const ValueType &dst_type, const ValueType &src_type,
const TensorPeek::DimList &dim_list)
{
for (const auto& dim: dst_type.dimensions()) {
dst_dim_sizes.push_back(dim.size);
}
for (const auto& dim: src_type.dimensions()) {
src_dim_sizes.push_back(dim.size);
}
Node_UP idx_expr;
size_t num_params = dst_dim_sizes.size();
for (size_t i = 0; i < dim_list.size(); ++i) {
auto dim_expr = make_dim_expr(dim_list[i]);
src_dim_funs.push_back(std::make_unique<CompiledFunction>(*dim_expr, num_params, PassParams::ARRAY));
if (i == 0) {
idx_expr = std::move(dim_expr);
} else {
idx_expr = make_floor(std::move(idx_expr));
idx_expr = make_op<Mul>(std::move(idx_expr), std::make_unique<Number>(src_dim_sizes[i]));
idx_expr = make_op<Add>(std::move(idx_expr), std::move(dim_expr));
}
}
src_idx_fun = Function::create(std::move(idx_expr), dst_type.dimension_names());
}
bool step_params(std::vector<double> ¶ms) {
for (size_t idx = params.size(); idx-- > 0; ) {
if (size_t(params[idx] += 1.0) < dst_dim_sizes[idx]) {
return true;
} else {
params[idx] = 0.0;
}
}
return false;
}
size_t calculate_index(const std::vector<size_t> &src_address) {
size_t result = 0;
for (size_t i = 0; i < src_address.size(); ++i) {
result *= src_dim_sizes[i];
result += src_address[i];
}
return result;
}
Result analyze_indexes() {
CellRange range{0,0};
bool is_complex = false;
std::vector<double> params(dst_dim_sizes.size(), 0.0);
std::vector<size_t> src_address(src_dim_sizes.size(), 0);
do {
for (size_t i = 0; i < src_dim_funs.size(); ++i) {
auto dim_fun = src_dim_funs[i]->get_function();
size_t dim_idx = dim_fun(¶ms[0]);
if (dim_idx >= src_dim_sizes[i]) {
return Result::invalid();
}
src_address[i] = dim_idx;
}
size_t idx = calculate_index(src_address);
if (range.length == 0) {
range.offset = idx;
}
if (idx == (range.offset + range.length)) {
++range.length;
} else {
is_complex = true;
}
} while(step_params(params));
if (is_complex) {
return Result::complex();
}
return Result::simple(range);
}
};
} // namespace <unnamed>
const TensorFunction &
DenseLambdaPeekOptimizer::optimize(const TensorFunction &expr, Stash &stash)
{
if (auto lambda = as<tensor_function::Lambda>(expr)) {
if (auto peek = find_simple_peek(*lambda)) {
const ValueType &dst_type = lambda->result_type();
const ValueType &src_type = lambda->types().get_type(peek->param());
if (src_type.is_dense()) {
assert(lambda->bindings().size() == 1);
assert(src_type.dimensions().size() == peek->dim_list().size());
size_t param_idx = lambda->bindings()[0];
PeekAnalyzer analyzer(dst_type, src_type, peek->dim_list());
auto result = analyzer.analyze_indexes();
if (result.valid) {
const auto &get_param = tensor_function::inject(src_type, param_idx, stash);
if (result.cell_range && (dst_type.cell_type() == src_type.cell_type())) {
auto cell_range = result.cell_range.value();
if (cell_range.is_full(src_type.dense_subspace_size())) {
return ReplaceTypeFunction::create_compact(dst_type, get_param, stash);
} else {
return stash.create<DenseCellRangeFunction>(dst_type, get_param,
cell_range.offset, cell_range.length);
}
} else {
return stash.create<DenseLambdaPeekFunction>(dst_type, get_param,
std::move(analyzer.src_idx_fun));
}
}
}
}
}
return expr;
}
} // namespace
<commit_msg>use SmallVector in dense_lambda_peek_optimizer<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "dense_lambda_peek_optimizer.h"
#include "dense_lambda_peek_function.h"
#include "dense_cell_range_function.h"
#include <vespa/eval/instruction/replace_type_function.h>
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/node_tools.h>
#include <vespa/eval/eval/basic_nodes.h>
#include <vespa/eval/eval/operator_nodes.h>
#include <vespa/eval/eval/call_nodes.h>
#include <vespa/eval/eval/tensor_nodes.h>
#include <vespa/eval/eval/llvm/compile_cache.h>
#include <optional>
using namespace vespalib::eval::nodes;
namespace vespalib::eval {
namespace {
// 'simple peek': deterministic peek into a single parameter with
// compilable dimension index expressions.
const TensorPeek *find_simple_peek(const tensor_function::Lambda &lambda) {
const Function &function = lambda.lambda();
const size_t num_dims = lambda.result_type().dimensions().size();
auto peek = as<TensorPeek>(function.root());
if (peek && (function.num_params() == (num_dims + 1))) {
auto param = as<Symbol>(peek->get_child(0));
if (param && (param->id() == num_dims)) {
for (size_t i = 1; i < peek->num_children(); ++i) {
const Node &dim_expr = peek->get_child(i);
if (NodeTools::min_num_params(dim_expr) > num_dims) {
return nullptr;
}
if (CompiledFunction::detect_issues(dim_expr)) {
return nullptr;
}
}
return peek;
}
}
return nullptr;
}
Node_UP make_dim_expr(const TensorPeek::Dim &src_dim) {
if (src_dim.second.is_expr()) {
return NodeTools::copy(*src_dim.second.expr);
} else {
return std::make_unique<Number>(as_number(src_dim.second.label));
}
}
template <typename OP>
Node_UP make_op(Node_UP a, Node_UP b) {
auto res = std::make_unique<OP>();
res->bind(std::move(a), std::move(b));
return res;
}
Node_UP make_floor(Node_UP a) {
auto res = std::make_unique<Floor>();
res->bind_next(std::move(a));
return res;
}
struct PeekAnalyzer {
SmallVector<size_t> dst_dim_sizes;
SmallVector<size_t> src_dim_sizes;
SmallVector<CompiledFunction::UP> src_dim_funs;
std::shared_ptr<Function const> src_idx_fun;
struct CellRange {
size_t offset;
size_t length;
bool is_full(size_t num_cells) const {
return ((offset == 0) && (length == num_cells));
}
};
struct Result {
bool valid;
std::optional<CellRange> cell_range;
static Result simple(CellRange range) { return Result{true, range}; }
static Result complex() { return Result{true, std::nullopt}; }
static Result invalid() { return Result{false, std::nullopt}; }
};
PeekAnalyzer(const ValueType &dst_type, const ValueType &src_type,
const TensorPeek::DimList &dim_list)
{
for (const auto& dim: dst_type.dimensions()) {
dst_dim_sizes.push_back(dim.size);
}
for (const auto& dim: src_type.dimensions()) {
src_dim_sizes.push_back(dim.size);
}
Node_UP idx_expr;
size_t num_params = dst_dim_sizes.size();
for (size_t i = 0; i < dim_list.size(); ++i) {
auto dim_expr = make_dim_expr(dim_list[i]);
src_dim_funs.push_back(std::make_unique<CompiledFunction>(*dim_expr, num_params, PassParams::ARRAY));
if (i == 0) {
idx_expr = std::move(dim_expr);
} else {
idx_expr = make_floor(std::move(idx_expr));
idx_expr = make_op<Mul>(std::move(idx_expr), std::make_unique<Number>(src_dim_sizes[i]));
idx_expr = make_op<Add>(std::move(idx_expr), std::move(dim_expr));
}
}
src_idx_fun = Function::create(std::move(idx_expr), dst_type.dimension_names());
}
bool step_params(SmallVector<double> ¶ms) {
for (size_t idx = params.size(); idx-- > 0; ) {
if (size_t(params[idx] += 1.0) < dst_dim_sizes[idx]) {
return true;
} else {
params[idx] = 0.0;
}
}
return false;
}
size_t calculate_index(const SmallVector<size_t> &src_address) {
size_t result = 0;
for (size_t i = 0; i < src_address.size(); ++i) {
result *= src_dim_sizes[i];
result += src_address[i];
}
return result;
}
Result analyze_indexes() {
CellRange range{0,0};
bool is_complex = false;
SmallVector<double> params(dst_dim_sizes.size(), 0.0);
SmallVector<size_t> src_address(src_dim_sizes.size(), 0);
do {
for (size_t i = 0; i < src_dim_funs.size(); ++i) {
auto dim_fun = src_dim_funs[i]->get_function();
size_t dim_idx = dim_fun(¶ms[0]);
if (dim_idx >= src_dim_sizes[i]) {
return Result::invalid();
}
src_address[i] = dim_idx;
}
size_t idx = calculate_index(src_address);
if (range.length == 0) {
range.offset = idx;
}
if (idx == (range.offset + range.length)) {
++range.length;
} else {
is_complex = true;
}
} while(step_params(params));
if (is_complex) {
return Result::complex();
}
return Result::simple(range);
}
};
} // namespace <unnamed>
const TensorFunction &
DenseLambdaPeekOptimizer::optimize(const TensorFunction &expr, Stash &stash)
{
if (auto lambda = as<tensor_function::Lambda>(expr)) {
if (auto peek = find_simple_peek(*lambda)) {
const ValueType &dst_type = lambda->result_type();
const ValueType &src_type = lambda->types().get_type(peek->param());
if (src_type.is_dense()) {
assert(lambda->bindings().size() == 1);
assert(src_type.dimensions().size() == peek->dim_list().size());
size_t param_idx = lambda->bindings()[0];
PeekAnalyzer analyzer(dst_type, src_type, peek->dim_list());
auto result = analyzer.analyze_indexes();
if (result.valid) {
const auto &get_param = tensor_function::inject(src_type, param_idx, stash);
if (result.cell_range && (dst_type.cell_type() == src_type.cell_type())) {
auto cell_range = result.cell_range.value();
if (cell_range.is_full(src_type.dense_subspace_size())) {
return ReplaceTypeFunction::create_compact(dst_type, get_param, stash);
} else {
return stash.create<DenseCellRangeFunction>(dst_type, get_param,
cell_range.offset, cell_range.length);
}
} else {
return stash.create<DenseLambdaPeekFunction>(dst_type, get_param,
std::move(analyzer.src_idx_fun));
}
}
}
}
}
return expr;
}
} // namespace
<|endoftext|> |
<commit_before>//
// Copyright (C) 2013-2014 mogemimi.
//
// Distributed under the MIT License.
// See accompanying file LICENSE.md or copy at
// http://enginetrouble.net/pomdog/LICENSE.md for details.
//
#include "VoxModelLoader.hpp"
#include "Pomdog/Content/detail/AssetLoaderContext.hpp"
#include "Pomdog/Utility/Exception.hpp"
#include <fstream>
#include <algorithm>
#include <utility>
///@todo badcode
#include <Pomdog/../../src/Content/Utility/MakeFourCC.hpp>
#include <Pomdog/../../src/Content/Utility/BinaryReader.hpp>
namespace Pomdog {
namespace Details {
namespace {
//-----------------------------------------------------------------------
static bool IsMagicaVoxelFormat(std::uint32_t signature)
{
constexpr auto fourCC = MakeFourCC('V', 'O', 'X', ' ');
return fourCC == signature;
}
//-----------------------------------------------------------------------
static std::string Error(std::string const& assetPath, char const* description)
{
return description + (": " + assetPath);
}
struct Chunk {
std::int32_t ID;
std::int32_t ContentSize;
std::int32_t ChildrenSize;
};
//-----------------------------------------------------------------------
static std::size_t ChunkSize(std::ifstream & stream, Chunk const& chunk)
{
POMDOG_ASSERT(chunk.ContentSize >= 0);
POMDOG_ASSERT(chunk.ChildrenSize >= 0);
POMDOG_ASSERT(stream.tellg() >= 0);
return static_cast<std::size_t>(stream.tellg()) + chunk.ContentSize + chunk.ChildrenSize;
}
//-----------------------------------------------------------------------
}// unnamed namespace
//-----------------------------------------------------------------------
MagicaVoxel::VoxModel AssetLoader<MagicaVoxel::VoxModel>::operator()(
AssetLoaderContext const& loaderContext, std::string const& assetPath)
{
constexpr int MagicaVoxelVersion = 150;
constexpr auto IdMain = MakeFourCC('M', 'A', 'I', 'N');
constexpr auto IdSize = MakeFourCC('S', 'I', 'Z', 'E');
constexpr auto IdXYZI = MakeFourCC('X', 'Y', 'Z', 'I');
constexpr auto IdRGBA = MakeFourCC('R', 'G', 'B', 'A');
std::ifstream stream = loaderContext.OpenStream(assetPath);
if (stream.fail()) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "cannot open file"));
}
if (!IsMagicaVoxelFormat(BinaryReader::Read<std::uint32_t>(stream))) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "invalid format"));
}
if (MagicaVoxelVersion != BinaryReader::Read<std::int32_t>(stream)) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "version does not much"));
}
const auto mainChunk = BinaryReader::Read<Chunk>(stream);
if (mainChunk.ID != IdMain) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "cannot find main chunk"));
}
const auto mainChunkEnd = ChunkSize(stream, mainChunk);
stream.seekg(mainChunk.ContentSize, std::ios::cur);
MagicaVoxel::VoxModel model;
while (stream.tellg() < mainChunkEnd)
{
const auto chunk = BinaryReader::Read<Chunk>(stream);
const auto chunkEnd = ChunkSize(stream, chunk);
switch (chunk.ID) {
case IdSize: {
const auto x = BinaryReader::Read<std::int32_t>(stream);
const auto y = BinaryReader::Read<std::int32_t>(stream);
const auto z = BinaryReader::Read<std::int32_t>(stream);
POMDOG_ASSERT(x >= 0);
POMDOG_ASSERT(y >= 0);
POMDOG_ASSERT(z >= 0);
model.X = static_cast<std::uint32_t>(x);
model.Y = static_cast<std::uint32_t>(y);
model.Z = static_cast<std::uint32_t>(z);
break;
}
case IdXYZI: {
const auto voxelCount = BinaryReader::Read<std::int32_t>(stream);
if (voxelCount < 0) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "negative number of voxels"));
}
if (voxelCount > 0) {
model.Voxels = BinaryReader::ReadArray<MagicaVoxel::Voxel>(stream, voxelCount);
}
break;
}
case IdRGBA: {
model.ColorPalette = BinaryReader::Read<decltype(model.ColorPalette)>(stream);
model.ColorPalette.back() = Color::Black;
POMDOG_ASSERT(model.ColorPalette.size() == 256);
std::rotate(std::begin(model.ColorPalette), std::next(std::begin(model.ColorPalette), 255), std::end(model.ColorPalette));
break;
}
default:
break;
}
stream.seekg(chunkEnd, std::ios::beg);
}
return std::move(model);
}
}// namespace Details
}// namespace Pomdog
<commit_msg>Fix build warning<commit_after>//
// Copyright (C) 2013-2014 mogemimi.
//
// Distributed under the MIT License.
// See accompanying file LICENSE.md or copy at
// http://enginetrouble.net/pomdog/LICENSE.md for details.
//
#include "VoxModelLoader.hpp"
#include "Pomdog/Content/detail/AssetLoaderContext.hpp"
#include "Pomdog/Utility/Exception.hpp"
#include <fstream>
#include <algorithm>
#include <utility>
///@todo badcode
#include <Pomdog/../../src/Content/Utility/MakeFourCC.hpp>
#include <Pomdog/../../src/Content/Utility/BinaryReader.hpp>
namespace Pomdog {
namespace Details {
namespace {
//-----------------------------------------------------------------------
static bool IsMagicaVoxelFormat(std::uint32_t signature)
{
constexpr auto fourCC = MakeFourCC('V', 'O', 'X', ' ');
return fourCC == signature;
}
//-----------------------------------------------------------------------
static std::string Error(std::string const& assetPath, char const* description)
{
return description + (": " + assetPath);
}
struct Chunk {
std::int32_t ID;
std::int32_t ContentSize;
std::int32_t ChildrenSize;
};
//-----------------------------------------------------------------------
static std::ifstream::pos_type ChunkSize(std::ifstream & stream, Chunk const& chunk)
{
POMDOG_ASSERT(chunk.ContentSize >= 0);
POMDOG_ASSERT(chunk.ChildrenSize >= 0);
POMDOG_ASSERT(stream.tellg() >= 0);
return stream.tellg() + static_cast<std::ifstream::pos_type>(chunk.ContentSize + chunk.ChildrenSize);
}
//-----------------------------------------------------------------------
}// unnamed namespace
//-----------------------------------------------------------------------
MagicaVoxel::VoxModel AssetLoader<MagicaVoxel::VoxModel>::operator()(
AssetLoaderContext const& loaderContext, std::string const& assetPath)
{
constexpr int MagicaVoxelVersion = 150;
constexpr auto IdMain = MakeFourCC('M', 'A', 'I', 'N');
constexpr auto IdSize = MakeFourCC('S', 'I', 'Z', 'E');
constexpr auto IdXYZI = MakeFourCC('X', 'Y', 'Z', 'I');
constexpr auto IdRGBA = MakeFourCC('R', 'G', 'B', 'A');
std::ifstream stream = loaderContext.OpenStream(assetPath);
if (stream.fail()) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "cannot open file"));
}
if (!IsMagicaVoxelFormat(BinaryReader::Read<std::uint32_t>(stream))) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "invalid format"));
}
if (MagicaVoxelVersion != BinaryReader::Read<std::int32_t>(stream)) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "version does not much"));
}
const auto mainChunk = BinaryReader::Read<Chunk>(stream);
if (mainChunk.ID != IdMain) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "cannot find main chunk"));
}
const auto mainChunkEnd = ChunkSize(stream, mainChunk);
stream.seekg(mainChunk.ContentSize, std::ios::cur);
MagicaVoxel::VoxModel model;
while (stream.tellg() < mainChunkEnd)
{
const auto chunk = BinaryReader::Read<Chunk>(stream);
const auto chunkEnd = ChunkSize(stream, chunk);
switch (chunk.ID) {
case IdSize: {
const auto x = BinaryReader::Read<std::int32_t>(stream);
const auto y = BinaryReader::Read<std::int32_t>(stream);
const auto z = BinaryReader::Read<std::int32_t>(stream);
POMDOG_ASSERT(x >= 0);
POMDOG_ASSERT(y >= 0);
POMDOG_ASSERT(z >= 0);
model.X = static_cast<std::uint32_t>(x);
model.Y = static_cast<std::uint32_t>(y);
model.Z = static_cast<std::uint32_t>(z);
break;
}
case IdXYZI: {
const auto voxelCount = BinaryReader::Read<std::int32_t>(stream);
if (voxelCount < 0) {
POMDOG_THROW_EXCEPTION(std::invalid_argument, Error(assetPath, "negative number of voxels"));
}
if (voxelCount > 0) {
model.Voxels = BinaryReader::ReadArray<MagicaVoxel::Voxel>(stream, voxelCount);
}
break;
}
case IdRGBA: {
model.ColorPalette = BinaryReader::Read<decltype(model.ColorPalette)>(stream);
model.ColorPalette.back() = Color::Black;
POMDOG_ASSERT(model.ColorPalette.size() == 256);
std::rotate(std::begin(model.ColorPalette), std::next(std::begin(model.ColorPalette), 255), std::end(model.ColorPalette));
break;
}
default:
break;
}
stream.seekg(chunkEnd, std::ios::beg);
}
return std::move(model);
}
}// namespace Details
}// namespace Pomdog
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
#include "splashbuild.h"
using namespace std;
void ShowUsage();
void ShowVersion();
//map of toolchain hashes to toolchain objects
map<string, Toolchain*> g_toolchains;
void CleanBuildDir();
void ProcessDependencyScan(Socket& sock, DependencyScan rxm);
void ProcessBuildRequest(Socket& sock, const NodeBuildRequest& rxm);
Toolchain* PrepBuild(string toolhash);
bool RefreshCachedFile(Socket& sock, string hash, string fname);
//Temporary directory we work in
string g_tmpdir;
//Temporary directory we do builds in
string g_builddir;
/**
@brief Program entry point
*/
int main(int argc, char* argv[])
{
Severity console_verbosity = Severity::NOTICE;
//TODO: argument for this?
string ctl_server;
int port = 49000;
//Parse command-line arguments
for(int i=1; i<argc; i++)
{
string s(argv[i]);
//Let the logger eat its args first
if(ParseLoggerArguments(i, argc, argv, console_verbosity))
continue;
else if(s == "--help")
{
ShowUsage();
return 0;
}
else if(s == "--version")
{
ShowVersion();
return 0;
}
//Last arg without switch is control server.
//TODO: mandatory arguments to introduce these?
else
ctl_server = argv[i];
}
//Set up temporary directory (TODO: argument for this?)
g_tmpdir = "/tmp/splashbuild-tmp";
MakeDirectoryRecursive(g_tmpdir, 0700);
g_builddir = g_tmpdir + "/build";
MakeDirectoryRecursive(g_builddir, 0700);
//Set up logging
g_log_sinks.emplace(g_log_sinks.begin(), new STDLogSink(console_verbosity));
//Print header
if(console_verbosity >= Severity::NOTICE)
{
ShowVersion();
printf("\n");
}
//Set up the config object from our arguments
g_clientSettings = new ClientSettings(ctl_server, port);
//Connect to the server
Socket sock(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if(!ConnectToServer(sock, ClientHello::CLIENT_BUILD))
return 1;
//Look for compilers
LogVerbose("Enumerating compilers...\n");
{
LogIndenter li;
FindLinkers();
FindCPPCompilers();
FindFPGACompilers();
}
//Get some basic metadata about our hardware and tell the server
SplashMsg binfo;
auto binfom = binfo.mutable_buildinfo();
binfom->set_cpucount(atoi(ShellCommand("cat /proc/cpuinfo | grep processor | wc -l").c_str()));
binfom->set_cpuspeed(atoi(ShellCommand("cat /proc/cpuinfo | grep bogo | head -n 1 | cut -d : -f 2").c_str()));
binfom->set_ramsize(atol(ShellCommand("cat /proc/meminfo | grep MemTotal | cut -d : -f 2").c_str()) / 1024);
binfom->set_numchains(g_toolchains.size());
if(!SendMessage(sock, binfo, ctl_server))
return 1;
//Report the toolchains we found to the server
for(auto it : g_toolchains)
{
auto t = it.second;
//DEBUG: Print it out
//t->DebugPrint();
//Send the toolchain info to the server
SplashMsg tadd;
auto madd = tadd.mutable_addcompiler();
madd->set_compilertype(t->GetType());
madd->set_versionnum((t->GetMajorVersion() << 16) |
(t->GetMinorVersion() << 8) |
(t->GetPatchVersion() << 0));
madd->set_hash(t->GetHash());
madd->set_versionstr(t->GetVersionString());
madd->set_exesuffix(t->GetExecutableSuffix());
madd->set_shlibsuffix(t->GetSharedLibrarySuffix());
madd->set_stlibsuffix(t->GetStaticLibrarySuffix());
madd->set_objsuffix(t->GetObjectSuffix());
auto dlangs = t->GetSupportedLanguages();
for(auto x : dlangs)
madd->add_lang(x);
auto triplets = t->GetTargetTriplets();
for(auto x : triplets)
*madd->add_triplet() = x;
if(!SendMessage(sock, tadd, ctl_server))
return 1;
}
//Initialize the cache
//TODO: Separate caches for each instance if we multithread? Or one + sharing?
g_cache = new Cache("splashbuild");
//Sit around and wait for stuff to come in
LogVerbose("\nReady\n\n");
while(true)
{
SplashMsg rxm;
if(!RecvMessage(sock, rxm))
return 1;
auto type = rxm.Payload_case();
switch(type)
{
//Requesting a dependency scan
case SplashMsg::kDependencyScan:
ProcessDependencyScan(sock, rxm.dependencyscan());
break;
//Requesting a compile operation
case SplashMsg::kNodeBuildRequest:
ProcessBuildRequest(sock, rxm.nodebuildrequest());
break;
//Asking for more data
case SplashMsg::kContentRequestByHash:
if(!ProcessContentRequest(sock, g_clientSettings->GetServerHostname(), rxm))
return false;
break;
default:
LogDebug("Got an unknown message, ignoring it\n");
break;
}
}
//clean up
delete g_cache;
for(auto x : g_toolchains)
delete x.second;
g_toolchains.clear();
delete g_clientSettings;
return 0;
}
/**
@brief Delete all files in the build directory
*/
void CleanBuildDir()
{
string cmd = "rm -rf \"" + g_builddir + "/*\"";
ShellCommand(cmd.c_str());
}
/**
@brief Prepare for a build
*/
Toolchain* PrepBuild(string toolhash)
{
//Look up the toolchain we need
if(g_toolchains.find(toolhash) == g_toolchains.end())
{
LogError(
"Server requested a toolchain that we do not have installed (hash %s)\n"
"This should never happen.\n",
toolhash.c_str());
return NULL;
}
Toolchain* chain = g_toolchains[toolhash];
LogDebug(" Toolchain: %s\n", chain->GetVersionString().c_str());
//Make sure we have a clean slate to build in
//LogDebug(" Cleaning temp directory\n");
CleanBuildDir();
return chain;
}
/**
@brief Make sure a particular file is in our cache
*/
bool RefreshCachedFile(Socket& sock, string hash, string fname)
{
if(!g_cache->IsCached(hash))
{
//Ask for the file
LogDebug(" Source file %s (%s) is not in cache, requesting it from server\n", fname.c_str(), hash.c_str());
string edat;
if(!GetRemoteFileByHash(sock, g_clientSettings->GetServerHostname(), hash, edat))
return false;
g_cache->AddFile(fname, hash, sha256(edat), edat.c_str(), edat.size());
}
return true;
}
/**
@brief Process a "dependency scan" message from a client
*/
void ProcessDependencyScan(Socket& sock, DependencyScan rxm)
{
LogDebug("Got a dependency scan request\n");
LogIndenter li;
//Do setup stuff
Toolchain* chain = PrepBuild(rxm.toolchain());
if(!chain)
return;
//Get the relative path of the source file
string fname = rxm.fname();
string basename = GetBasenameOfFile(fname);
string dir = GetDirOfFile(fname);
string adir = g_builddir + "/" + dir;
string aname = g_builddir + "/" + fname;
//Create the relative path as needed
//LogDebug(" Making build directory %s for source file %s\n", adir.c_str(), basename.c_str());
MakeDirectoryRecursive(adir, 0700);
//See if we have the file in our local cache
string hash = rxm.hash();
if(!RefreshCachedFile(sock, hash, fname))
return;
//It's in cache now, read it
string data = g_cache->ReadCachedFile(hash);
//Write the source file
LogDebug("Writing source file %s\n", aname.c_str());
if(!PutFileContents(aname, data))
return;
//Look up the flags
set<BuildFlag> flags;
for(int i=0; i<rxm.flags_size(); i++)
flags.emplace(BuildFlag(rxm.flags(i)));
//Format the return message
SplashMsg reply;
auto replym = reply.mutable_dependencyresults();
//Run the scanner proper
set<string> deps;
map<string, string> hashes;
if(!chain->ScanDependencies(rxm.arch(), aname, g_builddir, flags, deps, hashes))
{
LogDebug("Scan failed\n");
replym->set_result(false);
SendMessage(sock, reply);
return;
}
//TODO: If the scan found files we're missing, ask for them!
//Successful completion of the scan, crunch the results
LogDebug("Scan completed\n");
replym->set_result(true);
for(auto d : deps)
{
auto rd = replym->add_deps();
rd->set_fname(d);
rd->set_hash(hashes[d]);
}
SendMessage(sock, reply);
}
/**
@brief Process a "build request" message from a client
*/
void ProcessBuildRequest(Socket& sock, const NodeBuildRequest& rxm)
{
LogDebug("\n\nBuild request\n");
LogIndenter li;
//Do setup stuff
Toolchain* chain = PrepBuild(rxm.toolchain());
if(!chain)
return;
//Look up the list of sources
map<string, string> sources; //Map of fname to hash
for(int i=0; i<rxm.sources_size(); i++)
{
auto src = rxm.sources(i);
sources[src.fname()] = src.hash();
}
//Get each source file
set<string> fnames;
for(auto it : sources)
{
string fname = it.first;
string hash = it.second;
//See if we have the file in our local cache
if(!RefreshCachedFile(sock, hash, fname))
return;
//Write it
string path = g_builddir + "/" + GetDirOfFile(fname);
MakeDirectoryRecursive(path, 0700);
string data = g_cache->ReadCachedFile(hash);
string fpath = g_builddir + "/" + fname;
LogDebug("Writing input file %s\n", fpath.c_str());
if(!PutFileContents(fpath, data))
return;
fnames.emplace(fpath);
}
//Look up the list of flags
set<BuildFlag> flags;
for(int i=0; i<rxm.flags_size(); i++)
flags.emplace(BuildFlag(rxm.flags(i)));
//Format the return message
SplashMsg reply;
auto replym = reply.mutable_nodebuildresults();
//Do the actual build
map<string, string> outputs;
if(!chain->Build(
rxm.arch(),
fnames,
rxm.fname(),
flags,
outputs))
{
//TODO: handle failure
}
/*
//Run the scanner proper
set<string> deps;
map<string, string> hashes;
if(!chain->ScanDependencies(rxm.arch(), aname, g_builddir, flags, deps, hashes))
{
LogDebug(" Scan failed\n");
replym->set_result(false);
SendMessage(sock, reply);
return;
}
*/
/*
//TODO: If the scan found files we're missing, ask for them!
//Successful completion of the scan, crunch the results
LogDebug(" Scan completed\n");
replym->set_result(true);
for(auto d : deps)
{
auto rd = replym->add_deps();
rd->set_fname(d);
rd->set_hash(hashes[d]);
}
SendMessage(sock, reply);
*/
//exit(-1);
}
void ShowVersion()
{
printf(
"SPLASH build server daemon by Andrew D. Zonenberg.\n"
"\n"
"License: 3-clause BSD\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n");
}
void ShowUsage()
{
printf("Usage: splashbuild ctlserver\n");
exit(0);
}
<commit_msg>splashbuild: continued switching to logindenter<commit_after>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
#include "splashbuild.h"
using namespace std;
void ShowUsage();
void ShowVersion();
//map of toolchain hashes to toolchain objects
map<string, Toolchain*> g_toolchains;
void CleanBuildDir();
void ProcessDependencyScan(Socket& sock, DependencyScan rxm);
void ProcessBuildRequest(Socket& sock, const NodeBuildRequest& rxm);
Toolchain* PrepBuild(string toolhash);
bool RefreshCachedFile(Socket& sock, string hash, string fname);
//Temporary directory we work in
string g_tmpdir;
//Temporary directory we do builds in
string g_builddir;
/**
@brief Program entry point
*/
int main(int argc, char* argv[])
{
Severity console_verbosity = Severity::NOTICE;
//TODO: argument for this?
string ctl_server;
int port = 49000;
//Parse command-line arguments
for(int i=1; i<argc; i++)
{
string s(argv[i]);
//Let the logger eat its args first
if(ParseLoggerArguments(i, argc, argv, console_verbosity))
continue;
else if(s == "--help")
{
ShowUsage();
return 0;
}
else if(s == "--version")
{
ShowVersion();
return 0;
}
//Last arg without switch is control server.
//TODO: mandatory arguments to introduce these?
else
ctl_server = argv[i];
}
//Set up temporary directory (TODO: argument for this?)
g_tmpdir = "/tmp/splashbuild-tmp";
MakeDirectoryRecursive(g_tmpdir, 0700);
g_builddir = g_tmpdir + "/build";
MakeDirectoryRecursive(g_builddir, 0700);
//Set up logging
g_log_sinks.emplace(g_log_sinks.begin(), new STDLogSink(console_verbosity));
//Print header
if(console_verbosity >= Severity::NOTICE)
{
ShowVersion();
printf("\n");
}
//Set up the config object from our arguments
g_clientSettings = new ClientSettings(ctl_server, port);
//Connect to the server
Socket sock(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if(!ConnectToServer(sock, ClientHello::CLIENT_BUILD))
return 1;
//Look for compilers
LogVerbose("Enumerating compilers...\n");
{
LogIndenter li;
FindLinkers();
FindCPPCompilers();
FindFPGACompilers();
}
//Get some basic metadata about our hardware and tell the server
SplashMsg binfo;
auto binfom = binfo.mutable_buildinfo();
binfom->set_cpucount(atoi(ShellCommand("cat /proc/cpuinfo | grep processor | wc -l").c_str()));
binfom->set_cpuspeed(atoi(ShellCommand("cat /proc/cpuinfo | grep bogo | head -n 1 | cut -d : -f 2").c_str()));
binfom->set_ramsize(atol(ShellCommand("cat /proc/meminfo | grep MemTotal | cut -d : -f 2").c_str()) / 1024);
binfom->set_numchains(g_toolchains.size());
if(!SendMessage(sock, binfo, ctl_server))
return 1;
//Report the toolchains we found to the server
for(auto it : g_toolchains)
{
auto t = it.second;
//DEBUG: Print it out
//t->DebugPrint();
//Send the toolchain info to the server
SplashMsg tadd;
auto madd = tadd.mutable_addcompiler();
madd->set_compilertype(t->GetType());
madd->set_versionnum((t->GetMajorVersion() << 16) |
(t->GetMinorVersion() << 8) |
(t->GetPatchVersion() << 0));
madd->set_hash(t->GetHash());
madd->set_versionstr(t->GetVersionString());
madd->set_exesuffix(t->GetExecutableSuffix());
madd->set_shlibsuffix(t->GetSharedLibrarySuffix());
madd->set_stlibsuffix(t->GetStaticLibrarySuffix());
madd->set_objsuffix(t->GetObjectSuffix());
auto dlangs = t->GetSupportedLanguages();
for(auto x : dlangs)
madd->add_lang(x);
auto triplets = t->GetTargetTriplets();
for(auto x : triplets)
*madd->add_triplet() = x;
if(!SendMessage(sock, tadd, ctl_server))
return 1;
}
//Initialize the cache
//TODO: Separate caches for each instance if we multithread? Or one + sharing?
g_cache = new Cache("splashbuild");
//Sit around and wait for stuff to come in
LogVerbose("\nReady\n\n");
while(true)
{
SplashMsg rxm;
if(!RecvMessage(sock, rxm))
return 1;
auto type = rxm.Payload_case();
switch(type)
{
//Requesting a dependency scan
case SplashMsg::kDependencyScan:
ProcessDependencyScan(sock, rxm.dependencyscan());
break;
//Requesting a compile operation
case SplashMsg::kNodeBuildRequest:
ProcessBuildRequest(sock, rxm.nodebuildrequest());
break;
//Asking for more data
case SplashMsg::kContentRequestByHash:
if(!ProcessContentRequest(sock, g_clientSettings->GetServerHostname(), rxm))
return false;
break;
default:
LogDebug("Got an unknown message, ignoring it\n");
break;
}
}
//clean up
delete g_cache;
for(auto x : g_toolchains)
delete x.second;
g_toolchains.clear();
delete g_clientSettings;
return 0;
}
/**
@brief Delete all files in the build directory
*/
void CleanBuildDir()
{
string cmd = "rm -rf \"" + g_builddir + "/*\"";
ShellCommand(cmd.c_str());
}
/**
@brief Prepare for a build
*/
Toolchain* PrepBuild(string toolhash)
{
//Look up the toolchain we need
if(g_toolchains.find(toolhash) == g_toolchains.end())
{
LogError(
"Server requested a toolchain that we do not have installed (hash %s)\n"
"This should never happen.\n",
toolhash.c_str());
return NULL;
}
Toolchain* chain = g_toolchains[toolhash];
LogDebug("Toolchain: %s\n", chain->GetVersionString().c_str());
//Make sure we have a clean slate to build in
//LogDebug("Cleaning temp directory\n");
CleanBuildDir();
return chain;
}
/**
@brief Make sure a particular file is in our cache
*/
bool RefreshCachedFile(Socket& sock, string hash, string fname)
{
LogIndenter li;
if(!g_cache->IsCached(hash))
{
//Ask for the file
LogDebug("Source file %s (%s) is not in cache, requesting it from server\n", fname.c_str(), hash.c_str());
string edat;
if(!GetRemoteFileByHash(sock, g_clientSettings->GetServerHostname(), hash, edat))
return false;
g_cache->AddFile(fname, hash, sha256(edat), edat.c_str(), edat.size());
}
return true;
}
/**
@brief Process a "dependency scan" message from a client
*/
void ProcessDependencyScan(Socket& sock, DependencyScan rxm)
{
LogDebug("Got a dependency scan request\n");
LogIndenter li;
//Do setup stuff
Toolchain* chain = PrepBuild(rxm.toolchain());
if(!chain)
return;
//Get the relative path of the source file
string fname = rxm.fname();
string basename = GetBasenameOfFile(fname);
string dir = GetDirOfFile(fname);
string adir = g_builddir + "/" + dir;
string aname = g_builddir + "/" + fname;
//Create the relative path as needed
//LogDebug(" Making build directory %s for source file %s\n", adir.c_str(), basename.c_str());
MakeDirectoryRecursive(adir, 0700);
//See if we have the file in our local cache
string hash = rxm.hash();
if(!RefreshCachedFile(sock, hash, fname))
return;
//It's in cache now, read it
string data = g_cache->ReadCachedFile(hash);
//Write the source file
LogDebug("Writing source file %s\n", aname.c_str());
if(!PutFileContents(aname, data))
return;
//Look up the flags
set<BuildFlag> flags;
for(int i=0; i<rxm.flags_size(); i++)
flags.emplace(BuildFlag(rxm.flags(i)));
//Format the return message
SplashMsg reply;
auto replym = reply.mutable_dependencyresults();
//Run the scanner proper
set<string> deps;
map<string, string> hashes;
if(!chain->ScanDependencies(rxm.arch(), aname, g_builddir, flags, deps, hashes))
{
LogDebug("Scan failed\n");
replym->set_result(false);
SendMessage(sock, reply);
return;
}
//TODO: If the scan found files we're missing, ask for them!
//Successful completion of the scan, crunch the results
LogDebug("Scan completed\n");
replym->set_result(true);
for(auto d : deps)
{
auto rd = replym->add_deps();
rd->set_fname(d);
rd->set_hash(hashes[d]);
}
SendMessage(sock, reply);
}
/**
@brief Process a "build request" message from a client
*/
void ProcessBuildRequest(Socket& sock, const NodeBuildRequest& rxm)
{
LogDebug("\n\nBuild request\n");
LogIndenter li;
//Do setup stuff
Toolchain* chain = PrepBuild(rxm.toolchain());
if(!chain)
return;
//Look up the list of sources
map<string, string> sources; //Map of fname to hash
for(int i=0; i<rxm.sources_size(); i++)
{
auto src = rxm.sources(i);
sources[src.fname()] = src.hash();
}
//Get each source file
set<string> fnames;
for(auto it : sources)
{
string fname = it.first;
string hash = it.second;
//See if we have the file in our local cache
if(!RefreshCachedFile(sock, hash, fname))
return;
//Write it
string path = g_builddir + "/" + GetDirOfFile(fname);
MakeDirectoryRecursive(path, 0700);
string data = g_cache->ReadCachedFile(hash);
string fpath = g_builddir + "/" + fname;
LogDebug("Writing input file %s\n", fpath.c_str());
if(!PutFileContents(fpath, data))
return;
fnames.emplace(fpath);
}
//Look up the list of flags
set<BuildFlag> flags;
for(int i=0; i<rxm.flags_size(); i++)
flags.emplace(BuildFlag(rxm.flags(i)));
//Format the return message
SplashMsg reply;
auto replym = reply.mutable_nodebuildresults();
//Do the actual build
map<string, string> outputs;
if(!chain->Build(
rxm.arch(),
fnames,
rxm.fname(),
flags,
outputs))
{
//TODO: handle failure
}
/*
//Run the scanner proper
set<string> deps;
map<string, string> hashes;
if(!chain->ScanDependencies(rxm.arch(), aname, g_builddir, flags, deps, hashes))
{
LogDebug("Scan failed\n");
replym->set_result(false);
SendMessage(sock, reply);
return;
}
*/
/*
//TODO: If the scan found files we're missing, ask for them!
//Successful completion of the scan, crunch the results
LogDebug("Scan completed\n");
replym->set_result(true);
for(auto d : deps)
{
auto rd = replym->add_deps();
rd->set_fname(d);
rd->set_hash(hashes[d]);
}
SendMessage(sock, reply);
*/
//exit(-1);
}
void ShowVersion()
{
printf(
"SPLASH build server daemon by Andrew D. Zonenberg.\n"
"\n"
"License: 3-clause BSD\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n");
}
void ShowUsage()
{
printf("Usage: splashbuild ctlserver\n");
exit(0);
}
<|endoftext|> |
<commit_before>// FRAGMENT(include)
#include <iostream>
#include <seqan/seq_io.h>
#include <seqan/journaled_set.h>
using namespace seqan;
// FRAGMENT(searchAtBorder)
template <typename TJournalEntriesIterator, typename TJournal, typename TPattern>
void _searchAtBorder(String<int> & hitTarget,
TJournalEntriesIterator & entriesIt,
TJournal const & journal,
TPattern const & pattern)
{
typedef typename Iterator<TJournal const, Standard>::Type TJournalIterator;
// Define region before the border to the next node to search for the pattern.
TJournalIterator nodeIter = iter(journal, entriesIt->virtualPosition + _max(0,(int)entriesIt->length - (int)length(pattern) + 1));
// Define end of search region.
TJournalIterator nodeEnd = iter(journal, _min(entriesIt->virtualPosition + entriesIt->length, length(journal) - length(pattern) + 1));
// Move step by step over search region.
for (; nodeIter != nodeEnd; ++nodeIter)
{
// Define compare iterator.
TJournalIterator verifyIter = nodeIter;
bool isHit = true;
// Compare pattern with current search window.
for (unsigned posPattern = 0; posPattern < length(pattern); ++posPattern, ++verifyIter)
{
// Comparing the pattern value with the current value of the iterator.
if(pattern[posPattern] != getValue(verifyIter))
{
isHit = false;
break;
}
}
// Report hit if found.
if (isHit)
appendValue(hitTarget, position(nodeIter) + entriesIt->virtualPosition);
}
}
// FRAGMENT(findInPatchNodePart1)
template <typename TJournalEntriesIterator, typename TJournal, typename TPattern>
void _findInPatchNode(String<int> & hitTarget,
TJournalEntriesIterator & entriesIt,
TJournal const & journal,
TPattern const & pattern)
{
typedef typename Iterator<TJournal const, Standard>::Type TJournalIterator;
// FRAGMENT(findInPatchNodePart2)
// Search for pattern in the insertion node.
TJournalIterator patchIter = iter(journal, entriesIt->virtualPosition);
TJournalIterator patchEnd = patchIter + _max(0, (int)entriesIt->length - (int)length(pattern) + 1);
// Move step by step over search region.
for (; patchIter != patchEnd; ++patchIter)
{
// FRAGMENT(findInPatchNodePart3)
TJournalIterator verifyIter = patchIter;
bool isHit = true;
// Search for pattern in the insertion node.
for (unsigned posPattern = 0; posPattern < length(pattern); ++posPattern, ++verifyIter)
{
// Comparing the pattern value with the current value of the iterator.
if(pattern[posPattern] != getValue(verifyIter))
{
isHit = false;
break;
}
}
if (isHit)
appendValue(hitTarget, position(patchIter) + entriesIt->virtualPosition);
}
}
// FRAGMENT(findInOriginalNode)
template <typename TJournalEntriesIterator, typename TPattern>
void _findInOriginalNode(String<int> & hitTarget,
TJournalEntriesIterator & entriesIt,
TPattern const & pattern,
String<int> const & refHits)
{
// Define an Iterator which iterates over the reference hit set.
typedef typename Iterator<String<int> const, Standard>::Type THitIterator;
// Check if hits exist in the reference.
if(!empty(refHits))
{
// Find upper bound to physical position in sorted refHits.
THitIterator itHit = std::upper_bound(begin(refHits),end(refHits),(int)entriesIt->physicalPosition);
// Make sure we do not miss hits that begin at physical position of current node.
if(itHit != begin(refHits) && *(itHit - 1) >= (int)entriesIt->physicalPosition)
--itHit;
// Store all hits that are found in the region of the reference which is covered by this node.
while((int)*itHit < ((int)entriesIt->physicalPosition + (int)entriesIt->length - (int)length(pattern) + 1) && itHit != end(refHits))
{
appendValue(hitTarget, entriesIt->virtualPosition + (*itHit - (int)entriesIt->physicalPosition));
++itHit;
}
}
}
// FRAGMENT(findPatternInJournalStringPart1)
template <typename TValue, typename THostSpec, typename TJournalSpec, typename TBufferSpec, typename TPattern>
void findPatternInJournalString(String<int> & hitTarget,
String<TValue, Journaled<THostSpec, TJournalSpec, TBufferSpec> > const & journal,
TPattern const & pattern,
String<int> const & refHits)
{
typedef String<TValue, Journaled<THostSpec, TJournalSpec, TBufferSpec> > const TJournal;
typedef typename JournalType<TJournal>::Type TJournalEntries;
typedef typename Iterator<TJournalEntries>::Type TJournalEntriesIterator;
if (length(pattern) > length(journal))
return;
// FRAGMENT(findPatternInJournalStringPart2)
TJournalEntriesIterator it = begin(journal._journalEntries);
TJournalEntriesIterator itEnd = findInJournalEntries(journal._journalEntries, length(journal) - length(pattern) + 1) + 1;
// FRAGMENT(findPatternInJournalStringPart3)
while(it != itEnd)
{
if (it->segmentSource == SOURCE_ORIGINAL)
{ // Find a possible hit in the current source vertex.
_findInOriginalNode(hitTarget, it, pattern, refHits);
}
if (it->segmentSource == SOURCE_PATCH)
{ // Search for pattern within the patch node.
_findInPatchNode(hitTarget, it, journal, pattern);
}
// Scan the border for a possible match.
_searchAtBorder(hitTarget, it, journal, pattern);
++it;
}
}
// FRAGMENT(findPatternInReference)
template <typename TString, typename TPattern>
void findPatternInReference(String<int> & hits,
TString const & reference,
TPattern const & pattern)
{
// Check whether the pattern fits into the sequence.
if (length(pattern) > length(reference))
return;
//
for (unsigned pos = 0; pos < length(reference) - length(pattern) + 1; ++pos)
{
bool isHit = true;
for (unsigned posPattern = 0; posPattern < length(pattern); ++posPattern)
{
if(pattern[posPattern] != reference[posPattern + pos])
{
isHit = false;
break;
}
}
// Report the position if found a hit.
if(isHit)
appendValue(hits, pos);
}
}
// FRAGMENT(searchPatternPart1)
template <typename TString, typename TPattern>
void searchPattern(StringSet<String<int> > & hitSet,
StringSet<TString, Owner<JournaledSet> > const & journalSet,
TPattern const & pattern)
{
typedef typename Host<TString>::Type THost;
// Check for valid initial state.
if (empty(globalReference(journalSet)))
{
std::cout << "No reference set. Aborted search!" << std::endl;
return;
}
// Reset the hitSet to avoid phantom hits coming from a previous search.
clear(hitSet);
resize(hitSet, length(journalSet) + 1);
// FRAGMENT(searchPatternPart2)
// Access the reference sequence.
THost & globalRef = globalReference(journalSet);
// Search for pattern in the reference sequence.
findPatternInReference(hitSet[0], globalRef, pattern);
// FRAGMENT(searchPatternPart3)
// Search for pattern in the journaled sequences.
for (unsigned i = 0; i < length(journalSet); ++i)
findPatternInJournalString(hitSet[i+1], journalSet[i], pattern, hitSet[0]);
}
// FRAGMENT(laodAndJoin)
template <typename TString, typename TStream, typename TSpec>
inline int
loadAndJoin(StringSet<TString, Owner<JournaledSet> > & journalSet,
TStream & stream,
JoinConfig<TSpec> const & joinConfig)
{
typedef typename Host<TString>::Type THost;
RecordReader<std::ifstream, SinglePass<> > reader(stream);
clear(journalSet);
String<char> seqId;
THost sequence;
// No sequences in the fasta file!
if (atEnd(reader))
{
std::cerr << "Empty FASTA file." << std::endl;
return -1;
}
// First read sequence for reference sequence.
if (readRecord(seqId, sequence, reader, Fasta()) != 0)
{
std::cerr << "ERROR reading FASTA." << std::endl;
return 1;
}
// We have to create the global reference sequence otherwise we loose the information after this function terminates.
createGlobalReference(journalSet, sequence);
// If there are more
while (!atEnd(reader))
{
if (readRecord(seqId, sequence, reader, Fasta()) != 0)
{
std::cerr << "ERROR reading FASTA." << std::endl;
return 1;
}
appendValue(journalSet, TString(sequence));
join(journalSet, length(journalSet) - 1, joinConfig);
}
return 0;
}
// FRAGMENT(main)
int main()
{
// Definition of the used types.
typedef String<Dna,Alloc<> > TSequence;
typedef String<Dna,Journaled<Alloc<>,SortedArray,Alloc<> > > TJournal;
typedef StringSet< TJournal, Owner<JournaledSet> > TJournaledSet;
// Open the stream to the file containing the sequences.
String<char> seqDatabasePath = "/Users/rmaerker/Development/workspace_seqan_trunk/build/debug/sandbox/rmaerker/apps/seqGen/sequences.fasta";
std::ifstream databaseFile(toCString(seqDatabasePath), std::ios_base::in);
if(!databaseFile.good())
{
std::cerr << "Cannot open file <" << seqDatabasePath << ">!" << std::endl;
}
// Reading each sequence and journal them.
TJournaledSet journalSet;
JoinConfig<GlobalAlign<JournaledCompact> > joinConfig;
loadAndJoin(journalSet, databaseFile, joinConfig);
databaseFile.close();
// Define a pattern and start search.
StringSet<String<int> > hitSet;
TSequence pattern = "GTGGT";
std::cout << "Search for: " << pattern << ":\n";
searchPattern(hitSet, journalSet, pattern);
// FRAGMENT(printResult)
if (empty(hitSet[0]))
{
std::cout << "No hit in reference " << std::endl;
}
else
{
std::cout << "Hit in reference " << " at ";
for (unsigned j = 0; j < length(hitSet[0]); ++j)
std::cout << hitSet[0][j] << ": " << infix(globalReference(journalSet), hitSet[0][j],hitSet[0][j] + length(pattern)) << "\t";
}
std::cout << std::endl;
for (unsigned i = 1; i < length(hitSet); ++i)
{
if (empty(hitSet[i]))
{
std::cout << "No hit in sequence " << i - 1 << std::endl;
}
else
{
std::cout << "Hit in sequence " << i - 1 << " at ";
for (unsigned j = 0; j < length(hitSet[i]); ++j)
std::cout << hitSet[i][j] << ": " << infix(value(journalSet,i-1), hitSet[i][j],hitSet[i][j] + length(pattern)) << "\t";
}
std::cout << std::endl;
}
return 0;
}
<commit_msg>[FIX] Fixed problem with demo.<commit_after>// FRAGMENT(include)
#include <iostream>
#include <seqan/seq_io.h>
#include <seqan/journaled_set.h>
using namespace seqan;
// FRAGMENT(searchAtBorder)
template <typename TJournalEntriesIterator, typename TJournal, typename TPattern>
void _searchAtBorder(String<int> & hitTarget,
TJournalEntriesIterator & entriesIt,
TJournal const & journal,
TPattern const & pattern)
{
typedef typename Iterator<TJournal const, Standard>::Type TJournalIterator;
// Define region before the border to the next node to search for the pattern.
TJournalIterator nodeIter = iter(journal, entriesIt->virtualPosition +
_max(0, (int) entriesIt->length - (int) length(pattern) + 1));
// Define end of search region.
TJournalIterator nodeEnd = iter(journal, _min(entriesIt->virtualPosition + entriesIt->length, length(journal) -
length(pattern) + 1));
// Move step by step over search region.
if (nodeEnd == end(journal))
return;
for (; nodeIter != nodeEnd; ++nodeIter)
{
// Define compare iterator.
TJournalIterator verifyIter = nodeIter;
bool isHit = true;
// Compare pattern with current search window.
for (unsigned posPattern = 0; posPattern < length(pattern); ++posPattern, ++verifyIter)
{
// Comparing the pattern value with the current value of the iterator.
if(pattern[posPattern] != getValue(verifyIter))
{
isHit = false;
break;
}
}
// Report hit if found.
if (isHit)
appendValue(hitTarget, position(nodeIter) + entriesIt->virtualPosition);
}
}
// FRAGMENT(findInPatchNodePart1)
template <typename TJournalEntriesIterator, typename TJournal, typename TPattern>
void _findInPatchNode(String<int> & hitTarget,
TJournalEntriesIterator & entriesIt,
TJournal const & journal,
TPattern const & pattern)
{
typedef typename Iterator<TJournal const, Standard>::Type TJournalIterator;
// FRAGMENT(findInPatchNodePart2)
// Search for pattern in the insertion node.
TJournalIterator patchIter = iter(journal, entriesIt->virtualPosition);
TJournalIterator patchEnd = patchIter + _max(0, (int)entriesIt->length - (int)length(pattern) + 1);
// Move step by step over search region.
for (; patchIter != patchEnd; ++patchIter)
{
// FRAGMENT(findInPatchNodePart3)
TJournalIterator verifyIter = patchIter;
bool isHit = true;
// Search for pattern in the insertion node.
for (unsigned posPattern = 0; posPattern < length(pattern); ++posPattern, ++verifyIter)
{
// Comparing the pattern value with the current value of the iterator.
if(pattern[posPattern] != getValue(verifyIter))
{
isHit = false;
break;
}
}
if (isHit)
appendValue(hitTarget, position(patchIter) + entriesIt->virtualPosition);
}
}
// FRAGMENT(findInOriginalNode)
template <typename TJournalEntriesIterator, typename TPattern>
void _findInOriginalNode(String<int> & hitTarget,
TJournalEntriesIterator & entriesIt,
TPattern const & pattern,
String<int> const & refHits)
{
// Define an Iterator which iterates over the reference hit set.
typedef typename Iterator<String<int> const, Standard>::Type THitIterator;
// Check if hits exist in the reference.
if(!empty(refHits))
{
// Find upper bound to physical position in sorted refHits.
THitIterator itHit = std::upper_bound(begin(refHits),end(refHits),(int)entriesIt->physicalPosition);
// Make sure we do not miss hits that begin at physical position of current node.
if(itHit != begin(refHits) && *(itHit - 1) >= (int)entriesIt->physicalPosition)
--itHit;
// Store all hits that are found in the region of the reference which is covered by this node.
while((int)*itHit < ((int)entriesIt->physicalPosition + (int)entriesIt->length - (int)length(pattern) + 1) && itHit != end(refHits))
{
appendValue(hitTarget, entriesIt->virtualPosition + (*itHit - (int)entriesIt->physicalPosition));
++itHit;
}
}
}
// FRAGMENT(findPatternInJournalStringPart1)
template <typename TValue, typename THostSpec, typename TJournalSpec, typename TBufferSpec, typename TPattern>
void findPatternInJournalString(String<int> & hitTarget,
String<TValue, Journaled<THostSpec, TJournalSpec, TBufferSpec> > const & journal,
TPattern const & pattern,
String<int> const & refHits)
{
typedef String<TValue, Journaled<THostSpec, TJournalSpec, TBufferSpec> > const TJournal;
typedef typename JournalType<TJournal>::Type TJournalEntries;
typedef typename Iterator<TJournalEntries>::Type TJournalEntriesIterator;
if (length(pattern) > length(journal))
return;
// FRAGMENT(findPatternInJournalStringPart2)
TJournalEntriesIterator it = begin(journal._journalEntries);
TJournalEntriesIterator itEnd = findInJournalEntries(journal._journalEntries, length(journal) - length(pattern) + 1) + 1;
// FRAGMENT(findPatternInJournalStringPart3)
while(it != itEnd)
{
if (it->segmentSource == SOURCE_ORIGINAL)
{ // Find a possible hit in the current source vertex.
_findInOriginalNode(hitTarget, it, pattern, refHits);
}
if (it->segmentSource == SOURCE_PATCH)
{ // Search for pattern within the patch node.
_findInPatchNode(hitTarget, it, journal, pattern);
}
// Scan the border for a possible match.
_searchAtBorder(hitTarget, it, journal, pattern);
++it;
}
}
// FRAGMENT(findPatternInReference)
template <typename TString, typename TPattern>
void findPatternInReference(String<int> & hits,
TString const & reference,
TPattern const & pattern)
{
// Check whether the pattern fits into the sequence.
if (length(pattern) > length(reference))
return;
//
for (unsigned pos = 0; pos < length(reference) - length(pattern) + 1; ++pos)
{
bool isHit = true;
for (unsigned posPattern = 0; posPattern < length(pattern); ++posPattern)
{
if(pattern[posPattern] != reference[posPattern + pos])
{
isHit = false;
break;
}
}
// Report the position if found a hit.
if(isHit)
appendValue(hits, pos);
}
}
// FRAGMENT(searchPatternPart1)
template <typename TString, typename TPattern>
void searchPattern(StringSet<String<int> > & hitSet,
StringSet<TString, Owner<JournaledSet> > const & journalSet,
TPattern const & pattern)
{
typedef typename Host<TString>::Type THost;
// Check for valid initial state.
if (empty(globalReference(journalSet)))
{
std::cout << "No reference set. Aborted search!" << std::endl;
return;
}
// Reset the hitSet to avoid phantom hits coming from a previous search.
clear(hitSet);
resize(hitSet, length(journalSet) + 1);
// FRAGMENT(searchPatternPart2)
// Access the reference sequence.
THost & globalRef = globalReference(journalSet);
// Search for pattern in the reference sequence.
findPatternInReference(hitSet[0], globalRef, pattern);
// FRAGMENT(searchPatternPart3)
// Search for pattern in the journaled sequences.
for (unsigned i = 0; i < length(journalSet); ++i)
{
std::cout << "Journal: " << journalSet[i] << std::endl;
findPatternInJournalString(hitSet[i+1], journalSet[i], pattern, hitSet[0]);
}
}
// FRAGMENT(laodAndJoin)
template <typename TString, typename TStream, typename TSpec>
inline int
loadAndJoin(StringSet<TString, Owner<JournaledSet> > & journalSet,
TStream & stream,
JoinConfig<TSpec> const & joinConfig)
{
typedef typename Host<TString>::Type THost;
RecordReader<std::ifstream, SinglePass<> > reader(stream);
clear(journalSet);
String<char> seqId;
THost sequence;
// No sequences in the fasta file!
if (atEnd(reader))
{
std::cerr << "Empty FASTA file." << std::endl;
return -1;
}
// First read sequence for reference sequence.
if (readRecord(seqId, sequence, reader, Fasta()) != 0)
{
std::cerr << "ERROR reading FASTA." << std::endl;
return 1;
}
// We have to create the global reference sequence otherwise we loose the information after this function terminates.
createGlobalReference(journalSet, sequence);
// If there are more
while (!atEnd(reader))
{
if (readRecord(seqId, sequence, reader, Fasta()) != 0)
{
std::cerr << "ERROR reading FASTA." << std::endl;
return 1;
}
appendValue(journalSet, TString(sequence));
join(journalSet, length(journalSet) - 1, joinConfig);
}
return 0;
}
// FRAGMENT(main)
int main()
{
// Definition of the used types.
typedef String<Dna,Alloc<> > TSequence;
typedef String<Dna,Journaled<Alloc<>,SortedArray,Alloc<> > > TJournal;
typedef StringSet< TJournal, Owner<JournaledSet> > TJournaledSet;
// Open the stream to the file containing the sequences.
String<char> seqDatabasePath = "/Users/rahn_r/Downloads/sequences.fasta";
std::ifstream databaseFile(toCString(seqDatabasePath), std::ios_base::in);
if(!databaseFile.good())
{
std::cerr << "Cannot open file <" << seqDatabasePath << ">!" << std::endl;
}
// Reading each sequence and journal them.
TJournaledSet journalSet;
JoinConfig<GlobalAlign<JournaledCompact> > joinConfig;
loadAndJoin(journalSet, databaseFile, joinConfig);
databaseFile.close();
// Define a pattern and start search.
StringSet<String<int> > hitSet;
TSequence pattern = "GTGGT";
std::cout << "Search for: " << pattern << ":\n";
searchPattern(hitSet, journalSet, pattern);
// FRAGMENT(printResult)
if (empty(hitSet[0]))
{
std::cout << "No hit in reference " << std::endl;
}
else
{
std::cout << "Hit in reference " << " at ";
for (unsigned j = 0; j < length(hitSet[0]); ++j)
std::cout << hitSet[0][j] << ": " << infix(globalReference(journalSet), hitSet[0][j],hitSet[0][j] + length(pattern)) << "\t";
}
std::cout << std::endl;
for (unsigned i = 1; i < length(hitSet); ++i)
{
if (empty(hitSet[i]))
{
std::cout << "No hit in sequence " << i - 1 << std::endl;
}
else
{
std::cout << "Hit in sequence " << i - 1 << " at ";
for (unsigned j = 0; j < length(hitSet[i]); ++j)
std::cout << hitSet[i][j] << ": " << infix(value(journalSet,i-1), hitSet[i][j],hitSet[i][j] + length(pattern)) << "\t";
}
std::cout << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <windows.h>
#include <tchar.h>
#include "resource.h"
#include "MyMsgProc.h"
#include "server\LowDbAccess.h"
#include "server\VarController.h"
int GetMsgWidth(HWND WndHndl, TCHAR* Msg);
int GetMsgHeight(HWND WndHndl, TCHAR* Msg);
HWND HttpHdDelHttp = NULL;
bool HttpHdDelHttpFlag = false;
HWND HttpHdAddHttp = NULL;
bool HttpHdAddHttpFlag = false;
HWND HttpHdContentLen = NULL;
bool HttpHdContentLenFlag = false;
HWND HttpHdDate = NULL;
bool HttpHdDateFlag = false;
HWND HttpHdRequest = NULL;
bool HttpHdRequestFlag = false;
HWND HttpHdResponse = NULL;
HWND HttpHeaderEd = NULL;
wchar_t HttpHeaderEdBox[1024] = L"";
void ChangeHttpHeader()
{
if (HttpHdDelHttpFlag == true) {
SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_CHECKED, 0L);
EnableWindow(HttpHdDelHttp, true);
} else {
SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
EnableWindow(HttpHdDelHttp, true);
}
bool HttpHdFlag = false;
if (HttpHdAddHttpFlag == false) {
HttpHdFlag = false;
SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
EnableWindow(HttpHdAddHttp, true);
} else {
HttpHdFlag = true;
SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_CHECKED, 0L);
EnableWindow(HttpHdAddHttp, true);
}
EnableWindow(HttpHdContentLen, HttpHdFlag);
EnableWindow(HttpHdDate, HttpHdFlag);
EnableWindow(HttpHdRequest, HttpHdFlag);
EnableWindow(HttpHdResponse, HttpHdFlag);
EnableWindow(HttpHeaderEd, HttpHdFlag);
SendMessage(HttpHdContentLen, BM_SETCHECK, (HttpHdContentLenFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
SendMessage(HttpHdDate, BM_SETCHECK, (HttpHdDateFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
SendMessage(HttpHdRequest, BM_SETCHECK, (HttpHdRequestFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
SendMessage(HttpHdResponse, BM_SETCHECK, (HttpHdRequestFlag == true) ? BST_UNCHECKED : BST_CHECKED, 0L);
}
void HttpHeader(int CurrentId, int Type, HINSTANCE InstHndl, HWND WndHndl, UINT message, WPARAM wParam, LPARAM lParam)
{
RECT Rect;
GetClientRect(WndHndl, &Rect);
if (message == WM_CREATE) {
HttpHdDelHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 100,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)),
WndHndl, (HMENU)IDC_HTTPHD_DELETE, InstHndl, NULL);
HttpHdAddHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 130,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)),
WndHndl, (HMENU)IDC_HTTPHD_ADD, InstHndl, NULL);
HttpHdContentLen = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 160,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)),
WndHndl, (HMENU)IDC_HTTPHD_CONTLEN, InstHndl, NULL);
HttpHdDate = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 190,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)),
WndHndl, (HMENU)IDC_HTTPHD_DATE, InstHndl, NULL);
HttpHdRequest = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 40, 220,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)),
WndHndl, (HMENU)IDC_HTTPHD_REQUEST, InstHndl, NULL);
HttpHdResponse = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 40, 250,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)),
WndHndl, (HMENU)IDC_HTTPHD_RESPONSE, InstHndl, NULL);
HttpHeaderEd = CreateWindowEx(WS_EX_CLIENTEDGE, _T("EDIT"), _T(""), WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL, Rect.left + 40, 280, Rect.right - 50, 210, WndHndl, NULL, InstHndl, NULL);
SendMessage(HttpHeaderEd, EM_SETLIMITTEXT, (WPARAM)1024, (LPARAM)0);
SendMessage(HttpHeaderEd, WM_SETTEXT, (WPARAM)0, (LPARAM)HttpHeaderEdBox);
ChangeHttpHeader();
}
if (message == WM_COMMAND) {
if (HIWORD(wParam) == BN_CLICKED) {
if (LOWORD(wParam) == IDC_HTTPHD_DELETE) {
if (HttpHdDelHttpFlag == false) {
HttpHdDelHttpFlag = true;
} else {
HttpHdDelHttpFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_ADD) {
if (HttpHdAddHttpFlag == false) {
HttpHdAddHttpFlag = true;
} else {
HttpHdAddHttpFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_CONTLEN) {
if (HttpHdContentLenFlag == false) {
HttpHdContentLenFlag = true;
} else {
HttpHdContentLenFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_DATE) {
if (HttpHdDateFlag == false) {
HttpHdDateFlag = true;
} else {
HttpHdDateFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_REQUEST) {
HttpHdRequestFlag = true;
}
if (LOWORD(wParam) == IDC_HTTPHD_RESPONSE) {
HttpHdRequestFlag = false;
}
ChangeHttpHeader();
}
}
}
<commit_msg>#41 : Edit box operation<commit_after>#include <windows.h>
#include <tchar.h>
#include <cwchar>
#include <cstring>
#include "resource.h"
#include "MyMsgProc.h"
#include "server\LowDbAccess.h"
#include "server\VarController.h"
int GetMsgWidth(HWND WndHndl, TCHAR* Msg);
int GetMsgHeight(HWND WndHndl, TCHAR* Msg);
HWND HttpHdDelHttp = NULL;
bool HttpHdDelHttpFlag = false;
HWND HttpHdAddHttp = NULL;
bool HttpHdAddHttpFlag = false;
HWND HttpHdContentLen = NULL;
bool HttpHdContentLenFlag = false;
HWND HttpHdDate = NULL;
bool HttpHdDateFlag = false;
HWND HttpHdRequest = NULL;
bool HttpHdRequestFlag = false;
HWND HttpHdResponse = NULL;
HWND HttpHeaderEd = NULL;
wchar_t HttpHeaderEdBox[1024] = L"hello";
void ChangeHttpHeader()
{
if (HttpHdDelHttpFlag == true) {
SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_CHECKED, 0L);
EnableWindow(HttpHdDelHttp, true);
} else {
SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
EnableWindow(HttpHdDelHttp, true);
}
bool HttpHdFlag = false;
if (HttpHdAddHttpFlag == false) {
HttpHdFlag = false;
SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
EnableWindow(HttpHdAddHttp, true);
} else {
HttpHdFlag = true;
SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_CHECKED, 0L);
EnableWindow(HttpHdAddHttp, true);
}
EnableWindow(HttpHdContentLen, HttpHdFlag);
EnableWindow(HttpHdDate, HttpHdFlag);
EnableWindow(HttpHdRequest, HttpHdFlag);
EnableWindow(HttpHdResponse, HttpHdFlag);
EnableWindow(HttpHeaderEd, HttpHdFlag);
SendMessage(HttpHdContentLen, BM_SETCHECK, (HttpHdContentLenFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
SendMessage(HttpHdDate, BM_SETCHECK, (HttpHdDateFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
SendMessage(HttpHdRequest, BM_SETCHECK, (HttpHdRequestFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
SendMessage(HttpHdResponse, BM_SETCHECK, (HttpHdRequestFlag == true) ? BST_UNCHECKED : BST_CHECKED, 0L);
}
void UpdateHttpHeaderEdBoxForDate(bool Enable)
{
wchar_t HttpHeaderEdBoxTmp[1024] = L"";
wchar_t* tmp_ptr = HttpHeaderEdBoxTmp;
wchar_t* begin_ptr = NULL;
wchar_t* end_ptr = NULL;
SendMessage(HttpHeaderEd, WM_GETTEXT, (WPARAM)1024, (LPARAM)HttpHeaderEdBox);
begin_ptr = wcsstr(HttpHeaderEdBox, L"Date");
if (begin_ptr) {
end_ptr = wcsstr(begin_ptr, L"\r\n");
}
if (begin_ptr && end_ptr) {
//memcpy((char*)HttpHeaderEdBoxTmp, (char*)HttpHeaderEdBox, (char*)begin_ptr - (char*)HttpHeaderEdBox);
for (wchar_t* i = HttpHeaderEdBox; i < begin_ptr; i++) {
*tmp_ptr = *i;
tmp_ptr++;
}
for (wchar_t* i = end_ptr + 2; *i != '\0'; i++) {
*tmp_ptr = *i;
tmp_ptr++;
}
SendMessage(HttpHeaderEd, WM_SETTEXT, (WPARAM)0, (LPARAM)HttpHeaderEdBoxTmp);
}
}
void HttpHeader(int CurrentId, int Type, HINSTANCE InstHndl, HWND WndHndl, UINT message, WPARAM wParam, LPARAM lParam)
{
RECT Rect;
GetClientRect(WndHndl, &Rect);
if (message == WM_CREATE) {
HttpHdDelHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 100,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)),
WndHndl, (HMENU)IDC_HTTPHD_DELETE, InstHndl, NULL);
HttpHdAddHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 130,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)),
WndHndl, (HMENU)IDC_HTTPHD_ADD, InstHndl, NULL);
HttpHdContentLen = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 160,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)),
WndHndl, (HMENU)IDC_HTTPHD_CONTLEN, InstHndl, NULL);
HttpHdDate = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 190,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)),
WndHndl, (HMENU)IDC_HTTPHD_DATE, InstHndl, NULL);
HttpHdRequest = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 40, 220,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)),
WndHndl, (HMENU)IDC_HTTPHD_REQUEST, InstHndl, NULL);
HttpHdResponse = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 40, 250,
GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)) + 30,
GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)),
WndHndl, (HMENU)IDC_HTTPHD_RESPONSE, InstHndl, NULL);
HttpHeaderEd = CreateWindowEx(WS_EX_CLIENTEDGE, _T("EDIT"), _T(""), WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE, Rect.left + 40, 280, Rect.right - 50, 210, WndHndl, NULL, InstHndl, NULL);
SendMessage(HttpHeaderEd, EM_SETLIMITTEXT, (WPARAM)1024, (LPARAM)0);
SendMessage(HttpHeaderEd, WM_SETTEXT, (WPARAM)0, (LPARAM)HttpHeaderEdBox);
ChangeHttpHeader();
}
if (message == WM_COMMAND) {
if (HIWORD(wParam) == BN_CLICKED) {
if (LOWORD(wParam) == IDC_HTTPHD_DELETE) {
if (HttpHdDelHttpFlag == false) {
HttpHdDelHttpFlag = true;
} else {
HttpHdDelHttpFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_ADD) {
if (HttpHdAddHttpFlag == false) {
HttpHdAddHttpFlag = true;
} else {
HttpHdAddHttpFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_CONTLEN) {
if (HttpHdContentLenFlag == false) {
HttpHdContentLenFlag = true;
} else {
HttpHdContentLenFlag = false;
}
}
if (LOWORD(wParam) == IDC_HTTPHD_DATE) {
if (HttpHdDateFlag == false) {
HttpHdDateFlag = true;
} else {
HttpHdDateFlag = false;
}
UpdateHttpHeaderEdBoxForDate(HttpHdDateFlag);
}
if (LOWORD(wParam) == IDC_HTTPHD_REQUEST) {
HttpHdRequestFlag = true;
}
if (LOWORD(wParam) == IDC_HTTPHD_RESPONSE) {
HttpHdRequestFlag = false;
}
ChangeHttpHeader();
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmservs.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:08:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif
#ifndef _FM_STATIC_HXX_
#include "fmstatic.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
namespace svxform
{
// -----------------------
// service names for compatibility
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_EDIT,"stardiv.one.form.component.Edit"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TEXTFIELD,"stardiv.one.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_LISTBOX,"stardiv.one.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMBOBOX,"stardiv.one.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_RADIOBUTTON,"stardiv.one.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GROUPBOX,"stardiv.one.form.component.GroupBox"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FIXEDTEXT,"stardiv.one.form.component.FixedText"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMMANDBUTTON,"stardiv.one.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CHECKBOX,"stardiv.one.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRID,"stardiv.one.form.component.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRIDCONTROL,"stardiv.one.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGEBUTTON,"stardiv.one.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FILECONTROL,"stardiv.one.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TIMEFIELD,"stardiv.one.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_DATEFIELD,"stardiv.one.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_NUMERICFIELD,"stardiv.one.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CURRENCYFIELD,"stardiv.one.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_PATTERNFIELD,"stardiv.one.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDEN,"stardiv.one.form.component.Hidden");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDENCONTROL,"stardiv.one.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGECONTROL,"stardiv.one.form.component.ImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FORMATTEDFIELD,"stardiv.one.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRID,"stardiv.one.form.control.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRIDCONTROL,"stardiv.one.form.control.GridControl");
// -----------------------
// new (sun) service names
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORM,"com.sun.star.form.component.Form");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TEXTFIELD,"com.sun.star.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_LISTBOX,"com.sun.star.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMBOBOX,"com.sun.star.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_RADIOBUTTON,"com.sun.star.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GROUPBOX,"com.sun.star.form.component.GroupBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FIXEDTEXT,"com.sun.star.form.component.FixedText");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMMANDBUTTON,"com.sun.star.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CHECKBOX,"com.sun.star.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GRIDCONTROL,"com.sun.star.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGEBUTTON,"com.sun.star.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FILECONTROL,"com.sun.star.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TIMEFIELD,"com.sun.star.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_DATEFIELD,"com.sun.star.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_NUMERICFIELD,"com.sun.star.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CURRENCYFIELD,"com.sun.star.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_PATTERNFIELD,"com.sun.star.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_HIDDENCONTROL,"com.sun.star.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGECONTROL,"com.sun.star.form.component.DatabaseImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORMATTEDFIELD,"com.sun.star.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SCROLLBAR, "com.sun.star.form.component.ScrollBar" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SPINBUTTON, "com.sun.star.form.component.SpinButton" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_NAVIGATIONBAR,"com.sun.star.form.component.NavigationToolBar" );
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_CONTROL_GRIDCONTROL,"com.sun.star.form.control.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_NUMBER_FORMATTER,"com.sun.star.util.NumberFormatter");
IMPLEMENT_CONSTASCII_USTRING(FM_FORM_CONTROLLER,"com.sun.star.form.FormController");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_CONNECTION,"com.sun.star.sdb.Connection");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_INTERACTION_HANDLER,"com.sun.star.sdb.InteractionHandler");
} // namespace svxform
// ------------------------------------------------------------------------
#define DECL_SERVICE(ImplName) \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ImplName##_NewInstance_Impl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &) throw( ::com::sun::star::uno::Exception );
#define REGISTER_SERVICE(ImplName, ServiceName) \
sString = (ServiceName); \
xSingleFactory = ::cppu::createSingleFactory(xServiceFactory, \
::rtl::OUString(), ImplName##_NewInstance_Impl, \
::com::sun::star::uno::Sequence< ::rtl::OUString>(&sString, 1)); \
if (xSingleFactory.is()) \
xSet->insert(::com::sun::star::uno::makeAny(xSingleFactory));
DECL_SERVICE( FmXGridControl )
DECL_SERVICE( FmXFormController )
// ------------------------------------------------------------------------
namespace svxform
{
#define DECL_SELFAWARE_SERVICE( ClassName ) \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ClassName##_Create( \
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); \
::rtl::OUString SAL_CALL ClassName##_GetImplementationName(); \
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL ClassName##_GetSupportedServiceNames(); \
#define REGISTER_SELFAWARE_SERVICE( ClassName ) \
xSingleFactory = ::cppu::createSingleFactory( xServiceFactory, \
ClassName##_GetImplementationName(), \
ClassName##_Create, \
ClassName##_GetSupportedServiceNames() \
); \
if ( xSingleFactory.is() ) \
xSet->insert( ::com::sun::star::uno::makeAny( xSingleFactory ) );
// ------------------------------------------------------------------------
DECL_SELFAWARE_SERVICE( OAddConditionDialog )
// ------------------------------------------------------------------------
void ImplSmartRegisterUnoServices()
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory(::comphelper::getProcessServiceFactory(), ::com::sun::star::uno::UNO_QUERY);
::com::sun::star::uno::Reference< ::com::sun::star::container::XSet > xSet(xServiceFactory, ::com::sun::star::uno::UNO_QUERY);
if (!xSet.is())
return;
::com::sun::star::uno::Sequence< ::rtl::OUString> aServices;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > xSingleFactory;
::rtl::OUString sString;
// ------------------------------------------------------------------------
// FormController
REGISTER_SERVICE(FmXFormController, FM_FORM_CONTROLLER);
// ------------------------------------------------------------------------
// FormController
REGISTER_SELFAWARE_SERVICE( OAddConditionDialog );
// ------------------------------------------------------------------------
// DBGridControl
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRID); // compatibility
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRIDCONTROL);
REGISTER_SERVICE(FmXGridControl, FM_SUN_CONTROL_GRIDCONTROL);
};
} // namespace svxform
<commit_msg>INTEGRATION: CWS changefileheader (1.16.730); FILE MERGED 2008/04/01 15:51:02 thb 1.16.730.3: #i85898# Stripping all external header guards 2008/04/01 12:48:51 thb 1.16.730.2: #i85898# Stripping all external header guards 2008/03/31 14:21:55 rt 1.16.730.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmservs.cxx,v $
* $Revision: 1.17 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <com/sun/star/container/XSet.hpp>
#include "fmstatic.hxx"
#include <cppuhelper/factory.hxx>
#include <comphelper/processfactory.hxx>
namespace svxform
{
// -----------------------
// service names for compatibility
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_EDIT,"stardiv.one.form.component.Edit"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TEXTFIELD,"stardiv.one.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_LISTBOX,"stardiv.one.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMBOBOX,"stardiv.one.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_RADIOBUTTON,"stardiv.one.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GROUPBOX,"stardiv.one.form.component.GroupBox"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FIXEDTEXT,"stardiv.one.form.component.FixedText"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMMANDBUTTON,"stardiv.one.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CHECKBOX,"stardiv.one.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRID,"stardiv.one.form.component.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRIDCONTROL,"stardiv.one.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGEBUTTON,"stardiv.one.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FILECONTROL,"stardiv.one.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TIMEFIELD,"stardiv.one.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_DATEFIELD,"stardiv.one.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_NUMERICFIELD,"stardiv.one.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CURRENCYFIELD,"stardiv.one.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_PATTERNFIELD,"stardiv.one.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDEN,"stardiv.one.form.component.Hidden");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDENCONTROL,"stardiv.one.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGECONTROL,"stardiv.one.form.component.ImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FORMATTEDFIELD,"stardiv.one.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRID,"stardiv.one.form.control.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRIDCONTROL,"stardiv.one.form.control.GridControl");
// -----------------------
// new (sun) service names
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORM,"com.sun.star.form.component.Form");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TEXTFIELD,"com.sun.star.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_LISTBOX,"com.sun.star.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMBOBOX,"com.sun.star.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_RADIOBUTTON,"com.sun.star.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GROUPBOX,"com.sun.star.form.component.GroupBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FIXEDTEXT,"com.sun.star.form.component.FixedText");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMMANDBUTTON,"com.sun.star.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CHECKBOX,"com.sun.star.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GRIDCONTROL,"com.sun.star.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGEBUTTON,"com.sun.star.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FILECONTROL,"com.sun.star.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TIMEFIELD,"com.sun.star.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_DATEFIELD,"com.sun.star.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_NUMERICFIELD,"com.sun.star.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CURRENCYFIELD,"com.sun.star.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_PATTERNFIELD,"com.sun.star.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_HIDDENCONTROL,"com.sun.star.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGECONTROL,"com.sun.star.form.component.DatabaseImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORMATTEDFIELD,"com.sun.star.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SCROLLBAR, "com.sun.star.form.component.ScrollBar" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SPINBUTTON, "com.sun.star.form.component.SpinButton" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_NAVIGATIONBAR,"com.sun.star.form.component.NavigationToolBar" );
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_CONTROL_GRIDCONTROL,"com.sun.star.form.control.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_NUMBER_FORMATTER,"com.sun.star.util.NumberFormatter");
IMPLEMENT_CONSTASCII_USTRING(FM_FORM_CONTROLLER,"com.sun.star.form.FormController");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_CONNECTION,"com.sun.star.sdb.Connection");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_INTERACTION_HANDLER,"com.sun.star.sdb.InteractionHandler");
} // namespace svxform
// ------------------------------------------------------------------------
#define DECL_SERVICE(ImplName) \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ImplName##_NewInstance_Impl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &) throw( ::com::sun::star::uno::Exception );
#define REGISTER_SERVICE(ImplName, ServiceName) \
sString = (ServiceName); \
xSingleFactory = ::cppu::createSingleFactory(xServiceFactory, \
::rtl::OUString(), ImplName##_NewInstance_Impl, \
::com::sun::star::uno::Sequence< ::rtl::OUString>(&sString, 1)); \
if (xSingleFactory.is()) \
xSet->insert(::com::sun::star::uno::makeAny(xSingleFactory));
DECL_SERVICE( FmXGridControl )
DECL_SERVICE( FmXFormController )
// ------------------------------------------------------------------------
namespace svxform
{
#define DECL_SELFAWARE_SERVICE( ClassName ) \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ClassName##_Create( \
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); \
::rtl::OUString SAL_CALL ClassName##_GetImplementationName(); \
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL ClassName##_GetSupportedServiceNames(); \
#define REGISTER_SELFAWARE_SERVICE( ClassName ) \
xSingleFactory = ::cppu::createSingleFactory( xServiceFactory, \
ClassName##_GetImplementationName(), \
ClassName##_Create, \
ClassName##_GetSupportedServiceNames() \
); \
if ( xSingleFactory.is() ) \
xSet->insert( ::com::sun::star::uno::makeAny( xSingleFactory ) );
// ------------------------------------------------------------------------
DECL_SELFAWARE_SERVICE( OAddConditionDialog )
// ------------------------------------------------------------------------
void ImplSmartRegisterUnoServices()
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory(::comphelper::getProcessServiceFactory(), ::com::sun::star::uno::UNO_QUERY);
::com::sun::star::uno::Reference< ::com::sun::star::container::XSet > xSet(xServiceFactory, ::com::sun::star::uno::UNO_QUERY);
if (!xSet.is())
return;
::com::sun::star::uno::Sequence< ::rtl::OUString> aServices;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > xSingleFactory;
::rtl::OUString sString;
// ------------------------------------------------------------------------
// FormController
REGISTER_SERVICE(FmXFormController, FM_FORM_CONTROLLER);
// ------------------------------------------------------------------------
// FormController
REGISTER_SELFAWARE_SERVICE( OAddConditionDialog );
// ------------------------------------------------------------------------
// DBGridControl
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRID); // compatibility
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRIDCONTROL);
REGISTER_SERVICE(FmXGridControl, FM_SUN_CONTROL_GRIDCONTROL);
};
} // namespace svxform
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: prtopt.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: mtg $ $Date: 2001-08-08 21:38:13 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PRTOPT_HXX
#define _PRTOPT_HXX
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _SW_PRINTDATA_HXX
#include <printdata.hxx>
#endif
class SwPrintOptions : public SwPrintData, public utl::ConfigItem
{
sal_Bool bIsWeb;
com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
SwPrintOptions(sal_Bool bWeb);
virtual ~SwPrintOptions();
virtual void Commit();
virtual void doSetModified( ) { bModified = sal_True; SetModified();}
SwPrintOptions& operator=(const SwPrintData& rData)
{
SwPrintData::operator=( rData );
SetModified();
return *this;
}
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.1444); FILE MERGED 2005/09/05 13:45:33 rt 1.5.1444.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: prtopt.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09: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
*
************************************************************************/
#ifndef _PRTOPT_HXX
#define _PRTOPT_HXX
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _SW_PRINTDATA_HXX
#include <printdata.hxx>
#endif
class SwPrintOptions : public SwPrintData, public utl::ConfigItem
{
sal_Bool bIsWeb;
com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
SwPrintOptions(sal_Bool bWeb);
virtual ~SwPrintOptions();
virtual void Commit();
virtual void doSetModified( ) { bModified = sal_True; SetModified();}
SwPrintOptions& operator=(const SwPrintData& rData)
{
SwPrintData::operator=( rData );
SetModified();
return *this;
}
};
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperStringListParameter.h"
#include "otbVectorData.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataToRandomLineGenerator.h"
#include "itkAmoebaOptimizer.h"
#include "otbVectorDataToDSValidatedVectorDataFilter.h"
#include "otbStandardDSCostFunction.h"
#include "otbFuzzyDescriptorsModelManager.h"
namespace otb
{
namespace Wrapper
{
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::AmoebaOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer =
dynamic_cast< OptimizerPointer >( object );
if( ! itk::IterationEvent().CheckEvent( &event ) )
{
return;
}
std::ostringstream message;
message << optimizer->GetCachedValue() << " ";
message << optimizer->GetCachedCurrentPosition() << std::endl;
std::cout<<message.str()<<std::endl;
}
};
class DSFuzzyModelEstimation: public Application
{
public:
/** Standard class typedefs. */
typedef DSFuzzyModelEstimation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef VectorData<double> VectorDataType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef VectorDataType::ValuePrecisionType PrecisionType;
typedef VectorDataType::PrecisionType CoordRepType;
typedef otb::Wrapper::StringListParameter::StringListType StringListType;
typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType>
ValidationFilterType;
typedef otb::StandardDSCostFunction<ValidationFilterType> CostFunctionType;
typedef CostFunctionType::LabelSetType LabelSetType;
typedef itk::AmoebaOptimizer OptimizerType;
typedef otb::FuzzyDescriptorsModelManager::DescriptorsModelType
DescriptorsModelType;
typedef otb::FuzzyDescriptorsModelManager::DescriptorListType
DescriptorListType;
typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType>
TreeIteratorType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(DSFuzzyModelEstimation, otb::Application);
private:
void DoInit()
{
SetName("DSFuzzyModelEstimation");
SetDescription("Estimate feature fuzzy model parameters using 2 vector data (ground truth samples and wrong samples).");
SetDocName("Fuzzy Model estimation");
SetDocLongDescription("Estimate feature fuzzy model parameters using 2 vector data (ground truth samples and wrong samples).");
SetDocLimitations("None.");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::FeatureExtraction);
AddParameter(ParameterType_InputVectorData, "psin", "Input Positive Vector Data");
SetParameterDescription("psin", "Ground truth vector data for positive samples");
AddParameter(ParameterType_InputVectorData, "nsin", "Input Negative Vector Data");
SetParameterDescription("nsin", "Ground truth vector data for negative samples");
AddParameter(ParameterType_StringList, "belsup", "Belief Support");
SetParameterDescription("belsup", "Dempster Shafer study hypothesis to compute belief");
AddParameter(ParameterType_StringList, "plasup", "Plausibility Support");
SetParameterDescription("plasup", "Dempster Shafer study hypothesis to compute plausibility");
AddParameter(ParameterType_String, "cri", "Criterion");
SetParameterDescription("cri", "Dempster Shafer criterion (by default (belief+plausibility)/2)");
MandatoryOff("cri");
SetParameterString("cri","((Belief + Plausibility)/2.)");
AddParameter(ParameterType_Float,"wgt","Weighting");
SetParameterDescription("wgt","Coefficient between 0 and 1 to promote undetection or false detections (default 0.5)");
MandatoryOff("wgt");
SetParameterFloat("wgt", 0.5);
AddParameter(ParameterType_InputFilename,"initmod","initialization model");
SetParameterDescription("initmod","Initialization model (xml file) to be used. If the xml initialization model is set, the descriptor list is not used (specified using the option -desclist)");
MandatoryOff("initmod");
AddParameter(ParameterType_StringList, "desclist","Descriptor list");
SetParameterDescription("desclist","List of the descriptors to be used in the model (must be specified to perform an automatic initialization)");
MandatoryOff("desclist");
SetParameterString("desclist","");
AddParameter(ParameterType_Int,"maxnbit","Maximum number of iterations");
MandatoryOff("maxnbit");
SetParameterDescription("maxnbit","Maximum number of optimizer iteration (default 200)");
SetParameterInt("maxnbit", 200);
AddParameter(ParameterType_Empty,"optobs","Optimizer Observer");
SetParameterDescription("optobs","Activate the optimizer observer");
MandatoryOff("optobs");
AddParameter(ParameterType_OutputFilename,"out","Output filename");
SetParameterDescription("out","Output model file name (xml file) contains the optimal model to perform informations fusion.");
// Doc example parameter settings
SetDocExampleParameterValue("psin", "cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_gt.shp");
SetDocExampleParameterValue("nsin", "cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_wr.shp");
SetDocExampleParameterValue("belsup", "\"ROADSA\"");
SetDocExampleParameterValue("plasup", "\"NONDVI\" \"ROADSA\" \"NOBUIL\"");
SetDocExampleParameterValue("initmod", "Dempster-Shafer/DSFuzzyModel_Init.xml");
SetDocExampleParameterValue("maxnbit", "4");
SetDocExampleParameterValue("optobs", "true");
SetDocExampleParameterValue("out", "DSFuzzyModelEstimation.xml");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
// .. //
}
void DoExecute()
{
//Instantiate
m_CostFunction = CostFunctionType::New();
m_Optimizer = OptimizerType::New();
//Read the vector datas
VectorDataType::Pointer psVectorData = GetParameterVectorData("psin");
psVectorData->Update();
VectorDataType::Pointer nsVectorData = GetParameterVectorData("nsin");
nsVectorData->Update();
// Load the initial descriptor model
DescriptorListType descList;
DescriptorsModelType descMod;
if (IsParameterEnabled("initmod"))
{
std::string descModFile = GetParameterString("initmod");
descMod = FuzzyDescriptorsModelManager::Read(descModFile.c_str());
descList = FuzzyDescriptorsModelManager::GetDescriptorList(descMod);
}
else
{
StringListType stringList = GetParameterStringList("desclist");
int nbsdDesc = stringList.size();
for (int i = 0; i < nbsdDesc; i++)
{
descList.push_back(stringList[i]);
}
}
m_CostFunction->SetDescriptorList(descList);
// Compute statistics of all the descriptors
std::vector<double> accFirstOrderPS, accSecondOrderPS, minPS, maxPS;
accFirstOrderPS.resize(descList.size());
accSecondOrderPS.resize(descList.size());
std::fill(accFirstOrderPS.begin(), accFirstOrderPS.end(), 0);
std::fill(accSecondOrderPS.begin(), accSecondOrderPS.end(), 0);
minPS.resize(descList.size());
maxPS.resize(descList.size());
unsigned int accNbElemPS = 0;
TreeIteratorType itVectorPS(psVectorData->GetDataTree());
for (itVectorPS.GoToBegin(); !itVectorPS.IsAtEnd(); ++itVectorPS)
{
if (!itVectorPS.Get()->IsRoot() && !itVectorPS.Get()->IsDocument() && !itVectorPS.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVectorPS.Get();
for (unsigned int i = 0; i < descList.size(); ++i)
{
double desc = currentGeometry->GetFieldAsDouble(descList[i]);
accFirstOrderPS[i] += desc;
accSecondOrderPS[i] += desc * desc;
if (desc < minPS[i])
{
minPS[i] = desc;
}
if (desc > maxPS[i])
{
maxPS[i] = desc;
}
}
accNbElemPS++;
}
}
TreeIteratorType itVectorNS(nsVectorData->GetDataTree());
std::vector<double> accFirstOrderNS, accSecondOrderNS, minNS, maxNS;
minNS.resize(descList.size());
maxNS.resize(descList.size());
accFirstOrderNS.resize(descList.size());
accSecondOrderNS.resize(descList.size());
std::fill(accFirstOrderNS.begin(), accFirstOrderNS.end(), 0);
std::fill(accSecondOrderNS.begin(), accSecondOrderNS.end(), 0);
std::fill(minNS.begin(), minNS.end(), 1);
std::fill(maxNS.begin(), maxNS.end(), 0);
unsigned int accNbElemNS = 0;
for (itVectorNS.GoToBegin(); !itVectorNS.IsAtEnd(); ++itVectorNS)
{
if (!itVectorNS.Get()->IsRoot() && !itVectorNS.Get()->IsDocument() && !itVectorNS.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVectorNS.Get();
for (unsigned int i = 0; i < descList.size(); ++i)
{
double desc = currentGeometry->GetFieldAsDouble(descList[i]);
accFirstOrderNS[i] += desc;
accSecondOrderNS[i] += desc * desc;
if (desc < minNS[i])
{
minNS[i] = desc;
}
if (desc > maxNS[i])
{
maxNS[i] = desc;
}
}
accNbElemNS++;
}
}
otbAppLogINFO( << "Descriptors Stats : ");
otbAppLogINFO( << "Positive Samples");
for (unsigned int i = 0; i < descList.size(); ++i)
{
double mean = accFirstOrderPS[i] / accNbElemPS;
double stddev = vcl_sqrt(accSecondOrderPS[i] / accNbElemPS - mean * mean);
otbAppLogINFO( << descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minPS[i] << " max: " << maxPS[i] << ")"<< std::endl);
}
otbAppLogINFO( << "Negative Samples" << std::endl);
for (unsigned int i = 0; i < descList.size(); ++i)
{
double mean = accFirstOrderNS[i] / accNbElemNS;
double stddev = vcl_sqrt(accSecondOrderNS[i] / accNbElemNS - mean * mean);
otbAppLogINFO(<< descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minNS[i] << " max: " << maxNS[i] << ")"<< std::endl);
}
OptimizerType::ParametersType initialPosition(4 * descList.size());
if (IsParameterEnabled("initmod"))
{
for (unsigned int i = 0; i < 4; i++)
{
for (unsigned int j = 0; j < descList.size(); j++)
{
initialPosition.SetElement(
i + 4 * j,
otb::FuzzyDescriptorsModelManager::GetDescriptor(descList[j].c_str(), descMod).second[i]);
}
}
}
else
{
for (unsigned int j = 0; j < descList.size(); j++)
{
initialPosition.SetElement((j * 4), std::min(minNS[j], maxPS[j]));
initialPosition.SetElement((j * 4) + 2, std::max(minNS[j], maxPS[j]));
initialPosition.SetElement(
(j * 4) + 1,
0.5
* (initialPosition.GetElement((j * 4)) + initialPosition.GetElement((j * 4) + 2)));
initialPosition.SetElement((j * 4) + 3, 0.95);
}
}
//Cost Function
//Format Hypothesis
LabelSetType Bhyp, Phyp;
int nbSet;
StringListType stringList = GetParameterStringList("belsup");
nbSet = stringList.size();
for (int i = 0; i < nbSet; i++)
{
std::string str = stringList[i];
Bhyp.insert(str);
}
m_CostFunction->SetBeliefHypothesis(Bhyp);
stringList = GetParameterStringList("plasup");
nbSet = stringList.size();
for (int i = 0; i < nbSet; i++)
{
std::string str = stringList[i];
Phyp.insert(str);
}
m_CostFunction->SetPlausibilityHypothesis(Phyp);
m_CostFunction->SetWeight(GetParameterFloat("wgt"));
m_CostFunction->SetCriterionFormula(GetParameterString("cri"));
m_CostFunction->SetGTVectorData(psVectorData);
m_CostFunction->SetNSVectorData(nsVectorData);
//Optimizer
m_Optimizer->SetCostFunction(m_CostFunction);
m_Optimizer->SetMaximumNumberOfIterations(GetParameterInt("maxnbit"));
OptimizerType::ParametersType simplexDelta(m_CostFunction->GetNumberOfParameters());
simplexDelta.Fill(0.1);
m_Optimizer->AutomaticInitialSimplexOff();
m_Optimizer->SetInitialSimplexDelta(simplexDelta);
m_Optimizer->SetInitialPosition(initialPosition);
// Create the Command observer and register it with the optimizer.
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
if (IsParameterEnabled("optobs"))
{
m_Optimizer->AddObserver(itk::IterationEvent(), observer);
}
try
{
// do the optimization
m_Optimizer->StartOptimization();
}
catch (itk::ExceptionObject& err)
{
// An error has occurred in the optimization.
// Update the parameters
otbAppLogFATAL("ERROR: Exception Catched!" << std::endl);
otbAppLogFATAL(<< err.GetDescription() << std::endl);
const unsigned int numberOfIterations = m_Optimizer->GetOptimizer()->get_num_evaluations();
otbAppLogFATAL("numberOfIterations : " << numberOfIterations << std::endl);
otbAppLogFATAL("Results : " << m_Optimizer->GetCurrentPosition() << std::endl);
}
// get the results
const unsigned int numberOfIterations = m_Optimizer->GetOptimizer()->get_num_evaluations();
otbAppLogFATAL("numberOfIterations : " << numberOfIterations << std::endl);
otbAppLogFATAL("Results : " << m_Optimizer->GetCurrentPosition() << std::endl);
for (unsigned int i = 0; i < descList.size(); i++)
{
otb::FuzzyDescriptorsModelManager::ParameterType tmpParams;
for (unsigned int j = 0; j < 4; j++)
{
tmpParams.push_back(m_Optimizer->GetCurrentPosition()[(i * 4) + j]);
}
otb::FuzzyDescriptorsModelManager::AddDescriptor(descList[i], tmpParams, m_Model);
}
otb::FuzzyDescriptorsModelManager::Save(GetParameterString("out"), m_Model);
};
CostFunctionType::Pointer m_CostFunction;
OptimizerType::Pointer m_Optimizer;
otb::FuzzyDescriptorsModelManager::DescriptorsModelType m_Model;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DSFuzzyModelEstimation)
<commit_msg>BUG: Log level should be INFO, not FATAL<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperStringListParameter.h"
#include "otbVectorData.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataToRandomLineGenerator.h"
#include "itkAmoebaOptimizer.h"
#include "otbVectorDataToDSValidatedVectorDataFilter.h"
#include "otbStandardDSCostFunction.h"
#include "otbFuzzyDescriptorsModelManager.h"
namespace otb
{
namespace Wrapper
{
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::AmoebaOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer =
dynamic_cast< OptimizerPointer >( object );
if( ! itk::IterationEvent().CheckEvent( &event ) )
{
return;
}
std::ostringstream message;
message << optimizer->GetCachedValue() << " ";
message << optimizer->GetCachedCurrentPosition() << std::endl;
std::cout<<message.str()<<std::endl;
}
};
class DSFuzzyModelEstimation: public Application
{
public:
/** Standard class typedefs. */
typedef DSFuzzyModelEstimation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef VectorData<double> VectorDataType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef VectorDataType::ValuePrecisionType PrecisionType;
typedef VectorDataType::PrecisionType CoordRepType;
typedef otb::Wrapper::StringListParameter::StringListType StringListType;
typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType>
ValidationFilterType;
typedef otb::StandardDSCostFunction<ValidationFilterType> CostFunctionType;
typedef CostFunctionType::LabelSetType LabelSetType;
typedef itk::AmoebaOptimizer OptimizerType;
typedef otb::FuzzyDescriptorsModelManager::DescriptorsModelType
DescriptorsModelType;
typedef otb::FuzzyDescriptorsModelManager::DescriptorListType
DescriptorListType;
typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType>
TreeIteratorType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(DSFuzzyModelEstimation, otb::Application);
private:
void DoInit()
{
SetName("DSFuzzyModelEstimation");
SetDescription("Estimate feature fuzzy model parameters using 2 vector data (ground truth samples and wrong samples).");
SetDocName("Fuzzy Model estimation");
SetDocLongDescription("Estimate feature fuzzy model parameters using 2 vector data (ground truth samples and wrong samples).");
SetDocLimitations("None.");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::FeatureExtraction);
AddParameter(ParameterType_InputVectorData, "psin", "Input Positive Vector Data");
SetParameterDescription("psin", "Ground truth vector data for positive samples");
AddParameter(ParameterType_InputVectorData, "nsin", "Input Negative Vector Data");
SetParameterDescription("nsin", "Ground truth vector data for negative samples");
AddParameter(ParameterType_StringList, "belsup", "Belief Support");
SetParameterDescription("belsup", "Dempster Shafer study hypothesis to compute belief");
AddParameter(ParameterType_StringList, "plasup", "Plausibility Support");
SetParameterDescription("plasup", "Dempster Shafer study hypothesis to compute plausibility");
AddParameter(ParameterType_String, "cri", "Criterion");
SetParameterDescription("cri", "Dempster Shafer criterion (by default (belief+plausibility)/2)");
MandatoryOff("cri");
SetParameterString("cri","((Belief + Plausibility)/2.)");
AddParameter(ParameterType_Float,"wgt","Weighting");
SetParameterDescription("wgt","Coefficient between 0 and 1 to promote undetection or false detections (default 0.5)");
MandatoryOff("wgt");
SetParameterFloat("wgt", 0.5);
AddParameter(ParameterType_InputFilename,"initmod","initialization model");
SetParameterDescription("initmod","Initialization model (xml file) to be used. If the xml initialization model is set, the descriptor list is not used (specified using the option -desclist)");
MandatoryOff("initmod");
AddParameter(ParameterType_StringList, "desclist","Descriptor list");
SetParameterDescription("desclist","List of the descriptors to be used in the model (must be specified to perform an automatic initialization)");
MandatoryOff("desclist");
SetParameterString("desclist","");
AddParameter(ParameterType_Int,"maxnbit","Maximum number of iterations");
MandatoryOff("maxnbit");
SetParameterDescription("maxnbit","Maximum number of optimizer iteration (default 200)");
SetParameterInt("maxnbit", 200);
AddParameter(ParameterType_Empty,"optobs","Optimizer Observer");
SetParameterDescription("optobs","Activate the optimizer observer");
MandatoryOff("optobs");
AddParameter(ParameterType_OutputFilename,"out","Output filename");
SetParameterDescription("out","Output model file name (xml file) contains the optimal model to perform informations fusion.");
// Doc example parameter settings
SetDocExampleParameterValue("psin", "cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_gt.shp");
SetDocExampleParameterValue("nsin", "cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_wr.shp");
SetDocExampleParameterValue("belsup", "\"ROADSA\"");
SetDocExampleParameterValue("plasup", "\"NONDVI\" \"ROADSA\" \"NOBUIL\"");
SetDocExampleParameterValue("initmod", "Dempster-Shafer/DSFuzzyModel_Init.xml");
SetDocExampleParameterValue("maxnbit", "4");
SetDocExampleParameterValue("optobs", "true");
SetDocExampleParameterValue("out", "DSFuzzyModelEstimation.xml");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
// .. //
}
void DoExecute()
{
//Instantiate
m_CostFunction = CostFunctionType::New();
m_Optimizer = OptimizerType::New();
//Read the vector datas
VectorDataType::Pointer psVectorData = GetParameterVectorData("psin");
psVectorData->Update();
VectorDataType::Pointer nsVectorData = GetParameterVectorData("nsin");
nsVectorData->Update();
// Load the initial descriptor model
DescriptorListType descList;
DescriptorsModelType descMod;
if (IsParameterEnabled("initmod"))
{
std::string descModFile = GetParameterString("initmod");
descMod = FuzzyDescriptorsModelManager::Read(descModFile.c_str());
descList = FuzzyDescriptorsModelManager::GetDescriptorList(descMod);
}
else
{
StringListType stringList = GetParameterStringList("desclist");
int nbsdDesc = stringList.size();
for (int i = 0; i < nbsdDesc; i++)
{
descList.push_back(stringList[i]);
}
}
m_CostFunction->SetDescriptorList(descList);
// Compute statistics of all the descriptors
std::vector<double> accFirstOrderPS, accSecondOrderPS, minPS, maxPS;
accFirstOrderPS.resize(descList.size());
accSecondOrderPS.resize(descList.size());
std::fill(accFirstOrderPS.begin(), accFirstOrderPS.end(), 0);
std::fill(accSecondOrderPS.begin(), accSecondOrderPS.end(), 0);
minPS.resize(descList.size());
maxPS.resize(descList.size());
unsigned int accNbElemPS = 0;
TreeIteratorType itVectorPS(psVectorData->GetDataTree());
for (itVectorPS.GoToBegin(); !itVectorPS.IsAtEnd(); ++itVectorPS)
{
if (!itVectorPS.Get()->IsRoot() && !itVectorPS.Get()->IsDocument() && !itVectorPS.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVectorPS.Get();
for (unsigned int i = 0; i < descList.size(); ++i)
{
double desc = currentGeometry->GetFieldAsDouble(descList[i]);
accFirstOrderPS[i] += desc;
accSecondOrderPS[i] += desc * desc;
if (desc < minPS[i])
{
minPS[i] = desc;
}
if (desc > maxPS[i])
{
maxPS[i] = desc;
}
}
accNbElemPS++;
}
}
TreeIteratorType itVectorNS(nsVectorData->GetDataTree());
std::vector<double> accFirstOrderNS, accSecondOrderNS, minNS, maxNS;
minNS.resize(descList.size());
maxNS.resize(descList.size());
accFirstOrderNS.resize(descList.size());
accSecondOrderNS.resize(descList.size());
std::fill(accFirstOrderNS.begin(), accFirstOrderNS.end(), 0);
std::fill(accSecondOrderNS.begin(), accSecondOrderNS.end(), 0);
std::fill(minNS.begin(), minNS.end(), 1);
std::fill(maxNS.begin(), maxNS.end(), 0);
unsigned int accNbElemNS = 0;
for (itVectorNS.GoToBegin(); !itVectorNS.IsAtEnd(); ++itVectorNS)
{
if (!itVectorNS.Get()->IsRoot() && !itVectorNS.Get()->IsDocument() && !itVectorNS.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVectorNS.Get();
for (unsigned int i = 0; i < descList.size(); ++i)
{
double desc = currentGeometry->GetFieldAsDouble(descList[i]);
accFirstOrderNS[i] += desc;
accSecondOrderNS[i] += desc * desc;
if (desc < minNS[i])
{
minNS[i] = desc;
}
if (desc > maxNS[i])
{
maxNS[i] = desc;
}
}
accNbElemNS++;
}
}
otbAppLogINFO( << "Descriptors Stats : ");
otbAppLogINFO( << "Positive Samples");
for (unsigned int i = 0; i < descList.size(); ++i)
{
double mean = accFirstOrderPS[i] / accNbElemPS;
double stddev = vcl_sqrt(accSecondOrderPS[i] / accNbElemPS - mean * mean);
otbAppLogINFO( << descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minPS[i] << " max: " << maxPS[i] << ")"<< std::endl);
}
otbAppLogINFO( << "Negative Samples" << std::endl);
for (unsigned int i = 0; i < descList.size(); ++i)
{
double mean = accFirstOrderNS[i] / accNbElemNS;
double stddev = vcl_sqrt(accSecondOrderNS[i] / accNbElemNS - mean * mean);
otbAppLogINFO(<< descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minNS[i] << " max: " << maxNS[i] << ")"<< std::endl);
}
OptimizerType::ParametersType initialPosition(4 * descList.size());
if (IsParameterEnabled("initmod"))
{
for (unsigned int i = 0; i < 4; i++)
{
for (unsigned int j = 0; j < descList.size(); j++)
{
initialPosition.SetElement(
i + 4 * j,
otb::FuzzyDescriptorsModelManager::GetDescriptor(descList[j].c_str(), descMod).second[i]);
}
}
}
else
{
for (unsigned int j = 0; j < descList.size(); j++)
{
initialPosition.SetElement((j * 4), std::min(minNS[j], maxPS[j]));
initialPosition.SetElement((j * 4) + 2, std::max(minNS[j], maxPS[j]));
initialPosition.SetElement(
(j * 4) + 1,
0.5
* (initialPosition.GetElement((j * 4)) + initialPosition.GetElement((j * 4) + 2)));
initialPosition.SetElement((j * 4) + 3, 0.95);
}
}
//Cost Function
//Format Hypothesis
LabelSetType Bhyp, Phyp;
int nbSet;
StringListType stringList = GetParameterStringList("belsup");
nbSet = stringList.size();
for (int i = 0; i < nbSet; i++)
{
std::string str = stringList[i];
Bhyp.insert(str);
}
m_CostFunction->SetBeliefHypothesis(Bhyp);
stringList = GetParameterStringList("plasup");
nbSet = stringList.size();
for (int i = 0; i < nbSet; i++)
{
std::string str = stringList[i];
Phyp.insert(str);
}
m_CostFunction->SetPlausibilityHypothesis(Phyp);
m_CostFunction->SetWeight(GetParameterFloat("wgt"));
m_CostFunction->SetCriterionFormula(GetParameterString("cri"));
m_CostFunction->SetGTVectorData(psVectorData);
m_CostFunction->SetNSVectorData(nsVectorData);
//Optimizer
m_Optimizer->SetCostFunction(m_CostFunction);
m_Optimizer->SetMaximumNumberOfIterations(GetParameterInt("maxnbit"));
OptimizerType::ParametersType simplexDelta(m_CostFunction->GetNumberOfParameters());
simplexDelta.Fill(0.1);
m_Optimizer->AutomaticInitialSimplexOff();
m_Optimizer->SetInitialSimplexDelta(simplexDelta);
m_Optimizer->SetInitialPosition(initialPosition);
// Create the Command observer and register it with the optimizer.
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
if (IsParameterEnabled("optobs"))
{
m_Optimizer->AddObserver(itk::IterationEvent(), observer);
}
try
{
// do the optimization
m_Optimizer->StartOptimization();
}
catch (itk::ExceptionObject& err)
{
// An error has occurred in the optimization.
// Update the parameters
otbAppLogFATAL("ERROR: Exception Catched!" << std::endl);
otbAppLogFATAL(<< err.GetDescription() << std::endl);
const unsigned int numberOfIterations = m_Optimizer->GetOptimizer()->get_num_evaluations();
otbAppLogFATAL("numberOfIterations : " << numberOfIterations << std::endl);
otbAppLogFATAL("Results : " << m_Optimizer->GetCurrentPosition() << std::endl);
}
// get the results
const unsigned int numberOfIterations = m_Optimizer->GetOptimizer()->get_num_evaluations();
otbAppLogINFO("numberOfIterations : " << numberOfIterations << std::endl);
otbAppLogINFO("Results : " << m_Optimizer->GetCurrentPosition() << std::endl);
for (unsigned int i = 0; i < descList.size(); i++)
{
otb::FuzzyDescriptorsModelManager::ParameterType tmpParams;
for (unsigned int j = 0; j < 4; j++)
{
tmpParams.push_back(m_Optimizer->GetCurrentPosition()[(i * 4) + j]);
}
otb::FuzzyDescriptorsModelManager::AddDescriptor(descList[i], tmpParams, m_Model);
}
otb::FuzzyDescriptorsModelManager::Save(GetParameterString("out"), m_Model);
};
CostFunctionType::Pointer m_CostFunction;
OptimizerType::Pointer m_Optimizer;
otb::FuzzyDescriptorsModelManager::DescriptorsModelType m_Model;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DSFuzzyModelEstimation)
<|endoftext|> |
<commit_before>// tankview.cpp : Defines the entry point for the application.
//
#include "tankview.h"
#include "Model.h"
#include "config.h"
#include "TextUtils.h"
// for the stupid debug openGLcount model uses
#ifdef DEBUG
int __beginendCount;
#endif
class Application : public SimpleDisplayEventCallbacks
{
public:
Application();
virtual void key ( int key, bool down, const ModiferKeys& mods );
virtual void mouseButton( int key, int x, int y, bool down );
virtual void mouseMoved( int x, int y );
int run ( void );
protected:
bool init ( void );
void drawGridAndBounds ( void );
void loadModels ( void );
void drawModels ( void );
SimpleDisplay display;
SimpleDisplayCamera *camera;
OBJModel base,turret,barrel,lTread,rTread;
unsigned int red,green,blue,purple,black,current;
bool moveKeysDown[3];
int mousePos[2];
};
const char* convertPath ( const char* path )
{
static std::string temp;
if (!path)
return NULL;
temp = path;
#ifdef _WIN32
temp = TextUtils::replace_all(temp,std::string("/"),std::string("\\"));
#endif
return temp.c_str();
}
Application::Application() : display(800,600,false,"tankview")
{
camera = NULL;
for (int i = 0; i<3; i++)
moveKeysDown[i] = false;
}
void Application::drawGridAndBounds ( void )
{
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
// axis markers
glColor4f(1,0,0,0.25f);
glVertex3f(0,0,0);
glVertex3f(1,0,0);
glColor4f(0,1,0,0.25f);
glVertex3f(0,0,0);
glVertex3f(0,1,0);
glColor4f(0,0,1,0.25f);
glVertex3f(0,0,0);
glVertex3f(0,0,1);
// grid
glColor4f(1,1,1,0.125f);
float grid = 10.0f;
float increment = 0.25f;
for( float i = -grid; i <= grid; i += increment )
{
glVertex3f(i,grid,0);
glVertex3f(i,-grid,0);
glVertex3f(grid,i,0);
glVertex3f(-grid,i,0);
}
// tank bbox
glColor4f(0,1,1,0.25f);
float width = 1.4f;
float height = 2.05f;
float front = 4.94f;
float back = -3.10f;
// front
glVertex3f(front,-width,0);
glVertex3f(front,width,0);
glVertex3f(front,width,0);
glVertex3f(front,width,height);
glVertex3f(front,-width,height);
glVertex3f(front,width,height);
glVertex3f(front,-width,0);
glVertex3f(front,-width,height);
// back
glVertex3f(back,-width,0);
glVertex3f(back,width,0);
glVertex3f(back,width,0);
glVertex3f(back,width,height);
glVertex3f(back,-width,height);
glVertex3f(back,width,height);
glVertex3f(back,-width,0);
glVertex3f(back,-width,height);
// sides
glVertex3f(back,-width,0);
glVertex3f(front,-width,0);
glVertex3f(back,width,0);
glVertex3f(front,width,0);
glVertex3f(back,-width,height);
glVertex3f(front,-width,height);
glVertex3f(back,width,height);
glVertex3f(front,width,height);
glEnd();
glColor4f(1,1,1,1);
}
void Application::loadModels ( void )
{
barrel.read(convertPath("./data/geometry/tank/std/barrel.obj"));
base.read(convertPath("./data/geometry/tank/std/body.obj"));
turret.read(convertPath("./data/geometry/tank/std/turret.obj"));
lTread.read(convertPath("./data/geometry/tank/std/lcasing.obj"));
rTread.read(convertPath("/.data/geometry/tank/std/rcasing.obj"));
red = display.loadImage(convertPath("./data/skins/red/tank.png"));
green = display.loadImage(convertPath("./data/skins/green/tank.png"));
blue = display.loadImage(convertPath("./data/skins/blue/tank.png"));
purple = display.loadImage(convertPath("./data/skins/purple/tank.png"));
black = display.loadImage(convertPath("./data/skins/rogue/tank.png"));
current = green;
}
void Application::drawModels ( void )
{
base.draw();
lTread.draw();
rTread.draw();
turret.draw();
barrel.draw();
}
bool Application::init ( void )
{
camera = new SimpleDisplayCamera;
display.addEventCallback(this);
// load up the models
loadModels();
camera->rotateGlob(-90,1,0,0);
camera->moveLoc(0,0,-20);
camera->moveLoc(0,1.5f,0);
//setup light
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float v[4] = {1};
v[0] = v[1] = v[2] = 0.125f;
glLightfv (GL_LIGHT0, GL_AMBIENT,v);
v[0] = v[1] = v[2] = 0.75f;
glLightfv (GL_LIGHT0, GL_DIFFUSE,v);
v[0] = v[1] = v[2] = 0;
glLightfv (GL_LIGHT0, GL_SPECULAR,v);
return true;
}
int Application::run ( void )
{
if (!init())
return -1;
while (display.update())
{
display.clear();
camera->applyView();
drawGridAndBounds();
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float v[4] = {1};
v[0] = v[1] = v[2] = 20.f;
glLightfv (GL_LIGHT0, GL_POSITION,v);
display.bindImage(current);
drawModels();
camera->removeView();
display.flip();
//display.yeld(0.5f);
}
display.kill();
return 0;
}
void Application::key ( int key, bool down, const ModiferKeys& mods )
{
if (!camera || !down)
return;
switch(key)
{
case SD_KEY_ESCAPE:
display.quit();
break;
case SD_KEY_UP:
if (mods.alt)
camera->rotateLoc(2.5f,1,0,0);
else if (mods.ctl)
camera->moveLoc(0,0,0.25f);
else
camera->moveLoc(0,0.25f,0);
break;
case SD_KEY_DOWN:
if (mods.alt)
camera->rotateLoc(-2.5f,1,0,0);
else if (mods.ctl)
camera->moveLoc(0,0,-0.25f);
else
camera->moveLoc(0,-0.25f,0);
break;
case SD_KEY_LEFT:
if (mods.alt)
camera->rotateLoc(2.5f,0,1,0);
else
camera->moveLoc(-0.25f,0,0);
break;
case SD_KEY_RIGHT:
if (mods.alt)
camera->rotateLoc(-2.5f,0,1,0);
else
camera->moveLoc(0.25f,0,0);
break;
case SD_KEY_F1:
current = red;
break;
case SD_KEY_F2:
current = green;
break;
case SD_KEY_F3:
current = blue;
break;
case SD_KEY_F4:
current = purple;
break;
case SD_KEY_F5:
current = black;
break;
}
}
void Application::mouseButton( int key, int x, int y, bool down )
{
mousePos[0] = x;
mousePos[1] = y;
moveKeysDown[key-1] = down;
}
void Application::mouseMoved( int x, int y )
{
int mouseDelta[2];
mouseDelta[0] = x - mousePos[0];
mouseDelta[1] = y - mousePos[1];
if ( moveKeysDown[0] )
{
camera->moveLoc(-mouseDelta[0]*0.0125f,-mouseDelta[1]*0.0125f,0);
}
else if ( moveKeysDown[1] )
camera->moveLoc(0,0,mouseDelta[1]*0.025f);
if ( moveKeysDown[2] )
{
camera->rotateLoc(mouseDelta[1]*0.025f,1,0,0);
camera->rotateGlob(mouseDelta[0]*0.025f,0,0,-1);
}
mousePos[0] = x;
mousePos[1] = y;
}
#ifdef _WIN32
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR lpCmdLine, int nShowCmd )
{
#else
int main ( int argc, char* argv[] )
{
#endif
Application app;
return app.run();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8<commit_msg>Normal drawing for model debuging.<commit_after>// tankview.cpp : Defines the entry point for the application.
//
#include "tankview.h"
#include "Model.h"
#include "config.h"
#include "TextUtils.h"
// for the stupid debug openGLcount model uses
#ifdef DEBUG
int __beginendCount;
#endif
class Application : public SimpleDisplayEventCallbacks
{
public:
Application();
virtual void key ( int key, bool down, const ModiferKeys& mods );
virtual void mouseButton( int key, int x, int y, bool down );
virtual void mouseMoved( int x, int y );
int run ( void );
protected:
bool init ( void );
void drawGridAndBounds ( void );
void loadModels ( void );
void drawModels ( void );
void drawObjectNormals ( OBJModel &model );
SimpleDisplay display;
SimpleDisplayCamera *camera;
OBJModel base,turret,barrel,lTread,rTread;
unsigned int red,green,blue,purple,black,current;
bool moveKeysDown[3];
int mousePos[2];
};
const char* convertPath ( const char* path )
{
static std::string temp;
if (!path)
return NULL;
temp = path;
#ifdef _WIN32
temp = TextUtils::replace_all(temp,std::string("/"),std::string("\\"));
#endif
return temp.c_str();
}
Application::Application() : display(800,600,false,"tankview")
{
camera = NULL;
for (int i = 0; i<3; i++)
moveKeysDown[i] = false;
}
void Application::drawGridAndBounds ( void )
{
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
// axis markers
glColor4f(1,0,0,0.25f);
glVertex3f(0,0,0);
glVertex3f(1,0,0);
glColor4f(0,1,0,0.25f);
glVertex3f(0,0,0);
glVertex3f(0,1,0);
glColor4f(0,0,1,0.25f);
glVertex3f(0,0,0);
glVertex3f(0,0,1);
// grid
glColor4f(1,1,1,0.125f);
float grid = 10.0f;
float increment = 0.25f;
for( float i = -grid; i <= grid; i += increment )
{
glVertex3f(i,grid,0);
glVertex3f(i,-grid,0);
glVertex3f(grid,i,0);
glVertex3f(-grid,i,0);
}
// tank bbox
glColor4f(0,1,1,0.25f);
float width = 1.4f;
float height = 2.05f;
float front = 4.94f;
float back = -3.10f;
// front
glVertex3f(front,-width,0);
glVertex3f(front,width,0);
glVertex3f(front,width,0);
glVertex3f(front,width,height);
glVertex3f(front,-width,height);
glVertex3f(front,width,height);
glVertex3f(front,-width,0);
glVertex3f(front,-width,height);
// back
glVertex3f(back,-width,0);
glVertex3f(back,width,0);
glVertex3f(back,width,0);
glVertex3f(back,width,height);
glVertex3f(back,-width,height);
glVertex3f(back,width,height);
glVertex3f(back,-width,0);
glVertex3f(back,-width,height);
// sides
glVertex3f(back,-width,0);
glVertex3f(front,-width,0);
glVertex3f(back,width,0);
glVertex3f(front,width,0);
glVertex3f(back,-width,height);
glVertex3f(front,-width,height);
glVertex3f(back,width,height);
glVertex3f(front,width,height);
glEnd();
glColor4f(1,1,1,1);
}
void Application::loadModels ( void )
{
barrel.read(convertPath("./data/geometry/tank/std/barrel.obj"));
base.read(convertPath("./data/geometry/tank/std/body.obj"));
turret.read(convertPath("./data/geometry/tank/std/turret.obj"));
lTread.read(convertPath("./data/geometry/tank/std/lcasing.obj"));
rTread.read(convertPath("/.data/geometry/tank/std/rcasing.obj"));
red = display.loadImage(convertPath("./data/skins/red/tank.png"));
green = display.loadImage(convertPath("./data/skins/green/tank.png"));
blue = display.loadImage(convertPath("./data/skins/blue/tank.png"));
purple = display.loadImage(convertPath("./data/skins/purple/tank.png"));
black = display.loadImage(convertPath("./data/skins/rogue/tank.png"));
current = green;
}
void Application::drawModels ( void )
{
base.draw();
lTread.draw();
rTread.draw();
turret.draw();
barrel.draw();
}
void Application::drawObjectNormals ( OBJModel &model )
{
glBegin(GL_LINES);
for ( size_t f = 0; f < model.faces.size(); f++ )
{
for ( size_t v = 0; v < model.faces[f].verts.size(); v++ )
{
size_t vIndex = model.faces[f].verts[v];
if ( vIndex < model.vertList.size() )
{
OBJVert vert = model.vertList[vIndex];
size_t nIndex = model.faces[f].norms[v];
if ( nIndex < model.normList.size() )
{
vert.glVertex();
vert += model.normList[nIndex];
vert.glVertex();
}
}
}
}
glEnd();
}
bool Application::init ( void )
{
camera = new SimpleDisplayCamera;
display.addEventCallback(this);
// load up the models
loadModels();
camera->rotateGlob(-90,1,0,0);
camera->moveLoc(0,0,-20);
camera->moveLoc(0,1.5f,0);
//setup light
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float v[4] = {1};
v[0] = v[1] = v[2] = 0.125f;
glLightfv (GL_LIGHT0, GL_AMBIENT,v);
v[0] = v[1] = v[2] = 0.75f;
glLightfv (GL_LIGHT0, GL_DIFFUSE,v);
v[0] = v[1] = v[2] = 0;
glLightfv (GL_LIGHT0, GL_SPECULAR,v);
return true;
}
int Application::run ( void )
{
if (!init())
return -1;
while (display.update())
{
display.clear();
camera->applyView();
drawGridAndBounds();
// draw normals
glColor4f(1,0,0,1);
drawObjectNormals(base);
glColor4f(1,1,0,1);
drawObjectNormals(barrel);
glColor4f(0,1,1,1);
drawObjectNormals(turret);
glColor4f(0,0,1,1);
drawObjectNormals(lTread);
glColor4f(0,1,0,1);
drawObjectNormals(lTread);
glColor4f(1,1,1,1);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float v[4] = {1};
v[0] = v[1] = v[2] = 20.f;
glLightfv (GL_LIGHT0, GL_POSITION,v);
display.bindImage(current);
drawModels();
camera->removeView();
display.flip();
//display.yeld(0.5f);
}
display.kill();
return 0;
}
void Application::key ( int key, bool down, const ModiferKeys& mods )
{
if (!camera || !down)
return;
switch(key)
{
case SD_KEY_ESCAPE:
display.quit();
break;
case SD_KEY_UP:
if (mods.alt)
camera->rotateLoc(2.5f,1,0,0);
else if (mods.ctl)
camera->moveLoc(0,0,0.25f);
else
camera->moveLoc(0,0.25f,0);
break;
case SD_KEY_DOWN:
if (mods.alt)
camera->rotateLoc(-2.5f,1,0,0);
else if (mods.ctl)
camera->moveLoc(0,0,-0.25f);
else
camera->moveLoc(0,-0.25f,0);
break;
case SD_KEY_LEFT:
if (mods.alt)
camera->rotateLoc(2.5f,0,1,0);
else
camera->moveLoc(-0.25f,0,0);
break;
case SD_KEY_RIGHT:
if (mods.alt)
camera->rotateLoc(-2.5f,0,1,0);
else
camera->moveLoc(0.25f,0,0);
break;
case SD_KEY_F1:
current = red;
break;
case SD_KEY_F2:
current = green;
break;
case SD_KEY_F3:
current = blue;
break;
case SD_KEY_F4:
current = purple;
break;
case SD_KEY_F5:
current = black;
break;
}
}
void Application::mouseButton( int key, int x, int y, bool down )
{
mousePos[0] = x;
mousePos[1] = y;
moveKeysDown[key-1] = down;
}
void Application::mouseMoved( int x, int y )
{
int mouseDelta[2];
mouseDelta[0] = x - mousePos[0];
mouseDelta[1] = y - mousePos[1];
if ( moveKeysDown[0] )
{
camera->moveLoc(-mouseDelta[0]*0.0125f,-mouseDelta[1]*0.0125f,0);
}
else if ( moveKeysDown[1] )
camera->moveLoc(0,0,mouseDelta[1]*0.025f);
if ( moveKeysDown[2] )
{
camera->rotateLoc(mouseDelta[1]*0.025f,1,0,0);
camera->rotateGlob(mouseDelta[0]*0.025f,0,0,-1);
}
mousePos[0] = x;
mousePos[1] = y;
}
#ifdef _WIN32
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR lpCmdLine, int nShowCmd )
{
#else
int main ( int argc, char* argv[] )
{
#endif
Application app;
return app.run();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
#include <math.h>
#include "modelFunctions.cpp"
#include "cameraFunctions.cpp"
#if defined(__APPLE__)
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#else
#include<GL/gl.h>
#include<GL/freeglut.h>
#endif
/** TYPE DEFINITIONS **/
#ifndef __POINT_DEF__
#define __POINT_DEF__
struct Point {
double x, y, z;
};
#endif
/** PROGRAM CONSTATNS **/
const int START_HEIGHT = 600;
const int START_WIDTH = 600;
const int NUM_EXPECTED_PARAMETERS = 2;
/** GLOBAL VARIABLES **/
double ANGLE_X, ANGLE_Y, ANGLE_Z;
double SCALE, ROTATION_FACTOR, SPHERE_RAD;
unsigned char MODE;
int LAST_MOUSE_X, LAST_MOUSE_Y;
/**
* Close the the program
*/
void close() {
exit(1);
}
/**
* Display help information on default output channel
*/
void help() {
cout << endl;
cout << "---------------> >> HELP INFORMATION << <--------------" << endl;
cout << " Change camera mode [prespectiva | axonometrica]" << endl;
cout << " -> Press 'p' to change" << endl;
cout << " Print status information" << endl;
cout << " -> Press 's' to display" << endl;
cout << " Set the response of mouse events on window" << endl;
cout << " -> Press 'r' to set camera rotation mode" << endl;
// cout << " -> Press 't' to set translation mode" << endl;
cout << " Set the precision of rotation mode" << endl;
cout << " -> Press '+' to increment the rotation speed" << endl;
cout << " -> Press '-' to decrement the rotation speed" << endl;
cout << " Reset the program to starting camera position" << endl;
cout << " -> Press 'i' to reset" << endl;
cout << " Press ESC to exit" << endl;
cout << "-------------------------------------------------------" << endl;
}
/**
* Display program status information on default output channel
*/
void status() {
cout << endl;
cout << "--------------------> >> STATUS << <-------------------" << endl;
cout << " Camera mode : " << getStrCameraMode() << endl;
cout << " Rotation factor: " << ROTATION_FACTOR << " [Def. 10]"<< endl;
cout << "-------------------------------------------------------" << endl;
}
void usage() {
cout << endl;
cout << "Usage: file_with_model" << endl;
}
/**
* Paint the axes of current object
* The rotations and translations can affect to the painted axes
*/
void paintAxes() {
glBegin(GL_LINES);
glColor3f (1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(1, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 1, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 1);
glEnd();
}
void paintFloor() {
glPushMatrix();
glTranslated(0.0, -0.4, 0.0);
glBegin(GL_QUADS);
glColor3f (0.545, 0.271, 0.075);
glVertex3f( 0.75, 0, 0.75);
glVertex3f( 0.75, 0,-0.75);
glVertex3f(-0.75, 0,-0.75);
glVertex3f(-0.75, 0, 0.75);
glEnd();
glPopMatrix();
}
void paintSnowMan() {
glPushMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.4, 20, 20);
glPopMatrix();
glTranslated(0.0, 0.6, 0.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.2, 50, 50);
glPopMatrix();
glColor3f(1.0, 0.5, 0.0);
glTranslated(0.1, 0.0, 0.0);
glRotated(90, 0, 1, 0);
glutSolidCone(0.1, 0.2, 20, 20);
glPopMatrix();
}
/* ----------------------- CALLBACKS ----------------------- */
void refresh () {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotated(0, 1, 0, 0);
glScaled(SCALE, SCALE, SCALE);
paintFloor();
paintSnowMan();
paintModel();
glPopMatrix();
glutSwapBuffers();
}
/**
* Callback for resize events
* @param height New height of window
* @param width New width of window
*/
void onResize(int height, int width) {
double relX = (double)width/(double)(START_WIDTH);
double relY = (double)height/(double)(START_HEIGHT);
updateCamera(SPHERE_RAD*relX, SPHERE_RAD*relY);
glViewport(0, 0, height, width);
}
void onMouseClick(int buton, int evnt, int x, int y) {
if (evnt == GLUT_DOWN) {
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
}
}
void onMouseMotion(int x, int y) {
float height = glutGet(GLUT_WINDOW_HEIGHT);
float width = glutGet(GLUT_WINDOW_WIDTH);
switch (MODE) {
case 'r': incrementEulerAngles(((double)(LAST_MOUSE_Y - y)*ROTATION_FACTOR/height),
((double)(x - LAST_MOUSE_X)*ROTATION_FACTOR/width), 0.0);
setCameraMatrix();
break;
case 't': SCALE = x >= width - y ? (double)((x)*2.0/height) :
(double)((width - (y))*2.0/width);
break;
case 'c': TRANS_Z += (2.0*(y - LAST_MOUSE_Y))/(double)height;
TRANS_X += (2.0*(x - LAST_MOUSE_X))/(double)width;
break;
}
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
glutPostRedisplay();
}
void onKeyboardPulse(unsigned char key, int x, int y) {
switch (key) {
case 'h': help();
break;
case '+': ROTATION_FACTOR *= 1.3;
break;
case '-': ROTATION_FACTOR /= 1.3;
break;
case 's': status();
break;
case 'p': changeCameraType();
glutPostRedisplay();
break;
case 'i': initCamera(SPHERE_RAD);
setCameraMatrix();
glutPostRedisplay();
break;
case (char)27: close();
break;
}
if (MODE == 'c' && key == 'c') MODE == 'r';
else MODE = key;
}
/* -------------------- END OF CALLBACKS -------------------- */
/* ---------------------- INITIAL CALCS --------------------- */
Point calcVRP(Point min, Point max) {
Point ret;
ret.x = (max.x + min.x)*0.5;
ret.y = (max.y + min.y)*0.5;
ret.z = (max.z + min.z)*0.5;
return ret;
}
double calcMinSphereRadius(Point min, Point max) {
return sqrt((max.x - min.x)*(max.x - min.x) + (max.y - min.y)*(max.y - min.y) + (max.z - min.z)*(max.z - min.z))*0.5;
}
/**
* Initializate the Global variables of the program
*/
void initGlobalVars() {
SCALE = 1.0;
ROTATION_FACTOR = 10.0;
MODE = 'r';
}
/**
* Initializate the openGL envrionament
*/
void initGL() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
/* ------------------- END OF INITIAL CALCS ------------------ */
/* ----------------------- MAIN FUNCTION --------------------- */
int main(int argc, const char *argv[]) {
// Check num of paramaters
if (argc != NUM_EXPECTED_PARAMETERS) {
usage();
close();
}
// Initialitzation of GLUT
glutInit(&argc, ((char **)argv));
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(START_HEIGHT, START_WIDTH);
glutCreateWindow("IDI: Bloc 3");
// Registre de Callbacks
glutDisplayFunc(refresh);
glutReshapeFunc(onResize);
glutMouseFunc(onMouseClick);
glutMotionFunc(onMouseMotion);
glutKeyboardFunc(onKeyboardPulse);
// Initialization of openGL
initGL();
// Initialization of global variables
initGlobalVars();
Point p1 = {0.75, -0.4 + 0.25, 0.75};
loadModel(argv[1], 0.5, p1);
Point p2;
getScaledPoints(p1, p2);
SPHERE_RAD = 2.0;
cout << SPHERE_RAD << endl;
initCamera(SPHERE_RAD);
setCamDist(5, 4, 8);
setCameraMatrix();
// GLUT events loop
glutMainLoop();
return 0;
}
<commit_msg>Implemented calc and paint of min sphere for the scene<commit_after>#include <iostream>
using namespace std;
#include <math.h>
#include "modelFunctions.cpp"
#include "cameraFunctions.cpp"
#if defined(__APPLE__)
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#else
#include<GL/gl.h>
#include<GL/freeglut.h>
#endif
/** TYPE DEFINITIONS **/
#ifndef __POINT_DEF__
#define __POINT_DEF__
struct Point {
double x, y, z;
};
#endif
/** PROGRAM CONSTATNS **/
const int START_HEIGHT = 600;
const int START_WIDTH = 600;
const int NUM_EXPECTED_PARAMETERS = 2;
/** GLOBAL VARIABLES **/
double ANGLE_X, ANGLE_Y, ANGLE_Z;
double SCALE, ROTATION_FACTOR, SPHERE_RAD;
unsigned char MODE;
int LAST_MOUSE_X, LAST_MOUSE_Y;
/**
* Close the the program
*/
void close() {
exit(1);
}
/**
* Display help information on default output channel
*/
void help() {
cout << endl;
cout << "---------------> >> HELP INFORMATION << <--------------" << endl;
cout << " Change camera mode [prespectiva | axonometrica]" << endl;
cout << " -> Press 'p' to change" << endl;
cout << " Print status information" << endl;
cout << " -> Press 's' to display" << endl;
cout << " Set the response of mouse events on window" << endl;
cout << " -> Press 'r' to set camera rotation mode" << endl;
// cout << " -> Press 't' to set translation mode" << endl;
cout << " Set the precision of rotation mode" << endl;
cout << " -> Press '+' to increment the rotation speed" << endl;
cout << " -> Press '-' to decrement the rotation speed" << endl;
cout << " Reset the program to starting camera position" << endl;
cout << " -> Press 'i' to reset" << endl;
cout << " Press ESC to exit" << endl;
cout << "-------------------------------------------------------" << endl;
}
/**
* Display program status information on default output channel
*/
void status() {
cout << endl;
cout << "--------------------> >> STATUS << <-------------------" << endl;
cout << " Camera mode : " << getStrCameraMode() << endl;
cout << " Rotation factor: " << ROTATION_FACTOR << " [Def. 15]"<< endl;
cout << "-------------------------------------------------------" << endl;
}
void usage() {
cout << endl;
cout << "Usage: file_with_model" << endl;
}
/**
* Paint the axes of current object
* The rotations and translations can affect to the painted axes
*/
void paintAxes() {
glBegin(GL_LINES);
glColor3f (1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(1, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 1, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 1);
glEnd();
}
void paintFloor() {
glBegin(GL_QUADS);
glColor3f (0.545, 0.271, 0.075);
glVertex3f( 0.75, -0.4, 0.75);
glVertex3f( 0.75, -0.4,-0.75);
glVertex3f(-0.75, -0.4,-0.75);
glVertex3f(-0.75, -0.4, 0.75);
glEnd();
}
void paintSnowMan() {
glPushMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.4, 20, 20);
glPopMatrix();
glTranslated(0.0, 0.6, 0.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.2, 50, 50);
glPopMatrix();
glColor3f(1.0, 0.5, 0.0);
glTranslated(0.1, 0.0, 0.0);
glRotated(90, 0, 1, 0);
glutSolidCone(0.1, 0.2, 20, 20);
glPopMatrix();
}
/* ----------------------- CALLBACKS ----------------------- */
void refresh () {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotated(0, 1, 0, 0);
glScaled(SCALE, SCALE, SCALE);
paintFloor();
paintSnowMan();
paintModel();
glColor4f(0.0, 0.0, 0.5, 0.1);
glutWireSphere(SPHERE_RAD, 20, 20);
glPopMatrix();
glutSwapBuffers();
}
/**
* Callback for resize events
* @param height New height of window
* @param width New width of window
*/
void onResize(int height, int width) {
double relX = (double)width/(double)(START_WIDTH);
double relY = (double)height/(double)(START_HEIGHT);
updateCamera(SPHERE_RAD*relX, SPHERE_RAD*relY);
glViewport(0, 0, height, width);
}
void onMouseClick(int buton, int evnt, int x, int y) {
if (evnt == GLUT_DOWN) {
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
}
}
void onMouseMotion(int x, int y) {
float height = glutGet(GLUT_WINDOW_HEIGHT);
float width = glutGet(GLUT_WINDOW_WIDTH);
switch (MODE) {
case 'r': incrementEulerAngles(((double)(LAST_MOUSE_Y - y)*ROTATION_FACTOR/height),
((double)(x - LAST_MOUSE_X)*ROTATION_FACTOR/width), 0.0);
setCameraMatrix();
break;
case 't': SCALE = x >= width - y ? (double)((x)*2.0/height) :
(double)((width - (y))*2.0/width);
break;
case 'c': TRANS_Z += (2.0*(y - LAST_MOUSE_Y))/(double)height;
TRANS_X += (2.0*(x - LAST_MOUSE_X))/(double)width;
break;
}
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
glutPostRedisplay();
}
void onKeyboardPulse(unsigned char key, int x, int y) {
switch (key) {
case 'h': help();
break;
case '+': ROTATION_FACTOR *= 1.3;
break;
case '-': ROTATION_FACTOR /= 1.3;
break;
case 's': status();
break;
case 'p': changeCameraType();
glutPostRedisplay();
break;
case 'i': initCamera(SPHERE_RAD);
setCameraMatrix();
glutPostRedisplay();
break;
case (char)27: close();
break;
}
if (MODE == 'c' && key == 'c') MODE == 'r';
else MODE = key;
}
/* -------------------- END OF CALLBACKS -------------------- */
/* ---------------------- INITIAL CALCS --------------------- */
Point calcVRP(Point min, Point max) {
Point ret;
ret.x = (max.x + min.x)*0.5;
ret.y = (max.y + min.y)*0.5;
ret.z = (max.z + min.z)*0.5;
return ret;
}
double calcMinContainerBoxScene(Point &min, Point &max) {
int num_els = 3;
Point maxs[num_els - 1];
Point mins[num_els - 1];
// Get min and max points for all the elements on the scene
getScaledPoints(min, max);
mins[0].x = -0.75;
mins[0].y = -0.4;
mins[0].z = -0.75;
maxs[0].x = 0.75;
maxs[0].y = -0.4;
maxs[0].z = 0.75;
mins[1].x = -0.4;
mins[1].y = -0.4;
mins[1].z = -0.4;
maxs[1].x = 0.4;
maxs[1].y = 0.8;
maxs[1].z = 0.4;
for (int i = 0; i < num_els - 1; ++i) {
cout << min.x << " " << min.y << " " << min.z << endl;
cout << max.x << " " << max.y << " " << max.z << endl;
cout << i << endl;
if (mins[i].x < min.x) min.x = mins[i].x;
if (maxs[i].x > max.x) max.x = maxs[i].x;
if (mins[i].y < min.y) min.y = mins[i].y;
if (maxs[i].y > max.y) max.y = maxs[i].y;
if (mins[i].z < min.z) min.z = mins[i].z;
if (maxs[i].z > max.z) max.z = maxs[i].z;
}
}
double calcMinSphereRadius() {
Point max, min;
calcMinContainerBoxScene(min, max);
cout << min.x << " " << min.y << " " << min.z << endl;
cout << max.x << " " << max.y << " " << max.z << endl;
return sqrt((max.x - min.x)*(max.x - min.x) + (max.y - min.y)*(max.y - min.y) + (max.z - min.z)*(max.z - min.z))*0.5;
}
/**
* Initializate the Global variables of the program
*/
void initGlobalVars() {
SCALE = 1.0;
ROTATION_FACTOR = 15.0;
MODE = 'r';
}
/**
* Initializate the openGL envrionament
*/
void initGL() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
/* ------------------- END OF INITIAL CALCS ------------------ */
/* ----------------------- MAIN FUNCTION --------------------- */
int main(int argc, const char *argv[]) {
// Check num of paramaters
if (argc != NUM_EXPECTED_PARAMETERS) {
usage();
close();
}
// Initialitzation of GLUT
glutInit(&argc, ((char **)argv));
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(START_HEIGHT, START_WIDTH);
glutCreateWindow("IDI: Bloc 3");
// Registre de Callbacks
glutDisplayFunc(refresh);
glutReshapeFunc(onResize);
glutMouseFunc(onMouseClick);
glutMotionFunc(onMouseMotion);
glutKeyboardFunc(onKeyboardPulse);
// Initialization of openGL
initGL();
// Initialization of global variables
initGlobalVars();
Point p1 = {0.75, -0.4 + 0.25, 0.75};
loadModel(argv[1], 0.5, p1);
Point p2;
SPHERE_RAD = calcMinSphereRadius();
cout << SPHERE_RAD << endl;
initCamera(SPHERE_RAD);
setCamDist(SPHERE_RAD + 0.5, 0.5, SPHERE_RAD*2+0.5);
setCameraMatrix();
// GLUT events loop
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_constant_folding.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_query.h"
#include "tensorflow/compiler/xla/service/slow_operation_alarm.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/lib/core/errors.h"
namespace xla {
// Checks whether instr is or transitively contains an instruction that we
// shouldn't fold.
//
// Specifically, we don't fold kRng or kAfterAll instructions:
//
// - kRng is already marked as side-effecting and so is skipped elsewhere, but
// we check for it here. Even kRng weren't side-effecting and took an
// explicit seed, we *still* wouldn't want to constant-fold it, because the
// evaluator's handling of rng is not guaranteed to be identical to any
// particular backend's rng.
//
// - kAfterAll needs to be skipped because a kAfterAll op with no args can
// currently materialize a token "out of thin air". TODO(b/110532604):
// Remove this check once AfterAll requires at least one operand, in which
// case constant folding will be impossible.
static bool IsOrContainsIllegalInstr(const HloInstruction* instr) {
if (instr->opcode() == HloOpcode::kAfterAll ||
instr->opcode() == HloOpcode::kRng) {
return true;
}
for (const HloComputation* c : instr->called_computations()) {
if (absl::c_any_of(c->instructions(), IsOrContainsIllegalInstr)) {
return true;
}
}
return false;
}
/*static*/ std::atomic<int64_t> HloConstantFolding::slow_op_counter_{0};
StatusOr<bool> HloConstantFolding::Run(HloModule* module) {
// Limit the constant folding to 0 iterations to skip folding loops. This
// retains the behavior from before while loop support in HloEvaluator and may
// be revised.
auto evaluator = absl::make_unique<HloEvaluator>(/*max_loop_iterations=*/0);
// fast-path lets us e.g. use Eigen for matmuls.
evaluator->set_use_fast_path(true);
bool changed = false;
for (auto* computation : module->MakeNonfusionComputations()) {
for (auto instruction : computation->MakeInstructionPostOrder()) {
// Skip dead code.
if (instruction->IsDead()) {
continue;
}
// We only handle instructions where
//
// - at least one operand is a constant, and
// - all other operands are either constants or broadcast(constant).
//
// Why this particular set of rules around broadcasts?
//
// - We don't want to fold broadcast(constant) on its own, because in
// general it's "simpler" to remember that it's a broadcast. Also,
// algsimp will fold an all-one-value constant into a broadcast, so
// we'd just end up fighting with it.
//
// - We don't want to fold an op where all operands are broadcasts of
// constants, because algsimp will transform op(broadcast(constant) =>
// broadcast(op(constant)). Then we can constant-fold the smaller op.
//
// - So the only remaining case is where some but not all operands are
// broadcasts of constants, e.g. op(constant, broadcast(constant)).
//
if (!absl::c_any_of(instruction->operands(),
[](const HloInstruction* operand) {
return operand->opcode() == HloOpcode::kConstant;
}) ||
!absl::c_all_of(
instruction->operands(), [](const HloInstruction* operand) {
return operand->opcode() == HloOpcode::kConstant ||
(operand->opcode() == HloOpcode::kBroadcast &&
operand->operand(0)->opcode() == HloOpcode::kConstant);
})) {
continue;
}
// Don't fold Constant, Parameter, and Tuple instructions. Tuple
// constants are not directly supported by any backends, hence folding
// Tuple is not useful and would in fact be expanded back into kTuple by
// Algebraic Simplifier.
//
// (We do allow folding subcomputations that contain these instructions.)
if (instruction->opcode() == HloOpcode::kParameter ||
instruction->opcode() == HloOpcode::kConstant ||
instruction->opcode() == HloOpcode::kTuple) {
continue;
}
// Broadcasts dramatically increase the size of constants, which is often
// detrimental to performance and memory capacity, so do not fold
// broadcasts.
if (instruction->opcode() == HloOpcode::kBroadcast ||
instruction->opcode() == HloOpcode::kIota) {
continue;
}
// Check for instructions that we can't fold even if they appear inside of
// a subcomputation (e.g. a kCall).
if (IsOrContainsIllegalInstr(instruction)) {
continue;
}
// Don't constant-fold side-effecting instructions or instructions which
// contain side-effecting instructions.
if (instruction->HasSideEffect()) {
continue;
}
// Don't constant fold unless it's a net positive or the output is small.
if (instruction->shape().IsArray()) {
int64_t elements_in_removed_operands = 0;
for (HloInstruction* operand : instruction->operands()) {
if (operand->user_count() == 1 && operand->shape().IsArray()) {
elements_in_removed_operands +=
ShapeUtil::ElementsIn(operand->shape());
}
}
int64_t elements_in_constant =
ShapeUtil::ElementsIn(instruction->shape());
static const int64_t kMaximumConstantSizeElements = 45 * 1000 * 1000;
if (elements_in_constant > elements_in_removed_operands &&
elements_in_constant > kMaximumConstantSizeElements) {
continue;
}
}
VLOG(5) << "Constant folding: " << instruction->ToString();
absl::Duration slow_timeout =
absl::Seconds(uint64_t{1} << slow_op_counter_.load());
SlowOperationAlarm slow_alarm(slow_timeout, [instruction, slow_timeout] {
const bool ndebug =
#if NDEBUG
true;
#else
false;
#endif
absl::string_view explanation_msg =
ndebug
? "This isn't necessarily a bug; constant-folding is "
"inherently a trade-off between compilation time and speed "
"at runtime. XLA has some guards that attempt to keep "
"constant folding from taking too long, but fundamentally "
"you'll always be able to come up with an input program that "
"takes a long time.\n\n"
"If you'd like to file a bug, run with envvar "
"XLA_FLAGS=--xla_dump_to=/tmp/foo and attach the results."
: "XLA was built without compiler optimizations, which can be "
"slow. Try rebuilding with -c opt.";
return absl::StrFormat(
"Constant folding an instruction is taking > %s:\n\n"
" %s\n\n" // instruction->ToString()
"%s", // explanation_msg
absl::FormatDuration(slow_timeout), instruction->ToString(),
explanation_msg);
});
// Currently we skip unimplemented operations.
// TODO(b/35975797): Fold constant computations for more operations.
Literal result;
if (!evaluator->TryEvaluate(
instruction, &result,
/*recursively_evaluate_nonconstant_operands=*/true)) {
VLOG(2) << "Constant folding failed for instruction: "
<< instruction->ToString();
continue;
}
slow_alarm.cancel();
if (slow_alarm.fired()) {
slow_op_counter_++;
}
VLOG(4) << "Constant folded: " << instruction->ToString();
TF_RETURN_IF_ERROR(computation->ReplaceWithNewInstruction(
instruction, HloInstruction::CreateConstant(std::move(result))));
changed = true;
}
}
return changed;
}
} // namespace xla
<commit_msg>Do not constant fold HloOpcode::kFft to reduce compile time.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_constant_folding.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_query.h"
#include "tensorflow/compiler/xla/service/slow_operation_alarm.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/lib/core/errors.h"
namespace xla {
// Checks whether instr is or transitively contains an instruction that we
// shouldn't fold.
//
// Specifically, we don't fold kRng or kAfterAll instructions:
//
// - kRng is already marked as side-effecting and so is skipped elsewhere, but
// we check for it here. Even kRng weren't side-effecting and took an
// explicit seed, we *still* wouldn't want to constant-fold it, because the
// evaluator's handling of rng is not guaranteed to be identical to any
// particular backend's rng.
//
// - kAfterAll needs to be skipped because a kAfterAll op with no args can
// currently materialize a token "out of thin air". TODO(b/110532604):
// Remove this check once AfterAll requires at least one operand, in which
// case constant folding will be impossible.
static bool IsOrContainsIllegalInstr(const HloInstruction* instr) {
if (instr->opcode() == HloOpcode::kAfterAll ||
instr->opcode() == HloOpcode::kRng) {
return true;
}
for (const HloComputation* c : instr->called_computations()) {
if (absl::c_any_of(c->instructions(), IsOrContainsIllegalInstr)) {
return true;
}
}
return false;
}
/*static*/ std::atomic<int64_t> HloConstantFolding::slow_op_counter_{0};
StatusOr<bool> HloConstantFolding::Run(HloModule* module) {
// Limit the constant folding to 0 iterations to skip folding loops. This
// retains the behavior from before while loop support in HloEvaluator and may
// be revised.
auto evaluator = absl::make_unique<HloEvaluator>(/*max_loop_iterations=*/0);
// fast-path lets us e.g. use Eigen for matmuls.
evaluator->set_use_fast_path(true);
bool changed = false;
for (auto* computation : module->MakeNonfusionComputations()) {
for (auto instruction : computation->MakeInstructionPostOrder()) {
// Skip dead code.
if (instruction->IsDead()) {
continue;
}
// We only handle instructions where
//
// - at least one operand is a constant, and
// - all other operands are either constants or broadcast(constant).
//
// Why this particular set of rules around broadcasts?
//
// - We don't want to fold broadcast(constant) on its own, because in
// general it's "simpler" to remember that it's a broadcast. Also,
// algsimp will fold an all-one-value constant into a broadcast, so
// we'd just end up fighting with it.
//
// - We don't want to fold an op where all operands are broadcasts of
// constants, because algsimp will transform op(broadcast(constant) =>
// broadcast(op(constant)). Then we can constant-fold the smaller op.
//
// - So the only remaining case is where some but not all operands are
// broadcasts of constants, e.g. op(constant, broadcast(constant)).
//
if (!absl::c_any_of(instruction->operands(),
[](const HloInstruction* operand) {
return operand->opcode() == HloOpcode::kConstant;
}) ||
!absl::c_all_of(
instruction->operands(), [](const HloInstruction* operand) {
return operand->opcode() == HloOpcode::kConstant ||
(operand->opcode() == HloOpcode::kBroadcast &&
operand->operand(0)->opcode() == HloOpcode::kConstant);
})) {
continue;
}
// Don't fold Constant, Parameter, and Tuple instructions. Tuple
// constants are not directly supported by any backends, hence folding
// Tuple is not useful and would in fact be expanded back into kTuple by
// Algebraic Simplifier.
//
// (We do allow folding subcomputations that contain these instructions.)
if (instruction->opcode() == HloOpcode::kParameter ||
instruction->opcode() == HloOpcode::kConstant ||
instruction->opcode() == HloOpcode::kTuple) {
continue;
}
// Broadcasts dramatically increase the size of constants, which is often
// detrimental to performance and memory capacity, so do not fold
// broadcasts.
if (instruction->opcode() == HloOpcode::kBroadcast ||
instruction->opcode() == HloOpcode::kIota) {
continue;
}
// Do not fold FFT. Evaluating it may significantly increase compile time.
if (instruction->opcode() == HloOpcode::kFft) {
continue;
}
// Check for instructions that we can't fold even if they appear inside of
// a subcomputation (e.g. a kCall).
if (IsOrContainsIllegalInstr(instruction)) {
continue;
}
// Don't constant-fold side-effecting instructions or instructions which
// contain side-effecting instructions.
if (instruction->HasSideEffect()) {
continue;
}
// Don't constant fold unless it's a net positive or the output is small.
if (instruction->shape().IsArray()) {
int64_t elements_in_removed_operands = 0;
for (HloInstruction* operand : instruction->operands()) {
if (operand->user_count() == 1 && operand->shape().IsArray()) {
elements_in_removed_operands +=
ShapeUtil::ElementsIn(operand->shape());
}
}
int64_t elements_in_constant =
ShapeUtil::ElementsIn(instruction->shape());
static const int64_t kMaximumConstantSizeElements = 45 * 1000 * 1000;
if (elements_in_constant > elements_in_removed_operands &&
elements_in_constant > kMaximumConstantSizeElements) {
continue;
}
}
VLOG(5) << "Constant folding: " << instruction->ToString();
absl::Duration slow_timeout =
absl::Seconds(uint64_t{1} << slow_op_counter_.load());
SlowOperationAlarm slow_alarm(slow_timeout, [instruction, slow_timeout] {
const bool ndebug =
#if NDEBUG
true;
#else
false;
#endif
absl::string_view explanation_msg =
ndebug
? "This isn't necessarily a bug; constant-folding is "
"inherently a trade-off between compilation time and speed "
"at runtime. XLA has some guards that attempt to keep "
"constant folding from taking too long, but fundamentally "
"you'll always be able to come up with an input program that "
"takes a long time.\n\n"
"If you'd like to file a bug, run with envvar "
"XLA_FLAGS=--xla_dump_to=/tmp/foo and attach the results."
: "XLA was built without compiler optimizations, which can be "
"slow. Try rebuilding with -c opt.";
return absl::StrFormat(
"Constant folding an instruction is taking > %s:\n\n"
" %s\n\n" // instruction->ToString()
"%s", // explanation_msg
absl::FormatDuration(slow_timeout), instruction->ToString(),
explanation_msg);
});
// Currently we skip unimplemented operations.
// TODO(b/35975797): Fold constant computations for more operations.
Literal result;
if (!evaluator->TryEvaluate(
instruction, &result,
/*recursively_evaluate_nonconstant_operands=*/true)) {
VLOG(2) << "Constant folding failed for instruction: "
<< instruction->ToString();
continue;
}
slow_alarm.cancel();
if (slow_alarm.fired()) {
slow_op_counter_++;
}
VLOG(4) << "Constant folded: " << instruction->ToString();
TF_RETURN_IF_ERROR(computation->ReplaceWithNewInstruction(
instruction, HloInstruction::CreateConstant(std::move(result))));
changed = true;
}
}
return changed;
}
} // namespace xla
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Alexander Chumakov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "utils.h"
#include <QDebug>
#include <wbxml.h>
#include <string.h>
#include <SignOn/Identity>
#include <Accounts/Account>
#include <Accounts/Manager>
#include <QProcessEnvironment>
namespace {
const QLatin1String SsoMethod("auth/method");
const QLatin1String AsProviderName("activesync");
const QLatin1String AccountCredId("CredentialsId");
const QLatin1String NwSecureConnection("connection/secure_connection");
}
void Utils::registerAccount()
{
Accounts::Manager manager;
Accounts::Account *account = manager.account(1);
if (!account) {
account = manager.createAccount(AsProviderName);
}
account->setEnabled(true);
account->setDisplayName("Main AS Account");
const QProcessEnvironment &env = QProcessEnvironment::systemEnvironment();
const QString &userId = env.value("MY_USER", "<user>");
const QString &serverAddress = env.value("MY_ADDR", "exchange-server.com");
const QString &serverPort = env.value("MY_PORT", "443");
account->setValue("default_credentials_username", userId);
account->beginGroup("connection");
account->setValue("exchange_server", serverAddress + serverPort);
account->endGroup();
account->setValue(SsoMethod, "password");
account->setValue(AccountCredId, "1");
account->setValue(NwSecureConnection, true);
account->sync();
// SignOn handling
const QString &passwd = env.value("MY_PASS", "<password>");
SignOn::IdentityInfo identityInfo;
identityInfo.setUserName(userId);
identityInfo.setSecret(passwd, true);
SignOn::Identity *const identity = SignOn::Identity::newIdentity(identityInfo);
if (!identity) {
qDebug() << "[Utils::registerAccount] Cannot create 'identity'";
} else {
identity->storeCredentials();
}
qDebug() << "[Utils::registerAccount]: account, ID: " << account->id();
}
void Utils::hexDump(const char *pData)
{
const int length = strlen (pData);
hexDump (reinterpret_cast<const unsigned char *>(pData), length);
}
void Utils::hexDump(const unsigned char *pData, int length)
{
char buffer[20];
QDebug debug = qDebug();
debug.nospace();
for (int i = 0; i < length; ++i) {
if (!(i % 16)) {
snprintf(buffer, 20, "%4.4x: ", i);
debug << buffer;
}
char byte = pData[i];
char lowByte = (0xFU&byte) + '0';
char highByte = (0xFU&(byte>>4)) + '0';
if (lowByte > '9') {
// 0x0A => 'A', etc...
lowByte += 'A' - ('9' + 1);
}
if (highByte > '9') {
// 0x0A => 'A', etc...
highByte += 'A' - ('9' + 1);
}
if (byte < 32) {
byte = '.';
}
debug << highByte << lowByte << "(" << byte << ") ";
if (i%16 == 15) {
debug << "\n";
}
}
debug << "\n";
debug.space();
}
QString Utils::hexTreeNodeType(int treeNodeType)
{
QString name;
switch (treeNodeType) {
case WBXML_TREE_ELEMENT_NODE:
name = "WBXML_TREE_ELEMENT_NODE";
break;
case WBXML_TREE_TEXT_NODE:
name = "WBXML_TREE_TEXT_NODE";
break;
case WBXML_TREE_CDATA_NODE:
name = "WBXML_TREE_CDATA_NODE";
break;
case WBXML_TREE_PI_NODE:
name = "WBXML_TREE_PI_NODE";
break;
case WBXML_TREE_TREE_NODE:
name = "WBXML_TREE_TREE_NODE";
break;
default:
name = "WBXML_TREE_UNDEFINED";
break;
}
return name;
}
QDebug Utils::logNodeName(QDebug debug, WBXMLTag *nodeName)
{
if (!nodeName) return debug;
if (WBXML_VALUE_TOKEN == nodeName->type) {
debug << "[WBXML_VALUE_TOKEN: ";
const WBXMLTagEntry *const token = nodeName->u.token;
if (token) {
const WB_TINY *const xmlName = token->xmlName;
debug << "ENTRY: ";
if (xmlName) {
debug << "\"" << xmlName << "\", ";
} else {
debug << "<null>, ";
}
debug << "PAGE: " << token->wbxmlCodePage << ", TOKEN: " << token->wbxmlToken;
} else {
debug << "<null>";
}
debug << "]";
} else if (WBXML_VALUE_LITERAL == nodeName->type) {
debug << "[WBXML_VALUE_LITERAL: \"" << (const char *)wbxml_buffer_get_cstr(nodeName->u.literal) << "\"]";
} else {
debug << "[WBXML_VALUE_UNKNOWN]";
}
return debug;
}
QDebug Utils::logNode(QDebug debug, WBXMLTreeNode *node, int level)
{
// check if the 'node' exists
if (!node) return debug;
debug.nospace();
for (int i = 0; i < level; ++i) {
debug << " ";
}
const char *content = (const char *)wbxml_buffer_get_cstr(node->content);
if (!strlen(content)) {
debug << "Tree node type: " << hexTreeNodeType(node->type);
} else {
debug << "Tree node type: " << hexTreeNodeType(node->type) << ", content: \"" << content << "\"";
}
if (node->name) {
debug << ", name: \"";
Utils::logNodeName(debug, node->name);
debug << "\"";
}
debug << "\n";
debug.space();
WBXMLTreeNode *children = node->children;
while (children) {
logNode(debug, children, level + 1);
children = children->next;
}
return debug;
}
<commit_msg>Updated account registration<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Alexander Chumakov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "utils.h"
#include <QDebug>
#include <wbxml.h>
#include <string.h>
#include <SignOn/Identity>
#include <Accounts/Account>
#include <Accounts/Manager>
#include <QProcessEnvironment>
namespace {
const QLatin1String SsoMethod("auth/method");
const QLatin1String AsProviderName("activesync");
const QLatin1String AccountCredId("CredentialsId");
const QLatin1String ExchangeServerPort("connection/port");
const QLatin1String ExchangeServerHost("connection/exchange_server");
const QLatin1String NwSecureConnection("connection/secure_connection");
}
void Utils::registerAccount()
{
Accounts::Manager manager;
Accounts::Account *account = manager.account(1);
if (!account) {
account = manager.createAccount(AsProviderName);
}
account->setEnabled(true);
account->setDisplayName("Main AS Account");
const QProcessEnvironment &env = QProcessEnvironment::systemEnvironment();
const QString &userId = env.value("MY_USER", "<user>");
const QString &serverAddress = env.value("MY_ADDR", "exchange-server.com");
const QString &serverPort = env.value("MY_PORT", "443");
account->setValue("default_credentials_username", userId);
account->beginGroup("connection");
account->setValue("exchange_server", serverAddress);
account->setValue("port", serverPort);
account->endGroup();
account->setValue(SsoMethod, "password");
account->setValue(AccountCredId, "1");
account->setValue(NwSecureConnection, true);
account->sync();
// SignOn handling
const QString &passwd = env.value("MY_PASS", "<password>");
SignOn::IdentityInfo identityInfo;
identityInfo.setUserName(userId);
identityInfo.setSecret(passwd, true);
SignOn::Identity *const identity = SignOn::Identity::newIdentity(identityInfo);
if (!identity) {
qDebug() << "[Utils::registerAccount] Cannot create 'identity'";
} else {
identity->storeCredentials();
}
qDebug() << "[Utils::registerAccount]: account, ID: " << account->id();
}
void Utils::hexDump(const char *pData)
{
const int length = strlen (pData);
hexDump (reinterpret_cast<const unsigned char *>(pData), length);
}
void Utils::hexDump(const unsigned char *pData, int length)
{
char buffer[20];
QDebug debug = qDebug();
debug.nospace();
for (int i = 0; i < length; ++i) {
if (!(i % 16)) {
snprintf(buffer, 20, "%4.4x: ", i);
debug << buffer;
}
char byte = pData[i];
char lowByte = (0xFU&byte) + '0';
char highByte = (0xFU&(byte>>4)) + '0';
if (lowByte > '9') {
// 0x0A => 'A', etc...
lowByte += 'A' - ('9' + 1);
}
if (highByte > '9') {
// 0x0A => 'A', etc...
highByte += 'A' - ('9' + 1);
}
if (byte < 32) {
byte = '.';
}
debug << highByte << lowByte << "(" << byte << ") ";
if (i%16 == 15) {
debug << "\n";
}
}
debug << "\n";
debug.space();
}
QString Utils::hexTreeNodeType(int treeNodeType)
{
QString name;
switch (treeNodeType) {
case WBXML_TREE_ELEMENT_NODE:
name = "WBXML_TREE_ELEMENT_NODE";
break;
case WBXML_TREE_TEXT_NODE:
name = "WBXML_TREE_TEXT_NODE";
break;
case WBXML_TREE_CDATA_NODE:
name = "WBXML_TREE_CDATA_NODE";
break;
case WBXML_TREE_PI_NODE:
name = "WBXML_TREE_PI_NODE";
break;
case WBXML_TREE_TREE_NODE:
name = "WBXML_TREE_TREE_NODE";
break;
default:
name = "WBXML_TREE_UNDEFINED";
break;
}
return name;
}
QDebug Utils::logNodeName(QDebug debug, WBXMLTag *nodeName)
{
if (!nodeName) return debug;
if (WBXML_VALUE_TOKEN == nodeName->type) {
debug << "[WBXML_VALUE_TOKEN: ";
const WBXMLTagEntry *const token = nodeName->u.token;
if (token) {
const WB_TINY *const xmlName = token->xmlName;
debug << "ENTRY: ";
if (xmlName) {
debug << "\"" << xmlName << "\", ";
} else {
debug << "<null>, ";
}
debug << "PAGE: " << token->wbxmlCodePage << ", TOKEN: " << token->wbxmlToken;
} else {
debug << "<null>";
}
debug << "]";
} else if (WBXML_VALUE_LITERAL == nodeName->type) {
debug << "[WBXML_VALUE_LITERAL: \"" << (const char *)wbxml_buffer_get_cstr(nodeName->u.literal) << "\"]";
} else {
debug << "[WBXML_VALUE_UNKNOWN]";
}
return debug;
}
QDebug Utils::logNode(QDebug debug, WBXMLTreeNode *node, int level)
{
// check if the 'node' exists
if (!node) return debug;
debug.nospace();
for (int i = 0; i < level; ++i) {
debug << " ";
}
const char *content = (const char *)wbxml_buffer_get_cstr(node->content);
if (!strlen(content)) {
debug << "Tree node type: " << hexTreeNodeType(node->type);
} else {
debug << "Tree node type: " << hexTreeNodeType(node->type) << ", content: \"" << content << "\"";
}
if (node->name) {
debug << ", name: \"";
Utils::logNodeName(debug, node->name);
debug << "\"";
}
debug << "\n";
debug.space();
WBXMLTreeNode *children = node->children;
while (children) {
logNode(debug, children, level + 1);
children = children->next;
}
return debug;
}
<|endoftext|> |
<commit_before>#ifndef UTILS_HPP_
#define UTILS_HPP_
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "containers/printf_buffer.hpp"
#include "errors.hpp"
#include "config/args.hpp"
struct const_charslice {
const char *beg, *end;
const_charslice(const char *beg_, const char *end_) : beg(beg_), end(end_) { }
const_charslice() : beg(NULL), end(NULL) { }
};
typedef uint64_t microtime_t;
microtime_t current_microtime();
/* General exception to be thrown when some process is interrupted. It's in
`utils.hpp` because I can't think where else to put it */
class interrupted_exc_t : public std::exception {
public:
const char *what() const throw () {
return "interrupted";
}
};
/* Pad a value to the size of a cache line to avoid false sharing.
* TODO: This is implemented as a struct with subtraction rather than a union
* so that it gives an error when trying to pad a value bigger than
* CACHE_LINE_SIZE. If that's needed, this may have to be done differently.
*/
template<typename value_t>
struct cache_line_padded_t {
value_t value;
char padding[CACHE_LINE_SIZE - sizeof(value_t)];
};
void *malloc_aligned(size_t size, size_t alignment = 64);
template <class T1, class T2>
T1 ceil_aligned(T1 value, T2 alignment) {
return value + alignment - (((value + alignment - 1) % alignment) + 1);
}
template <class T1, class T2>
T1 ceil_divide(T1 dividend, T2 alignment) {
return (dividend + alignment - 1) / alignment;
}
template <class T1, class T2>
T1 floor_aligned(T1 value, T2 alignment) {
return value - (value % alignment);
}
template <class T1, class T2>
T1 ceil_modulo(T1 value, T2 alignment) {
T1 x = (value + alignment - 1) % alignment;
return value + alignment - ((x < 0 ? x + alignment : x) + 1);
}
inline bool divides(int64_t x, int64_t y) {
return y % x == 0;
}
int gcd(int x, int y);
int64_t round_up_to_power_of_two(int64_t x);
typedef uint64_t ticks_t;
ticks_t secs_to_ticks(float secs);
ticks_t get_ticks();
time_t get_secs();
int64_t get_ticks_res();
double ticks_to_secs(ticks_t ticks);
// HEY: Maybe debugf and log_call and TRACEPOINT should be placed in
// debugf.hpp (and debugf.cc).
/* Debugging printing API (prints current thread in addition to message) */
void debug_print_quoted_string(append_only_printf_buffer_t *buf, const uint8_t *s, size_t n);
void debugf_prefix_buf(printf_buffer_t<1000> *buf);
void debugf_dump_buf(printf_buffer_t<1000> *buf);
// Primitive debug_print declarations.
void debug_print(append_only_printf_buffer_t *buf, uint64_t x);
void debug_print(append_only_printf_buffer_t *buf, const std::string& s);
#ifndef NDEBUG
void debugf(const char *msg, ...) __attribute__((format (printf, 1, 2)));
template <class T>
void debugf_print(const char *msg, const T& obj) {
printf_buffer_t<1000> buf;
debugf_prefix_buf(&buf);
buf.appendf("%s: ", msg);
debug_print(&buf, obj);
buf.appendf("\n");
debugf_dump_buf(&buf);
}
#else
#define debugf(...) ((void)0)
#define debugf_print(...) ((void)0)
#endif
class rng_t {
public:
// Returns a random number in [0, n). Is not perfectly uniform; the
// bias tends to get worse when RAND_MAX is far from a multiple of n.
int randint(int n);
explicit rng_t(int seed = -1);
private:
struct drand48_data buffer_;
DISABLE_COPYING(rng_t);
};
int randint(int n);
std::string rand_string(int len);
bool begins_with_minus(const char *string);
// strtoul() and strtoull() will for some reason not fail if the input begins
// with a minus sign. strtou64_strict() does. Also we fix the constness of the
// end parameter.
int64_t strtoi64_strict(const char *string, const char **end, int base);
uint64_t strtou64_strict(const char *string, const char **end, int base);
// These functions return false and set the result to 0 if the conversion fails or
// does not consume the whole string.
MUST_USE bool strtoi64_strict(const std::string &str, int base, int64_t *out_result);
MUST_USE bool strtou64_strict(const std::string &str, int base, uint64_t *out_result);
std::string strprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
std::string vstrprintf(const char *format, va_list ap);
// formatted time:
// yyyy-mm-ddThh:mm:ss.nnnnnnnnn (29 characters)
const size_t formatted_time_length = 29; // not including null
void format_time(struct timespec time, append_only_printf_buffer_t *buf);
std::string format_time(struct timespec time);
struct timespec parse_time(const std::string &str) THROWS_ONLY(std::runtime_error);
/* Printing binary data to stdout in a nice format */
void print_hd(const void *buf, size_t offset, size_t length);
// Fast string compare
int sized_strcmp(const uint8_t *str1, int len1, const uint8_t *str2, int len2);
/* The home thread mixin is a mixin for objects that can only be used
on a single thread. Its thread ID is exposed as the `home_thread()`
method. Some subclasses of `home_thread_mixin_t` can move themselves to
another thread, modifying the field real_home_thread. */
#define INVALID_THREAD (-1)
class home_thread_mixin_t {
public:
int home_thread() const { return real_home_thread; }
#ifndef NDEBUG
void assert_thread() const;
#else
void assert_thread() const { }
#endif // NDEBUG
protected:
explicit home_thread_mixin_t(int specified_home_thread);
home_thread_mixin_t();
virtual ~home_thread_mixin_t() { }
int real_home_thread;
private:
// Things with home threads should not be copyable, since we don't
// want to nonchalantly copy their real_home_thread variable.
DISABLE_COPYING(home_thread_mixin_t);
};
/* `on_thread_t` switches to the given thread in its constructor, then switches
back in its destructor. For example:
printf("Suppose we are on thread 1.\n");
{
on_thread_t thread_switcher(2);
printf("Now we are on thread 2.\n");
}
printf("And now we are on thread 1 again.\n");
*/
class on_thread_t : public home_thread_mixin_t {
public:
explicit on_thread_t(int thread);
~on_thread_t();
};
template <class InputIterator, class UnaryPredicate>
bool all_match_predicate(InputIterator begin, InputIterator end, UnaryPredicate f) {
bool res = true;
for (; begin != end; begin++) {
res &= f(*begin);
}
return res;
}
template <class T, class UnaryPredicate>
bool all_in_container_match_predicate (const T &container, UnaryPredicate f) {
return all_match_predicate(container.begin(), container.end(), f);
}
bool notf(bool x);
/* Translates to and from `0123456789ABCDEF`. */
bool hex_to_int(char c, int *out);
char int_to_hex(int i);
std::string read_file(const char *path);
struct path_t {
std::vector<std::string> nodes;
bool is_absolute;
};
path_t parse_as_path(const std::string &);
std::string render_as_path(const path_t &);
enum region_join_result_t { REGION_JOIN_OK, REGION_JOIN_BAD_JOIN, REGION_JOIN_BAD_REGION };
template <class T>
void delete_a_thing(T *thing_to_delete) {
delete thing_to_delete;
}
template <class T>
class assignment_sentry_t {
public:
assignment_sentry_t(T *v, const T &value) :
var(v), old_value(*var) {
*var = value;
}
~assignment_sentry_t() {
*var = old_value;
}
private:
T *var;
T old_value;
};
#endif // UTILS_HPP_
<commit_msg>Removed the unused function delete_a_thing.<commit_after>#ifndef UTILS_HPP_
#define UTILS_HPP_
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "containers/printf_buffer.hpp"
#include "errors.hpp"
#include "config/args.hpp"
struct const_charslice {
const char *beg, *end;
const_charslice(const char *beg_, const char *end_) : beg(beg_), end(end_) { }
const_charslice() : beg(NULL), end(NULL) { }
};
typedef uint64_t microtime_t;
microtime_t current_microtime();
/* General exception to be thrown when some process is interrupted. It's in
`utils.hpp` because I can't think where else to put it */
class interrupted_exc_t : public std::exception {
public:
const char *what() const throw () {
return "interrupted";
}
};
/* Pad a value to the size of a cache line to avoid false sharing.
* TODO: This is implemented as a struct with subtraction rather than a union
* so that it gives an error when trying to pad a value bigger than
* CACHE_LINE_SIZE. If that's needed, this may have to be done differently.
*/
template<typename value_t>
struct cache_line_padded_t {
value_t value;
char padding[CACHE_LINE_SIZE - sizeof(value_t)];
};
void *malloc_aligned(size_t size, size_t alignment = 64);
template <class T1, class T2>
T1 ceil_aligned(T1 value, T2 alignment) {
return value + alignment - (((value + alignment - 1) % alignment) + 1);
}
template <class T1, class T2>
T1 ceil_divide(T1 dividend, T2 alignment) {
return (dividend + alignment - 1) / alignment;
}
template <class T1, class T2>
T1 floor_aligned(T1 value, T2 alignment) {
return value - (value % alignment);
}
template <class T1, class T2>
T1 ceil_modulo(T1 value, T2 alignment) {
T1 x = (value + alignment - 1) % alignment;
return value + alignment - ((x < 0 ? x + alignment : x) + 1);
}
inline bool divides(int64_t x, int64_t y) {
return y % x == 0;
}
int gcd(int x, int y);
int64_t round_up_to_power_of_two(int64_t x);
typedef uint64_t ticks_t;
ticks_t secs_to_ticks(float secs);
ticks_t get_ticks();
time_t get_secs();
int64_t get_ticks_res();
double ticks_to_secs(ticks_t ticks);
// HEY: Maybe debugf and log_call and TRACEPOINT should be placed in
// debugf.hpp (and debugf.cc).
/* Debugging printing API (prints current thread in addition to message) */
void debug_print_quoted_string(append_only_printf_buffer_t *buf, const uint8_t *s, size_t n);
void debugf_prefix_buf(printf_buffer_t<1000> *buf);
void debugf_dump_buf(printf_buffer_t<1000> *buf);
// Primitive debug_print declarations.
void debug_print(append_only_printf_buffer_t *buf, uint64_t x);
void debug_print(append_only_printf_buffer_t *buf, const std::string& s);
#ifndef NDEBUG
void debugf(const char *msg, ...) __attribute__((format (printf, 1, 2)));
template <class T>
void debugf_print(const char *msg, const T& obj) {
printf_buffer_t<1000> buf;
debugf_prefix_buf(&buf);
buf.appendf("%s: ", msg);
debug_print(&buf, obj);
buf.appendf("\n");
debugf_dump_buf(&buf);
}
#else
#define debugf(...) ((void)0)
#define debugf_print(...) ((void)0)
#endif
class rng_t {
public:
// Returns a random number in [0, n). Is not perfectly uniform; the
// bias tends to get worse when RAND_MAX is far from a multiple of n.
int randint(int n);
explicit rng_t(int seed = -1);
private:
struct drand48_data buffer_;
DISABLE_COPYING(rng_t);
};
int randint(int n);
std::string rand_string(int len);
bool begins_with_minus(const char *string);
// strtoul() and strtoull() will for some reason not fail if the input begins
// with a minus sign. strtou64_strict() does. Also we fix the constness of the
// end parameter.
int64_t strtoi64_strict(const char *string, const char **end, int base);
uint64_t strtou64_strict(const char *string, const char **end, int base);
// These functions return false and set the result to 0 if the conversion fails or
// does not consume the whole string.
MUST_USE bool strtoi64_strict(const std::string &str, int base, int64_t *out_result);
MUST_USE bool strtou64_strict(const std::string &str, int base, uint64_t *out_result);
std::string strprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
std::string vstrprintf(const char *format, va_list ap);
// formatted time:
// yyyy-mm-ddThh:mm:ss.nnnnnnnnn (29 characters)
const size_t formatted_time_length = 29; // not including null
void format_time(struct timespec time, append_only_printf_buffer_t *buf);
std::string format_time(struct timespec time);
struct timespec parse_time(const std::string &str) THROWS_ONLY(std::runtime_error);
/* Printing binary data to stdout in a nice format */
void print_hd(const void *buf, size_t offset, size_t length);
// Fast string compare
int sized_strcmp(const uint8_t *str1, int len1, const uint8_t *str2, int len2);
/* The home thread mixin is a mixin for objects that can only be used
on a single thread. Its thread ID is exposed as the `home_thread()`
method. Some subclasses of `home_thread_mixin_t` can move themselves to
another thread, modifying the field real_home_thread. */
#define INVALID_THREAD (-1)
class home_thread_mixin_t {
public:
int home_thread() const { return real_home_thread; }
#ifndef NDEBUG
void assert_thread() const;
#else
void assert_thread() const { }
#endif // NDEBUG
protected:
explicit home_thread_mixin_t(int specified_home_thread);
home_thread_mixin_t();
virtual ~home_thread_mixin_t() { }
int real_home_thread;
private:
// Things with home threads should not be copyable, since we don't
// want to nonchalantly copy their real_home_thread variable.
DISABLE_COPYING(home_thread_mixin_t);
};
/* `on_thread_t` switches to the given thread in its constructor, then switches
back in its destructor. For example:
printf("Suppose we are on thread 1.\n");
{
on_thread_t thread_switcher(2);
printf("Now we are on thread 2.\n");
}
printf("And now we are on thread 1 again.\n");
*/
class on_thread_t : public home_thread_mixin_t {
public:
explicit on_thread_t(int thread);
~on_thread_t();
};
template <class InputIterator, class UnaryPredicate>
bool all_match_predicate(InputIterator begin, InputIterator end, UnaryPredicate f) {
bool res = true;
for (; begin != end; begin++) {
res &= f(*begin);
}
return res;
}
template <class T, class UnaryPredicate>
bool all_in_container_match_predicate (const T &container, UnaryPredicate f) {
return all_match_predicate(container.begin(), container.end(), f);
}
bool notf(bool x);
/* Translates to and from `0123456789ABCDEF`. */
bool hex_to_int(char c, int *out);
char int_to_hex(int i);
std::string read_file(const char *path);
struct path_t {
std::vector<std::string> nodes;
bool is_absolute;
};
path_t parse_as_path(const std::string &);
std::string render_as_path(const path_t &);
enum region_join_result_t { REGION_JOIN_OK, REGION_JOIN_BAD_JOIN, REGION_JOIN_BAD_REGION };
template <class T>
class assignment_sentry_t {
public:
assignment_sentry_t(T *v, const T &value) :
var(v), old_value(*var) {
*var = value;
}
~assignment_sentry_t() {
*var = old_value;
}
private:
T *var;
T old_value;
};
#endif // UTILS_HPP_
<|endoftext|> |
<commit_before>//---------------------------- template.cc ---------------------------
// $Id: gradients.cc 22693 2010-11-11 20:11:47Z kanschat $
// Version: $Name$
//
// Copyright (C) 2005, 2008, 2009, 2010 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- template.cc ---------------------------
// Controls that the covariant matrix is calculated properly. It uses
// a Q1 finite element to calculate the scalar product of the gradient
// of a projected function (a monomial) with the tangential to the
// cell surface taken in the cell midpoint. The result obtained is
// compared with the exact one in the <1,2> case.
#include "../tests.h"
#include <fstream>
#include <base/logstream.h>
#include <string>
// all include files needed for the program
#include <base/function.h>
#include <base/function_lib.h>
#include <base/quadrature_lib.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <lac/constraint_matrix.h>
#include <fe/mapping.h>
#include <fe/mapping_q1.h>
#include <fe/fe_dgq.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <grid/tria.h>
#include <grid/grid_in.h>
#include <grid/grid_out.h>
#include <numerics/vectors.h>
#include <numerics/data_out.h>
#include <cmath>
std::ofstream logfile("gradients_1/output");
template <int dim, int spacedim>
void test(std::string filename, unsigned int degree = 1)
{
Triangulation<dim, spacedim> triangulation;
GridIn<dim, spacedim> gi;
gi.attach_triangulation (triangulation);
std::ifstream in (filename.c_str());
gi.read_ucd (in);
// finite elements used for the
// projection
const FE_Q<dim,spacedim> fe (degree);
const MappingQ<dim, spacedim> mapping(degree);
DoFHandler<dim,spacedim> dof_handler (triangulation);
dof_handler.distribute_dofs (fe);
deallog
<< "no. of cells "<< triangulation.n_cells() <<std::endl;
deallog
<< "no. of dofs "<< dof_handler.n_dofs()<< std::endl;
deallog
<< "no. of dofs per cell "<< fe.dofs_per_cell<< std::endl;
// definition of the exact function
// and calculation of the projected
// one
Vector<double> projected_one(dof_handler.n_dofs());
Functions::CosineFunction<spacedim> the_function;
// Tensor<1,spacedim> exp;
// exp[0]=1;
// exp[1]=0;
// if(spacedim==3)
// exp[2]=0;
// Functions::Monomial<spacedim> the_function(exp);
const QGauss<dim> quad(2*fe.degree+1);
ConstraintMatrix constraints;
constraints.close();
VectorTools::project(mapping, dof_handler, constraints,
quad, the_function, projected_one);
deallog << "L2 norm of projected vector: "
<< projected_one.l2_norm() << endl;
// compute the H1 difference
Vector<float> difference_per_cell (triangulation.n_active_cells());
VectorTools::integrate_difference (dof_handler, projected_one,
the_function, difference_per_cell,
quad, VectorTools::H1_norm);
deallog << "H1 error: " << difference_per_cell.l2_norm() << endl;
}
int main ()
{
logfile.precision (4);
deallog.attach(logfile);
deallog.depth_console(3);
deallog.threshold_double(1.e-12);
deallog<<"Test <1,2>, Q1, Q2, Q3"<<std::endl;
test<1,2>("grids/circle_4.inp",1);
test<1,2>("grids/circle_4.inp",2);
test<1,2>("grids/circle_4.inp",3);
deallog<<std::endl;
deallog<<"Test <2,3>, Q1, Q2, Q3"<<std::endl;
test<2,3>("grids/sphere_1.inp",1);
test<2,3>("grids/sphere_1.inp",2);
test<2,3>("grids/sphere_1.inp",3);
return 0;
}
<commit_msg>Avoid output to the screen.<commit_after>//---------------------------- template.cc ---------------------------
// $Id: gradients.cc 22693 2010-11-11 20:11:47Z kanschat $
// Version: $Name$
//
// Copyright (C) 2005, 2008, 2009, 2010 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- template.cc ---------------------------
// Controls that the covariant matrix is calculated properly. It uses
// a Q1 finite element to calculate the scalar product of the gradient
// of a projected function (a monomial) with the tangential to the
// cell surface taken in the cell midpoint. The result obtained is
// compared with the exact one in the <1,2> case.
#include "../tests.h"
#include <fstream>
#include <base/logstream.h>
#include <string>
// all include files needed for the program
#include <base/function.h>
#include <base/function_lib.h>
#include <base/quadrature_lib.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <lac/constraint_matrix.h>
#include <fe/mapping.h>
#include <fe/mapping_q1.h>
#include <fe/fe_dgq.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <grid/tria.h>
#include <grid/grid_in.h>
#include <grid/grid_out.h>
#include <numerics/vectors.h>
#include <numerics/data_out.h>
#include <cmath>
std::ofstream logfile("gradients_1/output");
template <int dim, int spacedim>
void test(std::string filename, unsigned int degree = 1)
{
Triangulation<dim, spacedim> triangulation;
GridIn<dim, spacedim> gi;
gi.attach_triangulation (triangulation);
std::ifstream in (filename.c_str());
gi.read_ucd (in);
// finite elements used for the
// projection
const FE_Q<dim,spacedim> fe (degree);
const MappingQ<dim, spacedim> mapping(degree);
DoFHandler<dim,spacedim> dof_handler (triangulation);
dof_handler.distribute_dofs (fe);
deallog
<< "no. of cells "<< triangulation.n_cells() <<std::endl;
deallog
<< "no. of dofs "<< dof_handler.n_dofs()<< std::endl;
deallog
<< "no. of dofs per cell "<< fe.dofs_per_cell<< std::endl;
// definition of the exact function
// and calculation of the projected
// one
Vector<double> projected_one(dof_handler.n_dofs());
Functions::CosineFunction<spacedim> the_function;
// Tensor<1,spacedim> exp;
// exp[0]=1;
// exp[1]=0;
// if(spacedim==3)
// exp[2]=0;
// Functions::Monomial<spacedim> the_function(exp);
const QGauss<dim> quad(2*fe.degree+1);
ConstraintMatrix constraints;
constraints.close();
VectorTools::project(mapping, dof_handler, constraints,
quad, the_function, projected_one);
deallog << "L2 norm of projected vector: "
<< projected_one.l2_norm() << endl;
// compute the H1 difference
Vector<float> difference_per_cell (triangulation.n_active_cells());
VectorTools::integrate_difference (dof_handler, projected_one,
the_function, difference_per_cell,
quad, VectorTools::H1_norm);
deallog << "H1 error: " << difference_per_cell.l2_norm() << endl;
}
int main ()
{
logfile.precision (4);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-12);
deallog<<"Test <1,2>, Q1, Q2, Q3"<<std::endl;
test<1,2>("grids/circle_4.inp",1);
test<1,2>("grids/circle_4.inp",2);
test<1,2>("grids/circle_4.inp",3);
deallog<<std::endl;
deallog<<"Test <2,3>, Q1, Q2, Q3"<<std::endl;
test<2,3>("grids/sphere_1.inp",1);
test<2,3>("grids/sphere_1.inp",2);
test<2,3>("grids/sphere_1.inp",3);
return 0;
}
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the LiveSupport project.
http://livesupport.campware.org/
To report bugs, send an e-mail to [email protected]
LiveSupport is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LiveSupport 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with LiveSupport; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author$
Version : $Revision$
Location : $URL$
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#include "SchedulerDaemon.h"
#include "BaseTestMethod.h"
using namespace LiveSupport::Scheduler;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
/*------------------------------------------------------------------------------
* The XML-RPC host to connect to.
*----------------------------------------------------------------------------*/
std::string LiveSupport::Scheduler::BaseTestMethod::xmlRpcHost;
/*------------------------------------------------------------------------------
* The XML-RPC port number to connect to.
*----------------------------------------------------------------------------*/
unsigned int LiveSupport::Scheduler::BaseTestMethod::xmlRpcPort;
/*------------------------------------------------------------------------------
* A flag to indicate if configuration has already been done.
*----------------------------------------------------------------------------*/
bool LiveSupport::Scheduler::BaseTestMethod::configured = false;
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Read configuration information.
*----------------------------------------------------------------------------*/
void
LiveSupport::Scheduler::
BaseTestMethod :: configure(std::string configFileName)
throw (std::exception)
{
if (!configured) {
Ptr<SchedulerDaemon>::Ref scheduler = SchedulerDaemon::getInstance();
try {
std::auto_ptr<xmlpp::DomParser>
parser(new xmlpp::DomParser(configFileName, true));
const xmlpp::Document * document = parser->get_document();
scheduler->configure(*(document->get_root_node()));
} catch (std::invalid_argument &e) {
std::cerr << "semantic error in configuration file" << std::endl
<< e.what() << std::endl;
} catch (xmlpp::exception &e) {
std::cerr << "error parsing configuration file" << std::endl
<< e.what() << std::endl;
}
xmlRpcHost = scheduler->getXmlRpcHost();
xmlRpcPort = scheduler->getXmlRpcPort();
}
}
<commit_msg>minor bugfix; the 'configured' variable was never set to true<commit_after>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the LiveSupport project.
http://livesupport.campware.org/
To report bugs, send an e-mail to [email protected]
LiveSupport is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LiveSupport 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with LiveSupport; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author$
Version : $Revision$
Location : $URL$
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#include "SchedulerDaemon.h"
#include "BaseTestMethod.h"
using namespace LiveSupport::Scheduler;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
/*------------------------------------------------------------------------------
* The XML-RPC host to connect to.
*----------------------------------------------------------------------------*/
std::string LiveSupport::Scheduler::BaseTestMethod::xmlRpcHost;
/*------------------------------------------------------------------------------
* The XML-RPC port number to connect to.
*----------------------------------------------------------------------------*/
unsigned int LiveSupport::Scheduler::BaseTestMethod::xmlRpcPort;
/*------------------------------------------------------------------------------
* A flag to indicate if configuration has already been done.
*----------------------------------------------------------------------------*/
bool LiveSupport::Scheduler::BaseTestMethod::configured = false;
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Read configuration information.
*----------------------------------------------------------------------------*/
void
LiveSupport::Scheduler::
BaseTestMethod :: configure(std::string configFileName)
throw (std::exception)
{
if (!configured) {
Ptr<SchedulerDaemon>::Ref scheduler = SchedulerDaemon::getInstance();
try {
std::auto_ptr<xmlpp::DomParser>
parser(new xmlpp::DomParser(configFileName, true));
const xmlpp::Document * document = parser->get_document();
scheduler->configure(*(document->get_root_node()));
} catch (std::invalid_argument &e) {
std::cerr << "semantic error in configuration file" << std::endl
<< e.what() << std::endl;
} catch (xmlpp::exception &e) {
std::cerr << "error parsing configuration file" << std::endl
<< e.what() << std::endl;
}
xmlRpcHost = scheduler->getXmlRpcHost();
xmlRpcPort = scheduler->getXmlRpcPort();
configured = true;
}
}
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/DcrDecoder.h"
#include "common/Common.h" // for uint32, uchar8, ushort16
#include "common/NORangesSet.h" // for NORangesSet
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/ByteStream.h" // for ByteStream
#include "io/IOException.h" // for IOException
#include "tiff/TiffEntry.h" // for TiffEntry, TiffDataType::T...
#include "tiff/TiffIFD.h" // for TiffRootIFD, TiffIFD
#include "tiff/TiffTag.h" // for TiffTag, TiffTag::COMPRESSION
#include <cassert> // for assert
#include <memory> // for unique_ptr
#include <string> // for operator==, string
using std::min;
namespace rawspeed {
class CameraMetaData;
bool DcrDecoder::isAppropriateDecoder(const TiffRootIFD* rootIFD,
const Buffer* file) {
const auto id = rootIFD->getID();
const std::string& make = id.make;
// FIXME: magic
return make == "Kodak";
}
void DcrDecoder::checkImageDimensions() {
if (width > 4516 || height > 3012)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height);
}
RawImage DcrDecoder::decodeRawInternal() {
SimpleTiffDecoder::prepareForRawDecoding();
ByteStream input(mFile, off);
int compression = raw->getEntry(COMPRESSION)->getU32();
if (65000 == compression) {
TiffEntry *ifdoffset = mRootIFD->getEntryRecursive(KODAK_IFD);
if (!ifdoffset)
ThrowRDE("Couldn't find the Kodak IFD offset");
NORangesSet<Buffer> ifds;
assert(ifdoffset != nullptr);
TiffRootIFD kodakifd(nullptr, &ifds, ifdoffset->getRootIfdData(),
ifdoffset->getU32());
TiffEntry *linearization = kodakifd.getEntryRecursive(KODAK_LINEARIZATION);
if (!linearization || linearization->count != 1024 ||
linearization->type != TIFF_SHORT)
ThrowRDE("Couldn't find the linearization table");
assert(linearization != nullptr);
auto linTable = linearization->getU16Array(1024);
RawImageCurveGuard curveHandler(&mRaw, linTable, uncorrectedRawValues);
// FIXME: dcraw does all sorts of crazy things besides this to fetch
// WB from what appear to be presets and calculate it in weird ways
// The only file I have only uses this method, if anybody careas look
// in dcraw.c parse_kodak_ifd() for all that weirdness
TiffEntry* blob = kodakifd.getEntryRecursive(static_cast<TiffTag>(0x03fd));
if (blob && blob->count == 72) {
mRaw->metadata.wbCoeffs[0] = 2048.0F / blob->getU16(20);
mRaw->metadata.wbCoeffs[1] = 2048.0F / blob->getU16(21);
mRaw->metadata.wbCoeffs[2] = 2048.0F / blob->getU16(22);
}
try {
decodeKodak65000(&input, width, height);
} catch (IOException &) {
mRaw->setError("IO error occurred while reading image. Returning partial result.");
}
} else
ThrowRDE("Unsupported compression %d", compression);
return mRaw;
}
void DcrDecoder::decodeKodak65000(ByteStream* input, uint32 w, uint32 h) {
ushort16 buf[256];
uint32 pred[2];
uchar8* data = mRaw->getData();
uint32 pitch = mRaw->pitch;
uint32 random = 0;
for (uint32 y = 0; y < h; y++) {
auto* dest = reinterpret_cast<ushort16*>(&data[y * pitch]);
for (uint32 x = 0 ; x < w; x += 256) {
pred[0] = pred[1] = 0;
uint32 len = min(256U, w - x);
decodeKodak65000Segment(input, buf, len);
for (uint32 i = 0; i < len; i++) {
pred[i & 1] += buf[i];
ushort16 value = pred[i & 1];
if (value > 1023)
ThrowRDE("Value out of bounds %d", value);
if(uncorrectedRawValues)
dest[x+i] = value;
else
mRaw->setWithLookUp(value, reinterpret_cast<uchar8*>(&dest[x + i]),
&random);
}
}
}
}
void DcrDecoder::decodeKodak65000Segment(ByteStream* input, ushort16* out,
uint32 bsize) {
uchar8 blen[768];
uint64 bitbuf=0;
uint32 bits=0;
bsize = (bsize + 3) & -4;
for (uint32 i=0; i < bsize; i+=2) {
blen[i] = input->peekByte() & 15;
blen[i + 1] = input->getByte() >> 4;
}
if ((bsize & 7) == 4) {
bitbuf = (static_cast<uint64>(input->getByte())) << 8UL;
bitbuf += (static_cast<int>(input->getByte()));
bits = 16;
}
for (uint32 i=0; i < bsize; i++) {
uint32 len = blen[i];
if (bits < len) {
for (uint32 j=0; j < 32; j+=8) {
bitbuf += static_cast<long long>(static_cast<int>(input->getByte()))
<< (bits + (j ^ 8));
}
bits += 32;
}
uint32 diff = static_cast<uint32>(bitbuf) & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
diff = len != 0 ? HuffmanTable::signExtended(diff, len) : diff;
out[i] = diff;
}
}
void DcrDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
setMetaData(meta, "", 0);
}
} // namespace rawspeed
<commit_msg>DcrDecoder::decodeRawInternal(): don't catch IOException.<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/DcrDecoder.h"
#include "common/Common.h" // for uint32, uchar8, ushort16
#include "common/NORangesSet.h" // for NORangesSet
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/ByteStream.h" // for ByteStream
#include "io/IOException.h" // for IOException
#include "tiff/TiffEntry.h" // for TiffEntry, TiffDataType::T...
#include "tiff/TiffIFD.h" // for TiffRootIFD, TiffIFD
#include "tiff/TiffTag.h" // for TiffTag, TiffTag::COMPRESSION
#include <cassert> // for assert
#include <memory> // for unique_ptr
#include <string> // for operator==, string
using std::min;
namespace rawspeed {
class CameraMetaData;
bool DcrDecoder::isAppropriateDecoder(const TiffRootIFD* rootIFD,
const Buffer* file) {
const auto id = rootIFD->getID();
const std::string& make = id.make;
// FIXME: magic
return make == "Kodak";
}
void DcrDecoder::checkImageDimensions() {
if (width > 4516 || height > 3012)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height);
}
RawImage DcrDecoder::decodeRawInternal() {
SimpleTiffDecoder::prepareForRawDecoding();
ByteStream input(mFile, off);
int compression = raw->getEntry(COMPRESSION)->getU32();
if (65000 == compression) {
TiffEntry *ifdoffset = mRootIFD->getEntryRecursive(KODAK_IFD);
if (!ifdoffset)
ThrowRDE("Couldn't find the Kodak IFD offset");
NORangesSet<Buffer> ifds;
assert(ifdoffset != nullptr);
TiffRootIFD kodakifd(nullptr, &ifds, ifdoffset->getRootIfdData(),
ifdoffset->getU32());
TiffEntry *linearization = kodakifd.getEntryRecursive(KODAK_LINEARIZATION);
if (!linearization || linearization->count != 1024 ||
linearization->type != TIFF_SHORT)
ThrowRDE("Couldn't find the linearization table");
assert(linearization != nullptr);
auto linTable = linearization->getU16Array(1024);
RawImageCurveGuard curveHandler(&mRaw, linTable, uncorrectedRawValues);
// FIXME: dcraw does all sorts of crazy things besides this to fetch
// WB from what appear to be presets and calculate it in weird ways
// The only file I have only uses this method, if anybody careas look
// in dcraw.c parse_kodak_ifd() for all that weirdness
TiffEntry* blob = kodakifd.getEntryRecursive(static_cast<TiffTag>(0x03fd));
if (blob && blob->count == 72) {
mRaw->metadata.wbCoeffs[0] = 2048.0F / blob->getU16(20);
mRaw->metadata.wbCoeffs[1] = 2048.0F / blob->getU16(21);
mRaw->metadata.wbCoeffs[2] = 2048.0F / blob->getU16(22);
}
decodeKodak65000(&input, width, height);
} else
ThrowRDE("Unsupported compression %d", compression);
return mRaw;
}
void DcrDecoder::decodeKodak65000(ByteStream* input, uint32 w, uint32 h) {
ushort16 buf[256];
uint32 pred[2];
uchar8* data = mRaw->getData();
uint32 pitch = mRaw->pitch;
uint32 random = 0;
for (uint32 y = 0; y < h; y++) {
auto* dest = reinterpret_cast<ushort16*>(&data[y * pitch]);
for (uint32 x = 0 ; x < w; x += 256) {
pred[0] = pred[1] = 0;
uint32 len = min(256U, w - x);
decodeKodak65000Segment(input, buf, len);
for (uint32 i = 0; i < len; i++) {
pred[i & 1] += buf[i];
ushort16 value = pred[i & 1];
if (value > 1023)
ThrowRDE("Value out of bounds %d", value);
if(uncorrectedRawValues)
dest[x+i] = value;
else
mRaw->setWithLookUp(value, reinterpret_cast<uchar8*>(&dest[x + i]),
&random);
}
}
}
}
void DcrDecoder::decodeKodak65000Segment(ByteStream* input, ushort16* out,
uint32 bsize) {
uchar8 blen[768];
uint64 bitbuf=0;
uint32 bits=0;
bsize = (bsize + 3) & -4;
for (uint32 i=0; i < bsize; i+=2) {
blen[i] = input->peekByte() & 15;
blen[i + 1] = input->getByte() >> 4;
}
if ((bsize & 7) == 4) {
bitbuf = (static_cast<uint64>(input->getByte())) << 8UL;
bitbuf += (static_cast<int>(input->getByte()));
bits = 16;
}
for (uint32 i=0; i < bsize; i++) {
uint32 len = blen[i];
if (bits < len) {
for (uint32 j=0; j < 32; j+=8) {
bitbuf += static_cast<long long>(static_cast<int>(input->getByte()))
<< (bits + (j ^ 8));
}
bits += 32;
}
uint32 diff = static_cast<uint32>(bitbuf) & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
diff = len != 0 ? HuffmanTable::signExtended(diff, len) : diff;
out[i] = diff;
}
}
void DcrDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
setMetaData(meta, "", 0);
}
} // namespace rawspeed
<|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) 1999-2009 Soeren Sonnenburg
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "classifier/svm/LibSVM.h"
#include "lib/io.h"
using namespace shogun;
#ifdef HAVE_BOOST_SERIALIZATION
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT(CLibSVM);
#endif //HAVE_BOOST_SERIALIZATION
CLibSVM::CLibSVM(LIBSVM_SOLVER_TYPE st)
: CSVM(), model(NULL), solver_type(st)
{
}
CLibSVM::CLibSVM(float64_t C, CKernel* k, CLabels* lab)
: CSVM(C, k, lab), model(NULL), solver_type(LIBSVM_C_SVC)
{
problem = svm_problem();
}
CLibSVM::~CLibSVM()
{
}
bool CLibSVM::train(CFeatures* data)
{
struct svm_node* x_space;
ASSERT(labels && labels->get_num_labels());
ASSERT(labels->is_two_class_labeling());
if (data)
{
if (labels->get_num_labels() != data->get_num_vectors())
SG_ERROR("Number of training vectors does not match number of labels\n");
kernel->init(data, data);
}
problem.l=labels->get_num_labels();
SG_INFO( "%d trainlabels\n", problem.l);
// check length of linear term
if (!linear_term.empty() &&
labels->get_num_labels() != (int32_t)linear_term.size())
{
SG_ERROR("Number of training vectors does not match length of linear term\n");
}
// set linear term
if (!linear_term.empty())
{
// set with linear term from base class
problem.pv = get_linear_term_array();
}
else
{
// fill with minus ones
problem.pv = new float64_t[problem.l];
for (int i=0; i!=problem.l; i++) {
problem.pv[i] = -1.0;
}
}
problem.y=new float64_t[problem.l];
problem.x=new struct svm_node*[problem.l];
problem.C=new float64_t[problem.l];
x_space=new struct svm_node[2*problem.l];
for (int32_t i=0; i<problem.l; i++)
{
problem.y[i]=labels->get_label(i);
problem.x[i]=&x_space[2*i];
x_space[2*i].index=i;
x_space[2*i+1].index=-1;
}
int32_t weights_label[2]={-1,+1};
float64_t weights[2]={1.0,get_C2()/get_C1()};
ASSERT(kernel && kernel->has_features());
ASSERT(kernel->get_num_vec_lhs()==problem.l);
param.svm_type=solver_type; // C SVM or NU_SVM
param.kernel_type = LINEAR;
param.degree = 3;
param.gamma = 0; // 1/k
param.coef0 = 0;
param.nu = get_nu();
param.kernel=kernel;
param.cache_size = kernel->get_cache_size();
param.max_train_time = max_train_time;
param.C = get_C1();
param.eps = epsilon;
param.p = 0.1;
param.shrinking = 1;
param.nr_weight = 2;
param.weight_label = weights_label;
param.weight = weights;
param.use_bias = get_bias_enabled();
const char* error_msg = svm_check_parameter(&problem, ¶m);
if(error_msg)
SG_ERROR("Error: %s\n",error_msg);
model = svm_train(&problem, ¶m);
if (model)
{
ASSERT(model->nr_class==2);
ASSERT((model->l==0) || (model->l>0 && model->SV && model->sv_coef && model->sv_coef[0]));
int32_t num_sv=model->l;
create_new_model(num_sv);
CSVM::set_objective(model->objective);
float64_t sgn=model->label[0];
set_bias(-sgn*model->rho[0]);
for (int32_t i=0; i<num_sv; i++)
{
set_support_vector(i, (model->SV[i])->index);
set_alpha(i, sgn*model->sv_coef[0][i]);
}
delete[] problem.x;
delete[] problem.y;
delete[] problem.pv;
delete[] problem.C;
delete[] x_space;
svm_destroy_model(model);
model=NULL;
return true;
}
else
return false;
}
<commit_msg>minor cleanup<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) 1999-2009 Soeren Sonnenburg
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "classifier/svm/LibSVM.h"
#include "lib/io.h"
using namespace shogun;
#ifdef HAVE_BOOST_SERIALIZATION
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT(CLibSVM);
#endif //HAVE_BOOST_SERIALIZATION
CLibSVM::CLibSVM(LIBSVM_SOLVER_TYPE st)
: CSVM(), model(NULL), solver_type(st)
{
}
CLibSVM::CLibSVM(float64_t C, CKernel* k, CLabels* lab)
: CSVM(C, k, lab), model(NULL), solver_type(LIBSVM_C_SVC)
{
problem = svm_problem();
}
CLibSVM::~CLibSVM()
{
}
bool CLibSVM::train(CFeatures* data)
{
struct svm_node* x_space;
ASSERT(labels && labels->get_num_labels());
ASSERT(labels->is_two_class_labeling());
if (data)
{
if (labels->get_num_labels() != data->get_num_vectors())
SG_ERROR("Number of training vectors does not match number of labels\n");
kernel->init(data, data);
}
problem.l=labels->get_num_labels();
SG_INFO( "%d trainlabels\n", problem.l);
// check length of linear term
if (!linear_term.empty() &&
labels->get_num_labels() != (int32_t)linear_term.size())
{
SG_ERROR("Number of training vectors does not match length of linear term\n");
}
// set linear term
if (!linear_term.empty())
{
// set with linear term from base class
problem.pv = get_linear_term_array();
}
else
{
// fill with minus ones
problem.pv = new float64_t[problem.l];
for (int i=0; i!=problem.l; i++)
problem.pv[i] = -1.0;
}
problem.y=new float64_t[problem.l];
problem.x=new struct svm_node*[problem.l];
problem.C=new float64_t[problem.l];
x_space=new struct svm_node[2*problem.l];
for (int32_t i=0; i<problem.l; i++)
{
problem.y[i]=labels->get_label(i);
problem.x[i]=&x_space[2*i];
x_space[2*i].index=i;
x_space[2*i+1].index=-1;
}
int32_t weights_label[2]={-1,+1};
float64_t weights[2]={1.0,get_C2()/get_C1()};
ASSERT(kernel && kernel->has_features());
ASSERT(kernel->get_num_vec_lhs()==problem.l);
param.svm_type=solver_type; // C SVM or NU_SVM
param.kernel_type = LINEAR;
param.degree = 3;
param.gamma = 0; // 1/k
param.coef0 = 0;
param.nu = get_nu();
param.kernel=kernel;
param.cache_size = kernel->get_cache_size();
param.max_train_time = max_train_time;
param.C = get_C1();
param.eps = epsilon;
param.p = 0.1;
param.shrinking = 1;
param.nr_weight = 2;
param.weight_label = weights_label;
param.weight = weights;
param.use_bias = get_bias_enabled();
const char* error_msg = svm_check_parameter(&problem, ¶m);
if(error_msg)
SG_ERROR("Error: %s\n",error_msg);
model = svm_train(&problem, ¶m);
if (model)
{
ASSERT(model->nr_class==2);
ASSERT((model->l==0) || (model->l>0 && model->SV && model->sv_coef && model->sv_coef[0]));
int32_t num_sv=model->l;
create_new_model(num_sv);
CSVM::set_objective(model->objective);
float64_t sgn=model->label[0];
set_bias(-sgn*model->rho[0]);
for (int32_t i=0; i<num_sv; i++)
{
set_support_vector(i, (model->SV[i])->index);
set_alpha(i, sgn*model->sv_coef[0][i]);
}
delete[] problem.x;
delete[] problem.y;
delete[] problem.pv;
delete[] problem.C;
delete[] x_space;
svm_destroy_model(model);
model=NULL;
return true;
}
else
return false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bloom.h"
#include "primitives/transaction.h"
#include "hash.h"
#include "script/script.h"
#include "script/standard.h"
#include "streams.h"
#include <math.h>
#include <stdlib.h>
#include <boost/foreach.hpp>
#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
#define LN2 0.6931471805599453094172321214581765680755001343602552
using namespace std;
CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :
/**
* The ideal size for a bloom filter with a given number of elements and false positive rate is:
* - nElements * log(fp rate) / ln(2)^2
* We ignore filter parameters which will create a bloom filter larger than the protocol limits
*/
vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
/**
* The ideal number of hash functions is filter size * ln(2) / number of elements
* Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
* See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
*/
isFull(false),
isEmpty(false),
nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
nTweak(nTweakIn),
nFlags(nFlagsIn)
{
}
// Private constructor used by CRollingBloomFilter
CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn) :
vData((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)) / 8),
isFull(false),
isEmpty(true),
nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
nTweak(nTweakIn),
nFlags(BLOOM_UPDATE_NONE)
{
}
inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
{
// 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
}
void CBloomFilter::insert(const vector<unsigned char>& vKey)
{
if (isFull)
return;
for (unsigned int i = 0; i < nHashFuncs; i++)
{
unsigned int nIndex = Hash(i, vKey);
// Sets bit nIndex of vData
vData[nIndex >> 3] |= (1 << (7 & nIndex));
}
isEmpty = false;
}
void CBloomFilter::insert(const COutPoint& outpoint)
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint;
vector<unsigned char> data(stream.begin(), stream.end());
insert(data);
}
void CBloomFilter::insert(const uint256& hash)
{
vector<unsigned char> data(hash.begin(), hash.end());
insert(data);
}
bool CBloomFilter::contains(const vector<unsigned char>& vKey) const
{
if (isFull)
return true;
if (isEmpty)
return false;
for (unsigned int i = 0; i < nHashFuncs; i++)
{
unsigned int nIndex = Hash(i, vKey);
// Checks bit nIndex of vData
if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
return false;
}
return true;
}
bool CBloomFilter::contains(const COutPoint& outpoint) const
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint;
vector<unsigned char> data(stream.begin(), stream.end());
return contains(data);
}
bool CBloomFilter::contains(const uint256& hash) const
{
vector<unsigned char> data(hash.begin(), hash.end());
return contains(data);
}
void CBloomFilter::clear()
{
vData.assign(vData.size(),0);
isFull = false;
isEmpty = true;
}
bool CBloomFilter::IsWithinSizeConstraints() const
{
return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
}
bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
{
bool fFound = false;
// Match if the filter contains the hash of tx
// for finding tx when they appear in a block
if (isFull)
return true;
if (isEmpty)
return false;
const uint256& hash = tx.GetHash();
if (contains(hash))
fFound = true;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
// Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
// If this matches, also add the specific output that was matched.
// This means clients don't have to update the filter themselves when a new relevant tx
// is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
CScript::const_iterator pc = txout.scriptPubKey.begin();
vector<unsigned char> data;
while (pc < txout.scriptPubKey.end())
{
opcodetype opcode;
if (!txout.scriptPubKey.GetOp(pc, opcode, data))
break;
if (data.size() != 0 && contains(data))
{
fFound = true;
if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
insert(COutPoint(hash, i));
else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
{
txnouttype type;
vector<vector<unsigned char> > vSolutions;
if (Solver(txout.scriptPubKey, type, vSolutions) &&
(type == TX_PUBKEY || type == TX_MULTISIG))
insert(COutPoint(hash, i));
}
break;
}
}
}
if (fFound)
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Match if the filter contains an outpoint tx spends
if (contains(txin.prevout))
return true;
// Match if the filter contains any arbitrary script data element in any scriptSig in tx
CScript::const_iterator pc = txin.scriptSig.begin();
vector<unsigned char> data;
while (pc < txin.scriptSig.end())
{
opcodetype opcode;
if (!txin.scriptSig.GetOp(pc, opcode, data))
break;
if (data.size() != 0 && contains(data))
return true;
}
}
return false;
}
void CBloomFilter::UpdateEmptyFull()
{
bool full = true;
bool empty = true;
for (unsigned int i = 0; i < vData.size(); i++)
{
full &= vData[i] == 0xff;
empty &= vData[i] == 0;
}
isFull = full;
isEmpty = empty;
}
CRollingBloomFilter::CRollingBloomFilter(unsigned int nElements, double fpRate, unsigned int nTweak) :
b1(nElements * 2, fpRate, nTweak), b2(nElements * 2, fpRate, nTweak)
{
// Implemented using two bloom filters of 2 * nElements each.
// We fill them up, and clear them, staggered, every nElements
// inserted, so at least one always contains the last nElements
// inserted.
nBloomSize = nElements * 2;
nInsertions = 0;
}
void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
{
if (nInsertions == 0) {
b1.clear();
} else if (nInsertions == nBloomSize / 2) {
b2.clear();
}
b1.insert(vKey);
b2.insert(vKey);
if (++nInsertions == nBloomSize) {
nInsertions = 0;
}
}
void CRollingBloomFilter::insert(const uint256& hash)
{
if (nInsertions == 0) {
b1.clear();
} else if (nInsertions == nBloomSize / 2) {
b2.clear();
}
b1.insert(hash);
b2.insert(hash);
if (++nInsertions == nBloomSize) {
nInsertions = 0;
}
}
bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{
if (nInsertions < nBloomSize / 2) {
return b2.contains(vKey);
}
return b1.contains(vKey);
}
bool CRollingBloomFilter::contains(const uint256& hash) const
{
if (nInsertions < nBloomSize / 2) {
return b2.contains(hash);
}
return b1.contains(hash);
}
void CRollingBloomFilter::clear()
{
b1.clear();
b2.clear();
nInsertions = 0;
}
<commit_msg>Reuse vector hashing code for uint256<commit_after>// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bloom.h"
#include "primitives/transaction.h"
#include "hash.h"
#include "script/script.h"
#include "script/standard.h"
#include "streams.h"
#include <math.h>
#include <stdlib.h>
#include <boost/foreach.hpp>
#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
#define LN2 0.6931471805599453094172321214581765680755001343602552
using namespace std;
CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :
/**
* The ideal size for a bloom filter with a given number of elements and false positive rate is:
* - nElements * log(fp rate) / ln(2)^2
* We ignore filter parameters which will create a bloom filter larger than the protocol limits
*/
vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
/**
* The ideal number of hash functions is filter size * ln(2) / number of elements
* Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
* See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
*/
isFull(false),
isEmpty(false),
nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
nTweak(nTweakIn),
nFlags(nFlagsIn)
{
}
// Private constructor used by CRollingBloomFilter
CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn) :
vData((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)) / 8),
isFull(false),
isEmpty(true),
nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
nTweak(nTweakIn),
nFlags(BLOOM_UPDATE_NONE)
{
}
inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
{
// 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
}
void CBloomFilter::insert(const vector<unsigned char>& vKey)
{
if (isFull)
return;
for (unsigned int i = 0; i < nHashFuncs; i++)
{
unsigned int nIndex = Hash(i, vKey);
// Sets bit nIndex of vData
vData[nIndex >> 3] |= (1 << (7 & nIndex));
}
isEmpty = false;
}
void CBloomFilter::insert(const COutPoint& outpoint)
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint;
vector<unsigned char> data(stream.begin(), stream.end());
insert(data);
}
void CBloomFilter::insert(const uint256& hash)
{
vector<unsigned char> data(hash.begin(), hash.end());
insert(data);
}
bool CBloomFilter::contains(const vector<unsigned char>& vKey) const
{
if (isFull)
return true;
if (isEmpty)
return false;
for (unsigned int i = 0; i < nHashFuncs; i++)
{
unsigned int nIndex = Hash(i, vKey);
// Checks bit nIndex of vData
if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
return false;
}
return true;
}
bool CBloomFilter::contains(const COutPoint& outpoint) const
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint;
vector<unsigned char> data(stream.begin(), stream.end());
return contains(data);
}
bool CBloomFilter::contains(const uint256& hash) const
{
vector<unsigned char> data(hash.begin(), hash.end());
return contains(data);
}
void CBloomFilter::clear()
{
vData.assign(vData.size(),0);
isFull = false;
isEmpty = true;
}
bool CBloomFilter::IsWithinSizeConstraints() const
{
return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
}
bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
{
bool fFound = false;
// Match if the filter contains the hash of tx
// for finding tx when they appear in a block
if (isFull)
return true;
if (isEmpty)
return false;
const uint256& hash = tx.GetHash();
if (contains(hash))
fFound = true;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
// Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
// If this matches, also add the specific output that was matched.
// This means clients don't have to update the filter themselves when a new relevant tx
// is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
CScript::const_iterator pc = txout.scriptPubKey.begin();
vector<unsigned char> data;
while (pc < txout.scriptPubKey.end())
{
opcodetype opcode;
if (!txout.scriptPubKey.GetOp(pc, opcode, data))
break;
if (data.size() != 0 && contains(data))
{
fFound = true;
if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
insert(COutPoint(hash, i));
else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
{
txnouttype type;
vector<vector<unsigned char> > vSolutions;
if (Solver(txout.scriptPubKey, type, vSolutions) &&
(type == TX_PUBKEY || type == TX_MULTISIG))
insert(COutPoint(hash, i));
}
break;
}
}
}
if (fFound)
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Match if the filter contains an outpoint tx spends
if (contains(txin.prevout))
return true;
// Match if the filter contains any arbitrary script data element in any scriptSig in tx
CScript::const_iterator pc = txin.scriptSig.begin();
vector<unsigned char> data;
while (pc < txin.scriptSig.end())
{
opcodetype opcode;
if (!txin.scriptSig.GetOp(pc, opcode, data))
break;
if (data.size() != 0 && contains(data))
return true;
}
}
return false;
}
void CBloomFilter::UpdateEmptyFull()
{
bool full = true;
bool empty = true;
for (unsigned int i = 0; i < vData.size(); i++)
{
full &= vData[i] == 0xff;
empty &= vData[i] == 0;
}
isFull = full;
isEmpty = empty;
}
CRollingBloomFilter::CRollingBloomFilter(unsigned int nElements, double fpRate, unsigned int nTweak) :
b1(nElements * 2, fpRate, nTweak), b2(nElements * 2, fpRate, nTweak)
{
// Implemented using two bloom filters of 2 * nElements each.
// We fill them up, and clear them, staggered, every nElements
// inserted, so at least one always contains the last nElements
// inserted.
nBloomSize = nElements * 2;
nInsertions = 0;
}
void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
{
if (nInsertions == 0) {
b1.clear();
} else if (nInsertions == nBloomSize / 2) {
b2.clear();
}
b1.insert(vKey);
b2.insert(vKey);
if (++nInsertions == nBloomSize) {
nInsertions = 0;
}
}
void CRollingBloomFilter::insert(const uint256& hash)
{
vector<unsigned char> data(hash.begin(), hash.end());
insert(data);
}
bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{
if (nInsertions < nBloomSize / 2) {
return b2.contains(vKey);
}
return b1.contains(vKey);
}
bool CRollingBloomFilter::contains(const uint256& hash) const
{
vector<unsigned char> data(hash.begin(), hash.end());
return contains(data);
}
void CRollingBloomFilter::clear()
{
b1.clear();
b2.clear();
nInsertions = 0;
}
<|endoftext|> |
<commit_before>#include "buffer.hh"
#include "buffer_manager.hh"
#include "window.hh"
#include "assert.hh"
#include "utils.hh"
#include "context.hh"
#include "utf8.hh"
#include <algorithm>
namespace Kakoune
{
Buffer::Buffer(String name, Flags flags, std::vector<String> lines)
: m_name(std::move(name)), m_flags(flags | Flags::NoUndo),
m_history(), m_history_cursor(m_history.begin()),
m_last_save_undo_index(0),
m_timestamp(0),
m_hooks(GlobalHooks::instance()),
m_options(GlobalOptions::instance())
{
BufferManager::instance().register_buffer(*this);
if (lines.empty())
lines.emplace_back("\n");
ByteCount pos = 0;
m_lines.reserve(lines.size());
for (auto& line : lines)
{
assert(not line.empty() and line.back() == '\n');
m_lines.emplace_back(Line{ pos, std::move(line) });
pos += m_lines.back().length();
}
Editor editor_for_hooks(*this);
Context context(editor_for_hooks);
if (flags & Flags::File and flags & Flags::New)
m_hooks.run_hook("BufNew", m_name, context);
else
m_hooks.run_hook("BufOpen", m_name, context);
m_hooks.run_hook("BufCreate", m_name, context);
// now we may begin to record undo data
m_flags = flags;
}
Buffer::~Buffer()
{
{
Editor hook_editor{*this};
Context hook_context{hook_editor};
m_hooks.run_hook("BufClose", m_name, hook_context);
}
BufferManager::instance().unregister_buffer(*this);
assert(m_change_listeners.empty());
}
BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column,
bool avoid_eol) const
{
return BufferIterator(*this, clamp(line_and_column, avoid_eol));
}
ByteCount Buffer::line_length(LineCount line) const
{
assert(line < line_count());
ByteCount end = (line < line_count() - 1) ?
m_lines[line + 1].start : character_count();
return end - m_lines[line].start;
}
BufferCoord Buffer::clamp(const BufferCoord& line_and_column,
bool avoid_eol) const
{
if (m_lines.empty())
return BufferCoord();
BufferCoord result(line_and_column.line, line_and_column.column);
result.line = Kakoune::clamp(result.line, 0_line, line_count() - 1);
ByteCount max_col = std::max(0_byte, line_length(result.line) - (avoid_eol ? 2 : 1));
result.column = Kakoune::clamp(result.column, 0_byte, max_col);
return result;
}
BufferIterator Buffer::iterator_at_line_begin(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return BufferIterator(*this, { line, 0 });
}
BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const
{
return iterator_at_line_begin(iterator.line());
}
BufferIterator Buffer::iterator_at_line_end(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const
{
return iterator_at_line_end(iterator.line());
}
BufferIterator Buffer::begin() const
{
return BufferIterator(*this, { 0_line, 0 });
}
BufferIterator Buffer::end() const
{
if (m_lines.empty())
return BufferIterator(*this, { 0_line, 0 });
return BufferIterator(*this, { line_count()-1, m_lines.back().length() });
}
ByteCount Buffer::character_count() const
{
if (m_lines.empty())
return 0;
return m_lines.back().start + m_lines.back().length();
}
LineCount Buffer::line_count() const
{
return LineCount(m_lines.size());
}
String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const
{
String res;
for (LineCount line = begin.line(); line <= end.line(); ++line)
{
ByteCount start = 0;
if (line == begin.line())
start = begin.column();
ByteCount count = -1;
if (line == end.line())
count = end.column() - start;
res += m_lines[line].content.substr(start, count);
}
return res;
}
void Buffer::commit_undo_group()
{
if (m_flags & Flags::NoUndo)
return;
if (m_current_undo_group.empty())
return;
m_history.erase(m_history_cursor, m_history.end());
m_history.push_back(std::move(m_current_undo_group));
m_current_undo_group.clear();
m_history_cursor = m_history.end();
if (m_history.size() < m_last_save_undo_index)
m_last_save_undo_index = -1;
}
// A Modification holds a single atomic modification to Buffer
struct Buffer::Modification
{
enum Type { Insert, Erase };
Type type;
BufferIterator position;
String content;
Modification(Type type, BufferIterator position, String content)
: type(type), position(position), content(std::move(content)) {}
Modification inverse() const
{
Type inverse_type = Insert;
switch (type)
{
case Insert: inverse_type = Erase; break;
case Erase: inverse_type = Insert; break;
default: assert(false);
}
return {inverse_type, position, content};
}
};
bool Buffer::undo()
{
commit_undo_group();
if (m_history_cursor == m_history.begin())
return false;
--m_history_cursor;
for (const Modification& modification : reversed(*m_history_cursor))
apply_modification(modification.inverse());
return true;
}
bool Buffer::redo()
{
if (m_history_cursor == m_history.end())
return false;
assert(m_current_undo_group.empty());
for (const Modification& modification : *m_history_cursor)
apply_modification(modification);
++m_history_cursor;
return true;
}
void Buffer::check_invariant() const
{
#ifdef KAK_DEBUG
ByteCount start = 0;
assert(not m_lines.empty());
for (auto& line : m_lines)
{
assert(line.start == start);
assert(line.length() > 0);
assert(line.content.back() == '\n');
start += line.length();
}
#endif
}
void Buffer::do_insert(const BufferIterator& pos, const String& content)
{
assert(pos.is_valid() and (pos.is_end() or utf8::is_character_start(pos)));
assert(not contains(content, '\0'));
++m_timestamp;
ByteCount offset = pos.offset();
// all following lines advanced by length
for (LineCount i = pos.line()+1; i < line_count(); ++i)
m_lines[i].start += content.length();
BufferIterator begin_it;
BufferIterator end_it;
// if we inserted at the end of the buffer, we have created a new
// line without inserting a '\n'
if (pos.is_end())
{
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) });
start = i + 1;
}
}
if (start != content.length())
m_lines.push_back({ offset + start, content.substr(start) });
begin_it = pos.column() == 0 ? pos : BufferIterator{*this, { pos.line() + 1, 0 }};
end_it = end();
}
else
{
String prefix = m_lines[pos.line()].content.substr(0, pos.column());
String suffix = m_lines[pos.line()].content.substr(pos.column());
auto line_it = m_lines.begin() + (int)pos.line();
line_it = m_lines.erase(line_it);
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
String line_content = content.substr(start, i + 1 - start);
if (start == 0)
{
line_content = prefix + line_content;
line_it = m_lines.insert(line_it, { offset + start - prefix.length(),
std::move(line_content) });
}
else
line_it = m_lines.insert(line_it, { offset + start,
std::move(line_content) });
++line_it;
start = i + 1;
}
}
if (start == 0)
line_it = m_lines.insert(line_it, { offset + start - prefix.length(), prefix + content + suffix });
else if (start != content.length() or not suffix.empty())
line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix });
else
--line_it;
begin_it = pos;
end_it = BufferIterator(*this, { LineCount(line_it - m_lines.begin()),
line_it->length() - suffix.length() });
}
check_invariant();
for (auto listener : m_change_listeners)
listener->on_insert(begin_it, end_it);
}
void Buffer::do_erase(const BufferIterator& begin, const BufferIterator& end)
{
assert(begin.is_valid());
assert(end.is_valid());
assert(utf8::is_character_start(begin) and
(end.is_end() or utf8::is_character_start(end)));
++m_timestamp;
const ByteCount length = end - begin;
String prefix = m_lines[begin.line()].content.substr(0, begin.column());
String suffix = m_lines[end.line()].content.substr(end.column());
Line new_line = { m_lines[begin.line()].start, prefix + suffix };
if (new_line.length() != 0)
{
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line());
m_lines[begin.line()] = std::move(new_line);
}
else
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line() + 1);
for (LineCount i = begin.line()+1; i < line_count(); ++i)
m_lines[i].start -= length;
check_invariant();
for (auto listener : m_change_listeners)
listener->on_erase(begin, end);
}
void Buffer::apply_modification(const Modification& modification)
{
const String& content = modification.content;
BufferIterator pos = modification.position;
// this may happen when a modification applied at the
// end of the buffer has been inverted for an undo.
if (not pos.is_end() and pos.column() == m_lines[pos.line()].length())
pos = { pos.buffer(), { pos.line() + 1, 0 }};
assert(pos.is_valid());
switch (modification.type)
{
case Modification::Insert:
{
do_insert(pos, content);
break;
}
case Modification::Erase:
{
ByteCount count = content.length();
BufferIterator end = pos + count;
assert(string(pos, end) == content);
do_erase(pos, end);
break;
}
default:
assert(false);
}
}
void Buffer::insert(BufferIterator pos, String content)
{
if (content.empty())
return;
if (pos.is_end() and content.back() != '\n')
content += '\n';
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Insert, pos, content);
do_insert(pos, content);
}
void Buffer::erase(BufferIterator begin, BufferIterator end)
{
if (end.is_end() and (begin.column() != 0 or begin.is_begin()))
--end;
if (begin == end)
return;
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Erase, begin,
string(begin, end));
do_erase(begin, end);
}
bool Buffer::is_modified() const
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
return m_last_save_undo_index != history_cursor_index
or not m_current_undo_group.empty();
}
void Buffer::notify_saved()
{
if (not m_current_undo_group.empty())
commit_undo_group();
m_flags &= ~Flags::New;
size_t history_cursor_index = m_history_cursor - m_history.begin();
if (m_last_save_undo_index != history_cursor_index)
{
++m_timestamp;
m_last_save_undo_index = history_cursor_index;
}
}
}
<commit_msg>Buffer: optimize do_insert to minimize changes in m_lines vector<commit_after>#include "buffer.hh"
#include "buffer_manager.hh"
#include "window.hh"
#include "assert.hh"
#include "utils.hh"
#include "context.hh"
#include "utf8.hh"
#include <algorithm>
namespace Kakoune
{
Buffer::Buffer(String name, Flags flags, std::vector<String> lines)
: m_name(std::move(name)), m_flags(flags | Flags::NoUndo),
m_history(), m_history_cursor(m_history.begin()),
m_last_save_undo_index(0),
m_timestamp(0),
m_hooks(GlobalHooks::instance()),
m_options(GlobalOptions::instance())
{
BufferManager::instance().register_buffer(*this);
if (lines.empty())
lines.emplace_back("\n");
ByteCount pos = 0;
m_lines.reserve(lines.size());
for (auto& line : lines)
{
assert(not line.empty() and line.back() == '\n');
m_lines.emplace_back(Line{ pos, std::move(line) });
pos += m_lines.back().length();
}
Editor editor_for_hooks(*this);
Context context(editor_for_hooks);
if (flags & Flags::File and flags & Flags::New)
m_hooks.run_hook("BufNew", m_name, context);
else
m_hooks.run_hook("BufOpen", m_name, context);
m_hooks.run_hook("BufCreate", m_name, context);
// now we may begin to record undo data
m_flags = flags;
}
Buffer::~Buffer()
{
{
Editor hook_editor{*this};
Context hook_context{hook_editor};
m_hooks.run_hook("BufClose", m_name, hook_context);
}
BufferManager::instance().unregister_buffer(*this);
assert(m_change_listeners.empty());
}
BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column,
bool avoid_eol) const
{
return BufferIterator(*this, clamp(line_and_column, avoid_eol));
}
ByteCount Buffer::line_length(LineCount line) const
{
assert(line < line_count());
ByteCount end = (line < line_count() - 1) ?
m_lines[line + 1].start : character_count();
return end - m_lines[line].start;
}
BufferCoord Buffer::clamp(const BufferCoord& line_and_column,
bool avoid_eol) const
{
if (m_lines.empty())
return BufferCoord();
BufferCoord result(line_and_column.line, line_and_column.column);
result.line = Kakoune::clamp(result.line, 0_line, line_count() - 1);
ByteCount max_col = std::max(0_byte, line_length(result.line) - (avoid_eol ? 2 : 1));
result.column = Kakoune::clamp(result.column, 0_byte, max_col);
return result;
}
BufferIterator Buffer::iterator_at_line_begin(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return BufferIterator(*this, { line, 0 });
}
BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const
{
return iterator_at_line_begin(iterator.line());
}
BufferIterator Buffer::iterator_at_line_end(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const
{
return iterator_at_line_end(iterator.line());
}
BufferIterator Buffer::begin() const
{
return BufferIterator(*this, { 0_line, 0 });
}
BufferIterator Buffer::end() const
{
if (m_lines.empty())
return BufferIterator(*this, { 0_line, 0 });
return BufferIterator(*this, { line_count()-1, m_lines.back().length() });
}
ByteCount Buffer::character_count() const
{
if (m_lines.empty())
return 0;
return m_lines.back().start + m_lines.back().length();
}
LineCount Buffer::line_count() const
{
return LineCount(m_lines.size());
}
String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const
{
String res;
for (LineCount line = begin.line(); line <= end.line(); ++line)
{
ByteCount start = 0;
if (line == begin.line())
start = begin.column();
ByteCount count = -1;
if (line == end.line())
count = end.column() - start;
res += m_lines[line].content.substr(start, count);
}
return res;
}
void Buffer::commit_undo_group()
{
if (m_flags & Flags::NoUndo)
return;
if (m_current_undo_group.empty())
return;
m_history.erase(m_history_cursor, m_history.end());
m_history.push_back(std::move(m_current_undo_group));
m_current_undo_group.clear();
m_history_cursor = m_history.end();
if (m_history.size() < m_last_save_undo_index)
m_last_save_undo_index = -1;
}
// A Modification holds a single atomic modification to Buffer
struct Buffer::Modification
{
enum Type { Insert, Erase };
Type type;
BufferIterator position;
String content;
Modification(Type type, BufferIterator position, String content)
: type(type), position(position), content(std::move(content)) {}
Modification inverse() const
{
Type inverse_type = Insert;
switch (type)
{
case Insert: inverse_type = Erase; break;
case Erase: inverse_type = Insert; break;
default: assert(false);
}
return {inverse_type, position, content};
}
};
bool Buffer::undo()
{
commit_undo_group();
if (m_history_cursor == m_history.begin())
return false;
--m_history_cursor;
for (const Modification& modification : reversed(*m_history_cursor))
apply_modification(modification.inverse());
return true;
}
bool Buffer::redo()
{
if (m_history_cursor == m_history.end())
return false;
assert(m_current_undo_group.empty());
for (const Modification& modification : *m_history_cursor)
apply_modification(modification);
++m_history_cursor;
return true;
}
void Buffer::check_invariant() const
{
#ifdef KAK_DEBUG
ByteCount start = 0;
assert(not m_lines.empty());
for (auto& line : m_lines)
{
assert(line.start == start);
assert(line.length() > 0);
assert(line.content.back() == '\n');
start += line.length();
}
#endif
}
void Buffer::do_insert(const BufferIterator& pos, const String& content)
{
assert(pos.is_valid() and (pos.is_end() or utf8::is_character_start(pos)));
assert(not contains(content, '\0'));
if (content.empty())
return;
++m_timestamp;
ByteCount offset = pos.offset();
// all following lines advanced by length
for (LineCount i = pos.line()+1; i < line_count(); ++i)
m_lines[i].start += content.length();
BufferIterator begin_it;
BufferIterator end_it;
// if we inserted at the end of the buffer, we have created a new
// line without inserting a '\n'
if (pos.is_end())
{
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) });
start = i + 1;
}
}
if (start != content.length())
m_lines.push_back({ offset + start, content.substr(start) });
begin_it = pos.column() == 0 ? pos : BufferIterator{*this, { pos.line() + 1, 0 }};
end_it = end();
}
else
{
String prefix = m_lines[pos.line()].content.substr(0, pos.column());
String suffix = m_lines[pos.line()].content.substr(pos.column());
std::vector<Line> new_lines;
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
String line_content = content.substr(start, i + 1 - start);
if (start == 0)
{
line_content = prefix + line_content;
new_lines.push_back({ offset + start - prefix.length(),
std::move(line_content) });
}
else
new_lines.push_back({ offset + start, std::move(line_content) });
start = i + 1;
}
}
if (start == 0)
new_lines.push_back({ offset + start - prefix.length(), prefix + content + suffix });
else if (start != content.length() or not suffix.empty())
new_lines.push_back({ offset + start, content.substr(start) + suffix });
LineCount last_line = pos.line() + new_lines.size() - 1;
auto line_it = m_lines.begin() + (int)pos.line();
*line_it = std::move(*new_lines.begin());
m_lines.insert(line_it+1, std::make_move_iterator(new_lines.begin() + 1),
std::make_move_iterator(new_lines.end()));
begin_it = pos;
end_it = BufferIterator{*this, { last_line, m_lines[last_line].length() - suffix.length() }};
}
check_invariant();
for (auto listener : m_change_listeners)
listener->on_insert(begin_it, end_it);
}
void Buffer::do_erase(const BufferIterator& begin, const BufferIterator& end)
{
assert(begin.is_valid());
assert(end.is_valid());
assert(utf8::is_character_start(begin) and
(end.is_end() or utf8::is_character_start(end)));
++m_timestamp;
const ByteCount length = end - begin;
String prefix = m_lines[begin.line()].content.substr(0, begin.column());
String suffix = m_lines[end.line()].content.substr(end.column());
Line new_line = { m_lines[begin.line()].start, prefix + suffix };
if (new_line.length() != 0)
{
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line());
m_lines[begin.line()] = std::move(new_line);
}
else
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line() + 1);
for (LineCount i = begin.line()+1; i < line_count(); ++i)
m_lines[i].start -= length;
check_invariant();
for (auto listener : m_change_listeners)
listener->on_erase(begin, end);
}
void Buffer::apply_modification(const Modification& modification)
{
const String& content = modification.content;
BufferIterator pos = modification.position;
// this may happen when a modification applied at the
// end of the buffer has been inverted for an undo.
if (not pos.is_end() and pos.column() == m_lines[pos.line()].length())
pos = { pos.buffer(), { pos.line() + 1, 0 }};
assert(pos.is_valid());
switch (modification.type)
{
case Modification::Insert:
{
do_insert(pos, content);
break;
}
case Modification::Erase:
{
ByteCount count = content.length();
BufferIterator end = pos + count;
assert(string(pos, end) == content);
do_erase(pos, end);
break;
}
default:
assert(false);
}
}
void Buffer::insert(BufferIterator pos, String content)
{
if (content.empty())
return;
if (pos.is_end() and content.back() != '\n')
content += '\n';
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Insert, pos, content);
do_insert(pos, content);
}
void Buffer::erase(BufferIterator begin, BufferIterator end)
{
if (end.is_end() and (begin.column() != 0 or begin.is_begin()))
--end;
if (begin == end)
return;
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Erase, begin,
string(begin, end));
do_erase(begin, end);
}
bool Buffer::is_modified() const
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
return m_last_save_undo_index != history_cursor_index
or not m_current_undo_group.empty();
}
void Buffer::notify_saved()
{
if (not m_current_undo_group.empty())
commit_undo_group();
m_flags &= ~Flags::New;
size_t history_cursor_index = m_history_cursor - m_history.begin();
if (m_last_save_undo_index != history_cursor_index)
{
++m_timestamp;
m_last_save_undo_index = history_cursor_index;
}
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include "boost/filesystem.hpp"
#include "context.h"
#include "env.h"
#include "error.h"
#include "recorder.h"
#include "agent.h"
#include "timer.h"
#include "dynamic_module.h"
namespace fs = boost::filesystem;
using cyclus::DynamicModule;
using cyclus::AgentSpec;
using cyclus::Agent;
TEST(DynamicLoadingTests, ConstructTestFacility) {
cyclus::Recorder rec;
cyclus::Timer ti;
cyclus::Context* ctx = new cyclus::Context(&ti, &rec);
EXPECT_NO_THROW(DynamicModule::Make(ctx, AgentSpec("TestFacility:TestFacility:TestFacility")));
EXPECT_NO_THROW(DynamicModule::CloseAll());
}
TEST(DynamicLoadingTests, LoadLibError) {
cyclus::Recorder rec;
cyclus::Timer ti;
cyclus::Context* ctx = new cyclus::Context(&ti, &rec);
EXPECT_THROW(DynamicModule::Make(ctx, AgentSpec("foo:foo:not_a_fac")), cyclus::IOError);
}
TEST(DynamicLoadingTests, CloneTestFacility) {
cyclus::Recorder rec;
cyclus::Timer ti;
cyclus::Context* ctx = new cyclus::Context(&ti, &rec);
EXPECT_NO_THROW(Agent* fac = DynamicModule::Make(ctx, AgentSpec("TestFacility:TestFacility:TestFacility"));
Agent* clone = fac->Clone(););
DynamicModule::CloseAll();
}
<commit_msg>minor agent spec updates<commit_after>#include <gtest/gtest.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include "boost/filesystem.hpp"
#include "context.h"
#include "env.h"
#include "error.h"
#include "recorder.h"
#include "agent.h"
#include "timer.h"
#include "dynamic_module.h"
namespace fs = boost::filesystem;
using cyclus::DynamicModule;
using cyclus::AgentSpec;
using cyclus::Agent;
TEST(DynamicLoadingTests, ConstructTestFacility) {
cyclus::Recorder rec;
cyclus::Timer ti;
cyclus::Context* ctx = new cyclus::Context(&ti, &rec);
EXPECT_NO_THROW(DynamicModule::Make(ctx, AgentSpec("tests:TestFacility:TestFacility")));
EXPECT_NO_THROW(DynamicModule::CloseAll());
}
TEST(DynamicLoadingTests, LoadLibError) {
cyclus::Recorder rec;
cyclus::Timer ti;
cyclus::Context* ctx = new cyclus::Context(&ti, &rec);
EXPECT_THROW(DynamicModule::Make(ctx, AgentSpec("foo:foo:not_a_fac")), cyclus::IOError);
}
TEST(DynamicLoadingTests, CloneTestFacility) {
cyclus::Recorder rec;
cyclus::Timer ti;
cyclus::Context* ctx = new cyclus::Context(&ti, &rec);
EXPECT_NO_THROW(Agent* fac = DynamicModule::Make(ctx, AgentSpec("tests:TestFacility:TestFacility"));
Agent* clone = fac->Clone(););
DynamicModule::CloseAll();
}
<|endoftext|> |
<commit_before>// maketable.hpp
//
#pragma once
#ifndef __SDL_SYSTEM_MAKETABLE_HPP__
#define __SDL_SYSTEM_MAKETABLE_HPP__
namespace sdl { namespace db { namespace make {
template<class this_table, class record>
record make_query<this_table, record>::find_with_index(key_type const & key) {
if (m_cluster) {
auto const db = m_table.get_db();
if (auto const id = make::index_tree<key_type>(db, m_cluster).find_page(key)) {
if (page_head const * const h = db->load_page_head(id)) {
SDL_ASSERT(h->is_data());
const datapage data(h);
if (!data.empty()) {
size_t const slot = data.lower_bound(
[this, &key](row_head const * const row, size_t) {
return (this->read_key(row) < key);
});
if (slot < data.size()) {
row_head const * const head = data[slot];
if (!(key < read_key(head))) {
return record(&m_table, head);
}
}
}
}
}
}
return {};
}
#if maketable_select_old_code
template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, ignore_index, unique_false) {
record_range result;
if (in.size()) {
result.reserve(in.size());
for (auto p : m_table) { // scan all table
A_STATIC_CHECK_TYPE(record, p);
auto const key = make_query::read_key(p);
for (auto const & k : in) {
if (key == k) {
result.push_back(p);
}
}
}
}
return result;
}
template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, ignore_index, unique_true) {
record_range result;
if (in.size()) {
result.reserve(in.size());
std::vector<const key_type *> look(in.size());
for (size_t i = 0; i < in.size(); ++i) {
look[i] = in.begin() + i;
}
size_t size = in.size();
for (auto p : m_table) { // scan table and filter found keys
A_STATIC_CHECK_TYPE(record, p);
auto const key = make_query::read_key(p);
for (size_t i = 0; i < size; ++i) {
if (key == *look[i]) {
result.push_back(p);
if (!(--size))
return result;
look[i] = look[size];
}
}
}
}
return result; // not all keys found
}
template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, use_index, unique_true) {
record_range result;
if (in.size()) {
result.reserve(in.size());
for (auto const & key : in) {
if (auto p = find_with_index(key)) {
result.push_back(p);
}
}
}
return result;
}
/*template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, enum_index const v1, enum_unique const v2) {
if (enum_index::ignore_index == v1) {
if (enum_unique::unique_false == v2) {
return select(in, enum_index_t<ignore_index>(), enum_unique_t<unique_false>());
}
SDL_ASSERT(enum_unique::unique_true == v2);
return select(in, enum_index_t<ignore_index>(), enum_unique_t<unique_true>());
}
SDL_ASSERT(enum_index::use_index == v1);
SDL_ASSERT(enum_unique::unique_true == v2);
return select(in, enum_index_t<use_index>(), enum_unique_t<unique_true>());
}*/
/*template<typename T, typename... Ts>
void select_n(where<T> col, Ts const & ... params) {
enum { col_found = TL::IndexOf<typename this_table::type_list, T>::value };
enum { key_found = meta::cluster_col_find<KEY_TYPE_LIST, T>::value };
static_assert(col_found != -1, "");
using type_list = typename TL::Seq<T, Ts...>::Type; // test
static_assert(TL::Length<type_list>::value == sizeof...(params) + 1, "");
//SDL_TRACE(typeid(type_list).name());
SDL_ASSERT(where<T>::name() == T::name()); // same memory
SDL_TRACE(
"col:", col_found,
" key:", key_found,
" name:", T::name(),
" value:", col.value);
select_n(params...);
}*/
#endif
#if 0
template<class this_table, class record>
struct make_query<this_table, record>::sub_expr_fun
{
template<class T> // T = where_::SEARCH
void operator()(identity<T>) {
if (0) {
SDL_TRACE(
T::col::name(), " INDEX::", where_::index_name<T::hint>(), " ",
T::col::PK ? "PK" : "");
}
static_assert((T::hint != where_::INDEX::USE) || T::col::PK, "INDEX::USE");
}
template<class T, sortorder ord>
void operator()(identity<where_::ORDER_BY<T, ord>>) {
}
template<class F>
void operator()(identity<where_::SELECT_IF<F>>) {
}
};
#endif
namespace make_query_ {
//--------------------------------------------------------------
#if maketable_reverse_order
template <class TList, size_t Count> struct reserse_order;
template <size_t Count>
struct reserse_order<NullType, Count>
{
using Result = NullType;
};
template <size_t i, class Tail, size_t Count>
struct reserse_order<Typelist<Int2Type<i>, Tail>, Count> {
private:
using reverse_i = Typelist<Int2Type<Count-1-i>, NullType>;
static_assert(i < Count, "reserse_order");
public:
using Result = typename TL::Append<reverse_i, typename reserse_order<Tail, Count>::Result>::Result;
};
#endif
//--------------------------------------------------------------
template<class T, where_::condition cond = T::cond>
struct use_index {
static_assert((T::hint != where_::INDEX::USE) || T::col::PK, "INDEX::USE");
enum { value = T::col::PK && (T::hint != where_::INDEX::IGNORE) };
};
template<class T>
struct use_index<T, where_::condition::_lambda> {
enum { value = false };
};
template<class T>
struct use_index<T, where_::condition::_order> {
enum { value = false };
};
//--------------------------------------------------------------
template <class TList, class OList, size_t> struct search_use_index;
template <size_t i> struct search_use_index<NullType, NullType, i>
{
using Index = NullType;
using Types = NullType;
using OList = NullType;
};
template <class Head, class Tail, where_::operator_ OP, class NextOP, size_t i>
struct search_use_index<Typelist<Head, Tail>, where_::operator_list<OP, NextOP>, i> {
private:
enum { flag = use_index<Head>::value };
using indx_i = typename Select<flag, Typelist<Int2Type<i>, NullType>, NullType>::Result;
using type_i = typename Select<flag, Typelist<Head, NullType>, NullType>::Result;
using oper_i = typename Select<flag, Typelist<where_::operator_t<OP>, NullType>, NullType>::Result;
public:
using Types = typename TL::Append<type_i, typename search_use_index<Tail, NextOP, i + 1>::Types>::Result;
using Index = typename TL::Append<indx_i, typename search_use_index<Tail, NextOP, i + 1>::Index>::Result;
using OList = typename TL::Append<oper_i, typename search_use_index<Tail, NextOP, i + 1>::OList>::Result;
};
//--------------------------------------------------------------
template<class TList> struct process_push_back;
template<> struct process_push_back<NullType>
{
template<class T>
static void push_back(T &){}
};
template<size_t i, class Tail>
struct process_push_back<Typelist<Int2Type<i>, Tail>>
{
template<class T>
static void push_back(T & dest){
A_STATIC_ASSERT_TYPE(size_t, typename T::value_type);
dest.push_back(i);
process_push_back<Tail>::push_back(dest);
}
};
template<class TList, class T>
inline void push_back(T & dest) {
dest.reserve(TL::Length<TList>::value);
process_push_back<TList>::push_back(dest);
}
//--------------------------------------------------------------
template<size_t i, class T, where_::operator_ op>
struct search_key
{
enum { pos = i };
using type = T;
static const where_::operator_ OP = op;
};
template<class Index, class TList, class OList> struct make_search_list;
template<> struct make_search_list<NullType, NullType, NullType>
{
using Result = NullType;
};
template<
size_t i, class NextIndex,
class T, class NextType,
where_::operator_ OP, class NextOP>
struct make_search_list<
Typelist<Int2Type<i>, NextIndex>,
Typelist<T, NextType>,
Typelist<where_::operator_t<OP>, NextOP>>
{
private:
using Item = Typelist<search_key<i, T, OP>, NullType>;
using Next = typename make_search_list<NextIndex, NextType, NextOP>::Result;
public:
using Result = typename TL::Append<Item, Next>::Result;
};
template<class sub_expr_type>
struct SEARCH_USE_INDEX {
private:
using use_index = make_query_::search_use_index<
typename sub_expr_type::type_list,
typename sub_expr_type::oper_list,
0>;
using Index = typename use_index::Index;
using Types = typename use_index::Types;
using OList = typename use_index::OList;
public:
using Result = typename make_query_::make_search_list<Index, Types, OList>::Result;
static_assert(TL::Length<Index>::value == TL::Length<Types>::value, "");
static_assert(TL::Length<Index>::value == TL::Length<OList>::value, "");
static_assert(TL::Length<Result>::value == TL::Length<OList>::value, "");
};
//--------------------------------------------------------------
using where_::condition;
using where_::condition_t;
template <class T> // T = search_key
struct SELECT_RECORD_WITH_INDEX : is_static
{
private:
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::WHERE>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::IN>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::NOT>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::LESS>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::GREATER>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::LESS_EQ>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::GREATER_EQ>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::BETWEEN>) {
SDL_ASSERT(!expr->value.values.empty());
}
public:
template<class sub_expr_type>
static void select(sub_expr_type const & expr) {
if (0) {
SDL_TRACE("[", T::pos, "] = ",
where_::operator_name<T::OP>(), " ",
where_::condition_name<T::type::cond>()
);
}
auto value = expr.get(Size2Type<T::pos>());
SELECT_RECORD_WITH_INDEX::select_cond(value, condition_t<T::type::cond>());
}
};
template <class search_list> struct SELECT_WITH_INDEX;
template <> struct SELECT_WITH_INDEX<NullType>
{
template<class sub_expr_type> static void select(sub_expr_type const & ) {}
};
template<class T, class NextType> // T = search_key
struct SELECT_WITH_INDEX<Typelist<T, NextType>> {
public:
template<class sub_expr_type>
static void select(sub_expr_type const & expr) {
SELECT_RECORD_WITH_INDEX<T>::select(expr);
SELECT_WITH_INDEX<NextType>::select(expr);
}
};
//--------------------------------------------------------------
} // make_query_
template<class this_table, class record>
template<class sub_expr_type>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::VALUES(sub_expr_type const & expr)
{
SDL_TRACE("\nVALUES:");
if (1) {
where_::trace_::trace_sub_expr(expr);
}
#if maketable_reverse_order
using use_index = make_query_::search_use_index<
typename sub_expr_type::reverse_type_list,
typename sub_expr_type::reverse_oper_list,
0>;
using Index = typename make_query_::reserse_order<typename use_index::Index, sub_expr_type::type_size>::Result;
using Types = typename use_index::Types;
using OList = typename use_index::OList;
using SL = typename make_query_::make_search_list<Index, Types, OList>::Result;
#else
/*using use_index = make_query_::search_use_index<
typename sub_expr_type::type_list,
typename sub_expr_type::oper_list,
0>;
using Index = typename use_index::Index;
using Types = typename use_index::Types;
using OList = typename use_index::OList;
using SL = typename make_query_::make_search_list<Index, Types, OList>::Result;*/
#endif
using SL = typename make_query_::SEARCH_USE_INDEX<sub_expr_type>::Result;
meta::trace_typelist<SL>();
make_query_::SELECT_WITH_INDEX<SL>::select(expr);
return {};
}
//std::vector<size_t> test;
//make_query_::push_back<Index>(test);
} // make
} // db
} // sdl
#endif // __SDL_SYSTEM_MAKETABLE_HPP__
<commit_msg>select_::sub_expr<commit_after>// maketable.hpp
//
#pragma once
#ifndef __SDL_SYSTEM_MAKETABLE_HPP__
#define __SDL_SYSTEM_MAKETABLE_HPP__
namespace sdl { namespace db { namespace make {
template<class this_table, class record>
record make_query<this_table, record>::find_with_index(key_type const & key) {
if (m_cluster) {
auto const db = m_table.get_db();
if (auto const id = make::index_tree<key_type>(db, m_cluster).find_page(key)) {
if (page_head const * const h = db->load_page_head(id)) {
SDL_ASSERT(h->is_data());
const datapage data(h);
if (!data.empty()) {
size_t const slot = data.lower_bound(
[this, &key](row_head const * const row, size_t) {
return (this->read_key(row) < key);
});
if (slot < data.size()) {
row_head const * const head = data[slot];
if (!(key < read_key(head))) {
return record(&m_table, head);
}
}
}
}
}
}
return {};
}
#if maketable_select_old_code
template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, ignore_index, unique_false) {
record_range result;
if (in.size()) {
result.reserve(in.size());
for (auto p : m_table) { // scan all table
A_STATIC_CHECK_TYPE(record, p);
auto const key = make_query::read_key(p);
for (auto const & k : in) {
if (key == k) {
result.push_back(p);
}
}
}
}
return result;
}
template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, ignore_index, unique_true) {
record_range result;
if (in.size()) {
result.reserve(in.size());
std::vector<const key_type *> look(in.size());
for (size_t i = 0; i < in.size(); ++i) {
look[i] = in.begin() + i;
}
size_t size = in.size();
for (auto p : m_table) { // scan table and filter found keys
A_STATIC_CHECK_TYPE(record, p);
auto const key = make_query::read_key(p);
for (size_t i = 0; i < size; ++i) {
if (key == *look[i]) {
result.push_back(p);
if (!(--size))
return result;
look[i] = look[size];
}
}
}
}
return result; // not all keys found
}
template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, use_index, unique_true) {
record_range result;
if (in.size()) {
result.reserve(in.size());
for (auto const & key : in) {
if (auto p = find_with_index(key)) {
result.push_back(p);
}
}
}
return result;
}
/*template<class this_table, class record>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::select(select_key_list in, enum_index const v1, enum_unique const v2) {
if (enum_index::ignore_index == v1) {
if (enum_unique::unique_false == v2) {
return select(in, enum_index_t<ignore_index>(), enum_unique_t<unique_false>());
}
SDL_ASSERT(enum_unique::unique_true == v2);
return select(in, enum_index_t<ignore_index>(), enum_unique_t<unique_true>());
}
SDL_ASSERT(enum_index::use_index == v1);
SDL_ASSERT(enum_unique::unique_true == v2);
return select(in, enum_index_t<use_index>(), enum_unique_t<unique_true>());
}*/
/*template<typename T, typename... Ts>
void select_n(where<T> col, Ts const & ... params) {
enum { col_found = TL::IndexOf<typename this_table::type_list, T>::value };
enum { key_found = meta::cluster_col_find<KEY_TYPE_LIST, T>::value };
static_assert(col_found != -1, "");
using type_list = typename TL::Seq<T, Ts...>::Type; // test
static_assert(TL::Length<type_list>::value == sizeof...(params) + 1, "");
//SDL_TRACE(typeid(type_list).name());
SDL_ASSERT(where<T>::name() == T::name()); // same memory
SDL_TRACE(
"col:", col_found,
" key:", key_found,
" name:", T::name(),
" value:", col.value);
select_n(params...);
}*/
#endif
#if 0
template<class this_table, class record>
struct make_query<this_table, record>::sub_expr_fun
{
template<class T> // T = where_::SEARCH
void operator()(identity<T>) {
if (0) {
SDL_TRACE(
T::col::name(), " INDEX::", where_::index_name<T::hint>(), " ",
T::col::PK ? "PK" : "");
}
static_assert((T::hint != where_::INDEX::USE) || T::col::PK, "INDEX::USE");
}
template<class T, sortorder ord>
void operator()(identity<where_::ORDER_BY<T, ord>>) {
}
template<class F>
void operator()(identity<where_::SELECT_IF<F>>) {
}
};
#endif
namespace make_query_ {
//--------------------------------------------------------------
template<class T, where_::condition cond = T::cond>
struct use_index {
static_assert((T::hint != where_::INDEX::USE) || T::col::PK, "INDEX::USE");
enum { value = T::col::PK && (T::hint != where_::INDEX::IGNORE) };
};
template<class T>
struct use_index<T, where_::condition::_lambda> {
enum { value = false };
};
template<class T>
struct use_index<T, where_::condition::_order> {
enum { value = false };
};
//--------------------------------------------------------------
template <class TList, class OList, size_t> struct search_use_index;
template <size_t i> struct search_use_index<NullType, NullType, i>
{
using Index = NullType;
using Types = NullType;
using OList = NullType;
};
template <class Head, class Tail, where_::operator_ OP, class NextOP, size_t i>
struct search_use_index<Typelist<Head, Tail>, where_::operator_list<OP, NextOP>, i> {
private:
enum { flag = use_index<Head>::value };
using indx_i = typename Select<flag, Typelist<Int2Type<i>, NullType>, NullType>::Result;
using type_i = typename Select<flag, Typelist<Head, NullType>, NullType>::Result;
using oper_i = typename Select<flag, Typelist<where_::operator_t<OP>, NullType>, NullType>::Result;
public:
using Types = typename TL::Append<type_i, typename search_use_index<Tail, NextOP, i + 1>::Types>::Result;
using Index = typename TL::Append<indx_i, typename search_use_index<Tail, NextOP, i + 1>::Index>::Result;
using OList = typename TL::Append<oper_i, typename search_use_index<Tail, NextOP, i + 1>::OList>::Result;
};
//--------------------------------------------------------------
template<class TList> struct process_push_back;
template<> struct process_push_back<NullType>
{
template<class T>
static void push_back(T &){}
};
template<size_t i, class Tail>
struct process_push_back<Typelist<Int2Type<i>, Tail>>
{
template<class T>
static void push_back(T & dest){
A_STATIC_ASSERT_TYPE(size_t, typename T::value_type);
dest.push_back(i);
process_push_back<Tail>::push_back(dest);
}
};
template<class TList, class T>
inline void push_back(T & dest) {
dest.reserve(TL::Length<TList>::value);
process_push_back<TList>::push_back(dest);
}
//--------------------------------------------------------------
template<size_t i, class T, where_::operator_ op>
struct search_key
{
enum { pos = i };
using type = T;
static const where_::operator_ OP = op;
};
template<class Index, class TList, class OList> struct make_search_list;
template<> struct make_search_list<NullType, NullType, NullType>
{
using Result = NullType;
};
template<
size_t i, class NextIndex,
class T, class NextType,
where_::operator_ OP, class NextOP>
struct make_search_list<
Typelist<Int2Type<i>, NextIndex>,
Typelist<T, NextType>,
Typelist<where_::operator_t<OP>, NextOP>>
{
private:
using Item = Typelist<search_key<i, T, OP>, NullType>;
using Next = typename make_search_list<NextIndex, NextType, NextOP>::Result;
public:
using Result = typename TL::Append<Item, Next>::Result;
};
template<class sub_expr_type>
struct SEARCH_USE_INDEX {
private:
using use_index = make_query_::search_use_index<
typename sub_expr_type::type_list,
typename sub_expr_type::oper_list,
0>;
using Index = typename use_index::Index;
using Types = typename use_index::Types;
using OList = typename use_index::OList;
public:
using Result = typename make_query_::make_search_list<Index, Types, OList>::Result;
static_assert(TL::Length<Index>::value == TL::Length<Types>::value, "");
static_assert(TL::Length<Index>::value == TL::Length<OList>::value, "");
static_assert(TL::Length<Result>::value == TL::Length<OList>::value, "");
};
//--------------------------------------------------------------
using where_::condition;
using where_::condition_t;
template <class T> // T = search_key
struct SELECT_RECORD_WITH_INDEX : is_static
{
private:
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::WHERE>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::IN>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::NOT>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::LESS>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::GREATER>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::LESS_EQ>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::GREATER_EQ>) {
SDL_ASSERT(!expr->value.values.empty());
}
template<class value_type>
static void select_cond(value_type const * expr, condition_t<condition::BETWEEN>) {
SDL_ASSERT(!expr->value.values.empty());
}
public:
template<class sub_expr_type>
static void select(sub_expr_type const & expr) {
if (0) {
SDL_TRACE("[", T::pos, "] = ",
where_::operator_name<T::OP>(), " ",
where_::condition_name<T::type::cond>()
);
}
auto value = expr.get(Size2Type<T::pos>());
SELECT_RECORD_WITH_INDEX::select_cond(value, condition_t<T::type::cond>());
}
};
template <class search_list> struct SELECT_WITH_INDEX;
template <> struct SELECT_WITH_INDEX<NullType>
{
template<class sub_expr_type> static void select(sub_expr_type const & ) {}
};
template<class T, class NextType> // T = search_key
struct SELECT_WITH_INDEX<Typelist<T, NextType>> {
public:
template<class sub_expr_type>
static void select(sub_expr_type const & expr) {
SELECT_RECORD_WITH_INDEX<T>::select(expr);
SELECT_WITH_INDEX<NextType>::select(expr);
}
};
//--------------------------------------------------------------
} // make_query_
template<class this_table, class record>
template<class sub_expr_type>
typename make_query<this_table, record>::record_range
make_query<this_table, record>::VALUES(sub_expr_type const & expr)
{
SDL_TRACE("\nVALUES:");
if (1) {
where_::trace_::trace_sub_expr(expr);
}
using SL = typename make_query_::SEARCH_USE_INDEX<sub_expr_type>::Result;
meta::trace_typelist<SL>();
make_query_::SELECT_WITH_INDEX<SL>::select(expr);
return {};
}
//std::vector<size_t> test;
//make_query_::push_back<Index>(test);
} // make
} // db
} // sdl
#endif // __SDL_SYSTEM_MAKETABLE_HPP__
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.