text stringlengths 54 60.6k |
|---|
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "num_feature_factory.hpp"
#include <string>
#include "exception.hpp"
#include "util.hpp"
using jubatus::util::lang::shared_ptr;
namespace jubatus {
namespace core {
namespace fv_converter {
shared_ptr<num_feature> num_feature_factory::create(
const std::string& name,
const param_t& params) const {
num_feature* p;
if (ext_ != NULL && (p = ext_(name, params))) {
return shared_ptr<num_feature>(p);
} else {
throw JUBATUS_EXCEPTION(
converter_exception(std::string("unknonwn num feature name: ") + name));
}
}
} // namespace fv_converter
} // namespace core
} // namespace jubatus
<commit_msg>Add necessary include<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "num_feature_factory.hpp"
#include <string>
#include "exception.hpp"
#include "util.hpp"
#include "num_feature.hpp"
using jubatus::util::lang::shared_ptr;
namespace jubatus {
namespace core {
namespace fv_converter {
shared_ptr<num_feature> num_feature_factory::create(
const std::string& name,
const param_t& params) const {
num_feature* p;
if (ext_ != NULL && (p = ext_(name, params))) {
return shared_ptr<num_feature>(p);
} else {
throw JUBATUS_EXCEPTION(
converter_exception(std::string("unknonwn num feature name: ") + name));
}
}
} // namespace fv_converter
} // namespace core
} // namespace jubatus
<|endoftext|> |
<commit_before> /* -*- mode: c++; c-basic-offset:4 -*-
decryptverifyfilescontroller.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 "decryptverifyfilescontroller.h"
#include <crypto/gui/decryptverifyoperationwidget.h>
#include <crypto/gui/decryptverifyfileswizard.h>
#include <crypto/decryptverifytask.h>
#include <crypto/taskcollection.h>
#include <utils/classify.h>
#include <utils/gnupg-helper.h>
#include <utils/input.h>
#include <utils/output.h>
#include <utils/kleo_assert.h>
#include <KDebug>
#include <KLocalizedString>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPointer>
#include <QTimer>
#include <boost/shared_ptr.hpp>
#include <memory>
#include <vector>
using namespace boost;
using namespace GpgME;
using namespace Kleo;
using namespace Kleo::Crypto;
using namespace Kleo::Crypto::Gui;
class DecryptVerifyFilesController::Private {
DecryptVerifyFilesController* const q;
public:
static QString heuristicBaseDirectory( const QStringList& fileNames );
static shared_ptr<AbstractDecryptVerifyTask> taskFromOperationWidget( const DecryptVerifyOperationWidget * w, const shared_ptr<QFile> & file, const QDir & outDir, const shared_ptr<OverwritePolicy> & overwritePolicy );
explicit Private( DecryptVerifyFilesController* qq );
void slotWizardOperationPrepared();
void slotWizardCanceled();
void schedule();
std::vector< shared_ptr<QFile> > prepareWizardFromPassedFiles();
std::vector<shared_ptr<Task> > buildTasks( const std::vector<shared_ptr<QFile> > &, const shared_ptr<OverwritePolicy> & );
QString heuristicBaseDirectory() const;
void ensureWizardCreated();
void ensureWizardVisible();
void reportError( int err, const QString & details ) {
emit q->error( err, details );
}
void cancelAllTasks();
std::vector<shared_ptr<QFile> > m_passedFiles, m_filesAfterPreparation;
QPointer<DecryptVerifyFilesWizard> m_wizard;
std::vector<shared_ptr<const DecryptVerifyResult> > m_results;
std::vector<shared_ptr<Task> > m_runnableTasks, m_completedTasks;
shared_ptr<Task> m_runningTask;
bool m_errorDetected;
DecryptVerifyOperation m_operation;
};
// static
shared_ptr<AbstractDecryptVerifyTask> DecryptVerifyFilesController::Private::taskFromOperationWidget( const DecryptVerifyOperationWidget * w, const shared_ptr<QFile> & file, const QDir & outDir, const shared_ptr<OverwritePolicy> & overwritePolicy ) {
kleo_assert( w );
shared_ptr<AbstractDecryptVerifyTask> task;
switch ( w->mode() ) {
case DecryptVerifyOperationWidget::VerifyDetachedWithSignature:
{
shared_ptr<VerifyDetachedTask> t( new VerifyDetachedTask );
t->setInput( Input::createFromFile( file ) );
t->setSignedData( Input::createFromFile( w->signedDataFileName() ) );
task = t;
kleo_assert( file->fileName() == w->inputFileName() );
}
break;
case DecryptVerifyOperationWidget::VerifyDetachedWithSignedData:
{
shared_ptr<VerifyDetachedTask> t( new VerifyDetachedTask );
t->setInput( Input::createFromFile( w->inputFileName() ) );
t->setSignedData( Input::createFromFile( file ) );
task = t;
kleo_assert( file->fileName() == w->signedDataFileName() );
}
break;
case DecryptVerifyOperationWidget::DecryptVerifyOpaque:
{
shared_ptr<DecryptVerifyTask> t( new DecryptVerifyTask );
t->setInput( Input::createFromFile( file ) );
t->setOutput( Output::createFromFile( outDir.absoluteFilePath( outputFileName( QFileInfo( file->fileName() ).fileName() ) ), overwritePolicy ) );
task = t;
kleo_assert( file->fileName() == w->inputFileName() );
}
break;
}
task->autodetectProtocolFromInput();
return task;
}
DecryptVerifyFilesController::Private::Private( DecryptVerifyFilesController* qq ) : q( qq ), m_errorDetected( false ), m_operation( DecryptVerify )
{
qRegisterMetaType<VerificationResult>();
}
void DecryptVerifyFilesController::Private::slotWizardOperationPrepared()
{
try {
ensureWizardCreated();
std::vector<shared_ptr<Task> > tasks = buildTasks( m_filesAfterPreparation, shared_ptr<OverwritePolicy>( new OverwritePolicy( m_wizard ) ) );
kleo_assert( m_runnableTasks.empty() );
m_runnableTasks.swap( tasks );
shared_ptr<TaskCollection> coll( new TaskCollection );
Q_FOREACH( const shared_ptr<Task> & i, m_runnableTasks )
q->connectTask( i );
coll->setTasks( m_runnableTasks );
m_wizard->setTaskCollection( coll );
QTimer::singleShot( 0, q, SLOT( schedule() ) );
} catch ( const Kleo::Exception & e ) {
reportError( e.error().encodedError(), e.message() );
} catch ( const std::exception & e ) {
reportError( gpg_error( GPG_ERR_UNEXPECTED ),
i18n("Caught unexpected exception in DecryptVerifyFilesController::Private::slotWizardOperationPrepared: %1",
QString::fromLocal8Bit( e.what() ) ) );
} catch ( ... ) {
reportError( gpg_error( GPG_ERR_UNEXPECTED ),
i18n("Caught unknown exception in DecryptVerifyFilesController::Private::slotWizardOperationPrepared") );
}
}
void DecryptVerifyFilesController::Private::slotWizardCanceled()
{
kDebug();
reportError( gpg_error( GPG_ERR_CANCELED ), i18n("User canceled") );
}
void DecryptVerifyFilesController::doTaskDone( const Task* task, const shared_ptr<const Task::Result> & result )
{
assert( task );
assert( task == d->m_runningTask.get() );
// We could just delete the tasks here, but we can't use
// Qt::QueuedConnection here (we need sender()) and other slots
// might not yet have executed. Therefore, we push completed tasks
// into a burial container
d->m_completedTasks.push_back( d->m_runningTask );
d->m_runningTask.reset();
if ( const shared_ptr<const DecryptVerifyResult> & dvr = boost::dynamic_pointer_cast<const DecryptVerifyResult>( result ) )
d->m_results.push_back( dvr );
QTimer::singleShot( 0, this, SLOT(schedule()) );
}
void DecryptVerifyFilesController::Private::schedule()
{
if ( !m_runningTask && !m_runnableTasks.empty() ) {
const shared_ptr<Task> t = m_runnableTasks.back();
m_runnableTasks.pop_back();
t->start();
m_runningTask = t;
}
if ( !m_runningTask ) {
kleo_assert( m_runnableTasks.empty() );
Q_FOREACH ( const shared_ptr<const DecryptVerifyResult> & i, m_results )
emit q->verificationResult( i->verificationResult() );
q->emitDoneOrError();
}
}
void DecryptVerifyFilesController::Private::ensureWizardCreated()
{
if ( m_wizard )
return;
std::auto_ptr<DecryptVerifyFilesWizard> w( new DecryptVerifyFilesWizard );
w->setWindowTitle( i18n( "Decrypt/Verify Files" ) );
w->setAttribute( Qt::WA_DeleteOnClose );
connect( w.get(), SIGNAL(operationPrepared()), q, SLOT(slotWizardOperationPrepared()), Qt::QueuedConnection );
connect( w.get(), SIGNAL(canceled()), q, SLOT(slotWizardCanceled()), Qt::QueuedConnection );
m_wizard = w.release();
}
std::vector<shared_ptr<QFile> > DecryptVerifyFilesController::Private::prepareWizardFromPassedFiles()
{
ensureWizardCreated();
std::vector< shared_ptr<QFile> > files;
unsigned int counter = 0;
Q_FOREACH( const shared_ptr<QFile> & file, m_passedFiles ) {
kleo_assert( file );
const QString fname = file->fileName();
kleo_assert( !fname.isEmpty() );
const unsigned int classification = classify( fname );
if ( mayBeOpaqueSignature( classification ) || mayBeCipherText( classification ) || mayBeDetachedSignature( classification ) ) {
DecryptVerifyOperationWidget * const op = m_wizard->operationWidget( counter++ );
kleo_assert( op != 0 );
if ( mayBeOpaqueSignature( classification ) || mayBeCipherText( classification ) )
op->setMode( DecryptVerifyOperationWidget::DecryptVerifyOpaque );
else
op->setMode( DecryptVerifyOperationWidget::VerifyDetachedWithSignature );
op->setInputFileName( fname );
op->setSignedDataFileName( findSignedData( fname ) );
files.push_back( file );
} else {
// probably the signed data file was selected:
QStringList signatures = findSignatures( fname );
if ( signatures.empty() )
signatures.push_back( QString() );
Q_FOREACH( const QString s, signatures ) {
DecryptVerifyOperationWidget * op = m_wizard->operationWidget( counter++ );
kleo_assert( op != 0 );
op->setMode( DecryptVerifyOperationWidget::VerifyDetachedWithSignedData );
op->setInputFileName( s.isEmpty() ? fname : s );
op->setSignedDataFileName( fname );
files.push_back( file );
}
}
}
kleo_assert( counter == files.size() );
if ( !counter )
throw Kleo::Exception( makeGnuPGError( GPG_ERR_ASS_NO_INPUT ), i18n("No usable inputs found") );
m_wizard->setOutputDirectory( heuristicBaseDirectory() );
return files;
}
std::vector< shared_ptr<Task> > DecryptVerifyFilesController::Private::buildTasks( const std::vector<shared_ptr<QFile> > & files, const shared_ptr<OverwritePolicy> & overwritePolicy )
{
const bool useOutDir = m_wizard->useOutputDirectory();
const QFileInfo outDirInfo( m_wizard->outputDirectory() );
kleo_assert( !useOutDir || outDirInfo.isDir() );
const QDir outDir( outDirInfo.absoluteFilePath() );
kleo_assert( !useOutDir || outDir.exists() );
std::vector<shared_ptr<Task> > tasks;
for ( unsigned int i = 0 ; i < files.size(); ++i )
try {
const QDir fileDir = QFileInfo( *files[i] ).absoluteDir();
kleo_assert( fileDir.exists() );
tasks.push_back( taskFromOperationWidget( m_wizard->operationWidget( i ), files[i], useOutDir ? outDir : fileDir, overwritePolicy ) );
} catch ( const GpgME::Exception & e ) {
tasks.push_back( Task::makeErrorTask( e.error().code(), QString::fromLocal8Bit( e.what() ), QFileInfo( *files[i] ).fileName() ) );
}
return tasks;
}
void DecryptVerifyFilesController::setFiles( const std::vector<boost::shared_ptr<QFile> >& files )
{
d->m_passedFiles = files;
}
void DecryptVerifyFilesController::Private::ensureWizardVisible()
{
ensureWizardCreated();
q->bringToForeground( m_wizard );
}
DecryptVerifyFilesController::DecryptVerifyFilesController( QObject* parent ) : Controller( parent ), d( new Private( this ) )
{
}
DecryptVerifyFilesController::DecryptVerifyFilesController( const shared_ptr<const ExecutionContext> & ctx, QObject* parent ) : Controller( ctx, parent ), d( new Private( this ) )
{
}
DecryptVerifyFilesController::~DecryptVerifyFilesController() { kDebug(); }
void DecryptVerifyFilesController::start()
{
d->m_filesAfterPreparation = d->prepareWizardFromPassedFiles();
d->ensureWizardVisible();
}
static QString commonPrefix( const QString & s1, const QString & s2 ) {
return QString( s1.data(), std::mismatch( s1.data(), s1.data() + std::min( s1.size(), s2.size() ), s2.data() ).first - s1.data() );
}
static QString longestCommonPrefix( const QStringList & sl ) {
if ( sl.empty() )
return QString();
QString result = sl.front();
Q_FOREACH( const QString & s, sl )
result = commonPrefix( s, result );
return result;
}
QString DecryptVerifyFilesController::Private::heuristicBaseDirectory() const {
QStringList fileNames;
Q_FOREACH ( const shared_ptr<QFile> & i, m_passedFiles )
fileNames.push_back( i->fileName() );
return heuristicBaseDirectory( fileNames );
}
QString DecryptVerifyFilesController::Private::heuristicBaseDirectory( const QStringList& fileNames ) {
const QString candidate = longestCommonPrefix( fileNames );
const QFileInfo fi( candidate );
if ( fi.isDir() )
return candidate;
else
return fi.absolutePath();
}
void DecryptVerifyFilesController::setOperation( DecryptVerifyOperation op )
{
d->m_operation = op;
}
DecryptVerifyOperation DecryptVerifyFilesController::operation() const
{
return d->m_operation;
}
void DecryptVerifyFilesController::Private::cancelAllTasks() {
// we just kill all runnable tasks - this will not result in
// signal emissions.
m_runnableTasks.clear();
// a cancel() will result in a call to
if ( m_runningTask )
m_runningTask->cancel();
}
void DecryptVerifyFilesController::cancel()
{
kDebug();
try {
d->m_errorDetected = true;
if ( d->m_wizard )
d->m_wizard->close();
d->cancelAllTasks();
} catch ( const std::exception & e ) {
qDebug( "Caught exception: %s", e.what() );
}
}
#include "decryptverifyfilescontroller.moc"
<commit_msg>Better fix for the case of an unsigned, wrongly named encrypted file. We know assume encrypted and allow the user to chose signature and then select the input data.<commit_after> /* -*- mode: c++; c-basic-offset:4 -*-
decryptverifyfilescontroller.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 "decryptverifyfilescontroller.h"
#include <crypto/gui/decryptverifyoperationwidget.h>
#include <crypto/gui/decryptverifyfileswizard.h>
#include <crypto/decryptverifytask.h>
#include <crypto/taskcollection.h>
#include <utils/classify.h>
#include <utils/gnupg-helper.h>
#include <utils/input.h>
#include <utils/output.h>
#include <utils/kleo_assert.h>
#include <KDebug>
#include <KLocalizedString>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPointer>
#include <QTimer>
#include <boost/shared_ptr.hpp>
#include <memory>
#include <vector>
using namespace boost;
using namespace GpgME;
using namespace Kleo;
using namespace Kleo::Crypto;
using namespace Kleo::Crypto::Gui;
class DecryptVerifyFilesController::Private {
DecryptVerifyFilesController* const q;
public:
static QString heuristicBaseDirectory( const QStringList& fileNames );
static shared_ptr<AbstractDecryptVerifyTask> taskFromOperationWidget( const DecryptVerifyOperationWidget * w, const shared_ptr<QFile> & file, const QDir & outDir, const shared_ptr<OverwritePolicy> & overwritePolicy );
explicit Private( DecryptVerifyFilesController* qq );
void slotWizardOperationPrepared();
void slotWizardCanceled();
void schedule();
std::vector< shared_ptr<QFile> > prepareWizardFromPassedFiles();
std::vector<shared_ptr<Task> > buildTasks( const std::vector<shared_ptr<QFile> > &, const shared_ptr<OverwritePolicy> & );
QString heuristicBaseDirectory() const;
void ensureWizardCreated();
void ensureWizardVisible();
void reportError( int err, const QString & details ) {
emit q->error( err, details );
}
void cancelAllTasks();
std::vector<shared_ptr<QFile> > m_passedFiles, m_filesAfterPreparation;
QPointer<DecryptVerifyFilesWizard> m_wizard;
std::vector<shared_ptr<const DecryptVerifyResult> > m_results;
std::vector<shared_ptr<Task> > m_runnableTasks, m_completedTasks;
shared_ptr<Task> m_runningTask;
bool m_errorDetected;
DecryptVerifyOperation m_operation;
};
// static
shared_ptr<AbstractDecryptVerifyTask> DecryptVerifyFilesController::Private::taskFromOperationWidget( const DecryptVerifyOperationWidget * w, const shared_ptr<QFile> & file, const QDir & outDir, const shared_ptr<OverwritePolicy> & overwritePolicy ) {
kleo_assert( w );
shared_ptr<AbstractDecryptVerifyTask> task;
switch ( w->mode() ) {
case DecryptVerifyOperationWidget::VerifyDetachedWithSignature:
{
shared_ptr<VerifyDetachedTask> t( new VerifyDetachedTask );
t->setInput( Input::createFromFile( file ) );
t->setSignedData( Input::createFromFile( w->signedDataFileName() ) );
task = t;
kleo_assert( file->fileName() == w->inputFileName() );
}
break;
case DecryptVerifyOperationWidget::VerifyDetachedWithSignedData:
{
shared_ptr<VerifyDetachedTask> t( new VerifyDetachedTask );
t->setInput( Input::createFromFile( w->inputFileName() ) );
t->setSignedData( Input::createFromFile( file ) );
task = t;
kleo_assert( file->fileName() == w->signedDataFileName() );
}
break;
case DecryptVerifyOperationWidget::DecryptVerifyOpaque:
{
shared_ptr<DecryptVerifyTask> t( new DecryptVerifyTask );
t->setInput( Input::createFromFile( file ) );
t->setOutput( Output::createFromFile( outDir.absoluteFilePath( outputFileName( QFileInfo( file->fileName() ).fileName() ) ), overwritePolicy ) );
task = t;
kleo_assert( file->fileName() == w->inputFileName() );
}
break;
}
task->autodetectProtocolFromInput();
return task;
}
DecryptVerifyFilesController::Private::Private( DecryptVerifyFilesController* qq ) : q( qq ), m_errorDetected( false ), m_operation( DecryptVerify )
{
qRegisterMetaType<VerificationResult>();
}
void DecryptVerifyFilesController::Private::slotWizardOperationPrepared()
{
try {
ensureWizardCreated();
std::vector<shared_ptr<Task> > tasks = buildTasks( m_filesAfterPreparation, shared_ptr<OverwritePolicy>( new OverwritePolicy( m_wizard ) ) );
kleo_assert( m_runnableTasks.empty() );
m_runnableTasks.swap( tasks );
shared_ptr<TaskCollection> coll( new TaskCollection );
Q_FOREACH( const shared_ptr<Task> & i, m_runnableTasks )
q->connectTask( i );
coll->setTasks( m_runnableTasks );
m_wizard->setTaskCollection( coll );
QTimer::singleShot( 0, q, SLOT( schedule() ) );
} catch ( const Kleo::Exception & e ) {
reportError( e.error().encodedError(), e.message() );
} catch ( const std::exception & e ) {
reportError( gpg_error( GPG_ERR_UNEXPECTED ),
i18n("Caught unexpected exception in DecryptVerifyFilesController::Private::slotWizardOperationPrepared: %1",
QString::fromLocal8Bit( e.what() ) ) );
} catch ( ... ) {
reportError( gpg_error( GPG_ERR_UNEXPECTED ),
i18n("Caught unknown exception in DecryptVerifyFilesController::Private::slotWizardOperationPrepared") );
}
}
void DecryptVerifyFilesController::Private::slotWizardCanceled()
{
kDebug();
reportError( gpg_error( GPG_ERR_CANCELED ), i18n("User canceled") );
}
void DecryptVerifyFilesController::doTaskDone( const Task* task, const shared_ptr<const Task::Result> & result )
{
assert( task );
assert( task == d->m_runningTask.get() );
// We could just delete the tasks here, but we can't use
// Qt::QueuedConnection here (we need sender()) and other slots
// might not yet have executed. Therefore, we push completed tasks
// into a burial container
d->m_completedTasks.push_back( d->m_runningTask );
d->m_runningTask.reset();
if ( const shared_ptr<const DecryptVerifyResult> & dvr = boost::dynamic_pointer_cast<const DecryptVerifyResult>( result ) )
d->m_results.push_back( dvr );
QTimer::singleShot( 0, this, SLOT(schedule()) );
}
void DecryptVerifyFilesController::Private::schedule()
{
if ( !m_runningTask && !m_runnableTasks.empty() ) {
const shared_ptr<Task> t = m_runnableTasks.back();
m_runnableTasks.pop_back();
t->start();
m_runningTask = t;
}
if ( !m_runningTask ) {
kleo_assert( m_runnableTasks.empty() );
Q_FOREACH ( const shared_ptr<const DecryptVerifyResult> & i, m_results )
emit q->verificationResult( i->verificationResult() );
q->emitDoneOrError();
}
}
void DecryptVerifyFilesController::Private::ensureWizardCreated()
{
if ( m_wizard )
return;
std::auto_ptr<DecryptVerifyFilesWizard> w( new DecryptVerifyFilesWizard );
w->setWindowTitle( i18n( "Decrypt/Verify Files" ) );
w->setAttribute( Qt::WA_DeleteOnClose );
connect( w.get(), SIGNAL(operationPrepared()), q, SLOT(slotWizardOperationPrepared()), Qt::QueuedConnection );
connect( w.get(), SIGNAL(canceled()), q, SLOT(slotWizardCanceled()), Qt::QueuedConnection );
m_wizard = w.release();
}
std::vector<shared_ptr<QFile> > DecryptVerifyFilesController::Private::prepareWizardFromPassedFiles()
{
ensureWizardCreated();
std::vector< shared_ptr<QFile> > files;
unsigned int counter = 0;
Q_FOREACH( const shared_ptr<QFile> & file, m_passedFiles ) {
kleo_assert( file );
const QString fname = file->fileName();
kleo_assert( !fname.isEmpty() );
const unsigned int classification = classify( fname );
if ( mayBeOpaqueSignature( classification ) || mayBeCipherText( classification ) || mayBeDetachedSignature( classification ) ) {
DecryptVerifyOperationWidget * const op = m_wizard->operationWidget( counter++ );
kleo_assert( op != 0 );
if ( mayBeOpaqueSignature( classification ) || mayBeCipherText( classification ) )
op->setMode( DecryptVerifyOperationWidget::DecryptVerifyOpaque );
else
op->setMode( DecryptVerifyOperationWidget::VerifyDetachedWithSignature );
op->setInputFileName( fname );
op->setSignedDataFileName( findSignedData( fname ) );
files.push_back( file );
} else {
// probably the signed data file was selected:
QStringList signatures = findSignatures( fname );
if ( signatures.empty() ) {
// We are assuming this is a detached signature file, but
// there were no signature files for it. Let's guess it's encrypted after all.
// ### FIXME once we have a proper heuristic for this, this should move into
// classify() and/or classifyContent()
DecryptVerifyOperationWidget * const op = m_wizard->operationWidget( counter++ );
kleo_assert( op != 0 );
op->setMode( DecryptVerifyOperationWidget::DecryptVerifyOpaque );
op->setInputFileName( fname );
files.push_back( file );
}
Q_FOREACH( const QString s, signatures ) {
DecryptVerifyOperationWidget * op = m_wizard->operationWidget( counter++ );
kleo_assert( op != 0 );
op->setMode( DecryptVerifyOperationWidget::VerifyDetachedWithSignedData );
op->setInputFileName( s );
op->setSignedDataFileName( fname );
files.push_back( file );
}
}
}
kleo_assert( counter == files.size() );
if ( !counter )
throw Kleo::Exception( makeGnuPGError( GPG_ERR_ASS_NO_INPUT ), i18n("No usable inputs found") );
m_wizard->setOutputDirectory( heuristicBaseDirectory() );
return files;
}
std::vector< shared_ptr<Task> > DecryptVerifyFilesController::Private::buildTasks( const std::vector<shared_ptr<QFile> > & files, const shared_ptr<OverwritePolicy> & overwritePolicy )
{
const bool useOutDir = m_wizard->useOutputDirectory();
const QFileInfo outDirInfo( m_wizard->outputDirectory() );
kleo_assert( !useOutDir || outDirInfo.isDir() );
const QDir outDir( outDirInfo.absoluteFilePath() );
kleo_assert( !useOutDir || outDir.exists() );
std::vector<shared_ptr<Task> > tasks;
for ( unsigned int i = 0 ; i < files.size(); ++i )
try {
const QDir fileDir = QFileInfo( *files[i] ).absoluteDir();
kleo_assert( fileDir.exists() );
tasks.push_back( taskFromOperationWidget( m_wizard->operationWidget( i ), files[i], useOutDir ? outDir : fileDir, overwritePolicy ) );
} catch ( const GpgME::Exception & e ) {
tasks.push_back( Task::makeErrorTask( e.error().code(), QString::fromLocal8Bit( e.what() ), QFileInfo( *files[i] ).fileName() ) );
}
return tasks;
}
void DecryptVerifyFilesController::setFiles( const std::vector<boost::shared_ptr<QFile> >& files )
{
d->m_passedFiles = files;
}
void DecryptVerifyFilesController::Private::ensureWizardVisible()
{
ensureWizardCreated();
q->bringToForeground( m_wizard );
}
DecryptVerifyFilesController::DecryptVerifyFilesController( QObject* parent ) : Controller( parent ), d( new Private( this ) )
{
}
DecryptVerifyFilesController::DecryptVerifyFilesController( const shared_ptr<const ExecutionContext> & ctx, QObject* parent ) : Controller( ctx, parent ), d( new Private( this ) )
{
}
DecryptVerifyFilesController::~DecryptVerifyFilesController() { kDebug(); }
void DecryptVerifyFilesController::start()
{
d->m_filesAfterPreparation = d->prepareWizardFromPassedFiles();
d->ensureWizardVisible();
}
static QString commonPrefix( const QString & s1, const QString & s2 ) {
return QString( s1.data(), std::mismatch( s1.data(), s1.data() + std::min( s1.size(), s2.size() ), s2.data() ).first - s1.data() );
}
static QString longestCommonPrefix( const QStringList & sl ) {
if ( sl.empty() )
return QString();
QString result = sl.front();
Q_FOREACH( const QString & s, sl )
result = commonPrefix( s, result );
return result;
}
QString DecryptVerifyFilesController::Private::heuristicBaseDirectory() const {
QStringList fileNames;
Q_FOREACH ( const shared_ptr<QFile> & i, m_passedFiles )
fileNames.push_back( i->fileName() );
return heuristicBaseDirectory( fileNames );
}
QString DecryptVerifyFilesController::Private::heuristicBaseDirectory( const QStringList& fileNames ) {
const QString candidate = longestCommonPrefix( fileNames );
const QFileInfo fi( candidate );
if ( fi.isDir() )
return candidate;
else
return fi.absolutePath();
}
void DecryptVerifyFilesController::setOperation( DecryptVerifyOperation op )
{
d->m_operation = op;
}
DecryptVerifyOperation DecryptVerifyFilesController::operation() const
{
return d->m_operation;
}
void DecryptVerifyFilesController::Private::cancelAllTasks() {
// we just kill all runnable tasks - this will not result in
// signal emissions.
m_runnableTasks.clear();
// a cancel() will result in a call to
if ( m_runningTask )
m_runningTask->cancel();
}
void DecryptVerifyFilesController::cancel()
{
kDebug();
try {
d->m_errorDetected = true;
if ( d->m_wizard )
d->m_wizard->close();
d->cancelAllTasks();
} catch ( const std::exception & e ) {
qDebug( "Caught exception: %s", e.what() );
}
}
#include "decryptverifyfilescontroller.moc"
<|endoftext|> |
<commit_before>#include <b9.hpp>
#include <b9/loader.hpp>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
/// B9run's usage string. Printed when run with -help.
static const char* usage =
"Usage: b9run [<option>...] [--] [<module> [<main>]]\n"
" Or: b9run -help\n"
"Options:\n"
" -callstyle <style>: Set the calling style. One of:\n"
" interpreter: Calls are made through the interpreter\n"
" direct: Calls are made directly, but parameters are on the operand stack\n"
" passparameter: Direct calls, with parameters passed in CPU registers\n"
" operandstack: Like passparam, but will keep the VM operand stack updated\n"
" -loop <n>: Run the program <n> times\n"
" -inline <n>: Enable inlining\n"
" -debug: Enable debug code\n"
" -verbose: Run with verbose printing\n"
" -help: Print this help message";
/// The b9run program's global configuration.
struct RunConfig {
b9::VirtualMachineConfig vm;
const char* module = "program.so";
const char* mainFunction = "b9main";
std::size_t loopCount = 1;
bool verbose = false;
};
/// Print the configuration summary.
std::ostream& operator <<(std::ostream& out, const RunConfig& cfg) {
return out
<< "Loading: " << cfg.module << std::endl
<< "Executing: " << cfg.mainFunction << std::endl
<< "Looping: " << cfg.loopCount << " times" << std::endl
<< "Inline depth: " << cfg.vm.jit.maxInlineDepth << std::endl
<< "Call Style: " << cfg.vm.jit.callStyle;
}
/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
/* Command Line Arguments */
for (int i = 1; i < argc; i++) {
const char *arg = argv[i];
if (strcmp(arg, "-help") == 0) {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
}
else if (strcmp(arg, "-loop") == 0) {
cfg.loopCount = atoi(argv[++i]);
}
else if (strcmp(arg, "-inline") == 0) {
cfg.vm.jit.maxInlineDepth = atoi(argv[++i]);
}
else if (strcmp(arg, "-verbose") == 0) {
cfg.verbose = true;
cfg.vm.verbose = true;
cfg.vm.jit.verbose = true;
}
else if (strcmp(arg, "-debug") == 0) {
cfg.vm.debug = true;
cfg.vm.jit.debug = true;
}
else if (strcmp(arg, "-callstyle") == 0) {
i += 1;
auto callStyle = argv[i];
if (strcmp("interpreter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::interpreter;
}
else if (strcmp("direct", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::direct;
}
else if (strcmp("passparameter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::passParameter;
}
else if (strcmp("operandstack", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::operandStack;
}
}
else if (strcmp(arg, "-program") == 0) {
cfg.mainFunction = argv[++i];
}
else if (strcmp(arg, "--") == 0) {
return true;
}
else {
std::cerr << "Unrecognized option: " << arg << std::endl;
return false;
}
}
return true;
}
static bool run(const RunConfig& cfg) {
b9::VirtualMachine virtualMachine{cfg.vm};
virtualMachine.initialize();
b9::DlLoader loader(true);
auto module = loader.loadModule(cfg.module);
return true;
#if 0
b9::VirtualMachine virtualMachine;
char sharelib[128];
virtualMachine.initialize();
if (!virtualMachine.loadLibrary()) {
return EXIT_FAILURE;
}
b9::Instruction *function = virtualMachine.getFunctionAddress(mainFunction);
if (function == nullptr) {
return EXIT_FAILURE;
}
b9::StackElement resultInterp = 0;
b9::StackElement resultJit = 0;
long timeInterp = 0;
long timeJIT = 0;
printf("Running Interpreted");
// printf(
// "Options: DirectCall (%d), DirectParameterPassing (%d), "
// "UseVMOperandStack (%d)\n",
// virtualMachine.directCall_, virtualMachine.passParameters_, virtualMachine.operandStack_);
resultInterp =
timeFunction(&virtualMachine, function, 1, &timeInterp);
printf("Running JIT looping %d times\n", 1);
//generateAllCode(&context);
//resultJit = timeFunction(&context, function, context.loopCount, &timeJIT);
printf("Result for Interp is %lld, resultJit is %lld\n", resultInterp, resultJit);
printf("Time for Interp %ld ms, JIT %ld ms\n", timeInterp, timeJIT);
printf("JIT speedup = %f\n", timeInterp * 1.0 / timeJIT);
if (resultInterp == resultJit) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
#endif // 0
}
int main(int argc, char* argv[]) {
RunConfig cfg;
if (parseArguments(cfg, argc, argv)) {
exit(EXIT_FAILURE);
}
if (cfg.vm.verbose) {
std::cout << cfg << std::endl;
}
if (!run(cfg)) {
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<commit_msg>Fix up argument parsing<commit_after>#include <b9.hpp>
#include <b9/loader.hpp>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
/// B9run's usage string. Printed when run with -help.
static const char* usage =
"Usage: b9run [<option>...] [--] [<module> [<main>]]\n"
" Or: b9run -help\n"
"Options:\n"
" -callstyle <style>: Set the calling style. One of:\n"
" interpreter: Calls are made through the interpreter\n"
" direct: Calls are made directly, but parameters are on the operand stack\n"
" passparameter: Direct calls, with parameters passed in CPU registers\n"
" operandstack: Like passparam, but will keep the VM operand stack updated\n"
" -loop <n>: Run the program <n> times\n"
" -inline <n>: Enable inlining\n"
" -debug: Enable debug code\n"
" -verbose: Run with verbose printing\n"
" -help: Print this help message";
/// The b9run program's global configuration.
struct RunConfig {
b9::VirtualMachineConfig vm;
const char* module = "program.so";
const char* mainFunction = "b9main";
std::size_t loopCount = 1;
bool verbose = false;
};
/// Print the configuration summary.
std::ostream& operator <<(std::ostream& out, const RunConfig& cfg) {
return out
<< "Loading: " << cfg.module << std::endl
<< "Executing: " << cfg.mainFunction << std::endl
<< "Looping: " << cfg.loopCount << " times" << std::endl
<< "Inline depth: " << cfg.vm.jit.maxInlineDepth << std::endl
<< "Call Style: " << cfg.vm.jit.callStyle;
}
/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
std::size_t i = 1;
for (; i < argc; i++) {
const char *arg = argv[i];
if (strcmp(arg, "-help") == 0) {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
}
else if (strcmp(arg, "-loop") == 0) {
cfg.loopCount = atoi(argv[++i]);
}
else if (strcmp(arg, "-inline") == 0) {
cfg.vm.jit.maxInlineDepth = atoi(argv[++i]);
}
else if (strcmp(arg, "-verbose") == 0) {
std::cout << "verbose is enabled" << std::endl;
cfg.verbose = true;
cfg.vm.verbose = true;
cfg.vm.jit.verbose = true;
}
else if (strcmp(arg, "-debug") == 0) {
cfg.vm.debug = true;
cfg.vm.jit.debug = true;
}
else if (strcmp(arg, "-callstyle") == 0) {
i += 1;
auto callStyle = argv[i];
if (strcmp("interpreter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::interpreter;
}
else if (strcmp("direct", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::direct;
}
else if (strcmp("passparameter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::passParameter;
}
else if (strcmp("operandstack", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::operandStack;
}
}
else if (strcmp(arg, "-program") == 0) {
cfg.mainFunction = argv[++i];
}
else if (strcmp(arg, "--") == 0) {
i++;
break;
}
else if (strcmp(arg, "-") == 0) {
std::cerr << "Unrecognized option: " << arg << std::endl;
return false;
}
else {
break;
}
}
// positional
if (i < argc) {
cfg.module = argv[i++];
if (i < argc) {
cfg.mainFunction = argv[i++];
}
}
return true;
}
static bool run(const RunConfig& cfg) {
b9::VirtualMachine virtualMachine{cfg.vm};
virtualMachine.initialize();
b9::DlLoader loader(true);
auto module = loader.loadModule(cfg.module);
return true;
#if 0
b9::VirtualMachine virtualMachine;
char sharelib[128];
virtualMachine.initialize();
if (!virtualMachine.loadLibrary()) {
return EXIT_FAILURE;
}
b9::Instruction *function = virtualMachine.getFunctionAddress(mainFunction);
if (function == nullptr) {
return EXIT_FAILURE;
}
b9::StackElement resultInterp = 0;
b9::StackElement resultJit = 0;
long timeInterp = 0;
long timeJIT = 0;
printf("Running Interpreted");
// printf(
// "Options: DirectCall (%d), DirectParameterPassing (%d), "
// "UseVMOperandStack (%d)\n",
// virtualMachine.directCall_, virtualMachine.passParameters_, virtualMachine.operandStack_);
resultInterp =
timeFunction(&virtualMachine, function, 1, &timeInterp);
printf("Running JIT looping %d times\n", 1);
//generateAllCode(&context);
//resultJit = timeFunction(&context, function, context.loopCount, &timeJIT);
printf("Result for Interp is %lld, resultJit is %lld\n", resultInterp, resultJit);
printf("Time for Interp %ld ms, JIT %ld ms\n", timeInterp, timeJIT);
printf("JIT speedup = %f\n", timeInterp * 1.0 / timeJIT);
if (resultInterp == resultJit) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
#endif // 0
}
int main(int argc, char* argv[]) {
RunConfig cfg;
if (!parseArguments(cfg, argc, argv)) {
exit(EXIT_FAILURE);
}
if (cfg.verbose) {
std::cout << cfg << std::endl;
}
if (!run(cfg)) {
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -Xclang -verify
// XFAIL: *
// The test exposes a weakness in the declaration extraction of types. As
// reported in issue ROOT-5248.
class MyClass;
extern MyClass* my;
class MyClass {
public:
MyClass* getMyClass() {
return 0;
}
} cl;
// The next line should work without complaints!
MyClass* my = cl.getMyClass();
<commit_msg>This is now passing, actually.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -Xclang -verify
// The test exposes a weakness in the declaration extraction of types. As
// reported in issue ROOT-5248.
class MyClass;
extern MyClass* my;
class MyClass {
public:
MyClass* getMyClass() {
return 0;
}
} cl;
// The next line should work without complaints!
MyClass* my = cl.getMyClass();
<|endoftext|> |
<commit_before>// matrixMultiplication.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
//0 - podanych macierzy nie mona pomnoy
//1 - wszystko poszo zgodnie z planem - macierz pomnoona
//RM - ResultMatrix
int matrixMultiplication(float **firstMatrix, float **secondMatrix, int FMRows, int FMColumns, int SMRows, int SMColumns, float **resultMatrix)
{
//Sprawdzenie czy macierze mona mnoy
if (FMColumns != SMRows) return 0;
//Stworzenie wymiarw nowej macierzy
int RMRows = FMRows;
int RMColumns = SMColumns;
//Alokacja pamici nowej macierzy
resultMatrix = (float **)malloc(RMRows*sizeof(float *));
for (int i = 0; i < RMRows; i++)
{
resultMatrix[i] = (float *)malloc(RMColumns*sizeof(float));
}
//Przypisanie wartoci do zaalokowanej tablicy
printf("\nResult matrix:\n");
int link = FMColumns;
float out;
for (int i = 0; i < RMRows; i++)
{
for (int j = 0; j < RMColumns; j++)
{
out = 0;
for (int x = 0; x < link; x++)
{
out += firstMatrix[i][x] * secondMatrix[x][j];
}
resultMatrix[i][j] = out;
printf("%.2f ", resultMatrix[i][j]);
}
printf("\n");
}
return 1;
}
int main()
{
//###Czytanie z pliku###
//Deklaracja plikw
FILE *firstMatrixFile, *secondMatrixFile, *outputFile;
//Zmienne do danych z plikw {FM - FirstMatrix | SM - SecondMatrix}
int FMRows=0, FMColumns=0, SMRows=0, SMColumns=0;
//Otwarcie plikw do odczytu
if ((firstMatrixFile = fopen("firstMatrixFile.txt", "r")) == NULL) {
printf("Nie mog otworzy pliku firstMatrixFile.txt!\n");
exit(1);
}
if ((secondMatrixFile = fopen("secondMatrixFile.txt", "r")) == NULL) {
printf("Nie mog otworzy pliku secondMatrixFile.txt!\n");
exit(1);
}
if ((outputFile = fopen("resultMatrix.txt", "w")) == NULL) {
printf("Nie mog otworzy pliku resultMatrix.txt!\n");
exit(1);
}
//Okrelenie dugoci wierszy i kolumn
fscanf(firstMatrixFile, "%d", &FMRows);
fscanf(firstMatrixFile, "%d", &FMColumns);
fscanf(secondMatrixFile, "%d", &SMRows);
fscanf(secondMatrixFile, "%d", &SMColumns);
//Alokacja pamici
//First matrix
float **firstMatrix = (float **)malloc(FMRows*sizeof(float *));
for (int i = 0; i < FMRows; i++)
{
firstMatrix[i] = (float *)malloc(FMColumns*sizeof(float));
}
//Second matrix
float **secondMatrix = (float **)malloc(SMRows*sizeof(float *));
for (int i = 0; i < SMRows; i++)
{
secondMatrix[i] = (float *)malloc(SMColumns*sizeof(float));
}
//Czytanie po caych plikach i zapisanie danych do odpowiednich tablic
//First Matrix
printf("First matrix:\n");
for (int i = 0; i < FMRows; i++)
{
for (int j = 0; j < FMColumns; j++)
{
fscanf(firstMatrixFile, "%f", &firstMatrix[i][j]);
printf("%.2f ", firstMatrix[i][j]);
}
printf("\n");
}
//Second Matrix
printf("\nSecond matrix:\n");
for (int i = 0; i < SMRows; i++)
{
for (int j = 0; j < SMColumns; j++)
{
fscanf(secondMatrixFile, "%f", &secondMatrix[i][j]);
printf("%.2f ", secondMatrix[i][j]);
}
printf("\n");
}
//MNOENIE
float **resultMatrix = 0;
matrixMultiplication(firstMatrix, secondMatrix, FMRows, FMColumns, SMRows, SMColumns, resultMatrix);
//fprintf(fp, "%s", tekst); /* zapisz nasz acuch w pliku */
//Zwolnienie pamici
//First matrix
for (int i = 0; i < FMRows; i++)
{
free(firstMatrix[i]);
}
free(firstMatrix);
//Second matrix
for (int i = 0; i < SMRows; i++)
{
free(secondMatrix[i]);
}
free(secondMatrix);
//Zamknicie plikw
fclose(firstMatrixFile);
fclose(secondMatrixFile);
system("pause");
return 0;
}
<commit_msg>Added not finished safe of matrix to file.<commit_after>// matrixMultiplication.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
//0 - podanych macierzy nie mona pomnoy
//1 - wszystko poszo zgodnie z planem - macierz pomnoona
//RM - ResultMatrix
int matrixMultiplication(float **firstMatrix, float **secondMatrix, int FMRows, int FMColumns, int SMRows, int SMColumns, float **resultMatrix, float *RMRows, float *RMColumns)
{
//Sprawdzenie czy macierze mona mnoy
if (FMColumns != SMRows) return 0;
//Stworzenie wymiarw nowej macierzy
*RMRows = FMRows;
*RMColumns = SMColumns;
//Alokacja pamici nowej macierzy
resultMatrix = (float **)malloc(*RMRows*sizeof(float *));
for (int i = 0; i < *RMRows; i++)
{
resultMatrix[i] = (float *)malloc(*RMColumns*sizeof(float));
}
//Przypisanie wartoci do zaalokowanej tablicy
printf("\nResult matrix:\n");
int link = FMColumns;
float out;
for (int i = 0; i < *RMRows; i++)
{
for (int j = 0; j < *RMColumns; j++)
{
out = 0;
for (int x = 0; x < link; x++)
{
out += firstMatrix[i][x] * secondMatrix[x][j];
}
resultMatrix[i][j] = out;
printf("%.2f ", resultMatrix[i][j]);
}
printf("\n");
}
return 1;
}
int main()
{
//###Czytanie z pliku###
//Deklaracja plikw
FILE *firstMatrixFile, *secondMatrixFile, *outputFile;
//Zmienne do danych z plikw {FM - FirstMatrix | SM - SecondMatrix}
int FMRows=0, FMColumns=0, SMRows=0, SMColumns=0;
//Otwarcie plikw do odczytu
if ((firstMatrixFile = fopen("firstMatrixFile.txt", "r")) == NULL) {
printf("Nie mog otworzy pliku firstMatrixFile.txt!\n");
exit(1);
}
if ((secondMatrixFile = fopen("secondMatrixFile.txt", "r")) == NULL) {
printf("Nie mog otworzy pliku secondMatrixFile.txt!\n");
exit(1);
}
if ((outputFile = fopen("resultMatrix.txt", "w")) == NULL) {
printf("Nie mog otworzy pliku resultMatrix.txt!\n");
exit(1);
}
//Okrelenie dugoci wierszy i kolumn
fscanf(firstMatrixFile, "%d", &FMRows);
fscanf(firstMatrixFile, "%d", &FMColumns);
fscanf(secondMatrixFile, "%d", &SMRows);
fscanf(secondMatrixFile, "%d", &SMColumns);
//Alokacja pamici
//First matrix
float **firstMatrix = (float **)malloc(FMRows*sizeof(float *));
for (int i = 0; i < FMRows; i++)
{
firstMatrix[i] = (float *)malloc(FMColumns*sizeof(float));
}
//Second matrix
float **secondMatrix = (float **)malloc(SMRows*sizeof(float *));
for (int i = 0; i < SMRows; i++)
{
secondMatrix[i] = (float *)malloc(SMColumns*sizeof(float));
}
//Czytanie po caych plikach i zapisanie danych do odpowiednich tablic
//First Matrix
printf("First matrix:\n");
for (int i = 0; i < FMRows; i++)
{
for (int j = 0; j < FMColumns; j++)
{
fscanf(firstMatrixFile, "%f", &firstMatrix[i][j]);
printf("%.2f ", firstMatrix[i][j]);
}
printf("\n");
}
//Second Matrix
printf("\nSecond matrix:\n");
for (int i = 0; i < SMRows; i++)
{
for (int j = 0; j < SMColumns; j++)
{
fscanf(secondMatrixFile, "%f", &secondMatrix[i][j]);
printf("%.2f ", secondMatrix[i][j]);
}
printf("\n");
}
//MNOENIE
float **resultMatrix = 0;
float RMRows = 0, RMColumns = 0;
matrixMultiplication(firstMatrix, secondMatrix, FMRows, FMColumns, SMRows, SMColumns, resultMatrix, &RMRows, &RMColumns);
//Zapisanie wyniku do pliku
//Wymiary macierzy
fprintf(outputFile, "%d ", RMRows);
fprintf(outputFile, "%d", RMColumns);
//Zawarto macierzy
for (int i = 0; i < RMRows; i++)
{
for (int j = 0; j < RMColumns; j++)
{
//TODO: THIS PART DONT WORK
fprintf(outputFile, "%.2f", resultMatrix[0][1]);
}
fprintf(outputFile, "\n");
}
//fprintf(fp, "%s", tekst); /* zapisz nasz acuch w pliku */
//Zwolnienie pamici
//First matrix
for (int i = 0; i < FMRows; i++)
{
free(firstMatrix[i]);
}
free(firstMatrix);
//Second matrix
for (int i = 0; i < SMRows; i++)
{
free(secondMatrix[i]);
}
free(secondMatrix);
//Zamknicie plikw
fclose(firstMatrixFile);
fclose(secondMatrixFile);
fclose(outputFile);
system("pause");
return 0;
}
<|endoftext|> |
<commit_before>#include <catch2/catch.hpp>
#include <higanbana/core/system/time.hpp>
#include <vector>
#include <thread>
#include <future>
#include <optional>
#include <cstdio>
#include <iostream>
#include <experimental/coroutine>
class SuperLBS
{
//std::vector<std::thread> m_threads;
};
struct suspend_never {
constexpr bool await_ready() const noexcept { return true; }
void await_suspend(std::experimental::coroutine_handle<>) const noexcept {}
constexpr void await_resume() const noexcept {}
};
struct suspend_always {
constexpr bool await_ready() const noexcept { return false; }
void await_suspend(std::experimental::coroutine_handle<>) const noexcept {}
constexpr void await_resume() const noexcept {}
};
class resumable {
public:
struct promise_type {
using coro_handle = std::experimental::coroutine_handle<promise_type>;
auto get_return_object() {
return coro_handle::from_promise(*this);
}
auto initial_suspend() { return suspend_always(); }
auto final_suspend() noexcept { return suspend_always(); }
void return_void() {}
void unhandled_exception() {
std::terminate();
}
};
using coro_handle = std::experimental::coroutine_handle<promise_type>;
resumable(coro_handle handle) : handle_(handle)
{
static int woot = 0;
ver = woot++;
printf("resumable created %d \n", ver);
assert(handle);
}
resumable(resumable& other) = delete;
resumable(resumable&& other) : handle_(std::move(other.handle_)) {
assert(handle_);
other.handle_ = nullptr;
}
bool resume() noexcept {
if (res > 0) {
res = res - 1;
return !handle_.done();
}
if (!handle_.done())
handle_.resume();
return !handle_.done();
}
// coroutine meat
void await_resume() noexcept {
printf("resumable await_resume%d \n", ver);
resume();
}
bool await_ready() noexcept {
printf("resumable await_ready%d \n", ver);
return handle_.done();
}
// enemy coroutine needs this coroutines result, therefore we compute it.
void await_suspend(coro_handle handle) noexcept {
printf("resumable await_suspend%d \n", ver);
while(resume());
}
// :o
~resumable() { if (handle_) handle_.destroy(); }
private:
coro_handle handle_;
int ver;
int res = 2;
};
resumable hehe_suspendi(int i){
std::cout << "suspendddd " << i << std::endl;
co_await suspend_always();
std::cout << "finishhhhh " << i << std::endl;
}
resumable hehe_suspend2(){
std::cout << "suspendddd2" << std::endl;
co_await hehe_suspendi(3);
std::cout << "finishhhhh2" << std::endl;
}
resumable hehe_suspend(){
std::cout << "suspendddd" << std::endl;
co_await hehe_suspend2();
std::cout << "finishhhhh" << std::endl;
}
resumable foo(){
std::cout << "Hello" << std::endl;
co_await hehe_suspend();
std::cout << "middle hello" << std::endl;
co_await hehe_suspend();
std::cout << "Coroutine" << std::endl;
}
TEST_CASE("c++ threading")
{
resumable res = foo();
std::cout << "created resumable" << std::endl;
while (res.resume()) {std::cout << "resume coroutines!!" << std::endl;}
}
int addInTreeNormal(int treeDepth) {
if (treeDepth <= 0)
return 1;
int sum = 0;
sum += addInTreeNormal(treeDepth-1);
sum += addInTreeNormal(treeDepth-1);
return sum;
}
std::future<int> addInTreeAsync(int treeDepth) {
if (treeDepth <= 0)
co_return 1;
int result=0;
result += co_await addInTreeAsync(treeDepth-1);
result += co_await addInTreeAsync(treeDepth-1);
co_return result;
}
TEST_CASE("simple recursive async")
{
int treeSize = 20;
higanbana::Timer time;
int basecase = addInTreeNormal(treeSize);
auto normalTime = time.reset();
int futured = addInTreeAsync(treeSize).get();
auto asyncTime = time.reset();
REQUIRE(basecase == futured);
printf("normal %.3fms vs coroutined %.3fms\n", normalTime/1000.f/1000.f, asyncTime/1000.f/1000.f);
}
template<typename T>
class my_future {
public:
struct promise_type {
using coro_handle = std::experimental::coroutine_handle<promise_type>;
auto get_return_object() {
return coro_handle::from_promise(*this);
}
auto initial_suspend() { return suspend_always(); }
auto final_suspend() noexcept { return suspend_always(); }
void return_value(T value) {m_value = value;}
void unhandled_exception() {
std::terminate();
}
T m_value;
};
using coro_handle = std::experimental::coroutine_handle<promise_type>;
my_future(coro_handle handle) : handle_(handle)
{
assert(handle);
}
my_future(my_future& other) = delete;
my_future(my_future&& other) : handle_(std::move(other.handle_)) {
assert(handle_);
other.handle_ = nullptr;
}
bool resume() noexcept {
if (!handle_.done())
handle_.resume();
return !handle_.done();
}
// coroutine meat
T await_resume() noexcept {
while(resume());
return handle_.promise().m_value;
}
bool await_ready() noexcept {
return handle_.done();
}
// enemy coroutine needs this coroutines result, therefore we compute it.
void await_suspend(coro_handle handle) noexcept {
while(resume());
}
// :o
~my_future() { if (handle_) handle_.destroy(); }
T get()
{
while(resume());
assert(handle_.done());
return handle_.promise().m_value;
}
private:
coro_handle handle_;
};
template<>
class my_future<void> {
public:
struct promise_type {
using coro_handle = std::experimental::coroutine_handle<promise_type>;
auto get_return_object() {
return coro_handle::from_promise(*this);
}
auto initial_suspend() { return suspend_always(); }
auto final_suspend() noexcept { return suspend_always(); }
void return_void() {}
void unhandled_exception() {
std::terminate();
}
};
using coro_handle = std::experimental::coroutine_handle<promise_type>;
my_future(coro_handle handle) : handle_(handle)
{
assert(handle);
}
my_future(my_future& other) = delete;
my_future(my_future&& other) : handle_(std::move(other.handle_)) {
assert(handle_);
other.handle_ = nullptr;
}
bool resume() noexcept {
if (!handle_.done())
handle_.resume();
return !handle_.done();
}
// coroutine meat
void await_resume() noexcept {
while(resume());
}
bool await_ready() noexcept {
return handle_.done();
}
// enemy coroutine needs this coroutines result, therefore we compute it.
void await_suspend(coro_handle handle) noexcept {
while(resume());
}
// :o
~my_future() { if (handle_) handle_.destroy(); }
private:
coro_handle handle_;
};
my_future<int> funfun() {
co_return 1;
}
my_future<void> funfun2() {
printf("woot\n");
co_return;
}
my_future<int> addInTreeAsync2(int treeDepth) {
if (treeDepth <= 0)
co_return 1;
int result=0;
result += co_await addInTreeAsync2(treeDepth-1);
result += co_await addInTreeAsync2(treeDepth-1);
co_return result;
}
TEST_CASE("simple my future")
{
auto fut = funfun().get();
REQUIRE(fut == 1);
funfun2().resume();
printf("had value in my future %d\n", fut);
int treeSize = 20;
higanbana::Timer time;
int basecase = addInTreeNormal(treeSize);
time.reset();
int futured2 = addInTreeAsync2(treeSize).get();
auto asyncTime2 = time.reset();
REQUIRE(basecase == futured2);
printf("my_future %.3fms\n", asyncTime2/1000.f/1000.f);
}<commit_msg>changed name to awaitable and included the await_transform function<commit_after>#include <catch2/catch.hpp>
#include <higanbana/core/system/time.hpp>
#include <vector>
#include <thread>
#include <future>
#include <optional>
#include <cstdio>
#include <iostream>
#include <experimental/coroutine>
class SuperLBS
{
//std::vector<std::thread> m_threads;
};
struct suspend_never {
constexpr bool await_ready() const noexcept { return true; }
void await_suspend(std::experimental::coroutine_handle<>) const noexcept {}
constexpr void await_resume() const noexcept {}
};
struct suspend_always {
constexpr bool await_ready() const noexcept { return false; }
void await_suspend(std::experimental::coroutine_handle<>) const noexcept {}
constexpr void await_resume() const noexcept {}
};
class resumable {
public:
struct promise_type {
using coro_handle = std::experimental::coroutine_handle<promise_type>;
auto get_return_object() {
return coro_handle::from_promise(*this);
}
auto initial_suspend() { return suspend_always(); }
auto final_suspend() noexcept { return suspend_always(); }
void return_void() {}
void unhandled_exception() {
std::terminate();
}
};
using coro_handle = std::experimental::coroutine_handle<promise_type>;
resumable(coro_handle handle) : handle_(handle)
{
static int woot = 0;
ver = woot++;
printf("resumable created %d \n", ver);
assert(handle);
}
resumable(resumable& other) = delete;
resumable(resumable&& other) : handle_(std::move(other.handle_)) {
assert(handle_);
other.handle_ = nullptr;
}
bool resume() noexcept {
if (res > 0) {
res = res - 1;
return !handle_.done();
}
if (!handle_.done())
handle_.resume();
return !handle_.done();
}
// coroutine meat
void await_resume() noexcept {
printf("resumable await_resume%d \n", ver);
resume();
}
bool await_ready() noexcept {
printf("resumable await_ready%d \n", ver);
return handle_.done();
}
// enemy coroutine needs this coroutines result, therefore we compute it.
void await_suspend(coro_handle handle) noexcept {
printf("resumable await_suspend%d \n", ver);
while(resume());
}
// :o
~resumable() { if (handle_) handle_.destroy(); }
private:
coro_handle handle_;
int ver;
int res = 2;
};
resumable hehe_suspendi(int i){
std::cout << "suspendddd " << i << std::endl;
co_await suspend_always();
std::cout << "finishhhhh " << i << std::endl;
}
resumable hehe_suspend2(){
std::cout << "suspendddd2" << std::endl;
co_await hehe_suspendi(3);
std::cout << "finishhhhh2" << std::endl;
}
resumable hehe_suspend(){
std::cout << "suspendddd" << std::endl;
co_await hehe_suspend2();
std::cout << "finishhhhh" << std::endl;
}
resumable foo(){
std::cout << "Hello" << std::endl;
co_await hehe_suspend();
std::cout << "middle hello" << std::endl;
co_await hehe_suspend();
std::cout << "Coroutine" << std::endl;
}
TEST_CASE("c++ threading")
{
resumable res = foo();
std::cout << "created resumable" << std::endl;
while (res.resume()) {std::cout << "resume coroutines!!" << std::endl;}
}
int addInTreeNormal(int treeDepth) {
if (treeDepth <= 0)
return 1;
int sum = 0;
sum += addInTreeNormal(treeDepth-1);
sum += addInTreeNormal(treeDepth-1);
return sum;
}
std::future<int> addInTreeAsync(int treeDepth) {
if (treeDepth <= 0)
co_return 1;
int result=0;
result += co_await addInTreeAsync(treeDepth-1);
result += co_await addInTreeAsync(treeDepth-1);
co_return result;
}
TEST_CASE("simple recursive async")
{
int treeSize = 20;
higanbana::Timer time;
int basecase = addInTreeNormal(treeSize);
auto normalTime = time.reset();
int futured = addInTreeAsync(treeSize).get();
auto asyncTime = time.reset();
REQUIRE(basecase == futured);
printf("normal %.3fms vs coroutined %.3fms\n", normalTime/1000.f/1000.f, asyncTime/1000.f/1000.f);
}
template<typename T>
class awaitable {
public:
struct promise_type {
using coro_handle = std::experimental::coroutine_handle<promise_type>;
auto get_return_object() {
return coro_handle::from_promise(*this);
}
auto initial_suspend() { return suspend_always(); }
auto final_suspend() noexcept { return suspend_always(); }
void return_value(T value) {m_value = value;}
void unhandled_exception() {
std::terminate();
}
auto await_transform(awaitable<T> handle) {
return handle;
}
T m_value;
};
using coro_handle = std::experimental::coroutine_handle<promise_type>;
awaitable(coro_handle handle) : handle_(handle)
{
assert(handle);
}
awaitable(awaitable& other) = delete;
awaitable(awaitable&& other) : handle_(std::move(other.handle_)) {
assert(handle_);
other.handle_ = nullptr;
}
bool resume() noexcept {
if (!handle_.done())
handle_.resume();
return !handle_.done();
}
// coroutine meat
T await_resume() noexcept {
while(resume());
return handle_.promise().m_value;
}
bool await_ready() noexcept {
return handle_.done();
}
// enemy coroutine needs this coroutines result, therefore we compute it.
void await_suspend(coro_handle handle) noexcept {
while(resume());
}
// :o
~awaitable() { if (handle_) handle_.destroy(); }
T get()
{
while(resume());
assert(handle_.done());
return handle_.promise().m_value;
}
private:
coro_handle handle_;
};
template<>
class awaitable<void> {
public:
struct promise_type {
using coro_handle = std::experimental::coroutine_handle<promise_type>;
auto get_return_object() {
return coro_handle::from_promise(*this);
}
auto initial_suspend() { return suspend_always(); }
auto final_suspend() noexcept { return suspend_always(); }
void return_void() {}
void unhandled_exception() {
std::terminate();
}
auto await_transform(awaitable<void> handle) {
return handle;
}
};
using coro_handle = std::experimental::coroutine_handle<promise_type>;
awaitable(coro_handle handle) : handle_(handle)
{
assert(handle);
}
awaitable(awaitable& other) = delete;
awaitable(awaitable&& other) : handle_(std::move(other.handle_)) {
assert(handle_);
other.handle_ = nullptr;
}
bool resume() noexcept {
if (!handle_.done())
handle_.resume();
return !handle_.done();
}
// coroutine meat
void await_resume() noexcept {
while(resume());
}
bool await_ready() noexcept {
return handle_.done();
}
// enemy coroutine needs this coroutines result, therefore we compute it.
void await_suspend(coro_handle handle) noexcept {
while(resume());
}
// :o
~awaitable() { if (handle_) handle_.destroy(); }
private:
coro_handle handle_;
};
awaitable<int> funfun() {
co_return 1;
}
awaitable<void> funfun2() {
printf("woot\n");
co_return;
}
awaitable<int> addInTreeAsync2(int treeDepth) {
if (treeDepth <= 0)
co_return 1;
int result=0;
result += co_await addInTreeAsync2(treeDepth-1);
result += co_await addInTreeAsync2(treeDepth-1);
co_return result;
}
TEST_CASE("simple my future")
{
auto fut = funfun().get();
REQUIRE(fut == 1);
funfun2().resume();
printf("had value in my future %d\n", fut);
int treeSize = 20;
higanbana::Timer time;
int basecase = addInTreeNormal(treeSize);
time.reset();
int futured2 = addInTreeAsync2(treeSize).get();
auto asyncTime2 = time.reset();
REQUIRE(basecase == futured2);
printf("my_future %.3fms\n", asyncTime2/1000.f/1000.f);
}<|endoftext|> |
<commit_before>#pragma once
constexpr double CESIUS_MIN = -273.15;
constexpr double KELVIN_MIN = 0;
constexpr double FAHRENHEIT_MIN = -459.67;
class TemperatureConverter
{
public:
// TemperatureConverter();
double celsiusToKelvin(const double& celsius);
double kelvinToCelsius(const double& celsius);
double celsiusToFahrenheit(const double& celsius);
double fahrenheitToCelsius(const double& celsius);
};
<commit_msg>Removing comment<commit_after>#pragma once
constexpr double CESIUS_MIN = -273.15;
constexpr double KELVIN_MIN = 0;
constexpr double FAHRENHEIT_MIN = -459.67;
class TemperatureConverter
{
public:
double celsiusToKelvin(const double& celsius);
double kelvinToCelsius(const double& celsius);
double celsiusToFahrenheit(const double& celsius);
double fahrenheitToCelsius(const double& celsius);
};
<|endoftext|> |
<commit_before>#include "Config.hpp"
#include "EventOutputQueue.hpp"
#include "PointingRelativeToScroll.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
List* PointingRelativeToScroll::queue_ = NULL;
Flags PointingRelativeToScroll::currentFromFlags_ = NULL;
TimerWrapper PointingRelativeToScroll::timer_;
void
PointingRelativeToScroll::static_initialize(IOWorkLoop& workloop)
{
queue_ = new List();
timer_.initialize(&workloop, NULL, PointingRelativeToScroll::callback);
}
void
PointingRelativeToScroll::static_terminate(void)
{
timer_.terminate();
if (queue_) {
delete queue_;
}
}
void
PointingRelativeToScroll::cancelScroll(void)
{
timer_.cancelTimeout();
if (queue_) {
queue_->clear();
}
}
PointingRelativeToScroll::PointingRelativeToScroll(void) : index_(0)
{}
PointingRelativeToScroll::~PointingRelativeToScroll(void)
{}
void
PointingRelativeToScroll::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_FLAGS:
{
fromFlags_ = newval;
break;
}
case BRIDGE_DATATYPE_POINTINGBUTTON:
{
fromButton_ = newval;
break;
}
default:
IOLOG_ERROR("PointingRelativeToScroll::add invalid datatype:%d\n", datatype);
break;
}
}
bool
PointingRelativeToScroll::remap(RemapPointingParams_relative& remapParams)
{
bool active = fromkeychecker_.isactive();
if (remapParams.isremapped) return false;
if (fromButton_ == PointingButton::NONE) {
if (! FlagStatus::makeFlags().isOn(fromFlags_)) return false;
} else {
if (! fromkeychecker_.isFromPointingButton(remapParams.params, fromButton_, fromFlags_) && ! active) return false;
}
remapParams.isremapped = true;
if (fromButton_ == PointingButton::NONE) {
goto doremap;
}
// first time
if (! active) {
// if the source buttons contains left button, we cancel left click for iPhoto, or some applications.
// iPhoto store the scroll events when left button is pressed, and restore events after left button is released.
// PointingRelativeToScroll doesn't aim it, we release the left button and do normal scroll event.
ButtonStatus::decrease(fromButton_);
EventOutputQueue::FireRelativePointer::fire();
ButtonStatus::increase(fromButton_);
absolute_distance_ = 0;
begin_ic_.begin();
chained_ic_.begin();
chained_delta1_ = 0;
chained_delta2_ = 0;
goto doremap;
}
// last time
if (! fromkeychecker_.isactive()) {
cancelScroll();
const uint32_t DISTANCE_THRESHOLD = 5;
const uint32_t TIME_THRESHOLD = 300;
if (absolute_distance_ <= DISTANCE_THRESHOLD && begin_ic_.getmillisec() < TIME_THRESHOLD) {
// Fire by a click event.
ButtonStatus::increase(fromButton_);
EventOutputQueue::FireRelativePointer::fire();
ButtonStatus::decrease(fromButton_);
EventOutputQueue::FireRelativePointer::fire();
}
return true;
}
doremap:
toscroll(remapParams);
return true;
}
void
PointingRelativeToScroll::toscroll(RemapPointingParams_relative& remapParams)
{
if (! queue_) return;
// ----------------------------------------
const uint32_t CANCEL_THRESHOLD = 100;
if (chained_ic_.getmillisec() > CANCEL_THRESHOLD) {
chained_delta1_ = 0;
chained_delta2_ = 0;
cancelScroll();
}
int delta1 = -remapParams.params.dy;
int delta2 = -remapParams.params.dx;
chained_ic_.begin();
// ----------------------------------------
if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_disable_vertical_scroll)) delta1 = 0;
if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_disable_horizontal_scroll)) delta2 = 0;
// ----------------------------------------
// ignore minuscule move
const unsigned int abs1 = abs(delta1);
const unsigned int abs2 = abs(delta2);
if (abs1 > abs2 * 2) {
delta2 = 0;
}
if (abs2 > abs1 * 2) {
delta1 = 0;
}
// ----------------------------------------
// Fixation processing
if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_enable_scrollwheel_fixation)) {
// When 300ms passes from the last event, we reset a value.
const uint32_t FIXATION_MILLISEC = 300;
if (fixation_ic_.getmillisec() > FIXATION_MILLISEC) {
fixation_begin_ic_.begin();
fixation_delta1_ = 0;
fixation_delta2_ = 0;
}
fixation_ic_.begin();
if (fixation_delta1_ > fixation_delta2_ * 2) {
delta2 = 0;
}
if (fixation_delta2_ > fixation_delta1_ * 2) {
delta1 = 0;
}
// Only first 1000ms performs the addition of fixation_delta1, fixation_delta2.
const uint32_t FIXATION_EARLY_MILLISEC = 1000;
if (fixation_begin_ic_.getmillisec() < FIXATION_EARLY_MILLISEC) {
if (delta1 == 0) fixation_delta2_ += abs2;
if (delta2 == 0) fixation_delta1_ += abs1;
}
}
// ------------------------------------------------------------
// when sign is different
if (0 > delta1 * chained_delta1_ ||
0 > delta2 * chained_delta2_) {
queue_->clear();
chained_delta1_ = delta1;
chained_delta2_ = delta2;
} else if (abs(delta1) > abs(chained_delta1_) ||
abs(delta2) > abs(chained_delta2_)) {
// greater delta.
chained_delta1_ = delta1;
chained_delta2_ = delta2;
}
absolute_distance_ += abs(chained_delta1_) + abs(chained_delta2_);
queue_->push_back(new Item(chained_delta1_ * EventOutputQueue::FireScrollWheel::DELTA_SCALE, chained_delta2_ * EventOutputQueue::FireScrollWheel::DELTA_SCALE));
currentFromFlags_ = fromFlags_;
timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
}
void
PointingRelativeToScroll::callback(OSObject* owner, IOTimerEventSource* sender)
{
IOLockWrapper::ScopedLock lk(timer_.getlock());
if (! queue_) return;
// ----------------------------------------
int delta1 = 0;
int delta2 = 0;
{
Item* p = static_cast<Item*>(queue_->front());
if (! p) return;
delta1 = p->delta1;
delta2 = p->delta2;
queue_->pop_front();
}
// ----------------------------------------
FlagStatus::temporary_decrease(currentFromFlags_);
EventOutputQueue::FireScrollWheel::fire(delta1, delta2);
// We need to call temporary_increase.
// Because when SimultaneousKeyPresses is enabled, temporary flags will be reset in unexpected timing.
// So, we need to restore temporary flags explicitly.
FlagStatus::temporary_increase(currentFromFlags_);
// ----------------------------------------
if (! Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_disable_momentum_scroll)) {
if (delta1 != 0 || delta2 != 0) {
queue_->push_back(new Item(delta1 / 2, delta2 / 2));
}
}
timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
}
}
}
<commit_msg>cleanup PointingRelativeToScroll<commit_after>#include "Config.hpp"
#include "EventOutputQueue.hpp"
#include "PointingRelativeToScroll.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
List* PointingRelativeToScroll::queue_ = NULL;
Flags PointingRelativeToScroll::currentFromFlags_ = NULL;
TimerWrapper PointingRelativeToScroll::timer_;
void
PointingRelativeToScroll::static_initialize(IOWorkLoop& workloop)
{
queue_ = new List();
timer_.initialize(&workloop, NULL, PointingRelativeToScroll::callback);
}
void
PointingRelativeToScroll::static_terminate(void)
{
timer_.terminate();
if (queue_) {
delete queue_;
}
}
void
PointingRelativeToScroll::cancelScroll(void)
{
timer_.cancelTimeout();
if (queue_) {
queue_->clear();
}
}
PointingRelativeToScroll::PointingRelativeToScroll(void) : index_(0)
{}
PointingRelativeToScroll::~PointingRelativeToScroll(void)
{}
void
PointingRelativeToScroll::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_FLAGS:
{
fromFlags_ = newval;
break;
}
case BRIDGE_DATATYPE_POINTINGBUTTON:
{
fromButton_ = newval;
break;
}
default:
IOLOG_ERROR("PointingRelativeToScroll::add invalid datatype:%d\n", datatype);
break;
}
}
bool
PointingRelativeToScroll::remap(RemapPointingParams_relative& remapParams)
{
bool active = fromkeychecker_.isactive();
if (remapParams.isremapped) return false;
if (fromButton_ == PointingButton::NONE) {
if (! FlagStatus::makeFlags().isOn(fromFlags_)) return false;
} else {
if (! fromkeychecker_.isFromPointingButton(remapParams.params, fromButton_, fromFlags_) && ! active) return false;
}
remapParams.isremapped = true;
if (fromButton_ == PointingButton::NONE) {
goto doremap;
}
// first time
if (! active) {
// if the source buttons contains left button, we cancel left click for iPhoto, or some applications.
// iPhoto store the scroll events when left button is pressed, and restore events after left button is released.
// PointingRelativeToScroll doesn't aim it, we release the left button and do normal scroll event.
ButtonStatus::decrease(fromButton_);
EventOutputQueue::FireRelativePointer::fire();
ButtonStatus::increase(fromButton_);
absolute_distance_ = 0;
begin_ic_.begin();
chained_ic_.begin();
chained_delta1_ = 0;
chained_delta2_ = 0;
goto doremap;
}
// last time
if (! fromkeychecker_.isactive()) {
cancelScroll();
const uint32_t DISTANCE_THRESHOLD = 5;
const uint32_t TIME_THRESHOLD = 300;
if (absolute_distance_ <= DISTANCE_THRESHOLD && begin_ic_.getmillisec() < TIME_THRESHOLD) {
// Fire by a click event.
ButtonStatus::increase(fromButton_);
EventOutputQueue::FireRelativePointer::fire();
ButtonStatus::decrease(fromButton_);
EventOutputQueue::FireRelativePointer::fire();
}
return true;
}
doremap:
toscroll(remapParams);
return true;
}
void
PointingRelativeToScroll::toscroll(RemapPointingParams_relative& remapParams)
{
if (! queue_) return;
// ----------------------------------------
const uint32_t CANCEL_THRESHOLD = 100;
if (chained_ic_.getmillisec() > CANCEL_THRESHOLD) {
chained_delta1_ = 0;
chained_delta2_ = 0;
cancelScroll();
}
int delta1 = -remapParams.params.dy;
int delta2 = -remapParams.params.dx;
chained_ic_.begin();
// ----------------------------------------
if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_disable_vertical_scroll)) delta1 = 0;
if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_disable_horizontal_scroll)) delta2 = 0;
// ----------------------------------------
// ignore minuscule move
const unsigned int abs1 = abs(delta1);
const unsigned int abs2 = abs(delta2);
if (abs1 > abs2 * 2) {
delta2 = 0;
}
if (abs2 > abs1 * 2) {
delta1 = 0;
}
// ----------------------------------------
// Fixation processing
if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_enable_scrollwheel_fixation)) {
// When 300ms passes from the last event, we reset a value.
const uint32_t FIXATION_MILLISEC = 300;
if (fixation_ic_.getmillisec() > FIXATION_MILLISEC) {
fixation_begin_ic_.begin();
fixation_delta1_ = 0;
fixation_delta2_ = 0;
}
fixation_ic_.begin();
if (fixation_delta1_ > fixation_delta2_ * 2) {
delta2 = 0;
}
if (fixation_delta2_ > fixation_delta1_ * 2) {
delta1 = 0;
}
// Only first 1000ms performs the addition of fixation_delta1, fixation_delta2.
const uint32_t FIXATION_EARLY_MILLISEC = 1000;
if (fixation_begin_ic_.getmillisec() < FIXATION_EARLY_MILLISEC) {
if (delta1 == 0) fixation_delta2_ += abs2;
if (delta2 == 0) fixation_delta1_ += abs1;
}
}
// ------------------------------------------------------------
// when sign is different
if (0 > delta1 * chained_delta1_ ||
0 > delta2 * chained_delta2_) {
queue_->clear();
chained_delta1_ = delta1;
chained_delta2_ = delta2;
} else if (abs(delta1) > abs(chained_delta1_) ||
abs(delta2) > abs(chained_delta2_)) {
// greater delta.
chained_delta1_ = delta1;
chained_delta2_ = delta2;
}
absolute_distance_ += abs(chained_delta1_) + abs(chained_delta2_);
queue_->push_back(new Item(chained_delta1_ * EventOutputQueue::FireScrollWheel::DELTA_SCALE, chained_delta2_ * EventOutputQueue::FireScrollWheel::DELTA_SCALE));
currentFromFlags_ = fromFlags_;
timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
}
void
PointingRelativeToScroll::callback(OSObject* owner, IOTimerEventSource* sender)
{
IOLockWrapper::ScopedLock lk(timer_.getlock());
if (! queue_) return;
// ----------------------------------------
int delta1 = 0;
int delta2 = 0;
{
Item* p = static_cast<Item*>(queue_->front());
if (! p) return;
delta1 = p->delta1;
delta2 = p->delta2;
queue_->pop_front();
}
// ----------------------------------------
FlagStatus::temporary_decrease(currentFromFlags_);
EventOutputQueue::FireScrollWheel::fire(delta1, delta2);
// ----------------------------------------
if (! Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_option_pointing_disable_momentum_scroll)) {
if (delta1 != 0 || delta2 != 0) {
queue_->push_back(new Item(delta1 / 2, delta2 / 2));
}
}
timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
}
}
}
<|endoftext|> |
<commit_before>// -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: vtkNetCDFCOARDSReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkNetCDFCOARDSReader.h"
#include "vtkDataArraySelection.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkRectilinearGrid.h"
#include "vtkStdString.h"
#include "vtkStructuredGrid.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
#include <netcdf.h>
#define CALL_NETCDF_GENERIC(call, on_error) \
{ \
int errorcode = call; \
if (errorcode != NC_NOERR) \
{ \
const char * errorstring = nc_strerror(errorcode); \
on_error; \
} \
}
#define CALL_NETCDF(call) \
CALL_NETCDF_GENERIC(call, vtkErrorMacro(<< "netCDF Error: " << errorstring); return 0;)
#define CALL_NETCDF_GW(call) \
CALL_NETCDF_GENERIC(call, vtkGenericWarningMacro(<< "netCDF Error: " << errorstring); return 0;)
#include <vtkstd/algorithm>
#include <math.h>
//=============================================================================
vtkNetCDFCOARDSReader::vtkDimensionInfo::vtkDimensionInfo(int ncFD, int id)
{
this->DimId = id;
this->LoadMetaData(ncFD);
}
int vtkNetCDFCOARDSReader::vtkDimensionInfo::LoadMetaData(int ncFD)
{
this->Units = UNDEFINED_UNITS;
char name[NC_MAX_NAME+1];
CALL_NETCDF_GW(nc_inq_dimname(ncFD, this->DimId, name));
this->Name = name;
size_t dimLen;
CALL_NETCDF_GW(nc_inq_dimlen(ncFD, this->DimId, &dimLen));
this->Coordinates = vtkSmartPointer<vtkDoubleArray>::New();
// this->Coordinates->SetName((this->Name + "_Coordinates").c_str());
this->Coordinates->SetNumberOfComponents(1);
this->Coordinates->SetNumberOfTuples(dimLen);
int varId;
int varNumDims;
int varDim;
// By convention if there is a single dimension variable with the same name as
// its dimension, then the data contains the coordinates for the dimension.
if ( (nc_inq_varid(ncFD, name, &varId) == NC_NOERR)
&& (nc_inq_varndims(ncFD, varId, &varNumDims) == NC_NOERR)
&& (varNumDims == 1)
&& (nc_inq_vardimid(ncFD, varId, &varDim) == NC_NOERR)
&& (varDim == this->DimId) )
{
// Read coordinates
CALL_NETCDF_GW(nc_get_var_double(ncFD, varId,
this->Coordinates->GetPointer(0)));
// Check to see if the spacing is regular.
this->Origin = this->Coordinates->GetValue(0);
this->Spacing
= (this->Coordinates->GetValue(dimLen-1) - this->Origin)/(dimLen-1);
this->HasRegularSpacing = true; // Then check to see if it is false.
double tolerance = 0.01*this->Spacing;
for (size_t i = 1; i < dimLen; i++)
{
double expectedValue = this->Origin + i*this->Spacing;
double actualValue = this->Coordinates->GetValue(i);
if ( (actualValue < expectedValue-tolerance)
|| (actualValue > expectedValue+tolerance) )
{
this->HasRegularSpacing = false;
break;
}
}
// Check units.
size_t unitsLength;
if (nc_inq_attlen(ncFD, varId, "units", &unitsLength) == NC_NOERR)
{
vtkStdString units;
units.resize(unitsLength); // Note: don't need terminating char.
CALL_NETCDF_GW(nc_get_att_text(ncFD, varId, "units", &units.at(0)));
// Time, latitude, and longitude dimensions are those with units that
// correspond to strings formatted with the Unidata udunits package. I'm
// not sure if these checks are complete, but they matches all of the
// examples I have seen.
if (units.find(" since ") != vtkStdString::npos)
{
this->Units = TIME_UNITS;
}
else if (units.find("degrees") != vtkStdString::npos)
{
this->Units = DEGREE_UNITS;
}
}
}
else
{
// Fake coordinates
for (size_t i = 0; i < dimLen; i++)
{
this->Coordinates->SetValue(i, static_cast<double>(i));
}
this->HasRegularSpacing = true;
this->Origin = 0.0;
this->Spacing = 1.0;
}
return 1;
}
//=============================================================================
vtkCxxRevisionMacro(vtkNetCDFCOARDSReader, "1.2");
vtkStandardNewMacro(vtkNetCDFCOARDSReader);
//-----------------------------------------------------------------------------
vtkNetCDFCOARDSReader::vtkNetCDFCOARDSReader()
{
this->SphericalCoordinates = 1;
}
vtkNetCDFCOARDSReader::~vtkNetCDFCOARDSReader()
{
}
void vtkNetCDFCOARDSReader::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "SphericalCoordinates: " << this->SphericalCoordinates <<endl;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::CanReadFile(const char *filename)
{
// We really just read basic arrays from netCDF files. If the netCDF library
// says we can read it, then we can read it.
int ncFD;
int errorcode = nc_open(filename, NC_NOWRITE, &ncFD);
if (errorcode == NC_NOERR)
{
nc_close(ncFD);
return 1;
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::RequestDataObject(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject *output = vtkDataObject::GetData(outInfo);
// This is really too early to know the appropriate data type. We need to
// have meta data and let the user select arrays. We have to do part
// of the RequestInformation to get the appropriate meta data.
if (!this->UpdateMetaData()) return 0;
int dataType = VTK_IMAGE_DATA;
int ncFD;
CALL_NETCDF(nc_open(this->FileName, NC_NOWRITE, &ncFD));
int numArrays = this->VariableArraySelection->GetNumberOfArrays();
for (int arrayIndex = 0; arrayIndex < numArrays; arrayIndex++)
{
if (!this->VariableArraySelection->GetArraySetting(arrayIndex)) continue;
const char *name = this->VariableArraySelection->GetArrayName(arrayIndex);
int varId;
CALL_NETCDF(nc_inq_varid(ncFD, name, &varId));
int currentNumDims;
CALL_NETCDF(nc_inq_varndims(ncFD, varId, ¤tNumDims));
if (currentNumDims < 1) continue;
VTK_CREATE(vtkIntArray, currentDimensions);
currentDimensions->SetNumberOfComponents(1);
currentDimensions->SetNumberOfTuples(currentNumDims);
CALL_NETCDF(nc_inq_vardimid(ncFD, varId,
currentDimensions->GetPointer(0)));
// Remove initial time dimension, which has no effect on data type.
if (this->IsTimeDimension(ncFD, currentDimensions->GetValue(0)))
{
currentDimensions->RemoveTuple(0);
currentNumDims--;
if (currentNumDims < 1) continue;
}
// Check to see if the dimensions fit spherical coordinates.
if ( this->SphericalCoordinates
&& (currentNumDims == 3)
&& ( this->DimensionInfo[currentDimensions->GetValue(1)].GetUnits()
== vtkDimensionInfo::DEGREE_UNITS)
&& ( this->DimensionInfo[currentDimensions->GetValue(2)].GetUnits()
== vtkDimensionInfo::DEGREE_UNITS) )
{
dataType = VTK_STRUCTURED_GRID;
break;
}
// Check to see if any dimension as irregular spacing.
for (int i = 0; i < currentNumDims; i++)
{
int dimId = currentDimensions->GetValue(i);
if (!this->DimensionInfo[dimId].GetHasRegularSpacing())
{
dataType = VTK_RECTILINEAR_GRID;
break;
}
}
break;
}
if (dataType == VTK_IMAGE_DATA)
{
if (!output || !output->IsA("vtkImageData"))
{
output = vtkImageData::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
else if (dataType == VTK_RECTILINEAR_GRID)
{
if (!output || !output->IsA("vtkRectilinearGrid"))
{
output = vtkRectilinearGrid::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
else // dataType == VTK_STRUCTURED_GRID
{
if (!output || !output->IsA("vtkStructuredGrid"))
{
output = vtkStructuredGrid::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::RequestData(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// Let the superclass do the heavy lifting.
if (!this->Superclass::RequestData(request, inputVector, outputVector))
{
return 0;
}
// Add spacing information defined by the COARDS conventions.
vtkImageData *imageOutput = vtkImageData::GetData(outputVector);
if (imageOutput)
{
double origin[3];
origin[0] = origin[1] = origin[2] = 0.0;
double spacing[3];
spacing[0] = spacing[1] = spacing[2] = 1.0;
int numDim = this->LoadingDimensions->GetNumberOfTuples();
if (numDim >= 3) numDim = 3;
for (int i = 0; i < numDim; i++)
{
// Remember that netCDF dimension ordering is backward from VTK.
int dim = this->LoadingDimensions->GetValue(numDim-i-1);
origin[i] = this->DimensionInfo[dim].GetOrigin();
spacing[i] = this->DimensionInfo[dim].GetSpacing();
}
}
vtkRectilinearGrid *rectOutput = vtkRectilinearGrid::GetData(outputVector);
if (rectOutput)
{
int extent[6];
rectOutput->GetExtent(extent);
int numDim = this->LoadingDimensions->GetNumberOfTuples();
for (int i = 0; i < numDim; i++)
{
// Remember that netCDF dimension ordering is backward from VTK.
int dim = this->LoadingDimensions->GetValue(numDim-i-1);
vtkSmartPointer<vtkDoubleArray> coords
= this->DimensionInfo[dim].GetCoordinates();
int extLow = extent[2*i];
int extHi = extent[2*i+1];
if ((extLow != 0) || (extHi != coords->GetNumberOfTuples()-1))
{
// Getting a subset of this dimension.
VTK_CREATE(vtkDoubleArray, newcoords);
newcoords->SetNumberOfComponents(1);
newcoords->SetNumberOfTuples(extHi-extLow+1);
vtkstd::copy(coords->GetPointer(extLow), coords->GetPointer(extHi+1),
newcoords->GetPointer(0));
coords = newcoords;
}
switch (dim)
{
case 0: rectOutput->SetXCoordinates(coords); break;
case 1: rectOutput->SetYCoordinates(coords); break;
case 2: rectOutput->SetZCoordinates(coords); break;
}
}
}
vtkStructuredGrid *structOutput = vtkStructuredGrid::GetData(outputVector);
if (structOutput)
{
int extent[6];
structOutput->GetExtent(extent);
vtkDoubleArray *longCoords = this->DimensionInfo[this->LoadingDimensions->GetValue(2)].GetCoordinates();
vtkDoubleArray *latCoords = this->DimensionInfo[this->LoadingDimensions->GetValue(1)].GetCoordinates();
vtkDoubleArray *heightCoords = this->DimensionInfo[this->LoadingDimensions->GetValue(0)].GetCoordinates();
VTK_CREATE(vtkPoints, points);
points->SetDataTypeToDouble();
points->Allocate( (extent[1]-extent[0]+1)
* (extent[3]-extent[2]+1)
* (extent[5]-extent[4]+1) );
for (int k = extent[4]; k <= extent[5]; k++)
{
double height = heightCoords->GetValue(k);
for (int j = extent[2]; j <= extent[3]; j++)
{
double phi = vtkMath::RadiansFromDegrees(latCoords->GetValue(j));
for (int i = extent[0]; i <= extent[1]; i++)
{
double theta = vtkMath::RadiansFromDegrees(longCoords->GetValue(i));
double cartesianCoord[3];
cartesianCoord[0] = height*cos(theta)*cos(phi);
cartesianCoord[1] = height*sin(theta)*cos(phi);
cartesianCoord[2] = height*sin(phi);
points->InsertNextPoint(cartesianCoord);
}
}
}
structOutput->SetPoints(points);
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::ReadMetaData(int ncFD)
{
int i;
vtkDebugMacro("ReadMetaData");
int numDimensions;
CALL_NETCDF(nc_inq_ndims(ncFD, &numDimensions));
this->DimensionInfo.resize(numDimensions);
for (i = 0; i < numDimensions; i++)
{
this->DimensionInfo[i] = vtkDimensionInfo(ncFD, i);
}
// Look at all variables and record them so that the user can select
// which ones he wants.
this->VariableArraySelection->RemoveAllArrays();
int numVariables;
CALL_NETCDF(nc_inq_nvars(ncFD, &numVariables));
for (i = 0; i < numVariables; i++)
{
char name[NC_MAX_NAME+1];
CALL_NETCDF(nc_inq_varname(ncFD, i, name));
int dimId;
if (nc_inq_dimid(ncFD, name, &dimId) == NC_NOERR)
{
// This is a special variable that just tells us information about
// a particular dimension.
}
else
{
// This is a real variable we want to expose.
this->VariableArraySelection->AddArray(name);
}
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::IsTimeDimension(int vtkNotUsed(ncFD), int dimId)
{
return this->DimensionInfo[dimId].GetUnits() == vtkDimensionInfo::TIME_UNITS;
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkDoubleArray> vtkNetCDFCOARDSReader::GetTimeValues(
int vtkNotUsed(ncFD), int dimId)
{
return this->DimensionInfo[dimId].GetCoordinates();
}
<commit_msg>COMP: New Microsoft compilers have declared that using many STL algorithms on basic C pointers (a task that they were originally designed to handle) is 'unsafe'. To protect me from myself, it now issues a warning any time I try to do something like copy one array to another. There is no effective way around this without using special forms of the function that are unique to Microsoft's new compiler. Essentially, I can no longer use these functions if I write portable code. Thanks Microsoft<commit_after>// -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: vtkNetCDFCOARDSReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkNetCDFCOARDSReader.h"
#include "vtkDataArraySelection.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkRectilinearGrid.h"
#include "vtkStdString.h"
#include "vtkStructuredGrid.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
#include <string.h>
#include <netcdf.h>
#define CALL_NETCDF_GENERIC(call, on_error) \
{ \
int errorcode = call; \
if (errorcode != NC_NOERR) \
{ \
const char * errorstring = nc_strerror(errorcode); \
on_error; \
} \
}
#define CALL_NETCDF(call) \
CALL_NETCDF_GENERIC(call, vtkErrorMacro(<< "netCDF Error: " << errorstring); return 0;)
#define CALL_NETCDF_GW(call) \
CALL_NETCDF_GENERIC(call, vtkGenericWarningMacro(<< "netCDF Error: " << errorstring); return 0;)
#include <vtkstd/algorithm>
#include <math.h>
//=============================================================================
vtkNetCDFCOARDSReader::vtkDimensionInfo::vtkDimensionInfo(int ncFD, int id)
{
this->DimId = id;
this->LoadMetaData(ncFD);
}
int vtkNetCDFCOARDSReader::vtkDimensionInfo::LoadMetaData(int ncFD)
{
this->Units = UNDEFINED_UNITS;
char name[NC_MAX_NAME+1];
CALL_NETCDF_GW(nc_inq_dimname(ncFD, this->DimId, name));
this->Name = name;
size_t dimLen;
CALL_NETCDF_GW(nc_inq_dimlen(ncFD, this->DimId, &dimLen));
this->Coordinates = vtkSmartPointer<vtkDoubleArray>::New();
// this->Coordinates->SetName((this->Name + "_Coordinates").c_str());
this->Coordinates->SetNumberOfComponents(1);
this->Coordinates->SetNumberOfTuples(dimLen);
int varId;
int varNumDims;
int varDim;
// By convention if there is a single dimension variable with the same name as
// its dimension, then the data contains the coordinates for the dimension.
if ( (nc_inq_varid(ncFD, name, &varId) == NC_NOERR)
&& (nc_inq_varndims(ncFD, varId, &varNumDims) == NC_NOERR)
&& (varNumDims == 1)
&& (nc_inq_vardimid(ncFD, varId, &varDim) == NC_NOERR)
&& (varDim == this->DimId) )
{
// Read coordinates
CALL_NETCDF_GW(nc_get_var_double(ncFD, varId,
this->Coordinates->GetPointer(0)));
// Check to see if the spacing is regular.
this->Origin = this->Coordinates->GetValue(0);
this->Spacing
= (this->Coordinates->GetValue(dimLen-1) - this->Origin)/(dimLen-1);
this->HasRegularSpacing = true; // Then check to see if it is false.
double tolerance = 0.01*this->Spacing;
for (size_t i = 1; i < dimLen; i++)
{
double expectedValue = this->Origin + i*this->Spacing;
double actualValue = this->Coordinates->GetValue(i);
if ( (actualValue < expectedValue-tolerance)
|| (actualValue > expectedValue+tolerance) )
{
this->HasRegularSpacing = false;
break;
}
}
// Check units.
size_t unitsLength;
if (nc_inq_attlen(ncFD, varId, "units", &unitsLength) == NC_NOERR)
{
vtkStdString units;
units.resize(unitsLength); // Note: don't need terminating char.
CALL_NETCDF_GW(nc_get_att_text(ncFD, varId, "units", &units.at(0)));
// Time, latitude, and longitude dimensions are those with units that
// correspond to strings formatted with the Unidata udunits package. I'm
// not sure if these checks are complete, but they matches all of the
// examples I have seen.
if (units.find(" since ") != vtkStdString::npos)
{
this->Units = TIME_UNITS;
}
else if (units.find("degrees") != vtkStdString::npos)
{
this->Units = DEGREE_UNITS;
}
}
}
else
{
// Fake coordinates
for (size_t i = 0; i < dimLen; i++)
{
this->Coordinates->SetValue(i, static_cast<double>(i));
}
this->HasRegularSpacing = true;
this->Origin = 0.0;
this->Spacing = 1.0;
}
return 1;
}
//=============================================================================
vtkCxxRevisionMacro(vtkNetCDFCOARDSReader, "1.3");
vtkStandardNewMacro(vtkNetCDFCOARDSReader);
//-----------------------------------------------------------------------------
vtkNetCDFCOARDSReader::vtkNetCDFCOARDSReader()
{
this->SphericalCoordinates = 1;
}
vtkNetCDFCOARDSReader::~vtkNetCDFCOARDSReader()
{
}
void vtkNetCDFCOARDSReader::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "SphericalCoordinates: " << this->SphericalCoordinates <<endl;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::CanReadFile(const char *filename)
{
// We really just read basic arrays from netCDF files. If the netCDF library
// says we can read it, then we can read it.
int ncFD;
int errorcode = nc_open(filename, NC_NOWRITE, &ncFD);
if (errorcode == NC_NOERR)
{
nc_close(ncFD);
return 1;
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::RequestDataObject(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject *output = vtkDataObject::GetData(outInfo);
// This is really too early to know the appropriate data type. We need to
// have meta data and let the user select arrays. We have to do part
// of the RequestInformation to get the appropriate meta data.
if (!this->UpdateMetaData()) return 0;
int dataType = VTK_IMAGE_DATA;
int ncFD;
CALL_NETCDF(nc_open(this->FileName, NC_NOWRITE, &ncFD));
int numArrays = this->VariableArraySelection->GetNumberOfArrays();
for (int arrayIndex = 0; arrayIndex < numArrays; arrayIndex++)
{
if (!this->VariableArraySelection->GetArraySetting(arrayIndex)) continue;
const char *name = this->VariableArraySelection->GetArrayName(arrayIndex);
int varId;
CALL_NETCDF(nc_inq_varid(ncFD, name, &varId));
int currentNumDims;
CALL_NETCDF(nc_inq_varndims(ncFD, varId, ¤tNumDims));
if (currentNumDims < 1) continue;
VTK_CREATE(vtkIntArray, currentDimensions);
currentDimensions->SetNumberOfComponents(1);
currentDimensions->SetNumberOfTuples(currentNumDims);
CALL_NETCDF(nc_inq_vardimid(ncFD, varId,
currentDimensions->GetPointer(0)));
// Remove initial time dimension, which has no effect on data type.
if (this->IsTimeDimension(ncFD, currentDimensions->GetValue(0)))
{
currentDimensions->RemoveTuple(0);
currentNumDims--;
if (currentNumDims < 1) continue;
}
// Check to see if the dimensions fit spherical coordinates.
if ( this->SphericalCoordinates
&& (currentNumDims == 3)
&& ( this->DimensionInfo[currentDimensions->GetValue(1)].GetUnits()
== vtkDimensionInfo::DEGREE_UNITS)
&& ( this->DimensionInfo[currentDimensions->GetValue(2)].GetUnits()
== vtkDimensionInfo::DEGREE_UNITS) )
{
dataType = VTK_STRUCTURED_GRID;
break;
}
// Check to see if any dimension as irregular spacing.
for (int i = 0; i < currentNumDims; i++)
{
int dimId = currentDimensions->GetValue(i);
if (!this->DimensionInfo[dimId].GetHasRegularSpacing())
{
dataType = VTK_RECTILINEAR_GRID;
break;
}
}
break;
}
if (dataType == VTK_IMAGE_DATA)
{
if (!output || !output->IsA("vtkImageData"))
{
output = vtkImageData::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
else if (dataType == VTK_RECTILINEAR_GRID)
{
if (!output || !output->IsA("vtkRectilinearGrid"))
{
output = vtkRectilinearGrid::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
else // dataType == VTK_STRUCTURED_GRID
{
if (!output || !output->IsA("vtkStructuredGrid"))
{
output = vtkStructuredGrid::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::RequestData(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// Let the superclass do the heavy lifting.
if (!this->Superclass::RequestData(request, inputVector, outputVector))
{
return 0;
}
// Add spacing information defined by the COARDS conventions.
vtkImageData *imageOutput = vtkImageData::GetData(outputVector);
if (imageOutput)
{
double origin[3];
origin[0] = origin[1] = origin[2] = 0.0;
double spacing[3];
spacing[0] = spacing[1] = spacing[2] = 1.0;
int numDim = this->LoadingDimensions->GetNumberOfTuples();
if (numDim >= 3) numDim = 3;
for (int i = 0; i < numDim; i++)
{
// Remember that netCDF dimension ordering is backward from VTK.
int dim = this->LoadingDimensions->GetValue(numDim-i-1);
origin[i] = this->DimensionInfo[dim].GetOrigin();
spacing[i] = this->DimensionInfo[dim].GetSpacing();
}
}
vtkRectilinearGrid *rectOutput = vtkRectilinearGrid::GetData(outputVector);
if (rectOutput)
{
int extent[6];
rectOutput->GetExtent(extent);
int numDim = this->LoadingDimensions->GetNumberOfTuples();
for (int i = 0; i < numDim; i++)
{
// Remember that netCDF dimension ordering is backward from VTK.
int dim = this->LoadingDimensions->GetValue(numDim-i-1);
vtkSmartPointer<vtkDoubleArray> coords
= this->DimensionInfo[dim].GetCoordinates();
int extLow = extent[2*i];
int extHi = extent[2*i+1];
if ((extLow != 0) || (extHi != coords->GetNumberOfTuples()-1))
{
// Getting a subset of this dimension.
VTK_CREATE(vtkDoubleArray, newcoords);
newcoords->SetNumberOfComponents(1);
newcoords->SetNumberOfTuples(extHi-extLow+1);
memcpy(newcoords->GetPointer(0), coords->GetPointer(extLow),
(extHi-extLow+1)*sizeof(double));
coords = newcoords;
}
switch (dim)
{
case 0: rectOutput->SetXCoordinates(coords); break;
case 1: rectOutput->SetYCoordinates(coords); break;
case 2: rectOutput->SetZCoordinates(coords); break;
}
}
}
vtkStructuredGrid *structOutput = vtkStructuredGrid::GetData(outputVector);
if (structOutput)
{
int extent[6];
structOutput->GetExtent(extent);
vtkDoubleArray *longCoords = this->DimensionInfo[this->LoadingDimensions->GetValue(2)].GetCoordinates();
vtkDoubleArray *latCoords = this->DimensionInfo[this->LoadingDimensions->GetValue(1)].GetCoordinates();
vtkDoubleArray *heightCoords = this->DimensionInfo[this->LoadingDimensions->GetValue(0)].GetCoordinates();
VTK_CREATE(vtkPoints, points);
points->SetDataTypeToDouble();
points->Allocate( (extent[1]-extent[0]+1)
* (extent[3]-extent[2]+1)
* (extent[5]-extent[4]+1) );
for (int k = extent[4]; k <= extent[5]; k++)
{
double height = heightCoords->GetValue(k);
for (int j = extent[2]; j <= extent[3]; j++)
{
double phi = vtkMath::RadiansFromDegrees(latCoords->GetValue(j));
for (int i = extent[0]; i <= extent[1]; i++)
{
double theta = vtkMath::RadiansFromDegrees(longCoords->GetValue(i));
double cartesianCoord[3];
cartesianCoord[0] = height*cos(theta)*cos(phi);
cartesianCoord[1] = height*sin(theta)*cos(phi);
cartesianCoord[2] = height*sin(phi);
points->InsertNextPoint(cartesianCoord);
}
}
}
structOutput->SetPoints(points);
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::ReadMetaData(int ncFD)
{
int i;
vtkDebugMacro("ReadMetaData");
int numDimensions;
CALL_NETCDF(nc_inq_ndims(ncFD, &numDimensions));
this->DimensionInfo.resize(numDimensions);
for (i = 0; i < numDimensions; i++)
{
this->DimensionInfo[i] = vtkDimensionInfo(ncFD, i);
}
// Look at all variables and record them so that the user can select
// which ones he wants.
this->VariableArraySelection->RemoveAllArrays();
int numVariables;
CALL_NETCDF(nc_inq_nvars(ncFD, &numVariables));
for (i = 0; i < numVariables; i++)
{
char name[NC_MAX_NAME+1];
CALL_NETCDF(nc_inq_varname(ncFD, i, name));
int dimId;
if (nc_inq_dimid(ncFD, name, &dimId) == NC_NOERR)
{
// This is a special variable that just tells us information about
// a particular dimension.
}
else
{
// This is a real variable we want to expose.
this->VariableArraySelection->AddArray(name);
}
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCOARDSReader::IsTimeDimension(int vtkNotUsed(ncFD), int dimId)
{
return this->DimensionInfo[dimId].GetUnits() == vtkDimensionInfo::TIME_UNITS;
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkDoubleArray> vtkNetCDFCOARDSReader::GetTimeValues(
int vtkNotUsed(ncFD), int dimId)
{
return this->DimensionInfo[dimId].GetCoordinates();
}
<|endoftext|> |
<commit_before>#include "model.h"
#include <QDebug>
using namespace qReal;
using namespace model;
Model::Model()
{
mClient = new client::Client();
rootItem = new ModelTreeItem(ROOT_ID, NULL);
treeItems.insert(ROOT_ID, rootItem);
mClient->setProperty(ROOT_ID, "Name", ROOT_ID.toString());
loadSubtreeFromClient(rootItem);
}
Model::~Model()
{
delete mClient;
}
Qt::ItemFlags Model::flags( const QModelIndex &index ) const
{
if (index.isValid()) {
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled
| Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;
} else {
return Qt::NoItemFlags;
}
}
QVariant Model::data(QModelIndex const &index, int role) const
{
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
Q_ASSERT(item);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return mClient->property(item->id(), "Name");
case roles::idRole: {
QVariant v;
v.setValue(item->id());
return v;
}
case roles::positionRole:
return mClient->property(item->id(), positionPropertyName(item));
}
Q_ASSERT(role < Qt::UserRole);
return QVariant();
} else {
return QVariant();
}
}
bool Model::setData(QModelIndex const &index, QVariant const &value, int role)
{
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
mClient->setProperty(item->id(), "Name", value);
return true;
case roles::positionRole:
mClient->setProperty(item->id(), positionPropertyName(item), value);
}
Q_ASSERT(role < Qt::UserRole);
return false;
} else {
return false;
}
}
QVariant Model::headerData( int section, Qt::Orientation orientation, int role ) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section == 0 ) {
return QVariant("Name");
} else {
return QVariant();
}
}
int Model::rowCount( const QModelIndex &parent ) const
{
ModelTreeItem *parentItem;
if (parent.isValid()) {
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
} else {
parentItem = rootItem;
}
return parentItem->children().size();
}
int Model::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED(parent)
return 1;
}
bool Model::removeRows( int row, int count, const QModelIndex &parent )
{
if (parent.isValid()) {
ModelTreeItem *parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
if (parentItem->children().size() < row + count) {
return false;
} else {
for (int i = row; i < row + count; i++) {
removeModelItems(parentItem->children().at(i));
}
return true;
}
} else {
return false;
}
}
PropertyName Model::pathToItem(ModelTreeItem const *item) const
{
if (item != rootItem) {
PropertyName path;
do {
item = item->parent();
path = item->id().toString() + PATH_DIVIDER + path;
} while (item!=rootItem);
return path;
}
else
return ROOT_ID.toString();
}
void Model::removeConfigurationInClient( ModelTreeItem *item )
{
mClient->removeProperty(item->id(), positionPropertyName(item));
mClient->removeProperty(item->id(), configurationPropertyName(item));
}
QModelIndex Model::index( ModelTreeItem *item )
{
if (item!=rootItem) {
return createIndex(item->row(),0,item);
} else {
return QModelIndex();
}
}
void Model::removeModelItems( ModelTreeItem *root )
{
foreach (ModelTreeItem *child, root->children()) {
removeModelItems(child);
int childRow = child->row();
beginRemoveRows(index(root),childRow,childRow);
removeConfigurationInClient(child);
child->parent()->removeChild(child);
treeItems.remove(child->id(),child);
if (treeItems.count(child->id())==0) {
mClient->removeChild(root->id(),child->id());
}
delete child;
endRemoveRows();
}
}
QModelIndex Model::index( int row, int column, const QModelIndex &parent ) const
{
ModelTreeItem *parentItem;
if (parent.isValid()) {
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
} else {
parentItem = rootItem;
}
if (parentItem->children().size()<=row) {
return QModelIndex();
}
ModelTreeItem *item = parentItem->children().at(row);
return createIndex(row,column,item);
}
QModelIndex Model::parent( const QModelIndex &index ) const
{
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
ModelTreeItem *parentItem = item->parent();
if ((parentItem==rootItem)||(parentItem==NULL)) {
return QModelIndex();
} else{
return createIndex(parentItem->row(),0,parentItem);
}
} else {
return QModelIndex();
}
}
Qt::DropActions Model::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;
}
QStringList Model::mimeTypes() const
{
QStringList types;
types.append(DEFAULT_MIME_TYPE);
return types;
}
QMimeData* Model::mimeData( const QModelIndexList &indexes ) const
{
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
stream << item->id().toString();
stream << pathToItem(item);
stream << mClient->property(item->id(), "Name");
stream << mClient->property(item->id(), positionPropertyName(item)).toPointF();
} else {
stream << ROOT_ID.toString();
stream << QString();
stream << ROOT_ID.toString();
stream << QPointF();
}
}
QMimeData *mimeData = new QMimeData();
mimeData->setData(DEFAULT_MIME_TYPE, data);
return mimeData;
}
bool Model::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent )
{
Q_UNUSED(row)
Q_UNUSED(column)
if (action == Qt::IgnoreAction) {
return true;
} else {
ModelTreeItem *parentItem;
if (parent.isValid()) {
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
} else {
parentItem = rootItem;
}
QByteArray dragData = data->data(DEFAULT_MIME_TYPE);
QDataStream stream(&dragData, QIODevice::ReadOnly);
QString idString;
PropertyName pathToItem;
QString name;
QPointF position;
stream >> idString;
stream >> pathToItem;
stream >> name;
stream >> position;
IdType id = Id::loadFromString(idString);
Q_ASSERT(id.idSize() == 4); // Бросать в модель мы можем только конкретные элементы.
return addElementToModel(parentItem,id,pathToItem,name,position,action) != NULL;
}
}
ModelTreeItem *Model::addElementToModel( ModelTreeItem *parentItem, const IdType &id,
const PropertyName &oldPathToItem, const QString &name, const QPointF &position, Qt::DropAction action )
{
Q_UNUSED(oldPathToItem)
Q_UNUSED(action)
int newRow = parentItem->children().size();
beginInsertRows(index(parentItem),newRow,newRow);
ModelTreeItem *item = new ModelTreeItem(id, parentItem);
parentItem->addChild(item);
treeItems.insert(id,item);
mClient->addChild(parentItem->id(),id);
mClient->setProperty(id, "Name", name);
mClient->setProperty(id, positionPropertyName(item), position);
endInsertRows();
return item;
}
void Model::loadSubtreeFromClient(ModelTreeItem * const parent)
{
foreach (IdType childId, mClient->children(parent->id())) {
PropertyName path = pathToItem(parent);
ModelTreeItem * child = addElementToModel(parent, childId, "",
mClient->property(childId, "Name").toString(),
mClient->property(childId, "position + " + path + PATH_DIVIDER).toPointF(),
Qt::MoveAction);
loadSubtreeFromClient(child);
}
}
QPersistentModelIndex Model::rootIndex()
{
return index(rootItem);
}
PropertyName Model::positionPropertyName(ModelTreeItem const *item) const
{
return "position + " + pathToItem(item);
}
PropertyName Model::configurationPropertyName(ModelTreeItem const *item) const
{
return "configuration + " + pathToItem(item);
}
<commit_msg>поправлен крэш<commit_after>#include "model.h"
#include <QDebug>
using namespace qReal;
using namespace model;
Model::Model()
{
mClient = new client::Client();
rootItem = new ModelTreeItem(ROOT_ID, NULL);
treeItems.insert(ROOT_ID, rootItem);
mClient->setProperty(ROOT_ID, "Name", ROOT_ID.toString());
loadSubtreeFromClient(rootItem);
}
Model::~Model()
{
delete mClient;
}
Qt::ItemFlags Model::flags( const QModelIndex &index ) const
{
if (index.isValid()) {
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled
| Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;
} else {
return Qt::NoItemFlags;
}
}
QVariant Model::data(QModelIndex const &index, int role) const
{
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
Q_ASSERT(item);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return mClient->property(item->id(), "Name");
case roles::idRole: {
QVariant v;
v.setValue(item->id());
return v;
}
case roles::positionRole:
return mClient->property(item->id(), positionPropertyName(item));
}
Q_ASSERT(role < Qt::UserRole);
return QVariant();
} else {
return QVariant();
}
}
bool Model::setData(QModelIndex const &index, QVariant const &value, int role)
{
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
mClient->setProperty(item->id(), "Name", value);
return true;
case roles::positionRole:
mClient->setProperty(item->id(), positionPropertyName(item), value);
return true;
}
Q_ASSERT(role < Qt::UserRole);
return false;
} else {
return false;
}
}
QVariant Model::headerData( int section, Qt::Orientation orientation, int role ) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section == 0 ) {
return QVariant("Name");
} else {
return QVariant();
}
}
int Model::rowCount( const QModelIndex &parent ) const
{
ModelTreeItem *parentItem;
if (parent.isValid()) {
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
} else {
parentItem = rootItem;
}
return parentItem->children().size();
}
int Model::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED(parent)
return 1;
}
bool Model::removeRows( int row, int count, const QModelIndex &parent )
{
if (parent.isValid()) {
ModelTreeItem *parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
if (parentItem->children().size() < row + count) {
return false;
} else {
for (int i = row; i < row + count; i++) {
removeModelItems(parentItem->children().at(i));
}
return true;
}
} else {
return false;
}
}
PropertyName Model::pathToItem(ModelTreeItem const *item) const
{
if (item != rootItem) {
PropertyName path;
do {
item = item->parent();
path = item->id().toString() + PATH_DIVIDER + path;
} while (item!=rootItem);
return path;
}
else
return ROOT_ID.toString();
}
void Model::removeConfigurationInClient( ModelTreeItem *item )
{
mClient->removeProperty(item->id(), positionPropertyName(item));
mClient->removeProperty(item->id(), configurationPropertyName(item));
}
QModelIndex Model::index( ModelTreeItem *item )
{
if (item!=rootItem) {
return createIndex(item->row(),0,item);
} else {
return QModelIndex();
}
}
void Model::removeModelItems( ModelTreeItem *root )
{
foreach (ModelTreeItem *child, root->children()) {
removeModelItems(child);
int childRow = child->row();
beginRemoveRows(index(root),childRow,childRow);
removeConfigurationInClient(child);
child->parent()->removeChild(child);
treeItems.remove(child->id(),child);
if (treeItems.count(child->id())==0) {
mClient->removeChild(root->id(),child->id());
}
delete child;
endRemoveRows();
}
}
QModelIndex Model::index( int row, int column, const QModelIndex &parent ) const
{
ModelTreeItem *parentItem;
if (parent.isValid()) {
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
} else {
parentItem = rootItem;
}
if (parentItem->children().size()<=row) {
return QModelIndex();
}
ModelTreeItem *item = parentItem->children().at(row);
return createIndex(row,column,item);
}
QModelIndex Model::parent( const QModelIndex &index ) const
{
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
ModelTreeItem *parentItem = item->parent();
if ((parentItem==rootItem)||(parentItem==NULL)) {
return QModelIndex();
} else{
return createIndex(parentItem->row(),0,parentItem);
}
} else {
return QModelIndex();
}
}
Qt::DropActions Model::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;
}
QStringList Model::mimeTypes() const
{
QStringList types;
types.append(DEFAULT_MIME_TYPE);
return types;
}
QMimeData* Model::mimeData( const QModelIndexList &indexes ) const
{
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
ModelTreeItem *item = static_cast<ModelTreeItem*>(index.internalPointer());
stream << item->id().toString();
stream << pathToItem(item);
stream << mClient->property(item->id(), "Name");
stream << mClient->property(item->id(), positionPropertyName(item)).toPointF();
} else {
stream << ROOT_ID.toString();
stream << QString();
stream << ROOT_ID.toString();
stream << QPointF();
}
}
QMimeData *mimeData = new QMimeData();
mimeData->setData(DEFAULT_MIME_TYPE, data);
return mimeData;
}
bool Model::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent )
{
Q_UNUSED(row)
Q_UNUSED(column)
if (action == Qt::IgnoreAction) {
return true;
} else {
ModelTreeItem *parentItem;
if (parent.isValid()) {
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
} else {
parentItem = rootItem;
}
QByteArray dragData = data->data(DEFAULT_MIME_TYPE);
QDataStream stream(&dragData, QIODevice::ReadOnly);
QString idString;
PropertyName pathToItem;
QString name;
QPointF position;
stream >> idString;
stream >> pathToItem;
stream >> name;
stream >> position;
IdType id = Id::loadFromString(idString);
Q_ASSERT(id.idSize() == 4); // Бросать в модель мы можем только конкретные элементы.
return addElementToModel(parentItem,id,pathToItem,name,position,action) != NULL;
}
}
ModelTreeItem *Model::addElementToModel( ModelTreeItem *parentItem, const IdType &id,
const PropertyName &oldPathToItem, const QString &name, const QPointF &position, Qt::DropAction action )
{
Q_UNUSED(oldPathToItem)
Q_UNUSED(action)
int newRow = parentItem->children().size();
beginInsertRows(index(parentItem),newRow,newRow);
ModelTreeItem *item = new ModelTreeItem(id, parentItem);
parentItem->addChild(item);
treeItems.insert(id,item);
mClient->addChild(parentItem->id(),id);
mClient->setProperty(id, "Name", name);
mClient->setProperty(id, positionPropertyName(item), position);
endInsertRows();
return item;
}
void Model::loadSubtreeFromClient(ModelTreeItem * const parent)
{
foreach (IdType childId, mClient->children(parent->id())) {
PropertyName path = pathToItem(parent);
ModelTreeItem * child = addElementToModel(parent, childId, "",
mClient->property(childId, "Name").toString(),
mClient->property(childId, "position + " + path + PATH_DIVIDER).toPointF(),
Qt::MoveAction);
loadSubtreeFromClient(child);
}
}
QPersistentModelIndex Model::rootIndex()
{
return index(rootItem);
}
PropertyName Model::positionPropertyName(ModelTreeItem const *item) const
{
return "position + " + pathToItem(item);
}
PropertyName Model::configurationPropertyName(ModelTreeItem const *item) const
{
return "configuration + " + pathToItem(item);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
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 "im-persons-data-source.h"
#include <KPeople/PersonsModel>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Presence>
#include "KTp/contact-factory.h"
#include "KTp/global-contact-manager.h"
#include "KTp/types.h"
#include <KDebug>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Nepomuk2/ResourceManager>
using namespace KPeople;
class KTpAllContacts : public AllContactsMonitor
{
Q_OBJECT
public:
KTpAllContacts();
~KTpAllContacts();
virtual KABC::Addressee::Map contacts();
private Q_SLOTS:
void onAccountManagerReady(Tp::PendingOperation *op);
void onContactChanged();
void onContactInvalidated();
void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);
private:
QString createUri(const Tp::ContactPtr &contact) const;
KABC::Addressee contactToAddressee(const Tp::ContactPtr &contact) const;
QHash<QString, KTp::ContactPtr> m_contacts;
};
KTpAllContacts::KTpAllContacts()
{
Tp::registerTypes();
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
KTpAllContacts::~KTpAllContacts()
{
}
QString KTpAllContacts::createUri(const Tp::ContactPtr &contact) const
{
return QLatin1String("ktp://") + contact->id();
}
void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Failed to initialize AccountManager:" << op->errorName();
kWarning() << op->errorMessage();
return;
}
kDebug() << "Account manager ready";
connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());
}
void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_contacts.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &contact, contactsRemoved) {
m_contacts.remove(contact->id());
Q_EMIT contactRemoved(createUri(contact));
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);
m_contacts.insert(contact->id(), ktpContact);
Q_EMIT contactAdded(createUri(ktpContact), contactToAddressee(ktpContact));
connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(invalidated()),
this, SLOT(onContactInvalidated()));
}
}
void KTpAllContacts::onContactChanged()
{
const Tp::ContactPtr contact(qobject_cast<Tp::Contact*>(sender()));
Q_EMIT contactChanged(createUri(contact), contactToAddressee(contact));
}
void KTpAllContacts::onContactInvalidated()
{
const Tp::ContactPtr contact(qobject_cast<Tp::Contact*>(sender()));
Q_EMIT contactChanged(createUri(contact), contactToAddressee(contact));
m_contacts.remove(contact->id());
}
KABC::Addressee::Map KTpAllContacts::contacts()
{
KABC::Addressee::Map contactMap;
Q_FOREACH(const Tp::ContactPtr &contact, m_contacts.values()) {
contactMap.insert(createUri(contact), contactToAddressee(contact));
}
kDebug() << contactMap.keys().size();
return contactMap;
}
KABC::Addressee KTpAllContacts::contactToAddressee(const Tp::ContactPtr &contact) const
{
KABC::Addressee vcard;
Tp::AccountPtr account = KTp::contactManager()->accountForContact(contact);
if (contact && account) {
vcard.setFormattedName(contact->alias());
vcard.setCategories(contact->groups());
vcard.insertCustom(QLatin1String("telepathy"), QLatin1String("contactId"), contact->id());
vcard.insertCustom(QLatin1String("telepathy"), QLatin1String("accountPath"), account->objectPath());
vcard.insertCustom(QLatin1String("telepathy"), QLatin1String("presence"), contact->presence().status());
vcard.setPhoto(KABC::Picture(contact->avatarData().fileName));
}
return vcard;
}
IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
Q_UNUSED(args);
}
IMPersonsDataSource::~IMPersonsDataSource()
{
}
AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()
{
return new KTpAllContacts();
}
#include "im-persons-data-source.moc"
<commit_msg>Watch for more contact properties changing in kpeople data source<commit_after>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
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 "im-persons-data-source.h"
#include <KPeople/PersonsModel>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Presence>
#include "KTp/contact-factory.h"
#include "KTp/global-contact-manager.h"
#include "KTp/types.h"
#include <KDebug>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Nepomuk2/ResourceManager>
using namespace KPeople;
class KTpAllContacts : public AllContactsMonitor
{
Q_OBJECT
public:
KTpAllContacts();
~KTpAllContacts();
virtual KABC::Addressee::Map contacts();
private Q_SLOTS:
void onAccountManagerReady(Tp::PendingOperation *op);
void onContactChanged();
void onContactInvalidated();
void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);
private:
QString createUri(const Tp::ContactPtr &contact) const;
KABC::Addressee contactToAddressee(const Tp::ContactPtr &contact) const;
QHash<QString, KTp::ContactPtr> m_contacts;
};
KTpAllContacts::KTpAllContacts()
{
Tp::registerTypes();
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
KTpAllContacts::~KTpAllContacts()
{
}
QString KTpAllContacts::createUri(const Tp::ContactPtr &contact) const
{
return QLatin1String("ktp://") + contact->id();
}
void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Failed to initialize AccountManager:" << op->errorName();
kWarning() << op->errorMessage();
return;
}
kDebug() << "Account manager ready";
connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());
}
void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_contacts.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &contact, contactsRemoved) {
m_contacts.remove(contact->id());
Q_EMIT contactRemoved(createUri(contact));
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);
m_contacts.insert(contact->id(), ktpContact);
Q_EMIT contactAdded(createUri(ktpContact), contactToAddressee(ktpContact));
connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(invalidated()),
this, SLOT(onContactInvalidated()));
connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),
this, SLOT(onContactChanged()));
}
}
void KTpAllContacts::onContactChanged()
{
const Tp::ContactPtr contact(qobject_cast<Tp::Contact*>(sender()));
Q_EMIT contactChanged(createUri(contact), contactToAddressee(contact));
}
void KTpAllContacts::onContactInvalidated()
{
const Tp::ContactPtr contact(qobject_cast<Tp::Contact*>(sender()));
Q_EMIT contactChanged(createUri(contact), contactToAddressee(contact));
m_contacts.remove(contact->id());
}
KABC::Addressee::Map KTpAllContacts::contacts()
{
KABC::Addressee::Map contactMap;
Q_FOREACH(const Tp::ContactPtr &contact, m_contacts.values()) {
contactMap.insert(createUri(contact), contactToAddressee(contact));
}
kDebug() << contactMap.keys().size();
return contactMap;
}
KABC::Addressee KTpAllContacts::contactToAddressee(const Tp::ContactPtr &contact) const
{
KABC::Addressee vcard;
Tp::AccountPtr account = KTp::contactManager()->accountForContact(contact);
if (contact && account) {
vcard.setFormattedName(contact->alias());
vcard.setCategories(contact->groups());
vcard.insertCustom(QLatin1String("telepathy"), QLatin1String("contactId"), contact->id());
vcard.insertCustom(QLatin1String("telepathy"), QLatin1String("accountPath"), account->objectPath());
vcard.insertCustom(QLatin1String("telepathy"), QLatin1String("presence"), contact->presence().status());
vcard.setPhoto(KABC::Picture(contact->avatarData().fileName));
}
return vcard;
}
IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
Q_UNUSED(args);
}
IMPersonsDataSource::~IMPersonsDataSource()
{
}
AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()
{
return new KTpAllContacts();
}
#include "im-persons-data-source.moc"
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2016 ME_Kun_Han
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 "rs_module_log.h"
#include "rs_kernel_io.h"
#include "rs_kernel_context.h"
#define MESSAGE_BUFFER_LENGTH 4096
RsTCPListener::RsTCPListener() {
_extra_param = nullptr;
// RsConnContext::getInstance()->do_register(this);
}
RsTCPListener::~RsTCPListener() {
close();
// RsConnContext::getInstance()->do_deregister(this);
}
void RsTCPListener::on_connection(uv_stream_t *s, int status) {
assert(status == 0);
int ret = ERROR_SUCCESS;
auto pr_this = static_cast<RsTCPListener *>(s->data);
uv_tcp_t *in_conn = new uv_tcp_t();
if ((ret = uv_tcp_init(uv_default_loop(), in_conn)) != ERROR_SUCCESS) {
rs_error(nullptr, "initialize the client socket from loop failed. ret=%d", ret);
return;
}
if ((ret = uv_accept(s, (uv_stream_t *) in_conn)) != ERROR_SUCCESS) {
rs_error(nullptr, "accept one connection failed. ret=%d", ret);
return;
}
RsTCPSocketIO io;
if ((ret = io.initialize(in_conn)) != ERROR_SUCCESS) {
rs_error(pr_this, "accept one connection for tcp failed. ret=%d", ret);
return;
}
pr_this->_cb(&io, pr_this->_extra_param);
}
int RsTCPListener::initialize(std::string ip, int port, on_new_connection_cb cb, void *param) {
int ret = ERROR_SUCCESS;
_cb = cb;
_extra_param = param;
if ((ret = uv_tcp_init(uv_default_loop(), &_listen_sock)) != ERROR_SUCCESS) {
rs_error(this, "create socket using libuv failed. ret=%d", ret);
return ret;
}
_listen_sock.data = this;
struct sockaddr_in addr{};
if ((ret = uv_ip4_addr(ip.c_str(), port, &addr)) != ERROR_SUCCESS) {
rs_error(this, "initialize the ip4 address failed. ret=%d", ret);
return ret;
}
if ((ret = uv_tcp_bind(&_listen_sock, (const struct sockaddr *) &addr, 0)) != ERROR_SUCCESS) {
rs_error(this, "bind socket failed. ret=%d", ret);
return ret;
}
if ((ret = uv_listen((uv_stream_t *) &_listen_sock, 128, on_connection)) != ERROR_SUCCESS) {
rs_error(this, "socket listen failed. ret=%d", ret);
return ret;
}
return ret;
}
void RsTCPListener::close() {
uv_shutdown_t uv_shutdown_req;
uv_shutdown_req.data = this;
int ret = ERROR_SUCCESS;
auto shutdown_cb = [](uv_shutdown_t *req, int status) {
auto io = (RsTCPListener *) req->data;
rs_info(io, "do shutdown!");
};
if ((ret = uv_shutdown(&uv_shutdown_req, (uv_stream_t *) &_listen_sock, shutdown_cb)) != 0) {
rs_error(this, "shutdown tcp listener failed. ret=%d", ret);
return;
}
/*
auto close_cb = [](uv_handle_t *handle) {
};
if ((ret = uv_close((uv_handle_t *) &_listen_sock, close_cb)) != ERROR_SUCCESS) {
rs_error(this, "close tcp listener failed. ret=%d", ret);
return;
}
*/
}
RsTCPSocketIO::RsTCPSocketIO() {
_base.reserve(MESSAGE_BUFFER_LENGTH);
RsConnContext::getInstance()->do_register(this);
}
RsTCPSocketIO::~RsTCPSocketIO() {
RsConnContext::getInstance()->do_deregister(this);
}
int RsTCPSocketIO::initialize(uv_tcp_t *stream) {
int ret = ERROR_SUCCESS;
assert(_uv_tcp_socket == nullptr);
_uv_tcp_socket = stream;
_uv_tcp_socket->data = this;
// start to read
auto alloc_cb = [](uv_handle_t *handle,
size_t suggested_size,
uv_buf_t *buf) {
auto io = (RsTCPSocketIO *) handle->data;
*buf = uv_buf_init(io->_base.data(), MESSAGE_BUFFER_LENGTH);
};
auto read_cb = [](uv_stream_t *stream,
ssize_t num_read,
const uv_buf_t *buf) {
auto io = (RsTCPSocketIO *) stream->data;
if (num_read <= 0) {
io->close();
return;
}
io->buffer.append(buf->base, (unsigned long) num_read);
rs_info(io, "get message: \n%s\n, number of read=%d", buf->base, num_read);
};
if ((ret = uv_read_start((uv_stream_t *) _uv_tcp_socket, alloc_cb, read_cb)) != ERROR_SUCCESS) {
rs_error(this, "start to read failed. ret=%d", ret);
return ret;
}
rs_info(this, "ready to read message");
return ret;
}
int RsTCPSocketIO::write(std::string buf, int size) {
int ret = ERROR_SUCCESS;
assert(buf.size() >= size);
auto write_cb = [](uv_write_t *req, int status) {
if (status == UV_EINVAL) {
rs_error(nullptr, "invalid");
}
rs_info(nullptr, "write finished, status=%d", status);
};
uv_write_t write_req;
uv_buf_t test_buf = {(char *) buf.c_str(), (size_t) size};
if ((ret = uv_write(&write_req, (uv_stream_t *) &_uv_tcp_socket, &test_buf, 1, write_cb)) !=
ERROR_SUCCESS) {
rs_error(this, "write failed. ret=%d", ret);
return ret;
}
return ret;
}
int RsTCPSocketIO::read(std::string &buf, int size) {
int ret = ERROR_SUCCESS;
while (buffer.size() < size) {
rs_info(this, "wait for new message from client");
}
buf = buffer.substr(0, (unsigned long) size);
buffer.erase(0, (unsigned long) size);
return ret;
}
void RsTCPSocketIO::close() {
uv_shutdown_t uvShutdown;
uv_shutdown(&uvShutdown, (uv_stream_t *) &_uv_tcp_socket, [](uv_shutdown_t *req, int status) {
rs_info(nullptr, "shut down");
});
uv_close((uv_handle_t *) &_uv_tcp_socket, [](uv_handle_t *handle) {
rs_info(nullptr, "close");
});
}
<commit_msg>fix io part<commit_after>/*
MIT License
Copyright (c) 2016 ME_Kun_Han
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 "rs_module_log.h"
#include "rs_kernel_io.h"
#include "rs_kernel_context.h"
#define MESSAGE_BUFFER_LENGTH 4096
RsTCPListener::RsTCPListener() {
_extra_param = nullptr;
RsConnContext::getInstance()->do_register(this);
}
RsTCPListener::~RsTCPListener() {
close();
RsConnContext::getInstance()->do_deregister(this);
}
void RsTCPListener::on_connection(uv_stream_t *s, int status) {
assert(status == 0);
int ret = ERROR_SUCCESS;
auto pt_this = static_cast<RsTCPListener *>(s->data);
rs_info(pt_this, "get one tcp connection");
auto in_conn = new uv_tcp_t();
if ((ret = uv_tcp_init(uv_default_loop(), in_conn)) != ERROR_SUCCESS) {
rs_error(nullptr, "initialize the client socket from loop failed. ret=%d", ret);
return;
}
if ((ret = uv_accept(s, (uv_stream_t *) in_conn)) != ERROR_SUCCESS) {
rs_error(nullptr, "accept one connection failed. ret=%d", ret);
return;
}
RsTCPSocketIO io;
if ((ret = io.initialize(in_conn)) != ERROR_SUCCESS) {
rs_error(pt_this, "accept one connection for tcp failed. ret=%d", ret);
return;
}
pt_this->_cb(&io, pt_this->_extra_param);
}
int RsTCPListener::initialize(std::string ip, int port, on_new_connection_cb cb, void *param) {
int ret = ERROR_SUCCESS;
_cb = cb;
_extra_param = param;
if ((ret = uv_tcp_init(uv_default_loop(), &_listen_sock)) != ERROR_SUCCESS) {
rs_error(this, "create socket using libuv failed. ret=%d", ret);
return ret;
}
_listen_sock.data = this;
struct sockaddr_in addr{};
if ((ret = uv_ip4_addr(ip.c_str(), port, &addr)) != ERROR_SUCCESS) {
rs_error(this, "initialize the ip4 address failed. ret=%d", ret);
return ret;
}
if ((ret = uv_tcp_bind(&_listen_sock, (const struct sockaddr *) &addr, 0)) != ERROR_SUCCESS) {
rs_error(this, "bind socket failed. ret=%d", ret);
return ret;
}
if ((ret = uv_listen((uv_stream_t *) &_listen_sock, 128, on_connection)) != ERROR_SUCCESS) {
rs_error(this, "socket listen failed. ret=%d", ret);
return ret;
}
rs_info(this, "initialize one tcp listener success!");
return ret;
}
void RsTCPListener::close() {
uv_shutdown_t uv_shutdown_req;
uv_shutdown_req.data = this;
int ret = ERROR_SUCCESS;
auto shutdown_cb = [](uv_shutdown_t *req, int status) {
auto io = (RsTCPListener *) req->data;
rs_info(io, "do shutdown!");
};
if ((ret = uv_shutdown(&uv_shutdown_req, (uv_stream_t *) &_listen_sock, shutdown_cb)) != 0) {
rs_error(this, "shutdown tcp listener failed. ret=%d", ret);
return;
}
/*
auto close_cb = [](uv_handle_t *handle) {
};
if ((ret = uv_close((uv_handle_t *) &_listen_sock, close_cb)) != ERROR_SUCCESS) {
rs_error(this, "close tcp listener failed. ret=%d", ret);
return;
}
*/
}
RsTCPSocketIO::RsTCPSocketIO() {
_base.reserve(MESSAGE_BUFFER_LENGTH);
_uv_tcp_socket = nullptr;
RsConnContext::getInstance()->do_register(this);
}
RsTCPSocketIO::~RsTCPSocketIO() {
RsConnContext::getInstance()->do_deregister(this);
}
int RsTCPSocketIO::initialize(uv_tcp_t *stream) {
int ret = ERROR_SUCCESS;
_uv_tcp_socket = stream;
_uv_tcp_socket->data = this;
// start to read
auto alloc_cb = [](uv_handle_t *handle,
size_t suggested_size,
uv_buf_t *buf) {
auto io = (RsTCPSocketIO *) handle->data;
*buf = uv_buf_init(io->_base.data(), MESSAGE_BUFFER_LENGTH);
};
auto read_cb = [](uv_stream_t *stream,
ssize_t num_read,
const uv_buf_t *buf) {
auto io = (RsTCPSocketIO *) stream->data;
if (num_read <= 0) {
io->close();
return;
}
rs_info(io, "get message: \n%s\n, number of read=%d", buf->base, num_read);
};
if ((ret = uv_read_start((uv_stream_t *) _uv_tcp_socket, alloc_cb, read_cb)) !=
ERROR_SUCCESS) {
rs_error(this, "start to read failed. ret=%d", ret);
return ret;
}
rs_info(this, "ready to read message");
return ret;
}
int RsTCPSocketIO::write(std::string buf, int size) {
int ret = ERROR_SUCCESS;
assert(buf.size() >= size);
auto write_cb = [](uv_write_t *req, int status) {
if (status == UV_EINVAL) {
rs_error(nullptr, "invalid");
}
rs_info(nullptr, "write finished, status=%d", status);
};
uv_write_t write_req;
uv_buf_t test_buf = {(char *) buf.c_str(), (size_t) size};
if ((ret = uv_write(&write_req, (uv_stream_t *) _uv_tcp_socket, &test_buf, 1,
write_cb)) !=
ERROR_SUCCESS) {
rs_error(this, "write failed. ret=%d", ret);
return ret;
}
return ret;
}
int RsTCPSocketIO::read(std::string &buf, int size) {
int ret = ERROR_SUCCESS;
while (buffer.size() < size) {
rs_info(this, "wait for new message from client");
}
buf = buffer.substr(0, (unsigned long) size);
buffer.erase(0, (unsigned long) size);
return ret;
}
void RsTCPSocketIO::close() {
uv_close((uv_handle_t *) _uv_tcp_socket, NULL);
rs_free_p(_uv_tcp_socket);
rs_info(this, "close one tcp io");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: servicenames_coosystems.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: iha $ $Date: 2004-01-17 13:09:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CHART2_SERVICENAMES_COOSYSTEMS_HXX
#define _CHART2_SERVICENAMES_COOSYSTEMS_HXX
//.............................................................................
namespace chart
{
//.............................................................................
#define CHART2_COOSYSTEM_CARTESIAN_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.Cartesian")
#define CHART2_COOSYSTEM_CARTESIAN_VIEW_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.CartesianView")
#define CHART2_COOSYSTEM_POLAR_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.Polar")
#define CHART2_COOSYSTEM_POLAR_VIEW_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.PolarView")
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.110); FILE MERGED 2005/09/05 18:42:56 rt 1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: servicenames_coosystems.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:48:04 $
*
* 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 _CHART2_SERVICENAMES_COOSYSTEMS_HXX
#define _CHART2_SERVICENAMES_COOSYSTEMS_HXX
//.............................................................................
namespace chart
{
//.............................................................................
#define CHART2_COOSYSTEM_CARTESIAN_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.Cartesian")
#define CHART2_COOSYSTEM_CARTESIAN_VIEW_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.CartesianView")
#define CHART2_COOSYSTEM_POLAR_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.Polar")
#define CHART2_COOSYSTEM_POLAR_VIEW_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.CoordinateSystems.PolarView")
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|> |
<commit_before>/* dtkCommunicatorMpi.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Mon Feb 15 16:51:02 2010 (+0100)
* Version: $Id$
* Last-Updated: jeu. oct. 4 18:11:31 2012 (+0200)
* By: Nicolas Niclausse
* Update #: 615
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkDistributedCommunicatorMpi.h"
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkLog/dtkLog.h>
#include <dtkMath>
#include <mpi.h>
// /////////////////////////////////////////////////////////////////
// Helper functions
// /////////////////////////////////////////////////////////////////
MPI::Datatype data_type(dtkDistributedCommunicator::DataType type)
{
switch(type) {
case dtkDistributedCommunicator::dtkDistributedCommunicatorBool: return MPI::BOOL;
case dtkDistributedCommunicator::dtkDistributedCommunicatorChar: return MPI::CHAR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorInt: return MPI::INT;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLong: return MPI::LONG;
case dtkDistributedCommunicator::dtkDistributedCommunicatorInt64: return MPI::LONG_LONG;
case dtkDistributedCommunicator::dtkDistributedCommunicatorFloat: return MPI::FLOAT;
case dtkDistributedCommunicator::dtkDistributedCommunicatorDouble: return MPI::DOUBLE;
default:
dtkInfo() << "dtkCommunicatorMpi: data type not handled.";
return MPI::BYTE;
}
}
MPI::Op operation_type(dtkDistributedCommunicator::OperationType type)
{
switch(type) {
case dtkDistributedCommunicator::dtkDistributedCommunicatorMin: return MPI::MIN;
case dtkDistributedCommunicator::dtkDistributedCommunicatorMax: return MPI::MAX;
case dtkDistributedCommunicator::dtkDistributedCommunicatorSum: return MPI::SUM;
case dtkDistributedCommunicator::dtkDistributedCommunicatorProduct: return MPI::PROD;
case dtkDistributedCommunicator::dtkDistributedCommunicatorBitwiseAnd: return MPI::BAND;
case dtkDistributedCommunicator::dtkDistributedCommunicatorBitwiseOr: return MPI::BOR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorBitwiseXor: return MPI::BXOR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLogicalAnd: return MPI::LAND;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLogicalOr: return MPI::LOR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLogicalXor: return MPI::LXOR;
default:
dtkInfo() << "dtkCommunicatorMpi: operation type not handled.";
return MPI::MIN;
}
}
// /////////////////////////////////////////////////////////////////
// dtkCommunicatorMpi
// /////////////////////////////////////////////////////////////////
class dtkDistributedCommunicatorMpiPrivate
{
public:
};
dtkDistributedCommunicatorMpi::dtkDistributedCommunicatorMpi(void) : dtkDistributedCommunicator(), d(new dtkDistributedCommunicatorMpiPrivate)
{
}
dtkDistributedCommunicatorMpi::~dtkDistributedCommunicatorMpi(void)
{
delete d;
d = NULL;
}
dtkDistributedCommunicatorMpi::dtkDistributedCommunicatorMpi(const dtkDistributedCommunicatorMpi& other)
{
}
dtkDistributedCommunicatorMpi& dtkDistributedCommunicatorMpi::operator=(const dtkDistributedCommunicatorMpi& other)
{
return *this;
}
//! Mpi communicator initializer.
/*!
* Initializes the MPI execution environment. This function must be
* called in every MPI program, must be called before any other MPI
* functions and must be called only once in an MPI program.
*
* \code
* dtkDistributedCommunicator *communicator = new dtkDistributedCommunicatorMpi;
* communicator->initialize();
* ...
* ...
* communicator->uninitialize();
* \endcode
*
* \sa uninitialize.
*/
void dtkDistributedCommunicatorMpi::initialize(void)
{
int argc = qApp->argc(); // These methods are obsolete but should be really exist in QCoreApplication
char **argv = qApp->argv(); // These methods are obsolete but should be really exist in QCoreApplication
MPI::Init(argc, argv);
}
bool dtkDistributedCommunicatorMpi::initialized(void)
{
return MPI::Is_initialized();
}
//! Mpi communicator uninitializer.
/*!
* Terminates the MPI execution environment. This function should be
* the last MPI routine called in every MPI program - no other MPI
* routines may be called after it.
*
* \code
* dtkDistributedCommunicator *communicator = new dtkDistributedCommunicatorMpi;
* communicator->initialize();
* ...
* ...
* communicator->uninitialize();
* \endcode
*
* \sa initialize.
*/
void dtkDistributedCommunicatorMpi::uninitialize(void)
{
MPI::Finalize();
}
//!
/*!
* Returns an elapsed wall clock time in seconds (double precision)
* on the calling processor.
*
* \sa tick.
*/
double dtkDistributedCommunicatorMpi::time(void)
{
return MPI::Wtime();
}
//!
/*!
* Returns the resolution in seconds (double precision) of time().
*
* \sa time.
*/
double dtkDistributedCommunicatorMpi::tick(void)
{
return MPI::Wtick();
}
//!
/*!
* Determines the rank of the calling process within the
* communicator. Initially, each process will be assigned a unique
* integer rank between 0 and number of processors - 1 within the
* communicator.
*
* \sa size.
*/
int dtkDistributedCommunicatorMpi::rank(void)
{
return MPI::COMM_WORLD.Get_rank();
}
//!
/*!
* Determines the number of processes in the group associated with a
* communicator.
*
* \sa rank.
*/
int dtkDistributedCommunicatorMpi::size(void)
{
return MPI::COMM_WORLD.Get_size();
}
//!
/*!
* Returns the name of the processor.
*/
QString dtkDistributedCommunicatorMpi::name(void) const
{
int len; char name[MPI_MAX_PROCESSOR_NAME];
memset(name,0,MPI_MAX_PROCESSOR_NAME);
MPI::Get_processor_name(name,len);
memset(name+len,0,MPI_MAX_PROCESSOR_NAME-len);
return QString(name);
}
//! Standard-mode, blocking send.
/*!
* Basic blocking send operation. Routine returns only after the
* application buffer in the sending task is free for reuse.
*/
void dtkDistributedCommunicatorMpi::send(void *data, qint64 size, DataType dataType, qint16 target, int tag)
{
MPI::COMM_WORLD.Send(data, size, data_type(dataType), target, tag);
}
//! Standard-mode, blocking receive.
/*!
* Receive a message and block until the requested data is available
* in the application buffer in the receiving task.
*/
void dtkDistributedCommunicatorMpi::receive(void *data, qint64 size, DataType dataType, qint16 source, int tag)
{
MPI::COMM_WORLD.Recv(data, size, data_type(dataType), source, tag);
}
void dtkDistributedCommunicatorMpi::receive(void *data, qint64 size, DataType dataType, qint16 source, int tag, int& from)
{
MPI::Status status;
MPI::COMM_WORLD.Recv(data, size, data_type(dataType), source, tag, status);
from = status.Get_source();
}
/*!
* send a dtkAbstractData object; we need to send it's type (with the
* size type) and then serialize the object.
*/
void dtkDistributedCommunicatorMpi::send(dtkAbstractData *data, qint16 target, int tag)
{
QString type = data->identifier();
qint64 typeLength = type.length()+1;
qint64 s=1;
dtkDistributedCommunicator::send(&typeLength,s,target,tag);
QByteArray typeArray = type.toAscii();
char *typeChar = typeArray.data();
dtkDistributedCommunicator::send(typeChar,typeLength,target,tag);
QByteArray *array = data->serialize();
if (!array) {
dtkError() <<"serialization failed";
} else {
qint64 arrayLength = array->length();
dtkDistributedCommunicator::send(&arrayLength,1,target,tag);
dtkDistributedCommunicator::send(array->data(),arrayLength,target,tag);
}
}
void dtkDistributedCommunicatorMpi::receive(dtkAbstractData *&data, qint16 source, int tag)
{
qint64 typeLength;
qint64 arrayLength;
dtkDistributedCommunicator::receive(&typeLength,1,source,tag);
char type[typeLength];
dtkDistributedCommunicator::receive(type, typeLength, source,tag);
dtkDistributedCommunicator::receive(&arrayLength,1,source,tag);
char rawArray[arrayLength];
dtkDistributedCommunicator::receive(rawArray, arrayLength, source,tag);
if(!data) {
data = dtkAbstractDataFactory::instance()->create(QString(type));
if (!data) {
dtkWarn() << "Can't instantiate object of type" << QString(type);
return;
}
} else {
if(data->identifier() != QString(type)) {
dtkWarn() << DTK_PRETTY_FUNCTION << "Warning, type mismatch";
}
}
QByteArray array = QByteArray::fromRawData(rawArray, arrayLength);
// FIXME: array is not null-terminated, does it matter ??
data = data->deserialize(array);
if (!data) {
dtkError() << "Warning: deserialization failed";
}
}
/*!
* send a QString
*/
void dtkDistributedCommunicatorMpi::send(const QString &s, qint16 target, int tag)
{
qint64 length = s.length()+1;
qint64 size_l=1;
dtkDistributedCommunicator::send(&length,size_l,target,tag);
QByteArray Array = s.toAscii();
char *char_array = Array.data();
dtkDistributedCommunicator::send(char_array,length,target,tag);
}
void dtkDistributedCommunicatorMpi::send(QByteArray &array, qint16 target, int tag)
{
qint64 arrayLength = array.length();
dtkDistributedCommunicator::send(&arrayLength,1,target,tag);
char *data = array.data();
dtkDistributedCommunicator::send(data, arrayLength, target, tag);
}
void dtkDistributedCommunicatorMpi::receive(QString &s, qint16 source, int tag)
{
qint64 length;
dtkDistributedCommunicator::receive(&length,1,source,tag);
char s_c[length];
dtkDistributedCommunicator::receive(s_c, length, source,tag);
s = QString(s_c);
}
void dtkDistributedCommunicatorMpi::receive(QByteArray &array, qint16 source, int tag)
{
qint64 arrayLength;
dtkDistributedCommunicator::receive(&arrayLength,1,source,tag);
array.resize(arrayLength);
dtkDistributedCommunicator::receive(array.data(), arrayLength, source, tag);
}
//! Barrier.
/*!
* Creates a barrier synchronization. Each task, when reaching the
* barrier call, blocks until all tasks in the group reach the same
* barrier call.
*/
void dtkDistributedCommunicatorMpi::barrier(void)
{
MPI::COMM_WORLD.Barrier();
}
//! Broadcast.
/*!
* Broadcasts (sends) a message from the process with rank "source"
* to all other processes in the group.
*/
void dtkDistributedCommunicatorMpi::broadcast(void *data, qint64 size, DataType dataType, qint16 source)
{
MPI::COMM_WORLD.Bcast(data, size, data_type(dataType), source);
}
//! Gather.
/*!
* Gathers distinct messages from each task in the group to a single
* destination task. This routine is the reverse operation of
* scatter. If all is true, target is not taken into account.
*
* \sa scatter.
*/
void dtkDistributedCommunicatorMpi::gather(void *send, void *recv, qint64 size, DataType dataType, qint16 target, bool all)
{
if(all)
MPI::COMM_WORLD.Allgather(send, size, data_type(dataType), recv, size, data_type(dataType));
else
MPI::COMM_WORLD.Gather(send, size, data_type(dataType), recv, size, data_type(dataType), target);
}
//! Scatter.
/*!
* Distributes distinct messages from a single source task to each
* task in the group.
*
* \sa gather.
*/
void dtkDistributedCommunicatorMpi::scatter(void *send, void *recv, qint64 size, DataType dataType, qint16 source)
{
MPI::COMM_WORLD.Scatter(send, size, data_type(dataType), recv, size, data_type(dataType), source);
}
//! Reduce.
/*!
* Applies a reduction operation on all tasks in the group and places
* the result in one task. If all is true, target is not taken into
* account.
*
* \sa dtkDistributedCommunicator::OperationType.
*/
void dtkDistributedCommunicatorMpi::reduce(void *send, void *recv, qint64 size, DataType dataType, OperationType operationType, qint16 target, bool all)
{
if(all)
MPI::COMM_WORLD.Allreduce(send, recv, size, data_type(dataType), operation_type(operationType));
else
MPI::COMM_WORLD.Reduce(send, recv, size, data_type(dataType), operation_type(operationType), target);
}
// /////////////////////////////////////////////////////////////////
// Documentation
// /////////////////////////////////////////////////////////////////
//! \class dtkDistributedCommunicatorMpi
/*!
* \brief A mpi based dtk communicator.
*/
<commit_msg>don't use intermediate pointer<commit_after>/* dtkCommunicatorMpi.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Mon Feb 15 16:51:02 2010 (+0100)
* Version: $Id$
* Last-Updated: lun. oct. 8 15:49:10 2012 (+0200)
* By: Nicolas Niclausse
* Update #: 629
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkDistributedCommunicatorMpi.h"
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkLog/dtkLog.h>
#include <dtkMath>
#include <mpi.h>
// /////////////////////////////////////////////////////////////////
// Helper functions
// /////////////////////////////////////////////////////////////////
MPI::Datatype data_type(dtkDistributedCommunicator::DataType type)
{
switch(type) {
case dtkDistributedCommunicator::dtkDistributedCommunicatorBool: return MPI::BOOL;
case dtkDistributedCommunicator::dtkDistributedCommunicatorChar: return MPI::CHAR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorInt: return MPI::INT;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLong: return MPI::LONG;
case dtkDistributedCommunicator::dtkDistributedCommunicatorInt64: return MPI::LONG_LONG;
case dtkDistributedCommunicator::dtkDistributedCommunicatorFloat: return MPI::FLOAT;
case dtkDistributedCommunicator::dtkDistributedCommunicatorDouble: return MPI::DOUBLE;
default:
dtkInfo() << "dtkCommunicatorMpi: data type not handled.";
return MPI::BYTE;
}
}
MPI::Op operation_type(dtkDistributedCommunicator::OperationType type)
{
switch(type) {
case dtkDistributedCommunicator::dtkDistributedCommunicatorMin: return MPI::MIN;
case dtkDistributedCommunicator::dtkDistributedCommunicatorMax: return MPI::MAX;
case dtkDistributedCommunicator::dtkDistributedCommunicatorSum: return MPI::SUM;
case dtkDistributedCommunicator::dtkDistributedCommunicatorProduct: return MPI::PROD;
case dtkDistributedCommunicator::dtkDistributedCommunicatorBitwiseAnd: return MPI::BAND;
case dtkDistributedCommunicator::dtkDistributedCommunicatorBitwiseOr: return MPI::BOR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorBitwiseXor: return MPI::BXOR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLogicalAnd: return MPI::LAND;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLogicalOr: return MPI::LOR;
case dtkDistributedCommunicator::dtkDistributedCommunicatorLogicalXor: return MPI::LXOR;
default:
dtkInfo() << "dtkCommunicatorMpi: operation type not handled.";
return MPI::MIN;
}
}
// /////////////////////////////////////////////////////////////////
// dtkCommunicatorMpi
// /////////////////////////////////////////////////////////////////
class dtkDistributedCommunicatorMpiPrivate
{
public:
};
dtkDistributedCommunicatorMpi::dtkDistributedCommunicatorMpi(void) : dtkDistributedCommunicator(), d(new dtkDistributedCommunicatorMpiPrivate)
{
}
dtkDistributedCommunicatorMpi::~dtkDistributedCommunicatorMpi(void)
{
delete d;
d = NULL;
}
dtkDistributedCommunicatorMpi::dtkDistributedCommunicatorMpi(const dtkDistributedCommunicatorMpi& other)
{
}
dtkDistributedCommunicatorMpi& dtkDistributedCommunicatorMpi::operator=(const dtkDistributedCommunicatorMpi& other)
{
return *this;
}
//! Mpi communicator initializer.
/*!
* Initializes the MPI execution environment. This function must be
* called in every MPI program, must be called before any other MPI
* functions and must be called only once in an MPI program.
*
* \code
* dtkDistributedCommunicator *communicator = new dtkDistributedCommunicatorMpi;
* communicator->initialize();
* ...
* ...
* communicator->uninitialize();
* \endcode
*
* \sa uninitialize.
*/
void dtkDistributedCommunicatorMpi::initialize(void)
{
int argc = qApp->argc(); // These methods are obsolete but should be really exist in QCoreApplication
char **argv = qApp->argv(); // These methods are obsolete but should be really exist in QCoreApplication
MPI::Init(argc, argv);
}
bool dtkDistributedCommunicatorMpi::initialized(void)
{
return MPI::Is_initialized();
}
//! Mpi communicator uninitializer.
/*!
* Terminates the MPI execution environment. This function should be
* the last MPI routine called in every MPI program - no other MPI
* routines may be called after it.
*
* \code
* dtkDistributedCommunicator *communicator = new dtkDistributedCommunicatorMpi;
* communicator->initialize();
* ...
* ...
* communicator->uninitialize();
* \endcode
*
* \sa initialize.
*/
void dtkDistributedCommunicatorMpi::uninitialize(void)
{
MPI::Finalize();
}
//!
/*!
* Returns an elapsed wall clock time in seconds (double precision)
* on the calling processor.
*
* \sa tick.
*/
double dtkDistributedCommunicatorMpi::time(void)
{
return MPI::Wtime();
}
//!
/*!
* Returns the resolution in seconds (double precision) of time().
*
* \sa time.
*/
double dtkDistributedCommunicatorMpi::tick(void)
{
return MPI::Wtick();
}
//!
/*!
* Determines the rank of the calling process within the
* communicator. Initially, each process will be assigned a unique
* integer rank between 0 and number of processors - 1 within the
* communicator.
*
* \sa size.
*/
int dtkDistributedCommunicatorMpi::rank(void)
{
return MPI::COMM_WORLD.Get_rank();
}
//!
/*!
* Determines the number of processes in the group associated with a
* communicator.
*
* \sa rank.
*/
int dtkDistributedCommunicatorMpi::size(void)
{
return MPI::COMM_WORLD.Get_size();
}
//!
/*!
* Returns the name of the processor.
*/
QString dtkDistributedCommunicatorMpi::name(void) const
{
int len; char name[MPI_MAX_PROCESSOR_NAME];
memset(name,0,MPI_MAX_PROCESSOR_NAME);
MPI::Get_processor_name(name,len);
memset(name+len,0,MPI_MAX_PROCESSOR_NAME-len);
return QString(name);
}
//! Standard-mode, blocking send.
/*!
* Basic blocking send operation. Routine returns only after the
* application buffer in the sending task is free for reuse.
*/
void dtkDistributedCommunicatorMpi::send(void *data, qint64 size, DataType dataType, qint16 target, int tag)
{
MPI::COMM_WORLD.Send(data, size, data_type(dataType), target, tag);
}
//! Standard-mode, blocking receive.
/*!
* Receive a message and block until the requested data is available
* in the application buffer in the receiving task.
*/
void dtkDistributedCommunicatorMpi::receive(void *data, qint64 size, DataType dataType, qint16 source, int tag)
{
MPI::COMM_WORLD.Recv(data, size, data_type(dataType), source, tag);
}
void dtkDistributedCommunicatorMpi::receive(void *data, qint64 size, DataType dataType, qint16 source, int tag, int& from)
{
MPI::Status status;
MPI::COMM_WORLD.Recv(data, size, data_type(dataType), source, tag, status);
from = status.Get_source();
}
/*!
* send a dtkAbstractData object; we need to send it's type (with the
* size type) and then serialize the object.
*/
void dtkDistributedCommunicatorMpi::send(dtkAbstractData *data, qint16 target, int tag)
{
QString type = data->identifier();
qint64 typeLength = type.length()+1;
qint64 s=1;
dtkDistributedCommunicator::send(&typeLength,s,target,tag);
QByteArray typeArray = type.toAscii();
char *typeChar = typeArray.data();
dtkDistributedCommunicator::send(typeChar,typeLength,target,tag);
QByteArray *array = data->serialize();
if (!array) {
dtkError() <<"serialization failed";
} else {
qint64 arrayLength = array->length();
dtkDistributedCommunicator::send(&arrayLength,1,target,tag);
dtkDistributedCommunicator::send(array->data(),arrayLength,target,tag);
}
}
void dtkDistributedCommunicatorMpi::receive(dtkAbstractData *&data, qint16 source, int tag)
{
qint64 typeLength;
qint64 arrayLength;
dtkDistributedCommunicator::receive(&typeLength,1,source,tag);
char type[typeLength];
dtkDistributedCommunicator::receive(type, typeLength, source,tag);
dtkDistributedCommunicator::receive(&arrayLength,1,source,tag);
char rawArray[arrayLength];
dtkDistributedCommunicator::receive(rawArray, arrayLength, source,tag);
if(!data) {
data = dtkAbstractDataFactory::instance()->create(QString(type));
if (!data) {
dtkWarn() << "Can't instantiate object of type" << QString(type);
return;
}
} else {
if(data->identifier() != QString(type)) {
dtkWarn() << DTK_PRETTY_FUNCTION << "Warning, type mismatch";
}
}
QByteArray array = QByteArray::fromRawData(rawArray, arrayLength);
// FIXME: array is not null-terminated, does it matter ??
data = data->deserialize(array);
if (!data) {
dtkError() << "Warning: deserialization failed";
}
}
/*!
* send a QString
*/
void dtkDistributedCommunicatorMpi::send(const QString &s, qint16 target, int tag)
{
qint64 length = s.length()+1;
qint64 size_l=1;
dtkDistributedCommunicator::send(&length,size_l,target,tag);
QByteArray Array = s.toAscii();
char *char_array = Array.data();
dtkDistributedCommunicator::send(char_array,length,target,tag);
}
void dtkDistributedCommunicatorMpi::send(QByteArray &array, qint16 target, int tag)
{
qint64 arrayLength = array.length();
dtkDistributedCommunicator::send(&arrayLength,1,target,tag);
dtkDistributedCommunicator::send(array.data(), arrayLength, target, tag);
}
void dtkDistributedCommunicatorMpi::receive(QString &s, qint16 source, int tag)
{
qint64 length;
dtkDistributedCommunicator::receive(&length,1,source,tag);
char s_c[length];
dtkDistributedCommunicator::receive(s_c, length, source,tag);
s = QString(s_c);
}
void dtkDistributedCommunicatorMpi::receive(QByteArray &array, qint16 source, int tag)
{
qint64 arrayLength;
dtkDistributedCommunicator::receive(&arrayLength,1,source,tag);
array.resize(arrayLength);
dtkDistributedCommunicator::receive(array.data(), arrayLength, source, tag);
}
//! Barrier.
/*!
* Creates a barrier synchronization. Each task, when reaching the
* barrier call, blocks until all tasks in the group reach the same
* barrier call.
*/
void dtkDistributedCommunicatorMpi::barrier(void)
{
MPI::COMM_WORLD.Barrier();
}
//! Broadcast.
/*!
* Broadcasts (sends) a message from the process with rank "source"
* to all other processes in the group.
*/
void dtkDistributedCommunicatorMpi::broadcast(void *data, qint64 size, DataType dataType, qint16 source)
{
MPI::COMM_WORLD.Bcast(data, size, data_type(dataType), source);
}
//! Gather.
/*!
* Gathers distinct messages from each task in the group to a single
* destination task. This routine is the reverse operation of
* scatter. If all is true, target is not taken into account.
*
* \sa scatter.
*/
void dtkDistributedCommunicatorMpi::gather(void *send, void *recv, qint64 size, DataType dataType, qint16 target, bool all)
{
if(all)
MPI::COMM_WORLD.Allgather(send, size, data_type(dataType), recv, size, data_type(dataType));
else
MPI::COMM_WORLD.Gather(send, size, data_type(dataType), recv, size, data_type(dataType), target);
}
//! Scatter.
/*!
* Distributes distinct messages from a single source task to each
* task in the group.
*
* \sa gather.
*/
void dtkDistributedCommunicatorMpi::scatter(void *send, void *recv, qint64 size, DataType dataType, qint16 source)
{
MPI::COMM_WORLD.Scatter(send, size, data_type(dataType), recv, size, data_type(dataType), source);
}
//! Reduce.
/*!
* Applies a reduction operation on all tasks in the group and places
* the result in one task. If all is true, target is not taken into
* account.
*
* \sa dtkDistributedCommunicator::OperationType.
*/
void dtkDistributedCommunicatorMpi::reduce(void *send, void *recv, qint64 size, DataType dataType, OperationType operationType, qint16 target, bool all)
{
if(all)
MPI::COMM_WORLD.Allreduce(send, recv, size, data_type(dataType), operation_type(operationType));
else
MPI::COMM_WORLD.Reduce(send, recv, size, data_type(dataType), operation_type(operationType), target);
}
// /////////////////////////////////////////////////////////////////
// Documentation
// /////////////////////////////////////////////////////////////////
//! \class dtkDistributedCommunicatorMpi
/*!
* \brief A mpi based dtk communicator.
*/
<|endoftext|> |
<commit_before>//===-- MipsMCTargetDesc.cpp - Mips Target Descriptions -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Mips specific target descriptions.
//
//===----------------------------------------------------------------------===//
#include "MipsMCAsmInfo.h"
#include "MipsMCTargetDesc.h"
#include "InstPrinter/MipsInstPrinter.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
#define GET_INSTRINFO_MC_DESC
#include "MipsGenInstrInfo.inc"
#define GET_SUBTARGETINFO_MC_DESC
#include "MipsGenSubtargetInfo.inc"
#define GET_REGINFO_MC_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
static MCInstrInfo *createMipsMCInstrInfo() {
MCInstrInfo *X = new MCInstrInfo();
InitMipsMCInstrInfo(X);
return X;
}
static MCRegisterInfo *createMipsMCRegisterInfo(StringRef TT) {
MCRegisterInfo *X = new MCRegisterInfo();
InitMipsMCRegisterInfo(X, Mips::RA);
return X;
}
static MCSubtargetInfo *createMipsMCSubtargetInfo(StringRef TT, StringRef CPU,
StringRef FS) {
MCSubtargetInfo *X = new MCSubtargetInfo();
InitMipsMCSubtargetInfo(X, TT, CPU, FS);
return X;
}
static MCAsmInfo *createMipsMCAsmInfo(const Target &T, StringRef TT) {
MCAsmInfo *MAI = new MipsMCAsmInfo(T, TT);
MachineLocation Dst(MachineLocation::VirtualFP);
MachineLocation Src(Mips::SP, 0);
MAI->addInitialFrameState(0, Dst, Src);
return MAI;
}
static MCCodeGenInfo *createMipsMCCodeGenInfo(StringRef TT, Reloc::Model RM,
CodeModel::Model CM,
CodeGenOpt::Level OL) {
MCCodeGenInfo *X = new MCCodeGenInfo();
if (RM == Reloc::Default)
RM = Reloc::PIC_;
X->InitMCCodeGenInfo(RM, CM, OL);
return X;
}
static MCInstPrinter *createMipsMCInstPrinter(const Target &T,
unsigned SyntaxVariant,
const MCAsmInfo &MAI,
const MCRegisterInfo &MRI,
const MCSubtargetInfo &STI) {
return new MipsInstPrinter(MAI, MRI);
}
static MCStreamer *createMCStreamer(const Target &T, StringRef TT,
MCContext &Ctx, MCAsmBackend &MAB,
raw_ostream &_OS,
MCCodeEmitter *_Emitter,
bool RelaxAll,
bool NoExecStack) {
Triple TheTriple(TT);
return createELFStreamer(Ctx, MAB, _OS, _Emitter, RelaxAll, NoExecStack);
}
extern "C" void LLVMInitializeMipsTargetMC() {
// Register the MC asm info.
RegisterMCAsmInfoFn X(TheMipsTarget, createMipsMCAsmInfo);
RegisterMCAsmInfoFn Y(TheMipselTarget, createMipsMCAsmInfo);
RegisterMCAsmInfoFn A(TheMips64Target, createMipsMCAsmInfo);
RegisterMCAsmInfoFn B(TheMips64elTarget, createMipsMCAsmInfo);
// Register the MC codegen info.
TargetRegistry::RegisterMCCodeGenInfo(TheMipsTarget,
createMipsMCCodeGenInfo);
TargetRegistry::RegisterMCCodeGenInfo(TheMipselTarget,
createMipsMCCodeGenInfo);
TargetRegistry::RegisterMCCodeGenInfo(TheMips64Target,
createMipsMCCodeGenInfo);
TargetRegistry::RegisterMCCodeGenInfo(TheMips64elTarget,
createMipsMCCodeGenInfo);
// Register the MC instruction info.
TargetRegistry::RegisterMCInstrInfo(TheMipsTarget, createMipsMCInstrInfo);
TargetRegistry::RegisterMCInstrInfo(TheMipselTarget, createMipsMCInstrInfo);
TargetRegistry::RegisterMCInstrInfo(TheMips64Target, createMipsMCInstrInfo);
TargetRegistry::RegisterMCInstrInfo(TheMips64elTarget,
createMipsMCInstrInfo);
// Register the MC register info.
TargetRegistry::RegisterMCRegInfo(TheMipsTarget, createMipsMCRegisterInfo);
TargetRegistry::RegisterMCRegInfo(TheMipselTarget, createMipsMCRegisterInfo);
TargetRegistry::RegisterMCRegInfo(TheMips64Target, createMipsMCRegisterInfo);
TargetRegistry::RegisterMCRegInfo(TheMips64elTarget,
createMipsMCRegisterInfo);
// Register the MC Code Emitter
TargetRegistry::RegisterMCCodeEmitter(TheMipsTarget,
createMipsMCCodeEmitterEB);
TargetRegistry::RegisterMCCodeEmitter(TheMipselTarget,
createMipsMCCodeEmitterEL);
TargetRegistry::RegisterMCCodeEmitter(TheMips64Target,
createMipsMCCodeEmitterEB);
TargetRegistry::RegisterMCCodeEmitter(TheMips64elTarget,
createMipsMCCodeEmitterEL);
// Register the object streamer.
TargetRegistry::RegisterMCObjectStreamer(TheMipsTarget, createMCStreamer);
TargetRegistry::RegisterMCObjectStreamer(TheMipselTarget, createMCStreamer);
TargetRegistry::RegisterMCObjectStreamer(TheMips64Target, createMCStreamer);
TargetRegistry::RegisterMCObjectStreamer(TheMips64elTarget,
createMCStreamer);
// Register the asm backend.
TargetRegistry::RegisterMCAsmBackend(TheMipsTarget,
createMipsAsmBackendEB);
TargetRegistry::RegisterMCAsmBackend(TheMipselTarget,
createMipsAsmBackendEL);
TargetRegistry::RegisterMCAsmBackend(TheMips64Target,
createMipsAsmBackendEB);
TargetRegistry::RegisterMCAsmBackend(TheMips64elTarget,
createMipsAsmBackendEL);
// Register the MC subtarget info.
TargetRegistry::RegisterMCSubtargetInfo(TheMipsTarget,
createMipsMCSubtargetInfo);
TargetRegistry::RegisterMCSubtargetInfo(TheMipselTarget,
createMipsMCSubtargetInfo);
TargetRegistry::RegisterMCSubtargetInfo(TheMips64Target,
createMipsMCSubtargetInfo);
TargetRegistry::RegisterMCSubtargetInfo(TheMips64elTarget,
createMipsMCSubtargetInfo);
// Register the MCInstPrinter.
TargetRegistry::RegisterMCInstPrinter(TheMipsTarget,
createMipsMCInstPrinter);
TargetRegistry::RegisterMCInstPrinter(TheMipselTarget,
createMipsMCInstPrinter);
TargetRegistry::RegisterMCInstPrinter(TheMips64Target,
createMipsMCInstPrinter);
TargetRegistry::RegisterMCInstPrinter(TheMips64elTarget,
createMipsMCInstPrinter);
}
<commit_msg>Select static relocation model if it is jitting.<commit_after>//===-- MipsMCTargetDesc.cpp - Mips Target Descriptions -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Mips specific target descriptions.
//
//===----------------------------------------------------------------------===//
#include "MipsMCAsmInfo.h"
#include "MipsMCTargetDesc.h"
#include "InstPrinter/MipsInstPrinter.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
#define GET_INSTRINFO_MC_DESC
#include "MipsGenInstrInfo.inc"
#define GET_SUBTARGETINFO_MC_DESC
#include "MipsGenSubtargetInfo.inc"
#define GET_REGINFO_MC_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
static MCInstrInfo *createMipsMCInstrInfo() {
MCInstrInfo *X = new MCInstrInfo();
InitMipsMCInstrInfo(X);
return X;
}
static MCRegisterInfo *createMipsMCRegisterInfo(StringRef TT) {
MCRegisterInfo *X = new MCRegisterInfo();
InitMipsMCRegisterInfo(X, Mips::RA);
return X;
}
static MCSubtargetInfo *createMipsMCSubtargetInfo(StringRef TT, StringRef CPU,
StringRef FS) {
MCSubtargetInfo *X = new MCSubtargetInfo();
InitMipsMCSubtargetInfo(X, TT, CPU, FS);
return X;
}
static MCAsmInfo *createMipsMCAsmInfo(const Target &T, StringRef TT) {
MCAsmInfo *MAI = new MipsMCAsmInfo(T, TT);
MachineLocation Dst(MachineLocation::VirtualFP);
MachineLocation Src(Mips::SP, 0);
MAI->addInitialFrameState(0, Dst, Src);
return MAI;
}
static MCCodeGenInfo *createMipsMCCodeGenInfo(StringRef TT, Reloc::Model RM,
CodeModel::Model CM,
CodeGenOpt::Level OL) {
MCCodeGenInfo *X = new MCCodeGenInfo();
if (CM == CodeModel::JITDefault)
RM = Reloc::Static;
else if (RM == Reloc::Default)
RM = Reloc::PIC_;
X->InitMCCodeGenInfo(RM, CM, OL);
return X;
}
static MCInstPrinter *createMipsMCInstPrinter(const Target &T,
unsigned SyntaxVariant,
const MCAsmInfo &MAI,
const MCRegisterInfo &MRI,
const MCSubtargetInfo &STI) {
return new MipsInstPrinter(MAI, MRI);
}
static MCStreamer *createMCStreamer(const Target &T, StringRef TT,
MCContext &Ctx, MCAsmBackend &MAB,
raw_ostream &_OS,
MCCodeEmitter *_Emitter,
bool RelaxAll,
bool NoExecStack) {
Triple TheTriple(TT);
return createELFStreamer(Ctx, MAB, _OS, _Emitter, RelaxAll, NoExecStack);
}
extern "C" void LLVMInitializeMipsTargetMC() {
// Register the MC asm info.
RegisterMCAsmInfoFn X(TheMipsTarget, createMipsMCAsmInfo);
RegisterMCAsmInfoFn Y(TheMipselTarget, createMipsMCAsmInfo);
RegisterMCAsmInfoFn A(TheMips64Target, createMipsMCAsmInfo);
RegisterMCAsmInfoFn B(TheMips64elTarget, createMipsMCAsmInfo);
// Register the MC codegen info.
TargetRegistry::RegisterMCCodeGenInfo(TheMipsTarget,
createMipsMCCodeGenInfo);
TargetRegistry::RegisterMCCodeGenInfo(TheMipselTarget,
createMipsMCCodeGenInfo);
TargetRegistry::RegisterMCCodeGenInfo(TheMips64Target,
createMipsMCCodeGenInfo);
TargetRegistry::RegisterMCCodeGenInfo(TheMips64elTarget,
createMipsMCCodeGenInfo);
// Register the MC instruction info.
TargetRegistry::RegisterMCInstrInfo(TheMipsTarget, createMipsMCInstrInfo);
TargetRegistry::RegisterMCInstrInfo(TheMipselTarget, createMipsMCInstrInfo);
TargetRegistry::RegisterMCInstrInfo(TheMips64Target, createMipsMCInstrInfo);
TargetRegistry::RegisterMCInstrInfo(TheMips64elTarget,
createMipsMCInstrInfo);
// Register the MC register info.
TargetRegistry::RegisterMCRegInfo(TheMipsTarget, createMipsMCRegisterInfo);
TargetRegistry::RegisterMCRegInfo(TheMipselTarget, createMipsMCRegisterInfo);
TargetRegistry::RegisterMCRegInfo(TheMips64Target, createMipsMCRegisterInfo);
TargetRegistry::RegisterMCRegInfo(TheMips64elTarget,
createMipsMCRegisterInfo);
// Register the MC Code Emitter
TargetRegistry::RegisterMCCodeEmitter(TheMipsTarget,
createMipsMCCodeEmitterEB);
TargetRegistry::RegisterMCCodeEmitter(TheMipselTarget,
createMipsMCCodeEmitterEL);
TargetRegistry::RegisterMCCodeEmitter(TheMips64Target,
createMipsMCCodeEmitterEB);
TargetRegistry::RegisterMCCodeEmitter(TheMips64elTarget,
createMipsMCCodeEmitterEL);
// Register the object streamer.
TargetRegistry::RegisterMCObjectStreamer(TheMipsTarget, createMCStreamer);
TargetRegistry::RegisterMCObjectStreamer(TheMipselTarget, createMCStreamer);
TargetRegistry::RegisterMCObjectStreamer(TheMips64Target, createMCStreamer);
TargetRegistry::RegisterMCObjectStreamer(TheMips64elTarget,
createMCStreamer);
// Register the asm backend.
TargetRegistry::RegisterMCAsmBackend(TheMipsTarget,
createMipsAsmBackendEB);
TargetRegistry::RegisterMCAsmBackend(TheMipselTarget,
createMipsAsmBackendEL);
TargetRegistry::RegisterMCAsmBackend(TheMips64Target,
createMipsAsmBackendEB);
TargetRegistry::RegisterMCAsmBackend(TheMips64elTarget,
createMipsAsmBackendEL);
// Register the MC subtarget info.
TargetRegistry::RegisterMCSubtargetInfo(TheMipsTarget,
createMipsMCSubtargetInfo);
TargetRegistry::RegisterMCSubtargetInfo(TheMipselTarget,
createMipsMCSubtargetInfo);
TargetRegistry::RegisterMCSubtargetInfo(TheMips64Target,
createMipsMCSubtargetInfo);
TargetRegistry::RegisterMCSubtargetInfo(TheMips64elTarget,
createMipsMCSubtargetInfo);
// Register the MCInstPrinter.
TargetRegistry::RegisterMCInstPrinter(TheMipsTarget,
createMipsMCInstPrinter);
TargetRegistry::RegisterMCInstPrinter(TheMipselTarget,
createMipsMCInstPrinter);
TargetRegistry::RegisterMCInstPrinter(TheMips64Target,
createMipsMCInstPrinter);
TargetRegistry::RegisterMCInstPrinter(TheMips64elTarget,
createMipsMCInstPrinter);
}
<|endoftext|> |
<commit_before>//===--- PartiallyInlineLibCalls.cpp - Partially inline libcalls ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass tries to partially inline the fast path of well-known library
// functions, such as using square-root instructions for cases where sqrt()
// does not need to set errno.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#define DEBUG_TYPE "partially-inline-libcalls"
namespace {
class PartiallyInlineLibCalls : public FunctionPass {
public:
static char ID;
PartiallyInlineLibCalls() :
FunctionPass(ID) {
initializePartiallyInlineLibCallsPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
private:
/// Optimize calls to sqrt.
bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
BasicBlock &CurrBB, Function::iterator &BB);
};
char PartiallyInlineLibCalls::ID = 0;
}
INITIALIZE_PASS(PartiallyInlineLibCalls, "partially-inline-libcalls",
"Partially inline calls to library functions", false, false)
void PartiallyInlineLibCalls::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
bool PartiallyInlineLibCalls::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
bool Changed = false;
Function::iterator CurrBB;
TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
const TargetTransformInfo *TTI =
&getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) {
CurrBB = BB++;
for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end();
II != IE; ++II) {
CallInst *Call = dyn_cast<CallInst>(&*II);
Function *CalledFunc;
if (!Call || !(CalledFunc = Call->getCalledFunction()))
continue;
// Skip if function either has local linkage or is not a known library
// function.
LibFunc::Func LibFunc;
if (CalledFunc->hasLocalLinkage() || !CalledFunc->hasName() ||
!TLI->getLibFunc(CalledFunc->getName(), LibFunc))
continue;
switch (LibFunc) {
case LibFunc::sqrtf:
case LibFunc::sqrt:
if (TTI->haveFastSqrt(Call->getType()) &&
optimizeSQRT(Call, CalledFunc, *CurrBB, BB))
break;
continue;
default:
continue;
}
Changed = true;
break;
}
}
return Changed;
}
bool PartiallyInlineLibCalls::optimizeSQRT(CallInst *Call,
Function *CalledFunc,
BasicBlock &CurrBB,
Function::iterator &BB) {
// There is no need to change the IR, since backend will emit sqrt
// instruction if the call has already been marked read-only.
if (Call->onlyReadsMemory())
return false;
// The call must have the expected result type.
if (!Call->getType()->isFloatingPointTy())
return false;
// Do the following transformation:
//
// (before)
// dst = sqrt(src)
//
// (after)
// v0 = sqrt_noreadmem(src) # native sqrt instruction.
// if (v0 is a NaN)
// v1 = sqrt(src) # library call.
// dst = phi(v0, v1)
//
// Move all instructions following Call to newly created block JoinBB.
// Create phi and replace all uses.
BasicBlock *JoinBB = llvm::SplitBlock(&CurrBB, Call->getNextNode());
IRBuilder<> Builder(JoinBB, JoinBB->begin());
PHINode *Phi = Builder.CreatePHI(Call->getType(), 2);
Call->replaceAllUsesWith(Phi);
// Create basic block LibCallBB and insert a call to library function sqrt.
BasicBlock *LibCallBB = BasicBlock::Create(CurrBB.getContext(), "call.sqrt",
CurrBB.getParent(), JoinBB);
Builder.SetInsertPoint(LibCallBB);
Instruction *LibCall = Call->clone();
Builder.Insert(LibCall);
Builder.CreateBr(JoinBB);
// Add attribute "readnone" so that backend can use a native sqrt instruction
// for this call. Insert a FP compare instruction and a conditional branch
// at the end of CurrBB.
Call->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
CurrBB.getTerminator()->eraseFromParent();
Builder.SetInsertPoint(&CurrBB);
Value *FCmp = Builder.CreateFCmpOEQ(Call, Call);
Builder.CreateCondBr(FCmp, JoinBB, LibCallBB);
// Add phi operands.
Phi->addIncoming(Call, &CurrBB);
Phi->addIncoming(LibCall, LibCallBB);
BB = JoinBB->getIterator();
return true;
}
FunctionPass *llvm::createPartiallyInlineLibCallsPass() {
return new PartiallyInlineLibCalls();
}
<commit_msg>[PM/PartiallyInlineLibCalls] Convert to static function in preparation for porting this pass to the new PM.<commit_after>//===--- PartiallyInlineLibCalls.cpp - Partially inline libcalls ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass tries to partially inline the fast path of well-known library
// functions, such as using square-root instructions for cases where sqrt()
// does not need to set errno.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#define DEBUG_TYPE "partially-inline-libcalls"
namespace {
class PartiallyInlineLibCalls : public FunctionPass {
public:
static char ID;
PartiallyInlineLibCalls() :
FunctionPass(ID) {
initializePartiallyInlineLibCallsPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
};
char PartiallyInlineLibCalls::ID = 0;
}
INITIALIZE_PASS(PartiallyInlineLibCalls, "partially-inline-libcalls",
"Partially inline calls to library functions", false, false)
void PartiallyInlineLibCalls::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
static bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
BasicBlock &CurrBB, Function::iterator &BB) {
// There is no need to change the IR, since backend will emit sqrt
// instruction if the call has already been marked read-only.
if (Call->onlyReadsMemory())
return false;
// The call must have the expected result type.
if (!Call->getType()->isFloatingPointTy())
return false;
// Do the following transformation:
//
// (before)
// dst = sqrt(src)
//
// (after)
// v0 = sqrt_noreadmem(src) # native sqrt instruction.
// if (v0 is a NaN)
// v1 = sqrt(src) # library call.
// dst = phi(v0, v1)
//
// Move all instructions following Call to newly created block JoinBB.
// Create phi and replace all uses.
BasicBlock *JoinBB = llvm::SplitBlock(&CurrBB, Call->getNextNode());
IRBuilder<> Builder(JoinBB, JoinBB->begin());
PHINode *Phi = Builder.CreatePHI(Call->getType(), 2);
Call->replaceAllUsesWith(Phi);
// Create basic block LibCallBB and insert a call to library function sqrt.
BasicBlock *LibCallBB = BasicBlock::Create(CurrBB.getContext(), "call.sqrt",
CurrBB.getParent(), JoinBB);
Builder.SetInsertPoint(LibCallBB);
Instruction *LibCall = Call->clone();
Builder.Insert(LibCall);
Builder.CreateBr(JoinBB);
// Add attribute "readnone" so that backend can use a native sqrt instruction
// for this call. Insert a FP compare instruction and a conditional branch
// at the end of CurrBB.
Call->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
CurrBB.getTerminator()->eraseFromParent();
Builder.SetInsertPoint(&CurrBB);
Value *FCmp = Builder.CreateFCmpOEQ(Call, Call);
Builder.CreateCondBr(FCmp, JoinBB, LibCallBB);
// Add phi operands.
Phi->addIncoming(Call, &CurrBB);
Phi->addIncoming(LibCall, LibCallBB);
BB = JoinBB->getIterator();
return true;
}
bool PartiallyInlineLibCalls::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
bool Changed = false;
Function::iterator CurrBB;
TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
const TargetTransformInfo *TTI =
&getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) {
CurrBB = BB++;
for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end();
II != IE; ++II) {
CallInst *Call = dyn_cast<CallInst>(&*II);
Function *CalledFunc;
if (!Call || !(CalledFunc = Call->getCalledFunction()))
continue;
// Skip if function either has local linkage or is not a known library
// function.
LibFunc::Func LibFunc;
if (CalledFunc->hasLocalLinkage() || !CalledFunc->hasName() ||
!TLI->getLibFunc(CalledFunc->getName(), LibFunc))
continue;
switch (LibFunc) {
case LibFunc::sqrtf:
case LibFunc::sqrt:
if (TTI->haveFastSqrt(Call->getType()) &&
optimizeSQRT(Call, CalledFunc, *CurrBB, BB))
break;
continue;
default:
continue;
}
Changed = true;
break;
}
}
return Changed;
}
FunctionPass *llvm::createPartiallyInlineLibCallsPass() {
return new PartiallyInlineLibCalls();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/accessibility_util.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_tts_api_platform.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace accessibility {
// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
public:
// Initialize the ContentScriptLoader with the ID of the extension
// and the RenderViewHost where the scripts should be loaded.
ContentScriptLoader(const std::string& extension_id,
RenderViewHost* render_view_host)
: extension_id_(extension_id),
render_view_host_(render_view_host) {}
// Call this once with the ExtensionResource corresponding to each
// content script to be loaded.
void AppendScript(ExtensionResource resource) {
resources_.push(resource);
}
// Fianlly, call this method once to fetch all of the resources and
// load them. This method will delete this object when done.
void Run() {
if (resources_.empty()) {
delete this;
return;
}
ExtensionResource resource = resources_.front();
resources_.pop();
scoped_refptr<FileReader> reader(new FileReader(resource, base::Bind(
&ContentScriptLoader::OnFileLoaded, base::Unretained(this))));
reader->Start();
}
private:
void OnFileLoaded(bool success, const std::string& data) {
if (success) {
ExtensionMsg_ExecuteCode_Params params;
params.request_id = 0;
params.extension_id = extension_id_;
params.is_javascript = true;
params.code = data;
params.all_frames = true;
params.in_main_world = false;
render_view_host_->Send(new ExtensionMsg_ExecuteCode(
render_view_host_->routing_id(), params));
}
Run();
}
std::string extension_id_;
RenderViewHost* render_view_host_;
std::queue<ExtensionResource> resources_;
};
void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
if (accessibility_enabled == enabled) {
LOG(INFO) << "Accessibility is already " <<
(enabled ? "enabled" : "disabled") << ". Going to do nothing.";
return;
}
g_browser_process->local_state()->SetBoolean(
prefs::kAccessibilityEnabled, enabled);
g_browser_process->local_state()->ScheduleSavePersistentPrefs();
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(enabled);
Speak(enabled ?
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_ACCESS_ENABLED).c_str() :
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_ACCESS_DISABLED).c_str());
// Load/Unload ChromeVox
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* extension_service =
profile->GetExtensionService();
std::string manifest = ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
if (enabled) { // Load ChromeVox
const Extension* extension =
extension_service->component_loader()->Add(manifest, path);
if (login_web_ui) {
RenderViewHost* render_view_host =
login_web_ui->tab_contents()->render_view_host();
ContentScriptLoader* loader = new ContentScriptLoader(
extension->id(), render_view_host);
for (size_t i = 0; i < extension->content_scripts().size(); i++) {
const UserScript& script = extension->content_scripts()[i];
for (size_t j = 0; j < script.js_scripts().size(); ++j) {
const UserScript::File &file = script.js_scripts()[j];
ExtensionResource resource = extension->GetResource(
file.relative_path());
loader->AppendScript(resource);
}
}
loader->Run(); // It cleans itself up when done.
}
LOG(INFO) << "ChromeVox was Loaded.";
} else { // Unload ChromeVox
extension_service->component_loader()->Remove(manifest);
LOG(INFO) << "ChromeVox was Unloaded.";
}
}
void ToggleAccessibility(WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
accessibility_enabled = !accessibility_enabled;
EnableAccessibility(accessibility_enabled, login_web_ui);
};
void Speak(const char* utterance) {
UtteranceContinuousParameters params;
ExtensionTtsPlatformImpl::GetInstance()->Speak(
-1, // No utterance ID because we don't need a callback when it finishes.
utterance,
g_browser_process->GetApplicationLocale(),
params);
}
} // namespace accessibility
} // namespace chromeos
<commit_msg>Tell BrowserAccessibilityState when Chrome OS accessibility is turned on. This will improve feedback for a couple of toolbar controls that check this state, and also start collecting UMA statistics on accessibility usage in Chrome OS.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/accessibility_util.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_tts_api_platform.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/accessibility/browser_accessibility_state.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace accessibility {
// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
public:
// Initialize the ContentScriptLoader with the ID of the extension
// and the RenderViewHost where the scripts should be loaded.
ContentScriptLoader(const std::string& extension_id,
RenderViewHost* render_view_host)
: extension_id_(extension_id),
render_view_host_(render_view_host) {}
// Call this once with the ExtensionResource corresponding to each
// content script to be loaded.
void AppendScript(ExtensionResource resource) {
resources_.push(resource);
}
// Fianlly, call this method once to fetch all of the resources and
// load them. This method will delete this object when done.
void Run() {
if (resources_.empty()) {
delete this;
return;
}
ExtensionResource resource = resources_.front();
resources_.pop();
scoped_refptr<FileReader> reader(new FileReader(resource, base::Bind(
&ContentScriptLoader::OnFileLoaded, base::Unretained(this))));
reader->Start();
}
private:
void OnFileLoaded(bool success, const std::string& data) {
if (success) {
ExtensionMsg_ExecuteCode_Params params;
params.request_id = 0;
params.extension_id = extension_id_;
params.is_javascript = true;
params.code = data;
params.all_frames = true;
params.in_main_world = false;
render_view_host_->Send(new ExtensionMsg_ExecuteCode(
render_view_host_->routing_id(), params));
}
Run();
}
std::string extension_id_;
RenderViewHost* render_view_host_;
std::queue<ExtensionResource> resources_;
};
void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
if (accessibility_enabled == enabled) {
LOG(INFO) << "Accessibility is already " <<
(enabled ? "enabled" : "disabled") << ". Going to do nothing.";
return;
}
g_browser_process->local_state()->SetBoolean(
prefs::kAccessibilityEnabled, enabled);
g_browser_process->local_state()->ScheduleSavePersistentPrefs();
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(enabled);
BrowserAccessibilityState::GetInstance()->OnAccessibilityEnabledManually();
Speak(enabled ?
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_ACCESS_ENABLED).c_str() :
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_ACCESS_DISABLED).c_str());
// Load/Unload ChromeVox
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* extension_service =
profile->GetExtensionService();
std::string manifest = ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
if (enabled) { // Load ChromeVox
const Extension* extension =
extension_service->component_loader()->Add(manifest, path);
if (login_web_ui) {
RenderViewHost* render_view_host =
login_web_ui->tab_contents()->render_view_host();
ContentScriptLoader* loader = new ContentScriptLoader(
extension->id(), render_view_host);
for (size_t i = 0; i < extension->content_scripts().size(); i++) {
const UserScript& script = extension->content_scripts()[i];
for (size_t j = 0; j < script.js_scripts().size(); ++j) {
const UserScript::File &file = script.js_scripts()[j];
ExtensionResource resource = extension->GetResource(
file.relative_path());
loader->AppendScript(resource);
}
}
loader->Run(); // It cleans itself up when done.
}
LOG(INFO) << "ChromeVox was Loaded.";
} else { // Unload ChromeVox
extension_service->component_loader()->Remove(manifest);
LOG(INFO) << "ChromeVox was Unloaded.";
}
}
void ToggleAccessibility(WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
accessibility_enabled = !accessibility_enabled;
EnableAccessibility(accessibility_enabled, login_web_ui);
};
void Speak(const char* utterance) {
UtteranceContinuousParameters params;
ExtensionTtsPlatformImpl::GetInstance()->Speak(
-1, // No utterance ID because we don't need a callback when it finishes.
utterance,
g_browser_process->GetApplicationLocale(),
params);
}
} // namespace accessibility
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login_manager_view.h"
#include <signal.h>
#include <sys/types.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/image_background.h"
#include "chrome/browser/chromeos/login_library.h"
#include "chrome/browser/chromeos/network_library.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/label.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
#include "views/window/window_gtk.h"
using views::Background;
using views::Label;
using views::Textfield;
using views::View;
using views::Widget;
const int kUsernameY = 386;
const int kPanelSpacing = 36;
const int kVersionPad = 4;
const int kTextfieldWidth = 286;
const SkColor kVersionColor = 0xFF7691DA;
const SkColor kErrorColor = 0xFF8F384F;
const char *kDefaultDomain = "@gmail.com";
namespace browser {
// Acts as a frame view with no UI.
class LoginManagerNonClientFrameView : public views::NonClientFrameView {
public:
explicit LoginManagerNonClientFrameView() : views::NonClientFrameView() {}
// Returns just the bounds of the window.
virtual gfx::Rect GetBoundsForClientView() const { return bounds(); }
// Doesn't add any size to the client bounds.
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
// There is no system menu.
virtual gfx::Point GetSystemMenuPoint() const { return gfx::Point(); }
// There is no non client area.
virtual int NonClientHitTest(const gfx::Point& point) { return 0; }
// There is no non client area.
virtual void GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {}
virtual void EnableClose(bool enable) {}
virtual void ResetWindowControls() {}
DISALLOW_COPY_AND_ASSIGN(LoginManagerNonClientFrameView);
};
// Subclass of WindowGtk, for use as the top level login window.
class LoginManagerWindow : public views::WindowGtk {
public:
static LoginManagerWindow* CreateLoginManagerWindow() {
LoginManagerWindow* login_manager_window =
new LoginManagerWindow();
login_manager_window->GetNonClientView()->SetFrameView(
new LoginManagerNonClientFrameView());
login_manager_window->Init(NULL, gfx::Rect());
return login_manager_window;
}
private:
LoginManagerWindow() : views::WindowGtk(new LoginManagerView) {
}
DISALLOW_COPY_AND_ASSIGN(LoginManagerWindow);
};
// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginManager() {
// if we can't load the library, we'll tell the user in LoginManagerView.
views::WindowGtk* window =
LoginManagerWindow::CreateLoginManagerWindow();
window->Show();
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->EmitLoginPromptReady();
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
} // namespace browser
LoginManagerView::LoginManagerView() {
Init();
}
LoginManagerView::~LoginManagerView() {
MessageLoop::current()->Quit();
}
void LoginManagerView::Init() {
username_field_ = new views::Textfield;
username_field_->RemoveBorder();
password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD);
password_field_->RemoveBorder();
os_version_label_ = new views::Label();
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_ = new views::Label();
error_label_->SetColor(kErrorColor);
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Creates the main window
BuildWindow();
// Controller to handle events from textfields
username_field_->SetController(this);
password_field_->SetController(this);
if (chromeos::LoginLibrary::EnsureLoaded()) {
loader_.GetVersion(
&consumer_, NewCallback(this, &LoginManagerView::OnOSVersion));
}
}
gfx::Size LoginManagerView::GetPreferredSize() {
return dialog_dimensions_;
}
void LoginManagerView::BuildWindow() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
panel_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_PANEL);
background_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_BACKGROUND);
// --------------------- Get attributes of images -----------------------
dialog_dimensions_.SetSize(gdk_pixbuf_get_width(background_pixbuf_),
gdk_pixbuf_get_height(background_pixbuf_));
int panel_height = gdk_pixbuf_get_height(panel_pixbuf_);
int panel_width = gdk_pixbuf_get_width(panel_pixbuf_);
// ---------------------- Set up root View ------------------------------
set_background(new views::ImageBackground(background_pixbuf_));
View* login_prompt = new View();
login_prompt->set_background(new views::ImageBackground(panel_pixbuf_));
login_prompt->SetBounds(0, 0, panel_width, panel_height);
int x = (panel_width - kTextfieldWidth) / 2;
int y = kUsernameY;
username_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
password_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
os_version_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
os_version_label_->GetPreferredSize().height());
y += kPanelSpacing;
error_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
error_label_->GetPreferredSize().height());
login_prompt->AddChildView(username_field_);
login_prompt->AddChildView(password_field_);
login_prompt->AddChildView(os_version_label_);
login_prompt->AddChildView(error_label_);
AddChildView(login_prompt);
if (!chromeos::LoginLibrary::EnsureLoaded()) {
error_label->SetText(
l10n_util::GetStringUTF16(IDS_LOGIN_DISABLED_NO_LIBCROS));
username_field_->SetReadOnly(true);
password_field_->SetReadOnly(true);
}
return;
}
views::View* LoginManagerView::GetContentsView() {
return this;
}
bool LoginManagerView::Authenticate(const std::string& username,
const std::string& password) {
base::ProcessHandle handle;
std::vector<std::string> argv;
// TODO(cmasone): we'll want this to be configurable.
argv.push_back("/opt/google/chrome/session");
argv.push_back(username);
argv.push_back(password);
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
base::LaunchApp(argv, no_env, no_files, false, &handle);
int child_exit_code;
return base::WaitForExitCode(handle, &child_exit_code) &&
child_exit_code == 0;
}
void LoginManagerView::SetupSession(const std::string& username) {
if (window()) {
window()->Close();
}
if (username.find("@google.com") != std::string::npos) {
// This isn't thread-safe. However, the login window is specifically
// supposed to be run in a blocking fashion, before any other threads are
// created by the initial browser process.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAutoSSLClientAuth);
}
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->StartSession(username, "");
}
bool LoginManagerView::HandleKeystroke(views::Textfield* s,
const views::Textfield::Keystroke& keystroke) {
if (!chromeos::LoginLibrary::EnsureLoaded())
return false;
if (keystroke.GetKeyboardCode() == base::VKEY_TAB) {
if (username_field_->text().length() != 0) {
std::string username = UTF16ToUTF8(username_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
return false;
}
} else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) {
// Disallow 0 size username.
if (username_field_->text().length() == 0) {
// Return true so that processing ends
return true;
} else {
std::string username = UTF16ToUTF8(username_field_->text());
// todo(cmasone) Need to sanitize memory used to store password.
std::string password = UTF16ToUTF8(password_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
// Set up credentials to prepare for authentication.
if (!Authenticate(username, password)) {
chromeos::NetworkLibrary* network = chromeos::NetworkLibrary::Get();
int errorID;
// Check networking after trying to login in case user is
// cached locally or the local admin account.
if (!network || !network->EnsureLoaded())
errorID = IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY;
else if (!network->Connected())
errorID = IDS_LOGIN_ERROR_NETWORK_NOT_CONNECTED;
else
errorID = IDS_LOGIN_ERROR_AUTHENTICATING;
error_label_->SetText(l10n_util::GetString(errorID));
return true;
}
// TODO(cmasone): something sensible if errors occur.
SetupSession(username);
// Return true so that processing ends
return true;
}
}
// Return false so that processing does not end
return false;
}
void LoginManagerView::OnOSVersion(
chromeos::VersionLoader::Handle handle,
std::string version) {
os_version_label_->SetText(ASCIIToWide(version));
}
<commit_msg>Fix bad var use. TBR:cmasone<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login_manager_view.h"
#include <signal.h>
#include <sys/types.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/image_background.h"
#include "chrome/browser/chromeos/login_library.h"
#include "chrome/browser/chromeos/network_library.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/label.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
#include "views/window/window_gtk.h"
using views::Background;
using views::Label;
using views::Textfield;
using views::View;
using views::Widget;
const int kUsernameY = 386;
const int kPanelSpacing = 36;
const int kVersionPad = 4;
const int kTextfieldWidth = 286;
const SkColor kVersionColor = 0xFF7691DA;
const SkColor kErrorColor = 0xFF8F384F;
const char *kDefaultDomain = "@gmail.com";
namespace browser {
// Acts as a frame view with no UI.
class LoginManagerNonClientFrameView : public views::NonClientFrameView {
public:
explicit LoginManagerNonClientFrameView() : views::NonClientFrameView() {}
// Returns just the bounds of the window.
virtual gfx::Rect GetBoundsForClientView() const { return bounds(); }
// Doesn't add any size to the client bounds.
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
// There is no system menu.
virtual gfx::Point GetSystemMenuPoint() const { return gfx::Point(); }
// There is no non client area.
virtual int NonClientHitTest(const gfx::Point& point) { return 0; }
// There is no non client area.
virtual void GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {}
virtual void EnableClose(bool enable) {}
virtual void ResetWindowControls() {}
DISALLOW_COPY_AND_ASSIGN(LoginManagerNonClientFrameView);
};
// Subclass of WindowGtk, for use as the top level login window.
class LoginManagerWindow : public views::WindowGtk {
public:
static LoginManagerWindow* CreateLoginManagerWindow() {
LoginManagerWindow* login_manager_window =
new LoginManagerWindow();
login_manager_window->GetNonClientView()->SetFrameView(
new LoginManagerNonClientFrameView());
login_manager_window->Init(NULL, gfx::Rect(0, 0, 1024,768));
return login_manager_window;
}
private:
LoginManagerWindow() : views::WindowGtk(new LoginManagerView) {
}
DISALLOW_COPY_AND_ASSIGN(LoginManagerWindow);
};
// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginManager() {
// if we can't load the library, we'll tell the user in LoginManagerView.
views::WindowGtk* window =
LoginManagerWindow::CreateLoginManagerWindow();
window->Show();
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->EmitLoginPromptReady();
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
} // namespace browser
LoginManagerView::LoginManagerView() {
Init();
}
LoginManagerView::~LoginManagerView() {
MessageLoop::current()->Quit();
}
void LoginManagerView::Init() {
username_field_ = new views::Textfield;
username_field_->RemoveBorder();
password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD);
password_field_->RemoveBorder();
os_version_label_ = new views::Label();
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_ = new views::Label();
error_label_->SetColor(kErrorColor);
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Creates the main window
BuildWindow();
// Controller to handle events from textfields
username_field_->SetController(this);
password_field_->SetController(this);
if (chromeos::LoginLibrary::EnsureLoaded()) {
loader_.GetVersion(
&consumer_, NewCallback(this, &LoginManagerView::OnOSVersion));
}
}
gfx::Size LoginManagerView::GetPreferredSize() {
return dialog_dimensions_;
}
void LoginManagerView::BuildWindow() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
panel_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_PANEL);
background_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_BACKGROUND);
// --------------------- Get attributes of images -----------------------
dialog_dimensions_.SetSize(gdk_pixbuf_get_width(background_pixbuf_),
gdk_pixbuf_get_height(background_pixbuf_));
int panel_height = gdk_pixbuf_get_height(panel_pixbuf_);
int panel_width = gdk_pixbuf_get_width(panel_pixbuf_);
// ---------------------- Set up root View ------------------------------
set_background(new views::ImageBackground(background_pixbuf_));
View* login_prompt = new View();
login_prompt->set_background(new views::ImageBackground(panel_pixbuf_));
login_prompt->SetBounds(0, 0, panel_width, panel_height);
int x = (panel_width - kTextfieldWidth) / 2;
int y = kUsernameY;
username_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
password_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
os_version_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
os_version_label_->GetPreferredSize().height());
y += kPanelSpacing;
error_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
error_label_->GetPreferredSize().height());
login_prompt->AddChildView(username_field_);
login_prompt->AddChildView(password_field_);
login_prompt->AddChildView(os_version_label_);
login_prompt->AddChildView(error_label_);
AddChildView(login_prompt);
if (!chromeos::LoginLibrary::EnsureLoaded()) {
error_label_->SetText(l10n_util::GetString(IDS_LOGIN_DISABLED_NO_LIBCROS));
username_field_->SetReadOnly(true);
password_field_->SetReadOnly(true);
}
return;
}
views::View* LoginManagerView::GetContentsView() {
return this;
}
bool LoginManagerView::Authenticate(const std::string& username,
const std::string& password) {
base::ProcessHandle handle;
std::vector<std::string> argv;
// TODO(cmasone): we'll want this to be configurable.
argv.push_back("/opt/google/chrome/session");
argv.push_back(username);
argv.push_back(password);
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
base::LaunchApp(argv, no_env, no_files, false, &handle);
int child_exit_code;
return base::WaitForExitCode(handle, &child_exit_code) &&
child_exit_code == 0;
}
void LoginManagerView::SetupSession(const std::string& username) {
if (window()) {
window()->Close();
}
if (username.find("@google.com") != std::string::npos) {
// This isn't thread-safe. However, the login window is specifically
// supposed to be run in a blocking fashion, before any other threads are
// created by the initial browser process.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAutoSSLClientAuth);
}
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->StartSession(username, "");
}
bool LoginManagerView::HandleKeystroke(views::Textfield* s,
const views::Textfield::Keystroke& keystroke) {
if (!chromeos::LoginLibrary::EnsureLoaded())
return false;
if (keystroke.GetKeyboardCode() == base::VKEY_TAB) {
if (username_field_->text().length() != 0) {
std::string username = UTF16ToUTF8(username_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
return false;
}
} else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) {
// Disallow 0 size username.
if (username_field_->text().length() == 0) {
// Return true so that processing ends
return true;
} else {
std::string username = UTF16ToUTF8(username_field_->text());
// todo(cmasone) Need to sanitize memory used to store password.
std::string password = UTF16ToUTF8(password_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
// Set up credentials to prepare for authentication.
if (!Authenticate(username, password)) {
chromeos::NetworkLibrary* network = chromeos::NetworkLibrary::Get();
int errorID;
// Check networking after trying to login in case user is
// cached locally or the local admin account.
if (!network || !network->EnsureLoaded())
errorID = IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY;
else if (!network->Connected())
errorID = IDS_LOGIN_ERROR_NETWORK_NOT_CONNECTED;
else
errorID = IDS_LOGIN_ERROR_AUTHENTICATING;
error_label_->SetText(l10n_util::GetString(errorID));
return true;
}
// TODO(cmasone): something sensible if errors occur.
SetupSession(username);
// Return true so that processing ends
return true;
}
}
// Return false so that processing does not end
return false;
}
void LoginManagerView::OnOSVersion(
chromeos::VersionLoader::Handle handle,
std::string version) {
os_version_label_->SetText(ASCIIToWide(version));
}
<|endoftext|> |
<commit_before>// inipp.hh - minimalistic ini file parser class in single header file
//
// Copyright (c) 2009, Florian Wagner <florian@wagner-flo.net>.
// 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 REGENTS 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.
#ifndef INIPP_HH
#define INIPP_HH
#define INIPP_VERSION "1.0"
#include <string>
#include <map>
#include <fstream>
#include <stdexcept>
namespace inipp
{
class inifile;
class inisection;
class unknown_entry_error : public std::runtime_error
{
public:
inline unknown_entry_error(const std::string& key)
: std::runtime_error("Unknown entry '" + key + "'.")
{ /* empty */ };
inline unknown_entry_error(const std::string& key,
const std::string& section)
: std::runtime_error("Unknown entry '" + key + "' in section '" +
section + "'.")
{ /* empty */ };
};
class unknown_section_error : public std::runtime_error
{
public:
inline unknown_section_error(const std::string& section)
: std::runtime_error("Unknown section '" + section + "'.")
{ /* empty */ };
};
class syntax_error : public std::runtime_error
{
public:
inline syntax_error(const std::string& msg)
: std::runtime_error(msg)
{ /* empty */ };
};
class inisection
{
friend class inifile;
public:
inline std::string get(const std::string& key) const;
inline std::string dget(const std::string& key,
const std::string& default_value) const;
protected:
inline inisection(const std::string& section, const inifile& ini);
const std::string _section;
const inifile& _ini;
};
class inifile
{
public:
inline inifile(std::ifstream& infile);
inline std::string get(const std::string& section,
const std::string& key) const;
inline std::string get(const std::string& key) const;
inline std::string dget(const std::string& section,
const std::string& key,
const std::string& default_value) const;
inline std::string dget(const std::string& key,
const std::string& default_value) const;
inline inisection section(const std::string& section) const;
protected:
std::map<std::string,std::map<std::string,std::string> > _sections;
std::map<std::string,std::string> _defaultsection;
};
namespace _private
{
inline std::string trim(const std::string& str,
const std::string& whitespace = " \t\n\r\f\v");
inline bool split(const std::string& in, const std::string& sep,
std::string& first, std::string& second);
}
inifile::inifile(std::ifstream& infile) {
std::map<std::string,std::string>* cursec = &this->_defaultsection;
std::string line;
while(std::getline(infile, line)) {
// trim line
line = _private::trim(line);
// ignore empty lines and comments
if(line.empty() || line[0] == '#') {
continue;
}
// section?
if(line[0] == '[') {
if(line[line.size() - 1] != ']') {
throw syntax_error("The section '" + line +
"' is missing a closing bracket.");
}
line = _private::trim(line.substr(1, line.size() - 2));
cursec = &this->_sections[line];
continue;
}
// entry: split by "=", trim and set
std::string key;
std::string value;
if(_private::split(line, "=", key, value)) {
(*cursec)[_private::trim(key)] = _private::trim(value);
continue;
}
// throw exception on invalid line
throw syntax_error("The line '" + line + "' is invalid.");
}
}
std::string inifile::get(const std::string& section,
const std::string& key) const {
if(!this->_sections.count(section)) {
throw unknown_section_error(section);
}
if(!this->_sections.find(section)->second.count(key)) {
throw unknown_entry_error(section, key);
}
return this->_sections.find(section)->second.find(key)->second;
}
std::string inifile::get(const std::string& key) const {
if(!this->_defaultsection.count(key)) {
throw unknown_entry_error(key);
}
return this->_defaultsection.find(key)->second;
};
std::string inifile::dget(const std::string& section,
const std::string& key,
const std::string& default_value) const {
try {
return this->get(section, key);
}
catch(unknown_section_error& ex) { /* ignore */ }
catch(unknown_entry_error& ex) { /* ignore */ }
return default_value;
}
std::string inifile::dget(const std::string& key,
const std::string& default_value) const {
try {
return this->get(key);
}
catch(unknown_entry_error& ex) { /* ignore */ }
return default_value;
}
inisection inifile::section(const std::string& section) const {
if(!this->_sections.count(section)) {
throw unknown_section_error(section);
}
return inisection(section, *this);
};
inisection::inisection(const std::string& section, const inifile& ini)
: _section(section),
_ini(ini) {
/* empty */
}
inline std::string inisection::get(const std::string& key) const {
return this->_ini.get(this->_section, key);
}
inline std::string inisection::dget(const std::string& key,
const std::string& default_val) const {
return this->_ini.dget(this->_section, key, default_val);
}
inline std::string _private::trim(const std::string& str,
const std::string& whitespace) {
size_t startpos = str.find_first_not_of(whitespace);
size_t endpos = str.find_last_not_of(whitespace);
// only whitespace, return empty line
if(startpos == std::string::npos || endpos == std::string::npos) {
return std::string();
}
// trim leading and trailing whitespace
return str.substr(startpos, endpos - startpos + 1);
}
inline bool _private::split(const std::string& in, const std::string& sep,
std::string& first, std::string& second) {
size_t eqpos = in.find(sep);
if(eqpos == std::string::npos) {
return false;
}
first = in.substr(0, eqpos);
second = in.substr(eqpos + sep.size(), in.size() - eqpos - sep.size());
return true;
}
}
#endif /* INIPP_HH */
<commit_msg>Added inisection::name() method<commit_after>// inipp.hh - minimalistic ini file parser class in single header file
//
// Copyright (c) 2009, Florian Wagner <florian@wagner-flo.net>.
// 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 REGENTS 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.
#ifndef INIPP_HH
#define INIPP_HH
#define INIPP_VERSION "1.0"
#include <string>
#include <map>
#include <fstream>
#include <stdexcept>
namespace inipp
{
class inifile;
class inisection;
class unknown_entry_error : public std::runtime_error
{
public:
inline unknown_entry_error(const std::string& key)
: std::runtime_error("Unknown entry '" + key + "'.")
{ /* empty */ };
inline unknown_entry_error(const std::string& key,
const std::string& section)
: std::runtime_error("Unknown entry '" + key + "' in section '" +
section + "'.")
{ /* empty */ };
};
class unknown_section_error : public std::runtime_error
{
public:
inline unknown_section_error(const std::string& section)
: std::runtime_error("Unknown section '" + section + "'.")
{ /* empty */ };
};
class syntax_error : public std::runtime_error
{
public:
inline syntax_error(const std::string& msg)
: std::runtime_error(msg)
{ /* empty */ };
};
class inisection
{
friend class inifile;
public:
inline std::string name() const;
inline std::string get(const std::string& key) const;
inline std::string dget(const std::string& key,
const std::string& default_value) const;
protected:
inline inisection(const std::string& section, const inifile& ini);
const std::string _section;
const inifile& _ini;
};
class inifile
{
public:
inline inifile(std::ifstream& infile);
inline std::string get(const std::string& section,
const std::string& key) const;
inline std::string get(const std::string& key) const;
inline std::string dget(const std::string& section,
const std::string& key,
const std::string& default_value) const;
inline std::string dget(const std::string& key,
const std::string& default_value) const;
inline inisection section(const std::string& section) const;
protected:
std::map<std::string,std::map<std::string,std::string> > _sections;
std::map<std::string,std::string> _defaultsection;
};
namespace _private
{
inline std::string trim(const std::string& str,
const std::string& whitespace = " \t\n\r\f\v");
inline bool split(const std::string& in, const std::string& sep,
std::string& first, std::string& second);
}
inifile::inifile(std::ifstream& infile) {
std::map<std::string,std::string>* cursec = &this->_defaultsection;
std::string line;
while(std::getline(infile, line)) {
// trim line
line = _private::trim(line);
// ignore empty lines and comments
if(line.empty() || line[0] == '#') {
continue;
}
// section?
if(line[0] == '[') {
if(line[line.size() - 1] != ']') {
throw syntax_error("The section '" + line +
"' is missing a closing bracket.");
}
line = _private::trim(line.substr(1, line.size() - 2));
cursec = &this->_sections[line];
continue;
}
// entry: split by "=", trim and set
std::string key;
std::string value;
if(_private::split(line, "=", key, value)) {
(*cursec)[_private::trim(key)] = _private::trim(value);
continue;
}
// throw exception on invalid line
throw syntax_error("The line '" + line + "' is invalid.");
}
}
std::string inifile::get(const std::string& section,
const std::string& key) const {
if(!this->_sections.count(section)) {
throw unknown_section_error(section);
}
if(!this->_sections.find(section)->second.count(key)) {
throw unknown_entry_error(section, key);
}
return this->_sections.find(section)->second.find(key)->second;
}
std::string inifile::get(const std::string& key) const {
if(!this->_defaultsection.count(key)) {
throw unknown_entry_error(key);
}
return this->_defaultsection.find(key)->second;
};
std::string inifile::dget(const std::string& section,
const std::string& key,
const std::string& default_value) const {
try {
return this->get(section, key);
}
catch(unknown_section_error& ex) { /* ignore */ }
catch(unknown_entry_error& ex) { /* ignore */ }
return default_value;
}
std::string inifile::dget(const std::string& key,
const std::string& default_value) const {
try {
return this->get(key);
}
catch(unknown_entry_error& ex) { /* ignore */ }
return default_value;
}
inisection inifile::section(const std::string& section) const {
if(!this->_sections.count(section)) {
throw unknown_section_error(section);
}
return inisection(section, *this);
};
inisection::inisection(const std::string& section, const inifile& ini)
: _section(section),
_ini(ini) {
/* empty */
}
inline std::string inisection::name() const {
return this->_section;
}
inline std::string inisection::get(const std::string& key) const {
return this->_ini.get(this->_section, key);
}
inline std::string inisection::dget(const std::string& key,
const std::string& default_val) const {
return this->_ini.dget(this->_section, key, default_val);
}
inline std::string _private::trim(const std::string& str,
const std::string& whitespace) {
size_t startpos = str.find_first_not_of(whitespace);
size_t endpos = str.find_last_not_of(whitespace);
// only whitespace, return empty line
if(startpos == std::string::npos || endpos == std::string::npos) {
return std::string();
}
// trim leading and trailing whitespace
return str.substr(startpos, endpos - startpos + 1);
}
inline bool _private::split(const std::string& in, const std::string& sep,
std::string& first, std::string& second) {
size_t eqpos = in.find(sep);
if(eqpos == std::string::npos) {
return false;
}
first = in.substr(0, eqpos);
second = in.substr(eqpos + sep.size(), in.size() - eqpos - sep.size());
return true;
}
}
#endif /* INIPP_HH */
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/device_token_fetcher.h"
#include <algorithm>
#include "base/message_loop.h"
#include "chrome/browser/policy/cloud_policy_cache.h"
#include "chrome/browser/policy/device_management_service.h"
#include "chrome/browser/policy/proto/device_management_constants.h"
#include "chrome/browser/policy/proto/device_management_local.pb.h"
namespace {
// Retry after 3 seconds (with exponential backoff) after token fetch errors.
const int64 kTokenFetchErrorDelayMilliseconds = 3 * 1000;
// For unmanaged devices, check once per day whether they're still unmanaged.
const int64 kUnmanagedDeviceRefreshRateMilliseconds = 24 * 60 * 60 * 1000;
} // namespace
namespace policy {
namespace em = enterprise_management;
DeviceTokenFetcher::DeviceTokenFetcher(
DeviceManagementService* service,
CloudPolicyCache* cache)
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
Initialize(service,
cache,
kTokenFetchErrorDelayMilliseconds,
kUnmanagedDeviceRefreshRateMilliseconds);
}
DeviceTokenFetcher::DeviceTokenFetcher(
DeviceManagementService* service,
CloudPolicyCache* cache,
int64 token_fetch_error_delay_ms,
int64 unmanaged_device_refresh_rate_ms)
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
Initialize(service,
cache,
token_fetch_error_delay_ms,
unmanaged_device_refresh_rate_ms);
}
DeviceTokenFetcher::~DeviceTokenFetcher() {
CancelRetryTask();
}
void DeviceTokenFetcher::FetchToken(
const std::string& auth_token,
const std::string& device_id,
em::DeviceRegisterRequest_Type policy_type,
const std::string& machine_id) {
SetState(STATE_INACTIVE);
auth_token_ = auth_token;
device_id_ = device_id;
policy_type_ = policy_type;
machine_id_ = machine_id;
FetchTokenInternal();
}
void DeviceTokenFetcher::FetchTokenInternal() {
DCHECK(state_ != STATE_TOKEN_AVAILABLE);
if (auth_token_.empty() || device_id_.empty()) {
// Maybe this device is unmanaged, just exit. The CloudPolicyController
// will call FetchToken() again if something changes.
return;
}
// Construct a new backend, which will discard any previous requests.
backend_.reset(service_->CreateBackend());
em::DeviceRegisterRequest request;
request.set_type(policy_type_);
if (!machine_id_.empty())
request.set_machine_id(machine_id_);
request.set_machine_model(kRegisterRequestMachineModel);
backend_->ProcessRegisterRequest(auth_token_, device_id_, request, this);
}
void DeviceTokenFetcher::SetUnmanagedState() {
// The call to |cache_->SetUnmanaged()| has to happen first because it sets
// the timestamp that |SetState()| needs to determine the correct refresh
// time.
cache_->SetUnmanaged();
SetState(STATE_UNMANAGED);
}
const std::string& DeviceTokenFetcher::GetDeviceToken() {
return device_token_;
}
void DeviceTokenFetcher::AddObserver(DeviceTokenFetcher::Observer* observer) {
observer_list_.AddObserver(observer);
}
void DeviceTokenFetcher::RemoveObserver(
DeviceTokenFetcher::Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void DeviceTokenFetcher::HandleRegisterResponse(
const em::DeviceRegisterResponse& response) {
if (response.has_device_management_token()) {
device_token_ = response.device_management_token();
SetState(STATE_TOKEN_AVAILABLE);
} else {
NOTREACHED();
SetState(STATE_ERROR);
}
}
void DeviceTokenFetcher::OnError(DeviceManagementBackend::ErrorCode code) {
if (code == DeviceManagementBackend::kErrorServiceManagementNotSupported) {
cache_->SetUnmanaged();
SetState(STATE_UNMANAGED);
}
SetState(STATE_ERROR);
}
void DeviceTokenFetcher::Initialize(DeviceManagementService* service,
CloudPolicyCache* cache,
int64 token_fetch_error_delay_ms,
int64 unmanaged_device_refresh_rate_ms) {
service_ = service;
cache_ = cache;
token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;
effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;
unmanaged_device_refresh_rate_ms_ = unmanaged_device_refresh_rate_ms;
state_ = STATE_INACTIVE;
retry_task_ = NULL;
if (cache_->is_unmanaged())
SetState(STATE_UNMANAGED);
}
void DeviceTokenFetcher::SetState(FetcherState state) {
state_ = state;
if (state_ != STATE_ERROR)
effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms_;
base::Time delayed_work_at;
switch (state_) {
case STATE_INACTIVE:
device_token_.clear();
auth_token_.clear();
device_id_.clear();
break;
case STATE_TOKEN_AVAILABLE:
FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenAvailable());
break;
case STATE_UNMANAGED:
delayed_work_at = cache_->last_policy_refresh_time() +
base::TimeDelta::FromMilliseconds(unmanaged_device_refresh_rate_ms_);
break;
case STATE_ERROR:
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
effective_token_fetch_error_delay_ms_ *= 2;
break;
}
CancelRetryTask();
if (!delayed_work_at.is_null()) {
base::Time now(base::Time::Now());
int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);
retry_task_ = method_factory_.NewRunnableMethod(
&DeviceTokenFetcher::ExecuteRetryTask);
MessageLoop::current()->PostDelayedTask(FROM_HERE, retry_task_,
delay);
}
}
void DeviceTokenFetcher::ExecuteRetryTask() {
DCHECK(retry_task_);
retry_task_ = NULL;
switch (state_) {
case STATE_INACTIVE:
case STATE_TOKEN_AVAILABLE:
break;
case STATE_UNMANAGED:
case STATE_ERROR:
FetchTokenInternal();
break;
}
}
void DeviceTokenFetcher::CancelRetryTask() {
if (retry_task_) {
retry_task_->Cancel();
retry_task_ = NULL;
}
}
} // namespace policy
<commit_msg>Fix handling of unmanaged signal for cloud policy.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/device_token_fetcher.h"
#include <algorithm>
#include "base/message_loop.h"
#include "chrome/browser/policy/cloud_policy_cache.h"
#include "chrome/browser/policy/device_management_service.h"
#include "chrome/browser/policy/proto/device_management_constants.h"
#include "chrome/browser/policy/proto/device_management_local.pb.h"
namespace {
// Retry after 3 seconds (with exponential backoff) after token fetch errors.
const int64 kTokenFetchErrorDelayMilliseconds = 3 * 1000;
// For unmanaged devices, check once per day whether they're still unmanaged.
const int64 kUnmanagedDeviceRefreshRateMilliseconds = 24 * 60 * 60 * 1000;
} // namespace
namespace policy {
namespace em = enterprise_management;
DeviceTokenFetcher::DeviceTokenFetcher(
DeviceManagementService* service,
CloudPolicyCache* cache)
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
Initialize(service,
cache,
kTokenFetchErrorDelayMilliseconds,
kUnmanagedDeviceRefreshRateMilliseconds);
}
DeviceTokenFetcher::DeviceTokenFetcher(
DeviceManagementService* service,
CloudPolicyCache* cache,
int64 token_fetch_error_delay_ms,
int64 unmanaged_device_refresh_rate_ms)
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
Initialize(service,
cache,
token_fetch_error_delay_ms,
unmanaged_device_refresh_rate_ms);
}
DeviceTokenFetcher::~DeviceTokenFetcher() {
CancelRetryTask();
}
void DeviceTokenFetcher::FetchToken(
const std::string& auth_token,
const std::string& device_id,
em::DeviceRegisterRequest_Type policy_type,
const std::string& machine_id) {
SetState(STATE_INACTIVE);
auth_token_ = auth_token;
device_id_ = device_id;
policy_type_ = policy_type;
machine_id_ = machine_id;
FetchTokenInternal();
}
void DeviceTokenFetcher::FetchTokenInternal() {
DCHECK(state_ != STATE_TOKEN_AVAILABLE);
if (auth_token_.empty() || device_id_.empty()) {
// Maybe this device is unmanaged, just exit. The CloudPolicyController
// will call FetchToken() again if something changes.
return;
}
// Construct a new backend, which will discard any previous requests.
backend_.reset(service_->CreateBackend());
em::DeviceRegisterRequest request;
request.set_type(policy_type_);
if (!machine_id_.empty())
request.set_machine_id(machine_id_);
request.set_machine_model(kRegisterRequestMachineModel);
backend_->ProcessRegisterRequest(auth_token_, device_id_, request, this);
}
void DeviceTokenFetcher::SetUnmanagedState() {
// The call to |cache_->SetUnmanaged()| has to happen first because it sets
// the timestamp that |SetState()| needs to determine the correct refresh
// time.
cache_->SetUnmanaged();
SetState(STATE_UNMANAGED);
}
const std::string& DeviceTokenFetcher::GetDeviceToken() {
return device_token_;
}
void DeviceTokenFetcher::AddObserver(DeviceTokenFetcher::Observer* observer) {
observer_list_.AddObserver(observer);
}
void DeviceTokenFetcher::RemoveObserver(
DeviceTokenFetcher::Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void DeviceTokenFetcher::HandleRegisterResponse(
const em::DeviceRegisterResponse& response) {
if (response.has_device_management_token()) {
device_token_ = response.device_management_token();
SetState(STATE_TOKEN_AVAILABLE);
} else {
NOTREACHED();
SetState(STATE_ERROR);
}
}
void DeviceTokenFetcher::OnError(DeviceManagementBackend::ErrorCode code) {
if (code == DeviceManagementBackend::kErrorServiceManagementNotSupported) {
cache_->SetUnmanaged();
SetState(STATE_UNMANAGED);
} else {
SetState(STATE_ERROR);
}
}
void DeviceTokenFetcher::Initialize(DeviceManagementService* service,
CloudPolicyCache* cache,
int64 token_fetch_error_delay_ms,
int64 unmanaged_device_refresh_rate_ms) {
service_ = service;
cache_ = cache;
token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;
effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;
unmanaged_device_refresh_rate_ms_ = unmanaged_device_refresh_rate_ms;
state_ = STATE_INACTIVE;
retry_task_ = NULL;
if (cache_->is_unmanaged())
SetState(STATE_UNMANAGED);
}
void DeviceTokenFetcher::SetState(FetcherState state) {
state_ = state;
if (state_ != STATE_ERROR)
effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms_;
base::Time delayed_work_at;
switch (state_) {
case STATE_INACTIVE:
device_token_.clear();
auth_token_.clear();
device_id_.clear();
break;
case STATE_TOKEN_AVAILABLE:
FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenAvailable());
break;
case STATE_UNMANAGED:
delayed_work_at = cache_->last_policy_refresh_time() +
base::TimeDelta::FromMilliseconds(unmanaged_device_refresh_rate_ms_);
break;
case STATE_ERROR:
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
effective_token_fetch_error_delay_ms_ *= 2;
break;
}
CancelRetryTask();
if (!delayed_work_at.is_null()) {
base::Time now(base::Time::Now());
int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);
retry_task_ = method_factory_.NewRunnableMethod(
&DeviceTokenFetcher::ExecuteRetryTask);
MessageLoop::current()->PostDelayedTask(FROM_HERE, retry_task_,
delay);
}
}
void DeviceTokenFetcher::ExecuteRetryTask() {
DCHECK(retry_task_);
retry_task_ = NULL;
switch (state_) {
case STATE_INACTIVE:
case STATE_TOKEN_AVAILABLE:
break;
case STATE_UNMANAGED:
case STATE_ERROR:
FetchTokenInternal();
break;
}
}
void DeviceTokenFetcher::CancelRetryTask() {
if (retry_task_) {
retry_task_->Cancel();
retry_task_ = NULL;
}
}
} // namespace policy
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
void ExitTimeout(void* parg)
{
#ifdef __WXMSW__
Sleep(5000);
ExitProcess(0);
#endif
}
void Shutdown(void* parg)
{
static CCriticalSection cs_Shutdown;
static bool fTaken;
bool fFirstThread;
CRITICAL_BLOCK(cs_Shutdown)
{
fFirstThread = !fTaken;
fTaken = true;
}
static bool fExit;
if (fFirstThread)
{
fShutdown = true;
nTransactionsUpdated++;
DBFlush(false);
StopNode();
DBFlush(true);
CreateThread(ExitTimeout, NULL);
Sleep(50);
printf("Bitcoin exiting\n\n");
fExit = true;
exit(0);
}
else
{
while (!fExit)
Sleep(500);
Sleep(100);
ExitThread(0);
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#ifndef GUI
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]))
fCommandLine = true;
fDaemon = !fCommandLine;
#ifdef __WXGTK__
if (!fCommandLine)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return 1;
}
if (pid > 0)
pthread_exit((void*)0);
}
#endif
if (!AppInit(argc, argv))
return 1;
while (!fShutdown)
Sleep(1000000);
return 0;
}
#endif
bool AppInit(int argc, char* argv[])
{
bool fRet = false;
try
{
fRet = AppInit2(argc, argv);
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
Shutdown(NULL);
return fRet;
}
bool AppInit2(int argc, char* argv[])
{
#ifdef _MSC_VER
// Turn off microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, ctrl-c
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifndef __WXMSW__
umask(077);
#endif
#ifndef __WXMSW__
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
#endif
//
// Parameters
//
ParseParameters(argc, argv);
if (mapArgs.count("-datadir"))
{
filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
}
ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
string strUsage = string() +
_("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
" bitcoin [options] \t " + "\n" +
" bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
" bitcoin [options] help \t\t " + _("List commands\n") +
" bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
_("Options:\n") +
" -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
" -gen \t\t " + _("Generate coins\n") +
" -gen=0 \t\t " + _("Don't generate coins\n") +
" -min \t\t " + _("Start minimized\n") +
" -datadir=<dir> \t\t " + _("Specify data directory\n") +
" -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
" -addnode=<ip> \t " + _("Add a node to connect to\n") +
" -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
" -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
" -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
" -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
" -testnet \t\t " + _("Use the test network\n") +
" -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
" -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
" -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port>\n") +
" -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
" -rpcconnect=<ip> \t " + _("Send commands to node running on <ip>\n") +
" -keypool=<n> \t " + _("Set key pool size to <n>\n") +
" -nolisten \t " + _("Don't accept connections from outside");
#ifdef USE_SSL
strUsage += string() +
_("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
" -rpcssl=1 \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
" -rpcsslcertificatchainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
" -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
" -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
#endif
strUsage += string() +
" -? \t\t " + _("This help message\n");
#if defined(__WXMSW__) && defined(GUI)
// Tabs make the columns line up in the message box
wxMessageBox(strUsage, "Bitcoin", wxOK);
#else
// Remove tabs
strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
fprintf(stderr, "%s", strUsage.c_str());
#endif
return false;
}
fDebug = GetBoolArg("-debug");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fTestNet = GetBoolArg("-testnet");
fNoListen = GetBoolArg("-nolisten");
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
if (!fDebug && !pszSetDataDir[0])
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer);
#ifdef GUI
printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
#endif
printf("Default data directory %s\n", GetDefaultDataDir().c_str());
if (GetBoolArg("-loadblockindextest"))
{
CTxDB txdb("r");
txdb.LoadBlockIndex();
PrintBlockTree();
return false;
}
//
// Limit to single instance per user
// Required to protect the database files if we're going to keep deleting log.*
//
#if defined(__WXMSW__) && defined(GUI)
// wxSingleInstanceChecker doesn't work on Linux
wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
for (int i = 0; i < strMutexName.size(); i++)
if (!isalnum(strMutexName[i]))
strMutexName[i] = '.';
wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
if (psingleinstancechecker->IsAnotherRunning())
{
printf("Existing instance found\n");
unsigned int nStart = GetTime();
loop
{
// Show the previous instance and exit
HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
if (hwndPrev)
{
if (IsIconic(hwndPrev))
ShowWindow(hwndPrev, SW_RESTORE);
SetForegroundWindow(hwndPrev);
return false;
}
if (GetTime() > nStart + 60)
return false;
// Resume this instance if the other exits
delete psingleinstancechecker;
Sleep(1000);
psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
if (!psingleinstancechecker->IsAnotherRunning())
break;
}
}
#endif
// Make sure only a single bitcoin process is using the data directory.
string strLockFile = GetDataDir() + "/.lock";
FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
fclose(file);
static boost::interprocess::file_lock lock(strLockFile.c_str());
if (!lock.try_lock())
{
wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
return false;
}
// Bind to the port early so we can tell if another instance is already running.
string strErrors;
if (!fNoListen)
{
if (!BindListenPort(strErrors))
{
wxMessageBox(strErrors, "Bitcoin");
return false;
}
}
//
// Load data files
//
if (fDaemon)
fprintf(stdout, "bitcoin server starting\n");
strErrors = "";
int64 nStart;
printf("Loading addresses...\n");
nStart = GetTimeMillis();
if (!LoadAddresses())
strErrors += _("Error loading addr.dat \n");
printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Loading block index...\n");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
strErrors += _("Error loading blkindex.dat \n");
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun;
if (!LoadWallet(fFirstRun))
strErrors += _("Error loading wallet.dat \n");
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Done loading\n");
//// debug print
printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("mapKeys.size() = %d\n", mapKeys.size());
printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
printf("mapWallet.size() = %d\n", mapWallet.size());
printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
if (!strErrors.empty())
{
wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
return false;
}
// Add wallet transactions that aren't already in a block to mapTransactions
ReacceptWalletTransactions();
//
// Parameters
//
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
fGenerateBitcoins = GetBoolArg("-gen");
if (mapArgs.count("-proxy"))
{
fUseProxy = true;
addrProxy = CAddress(mapArgs["-proxy"]);
if (!addrProxy.IsValid())
{
wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
return false;
}
}
if (mapArgs.count("-addnode"))
{
foreach(string strAddr, mapMultiArgs["-addnode"])
{
CAddress addr(strAddr, NODE_NETWORK);
addr.nTime = 0; // so it won't relay unless successfully connected
if (addr.IsValid())
AddAddress(addr);
}
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
{
wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
return false;
}
if (nTransactionFee > 0.25 * COIN)
wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
}
//
// Create the main window and start the node
//
#ifdef GUI
if (!fDaemon)
CreateMainWindow();
#endif
if (!CheckDiskSpace())
return false;
RandAddSeedPerfmon();
if (!CreateThread(StartNode, NULL))
wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
if (GetBoolArg("-server") || fDaemon)
CreateThread(ThreadRPCServer, NULL);
#if defined(__WXMSW__) && defined(GUI)
if (fFirstRun)
SetStartOnSystemStartup(true);
#endif
return true;
}
<commit_msg>The --help text wasn't showing the default values for three of the options, as follows:<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
void ExitTimeout(void* parg)
{
#ifdef __WXMSW__
Sleep(5000);
ExitProcess(0);
#endif
}
void Shutdown(void* parg)
{
static CCriticalSection cs_Shutdown;
static bool fTaken;
bool fFirstThread;
CRITICAL_BLOCK(cs_Shutdown)
{
fFirstThread = !fTaken;
fTaken = true;
}
static bool fExit;
if (fFirstThread)
{
fShutdown = true;
nTransactionsUpdated++;
DBFlush(false);
StopNode();
DBFlush(true);
CreateThread(ExitTimeout, NULL);
Sleep(50);
printf("Bitcoin exiting\n\n");
fExit = true;
exit(0);
}
else
{
while (!fExit)
Sleep(500);
Sleep(100);
ExitThread(0);
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#ifndef GUI
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]))
fCommandLine = true;
fDaemon = !fCommandLine;
#ifdef __WXGTK__
if (!fCommandLine)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return 1;
}
if (pid > 0)
pthread_exit((void*)0);
}
#endif
if (!AppInit(argc, argv))
return 1;
while (!fShutdown)
Sleep(1000000);
return 0;
}
#endif
bool AppInit(int argc, char* argv[])
{
bool fRet = false;
try
{
fRet = AppInit2(argc, argv);
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
Shutdown(NULL);
return fRet;
}
bool AppInit2(int argc, char* argv[])
{
#ifdef _MSC_VER
// Turn off microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, ctrl-c
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifndef __WXMSW__
umask(077);
#endif
#ifndef __WXMSW__
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
#endif
//
// Parameters
//
ParseParameters(argc, argv);
if (mapArgs.count("-datadir"))
{
filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
}
ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
string strUsage = string() +
_("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
" bitcoin [options] \t " + "\n" +
" bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
" bitcoin [options] help \t\t " + _("List commands\n") +
" bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
_("Options:\n") +
" -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
" -gen \t\t " + _("Generate coins\n") +
" -gen=0 \t\t " + _("Don't generate coins\n") +
" -min \t\t " + _("Start minimized\n") +
" -datadir=<dir> \t\t " + _("Specify data directory\n") +
" -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
" -addnode=<ip> \t " + _("Add a node to connect to\n") +
" -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
" -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
" -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
" -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
" -testnet \t\t " + _("Use the test network\n") +
" -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
" -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
" -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
" -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
" -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
" -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
" -nolisten \t " + _("Don't accept connections from outside");
#ifdef USE_SSL
strUsage += string() +
_("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
" -rpcssl=1 \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
" -rpcsslcertificatchainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
" -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
" -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
#endif
strUsage += string() +
" -? \t\t " + _("This help message\n");
#if defined(__WXMSW__) && defined(GUI)
// Tabs make the columns line up in the message box
wxMessageBox(strUsage, "Bitcoin", wxOK);
#else
// Remove tabs
strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
fprintf(stderr, "%s", strUsage.c_str());
#endif
return false;
}
fDebug = GetBoolArg("-debug");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fTestNet = GetBoolArg("-testnet");
fNoListen = GetBoolArg("-nolisten");
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
if (!fDebug && !pszSetDataDir[0])
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer);
#ifdef GUI
printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
#endif
printf("Default data directory %s\n", GetDefaultDataDir().c_str());
if (GetBoolArg("-loadblockindextest"))
{
CTxDB txdb("r");
txdb.LoadBlockIndex();
PrintBlockTree();
return false;
}
//
// Limit to single instance per user
// Required to protect the database files if we're going to keep deleting log.*
//
#if defined(__WXMSW__) && defined(GUI)
// wxSingleInstanceChecker doesn't work on Linux
wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
for (int i = 0; i < strMutexName.size(); i++)
if (!isalnum(strMutexName[i]))
strMutexName[i] = '.';
wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
if (psingleinstancechecker->IsAnotherRunning())
{
printf("Existing instance found\n");
unsigned int nStart = GetTime();
loop
{
// Show the previous instance and exit
HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
if (hwndPrev)
{
if (IsIconic(hwndPrev))
ShowWindow(hwndPrev, SW_RESTORE);
SetForegroundWindow(hwndPrev);
return false;
}
if (GetTime() > nStart + 60)
return false;
// Resume this instance if the other exits
delete psingleinstancechecker;
Sleep(1000);
psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
if (!psingleinstancechecker->IsAnotherRunning())
break;
}
}
#endif
// Make sure only a single bitcoin process is using the data directory.
string strLockFile = GetDataDir() + "/.lock";
FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
fclose(file);
static boost::interprocess::file_lock lock(strLockFile.c_str());
if (!lock.try_lock())
{
wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
return false;
}
// Bind to the port early so we can tell if another instance is already running.
string strErrors;
if (!fNoListen)
{
if (!BindListenPort(strErrors))
{
wxMessageBox(strErrors, "Bitcoin");
return false;
}
}
//
// Load data files
//
if (fDaemon)
fprintf(stdout, "bitcoin server starting\n");
strErrors = "";
int64 nStart;
printf("Loading addresses...\n");
nStart = GetTimeMillis();
if (!LoadAddresses())
strErrors += _("Error loading addr.dat \n");
printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Loading block index...\n");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
strErrors += _("Error loading blkindex.dat \n");
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun;
if (!LoadWallet(fFirstRun))
strErrors += _("Error loading wallet.dat \n");
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Done loading\n");
//// debug print
printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("mapKeys.size() = %d\n", mapKeys.size());
printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
printf("mapWallet.size() = %d\n", mapWallet.size());
printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
if (!strErrors.empty())
{
wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
return false;
}
// Add wallet transactions that aren't already in a block to mapTransactions
ReacceptWalletTransactions();
//
// Parameters
//
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
fGenerateBitcoins = GetBoolArg("-gen");
if (mapArgs.count("-proxy"))
{
fUseProxy = true;
addrProxy = CAddress(mapArgs["-proxy"]);
if (!addrProxy.IsValid())
{
wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
return false;
}
}
if (mapArgs.count("-addnode"))
{
foreach(string strAddr, mapMultiArgs["-addnode"])
{
CAddress addr(strAddr, NODE_NETWORK);
addr.nTime = 0; // so it won't relay unless successfully connected
if (addr.IsValid())
AddAddress(addr);
}
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
{
wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
return false;
}
if (nTransactionFee > 0.25 * COIN)
wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
}
//
// Create the main window and start the node
//
#ifdef GUI
if (!fDaemon)
CreateMainWindow();
#endif
if (!CheckDiskSpace())
return false;
RandAddSeedPerfmon();
if (!CreateThread(StartNode, NULL))
wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
if (GetBoolArg("-server") || fDaemon)
CreateThread(ThreadRPCServer, NULL);
#if defined(__WXMSW__) && defined(GUI)
if (fFirstRun)
SetStartOnSystemStartup(true);
#endif
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_manager.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_manager.h"
#include "chrome/common/render_messages.h"
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
PRERENDER_MODE_ENABLED;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::GetMode() {
return mode_;
}
// static
void PrerenderManager::SetMode(PrerenderManagerMode mode) {
mode_ = mode;
}
struct PrerenderManager::PrerenderContentsData {
PrerenderContents* contents_;
base::Time start_time_;
GURL url_;
PrerenderContentsData(PrerenderContents* contents,
base::Time start_time,
GURL url)
: contents_(contents),
start_time_(start_time),
url_(url) {
}
};
PrerenderManager::PrerenderManager(Profile* profile)
: profile_(profile),
max_prerender_age_(base::TimeDelta::FromSeconds(
kDefaultMaxPrerenderAgeSeconds)),
max_elements_(kDefaultMaxPrerenderElements),
prerender_contents_factory_(PrerenderContents::CreateFactory()) {
}
PrerenderManager::~PrerenderManager() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(
PrerenderContents::FINAL_STATUS_MANAGER_SHUTDOWN);
delete data.contents_;
}
}
void PrerenderManager::SetPrerenderContentsFactory(
PrerenderContents::Factory* prerender_contents_factory) {
prerender_contents_factory_.reset(prerender_contents_factory);
}
void PrerenderManager::AddPreload(const GURL& url,
const std::vector<GURL>& alias_urls) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeleteOldEntries();
// If the URL already exists in the set of preloaded URLs, don't do anything.
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->url_ == url)
return;
}
PrerenderContentsData data(CreatePrerenderContents(url, alias_urls),
GetCurrentTime(), url);
prerender_list_.push_back(data);
data.contents_->StartPrerendering();
while (prerender_list_.size() > max_elements_) {
data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_EVICTED);
delete data.contents_;
}
}
void PrerenderManager::DeleteOldEntries() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
if (IsPrerenderElementFresh(data.start_time_))
return;
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_TIMED_OUT);
delete data.contents_;
}
}
PrerenderContents* PrerenderManager::GetEntry(const GURL& url) {
DeleteOldEntries();
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
PrerenderContents* pc = it->contents_;
if (pc->MatchesURL(url)) {
PrerenderContents* pc = it->contents_;
prerender_list_.erase(it);
return pc;
}
}
// Entry not found.
return NULL;
}
bool PrerenderManager::MaybeUsePreloadedPage(TabContents* tc, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
scoped_ptr<PrerenderContents> pc(GetEntry(url));
if (pc.get() == NULL)
return false;
if (!pc->load_start_time().is_null())
RecordTimeUntilUsed(base::TimeTicks::Now() - pc->load_start_time());
pc->set_final_status(PrerenderContents::FINAL_STATUS_USED);
RenderViewHost* rvh = pc->render_view_host();
pc->set_render_view_host(NULL);
rvh->Send(new ViewMsg_DisplayPrerenderedPage(rvh->routing_id()));
tc->SwapInRenderViewHost(rvh);
ViewHostMsg_FrameNavigate_Params* p = pc->navigate_params();
if (p != NULL)
tc->DidNavigate(rvh, *p);
string16 title = pc->title();
if (!title.empty())
tc->UpdateTitle(rvh, pc->page_id(), UTF16ToWideHack(title));
if (pc->has_stopped_loading())
tc->DidStopLoading();
return true;
}
void PrerenderManager::RemoveEntry(PrerenderContents* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_ == entry) {
prerender_list_.erase(it);
break;
}
}
DeleteOldEntries();
}
base::Time PrerenderManager::GetCurrentTime() const {
return base::Time::Now();
}
bool PrerenderManager::IsPrerenderElementFresh(const base::Time start) const {
base::Time now = GetCurrentTime();
return (now - start < max_prerender_age_);
}
PrerenderContents* PrerenderManager::CreatePrerenderContents(
const GURL& url,
const std::vector<GURL>& alias_urls) {
return prerender_contents_factory_->CreatePrerenderContents(
this, profile_, url, alias_urls);
}
void PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta pplt) {
bool record_windowed_pplt = ShouldRecordWindowedPPLT();
switch (mode_) {
case PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderControl", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderControl", pplt);
}
break;
case PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderTreatment", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderTreatment", pplt);
}
break;
default:
break;
}
}
void PrerenderManager::RecordTimeUntilUsed(base::TimeDelta time_until_used) {
if (mode_ == PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP) {
UMA_HISTOGRAM_TIMES("PLT.TimeUntilUsed_PrerenderTreatment",
time_until_used);
}
}
PrerenderContents* PrerenderManager::FindEntry(const GURL& url) {
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_->MatchesURL(url))
return it->contents_;
}
// Entry not found.
return NULL;
}
void PrerenderManager::RecordPrefetchTagObserved() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// If we observe multiple tags within the 30 second window, we will still
// reset the window to begin at the most recent occurrence, so that we will
// always be in a window in the 30 seconds from each occurrence.
last_prefetch_seen_time_ = base::TimeTicks::Now();
}
bool PrerenderManager::ShouldRecordWindowedPPLT() const {
if (last_prefetch_seen_time_.is_null())
return false;
base::TimeDelta elapsed_time =
base::TimeTicks::Now() - last_prefetch_seen_time_;
return elapsed_time <= base::TimeDelta::FromSeconds(kWindowedPPLTSeconds);
}
<commit_msg>fix for build break BUG=none TEST=none Review URL: http://codereview.chromium.org/6334063<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_manager.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_manager.h"
#include "chrome/common/render_messages.h"
// static
base::TimeTicks PrerenderManager::last_prefetch_seen_time_;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
PRERENDER_MODE_ENABLED;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::GetMode() {
return mode_;
}
// static
void PrerenderManager::SetMode(PrerenderManagerMode mode) {
mode_ = mode;
}
struct PrerenderManager::PrerenderContentsData {
PrerenderContents* contents_;
base::Time start_time_;
GURL url_;
PrerenderContentsData(PrerenderContents* contents,
base::Time start_time,
GURL url)
: contents_(contents),
start_time_(start_time),
url_(url) {
}
};
PrerenderManager::PrerenderManager(Profile* profile)
: profile_(profile),
max_prerender_age_(base::TimeDelta::FromSeconds(
kDefaultMaxPrerenderAgeSeconds)),
max_elements_(kDefaultMaxPrerenderElements),
prerender_contents_factory_(PrerenderContents::CreateFactory()) {
}
PrerenderManager::~PrerenderManager() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(
PrerenderContents::FINAL_STATUS_MANAGER_SHUTDOWN);
delete data.contents_;
}
}
void PrerenderManager::SetPrerenderContentsFactory(
PrerenderContents::Factory* prerender_contents_factory) {
prerender_contents_factory_.reset(prerender_contents_factory);
}
void PrerenderManager::AddPreload(const GURL& url,
const std::vector<GURL>& alias_urls) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeleteOldEntries();
// If the URL already exists in the set of preloaded URLs, don't do anything.
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->url_ == url)
return;
}
PrerenderContentsData data(CreatePrerenderContents(url, alias_urls),
GetCurrentTime(), url);
prerender_list_.push_back(data);
data.contents_->StartPrerendering();
while (prerender_list_.size() > max_elements_) {
data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_EVICTED);
delete data.contents_;
}
}
void PrerenderManager::DeleteOldEntries() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
if (IsPrerenderElementFresh(data.start_time_))
return;
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_TIMED_OUT);
delete data.contents_;
}
}
PrerenderContents* PrerenderManager::GetEntry(const GURL& url) {
DeleteOldEntries();
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
PrerenderContents* pc = it->contents_;
if (pc->MatchesURL(url)) {
PrerenderContents* pc = it->contents_;
prerender_list_.erase(it);
return pc;
}
}
// Entry not found.
return NULL;
}
bool PrerenderManager::MaybeUsePreloadedPage(TabContents* tc, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
scoped_ptr<PrerenderContents> pc(GetEntry(url));
if (pc.get() == NULL)
return false;
if (!pc->load_start_time().is_null())
RecordTimeUntilUsed(base::TimeTicks::Now() - pc->load_start_time());
pc->set_final_status(PrerenderContents::FINAL_STATUS_USED);
RenderViewHost* rvh = pc->render_view_host();
pc->set_render_view_host(NULL);
rvh->Send(new ViewMsg_DisplayPrerenderedPage(rvh->routing_id()));
tc->SwapInRenderViewHost(rvh);
ViewHostMsg_FrameNavigate_Params* p = pc->navigate_params();
if (p != NULL)
tc->DidNavigate(rvh, *p);
string16 title = pc->title();
if (!title.empty())
tc->UpdateTitle(rvh, pc->page_id(), UTF16ToWideHack(title));
if (pc->has_stopped_loading())
tc->DidStopLoading();
return true;
}
void PrerenderManager::RemoveEntry(PrerenderContents* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_ == entry) {
prerender_list_.erase(it);
break;
}
}
DeleteOldEntries();
}
base::Time PrerenderManager::GetCurrentTime() const {
return base::Time::Now();
}
bool PrerenderManager::IsPrerenderElementFresh(const base::Time start) const {
base::Time now = GetCurrentTime();
return (now - start < max_prerender_age_);
}
PrerenderContents* PrerenderManager::CreatePrerenderContents(
const GURL& url,
const std::vector<GURL>& alias_urls) {
return prerender_contents_factory_->CreatePrerenderContents(
this, profile_, url, alias_urls);
}
void PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta pplt) {
bool record_windowed_pplt = ShouldRecordWindowedPPLT();
switch (mode_) {
case PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderControl", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderControl", pplt);
}
break;
case PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderTreatment", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderTreatment", pplt);
}
break;
default:
break;
}
}
void PrerenderManager::RecordTimeUntilUsed(base::TimeDelta time_until_used) {
if (mode_ == PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP) {
UMA_HISTOGRAM_TIMES("PLT.TimeUntilUsed_PrerenderTreatment",
time_until_used);
}
}
PrerenderContents* PrerenderManager::FindEntry(const GURL& url) {
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_->MatchesURL(url))
return it->contents_;
}
// Entry not found.
return NULL;
}
void PrerenderManager::RecordPrefetchTagObserved() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// If we observe multiple tags within the 30 second window, we will still
// reset the window to begin at the most recent occurrence, so that we will
// always be in a window in the 30 seconds from each occurrence.
last_prefetch_seen_time_ = base::TimeTicks::Now();
}
bool PrerenderManager::ShouldRecordWindowedPPLT() const {
if (last_prefetch_seen_time_.is_null())
return false;
base::TimeDelta elapsed_time =
base::TimeTicks::Now() - last_prefetch_seen_time_;
return elapsed_time <= base::TimeDelta::FromSeconds(kWindowedPPLTSeconds);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) DataStax, 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 "loop_test.hpp"
#include "callback.hpp"
#include "name_resolver.hpp"
#ifdef WIN32
#include "winsock.h"
#endif
#define RESOLVE_TIMEOUT 2000
using namespace datastax;
using namespace datastax::internal::core;
class NameResolverUnitTest : public LoopTest {
public:
NameResolverUnitTest()
: status_(NameResolver::NEW) {}
NameResolver::Ptr create(const Address& address) {
return NameResolver::Ptr(
new NameResolver(address, bind_callback(&NameResolverUnitTest::on_resolve, this)));
}
NameResolver::Status status() const { return status_; }
const String& hostname() const { return hostname_; }
private:
void on_resolve(NameResolver* resolver) {
status_ = resolver->status();
hostname_ = resolver->hostname();
}
private:
NameResolver::Status status_;
String hostname_;
};
TEST_F(NameResolverUnitTest, Simple) {
NameResolver::Ptr resolver(create(Address("127.254.254.254", 9042)));
resolver->resolve(loop(), RESOLVE_TIMEOUT);
run_loop();
ASSERT_EQ(NameResolver::SUCCESS, status());
#ifdef WIN32
char win_hostname[64];
gethostname(win_hostname, 64);
EXPECT_EQ(String(win_hostname), hostname());
#else
EXPECT_EQ("cpp-driver.hostname.", hostname());
#endif
}
TEST_F(NameResolverUnitTest, Timeout) {
NameResolver::Ptr resolver(create(Address("127.254.254.254", 9042)));
// Libuv's address resolver uses the uv_work thread pool to handle resolution
// asynchronously. If we starve all the threads in the uv_work thread pool
// then it will prevent the resolver work from completing before the timeout.
// This work must be queued before the resolver's work.
starve_thread_pool(200);
resolver->resolve(loop(), 1); // Use shortest possible timeout
run_loop();
ASSERT_EQ(NameResolver::FAILED_TIMED_OUT, status());
EXPECT_TRUE(hostname().empty());
}
TEST_F(NameResolverUnitTest, Invalid) {
NameResolver::Ptr resolver(create(Address()));
resolver->resolve(loop(), RESOLVE_TIMEOUT);
run_loop();
ASSERT_EQ(NameResolver::FAILED_BAD_PARAM, status());
EXPECT_TRUE(hostname().empty());
}
TEST_F(NameResolverUnitTest, Cancel) {
NameResolver::Ptr resolver(create(Address("127.254.254.254", 9042)));
resolver->resolve(loop(), RESOLVE_TIMEOUT);
resolver->cancel();
run_loop();
EXPECT_EQ(NameResolver::CANCELED, status());
EXPECT_TRUE(hostname().empty());
}
<commit_msg>Remove windows specific code from name resolver test<commit_after>/*
Copyright (c) DataStax, 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 "loop_test.hpp"
#include "callback.hpp"
#include "name_resolver.hpp"
#define RESOLVE_TIMEOUT 2000
using namespace datastax;
using namespace datastax::internal::core;
class NameResolverUnitTest : public LoopTest {
public:
NameResolverUnitTest()
: status_(NameResolver::NEW) {}
NameResolver::Ptr create(const Address& address) {
return NameResolver::Ptr(
new NameResolver(address, bind_callback(&NameResolverUnitTest::on_resolve, this)));
}
NameResolver::Status status() const { return status_; }
const String& hostname() const { return hostname_; }
private:
void on_resolve(NameResolver* resolver) {
status_ = resolver->status();
hostname_ = resolver->hostname();
}
private:
NameResolver::Status status_;
String hostname_;
};
TEST_F(NameResolverUnitTest, Simple) {
NameResolver::Ptr resolver(create(Address("127.254.254.254", 9042)));
resolver->resolve(loop(), RESOLVE_TIMEOUT);
run_loop();
ASSERT_EQ(NameResolver::SUCCESS, status());
EXPECT_EQ("cpp-driver.hostname.", hostname());
}
TEST_F(NameResolverUnitTest, Timeout) {
NameResolver::Ptr resolver(create(Address("127.254.254.254", 9042)));
// Libuv's address resolver uses the uv_work thread pool to handle resolution
// asynchronously. If we starve all the threads in the uv_work thread pool
// then it will prevent the resolver work from completing before the timeout.
// This work must be queued before the resolver's work.
starve_thread_pool(200);
resolver->resolve(loop(), 1); // Use shortest possible timeout
run_loop();
ASSERT_EQ(NameResolver::FAILED_TIMED_OUT, status());
EXPECT_TRUE(hostname().empty());
}
TEST_F(NameResolverUnitTest, Invalid) {
NameResolver::Ptr resolver(create(Address()));
resolver->resolve(loop(), RESOLVE_TIMEOUT);
run_loop();
ASSERT_EQ(NameResolver::FAILED_BAD_PARAM, status());
EXPECT_TRUE(hostname().empty());
}
TEST_F(NameResolverUnitTest, Cancel) {
NameResolver::Ptr resolver(create(Address("127.254.254.254", 9042)));
resolver->resolve(loop(), RESOLVE_TIMEOUT);
resolver->cancel();
run_loop();
EXPECT_EQ(NameResolver::CANCELED, status());
EXPECT_TRUE(hostname().empty());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include <algorithm>
#include <limits>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "chrome/browser/privacy_blacklist/blacklist_store.h"
#include "chrome/common/url_constants.h"
#include "net/http/http_util.h"
#define STRINGIZE(s) #s
namespace {
const char* const cookie_headers[2] = { "cookie", "set-cookie" };
} // namespace
const unsigned int Blacklist::kBlockAll = 1;
const unsigned int Blacklist::kBlockCookies = 1 << 1;
const unsigned int Blacklist::kDontSendReferrer = 1 << 2;
const unsigned int Blacklist::kDontSendUserAgent = 1 << 3;
const unsigned int Blacklist::kBlockUnsecure = 1 << 4;
const unsigned int Blacklist::kBlockRequest = kBlockAll | kBlockUnsecure;
const unsigned int Blacklist::kModifySentHeaders =
kBlockCookies | kDontSendUserAgent | kDontSendReferrer;
const unsigned int Blacklist::kModifyReceivedHeaders = kBlockCookies;
unsigned int Blacklist::String2Attribute(const std::string& s) {
if (s == STRINGIZE(kBlockAll))
return kBlockAll;
else if (s == STRINGIZE(kBlockCookies))
return kBlockCookies;
else if (s == STRINGIZE(kDontSendReferrer))
return kDontSendReferrer;
else if (s == STRINGIZE(kDontSendUserAgent))
return kDontSendUserAgent;
else if (s == STRINGIZE(kBlockUnsecure))
return kBlockUnsecure;
return 0;
}
// static
bool Blacklist::Matches(const std::string& pattern, const std::string& url) {
if (pattern.size() > url.size())
return false;
std::string::size_type p = 0;
std::string::size_type u = 0;
while (pattern[p] != '\0' && url[u] != '\0') {
if (pattern[p] == '@') {
while (pattern[++p] == '@'); // Consecutive @ are redundant.
if (pattern[p] == '\0')
return true; // Nothing to match after the @.
// Look for another wildcard to determine pattern-chunk.
std::string::size_type tp = pattern.find_first_of("@", p);
// If it must match until the end, compare the last characters.
if (tp == std::string::npos) {
std::string::size_type ur = url.size() - u;
std::string::size_type pr = pattern.size() - p;
return (pr <= ur) &&
(url.compare(url.size() - pr, pr, pattern.c_str() + p) == 0);
}
// Else find the pattern chunk which is pattern[p:tp]
std::string::size_type tu = url.find(pattern.c_str() + p, u, tp - p);
if (tu == std::string::npos)
return false; // Pattern chunk not found.
// Since tp is strictly greater than p, both u and p always increase.
u = tu + tp - p;
p = tp;
continue;
}
// Match non-wildcard character.
if (pattern[p++] != url[u++])
return false;
}
return pattern[p] == '\0';
}
bool Blacklist::Entry::IsBlocked(const GURL& url) const {
return (attributes_ & kBlockAll) ||
((attributes_ & kBlockUnsecure) && !url.SchemeIsSecure());
}
Blacklist::Entry::Entry(const std::string& pattern, const Provider* provider,
bool is_exception)
: attributes_(0),
is_exception_(is_exception),
pattern_(pattern),
provider_(provider) {}
void Blacklist::Entry::AddAttributes(unsigned int attributes) {
attributes_ |= attributes;
}
void Blacklist::Entry::Merge(const Entry& entry) {
attributes_ |= entry.attributes_;
}
bool Blacklist::Match::IsBlocked(const GURL& url) const {
return (attributes() & kBlockAll) ||
((attributes() & kBlockUnsecure) && !url.SchemeIsSecure());
}
Blacklist::Match::Match() : matching_attributes_(0), exception_attributes_(0) {}
void Blacklist::Match::AddEntry(const Entry* entry) {
if (entry->is_exception()) {
exception_attributes_ |= entry->attributes();
exception_entries_.push_back(entry);
} else {
matching_attributes_ |= entry->attributes();
matching_entries_.push_back(entry);
}
}
Blacklist::Blacklist() {
}
Blacklist::~Blacklist() {
}
void Blacklist::AddEntry(Entry* entry) {
DCHECK(entry);
blacklist_.push_back(linked_ptr<Entry>(entry));
}
void Blacklist::AddProvider(Provider* provider) {
DCHECK(provider);
providers_.push_back(linked_ptr<Provider>(provider));
}
// Returns a pointer to the Blacklist-owned entry which matches the given
// URL. If no matching Entry is found, returns null.
Blacklist::Match* Blacklist::FindMatch(const GURL& url) const {
// Never match something which is not http, https or ftp.
// TODO(idanan): Investigate if this would be an inclusion test instead of an
// exclusion test and if there are other schemes to test for.
if (!url.SchemeIs(chrome::kHttpScheme) &&
!url.SchemeIs(chrome::kHttpsScheme) &&
!url.SchemeIs(chrome::kFtpScheme))
return 0;
std::string url_spec = GetURLAsLookupString(url);
Match* match = NULL;
for (EntryList::const_iterator i = blacklist_.begin();
i != blacklist_.end(); ++i) {
if (Matches((*i)->pattern(), url_spec)) {
if (!match)
match = new Match;
match->AddEntry(i->get());
}
}
return match;
}
// static
std::string Blacklist::GetURLAsLookupString(const GURL& url) {
std::string url_spec = url.host() + url.path();
if (!url.query().empty())
url_spec = url_spec + "?" + url.query();
return url_spec;
}
std::string Blacklist::StripCookies(const std::string& header) {
return net::HttpUtil::StripHeaders(header, cookie_headers, 2);
}
<commit_msg>Whitespace change to clobber bots<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include <algorithm>
#include <limits>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "chrome/browser/privacy_blacklist/blacklist_store.h"
#include "chrome/common/url_constants.h"
#include "net/http/http_util.h"
#define STRINGIZE(s) #s
namespace {
const char* const cookie_headers[2] = { "cookie", "set-cookie" };
} // namespace
const unsigned int Blacklist::kBlockAll = 1;
const unsigned int Blacklist::kBlockCookies = 1 << 1;
const unsigned int Blacklist::kDontSendReferrer = 1 << 2;
const unsigned int Blacklist::kDontSendUserAgent = 1 << 3;
const unsigned int Blacklist::kBlockUnsecure = 1 << 4;
const unsigned int Blacklist::kBlockRequest = kBlockAll | kBlockUnsecure;
const unsigned int Blacklist::kModifySentHeaders =
kBlockCookies | kDontSendUserAgent | kDontSendReferrer;
const unsigned int Blacklist::kModifyReceivedHeaders = kBlockCookies;
unsigned int Blacklist::String2Attribute(const std::string& s) {
if (s == STRINGIZE(kBlockAll))
return kBlockAll;
else if (s == STRINGIZE(kBlockCookies))
return kBlockCookies;
else if (s == STRINGIZE(kDontSendReferrer))
return kDontSendReferrer;
else if (s == STRINGIZE(kDontSendUserAgent))
return kDontSendUserAgent;
else if (s == STRINGIZE(kBlockUnsecure))
return kBlockUnsecure;
return 0;
}
// static
bool Blacklist::Matches(const std::string& pattern, const std::string& url) {
if (pattern.size() > url.size())
return false;
std::string::size_type p = 0;
std::string::size_type u = 0;
while (pattern[p] != '\0' && url[u] != '\0') {
if (pattern[p] == '@') {
while (pattern[++p] == '@'); // Consecutive @ are redundant.
if (pattern[p] == '\0')
return true; // Nothing to match after the @.
// Look for another wildcard to determine pattern-chunk.
std::string::size_type tp = pattern.find_first_of("@", p);
// If it must match until the end, compare the last characters.
if (tp == std::string::npos) {
std::string::size_type ur = url.size() - u;
std::string::size_type pr = pattern.size() - p;
return (pr <= ur) &&
(url.compare(url.size() - pr, pr, pattern.c_str() + p) == 0);
}
// Else find the pattern chunk which is pattern[p:tp]
std::string::size_type tu = url.find(pattern.c_str() + p, u, tp - p);
if (tu == std::string::npos)
return false; // Pattern chunk not found.
// Since tp is strictly greater than p, both u and p always increase.
u = tu + tp - p;
p = tp;
continue;
}
// Match non-wildcard character.
if (pattern[p++] != url[u++])
return false;
}
return pattern[p] == '\0';
}
bool Blacklist::Entry::IsBlocked(const GURL& url) const {
return (attributes_ & kBlockAll) ||
((attributes_ & kBlockUnsecure) && !url.SchemeIsSecure());
}
Blacklist::Entry::Entry(const std::string& pattern, const Provider* provider,
bool is_exception)
: attributes_(0),
is_exception_(is_exception),
pattern_(pattern),
provider_(provider) {}
void Blacklist::Entry::AddAttributes(unsigned int attributes) {
attributes_ |= attributes;
}
void Blacklist::Entry::Merge(const Entry& entry) {
attributes_ |= entry.attributes_;
}
bool Blacklist::Match::IsBlocked(const GURL& url) const {
return (attributes() & kBlockAll) ||
((attributes() & kBlockUnsecure) && !url.SchemeIsSecure());
}
Blacklist::Match::Match() : matching_attributes_(0), exception_attributes_(0) {}
void Blacklist::Match::AddEntry(const Entry* entry) {
if (entry->is_exception()) {
exception_attributes_ |= entry->attributes();
exception_entries_.push_back(entry);
} else {
matching_attributes_ |= entry->attributes();
matching_entries_.push_back(entry);
}
}
Blacklist::Blacklist() {
}
Blacklist::~Blacklist() {
}
void Blacklist::AddEntry(Entry* entry) {
DCHECK(entry);
blacklist_.push_back(linked_ptr<Entry>(entry));
}
void Blacklist::AddProvider(Provider* provider) {
DCHECK(provider);
providers_.push_back(linked_ptr<Provider>(provider));
}
// Returns a pointer to the Blacklist-owned entry which matches the given
// URL. If no matching Entry is found, returns null.
Blacklist::Match* Blacklist::FindMatch(const GURL& url) const {
// Never match something which is not http, https or ftp.
// TODO(idanan): Investigate if this would be an inclusion test instead of an
// exclusion test and if there are other schemes to test for.
if (!url.SchemeIs(chrome::kHttpScheme) &&
!url.SchemeIs(chrome::kHttpsScheme) &&
!url.SchemeIs(chrome::kFtpScheme))
return 0;
std::string url_spec = GetURLAsLookupString(url);
Match* match = NULL;
for (EntryList::const_iterator i = blacklist_.begin();
i != blacklist_.end(); ++i) {
if (Matches((*i)->pattern(), url_spec)) {
if (!match)
match = new Match;
match->AddEntry(i->get());
}
}
return match;
}
// static
std::string Blacklist::GetURLAsLookupString(const GURL& url) {
std::string url_spec = url.host() + url.path();
if (!url.query().empty())
url_spec = url_spec + "?" + url.query();
return url_spec;
}
std::string Blacklist::StripCookies(const std::string& header) {
return net::HttpUtil::StripHeaders(header, cookie_headers, 2);
}
<|endoftext|> |
<commit_before>#include <QString>
#include <QtTest>
#include <getopt.h>
#include "application.h"
#include <iostream>
#include <fstream>
class StreamRedirect
{
public:
StreamRedirect(std::ostream & in_original, std::ostream & in_redirect) :
m_original(in_original),
m_old_buf(in_original.rdbuf(in_redirect.rdbuf()))
{ }
~StreamRedirect()
{
m_original.rdbuf(m_old_buf);
}
private:
Q_DISABLE_COPY(ScopedRedirect)
std::ostream &m_original;
std::streambuf *m_old_buf;
};
class Test_Application : public QObject
{
Q_OBJECT
public:
Test_Application();
private slots:
void test_process_cmd();
void test_crc_index_cmd();
void test_crc_name_cmd();
private:
void prepare_report(QuCRC_t & uCRC);
void prepare_argv(std::vector<std::string> &cmd);
static const size_t MAX_ARGC = 512;
QString report;
int argc;
char *argv[MAX_ARGC];
Application& app;
CRC_Param_Info info;
};
Test_Application::Test_Application():
QObject(0),
//private
argc(0),
app(Application::get_instance(argc, NULL))
{
}
void Test_Application::test_process_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--bits" , QString::number(info.bits, 10).toStdString(),
"--poly" , QString::number(info.poly, 16).toStdString(),
"--init" , QString::number(info.init, 16).toStdString(),
"--xor_out" , QString::number(info.xor_out, 16).toStdString(),
"--ref_in" , QString::number(info.ref_in, 10).toStdString(),
"--ref_out" , QString::number(info.ref_out, 10).toStdString()
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_index_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_index" , QString::number(i).toStdString(),
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_name_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_name" , info.name.toStdString(),
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::prepare_report(QuCRC_t & uCRC)
{
report = "For CRC: " + info.name + "\n cmd: ";
for(int j = 1; j < argc; j++)
{
report += argv[j];
report += " ";
}
report += "\n but get:";
report += " bits " + QString::number(uCRC.get_bits(), 10);
report += " poly " + QString::number(uCRC.get_poly(), 16);
report += " init " + QString::number(uCRC.get_init(), 16);
report += " xor_out " + QString::number(uCRC.get_xor_out(), 16);
report += " ref_in " + QString::number(uCRC.get_ref_in(), 10);
report += " ref_out " + QString::number(uCRC.get_ref_out(), 10);
}
void Test_Application::prepare_argv(std::vector<std::string> &cmd)
{
argc = cmd.size()+1; //+1 see getopt_long function
for(size_t j = 1; j <= cmd.size(); j++)
{
argv[j] = (char *)cmd[j-1].c_str();
}
// We use the processing_cmd function for processing the command line
// For this we use the getopt_long function several times
// to work properly, we must reset the optind
optind = 0;
}
QTEST_APPLESS_MAIN(Test_Application)
#include "test_application.moc"
<commit_msg>add Test_Application::test_crc_hex_cmd()<commit_after>#include <QString>
#include <QtTest>
#include <getopt.h>
#include "application.h"
#include <iostream>
#include <fstream>
#include <sstream> // std::stringstream, std::stringbuf
class StreamRedirect
{
public:
StreamRedirect(std::ostream & in_original, std::ostream & in_redirect) :
m_original(in_original),
m_old_buf(in_original.rdbuf(in_redirect.rdbuf()))
{ }
~StreamRedirect()
{
m_original.rdbuf(m_old_buf);
}
private:
Q_DISABLE_COPY(StreamRedirect)
std::ostream &m_original;
std::streambuf *m_old_buf;
};
class Test_Application : public QObject
{
Q_OBJECT
public:
Test_Application();
private slots:
void test_process_cmd();
void test_crc_index_cmd();
void test_crc_name_cmd();
void test_crc_hex_cmd();
private:
void prepare_report(const QString & name);
void prepare_report0(const QString & name);
void prepare_report1();
void prepare_argv(std::vector<std::string> &cmd);
static const size_t MAX_ARGC = 512;
QString report;
int argc;
char *argv[MAX_ARGC];
Application& app;
CRC_Param_Info info;
};
Test_Application::Test_Application():
QObject(0),
//private
argc(0),
app(Application::get_instance(argc, NULL))
{
}
void Test_Application::test_process_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--bits" , QString::number(info.bits, 10).toStdString(),
"--poly" , QString::number(info.poly, 16).toStdString(),
"--init" , QString::number(info.init, 16).toStdString(),
"--xor_out" , QString::number(info.xor_out, 16).toStdString(),
"--ref_in" , QString::number(info.ref_in, 10).toStdString(),
"--ref_out" , QString::number(info.ref_out, 10).toStdString()
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(info.name);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_index_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_index" , QString::number(i).toStdString(),
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(info.name);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_name_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_name" , info.name.toStdString(),
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(info.name);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_hex_cmd()
{
std::stringstream ss;
StreamRedirect redirect(std::cout, ss);
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_index" , QString::number(i).toStdString(),
"--hex", "\"31 32 33 34 35 36 37 38 39\""
};
//clear ss
ss.str("");
ss.clear();
//process
prepare_argv(cmd);
app.processing_cmd(argc, argv);
QString res(ss.str().c_str());
QString right_res = QString::number(app.uCRC.get_check(), 16) + "\n";
if( ( right_res.toUpper() != res) ) //Result in Upper format
{
prepare_report0(info.name);
report += " right_res: " + right_res + " but get: " + res;
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::prepare_report(const QString &name)
{
prepare_report0(name);
prepare_report1();
}
void Test_Application::prepare_report0(const QString & name)
{
report = "For CRC: " + name + "\n cmd: ";
for(int j = 1; j < argc; j++)
{
report += argv[j];
report += " ";
}
}
void Test_Application::prepare_report1()
{
report += "\n but get:";
report += " bits " + QString::number(app.uCRC.get_bits(), 10);
report += " poly " + QString::number(app.uCRC.get_poly(), 16);
report += " init " + QString::number(app.uCRC.get_init(), 16);
report += " xor_out " + QString::number(app.uCRC.get_xor_out(), 16);
report += " ref_in " + QString::number(app.uCRC.get_ref_in(), 10);
report += " ref_out " + QString::number(app.uCRC.get_ref_out(), 10);
}
void Test_Application::prepare_argv(std::vector<std::string> &cmd)
{
argc = cmd.size()+1; //+1 see getopt_long function
for(size_t j = 1; j <= cmd.size(); j++)
{
argv[j] = (char *)cmd[j-1].c_str();
}
// We use the processing_cmd function for processing the command line
// For this we use the getopt_long function several times
// to work properly, we must reset the optind
optind = 0;
}
QTEST_APPLESS_MAIN(Test_Application)
#include "test_application.moc"
<|endoftext|> |
<commit_before>// RUN: cat %s | %cling | FileCheck %s
// This test makes sure the interpreter doesn't create many useless empty
// transactions.
// Author: Vassil Vassilev
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "clang/AST/Decl.h"
#include <stdio.h>
.rawInput 1
using namespace cling;
void generateNestedTransaction(int depth) {
if (!depth)
return;
cling::Interpreter::PushTransactionRAII RAIIT(gCling);
if (depth | 0x1) { // if odd
char buff[100];
sprintf(buff, "int i%d;", depth);
gCling->process(buff);
} // this will cause every even transaction to be reused.
generateNestedTransaction(--depth);
}
.rawInput 0
generateNestedTransaction(5);
const cling::Transaction* T = gCling->getFirstTransaction();
while(T) {
if (!T->size())
printf("Empty transaction detected!\n");
else if (T->getWrapperFD() && T->getWrapperFD()->getKind() != clang::Decl::Function)
printf("Unexpected wrapper kind!\n");
if (T->getState() != Transaction::kCommitted)
printf("Unexpected transaction state!\n");
//T->printStructure();
T = T->getNext();
}
printf("Just make FileCheck(CHECK-NOT) happy.\n")
//CHECK-NOT:Empty transaction detected!
//CHECK-NOT:Unexpected wrapper kind!
//CHECK-NOT:Unexpected transaction state!
.q
<commit_msg>Use the correct interface to check for emptiness.<commit_after>// RUN: cat %s | %cling | FileCheck %s
// This test makes sure the interpreter doesn't create many useless empty
// transactions.
// Author: Vassil Vassilev
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "clang/AST/Decl.h"
#include <stdio.h>
.rawInput 1
using namespace cling;
void generateNestedTransaction(int depth) {
if (!depth)
return;
cling::Interpreter::PushTransactionRAII RAIIT(gCling);
if (depth | 0x1) { // if odd
char buff[100];
sprintf(buff, "int i%d;", depth);
gCling->process(buff);
} // this will cause every even transaction to be reused.
generateNestedTransaction(--depth);
}
.rawInput 0
generateNestedTransaction(5);
const cling::Transaction* T = gCling->getFirstTransaction();
while(T) {
if (T->empty())
printf("Empty transaction detected!\n");
else if (T->getWrapperFD() && T->getWrapperFD()->getKind() != clang::Decl::Function)
printf("Unexpected wrapper kind!\n");
if (T->getState() != Transaction::kCommitted)
printf("Unexpected transaction state!\n");
//T->printStructure();
T = T->getNext();
}
printf("Just make FileCheck(CHECK-NOT) happy.\n")
//CHECK-NOT:Empty transaction detected!
//CHECK-NOT:Unexpected wrapper kind!
//CHECK-NOT:Unexpected transaction state!
.q
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#if defined(_WIN32) || defined(_WIN64)
# include <windows.h>
# define sleep(x) Sleep((DWORD)(x*1000))
#else
# include <unistd.h>
#endif
#include "pokemon.h"
static
int
xSleep(lua_State* L) {
(void)luaD_push_location(L, __FILE__, __LINE__);
sleep(lua_tointeger(L, 1));
(void)luaD_pop_location(L);
return 0;
}
using namespace std;
int
main(int argc, char** argv) {
// set up pokemon
int error = luaD_setup(&argc, argv);
if (error) {
fprintf(stderr, "Pokemon setup error %d\n", error);
return error;
}
// create Lua state and register packages
#if LUA_VERSION_NUM >= 502
lua_State* L = luaL_newstate();
#else
lua_State* L = lua_open();
#endif
luaL_openlibs(L);
// register a global C function with name 'sleep'
lua_pushcfunction(L, xSleep);
lua_setglobal(L, "sleep");
// register Lua state with the debugger
(void)luaD_register(L);
// register inline Lua code with the deugger
(void)luaD_push_location(L, __FILE__, __LINE__ + 2);
error = luaL_loadstring(L,
"dofile(\"lua.lua\")"
);
if (error) {
fprintf(stderr, "lua_loadstring error %d\n", error);
} else {
error = lua_pcall(L, 0, LUA_MULTRET, 0);
if (error) {
const char* errorMessage = lua_tostring(L, 1);
fprintf(stderr, "%s\n", errorMessage);
}
}
// unregister Lua state from the debugger
(void)luaD_unregister(L);
// tear down pokemon
luaD_teardown();
return error;
}
<commit_msg>Fixed path to Lua file.<commit_after>#include <cstdio>
#include <cstdlib>
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#if defined(_WIN32) || defined(_WIN64)
# include <windows.h>
# define sleep(x) Sleep((DWORD)(x*1000))
#else
# include <unistd.h>
#endif
#include "pokemon.h"
static
int
xSleep(lua_State* L) {
(void)luaD_push_location(L, __FILE__, __LINE__);
sleep(lua_tointeger(L, 1));
(void)luaD_pop_location(L);
return 0;
}
using namespace std;
int
main(int argc, char** argv) {
// set up pokemon
int error = luaD_setup(&argc, argv);
if (error) {
fprintf(stderr, "Pokemon setup error %d\n", error);
return error;
}
// create Lua state and register packages
#if LUA_VERSION_NUM >= 502
lua_State* L = luaL_newstate();
#else
lua_State* L = lua_open();
#endif
luaL_openlibs(L);
// register a global C function with name 'sleep'
lua_pushcfunction(L, xSleep);
lua_setglobal(L, "sleep");
// register Lua state with the debugger
(void)luaD_register(L);
// register inline Lua code with the deugger
(void)luaD_push_location(L, __FILE__, __LINE__ + 2);
error = luaL_loadstring(L,
"dofile(\"example.lua\")"
);
if (error) {
fprintf(stderr, "lua_loadstring error %d\n", error);
} else {
error = lua_pcall(L, 0, LUA_MULTRET, 0);
if (error) {
const char* errorMessage = lua_tostring(L, 1);
fprintf(stderr, "%s\n", errorMessage);
}
}
// unregister Lua state from the debugger
(void)luaD_unregister(L);
// tear down pokemon
luaD_teardown();
return error;
}
<|endoftext|> |
<commit_before>#include "hand_rolled.hpp"
#define ACCEPT_REFERENCE_WRAPPER 1
#define INSTRUMENT_COPIES 1
#define BOOST_TEST_MODULE TypeErasure
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(hand_rolled)
{
#define ECHO(expr) \
do { \
std::cout << #expr << ";\nap.print() = "; \
expr; \
ap.print(); \
std::cout << "allocations: " << allocations() << "\n\n"; \
reset_allocations(); \
} while (false)
ECHO(hi_printable hi; any_printable ap(hi));
ECHO(large_printable large; any_printable ap(large));
ECHO(bye_printable bye; any_printable ap(bye));
ECHO(hi_printable hi; any_printable ap = hi);
ECHO(large_printable large; any_printable ap = large);
ECHO(bye_printable bye; any_printable ap = bye);
ECHO(hi_printable hi; any_printable tmp = hi; any_printable ap = tmp);
ECHO(large_printable large; any_printable tmp = large; any_printable ap = tmp);
ECHO(bye_printable bye; any_printable tmp = bye; any_printable ap = tmp);
ECHO(hi_printable hi; any_printable ap; ap = hi);
ECHO(large_printable large; any_printable ap; ap = large);
ECHO(bye_printable bye; any_printable ap; ap = bye);
ECHO(const hi_printable hi{}; any_printable ap(hi));
ECHO(const large_printable large{}; any_printable ap(large));
ECHO(const bye_printable bye{}; any_printable ap(bye));
ECHO(const hi_printable hi{}; any_printable ap = hi);
ECHO(const large_printable large{}; any_printable ap = large);
ECHO(const bye_printable bye{}; any_printable ap = bye);
ECHO(const hi_printable hi{}; any_printable tmp = hi; any_printable ap = tmp);
ECHO(const large_printable large{}; any_printable tmp = large; any_printable ap = tmp);
ECHO(const bye_printable bye{}; any_printable tmp = bye; any_printable ap = tmp);
ECHO(const hi_printable hi{}; any_printable ap; ap = hi);
ECHO(const large_printable large{}; any_printable ap; ap = large);
ECHO(const bye_printable bye{}; any_printable ap; ap = bye);
ECHO(any_printable ap(hi_printable{}));
ECHO(any_printable ap(large_printable{}));
ECHO(any_printable ap(bye_printable{}));
ECHO(any_printable ap = hi_printable{});
ECHO(any_printable ap = large_printable{});
ECHO(any_printable ap = bye_printable{});
#if ACCEPT_REFERENCE_WRAPPER
ECHO(hi_printable hi; any_printable ap(std::ref(hi)));
ECHO(large_printable large; any_printable ap(std::ref(large)));
ECHO(bye_printable bye; any_printable ap(std::ref(bye)));
ECHO(hi_printable hi; any_printable ap(std::cref(hi)));
ECHO(large_printable large; any_printable ap(std::cref(large)));
ECHO(bye_printable bye; any_printable ap(std::cref(bye)));
#endif
#undef ECHO
}
BOOST_AUTO_TEST_CASE(hand_rolled_vector)
{
hi_printable hi;
large_printable large;
bye_printable bye;
const hi_printable const_hi{};
const large_printable const_large{};
const bye_printable const_bye{};
std::vector<any_printable> several_printables = {
hi,
large,
bye,
#if ACCEPT_REFERENCE_WRAPPER
std::ref(hi),
std::ref(large),
std::cref(bye),
#endif
const_hi,
const_large,
const_bye
};
for (const auto & printable : several_printables) {
printable.print();
}
std::cout << "allocations: " << allocations() << "\n\n";
reset_allocations();
}
<commit_msg>Add COW vector to basic_test.cpp.<commit_after>#define ACCEPT_REFERENCE_WRAPPER 1
#define INSTRUMENT_COPIES 1
#include "hand_rolled.hpp"
#include "copy_on_write.hpp"
#define BOOST_TEST_MODULE TypeErasure
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(hand_rolled)
{
#define ECHO(expr) \
do { \
std::cout << #expr << ";\nap.print() = "; \
expr; \
ap.print(); \
std::cout << "allocations: " << allocations() << "\n\n"; \
reset_allocations(); \
} while (false)
ECHO(hi_printable hi; any_printable ap(hi));
ECHO(large_printable large; any_printable ap(large));
ECHO(bye_printable bye; any_printable ap(bye));
ECHO(hi_printable hi; any_printable ap = hi);
ECHO(large_printable large; any_printable ap = large);
ECHO(bye_printable bye; any_printable ap = bye);
ECHO(hi_printable hi; any_printable tmp = hi; any_printable ap = tmp);
ECHO(large_printable large; any_printable tmp = large; any_printable ap = tmp);
ECHO(bye_printable bye; any_printable tmp = bye; any_printable ap = tmp);
ECHO(hi_printable hi; any_printable ap; ap = hi);
ECHO(large_printable large; any_printable ap; ap = large);
ECHO(bye_printable bye; any_printable ap; ap = bye);
ECHO(const hi_printable hi{}; any_printable ap(hi));
ECHO(const large_printable large{}; any_printable ap(large));
ECHO(const bye_printable bye{}; any_printable ap(bye));
ECHO(const hi_printable hi{}; any_printable ap = hi);
ECHO(const large_printable large{}; any_printable ap = large);
ECHO(const bye_printable bye{}; any_printable ap = bye);
ECHO(const hi_printable hi{}; any_printable tmp = hi; any_printable ap = tmp);
ECHO(const large_printable large{}; any_printable tmp = large; any_printable ap = tmp);
ECHO(const bye_printable bye{}; any_printable tmp = bye; any_printable ap = tmp);
ECHO(const hi_printable hi{}; any_printable ap; ap = hi);
ECHO(const large_printable large{}; any_printable ap; ap = large);
ECHO(const bye_printable bye{}; any_printable ap; ap = bye);
ECHO(any_printable ap(hi_printable{}));
ECHO(any_printable ap(large_printable{}));
ECHO(any_printable ap(bye_printable{}));
ECHO(any_printable ap = hi_printable{});
ECHO(any_printable ap = large_printable{});
ECHO(any_printable ap = bye_printable{});
#if ACCEPT_REFERENCE_WRAPPER
ECHO(hi_printable hi; any_printable ap(std::ref(hi)));
ECHO(large_printable large; any_printable ap(std::ref(large)));
ECHO(bye_printable bye; any_printable ap(std::ref(bye)));
ECHO(hi_printable hi; any_printable ap(std::cref(hi)));
ECHO(large_printable large; any_printable ap(std::cref(large)));
ECHO(bye_printable bye; any_printable ap(std::cref(bye)));
#endif
#undef ECHO
}
BOOST_AUTO_TEST_CASE(hand_rolled_vector)
{
hi_printable hi;
large_printable large;
bye_printable bye;
const hi_printable const_hi{};
const large_printable const_large{};
const bye_printable const_bye{};
std::vector<any_printable> several_printables = {
hi,
large,
bye,
#if ACCEPT_REFERENCE_WRAPPER
std::ref(hi),
std::ref(large),
std::cref(bye),
#endif
const_hi,
const_large,
const_bye
};
for (const auto & printable : several_printables) {
printable.print();
}
std::cout << "allocations: " << allocations() << "\n\n";
reset_allocations();
}
BOOST_AUTO_TEST_CASE(hand_rolled_vector_copy_on_write)
{
hi_printable hi;
large_printable large;
bye_printable bye;
const hi_printable const_hi{};
const large_printable const_large{};
const bye_printable const_bye{};
std::vector<copy_on_write<any_printable>> several_printables = {
{hi},
{large},
{bye},
#if ACCEPT_REFERENCE_WRAPPER
{std::ref(hi)},
{std::ref(large)},
{std::cref(bye)},
#endif
{const_hi},
{const_large},
{const_bye}
};
for (const auto & printable : several_printables) {
printable->print();
}
std::cout << "allocations: " << allocations() << "\n\n";
reset_allocations();
}
<|endoftext|> |
<commit_before>//===--- AccessMarkerElimination.cpp - Eliminate access markers. ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This pass eliminates the instructions that demarcate memory access regions.
/// If no memory access markers exist, then the pass does nothing. Otherwise, it
/// unconditionally eliminates all non-dynamic markers (plus any dynamic markers
/// if dynamic exclusivity checking is disabled).
///
/// This is an always-on pass for temporary bootstrapping. It allows running
/// test cases through the pipeline and exercising SIL verification before all
/// passes support access markers.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "access-marker-elim"
#include "swift/Basic/Range.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
using namespace swift;
// This option allows markers to remain in -Onone as a structural SIL property.
// Regardless of this option, sufficient markers are always emitted to satisfy
// the current enforcement level. This options simply allows markers to remain
// for testing and validation.
//
// This option only applies to InactiveAccessMarkerElimination. Any occurrence
// of FullAccessMarkerElimination in the pass pipeline effectively overrides the
// options and removes all markers.
//
// At -Onone, with EnableMarkers, no static markers are removed.
// With !EnableMarkers:
// Enforcement | Static | Dynamic
// none | Remove after Diag | Remove ASAP
// unchecked | Remain through IRGen | Remove ASAP
// checked | Remain through IRGen | Remain through IRGen
// dynamic-only| Remove after Diag | Remain through IRGen
llvm::cl::opt<bool> EnableAccessMarkers(
"sil-access-markers", llvm::cl::init(true),
llvm::cl::desc("Enable memory access makers that aren't needed for "
"diagnostics."));
namespace {
struct AccessMarkerElimination : SILModuleTransform {
virtual bool isFullElimination() = 0;
bool removedAny = false;
SILBasicBlock::iterator eraseInst(SILInstruction *inst) {
removedAny = true;
return inst->getParent()->erase(inst);
};
void replaceBeginAccessUsers(BeginAccessInst *beginAccess);
// Precondition: !EnableAccessMarkers || isFullElimination()
bool shouldPreserveAccess(SILAccessEnforcement enforcement);
// Check if the instruction is a marker that should be eliminated. If so,
// updated the SIL, short of erasing the marker itself, and return true.
bool checkAndEliminateMarker(SILInstruction *inst);
// Entry point called by the pass manager.
void run() override;
};
void AccessMarkerElimination::replaceBeginAccessUsers(
BeginAccessInst *beginAccess) {
// Handle all the uses:
while (!beginAccess->use_empty()) {
Operand *op = *beginAccess->use_begin();
// Delete any associated end_access instructions.
if (auto endAccess = dyn_cast<EndAccessInst>(op->getUser())) {
assert(endAccess->use_empty() && "found use of end_access");
endAccess->eraseFromParent();
// Forward all other uses to the original address.
} else {
op->set(beginAccess->getSource());
}
}
}
// Precondition: !EnableAccessMarkers || isFullElimination()
bool AccessMarkerElimination::shouldPreserveAccess(
SILAccessEnforcement enforcement) {
if (isFullElimination())
return false;
auto &M = *getModule();
switch (enforcement) {
case SILAccessEnforcement::Unknown:
return false;
case SILAccessEnforcement::Static:
// Even though static enforcement is already performed, this flag is
// useful to control marker preservation for now.
return EnableAccessMarkers || M.getOptions().EnforceExclusivityStatic;
case SILAccessEnforcement::Dynamic:
// FIXME: when dynamic markers are fully supported, don't strip:
// return EnableAccessMarkers || M.getOptions().EnforceExclusivityDynamic;
return M.getOptions().EnforceExclusivityDynamic;
case SILAccessEnforcement::Unsafe:
return false;
}
}
// Check if the instruction is a marker that should be eliminated. If so,
// updated the SIL, short of erasing the marker itself, and return true.
bool AccessMarkerElimination::checkAndEliminateMarker(SILInstruction *inst) {
if (auto beginAccess = dyn_cast<BeginAccessInst>(inst)) {
// Leave dynamic accesses in place, but delete all others.
if (shouldPreserveAccess(beginAccess->getEnforcement()))
return false;
replaceBeginAccessUsers(beginAccess);
return true;
}
// end_access instructions will be handled when we process the
// begin_access.
// begin_unpaired_access instructions will be directly removed and
// simply replaced with their operand.
if (auto BUA = dyn_cast<BeginUnpairedAccessInst>(inst)) {
if (shouldPreserveAccess(BUA->getEnforcement()))
return false;
BUA->replaceAllUsesWith(BUA->getSource());
return true;
}
// end_unpaired_access instructions will be directly removed and
// simply replaced with their operand.
if (auto EUA = dyn_cast<EndUnpairedAccessInst>(inst)) {
if (shouldPreserveAccess(EUA->getEnforcement()))
return false;
assert(EUA->use_empty() && "use of end_unpaired_access");
return true;
}
return false;
}
void AccessMarkerElimination::run() {
// FIXME: When dynamic markers are fully supported, just skip this pass:
// if (EnableAccessMarkers && !isFullElimination())
// return;
auto &M = *getModule();
for (auto &F : M) {
// Iterating in reverse eliminates more begin_access users before they
// need to be replaced.
for (auto &BB : reversed(F)) {
// Don't cache the begin iterator since we're reverse iterating.
for (auto II = BB.end(); II != BB.begin();) {
SILInstruction *inst = &*(--II);
if (checkAndEliminateMarker(inst))
II = eraseInst(inst);
}
}
// Don't invalidate any analyses if we didn't do anything.
if (!removedAny)
continue;
auto InvalidKind = SILAnalysis::InvalidationKind::Instructions;
invalidateAnalysis(&F, InvalidKind);
}
}
struct InactiveAccessMarkerElimination : AccessMarkerElimination {
virtual bool isFullElimination() { return false; }
};
struct FullAccessMarkerElimination : AccessMarkerElimination {
virtual bool isFullElimination() { return true; }
};
} // end anonymous namespace
SILTransform *swift::createInactiveAccessMarkerElimination() {
return new InactiveAccessMarkerElimination();
}
SILTransform *swift::createFullAccessMarkerElimination() {
return new FullAccessMarkerElimination();
}
<commit_msg>SIL: IWYU (NFC)<commit_after>//===--- AccessMarkerElimination.cpp - Eliminate access markers. ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This pass eliminates the instructions that demarcate memory access regions.
/// If no memory access markers exist, then the pass does nothing. Otherwise, it
/// unconditionally eliminates all non-dynamic markers (plus any dynamic markers
/// if dynamic exclusivity checking is disabled).
///
/// This is an always-on pass for temporary bootstrapping. It allows running
/// test cases through the pipeline and exercising SIL verification before all
/// passes support access markers.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "access-marker-elim"
#include "swift/Basic/Range.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
// This option allows markers to remain in -Onone as a structural SIL property.
// Regardless of this option, sufficient markers are always emitted to satisfy
// the current enforcement level. This options simply allows markers to remain
// for testing and validation.
//
// This option only applies to InactiveAccessMarkerElimination. Any occurrence
// of FullAccessMarkerElimination in the pass pipeline effectively overrides the
// options and removes all markers.
//
// At -Onone, with EnableMarkers, no static markers are removed.
// With !EnableMarkers:
// Enforcement | Static | Dynamic
// none | Remove after Diag | Remove ASAP
// unchecked | Remain through IRGen | Remove ASAP
// checked | Remain through IRGen | Remain through IRGen
// dynamic-only| Remove after Diag | Remain through IRGen
llvm::cl::opt<bool> EnableAccessMarkers(
"sil-access-markers", llvm::cl::init(true),
llvm::cl::desc("Enable memory access makers that aren't needed for "
"diagnostics."));
namespace {
struct AccessMarkerElimination : SILModuleTransform {
virtual bool isFullElimination() = 0;
bool removedAny = false;
SILBasicBlock::iterator eraseInst(SILInstruction *inst) {
removedAny = true;
return inst->getParent()->erase(inst);
};
void replaceBeginAccessUsers(BeginAccessInst *beginAccess);
// Precondition: !EnableAccessMarkers || isFullElimination()
bool shouldPreserveAccess(SILAccessEnforcement enforcement);
// Check if the instruction is a marker that should be eliminated. If so,
// updated the SIL, short of erasing the marker itself, and return true.
bool checkAndEliminateMarker(SILInstruction *inst);
// Entry point called by the pass manager.
void run() override;
};
void AccessMarkerElimination::replaceBeginAccessUsers(
BeginAccessInst *beginAccess) {
// Handle all the uses:
while (!beginAccess->use_empty()) {
Operand *op = *beginAccess->use_begin();
// Delete any associated end_access instructions.
if (auto endAccess = dyn_cast<EndAccessInst>(op->getUser())) {
assert(endAccess->use_empty() && "found use of end_access");
endAccess->eraseFromParent();
// Forward all other uses to the original address.
} else {
op->set(beginAccess->getSource());
}
}
}
// Precondition: !EnableAccessMarkers || isFullElimination()
bool AccessMarkerElimination::shouldPreserveAccess(
SILAccessEnforcement enforcement) {
if (isFullElimination())
return false;
auto &M = *getModule();
switch (enforcement) {
case SILAccessEnforcement::Unknown:
return false;
case SILAccessEnforcement::Static:
// Even though static enforcement is already performed, this flag is
// useful to control marker preservation for now.
return EnableAccessMarkers || M.getOptions().EnforceExclusivityStatic;
case SILAccessEnforcement::Dynamic:
// FIXME: when dynamic markers are fully supported, don't strip:
// return EnableAccessMarkers || M.getOptions().EnforceExclusivityDynamic;
return M.getOptions().EnforceExclusivityDynamic;
case SILAccessEnforcement::Unsafe:
return false;
}
}
// Check if the instruction is a marker that should be eliminated. If so,
// updated the SIL, short of erasing the marker itself, and return true.
bool AccessMarkerElimination::checkAndEliminateMarker(SILInstruction *inst) {
if (auto beginAccess = dyn_cast<BeginAccessInst>(inst)) {
// Leave dynamic accesses in place, but delete all others.
if (shouldPreserveAccess(beginAccess->getEnforcement()))
return false;
replaceBeginAccessUsers(beginAccess);
return true;
}
// end_access instructions will be handled when we process the
// begin_access.
// begin_unpaired_access instructions will be directly removed and
// simply replaced with their operand.
if (auto BUA = dyn_cast<BeginUnpairedAccessInst>(inst)) {
if (shouldPreserveAccess(BUA->getEnforcement()))
return false;
BUA->replaceAllUsesWith(BUA->getSource());
return true;
}
// end_unpaired_access instructions will be directly removed and
// simply replaced with their operand.
if (auto EUA = dyn_cast<EndUnpairedAccessInst>(inst)) {
if (shouldPreserveAccess(EUA->getEnforcement()))
return false;
assert(EUA->use_empty() && "use of end_unpaired_access");
return true;
}
return false;
}
void AccessMarkerElimination::run() {
// FIXME: When dynamic markers are fully supported, just skip this pass:
// if (EnableAccessMarkers && !isFullElimination())
// return;
auto &M = *getModule();
for (auto &F : M) {
// Iterating in reverse eliminates more begin_access users before they
// need to be replaced.
for (auto &BB : reversed(F)) {
// Don't cache the begin iterator since we're reverse iterating.
for (auto II = BB.end(); II != BB.begin();) {
SILInstruction *inst = &*(--II);
if (checkAndEliminateMarker(inst))
II = eraseInst(inst);
}
}
// Don't invalidate any analyses if we didn't do anything.
if (!removedAny)
continue;
auto InvalidKind = SILAnalysis::InvalidationKind::Instructions;
invalidateAnalysis(&F, InvalidKind);
}
}
struct InactiveAccessMarkerElimination : AccessMarkerElimination {
virtual bool isFullElimination() { return false; }
};
struct FullAccessMarkerElimination : AccessMarkerElimination {
virtual bool isFullElimination() { return true; }
};
} // end anonymous namespace
SILTransform *swift::createInactiveAccessMarkerElimination() {
return new InactiveAccessMarkerElimination();
}
SILTransform *swift::createFullAccessMarkerElimination() {
return new FullAccessMarkerElimination();
}
<|endoftext|> |
<commit_before>
//g++-4.4 -DNOMTL -Wl,-rpath /usr/local/lib/oski -L /usr/local/lib/oski/ -l oski -l oski_util -l oski_util_Tid -DOSKI -I ~/Coding/LinearAlgebra/mtl4/ spmv.cpp -I .. -O2 -DNDEBUG -lrt -lm -l oski_mat_CSC_Tid -loskilt && ./a.out r200000 c200000 n100 t1 p1
#define SCALAR double
#include <iostream>
#include <algorithm>
#include "BenchTimer.h"
#include "BenchSparseUtil.h"
#define SPMV_BENCH(CODE) BENCH(t,tries,repeats,CODE);
// #ifdef MKL
//
// #include "mkl_types.h"
// #include "mkl_spblas.h"
//
// template<typename Lhs,typename Rhs,typename Res>
// void mkl_multiply(const Lhs& lhs, const Rhs& rhs, Res& res)
// {
// char n = 'N';
// float alpha = 1;
// char matdescra[6];
// matdescra[0] = 'G';
// matdescra[1] = 0;
// matdescra[2] = 0;
// matdescra[3] = 'C';
// mkl_scscmm(&n, lhs.rows(), rhs.cols(), lhs.cols(), &alpha, matdescra,
// lhs._valuePtr(), lhs._innerIndexPtr(), lhs.outerIndexPtr(),
// pntre, b, &ldb, &beta, c, &ldc);
// // mkl_somatcopy('C', 'T', lhs.rows(), lhs.cols(), 1,
// // lhs._valuePtr(), lhs.rows(), DST, dst_stride);
// }
//
// #endif
int main(int argc, char *argv[])
{
int size = 10000;
int rows = size;
int cols = size;
int nnzPerCol = 40;
int tries = 2;
int repeats = 2;
bool need_help = false;
for(int i = 1; i < argc; i++)
{
if(argv[i][0] == 'r')
{
rows = atoi(argv[i]+1);
}
else if(argv[i][0] == 'c')
{
cols = atoi(argv[i]+1);
}
else if(argv[i][0] == 'n')
{
nnzPerCol = atoi(argv[i]+1);
}
else if(argv[i][0] == 't')
{
tries = atoi(argv[i]+1);
}
else if(argv[i][0] == 'p')
{
repeats = atoi(argv[i]+1);
}
else
{
need_help = true;
}
}
if(need_help)
{
std::cout << argv[0] << " r<nb rows> c<nb columns> n<non zeros per column> t<nb tries> p<nb repeats>\n";
return 1;
}
std::cout << "SpMV " << rows << " x " << cols << " with " << nnzPerCol << " non zeros per column. (" << repeats << " repeats, and " << tries << " tries)\n\n";
EigenSparseMatrix sm(rows,cols);
DenseVector dv(cols), res(rows);
dv.setRandom();
BenchTimer t;
while (nnzPerCol>=4)
{
std::cout << "nnz: " << nnzPerCol << "\n";
sm.setZero();
fillMatrix2(nnzPerCol, rows, cols, sm);
// dense matrices
#ifdef DENSEMATRIX
{
DenseMatrix dm(rows,cols), (rows,cols);
eiToDense(sm, dm);
SPMV_BENCH(res = dm * sm);
std::cout << "Dense " << t.value()/repeats << "\t";
SPMV_BENCHres = dm.transpose() * sm);
std::cout << t.value()/repeats << endl;
}
#endif
// eigen sparse matrices
{
SPMV_BENCH(res.noalias() += sm * dv; )
std::cout << "Eigen " << t.value()/repeats << "\t";
SPMV_BENCH(res.noalias() += sm.transpose() * dv; )
std::cout << t.value()/repeats << endl;
}
// CSparse
#ifdef CSPARSE
{
std::cout << "CSparse \n";
cs *csm;
eiToCSparse(sm, csm);
// BENCH();
// timer.stop();
// std::cout << " a * b:\t" << timer.value() << endl;
// BENCH( { m3 = cs_sorted_multiply2(m1, m2); cs_spfree(m3); } );
// std::cout << " a * b:\t" << timer.value() << endl;
}
#endif
#ifdef OSKI
{
oski_matrix_t om;
oski_vecview_t ov, ores;
oski_Init();
om = oski_CreateMatCSC(sm._outerIndexPtr(), sm._innerIndexPtr(), sm._valuePtr(), rows, cols,
SHARE_INPUTMAT, 1, INDEX_ZERO_BASED);
ov = oski_CreateVecView(dv.data(), cols, STRIDE_UNIT);
ores = oski_CreateVecView(res.data(), rows, STRIDE_UNIT);
SPMV_BENCH( oski_MatMult(om, OP_NORMAL, 1, ov, 0, ores) );
std::cout << "OSKI " << t.value()/repeats << "\t";
SPMV_BENCH( oski_MatMult(om, OP_TRANS, 1, ov, 0, ores) );
std::cout << t.value()/repeats << "\n";
// tune
t.reset();
t.start();
oski_SetHintMatMult(om, OP_NORMAL, 1.0, SYMBOLIC_VEC, 0.0, SYMBOLIC_VEC, ALWAYS_TUNE_AGGRESSIVELY);
oski_TuneMat(om);
t.stop();
double tuning = t.value();
SPMV_BENCH( oski_MatMult(om, OP_NORMAL, 1, ov, 0, ores) );
std::cout << "OSKI tuned " << t.value()/repeats << "\t";
SPMV_BENCH( oski_MatMult(om, OP_TRANS, 1, ov, 0, ores) );
std::cout << t.value()/repeats << "\t(" << tuning << ")\n";
oski_DestroyMat(om);
oski_DestroyVecView(ov);
oski_DestroyVecView(ores);
oski_Close();
}
#endif
#ifndef NOUBLAS
{
using namespace boost::numeric;
UblasMatrix um(rows,cols);
eiToUblas(sm, um);
boost::numeric::ublas::vector<Scalar> uv(cols), ures(rows);
Map<Matrix<Scalar,Dynamic,1> >(&uv[0], cols) = dv;
Map<Matrix<Scalar,Dynamic,1> >(&ures[0], rows) = res;
SPMV_BENCH(ublas::axpy_prod(um, uv, ures, true));
std::cout << "ublas " << t.value()/repeats << "\t";
SPMV_BENCH(ublas::axpy_prod(boost::numeric::ublas::trans(um), uv, ures, true));
std::cout << t.value()/repeats << endl;
}
#endif
// GMM++
#ifndef NOGMM
{
GmmSparse gm(rows,cols);
eiToGmm(sm, gm);
std::vector<Scalar> gv(cols), gres(rows);
Map<Matrix<Scalar,Dynamic,1> >(&gv[0], cols) = dv;
Map<Matrix<Scalar,Dynamic,1> >(&gres[0], rows) = res;
SPMV_BENCH(gmm::mult(gm, gv, gres));
std::cout << "GMM++ " << t.value()/repeats << "\t";
SPMV_BENCH(gmm::mult(gmm::transposed(gm), gv, gres));
std::cout << t.value()/repeats << endl;
}
#endif
// MTL4
#ifndef NOMTL
{
MtlSparse mm(rows,cols);
eiToMtl(sm, mm);
mtl::dense_vector<Scalar> mv(cols, 1.0);
mtl::dense_vector<Scalar> mres(rows, 1.0);
SPMV_BENCH(mres = mm * mv);
std::cout << "MTL4 " << t.value()/repeats << "\t";
SPMV_BENCH(mres = trans(mm) * mv);
std::cout << t.value()/repeats << endl;
}
#endif
std::cout << "\n";
if(nnzPerCol==1)
break;
nnzPerCol -= nnzPerCol/2;
}
return 0;
}
<commit_msg>Fix bug 595: typo<commit_after>
//g++-4.4 -DNOMTL -Wl,-rpath /usr/local/lib/oski -L /usr/local/lib/oski/ -l oski -l oski_util -l oski_util_Tid -DOSKI -I ~/Coding/LinearAlgebra/mtl4/ spmv.cpp -I .. -O2 -DNDEBUG -lrt -lm -l oski_mat_CSC_Tid -loskilt && ./a.out r200000 c200000 n100 t1 p1
#define SCALAR double
#include <iostream>
#include <algorithm>
#include "BenchTimer.h"
#include "BenchSparseUtil.h"
#define SPMV_BENCH(CODE) BENCH(t,tries,repeats,CODE);
// #ifdef MKL
//
// #include "mkl_types.h"
// #include "mkl_spblas.h"
//
// template<typename Lhs,typename Rhs,typename Res>
// void mkl_multiply(const Lhs& lhs, const Rhs& rhs, Res& res)
// {
// char n = 'N';
// float alpha = 1;
// char matdescra[6];
// matdescra[0] = 'G';
// matdescra[1] = 0;
// matdescra[2] = 0;
// matdescra[3] = 'C';
// mkl_scscmm(&n, lhs.rows(), rhs.cols(), lhs.cols(), &alpha, matdescra,
// lhs._valuePtr(), lhs._innerIndexPtr(), lhs.outerIndexPtr(),
// pntre, b, &ldb, &beta, c, &ldc);
// // mkl_somatcopy('C', 'T', lhs.rows(), lhs.cols(), 1,
// // lhs._valuePtr(), lhs.rows(), DST, dst_stride);
// }
//
// #endif
int main(int argc, char *argv[])
{
int size = 10000;
int rows = size;
int cols = size;
int nnzPerCol = 40;
int tries = 2;
int repeats = 2;
bool need_help = false;
for(int i = 1; i < argc; i++)
{
if(argv[i][0] == 'r')
{
rows = atoi(argv[i]+1);
}
else if(argv[i][0] == 'c')
{
cols = atoi(argv[i]+1);
}
else if(argv[i][0] == 'n')
{
nnzPerCol = atoi(argv[i]+1);
}
else if(argv[i][0] == 't')
{
tries = atoi(argv[i]+1);
}
else if(argv[i][0] == 'p')
{
repeats = atoi(argv[i]+1);
}
else
{
need_help = true;
}
}
if(need_help)
{
std::cout << argv[0] << " r<nb rows> c<nb columns> n<non zeros per column> t<nb tries> p<nb repeats>\n";
return 1;
}
std::cout << "SpMV " << rows << " x " << cols << " with " << nnzPerCol << " non zeros per column. (" << repeats << " repeats, and " << tries << " tries)\n\n";
EigenSparseMatrix sm(rows,cols);
DenseVector dv(cols), res(rows);
dv.setRandom();
BenchTimer t;
while (nnzPerCol>=4)
{
std::cout << "nnz: " << nnzPerCol << "\n";
sm.setZero();
fillMatrix2(nnzPerCol, rows, cols, sm);
// dense matrices
#ifdef DENSEMATRIX
{
DenseMatrix dm(rows,cols), (rows,cols);
eiToDense(sm, dm);
SPMV_BENCH(res = dm * sm);
std::cout << "Dense " << t.value()/repeats << "\t";
SPMV_BENCH(res = dm.transpose() * sm);
std::cout << t.value()/repeats << endl;
}
#endif
// eigen sparse matrices
{
SPMV_BENCH(res.noalias() += sm * dv; )
std::cout << "Eigen " << t.value()/repeats << "\t";
SPMV_BENCH(res.noalias() += sm.transpose() * dv; )
std::cout << t.value()/repeats << endl;
}
// CSparse
#ifdef CSPARSE
{
std::cout << "CSparse \n";
cs *csm;
eiToCSparse(sm, csm);
// BENCH();
// timer.stop();
// std::cout << " a * b:\t" << timer.value() << endl;
// BENCH( { m3 = cs_sorted_multiply2(m1, m2); cs_spfree(m3); } );
// std::cout << " a * b:\t" << timer.value() << endl;
}
#endif
#ifdef OSKI
{
oski_matrix_t om;
oski_vecview_t ov, ores;
oski_Init();
om = oski_CreateMatCSC(sm._outerIndexPtr(), sm._innerIndexPtr(), sm._valuePtr(), rows, cols,
SHARE_INPUTMAT, 1, INDEX_ZERO_BASED);
ov = oski_CreateVecView(dv.data(), cols, STRIDE_UNIT);
ores = oski_CreateVecView(res.data(), rows, STRIDE_UNIT);
SPMV_BENCH( oski_MatMult(om, OP_NORMAL, 1, ov, 0, ores) );
std::cout << "OSKI " << t.value()/repeats << "\t";
SPMV_BENCH( oski_MatMult(om, OP_TRANS, 1, ov, 0, ores) );
std::cout << t.value()/repeats << "\n";
// tune
t.reset();
t.start();
oski_SetHintMatMult(om, OP_NORMAL, 1.0, SYMBOLIC_VEC, 0.0, SYMBOLIC_VEC, ALWAYS_TUNE_AGGRESSIVELY);
oski_TuneMat(om);
t.stop();
double tuning = t.value();
SPMV_BENCH( oski_MatMult(om, OP_NORMAL, 1, ov, 0, ores) );
std::cout << "OSKI tuned " << t.value()/repeats << "\t";
SPMV_BENCH( oski_MatMult(om, OP_TRANS, 1, ov, 0, ores) );
std::cout << t.value()/repeats << "\t(" << tuning << ")\n";
oski_DestroyMat(om);
oski_DestroyVecView(ov);
oski_DestroyVecView(ores);
oski_Close();
}
#endif
#ifndef NOUBLAS
{
using namespace boost::numeric;
UblasMatrix um(rows,cols);
eiToUblas(sm, um);
boost::numeric::ublas::vector<Scalar> uv(cols), ures(rows);
Map<Matrix<Scalar,Dynamic,1> >(&uv[0], cols) = dv;
Map<Matrix<Scalar,Dynamic,1> >(&ures[0], rows) = res;
SPMV_BENCH(ublas::axpy_prod(um, uv, ures, true));
std::cout << "ublas " << t.value()/repeats << "\t";
SPMV_BENCH(ublas::axpy_prod(boost::numeric::ublas::trans(um), uv, ures, true));
std::cout << t.value()/repeats << endl;
}
#endif
// GMM++
#ifndef NOGMM
{
GmmSparse gm(rows,cols);
eiToGmm(sm, gm);
std::vector<Scalar> gv(cols), gres(rows);
Map<Matrix<Scalar,Dynamic,1> >(&gv[0], cols) = dv;
Map<Matrix<Scalar,Dynamic,1> >(&gres[0], rows) = res;
SPMV_BENCH(gmm::mult(gm, gv, gres));
std::cout << "GMM++ " << t.value()/repeats << "\t";
SPMV_BENCH(gmm::mult(gmm::transposed(gm), gv, gres));
std::cout << t.value()/repeats << endl;
}
#endif
// MTL4
#ifndef NOMTL
{
MtlSparse mm(rows,cols);
eiToMtl(sm, mm);
mtl::dense_vector<Scalar> mv(cols, 1.0);
mtl::dense_vector<Scalar> mres(rows, 1.0);
SPMV_BENCH(mres = mm * mv);
std::cout << "MTL4 " << t.value()/repeats << "\t";
SPMV_BENCH(mres = trans(mm) * mv);
std::cout << t.value()/repeats << endl;
}
#endif
std::cout << "\n";
if(nnzPerCol==1)
break;
nnzPerCol -= nnzPerCol/2;
}
return 0;
}
<|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.
*
* Copyright (c) 2012, Sergey Lisitsyn
*/
#ifndef TAPKEE_MAIN_H_
#define TAPKEE_MAIN_H_
#include <shogun/lib/tapkee/tapkee_defines.hpp>
#include <shogun/lib/tapkee/tapkee_methods.hpp>
namespace tapkee
{
//! Main entry-point of the library. Constructs dense embedding with specified dimension
//! using provided data and callbacks. Returns DenseMatrix and ProjectingFunction with
//! corresponding ProjectionImplementation.
//!
//! Has four template parameters:
//!
//! RandomAccessIterator basic random access iterator with no specific capabilities.
//!
//! KernelCallback that defines ScalarType operator()(RandomAccessIterator, RandomAccessIterator) operation
//! between two iterators. The operation should return value of Mercer kernel function
//! between vectors/objects iterators pointing to. KernelCallback should be marked as a kernel function using
//! TAPKEE_CALLBACK_IS_KERNEL macro (fails on compilation in other case).
//!
//! DistanceCallback that defines ScalarType operator()(RandomAccessIterator, RandomAccessIterator) operation
//! between two iterators. DistanceCallback should be marked as a distance function using
//! TAPKEE_CALLBACK_IS_DISTANCE macro (fails during compilation in other case).
//!
//! FeatureVectorCallback that defines void operator()(RandomAccessIterator, DenseVector) operation
//! used to access feature vector pointed by iterator. The callback should put the feature vector pointed by iterator
//! to the vector of second argument.
//!
//! Parameters required by the chosen algorithm are obtained from the parameter map. It fails during runtime and
//! throws exception if some of required parameters are not specified or have improper values.
//!
//! @param begin begin iterator of data
//! @param end end iterator of data
//! @param kernel_callback the kernel callback described before
//! @param distance_callback the distance callback described before
//! @param feature_vector_callback the feature vector access callback descrbied before
//! @param options parameter map
//!
template <class RandomAccessIterator, class KernelCallback, class DistanceCallback, class FeatureVectorCallback>
ReturnResult embed(RandomAccessIterator begin, RandomAccessIterator end,
KernelCallback kernel_callback, DistanceCallback distance_callback,
FeatureVectorCallback feature_vector_callback, ParametersMap options)
{
Eigen::initParallel();
ReturnResult return_result;
TAPKEE_METHOD method;
try
{
method = options[REDUCTION_METHOD].cast<TAPKEE_METHOD>();
}
catch (const anyimpl::bad_any_cast&)
{
throw wrong_parameter_error("Wrong method specified.");
}
#define CALL_IMPLEMENTATION(X) \
tapkee_internal::implementation<RandomAccessIterator,KernelCallback,DistanceCallback,FeatureVectorCallback,X>()(\
begin,end,kernel_callback,distance_callback,feature_vector_callback,options)
#define HANDLE_IMPLEMENTATION(X) \
case X: return_result = CALL_IMPLEMENTATION(X); break
try
{
LoggingSingleton::instance().message_info("Using " + tapkee_internal::get_method_name(method) + " method.");
switch (method)
{
HANDLE_IMPLEMENTATION(KERNEL_LOCALLY_LINEAR_EMBEDDING);
HANDLE_IMPLEMENTATION(KERNEL_LOCAL_TANGENT_SPACE_ALIGNMENT);
HANDLE_IMPLEMENTATION(DIFFUSION_MAP);
HANDLE_IMPLEMENTATION(MULTIDIMENSIONAL_SCALING);
HANDLE_IMPLEMENTATION(LANDMARK_MULTIDIMENSIONAL_SCALING);
HANDLE_IMPLEMENTATION(ISOMAP);
HANDLE_IMPLEMENTATION(LANDMARK_ISOMAP);
HANDLE_IMPLEMENTATION(NEIGHBORHOOD_PRESERVING_EMBEDDING);
HANDLE_IMPLEMENTATION(LINEAR_LOCAL_TANGENT_SPACE_ALIGNMENT);
HANDLE_IMPLEMENTATION(HESSIAN_LOCALLY_LINEAR_EMBEDDING);
HANDLE_IMPLEMENTATION(LAPLACIAN_EIGENMAPS);
HANDLE_IMPLEMENTATION(LOCALITY_PRESERVING_PROJECTIONS);
HANDLE_IMPLEMENTATION(PCA);
HANDLE_IMPLEMENTATION(KERNEL_PCA);
HANDLE_IMPLEMENTATION(RANDOM_PROJECTION);
HANDLE_IMPLEMENTATION(STOCHASTIC_PROXIMITY_EMBEDDING);
HANDLE_IMPLEMENTATION(PASS_THRU);
HANDLE_IMPLEMENTATION(FACTOR_ANALYSIS);
HANDLE_IMPLEMENTATION(TSNE);
case UNKNOWN_METHOD: throw wrong_parameter_error("unknown method"); break;
}
}
catch (const std::bad_alloc& ba)
{
LoggingSingleton::instance().message_error("Not enough memory available.");
throw not_enough_memory_error("Not enough memory");
}
#undef CALL_IMPLEMENTATION
#undef HANDLE_IMPLEMENTATION
return return_result;
};
} // namespace tapkee
#endif
<commit_msg>Commented out initParallel of eigen in tapkee<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.
*
* Copyright (c) 2012, Sergey Lisitsyn
*/
#ifndef TAPKEE_MAIN_H_
#define TAPKEE_MAIN_H_
#include <shogun/lib/tapkee/tapkee_defines.hpp>
#include <shogun/lib/tapkee/tapkee_methods.hpp>
namespace tapkee
{
//! Main entry-point of the library. Constructs dense embedding with specified dimension
//! using provided data and callbacks. Returns DenseMatrix and ProjectingFunction with
//! corresponding ProjectionImplementation.
//!
//! Has four template parameters:
//!
//! RandomAccessIterator basic random access iterator with no specific capabilities.
//!
//! KernelCallback that defines ScalarType operator()(RandomAccessIterator, RandomAccessIterator) operation
//! between two iterators. The operation should return value of Mercer kernel function
//! between vectors/objects iterators pointing to. KernelCallback should be marked as a kernel function using
//! TAPKEE_CALLBACK_IS_KERNEL macro (fails on compilation in other case).
//!
//! DistanceCallback that defines ScalarType operator()(RandomAccessIterator, RandomAccessIterator) operation
//! between two iterators. DistanceCallback should be marked as a distance function using
//! TAPKEE_CALLBACK_IS_DISTANCE macro (fails during compilation in other case).
//!
//! FeatureVectorCallback that defines void operator()(RandomAccessIterator, DenseVector) operation
//! used to access feature vector pointed by iterator. The callback should put the feature vector pointed by iterator
//! to the vector of second argument.
//!
//! Parameters required by the chosen algorithm are obtained from the parameter map. It fails during runtime and
//! throws exception if some of required parameters are not specified or have improper values.
//!
//! @param begin begin iterator of data
//! @param end end iterator of data
//! @param kernel_callback the kernel callback described before
//! @param distance_callback the distance callback described before
//! @param feature_vector_callback the feature vector access callback descrbied before
//! @param options parameter map
//!
template <class RandomAccessIterator, class KernelCallback, class DistanceCallback, class FeatureVectorCallback>
ReturnResult embed(RandomAccessIterator begin, RandomAccessIterator end,
KernelCallback kernel_callback, DistanceCallback distance_callback,
FeatureVectorCallback feature_vector_callback, ParametersMap options)
{
//Eigen::initParallel();
ReturnResult return_result;
TAPKEE_METHOD method;
try
{
method = options[REDUCTION_METHOD].cast<TAPKEE_METHOD>();
}
catch (const anyimpl::bad_any_cast&)
{
throw wrong_parameter_error("Wrong method specified.");
}
#define CALL_IMPLEMENTATION(X) \
tapkee_internal::implementation<RandomAccessIterator,KernelCallback,DistanceCallback,FeatureVectorCallback,X>()(\
begin,end,kernel_callback,distance_callback,feature_vector_callback,options)
#define HANDLE_IMPLEMENTATION(X) \
case X: return_result = CALL_IMPLEMENTATION(X); break
try
{
LoggingSingleton::instance().message_info("Using " + tapkee_internal::get_method_name(method) + " method.");
switch (method)
{
HANDLE_IMPLEMENTATION(KERNEL_LOCALLY_LINEAR_EMBEDDING);
HANDLE_IMPLEMENTATION(KERNEL_LOCAL_TANGENT_SPACE_ALIGNMENT);
HANDLE_IMPLEMENTATION(DIFFUSION_MAP);
HANDLE_IMPLEMENTATION(MULTIDIMENSIONAL_SCALING);
HANDLE_IMPLEMENTATION(LANDMARK_MULTIDIMENSIONAL_SCALING);
HANDLE_IMPLEMENTATION(ISOMAP);
HANDLE_IMPLEMENTATION(LANDMARK_ISOMAP);
HANDLE_IMPLEMENTATION(NEIGHBORHOOD_PRESERVING_EMBEDDING);
HANDLE_IMPLEMENTATION(LINEAR_LOCAL_TANGENT_SPACE_ALIGNMENT);
HANDLE_IMPLEMENTATION(HESSIAN_LOCALLY_LINEAR_EMBEDDING);
HANDLE_IMPLEMENTATION(LAPLACIAN_EIGENMAPS);
HANDLE_IMPLEMENTATION(LOCALITY_PRESERVING_PROJECTIONS);
HANDLE_IMPLEMENTATION(PCA);
HANDLE_IMPLEMENTATION(KERNEL_PCA);
HANDLE_IMPLEMENTATION(RANDOM_PROJECTION);
HANDLE_IMPLEMENTATION(STOCHASTIC_PROXIMITY_EMBEDDING);
HANDLE_IMPLEMENTATION(PASS_THRU);
HANDLE_IMPLEMENTATION(FACTOR_ANALYSIS);
HANDLE_IMPLEMENTATION(TSNE);
case UNKNOWN_METHOD: throw wrong_parameter_error("unknown method"); break;
}
}
catch (const std::bad_alloc& ba)
{
LoggingSingleton::instance().message_error("Not enough memory available.");
throw not_enough_memory_error("Not enough memory");
}
#undef CALL_IMPLEMENTATION
#undef HANDLE_IMPLEMENTATION
return return_result;
};
} // namespace tapkee
#endif
<|endoftext|> |
<commit_before>
//
// big_number.cpp
//
// Class that implements a BigNumber representation.
//
// Created by Ryan Faulkner on 4/16/13.
// Copyright (c) 2013. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class BigNumber {
public:
BigNumber()
{
this->digits = NULL;
this->size = 0;
this->is_neg = false;
this->remainder = NULL;
}
BigNumber(const BigNumber& bn)
{
this->digits = new int[bn.get_size()];
this->size = bn.get_size();
this->is_neg = bn.is_negative_number();
this->digits = bn.get_digits_copy();
this->remainder = bn.get_remainder_copy();
}
BigNumber(int dim) {
this->digits = new int[dim];
this->size = dim;
this->is_neg = false;
for (int i = 0; i < dim; i++) this->digits[i] = 0;
this->remainder = NULL;
}
BigNumber(int dim, long val) {
int i;
this->digits = new int[dim];
this->size = dim;
this->is_neg = false;
for (i = 0; i < dim; i++) {
this->digits[i] = val % 10;
val /= 10;
}
this->remainder = NULL;
}
~BigNumber() {
delete[] this->digits;
if (this->remainder != NULL)
delete[] this->remainder;
}
/*
* Prints the number
*/
void print() const {
for (int i = this->size - 1; i >= 0; i--) cout << this->digits[i];
cout << endl;
}
/*
* Prints the remainder
*/
void print_remainder() const {
if (this->remainder != NULL)
{
for (int i = this->size - 1; i >= 0; i--) cout << this->remainder[i];
cout << endl;
}
}
bool is_negative_number() const { return this->is_neg; }
int get_size() const { return this->size; }
int get_digit(int index) const { return this->digits[index]; }
int get_most_significant_digit() const
{
for (int i = this->size - 1; i >= 0; i--)
if (digits[i] > 0)
return i;
return 0;
}
int* get_digits_copy() const
{
int* digits_cp = new int[this->size];
for (int i = 0; i < this->size; i++)
digits_cp[i] = this->digits[i];
return digits_cp;
}
int* get_remainder_copy() const
{
if (this->remainder != NULL)
{
int* rem_cp = new int[this->size];
for (int i = 0; i < this->size; i++)
rem_cp[i] = this->remainder[i];
return rem_cp;
}
return NULL;
}
bool has_remainder() {
if (this->remainder != NULL)
{
for (int i = 0; i < this->size; i++)
if (this->remainder[i] > 0)
return true;
}
return false;
}
void set_digits(int* digits) {
delete [] this->digits;
this->digits = digits;
this->size = sizeof(digits) / sizeof(int);
}
/*
* Set a digit in the array
*/
bool set_digit(int index, int value)
{
int most_sigdig = this->get_most_significant_digit();
if (value < 10 && value >= 0 && index >= 0 && index <= most_sigdig)
{
this->digits[index] = value;
return true;
}
return false;
}
/*
* Right shift the digits
*/
void right_shift()
{
int* new_digits = new int[this->size];
for (int i = 1; i < this->size; i++)
new_digits[i - 1] = this->digits[i];
new_digits[this->size - 1] = 0;
delete[] this->digits;
this->digits = new_digits;
}
/*
* Left shift the digits
*/
void left_shift() {
int* new_digits = new int[this->size];
for (int i = this->size - 1; i > 0; i--)
new_digits[i] = this->digits[i-1];
new_digits[0] = 0;
delete[] this->digits;
this->digits = new_digits;
}
BigNumber & operator=(const BigNumber &rhs)
{
// Check for self-assignment!
if (this == &rhs)
return *this;
delete[] this->digits;
this->size = rhs.get_size();
this->digits = rhs.get_digits_copy();
this->is_neg = rhs.is_negative_number();
this->remainder = rhs.get_remainder_copy();
return *this;
}
/*
* Adds this big number by the arg - size of operands
*/
BigNumber & operator+=(const BigNumber& other)
{
int i, new_val, carry = 0;
// TODO - throw exception instead
if (this->size != other.get_size())
{
cout << "BigNumber::operator+= - Mismatched sizes." << endl;
return *(new BigNumber(1,0));
}
for (i=0; i < this->size; i++)
{
new_val = digits[i] + other.get_digit(i) + carry;
this->digits[i] = new_val % 10;
if (new_val >= 10)
carry = new_val / 10;
else
carry = 0;
}
// TODO - throw exception instead
if (carry > 0)
cout << "BigNumber::operator+= - Overflow." << endl;
return *this;
}
/*
* Adds this big number by the arg - size of operands
*/
BigNumber & operator-=(const BigNumber& other)
{
int i, new_val;
int this_msd = this->get_most_significant_digit();
int other_msd = other.get_most_significant_digit();
bool this_larger = true;
int last_idx = this->size - 1;
int* digits_cp = other.get_digits_copy();
int *large_ref, *small_ref;
// TODO - throw exception instead
if (this->size != other.get_size())
{
cout << "BigNumber::operator-= - Mismatched sizes." << endl;
return *(new BigNumber(1,0));
}
// Determine which is larger
if (other_msd > this_msd)
this_larger = false;
else if (other_msd == this_msd)
for (i = this_msd; i >= 0; i--)
{
if (this->digits[i] < digits_cp[i])
{
this_larger = false;
this->is_neg = true;
break;
}
else if (this->digits[i] > digits_cp[i])
break;
}
// Set refs
if (this_larger)
{
large_ref = this->digits;
small_ref = digits_cp;
}
else
{
small_ref = this->digits;
large_ref = digits_cp;
}
// Perform subtraction
for (i = 0; i < this->size-1; i++)
{
new_val = large_ref[i] - small_ref[i];
// need to borrow?
if (new_val < 0)
{
large_ref[i] = new_val + 10;
large_ref[i+1] -= 1;
}
else
large_ref[i] = new_val;
}
new_val = large_ref[last_idx] - small_ref[last_idx];
large_ref[last_idx] = new_val;
if (large_ref != this->digits)
for (i = 0; i < this->size; i++)
this->digits[i] = large_ref[i];
delete[] digits_cp;
return *this;
}
/*
* Divide this big number by the arg. Uses long division.
*
*/
BigNumber & operator/=(const BigNumber& other)
{
int digit_value = 0;
int digit_index = this->get_most_significant_digit();
int* new_digits = new int[this->size];
BigNumber remainder(this->size, 0);
// Perform division
while (digit_index >= 0) {
digit_value = 0;
remainder.left_shift();
remainder.set_digit(0, this->get_digit(digit_index));
while (remainder >= other) {
digit_value++;
remainder -= other;
}
new_digits[digit_index] = digit_value;
digit_index--;
}
// Assign result and remainder
delete[] this->digits;
this->digits = new_digits;
if (this->remainder != NULL)
delete this->remainder;
this->remainder = remainder.get_digits_copy();
return *this;
}
/*
* Multiplies this big number by the arg
*/
BigNumber & operator*=(const int &other) {
int i, new_val, carry = 0;
for (i=0; i < this->size; i++) {
new_val = digits[i] * other + carry;
this->digits[i] = new_val % 10;
if (new_val >= 10)
carry = new_val / 10;
else
carry = 0;
}
return *this;
}
bool operator>(const BigNumber &rhs) const {
if (this->size < rhs.get_size())
for (int i = this->size; i < rhs.get_size(); i++)
if (rhs.get_digit(i) > 0)
return false;
else if (this->size > rhs.get_size())
for (int i = this->size - 1; i > rhs.get_size() - 1; i--)
if (this->digits[i] > 0)
return true;
for (int i = this->size - 1; i >= 0; i--) {
if (this->digits[i] > rhs.get_digit(i))
return true;
else if (this->digits[i] < rhs.get_digit(i))
return false;
}
return false;
}
bool operator<(const BigNumber &rhs) const {
return rhs > *this;
}
bool operator>=(const BigNumber &rhs) const {
return *this > rhs || *this == rhs;
}
bool operator<=(const BigNumber &rhs) const {
return *this < rhs || *this == rhs;
}
bool operator==(const BigNumber &other) const {
// If the sizes are not the values are not equal
if (this->size != other.size)
return false;
// Test each digit to ensure they match
for (int i = 0; i < this->size; i++)
if (this->digits[i] != other.get_digit(i))
return false;
// Everything matches, success!
return true;
}
bool operator!=(const BigNumber &other) const {
return !(*this==other);
}
private:
int* remainder;
int* digits;
int size;
bool is_neg;
};
inline BigNumber operator+(BigNumber lhs, const BigNumber &other) {
lhs += other;
return lhs;
}
inline BigNumber operator-(BigNumber lhs, const BigNumber &other) {
lhs -= other;
return lhs;
}
inline BigNumber operator*(BigNumber lhs, const int &other) {
lhs *= other;
return lhs;
}
inline BigNumber operator/(BigNumber lhs, const BigNumber &other) {
lhs /= other;
return lhs;
}
/*
* Determines if the number is prime
*
*/
inline bool is_prime(const BigNumber& value) {
BigNumber divisor(value.get_size(), 2);
BigNumber limit = value;
const BigNumber one(value.get_size(), 1);
while (divisor < limit) {
if (!(value / divisor).has_remainder()) {
return false;
}
divisor += one;
limit = value / divisor + one;
}
return true;
}
/*
* Determines if the number is pandigital
*
*/
inline bool is_pandigital(const BigNumber& value) {
int size = value.get_size();
int* buckets = new int[size];
int digit;
for (int i = 0; i < size; i ++) {
digit = value.get_digit(i);
if (digit > size)
return false;
else if (buckets[digit] == 1)
return false;
else
buckets[digit] = 1;
}
return true;
}
<commit_msg>fix - padding issue on /=.<commit_after>
//
// big_number.cpp
//
// Class that implements a BigNumber representation.
//
// Created by Ryan Faulkner on 4/16/13.
// Copyright (c) 2013. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class BigNumber {
public:
BigNumber()
{
this->digits = NULL;
this->size = 0;
this->is_neg = false;
this->remainder = NULL;
}
BigNumber(const BigNumber& bn)
{
this->digits = new int[bn.get_size()];
this->size = bn.get_size();
this->is_neg = bn.is_negative_number();
this->digits = bn.get_digits_copy();
this->remainder = bn.get_remainder_copy();
}
BigNumber(int dim) {
this->digits = new int[dim];
this->size = dim;
this->is_neg = false;
for (int i = 0; i < dim; i++) this->digits[i] = 0;
this->remainder = NULL;
}
BigNumber(int dim, long val) {
int i;
this->digits = new int[dim];
this->size = dim;
this->is_neg = false;
for (i = 0; i < dim; i++) {
this->digits[i] = val % 10;
val /= 10;
}
this->remainder = NULL;
}
~BigNumber() {
delete[] this->digits;
if (this->remainder != NULL)
delete[] this->remainder;
}
/*
* Prints the number
*/
void print() const {
for (int i = this->size - 1; i >= 0; i--) cout << this->digits[i];
cout << endl;
}
/*
* Prints the remainder
*/
void print_remainder() const {
if (this->remainder != NULL)
{
for (int i = this->size - 1; i >= 0; i--) cout << this->remainder[i];
cout << endl;
}
}
bool is_negative_number() const { return this->is_neg; }
int get_size() const { return this->size; }
int get_digit(int index) const { return this->digits[index]; }
int get_most_significant_digit() const
{
for (int i = this->size - 1; i >= 0; i--)
if (digits[i] > 0)
return i;
return 0;
}
int* get_digits_copy() const
{
int* digits_cp = new int[this->size];
for (int i = 0; i < this->size; i++)
digits_cp[i] = this->digits[i];
return digits_cp;
}
int* get_remainder_copy() const
{
if (this->remainder != NULL)
{
int* rem_cp = new int[this->size];
for (int i = 0; i < this->size; i++)
rem_cp[i] = this->remainder[i];
return rem_cp;
}
return NULL;
}
bool has_remainder() {
if (this->remainder != NULL)
{
for (int i = 0; i < this->size; i++)
if (this->remainder[i] > 0)
return true;
}
return false;
}
void set_digits(int* digits) {
delete [] this->digits;
this->digits = digits;
this->size = sizeof(digits) / sizeof(int);
}
/*
* Set a digit in the array
*/
bool set_digit(int index, int value)
{
int most_sigdig = this->get_most_significant_digit();
if (value < 10 && value >= 0 && index >= 0 && index <= most_sigdig)
{
this->digits[index] = value;
return true;
}
return false;
}
/*
* Right shift the digits
*/
void right_shift()
{
int* new_digits = new int[this->size];
for (int i = 1; i < this->size; i++)
new_digits[i - 1] = this->digits[i];
new_digits[this->size - 1] = 0;
delete[] this->digits;
this->digits = new_digits;
}
/*
* Left shift the digits
*/
void left_shift() {
int* new_digits = new int[this->size];
for (int i = this->size - 1; i > 0; i--)
new_digits[i] = this->digits[i-1];
new_digits[0] = 0;
delete[] this->digits;
this->digits = new_digits;
}
BigNumber & operator=(const BigNumber &rhs)
{
// Check for self-assignment!
if (this == &rhs)
return *this;
delete[] this->digits;
this->size = rhs.get_size();
this->digits = rhs.get_digits_copy();
this->is_neg = rhs.is_negative_number();
this->remainder = rhs.get_remainder_copy();
return *this;
}
/*
* Adds this big number by the arg - size of operands
*/
BigNumber & operator+=(const BigNumber& other)
{
int i, new_val, carry = 0;
// TODO - throw exception instead
if (this->size != other.get_size())
{
cout << "BigNumber::operator+= - Mismatched sizes." << endl;
return *(new BigNumber(1,0));
}
for (i=0; i < this->size; i++)
{
new_val = this->digits[i] + other.get_digit(i) + carry;
this->digits[i] = new_val % 10;
if (new_val >= 10)
carry = new_val / 10;
else
carry = 0;
}
// TODO - throw exception instead
if (carry > 0)
cout << "BigNumber::operator+= - Overflow." << endl;
return *this;
}
/*
* Adds this big number by the arg - size of operands
*/
BigNumber & operator-=(const BigNumber& other)
{
int i, new_val;
int this_msd = this->get_most_significant_digit();
int other_msd = other.get_most_significant_digit();
bool this_larger = true;
int last_idx = this->size - 1;
int* digits_cp = other.get_digits_copy();
int *large_ref, *small_ref;
// TODO - throw exception instead
if (this->size != other.get_size())
{
cout << "BigNumber::operator-= - Mismatched sizes." << endl;
return *(new BigNumber(1,0));
}
// Determine which is larger
if (other_msd > this_msd)
this_larger = false;
else if (other_msd == this_msd)
for (i = this_msd; i >= 0; i--)
{
if (this->digits[i] < digits_cp[i])
{
this_larger = false;
this->is_neg = true;
break;
}
else if (this->digits[i] > digits_cp[i])
break;
}
// Set refs
if (this_larger)
{
large_ref = this->digits;
small_ref = digits_cp;
}
else
{
small_ref = this->digits;
large_ref = digits_cp;
}
// Perform subtraction
for (i = 0; i < this->size-1; i++)
{
new_val = large_ref[i] - small_ref[i];
// need to borrow?
if (new_val < 0)
{
large_ref[i] = new_val + 10;
large_ref[i+1] -= 1;
}
else
large_ref[i] = new_val;
}
new_val = large_ref[last_idx] - small_ref[last_idx];
large_ref[last_idx] = new_val;
if (large_ref != this->digits)
for (i = 0; i < this->size; i++)
this->digits[i] = large_ref[i];
delete[] digits_cp;
return *this;
}
/*
* Divide this big number by the arg. Uses long division.
*
*/
BigNumber & operator/=(const BigNumber& other)
{
int digit_value = 0;
int digit_index = this->get_most_significant_digit();
int* new_digits = new int[this->size];
BigNumber remainder(this->size, 0);
// Perform division
while (digit_index >= 0) {
digit_value = 0;
remainder.left_shift();
remainder.set_digit(0, this->digits[digit_index]);
while (remainder >= other) {
digit_value++;
remainder -= other;
}
new_digits[digit_index] = digit_value;
digit_index--;
}
// Keep the padding consistent
for (int i = this->get_most_significant_digit() + 1; i < this->size; i++)
new_digits[i] = 0;
// Assign result and remainder
delete[] this->digits;
this->digits = new_digits;
if (this->remainder != NULL)
delete this->remainder;
this->remainder = remainder.get_digits_copy();
return *this;
}
/*
* Multiplies this big number by the arg
*/
BigNumber & operator*=(const int &other) {
int i, new_val, carry = 0;
for (i=0; i < this->size; i++) {
new_val = digits[i] * other + carry;
this->digits[i] = new_val % 10;
if (new_val >= 10)
carry = new_val / 10;
else
carry = 0;
}
return *this;
}
bool operator>(const BigNumber &rhs) const {
if (this->size < rhs.get_size())
for (int i = this->size; i < rhs.get_size(); i++)
if (rhs.get_digit(i) > 0)
return false;
else if (this->size > rhs.get_size())
for (int i = this->size - 1; i > rhs.get_size() - 1; i--)
if (this->digits[i] > 0)
return true;
for (int i = this->size - 1; i >= 0; i--) {
if (this->digits[i] > rhs.get_digit(i))
return true;
else if (this->digits[i] < rhs.get_digit(i))
return false;
}
return false;
}
bool operator<(const BigNumber &rhs) const {
return rhs > *this;
}
bool operator>=(const BigNumber &rhs) const {
return *this > rhs || *this == rhs;
}
bool operator<=(const BigNumber &rhs) const {
return *this < rhs || *this == rhs;
}
bool operator==(const BigNumber &other) const {
// If the sizes are not the values are not equal
if (this->size != other.size)
return false;
// Test each digit to ensure they match
for (int i = 0; i < this->size; i++)
if (this->digits[i] != other.get_digit(i))
return false;
// Everything matches, success!
return true;
}
bool operator!=(const BigNumber &other) const {
return !(*this==other);
}
private:
int* remainder;
int* digits;
int size;
bool is_neg;
};
inline BigNumber operator+(BigNumber lhs, const BigNumber &other) {
lhs += other;
return lhs;
}
inline BigNumber operator-(BigNumber lhs, const BigNumber &other) {
lhs -= other;
return lhs;
}
inline BigNumber operator*(BigNumber lhs, const int &other) {
lhs *= other;
return lhs;
}
inline BigNumber operator/(BigNumber lhs, const BigNumber &other) {
lhs /= other;
return lhs;
}
/*
* Determines if the number is prime
*
*/
inline bool is_prime(const BigNumber& value) {
BigNumber divisor(value.get_size(), 2);
BigNumber limit = value;
const BigNumber one(value.get_size(), 1);
while (divisor < limit) {
limit = value / divisor;
if (!limit.has_remainder())
return false;
divisor += one;
limit += one;
}
return true;
}
/*
* Determines if the number is pandigital
*
*/
inline bool is_pandigital(const BigNumber& value) {
int size = value.get_size();
int* buckets = new int[size];
int digit;
for (int i = 0; i < size; i ++) {
digit = value.get_digit(i);
if (digit > size)
return false;
else if (buckets[digit] == 1)
return false;
else
buckets[digit] = 1;
}
return true;
}
<|endoftext|> |
<commit_before>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief String utilities.
*/
#pragma once
#include "./config.hpp"
#include "./char.hpp"
#include "./string.hpp"
#include "./detail/string_traits.hpp"
#include "./EncodingUtils.hpp"
#include <cstring>
#include <type_traits>
#include <utility>
namespace duct {
namespace StringUtils {
/**
@addtogroup text
@{
*/
/**
@name General utilities
@{
*/
/** @cond INTERNAL */
namespace {
template<
class StringD,
class FromU
>
struct cvt_defs {
using string_type = StringD;
using
to_utils = typename detail::string_traits<string_type>::encoding_utils;
using from_utils = FromU;
using to_char = typename to_utils::char_type;
static constexpr bool
equivalent = std::is_same<
typename from_utils::char_type,
to_char
>::value;
enum {BUFFER_SIZE = 256u};
};
template<
class DefsT,
typename RandomAccessIt
>
bool
do_cvt(
typename DefsT::string_type& dest,
RandomAccessIt pos,
RandomAccessIt const end
) {
typename DefsT::to_char
out_buffer[DefsT::BUFFER_SIZE],
*out_iter = out_buffer
;
RandomAccessIt next;
char32 cp;
for (; end != pos; pos = next) {
next = DefsT::from_utils::decode(pos, end, cp, CHAR_NULL);
// Incomplete sequence
if (next == pos) {
// Flush if any data is left in the buffer
if (out_buffer != out_iter) {
dest.append(out_buffer, out_iter);
}
return false;
}
out_iter = DefsT::to_utils::encode(cp, out_iter, CHAR_NULL);
// Prevent output overrun
if (DefsT::BUFFER_SIZE <= 6 + (out_iter - out_buffer)) {
dest.append(out_buffer, out_iter);
out_iter = out_buffer;
}
}
// Flush if any data is left in the buffer
if (out_buffer != out_iter) {
dest.append(out_buffer, out_iter);
}
return true;
}
template<
class DefsT,
bool = DefsT::equivalent
>
struct cvt_impl;
template<
class DefsT
>
struct cvt_impl<DefsT, false> {
template<
typename RandomAccessIt
>
static bool
do_sequence(
typename DefsT::string_type& dest,
RandomAccessIt pos,
RandomAccessIt const end
) {
return do_cvt<DefsT>(dest, pos, end);
}
template<
class StringS
>
static bool
do_string(
typename DefsT::string_type& dest,
StringS const& src
) {
return do_cvt<DefsT>(dest, src.cbegin(), src.cend());
}
};
template<
class DefsT
>
struct cvt_impl<DefsT, true> {
template<
typename InputIt
>
static bool
do_sequence(
typename DefsT::string_type& dest,
InputIt pos,
InputIt const end
) {
dest.append(pos, end);
return true;
}
template<
class StringS
>
static bool
do_string(
typename DefsT::string_type& dest,
StringS const& src
) {
dest.append(src);
return true;
}
};
} // anonymous namespace
/** @endcond */ // INTERNAL
/**
Convert a string from one type (and encoding) to another.
@note If @a StringD and @a StringS have equivalent character
sizes, @a src is directly copied to @a dest (no re-encoding is
performed).
@note If an incomplete sequence was encountered in @a src
(@c false is returned), @a dest is guaranteed to contain all valid
code points up to the incomplete sequence.
@returns
- @c true on success; or
- @c false if an incomplete sequence was encountered.
@tparam StringD Destination string type; inferred from @a dest.
@tparam StringS Source string type; inferred from @a src.
@param[out] dest Destination string.
@param src Source string.
@param append Whether to append to @a dest; defaults to @c false
(@a dest is cleared on entry).
*/
template<
class StringD,
class StringS
>
inline bool
convert(
StringD& dest,
StringS const& src,
bool const append = false
) {
if (!append) {
dest.clear();
}
using FromU = typename detail::string_traits<StringS>::encoding_utils;
return cvt_impl<cvt_defs<StringD, FromU> >::do_string(dest, src);
}
/**
Convert a sequence from one encoding to another.
@note If @a StringD's encoding is equivalent
to @a FromU, @c [pos..end] is directly copied to @a dest
(no re-encoding is performed).
@note If an incomplete sequence was encountered (@c false is
returned), @a dest is guaranteed to contain all valid code points
up to the incomplete sequence.
@returns
- @c true on success; or
- @c false if an incomplete sequence was encountered.
@tparam FromU @c EncodingUtils specialization for decoding the
sequence.
@tparam StringD Destination string type; inferred from @a dest.
@tparam InputIt Type which satisfies @c InputIt requirements;
inferred from @a pos.
@param[out] dest Destination string.
@param pos Start of sequence.
@param end End of sequence.
@param append Whether to append to @a dest; defaults to @c false
(@a dest is cleared on entry).
*/
template<
class FromU,
class StringD,
typename InputIt
>
inline bool
convert(
StringD& dest,
InputIt pos,
InputIt const end,
bool const append = false
) {
if (!append) {
dest.clear();
}
return cvt_impl<cvt_defs<StringD, FromU> >::do_sequence(dest, pos, end);
}
/**
Count the number of times a code unit occurs in a sequence.
@note This function does not decode the string into code points;
it operates with <strong>code units</strong>.
@returns The number of times @a cu occurs in the sequence.
@tparam CharT Character type; inferred from @a cu.
@tparam InputIt Input iterator type; inferred from @a pos.
@param cu Code unit to count.
@param pos Start of sequence.
@param end End of sequence.
*/
template<
typename CharT,
typename InputIt
>
inline unsigned
unit_occurrences(
CharT const cu,
InputIt pos,
InputIt const end
) noexcept {
unsigned count = 0;
for (; end != pos; ++pos) {
if (cu == *pos) {
++count;
}
}
return count;
}
/**
Count the number of times a code unit occurs in a string.
@note This function does not decode the string into code points;
it operates with <strong>code units</strong>.
@returns The number of times @a cu occurs in @a str.
@tparam StringT String type; inferred from @a str.
@param cu Code unit to count.
@param str String to test.
*/
template<
class StringT
>
inline unsigned
unit_occurrences(
typename StringT::value_type const cu,
StringT const& str
) {
return unit_occurrences(cu, str.cbegin(), str.cend());
}
/** @} */ // end of name-group General utilities
/**
@name Escape utilities
@note Observe that all escape utilities operate only with ASCII
and the backslash.
@{
*/
/**
Pair of escapable chars (member @c first) and their replacements
(member @c second).
@warning Both strings must be the same size; behavior
is undefined otherwise.
*/
using EscapeablePair = std::pair<char const*, char const*>;
/**
Get the escapeable character for its replacement (e.g., 't' ->
literal tabulation).
@returns
- The escapeable character for @a cu; or
- @c CHAR_NULL if @a cu was non-matching.
@tparam CharT Character type; inferred from @a cu.
@param cu Code unit to test.
@param esc_pair Escapeables and replacements.
*/
template<
typename CharT
>
inline CharT
get_escape_char(
CharT const cu,
EscapeablePair const& esc_pair
) noexcept {
auto const pos = std::strchr(esc_pair.second, static_cast<signed>(cu));
if (nullptr != pos) {
return static_cast<CharT>(esc_pair.first[pos - esc_pair.second]);
} else {
return static_cast<CharT>(CHAR_NULL);
}
}
/**
Escape code units in a string.
@returns The number of units escaped.
@tparam StringT Input and result string type; inferred
from @a result.
@param[out] result Result string.
@param str String to escape.
@param esc_pair Escapeables and replacements.
@param ignore_invalids Whether to ignore existing non-matching
escape sequences. If @c false, will escape the backslash for
non-matching sequences.
@param clear Whether to clear @a result before
escaping; @c false by default.
*/
template<
class StringT,
class StringU = typename detail::string_traits<StringT>::encoding_utils,
typename CharT = typename detail::string_traits<StringT>::char_type
>
unsigned
escape_string(
StringT& result,
StringT const& str,
EscapeablePair const& esc_pair,
bool const ignore_invalids = false,
bool const clear = false
) {
unsigned escaped_count = 0;
typename StringT::const_iterator
next, last = str.cbegin();
CharT cu;
char const* es_pos;
if (clear) {
result.clear();
}
result.reserve(str.size());
for (auto it = str.cbegin(); str.cend() != it; it = next) {
cu = (*it);
next = it + 1;
if (CHAR_BACKSLASH == cu) {
// Escape if backslash is trailing or if escaped unit
// is non-matching (only when ignoring invalids)
if (str.cend() == next
|| (!ignore_invalids
&& nullptr
== std::strchr(
esc_pair.second, static_cast<signed>(*next)
)
)
) {
// Append section from last position to backslash
// (inclusive)
result.append(last, next);
// Prior backslash will form an escaped backslash
result.append(1, CHAR_BACKSLASH);
last = next;
++escaped_count;
}
// Can skip entire unit sequence
next = StringU::next(next, str.cend());
if ((it + 1) == next) {
// Invalid or incomplete sequence
break;
}
} else if (
(es_pos = std::strchr(
esc_pair.first, static_cast<signed>(cu))
, nullptr != es_pos)
) {
// Append last position to escapable unit (exclusive)
result.append(last, it);
result.append(1, CHAR_BACKSLASH);
// Append escaped form of unit
result.append(1, static_cast<CharT>(
esc_pair.second[es_pos - esc_pair.first]));
// Skip over the unit replaced
last = next;
++escaped_count;
} else { // Non-escapeable
// Can skip entire unit sequence
next = StringU::next(it, str.cend());
if (next == it) {
// Invalid or incomplete sequence
break;
}
}
}
result.append(last, str.cend());
return escaped_count;
}
/**
Escape code units in a string.
@returns The escaped string.
@tparam StringT Input and result string type; inferred
from @a str.
@param str String to escape.
@param esc_pair Escapeables and replacements.
@param ignore_invalids Whether to ignore existing non-matching
escape sequences. If @c false, will escape the backslash for
non-matching sequences.
*/
template<
class StringT
>
inline StringT
escape_string(
StringT const& str,
EscapeablePair const& esc_pair,
bool const ignore_invalids = false
) {
StringT escaped;
escape_string(escaped, str, esc_pair, ignore_invalids, false);
return escaped;
}
/** @} */ // end of name-group Escape utilities
/** @} */ // end of doc-group text
} // namespace StringUtils
} // namespace duct
<commit_msg>StringUtils: tidy.<commit_after>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief String utilities.
*/
#pragma once
#include "./config.hpp"
#include "./char.hpp"
#include "./string.hpp"
#include "./detail/string_traits.hpp"
#include "./EncodingUtils.hpp"
#include <cstring>
#include <type_traits>
#include <utility>
namespace duct {
namespace StringUtils {
/**
@addtogroup text
@{
*/
/**
@name General utilities
@{
*/
/** @cond INTERNAL */
namespace {
template<
class StringD,
class FromU
>
struct cvt_defs {
using string_type = StringD;
using
to_utils = typename detail::string_traits<string_type>::encoding_utils;
using from_utils = FromU;
using to_char = typename to_utils::char_type;
static constexpr bool
equivalent = std::is_same<
typename from_utils::char_type,
to_char
>::value;
enum {BUFFER_SIZE = 256u};
};
template<
class DefsT,
typename RandomAccessIt
>
bool
do_cvt(
typename DefsT::string_type& dest,
RandomAccessIt pos,
RandomAccessIt const end
) {
typename DefsT::to_char
out_buffer[DefsT::BUFFER_SIZE],
*out_iter = out_buffer
;
RandomAccessIt next;
char32 cp;
for (; end != pos; pos = next) {
next = DefsT::from_utils::decode(pos, end, cp, CHAR_NULL);
// Incomplete sequence
if (next == pos) {
// Flush if any data is left in the buffer
if (out_buffer != out_iter) {
dest.append(out_buffer, out_iter);
}
return false;
}
out_iter = DefsT::to_utils::encode(cp, out_iter, CHAR_NULL);
// Prevent output overrun
if (DefsT::BUFFER_SIZE <= 6 + (out_iter - out_buffer)) {
dest.append(out_buffer, out_iter);
out_iter = out_buffer;
}
}
// Flush if any data is left in the buffer
if (out_buffer != out_iter) {
dest.append(out_buffer, out_iter);
}
return true;
}
template<
class DefsT,
bool = DefsT::equivalent
>
struct cvt_impl;
template<
class DefsT
>
struct cvt_impl<DefsT, false> {
template<
typename RandomAccessIt
>
static bool
do_sequence(
typename DefsT::string_type& dest,
RandomAccessIt pos,
RandomAccessIt const end
) {
return do_cvt<DefsT>(dest, pos, end);
}
template<
class StringS
>
static bool
do_string(
typename DefsT::string_type& dest,
StringS const& src
) {
return do_cvt<DefsT>(dest, src.cbegin(), src.cend());
}
};
template<
class DefsT
>
struct cvt_impl<DefsT, true> {
template<
typename InputIt
>
static bool
do_sequence(
typename DefsT::string_type& dest,
InputIt pos,
InputIt const end
) {
dest.append(pos, end);
return true;
}
template<
class StringS
>
static bool
do_string(
typename DefsT::string_type& dest,
StringS const& src
) {
dest.append(src);
return true;
}
};
} // anonymous namespace
/** @endcond */ // INTERNAL
/**
Convert a string from one type (and encoding) to another.
@note If @a StringD and @a StringS have equivalent character
sizes, @a src is directly copied to @a dest (no re-encoding is
performed).
@note If an incomplete sequence was encountered in @a src
(@c false is returned), @a dest is guaranteed to contain all valid
code points up to the incomplete sequence.
@returns
- @c true on success; or
- @c false if an incomplete sequence was encountered.
@tparam StringD Destination string type; inferred from @a dest.
@tparam StringS Source string type; inferred from @a src.
@param[out] dest Destination string.
@param src Source string.
@param append Whether to append to @a dest; defaults to @c false
(@a dest is cleared on entry).
*/
template<
class StringD,
class StringS
>
inline bool
convert(
StringD& dest,
StringS const& src,
bool const append = false
) {
if (!append) {
dest.clear();
}
using FromU = typename detail::string_traits<StringS>::encoding_utils;
return cvt_impl<cvt_defs<StringD, FromU> >::do_string(dest, src);
}
/**
Convert a sequence from one encoding to another.
@note If @a StringD's encoding is equivalent
to @a FromU, @c [pos..end] is directly copied to @a dest
(no re-encoding is performed).
@note If an incomplete sequence was encountered (@c false is
returned), @a dest is guaranteed to contain all valid code points
up to the incomplete sequence.
@returns
- @c true on success; or
- @c false if an incomplete sequence was encountered.
@tparam FromU @c EncodingUtils specialization for decoding the
sequence.
@tparam StringD Destination string type; inferred from @a dest.
@tparam InputIt Type which satisfies @c InputIt requirements;
inferred from @a pos.
@param[out] dest Destination string.
@param pos Start of sequence.
@param end End of sequence.
@param append Whether to append to @a dest; defaults to @c false
(@a dest is cleared on entry).
*/
template<
class FromU,
class StringD,
typename InputIt
>
inline bool
convert(
StringD& dest,
InputIt pos,
InputIt const end,
bool const append = false
) {
if (!append) {
dest.clear();
}
return cvt_impl<cvt_defs<StringD, FromU> >::do_sequence(dest, pos, end);
}
/**
Count the number of times a code unit occurs in a sequence.
@note This function does not decode the string into code points;
it operates with <strong>code units</strong>.
@returns The number of times @a cu occurs in the sequence.
@tparam CharT Character type; inferred from @a cu.
@tparam InputIt Input iterator type; inferred from @a pos.
@param cu Code unit to count.
@param pos Start of sequence.
@param end End of sequence.
*/
template<
typename CharT,
typename InputIt
>
inline unsigned
unit_occurrences(
CharT const cu,
InputIt pos,
InputIt const end
) noexcept {
unsigned count = 0;
for (; end != pos; ++pos) {
if (cu == *pos) {
++count;
}
}
return count;
}
/**
Count the number of times a code unit occurs in a string.
@note This function does not decode the string into code points;
it operates with <strong>code units</strong>.
@returns The number of times @a cu occurs in @a str.
@tparam StringT String type; inferred from @a str.
@param cu Code unit to count.
@param str String to test.
*/
template<
class StringT
>
inline unsigned
unit_occurrences(
typename StringT::value_type const cu,
StringT const& str
) {
return unit_occurrences(cu, str.cbegin(), str.cend());
}
/** @} */ // end of name-group General utilities
/**
@name Escape utilities
@note Observe that all escape utilities operate only with ASCII
and the backslash.
@{
*/
/**
Pair of escapable chars (member @c first) and their replacements
(member @c second).
@warning Both strings must be the same size; behavior
is undefined otherwise.
*/
using EscapeablePair = std::pair<char const*, char const*>;
/**
Get the escapeable character for its replacement (e.g., 't' ->
literal tabulation).
@returns
- The escapeable character for @a cu; or
- @c CHAR_NULL if @a cu was non-matching.
@tparam CharT Character type; inferred from @a cu.
@param cu Code unit to test.
@param esc_pair Escapeables and replacements.
*/
template<
typename CharT
>
inline CharT
get_escape_char(
CharT const cu,
EscapeablePair const& esc_pair
) noexcept {
auto const pos = std::strchr(esc_pair.second, static_cast<signed>(cu));
if (nullptr != pos) {
return static_cast<CharT>(esc_pair.first[pos - esc_pair.second]);
} else {
return static_cast<CharT>(CHAR_NULL);
}
}
/**
Escape code units in a string.
@returns The number of units escaped.
@tparam StringT Input and result string type; inferred
from @a result.
@param[out] result Result string.
@param str String to escape.
@param esc_pair Escapeables and replacements.
@param ignore_invalids Whether to ignore existing non-matching
escape sequences. If @c false, will escape the backslash for
non-matching sequences.
@param clear Whether to clear @a result before
escaping; @c false by default.
*/
template<
class StringT,
class StringU = typename detail::string_traits<StringT>::encoding_utils,
typename CharT = typename detail::string_traits<StringT>::char_type
>
unsigned
escape_string(
StringT& result,
StringT const& str,
EscapeablePair const& esc_pair,
bool const ignore_invalids = false,
bool const clear = false
) {
unsigned escaped_count = 0;
typename StringT::const_iterator
next, last = str.cbegin();
CharT cu;
char const* es_pos;
if (clear) {
result.clear();
}
result.reserve(str.size());
for (auto it = str.cbegin(); str.cend() != it; it = next) {
cu = (*it);
next = it + 1;
if (CHAR_BACKSLASH == cu) {
// Escape if backslash is trailing or if escaped unit
// is non-matching (only when ignoring invalids)
if (str.cend() == next
|| (!ignore_invalids
&& nullptr
== std::strchr(
esc_pair.second, static_cast<signed>(*next)
)
)
) {
// Append section from last position to backslash
// (inclusive)
result.append(last, next);
// Prior backslash will form an escaped backslash
result.append(1, CHAR_BACKSLASH);
last = next;
++escaped_count;
}
// Can skip entire unit sequence
next = StringU::next(next, str.cend());
if ((it + 1) == next) {
// Invalid or incomplete sequence
break;
}
} else if (
(es_pos = std::strchr(
esc_pair.first, static_cast<signed>(cu))
, nullptr != es_pos)
) {
// Append last position to escapable unit (exclusive)
result.append(last, it);
result.append(1, CHAR_BACKSLASH);
// Append escaped form of unit
result.append(1, static_cast<CharT>(
esc_pair.second[es_pos - esc_pair.first]));
// Skip over the unit replaced
last = next;
++escaped_count;
} else { // Non-escapeable
// Can skip entire unit sequence
next = StringU::next(it, str.cend());
if (next == it) {
// Invalid or incomplete sequence
break;
}
}
}
result.append(last, str.cend());
return escaped_count;
}
/**
Escape code units in a string.
@returns The escaped string.
@tparam StringT Input and result string type; inferred
from @a str.
@param str String to escape.
@param esc_pair Escapeables and replacements.
@param ignore_invalids Whether to ignore existing non-matching
escape sequences. If @c false, will escape the backslash for
non-matching sequences.
*/
template<
class StringT
>
inline StringT
escape_string(
StringT const& str,
EscapeablePair const& esc_pair,
bool const ignore_invalids = false
) {
StringT escaped;
escape_string(escaped, str, esc_pair, ignore_invalids, false);
return escaped;
}
/** @} */ // end of name-group Escape utilities
/** @} */ // end of doc-group text
} // namespace StringUtils
} // namespace duct
<|endoftext|> |
<commit_before>#include "helpers.hpp"
#include <combinations.hpp>
#include <set>
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::combinations;
using itertest::BasicIterable;
using itertest::SolidInt;
using CharCombSet = std::vector<std::vector<char>>;
TEST_CASE("combinations: Simple combination of 4", "[combinations]") {
std::string s{"ABCD"};
CharCombSet sc;
for (auto v : combinations(s, 2)) {
sc.emplace_back(std::begin(v), std::end(v));
}
CharCombSet ans =
{{'A','B'}, {'A','C'}, {'A','D'}, {'B','C'}, {'B','D'}, {'C','D'}};
REQUIRE( ans == sc );
}
TEST_CASE("combinations: iterators can be compared", "[combinations]") {
std::string s{"ABCD"};
auto c = combinations(s, 2);
auto it = std::begin(c);
REQUIRE( it == std::begin(c) );
REQUIRE_FALSE( it != std::begin(c) );
++it;
REQUIRE( it != std::begin(c) );
REQUIRE_FALSE( it == std::begin(c) );
}
TEST_CASE("combinations: size too large gives no results", "[combinations]") {
std::string s{"ABCD"};
auto c = combinations(s, 5);
REQUIRE( std::begin(c) == std::end(c) );
}
TEST_CASE("combinations: size 0 gives nothing", "[combinations]") {
std::string s{"ABCD"};
auto c = combinations(s, 0);
REQUIRE( std::begin(c) == std::end(c) );
}
TEST_CASE("combinations: binds to lvalues, moves rvalues", "[combinations]") {
BasicIterable<char> bi{'x', 'y', 'z'};
SECTION("binds to lvalues") {
combinations(bi, 1);
REQUIRE_FALSE( bi.was_moved_from() );
}
SECTION("moves rvalues") {
combinations(std::move(bi), 1);
REQUIRE( bi.was_moved_from() );
}
}
TEST_CASE("combinations: doesn't move or copy elements of iterable",
"[combinations]") {
constexpr SolidInt arr[] = {{6}, {7}, {8}};
for (auto&& i : combinations(arr, 1)) {
(void)i;
}
}
<commit_msg>tests combinations iterator requirements<commit_after>#include "helpers.hpp"
#include <combinations.hpp>
#include <set>
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::combinations;
using itertest::BasicIterable;
using itertest::SolidInt;
using CharCombSet = std::vector<std::vector<char>>;
TEST_CASE("combinations: Simple combination of 4", "[combinations]") {
std::string s{"ABCD"};
CharCombSet sc;
for (auto v : combinations(s, 2)) {
sc.emplace_back(std::begin(v), std::end(v));
}
CharCombSet ans =
{{'A','B'}, {'A','C'}, {'A','D'}, {'B','C'}, {'B','D'}, {'C','D'}};
REQUIRE( ans == sc );
}
TEST_CASE("combinations: iterators can be compared", "[combinations]") {
std::string s{"ABCD"};
auto c = combinations(s, 2);
auto it = std::begin(c);
REQUIRE( it == std::begin(c) );
REQUIRE_FALSE( it != std::begin(c) );
++it;
REQUIRE( it != std::begin(c) );
REQUIRE_FALSE( it == std::begin(c) );
}
TEST_CASE("combinations: size too large gives no results", "[combinations]") {
std::string s{"ABCD"};
auto c = combinations(s, 5);
REQUIRE( std::begin(c) == std::end(c) );
}
TEST_CASE("combinations: size 0 gives nothing", "[combinations]") {
std::string s{"ABCD"};
auto c = combinations(s, 0);
REQUIRE( std::begin(c) == std::end(c) );
}
TEST_CASE("combinations: binds to lvalues, moves rvalues", "[combinations]") {
BasicIterable<char> bi{'x', 'y', 'z'};
SECTION("binds to lvalues") {
combinations(bi, 1);
REQUIRE_FALSE( bi.was_moved_from() );
}
SECTION("moves rvalues") {
combinations(std::move(bi), 1);
REQUIRE( bi.was_moved_from() );
}
}
TEST_CASE("combinations: doesn't move or copy elements of iterable",
"[combinations]") {
constexpr SolidInt arr[] = {{6}, {7}, {8}};
for (auto&& i : combinations(arr, 1)) {
(void)i;
}
}
TEST_CASE("combinations: iterator meets requirements", "[combinations]") {
std::string s{"abc"};
auto c = combinations(s, 1);
REQUIRE( itertest::IsIterator<decltype(std::begin(c))>::value );
auto&& row = *std::begin(c);
REQUIRE( itertest::IsIterator<decltype(std::begin(row))>::value );
}
<|endoftext|> |
<commit_before>//===-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation of the MC-JIT runtime dynamic linker.
//
//===----------------------------------------------------------------------===//
#include "RuntimeDyldMachO.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "Targets/RuntimeDyldMachOARM.h"
#include "Targets/RuntimeDyldMachOAArch64.h"
#include "Targets/RuntimeDyldMachOI386.h"
#include "Targets/RuntimeDyldMachOX86_64.h"
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "dyld"
namespace {
class LoadedMachOObjectInfo : public RuntimeDyld::LoadedObjectInfo {
public:
LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
unsigned EndIdx)
: RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile &Obj) const override {
return OwningBinary<ObjectFile>();
}
};
};
namespace llvm {
int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
unsigned NumBytes = 1 << RE.Size;
uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
}
RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
const ObjectFile &BaseTObj, const relocation_iterator &RI,
const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID,
const SymbolTableMap &Symbols) {
const MachOObjectFile &Obj =
static_cast<const MachOObjectFile &>(BaseTObj);
MachO::any_relocation_info RelInfo =
Obj.getRelocation(RI->getRawDataRefImpl());
RelocationValueRef Value;
bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
if (IsExternal) {
symbol_iterator Symbol = RI->getSymbol();
StringRef TargetName;
Symbol->getName(TargetName);
SymbolTableMap::const_iterator SI = Symbols.find(TargetName.data());
if (SI != Symbols.end()) {
Value.SectionID = SI->second.first;
Value.Offset = SI->second.second + RE.Addend;
} else {
SI = GlobalSymbolTable.find(TargetName.data());
if (SI != GlobalSymbolTable.end()) {
Value.SectionID = SI->second.first;
Value.Offset = SI->second.second + RE.Addend;
} else {
Value.SymbolName = TargetName.data();
Value.Offset = RE.Addend;
}
}
} else {
SectionRef Sec = Obj.getRelocationSection(RelInfo);
bool IsCode = Sec.isText();
Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
uint64_t Addr = Sec.getAddress();
Value.Offset = RE.Addend - Addr;
}
return Value;
}
void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
const ObjectFile &BaseTObj,
const relocation_iterator &RI,
unsigned OffsetToNextPC) {
const MachOObjectFile &Obj =
static_cast<const MachOObjectFile &>(BaseTObj);
MachO::any_relocation_info RelInfo =
Obj.getRelocation(RI->getRawDataRefImpl());
bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
if (IsPCRel) {
uint64_t RelocAddr = 0;
RI->getAddress(RelocAddr);
Value.Offset += RelocAddr + OffsetToNextPC;
}
}
void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
uint64_t Value) const {
const SectionEntry &Section = Sections[RE.SectionID];
uint8_t *LocalAddress = Section.Address + RE.Offset;
uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
dbgs() << "resolveRelocation Section: " << RE.SectionID
<< " LocalAddress: " << format("%p", LocalAddress)
<< " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
<< " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
<< " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
<< " Size: " << (1 << RE.Size) << "\n";
}
section_iterator
RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
uint64_t Addr) {
section_iterator SI = Obj.section_begin();
section_iterator SE = Obj.section_end();
for (; SI != SE; ++SI) {
uint64_t SAddr = SI->getAddress();
uint64_t SSize = SI->getSize();
if ((Addr >= SAddr) && (Addr < SAddr + SSize))
return SI;
}
return SE;
}
// Populate __pointers section.
void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
const MachOObjectFile &Obj,
const SectionRef &PTSection,
unsigned PTSectionID) {
assert(!Obj.is64Bit() &&
"Pointer table section not supported in 64-bit MachO.");
MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
uint32_t PTSectionSize = Sec32.size;
unsigned FirstIndirectSymbol = Sec32.reserved1;
const unsigned PTEntrySize = 4;
unsigned NumPTEntries = PTSectionSize / PTEntrySize;
unsigned PTEntryOffset = 0;
assert((PTSectionSize % PTEntrySize) == 0 &&
"Pointers section does not contain a whole number of stubs?");
DEBUG(dbgs() << "Populating pointer table section "
<< Sections[PTSectionID].Name
<< ", Section ID " << PTSectionID << ", "
<< NumPTEntries << " entries, " << PTEntrySize
<< " bytes each:\n");
for (unsigned i = 0; i < NumPTEntries; ++i) {
unsigned SymbolIndex =
Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
StringRef IndirectSymbolName;
SI->getName(IndirectSymbolName);
DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
<< ", PT offset: " << PTEntryOffset << "\n");
RelocationEntry RE(PTSectionID, PTEntryOffset,
MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
addRelocationForSymbol(RE, IndirectSymbolName);
PTEntryOffset += PTEntrySize;
}
}
bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
return Obj.isMachO();
}
template <typename Impl>
void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &ObjImg,
ObjSectionToIDMap &SectionMap) {
unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
ObjSectionToIDMap::iterator i, e;
for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
const SectionRef &Section = i->first;
StringRef Name;
Section.getName(Name);
if (Name == "__eh_frame")
EHFrameSID = i->second;
else if (Name == "__text")
TextSID = i->second;
else if (Name == "__gcc_except_tab")
ExceptTabSID = i->second;
else
impl().finalizeSection(ObjImg, i->second, Section);
}
UnregisteredEHFrameSections.push_back(
EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
}
template <typename Impl>
unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
int64_t DeltaForText,
int64_t DeltaForEH) {
typedef typename Impl::TargetPtrT TargetPtrT;
DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
<< ", Delta for EH: " << DeltaForEH << "\n");
uint32_t Length = readBytesUnaligned(P, 4);
P += 4;
unsigned char *Ret = P + Length;
uint32_t Offset = readBytesUnaligned(P, 4);
if (Offset == 0) // is a CIE
return Ret;
P += 4;
TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
TargetPtrT NewLocation = FDELocation - DeltaForText;
writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
P += sizeof(TargetPtrT);
// Skip the FDE address range
P += sizeof(TargetPtrT);
uint8_t Augmentationsize = *P;
P += 1;
if (Augmentationsize != 0) {
TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
TargetPtrT NewLSDA = LSDA - DeltaForEH;
writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
}
return Ret;
}
static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
int64_t ObjDistance = A->ObjAddress - B->ObjAddress;
int64_t MemDistance = A->LoadAddress - B->LoadAddress;
return ObjDistance - MemDistance;
}
template <typename Impl>
void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
if (!MemMgr)
return;
for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
continue;
SectionEntry *Text = &Sections[SectionInfo.TextSID];
SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
SectionEntry *ExceptTab = nullptr;
if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
ExceptTab = &Sections[SectionInfo.ExceptTabSID];
int64_t DeltaForText = computeDelta(Text, EHFrame);
int64_t DeltaForEH = 0;
if (ExceptTab)
DeltaForEH = computeDelta(ExceptTab, EHFrame);
unsigned char *P = EHFrame->Address;
unsigned char *End = P + EHFrame->Size;
do {
P = processFDE(P, DeltaForText, DeltaForEH);
} while (P != End);
MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
EHFrame->Size);
}
UnregisteredEHFrameSections.clear();
}
std::unique_ptr<RuntimeDyldMachO>
RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
switch (Arch) {
default:
llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
break;
case Triple::arm: return make_unique<RuntimeDyldMachOARM>(MM);
case Triple::aarch64: return make_unique<RuntimeDyldMachOAArch64>(MM);
case Triple::x86: return make_unique<RuntimeDyldMachOI386>(MM);
case Triple::x86_64: return make_unique<RuntimeDyldMachOX86_64>(MM);
}
}
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
unsigned SectionStartIdx, SectionEndIdx;
std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
SectionEndIdx);
}
} // end namespace llvm
<commit_msg>Removing a spurious semicolon; NFC<commit_after>//===-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation of the MC-JIT runtime dynamic linker.
//
//===----------------------------------------------------------------------===//
#include "RuntimeDyldMachO.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "Targets/RuntimeDyldMachOARM.h"
#include "Targets/RuntimeDyldMachOAArch64.h"
#include "Targets/RuntimeDyldMachOI386.h"
#include "Targets/RuntimeDyldMachOX86_64.h"
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "dyld"
namespace {
class LoadedMachOObjectInfo : public RuntimeDyld::LoadedObjectInfo {
public:
LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
unsigned EndIdx)
: RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile &Obj) const override {
return OwningBinary<ObjectFile>();
}
};
}
namespace llvm {
int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
unsigned NumBytes = 1 << RE.Size;
uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
}
RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
const ObjectFile &BaseTObj, const relocation_iterator &RI,
const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID,
const SymbolTableMap &Symbols) {
const MachOObjectFile &Obj =
static_cast<const MachOObjectFile &>(BaseTObj);
MachO::any_relocation_info RelInfo =
Obj.getRelocation(RI->getRawDataRefImpl());
RelocationValueRef Value;
bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
if (IsExternal) {
symbol_iterator Symbol = RI->getSymbol();
StringRef TargetName;
Symbol->getName(TargetName);
SymbolTableMap::const_iterator SI = Symbols.find(TargetName.data());
if (SI != Symbols.end()) {
Value.SectionID = SI->second.first;
Value.Offset = SI->second.second + RE.Addend;
} else {
SI = GlobalSymbolTable.find(TargetName.data());
if (SI != GlobalSymbolTable.end()) {
Value.SectionID = SI->second.first;
Value.Offset = SI->second.second + RE.Addend;
} else {
Value.SymbolName = TargetName.data();
Value.Offset = RE.Addend;
}
}
} else {
SectionRef Sec = Obj.getRelocationSection(RelInfo);
bool IsCode = Sec.isText();
Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
uint64_t Addr = Sec.getAddress();
Value.Offset = RE.Addend - Addr;
}
return Value;
}
void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
const ObjectFile &BaseTObj,
const relocation_iterator &RI,
unsigned OffsetToNextPC) {
const MachOObjectFile &Obj =
static_cast<const MachOObjectFile &>(BaseTObj);
MachO::any_relocation_info RelInfo =
Obj.getRelocation(RI->getRawDataRefImpl());
bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
if (IsPCRel) {
uint64_t RelocAddr = 0;
RI->getAddress(RelocAddr);
Value.Offset += RelocAddr + OffsetToNextPC;
}
}
void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
uint64_t Value) const {
const SectionEntry &Section = Sections[RE.SectionID];
uint8_t *LocalAddress = Section.Address + RE.Offset;
uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
dbgs() << "resolveRelocation Section: " << RE.SectionID
<< " LocalAddress: " << format("%p", LocalAddress)
<< " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
<< " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
<< " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
<< " Size: " << (1 << RE.Size) << "\n";
}
section_iterator
RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
uint64_t Addr) {
section_iterator SI = Obj.section_begin();
section_iterator SE = Obj.section_end();
for (; SI != SE; ++SI) {
uint64_t SAddr = SI->getAddress();
uint64_t SSize = SI->getSize();
if ((Addr >= SAddr) && (Addr < SAddr + SSize))
return SI;
}
return SE;
}
// Populate __pointers section.
void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
const MachOObjectFile &Obj,
const SectionRef &PTSection,
unsigned PTSectionID) {
assert(!Obj.is64Bit() &&
"Pointer table section not supported in 64-bit MachO.");
MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
uint32_t PTSectionSize = Sec32.size;
unsigned FirstIndirectSymbol = Sec32.reserved1;
const unsigned PTEntrySize = 4;
unsigned NumPTEntries = PTSectionSize / PTEntrySize;
unsigned PTEntryOffset = 0;
assert((PTSectionSize % PTEntrySize) == 0 &&
"Pointers section does not contain a whole number of stubs?");
DEBUG(dbgs() << "Populating pointer table section "
<< Sections[PTSectionID].Name
<< ", Section ID " << PTSectionID << ", "
<< NumPTEntries << " entries, " << PTEntrySize
<< " bytes each:\n");
for (unsigned i = 0; i < NumPTEntries; ++i) {
unsigned SymbolIndex =
Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
StringRef IndirectSymbolName;
SI->getName(IndirectSymbolName);
DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
<< ", PT offset: " << PTEntryOffset << "\n");
RelocationEntry RE(PTSectionID, PTEntryOffset,
MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
addRelocationForSymbol(RE, IndirectSymbolName);
PTEntryOffset += PTEntrySize;
}
}
bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
return Obj.isMachO();
}
template <typename Impl>
void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &ObjImg,
ObjSectionToIDMap &SectionMap) {
unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
ObjSectionToIDMap::iterator i, e;
for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
const SectionRef &Section = i->first;
StringRef Name;
Section.getName(Name);
if (Name == "__eh_frame")
EHFrameSID = i->second;
else if (Name == "__text")
TextSID = i->second;
else if (Name == "__gcc_except_tab")
ExceptTabSID = i->second;
else
impl().finalizeSection(ObjImg, i->second, Section);
}
UnregisteredEHFrameSections.push_back(
EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
}
template <typename Impl>
unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
int64_t DeltaForText,
int64_t DeltaForEH) {
typedef typename Impl::TargetPtrT TargetPtrT;
DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
<< ", Delta for EH: " << DeltaForEH << "\n");
uint32_t Length = readBytesUnaligned(P, 4);
P += 4;
unsigned char *Ret = P + Length;
uint32_t Offset = readBytesUnaligned(P, 4);
if (Offset == 0) // is a CIE
return Ret;
P += 4;
TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
TargetPtrT NewLocation = FDELocation - DeltaForText;
writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
P += sizeof(TargetPtrT);
// Skip the FDE address range
P += sizeof(TargetPtrT);
uint8_t Augmentationsize = *P;
P += 1;
if (Augmentationsize != 0) {
TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
TargetPtrT NewLSDA = LSDA - DeltaForEH;
writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
}
return Ret;
}
static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
int64_t ObjDistance = A->ObjAddress - B->ObjAddress;
int64_t MemDistance = A->LoadAddress - B->LoadAddress;
return ObjDistance - MemDistance;
}
template <typename Impl>
void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
if (!MemMgr)
return;
for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
continue;
SectionEntry *Text = &Sections[SectionInfo.TextSID];
SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
SectionEntry *ExceptTab = nullptr;
if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
ExceptTab = &Sections[SectionInfo.ExceptTabSID];
int64_t DeltaForText = computeDelta(Text, EHFrame);
int64_t DeltaForEH = 0;
if (ExceptTab)
DeltaForEH = computeDelta(ExceptTab, EHFrame);
unsigned char *P = EHFrame->Address;
unsigned char *End = P + EHFrame->Size;
do {
P = processFDE(P, DeltaForText, DeltaForEH);
} while (P != End);
MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
EHFrame->Size);
}
UnregisteredEHFrameSections.clear();
}
std::unique_ptr<RuntimeDyldMachO>
RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
switch (Arch) {
default:
llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
break;
case Triple::arm: return make_unique<RuntimeDyldMachOARM>(MM);
case Triple::aarch64: return make_unique<RuntimeDyldMachOAArch64>(MM);
case Triple::x86: return make_unique<RuntimeDyldMachOI386>(MM);
case Triple::x86_64: return make_unique<RuntimeDyldMachOX86_64>(MM);
}
}
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
unsigned SectionStartIdx, SectionEndIdx;
std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
SectionEndIdx);
}
} // end namespace llvm
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TestService.cpp
* @author Arkadiy Paronyan arkadiy@ethdev.com
* @date 2015
* Ethereum IDE client.
*/
#include <iostream>
#include "TestService.h"
#include <QtTest/QSignalSpy>
#include <QElapsedTimer>
#include <QQuickItem>
#include <QQuickWindow>
#include <QtTest/QTest>
#include <QtTest/qtestkeyboard.h>
namespace dev
{
namespace mix
{
enum MouseAction { MousePress, MouseRelease, MouseClick, MouseDoubleClick, MouseMove };
static void mouseEvent(MouseAction _action, QWindow* _window, QObject* _item, Qt::MouseButton _button, Qt::KeyboardModifiers _stateKey, QPointF _pos, int _delay = -1)
{
if (_delay == -1 || _delay < 30)
_delay = 30;
if (_delay > 0)
QTest::qWait(_delay);
if (_action == MouseClick)
{
mouseEvent(MousePress, _window, _item, _button, _stateKey, _pos);
mouseEvent(MouseRelease, _window, _item, _button, _stateKey, _pos);
return;
}
QPoint pos = _pos.toPoint();
QQuickItem* sgitem = qobject_cast<QQuickItem*>(_item);
if (sgitem)
pos = sgitem->mapToScene(_pos).toPoint();
_stateKey &= static_cast<unsigned int>(Qt::KeyboardModifierMask);
QMouseEvent me(QEvent::User, QPoint(), Qt::LeftButton, _button, _stateKey);
switch (_action)
{
case MousePress:
me = QMouseEvent(QEvent::MouseButtonPress, pos, _window->mapToGlobal(pos), _button, _button, _stateKey);
break;
case MouseRelease:
me = QMouseEvent(QEvent::MouseButtonRelease, pos, _window->mapToGlobal(pos), _button, 0, _stateKey);
break;
case MouseDoubleClick:
me = QMouseEvent(QEvent::MouseButtonDblClick, pos, _window->mapToGlobal(pos), _button, _button, _stateKey);
break;
case MouseMove:
// with move event the _button is NoButton, but 'buttons' holds the currently pressed buttons
me = QMouseEvent(QEvent::MouseMove, pos, _window->mapToGlobal(pos), Qt::NoButton, _button, _stateKey);
break;
default:
break;
}
QSpontaneKeyEvent::setSpontaneous(&me);
if (!qApp->notify(_window, &me))
{
static const char* mouseActionNames[] = { "MousePress", "MouseRelease", "MouseClick", "MouseDoubleClick", "MouseMove" };
QString warning = QString::fromLatin1("Mouse event \"%1\" not accepted by receiving window");
QWARN(warning.arg(QString::fromLatin1(mouseActionNames[static_cast<int>(_action)])).toLatin1().data());
}
}
bool TestService::waitForSignal(QObject* _item, QString _signalName, int _timeout)
{
QSignalSpy spy(_item, ("2" + _signalName.toStdString()).c_str());
QMetaObject const* mo = _item->metaObject();
QStringList methods;
for (int i = mo->methodOffset(); i < mo->methodCount(); ++i)
if (mo->method(i).methodType() == QMetaMethod::Signal)
methods << QString::fromLatin1(mo->method(i).methodSignature());
QElapsedTimer timer;
timer.start();
while (!spy.size())
{
int remaining = _timeout - int(timer.elapsed());
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
QTest::qSleep(10);
}
return spy.size();
}
bool TestService::waitForRendering(QObject* _item, int timeout)
{
QWindow* window = eventWindow(_item);
return waitForSignal(window, "frameSwapped()", timeout);
}
bool TestService::keyPress(QObject* _item, int _key, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyPress(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyRelease(QObject* _item, int _key, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyRelease(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyClick(QObject* _item, int _key, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyClick(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyPressChar(QObject* _item, QString const& _character, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyPress(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyReleaseChar(QObject* _item, QString const& _character, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyRelease(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyClickChar(QObject* _item, QString const& _character, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyClick(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::mouseClick(QObject* _item, qreal _x, qreal _y, int _button, int _modifiers, int _delay)
{
QWindow* window = qobject_cast<QWindow*>(_item);
QMetaObject const* mo = _item->metaObject();
if (!window)
window = eventWindow(_item);
mouseEvent(MouseClick, window, _item, Qt::MouseButton(_button), Qt::KeyboardModifiers(_modifiers), QPointF(_x, _y), _delay);
return true;
}
void TestService::setTargetWindow(QObject* _window)
{
QQuickWindow* window = qobject_cast<QQuickWindow*>(_window);
if (window)
m_targetWindow = window;
window->requestActivate();
}
QWindow* TestService::eventWindow(QObject* _item)
{
QQuickItem* item = qobject_cast<QQuickItem*>(_item);
if (item && item->window())
return item->window();
QWindow* window = qobject_cast<QQuickWindow*>(_item);
if (!window && _item->parent())
window = eventWindow(_item->parent());
if (!window)
window = qobject_cast<QQuickWindow*>(m_targetWindow);
if (window)
{
window->requestActivate();
std::cout << window->title().toStdString();
return window;
}
item = qobject_cast<QQuickItem*>(m_targetWindow);
if (item)
return item->window();
return 0;
}
}
}
<commit_msg>removed obsolete line<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TestService.cpp
* @author Arkadiy Paronyan arkadiy@ethdev.com
* @date 2015
* Ethereum IDE client.
*/
#include <iostream>
#include "TestService.h"
#include <QtTest/QSignalSpy>
#include <QElapsedTimer>
#include <QQuickItem>
#include <QQuickWindow>
#include <QtTest/QTest>
#include <QtTest/qtestkeyboard.h>
namespace dev
{
namespace mix
{
enum MouseAction { MousePress, MouseRelease, MouseClick, MouseDoubleClick, MouseMove };
static void mouseEvent(MouseAction _action, QWindow* _window, QObject* _item, Qt::MouseButton _button, Qt::KeyboardModifiers _stateKey, QPointF _pos, int _delay = -1)
{
if (_delay == -1 || _delay < 30)
_delay = 30;
if (_delay > 0)
QTest::qWait(_delay);
if (_action == MouseClick)
{
mouseEvent(MousePress, _window, _item, _button, _stateKey, _pos);
mouseEvent(MouseRelease, _window, _item, _button, _stateKey, _pos);
return;
}
QPoint pos = _pos.toPoint();
QQuickItem* sgitem = qobject_cast<QQuickItem*>(_item);
if (sgitem)
pos = sgitem->mapToScene(_pos).toPoint();
_stateKey &= static_cast<unsigned int>(Qt::KeyboardModifierMask);
QMouseEvent me(QEvent::User, QPoint(), Qt::LeftButton, _button, _stateKey);
switch (_action)
{
case MousePress:
me = QMouseEvent(QEvent::MouseButtonPress, pos, _window->mapToGlobal(pos), _button, _button, _stateKey);
break;
case MouseRelease:
me = QMouseEvent(QEvent::MouseButtonRelease, pos, _window->mapToGlobal(pos), _button, 0, _stateKey);
break;
case MouseDoubleClick:
me = QMouseEvent(QEvent::MouseButtonDblClick, pos, _window->mapToGlobal(pos), _button, _button, _stateKey);
break;
case MouseMove:
// with move event the _button is NoButton, but 'buttons' holds the currently pressed buttons
me = QMouseEvent(QEvent::MouseMove, pos, _window->mapToGlobal(pos), Qt::NoButton, _button, _stateKey);
break;
default:
break;
}
QSpontaneKeyEvent::setSpontaneous(&me);
if (!qApp->notify(_window, &me))
{
static const char* mouseActionNames[] = { "MousePress", "MouseRelease", "MouseClick", "MouseDoubleClick", "MouseMove" };
QString warning = QString::fromLatin1("Mouse event \"%1\" not accepted by receiving window");
QWARN(warning.arg(QString::fromLatin1(mouseActionNames[static_cast<int>(_action)])).toLatin1().data());
}
}
bool TestService::waitForSignal(QObject* _item, QString _signalName, int _timeout)
{
QSignalSpy spy(_item, ("2" + _signalName.toStdString()).c_str());
QMetaObject const* mo = _item->metaObject();
QStringList methods;
for (int i = mo->methodOffset(); i < mo->methodCount(); ++i)
if (mo->method(i).methodType() == QMetaMethod::Signal)
methods << QString::fromLatin1(mo->method(i).methodSignature());
QElapsedTimer timer;
timer.start();
while (!spy.size())
{
int remaining = _timeout - int(timer.elapsed());
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
QTest::qSleep(10);
}
return spy.size();
}
bool TestService::waitForRendering(QObject* _item, int timeout)
{
QWindow* window = eventWindow(_item);
return waitForSignal(window, "frameSwapped()", timeout);
}
bool TestService::keyPress(QObject* _item, int _key, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyPress(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyRelease(QObject* _item, int _key, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyRelease(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyClick(QObject* _item, int _key, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyClick(window, Qt::Key(_key), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyPressChar(QObject* _item, QString const& _character, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyPress(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyReleaseChar(QObject* _item, QString const& _character, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyRelease(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::keyClickChar(QObject* _item, QString const& _character, int _modifiers, int _delay)
{
QWindow* window = eventWindow(_item);
QTest::keyClick(window, _character[0].toLatin1(), Qt::KeyboardModifiers(_modifiers), _delay);
return true;
}
bool TestService::mouseClick(QObject* _item, qreal _x, qreal _y, int _button, int _modifiers, int _delay)
{
QWindow* window = qobject_cast<QWindow*>(_item);
if (!window)
window = eventWindow(_item);
mouseEvent(MouseClick, window, _item, Qt::MouseButton(_button), Qt::KeyboardModifiers(_modifiers), QPointF(_x, _y), _delay);
return true;
}
void TestService::setTargetWindow(QObject* _window)
{
QQuickWindow* window = qobject_cast<QQuickWindow*>(_window);
if (window)
m_targetWindow = window;
window->requestActivate();
}
QWindow* TestService::eventWindow(QObject* _item)
{
QQuickItem* item = qobject_cast<QQuickItem*>(_item);
if (item && item->window())
return item->window();
QWindow* window = qobject_cast<QQuickWindow*>(_item);
if (!window && _item->parent())
window = eventWindow(_item->parent());
if (!window)
window = qobject_cast<QQuickWindow*>(m_targetWindow);
if (window)
{
window->requestActivate();
std::cout << window->title().toStdString();
return window;
}
item = qobject_cast<QQuickItem*>(m_targetWindow);
if (item)
return item->window();
return 0;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google 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 "ipmi.hpp"
#include "cable.hpp"
#include "commands.hpp"
#include "cpld.hpp"
#include "entity_name.hpp"
#include "eth.hpp"
#include "handler_impl.hpp"
#include "pcie_i2c.hpp"
#include "psu.hpp"
#include <ipmid/api.h>
#include <cstdint>
#include <cstdio>
namespace google
{
namespace ipmi
{
ipmi_ret_t handleSysCommand(HandlerInterface* handler, ipmi_cmd_t cmd,
const uint8_t* reqBuf, uint8_t* replyCmdBuf,
size_t* dataLen)
{
// Verify it's at least as long as it needs to be for a subcommand.
if ((*dataLen) < 1)
{
std::fprintf(stderr, "*dataLen too small: %u\n",
static_cast<uint32_t>(*dataLen));
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
switch (reqBuf[0])
{
case SysCableCheck:
return cableCheck(reqBuf, replyCmdBuf, dataLen, handler);
case SysCpldVersion:
return cpldVersion(reqBuf, replyCmdBuf, dataLen, handler);
case SysGetEthDevice:
return getEthDevice(reqBuf, replyCmdBuf, dataLen, handler);
case SysPsuHardReset:
return psuHardReset(reqBuf, replyCmdBuf, dataLen, handler);
case SysPcieSlotCount:
return pcieSlotCount(reqBuf, replyCmdBuf, dataLen, handler);
case SysPcieSlotI2cBusMapping:
return pcieSlotI2cBusMapping(reqBuf, replyCmdBuf, dataLen, handler);
case SysEntityName:
return getEntityName(reqBuf, replyCmdBuf, dataLen, handler);
default:
std::fprintf(stderr, "Invalid subcommand: 0x%x\n", reqBuf[0]);
return IPMI_CC_INVALID;
}
}
} // namespace ipmi
} // namespace google
<commit_msg>drop unused header: handler_ipml<commit_after>/*
* Copyright 2018 Google 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 "ipmi.hpp"
#include "cable.hpp"
#include "commands.hpp"
#include "cpld.hpp"
#include "entity_name.hpp"
#include "eth.hpp"
#include "handler.hpp"
#include "pcie_i2c.hpp"
#include "psu.hpp"
#include <ipmid/api.h>
#include <cstdint>
#include <cstdio>
namespace google
{
namespace ipmi
{
ipmi_ret_t handleSysCommand(HandlerInterface* handler, ipmi_cmd_t cmd,
const uint8_t* reqBuf, uint8_t* replyCmdBuf,
size_t* dataLen)
{
// Verify it's at least as long as it needs to be for a subcommand.
if ((*dataLen) < 1)
{
std::fprintf(stderr, "*dataLen too small: %u\n",
static_cast<uint32_t>(*dataLen));
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
switch (reqBuf[0])
{
case SysCableCheck:
return cableCheck(reqBuf, replyCmdBuf, dataLen, handler);
case SysCpldVersion:
return cpldVersion(reqBuf, replyCmdBuf, dataLen, handler);
case SysGetEthDevice:
return getEthDevice(reqBuf, replyCmdBuf, dataLen, handler);
case SysPsuHardReset:
return psuHardReset(reqBuf, replyCmdBuf, dataLen, handler);
case SysPcieSlotCount:
return pcieSlotCount(reqBuf, replyCmdBuf, dataLen, handler);
case SysPcieSlotI2cBusMapping:
return pcieSlotI2cBusMapping(reqBuf, replyCmdBuf, dataLen, handler);
case SysEntityName:
return getEntityName(reqBuf, replyCmdBuf, dataLen, handler);
default:
std::fprintf(stderr, "Invalid subcommand: 0x%x\n", reqBuf[0]);
return IPMI_CC_INVALID;
}
}
} // namespace ipmi
} // namespace google
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include <queso/asserts.h>
#include <queso/GslVector.h>
#include <queso/GslMatrix.h>
#include <queso/VectorSet.h>
#include <queso/VectorSpace.h>
#include <queso/BoxSubset.h>
#include <queso/ScalarFunction.h>
#include <queso/GslOptimizer.h>
#include <queso/OptimizerMonitor.h>
template <class V, class M>
class ObjectiveFunction : public QUESO::BaseScalarFunction<V, M> {
public:
ObjectiveFunction(const char * prefix,
const QUESO::VectorSet<V, M> & domainSet)
: QUESO::BaseScalarFunction<V, M>(prefix, domainSet) {
// Do nothing
}
virtual double actualValue(const V & domainVector, const V * domainDirection,
V * gradVector, M * hessianMatrix, V * hessianEffect) const {
return std::exp(this->lnValue(domainVector, domainDirection,
gradVector, hessianMatrix, hessianEffect));
}
virtual double lnValue(const V & domainVector, const V * domainDirection,
V * gradVector, M * hessianMatrix, V * hessianEffect) const {
// Need to check if NULL because QUESO will somtimes call this with a
// NULL pointer
if (gradVector != NULL) {
(*gradVector)[0] = -2.0 * (domainVector[0]-1);
(*gradVector)[1] = -2.0 * (domainVector[1]-2);
(*gradVector)[2] = -2.0 * (domainVector[2]-3);
}
// Mean = (1,2)
return -( (domainVector[0]-1)*(domainVector[0]-1) +
(domainVector[1]-2)*(domainVector[1]-2) +
(domainVector[2]-3)*(domainVector[2]-3) );
}
};
int main(int argc, char ** argv) {
MPI_Init(&argc, &argv);
QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", NULL);
QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
"space_", 3, NULL);
QUESO::GslVector minBound(paramSpace.zeroVector());
minBound[0] = -10.0;
minBound[1] = -10.0;
minBound[2] = -10.0;
QUESO::GslVector maxBound(paramSpace.zeroVector());
maxBound[0] = 10.0;
maxBound[1] = 10.0;
maxBound[2] = 10.0;
QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> domain("", paramSpace,
minBound, maxBound);
ObjectiveFunction<QUESO::GslVector, QUESO::GslMatrix> objectiveFunction(
"", domain);
QUESO::GslVector initialPoint(paramSpace.zeroVector());
initialPoint[0] = 9.0;
initialPoint[1] = -9.0;
initialPoint[1] = -1.0;
QUESO::GslOptimizer optimizer(objectiveFunction);
double tol = 1.0e-10;
optimizer.setTolerance(tol);
optimizer.set_solver_type(QUESO::GslOptimizer::STEEPEST_DECENT);
QUESO::OptimizerMonitor monitor;
monitor.set_display_output(true,true);
std::cout << "Solving with Steepest Decent" << std::endl;
optimizer.minimize(&monitor);
if (std::abs((*minimizer)[0] - 1.0) > tol) {
std::cerr << "GslOptimize failed. Found minimizer at: " << (*minimizer)[0]
<< std::endl;
std::cerr << "Actual minimizer is 1.0" << std::endl;
queso_error();
}
optimizer.set_solver_type(QUESO::GslOptimizer::NELDER_MEAD2);
monitor.reset();
monitor.set_display_output(true,true);
std::cout << std::endl << "Solving with Nelder Mead" << std::endl;
optimizer.minimize(&monitor);
return 0;
}
<commit_msg>Print to screen in test using print method<commit_after>#include <iostream>
#include <cmath>
#include <queso/asserts.h>
#include <queso/GslVector.h>
#include <queso/GslMatrix.h>
#include <queso/VectorSet.h>
#include <queso/VectorSpace.h>
#include <queso/BoxSubset.h>
#include <queso/ScalarFunction.h>
#include <queso/GslOptimizer.h>
#include <queso/OptimizerMonitor.h>
template <class V, class M>
class ObjectiveFunction : public QUESO::BaseScalarFunction<V, M> {
public:
ObjectiveFunction(const char * prefix,
const QUESO::VectorSet<V, M> & domainSet)
: QUESO::BaseScalarFunction<V, M>(prefix, domainSet) {
// Do nothing
}
virtual double actualValue(const V & domainVector, const V * domainDirection,
V * gradVector, M * hessianMatrix, V * hessianEffect) const {
return std::exp(this->lnValue(domainVector, domainDirection,
gradVector, hessianMatrix, hessianEffect));
}
virtual double lnValue(const V & domainVector, const V * domainDirection,
V * gradVector, M * hessianMatrix, V * hessianEffect) const {
// Need to check if NULL because QUESO will somtimes call this with a
// NULL pointer
if (gradVector != NULL) {
(*gradVector)[0] = -2.0 * (domainVector[0]-1);
(*gradVector)[1] = -2.0 * (domainVector[1]-2);
(*gradVector)[2] = -2.0 * (domainVector[2]-3);
}
// Mean = (1,2)
return -( (domainVector[0]-1)*(domainVector[0]-1) +
(domainVector[1]-2)*(domainVector[1]-2) +
(domainVector[2]-3)*(domainVector[2]-3) );
}
};
int main(int argc, char ** argv) {
MPI_Init(&argc, &argv);
QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", NULL);
QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
"space_", 3, NULL);
QUESO::GslVector minBound(paramSpace.zeroVector());
minBound[0] = -10.0;
minBound[1] = -10.0;
minBound[2] = -10.0;
QUESO::GslVector maxBound(paramSpace.zeroVector());
maxBound[0] = 10.0;
maxBound[1] = 10.0;
maxBound[2] = 10.0;
QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> domain("", paramSpace,
minBound, maxBound);
ObjectiveFunction<QUESO::GslVector, QUESO::GslMatrix> objectiveFunction(
"", domain);
QUESO::GslVector initialPoint(paramSpace.zeroVector());
initialPoint[0] = 9.0;
initialPoint[1] = -9.0;
initialPoint[1] = -1.0;
QUESO::GslOptimizer optimizer(objectiveFunction);
double tol = 1.0e-10;
optimizer.setTolerance(tol);
optimizer.set_solver_type(QUESO::GslOptimizer::STEEPEST_DECENT);
QUESO::OptimizerMonitor monitor;
monitor.set_display_output(true,true);
std::cout << "Solving with Steepest Decent" << std::endl;
optimizer.minimize(&monitor);
if (std::abs((*minimizer)[0] - 1.0) > tol) {
std::cerr << "GslOptimize failed. Found minimizer at: " << (*minimizer)[0]
<< std::endl;
std::cerr << "Actual minimizer is 1.0" << std::endl;
queso_error();
}
optimizer.set_solver_type(QUESO::GslOptimizer::NELDER_MEAD2);
monitor.reset();
monitor.set_display_output(true,true);
std::cout << std::endl << "Solving with Nelder Mead" << std::endl;
optimizer.minimize(&monitor);
monitor.print(std::cout,false);
return 0;
}
<|endoftext|> |
<commit_before>// -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & Newcastle University for the benefit of the
// BioDynaMo collaboration. 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
// I/O related code must be in header file
#include "unit/core/resource_manager_test.h"
#include "core/model_initializer.h"
#include "unit/test_util/io_test.h"
#include "unit/test_util/test_agent.h"
namespace bdm {
TEST(ResourceManagerTest, ForEachAgent) { RunForEachAgentTest(); }
TEST(ResourceManagerTest, ForEachAgentFilter) {
Simulation simulation(TEST_NAME);
auto* rm = simulation.GetResourceManager();
auto ref_uid = AgentUid(simulation.GetAgentUidGenerator()->GetHighestIndex());
rm->AddAgent(new TestAgent(0));
rm->AddAgent(new TestAgent(1));
rm->AddAgent(new TestAgent(2));
rm->AddAgent(new TestAgent(3));
auto evenf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 0;
});
uint64_t counter = 0;
rm->ForEachAgent(
[&](Agent* a) { // NOLINT
counter++;
switch (a->GetUid() - ref_uid) {
case 0:
EXPECT_EQ(0, dynamic_cast<TestAgent*>(a)->GetData());
break;
case 2:
EXPECT_EQ(2, dynamic_cast<TestAgent*>(a)->GetData());
break;
default:
FAIL() << "Must not happen";
}
},
&evenf);
EXPECT_EQ(2u, counter);
auto oddf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 1;
});
counter = 0;
rm->ForEachAgent(
[&](Agent* a) { // NOLINT
counter++;
switch (a->GetUid() - ref_uid) {
case 1:
EXPECT_EQ(1, dynamic_cast<TestAgent*>(a)->GetData());
break;
case 3:
EXPECT_EQ(3, dynamic_cast<TestAgent*>(a)->GetData());
break;
default:
FAIL() << "Must not happen";
}
},
&oddf);
EXPECT_EQ(2u, counter);
}
TEST(ResourceManagerTest, ForEachAgentParallelFilter) {
Simulation simulation(TEST_NAME);
auto* rm = simulation.GetResourceManager();
for (uint64_t i = 0; i < 10000; i++) {
rm->AddAgent(new TestAgent(i));
}
auto evenf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 0;
});
uint64_t counter = 0;
std::set<TestAgent*> called;
auto functor = L2F([&](Agent* a, AgentHandle) {
#pragma omp critical
{
counter++;
called.insert(bdm_static_cast<TestAgent*>(a));
}
});
rm->ForEachAgentParallel(functor, &evenf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 0);
}
counter = 0;
called.clear();
rm->ForEachAgentParallel(10, functor, &evenf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 0);
}
auto oddf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 1;
});
counter = 0;
called.clear();
rm->ForEachAgentParallel(functor, &oddf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 1);
}
counter = 0;
called.clear();
rm->ForEachAgentParallel(10, functor, &oddf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 1);
}
}
TEST(ResourceManagerTest, GetNumAgents) { RunGetNumAgents(); }
TEST(ResourceManagerTest, ForEachAgentParallel) {
RunForEachAgentParallelTest();
}
#ifdef USE_DICT
TEST(ResourceManagerTest, IO) { RunIOTest(); }
#endif // USE_DICT
TEST(ResourceManagerTest, PushBackAndGetAgentTest) {
RunPushBackAndGetAgentTest();
}
TEST(ResourceManagerTest, RemoveAndContains) { RunRemoveAndContainsTest(); }
TEST(ResourceManagerTest, Clear) { RunClearTest(); }
TEST(ResourceManagerTest, SortAndForEachAgentParallel) {
RunSortAndForEachAgentParallel();
}
TEST(ResourceManagerTest, SortAndForEachAgentParallelDynamic) {
RunSortAndForEachAgentParallelDynamic();
}
TEST(ResourceManagerTest, DiffusionGrid) {
Simulation simulation(TEST_NAME);
auto* rm = simulation.GetResourceManager();
int counter = 0;
auto count = [&](DiffusionGrid* dg) { counter++; };
DiffusionGrid* dgrid_1 = new EulerGrid(0, "Kalium", 0.4, 0, 2);
DiffusionGrid* dgrid_2 = new EulerGrid(1, "Natrium", 0.2, 0.1, 1);
DiffusionGrid* dgrid_3 = new EulerGrid(2, "Calcium", 0.5, 0.1, 1);
rm->AddDiffusionGrid(dgrid_1);
rm->AddDiffusionGrid(dgrid_2);
rm->AddDiffusionGrid(dgrid_3);
rm->ForEachDiffusionGrid(count);
ASSERT_EQ(3, counter);
EXPECT_EQ(dgrid_1, rm->GetDiffusionGrid(0));
EXPECT_EQ(dgrid_1, rm->GetDiffusionGrid("Kalium"));
EXPECT_EQ(dgrid_2, rm->GetDiffusionGrid(1));
EXPECT_EQ(dgrid_2, rm->GetDiffusionGrid("Natrium"));
EXPECT_EQ(dgrid_3, rm->GetDiffusionGrid(2));
EXPECT_EQ(dgrid_3, rm->GetDiffusionGrid("Calcium"));
rm->RemoveDiffusionGrid(dgrid_2->GetSubstanceId());
counter = 0;
rm->ForEachDiffusionGrid(count);
ASSERT_EQ(2, counter);
}
TEST(ResourceManagerTest, Defragmentation) {
auto set_param = [](Param* param) {
param->agent_uid_defragmentation_low_watermark = 0.3;
param->agent_uid_defragmentation_high_watermark = 0.8;
};
Simulation simulation(TEST_NAME, set_param);
auto* rm = simulation.GetResourceManager();
auto* agent_uid_generator = simulation.GetAgentUidGenerator();
// we don't know the how big the internal agent uid map is
rm->AddAgent(new TestAgent());
rm->EndOfIteration();
EXPECT_TRUE(agent_uid_generator->IsInDefragmentationMode());
// fill it to the max
uint64_t cnt = 1;
while (agent_uid_generator->IsInDefragmentationMode()) {
rm->AddAgent(new TestAgent());
cnt++;
}
// now we know how many agents are 100%
rm->EndOfIteration();
EXPECT_FALSE(agent_uid_generator->IsInDefragmentationMode());
// remove enough agents to drop below the low watermark
uint64_t remove = std::ceil(cnt * 0.7) + 1;
while (remove != 0) {
remove--;
rm->RemoveAgent(AgentUid(remove));
}
rm->EndOfIteration();
EXPECT_TRUE(agent_uid_generator->IsInDefragmentationMode());
// add enough agents to exceed the high watermark
uint64_t add = std::ceil(cnt * 0.5) + 1;
while (add != 0) {
add--;
rm->AddAgent(new TestAgent());
}
rm->EndOfIteration();
EXPECT_FALSE(agent_uid_generator->IsInDefragmentationMode());
auto uid = agent_uid_generator->GenerateUid();
EXPECT_GE(uid.GetIndex(), cnt);
EXPECT_EQ(0u, uid.GetReused());
}
// -----------------------------------------------------------------------------
struct DeleteFunctor : public Functor<void, Agent*, AgentHandle> {
std::vector<bool>& remove;
DeleteFunctor(std::vector<bool>& remove) : remove(remove) {}
virtual ~DeleteFunctor() {}
void operator()(Agent* agent, AgentHandle ah) override {
if (remove[agent->GetUid().GetIndex()]) {
agent->RemoveFromSimulation();
}
}
};
// -----------------------------------------------------------------------------
void RunParallelAgentRemovalTest(
uint64_t agents_per_dim,
const std::function<bool(uint64_t index)>& remove_functor) {
Simulation simulation("RunForEachAgentTest_ParallelAgentRemoval");
auto construct = [](const Double3& pos) {
auto* agent = new TestAgent(pos);
agent->SetDiameter(10);
return agent;
};
ModelInitializer::Grid3D(agents_per_dim, 20, construct);
auto* rm = simulation.GetResourceManager();
simulation.GetScheduler()->Simulate(1);
std::vector<bool> remove(rm->GetNumAgents());
for (uint64_t i = 0; i < remove.size(); ++i) {
remove[i] = remove_functor(i);
}
DeleteFunctor f(remove);
rm->ForEachAgentParallel(f);
simulation.GetScheduler()->Simulate(1);
for (uint64_t i = 0; i < remove.size(); ++i) {
auto uid = AgentUid(i);
EXPECT_EQ(!remove[i], rm->ContainsAgent(uid));
if (!remove[i]) {
// access data member to check that remaining agents
// are still valid and haven't been deleted erroneously.
EXPECT_EQ(uid, rm->GetAgent(uid)->GetUid());
}
}
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale) {
RunParallelAgentRemovalTest(
2, [](uint64_t i) { return i == 0 || i == 3 || i == 6 || i == 7; });
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale_All) {
RunParallelAgentRemovalTest(2, [](uint64_t i) { return true; });
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale_None) {
RunParallelAgentRemovalTest(2, [](uint64_t i) { return false; });
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale1) {
RunParallelAgentRemovalTest(3, [](uint64_t i) {
return i == 0 || i == 3 || (i >= 6 && i <= 11) || i == 13 || i == 14 ||
(i >= 23 && i <= 26);
});
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_LargeScale25) {
RunParallelAgentRemovalTest(32, [](uint64_t i) {
return Simulation::GetActive()->GetRandom()->Uniform() > 0.25;
});
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_LargeScale50) {
RunParallelAgentRemovalTest(32, [](uint64_t i) {
return Simulation::GetActive()->GetRandom()->Uniform() > 0.5;
});
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_LargeScale75) {
RunParallelAgentRemovalTest(32, [](uint64_t i) {
return Simulation::GetActive()->GetRandom()->Uniform() > 0.75;
});
}
} // namespace bdm
<commit_msg>Disable ForEachAgentParallelFilter on M1 (clang13) (#207)<commit_after>// -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & Newcastle University for the benefit of the
// BioDynaMo collaboration. 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
// I/O related code must be in header file
#include "unit/core/resource_manager_test.h"
#include "core/model_initializer.h"
#include "unit/test_util/io_test.h"
#include "unit/test_util/test_agent.h"
namespace bdm {
TEST(ResourceManagerTest, ForEachAgent) { RunForEachAgentTest(); }
TEST(ResourceManagerTest, ForEachAgentFilter) {
Simulation simulation(TEST_NAME);
auto* rm = simulation.GetResourceManager();
auto ref_uid = AgentUid(simulation.GetAgentUidGenerator()->GetHighestIndex());
rm->AddAgent(new TestAgent(0));
rm->AddAgent(new TestAgent(1));
rm->AddAgent(new TestAgent(2));
rm->AddAgent(new TestAgent(3));
auto evenf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 0;
});
uint64_t counter = 0;
rm->ForEachAgent(
[&](Agent* a) { // NOLINT
counter++;
switch (a->GetUid() - ref_uid) {
case 0:
EXPECT_EQ(0, dynamic_cast<TestAgent*>(a)->GetData());
break;
case 2:
EXPECT_EQ(2, dynamic_cast<TestAgent*>(a)->GetData());
break;
default:
FAIL() << "Must not happen";
}
},
&evenf);
EXPECT_EQ(2u, counter);
auto oddf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 1;
});
counter = 0;
rm->ForEachAgent(
[&](Agent* a) { // NOLINT
counter++;
switch (a->GetUid() - ref_uid) {
case 1:
EXPECT_EQ(1, dynamic_cast<TestAgent*>(a)->GetData());
break;
case 3:
EXPECT_EQ(3, dynamic_cast<TestAgent*>(a)->GetData());
break;
default:
FAIL() << "Must not happen";
}
},
&oddf);
EXPECT_EQ(2u, counter);
}
// This test currently produces a segmentation fault with clang 13 on macOS 11.6
// during the build and is therefore disabled for the specific combination of
// OS, architecture, and compiler version. Submitted bug to Apple on 2021-09-22.
// The issue arises with the `#pragma omp critical` statement.
// Todo(tobias): revisit this bug asap.
#if !(defined(__APPLE__) && defined(__arm64__) && __clang_major__ == 13)
TEST(ResourceManagerTest, ForEachAgentParallelFilter) {
Simulation simulation(TEST_NAME);
auto* rm = simulation.GetResourceManager();
for (uint64_t i = 0; i < 10000; i++) {
rm->AddAgent(new TestAgent(i));
}
auto evenf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 0;
});
uint64_t counter = 0;
std::set<TestAgent*> called;
auto functor = L2F([&](Agent* a, AgentHandle) {
#pragma omp critical
{
counter++;
called.insert(bdm_static_cast<TestAgent*>(a));
}
});
rm->ForEachAgentParallel(functor, &evenf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 0);
}
counter = 0;
called.clear();
rm->ForEachAgentParallel(10, functor, &evenf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 0);
}
auto oddf = L2F([](Agent* a) {
return bdm_static_cast<TestAgent*>(a)->GetData() % 2 == 1;
});
counter = 0;
called.clear();
rm->ForEachAgentParallel(functor, &oddf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 1);
}
counter = 0;
called.clear();
rm->ForEachAgentParallel(10, functor, &oddf);
EXPECT_EQ(5000u, counter);
for (auto* a : called) {
EXPECT_TRUE(a->GetData() % 2 == 1);
}
}
#endif // APPLE ARM64 CLANG==13
TEST(ResourceManagerTest, GetNumAgents) { RunGetNumAgents(); }
TEST(ResourceManagerTest, ForEachAgentParallel) {
RunForEachAgentParallelTest();
}
#ifdef USE_DICT
TEST(ResourceManagerTest, IO) { RunIOTest(); }
#endif // USE_DICT
TEST(ResourceManagerTest, PushBackAndGetAgentTest) {
RunPushBackAndGetAgentTest();
}
TEST(ResourceManagerTest, RemoveAndContains) { RunRemoveAndContainsTest(); }
TEST(ResourceManagerTest, Clear) { RunClearTest(); }
TEST(ResourceManagerTest, SortAndForEachAgentParallel) {
RunSortAndForEachAgentParallel();
}
TEST(ResourceManagerTest, SortAndForEachAgentParallelDynamic) {
RunSortAndForEachAgentParallelDynamic();
}
TEST(ResourceManagerTest, DiffusionGrid) {
Simulation simulation(TEST_NAME);
auto* rm = simulation.GetResourceManager();
int counter = 0;
auto count = [&](DiffusionGrid* dg) { counter++; };
DiffusionGrid* dgrid_1 = new EulerGrid(0, "Kalium", 0.4, 0, 2);
DiffusionGrid* dgrid_2 = new EulerGrid(1, "Natrium", 0.2, 0.1, 1);
DiffusionGrid* dgrid_3 = new EulerGrid(2, "Calcium", 0.5, 0.1, 1);
rm->AddDiffusionGrid(dgrid_1);
rm->AddDiffusionGrid(dgrid_2);
rm->AddDiffusionGrid(dgrid_3);
rm->ForEachDiffusionGrid(count);
ASSERT_EQ(3, counter);
EXPECT_EQ(dgrid_1, rm->GetDiffusionGrid(0));
EXPECT_EQ(dgrid_1, rm->GetDiffusionGrid("Kalium"));
EXPECT_EQ(dgrid_2, rm->GetDiffusionGrid(1));
EXPECT_EQ(dgrid_2, rm->GetDiffusionGrid("Natrium"));
EXPECT_EQ(dgrid_3, rm->GetDiffusionGrid(2));
EXPECT_EQ(dgrid_3, rm->GetDiffusionGrid("Calcium"));
rm->RemoveDiffusionGrid(dgrid_2->GetSubstanceId());
counter = 0;
rm->ForEachDiffusionGrid(count);
ASSERT_EQ(2, counter);
}
TEST(ResourceManagerTest, Defragmentation) {
auto set_param = [](Param* param) {
param->agent_uid_defragmentation_low_watermark = 0.3;
param->agent_uid_defragmentation_high_watermark = 0.8;
};
Simulation simulation(TEST_NAME, set_param);
auto* rm = simulation.GetResourceManager();
auto* agent_uid_generator = simulation.GetAgentUidGenerator();
// we don't know the how big the internal agent uid map is
rm->AddAgent(new TestAgent());
rm->EndOfIteration();
EXPECT_TRUE(agent_uid_generator->IsInDefragmentationMode());
// fill it to the max
uint64_t cnt = 1;
while (agent_uid_generator->IsInDefragmentationMode()) {
rm->AddAgent(new TestAgent());
cnt++;
}
// now we know how many agents are 100%
rm->EndOfIteration();
EXPECT_FALSE(agent_uid_generator->IsInDefragmentationMode());
// remove enough agents to drop below the low watermark
uint64_t remove = std::ceil(cnt * 0.7) + 1;
while (remove != 0) {
remove--;
rm->RemoveAgent(AgentUid(remove));
}
rm->EndOfIteration();
EXPECT_TRUE(agent_uid_generator->IsInDefragmentationMode());
// add enough agents to exceed the high watermark
uint64_t add = std::ceil(cnt * 0.5) + 1;
while (add != 0) {
add--;
rm->AddAgent(new TestAgent());
}
rm->EndOfIteration();
EXPECT_FALSE(agent_uid_generator->IsInDefragmentationMode());
auto uid = agent_uid_generator->GenerateUid();
EXPECT_GE(uid.GetIndex(), cnt);
EXPECT_EQ(0u, uid.GetReused());
}
// -----------------------------------------------------------------------------
struct DeleteFunctor : public Functor<void, Agent*, AgentHandle> {
std::vector<bool>& remove;
DeleteFunctor(std::vector<bool>& remove) : remove(remove) {}
virtual ~DeleteFunctor() {}
void operator()(Agent* agent, AgentHandle ah) override {
if (remove[agent->GetUid().GetIndex()]) {
agent->RemoveFromSimulation();
}
}
};
// -----------------------------------------------------------------------------
void RunParallelAgentRemovalTest(
uint64_t agents_per_dim,
const std::function<bool(uint64_t index)>& remove_functor) {
Simulation simulation("RunForEachAgentTest_ParallelAgentRemoval");
auto construct = [](const Double3& pos) {
auto* agent = new TestAgent(pos);
agent->SetDiameter(10);
return agent;
};
ModelInitializer::Grid3D(agents_per_dim, 20, construct);
auto* rm = simulation.GetResourceManager();
simulation.GetScheduler()->Simulate(1);
std::vector<bool> remove(rm->GetNumAgents());
for (uint64_t i = 0; i < remove.size(); ++i) {
remove[i] = remove_functor(i);
}
DeleteFunctor f(remove);
rm->ForEachAgentParallel(f);
simulation.GetScheduler()->Simulate(1);
for (uint64_t i = 0; i < remove.size(); ++i) {
auto uid = AgentUid(i);
EXPECT_EQ(!remove[i], rm->ContainsAgent(uid));
if (!remove[i]) {
// access data member to check that remaining agents
// are still valid and haven't been deleted erroneously.
EXPECT_EQ(uid, rm->GetAgent(uid)->GetUid());
}
}
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale) {
RunParallelAgentRemovalTest(
2, [](uint64_t i) { return i == 0 || i == 3 || i == 6 || i == 7; });
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale_All) {
RunParallelAgentRemovalTest(2, [](uint64_t i) { return true; });
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale_None) {
RunParallelAgentRemovalTest(2, [](uint64_t i) { return false; });
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_SmallScale1) {
RunParallelAgentRemovalTest(3, [](uint64_t i) {
return i == 0 || i == 3 || (i >= 6 && i <= 11) || i == 13 || i == 14 ||
(i >= 23 && i <= 26);
});
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_LargeScale25) {
RunParallelAgentRemovalTest(32, [](uint64_t i) {
return Simulation::GetActive()->GetRandom()->Uniform() > 0.25;
});
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_LargeScale50) {
RunParallelAgentRemovalTest(32, [](uint64_t i) {
return Simulation::GetActive()->GetRandom()->Uniform() > 0.5;
});
}
// -----------------------------------------------------------------------------
TEST(ResourceManagerTest, ParallelAgentRemoval_LargeScale75) {
RunParallelAgentRemovalTest(32, [](uint64_t i) {
return Simulation::GetActive()->GetRandom()->Uniform() > 0.75;
});
}
} // namespace bdm
<|endoftext|> |
<commit_before>//Implementation of a Forest Fire Simulation
#include <cassert>
#include <random>
#include "forest.hpp"
#include "tclap/ValueArg.h"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ForestEvent)
std::vector<std::shared_ptr<warped::Event> > Forest::initializeLP() {
// Register random number generator
//this->registerRNG<std::default_random_engine>(this->rng_);
std::default_random_engine rng;
uniform_int_distribution<int> LPS(0, this->width * this->height);
std::vector<std::shared_ptr<warped::Event> > events;
events.emplace_back(new ForestEvent {lp_name(LPS(rng), IGNITION, 1});
return events;
}
inline std::string Forest::lp_name(const unsigned int lp_index){
return std::string("Forest_") + std::to_string(lp_index);
}
std::vector<std::shared_ptr<warped::Event> > Forest::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
auto received_event = static_cast<const ForestEvent&>(event);
switch (received_event.type_) {
case RADIATION: {
this->state_.heat_content_=this->state_.heat_content_ + recieved_event.heat_content;
// if there is enough heat and the vegtation is unburnt Schedule ignition
if(this->state_.heat_content_ >= this->ignition_threshold && this->state_burn_status == UNBURNT){
unsigned int ignition_time = recieved_event.ts+1;
response_events.emplace_back(new ForestEvent {this->name_, IGNITION, ignition_time });
}
break;
}
case RADIATION_TIMER: {
unsigned int radiation_heat=this->state_.heat_content_ /100 * 5
this->state_.heat_content_ /100 * 95;
// Schedule Radiation events for each of the eight surrounding LPs
/*begin for loop*/
unsigned int radiation_time = received_event.ts_ + 1;
response_events.emplace_back(new ForestEvent { this->name_, RADIATION,
radiation_time });
/*end for loop*/
if(this->state_.heat_content_ <= this->burnout_threshold){
this->state_.burn_status_ = BURNOUT
}
else{
unsigned int radiation_timer = recieved_event.ts + 5;
response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer });
}
break;
}
case IGNITION: {
this->state_.burn_status_=GROWTH;
// Schedule Peak Event
unsigned int peak_time = received_event.ts + ((this->peak_threshold-this->ignition_threshold)/this->heat_rate);
response_events.emplace_back(new ForestEvent {this->name_, PEAK, peak_time });
break;
}
case PEAK: {
this->state_.burn_status_=DECAY;
this->state_.heat_content_=this->state_.heat_content_ + (this->peak_threshold - this->ignition_threshold);
// Schedule first Radiation Timer
unsigned int radiation_timer = recieved_event.ts + 5;
response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer });
break;
}
}
return response_events;
}
std::queue<int> ignition_threshold_vector;
std::queue<int> peak_threshold_vector;
unsigned int width,height;
unsigned char *read_bmp( std::string img_name, unsigned int heat_rate,
unsigned int radiation_percent, unsigned int burnout_threshold){
FILE *fp = fopen(img_name.c_str(), "rb");
if(!fp) throw "Argument Exception";
// Read the 54-byte header
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, fp);
// Extract image height and width from header
width = *(unsigned int *)&info[18];
height = *(unsigned int *)&info[22];
std::cout << "Width : " << width << std::endl;
std::cout << "Height : " << height << std::endl;
unsigned int row_padded = (width*3 + 3) & (~3);
unsigned char *data = new unsigned char[row_padded];
for( unsigned int i = 0; i < height; i++ ) {
fread(data, sizeof(unsigned char), row_padded, fp);
for(unsigned int j = 0; j < width*3; j += 3) {
//std::cout << "B: "<< (int)data[j]
// << " G: " << (int)data[j+1]
// << " R: " << (int)data[j+2]
// << std::endl;
unsigned int index_num = i*j;
//Placeholder equations for threshold calculation
unsigned int ignition_threshold = (int)data[j] + (int)data[j+1] + (int)data[j+2];
unsigned int peak_threshold = ((int)data[j] + (int)data[j+1] + (int)data[j+2]) * 2;
std::string name = Forest::lp_name(index_num)
lps.emplace_back(name, width, height,ignition_threshold, heat_rate,
peak_threshold, burnout_threshold, index_num);
}
}
fclose(fp);
return data;
}
int main(int argc, char *argv[],){
std::string config_filename = "map_hawaii.bmp";
unsigned int heat_rate = 100;
unsigned int radiation_percent = 5;
unsigned int burnout_threshold = 50;
TCLAP::ValueArg<std::string> config_arg("m", "map",
"Forest model vegetation config", false, config_filename, "string");
TCLAP::ValueArg<unsigned int> heat_rate_arg("h", "heat-rate", "Speed of growth of the fire",
false, heat_rate, "unsigned int");
TCLAP::ValueArg<unsigned int> radition_percent_arg("r", "radiation-percent",
"Percent of Heat released every timstamp", false, radiation_percent, "unsigned int");
TCLAP::ValueArg<unsigned int> burnout_threshold_arg("b", "burnout-threshold",
"Amount of heat needed for a cell to burn out", false,
burnout_threshold, "unsigned int");
std::vector<TCLAP::Arg*> args = {&config_arg, &heat_rate_arg,
&radiation_percent_arg, &burnout_threshold_arg};
config_filename = config_arg.getValue();
heat_rate = heat_rate_arg.getValue();
radiation_percent = radiation_percent_arg.getValue();
burnout_threshold = burnout_threshold.getValue();
warped::Simulation forest_sim {"Forest Simulation", argc, argv, args};
std::vector<Forest> lps;
(void) read_bmp(config_filename, heat_rate, radiation_percent, burnout_threshold);
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
forest_sim.simulate(lp_pointers);
return 0;
}
<commit_msg>fixed some names in recieve event<commit_after>//Implementation of a Forest Fire Simulation
#include <cassert>
#include <random>
#include "forest.hpp"
#include "tclap/ValueArg.h"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ForestEvent)
std::vector<std::shared_ptr<warped::Event> > Forest::initializeLP() {
// Register random number generator
//this->registerRNG<std::default_random_engine>(this->rng_);
std::default_random_engine rng;
uniform_int_distribution<int> LPS(0, this->width * this->height);
std::vector<std::shared_ptr<warped::Event> > events;
events.emplace_back(new ForestEvent {lp_name(LPS(rng), IGNITION, 1});
return events;
}
inline std::string Forest::lp_name(const unsigned int lp_index){
return std::string("Forest_") + std::to_string(lp_index);
}
std::vector<std::shared_ptr<warped::Event> > Forest::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
auto received_event = static_cast<const ForestEvent&>(event);
switch (received_event.type_) {
case RADIATION: {
if(this->state_.burn_status_==BURNT_OUT){
break
}
this->state_.heat_content_=this->state_.heat_content_ + recieved_event.heat_content;
// if there is enough heat and the vegtation is unburnt Schedule ignition
if(this->state_.heat_content_ >= this->ignition_threshold && this->state_burn_status == UNBURNT){
unsigned int ignition_time = recieved_event.ts+1;
response_events.emplace_back(new ForestEvent {this->name, IGNITION, ignition_time });
}
break;
}
case RADIATION_TIMER: {
unsigned int radiation_heat=this->state_.heat_content_ /100 * 5
this->state_.heat_content_ /100 * 95;
// Schedule Radiation events for each of the eight surrounding LPs
/*begin for loop*/
unsigned int radiation_time = received_event.ts_ + 1;
response_events.emplace_back(new ForestEvent { name, RADIATION,
radiation_time });
/*end for loop*/
if(this->state_.heat_content_ <= this->burnout_threshold){
this->state_.burn_status_ = BURNT_OUT
}
else{
unsigned int radiation_timer = recieved_event.ts + 5;
response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer });
}
break;
}
case IGNITION: {
this->state_.burn_status_=GROWTH;
// Schedule Peak Event
unsigned int peak_time = received_event.ts + ((this->peak_threshold-this->ignition_threshold)/this->heat_rate);
response_events.emplace_back(new ForestEvent {this->name_, PEAK, peak_time });
break;
}
case PEAK: {
this->state_.burn_status_=DECAY;
this->state_.heat_content_=this->state_.heat_content_ + (this->peak_threshold - this->ignition_threshold);
// Schedule first Radiation Timer
unsigned int radiation_timer = recieved_event.ts + 5;
response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer });
break;
}
}
return response_events;
}
std::queue<int> ignition_threshold_vector;
std::queue<int> peak_threshold_vector;
unsigned int width,height;
unsigned char *read_bmp( std::string img_name, unsigned int heat_rate,
unsigned int radiation_percent, unsigned int burnout_threshold){
FILE *fp = fopen(img_name.c_str(), "rb");
if(!fp) throw "Argument Exception";
// Read the 54-byte header
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, fp);
// Extract image height and width from header
width = *(unsigned int *)&info[18];
height = *(unsigned int *)&info[22];
std::cout << "Width : " << width << std::endl;
std::cout << "Height : " << height << std::endl;
unsigned int row_padded = (width*3 + 3) & (~3);
unsigned char *data = new unsigned char[row_padded];
for( unsigned int i = 0; i < height; i++ ) {
fread(data, sizeof(unsigned char), row_padded, fp);
for(unsigned int j = 0; j < width*3; j += 3) {
//std::cout << "B: "<< (int)data[j]
// << " G: " << (int)data[j+1]
// << " R: " << (int)data[j+2]
// << std::endl;
unsigned int index_num = i*j;
//Placeholder equations for threshold calculation
unsigned int ignition_threshold = (int)data[j] + (int)data[j+1] + (int)data[j+2];
unsigned int peak_threshold = ((int)data[j] + (int)data[j+1] + (int)data[j+2]) * 2;
std::string name = Forest::lp_name(index_num)
lps.emplace_back(name, width, height,ignition_threshold, heat_rate,
peak_threshold, burnout_threshold, index_num);
}
}
fclose(fp);
return data;
}
int main(int argc, char *argv[],){
std::string config_filename = "map_hawaii.bmp";
unsigned int heat_rate = 100;
unsigned int radiation_percent = 5;
unsigned int burnout_threshold = 50;
TCLAP::ValueArg<std::string> config_arg("m", "map",
"Forest model vegetation config", false, config_filename, "string");
TCLAP::ValueArg<unsigned int> heat_rate_arg("h", "heat-rate", "Speed of growth of the fire",
false, heat_rate, "unsigned int");
TCLAP::ValueArg<unsigned int> radition_percent_arg("r", "radiation-percent",
"Percent of Heat released every timstamp", false, radiation_percent, "unsigned int");
TCLAP::ValueArg<unsigned int> burnout_threshold_arg("b", "burnout-threshold",
"Amount of heat needed for a cell to burn out", false,
burnout_threshold, "unsigned int");
std::vector<TCLAP::Arg*> args = {&config_arg, &heat_rate_arg,
&radiation_percent_arg, &burnout_threshold_arg};
config_filename = config_arg.getValue();
heat_rate = heat_rate_arg.getValue();
radiation_percent = radiation_percent_arg.getValue();
burnout_threshold = burnout_threshold.getValue();
warped::Simulation forest_sim {"Forest Simulation", argc, argv, args};
std::vector<Forest> lps;
(void) read_bmp(config_filename, heat_rate, radiation_percent, burnout_threshold);
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
forest_sim.simulate(lp_pointers);
return 0;
}
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_dataframe
/// \notebook -nodraw
/// Showcase registration of callback functions that act on partial results while
/// the event-loop is running using `OnPartialResult` and `OnPartialResultSlot`.
/// This tutorial is not meant to run in batch mode.
///
/// \macro_code
///
/// \date September 2017
/// \author Enrico Guiraud
using namespace ROOT; // RDataFrame lives in here
void df013_InspectAnalysis()
{
ROOT::EnableImplicitMT();
const auto poolSize = ROOT::GetImplicitMTPoolSize();
const auto nSlots = 0 == poolSize ? 1 : poolSize;
// ## Setup a simple RDataFrame
// We start by creating a RDataFrame with a good number of empty events
const auto nEvents = nSlots * 10000ull;
RDataFrame d(nEvents);
// `heavyWork` is a lambda that fakes some interesting computation and just returns a normally distributed double
TRandom r;
auto heavyWork = [&r]() {
for (volatile int i = 0; i < 1000000; ++i)
;
return r.Gaus();
};
// Let's define a column "x" produced by invoking `heavyWork` for each event
// `tdf` stores a modified data-frame that contains "x"
auto tdf = d.Define("x", heavyWork);
// Now we register a histogram-filling action with the RDataFrame.
// `h` can be used just like a pointer to TH1D but it is actually a TResultProxy<TH1D>, a smart object that triggers
// an event-loop to fill the pointee histogram if needed.
auto h = tdf.Histo1D<double>({"browserHisto", "", 100, -2., 2.}, "x");
// ## Use the callback mechanism to draw the histogram on a TBrowser while it is being filled
// So far we have registered a column "x" to a data-frame with `nEvents` events and we registered the filling of a
// histogram with the values of column "x".
// In the following we will register three functions for execution during the event-loop:
// - one is to be executed once just before the loop and adds a partially-filled histogram to a TBrowser
// - the next is executed every 50 events and draws the partial histogram on the TBrowser's TPad
// - another callback is responsible of updating a simple progress bar from multiple threads
// First off we create a TBrowser that contains a "RDFResults" directory
auto *tdfDirectory = new TMemFile("RDFResults", "RECREATE");
auto *browser = new TBrowser("b", tdfDirectory);
// The global pad should now be set to the TBrowser's canvas, let's store its value in a local variable
auto browserPad = gPad;
// A useful feature of `TResultProxy` is its `OnPartialResult` method: it allows us to register a callback that is
// executed once per specified number of events during the event-loop, on "partial" versions of the result objects
// contained in the `TResultProxy`. In this case, the partial result is going to be a histogram filled with an
// increasing number of events.
// Instead of requesting the callback to be executed every N entries, this time we use the special value `kOnce` to
// request that it is executed once right before starting the event-loop.
// The callback is a C++11 lambda that registers the partial result object in `tdfDirectory`.
h.OnPartialResult(h.kOnce, [tdfDirectory](TH1D &h_) { tdfDirectory->Add(&h_); });
// Note that we called `OnPartialResult` with a dot, `.`, since this is a method of `TResultProxy` itself.
// We do not want to call `OnPartialResult` on the pointee histogram!)
// Multiple callbacks can be registered on the same `TResultProxy` (they are executed one after the other in the
// same order as they were registered). We now request that the partial result is drawn and the TBrowser's TPad is
// updated every 50 events.
h.OnPartialResult(50, [&browserPad](TH1D &hist) {
if (!browserPad)
return; // in case root -b was invoked
browserPad->cd();
hist.Draw();
browserPad->Update();
// This call tells ROOT to process all pending GUI events
// It allows users to use the TBrowser as usual while the event-loop is running
gSystem->ProcessEvents();
});
// Finally, we would like to print a progress bar on the terminal to show how the event-loop is progressing.
// To take into account _all_ events we use `OnPartialResultSlot`: when Implicit Multi-Threading is enabled, in fact,
// `OnPartialResult` invokes the callback only in one of the worker threads, and always returns that worker threads'
// partial result. This is useful because it means we don't have to worry about concurrent execution and
// thread-safety of the callbacks if we are happy with just one threads' partial result.
// `OnPartialResultSlot`, on the other hand, invokes the callback in each one of the worker threads, every time a
// thread finishes processing a batch of `everyN` events. This is what we want for the progress bar, but we need to
// take care that two threads will not print to terminal at the same time: we need a std::mutex for synchronization.
std::string progressBar;
std::mutex barMutex; // Only one thread at a time can lock a mutex. Let's use this to avoid concurrent printing.
// Magic numbers that yield good progress bars for nSlots = 1,2,4,8
const auto everyN = nSlots == 8 ? 1000 : 100ull * nSlots;
const auto barWidth = nEvents / everyN;
h.OnPartialResultSlot(everyN, [&barWidth, &progressBar, &barMutex](unsigned int /*slot*/, TH1D & /*partialHist*/) {
std::lock_guard<std::mutex> l(barMutex); // lock_guard locks the mutex at construction, releases it at destruction
progressBar.push_back('#');
// re-print the line with the progress bar
std::cout << "\r[" << std::left << std::setw(barWidth) << progressBar << ']' << std::flush;
});
// ## Running the analysis
// So far we told RDataFrame what we want to happen during the event-loop, but we have not actually run any of those
// actions: the TBrowser is still empty, the progress bar has not been printed even once, and we haven't produced
// a single data-point!
// As usual with RDataFrame, the event-loop is triggered by accessing the contents of a TResultProxy for the first
// time. Let's run!
std::cout << "Analysis running..." << std::endl;
h->Draw(); // the final, complete result will be drawn after the event-loop has completed.
std::cout << "\nDone!" << std::endl;
// Finally, some book-keeping: in the TMemFile that we are using as TBrowser directory, we substitute the partial
// result with a clone of the final result (the "original" final result will be deleted at the end of the macro).
tdfDirectory->Clear();
auto clone = static_cast<TH1D *>(h->Clone());
clone->SetDirectory(nullptr);
tdfDirectory->Add(clone);
if (!browserPad)
return; // in case root -b was invoked
browserPad->cd();
clone->Draw();
}
<commit_msg>[DF] Use auto instead of auto* when it's clear type is a pointer<commit_after>/// \file
/// \ingroup tutorial_dataframe
/// \notebook -nodraw
/// Showcase registration of callback functions that act on partial results while
/// the event-loop is running using `OnPartialResult` and `OnPartialResultSlot`.
/// This tutorial is not meant to run in batch mode.
///
/// \macro_code
///
/// \date September 2017
/// \author Enrico Guiraud
using namespace ROOT; // RDataFrame lives in here
void df013_InspectAnalysis()
{
ROOT::EnableImplicitMT();
const auto poolSize = ROOT::GetImplicitMTPoolSize();
const auto nSlots = 0 == poolSize ? 1 : poolSize;
// ## Setup a simple RDataFrame
// We start by creating a RDataFrame with a good number of empty events
const auto nEvents = nSlots * 10000ull;
RDataFrame d(nEvents);
// `heavyWork` is a lambda that fakes some interesting computation and just returns a normally distributed double
TRandom r;
auto heavyWork = [&r]() {
for (volatile int i = 0; i < 1000000; ++i)
;
return r.Gaus();
};
// Let's define a column "x" produced by invoking `heavyWork` for each event
// `tdf` stores a modified data-frame that contains "x"
auto tdf = d.Define("x", heavyWork);
// Now we register a histogram-filling action with the RDataFrame.
// `h` can be used just like a pointer to TH1D but it is actually a TResultProxy<TH1D>, a smart object that triggers
// an event-loop to fill the pointee histogram if needed.
auto h = tdf.Histo1D<double>({"browserHisto", "", 100, -2., 2.}, "x");
// ## Use the callback mechanism to draw the histogram on a TBrowser while it is being filled
// So far we have registered a column "x" to a data-frame with `nEvents` events and we registered the filling of a
// histogram with the values of column "x".
// In the following we will register three functions for execution during the event-loop:
// - one is to be executed once just before the loop and adds a partially-filled histogram to a TBrowser
// - the next is executed every 50 events and draws the partial histogram on the TBrowser's TPad
// - another callback is responsible of updating a simple progress bar from multiple threads
// First off we create a TBrowser that contains a "RDFResults" directory
auto tdfDirectory = new TMemFile("RDFResults", "RECREATE");
auto browser = new TBrowser("b", tdfDirectory);
// The global pad should now be set to the TBrowser's canvas, let's store its value in a local variable
auto browserPad = gPad;
// A useful feature of `TResultProxy` is its `OnPartialResult` method: it allows us to register a callback that is
// executed once per specified number of events during the event-loop, on "partial" versions of the result objects
// contained in the `TResultProxy`. In this case, the partial result is going to be a histogram filled with an
// increasing number of events.
// Instead of requesting the callback to be executed every N entries, this time we use the special value `kOnce` to
// request that it is executed once right before starting the event-loop.
// The callback is a C++11 lambda that registers the partial result object in `tdfDirectory`.
h.OnPartialResult(h.kOnce, [tdfDirectory](TH1D &h_) { tdfDirectory->Add(&h_); });
// Note that we called `OnPartialResult` with a dot, `.`, since this is a method of `TResultProxy` itself.
// We do not want to call `OnPartialResult` on the pointee histogram!)
// Multiple callbacks can be registered on the same `TResultProxy` (they are executed one after the other in the
// same order as they were registered). We now request that the partial result is drawn and the TBrowser's TPad is
// updated every 50 events.
h.OnPartialResult(50, [&browserPad](TH1D &hist) {
if (!browserPad)
return; // in case root -b was invoked
browserPad->cd();
hist.Draw();
browserPad->Update();
// This call tells ROOT to process all pending GUI events
// It allows users to use the TBrowser as usual while the event-loop is running
gSystem->ProcessEvents();
});
// Finally, we would like to print a progress bar on the terminal to show how the event-loop is progressing.
// To take into account _all_ events we use `OnPartialResultSlot`: when Implicit Multi-Threading is enabled, in fact,
// `OnPartialResult` invokes the callback only in one of the worker threads, and always returns that worker threads'
// partial result. This is useful because it means we don't have to worry about concurrent execution and
// thread-safety of the callbacks if we are happy with just one threads' partial result.
// `OnPartialResultSlot`, on the other hand, invokes the callback in each one of the worker threads, every time a
// thread finishes processing a batch of `everyN` events. This is what we want for the progress bar, but we need to
// take care that two threads will not print to terminal at the same time: we need a std::mutex for synchronization.
std::string progressBar;
std::mutex barMutex; // Only one thread at a time can lock a mutex. Let's use this to avoid concurrent printing.
// Magic numbers that yield good progress bars for nSlots = 1,2,4,8
const auto everyN = nSlots == 8 ? 1000 : 100ull * nSlots;
const auto barWidth = nEvents / everyN;
h.OnPartialResultSlot(everyN, [&barWidth, &progressBar, &barMutex](unsigned int /*slot*/, TH1D & /*partialHist*/) {
std::lock_guard<std::mutex> l(barMutex); // lock_guard locks the mutex at construction, releases it at destruction
progressBar.push_back('#');
// re-print the line with the progress bar
std::cout << "\r[" << std::left << std::setw(barWidth) << progressBar << ']' << std::flush;
});
// ## Running the analysis
// So far we told RDataFrame what we want to happen during the event-loop, but we have not actually run any of those
// actions: the TBrowser is still empty, the progress bar has not been printed even once, and we haven't produced
// a single data-point!
// As usual with RDataFrame, the event-loop is triggered by accessing the contents of a TResultProxy for the first
// time. Let's run!
std::cout << "Analysis running..." << std::endl;
h->Draw(); // the final, complete result will be drawn after the event-loop has completed.
std::cout << "\nDone!" << std::endl;
// Finally, some book-keeping: in the TMemFile that we are using as TBrowser directory, we substitute the partial
// result with a clone of the final result (the "original" final result will be deleted at the end of the macro).
tdfDirectory->Clear();
auto clone = static_cast<TH1D *>(h->Clone());
clone->SetDirectory(nullptr);
tdfDirectory->Add(clone);
if (!browserPad)
return; // in case root -b was invoked
browserPad->cd();
clone->Draw();
}
<|endoftext|> |
<commit_before>//= CheckerDocumentation.cpp - Documentation checker ---------------*- C++ -*-//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This checker lists all the checker callbacks and provides documentation for
// checker writers.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
using namespace clang;
using namespace ento;
// All checkers should be placed into anonymous namespace.
// We place the CheckerDocumentation inside ento namespace to make the
// it visible in doxygen.
namespace ento {
/// This checker documents the callback functions checkers can use to implement
/// the custom handling of the specific events during path exploration as well
/// as reporting bugs. Most of the callbacks are targeted at path-sensitive
/// checking.
///
/// \sa CheckerContext
class CheckerDocumentation : public Checker< check::PreStmt<DeclStmt>,
check::PostStmt<CallExpr>,
check::PreObjCMessage,
check::PostObjCMessage,
check::BranchCondition,
check::Location,
check::Bind,
check::DeadSymbols,
check::EndPath,
check::EndAnalysis,
check::EndOfTranslationUnit,
eval::Call,
eval::Assume,
check::LiveSymbols,
check::RegionChanges,
check::Event<ImplicitNullDerefEvent>,
check::ASTDecl<FunctionDecl> > {
public:
/// \brief Pre-visit the Statement.
///
/// The method will be called before the analyzer core processes the
/// statement. The notification is performed for every explored CFGElement,
/// which does not include the control flow statements such as IfStmt. The
/// callback can be specialized to be called with any subclass of Stmt.
///
/// See checkBranchCondition() callback for performing custom processing of
/// the branching statements.
///
/// check::PreStmt<DeclStmt>
void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {}
/// \brief Post-visit the Statement.
///
/// The method will be called after the analyzer core processes the
/// statement. The notification is performed for every explored CFGElement,
/// which does not include the control flow statements such as IfStmt. The
/// callback can be specialized to be called with any subclass of Stmt.
///
/// check::PostStmt<DeclStmt>
void checkPostStmt(const CallExpr *DS, CheckerContext &C) const;
/// \brief Pre-visit the Objective C messages.
void checkPreObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const {}
/// \brief Post-visit the Objective C messages.
void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const {}
/// \brief Pre-visit of the condition statement of a branch (such as IfStmt).
void checkBranchCondition(const Stmt *Condition, CheckerContext &Ctx) const {}
/// \brief Called on a load from and a store to a location.
///
/// The method will be called each time a location (pointer) value is
/// accessed.
/// \param Loc The value of the location (pointer).
/// \param IsLoad The flag specifying if the location is a store or a load.
/// \param S The load is performed while processing the statement.
///
/// check::Location
void checkLocation(SVal Loc, bool IsLoad, const Stmt *S,
CheckerContext &C) const {}
/// \brief Called on binding of a value to a location.
///
/// \param Loc The value of the location (pointer).
/// \param Val The value which will be stored at the location Loc.
/// \param S The bind is performed while processing the statement S.
///
/// check::Bind
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {}
/// \brief Called whenever a symbol becomes dead.
///
/// This callback should be used by the checkers to aggressively clean
/// up/reduce the checker state, which is important for reducing the overall
/// memory usage. Specifically, if a checker keeps symbol specific information
/// in the sate, it can and should be dropped after the symbol becomes dead.
/// In addition, reporting a bug as soon as the checker becomes dead leads to
/// more precise diagnostics. (For example, one should report that a malloced
/// variable is not freed right after it goes out of scope.)
///
/// \param SR The SymbolReaper object can be queried to determine which
/// symbols are dead.
///
/// check::DeadSymbols
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const {}
/// \brief Called when an end of path is reached in the ExplodedGraph.
///
/// This callback should be used to check if the allocated resources are freed.
///
/// check::EndPath
void checkEndPath(CheckerContext &Ctx) const {}
/// \brief Called after all the paths in the ExplodedGraph reach end of path
/// - the symbolic execution graph is fully explored.
///
/// This callback should be used in cases when a checker needs to have a
/// global view of the information generated on all paths. For example, to
/// compare execution summary/result several paths.
/// See IdempotentOperationChecker for a usage example.
///
/// check::EndAnalysis
void checkEndAnalysis(ExplodedGraph &G,
BugReporter &BR,
ExprEngine &Eng) const {}
/// \brief Called after analysis of a TranslationUnit is complete.
///
/// check::EndOfTranslationUnit
void checkEndOfTranslationUnit(const TranslationUnitDecl *TU,
AnalysisManager &Mgr,
BugReporter &BR) const {}
/// \brief Evaluates function call.
///
/// The analysis core threats all function calls in the same way. However, some
/// functions have special meaning, which should be reflected in the program
/// state. This callback allows a checker to provide domain specific knowledge
/// about the particular functions it knows about.
///
/// \returns true if the call has been successfully evaluated
/// and false otherwise. Note, that only one checker can evaluate a call. If
/// more then one checker claim that they can evaluate the same call the
/// first one wins.
///
/// eval::Call
bool evalCall(const CallExpr *CE, CheckerContext &C) const { return true; }
/// \brief Handles assumptions on symbolic values.
///
/// This method is called when a symbolic expression is assumed to be true or
/// false. For example, the assumptions are performed when evaluating a
/// condition at a branch. The callback allows checkers track the assumptions
/// performed on the symbols of interest and change the state accordingly.
///
/// eval::Assume
ProgramStateRef evalAssume(ProgramStateRef State,
SVal Cond,
bool Assumption) const { return State; }
/// Allows modifying SymbolReaper object. For example, checkers can explicitly
/// register symbols of interest as live. These symbols will not be marked
/// dead and removed.
///
/// check::LiveSymbols
void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SR) const {}
bool wantsRegionChangeUpdate(ProgramStateRef St) const { return true; }
/// check::RegionChanges
/// Allows tracking regions which get invalidated.
/// \param state The current program state.
/// \param invalidated A set of all symbols potentially touched by the change.
/// \param ExplicitRegions The regions explicitly requested for invalidation.
/// For example, in the case of a function call, these would be arguments.
/// \param Regions The transitive closure of accessible regions,
/// i.e. all regions that may have been touched by this change.
/// \param The call expression wrapper if the regions are invalidated by a
/// call, 0 otherwise.
/// Note, in order to be notified, the checker should also implement
/// wantsRegionChangeUpdate callback.
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const StoreManager::InvalidatedSymbols *,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const CallOrObjCMessage *Call) const {
return State;
}
/// check::Event<ImplicitNullDerefEvent>
void checkEvent(ImplicitNullDerefEvent Event) const {}
/// \brief Check every declaration in the AST.
///
/// An AST traversal callback, which should only be used when the checker is
/// not path sensitive. It will be called for every Declaration in the AST and
/// can be specialized to only be called on subclasses of Decl, for example,
/// FunctionDecl.
///
/// check::ASTDecl<FunctionDecl>
void checkASTDecl(const FunctionDecl *D,
AnalysisManager &Mgr,
BugReporter &BR) const {}
};
void CheckerDocumentation::checkPostStmt(const CallExpr *DS,
CheckerContext &C) const {
return;
}
} // end namespace
<commit_msg>Documentation cleanup: * Add \brief to produce a summary in the Doxygen output; * Add missing parameter names to \param commands; * Fix mismatched parameter names for \param commands; * Add a parameter name so that the \param has a target.<commit_after>//= CheckerDocumentation.cpp - Documentation checker ---------------*- C++ -*-//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This checker lists all the checker callbacks and provides documentation for
// checker writers.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
using namespace clang;
using namespace ento;
// All checkers should be placed into anonymous namespace.
// We place the CheckerDocumentation inside ento namespace to make the
// it visible in doxygen.
namespace ento {
/// This checker documents the callback functions checkers can use to implement
/// the custom handling of the specific events during path exploration as well
/// as reporting bugs. Most of the callbacks are targeted at path-sensitive
/// checking.
///
/// \sa CheckerContext
class CheckerDocumentation : public Checker< check::PreStmt<DeclStmt>,
check::PostStmt<CallExpr>,
check::PreObjCMessage,
check::PostObjCMessage,
check::BranchCondition,
check::Location,
check::Bind,
check::DeadSymbols,
check::EndPath,
check::EndAnalysis,
check::EndOfTranslationUnit,
eval::Call,
eval::Assume,
check::LiveSymbols,
check::RegionChanges,
check::Event<ImplicitNullDerefEvent>,
check::ASTDecl<FunctionDecl> > {
public:
/// \brief Pre-visit the Statement.
///
/// The method will be called before the analyzer core processes the
/// statement. The notification is performed for every explored CFGElement,
/// which does not include the control flow statements such as IfStmt. The
/// callback can be specialized to be called with any subclass of Stmt.
///
/// See checkBranchCondition() callback for performing custom processing of
/// the branching statements.
///
/// check::PreStmt<DeclStmt>
void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {}
/// \brief Post-visit the Statement.
///
/// The method will be called after the analyzer core processes the
/// statement. The notification is performed for every explored CFGElement,
/// which does not include the control flow statements such as IfStmt. The
/// callback can be specialized to be called with any subclass of Stmt.
///
/// check::PostStmt<DeclStmt>
void checkPostStmt(const CallExpr *DS, CheckerContext &C) const;
/// \brief Pre-visit the Objective C messages.
void checkPreObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const {}
/// \brief Post-visit the Objective C messages.
void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const {}
/// \brief Pre-visit of the condition statement of a branch (such as IfStmt).
void checkBranchCondition(const Stmt *Condition, CheckerContext &Ctx) const {}
/// \brief Called on a load from and a store to a location.
///
/// The method will be called each time a location (pointer) value is
/// accessed.
/// \param Loc The value of the location (pointer).
/// \param IsLoad The flag specifying if the location is a store or a load.
/// \param S The load is performed while processing the statement.
///
/// check::Location
void checkLocation(SVal Loc, bool IsLoad, const Stmt *S,
CheckerContext &) const {}
/// \brief Called on binding of a value to a location.
///
/// \param Loc The value of the location (pointer).
/// \param Val The value which will be stored at the location Loc.
/// \param S The bind is performed while processing the statement S.
///
/// check::Bind
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &) const {}
/// \brief Called whenever a symbol becomes dead.
///
/// This callback should be used by the checkers to aggressively clean
/// up/reduce the checker state, which is important for reducing the overall
/// memory usage. Specifically, if a checker keeps symbol specific information
/// in the sate, it can and should be dropped after the symbol becomes dead.
/// In addition, reporting a bug as soon as the checker becomes dead leads to
/// more precise diagnostics. (For example, one should report that a malloced
/// variable is not freed right after it goes out of scope.)
///
/// \param SR The SymbolReaper object can be queried to determine which
/// symbols are dead.
///
/// check::DeadSymbols
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const {}
/// \brief Called when an end of path is reached in the ExplodedGraph.
///
/// This callback should be used to check if the allocated resources are freed.
///
/// check::EndPath
void checkEndPath(CheckerContext &Ctx) const {}
/// \brief Called after all the paths in the ExplodedGraph reach end of path
/// - the symbolic execution graph is fully explored.
///
/// This callback should be used in cases when a checker needs to have a
/// global view of the information generated on all paths. For example, to
/// compare execution summary/result several paths.
/// See IdempotentOperationChecker for a usage example.
///
/// check::EndAnalysis
void checkEndAnalysis(ExplodedGraph &G,
BugReporter &BR,
ExprEngine &Eng) const {}
/// \brief Called after analysis of a TranslationUnit is complete.
///
/// check::EndOfTranslationUnit
void checkEndOfTranslationUnit(const TranslationUnitDecl *TU,
AnalysisManager &Mgr,
BugReporter &BR) const {}
/// \brief Evaluates function call.
///
/// The analysis core threats all function calls in the same way. However, some
/// functions have special meaning, which should be reflected in the program
/// state. This callback allows a checker to provide domain specific knowledge
/// about the particular functions it knows about.
///
/// \returns true if the call has been successfully evaluated
/// and false otherwise. Note, that only one checker can evaluate a call. If
/// more then one checker claim that they can evaluate the same call the
/// first one wins.
///
/// eval::Call
bool evalCall(const CallExpr *CE, CheckerContext &C) const { return true; }
/// \brief Handles assumptions on symbolic values.
///
/// This method is called when a symbolic expression is assumed to be true or
/// false. For example, the assumptions are performed when evaluating a
/// condition at a branch. The callback allows checkers track the assumptions
/// performed on the symbols of interest and change the state accordingly.
///
/// eval::Assume
ProgramStateRef evalAssume(ProgramStateRef State,
SVal Cond,
bool Assumption) const { return State; }
/// Allows modifying SymbolReaper object. For example, checkers can explicitly
/// register symbols of interest as live. These symbols will not be marked
/// dead and removed.
///
/// check::LiveSymbols
void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SR) const {}
bool wantsRegionChangeUpdate(ProgramStateRef St) const { return true; }
/// \brief Allows tracking regions which get invalidated.
///
/// \param State The current program state.
/// \param Invalidated A set of all symbols potentially touched by the change.
/// \param ExplicitRegions The regions explicitly requested for invalidation.
/// For example, in the case of a function call, these would be arguments.
/// \param Regions The transitive closure of accessible regions,
/// i.e. all regions that may have been touched by this change.
/// \param Call The call expression wrapper if the regions are invalidated
/// by a call, 0 otherwise.
/// Note, in order to be notified, the checker should also implement the
/// wantsRegionChangeUpdate callback.
///
/// check::RegionChanges
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const StoreManager::InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const CallOrObjCMessage *Call) const {
return State;
}
/// check::Event<ImplicitNullDerefEvent>
void checkEvent(ImplicitNullDerefEvent Event) const {}
/// \brief Check every declaration in the AST.
///
/// An AST traversal callback, which should only be used when the checker is
/// not path sensitive. It will be called for every Declaration in the AST and
/// can be specialized to only be called on subclasses of Decl, for example,
/// FunctionDecl.
///
/// check::ASTDecl<FunctionDecl>
void checkASTDecl(const FunctionDecl *D,
AnalysisManager &Mgr,
BugReporter &BR) const {}
};
void CheckerDocumentation::checkPostStmt(const CallExpr *DS,
CheckerContext &C) const {
return;
}
} // end namespace
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include <experimental/filesystem>
#include <pddlparse/AST.h>
#include <pddlparse/Parse.h>
namespace fs = std::experimental::filesystem;
const pddl::Context::WarningCallback ignoreWarnings = [](const auto &, const auto &){};
const auto pddlInstanceBasePath = fs::path("data") / "pddl-instances";
////////////////////////////////////////////////////////////////////////////////////////////////////
TEST_CASE("[PDDL parser] The official PDDL instances are parsed correctly", "[PDDL parser]")
{
std::cout << std::endl;
pddl::Tokenizer tokenizer;
pddl::Context context(std::move(tokenizer), ignoreWarnings);
SECTION("“either” type in zenotravel domain")
{
const auto domainFile = pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-numeric-hand-coded" / "domain.pddl";
context.tokenizer.read(domainFile);
auto description = pddl::parseDescription(context);
const auto &predicates = description.domain->predicates;
REQUIRE(predicates.size() == 2);
REQUIRE(predicates[0]->name == "at");
REQUIRE(predicates[0]->parameters.size() == 2);
REQUIRE(predicates[0]->parameters[0]->name == "x");
REQUIRE(predicates[0]->parameters[0]->type);
REQUIRE(predicates[0]->parameters[0]->type.value().is<pddl::ast::EitherPointer<pddl::ast::PrimitiveTypePointer>>());
CHECK(predicates[0]->parameters[0]->type.value().get<pddl::ast::EitherPointer<pddl::ast::PrimitiveTypePointer>>()->arguments[0]->declaration->name == "person");
CHECK(predicates[0]->parameters[0]->type.value().get<pddl::ast::EitherPointer<pddl::ast::PrimitiveTypePointer>>()->arguments[1]->declaration->name == "aircraft");
REQUIRE(predicates[0]->parameters[1]->name == "c");
REQUIRE(predicates[0]->parameters[1]->type);
REQUIRE(predicates[0]->parameters[1]->type.value().is<pddl::ast::PrimitiveTypePointer>());
CHECK(predicates[0]->parameters[1]->type.value().get<pddl::ast::PrimitiveTypePointer>()->declaration->name == "city");
}
}
<commit_msg>Minor formatting.<commit_after>#include <catch.hpp>
#include <experimental/filesystem>
#include <pddlparse/AST.h>
#include <pddlparse/Parse.h>
namespace fs = std::experimental::filesystem;
const pddl::Context::WarningCallback ignoreWarnings = [](const auto &, const auto &){};
const auto pddlInstanceBasePath = fs::path("data") / "pddl-instances";
////////////////////////////////////////////////////////////////////////////////////////////////////
TEST_CASE("[PDDL parser] The official PDDL instances are parsed correctly", "[PDDL parser]")
{
pddl::Tokenizer tokenizer;
pddl::Context context(std::move(tokenizer), ignoreWarnings);
SECTION("“either” type in zenotravel domain")
{
const auto domainFile = pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-numeric-hand-coded" / "domain.pddl";
context.tokenizer.read(domainFile);
auto description = pddl::parseDescription(context);
const auto &predicates = description.domain->predicates;
REQUIRE(predicates.size() == 2);
REQUIRE(predicates[0]->name == "at");
REQUIRE(predicates[0]->parameters.size() == 2);
REQUIRE(predicates[0]->parameters[0]->name == "x");
REQUIRE(predicates[0]->parameters[0]->type);
REQUIRE(predicates[0]->parameters[0]->type.value().is<pddl::ast::EitherPointer<pddl::ast::PrimitiveTypePointer>>());
CHECK(predicates[0]->parameters[0]->type.value().get<pddl::ast::EitherPointer<pddl::ast::PrimitiveTypePointer>>()->arguments[0]->declaration->name == "person");
CHECK(predicates[0]->parameters[0]->type.value().get<pddl::ast::EitherPointer<pddl::ast::PrimitiveTypePointer>>()->arguments[1]->declaration->name == "aircraft");
REQUIRE(predicates[0]->parameters[1]->name == "c");
REQUIRE(predicates[0]->parameters[1]->type);
REQUIRE(predicates[0]->parameters[1]->type.value().is<pddl::ast::PrimitiveTypePointer>());
CHECK(predicates[0]->parameters[1]->type.value().get<pddl::ast::PrimitiveTypePointer>()->declaration->name == "city");
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/protocol/config.hpp>
#define GRAPHENE_MIN_UNDO_HISTORY 10
#define GRAPHENE_MAX_UNDO_HISTORY 10000
#define GRAPHENE_MAX_NESTED_OBJECTS (200)
#define GRAPHENE_CURRENT_DB_VERSION "20190503"
#define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4
#define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3
<commit_msg>Bump DB_VERSION<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/protocol/config.hpp>
#define GRAPHENE_MIN_UNDO_HISTORY 10
#define GRAPHENE_MAX_UNDO_HISTORY 10000
#define GRAPHENE_MAX_NESTED_OBJECTS (200)
#define GRAPHENE_CURRENT_DB_VERSION "20190818"
#define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4
#define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3
<|endoftext|> |
<commit_before>/**
* @file perceptron_test.cpp
* @author Udit Saxena
*
* Tests for perceptron.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/perceptron/perceptron.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack;
using namespace arma;
using namespace mlpack::perceptron;
using namespace mlpack::distribution;
BOOST_AUTO_TEST_SUITE(PerceptronTest);
/**
* This test tests whether the perceptron converges for the AND gate classifier.
*/
BOOST_AUTO_TEST_CASE(And)
{
mat trainData;
trainData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Mat<size_t> labels;
labels << 0 << 0 << 1 << 0;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 3), 0);
}
/**
* This test tests whether the perceptron converges for the OR gate classifier.
*/
BOOST_AUTO_TEST_CASE(Or)
{
mat trainData;
trainData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Mat<size_t> labels;
labels << 1 << 1 << 1 << 0;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 3), 0);
}
/**
* This tests the convergence on a set of linearly separable data with 3
* classes.
*/
BOOST_AUTO_TEST_CASE(Random3)
{
mat trainData;
trainData << 0 << 1 << 1 << 4 << 5 << 4 << 1 << 2 << 1 << endr
<< 1 << 0 << 1 << 1 << 1 << 2 << 4 << 5 << 4 << endr;
Mat<size_t> labels;
labels << 0 << 0 << 0 << 1 << 1 << 1 << 2 << 2 << 2;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << 1 << endr
<< 1 << 0 << 1 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
for (size_t i = 0; i < predictedLabels.n_cols; i++)
BOOST_CHECK_EQUAL(predictedLabels(0, i), 0);
}
/**
* This tests the convergence of the perceptron on a dataset which has only TWO
* points which belong to different classes.
*/
BOOST_AUTO_TEST_CASE(TwoPoints)
{
mat trainData;
trainData << 0 << 1 << endr
<< 1 << 0 << endr;
Mat<size_t> labels;
labels << 0 << 1;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << endr
<< 1 << 0 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 1);
}
/**
* This tests the convergence of the perceptron on a dataset which has a
* non-linearly separable dataset.
*/
BOOST_AUTO_TEST_CASE(NonLinearlySeparableDataset)
{
mat trainData;
trainData << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8
<< 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << endr
<< 1 << 1 << 1 << 1 << 1 << 1 << 1 << 1
<< 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << endr;
Mat<size_t> labels;
labels << 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1
<< 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1;
// labels.print("Here too.");
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 3 << 4 << 5 << 6 << endr
<< 3 << 2.3 << 1.7 << 1.5 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 3), 1);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Minor updates<commit_after>/**
* @file perceptron_test.cpp
* @author Udit Saxena
*
* Tests for perceptron.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/perceptron/perceptron.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack;
using namespace arma;
using namespace mlpack::perceptron;
using namespace mlpack::distribution;
BOOST_AUTO_TEST_SUITE(PerceptronTest);
/**
* This test tests whether the perceptron converges for the AND gate classifier.
*/
BOOST_AUTO_TEST_CASE(And)
{
mat trainData;
trainData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Mat<size_t> labels;
labels << 0 << 0 << 1 << 0;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 3), 0);
}
/**
* This test tests whether the perceptron converges for the OR gate classifier.
*/
BOOST_AUTO_TEST_CASE(Or)
{
mat trainData;
trainData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Mat<size_t> labels;
labels << 1 << 1 << 1 << 0;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << 1 << 0 << endr
<< 1 << 0 << 1 << 0 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 3), 0);
}
/**
* This tests the convergence on a set of linearly separable data with 3
* classes.
*/
BOOST_AUTO_TEST_CASE(Random3)
{
mat trainData;
trainData << 0 << 1 << 1 << 4 << 5 << 4 << 1 << 2 << 1 << endr
<< 1 << 0 << 1 << 1 << 1 << 2 << 4 << 5 << 4 << endr;
Mat<size_t> labels;
labels << 0 << 0 << 0 << 1 << 1 << 1 << 2 << 2 << 2;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << 1 << endr
<< 1 << 0 << 1 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
for (size_t i = 0; i < predictedLabels.n_cols; i++)
BOOST_CHECK_EQUAL(predictedLabels(0, i), 0);
}
/**
* This tests the convergence of the perceptron on a dataset which has only TWO
* points which belong to different classes.
*/
BOOST_AUTO_TEST_CASE(TwoPoints)
{
mat trainData;
trainData << 0 << 1 << endr
<< 1 << 0 << endr;
Mat<size_t> labels;
labels << 0 << 1;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 0 << 1 << endr
<< 1 << 0 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 1);
}
/**
* This tests the convergence of the perceptron on a dataset which has a
* non-linearly separable dataset.
*/
BOOST_AUTO_TEST_CASE(NonLinearlySeparableDataset)
{
mat trainData;
trainData << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8
<< 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << endr
<< 1 << 1 << 1 << 1 << 1 << 1 << 1 << 1
<< 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << endr;
Mat<size_t> labels;
labels << 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1
<< 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1;
Perceptron<> p(trainData, labels.row(0), 1000);
mat testData;
testData << 3 << 4 << 5 << 6 << endr
<< 3 << 2.3 << 1.7 << 1.5 << endr;
Row<size_t> predictedLabels(testData.n_cols);
p.Classify(testData, predictedLabels);
BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 1), 0);
BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);
BOOST_CHECK_EQUAL(predictedLabels(0, 3), 1);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Mikhail Baranov
* Copyright (c) 2015 Victor Gaydov
*
* 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/.
*/
#include "roc_core/panic.h"
#include "roc_core/log.h"
#include "roc_pipeline/session.h"
#include "roc_pipeline/config.h"
namespace roc {
namespace pipeline {
Session::Session(const ServerConfig& config,
const datagram::Address& address, packet::IPacketParser& parser)
: config_(config)
, address_(address)
, packet_parser_(parser)
, streamers_(MaxChannels)
, resamplers_(MaxChannels)
, readers_(MaxChannels) {
//
if (!config_.session_pool) {
roc_panic("session: session pool is null");
}
make_pipeline_();
}
void Session::free() {
config_.session_pool->destroy(*this);
}
const datagram::Address& Session::address() const {
return address_;
}
bool Session::store(const datagram::IDatagram& dgm) {
packet::IPacketConstPtr packet = packet_parser_.parse(dgm.buffer());
if (!packet) {
roc_log(LOG_TRACE, "session: dropping datagram: can't parse");
return false;
}
router_.write(packet);
return true;
}
bool Session::update() {
audio::ITuner* tuner = tuners_.front();
for (; tuner != NULL; tuner = tuners_.next(*tuner)) {
if (!tuner->update()) {
roc_log(LOG_DEBUG, "session: tuner failed to update, terminating session");
return false;
}
}
return true;
}
void Session::attach(audio::ISink& sink) {
roc_log(LOG_TRACE, "session: attaching readers to sink");
for (size_t ch = 0; ch < readers_.size(); ch++) {
if (readers_[ch]) {
sink.attach(packet::channel_t(ch), *readers_[ch]);
}
}
}
void Session::detach(audio::ISink& sink) {
roc_log(LOG_TRACE, "session: detaching readers from sink");
for (size_t ch = 0; ch < readers_.size(); ch++) {
if (readers_[ch]) {
sink.detach(packet::channel_t(ch), *readers_[ch]);
}
}
}
void Session::make_pipeline_() {
packet::IPacketReader* packet_reader = make_packet_reader_();
roc_panic_if(!packet_reader);
if (config_.options & EnableResampling) {
packet_reader = new (scaler_) audio::Scaler(*packet_reader, *audio_packet_queue_);
tuners_.append(*scaler_);
}
audio::IAudioPacketReader* audio_packet_reader =
new (chanalyzer_) audio::Chanalyzer(*packet_reader, config_.channels);
for (packet::channel_t ch = 0; ch < MaxChannels; ch++) {
if ((config_.channels & (1 << ch)) == 0) {
continue;
}
readers_[ch] = make_stream_reader_(audio_packet_reader, ch);
roc_panic_if(!readers_[ch]);
}
}
audio::IStreamReader*
Session::make_stream_reader_(audio::IAudioPacketReader* audio_packet_reader,
packet::channel_t ch) {
//
audio::IStreamReader* stream_reader = new (streamers_[ch])
audio::Streamer(*audio_packet_reader, ch, config_.options & EnableBeep);
if (config_.options & EnableResampling) {
roc_panic_if_not(scaler_);
stream_reader = new (resamplers_[ch])
audio::Resampler(*stream_reader, *config_.sample_buffer_composer);
scaler_->add_resampler(*resamplers_[ch]);
}
return stream_reader;
}
packet::IPacketReader* Session::make_packet_reader_() {
packet::IPacketReader* packet_reader =
new (audio_packet_queue_) packet::PacketQueue(config_.max_session_packets);
router_.add_route(packet::IAudioPacket::Type, *audio_packet_queue_);
packet_reader = new (delayer_) audio::Delayer(*packet_reader, config_.latency);
packet_reader = new (watchdog_) audio::Watchdog(*packet_reader, config_.timeout);
tuners_.append(*watchdog_);
if (config_.options & EnableLDPC) {
packet_reader = make_fec_decoder_(packet_reader);
}
return packet_reader;
}
#ifdef ROC_TARGET_OPENFEC
packet::IPacketReader* Session::make_fec_decoder_(packet::IPacketReader* packet_reader) {
//
new (fec_packet_queue_) packet::PacketQueue(config_.max_session_packets);
new (fec_ldpc_decoder_) fec::LDPC_BlockDecoder(*config_.byte_buffer_composer);
router_.add_route(packet::IFECPacket::Type, *fec_packet_queue_);
return new (fec_decoder_) fec::Decoder(*fec_ldpc_decoder_, *packet_reader,
*fec_packet_queue_, packet_parser_);
}
#else
packet::IPacketReader* Session::make_fec_decoder_(packet::IPacketReader* packet_reader) {
roc_log(LOG_ERROR, "session: OpenFEC support not enabled, disabling fec decoder");
return packet_reader;
}
#endif
} // namespace pipeline
} // namespace roc
<commit_msg>Fix GCC warnings<commit_after>/*
* Copyright (c) 2015 Mikhail Baranov
* Copyright (c) 2015 Victor Gaydov
*
* 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/.
*/
#include "roc_core/panic.h"
#include "roc_core/log.h"
#include "roc_pipeline/session.h"
#include "roc_pipeline/config.h"
namespace roc {
namespace pipeline {
Session::Session(const ServerConfig& config,
const datagram::Address& addr, packet::IPacketParser& parser)
: config_(config)
, address_(addr)
, packet_parser_(parser)
, streamers_(MaxChannels)
, resamplers_(MaxChannels)
, readers_(MaxChannels) {
//
if (!config_.session_pool) {
roc_panic("session: session pool is null");
}
make_pipeline_();
}
void Session::free() {
config_.session_pool->destroy(*this);
}
const datagram::Address& Session::address() const {
return address_;
}
bool Session::store(const datagram::IDatagram& dgm) {
packet::IPacketConstPtr packet = packet_parser_.parse(dgm.buffer());
if (!packet) {
roc_log(LOG_TRACE, "session: dropping datagram: can't parse");
return false;
}
router_.write(packet);
return true;
}
bool Session::update() {
audio::ITuner* tuner = tuners_.front();
for (; tuner != NULL; tuner = tuners_.next(*tuner)) {
if (!tuner->update()) {
roc_log(LOG_DEBUG, "session: tuner failed to update, terminating session");
return false;
}
}
return true;
}
void Session::attach(audio::ISink& sink) {
roc_log(LOG_TRACE, "session: attaching readers to sink");
for (size_t ch = 0; ch < readers_.size(); ch++) {
if (readers_[ch]) {
sink.attach(packet::channel_t(ch), *readers_[ch]);
}
}
}
void Session::detach(audio::ISink& sink) {
roc_log(LOG_TRACE, "session: detaching readers from sink");
for (size_t ch = 0; ch < readers_.size(); ch++) {
if (readers_[ch]) {
sink.detach(packet::channel_t(ch), *readers_[ch]);
}
}
}
void Session::make_pipeline_() {
packet::IPacketReader* packet_reader = make_packet_reader_();
roc_panic_if(!packet_reader);
if (config_.options & EnableResampling) {
packet_reader = new (scaler_) audio::Scaler(*packet_reader, *audio_packet_queue_);
tuners_.append(*scaler_);
}
audio::IAudioPacketReader* audio_packet_reader =
new (chanalyzer_) audio::Chanalyzer(*packet_reader, config_.channels);
for (packet::channel_t ch = 0; ch < MaxChannels; ch++) {
if ((config_.channels & (1 << ch)) == 0) {
continue;
}
readers_[ch] = make_stream_reader_(audio_packet_reader, ch);
roc_panic_if(!readers_[ch]);
}
}
audio::IStreamReader*
Session::make_stream_reader_(audio::IAudioPacketReader* audio_packet_reader,
packet::channel_t ch) {
//
audio::IStreamReader* stream_reader = new (streamers_[ch])
audio::Streamer(*audio_packet_reader, ch, config_.options & EnableBeep);
if (config_.options & EnableResampling) {
roc_panic_if_not(scaler_);
stream_reader = new (resamplers_[ch])
audio::Resampler(*stream_reader, *config_.sample_buffer_composer);
scaler_->add_resampler(*resamplers_[ch]);
}
return stream_reader;
}
packet::IPacketReader* Session::make_packet_reader_() {
packet::IPacketReader* packet_reader =
new (audio_packet_queue_) packet::PacketQueue(config_.max_session_packets);
router_.add_route(packet::IAudioPacket::Type, *audio_packet_queue_);
packet_reader = new (delayer_) audio::Delayer(*packet_reader, config_.latency);
packet_reader = new (watchdog_) audio::Watchdog(*packet_reader, config_.timeout);
tuners_.append(*watchdog_);
if (config_.options & EnableLDPC) {
packet_reader = make_fec_decoder_(packet_reader);
}
return packet_reader;
}
#ifdef ROC_TARGET_OPENFEC
packet::IPacketReader* Session::make_fec_decoder_(packet::IPacketReader* packet_reader) {
//
new (fec_packet_queue_) packet::PacketQueue(config_.max_session_packets);
new (fec_ldpc_decoder_) fec::LDPC_BlockDecoder(*config_.byte_buffer_composer);
router_.add_route(packet::IFECPacket::Type, *fec_packet_queue_);
return new (fec_decoder_) fec::Decoder(*fec_ldpc_decoder_, *packet_reader,
*fec_packet_queue_, packet_parser_);
}
#else
packet::IPacketReader* Session::make_fec_decoder_(packet::IPacketReader* packet_reader) {
roc_log(LOG_ERROR, "session: OpenFEC support not enabled, disabling fec decoder");
return packet_reader;
}
#endif
} // namespace pipeline
} // namespace roc
<|endoftext|> |
<commit_before>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* 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 General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "blackrock_spire.h"
enum Spells
{
SPELL_REND = 13738,
SPELL_THRASH = 3391,
};
enum Says
{
EMOTE_DEATH = 0
};
enum Events
{
EVENT_REND = 1,
EVENT_THRASH = 2,
};
const Position SummonLocation = { -167.9561f, -411.7844f, 76.23057f, 1.53589f };
class boss_halycon : public CreatureScript
{
public:
boss_halycon() : CreatureScript("boss_halycon") { }
struct boss_halyconAI : public BossAI
{
boss_halyconAI(Creature* creature) : BossAI(creature, DATA_HALYCON) { }
void Reset() override
{
_Reset();
Summoned = false;
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_REND, urand(17000, 20000));
events.ScheduleEvent(EVENT_THRASH, urand(10000, 12000));
}
void JustDied(Unit* /*killer*/) override
{
me->SummonCreature(NPC_GIZRUL_THE_SLAVENER, SummonLocation, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 300000);
Talk(EMOTE_DEATH);
Summoned = true;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_REND:
DoCastVictim(SPELL_REND);
events.ScheduleEvent(EVENT_REND, urand(8000, 10000));
break;
case EVENT_THRASH:
DoCast(me, SPELL_THRASH);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
bool Summoned;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetBlackrockSpireAI<boss_halyconAI>(creature);
}
};
void AddSC_boss_halycon()
{
new boss_halycon();
}
<commit_msg>fix(Scrips/BlackrockSpires): add missing `_JustDied()` to Halycon script (#10065)<commit_after>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* 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 General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "blackrock_spire.h"
enum Spells
{
SPELL_REND = 13738,
SPELL_THRASH = 3391,
};
enum Says
{
EMOTE_DEATH = 0
};
enum Events
{
EVENT_REND = 1,
EVENT_THRASH = 2,
};
const Position SummonLocation = { -167.9561f, -411.7844f, 76.23057f, 1.53589f };
class boss_halycon : public CreatureScript
{
public:
boss_halycon() : CreatureScript("boss_halycon") { }
struct boss_halyconAI : public BossAI
{
boss_halyconAI(Creature* creature) : BossAI(creature, DATA_HALYCON) { }
void Reset() override
{
_Reset();
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_REND, urand(17000, 20000));
events.ScheduleEvent(EVENT_THRASH, urand(10000, 12000));
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
me->SummonCreature(NPC_GIZRUL_THE_SLAVENER, SummonLocation, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 300000);
Talk(EMOTE_DEATH);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_REND:
DoCastVictim(SPELL_REND);
events.ScheduleEvent(EVENT_REND, urand(8000, 10000));
break;
case EVENT_THRASH:
DoCast(me, SPELL_THRASH);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetBlackrockSpireAI<boss_halyconAI>(creature);
}
};
void AddSC_boss_halycon()
{
new boss_halycon();
}
<|endoftext|> |
<commit_before>//===-- sanitizer_symbolizer_report.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// This file is shared between AddressSanitizer and other sanitizer run-time
/// libraries and implements symbolized reports related functions.
///
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_file.h"
#include "sanitizer_flags.h"
#include "sanitizer_procmaps.h"
#include "sanitizer_report_decorator.h"
#include "sanitizer_stacktrace.h"
#include "sanitizer_stacktrace_printer.h"
#include "sanitizer_symbolizer.h"
#if SANITIZER_POSIX
# include "sanitizer_posix.h"
# include <sys/mman.h>
#endif
namespace __sanitizer {
#if !SANITIZER_GO
void ReportErrorSummary(const char *error_type, const AddressInfo &info,
const char *alt_tool_name) {
if (!common_flags()->print_summary) return;
InternalScopedString buff(kMaxSummaryLength);
buff.append("%s ", error_type);
RenderFrame(&buff, "%L %F", 0, info, common_flags()->symbolize_vs_style,
common_flags()->strip_path_prefix);
ReportErrorSummary(buff.data(), alt_tool_name);
}
#endif
#if !SANITIZER_FUCHSIA
bool ReportFile::SupportsColors() {
SpinMutexLock l(mu);
ReopenIfNecessary();
return SupportsColoredOutput(fd);
}
static INLINE bool ReportSupportsColors() {
return report_file.SupportsColors();
}
#else // SANITIZER_FUCHSIA
// Fuchsia's logs always go through post-processing that handles colorization.
static INLINE bool ReportSupportsColors() { return true; }
#endif // !SANITIZER_FUCHSIA
bool ColorizeReports() {
// FIXME: Add proper Windows support to AnsiColorDecorator and re-enable color
// printing on Windows.
if (SANITIZER_WINDOWS)
return false;
const char *flag = common_flags()->color;
return internal_strcmp(flag, "always") == 0 ||
(internal_strcmp(flag, "auto") == 0 && ReportSupportsColors());
}
void ReportErrorSummary(const char *error_type, const StackTrace *stack,
const char *alt_tool_name) {
#if !SANITIZER_GO
if (!common_flags()->print_summary)
return;
if (stack->size == 0) {
ReportErrorSummary(error_type);
return;
}
// Currently, we include the first stack frame into the report summary.
// Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);
ReportErrorSummary(error_type, frame->info, alt_tool_name);
frame->ClearAll();
#endif
}
void ReportMmapWriteExec(int prot) {
#if SANITIZER_POSIX && (!SANITIZER_GO && !SANITIZER_ANDROID)
if ((prot & (PROT_WRITE | PROT_EXEC)) != (PROT_WRITE | PROT_EXEC))
return;
ScopedErrorReportLock l;
SanitizerCommonDecorator d;
InternalMmapVector<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
uptr top = 0;
uptr bottom = 0;
GET_CALLER_PC_BP_SP;
(void)sp;
bool fast = common_flags()->fast_unwind_on_fatal;
if (StackTrace::WillUseFastUnwind(fast)) {
GetThreadStackTopAndBottom(false, &top, &bottom);
stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, true);
} else {
stack->Unwind(kStackTraceMax, pc, 0, nullptr, 0, 0, false);
}
Printf("%s", d.Warning());
Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
Printf("%s", d.Default());
stack->Print();
ReportErrorSummary("w-and-x-usage", stack);
#endif
}
#if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS && !SANITIZER_GO
void StartReportDeadlySignal() {
// Write the first message using fd=2, just in case.
// It may actually fail to write in case stderr is closed.
CatastrophicErrorWrite(SanitizerToolName, internal_strlen(SanitizerToolName));
static const char kDeadlySignal[] = ":DEADLYSIGNAL\n";
CatastrophicErrorWrite(kDeadlySignal, sizeof(kDeadlySignal) - 1);
}
static void MaybeReportNonExecRegion(uptr pc) {
#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
MemoryMappedSegment segment;
while (proc_maps.Next(&segment)) {
if (pc >= segment.start && pc < segment.end && !segment.IsExecutable())
Report("Hint: PC is at a non-executable region. Maybe a wild jump?\n");
}
#endif
}
static void PrintMemoryByte(InternalScopedString *str, const char *before,
u8 byte) {
SanitizerCommonDecorator d;
str->append("%s%s%x%x%s ", before, d.MemoryByte(), byte >> 4, byte & 15,
d.Default());
}
static void MaybeDumpInstructionBytes(uptr pc) {
if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
return;
InternalScopedString str(1024);
str.append("First 16 instruction bytes at pc: ");
if (IsAccessibleMemoryRange(pc, 16)) {
for (int i = 0; i < 16; ++i) {
PrintMemoryByte(&str, "", ((u8 *)pc)[i]);
}
str.append("\n");
} else {
str.append("unaccessible\n");
}
Report("%s", str.data());
}
static void MaybeDumpRegisters(void *context) {
if (!common_flags()->dump_registers) return;
SignalContext::DumpAllRegisters(context);
}
static void ReportStackOverflowImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
static const char kDescription[] = "stack-overflow";
Report("ERROR: %s: %s on address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, kDescription, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
InternalMmapVector<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
ReportErrorSummary(kDescription, stack);
}
static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
const char *description = sig.Describe();
if (sig.is_memory_access && !sig.is_true_faulting_addr)
Report("ERROR: %s: %s on unknown address (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, description, (void *)sig.pc, (void *)sig.bp,
(void *)sig.sp, tid);
else
Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
if (sig.pc < GetPageSizeCached())
Report("Hint: pc points to the zero page.\n");
if (sig.is_memory_access) {
const char *access_type =
sig.write_flag == SignalContext::WRITE
? "WRITE"
: (sig.write_flag == SignalContext::READ ? "READ" : "UNKNOWN");
Report("The signal is caused by a %s memory access.\n", access_type);
if (!sig.is_true_faulting_addr)
Report("Hint: this fault was caused by a dereference of a high value "
"address (see registers below). Dissassemble the provided pc "
"to learn which register value was used.\n");
else if (sig.addr < GetPageSizeCached())
Report("Hint: address points to the zero page.\n");
}
MaybeReportNonExecRegion(sig.pc);
InternalMmapVector<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
MaybeDumpInstructionBytes(sig.pc);
MaybeDumpRegisters(sig.context);
Printf("%s can not provide additional info.\n", SanitizerToolName);
ReportErrorSummary(description, stack);
}
void ReportDeadlySignal(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
if (sig.IsStackOverflow())
ReportStackOverflowImpl(sig, tid, unwind, unwind_context);
else
ReportDeadlySignalImpl(sig, tid, unwind, unwind_context);
}
void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
StartReportDeadlySignal();
ScopedErrorReportLock rl;
SignalContext sig(siginfo, context);
ReportDeadlySignal(sig, tid, unwind, unwind_context);
Report("ABORTING\n");
Die();
}
#endif // !SANITIZER_FUCHSIA && !SANITIZER_GO
static atomic_uintptr_t reporting_thread = {0};
static StaticSpinMutex CommonSanitizerReportMutex;
ScopedErrorReportLock::ScopedErrorReportLock() {
uptr current = GetThreadSelf();
for (;;) {
uptr expected = 0;
if (atomic_compare_exchange_strong(&reporting_thread, &expected, current,
memory_order_relaxed)) {
// We've claimed reporting_thread so proceed.
CommonSanitizerReportMutex.Lock();
return;
}
if (expected == current) {
// This is either asynch signal or nested error during error reporting.
// Fail simple to avoid deadlocks in Report().
// Can't use Report() here because of potential deadlocks in nested
// signal handlers.
CatastrophicErrorWrite(SanitizerToolName,
internal_strlen(SanitizerToolName));
static const char msg[] = ": nested bug in the same thread, aborting.\n";
CatastrophicErrorWrite(msg, sizeof(msg) - 1);
internal__exit(common_flags()->exitcode);
}
internal_sched_yield();
}
}
ScopedErrorReportLock::~ScopedErrorReportLock() {
CommonSanitizerReportMutex.Unlock();
atomic_store_relaxed(&reporting_thread, 0);
}
void ScopedErrorReportLock::CheckLocked() {
CommonSanitizerReportMutex.CheckLocked();
}
} // namespace __sanitizer
<commit_msg>[ASan] Refine diagnoses messages<commit_after>//===-- sanitizer_symbolizer_report.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// This file is shared between AddressSanitizer and other sanitizer run-time
/// libraries and implements symbolized reports related functions.
///
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_file.h"
#include "sanitizer_flags.h"
#include "sanitizer_procmaps.h"
#include "sanitizer_report_decorator.h"
#include "sanitizer_stacktrace.h"
#include "sanitizer_stacktrace_printer.h"
#include "sanitizer_symbolizer.h"
#if SANITIZER_POSIX
# include "sanitizer_posix.h"
# include <sys/mman.h>
#endif
namespace __sanitizer {
#if !SANITIZER_GO
void ReportErrorSummary(const char *error_type, const AddressInfo &info,
const char *alt_tool_name) {
if (!common_flags()->print_summary) return;
InternalScopedString buff(kMaxSummaryLength);
buff.append("%s ", error_type);
RenderFrame(&buff, "%L %F", 0, info, common_flags()->symbolize_vs_style,
common_flags()->strip_path_prefix);
ReportErrorSummary(buff.data(), alt_tool_name);
}
#endif
#if !SANITIZER_FUCHSIA
bool ReportFile::SupportsColors() {
SpinMutexLock l(mu);
ReopenIfNecessary();
return SupportsColoredOutput(fd);
}
static INLINE bool ReportSupportsColors() {
return report_file.SupportsColors();
}
#else // SANITIZER_FUCHSIA
// Fuchsia's logs always go through post-processing that handles colorization.
static INLINE bool ReportSupportsColors() { return true; }
#endif // !SANITIZER_FUCHSIA
bool ColorizeReports() {
// FIXME: Add proper Windows support to AnsiColorDecorator and re-enable color
// printing on Windows.
if (SANITIZER_WINDOWS)
return false;
const char *flag = common_flags()->color;
return internal_strcmp(flag, "always") == 0 ||
(internal_strcmp(flag, "auto") == 0 && ReportSupportsColors());
}
void ReportErrorSummary(const char *error_type, const StackTrace *stack,
const char *alt_tool_name) {
#if !SANITIZER_GO
if (!common_flags()->print_summary)
return;
if (stack->size == 0) {
ReportErrorSummary(error_type);
return;
}
// Currently, we include the first stack frame into the report summary.
// Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);
ReportErrorSummary(error_type, frame->info, alt_tool_name);
frame->ClearAll();
#endif
}
void ReportMmapWriteExec(int prot) {
#if SANITIZER_POSIX && (!SANITIZER_GO && !SANITIZER_ANDROID)
if ((prot & (PROT_WRITE | PROT_EXEC)) != (PROT_WRITE | PROT_EXEC))
return;
ScopedErrorReportLock l;
SanitizerCommonDecorator d;
InternalMmapVector<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
uptr top = 0;
uptr bottom = 0;
GET_CALLER_PC_BP_SP;
(void)sp;
bool fast = common_flags()->fast_unwind_on_fatal;
if (StackTrace::WillUseFastUnwind(fast)) {
GetThreadStackTopAndBottom(false, &top, &bottom);
stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, true);
} else {
stack->Unwind(kStackTraceMax, pc, 0, nullptr, 0, 0, false);
}
Printf("%s", d.Warning());
Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
Printf("%s", d.Default());
stack->Print();
ReportErrorSummary("w-and-x-usage", stack);
#endif
}
#if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS && !SANITIZER_GO
void StartReportDeadlySignal() {
// Write the first message using fd=2, just in case.
// It may actually fail to write in case stderr is closed.
CatastrophicErrorWrite(SanitizerToolName, internal_strlen(SanitizerToolName));
static const char kDeadlySignal[] = ":DEADLYSIGNAL\n";
CatastrophicErrorWrite(kDeadlySignal, sizeof(kDeadlySignal) - 1);
}
static void MaybeReportNonExecRegion(uptr pc) {
#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
MemoryMappedSegment segment;
while (proc_maps.Next(&segment)) {
if (pc >= segment.start && pc < segment.end && !segment.IsExecutable())
Report("Hint: PC is at a non-executable region. Maybe a wild jump?\n");
}
#endif
}
static void PrintMemoryByte(InternalScopedString *str, const char *before,
u8 byte) {
SanitizerCommonDecorator d;
str->append("%s%s%x%x%s ", before, d.MemoryByte(), byte >> 4, byte & 15,
d.Default());
}
static void MaybeDumpInstructionBytes(uptr pc) {
if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
return;
InternalScopedString str(1024);
str.append("First 16 instruction bytes at pc: ");
if (IsAccessibleMemoryRange(pc, 16)) {
for (int i = 0; i < 16; ++i) {
PrintMemoryByte(&str, "", ((u8 *)pc)[i]);
}
str.append("\n");
} else {
str.append("unaccessible\n");
}
Report("%s", str.data());
}
static void MaybeDumpRegisters(void *context) {
if (!common_flags()->dump_registers) return;
SignalContext::DumpAllRegisters(context);
}
static void ReportStackOverflowImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
static const char kDescription[] = "stack-overflow";
Report("ERROR: %s: %s on address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, kDescription, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
InternalMmapVector<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
ReportErrorSummary(kDescription, stack);
}
static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
const char *description = sig.Describe();
if (sig.is_memory_access && !sig.is_true_faulting_addr)
Report("ERROR: %s: %s on unknown address (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, description, (void *)sig.pc, (void *)sig.bp,
(void *)sig.sp, tid);
else
Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
if (sig.pc < GetPageSizeCached())
Report("Hint: pc points to the zero page.\n");
if (sig.is_memory_access) {
const char *access_type =
sig.write_flag == SignalContext::WRITE
? "WRITE"
: (sig.write_flag == SignalContext::READ ? "READ" : "UNKNOWN");
Report("The signal is caused by a %s memory access.\n", access_type);
if (!sig.is_true_faulting_addr)
Report("Hint: this fault was caused by a dereference of a high value "
"address (see register values below).\n");
else if (sig.addr < GetPageSizeCached())
Report("Hint: address points to the zero page.\n");
}
MaybeReportNonExecRegion(sig.pc);
InternalMmapVector<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
MaybeDumpInstructionBytes(sig.pc);
MaybeDumpRegisters(sig.context);
Printf("%s can not provide additional info.\n", SanitizerToolName);
ReportErrorSummary(description, stack);
}
void ReportDeadlySignal(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
if (sig.IsStackOverflow())
ReportStackOverflowImpl(sig, tid, unwind, unwind_context);
else
ReportDeadlySignalImpl(sig, tid, unwind, unwind_context);
}
void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
StartReportDeadlySignal();
ScopedErrorReportLock rl;
SignalContext sig(siginfo, context);
ReportDeadlySignal(sig, tid, unwind, unwind_context);
Report("ABORTING\n");
Die();
}
#endif // !SANITIZER_FUCHSIA && !SANITIZER_GO
static atomic_uintptr_t reporting_thread = {0};
static StaticSpinMutex CommonSanitizerReportMutex;
ScopedErrorReportLock::ScopedErrorReportLock() {
uptr current = GetThreadSelf();
for (;;) {
uptr expected = 0;
if (atomic_compare_exchange_strong(&reporting_thread, &expected, current,
memory_order_relaxed)) {
// We've claimed reporting_thread so proceed.
CommonSanitizerReportMutex.Lock();
return;
}
if (expected == current) {
// This is either asynch signal or nested error during error reporting.
// Fail simple to avoid deadlocks in Report().
// Can't use Report() here because of potential deadlocks in nested
// signal handlers.
CatastrophicErrorWrite(SanitizerToolName,
internal_strlen(SanitizerToolName));
static const char msg[] = ": nested bug in the same thread, aborting.\n";
CatastrophicErrorWrite(msg, sizeof(msg) - 1);
internal__exit(common_flags()->exitcode);
}
internal_sched_yield();
}
}
ScopedErrorReportLock::~ScopedErrorReportLock() {
CommonSanitizerReportMutex.Unlock();
atomic_store_relaxed(&reporting_thread, 0);
}
void ScopedErrorReportLock::CheckLocked() {
CommonSanitizerReportMutex.CheckLocked();
}
} // namespace __sanitizer
<|endoftext|> |
<commit_before>#include "face_normals.hpp"
#include "triangulation_enums.hpp"
#include "indexing.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <vector> // std::vector
namespace geometry
{
bool compute_face_normals(
std::vector<glm::vec3>& temp_vertices,
std::vector<glm::vec3>& face_normal_vector_vec3,
const int32_t actual_image_width,
const int32_t actual_image_height,
const bool is_bilinear_interpolation_in_use,
const bool is_southwest_northeast_edges_in_use,
const bool is_southeast_northwest_edges_in_use)
{
int32_t current_interpolated_vertex_i = actual_image_width * actual_image_height;
if (actual_image_width < 2 || actual_image_height < 2)
{
// If width or height is < 2, there are no faces.
return false;
}
for (int32_t z = 1; z < actual_image_height; z++)
{
for (int32_t x = 1; x < actual_image_width; x++)
{
int32_t current_vertex_i = actual_image_width * z + x;
// Computing of face normals depends on triangulation type.
if (is_bilinear_interpolation_in_use)
{
glm::vec3 edge1;
glm::vec3 edge2;
glm::vec3 face_normal;
// Compute the normal of S face.
edge1 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of W face.
edge1 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of N face.
edge1 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of E face.
edge1 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
}
else if (is_southwest_northeast_edges_in_use)
{
glm::vec3 edge1;
glm::vec3 edge2;
glm::vec3 face_normal;
// Compute the normal of SE face.
edge1 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[southeast(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[southeast(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of NW face.
edge1 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[northwest(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[northwest(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
}
else if (is_southeast_northwest_edges_in_use)
{
glm::vec3 edge1;
glm::vec3 edge2;
glm::vec3 face_normal;
// Compute the normal of SW face.
edge1 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[southwest(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[southwest(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of NE face.
edge1 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[northeast(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[northeast(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
}
else
{
std::cerr << "invalid triangulation type!\n";
return false;
}
current_interpolated_vertex_i++;
}
}
return true;
}
// for bilinear interpolation.
glm::vec3 get_face_normal(
const std::vector<glm::vec3>& face_normal_data,
const int32_t x,
const int32_t z,
const BilinearDirections compass_point_code,
const int32_t actual_image_width)
{
if (x < 0 || z < 0)
{
std::cerr << "negative coordinates are not supported!";
}
int32_t face_normal_i = get_face_normal_i(x, z, compass_point_code, actual_image_width);
if (face_normal_i == -1)
{
std::cerr << "invalid compass point code!\n";
return glm::vec3(NAN, NAN, NAN);
}
return face_normal_data[face_normal_i];
}
// for bilinear interpolation.
// These functions exist to avoid need to remember
// the array order when calling `geometry::get_face_normal`.
glm::vec3 s_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, ENE, image_width);
}
glm::vec3 w_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, NNE, image_width);
}
glm::vec3 n_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x, z, WSW, image_width);
}
glm::vec3 e_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x, z, SSW, image_width);
}
// for southeast-northwest edges.
glm::vec3 get_face_normal_for_SE_NW(
const std::vector<glm::vec3>& face_normal_data,
const int32_t x,
const int32_t z,
const SoutheastNorthwestEdgesDirections compass_point_code,
const int32_t image_width)
{
int32_t face_normal_i;
switch (compass_point_code)
{
case SSE_CODE_FOR_SE_NW:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x;
break;
case WNW_CODE_FOR_SE_NW:
face_normal_i = 2 * z * (image_width - 1) + 2 * x - 2;
break;
case ESE_CODE_FOR_SE_NW:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x + 1;
break;
case NNW_CODE_FOR_SE_NW:
face_normal_i = 2 * z * (image_width - 1) + 2 * x - 1;
break;
case SW_CODE_FOR_SE_NW:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x - 1;
break;
case NE_CODE_FOR_SE_NW:
face_normal_i = 2 * z * (image_width - 1) + 2 * x;
break;
default:
std::cerr << "invalid compass point code!\n";
return glm::vec3(NAN, NAN, NAN);
}
return face_normal_data[face_normal_i];
}
// for southwest-northeast edges.
glm::vec3 get_face_normal_for_SW_NE(
const std::vector<glm::vec3>& face_normal_data,
const int32_t x,
const int32_t z,
const SouthwestNortheastEdgesDirections compass_point_code,
const int32_t image_width)
{
int32_t face_normal_i;
switch (compass_point_code)
{
case SSW_CODE_FOR_SW_NE:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x - 2;
break;
case ENE_CODE_FOR_SW_NE:
face_normal_i = 2 * z * (image_width - 1) + 2 * x;
break;
case WSW_CODE_FOR_SW_NE:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x - 1;
break;
case NNE_CODE_FOR_SW_NE:
face_normal_i = 2 * z * (image_width - 1) + 2 * x + 1;
break;
case SE_CODE_FOR_SW_NE:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x + 1;
break;
case NW_CODE_FOR_SW_NE:
face_normal_i = 2 * z * (image_width - 1) + 2 * x - 1;
break;
default:
std::cerr << "invalid compass point code!\n";
return glm::vec3(NAN, NAN, NAN);
}
if (face_normal_i < 0)
{
// Face normal index can not be negative.
return glm::vec3(NAN, NAN, NAN);
}
return face_normal_data[face_normal_i];
}
}
<commit_msg>Bugfix: return `glm::vec3(NAN, NAN, NAN)` when `x` or `z` is invalid.<commit_after>#include "face_normals.hpp"
#include "triangulation_enums.hpp"
#include "indexing.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <vector> // std::vector
namespace geometry
{
bool compute_face_normals(
std::vector<glm::vec3>& temp_vertices,
std::vector<glm::vec3>& face_normal_vector_vec3,
const int32_t actual_image_width,
const int32_t actual_image_height,
const bool is_bilinear_interpolation_in_use,
const bool is_southwest_northeast_edges_in_use,
const bool is_southeast_northwest_edges_in_use)
{
int32_t current_interpolated_vertex_i = actual_image_width * actual_image_height;
if (actual_image_width < 2 || actual_image_height < 2)
{
// If width or height is < 2, there are no faces.
return false;
}
for (int32_t z = 1; z < actual_image_height; z++)
{
for (int32_t x = 1; x < actual_image_width; x++)
{
int32_t current_vertex_i = actual_image_width * z + x;
// Computing of face normals depends on triangulation type.
if (is_bilinear_interpolation_in_use)
{
glm::vec3 edge1;
glm::vec3 edge2;
glm::vec3 face_normal;
// Compute the normal of S face.
edge1 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of W face.
edge1 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of N face.
edge1 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of E face.
edge1 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
edge2 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[current_interpolated_vertex_i];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
}
else if (is_southwest_northeast_edges_in_use)
{
glm::vec3 edge1;
glm::vec3 edge2;
glm::vec3 face_normal;
// Compute the normal of SE face.
edge1 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[southeast(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[southeast(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of NW face.
edge1 = temp_vertices[northeast(current_vertex_i, actual_image_width)] - temp_vertices[northwest(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[southwest(current_vertex_i, actual_image_width)] - temp_vertices[northwest(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
}
else if (is_southeast_northwest_edges_in_use)
{
glm::vec3 edge1;
glm::vec3 edge2;
glm::vec3 face_normal;
// Compute the normal of SW face.
edge1 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[southwest(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[southwest(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
// Compute the normal of NE face.
edge1 = temp_vertices[southeast(current_vertex_i, actual_image_width)] - temp_vertices[northeast(current_vertex_i, actual_image_width)];
edge2 = temp_vertices[northwest(current_vertex_i, actual_image_width)] - temp_vertices[northeast(current_vertex_i, actual_image_width)];
face_normal = glm::normalize(glm::cross(edge1, edge2));
face_normal_vector_vec3.push_back(face_normal);
}
else
{
std::cerr << "invalid triangulation type!\n";
return false;
}
current_interpolated_vertex_i++;
}
}
return true;
}
// for bilinear interpolation.
glm::vec3 get_face_normal(
const std::vector<glm::vec3>& face_normal_data,
const int32_t x,
const int32_t z,
const BilinearDirections compass_point_code,
const int32_t actual_image_width)
{
if (x < 0 || z < 0)
{
std::cerr << "negative coordinates are not supported!";
return glm::vec3(NAN, NAN, NAN);
}
int32_t face_normal_i = get_face_normal_i(x, z, compass_point_code, actual_image_width);
if (face_normal_i == -1)
{
std::cerr << "invalid compass point code!\n";
return glm::vec3(NAN, NAN, NAN);
}
return face_normal_data[face_normal_i];
}
// for bilinear interpolation.
// These functions exist to avoid need to remember
// the array order when calling `geometry::get_face_normal`.
glm::vec3 s_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, ENE, image_width);
}
glm::vec3 w_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, NNE, image_width);
}
glm::vec3 n_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x, z, WSW, image_width);
}
glm::vec3 e_face_normal(const std::vector<glm::vec3>& face_normal_vector_vec3, const int32_t x, const int32_t z, const int32_t image_width)
{
return geometry::get_face_normal(face_normal_vector_vec3, x, z, SSW, image_width);
}
// for southeast-northwest edges.
glm::vec3 get_face_normal_for_SE_NW(
const std::vector<glm::vec3>& face_normal_data,
const int32_t x,
const int32_t z,
const SoutheastNorthwestEdgesDirections compass_point_code,
const int32_t image_width)
{
int32_t face_normal_i;
switch (compass_point_code)
{
case SSE_CODE_FOR_SE_NW:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x;
break;
case WNW_CODE_FOR_SE_NW:
face_normal_i = 2 * z * (image_width - 1) + 2 * x - 2;
break;
case ESE_CODE_FOR_SE_NW:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x + 1;
break;
case NNW_CODE_FOR_SE_NW:
face_normal_i = 2 * z * (image_width - 1) + 2 * x - 1;
break;
case SW_CODE_FOR_SE_NW:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x - 1;
break;
case NE_CODE_FOR_SE_NW:
face_normal_i = 2 * z * (image_width - 1) + 2 * x;
break;
default:
std::cerr << "invalid compass point code!\n";
return glm::vec3(NAN, NAN, NAN);
}
return face_normal_data[face_normal_i];
}
// for southwest-northeast edges.
glm::vec3 get_face_normal_for_SW_NE(
const std::vector<glm::vec3>& face_normal_data,
const int32_t x,
const int32_t z,
const SouthwestNortheastEdgesDirections compass_point_code,
const int32_t image_width)
{
int32_t face_normal_i;
switch (compass_point_code)
{
case SSW_CODE_FOR_SW_NE:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x - 2;
break;
case ENE_CODE_FOR_SW_NE:
face_normal_i = 2 * z * (image_width - 1) + 2 * x;
break;
case WSW_CODE_FOR_SW_NE:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x - 1;
break;
case NNE_CODE_FOR_SW_NE:
face_normal_i = 2 * z * (image_width - 1) + 2 * x + 1;
break;
case SE_CODE_FOR_SW_NE:
face_normal_i = 2 * (z - 1) * (image_width - 1) + 2 * x + 1;
break;
case NW_CODE_FOR_SW_NE:
face_normal_i = 2 * z * (image_width - 1) + 2 * x - 1;
break;
default:
std::cerr << "invalid compass point code!\n";
return glm::vec3(NAN, NAN, NAN);
}
if (face_normal_i < 0)
{
// Face normal index can not be negative.
return glm::vec3(NAN, NAN, NAN);
}
return face_normal_data[face_normal_i];
}
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgTerrain/GeometryTechnique>
#include <osgTerrain/TerrainNode>
#include <osgUtil/SmoothingVisitor>
#include <osgDB/FileUtils>
#include <osg/io_utils>
#include <osg/Texture2D>
#include <osg/Texture1D>
#include <osg/TexEnvCombine>
#include <osg/Program>
using namespace osgTerrain;
GeometryTechnique::GeometryTechnique()
{
}
GeometryTechnique::GeometryTechnique(const GeometryTechnique& gt,const osg::CopyOp& copyop):
TerrainTechnique(gt,copyop)
{
}
GeometryTechnique::~GeometryTechnique()
{
}
void GeometryTechnique::init()
{
osg::notify(osg::NOTICE)<<"Doing init()"<<std::endl;
if (!_terrainNode) return;
osgTerrain::Layer* elevationLayer = _terrainNode->getElevationLayer();
osgTerrain::Layer* colorLayer = _terrainNode->getColorLayer();
osg::TransferFunction* colorTF = _terrainNode->getColorTransferFunction();
osg::notify(osg::NOTICE)<<"elevationLayer = "<<elevationLayer<<std::endl;
osg::notify(osg::NOTICE)<<"colorLayer = "<<colorLayer<<std::endl;
osg::notify(osg::NOTICE)<<"colorTF = "<<colorTF<<std::endl;
Locator* elevationLocator = elevationLayer ? elevationLayer->getLocator() : 0;
Locator* colorLocator = colorLayer ? colorLayer->getLocator() : 0;
Locator* masterLocator = elevationLocator ? elevationLocator : colorLocator;
if (!masterLocator)
{
osg::notify(osg::NOTICE)<<"Problem, no locator found in any of the terrain layers"<<std::endl;
return;
}
if (!elevationLocator) elevationLocator = masterLocator;
if (!colorLocator) colorLocator = masterLocator;
osg::Vec3d bottomLeftNDC(DBL_MAX, DBL_MAX, 0.0);
osg::Vec3d topRightNDC(-DBL_MAX, -DBL_MAX, 0.0);
if (elevationLayer)
{
if (elevationLocator!= masterLocator)
{
masterLocator->computeLocalBounds(*elevationLocator, bottomLeftNDC, topRightNDC);
}
else
{
bottomLeftNDC.x() = osg::minimum(bottomLeftNDC.x(), 0.0);
bottomLeftNDC.y() = osg::minimum(bottomLeftNDC.y(), 0.0);
topRightNDC.x() = osg::maximum(topRightNDC.x(), 1.0);
topRightNDC.y() = osg::maximum(topRightNDC.y(), 1.0);
}
}
if (colorLayer)
{
if (colorLocator!= masterLocator)
{
masterLocator->computeLocalBounds(*colorLocator, bottomLeftNDC, topRightNDC);
}
else
{
bottomLeftNDC.x() = osg::minimum(bottomLeftNDC.x(), 0.0);
bottomLeftNDC.y() = osg::minimum(bottomLeftNDC.y(), 0.0);
topRightNDC.x() = osg::maximum(topRightNDC.x(), 1.0);
topRightNDC.y() = osg::maximum(topRightNDC.y(), 1.0);
}
}
osg::notify(osg::NOTICE)<<"bottomLeftNDC = "<<bottomLeftNDC<<std::endl;
osg::notify(osg::NOTICE)<<"topRightNDC = "<<topRightNDC<<std::endl;
_geode = new osg::Geode;
_geometry = new osg::Geometry;
_geode->addDrawable(_geometry.get());
unsigned int numRows = 100;
unsigned int numColumns = 100;
if (elevationLayer)
{
numColumns = elevationLayer->getNumColumns();
numRows = elevationLayer->getNumRows();
}
unsigned int numVertices = numRows * numColumns;
// allocate and assign vertices
osg::Vec3Array* vertices = new osg::Vec3Array(numVertices);
_geometry->setVertexArray(vertices);
// allocate and assign normals
osg::Vec3Array* normals = new osg::Vec3Array(numVertices);
_geometry->setNormalArray(normals);
_geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
osg::FloatArray* heights = 0;
if (colorTF)
{
heights = new osg::FloatArray(numVertices);
_geometry->setTexCoordArray(1, heights);
}
// allocate and assign tex coords
osg::Vec2Array* texcoords = 0;
if (colorLayer)
{
texcoords = new osg::Vec2Array(numVertices);
_geometry->setTexCoordArray(0, texcoords);
}
// allocate and assign color
osg::Vec4Array* colors = new osg::Vec4Array(1);
_geometry->setColorArray(colors);
_geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
(*colors)[0].set(1.0f,1.0f,1.0f,1.0f);
// populate vertex and tex coord arrays
unsigned int j;
for(j=0; j<numRows; ++j)
{
for(unsigned int i=0; i<numColumns; ++i)
{
unsigned int iv = j*numColumns + i;
osg::Vec3d ndc( (double)i/(double)(numColumns-1), (double)j/(double)(numColumns-1), 0.0);
if (elevationLayer)
{
float value = 0.0f;
elevationLayer->getValue(i,j, value);
// osg::notify(osg::NOTICE)<<"i="<<i<<" j="<<j<<" z="<<value<<std::endl;
ndc.z() = value;
}
osg::Vec3d model;
masterLocator->convertLocalToModel(ndc, model);
(*vertices)[iv] = model;
if (colorLayer)
{
if (colorLocator!= masterLocator)
{
osg::Vec3d color_ndc;
colorLocator->computeLocalBounds(*masterLocator, ndc, color_ndc);
(*texcoords)[iv].set(color_ndc.x(), color_ndc.y());
}
else
{
(*texcoords)[iv].set(ndc.x(), ndc.y());
}
}
if (heights)
{
(*heights)[iv] = ndc.z();
}
// compute the local normal
osg::Vec3d ndc_one( (double)i/(double)(numColumns-1), (double)j/(double)(numColumns-1), 1.0);
osg::Vec3d model_one;
masterLocator->convertLocalToModel(ndc_one, model_one);
model_one -= model;
model_one.normalize();
(*normals)[iv] = model_one;
}
}
// populate primitive sets
for(j=0; j<numRows-1; ++j)
{
osg::DrawElementsUInt* elements = new osg::DrawElementsUInt(GL_TRIANGLE_STRIP, numColumns*2);
for(unsigned int i=0; i<numColumns; ++i)
{
unsigned int iv = j*numColumns + i;
(*elements)[i*2] = iv + numColumns;
(*elements)[i*2+1] = iv;
}
_geometry->addPrimitiveSet(elements);
}
osgUtil::SmoothingVisitor smoother;
_geode->accept(smoother);
if (colorLayer)
{
osgTerrain::ImageLayer* imageLayer = dynamic_cast<osgTerrain::ImageLayer*>(colorLayer);
if (imageLayer)
{
osg::Image* image = imageLayer->getImage();
osg::StateSet* stateset = _geode->getOrCreateStateSet();
osg::Texture2D* texture2D = new osg::Texture2D;
texture2D->setImage(image);
texture2D->setResizeNonPowerOfTwoHint(false);
stateset->setTextureAttributeAndModes(0, texture2D, osg::StateAttribute::ON);
}
}
osg::TransferFunction1D* tf = dynamic_cast<osg::TransferFunction1D*>(colorTF);
if (tf)
{
osg::notify(osg::NOTICE)<<"Requires TransferFunction"<<std::endl;
osg::Image* image = tf->getImage();
osg::StateSet* stateset = _geode->getOrCreateStateSet();
osg::Texture1D* texture1D = new osg::Texture1D;
texture1D->setImage(image);
texture1D->setResizeNonPowerOfTwoHint(false);
texture1D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
texture1D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
stateset->setTextureAttributeAndModes(1, texture1D, osg::StateAttribute::ON);
osg::Program* program = new osg::Program;
stateset->setAttribute(program);
// get shaders from source
std::string vertexShaderFile = osgDB::findDataFile("lookup.vert");
if (!vertexShaderFile.empty())
{
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, vertexShaderFile));
}
else
{
osg::notify(osg::NOTICE)<<"Not found lookup.vert"<<std::endl;
}
std::string fragmentShaderFile = osgDB::findDataFile("lookup.frag");
if (!fragmentShaderFile.empty())
{
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, fragmentShaderFile));
}
else
{
osg::notify(osg::NOTICE)<<"Not found lookup.frag"<<std::endl;
}
osg::Uniform* sourceSampler = new osg::Uniform("sourceTexture",0);
stateset->addUniform(sourceSampler);
osg::Uniform* lookupTexture = new osg::Uniform("lookupTexture",1);
stateset->addUniform(lookupTexture);
osg::Uniform* minValue = new osg::Uniform("minValue", tf->getMinimum());
stateset->addUniform(minValue);
osg::Uniform* inverseRange = new osg::Uniform("inverseRange", 1.0f/(tf->getMaximum()-tf->getMinimum()));
stateset->addUniform(inverseRange);
}
_dirty = false;
}
void GeometryTechnique::update(osgUtil::UpdateVisitor* nv)
{
}
void GeometryTechnique::cull(osgUtil::CullVisitor* nv)
{
if (_geode.valid())
{
_geode->accept(*nv);
}
}
void GeometryTechnique::cleanSceneGraph()
{
}
void GeometryTechnique::dirty()
{
TerrainTechnique::dirty();
}
<commit_msg>Added better handling of colour layer/elevation layer/transfer function combinations and use of 16bit luminance format for colour layers used as input to transfer functions<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgTerrain/GeometryTechnique>
#include <osgTerrain/TerrainNode>
#include <osgUtil/SmoothingVisitor>
#include <osgDB/FileUtils>
#include <osg/io_utils>
#include <osg/Texture2D>
#include <osg/Texture1D>
#include <osg/TexEnvCombine>
#include <osg/Program>
using namespace osgTerrain;
GeometryTechnique::GeometryTechnique()
{
}
GeometryTechnique::GeometryTechnique(const GeometryTechnique& gt,const osg::CopyOp& copyop):
TerrainTechnique(gt,copyop)
{
}
GeometryTechnique::~GeometryTechnique()
{
}
void GeometryTechnique::init()
{
osg::notify(osg::NOTICE)<<"Doing init()"<<std::endl;
if (!_terrainNode) return;
osgTerrain::Layer* elevationLayer = _terrainNode->getElevationLayer();
osgTerrain::Layer* colorLayer = _terrainNode->getColorLayer();
osg::TransferFunction* colorTF = _terrainNode->getColorTransferFunction();
// if the elevationLayer and colorLayer are the same, and there is colorTF then
// simply assing as a texture coordinate.
if ((elevationLayer==colorLayer) && colorTF) colorLayer = 0;
osg::notify(osg::NOTICE)<<"elevationLayer = "<<elevationLayer<<std::endl;
osg::notify(osg::NOTICE)<<"colorLayer = "<<colorLayer<<std::endl;
osg::notify(osg::NOTICE)<<"colorTF = "<<colorTF<<std::endl;
Locator* elevationLocator = elevationLayer ? elevationLayer->getLocator() : 0;
Locator* colorLocator = colorLayer ? colorLayer->getLocator() : 0;
Locator* masterLocator = elevationLocator ? elevationLocator : colorLocator;
if (!masterLocator)
{
osg::notify(osg::NOTICE)<<"Problem, no locator found in any of the terrain layers"<<std::endl;
return;
}
if (!elevationLocator) elevationLocator = masterLocator;
if (!colorLocator) colorLocator = masterLocator;
osg::Vec3d bottomLeftNDC(DBL_MAX, DBL_MAX, 0.0);
osg::Vec3d topRightNDC(-DBL_MAX, -DBL_MAX, 0.0);
if (elevationLayer)
{
if (elevationLocator!= masterLocator)
{
masterLocator->computeLocalBounds(*elevationLocator, bottomLeftNDC, topRightNDC);
}
else
{
bottomLeftNDC.x() = osg::minimum(bottomLeftNDC.x(), 0.0);
bottomLeftNDC.y() = osg::minimum(bottomLeftNDC.y(), 0.0);
topRightNDC.x() = osg::maximum(topRightNDC.x(), 1.0);
topRightNDC.y() = osg::maximum(topRightNDC.y(), 1.0);
}
}
if (colorLayer)
{
if (colorLocator!= masterLocator)
{
masterLocator->computeLocalBounds(*colorLocator, bottomLeftNDC, topRightNDC);
}
else
{
bottomLeftNDC.x() = osg::minimum(bottomLeftNDC.x(), 0.0);
bottomLeftNDC.y() = osg::minimum(bottomLeftNDC.y(), 0.0);
topRightNDC.x() = osg::maximum(topRightNDC.x(), 1.0);
topRightNDC.y() = osg::maximum(topRightNDC.y(), 1.0);
}
}
osg::notify(osg::NOTICE)<<"bottomLeftNDC = "<<bottomLeftNDC<<std::endl;
osg::notify(osg::NOTICE)<<"topRightNDC = "<<topRightNDC<<std::endl;
_geode = new osg::Geode;
_geometry = new osg::Geometry;
_geode->addDrawable(_geometry.get());
unsigned int numRows = 100;
unsigned int numColumns = 100;
if (elevationLayer)
{
numColumns = elevationLayer->getNumColumns();
numRows = elevationLayer->getNumRows();
}
unsigned int numVertices = numRows * numColumns;
// allocate and assign vertices
osg::Vec3Array* vertices = new osg::Vec3Array(numVertices);
_geometry->setVertexArray(vertices);
// allocate and assign normals
osg::Vec3Array* normals = new osg::Vec3Array(numVertices);
_geometry->setNormalArray(normals);
_geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
int texcoord_index = 0;
int color_index = -1;
int tf_index = -1;
float minHeight = 0.0;
float scaleHeight = 1.0;
// allocate and assign tex coords
osg::Vec2Array* texcoords = 0;
if (colorLayer)
{
color_index = texcoord_index;
++texcoord_index;
texcoords = new osg::Vec2Array(numVertices);
_geometry->setTexCoordArray(color_index, texcoords);
}
osg::FloatArray* heights = 0;
osg::TransferFunction1D* tf = dynamic_cast<osg::TransferFunction1D*>(colorTF);
if (tf)
{
tf_index = texcoord_index;
++texcoord_index;
if (!colorLayer)
{
heights = new osg::FloatArray(numVertices);
_geometry->setTexCoordArray(tf_index, heights);
minHeight = tf->getMinimum();
scaleHeight = 1.0f/(tf->getMaximum()-tf->getMinimum());
}
}
// allocate and assign color
osg::Vec4Array* colors = new osg::Vec4Array(1);
_geometry->setColorArray(colors);
_geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
(*colors)[0].set(1.0f,1.0f,1.0f,1.0f);
// populate vertex and tex coord arrays
unsigned int j;
for(j=0; j<numRows; ++j)
{
for(unsigned int i=0; i<numColumns; ++i)
{
unsigned int iv = j*numColumns + i;
osg::Vec3d ndc( (double)i/(double)(numColumns-1), (double)j/(double)(numColumns-1), 0.0);
if (elevationLayer)
{
float value = 0.0f;
elevationLayer->getValue(i,j, value);
// osg::notify(osg::NOTICE)<<"i="<<i<<" j="<<j<<" z="<<value<<std::endl;
ndc.z() = value;
}
osg::Vec3d model;
masterLocator->convertLocalToModel(ndc, model);
(*vertices)[iv] = model;
if (colorLayer)
{
if (colorLocator!= masterLocator)
{
osg::Vec3d color_ndc;
colorLocator->computeLocalBounds(*masterLocator, ndc, color_ndc);
(*texcoords)[iv].set(color_ndc.x(), color_ndc.y());
}
else
{
(*texcoords)[iv].set(ndc.x(), ndc.y());
}
}
if (heights)
{
(*heights)[iv] = (ndc.z()-minHeight)*scaleHeight;
}
// compute the local normal
osg::Vec3d ndc_one( (double)i/(double)(numColumns-1), (double)j/(double)(numColumns-1), 1.0);
osg::Vec3d model_one;
masterLocator->convertLocalToModel(ndc_one, model_one);
model_one -= model;
model_one.normalize();
(*normals)[iv] = model_one;
}
}
// populate primitive sets
for(j=0; j<numRows-1; ++j)
{
osg::DrawElementsUInt* elements = new osg::DrawElementsUInt(GL_TRIANGLE_STRIP, numColumns*2);
for(unsigned int i=0; i<numColumns; ++i)
{
unsigned int iv = j*numColumns + i;
(*elements)[i*2] = iv + numColumns;
(*elements)[i*2+1] = iv;
}
_geometry->addPrimitiveSet(elements);
}
osgUtil::SmoothingVisitor smoother;
_geode->accept(smoother);
if (colorLayer)
{
osgTerrain::ImageLayer* imageLayer = dynamic_cast<osgTerrain::ImageLayer*>(colorLayer);
if (imageLayer)
{
osg::Image* image = imageLayer->getImage();
osg::StateSet* stateset = _geode->getOrCreateStateSet();
osg::Texture2D* texture2D = new osg::Texture2D;
texture2D->setImage(image);
texture2D->setResizeNonPowerOfTwoHint(false);
stateset->setTextureAttributeAndModes(color_index, texture2D, osg::StateAttribute::ON);
if (tf)
{
// up the precision of hte internal texture format to its maximum.
//image->setInternalTextureFormat(GL_LUMINANCE32F_ARB);
image->setInternalTextureFormat(GL_LUMINANCE16);
}
}
}
if (tf)
{
osg::notify(osg::NOTICE)<<"Requires TransferFunction"<<std::endl;
osg::Image* image = tf->getImage();
osg::StateSet* stateset = _geode->getOrCreateStateSet();
osg::Texture1D* texture1D = new osg::Texture1D;
texture1D->setImage(image);
texture1D->setResizeNonPowerOfTwoHint(false);
texture1D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
texture1D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
stateset->setTextureAttributeAndModes(tf_index, texture1D, osg::StateAttribute::ON);
if (colorLayer)
{
osg::notify(osg::NOTICE)<<"Using fragment program"<<std::endl;
osg::Program* program = new osg::Program;
stateset->setAttribute(program);
// get shaders from source
std::string vertexShaderFile = osgDB::findDataFile("lookup.vert");
if (!vertexShaderFile.empty())
{
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, vertexShaderFile));
}
else
{
osg::notify(osg::NOTICE)<<"Not found lookup.vert"<<std::endl;
}
std::string fragmentShaderFile = osgDB::findDataFile("lookup.frag");
if (!fragmentShaderFile.empty())
{
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, fragmentShaderFile));
}
else
{
osg::notify(osg::NOTICE)<<"Not found lookup.frag"<<std::endl;
}
osg::Uniform* sourceSampler = new osg::Uniform("sourceTexture",color_index);
stateset->addUniform(sourceSampler);
osg::Uniform* lookupTexture = new osg::Uniform("lookupTexture",tf_index);
stateset->addUniform(lookupTexture);
osg::Uniform* minValue = new osg::Uniform("minValue", tf->getMinimum());
stateset->addUniform(minValue);
osg::Uniform* inverseRange = new osg::Uniform("inverseRange", 1.0f/(tf->getMaximum()-tf->getMinimum()));
stateset->addUniform(inverseRange);
}
else
{
osg::notify(osg::NOTICE)<<"Using standard OpenGL fixed function pipeline"<<std::endl;
}
}
_dirty = false;
}
void GeometryTechnique::update(osgUtil::UpdateVisitor* nv)
{
}
void GeometryTechnique::cull(osgUtil::CullVisitor* nv)
{
if (_geode.valid())
{
_geode->accept(*nv);
}
}
void GeometryTechnique::cleanSceneGraph()
{
}
void GeometryTechnique::dirty()
{
TerrainTechnique::dirty();
}
<|endoftext|> |
<commit_before>// Copyright (C) 2018 Egor Pugin <egor.pugin@gmail.com>
//
// 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/.
#include <primitives/exceptions.h>
#ifdef USE_STACKTRACE
#include <boost/stacktrace.hpp>
#endif
#include <primitives/debug.h>
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
bool gUseStackTrace;
bool gDebugOnException;
std::string gSymbolPath;
#ifdef USE_STACKTRACE
#ifdef _WIN32
#include "exceptions_msvc.h"
#endif
#endif
using namespace std::chrono_literals;
namespace sw
{
namespace detail
{
BaseException::BaseException(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: file(file), function(function), line(line), message(msg)
{
#ifdef USE_STACKTRACE
if (stacktrace && gUseStackTrace)
{
// skip 3 frames
// -1 means till the end
boost::stacktrace::stacktrace t(3, -1);
message += "\nStacktrace:\n";
#ifdef _WIN32
message += ::to_string(t);
#else
std::ostringstream ss;
ss << t;
message += ss.str();
#endif
}
#endif
}
const char *BaseException::getMessage() const
{
if (what_.empty())
what_ = format();
return what_.c_str();
}
std::string BaseException::format() const
{
std::string s;
//s += ex_type;
#ifdef USE_STACKTRACE
//s += "Exception: " + message; // disabled for now, too poor :(
#else
#endif
if (file.empty() && function.empty() && line == 0)
s += "Exception: " + message;
else
s += "Exception in file " + file + ":" + std::to_string(line) + ", function " + function + ": " + message;
return s;
}
}
Exception::Exception(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: BaseException(file, function, line, msg, stacktrace), std::exception(
#ifdef _MSC_VER
getMessage()
#endif
)
{
}
static void doe(const std::string &msg)
{
if (!gDebugOnException)
return;
std::cerr << msg << "\n";
std::cerr << "Waiting for debugger..." << "\n";
while (!primitives::isDebuggerAttached())
std::this_thread::sleep_for(100ms);
}
RuntimeError::RuntimeError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: BaseException
//Exception
(file, function, line, msg, stacktrace), std::runtime_error(getMessage())
{
doe(getMessage());
}
LogicError::LogicError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: BaseException
//Exception
(file, function, line, msg, stacktrace), std::logic_error(getMessage())
{
doe(getMessage());
}
} // namespace sw
<commit_msg>Do not print message when debugger is attached and doe turned on.<commit_after>// Copyright (C) 2018 Egor Pugin <egor.pugin@gmail.com>
//
// 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/.
#include <primitives/exceptions.h>
#ifdef USE_STACKTRACE
#include <boost/stacktrace.hpp>
#endif
#include <primitives/debug.h>
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
bool gUseStackTrace;
bool gDebugOnException;
std::string gSymbolPath;
#ifdef USE_STACKTRACE
#ifdef _WIN32
#include "exceptions_msvc.h"
#endif
#endif
using namespace std::chrono_literals;
namespace sw
{
namespace detail
{
BaseException::BaseException(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: file(file), function(function), line(line), message(msg)
{
#ifdef USE_STACKTRACE
if (stacktrace && gUseStackTrace)
{
// skip 3 frames
// -1 means till the end
boost::stacktrace::stacktrace t(3, -1);
message += "\nStacktrace:\n";
#ifdef _WIN32
message += ::to_string(t);
#else
std::ostringstream ss;
ss << t;
message += ss.str();
#endif
}
#endif
}
const char *BaseException::getMessage() const
{
if (what_.empty())
what_ = format();
return what_.c_str();
}
std::string BaseException::format() const
{
std::string s;
//s += ex_type;
#ifdef USE_STACKTRACE
//s += "Exception: " + message; // disabled for now, too poor :(
#else
#endif
if (file.empty() && function.empty() && line == 0)
s += "Exception: " + message;
else
s += "Exception in file " + file + ":" + std::to_string(line) + ", function " + function + ": " + message;
return s;
}
}
Exception::Exception(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: BaseException(file, function, line, msg, stacktrace), std::exception(
#ifdef _MSC_VER
getMessage()
#endif
)
{
}
static void doe(const std::string &msg)
{
if (!gDebugOnException)
return;
if (primitives::isDebuggerAttached())
return;
std::cerr << msg << "\n";
std::cerr << "Waiting for debugger..." << "\n";
while (!primitives::isDebuggerAttached())
std::this_thread::sleep_for(100ms);
}
RuntimeError::RuntimeError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: BaseException
//Exception
(file, function, line, msg, stacktrace), std::runtime_error(getMessage())
{
doe(getMessage());
}
LogicError::LogicError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
: BaseException
//Exception
(file, function, line, msg, stacktrace), std::logic_error(getMessage())
{
doe(getMessage());
}
} // namespace sw
<|endoftext|> |
<commit_before>//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h"
#include <string>
namespace clang {
namespace tooling {
namespace {
/// Takes an ast consumer and returns it from CreateASTConsumer. This only
/// works with single translation unit compilations.
class TestAction : public clang::ASTFrontendAction {
public:
/// Takes ownership of TestConsumer.
explicit TestAction(clang::ASTConsumer *TestConsumer)
: TestConsumer(TestConsumer) {}
protected:
virtual clang::ASTConsumer* CreateASTConsumer(
clang::CompilerInstance& compiler, StringRef dummy) {
/// TestConsumer will be deleted by the framework calling us.
return TestConsumer;
}
private:
clang::ASTConsumer * const TestConsumer;
};
class FindTopLevelDeclConsumer : public clang::ASTConsumer {
public:
explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
: FoundTopLevelDecl(FoundTopLevelDecl) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) {
*FoundTopLevelDecl = true;
return true;
}
private:
bool * const FoundTopLevelDecl;
};
} // end namespace
TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
bool FoundTopLevelDecl = false;
EXPECT_TRUE(runToolOnCode(
new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), ""));
EXPECT_FALSE(FoundTopLevelDecl);
}
namespace {
class FindClassDeclXConsumer : public clang::ASTConsumer {
public:
FindClassDeclXConsumer(bool *FoundClassDeclX)
: FoundClassDeclX(FoundClassDeclX) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
*GroupRef.begin())) {
if (Record->getName() == "X") {
*FoundClassDeclX = true;
}
}
return true;
}
private:
bool *FoundClassDeclX;
};
bool FindClassDeclX(ASTUnit *AST) {
for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
e = AST->top_level_end();
i != e; ++i) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
if (Record->getName() == "X") {
return true;
}
}
}
return false;
}
} // end namespace
TEST(runToolOnCode, FindsClassDecl) {
bool FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;"));
EXPECT_TRUE(FoundClassDeclX);
FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;"));
EXPECT_FALSE(FoundClassDeclX);
}
TEST(buildASTFromCode, FindsClassDecl) {
OwningPtr<ASTUnit> AST(buildASTFromCode("class X;"));
ASSERT_TRUE(AST.get());
EXPECT_TRUE(FindClassDeclX(AST.get()));
AST.reset(buildASTFromCode("class Y;"));
ASSERT_TRUE(AST.get());
EXPECT_FALSE(FindClassDeclX(AST.get()));
}
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory<SyntaxOnlyAction>());
OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
struct IndependentFrontendActionCreator {
ASTConsumer *newASTConsumer() {
return new FindTopLevelDeclConsumer(NULL);
}
};
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
IndependentFrontendActionCreator Creator;
OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Creator));
OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
TEST(ToolInvocation, TestMapVirtualFile) {
IntrusiveRefCntPtr<clang::FileManager> Files(
new clang::FileManager(clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Files.getPtr());
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
EXPECT_TRUE(Invocation.run());
}
TEST(ToolInvocation, TestVirtualModulesCompilation) {
// FIXME: Currently, this only tests that we don't exit with an error if a
// mapped module.map is found on the include path. In the future, expand this
// test to run a full modules enabled compilation, so we make sure we can
// rerun modules compilations with a virtual file system.
IntrusiveRefCntPtr<clang::FileManager> Files(
new clang::FileManager(clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Files.getPtr());
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
// Add a module.map file in the include directory of our header, so we trigger
// the module.map header search logic.
Invocation.mapVirtualFile("def/module.map", "\n");
EXPECT_TRUE(Invocation.run());
}
struct VerifyEndCallback : public SourceFileCallbacks {
VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
virtual bool handleBeginSource(CompilerInstance &CI,
StringRef Filename) override {
++BeginCalled;
return true;
}
virtual void handleEndSource() {
++EndCalled;
}
ASTConsumer *newASTConsumer() {
return new FindTopLevelDeclConsumer(&Matched);
}
unsigned BeginCalled;
unsigned EndCalled;
bool Matched;
};
#if !defined(_WIN32)
TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
VerifyEndCallback EndCallback;
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
std::vector<std::string> Sources;
Sources.push_back("/a.cc");
Sources.push_back("/b.cc");
ClangTool Tool(Compilations, Sources);
Tool.mapVirtualFile("/a.cc", "void a() {}");
Tool.mapVirtualFile("/b.cc", "void b() {}");
Tool.run(newFrontendActionFactory(&EndCallback, &EndCallback));
EXPECT_TRUE(EndCallback.Matched);
EXPECT_EQ(2u, EndCallback.BeginCalled);
EXPECT_EQ(2u, EndCallback.EndCalled);
}
#endif
struct SkipBodyConsumer : public clang::ASTConsumer {
/// Skip the 'skipMe' function.
virtual bool shouldSkipFunctionBody(Decl *D) {
FunctionDecl *F = dyn_cast<FunctionDecl>(D);
return F && F->getNameAsString() == "skipMe";
}
};
struct SkipBodyAction : public clang::ASTFrontendAction {
virtual ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler,
StringRef) {
Compiler.getFrontendOpts().SkipFunctionBodies = true;
return new SkipBodyConsumer;
}
};
TEST(runToolOnCode, TestSkipFunctionBody) {
EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
"int skipMe() { an_error_here }"));
EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
"int skipMeNot() { an_error_here }"));
}
TEST(runToolOnCodeWithArgs, TestNoDepFile) {
llvm::SmallString<32> DepFilePath;
ASSERT_FALSE(
llvm::sys::fs::createTemporaryFile("depfile", "d", DepFilePath));
std::vector<std::string> Args = { "-MMD", "-MT", DepFilePath.str(), "-MF",
DepFilePath.str() };
EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args));
EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
}
struct CheckSyntaxOnlyAdjuster: public ArgumentsAdjuster {
bool &Found;
bool &Ran;
CheckSyntaxOnlyAdjuster(bool &Found, bool &Ran) : Found(Found), Ran(Ran) { }
virtual CommandLineArguments
Adjust(const CommandLineArguments &Args) override {
Ran = true;
for (unsigned I = 0, E = Args.size(); I != E; ++I) {
if (Args[I] == "-fsyntax-only") {
Found = true;
break;
}
}
return Args;
}
};
TEST(ClangToolTest, ArgumentAdjusters) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "void a() {}");
bool Found = false;
bool Ran = false;
Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
Tool.run(newFrontendActionFactory<SyntaxOnlyAction>());
EXPECT_TRUE(Ran);
EXPECT_TRUE(Found);
Ran = Found = false;
Tool.clearArgumentsAdjusters();
Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
Tool.appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster());
Tool.run(newFrontendActionFactory<SyntaxOnlyAction>());
EXPECT_TRUE(Ran);
EXPECT_FALSE(Found);
}
#ifndef _WIN32
TEST(ClangToolTest, BuildASTs) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
std::vector<std::string> Sources;
Sources.push_back("/a.cc");
Sources.push_back("/b.cc");
ClangTool Tool(Compilations, Sources);
Tool.mapVirtualFile("/a.cc", "void a() {}");
Tool.mapVirtualFile("/b.cc", "void b() {}");
std::vector<ASTUnit *> ASTs;
EXPECT_EQ(0, Tool.buildASTs(ASTs));
EXPECT_EQ(2u, ASTs.size());
llvm::DeleteContainerPointers(ASTs);
}
struct TestDiagnosticConsumer : public DiagnosticConsumer {
TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Info) {
++NumDiagnosticsSeen;
}
unsigned NumDiagnosticsSeen;
};
TEST(ClangToolTest, InjectDiagnosticConsumer) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
TestDiagnosticConsumer Consumer;
Tool.setDiagnosticConsumer(&Consumer);
Tool.run(newFrontendActionFactory<SyntaxOnlyAction>());
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
TestDiagnosticConsumer Consumer;
Tool.setDiagnosticConsumer(&Consumer);
std::vector<ASTUnit*> ASTs;
Tool.buildASTs(ASTs);
EXPECT_EQ(1u, ASTs.size());
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
#endif
} // end namespace tooling
} // end namespace clang
<commit_msg>MSVC 2012 doesn't support std::initializer_list at all, so don't rely on that std::vector constructor.<commit_after>//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h"
#include <string>
namespace clang {
namespace tooling {
namespace {
/// Takes an ast consumer and returns it from CreateASTConsumer. This only
/// works with single translation unit compilations.
class TestAction : public clang::ASTFrontendAction {
public:
/// Takes ownership of TestConsumer.
explicit TestAction(clang::ASTConsumer *TestConsumer)
: TestConsumer(TestConsumer) {}
protected:
virtual clang::ASTConsumer* CreateASTConsumer(
clang::CompilerInstance& compiler, StringRef dummy) {
/// TestConsumer will be deleted by the framework calling us.
return TestConsumer;
}
private:
clang::ASTConsumer * const TestConsumer;
};
class FindTopLevelDeclConsumer : public clang::ASTConsumer {
public:
explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
: FoundTopLevelDecl(FoundTopLevelDecl) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) {
*FoundTopLevelDecl = true;
return true;
}
private:
bool * const FoundTopLevelDecl;
};
} // end namespace
TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
bool FoundTopLevelDecl = false;
EXPECT_TRUE(runToolOnCode(
new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), ""));
EXPECT_FALSE(FoundTopLevelDecl);
}
namespace {
class FindClassDeclXConsumer : public clang::ASTConsumer {
public:
FindClassDeclXConsumer(bool *FoundClassDeclX)
: FoundClassDeclX(FoundClassDeclX) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
*GroupRef.begin())) {
if (Record->getName() == "X") {
*FoundClassDeclX = true;
}
}
return true;
}
private:
bool *FoundClassDeclX;
};
bool FindClassDeclX(ASTUnit *AST) {
for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
e = AST->top_level_end();
i != e; ++i) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
if (Record->getName() == "X") {
return true;
}
}
}
return false;
}
} // end namespace
TEST(runToolOnCode, FindsClassDecl) {
bool FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;"));
EXPECT_TRUE(FoundClassDeclX);
FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;"));
EXPECT_FALSE(FoundClassDeclX);
}
TEST(buildASTFromCode, FindsClassDecl) {
OwningPtr<ASTUnit> AST(buildASTFromCode("class X;"));
ASSERT_TRUE(AST.get());
EXPECT_TRUE(FindClassDeclX(AST.get()));
AST.reset(buildASTFromCode("class Y;"));
ASSERT_TRUE(AST.get());
EXPECT_FALSE(FindClassDeclX(AST.get()));
}
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory<SyntaxOnlyAction>());
OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
struct IndependentFrontendActionCreator {
ASTConsumer *newASTConsumer() {
return new FindTopLevelDeclConsumer(NULL);
}
};
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
IndependentFrontendActionCreator Creator;
OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Creator));
OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
TEST(ToolInvocation, TestMapVirtualFile) {
IntrusiveRefCntPtr<clang::FileManager> Files(
new clang::FileManager(clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Files.getPtr());
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
EXPECT_TRUE(Invocation.run());
}
TEST(ToolInvocation, TestVirtualModulesCompilation) {
// FIXME: Currently, this only tests that we don't exit with an error if a
// mapped module.map is found on the include path. In the future, expand this
// test to run a full modules enabled compilation, so we make sure we can
// rerun modules compilations with a virtual file system.
IntrusiveRefCntPtr<clang::FileManager> Files(
new clang::FileManager(clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Files.getPtr());
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
// Add a module.map file in the include directory of our header, so we trigger
// the module.map header search logic.
Invocation.mapVirtualFile("def/module.map", "\n");
EXPECT_TRUE(Invocation.run());
}
struct VerifyEndCallback : public SourceFileCallbacks {
VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
virtual bool handleBeginSource(CompilerInstance &CI,
StringRef Filename) override {
++BeginCalled;
return true;
}
virtual void handleEndSource() {
++EndCalled;
}
ASTConsumer *newASTConsumer() {
return new FindTopLevelDeclConsumer(&Matched);
}
unsigned BeginCalled;
unsigned EndCalled;
bool Matched;
};
#if !defined(_WIN32)
TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
VerifyEndCallback EndCallback;
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
std::vector<std::string> Sources;
Sources.push_back("/a.cc");
Sources.push_back("/b.cc");
ClangTool Tool(Compilations, Sources);
Tool.mapVirtualFile("/a.cc", "void a() {}");
Tool.mapVirtualFile("/b.cc", "void b() {}");
Tool.run(newFrontendActionFactory(&EndCallback, &EndCallback));
EXPECT_TRUE(EndCallback.Matched);
EXPECT_EQ(2u, EndCallback.BeginCalled);
EXPECT_EQ(2u, EndCallback.EndCalled);
}
#endif
struct SkipBodyConsumer : public clang::ASTConsumer {
/// Skip the 'skipMe' function.
virtual bool shouldSkipFunctionBody(Decl *D) {
FunctionDecl *F = dyn_cast<FunctionDecl>(D);
return F && F->getNameAsString() == "skipMe";
}
};
struct SkipBodyAction : public clang::ASTFrontendAction {
virtual ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler,
StringRef) {
Compiler.getFrontendOpts().SkipFunctionBodies = true;
return new SkipBodyConsumer;
}
};
TEST(runToolOnCode, TestSkipFunctionBody) {
EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
"int skipMe() { an_error_here }"));
EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
"int skipMeNot() { an_error_here }"));
}
TEST(runToolOnCodeWithArgs, TestNoDepFile) {
llvm::SmallString<32> DepFilePath;
ASSERT_FALSE(
llvm::sys::fs::createTemporaryFile("depfile", "d", DepFilePath));
std::vector<std::string> Args;
Args.push_back("-MMD");
Args.push_back("-MT");
Args.push_back(DepFilePath.str());
Args.push_back("-MF");
Args.push_back(DepFilePath.str());
EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args));
EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
}
struct CheckSyntaxOnlyAdjuster: public ArgumentsAdjuster {
bool &Found;
bool &Ran;
CheckSyntaxOnlyAdjuster(bool &Found, bool &Ran) : Found(Found), Ran(Ran) { }
virtual CommandLineArguments
Adjust(const CommandLineArguments &Args) override {
Ran = true;
for (unsigned I = 0, E = Args.size(); I != E; ++I) {
if (Args[I] == "-fsyntax-only") {
Found = true;
break;
}
}
return Args;
}
};
TEST(ClangToolTest, ArgumentAdjusters) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "void a() {}");
bool Found = false;
bool Ran = false;
Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
Tool.run(newFrontendActionFactory<SyntaxOnlyAction>());
EXPECT_TRUE(Ran);
EXPECT_TRUE(Found);
Ran = Found = false;
Tool.clearArgumentsAdjusters();
Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
Tool.appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster());
Tool.run(newFrontendActionFactory<SyntaxOnlyAction>());
EXPECT_TRUE(Ran);
EXPECT_FALSE(Found);
}
#ifndef _WIN32
TEST(ClangToolTest, BuildASTs) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
std::vector<std::string> Sources;
Sources.push_back("/a.cc");
Sources.push_back("/b.cc");
ClangTool Tool(Compilations, Sources);
Tool.mapVirtualFile("/a.cc", "void a() {}");
Tool.mapVirtualFile("/b.cc", "void b() {}");
std::vector<ASTUnit *> ASTs;
EXPECT_EQ(0, Tool.buildASTs(ASTs));
EXPECT_EQ(2u, ASTs.size());
llvm::DeleteContainerPointers(ASTs);
}
struct TestDiagnosticConsumer : public DiagnosticConsumer {
TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Info) {
++NumDiagnosticsSeen;
}
unsigned NumDiagnosticsSeen;
};
TEST(ClangToolTest, InjectDiagnosticConsumer) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
TestDiagnosticConsumer Consumer;
Tool.setDiagnosticConsumer(&Consumer);
Tool.run(newFrontendActionFactory<SyntaxOnlyAction>());
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
TestDiagnosticConsumer Consumer;
Tool.setDiagnosticConsumer(&Consumer);
std::vector<ASTUnit*> ASTs;
Tool.buildASTs(ASTs);
EXPECT_EQ(1u, ASTs.size());
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
#endif
} // end namespace tooling
} // end namespace clang
<|endoftext|> |
<commit_before>#ifndef TEST__PERFORMANCE__UTILITY_HPP
#define TEST__PERFORMANCE__UTILITY_HPP
#include <stdexcept>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/uniform_real_distribution.hpp>
#include <stan/model/gradient.hpp>
#include <stan/services/sample/hmc_nuts_diag_e_adapt.hpp>
#include <stan/io/empty_var_context.hpp>
#include <stan/callbacks/interrupt.hpp>
#include <stan/callbacks/stream_writer.hpp>
#include <stan/callbacks/writer.hpp>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
namespace stan {
namespace test {
namespace performance {
struct run_command_output {
std::string command;
std::string output;
long time;
int err_code;
bool hasError;
std::string header;
std::string body;
run_command_output(const std::string command,
const std::string output,
const long time,
const int err_code)
: command(command),
output(output),
time(time),
err_code(err_code),
hasError(err_code != 0),
header(),
body()
{
size_t end_of_header = output.find("\n\n");
if (end_of_header == std::string::npos)
end_of_header = 0;
else
end_of_header += 2;
header = output.substr(0, end_of_header);
body = output.substr(end_of_header);
}
run_command_output()
: command(),
output(),
time(0),
err_code(0),
hasError(false),
header(),
body()
{ }
};
std::ostream& operator<<(std::ostream& os, const run_command_output& out) {
os << "run_command output:" << "\n"
<< "- command: " << out.command << "\n"
<< "- output: " << out.output << "\n"
<< "- time (ms): " << out.time << "\n"
<< "- err_code: " << out.err_code << "\n"
<< "- hasError: " << (out.hasError ? "true" : "false") << "\n"
<< "- header: " << out.header << "\n"
<< "- body: " << out.body << std::endl;
return os;
}
/**
* Runs the command provided and returns the system output
* as a string.
*
* @param command A command that can be run from the shell
* @return the system output of the command
*/
run_command_output run_command(std::string command) {
using boost::posix_time::ptime;
using boost::posix_time::microsec_clock;
FILE *in;
std::string new_command = command + " 2>&1";
// captures both cout amd err
in = popen(command.c_str(), "r");
if(!in) {
std::string err_msg;
err_msg = "Fatal error with popen; could not execute: \"";
err_msg+= command;
err_msg+= "\"";
throw std::runtime_error(err_msg.c_str());
}
std::string output;
char buf[1024];
size_t count;
ptime time_start(microsec_clock::universal_time()); // start timer
while ((count = fread(&buf, 1, 1024, in)) > 0)
output += std::string(&buf[0], &buf[count]);
ptime time_end(microsec_clock::universal_time()); // end timer
// bits 15-8 is err code, bit 7 if core dump, bits 6-0 is signal number
int err_code = pclose(in);
// on Windows, err code is the return code.
if (err_code != 0 && (err_code >> 8) > 0)
err_code >>= 8;
return run_command_output(command, output,
(time_end - time_start).total_milliseconds(),
err_code);
}
std::vector<double> get_last_iteration_from_file(const char* filename) {
std::vector<double> draw;
const char comment = '#';
std::ifstream file_stream(filename);
std::string line;
std::string last_values;
while (std::getline(file_stream, line)) {
if (line.length() > 0 && line[0] != comment)
last_values = line;
}
std::stringstream values_stream(last_values);
std::vector<std::string> values;
std::string value;
while (std::getline(values_stream, value, ','))
values.push_back(value);
draw.resize(values.size());
for (size_t n = 0; n < draw.size(); ++n) {
draw[n] = atof(values[n].c_str());
}
return draw;
}
template <typename T>
std::string quote(const T& val) {
std::stringstream quoted_val;
quoted_val << "\""
<< val
<< "\"";
return quoted_val.str();
}
std::string get_git_hash() {
run_command_output git_hash = run_command("git rev-parse HEAD");
if (git_hash.hasError)
return "NA";
boost::trim(git_hash.body);
return git_hash.body;
}
std::string get_git_date() {
run_command_output git_date_command
= run_command("git log --format=%ct -1");
if (git_date_command.hasError)
return "NA";
boost::trim(git_date_command.body);
long timestamp = atol(git_date_command.body.c_str());
std::time_t git_date(timestamp);
std::stringstream date_ss;
date_ss << std::ctime(&git_date);
std::string date;
date = date_ss.str();
boost::trim(date);
return date;
}
std::string get_date() {
std::time_t curr_date;
time(&curr_date);
std::stringstream date_ss;
date_ss << std::ctime(&curr_date);
std::string date;
date = date_ss.str();
boost::trim(date);
return date;
}
template <class Model>
int command(int num_warmup,
int num_samples,
const std::string data_file,
const std::string output_file,
unsigned int random_seed) {
// Data input
std::fstream data_stream(data_file.c_str(),
std::fstream::in);
stan::io::dump data_var_context(data_stream);
data_stream.close();
// Sample output
callbacks::writer init_writer;
callbacks::stream_writer info(std::cout, "# ");
callbacks::stream_writer err(std::cerr);
std::fstream output_stream(output_file.c_str(), std::fstream::out);
callbacks::stream_writer sample_writer(output_stream, "# ");
callbacks::writer diagnostic_writer;
callbacks::interrupt interrupt;
Model model(data_var_context, &std::cout);
stan::io::empty_var_context init_context;
double init_radius = 0;
int id = 0;
int num_thin = 1;
bool save_warmup = false;
int refresh = num_samples;
double stepsize = 1.0;
double stepsize_jitter = 0.0;
int max_depth = 10;
double delta = 0.8;
double gamma = 0.05;
double kappa = 0.75;
double t0 = 10;
int init_buffer = 75;
int term_buffer = 50;
int window = 25;
return stan::services::sample::hmc_nuts_diag_e_adapt(model,
init_context,
random_seed,
id,
init_radius,
num_warmup,
num_samples,
num_thin,
save_warmup,
refresh,
stepsize,
stepsize_jitter,
max_depth,
delta,
gamma,
kappa,
t0,
init_buffer,
term_buffer,
window,
interrupt,
info,
err,
init_writer,
sample_writer,
diagnostic_writer);
}
}
}
}
#endif
<commit_msg>Fixing src/test/performance<commit_after>#ifndef TEST__PERFORMANCE__UTILITY_HPP
#define TEST__PERFORMANCE__UTILITY_HPP
#include <stdexcept>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/uniform_real_distribution.hpp>
#include <stan/model/gradient.hpp>
#include <stan/services/sample/hmc_nuts_diag_e_adapt.hpp>
#include <stan/io/empty_var_context.hpp>
#include <stan/callbacks/interrupt.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <stan/callbacks/stream_writer.hpp>
#include <stan/callbacks/writer.hpp>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
namespace stan {
namespace test {
namespace performance {
struct run_command_output {
std::string command;
std::string output;
long time;
int err_code;
bool hasError;
std::string header;
std::string body;
run_command_output(const std::string command,
const std::string output,
const long time,
const int err_code)
: command(command),
output(output),
time(time),
err_code(err_code),
hasError(err_code != 0),
header(),
body()
{
size_t end_of_header = output.find("\n\n");
if (end_of_header == std::string::npos)
end_of_header = 0;
else
end_of_header += 2;
header = output.substr(0, end_of_header);
body = output.substr(end_of_header);
}
run_command_output()
: command(),
output(),
time(0),
err_code(0),
hasError(false),
header(),
body()
{ }
};
std::ostream& operator<<(std::ostream& os, const run_command_output& out) {
os << "run_command output:" << "\n"
<< "- command: " << out.command << "\n"
<< "- output: " << out.output << "\n"
<< "- time (ms): " << out.time << "\n"
<< "- err_code: " << out.err_code << "\n"
<< "- hasError: " << (out.hasError ? "true" : "false") << "\n"
<< "- header: " << out.header << "\n"
<< "- body: " << out.body << std::endl;
return os;
}
/**
* Runs the command provided and returns the system output
* as a string.
*
* @param command A command that can be run from the shell
* @return the system output of the command
*/
run_command_output run_command(std::string command) {
using boost::posix_time::ptime;
using boost::posix_time::microsec_clock;
FILE *in;
std::string new_command = command + " 2>&1";
// captures both cout amd err
in = popen(command.c_str(), "r");
if(!in) {
std::string err_msg;
err_msg = "Fatal error with popen; could not execute: \"";
err_msg+= command;
err_msg+= "\"";
throw std::runtime_error(err_msg.c_str());
}
std::string output;
char buf[1024];
size_t count;
ptime time_start(microsec_clock::universal_time()); // start timer
while ((count = fread(&buf, 1, 1024, in)) > 0)
output += std::string(&buf[0], &buf[count]);
ptime time_end(microsec_clock::universal_time()); // end timer
// bits 15-8 is err code, bit 7 if core dump, bits 6-0 is signal number
int err_code = pclose(in);
// on Windows, err code is the return code.
if (err_code != 0 && (err_code >> 8) > 0)
err_code >>= 8;
return run_command_output(command, output,
(time_end - time_start).total_milliseconds(),
err_code);
}
std::vector<double> get_last_iteration_from_file(const char* filename) {
std::vector<double> draw;
const char comment = '#';
std::ifstream file_stream(filename);
std::string line;
std::string last_values;
while (std::getline(file_stream, line)) {
if (line.length() > 0 && line[0] != comment)
last_values = line;
}
std::stringstream values_stream(last_values);
std::vector<std::string> values;
std::string value;
while (std::getline(values_stream, value, ','))
values.push_back(value);
draw.resize(values.size());
for (size_t n = 0; n < draw.size(); ++n) {
draw[n] = atof(values[n].c_str());
}
return draw;
}
template <typename T>
std::string quote(const T& val) {
std::stringstream quoted_val;
quoted_val << "\""
<< val
<< "\"";
return quoted_val.str();
}
std::string get_git_hash() {
run_command_output git_hash = run_command("git rev-parse HEAD");
if (git_hash.hasError)
return "NA";
boost::trim(git_hash.body);
return git_hash.body;
}
std::string get_git_date() {
run_command_output git_date_command
= run_command("git log --format=%ct -1");
if (git_date_command.hasError)
return "NA";
boost::trim(git_date_command.body);
long timestamp = atol(git_date_command.body.c_str());
std::time_t git_date(timestamp);
std::stringstream date_ss;
date_ss << std::ctime(&git_date);
std::string date;
date = date_ss.str();
boost::trim(date);
return date;
}
std::string get_date() {
std::time_t curr_date;
time(&curr_date);
std::stringstream date_ss;
date_ss << std::ctime(&curr_date);
std::string date;
date = date_ss.str();
boost::trim(date);
return date;
}
template <class Model>
int command(int num_warmup,
int num_samples,
const std::string data_file,
const std::string output_file,
unsigned int random_seed) {
// Data input
std::fstream data_stream(data_file.c_str(),
std::fstream::in);
stan::io::dump data_var_context(data_stream);
data_stream.close();
// Sample output
callbacks::writer init_writer;
callbacks::stream_logger logger(std::cout, std::cout, std::cout, std::cerr, std::cerr);
std::fstream output_stream(output_file.c_str(), std::fstream::out);
callbacks::stream_writer sample_writer(output_stream, "# ");
callbacks::writer diagnostic_writer;
callbacks::interrupt interrupt;
Model model(data_var_context, &std::cout);
stan::io::empty_var_context init_context;
double init_radius = 0;
int id = 0;
int num_thin = 1;
bool save_warmup = false;
int refresh = num_samples;
double stepsize = 1.0;
double stepsize_jitter = 0.0;
int max_depth = 10;
double delta = 0.8;
double gamma = 0.05;
double kappa = 0.75;
double t0 = 10;
int init_buffer = 75;
int term_buffer = 50;
int window = 25;
return stan::services::sample::hmc_nuts_diag_e_adapt(model,
init_context,
random_seed,
id,
init_radius,
num_warmup,
num_samples,
num_thin,
save_warmup,
refresh,
stepsize,
stepsize_jitter,
max_depth,
delta,
gamma,
kappa,
t0,
init_buffer,
term_buffer,
window,
interrupt,
logger,
init_writer,
sample_writer,
diagnostic_writer);
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
anycmd.cpp - Total Commander lister plugin
Copyright (C) 2012-2013 by Serge Lamikhov-Center
MIT License
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.
*/
#define _CRT_SECURE_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <stdlib.h>
#include <shellapi.h>
#include <malloc.h>
#include <richedit.h>
#include <commdlg.h>
#include <math.h>
#include <algorithm>
#include <string>
#include "anycmd.h"
HINSTANCE hinst;
HWND listWin = 0;
std::string g_text;
std::string g_text_lo;
char inifilename[MAX_PATH]="anycmd.ini"; // Unused in this plugin,
// may be used to save data
char detect_string[MAX_PATH];
char command_string[MAX_PATH];
char cmd[MAX_PATH];
int streams = 3;
//---------------------------------------------------------------------------
static char*
strlcpy( char* p, char* p2, int maxlen )
{
strncpy( p, p2, maxlen );
p[maxlen] = 0;
return p;
}
//---------------------------------------------------------------------------
static void
searchAndReplace( std::string& value, std::string const& search,
std::string const& replace )
{
std::string::size_type next;
for ( next = value.find( search ); // Try and find the first match
next != std::string::npos; // next is npos if nothing was found
next = value.find( search, next ) // search for the next match starting after
// the last match that was found.
) {
// Inside the loop. So we found a match.
if ( next == 0 || value[next - 1] != '\r' ) {
value.replace( next, search.length(), replace ); // Do the replacement.
}
next += replace.length(); // Move to just after the replace
// This is the point were we start
// the next search from.
}
}
//---------------------------------------------------------------------------
void
find_and_substitute_env_vars( char* str, size_t size )
{
std::string work( str );
bool found = true;
std::basic_string <char>::size_type start_from = 0;
while ( found ) {
found = false;
// Find first occurrence of '%' sign
std::basic_string <char>::size_type first = work.find( '%', start_from );
if ( first != std::string::npos ) {
// Find second occurrence of '%' sign
std::basic_string <char>::size_type second = work.find( '%', first + 1 );
if ( second != std::string::npos ) {
found = true;
start_from = first + 1;
std::string var = work.substr( first + 1, second - first - 1 );
// Try to substitute the substring between two '%' signs
char buffer[MAX_PATH];
if ( GetEnvironmentVariable( var.c_str(), buffer, MAX_PATH ) != 0 ) {
buffer[MAX_PATH - 1] = 0;
work.replace( first, second - first + 1, buffer );
}
}
}
}
std::strncpy( str, work.c_str(), size );
str[size - 1] = 0;
}
//---------------------------------------------------------------------------
BOOL APIENTRY
DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
{
switch ( ul_reason_for_call )
{
case DLL_PROCESS_ATTACH:
hinst = (HINSTANCE)hModule;
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
//---------------------------------------------------------------------------
void APIENTRY
ListGetDetectString( char* detectString, int maxlen )
{
strlcpy( detectString, detect_string, maxlen );
}
//---------------------------------------------------------------------------
void APIENTRY
ListSetDefaultParams( ListDefaultParamStruct* dps )
{
dps->PluginInterfaceVersionHi = ANYELF_VERSION_HI;
dps->PluginInterfaceVersionLow = ANYELF_VERSION_LOW;
strlcpy( inifilename, dps->DefaultIniName, MAX_PATH-1 );
GetPrivateProfileString( "AnyCmd",
"DetectString",
"EXT=TXT",
detect_string,
sizeof( detect_string ),
dps->DefaultIniName );
GetPrivateProfileString( "AnyCmd",
"Command",
"sort.exe %s",
command_string,
sizeof( command_string ),
dps->DefaultIniName );
streams = GetPrivateProfileInt( "AnyCmd",
"Stream",
ANYCMD_CATCH_STD_OUT | ANYCMD_CATCH_STD_ERR,
dps->DefaultIniName );
if ( ( streams & ( ANYCMD_CATCH_STD_OUT | ANYCMD_CATCH_STD_ERR ) ) == 0 ) {
streams = ANYCMD_CATCH_STD_OUT | ANYCMD_CATCH_STD_ERR;
}
sprintf_s( cmd, "%d", streams );
WritePrivateProfileString( "AnyCmd",
"DetectString",
detect_string,
dps->DefaultIniName );
WritePrivateProfileString( "AnyCmd",
"Command",
command_string,
dps->DefaultIniName );
WritePrivateProfileString( "AnyCmd",
"Stream",
cmd,
dps->DefaultIniName );
// Substitute environment variables within the command
find_and_substitute_env_vars( command_string, sizeof( command_string ) );
}
//---------------------------------------------------------------------------
HWND APIENTRY
ListLoad( HWND parentWin, char* fileToLoad, int showFlags )
{
RECT r;
GetClientRect( parentWin, &r );
// Create window invisbile, only show when data fully loaded!
listWin = CreateWindow( "EDIT", "", WS_CHILD | ES_MULTILINE | ES_WANTRETURN |
ES_READONLY | WS_HSCROLL | WS_VSCROLL |
ES_AUTOVSCROLL | ES_NOHIDESEL,
r.left, r.top, r.right-r.left, r.bottom-r.top,
parentWin, NULL, hinst, NULL);
if ( listWin != 0 ) {
SendMessage( listWin, EM_SETMARGINS, EC_LEFTMARGIN, 8 );
SendMessage( listWin, EM_SETEVENTMASK, 0, ENM_UPDATE ); //ENM_SCROLL doesn't work for thumb movements!
ShowWindow( listWin, SW_SHOW );
int ret = ListLoadNext( parentWin, listWin, fileToLoad, showFlags );
if ( ret == LISTPLUGIN_ERROR ) {
DestroyWindow( listWin );
listWin = 0;
}
}
return listWin;
}
//---------------------------------------------------------------------------
int APIENTRY
ListLoadNext( HWND parentWin, HWND listWin, char* fileToLoad, int showFlags)
{
std::string cmd( command_string );
searchAndReplace( cmd, "%s", fileToLoad );
g_text = receive_text( cmd.c_str(), streams );
if ( g_text.empty() ) {
return LISTPLUGIN_ERROR;
}
searchAndReplace( g_text, "\n", "\r\n" );
g_text_lo.resize( g_text.length() );
std::transform( g_text.begin(), g_text.end(), g_text_lo.begin(), ::tolower );
HFONT font;
if ( showFlags & lcp_ansi ) {
font = (HFONT)GetStockObject( ANSI_FIXED_FONT );
}
else {
font = (HFONT)GetStockObject( SYSTEM_FIXED_FONT );
}
SendMessage( listWin, WM_SETFONT, (WPARAM)font, MAKELPARAM( true, 0 ) );
SendMessage( listWin, WM_SETTEXT, 0, (LPARAM)g_text.c_str() );
PostMessage( parentWin, WM_COMMAND, MAKELONG( 0, itm_percent ), (LPARAM)listWin );
return LISTPLUGIN_OK;
}
//---------------------------------------------------------------------------
void APIENTRY
ListCloseWindow( HWND listWin )
{
DestroyWindow( listWin );
return;
}
//---------------------------------------------------------------------------
int APIENTRY
ListNotificationReceived( HWND listWin, int message, WPARAM wParam, LPARAM lParam )
{
int firstvisible;
int linecount;
switch ( message ) {
case WM_COMMAND:
switch ( HIWORD( wParam ) ) {
case EN_UPDATE:
case EN_VSCROLL:
firstvisible = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
linecount = (int)SendMessage( listWin, EM_GETLINECOUNT, 0, 0 );
if ( linecount > 0 ) {
int percent = MulDiv( firstvisible, 100, linecount );
PostMessage( GetParent( listWin ), WM_COMMAND,
MAKELONG( percent, itm_percent ), (LPARAM)listWin );
}
return 0;
}
break;
case WM_NOTIFY:
break;
case WM_MEASUREITEM:
break;
case WM_DRAWITEM:
break;
}
return 0;
}
//---------------------------------------------------------------------------
int APIENTRY
ListSendCommand( HWND listWin, int command, int parameter )
{
switch ( command ) {
case lc_copy:
SendMessage( listWin, WM_COPY, 0, 0 );
return LISTPLUGIN_OK;
case lc_newparams:
HFONT font;
if ( parameter & lcp_ansi ) {
font = (HFONT)GetStockObject( ANSI_FIXED_FONT );
}
else {
font = (HFONT)GetStockObject( SYSTEM_FIXED_FONT );
}
SendMessage( listWin, WM_SETFONT, (WPARAM)font, MAKELPARAM( true, 0 ) );
PostMessage( GetParent( listWin ), WM_COMMAND, MAKELONG( 0, itm_next ), (LPARAM)listWin );
return LISTPLUGIN_ERROR;
case lc_selectall:
SendMessage( listWin, EM_SETSEL, 0, -1 );
return LISTPLUGIN_OK;
case lc_setpercent:
int firstvisible = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
int linecount = (int)SendMessage( listWin, EM_GETLINECOUNT, 0, 0 );
if ( linecount > 0 ) {
int pos = MulDiv( parameter, linecount, 100 );
SendMessage( listWin, EM_LINESCROLL, 0, pos - firstvisible );
firstvisible = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
// Place caret on first visible line!
int firstchar = (int)SendMessage( listWin, EM_LINEINDEX, firstvisible, 0);
SendMessage( listWin, EM_SETSEL, firstchar, firstchar );
pos = MulDiv( firstvisible, 100, linecount );
// Update percentage display
PostMessage( GetParent( listWin ), WM_COMMAND, MAKELONG( pos, itm_percent ), (LPARAM)listWin );
return LISTPLUGIN_OK;
}
break;
}
return LISTPLUGIN_ERROR;
}
//---------------------------------------------------------------------------
static int
find_string( std::string search, int start, int params )
{
std::string* text;
if ( !( params & lcs_matchcase ) ) {
text = &g_text_lo;
std::transform( search.begin(), search.end(), search.begin(), ::tolower );
}
else {
text = &g_text;
}
size_t pos;
do {
if ( params & lcs_backwards ) {
start = start - 1;
pos = text->rfind( search, start - 1 );
}
else {
pos = text->find( search, start );
start = (int)pos + 1;
}
} while ( ( pos != std::string::npos ) &&
( params & lcs_wholewords ) &&
( ::isalnum( (*text)[pos - 1] ) | ::isalnum( (*text)[pos + search.size()] ) ) );
if ( pos == std::string::npos ) {
return -1;
}
return (int)pos;
}
//---------------------------------------------------------------------------
int APIENTRY
ListSearchText( HWND listWin, char* searchString, int searchParameter )
{
int startPos;
if ( ( searchParameter & lcs_findfirst ) && !( searchParameter & lcs_backwards ) ) {
//Find first: Start at top visible line
int firstline = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
startPos = (int)SendMessage( listWin, EM_LINEINDEX, firstline, 0 );
SendMessage( listWin, EM_SETSEL, startPos, startPos );
} else {
//Find next: Start at current selection+1
SendMessage( listWin, EM_GETSEL, (WPARAM)&startPos, 0 );
++startPos;
}
int index = find_string( searchString, startPos, searchParameter );
if ( index != -1 ) {
int indexend = index + (int)strlen( searchString );
SendMessage( listWin, EM_SETSEL, index, indexend );
int line = (int)SendMessage( listWin, EM_LINEFROMCHAR, index, 0 ) - 3;
if ( line < 0 )
line = 0;
line -= (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
SendMessage( listWin, EM_LINESCROLL, 0, line );
return LISTPLUGIN_OK;
}
SendMessage( listWin, EM_SETSEL, -1, -1); // Restart search at the beginning
return LISTPLUGIN_ERROR;
}
<commit_msg>Use #define for repetitive strings<commit_after>/*
anycmd.cpp - Total Commander lister plugin
Copyright (C) 2012-2013 by Serge Lamikhov-Center
MIT License
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.
*/
#define _CRT_SECURE_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <stdlib.h>
#include <shellapi.h>
#include <malloc.h>
#include <richedit.h>
#include <commdlg.h>
#include <math.h>
#include <algorithm>
#include <string>
#include "anycmd.h"
#define PLUGIN_NAME "AnyCmd"
#define DETECT_STRING_KEY "DetectString"
#define COMMAND_STRING_KEY "Command"
#define STREAM_SELECT_KEY "Stream"
HINSTANCE hinst;
HWND listWin = 0;
std::string g_text;
std::string g_text_lo;
char inifilename[MAX_PATH]="anycmd.ini"; // Unused in this plugin,
// may be used to save data
char detect_string[MAX_PATH];
char command_string[MAX_PATH];
char cmd[MAX_PATH];
int streams = 3;
//---------------------------------------------------------------------------
static char*
strlcpy( char* p, char* p2, int maxlen )
{
strncpy( p, p2, maxlen );
p[maxlen] = 0;
return p;
}
//---------------------------------------------------------------------------
static void
searchAndReplace( std::string& value, std::string const& search,
std::string const& replace )
{
std::string::size_type next;
for ( next = value.find( search ); // Try and find the first match
next != std::string::npos; // next is npos if nothing was found
next = value.find( search, next ) // search for the next match starting after
// the last match that was found.
) {
// Inside the loop. So we found a match.
if ( next == 0 || value[next - 1] != '\r' ) {
value.replace( next, search.length(), replace ); // Do the replacement.
}
next += replace.length(); // Move to just after the replace
// This is the point were we start
// the next search from.
}
}
//---------------------------------------------------------------------------
void
find_and_substitute_env_vars( char* str, size_t size )
{
std::string work( str );
bool found = true;
std::basic_string <char>::size_type start_from = 0;
while ( found ) {
found = false;
// Find first occurrence of '%' sign
std::basic_string <char>::size_type first = work.find( '%', start_from );
if ( first != std::string::npos ) {
// Find second occurrence of '%' sign
std::basic_string <char>::size_type second = work.find( '%', first + 1 );
if ( second != std::string::npos ) {
found = true;
start_from = first + 1;
std::string var = work.substr( first + 1, second - first - 1 );
// Try to substitute the substring between two '%' signs
char buffer[MAX_PATH];
if ( GetEnvironmentVariable( var.c_str(), buffer, MAX_PATH ) != 0 ) {
buffer[MAX_PATH - 1] = 0;
work.replace( first, second - first + 1, buffer );
}
}
}
}
std::strncpy( str, work.c_str(), size );
str[size - 1] = 0;
}
//---------------------------------------------------------------------------
BOOL APIENTRY
DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
{
switch ( ul_reason_for_call )
{
case DLL_PROCESS_ATTACH:
hinst = (HINSTANCE)hModule;
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
//---------------------------------------------------------------------------
void APIENTRY
ListGetDetectString( char* detectString, int maxlen )
{
strlcpy( detectString, detect_string, maxlen );
}
//---------------------------------------------------------------------------
void APIENTRY
ListSetDefaultParams( ListDefaultParamStruct* dps )
{
dps->PluginInterfaceVersionHi = ANYELF_VERSION_HI;
dps->PluginInterfaceVersionLow = ANYELF_VERSION_LOW;
strlcpy( inifilename, dps->DefaultIniName, MAX_PATH-1 );
GetPrivateProfileString( PLUGIN_NAME,
DETECT_STRING_KEY,
"EXT=TXT",
detect_string,
sizeof( detect_string ),
dps->DefaultIniName );
GetPrivateProfileString( PLUGIN_NAME,
COMMAND_STRING_KEY,
"sort.exe %s",
command_string,
sizeof( command_string ),
dps->DefaultIniName );
streams = GetPrivateProfileInt( PLUGIN_NAME,
STREAM_SELECT_KEY,
ANYCMD_CATCH_STD_OUT | ANYCMD_CATCH_STD_ERR,
dps->DefaultIniName );
if ( ( streams & ( ANYCMD_CATCH_STD_OUT | ANYCMD_CATCH_STD_ERR ) ) == 0 ) {
streams = ANYCMD_CATCH_STD_OUT | ANYCMD_CATCH_STD_ERR;
}
sprintf_s( cmd, "%d", streams );
WritePrivateProfileString( PLUGIN_NAME,
DETECT_STRING_KEY,
detect_string,
dps->DefaultIniName );
WritePrivateProfileString( PLUGIN_NAME,
COMMAND_STRING_KEY,
command_string,
dps->DefaultIniName );
WritePrivateProfileString( PLUGIN_NAME,
STREAM_SELECT_KEY,
cmd,
dps->DefaultIniName );
// Substitute environment variables within the command
find_and_substitute_env_vars( command_string, sizeof( command_string ) );
}
//---------------------------------------------------------------------------
HWND APIENTRY
ListLoad( HWND parentWin, char* fileToLoad, int showFlags )
{
RECT r;
GetClientRect( parentWin, &r );
// Create window invisbile, only show when data fully loaded!
listWin = CreateWindow( "EDIT", "", WS_CHILD | ES_MULTILINE | ES_WANTRETURN |
ES_READONLY | WS_HSCROLL | WS_VSCROLL |
ES_AUTOVSCROLL | ES_NOHIDESEL,
r.left, r.top, r.right-r.left, r.bottom-r.top,
parentWin, NULL, hinst, NULL);
if ( listWin != 0 ) {
SendMessage( listWin, EM_SETMARGINS, EC_LEFTMARGIN, 8 );
SendMessage( listWin, EM_SETEVENTMASK, 0, ENM_UPDATE ); //ENM_SCROLL doesn't work for thumb movements!
ShowWindow( listWin, SW_SHOW );
int ret = ListLoadNext( parentWin, listWin, fileToLoad, showFlags );
if ( ret == LISTPLUGIN_ERROR ) {
DestroyWindow( listWin );
listWin = 0;
}
}
return listWin;
}
//---------------------------------------------------------------------------
int APIENTRY
ListLoadNext( HWND parentWin, HWND listWin, char* fileToLoad, int showFlags)
{
std::string cmd( command_string );
searchAndReplace( cmd, "%s", fileToLoad );
g_text = receive_text( cmd.c_str(), streams );
if ( g_text.empty() ) {
return LISTPLUGIN_ERROR;
}
searchAndReplace( g_text, "\n", "\r\n" );
g_text_lo.resize( g_text.length() );
std::transform( g_text.begin(), g_text.end(), g_text_lo.begin(), ::tolower );
HFONT font;
if ( showFlags & lcp_ansi ) {
font = (HFONT)GetStockObject( ANSI_FIXED_FONT );
}
else {
font = (HFONT)GetStockObject( SYSTEM_FIXED_FONT );
}
SendMessage( listWin, WM_SETFONT, (WPARAM)font, MAKELPARAM( true, 0 ) );
SendMessage( listWin, WM_SETTEXT, 0, (LPARAM)g_text.c_str() );
PostMessage( parentWin, WM_COMMAND, MAKELONG( 0, itm_percent ), (LPARAM)listWin );
return LISTPLUGIN_OK;
}
//---------------------------------------------------------------------------
void APIENTRY
ListCloseWindow( HWND listWin )
{
DestroyWindow( listWin );
return;
}
//---------------------------------------------------------------------------
int APIENTRY
ListNotificationReceived( HWND listWin, int message, WPARAM wParam, LPARAM lParam )
{
int firstvisible;
int linecount;
switch ( message ) {
case WM_COMMAND:
switch ( HIWORD( wParam ) ) {
case EN_UPDATE:
case EN_VSCROLL:
firstvisible = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
linecount = (int)SendMessage( listWin, EM_GETLINECOUNT, 0, 0 );
if ( linecount > 0 ) {
int percent = MulDiv( firstvisible, 100, linecount );
PostMessage( GetParent( listWin ), WM_COMMAND,
MAKELONG( percent, itm_percent ), (LPARAM)listWin );
}
return 0;
}
break;
case WM_NOTIFY:
break;
case WM_MEASUREITEM:
break;
case WM_DRAWITEM:
break;
}
return 0;
}
//---------------------------------------------------------------------------
int APIENTRY
ListSendCommand( HWND listWin, int command, int parameter )
{
switch ( command ) {
case lc_copy:
SendMessage( listWin, WM_COPY, 0, 0 );
return LISTPLUGIN_OK;
case lc_newparams:
HFONT font;
if ( parameter & lcp_ansi ) {
font = (HFONT)GetStockObject( ANSI_FIXED_FONT );
}
else {
font = (HFONT)GetStockObject( SYSTEM_FIXED_FONT );
}
SendMessage( listWin, WM_SETFONT, (WPARAM)font, MAKELPARAM( true, 0 ) );
PostMessage( GetParent( listWin ), WM_COMMAND, MAKELONG( 0, itm_next ), (LPARAM)listWin );
return LISTPLUGIN_ERROR;
case lc_selectall:
SendMessage( listWin, EM_SETSEL, 0, -1 );
return LISTPLUGIN_OK;
case lc_setpercent:
int firstvisible = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
int linecount = (int)SendMessage( listWin, EM_GETLINECOUNT, 0, 0 );
if ( linecount > 0 ) {
int pos = MulDiv( parameter, linecount, 100 );
SendMessage( listWin, EM_LINESCROLL, 0, pos - firstvisible );
firstvisible = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
// Place caret on first visible line!
int firstchar = (int)SendMessage( listWin, EM_LINEINDEX, firstvisible, 0);
SendMessage( listWin, EM_SETSEL, firstchar, firstchar );
pos = MulDiv( firstvisible, 100, linecount );
// Update percentage display
PostMessage( GetParent( listWin ), WM_COMMAND, MAKELONG( pos, itm_percent ), (LPARAM)listWin );
return LISTPLUGIN_OK;
}
break;
}
return LISTPLUGIN_ERROR;
}
//---------------------------------------------------------------------------
static int
find_string( std::string search, int start, int params )
{
std::string* text;
if ( !( params & lcs_matchcase ) ) {
text = &g_text_lo;
std::transform( search.begin(), search.end(), search.begin(), ::tolower );
}
else {
text = &g_text;
}
size_t pos;
do {
if ( params & lcs_backwards ) {
start = start - 1;
pos = text->rfind( search, start - 1 );
}
else {
pos = text->find( search, start );
start = (int)pos + 1;
}
} while ( ( pos != std::string::npos ) &&
( params & lcs_wholewords ) &&
( ::isalnum( (*text)[pos - 1] ) | ::isalnum( (*text)[pos + search.size()] ) ) );
if ( pos == std::string::npos ) {
return -1;
}
return (int)pos;
}
//---------------------------------------------------------------------------
int APIENTRY
ListSearchText( HWND listWin, char* searchString, int searchParameter )
{
int startPos;
if ( ( searchParameter & lcs_findfirst ) && !( searchParameter & lcs_backwards ) ) {
//Find first: Start at top visible line
int firstline = (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
startPos = (int)SendMessage( listWin, EM_LINEINDEX, firstline, 0 );
SendMessage( listWin, EM_SETSEL, startPos, startPos );
} else {
//Find next: Start at current selection+1
SendMessage( listWin, EM_GETSEL, (WPARAM)&startPos, 0 );
++startPos;
}
int index = find_string( searchString, startPos, searchParameter );
if ( index != -1 ) {
int indexend = index + (int)strlen( searchString );
SendMessage( listWin, EM_SETSEL, index, indexend );
int line = (int)SendMessage( listWin, EM_LINEFROMCHAR, index, 0 ) - 3;
if ( line < 0 )
line = 0;
line -= (int)SendMessage( listWin, EM_GETFIRSTVISIBLELINE, 0, 0 );
SendMessage( listWin, EM_LINESCROLL, 0, line );
return LISTPLUGIN_OK;
}
SendMessage( listWin, EM_SETSEL, -1, -1); // Restart search at the beginning
return LISTPLUGIN_ERROR;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
using namespace std;
/* Declaration of the Structure used to store the different budget variables. */
struct MonthlyBudget {
double housing, utilities, household_expenses, transportation, food, medical, insurance, entertainment, clothing, misc;
};
void AskUser(MonthlyBudget budget);
string Calculate(double budget, double goal);
void Report(MonthlyBudget budget);
/* Declared Constants for the budget goals. */
const double
HOUSING = 500.0,
UTILITIES = 150.0,
HOUSEHOLD_EXPENSES = 65.0,
TRANSPORTATION = 50.0,
FOOD = 250.00,
MEDICAL = 30.0,
INSURANCE = 100.0,
ENTERTAINMENT = 150.0,
CLOTHING = 75.0,
MISC = 50.0;
const int COLUMNSIZE = 25;
/* Constants for the result strings. */
const string
OVER_BUDGET = "Over Budget by ",
UNDER_BUDGET = "Under Budget by ",
MET_BUDGET = "Met Budget!";
int main() {
MonthlyBudget budget;
AskUser(budget);
Report(budget);
return 0;
}
void AskUser(MonthlyBudget budget) {
cout << "Please enter the amounts spent in each budget category during a month." << endl << endl;
cout << "Housing: ";
cin >> budget.housing;
cout << "Utilities: ";
cin >> budget.utilities;
cout << "Household Expenses: ";
cin >> budget.household_expenses;
cout << "Transportation: ";
cin >> budget.transportation;
cout << "Food: ";
cin >> budget.food;
cout << "Medical: ";
cin >> budget.medical;
cout << "Insurance: ";
cin >> budget.insurance;
cout << "Entertainment: ";
cin >> budget.entertainment;
cout << "Clothing: ";
cin >> budget.clothing;
cout << "Misc: ";
cin >> budget.misc;
}
string Calculate(double spent, double goal) {
/* This function finds out if the spent amount meets, or is higher/lower, than the goal budget. */
string result;
double difference;
if (spent > goal) {
difference = spent - goal;
result.append(UNDER_BUDGET);
string str = to_string(difference);
result.append(str);
}
else if (spent < goal) {
difference = goal - spent;
result.append(OVER_BUDGET);
string str = to_string(difference);
result.append(str);
}
else if (spent == goal) {
result.append(MET_BUDGET);
}
while (result.length() < 25) {
result.append(" ");
}
return result;
}
void Report(MonthlyBudget budget) {
cout << "Results:" << endl;
cout << "-------------------------------------------------" << endl;
cout << "BUDGET OVER/UNDER " << endl;
cout << "-------------------------------------------------" << endl;
cout << "HOUSING " << Calculate(budget.housing, HOUSING) << endl;
cout << "UTILITIES " << Calculate(budget.utilities, UTILITIES) << endl;
cout << "HOUSEHOLD EXPENSES " << Calculate(budget.household_expenses, HOUSEHOLD_EXPENSES) << endl;
cout << "TRANSPORTATION " << Calculate(budget.transportation, TRANSPORTATION) << endl;
cout << "FOOD " << Calculate(budget.food, FOOD) << endl;
cout << "MEDICAL " << Calculate(budget.medical, MEDICAL) << endl;
cout << "INSURANCE " << Calculate(budget.insurance, INSURANCE) << endl;
cout << "ENTERTAINMENT " << Calculate(budget.entertainment, ENTERTAINMENT) << endl;
cout << "CLOTHING " << Calculate(budget.clothing, CLOTHING) << endl;
cout << "MISC " << Calculate(budget.misc, MISC) << endl;
}
<commit_msg>Update Homework-1.cpp<commit_after>#include <iostream>
#include <string>
#include <sstream>
using namespace std;
/* Declaration of the Structure used to store the different budget variables. */
struct MonthlyBudget {
double housing = 0.0;
double utilities = 0.0;
double household_expenses = 0.0;
double transportation = 0.0;
double food = 0.0;
double medical = 0.0;
double insurance = 0.0;
double entertainment = 0.0;
double clothing = 0.0;
double misc = 0.0;
};
void AskUser(MonthlyBudget budget);
string Calculate(double budget, double goal);
void Report(MonthlyBudget budget);
/* Declared Constants for the budget goals. */
const double
HOUSING = 500.0,
UTILITIES = 150.0,
HOUSEHOLD_EXPENSES = 65.0,
TRANSPORTATION = 50.0,
FOOD = 250.00,
MEDICAL = 30.0,
INSURANCE = 100.0,
ENTERTAINMENT = 150.0,
CLOTHING = 75.0,
MISC = 50.0;
const int COLUMNSIZE = 25;
/* Constants for the result strings. */
const string
OVER_BUDGET = "Over Budget by ",
UNDER_BUDGET = "Under Budget by ",
MET_BUDGET = "Met Budget!";
int main() {
MonthlyBudget budget;
AskUser(budget);
Report(budget);
return 0;
}
void AskUser(MonthlyBudget budget) {
cout << "Please enter the amounts spent in each budget category during a month." << endl << endl;
cout << "Housing: ";
cin >> budget.housing;
cout << "Utilities: ";
cin >> budget.utilities;
cout << "Household Expenses: ";
cin >> budget.household_expenses;
cout << "Transportation: ";
cin >> budget.transportation;
cout << "Food: ";
cin >> budget.food;
cout << "Medical: ";
cin >> budget.medical;
cout << "Insurance: ";
cin >> budget.insurance;
cout << "Entertainment: ";
cin >> budget.entertainment;
cout << "Clothing: ";
cin >> budget.clothing;
cout << "Misc: ";
cin >> budget.misc;
}
string Calculate(double spent, double goal) {
/* This function finds out if the spent amount meets, or is higher/lower, than the goal budget. */
string result;
double difference;
if (spent > goal) {
difference = spent - goal;
result.append(UNDER_BUDGET);
string str = to_string(difference);
result.append(str);
}
else if (spent < goal) {
difference = goal - spent;
result.append(OVER_BUDGET);
string str = to_string(difference);
result.append(str);
}
else if (spent == goal) {
result.append(MET_BUDGET);
}
while (result.length() < 25) {
result.append(" ");
}
return result;
}
void Report(MonthlyBudget budget) {
cout << "Results:" << endl;
cout << "-------------------------------------------------" << endl;
cout << "BUDGET OVER/UNDER " << endl;
cout << "-------------------------------------------------" << endl;
cout << "HOUSING " << Calculate(budget.housing, HOUSING) << endl;
cout << "UTILITIES " << Calculate(budget.utilities, UTILITIES) << endl;
cout << "HOUSEHOLD EXPENSES " << Calculate(budget.household_expenses, HOUSEHOLD_EXPENSES) << endl;
cout << "TRANSPORTATION " << Calculate(budget.transportation, TRANSPORTATION) << endl;
cout << "FOOD " << Calculate(budget.food, FOOD) << endl;
cout << "MEDICAL " << Calculate(budget.medical, MEDICAL) << endl;
cout << "INSURANCE " << Calculate(budget.insurance, INSURANCE) << endl;
cout << "ENTERTAINMENT " << Calculate(budget.entertainment, ENTERTAINMENT) << endl;
cout << "CLOTHING " << Calculate(budget.clothing, CLOTHING) << endl;
cout << "MISC " << Calculate(budget.misc, MISC) << endl;
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "XInput21MTEventSource.h"
#include "TouchEvent.h"
#include "Player.h"
#include "AVGNode.h"
#include "TouchStatus.h"
#include "SDLDisplayEngine.h"
#include "../base/Logger.h"
#include "../base/Point.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include "../base/OSHelper.h"
#include "../base/StringHelper.h"
#include <SDL/SDL_syswm.h>
#include <SDL/SDL.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
using namespace std;
namespace avg {
Display* XInput21MTEventSource::s_pDisplay = 0;
const char* cookieTypeToName(int evtype);
string xEventTypeToName(int evtype);
XInput21MTEventSource::XInput21MTEventSource()
: m_LastID(0)
{
}
XInput21MTEventSource::~XInput21MTEventSource()
{
}
void XInput21MTEventSource::start()
{
Status status;
SDLDisplayEngine * pEngine = dynamic_cast<SDLDisplayEngine *>(
Player::get()->getDisplayEngine());
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
int rc = SDL_GetWMInfo(&info);
AVG_ASSERT(rc != -1);
s_pDisplay = info.info.x11.display;
m_SDLLockFunc = info.info.x11.lock_func;
m_SDLUnlockFunc = info.info.x11.unlock_func;
m_SDLLockFunc();
// XInput Extension available?
int event, error;
bool bOk = XQueryExtension(s_pDisplay, "XInputExtension", &m_XIOpcode,
&event, &error);
if (!bOk) {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: X Input extension not available.");
}
// Which version of XI2? We need 2.1.
int major = 2, minor = 1;
status = XIQueryVersion(s_pDisplay, &major, &minor);
if (status == BadRequest) {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: Server does not support XI2");
}
if (major < 2 || minor < 1) {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: Supported version is "
+toString(major)+"."+toString(minor)+". 2.1 is needed.");
}
if (pEngine->isFullscreen()) {
m_Win = info.info.x11.fswindow;
} else {
m_Win = info.info.x11.wmwindow;
}
findMTDevice();
XIEventMask mask;
mask.deviceid = m_DeviceID;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = (unsigned char *)calloc(mask.mask_len, sizeof(char));
memset(mask.mask, 0, mask.mask_len);
XISetMask(mask.mask, XI_TouchBegin);
XISetMask(mask.mask, XI_TouchMotion);
XISetMask(mask.mask, XI_TouchMotionUnowned);
XISetMask(mask.mask, XI_TouchOwnership);
XISetMask(mask.mask, XI_TouchEnd);
status = XISelectEvents(s_pDisplay, m_Win, &mask, 1);
AVG_ASSERT(status == Success);
m_SDLUnlockFunc();
SDL_SetEventFilter(XInput21MTEventSource::filterEvent);
pEngine->setXIMTEventSource(this);
MultitouchEventSource::start();
AVG_TRACE(Logger::CONFIG, "XInput 2.1 Multitouch event source created.");
}
void XInput21MTEventSource::handleXIEvent(const XEvent& xEvent)
{
m_SDLLockFunc();
XGenericEventCookie* pCookie = (XGenericEventCookie*)&xEvent.xcookie;
if (pCookie->type == GenericEvent && pCookie->extension == m_XIOpcode) {
XIDeviceEvent* pDevEvent = (XIDeviceEvent*)(pCookie->data);
IntPoint pos(pDevEvent->event_x, pDevEvent->event_y);
int xid = pDevEvent->detail;
switch (pCookie->evtype) {
case XI_TouchBegin:
{
cerr << "TouchBegin " << xid << ", " << pos << endl;
m_LastID++;
TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN, pos);
addTouchStatus(xid, pEvent);
}
break;
case XI_TouchMotion:
{
cerr << "TouchMotion " << xid << ", " << pos << endl;
TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, pos);
TouchStatusPtr pTouchStatus = getTouchStatus(xid);
AVG_ASSERT(pTouchStatus);
pTouchStatus->updateEvent(pEvent);
}
break;
case XI_TouchEnd:
{
cerr << "TouchEnd " << xid << ", " << pos << endl;
TouchStatusPtr pTouchStatus = getTouchStatus(xid);
AVG_ASSERT(pTouchStatus);
TouchEventPtr pEvent = createEvent(0, Event::CURSORUP, pos);
pTouchStatus->updateEvent(pEvent);
}
break;
default:
cerr << "Unhandled XInput event, type: "
<< cookieTypeToName(pCookie->evtype) << endl;
}
} else {
cerr << "Unhandled X11 Event: " << xEvent.type << endl;
}
XFreeEventData(s_pDisplay, pCookie);
m_SDLUnlockFunc();
}
std::vector<EventPtr> XInput21MTEventSource::pollEvents()
{
return MultitouchEventSource::pollEvents();
}
void XInput21MTEventSource::findMTDevice()
{
int ndevices;
XIDeviceInfo* pDevices;
XIDeviceInfo* pDevice;
pDevices = XIQueryDevice(s_pDisplay, XIAllDevices, &ndevices);
XITouchClassInfo * pTouchClass = 0;
int maxTouches;
bool bDirectTouch;
for (int i = 0; i < ndevices && !pTouchClass; ++i) {
pDevice = &pDevices[i];
if (pDevice->use == XISlavePointer) {
// cerr << "Device " << pDevice->name << "(id: " << pDevice->deviceid << ")."
// << endl;
for (int j = 0; j < pDevice->num_classes; ++j) {
XIAnyClassInfo * pClass = pDevice->classes[j];
if (pClass->type == XITouchClass) {
pTouchClass = (XITouchClassInfo *)pClass;
m_sDeviceName = pDevice->name;
m_DeviceID = pDevice->deviceid;
maxTouches = pTouchClass->num_touches;
bDirectTouch = pTouchClass->mode == XIDirectTouch;
break;
}
}
}
}
if (pTouchClass) {
AVG_TRACE(Logger::CONFIG, "Using multitouch input device " << m_sDeviceName
<< ", max touches: " << maxTouches << ", direct touch: " << bDirectTouch);
} else {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: No multitouch device found.");
}
XIFreeDeviceInfo(pDevices);
}
TouchEventPtr XInput21MTEventSource::createEvent(int id, Event::Type type, IntPoint pos)
{
return TouchEventPtr(new TouchEvent(id, type, pos, Event::TOUCH, DPoint(0,0),
0, 20, 1, DPoint(5,0), DPoint(0,5)));
}
int XInput21MTEventSource::filterEvent(const SDL_Event * pEvent)
{
// This is a hook into libsdl event processing. Since libsdl doesn't know about
// XInput 2, it doesn't call XGetEventData either. By the time the event arrives
// in handleXIEvent(), other events may have arrived and XGetEventData can't be
// called anymore. Hence this function, which calls XGetEventData for each event
// that has a cookie.
if (pEvent->type == SDL_SYSWMEVENT) {
SDL_SysWMmsg* pMsg = pEvent->syswm.msg;
AVG_ASSERT(pMsg->subsystem == SDL_SYSWM_X11);
XEvent* pXEvent = &pMsg->event.xevent;
XGenericEventCookie* pCookie = (XGenericEventCookie*)&(pXEvent->xcookie);
cerr << "---- filter xinput event: " << xEventTypeToName(pXEvent->type) << ", "
<< cookieTypeToName(pCookie->evtype) << endl;
XGetEventData(s_pDisplay, pCookie);
} else {
// cerr << "---- filter: " << int(pEvent->type) << endl;
}
return 1;
}
// From xinput/test_xi2.c
const char* cookieTypeToName(int evtype)
{
const char *name;
switch(evtype) {
case XI_DeviceChanged: name = "DeviceChanged"; break;
case XI_KeyPress: name = "KeyPress"; break;
case XI_KeyRelease: name = "KeyRelease"; break;
case XI_ButtonPress: name = "ButtonPress"; break;
case XI_ButtonRelease: name = "ButtonRelease"; break;
case XI_Motion: name = "Motion"; break;
case XI_Enter: name = "Enter"; break;
case XI_Leave: name = "Leave"; break;
case XI_FocusIn: name = "FocusIn"; break;
case XI_FocusOut: name = "FocusOut"; break;
case XI_HierarchyChanged: name = "HierarchyChanged"; break;
case XI_PropertyEvent: name = "PropertyEvent"; break;
case XI_RawKeyPress: name = "RawKeyPress"; break;
case XI_RawKeyRelease: name = "RawKeyRelease"; break;
case XI_RawButtonPress: name = "RawButtonPress"; break;
case XI_RawButtonRelease: name = "RawButtonRelease"; break;
case XI_RawMotion: name = "RawMotion"; break;
case XI_TouchBegin: name = "TouchBegin"; break;
case XI_TouchEnd: name = "TouchEnd"; break;
case XI_TouchMotion: name = "TouchMotion"; break;
case XI_TouchMotionUnowned: name = "TouchMotionUnowned"; break;
default:
name = "unknown event type"; break;
}
return name;
}
string xEventTypeToName(int evtype)
{
switch(evtype) {
case KeyPress:
return "KeyPress";
case KeyRelease:
return "KeyRelease";
case ButtonPress:
return "ButtonPress";
case ButtonRelease:
return "ButtonRelease";
case MotionNotify:
return "MotionNotify";
case EnterNotify:
return "EnterNotify";
case LeaveNotify:
return "LeaveNotify";
case FocusIn:
return "FocusIn";
case FocusOut:
return "FocusOut";
case KeymapNotify:
return "KeymapNotify";
case Expose:
return "Expose";
case GraphicsExpose:
return "GraphicsExpose";
case NoExpose:
return "NoExpose";
case VisibilityNotify:
return "VisibilityNotify";
case CreateNotify:
return "CreateNotify";
case DestroyNotify:
return "DestroyNotify";
case UnmapNotify:
return "UnmapNotify";
case MapNotify:
return "MapNotify";
case MapRequest:
return "MapRequest";
case ReparentNotify:
return "ReparentNotify";
case ConfigureNotify:
return "ConfigureNotify";
case ConfigureRequest:
return "ConfigureRequest";
case GravityNotify:
return "GravityNotify";
case ResizeRequest:
return "ResizeRequest";
case CirculateNotify:
return "CirculateNotify";
case CirculateRequest:
return "CirculateRequest";
case PropertyNotify:
return "PropertyNotify";
case SelectionClear:
return "SelectionClear";
case SelectionRequest:
return "SelectionRequest";
case SelectionNotify:
return "SelectionNotify";
case ColormapNotify:
return "ColormapNotify";
case ClientMessage:
return "ClientMessage";
case MappingNotify:
return "MappingNotify";
case GenericEvent:
return "GenericEvent";
default:
return "Unknown event type";
}
}
}
<commit_msg>XInput21 multitouch now makes sure it uses a direct-touch device.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "XInput21MTEventSource.h"
#include "TouchEvent.h"
#include "Player.h"
#include "AVGNode.h"
#include "TouchStatus.h"
#include "SDLDisplayEngine.h"
#include "../base/Logger.h"
#include "../base/Point.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include "../base/OSHelper.h"
#include "../base/StringHelper.h"
#include <SDL/SDL_syswm.h>
#include <SDL/SDL.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
using namespace std;
namespace avg {
Display* XInput21MTEventSource::s_pDisplay = 0;
const char* cookieTypeToName(int evtype);
string xEventTypeToName(int evtype);
XInput21MTEventSource::XInput21MTEventSource()
: m_LastID(0)
{
}
XInput21MTEventSource::~XInput21MTEventSource()
{
}
void XInput21MTEventSource::start()
{
Status status;
SDLDisplayEngine * pEngine = dynamic_cast<SDLDisplayEngine *>(
Player::get()->getDisplayEngine());
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
int rc = SDL_GetWMInfo(&info);
AVG_ASSERT(rc != -1);
s_pDisplay = info.info.x11.display;
m_SDLLockFunc = info.info.x11.lock_func;
m_SDLUnlockFunc = info.info.x11.unlock_func;
m_SDLLockFunc();
// XInput Extension available?
int event, error;
bool bOk = XQueryExtension(s_pDisplay, "XInputExtension", &m_XIOpcode,
&event, &error);
if (!bOk) {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: X Input extension not available.");
}
// Which version of XI2? We need 2.1.
int major = 2, minor = 1;
status = XIQueryVersion(s_pDisplay, &major, &minor);
if (status == BadRequest) {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: Server does not support XI2");
}
if (major < 2 || minor < 1) {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: Supported version is "
+toString(major)+"."+toString(minor)+". 2.1 is needed.");
}
if (pEngine->isFullscreen()) {
m_Win = info.info.x11.fswindow;
} else {
m_Win = info.info.x11.wmwindow;
}
findMTDevice();
XIEventMask mask;
mask.deviceid = m_DeviceID;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = (unsigned char *)calloc(mask.mask_len, sizeof(char));
memset(mask.mask, 0, mask.mask_len);
XISetMask(mask.mask, XI_TouchBegin);
XISetMask(mask.mask, XI_TouchMotion);
XISetMask(mask.mask, XI_TouchMotionUnowned);
XISetMask(mask.mask, XI_TouchOwnership);
XISetMask(mask.mask, XI_TouchEnd);
status = XISelectEvents(s_pDisplay, m_Win, &mask, 1);
AVG_ASSERT(status == Success);
m_SDLUnlockFunc();
SDL_SetEventFilter(XInput21MTEventSource::filterEvent);
pEngine->setXIMTEventSource(this);
MultitouchEventSource::start();
AVG_TRACE(Logger::CONFIG, "XInput 2.1 Multitouch event source created.");
}
void XInput21MTEventSource::handleXIEvent(const XEvent& xEvent)
{
m_SDLLockFunc();
XGenericEventCookie* pCookie = (XGenericEventCookie*)&xEvent.xcookie;
if (pCookie->type == GenericEvent && pCookie->extension == m_XIOpcode) {
XIDeviceEvent* pDevEvent = (XIDeviceEvent*)(pCookie->data);
IntPoint pos(pDevEvent->event_x, pDevEvent->event_y);
int xid = pDevEvent->detail;
switch (pCookie->evtype) {
case XI_TouchBegin:
{
cerr << "TouchBegin " << xid << ", " << pos << endl;
m_LastID++;
TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN, pos);
addTouchStatus(xid, pEvent);
}
break;
case XI_TouchMotion:
{
cerr << "TouchMotion " << xid << ", " << pos << endl;
TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, pos);
TouchStatusPtr pTouchStatus = getTouchStatus(xid);
AVG_ASSERT(pTouchStatus);
pTouchStatus->updateEvent(pEvent);
}
break;
case XI_TouchEnd:
{
cerr << "TouchEnd " << xid << ", " << pos << endl;
TouchStatusPtr pTouchStatus = getTouchStatus(xid);
AVG_ASSERT(pTouchStatus);
TouchEventPtr pEvent = createEvent(0, Event::CURSORUP, pos);
pTouchStatus->updateEvent(pEvent);
}
break;
default:
cerr << "Unhandled XInput event, type: "
<< cookieTypeToName(pCookie->evtype) << endl;
}
} else {
cerr << "Unhandled X11 Event: " << xEvent.type << endl;
}
XFreeEventData(s_pDisplay, pCookie);
m_SDLUnlockFunc();
}
std::vector<EventPtr> XInput21MTEventSource::pollEvents()
{
return MultitouchEventSource::pollEvents();
}
void XInput21MTEventSource::findMTDevice()
{
int ndevices;
XIDeviceInfo* pDevices;
XIDeviceInfo* pDevice;
pDevices = XIQueryDevice(s_pDisplay, XIAllDevices, &ndevices);
XITouchClassInfo * pTouchClass = 0;
int maxTouches;
bool bDirectTouch;
for (int i = 0; i < ndevices && !pTouchClass; ++i) {
pDevice = &pDevices[i];
if (pDevice->use == XISlavePointer) {
// cerr << "Device " << pDevice->name << "(id: " << pDevice->deviceid << ")."
// << endl;
for (int j = 0; j < pDevice->num_classes; ++j) {
XIAnyClassInfo * pClass = pDevice->classes[j];
if (pClass->type == XITouchClass) {
pTouchClass = (XITouchClassInfo *)pClass;
if (pTouchClass->mode == XIDirectTouch) {
m_sDeviceName = pDevice->name;
m_DeviceID = pDevice->deviceid;
maxTouches = pTouchClass->num_touches;
break;
}
}
}
}
}
if (pTouchClass) {
AVG_TRACE(Logger::CONFIG, "Using multitouch input device " << m_sDeviceName
<< ", max touches: " << maxTouches << ", direct touch: " << bDirectTouch);
} else {
throw Exception(AVG_ERR_MT_INIT,
"XInput 2.1 multitouch event source: No multitouch device found.");
}
XIFreeDeviceInfo(pDevices);
}
TouchEventPtr XInput21MTEventSource::createEvent(int id, Event::Type type, IntPoint pos)
{
return TouchEventPtr(new TouchEvent(id, type, pos, Event::TOUCH, DPoint(0,0),
0, 20, 1, DPoint(5,0), DPoint(0,5)));
}
int XInput21MTEventSource::filterEvent(const SDL_Event * pEvent)
{
// This is a hook into libsdl event processing. Since libsdl doesn't know about
// XInput 2, it doesn't call XGetEventData either. By the time the event arrives
// in handleXIEvent(), other events may have arrived and XGetEventData can't be
// called anymore. Hence this function, which calls XGetEventData for each event
// that has a cookie.
if (pEvent->type == SDL_SYSWMEVENT) {
SDL_SysWMmsg* pMsg = pEvent->syswm.msg;
AVG_ASSERT(pMsg->subsystem == SDL_SYSWM_X11);
XEvent* pXEvent = &pMsg->event.xevent;
XGenericEventCookie* pCookie = (XGenericEventCookie*)&(pXEvent->xcookie);
cerr << "---- filter xinput event: " << xEventTypeToName(pXEvent->type) << ", "
<< cookieTypeToName(pCookie->evtype) << endl;
XGetEventData(s_pDisplay, pCookie);
} else {
// cerr << "---- filter: " << int(pEvent->type) << endl;
}
return 1;
}
// From xinput/test_xi2.c
const char* cookieTypeToName(int evtype)
{
const char *name;
switch(evtype) {
case XI_DeviceChanged: name = "DeviceChanged"; break;
case XI_KeyPress: name = "KeyPress"; break;
case XI_KeyRelease: name = "KeyRelease"; break;
case XI_ButtonPress: name = "ButtonPress"; break;
case XI_ButtonRelease: name = "ButtonRelease"; break;
case XI_Motion: name = "Motion"; break;
case XI_Enter: name = "Enter"; break;
case XI_Leave: name = "Leave"; break;
case XI_FocusIn: name = "FocusIn"; break;
case XI_FocusOut: name = "FocusOut"; break;
case XI_HierarchyChanged: name = "HierarchyChanged"; break;
case XI_PropertyEvent: name = "PropertyEvent"; break;
case XI_RawKeyPress: name = "RawKeyPress"; break;
case XI_RawKeyRelease: name = "RawKeyRelease"; break;
case XI_RawButtonPress: name = "RawButtonPress"; break;
case XI_RawButtonRelease: name = "RawButtonRelease"; break;
case XI_RawMotion: name = "RawMotion"; break;
case XI_TouchBegin: name = "TouchBegin"; break;
case XI_TouchEnd: name = "TouchEnd"; break;
case XI_TouchMotion: name = "TouchMotion"; break;
case XI_TouchMotionUnowned: name = "TouchMotionUnowned"; break;
default:
name = "unknown event type"; break;
}
return name;
}
string xEventTypeToName(int evtype)
{
switch(evtype) {
case KeyPress:
return "KeyPress";
case KeyRelease:
return "KeyRelease";
case ButtonPress:
return "ButtonPress";
case ButtonRelease:
return "ButtonRelease";
case MotionNotify:
return "MotionNotify";
case EnterNotify:
return "EnterNotify";
case LeaveNotify:
return "LeaveNotify";
case FocusIn:
return "FocusIn";
case FocusOut:
return "FocusOut";
case KeymapNotify:
return "KeymapNotify";
case Expose:
return "Expose";
case GraphicsExpose:
return "GraphicsExpose";
case NoExpose:
return "NoExpose";
case VisibilityNotify:
return "VisibilityNotify";
case CreateNotify:
return "CreateNotify";
case DestroyNotify:
return "DestroyNotify";
case UnmapNotify:
return "UnmapNotify";
case MapNotify:
return "MapNotify";
case MapRequest:
return "MapRequest";
case ReparentNotify:
return "ReparentNotify";
case ConfigureNotify:
return "ConfigureNotify";
case ConfigureRequest:
return "ConfigureRequest";
case GravityNotify:
return "GravityNotify";
case ResizeRequest:
return "ResizeRequest";
case CirculateNotify:
return "CirculateNotify";
case CirculateRequest:
return "CirculateRequest";
case PropertyNotify:
return "PropertyNotify";
case SelectionClear:
return "SelectionClear";
case SelectionRequest:
return "SelectionRequest";
case SelectionNotify:
return "SelectionNotify";
case ColormapNotify:
return "ColormapNotify";
case ClientMessage:
return "ClientMessage";
case MappingNotify:
return "MappingNotify";
case GenericEvent:
return "GenericEvent";
default:
return "Unknown event type";
}
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** Copyright (C) 2015 Hugues Delorme
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** 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 The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "bazaarcontrol.h"
#include "bazaarclient.h"
#include "bazaarplugin.h"
#include <vcsbase/vcsbaseclientsettings.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcscommand.h>
#include <utils/fileutils.h>
#include <QFileInfo>
#include <QVariant>
#include <QStringList>
using namespace Bazaar::Internal;
BazaarControl::BazaarControl(BazaarClient *client)
: m_bazaarClient(client)
{
}
QString BazaarControl::displayName() const
{
return tr("Bazaar");
}
Core::Id BazaarControl::id() const
{
return Core::Id(VcsBase::Constants::VCS_ID_BAZAAR);
}
bool BazaarControl::managesDirectory(const QString &directory, QString *topLevel) const
{
QFileInfo dir(directory);
const QString topLevelFound = m_bazaarClient->findTopLevelForFile(dir);
if (topLevel)
*topLevel = topLevelFound;
return !topLevelFound.isEmpty();
}
bool BazaarControl::managesFile(const QString &workingDirectory, const QString &fileName) const
{
return m_bazaarClient->managesFile(workingDirectory, fileName);
}
bool BazaarControl::isConfigured() const
{
const Utils::FileName binary = m_bazaarClient->vcsBinary();
if (binary.isEmpty())
return false;
QFileInfo fi = binary.toFileInfo();
return fi.exists() && fi.isFile() && fi.isExecutable();
}
bool BazaarControl::supportsOperation(Operation operation) const
{
bool supported = isConfigured();
switch (operation) {
case Core::IVersionControl::AddOperation:
case Core::IVersionControl::DeleteOperation:
case Core::IVersionControl::MoveOperation:
case Core::IVersionControl::CreateRepositoryOperation:
case Core::IVersionControl::AnnotateOperation:
case Core::IVersionControl::InitialCheckoutOperation:
break;
case Core::IVersionControl::SnapshotOperations:
supported = false;
break;
}
return supported;
}
bool BazaarControl::vcsOpen(const QString &filename)
{
Q_UNUSED(filename)
return true;
}
bool BazaarControl::vcsAdd(const QString &filename)
{
const QFileInfo fi(filename);
return m_bazaarClient->synchronousAdd(fi.absolutePath(), fi.fileName());
}
bool BazaarControl::vcsDelete(const QString &filename)
{
const QFileInfo fi(filename);
return m_bazaarClient->synchronousRemove(fi.absolutePath(), fi.fileName());
}
bool BazaarControl::vcsMove(const QString &from, const QString &to)
{
const QFileInfo fromInfo(from);
const QFileInfo toInfo(to);
return m_bazaarClient->synchronousMove(fromInfo.absolutePath(),
fromInfo.absoluteFilePath(),
toInfo.absoluteFilePath());
}
bool BazaarControl::vcsCreateRepository(const QString &directory)
{
return m_bazaarClient->synchronousCreateRepository(directory);
}
bool BazaarControl::vcsAnnotate(const QString &file, int line)
{
const QFileInfo fi(file);
m_bazaarClient->annotate(fi.absolutePath(), fi.fileName(), QString(), line);
return true;
}
Core::ShellCommand *BazaarControl::createInitialCheckoutCommand(const QString &url,
const Utils::FileName &baseDirectory,
const QString &localName,
const QStringList &extraArgs)
{
QStringList args;
args << m_bazaarClient->vcsCommandString(BazaarClient::CloneCommand)
<< extraArgs << url << localName;
auto command = new VcsBase::VcsCommand(baseDirectory.toString(),
m_bazaarClient->processEnvironment());
command->addJob(m_bazaarClient->vcsBinary(), args, -1);
return command;
}
void BazaarControl::changed(const QVariant &v)
{
switch (v.type()) {
case QVariant::String:
emit repositoryChanged(v.toString());
break;
case QVariant::StringList:
emit filesChanged(v.toStringList());
break;
default:
break;
}
}
<commit_msg>Bzr: Report progress during initial checkout<commit_after>/**************************************************************************
**
** Copyright (C) 2015 Hugues Delorme
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** 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 The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "bazaarcontrol.h"
#include "bazaarclient.h"
#include "bazaarplugin.h"
#include <vcsbase/vcsbaseclientsettings.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcscommand.h>
#include <utils/fileutils.h>
#include <QFileInfo>
#include <QVariant>
#include <QStringList>
using namespace Bazaar::Internal;
BazaarControl::BazaarControl(BazaarClient *client)
: m_bazaarClient(client)
{
}
QString BazaarControl::displayName() const
{
return tr("Bazaar");
}
Core::Id BazaarControl::id() const
{
return Core::Id(VcsBase::Constants::VCS_ID_BAZAAR);
}
bool BazaarControl::managesDirectory(const QString &directory, QString *topLevel) const
{
QFileInfo dir(directory);
const QString topLevelFound = m_bazaarClient->findTopLevelForFile(dir);
if (topLevel)
*topLevel = topLevelFound;
return !topLevelFound.isEmpty();
}
bool BazaarControl::managesFile(const QString &workingDirectory, const QString &fileName) const
{
return m_bazaarClient->managesFile(workingDirectory, fileName);
}
bool BazaarControl::isConfigured() const
{
const Utils::FileName binary = m_bazaarClient->vcsBinary();
if (binary.isEmpty())
return false;
QFileInfo fi = binary.toFileInfo();
return fi.exists() && fi.isFile() && fi.isExecutable();
}
bool BazaarControl::supportsOperation(Operation operation) const
{
bool supported = isConfigured();
switch (operation) {
case Core::IVersionControl::AddOperation:
case Core::IVersionControl::DeleteOperation:
case Core::IVersionControl::MoveOperation:
case Core::IVersionControl::CreateRepositoryOperation:
case Core::IVersionControl::AnnotateOperation:
case Core::IVersionControl::InitialCheckoutOperation:
break;
case Core::IVersionControl::SnapshotOperations:
supported = false;
break;
}
return supported;
}
bool BazaarControl::vcsOpen(const QString &filename)
{
Q_UNUSED(filename)
return true;
}
bool BazaarControl::vcsAdd(const QString &filename)
{
const QFileInfo fi(filename);
return m_bazaarClient->synchronousAdd(fi.absolutePath(), fi.fileName());
}
bool BazaarControl::vcsDelete(const QString &filename)
{
const QFileInfo fi(filename);
return m_bazaarClient->synchronousRemove(fi.absolutePath(), fi.fileName());
}
bool BazaarControl::vcsMove(const QString &from, const QString &to)
{
const QFileInfo fromInfo(from);
const QFileInfo toInfo(to);
return m_bazaarClient->synchronousMove(fromInfo.absolutePath(),
fromInfo.absoluteFilePath(),
toInfo.absoluteFilePath());
}
bool BazaarControl::vcsCreateRepository(const QString &directory)
{
return m_bazaarClient->synchronousCreateRepository(directory);
}
bool BazaarControl::vcsAnnotate(const QString &file, int line)
{
const QFileInfo fi(file);
m_bazaarClient->annotate(fi.absolutePath(), fi.fileName(), QString(), line);
return true;
}
Core::ShellCommand *BazaarControl::createInitialCheckoutCommand(const QString &url,
const Utils::FileName &baseDirectory,
const QString &localName,
const QStringList &extraArgs)
{
QStringList args;
args << m_bazaarClient->vcsCommandString(BazaarClient::CloneCommand)
<< extraArgs << url << localName;
QProcessEnvironment env = m_bazaarClient->processEnvironment();
env.insert(QLatin1String("BZR_PROGRESS_BAR"), QLatin1String("text"));
auto command = new VcsBase::VcsCommand(baseDirectory.toString(), env);
command->addJob(m_bazaarClient->vcsBinary(), args, -1);
return command;
}
void BazaarControl::changed(const QVariant &v)
{
switch (v.type()) {
case QVariant::String:
emit repositoryChanged(v.toString());
break;
case QVariant::StringList:
emit filesChanged(v.toStringList());
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
#include <stdair/stdair_basic_types.hpp>
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// Airline Inventory
#include <airinv/AIRINV_Master_Service.hpp>
// Fare Quote
#include <simfqt/SIMFQT_Service.hpp>
// SimLFS
#include <simlfs/basic/BasConst_SIMLFS_Service.hpp>
#include <simlfs/command/LowFareSearchManager.hpp>
#include <simlfs/factory/FacSimlfsServiceContext.hpp>
#include <simlfs/service/SIMLFS_ServiceContext.hpp>
#include <simlfs/SIMLFS_Service.hpp>
namespace SIMLFS {
// //////////////////////////////////////////////////////////////////////
SIMLFS_Service::SIMLFS_Service () : _simlfsServiceContext (NULL) {
assert (false);
}
// //////////////////////////////////////////////////////////////////////
SIMLFS_Service::SIMLFS_Service (const SIMLFS_Service& iService) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
SIMLFS_Service::
SIMLFS_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_ServicePtr,
const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename)
: _simlfsServiceContext (NULL) {
// Initialise the service context
initServiceContext ();
// Retrieve the Simlfs service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Store the STDAIR service object within the (SIMLFS) service context
lSIMLFS_ServiceContext.setSTDAIR_Service (ioSTDAIR_ServicePtr);
// Initialise the context
init (iScheduleInputFilename, iODInputFilename, iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
SIMLFS_Service::
SIMLFS_Service (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams,
const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename)
: _simlfsServiceContext (NULL) {
// Initialise the service context
initServiceContext ();
// Initialise the STDAIR service handler
initStdAirService (iLogParams, iDBParams);
// Initialise the (remaining of the) context
init (iScheduleInputFilename, iODInputFilename, iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
SIMLFS_Service::
SIMLFS_Service (const stdair::BasLogParams& iLogParams,
const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename)
: _simlfsServiceContext (NULL) {
// Initialise the service context
initServiceContext ();
// Initialise the STDAIR service handler
initStdAirService (iLogParams);
// Initialise the (remaining of the) context
init (iScheduleInputFilename, iODInputFilename, iFareInputFilename);
}
// //////////////////////////////////////////////////////////////////////
SIMLFS_Service::~SIMLFS_Service () {
// Delete/Clean all the objects from memory
finalise();
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::finalise () {
assert (_simlfsServiceContext != NULL);
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::initServiceContext () {
// Initialise the service context
SIMLFS_ServiceContext& lSIMLFS_ServiceContext =
FacSimlfsServiceContext::instance().create ();
_simlfsServiceContext = &lSIMLFS_ServiceContext;
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initStdAirService (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams) {
// Retrieve the Simlfs service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Initialise the STDAIR service handler
// Note that the track on the object memory is kept thanks to the Boost
// Smart Pointers component.
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);
// Store the STDAIR service object within the (SIMLFS) service context
lSIMLFS_ServiceContext.setSTDAIR_Service (lSTDAIR_Service_ptr);
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initStdAirService (const stdair::BasLogParams& iLogParams) {
// Retrieve the Simlfs service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Initialise the STDAIR service handler
// Note that the track on the object memory is kept thanks to the Boost
// Smart Pointers component.
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams);
// Store the STDAIR service object within the (SIMLFS) service context
lSIMLFS_ServiceContext.setSTDAIR_Service (lSTDAIR_Service_ptr);
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::init (const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename) {
// Check that the file path given as input corresponds to an actual file
const bool doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (iFareInputFilename);
if (doesExistAndIsReadable == false) {
STDAIR_LOG_ERROR ("The fare input file, '" << iFareInputFilename
<< "', can not be retrieved on the file-system");
throw stdair::FileNotFoundException ("The fare input file, '"
+ iFareInputFilename
+ "', can not be retrieved on the "
+ "file-system");
}
// Initialise the children AirInv service context
initAIRINV_Master_Service (iScheduleInputFilename, iODInputFilename);
// Initialise the children SimFQT service context
initSIMFQTService (iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initSIMFQTService (const stdair::Filename_T& iFareInputFilename) {
// Retrieve the SimLFS service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Retrieve the StdAir service context
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
lSIMLFS_ServiceContext.getSTDAIR_Service();
assert (lSTDAIR_Service_ptr != NULL);
// Initialise the SIMFQT service handler
// Note that the (Boost.)Smart Pointer keeps track of the references
// on the Service object, and deletes that object when it is no longer
// referenced (e.g., at the end of the process).
SIMFQT_ServicePtr_T lSIMFQT_Service_ptr =
boost::make_shared<SIMFQT::SIMFQT_Service> (lSTDAIR_Service_ptr,
iFareInputFilename);
// Store the Simfqt service object within the (SimLFS) service context
lSIMLFS_ServiceContext.setSIMFQT_Service (lSIMFQT_Service_ptr);
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initAIRINV_Master_Service (const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename) {
// Retrieve the SimLFS service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Retrieve the StdAir service context
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
lSIMLFS_ServiceContext.getSTDAIR_Service();
assert (lSTDAIR_Service_ptr != NULL);
// Initialise the AIRINV service handler
// Note that the (Boost.)Smart Pointer keeps track of the references
// on the Service object, and deletes that object when it is no longer
// referenced (e.g., at the end of the process).
AIRINV_Master_ServicePtr_T lAIRINV_Master_Service_ptr =
boost::make_shared<AIRINV::AIRINV_Master_Service> (lSTDAIR_Service_ptr);
// Parse and load the schedule and O&D input files
lAIRINV_Master_Service_ptr->parseAndLoad (iScheduleInputFilename,
iODInputFilename);
// Store the Airinv service object within the (SimLFS) service context
lSIMLFS_ServiceContext.setAIRINV_Master_Service(lAIRINV_Master_Service_ptr);
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
fareQuote (const stdair::BookingRequestStruct& iBookingRequest,
stdair::TravelSolutionList_T& ioTravelSolutionList) {
if (_simlfsServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The SimLFS service has "
"not been initialised");
}
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
stdair::TravelSolutionList_T oTravelSolutionList;
// Get a reference on the SIMFQT service handler
SIMFQT_ServicePtr_T lSIMFQT_Service_ptr =
lSIMLFS_ServiceContext.getSIMFQT_Service();
assert (lSIMFQT_Service_ptr != NULL);
// Delegate the action to the dedicated command
stdair::BasChronometer lFareQuoteRetrievalChronometer;
lFareQuoteRetrievalChronometer.start();
lSIMFQT_Service_ptr->quotePrices (iBookingRequest, ioTravelSolutionList);
// DEBUG
const double lFareQuoteRetrievalMeasure =
lFareQuoteRetrievalChronometer.elapsed();
STDAIR_LOG_DEBUG ("Fare Quote retrieving: " << lFareQuoteRetrievalMeasure
<< " - " << lSIMLFS_ServiceContext.display());
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
calculateAvailability (stdair::TravelSolutionList_T& ioTravelSolutionList) {
if (_simlfsServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The SimLFS service has "
"not been initialised");
}
assert (_simlfsServiceContext != NULL);
//SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
}
}
<commit_msg>[SimLFS][Dev] Adapted the SimFQT service call to the new API.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
#include <stdair/stdair_basic_types.hpp>
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// Airline Inventory
#include <airinv/AIRINV_Master_Service.hpp>
// Fare Quote
#include <simfqt/SIMFQT_Service.hpp>
// SimLFS
#include <simlfs/basic/BasConst_SIMLFS_Service.hpp>
#include <simlfs/command/LowFareSearchManager.hpp>
#include <simlfs/factory/FacSimlfsServiceContext.hpp>
#include <simlfs/service/SIMLFS_ServiceContext.hpp>
#include <simlfs/SIMLFS_Service.hpp>
namespace SIMLFS {
// //////////////////////////////////////////////////////////////////////
SIMLFS_Service::SIMLFS_Service () : _simlfsServiceContext (NULL) {
assert (false);
}
// //////////////////////////////////////////////////////////////////////
SIMLFS_Service::SIMLFS_Service (const SIMLFS_Service& iService) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
SIMLFS_Service::
SIMLFS_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_ServicePtr,
const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename)
: _simlfsServiceContext (NULL) {
// Initialise the service context
initServiceContext ();
// Retrieve the Simlfs service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Store the STDAIR service object within the (SIMLFS) service context
lSIMLFS_ServiceContext.setSTDAIR_Service (ioSTDAIR_ServicePtr);
// Initialise the context
init (iScheduleInputFilename, iODInputFilename, iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
SIMLFS_Service::
SIMLFS_Service (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams,
const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename)
: _simlfsServiceContext (NULL) {
// Initialise the service context
initServiceContext ();
// Initialise the STDAIR service handler
initStdAirService (iLogParams, iDBParams);
// Initialise the (remaining of the) context
init (iScheduleInputFilename, iODInputFilename, iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
SIMLFS_Service::
SIMLFS_Service (const stdair::BasLogParams& iLogParams,
const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename)
: _simlfsServiceContext (NULL) {
// Initialise the service context
initServiceContext ();
// Initialise the STDAIR service handler
initStdAirService (iLogParams);
// Initialise the (remaining of the) context
init (iScheduleInputFilename, iODInputFilename, iFareInputFilename);
}
// //////////////////////////////////////////////////////////////////////
SIMLFS_Service::~SIMLFS_Service () {
// Delete/Clean all the objects from memory
finalise();
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::finalise () {
assert (_simlfsServiceContext != NULL);
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::initServiceContext () {
// Initialise the service context
SIMLFS_ServiceContext& lSIMLFS_ServiceContext =
FacSimlfsServiceContext::instance().create ();
_simlfsServiceContext = &lSIMLFS_ServiceContext;
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initStdAirService (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams) {
// Retrieve the Simlfs service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Initialise the STDAIR service handler
// Note that the track on the object memory is kept thanks to the Boost
// Smart Pointers component.
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);
// Store the STDAIR service object within the (SIMLFS) service context
lSIMLFS_ServiceContext.setSTDAIR_Service (lSTDAIR_Service_ptr);
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initStdAirService (const stdair::BasLogParams& iLogParams) {
// Retrieve the Simlfs service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Initialise the STDAIR service handler
// Note that the track on the object memory is kept thanks to the Boost
// Smart Pointers component.
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams);
// Store the STDAIR service object within the (SIMLFS) service context
lSIMLFS_ServiceContext.setSTDAIR_Service (lSTDAIR_Service_ptr);
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::init (const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename,
const stdair::Filename_T& iFareInputFilename) {
// Check that the file path given as input corresponds to an actual file
const bool doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (iFareInputFilename);
if (doesExistAndIsReadable == false) {
STDAIR_LOG_ERROR ("The fare input file, '" << iFareInputFilename
<< "', can not be retrieved on the file-system");
throw stdair::FileNotFoundException ("The fare input file, '"
+ iFareInputFilename
+ "', can not be retrieved on the "
+ "file-system");
}
// Initialise the children AirInv service context
initAIRINV_Master_Service (iScheduleInputFilename, iODInputFilename);
// Initialise the children SimFQT service context
initSIMFQTService (iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initSIMFQTService (const stdair::Filename_T& iFareInputFilename) {
// Retrieve the SimLFS service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Retrieve the StdAir service context
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
lSIMLFS_ServiceContext.getSTDAIR_Service();
assert (lSTDAIR_Service_ptr != NULL);
// Initialise the SIMFQT service handler
// Note that the (Boost.)Smart Pointer keeps track of the references
// on the Service object, and deletes that object when it is no longer
// referenced (e.g., at the end of the process).
SIMFQT_ServicePtr_T lSIMFQT_Service_ptr =
boost::make_shared<SIMFQT::SIMFQT_Service> (lSTDAIR_Service_ptr);
// Store the Simfqt service object within the (SimLFS) service context
lSIMLFS_ServiceContext.setSIMFQT_Service (lSIMFQT_Service_ptr);
// Parse the fare input file and load its content into memory
lSIMFQT_Service_ptr->parseAndLoad (iFareInputFilename);
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
initAIRINV_Master_Service (const stdair::Filename_T& iScheduleInputFilename,
const stdair::Filename_T& iODInputFilename) {
// Retrieve the SimLFS service context
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
// Retrieve the StdAir service context
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
lSIMLFS_ServiceContext.getSTDAIR_Service();
assert (lSTDAIR_Service_ptr != NULL);
// Initialise the AIRINV service handler
// Note that the (Boost.)Smart Pointer keeps track of the references
// on the Service object, and deletes that object when it is no longer
// referenced (e.g., at the end of the process).
AIRINV_Master_ServicePtr_T lAIRINV_Master_Service_ptr =
boost::make_shared<AIRINV::AIRINV_Master_Service> (lSTDAIR_Service_ptr);
// Parse and load the schedule and O&D input files
lAIRINV_Master_Service_ptr->parseAndLoad (iScheduleInputFilename,
iODInputFilename);
// Store the Airinv service object within the (SimLFS) service context
lSIMLFS_ServiceContext.setAIRINV_Master_Service(lAIRINV_Master_Service_ptr);
}
// //////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
fareQuote (const stdair::BookingRequestStruct& iBookingRequest,
stdair::TravelSolutionList_T& ioTravelSolutionList) {
if (_simlfsServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The SimLFS service has "
"not been initialised");
}
assert (_simlfsServiceContext != NULL);
SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
stdair::TravelSolutionList_T oTravelSolutionList;
// Get a reference on the SIMFQT service handler
SIMFQT_ServicePtr_T lSIMFQT_Service_ptr =
lSIMLFS_ServiceContext.getSIMFQT_Service();
assert (lSIMFQT_Service_ptr != NULL);
// Delegate the action to the dedicated command
stdair::BasChronometer lFareQuoteRetrievalChronometer;
lFareQuoteRetrievalChronometer.start();
lSIMFQT_Service_ptr->quotePrices (iBookingRequest, ioTravelSolutionList);
// DEBUG
const double lFareQuoteRetrievalMeasure =
lFareQuoteRetrievalChronometer.elapsed();
STDAIR_LOG_DEBUG ("Fare Quote retrieving: " << lFareQuoteRetrievalMeasure
<< " - " << lSIMLFS_ServiceContext.display());
}
// ////////////////////////////////////////////////////////////////////
void SIMLFS_Service::
calculateAvailability (stdair::TravelSolutionList_T& ioTravelSolutionList) {
if (_simlfsServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The SimLFS service has "
"not been initialised");
}
assert (_simlfsServiceContext != NULL);
//SIMLFS_ServiceContext& lSIMLFS_ServiceContext = *_simlfsServiceContext;
}
}
<|endoftext|> |
<commit_before>//#include "lodepng.h"
#include "filters.h"
//#include <iostream>
void decodeOneStep(const char* filename, std::vector<unsigned char> *image, unsigned *width, unsigned *height)
{
//decode
unsigned error = lodepng::decode(*image, *width, *height, filename);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
void encodeOneStep(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height)
{
//Encode the image
unsigned error = lodepng::encode(filename, image, width, height);
//if there's an error, display it
if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
}
void sepiaFilter(std::vector<unsigned char> *image, unsigned width, unsigned height){
float inRed, inGreen, inBlue;
for(unsigned y = 0; y < height*4; y++)
#pragma vector always
for(unsigned x = 0; x < width*4; x++)
{
int pos = width * y + x;
float newColor;
try{
switch (pos % 4) {
//RED
case 0:
inRed = image->at(pos);
inGreen = image->at(pos+1);
inBlue = image->at(pos+2);
newColor = (inRed * .393) + (inGreen * .769) + (inBlue * .189) - 30;
if (newColor > 255) {
image->at(pos) = 255;
}
else if (newColor < 0) {
image->at(pos) = 0;
}
else {
image->at(pos) = newColor;
}
break;
//GREEN
case 1:
newColor = (inRed * .349) + (inGreen * .686) + (inBlue * .168) - 30;
if (newColor > 255) {
image->at(pos) = 255;
}
else if (newColor < 0) {
image->at(pos) = 0;
}
else {
image->at(pos) = newColor;
}
break;
//BLUE
case 2:
newColor = (inRed * .272) + (inGreen * .534) + (inBlue * .131) - 30;
if (newColor > 255) {
image->at(pos) = 255;
}
else if (newColor < 0) {
image->at(pos) = 0;
}
else {
image->at(pos) = newColor;
}
break;
}
}
catch(std::out_of_range e){
}
}
}
void grayFilter(std::vector<unsigned char> *image, unsigned width, unsigned height){
float inRed, inGreen, inBlue;
for(unsigned y = 0; y < height*4; y++)
//#pragma vector always
for(unsigned x = 0; x < width*4; x = x + 4)
{
int pos = width * y + x;
float newColor;
try{
inRed = image->at(pos);
inGreen = image->at(pos+1);
inBlue = image->at(pos+2);
newColor = ( inRed + inGreen + inBlue ) / 3;
image->at(pos) = newColor;
image->at(pos + 1) = newColor;
image->at(pos + 2) = newColor;
}
catch(std::out_of_range e){
}
}
}
// int main(int argc, char *argv[])
// {
// const char* filename = argc > 1 ? argv[1] : "test.png";
// std::vector<unsigned char> image; //the raw pixels
// unsigned width, height;
// decodeOneStep(filename, &image, &width, &height);
// grayFilter(&image, width, height);
// encodeOneStep(filename, image, width, height);
// }<commit_msg>[MODIFY] filters.cpp optimization<commit_after>#include "filters.h"
void decodeOneStep(const char* filename,
std::vector<unsigned char> *image,
unsigned *width,
unsigned *height)
{
// decode
unsigned error = lodepng::decode(*image, *width, *height, filename);
// if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
// the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
void encodeOneStep(const char* filename,
std::vector<unsigned char>& image,
unsigned width,
unsigned height)
{
// Encode the image
unsigned error = lodepng::encode(filename, image, width, height);
// if there's an error, display it
if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
}
void sepiaFilter(std::vector<unsigned char> *image,
unsigned width,
unsigned height)
{
float inRed, inGreen, inBlue;
for(unsigned y = 0; y < height; y++)
#pragma simd
for(unsigned x = 0; x < width; x++)
{
int pos = ( width * y + x ) * 4;
float newColor;
inRed = image->at(pos);
inGreen = image->at(pos+1);
inBlue = image->at(pos+2);
//RED
newColor = (inRed * .393) + (inGreen * .769) + (inBlue * .189) - 30;
if (newColor > 255) {
image->at(pos) = 255;
}
else if (newColor < 0) {
image->at(pos) = 0;
}
else {
image->at(pos) = newColor;
}
//GREEN
newColor = (inRed * .349) + (inGreen * .686) + (inBlue * .168) - 30;
if (newColor > 255) {
image->at(pos + 1) = 255;
}
else if (newColor < 0) {
image->at(pos + 1) = 0;
}
else {
image->at(pos + 1) = newColor;
}
//BLUE
newColor = (inRed * .272) + (inGreen * .534) + (inBlue * .131) - 30;
if (newColor > 255) {
image->at(pos + 2) = 255;
}
else if (newColor < 0) {
image->at(pos + 2) = 0;
}
else {
image->at(pos + 2) = newColor;
}
}
}
void grayFilter(std::vector<unsigned char> *image,
unsigned width,
unsigned height)
{
float inRed, inGreen, inBlue;
for(unsigned y = 0; y < height; y++)
#pragma simd
for(unsigned x = 0; x < width; x++)
{
int pos = ( width * y + x ) * 4 ;
float newColor;
inRed = image->at(pos);
inGreen = image->at(pos+1);
inBlue = image->at(pos+2);
newColor = ( inRed + inGreen + inBlue ) / 3;
image->at(pos) = newColor;
image->at(pos + 1) = newColor;
image->at(pos + 2) = newColor;
}
}<|endoftext|> |
<commit_before>#include <apf.h>
#include "apfMDS.h"
#include <apfMesh2.h>
#include <gmi_mesh.h>
#include <PCU.h>
int main(int argc, char** argv)
{
assert(argc == 3);
MPI_Init(&argc,&argv);
PCU_Comm_Init();
gmi_register_mesh();
//load model and mesh
double t0 = MPI_Wtime();
apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
double t1 = MPI_Wtime();
if (!PCU_Comm_Self())
std::cout << t1-t0 << " seconds to load\n";
m->verify();
// adapt mds
apf::writeVtkFiles("out",m);
t0 = MPI_Wtime();
m->writeNative("out.smb");
t1 = MPI_Wtime();
if (!PCU_Comm_Self())
std::cout << t1-t0 << " seconds to write\n";
// destroy mds
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>mds_test works with sim model<commit_after>#include <apf.h>
#include "apfMDS.h"
#include <apfMesh2.h>
#include <gmi_mesh.h>
#include <gmi_sim.h>
#include <PCU.h>
#include <SimUtil.h>
#include <SimModel.h>
int main(int argc, char** argv)
{
assert(argc == 3);
MPI_Init(&argc,&argv);
Sim_readLicenseFile(0);
SimModel_start();
PCU_Comm_Init();
gmi_register_mesh();
gmi_register_sim();
//load model and mesh
double t0 = MPI_Wtime();
apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
double t1 = MPI_Wtime();
if (!PCU_Comm_Self())
std::cout << t1-t0 << " seconds to load\n";
m->verify();
// adapt mds
apf::writeVtkFiles("out",m);
t0 = MPI_Wtime();
m->writeNative("out.smb");
t1 = MPI_Wtime();
if (!PCU_Comm_Self())
std::cout << t1-t0 << " seconds to write\n";
// destroy mds
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
SimModel_stop();
Sim_unregisterAllKeys();
MPI_Finalize();
}
<|endoftext|> |
<commit_before>#include "HeatConductionMaterial.h"
template<>
InputParameters validParams<HeatConductionMaterial>()
{
InputParameters params = validParams<Material>();
params.addCoupledVar("temp", "Coupled Temperature");
params.addParam<Real>("thermal_conductivity", "The thermal conductivity value");
params.addParam<Real>("thermal_conductivity_x", "The thermal conductivity value in the x direction");
params.addParam<Real>("thermal_conductivity_y", "The thermal conductivity value in the y direction");
params.addParam<Real>("thermal_conductivity_z", "The thermal conductivity value in the z direction");
params.addParam<FunctionName>("thermal_conductivity_temperature_function", "", "Thermal conductivity as a function of temperature.");
params.addParam<Real>("specific_heat", "The specific heat value");
params.addParam<FunctionName>("specific_heat_temperature_function", "", "Specific heat as a function of temperature.");
return params;
}
HeatConductionMaterial::HeatConductionMaterial(const std::string & name, InputParameters parameters) :
Material(name, parameters),
_has_temp(isCoupled("temp")),
_temperature(_has_temp ? coupledValue("temp") : _zero),
_my_thermal_conductivity(isParamValid("thermal_conductivity") ? getParam<Real>("thermal_conductivity") : 0),
_my_thermal_conductivity_x(isParamValid("thermal_conductivity_x") ? getParam<Real>("thermal_conductivity_x") : 0),
_my_thermal_conductivity_y(isParamValid("thermal_conductivity_y") ? getParam<Real>("thermal_conductivity_y") : 0),
_my_thermal_conductivity_z(isParamValid("thermal_conductivity_z") ? getParam<Real>("thermal_conductivity_z") : 0),
_my_specific_heat(isParamValid("specific_heat") ? getParam<Real>("specific_heat") : 0),
_isotropic_thcond(isParamValid("thermal_conductivity") || getParam<FunctionName>("thermal_conductivity_temperature_function") != ""),
_thermal_conductivity(_isotropic_thcond ? &declareProperty<Real>("thermal_conductivity") : NULL),
_thermal_conductivity_dT(_isotropic_thcond ? &declareProperty<Real>("thermal_conductivity_dT") : NULL),
_thermal_conductivity_x(isParamValid("thermal_conductivity_x") ? &declareProperty<Real>("thermal_conductivity_x") : NULL),
_thermal_conductivity_x_dT(isParamValid("thermal_conductivity_x") ? &declareProperty<Real>("thermal_conductivity_x_dT") : NULL),
_thermal_conductivity_y(isParamValid("thermal_conductivity_y") ? &declareProperty<Real>("thermal_conductivity_y") : NULL),
_thermal_conductivity_y_dT(isParamValid("thermal_conductivity_y") ? &declareProperty<Real>("thermal_conductivity_y_dT") : NULL),
_thermal_conductivity_z(isParamValid("thermal_conductivity_z") ? &declareProperty<Real>("thermal_conductivity_z") : NULL),
_thermal_conductivity_z_dT(isParamValid("thermal_conductivity_z") ? &declareProperty<Real>("thermal_conductivity_z_dT") : NULL),
_thermal_conductivity_temperature_function( getParam<FunctionName>("thermal_conductivity_temperature_function") != "" ? &getFunction("thermal_conductivity_temperature_function") : NULL),
_specific_heat(declareProperty<Real>("specific_heat")),
_specific_heat_temperature_function( getParam<FunctionName>("specific_heat_temperature_function") != "" ? &getFunction("specific_heat_temperature_function") : NULL)
{
if (_thermal_conductivity_temperature_function && !_has_temp)
{
mooseError("Must couple with temperature if using thermal conductivity function");
}
if (_isotropic_thcond && (_thermal_conductivity_x || _thermal_conductivity_y || _thermal_conductivity_z))
{
mooseError("Cannot define both isotropic and orthotropic thermal conductivity");
}
if (!_isotropic_thcond && !_thermal_conductivity_x)
{
mooseError("Must define either isotropic or orthotropic thermal conductivity");
}
if (isParamValid("thermal_conductivity") && _thermal_conductivity_temperature_function)
{
mooseError("Cannot define both thermal conductivity and thermal conductivity temperature function");
}
if (!_isotropic_thcond &&
(_subproblem.mesh().dimension() > 1 && !_thermal_conductivity_y) ||
(_subproblem.mesh().dimension() > 2 && !_thermal_conductivity_z))
{
mooseError("Incomplete set of orthotropic thermal conductivity parameters");
}
if (_specific_heat_temperature_function && !_has_temp)
{
mooseError("Must couple with temperature if using specific heat function");
}
if (isParamValid("specific_heat") && _specific_heat_temperature_function)
{
mooseError("Cannot define both specific heat and specific heat temperature function");
}
}
void
HeatConductionMaterial::computeProperties()
{
for(unsigned int qp(0); qp < _qrule->n_points(); ++qp)
{
if (_isotropic_thcond)
{
if (_thermal_conductivity_temperature_function)
{
Point p;
(*_thermal_conductivity)[qp] = _thermal_conductivity_temperature_function->value(_temperature[qp], p);
(*_thermal_conductivity_dT)[qp] = 0;
}
else
{
(*_thermal_conductivity)[qp] = _my_thermal_conductivity;
(*_thermal_conductivity_dT)[qp] = 0;
}
}
else
{
(*_thermal_conductivity_x)[qp] = _my_thermal_conductivity_x;
(*_thermal_conductivity_x_dT)[qp] = 0;
if (_thermal_conductivity_y)
{
(*_thermal_conductivity_y)[qp] = _my_thermal_conductivity_y;
(*_thermal_conductivity_y_dT)[qp] = 0;
}
if (_thermal_conductivity_z)
{
(*_thermal_conductivity_z)[qp] = _my_thermal_conductivity_z;
(*_thermal_conductivity_z_dT)[qp] = 0;
}
}
if (_specific_heat_temperature_function)
{
Point p;
_specific_heat[qp] = _specific_heat_temperature_function->value(_temperature[qp], p);
}
else
{
_specific_heat[qp] = _my_specific_heat;
}
}
}
<commit_msg>Fix stuff I broke.<commit_after>#include "HeatConductionMaterial.h"
template<>
InputParameters validParams<HeatConductionMaterial>()
{
InputParameters params = validParams<Material>();
params.addCoupledVar("temp", "Coupled Temperature");
params.addParam<Real>("thermal_conductivity", "The thermal conductivity value");
params.addParam<Real>("thermal_conductivity_x", "The thermal conductivity value in the x direction");
params.addParam<Real>("thermal_conductivity_y", "The thermal conductivity value in the y direction");
params.addParam<Real>("thermal_conductivity_z", "The thermal conductivity value in the z direction");
params.addParam<FunctionName>("thermal_conductivity_temperature_function", "", "Thermal conductivity as a function of temperature.");
params.addParam<Real>("specific_heat", "The specific heat value");
params.addParam<FunctionName>("specific_heat_temperature_function", "", "Specific heat as a function of temperature.");
return params;
}
HeatConductionMaterial::HeatConductionMaterial(const std::string & name, InputParameters parameters) :
Material(name, parameters),
_has_temp(isCoupled("temp")),
_temperature(_has_temp ? coupledValue("temp") : _zero),
_my_thermal_conductivity(isParamValid("thermal_conductivity") ? getParam<Real>("thermal_conductivity") : 0),
_my_thermal_conductivity_x(isParamValid("thermal_conductivity_x") ? getParam<Real>("thermal_conductivity_x") : 0),
_my_thermal_conductivity_y(isParamValid("thermal_conductivity_y") ? getParam<Real>("thermal_conductivity_y") : 0),
_my_thermal_conductivity_z(isParamValid("thermal_conductivity_z") ? getParam<Real>("thermal_conductivity_z") : 0),
_my_specific_heat(isParamValid("specific_heat") ? getParam<Real>("specific_heat") : 0),
_isotropic_thcond(isParamValid("thermal_conductivity") || getParam<FunctionName>("thermal_conductivity_temperature_function") != ""),
_thermal_conductivity(_isotropic_thcond ? &declareProperty<Real>("thermal_conductivity") : NULL),
_thermal_conductivity_dT(_isotropic_thcond ? &declareProperty<Real>("thermal_conductivity_dT") : NULL),
_thermal_conductivity_x(isParamValid("thermal_conductivity_x") ? &declareProperty<Real>("thermal_conductivity_x") : NULL),
_thermal_conductivity_x_dT(isParamValid("thermal_conductivity_x") ? &declareProperty<Real>("thermal_conductivity_x_dT") : NULL),
_thermal_conductivity_y(isParamValid("thermal_conductivity_y") ? &declareProperty<Real>("thermal_conductivity_y") : NULL),
_thermal_conductivity_y_dT(isParamValid("thermal_conductivity_y") ? &declareProperty<Real>("thermal_conductivity_y_dT") : NULL),
_thermal_conductivity_z(isParamValid("thermal_conductivity_z") ? &declareProperty<Real>("thermal_conductivity_z") : NULL),
_thermal_conductivity_z_dT(isParamValid("thermal_conductivity_z") ? &declareProperty<Real>("thermal_conductivity_z_dT") : NULL),
_thermal_conductivity_temperature_function( getParam<FunctionName>("thermal_conductivity_temperature_function") != "" ? &getFunction("thermal_conductivity_temperature_function") : NULL),
_specific_heat(declareProperty<Real>("specific_heat")),
_specific_heat_temperature_function( getParam<FunctionName>("specific_heat_temperature_function") != "" ? &getFunction("specific_heat_temperature_function") : NULL)
{
if (_thermal_conductivity_temperature_function && !_has_temp)
{
mooseError("Must couple with temperature if using thermal conductivity function");
}
if (_isotropic_thcond && (_thermal_conductivity_x || _thermal_conductivity_y || _thermal_conductivity_z))
{
mooseError("Cannot define both isotropic and orthotropic thermal conductivity");
}
if (!_isotropic_thcond && !_thermal_conductivity_x)
{
mooseError("Must define either isotropic or orthotropic thermal conductivity");
}
if (isParamValid("thermal_conductivity") && _thermal_conductivity_temperature_function)
{
mooseError("Cannot define both thermal conductivity and thermal conductivity temperature function");
}
if (!_isotropic_thcond &&
((_subproblem.mesh().dimension() > 1 && !_thermal_conductivity_y) ||
(_subproblem.mesh().dimension() > 2 && !_thermal_conductivity_z)))
{
mooseError("Incomplete set of orthotropic thermal conductivity parameters");
}
if (_specific_heat_temperature_function && !_has_temp)
{
mooseError("Must couple with temperature if using specific heat function");
}
if (isParamValid("specific_heat") && _specific_heat_temperature_function)
{
mooseError("Cannot define both specific heat and specific heat temperature function");
}
}
void
HeatConductionMaterial::computeProperties()
{
for(unsigned int qp(0); qp < _qrule->n_points(); ++qp)
{
if (_isotropic_thcond)
{
if (_thermal_conductivity_temperature_function)
{
Point p;
(*_thermal_conductivity)[qp] = _thermal_conductivity_temperature_function->value(_temperature[qp], p);
(*_thermal_conductivity_dT)[qp] = 0;
}
else
{
(*_thermal_conductivity)[qp] = _my_thermal_conductivity;
(*_thermal_conductivity_dT)[qp] = 0;
}
}
else
{
(*_thermal_conductivity_x)[qp] = _my_thermal_conductivity_x;
(*_thermal_conductivity_x_dT)[qp] = 0;
if (_thermal_conductivity_y)
{
(*_thermal_conductivity_y)[qp] = _my_thermal_conductivity_y;
(*_thermal_conductivity_y_dT)[qp] = 0;
}
if (_thermal_conductivity_z)
{
(*_thermal_conductivity_z)[qp] = _my_thermal_conductivity_z;
(*_thermal_conductivity_z_dT)[qp] = 0;
}
}
if (_specific_heat_temperature_function)
{
Point p;
_specific_heat[qp] = _specific_heat_temperature_function->value(_temperature[qp], p);
}
else
{
_specific_heat[qp] = _my_specific_heat;
}
}
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robert Bosch LLC.
* 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 Robert Bosch 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 "modules/perception/traffic_light/util/color_space.h"
#include <cassert>
#include <cstdint>
#include "modules/common/log.h"
namespace apollo {
namespace perception {
namespace traffic_light {
#ifdef __USE_AVX__
template <bool align>
SIMD_INLINE void YuvSeperateAvx2(uint8_t *y, __m256i *y0, __m256i *y1,
__m256i *u0, __m256i *v0) {
DCHECK_NOTNULL(y0);
DCHECK_NOTNULL(y1);
DCHECK_NOTNULL(u0);
DCHECK_NOTNULL(v0);
__m256i yuv_m256[4];
if (align) {
yuv_m256[0] = Load<true>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<true>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<true>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<true>(reinterpret_cast<__m256i *>(y) + 3);
} else {
yuv_m256[0] = Load<false>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<false>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<false>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<false>(reinterpret_cast<__m256i *>(y) + 3);
}
*y0 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8));
*y1 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8));
*u0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))),
U_SHUFFLE4);
*v0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))),
U_SHUFFLE4);
}
template <bool align>
void Yuv2rgbAvx2(__m256i y0, __m256i u0, __m256i v0, uint8_t *rgb) {
__m256i r0 = YuvToRed(y0, v0);
__m256i g0 = YuvToGreen(y0, u0, v0);
__m256i b0 = YuvToBlue(y0, u0);
Store<align>(reinterpret_cast<__m256i *>(rgb) + 0,
InterleaveBgr<0>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 1,
InterleaveBgr<1>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 2,
InterleaveBgr<2>(r0, g0, b0));
}
template <bool align>
void Yuv2rgbAvx2(uint8_t *yuv, uint8_t *rgb) {
__m256i y0, y1, u0, v0;
YuvSeperateAvx2<align>(yuv, &y0, &y1, &u0, &v0);
__m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8);
__m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8);
Yuv2rgbAvx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0),
_mm256_unpacklo_epi8(v0_v0, v0_v0), rgb);
Yuv2rgbAvx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0),
_mm256_unpackhi_epi8(v0_v0, v0_v0),
rgb + 3 * sizeof(__m256i));
}
void Yuyv2rgb(unsigned char *YUV, unsigned char *RGB, int NumPixels) {
bool align = Aligned(YUV) & Aligned(RGB);
uint8_t *yuv_offset = YUV;
uint8_t *rgb_offset = RGB;
if (align) {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<true>(yuv_offset, rgb_offset);
}
} else {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<false>(yuv_offset, rgb_offset);
}
}
}
#else
unsigned char CLIPVALUE(int val) {
// Old method (if)
val = val < 0 ? 0 : val;
return val > 255 ? 255 : val;
// New method (array)
// return uchar_clipping_table[val + clipping_table_offset];
}
void YUV2RGB(const unsigned char y, const unsigned char u,
const unsigned char v, unsigned char* r, unsigned char* g,
unsigned char* b) {
const int y2 = static_cast<int>(y);
const int u2 = static_cast<int>(u) - 128;
const int v2 = static_cast<int>(v) - 128;
double r2 = y2 + (1.4065 * v2);
double g2 = y2 - (0.3455 * u2) - (0.7169 * v2);
double b2 = y2 + (2.041 * u2);
*r = CLIPVALUE(r2);
*g = CLIPVALUE(g2);
*b = CLIPVALUE(b2);
}
void Yuyv2rgb(unsigned char* YUV, unsigned char* RGB, int NumPixels) {
for (int i = 0, int j = 0; i < (NumPixels << 1); i += 4, j += 6) {
unsigned char u = (unsigned char)YUV[i + 0];
unsigned char y0 = (unsigned char)YUV[i + 1];
unsigned char v = (unsigned char)YUV[i + 2];
unsigned char y1 = (unsigned char)YUV[i + 3];
unsigned char r, g, b;
YUV2RGB(y0, u, v, &r, &g, &b);
RGB[j + 0] = r;
RGB[j + 1] = g;
RGB[j + 2] = b;
YUV2RGB(y1, u, v, &r, &g, &b);
RGB[j + 3] = r;
RGB[j + 4] = g;
RGB[j + 5] = b;
}
}
#endif
} // namespace traffic_light
} // namespace perception
} // namespace apollo
<commit_msg>Update color_space.cc<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robert Bosch LLC.
* 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 Robert Bosch 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 "modules/perception/traffic_light/util/color_space.h"
#include <cassert>
#include <cstdint>
#include "modules/common/log.h"
namespace apollo {
namespace perception {
namespace traffic_light {
#ifdef __USE_AVX__
template <bool align>
SIMD_INLINE void YuvSeperateAvx2(uint8_t *y, __m256i *y0, __m256i *y1,
__m256i *u0, __m256i *v0) {
DCHECK_NOTNULL(y0);
DCHECK_NOTNULL(y1);
DCHECK_NOTNULL(u0);
DCHECK_NOTNULL(v0);
__m256i yuv_m256[4];
if (align) {
yuv_m256[0] = Load<true>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<true>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<true>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<true>(reinterpret_cast<__m256i *>(y) + 3);
} else {
yuv_m256[0] = Load<false>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<false>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<false>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<false>(reinterpret_cast<__m256i *>(y) + 3);
}
*y0 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8));
*y1 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8));
*u0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))),
U_SHUFFLE4);
*v0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))),
U_SHUFFLE4);
}
template <bool align>
void Yuv2rgbAvx2(__m256i y0, __m256i u0, __m256i v0, uint8_t *rgb) {
__m256i r0 = YuvToRed(y0, v0);
__m256i g0 = YuvToGreen(y0, u0, v0);
__m256i b0 = YuvToBlue(y0, u0);
Store<align>(reinterpret_cast<__m256i *>(rgb) + 0,
InterleaveBgr<0>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 1,
InterleaveBgr<1>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 2,
InterleaveBgr<2>(r0, g0, b0));
}
template <bool align>
void Yuv2rgbAvx2(uint8_t *yuv, uint8_t *rgb) {
__m256i y0, y1, u0, v0;
YuvSeperateAvx2<align>(yuv, &y0, &y1, &u0, &v0);
__m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8);
__m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8);
Yuv2rgbAvx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0),
_mm256_unpacklo_epi8(v0_v0, v0_v0), rgb);
Yuv2rgbAvx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0),
_mm256_unpackhi_epi8(v0_v0, v0_v0),
rgb + 3 * sizeof(__m256i));
}
void Yuyv2rgb(unsigned char *YUV, unsigned char *RGB, int NumPixels) {
bool align = Aligned(YUV) & Aligned(RGB);
uint8_t *yuv_offset = YUV;
uint8_t *rgb_offset = RGB;
if (align) {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<true>(yuv_offset, rgb_offset);
}
} else {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<false>(yuv_offset, rgb_offset);
}
}
}
#else
unsigned char CLIPVALUE(int val) {
// Old method (if)
val = val < 0 ? 0 : val;
return val > 255 ? 255 : val;
// New method (array)
// return uchar_clipping_table[val + clipping_table_offset];
}
void YUV2RGB(const unsigned char y, const unsigned char u,
const unsigned char v, unsigned char* r, unsigned char* g,
unsigned char* b) {
const int y2 = static_cast<int>(y);
const int u2 = static_cast<int>(u) - 128;
const int v2 = static_cast<int>(v) - 128;
double r2 = y2 + (1.4065 * v2);
double g2 = y2 - (0.3455 * u2) - (0.7169 * v2);
double b2 = y2 + (2.041 * u2);
*r = CLIPVALUE(r2);
*g = CLIPVALUE(g2);
*b = CLIPVALUE(b2);
}
void Yuyv2rgb(unsigned char* YUV, unsigned char* RGB, int NumPixels) {
for (int i = 0, j = 0; i < (NumPixels << 1); i += 4, j += 6) {
unsigned char u = (unsigned char)YUV[i + 0];
unsigned char y0 = (unsigned char)YUV[i + 1];
unsigned char v = (unsigned char)YUV[i + 2];
unsigned char y1 = (unsigned char)YUV[i + 3];
unsigned char r, g, b;
YUV2RGB(y0, u, v, &r, &g, &b);
RGB[j + 0] = r;
RGB[j + 1] = g;
RGB[j + 2] = b;
YUV2RGB(y1, u, v, &r, &g, &b);
RGB[j + 3] = r;
RGB[j + 4] = g;
RGB[j + 5] = b;
}
}
#endif
} // namespace traffic_light
} // namespace perception
} // namespace apollo
<|endoftext|> |
<commit_before>
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_COLLISION_FRICTIONCONTACT_INL
#define SOFA_COMPONENT_COLLISION_FRICTIONCONTACT_INL
#include <sofa/component/collision/FrictionContact.h>
#include <sofa/component/collision/DefaultContactManager.h>
#include <sofa/component/collision/BarycentricContactMapper.h>
#include <sofa/component/collision/IdentityContactMapper.h>
#include <sofa/simulation/common/Node.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace core::collision;
using simulation::Node;
template < class TCollisionModel1, class TCollisionModel2 >
FrictionContact<TCollisionModel1,TCollisionModel2>::FrictionContact(CollisionModel1* model1, CollisionModel2* model2, Intersection* intersectionMethod)
: model1(model1)
, model2(model2)
, intersectionMethod(intersectionMethod)
, m_constraint(NULL)
, parent(NULL)
, mu (initData(&mu, 0.8, "mu", "friction coefficient (0 for frictionless contacts)"))
{
selfCollision = ((core::CollisionModel*)model1 == (core::CollisionModel*)model2);
mapper1.setCollisionModel(model1);
if (!selfCollision) mapper2.setCollisionModel(model2);
contacts.clear();
mappedContacts.clear();
}
template < class TCollisionModel1, class TCollisionModel2 >
FrictionContact<TCollisionModel1,TCollisionModel2>::~FrictionContact()
{
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::cleanup()
{
if (m_constraint)
{
m_constraint->cleanup();
if (parent != NULL)
parent->removeObject(m_constraint);
delete m_constraint;
parent = NULL;
m_constraint = NULL;
mapper1.cleanup();
if (!selfCollision)
mapper2.cleanup();
}
contacts.clear();
mappedContacts.clear();
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::setDetectionOutputs(OutputVector* o)
{
TOutputVector& outputs = *static_cast<TOutputVector*>(o);
// We need to remove duplicate contacts
const double minDist2 = 0.00000001f;
contacts.clear();
contacts.reserve(outputs.size());
int SIZE = outputs.size();
// the following procedure cancels the duplicated detection outputs
for (int cpt=0; cpt<SIZE; cpt++)
{
DetectionOutput* o = &outputs[cpt];
bool found = false;
for (unsigned int i=0; i<contacts.size() && !found; i++)
{
DetectionOutput* p = contacts[i];
if ((o->point[0]-p->point[0]).norm2()+(o->point[1]-p->point[1]).norm2() < minDist2)
found = true;
}
if (!found)
contacts.push_back(o);
}
if (contacts.size()<outputs.size())
{
// DUPLICATED CONTACTS FOUND
sout << "Removed " << (outputs.size()-contacts.size()) <<" / " << outputs.size() << " collision points." << sendl;
}
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::activateMappers()
{
if (!m_constraint)
{
// Get the mechanical model from mapper1 to fill the constraint vector
MechanicalState1* mmodel1 = mapper1.createMapping();
// Get the mechanical model from mapper2 to fill the constraints vector
MechanicalState2* mmodel2 = selfCollision ? mmodel1 : mapper2.createMapping();
m_constraint = new constraintset::UnilateralInteractionConstraint<Vec3Types>(mmodel1, mmodel2);
m_constraint->setName( getName() );
}
int size = contacts.size();
m_constraint->clear(size);
if (selfCollision)
mapper1.resize(2*size);
else
{
mapper1.resize(size);
mapper2.resize(size);
}
int i = 0;
const double d0 = intersectionMethod->getContactDistance() + model1->getProximity() + model2->getProximity(); // - 0.001;
//std::cout<<" d0 = "<<d0<<std::endl;
mappedContacts.resize(contacts.size());
for (std::vector<DetectionOutput*>::const_iterator it = contacts.begin(); it!=contacts.end(); it++, i++)
{
DetectionOutput* o = *it;
//std::cout<<" collisionElements :"<<o->elem.first<<" - "<<o->elem.second<<std::endl;
CollisionElement1 elem1(o->elem.first);
CollisionElement2 elem2(o->elem.second);
int index1 = elem1.getIndex();
int index2 = elem2.getIndex();
//std::cout<<" indices :"<<index1<<" - "<<index2<<std::endl;
typename DataTypes1::Real r1 = o->baryCoords[0][0];
typename DataTypes2::Real r2 = o->baryCoords[1][0];
//double constraintValue = ((o->point[1] - o->point[0]) * o->normal) - intersectionMethod->getContactDistance();
// Create mapping for first point
index1 = mapper1.addPoint(o->point[0], index1, r1);
// Create mapping for second point
index2 = selfCollision ? mapper1.addPoint(o->point[1], index2, r2) : mapper2.addPoint(o->point[1], index2, r2);
double distance = d0 + r1 + r2;
mappedContacts[i].first.first = index1;
mappedContacts[i].first.second = index2;
mappedContacts[i].second = distance;
}
// Update mappings
mapper1.update();
mapper1.updateXfree();
if (!selfCollision) mapper2.update();
if (!selfCollision) mapper2.updateXfree();
//std::cerr<<" end activateMappers call"<<std::endl;
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::createResponse(core::objectmodel::BaseContext* group)
{
activateMappers();
const double mu_ = this->mu.getValue();
// Checks if friction is considered
if (mu_ < 0.0 || mu_ > 1.0)
serr << sendl << "Error: mu has to take values between 0.0 and 1.0" << sendl;
int i=0;
if (m_constraint)
{
for (std::vector<DetectionOutput*>::const_iterator it = contacts.begin(); it!=contacts.end(); it++, i++)
{
DetectionOutput* o = *it;
int index1 = mappedContacts[i].first.first;
int index2 = mappedContacts[i].first.second;
double distance = mappedContacts[i].second;
// Polynome de Cantor de NxN sur N bijectif f(x,y)=((x+y)^2+3x+y)/2
long index = cantorPolynomia(o->id /*cantorPolynomia(index1, index2)*/,id);
// Add contact in unilateral constraint
m_constraint->addContact(mu_, o->normal, distance, index1, index2, index, o->id);
}
if (parent!=NULL)
{
parent->removeObject(this);
parent->removeObject(m_constraint);
}
parent = group;
if (parent!=NULL)
{
//sout << "Attaching contact response to "<<parent->getName()<<sendl;
parent->addObject(this);
parent->addObject(m_constraint);
}
}
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::removeResponse()
{
if (m_constraint)
{
mapper1.resize(0);
mapper2.resize(0);
if (parent!=NULL)
{
//sout << "Removing contact response from "<<parent->getName()<<sendl;
parent->removeObject(this);
parent->removeObject(m_constraint);
}
parent = NULL;
}
}
} // namespace collision
} // namespace component
} // namespace sofa
#endif
<commit_msg>r9884/sofa-dev : FIX : revert ContactFriction<commit_after>
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_COLLISION_FRICTIONCONTACT_INL
#define SOFA_COMPONENT_COLLISION_FRICTIONCONTACT_INL
#include <sofa/component/collision/FrictionContact.h>
#include <sofa/component/collision/DefaultContactManager.h>
#include <sofa/component/collision/BarycentricContactMapper.h>
#include <sofa/component/collision/IdentityContactMapper.h>
#include <sofa/simulation/common/Node.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace core::collision;
using simulation::Node;
template < class TCollisionModel1, class TCollisionModel2 >
FrictionContact<TCollisionModel1,TCollisionModel2>::FrictionContact(CollisionModel1* model1, CollisionModel2* model2, Intersection* intersectionMethod)
: model1(model1)
, model2(model2)
, intersectionMethod(intersectionMethod)
, m_constraint(NULL)
, parent(NULL)
, mu (initData(&mu, 0.8, "mu", "friction coefficient (0 for frictionless contacts)"))
{
selfCollision = ((core::CollisionModel*)model1 == (core::CollisionModel*)model2);
mapper1.setCollisionModel(model1);
if (!selfCollision) mapper2.setCollisionModel(model2);
contacts.clear();
mappedContacts.clear();
}
template < class TCollisionModel1, class TCollisionModel2 >
FrictionContact<TCollisionModel1,TCollisionModel2>::~FrictionContact()
{
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::cleanup()
{
if (m_constraint)
{
m_constraint->cleanup();
if (parent != NULL)
parent->removeObject(m_constraint);
delete m_constraint;
parent = NULL;
m_constraint = NULL;
mapper1.cleanup();
if (!selfCollision)
mapper2.cleanup();
}
contacts.clear();
mappedContacts.clear();
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::setDetectionOutputs(OutputVector* o)
{
TOutputVector& outputs = *static_cast<TOutputVector*>(o);
// We need to remove duplicate contacts
const double minDist2 = 0.00000001f;
contacts.clear();
contacts.reserve(outputs.size());
int SIZE = outputs.size();
// the following procedure cancels the duplicated detection outputs
for (int cpt=0; cpt<SIZE; cpt++)
{
DetectionOutput* o = &outputs[cpt];
bool found = false;
for (unsigned int i=0; i<contacts.size() && !found; i++)
{
DetectionOutput* p = contacts[i];
if ((o->point[0]-p->point[0]).norm2()+(o->point[1]-p->point[1]).norm2() < minDist2)
found = true;
}
if (!found)
contacts.push_back(o);
}
if (contacts.size()<outputs.size())
{
// DUPLICATED CONTACTS FOUND
sout << "Removed " << (outputs.size()-contacts.size()) <<" / " << outputs.size() << " collision points." << sendl;
}
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::activateMappers()
{
if (!m_constraint)
{
// Get the mechanical model from mapper1 to fill the constraint vector
MechanicalState1* mmodel1 = mapper1.createMapping();
// Get the mechanical model from mapper2 to fill the constraints vector
MechanicalState2* mmodel2 = selfCollision ? mmodel1 : mapper2.createMapping();
m_constraint = new constraintset::UnilateralInteractionConstraint<Vec3Types>(mmodel1, mmodel2);
m_constraint->setName( getName() );
}
int size = contacts.size();
m_constraint->clear(size);
if (selfCollision)
mapper1.resize(2*size);
else
{
mapper1.resize(size);
mapper2.resize(size);
}
int i = 0;
const double d0 = intersectionMethod->getContactDistance() + model1->getProximity() + model2->getProximity(); // - 0.001;
//std::cout<<" d0 = "<<d0<<std::endl;
mappedContacts.resize(contacts.size());
for (std::vector<DetectionOutput*>::const_iterator it = contacts.begin(); it!=contacts.end(); it++, i++)
{
DetectionOutput* o = *it;
//std::cout<<" collisionElements :"<<o->elem.first<<" - "<<o->elem.second<<std::endl;
CollisionElement1 elem1(o->elem.first);
CollisionElement2 elem2(o->elem.second);
int index1 = elem1.getIndex();
int index2 = elem2.getIndex();
//std::cout<<" indices :"<<index1<<" - "<<index2<<std::endl;
typename DataTypes1::Real r1 = 0.;
typename DataTypes2::Real r2 = 0.;
//double constraintValue = ((o->point[1] - o->point[0]) * o->normal) - intersectionMethod->getContactDistance();
// Create mapping for first point
index1 = mapper1.addPoint(o->point[0], index1, r1);
// Create mapping for second point
index2 = selfCollision ? mapper1.addPoint(o->point[1], index2, r2) : mapper2.addPoint(o->point[1], index2, r2);
double distance = d0 + r1 + r2;
mappedContacts[i].first.first = index1;
mappedContacts[i].first.second = index2;
mappedContacts[i].second = distance;
}
// Update mappings
mapper1.update();
mapper1.updateXfree();
if (!selfCollision) mapper2.update();
if (!selfCollision) mapper2.updateXfree();
//std::cerr<<" end activateMappers call"<<std::endl;
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::createResponse(core::objectmodel::BaseContext* group)
{
activateMappers();
const double mu_ = this->mu.getValue();
// Checks if friction is considered
if (mu_ < 0.0 || mu_ > 1.0)
serr << sendl << "Error: mu has to take values between 0.0 and 1.0" << sendl;
int i=0;
if (m_constraint)
{
for (std::vector<DetectionOutput*>::const_iterator it = contacts.begin(); it!=contacts.end(); it++, i++)
{
DetectionOutput* o = *it;
int index1 = mappedContacts[i].first.first;
int index2 = mappedContacts[i].first.second;
double distance = mappedContacts[i].second;
// Polynome de Cantor de NxN sur N bijectif f(x,y)=((x+y)^2+3x+y)/2
long index = cantorPolynomia(o->id /*cantorPolynomia(index1, index2)*/,id);
// Add contact in unilateral constraint
m_constraint->addContact(mu_, o->normal, distance, index1, index2, index, o->id);
}
if (parent!=NULL)
{
parent->removeObject(this);
parent->removeObject(m_constraint);
}
parent = group;
if (parent!=NULL)
{
//sout << "Attaching contact response to "<<parent->getName()<<sendl;
parent->addObject(this);
parent->addObject(m_constraint);
}
}
}
template < class TCollisionModel1, class TCollisionModel2 >
void FrictionContact<TCollisionModel1,TCollisionModel2>::removeResponse()
{
if (m_constraint)
{
mapper1.resize(0);
mapper2.resize(0);
if (parent!=NULL)
{
//sout << "Removing contact response from "<<parent->getName()<<sendl;
parent->removeObject(this);
parent->removeObject(m_constraint);
}
parent = NULL;
}
}
} // namespace collision
} // namespace component
} // namespace sofa
#endif
<|endoftext|> |
<commit_before>
#include "firebasepush.hh"
#include <iostream>
#include <string.h>
#include <flexisip/logmanager.hh>
using namespace std;
using namespace flexisip;
/*
* This supports the legacy http Firebase protocol:
* https://firebase.google.com/docs/cloud-messaging/http-server-ref
*/
FirebasePushNotificationRequest::FirebasePushNotificationRequest(const PushInfo &pinfo)
: PushNotificationRequest(pinfo.mAppId, "firebase") {
const string &deviceToken = pinfo.mDeviceToken;
const string &apiKey = pinfo.mApiKey;
const string &from = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName;
ostringstream httpBody;
string date = getPushTimeStamp();
httpBody << "{\"to\":\"" << deviceToken << "\", \"priority\":\"high\""
<< ", \"data\":{"
<< "\"uuid\":" << quoteStringIfNeeded(pinfo.mUid)
<< ", \"call-id\":" << quoteStringIfNeeded(pinfo.mCallId)
<< ", \"sip-from\":" << quoteStringIfNeeded(from)
<< ", \"loc-key\":" << quoteStringIfNeeded(pinfo.mAlertMsgId)
<< ", \"loc-args\":" << quoteStringIfNeeded(from)
<< ", \"send-time\":" << quoteStringIfNeeded(date) << "}"
<< "}";
mHttpBody = httpBody.str();
LOGD("Push notification https post body is %s", mHttpBody.c_str());
ostringstream httpHeader;
httpHeader << "POST /fcm/send "
"HTTP/1.1\r\nHost:fcm.googleapis.com\r\nContent-Type:application/json\r\nAuthorization:key="
<< apiKey << "\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n";
mHttpHeader = httpHeader.str();
SLOGD << "PNR " << this << " https post header is " << mHttpHeader;
}
void FirebasePushNotificationRequest::createPushNotification() {
int headerLength = mHttpHeader.length();
int bodyLength = mHttpBody.length();
mBuffer.clear();
mBuffer.resize(headerLength + bodyLength);
char *binaryMessageBuff = &mBuffer[0];
char *binaryMessagePt = binaryMessageBuff;
memcpy(binaryMessagePt, &mHttpHeader[0], headerLength);
binaryMessagePt += headerLength;
memcpy(binaryMessagePt, &mHttpBody[0], bodyLength);
binaryMessagePt += bodyLength;
}
const vector<char> &FirebasePushNotificationRequest::getData() {
createPushNotification();
return mBuffer;
}
string FirebasePushNotificationRequest::isValidResponse(const string &str) {
static const char expected[] = "HTTP/1.1 200";
return strncmp(expected, str.c_str(), sizeof(expected) - 1) == 0 ? "" : "Unexpected HTTP response value (not 200 OK)";
}
<commit_msg>Trying to set ttl to 0 to fix push not received<commit_after>
#include "firebasepush.hh"
#include <iostream>
#include <string.h>
#include <flexisip/logmanager.hh>
using namespace std;
using namespace flexisip;
/*
* This supports the legacy http Firebase protocol:
* https://firebase.google.com/docs/cloud-messaging/http-server-ref
*/
FirebasePushNotificationRequest::FirebasePushNotificationRequest(const PushInfo &pinfo)
: PushNotificationRequest(pinfo.mAppId, "firebase") {
const string &deviceToken = pinfo.mDeviceToken;
const string &apiKey = pinfo.mApiKey;
const string &from = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName;
ostringstream httpBody;
string date = getPushTimeStamp();
int ttl = (pinfo.mEvent == PushInfo::Call) ? 0 : 2419200; // 4 weeks, it is the maximum allowed TTL for firebase push
httpBody << "{\"to\":\"" << deviceToken << "\", "
<< "\"time_to_live\": " << ttl << ", "
<< "\"priority\":\"high\""
<< ", \"data\":{"
<< "\"uuid\":" << quoteStringIfNeeded(pinfo.mUid)
<< ", \"call-id\":" << quoteStringIfNeeded(pinfo.mCallId)
<< ", \"sip-from\":" << quoteStringIfNeeded(from)
<< ", \"loc-key\":" << quoteStringIfNeeded(pinfo.mAlertMsgId)
<< ", \"loc-args\":" << quoteStringIfNeeded(from)
<< ", \"send-time\":" << quoteStringIfNeeded(date) << "}"
<< "}";
mHttpBody = httpBody.str();
LOGD("Push notification https post body is %s", mHttpBody.c_str());
ostringstream httpHeader;
httpHeader << "POST /fcm/send "
"HTTP/1.1\r\nHost:fcm.googleapis.com\r\nContent-Type:application/json\r\nAuthorization:key="
<< apiKey << "\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n";
mHttpHeader = httpHeader.str();
SLOGD << "PNR " << this << " https post header is " << mHttpHeader;
}
void FirebasePushNotificationRequest::createPushNotification() {
int headerLength = mHttpHeader.length();
int bodyLength = mHttpBody.length();
mBuffer.clear();
mBuffer.resize(headerLength + bodyLength);
char *binaryMessageBuff = &mBuffer[0];
char *binaryMessagePt = binaryMessageBuff;
memcpy(binaryMessagePt, &mHttpHeader[0], headerLength);
binaryMessagePt += headerLength;
memcpy(binaryMessagePt, &mHttpBody[0], bodyLength);
binaryMessagePt += bodyLength;
}
const vector<char> &FirebasePushNotificationRequest::getData() {
createPushNotification();
return mBuffer;
}
string FirebasePushNotificationRequest::isValidResponse(const string &str) {
static const char expected[] = "HTTP/1.1 200";
return strncmp(expected, str.c_str(), sizeof(expected) - 1) == 0 ? "" : "Unexpected HTTP response value (not 200 OK)";
}
<|endoftext|> |
<commit_before>// Copyright (C) 2014, Richard Thomson. All rights reserved.
#include "json.h"
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/qi.hpp>
using namespace boost::spirit::qi;
namespace
{
typedef std::pair<std::string, json::value> key_value_pair;
}
BOOST_FUSION_ADAPT_STRUCT(::key_value_pair,
(std::string, first)
(json::value, second)
);
namespace
{
typedef ascii::space_type skipper;
template <typename Iter>
struct json_grammar : grammar<Iter, json::value(), skipper>
{
json_grammar() : json_grammar::base_type(start)
{
boolean = bool_;
integer = int_ >> !no_case[char_(".e")];
number = double_;
escapes.add(R"(\")", '"')
(R"(\\)", '\\')
(R"(\/)", '/')
(R"(\b)", '\b')
(R"(\f)", '\f')
(R"(\n)", '\n')
(R"(\r)", '\r')
(R"(\t)", '\t');
quoted_string = lexeme['"' >> *(escapes | (char_ - '"')) >> '"'];
array_value = '[' >> ((value % ',') | eps) >> ']';
key_value = quoted_string >> ':' >> value;
object_value = ('{' >> ((key_value % ',') | eps) >> '}');
value = boolean | integer | number | quoted_string
| array_value | object_value;
start = value;
}
rule<Iter, json::value(), skipper> start;
rule<Iter, bool(), skipper> boolean;
rule<Iter, int(), skipper> integer;
rule<Iter, double(), skipper> number;
rule<Iter, std::string(), skipper> quoted_string;
symbols<char const, char const> escapes;
rule<Iter, json::value(), skipper> value;
rule<Iter, json::array(), skipper> array_value;
rule<Iter, key_value_pair(), skipper> key_value;
rule<Iter, json::object(), skipper> object_value;
};
}
namespace json
{
value parse(std::string const& text)
{
std::string::const_iterator start{text.begin()};
value result;
if (phrase_parse(start, text.end(),
json_grammar<std::string::const_iterator>(),
ascii::space, result)
&& start == text.end())
{
return result;
}
throw std::domain_error("invalid JSON input");
}
}
<commit_msg>Include what you use<commit_after>// Copyright (C) 2014, Richard Thomson. All rights reserved.
#include "json.h"
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <stdexcept>
using namespace boost::spirit::qi;
namespace
{
typedef std::pair<std::string, json::value> key_value_pair;
}
BOOST_FUSION_ADAPT_STRUCT(::key_value_pair,
(std::string, first)
(json::value, second)
);
namespace
{
typedef ascii::space_type skipper;
template <typename Iter>
struct json_grammar : grammar<Iter, json::value(), skipper>
{
json_grammar() : json_grammar::base_type(start)
{
boolean = bool_;
integer = int_ >> !no_case[char_(".e")];
number = double_;
escapes.add(R"(\")", '"')
(R"(\\)", '\\')
(R"(\/)", '/')
(R"(\b)", '\b')
(R"(\f)", '\f')
(R"(\n)", '\n')
(R"(\r)", '\r')
(R"(\t)", '\t');
quoted_string = lexeme['"' >> *(escapes | (char_ - '"')) >> '"'];
array_value = '[' >> ((value % ',') | eps) >> ']';
key_value = quoted_string >> ':' >> value;
object_value = ('{' >> ((key_value % ',') | eps) >> '}');
value = boolean | integer | number | quoted_string
| array_value | object_value;
start = value;
}
rule<Iter, json::value(), skipper> start;
rule<Iter, bool(), skipper> boolean;
rule<Iter, int(), skipper> integer;
rule<Iter, double(), skipper> number;
rule<Iter, std::string(), skipper> quoted_string;
symbols<char const, char const> escapes;
rule<Iter, json::value(), skipper> value;
rule<Iter, json::array(), skipper> array_value;
rule<Iter, key_value_pair(), skipper> key_value;
rule<Iter, json::object(), skipper> object_value;
};
}
namespace json
{
value parse(std::string const& text)
{
std::string::const_iterator start{text.begin()};
value result;
if (phrase_parse(start, text.end(),
json_grammar<std::string::const_iterator>(),
ascii::space, result)
&& start == text.end())
{
return result;
}
throw std::domain_error("invalid JSON input");
}
}
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsenote.hh"
#include "bseutils.hh"
#include "bseieee754.hh"
#include "bsemathsignal.hh"
#include <string.h>
#include <birnet/birnet.hh>
/* --- functions --- */
namespace {
struct FreqCmp {
inline int
operator() (float f1,
float f2)
{
return f1 < f2 ? -1 : f1 > f2;
}
};
} // Anon
int
bse_note_from_freq (BseMusicalTuningType musical_tuning,
double freq)
{
freq /= BSE_KAMMER_FREQUENCY;
const double *table = bse_semitone_table_from_tuning (musical_tuning);
const double *start = table - 132;
const double *end = table + 1 + 132;
const double *m = Birnet::binary_lookup_sibling (start, end, FreqCmp(), freq);
if (m == end)
return BSE_NOTE_VOID;
/* improve from sibling to nearest */
#if 1 /* nearest by smallest detuning factor */
if (freq > m[0] && m + 1 < end && m[1] / freq < freq / m[0])
m++;
else if (freq < m[0] && m > start && freq / m[-1] < m[0] / freq)
m--;
#else /* nearest by linear distance */
if (freq > m[0] && m + 1 < end && m[1] - freq < freq - m[0])
m++;
else if (freq < m[0] && m > start && freq - m[-1] < m[0] - freq)
m--;
#endif
/* transform to note */
if (0)
g_printerr ("freqlookup: %.9f < %.9f < %.9f : key = %.9f diffs = %+.9f %+.9f %+.9f\n", m[-1], m[0], m[1], freq,
freq - m[-1], freq - m[0], m[1] - freq);
int note = m - table + BSE_KAMMER_NOTE;
/* yield VOID when exceeding corner cases */
if (note + 1 < BSE_MIN_NOTE || note > BSE_MAX_NOTE + 1)
return BSE_NOTE_VOID;
return CLAMP (note, BSE_MIN_NOTE, BSE_MAX_NOTE);
}
int
bse_note_from_freq_bounded (BseMusicalTuningType musical_tuning,
double freq)
{
int note = bse_note_from_freq (musical_tuning, freq);
if (note != BSE_NOTE_VOID)
return note;
else
return freq > BSE_KAMMER_FREQUENCY ? BSE_MAX_NOTE : BSE_MIN_NOTE;
}
int
bse_note_fine_tune_from_note_freq (BseMusicalTuningType musical_tuning,
int note,
double freq)
{
double semitone_factor = bse_transpose_factor (musical_tuning, CLAMP (note, BSE_MIN_NOTE, BSE_MAX_NOTE) - SFI_KAMMER_NOTE);
freq /= BSE_KAMMER_FREQUENCY * semitone_factor;
double d = log (freq) / BSE_LN_2_POW_1_DIV_1200_d;
int fine_tune = bse_ftoi (d);
return CLAMP (fine_tune, BSE_MIN_FINE_TUNE, BSE_MAX_FINE_TUNE);
}
double
bse_note_to_freq (BseMusicalTuningType musical_tuning,
int note)
{
if (note < BSE_MIN_NOTE || note > BSE_MAX_NOTE)
return 0.0;
double semitone_factor = bse_transpose_factor (musical_tuning, note - SFI_KAMMER_NOTE);
return BSE_KAMMER_FREQUENCY * semitone_factor;
}
double
bse_note_to_tuned_freq (BseMusicalTuningType musical_tuning,
int note,
int fine_tune)
{
if (note < BSE_MIN_NOTE || note > BSE_MAX_NOTE)
return 0.0;
double semitone_factor = bse_transpose_factor (musical_tuning, note - SFI_KAMMER_NOTE);
return BSE_KAMMER_FREQUENCY * semitone_factor * bse_cent_tune_fast (fine_tune);
}
/* --- freq array --- */
struct BseFreqArray {
guint n_values;
guint n_prealloced;
gdouble *values;
};
BseFreqArray*
bse_freq_array_new (guint prealloc)
{
BseFreqArray *farray = g_new0 (BseFreqArray, 1);
farray->n_prealloced = prealloc;
farray->values = g_new0 (gdouble, farray->n_prealloced);
return farray;
}
void
bse_freq_array_free (BseFreqArray *farray)
{
g_return_if_fail (farray != NULL);
g_free (farray->values);
g_free (farray);
}
guint
bse_freq_array_n_values (BseFreqArray *farray)
{
g_return_val_if_fail (farray != NULL, 0);
return farray->n_values;
}
gdouble
bse_freq_array_get (BseFreqArray *farray,
guint index)
{
g_return_val_if_fail (farray != NULL, 0);
g_return_val_if_fail (index < farray->n_values, 0);
return farray->values[index];
}
void
bse_freq_array_insert (BseFreqArray *farray,
guint index,
gdouble value)
{
guint i;
g_return_if_fail (farray != NULL);
g_return_if_fail (index <= farray->n_values);
i = farray->n_values;
i = farray->n_values += 1;
if (farray->n_values > farray->n_prealloced)
{
farray->n_prealloced = farray->n_values;
farray->values = g_renew (gdouble, farray->values, farray->n_prealloced);
}
g_memmove (farray->values + index + 1,
farray->values + index,
i - index);
farray->values[index] = value;
}
void
bse_freq_array_append (BseFreqArray *farray,
gdouble value)
{
bse_freq_array_insert (farray, farray->n_values, value);
}
void
bse_freq_array_set (BseFreqArray *farray,
guint index,
gdouble value)
{
g_return_if_fail (farray != NULL);
g_return_if_fail (index < farray->n_values);
farray->values[index] = value;
}
gboolean
bse_freq_arrays_match_freq (gfloat match_freq,
BseFreqArray *inclusive_set,
BseFreqArray *exclusive_set)
{
guint i;
if (exclusive_set)
for (i = 0; i < exclusive_set->n_values; i++)
{
gdouble *value = exclusive_set->values + i;
if (fabs (*value - match_freq) < BSE_FREQUENCY_EPSILON)
return FALSE;
}
if (!inclusive_set)
return TRUE;
for (i = 0; i < inclusive_set->n_values; i++)
{
gdouble *value = inclusive_set->values + i;
if (fabs (*value - match_freq) < BSE_FREQUENCY_EPSILON)
return TRUE;
}
return FALSE;
}
<commit_msg>BSE: use Bse::binary_lookup* functions<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsenote.hh"
#include "bseutils.hh"
#include "bseieee754.hh"
#include "bsemathsignal.hh"
#include <string.h>
#include <birnet/birnet.hh>
/* --- functions --- */
namespace {
struct FreqCmp {
inline int
operator() (float f1,
float f2)
{
return f1 < f2 ? -1 : f1 > f2;
}
};
} // Anon
int
bse_note_from_freq (BseMusicalTuningType musical_tuning,
double freq)
{
freq /= BSE_KAMMER_FREQUENCY;
const double *table = bse_semitone_table_from_tuning (musical_tuning);
const double *start = table - 132;
const double *end = table + 1 + 132;
const double *m = Bse::binary_lookup_sibling (start, end, FreqCmp(), freq);
if (m == end)
return BSE_NOTE_VOID;
/* improve from sibling to nearest */
#if 1 /* nearest by smallest detuning factor */
if (freq > m[0] && m + 1 < end && m[1] / freq < freq / m[0])
m++;
else if (freq < m[0] && m > start && freq / m[-1] < m[0] / freq)
m--;
#else /* nearest by linear distance */
if (freq > m[0] && m + 1 < end && m[1] - freq < freq - m[0])
m++;
else if (freq < m[0] && m > start && freq - m[-1] < m[0] - freq)
m--;
#endif
/* transform to note */
if (0)
g_printerr ("freqlookup: %.9f < %.9f < %.9f : key = %.9f diffs = %+.9f %+.9f %+.9f\n", m[-1], m[0], m[1], freq,
freq - m[-1], freq - m[0], m[1] - freq);
int note = m - table + BSE_KAMMER_NOTE;
/* yield VOID when exceeding corner cases */
if (note + 1 < BSE_MIN_NOTE || note > BSE_MAX_NOTE + 1)
return BSE_NOTE_VOID;
return CLAMP (note, BSE_MIN_NOTE, BSE_MAX_NOTE);
}
int
bse_note_from_freq_bounded (BseMusicalTuningType musical_tuning,
double freq)
{
int note = bse_note_from_freq (musical_tuning, freq);
if (note != BSE_NOTE_VOID)
return note;
else
return freq > BSE_KAMMER_FREQUENCY ? BSE_MAX_NOTE : BSE_MIN_NOTE;
}
int
bse_note_fine_tune_from_note_freq (BseMusicalTuningType musical_tuning,
int note,
double freq)
{
double semitone_factor = bse_transpose_factor (musical_tuning, CLAMP (note, BSE_MIN_NOTE, BSE_MAX_NOTE) - SFI_KAMMER_NOTE);
freq /= BSE_KAMMER_FREQUENCY * semitone_factor;
double d = log (freq) / BSE_LN_2_POW_1_DIV_1200_d;
int fine_tune = bse_ftoi (d);
return CLAMP (fine_tune, BSE_MIN_FINE_TUNE, BSE_MAX_FINE_TUNE);
}
double
bse_note_to_freq (BseMusicalTuningType musical_tuning,
int note)
{
if (note < BSE_MIN_NOTE || note > BSE_MAX_NOTE)
return 0.0;
double semitone_factor = bse_transpose_factor (musical_tuning, note - SFI_KAMMER_NOTE);
return BSE_KAMMER_FREQUENCY * semitone_factor;
}
double
bse_note_to_tuned_freq (BseMusicalTuningType musical_tuning,
int note,
int fine_tune)
{
if (note < BSE_MIN_NOTE || note > BSE_MAX_NOTE)
return 0.0;
double semitone_factor = bse_transpose_factor (musical_tuning, note - SFI_KAMMER_NOTE);
return BSE_KAMMER_FREQUENCY * semitone_factor * bse_cent_tune_fast (fine_tune);
}
/* --- freq array --- */
struct BseFreqArray {
guint n_values;
guint n_prealloced;
gdouble *values;
};
BseFreqArray*
bse_freq_array_new (guint prealloc)
{
BseFreqArray *farray = g_new0 (BseFreqArray, 1);
farray->n_prealloced = prealloc;
farray->values = g_new0 (gdouble, farray->n_prealloced);
return farray;
}
void
bse_freq_array_free (BseFreqArray *farray)
{
g_return_if_fail (farray != NULL);
g_free (farray->values);
g_free (farray);
}
guint
bse_freq_array_n_values (BseFreqArray *farray)
{
g_return_val_if_fail (farray != NULL, 0);
return farray->n_values;
}
gdouble
bse_freq_array_get (BseFreqArray *farray,
guint index)
{
g_return_val_if_fail (farray != NULL, 0);
g_return_val_if_fail (index < farray->n_values, 0);
return farray->values[index];
}
void
bse_freq_array_insert (BseFreqArray *farray,
guint index,
gdouble value)
{
guint i;
g_return_if_fail (farray != NULL);
g_return_if_fail (index <= farray->n_values);
i = farray->n_values;
i = farray->n_values += 1;
if (farray->n_values > farray->n_prealloced)
{
farray->n_prealloced = farray->n_values;
farray->values = g_renew (gdouble, farray->values, farray->n_prealloced);
}
g_memmove (farray->values + index + 1,
farray->values + index,
i - index);
farray->values[index] = value;
}
void
bse_freq_array_append (BseFreqArray *farray,
gdouble value)
{
bse_freq_array_insert (farray, farray->n_values, value);
}
void
bse_freq_array_set (BseFreqArray *farray,
guint index,
gdouble value)
{
g_return_if_fail (farray != NULL);
g_return_if_fail (index < farray->n_values);
farray->values[index] = value;
}
gboolean
bse_freq_arrays_match_freq (gfloat match_freq,
BseFreqArray *inclusive_set,
BseFreqArray *exclusive_set)
{
guint i;
if (exclusive_set)
for (i = 0; i < exclusive_set->n_values; i++)
{
gdouble *value = exclusive_set->values + i;
if (fabs (*value - match_freq) < BSE_FREQUENCY_EPSILON)
return FALSE;
}
if (!inclusive_set)
return TRUE;
for (i = 0; i < inclusive_set->n_values; i++)
{
gdouble *value = inclusive_set->values + i;
if (fabs (*value - match_freq) < BSE_FREQUENCY_EPSILON)
return TRUE;
}
return FALSE;
}
<|endoftext|> |
<commit_before>#include "includes.h"
SDL_Window * mainWindow = NULL;
SDL_Renderer * mainRenderer = NULL;
bool init();
bool loadMedia();
void close();
bool checkCollision(vector<SDL_Rect>& a, vector<SDL_Rect>& b);
const int gameWidth = 1280;
const int gameHeight = 720;
#include <iostream>
#include <cstring>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <vector>
using namespace std;
class monster
{
public:
monster(int, int, int);
void renderMonster();
void shoot();
void moveMonster();
void kill();
vector<SDL_Rect> &getCollider();
void setCollider();
void setSize();
private:
int spawnX, spawnY;
int monsterType;
int offsetX, offsetY;
vector<SDL_Rect> mCollider;
int monsterWidth;
int monsterHeight;
bool changeDir;
};
class bullet
{
public:
bullet(int, int);
static const int bulletvelocity = 12;
void travel();
void renderbullet();
void destroy();
void setCollider();
vector<SDL_Rect>& getCollider();
private:
int bPosX, bPosY;
int bVelY;
vector<SDL_Rect> bCollider;
};
struct node
{
bullet * currentBullet;
node * next;
};
void insertLLLnode(node * &head, int, int);
void renderLLLbullet(node * head);
void findCollision(node * head, shipProtector, shipProtector, shipProtector, shipProtector, shipProtector);
void setColliders(node * head);
class mainShip
{
public:
mainShip();
static const int shipWidth = 64;
static const int shipHeight = 64;
static const int shipVelocity = 10;
void handleEvent(SDL_Event &event);
void moveShip();
void render();
private:
int sPosX, sPosY;
int sVelX, sVelY;
};
class GameTexture
{
public:
GameTexture();
~GameTexture();
bool loadFromFile(string);
void deallocate();
void render(int, int);
void free();
int getWidth();
int getHeight();
private:
SDL_Texture * mTexture;
int tWidth;
int tHeight;
};
class shipProtector
{
public:
static const int protectorWidth = 128;
static const int protectorHeight = 110;
shipProtector(int, int);
void renderProtector();
vector<SDL_Rect>& getColliders(int);
int getX();
int getY();
void coutCollision();
void setColliders();
private:
int pPosX, pPosY;
vector<SDL_Rect> pColliders;
};
node * head = NULL;
GameTexture bgTexture;
GameTexture shipTexture;
GameTexture pTexLBB;
GameTexture pTexRBB;
GameTexture pTexLBT;
GameTexture pTexLCEB;
GameTexture pTexLCET;
GameTexture pTexLCOB;
GameTexture pTexLCOT;
GameTexture pTexRBT;
GameTexture pTexRCEB;
GameTexture pTexRCET;
GameTexture pTexRCOB;
GameTexture pTexRCOT;
GameTexture bulletTexture;
GameTexture monsterTypeA;
GameTexture monsterTypeB;
GameTexture monsterTypeC;
int main(int argc, char * argv[])
{
int adder = 150;
if(!init())
cout << "\nSDL Failed to Initialize. ERROR: " << SDL_GetError();
else
{
if(!loadMedia())
cout << "\nLoading media failed. ERROR: " << SDL_GetError();
else
{
bool quit = false;
SDL_Event event;
mainShip ship;
monster testMonster(1140, 250, 1);
monster testMonsterb(1040, 250, 2);
monster testMonsterc(940, 250, 3);
//shipProtector protectora(150, 440);
shipProtector protectorb(375, 440);
shipProtector protectorc(600, 440);
shipProtector protectord(825, 440);
shipProtector protectore(1025, 440);
//protectora.setColliders();
protectorb.setColliders();
protectorc.setColliders();
protectord.setColliders();
protectore.setColliders();
while (!quit)
{
while(SDL_PollEvent(&event) != 0)
{
if(event.type == SDL_QUIT)
quit = true;
ship.handleEvent(event);
}
ship.moveShip();
testMonster.setSize();
testMonsterb.setSize();
testMonsterc.setSize();
testMonster.moveMonster();
testMonsterb.moveMonster();
testMonsterc.moveMonster();
SDL_SetRenderDrawColor(mainRenderer, 0xFF, 0xFF, 0xFF,0xFF);
bgTexture.render(0,0);
shipProtector protectora(adder, 440);
protectora.setColliders();
setColliders(head);
findCollision(head, protectora, protectorb, protectorc, protectord, protectore);
ship.render();
protectora.renderProtector();
protectorb.renderProtector();
protectorc.renderProtector();
protectord.renderProtector();
protectore.renderProtector();
renderLLLbullet(head);
testMonster.renderMonster();
testMonsterb.renderMonster();
testMonsterc.renderMonster();
SDL_RenderPresent(mainRenderer); // RENDER ALL TO FRONT BUFFER
/* if(checkCollision(protectora.getColliders(),protectorb.getColliders()))
cout << "\nCOLLISION DETECTED!";
else if(!(checkCollision(protectora.getColliders(),protectorb.getColliders())))
cout << "\nNO COLLISION";
adder += 1;*/
}
}
}
close();
return 0;
}
bool checkCollision(vector<SDL_Rect>& a, vector<SDL_Rect>& b)
{
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
for( int Abox = 0; Abox < a.size(); Abox++ )
{
leftA = a[ Abox ].x;
rightA = a[ Abox ].x + a[ Abox ].w;
topA = a[ Abox ].y;
bottomA = a[ Abox ].y + a[ Abox ].h;
for( int Bbox = 0; Bbox < b.size(); Bbox++ )
{
leftB = b[ Bbox ].x;
rightB = b[ Bbox ].x + b[ Bbox ].w;
topB = b[ Bbox ].y;
bottomB = b[ Bbox ].y + b[ Bbox ].h;
if( ( ( bottomA <= topB ) || ( topA >= bottomB ) || ( rightA <= leftB ) || ( leftA >= rightB ) ) == false )
return true;
}
}
return false;
}
void insertLLLnode(node *&head, int PosX, int PosY)
{
if(!head)
{
head = new node;
head -> currentBullet = new bullet(PosX +31, PosY);
head -> next = NULL;
return;
}
insertLLLnode(head -> next, PosX, PosY);
}
void renderLLLbullet(node * head)
{
if(!head)
return;
head -> currentBullet->renderbullet();
head -> currentBullet->travel();
renderLLLbullet(head -> next);
}
void findCollision(node * head, shipProtector a, shipProtector b, shipProtector c, shipProtector d, shipProtector e)
{
if(!head)
return;
for (int i = 0; i < 12; i++)
{
if(
checkCollision(a.getColliders(i), head -> currentBullet -> getCollider()) == true ||
checkCollision(b.getColliders(i), head -> currentBullet -> getCollider()) == true ||
checkCollision(c.getColliders(i), head -> currentBullet -> getCollider()) == true ||
checkCollision(d.getColliders(i), head -> currentBullet -> getCollider()) == true ||
checkCollision(e.getColliders(i), head -> currentBullet -> getCollider()) == true)
cout << "\nCollision DETECTED!";
}
findCollision(head -> next, a,b,c,d,e);
}
void setColliders(node * head)
{
if(!head)
return;
head -> currentBullet -> setCollider();
setColliders(head -> next);
}
bool init()
{
bool working = true;
if(SDL_Init(SDL_INIT_VIDEO))
{
cout << "\nSDL Video Subsystem failed. ERROR: " << SDL_GetError();
working = false;
}
else
{
mainWindow = SDL_CreateWindow("Space Invaders v 1.0.5", ((1920 - gameWidth) / 2), ((1080 - gameHeight) / 2), gameWidth, gameHeight, SDL_WINDOW_SHOWN);
if(!mainWindow)
{
cout << "\nFailed to create main game window. ERROR: " << SDL_GetError();
working = false;
}
else
{
mainRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if(!mainRenderer)
{
cout << "\nFailed to initialize renderer. ERROR: " << SDL_GetError();
working = false;
}
else
{
SDL_SetRenderDrawColor(mainRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
int imgFlags = IMG_INIT_PNG;
if(!(IMG_Init(imgFlags) & imgFlags))
{
cout << "\nSDL_image PNG module failed to initialize.Error: " << SDL_GetError();
working = false;
}
}
}
}
return working;
}
bool loadMedia()
{
bool loaded = true;
if(!bgTexture.loadFromFile("_img/mainBG.png"))
{
cout << "\nFailed to load BG texture. ERROR: " << SDL_GetError();
loaded = false;
}
if(!shipTexture.loadFromFile("_img/ship.png"))
{
cout << "\nFailed to load ship texture. ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexLBB.loadFromFile("_img/protectorLBB.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexLBT.loadFromFile("_img/protectorLBT.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexLCEB.loadFromFile("_img/protectorLCEB.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexLCET.loadFromFile("_img/protectorLCET.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexLCOB.loadFromFile("_img/protectorLCOB.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexLCOT.loadFromFile("_img/protectorLCOT.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexRBB.loadFromFile("_img/protectorRBB.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexRBT.loadFromFile("_img/protectorRBT.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexRCEB.loadFromFile("_img/protectorRCEB.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexRCET.loadFromFile("_img/protectorRCET.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexRCOB.loadFromFile("_img/protectorRCOB.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!pTexRCOT.loadFromFile("_img/protectorRCOT.png"))
{
cout << "\nFailed to load ship protector texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!bulletTexture.loadFromFile("_img/bullet.png"))
{
cout << "\nFailed to load bullet texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!monsterTypeA.loadFromFile("_img/monsterTypeA.png"))
{
cout << "\nFailed to load monsterA texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!monsterTypeB.loadFromFile("_img/monsterTypeB.png"))
{
cout << "\nFailed to load monsterB texture ERROR: " << SDL_GetError();
loaded = false;
}
if(!monsterTypeC.loadFromFile("_img/monsterTypeC.png"))
{
cout << "\nFailed to load monsterC texture ERROR: " << SDL_GetError();
loaded = false;
}
return loaded;
}
void close()
{
bgTexture.free();
shipTexture.free();
SDL_DestroyRenderer(mainRenderer);
SDL_DestroyWindow(mainWindow);
mainRenderer = NULL;
mainWindow = NULL;
IMG_Quit();
SDL_Quit();
}
bullet::bullet(int posX, int posY)
{
bPosX = posX;
bPosY = posY;
bVelY = 0;
bCollider.resize(1);
bCollider[0].w = 4;
bCollider[0].h = 16;
}
void bullet::travel()
{
bPosY -= bulletvelocity;
}
void bullet::renderbullet()
{
bulletTexture.render(bPosX, bPosY);
}
void bullet::setCollider()
{
bCollider[0].x = bPosX;
bCollider[0].y = bPosY;
}
vector<SDL_Rect> &bullet::getCollider()
{
return bCollider;
}
shipProtector::shipProtector(int x, int y)
{
pPosX = x;
pPosY = y;
pColliders.resize(12); // creates 12 colliders
pColliders[0].w = 32;
pColliders[0].h = 28;
pColliders[1].w = 32;
pColliders[1].h = 28;
pColliders[2].w = 32;
pColliders[2].h = 25;
pColliders[3].w = 32;
pColliders[3].h = 25;
pColliders[4].w = 46;
pColliders[4].h = 32;
pColliders[5].w = 46;
pColliders[5].h = 32;
pColliders[6].w = 43;
pColliders[6].h = 25;
pColliders[7].w = 43;
pColliders[7].h = 25;
pColliders[8].w = 19;
pColliders[8].h = 25;
pColliders[9].w = 19;
pColliders[9].h = 25;
pColliders[10].w = 19;
pColliders[10].h = 17;
pColliders[11].w = 19;
pColliders[11].h = 17;
}
void shipProtector::setColliders()
{
pColliders[0].x = pPosX;
pColliders[0].y = pPosY + protectorHeight - (pColliders[0].h / 2);
pColliders[1].x = pPosX + protectorWidth - (pColliders[1].w);
pColliders[1].y = pPosY + protectorHeight - (pColliders[1].h);
pColliders[2].x = pPosX;
pColliders[2].y = pPosY + protectorHeight - (pColliders[1].h) - (pColliders[2].h);
pColliders[3].x = pPosX + protectorWidth - (pColliders[3].w);
pColliders[3].y = pPosY + protectorHeight - pColliders[1].h - (pColliders[3].h);
pColliders[4].x = pPosX;
pColliders[4].y = pPosY + (pColliders[6].h);
pColliders[5].x = pPosX + protectorWidth - (pColliders[5].w);
pColliders[5].y = pPosY + (pColliders[7].h);
pColliders[6].x = pPosX;
pColliders[6].y = pPosY;
pColliders[7].x = pPosX + protectorWidth - (pColliders[7].w) - 3;
pColliders[7].y = pPosY;
pColliders[8].x = pPosX + (pColliders[6].w) + 3;
pColliders[8].y = pPosY;
pColliders[9].x = pPosX + protectorWidth / 2;
pColliders[9].y = pPosY;
pColliders[10].x = pPosX + (pColliders[4].w);
pColliders[10].y = pPosY + (pColliders[8].h);
pColliders[11].x = pPosX + protectorWidth / 2;
pColliders[11].y = pPosY + (pColliders[8].h);
}
void shipProtector::renderProtector()
{
pTexLBB.render(pPosX, pPosY);
pTexRBB.render(pPosX, pPosY);
pTexLBT.render(pPosX, pPosY);
pTexLCEB.render(pPosX, pPosY);
pTexLCET.render(pPosX, pPosY);
pTexLCOB.render(pPosX, pPosY);
pTexLCOT.render(pPosX, pPosY);
pTexRBT.render(pPosX, pPosY);
pTexRCEB.render(pPosX, pPosY);
pTexRCET.render(pPosX, pPosY);
pTexRCOB.render(pPosX, pPosY);
pTexRCOT.render(pPosX, pPosY);
}
int shipProtector::getX()
{
return pPosX;
}
int shipProtector::getY()
{
return pPosY;
}
vector<SDL_Rect> &shipProtector::getColliders(int current)
{
return pColliders;
}
void shipProtector::coutCollision()
{
cout << pColliders[5].x << " ";
cout << pColliders[5].y;
}
GameTexture::GameTexture()
{
mTexture = NULL;
tWidth = 0;
tHeight = 0;
}
GameTexture::~GameTexture()
{
free();
}
bool GameTexture::loadFromFile(string path)
{
free(); // Clear previous texture.
SDL_Texture * newTexture = NULL;
SDL_Surface * loadedSurface = IMG_Load(path.c_str());
if (!loadedSurface)
cout << "\nFailed to load image at " << path << " ERROR: " << SDL_GetError();
else
{
newTexture = SDL_CreateTextureFromSurface(mainRenderer, loadedSurface);
if(!newTexture)
cout << "\nUnable to create game texture form file. EROR: " << SDL_GetError();
else
{
tWidth = loadedSurface -> w;
tHeight = loadedSurface -> h;
}
SDL_FreeSurface(loadedSurface);
}
mTexture = newTexture;
return mTexture != NULL;
}
void GameTexture::free()
{
if(mTexture != NULL)
{
SDL_DestroyTexture(mTexture);
mTexture = NULL;
tWidth = 0;
tHeight = 0;
}
}
void GameTexture::render(int x, int y)
{
SDL_Rect renderquad = {x, y, tWidth, tHeight};
SDL_RenderCopy(mainRenderer, mTexture, NULL, &renderquad);
}
int GameTexture::getWidth()
{
return tWidth;
}
int GameTexture::getHeight()
{
return tHeight;
}
monster::monster(int x, int y, int type)
{
spawnX = x;
spawnY = y;
offsetX = 15;
offsetY = 0;
mCollider.resize(1);
mCollider[0].w = 0;
mCollider[0].h = 32;
monsterWidth = 0;
monsterHeight = 32;
monsterType = type;
changeDir = false;
}
void monster::renderMonster()
{
switch(monsterType)
{
case 1:
{
monsterTypeA.render(spawnX, spawnY);
break;
}
case 2:
{
monsterTypeB.render(spawnX, spawnY);
break;
}
case 3:
{
monsterTypeC.render(spawnX, spawnY);
break;
}
default:
{
cout << "\nENTERED MONSTER SWITCH DEFAULT!";
break;
}
}
}
void monster::shoot()
{
insertLLLnode(head, spawnX, spawnY);
}
void monster::moveMonster()
{
if(spawnX + monsterWidth > gameWidth)
changeDir = true;
else if(spawnX < 0)
changeDir = false;
if(!changeDir)
{
spawnX += offsetX;
cout << "\nSPAWN X : " << spawnX;
}
else if(changeDir)
{
spawnX -= offsetX;
cout << "\nHELLO";
}
}
void monster::setCollider()
{
mCollider.resize(1);
mCollider[0].x = spawnX;
mCollider[0].y = spawnY;
switch(monsterType)
{
case 1:
{
mCollider[0].w = 32;
break;
}
case 2:
{
mCollider[0].w = 44;
break;
}
case 3:
{
mCollider[0].w = 48;
break;
}
}
}
vector<SDL_Rect> &monster::getCollider()
{
return mCollider;
}
void monster::setSize()
{
switch(monsterType)
{
case 1:
{
monsterWidth = 32;
break;
}
case 2:
{
monsterWidth = 44;
break;
}
case 3:
{
monsterWidth = 48;
break;
}
}
}
mainShip::mainShip()
{
sPosX = 640;
sPosY = 656;
sVelX = 0;
sVelY = 0;
}
void mainShip::handleEvent(SDL_Event &event)
{
if(event.type == SDL_KEYDOWN && event.key.repeat == 0)
{
switch (event.key.keysym.sym)
{
case SDLK_UP:
{
cout << "\nPressed KEY UP!";
sVelY -= shipVelocity;
cout << "\nVELOCITY ON Y IS: " << sVelY;
break;
}
case SDLK_DOWN:
{
cout << "\nPressed KEY DOWN!";
sVelY += shipVelocity;
cout << "\nVELOCITY ON Y IS: " << sVelY;
break;
}
case SDLK_LEFT:
{
cout << "\n\nPressed KEY LEFT!";
sVelX -= shipVelocity;
cout << "\nVELOCITY ON X IS: " << sVelX;
cout << "\nPOSITION ON X IS: " << sPosX;
break;
}
case SDLK_RIGHT:
{
cout << "\nPressed KEY RIGHT!";
sVelX += shipVelocity;
cout << "\nVELOCITY ON X IS: " << sVelX;
cout << "\nPOSITION ON X IS: " << sPosX;
break;
}
case SDLK_SPACE:
{
cout << "\nSPACE IS PRESSED";
insertLLLnode(head, sPosX, sPosY);
break;
}
}
}
else if(event.type == SDL_KEYUP && event.key.repeat == 0)
{
switch (event.key.keysym.sym)
{
case SDLK_UP:
{
cout << "\nUP KEY RELEASED";
sVelY += shipVelocity;
break;
}
case SDLK_DOWN:
{
cout << "\nDOWN KEY RELEASED";
sVelY -= shipVelocity;
break;
}
case SDLK_LEFT:
{
cout << "\n\nLEFT KEY RELEASED";
sVelX += shipVelocity;
break;
}
case SDLK_RIGHT:
{
cout << "\nRIGHT KEY RELEASED";
sVelX -= shipVelocity;
break;
}
case SDLK_SPACE:
{
cout << "\nSPACE RELEASED!";
/** delete aBullet;
aBullet = NULL; **/
break;
}
}
}
}
void mainShip::moveShip()
{
sPosX += sVelX;
if ((sPosX < 0) || (sPosX + shipWidth > gameWidth))
{
sPosX -= sVelX;
cout << "\nDAFUQ";
}
sPosY += sVelY;
if ((sPosY < 0) || (sPosY + shipHeight > gameHeight))
sPosY -= sVelY;
}
void mainShip::render()
{
shipTexture.render(sPosX,sPosY);
}
<commit_msg>Delete junk.cpp<commit_after><|endoftext|> |
<commit_before>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015-2018 Vladimir Menshakov
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <mtp/ptp/ObjectFormat.h>
#include <algorithm>
#include <ctype.h>
#include <map>
#ifdef HAVE_LIBMAGIC
# include <magic.h>
#endif
namespace mtp
{
#ifdef HAVE_LIBMAGIC
namespace
{
class Magic
{
magic_t _magic;
std::map<std::string, ObjectFormat> _types;
public:
Magic(): _magic(magic_open(MAGIC_MIME_TYPE | MAGIC_SYMLINK | MAGIC_ERROR))
{
#define MAP_TYPE(name, format) _types[name] = (format)
magic_load(_magic, NULL);
MAP_TYPE("inode/directory", ObjectFormat::Association);
MAP_TYPE("audio/mpeg", ObjectFormat::Mp3);
MAP_TYPE("text/plain", ObjectFormat::Text);
MAP_TYPE("image/jpeg", ObjectFormat::Jfif);
MAP_TYPE("image/gif", ObjectFormat::Gif);
MAP_TYPE("image/x-ms-bmp", ObjectFormat::Bmp);
MAP_TYPE("image/png", ObjectFormat::Png);
MAP_TYPE("audio/x-ms-wma", ObjectFormat::Wma);
MAP_TYPE("audio/ogg", ObjectFormat::Ogg);
MAP_TYPE("audio/x-flac", ObjectFormat::Flac);
MAP_TYPE("audio/x-m4a", ObjectFormat::Aac);
MAP_TYPE("audio/audio/x-wav", ObjectFormat::Aiff);
MAP_TYPE("video/x-ms-asf", ObjectFormat::Asf);
MAP_TYPE("audio/mp4", ObjectFormat::Mp4);
#undef MAP_TYPE
}
ObjectFormat GetType(const std::string &path)
{
const char *type = _magic? magic_file(_magic, path.c_str()): NULL;
if (!type)
return ObjectFormat::Undefined;
//debug("MAGIC MIME: ", type);
auto it = _types.find(type);
return it != _types.end()? it->second: ObjectFormat::Undefined;
}
~Magic()
{ if (_magic) magic_close(_magic); }
};
}
#else
namespace
{
struct Magic
{
const ObjectFormat GetType(const std::string &) { return ObjectFormat::Undefined; }
};
}
#endif
ObjectFormat ObjectFormatFromFilename(const std::string &filename)
{
static Magic magic;
{
ObjectFormat magicType = magic.GetType(filename);
if (magicType != ObjectFormat::Undefined)
return magicType;
}
size_t extPos = filename.rfind('.');
if (extPos == filename.npos)
return ObjectFormat::Undefined;
std::string ext = filename.substr(extPos + 1);
std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
if (ext == "mp3")
return mtp::ObjectFormat::Mp3;
else if (ext == "txt")
return mtp::ObjectFormat::Text;
else if (ext == "jpeg" || ext == "jpg")
return mtp::ObjectFormat::Jfif;
else if (ext == "gif")
return mtp::ObjectFormat::Gif;
else if (ext == "bmp")
return mtp::ObjectFormat::Bmp;
else if (ext == "png")
return mtp::ObjectFormat::Png;
else if (ext == "wma")
return mtp::ObjectFormat::Wma;
else if (ext == "ogg")
return mtp::ObjectFormat::Ogg;
else if (ext == "flac")
return mtp::ObjectFormat::Flac;
else if (ext == "aac")
return mtp::ObjectFormat::Aac;
else if (ext == "wav")
return mtp::ObjectFormat::Aiff;
else if (ext == "wmv")
return mtp::ObjectFormat::Wmv;
else if (ext == "mp4")
return mtp::ObjectFormat::Mp4;
else if (ext == "3gp")
return mtp::ObjectFormat::_3gp;
else if (ext == "asf")
return mtp::ObjectFormat::Asf;
else if (ext == "m3u")
return mtp::ObjectFormat::M3u;
else
return ObjectFormat::Undefined;
}
time_t ConvertDateTime(const std::string ×pec)
{
struct tm time = {};
char *end = strptime(timespec.c_str(), "%Y%m%dT%H%M%S", &time);
if (!end)
return 0;
return mktime(&time);
}
std::string ConvertDateTime(time_t time)
{
struct tm bdt = {};
if (!gmtime_r(&time, &bdt))
throw std::runtime_error("gmtime_r failed");
char buf[64];
size_t r = strftime(buf, sizeof(buf), "%Y%m%dT%H%M%SZ", &bdt);
return std::string(buf, r);
}
}
<commit_msg>added workaround libmagic m3u problem<commit_after>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015-2018 Vladimir Menshakov
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <mtp/ptp/ObjectFormat.h>
#include <algorithm>
#include <ctype.h>
#include <map>
#ifdef HAVE_LIBMAGIC
# include <magic.h>
#endif
namespace mtp
{
#ifdef HAVE_LIBMAGIC
namespace
{
std::string GetExtension(const std::string &filename)
{
size_t extPos = filename.rfind('.');
std::string ext = (extPos != filename.npos)? filename.substr(extPos + 1): std::string();
std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
return ext;
}
class Magic
{
magic_t _magic;
std::map<std::string, ObjectFormat> _types;
public:
Magic(): _magic(magic_open(MAGIC_MIME_TYPE | MAGIC_SYMLINK | MAGIC_ERROR))
{
#define MAP_TYPE(name, format) _types[name] = (format)
magic_load(_magic, NULL);
MAP_TYPE("inode/directory", ObjectFormat::Association);
MAP_TYPE("audio/mpeg", ObjectFormat::Mp3);
MAP_TYPE("text/plain", ObjectFormat::Text);
MAP_TYPE("image/jpeg", ObjectFormat::Jfif);
MAP_TYPE("image/gif", ObjectFormat::Gif);
MAP_TYPE("image/x-ms-bmp", ObjectFormat::Bmp);
MAP_TYPE("image/png", ObjectFormat::Png);
MAP_TYPE("audio/x-ms-wma", ObjectFormat::Wma);
MAP_TYPE("audio/ogg", ObjectFormat::Ogg);
MAP_TYPE("audio/x-flac", ObjectFormat::Flac);
MAP_TYPE("audio/x-m4a", ObjectFormat::Aac);
MAP_TYPE("audio/audio/x-wav", ObjectFormat::Aiff);
MAP_TYPE("video/x-ms-asf", ObjectFormat::Asf);
MAP_TYPE("audio/mp4", ObjectFormat::Mp4);
MAP_TYPE("application/x-mpegurl", ObjectFormat::M3u);
#undef MAP_TYPE
}
ObjectFormat GetType(const std::string &path)
{
const char *type = _magic? magic_file(_magic, path.c_str()): NULL;
if (!type)
return ObjectFormat::Undefined;
//debug("MAGIC MIME: ", type);
auto it = _types.find(type);
return it != _types.end()? it->second: ObjectFormat::Undefined;
}
~Magic()
{ if (_magic) magic_close(_magic); }
};
}
#else
namespace
{
struct Magic
{
const ObjectFormat GetType(const std::string &) { return ObjectFormat::Undefined; }
};
}
#endif
ObjectFormat ObjectFormatFromFilename(const std::string &filename)
{
//libmagic missing mime type for m3u files
auto ext = GetExtension(filename);
if (ext == "m3u")
return mtp::ObjectFormat::M3u;
static Magic magic;
{
ObjectFormat magicType = magic.GetType(filename);
if (magicType != ObjectFormat::Undefined)
return magicType;
}
if (ext == "mp3")
return mtp::ObjectFormat::Mp3;
else if (ext == "txt")
return mtp::ObjectFormat::Text;
else if (ext == "jpeg" || ext == "jpg")
return mtp::ObjectFormat::Jfif;
else if (ext == "gif")
return mtp::ObjectFormat::Gif;
else if (ext == "bmp")
return mtp::ObjectFormat::Bmp;
else if (ext == "png")
return mtp::ObjectFormat::Png;
else if (ext == "wma")
return mtp::ObjectFormat::Wma;
else if (ext == "ogg")
return mtp::ObjectFormat::Ogg;
else if (ext == "flac")
return mtp::ObjectFormat::Flac;
else if (ext == "aac")
return mtp::ObjectFormat::Aac;
else if (ext == "wav")
return mtp::ObjectFormat::Aiff;
else if (ext == "wmv")
return mtp::ObjectFormat::Wmv;
else if (ext == "mp4")
return mtp::ObjectFormat::Mp4;
else if (ext == "3gp")
return mtp::ObjectFormat::_3gp;
else if (ext == "asf")
return mtp::ObjectFormat::Asf;
else
return ObjectFormat::Undefined;
}
time_t ConvertDateTime(const std::string ×pec)
{
struct tm time = {};
char *end = strptime(timespec.c_str(), "%Y%m%dT%H%M%S", &time);
if (!end)
return 0;
return mktime(&time);
}
std::string ConvertDateTime(time_t time)
{
struct tm bdt = {};
if (!gmtime_r(&time, &bdt))
throw std::runtime_error("gmtime_r failed");
char buf[64];
size_t r = strftime(buf, sizeof(buf), "%Y%m%dT%H%M%SZ", &bdt);
return std::string(buf, r);
}
}
<|endoftext|> |
<commit_before>#include "replication/heartbeat_manager.hpp"
#include "arch/arch.hpp"
#include "arch/timing.hpp"
heartbeat_sender_t::heartbeat_sender_t(int heartbeat_frequency_ms) :
heartbeat_frequency_ms_(heartbeat_frequency_ms), heartbeat_timer_(NULL), continue_firing(false) {
rassert(heartbeat_frequency_ms_ > 0);
}
heartbeat_sender_t::~heartbeat_sender_t() {
stop_sending_heartbeats();
}
void heartbeat_sender_t::start_sending_heartbeats() {
rassert(!heartbeat_timer_);
continue_firing = true;
heartbeat_timer_ = fire_timer_once(heartbeat_frequency_ms_, send_heartbeat_callback, this);
}
void heartbeat_sender_t::stop_sending_heartbeats() {
continue_firing = false; // Make sure that currently active send_heartbeat coros don't restart the timer
if (heartbeat_timer_) {
cancel_timer(heartbeat_timer_);
heartbeat_timer_ = NULL;
}
}
void heartbeat_sender_t::send_heartbeat_callback(void *data) {
heartbeat_sender_t *self = ptr_cast<heartbeat_sender_t>(data);
self->heartbeat_timer_ = NULL;
coro_t::spawn_now(boost::bind(&heartbeat_sender_t::send_heartbeat_wrapper, self));
// Once that heartbeat got dispatched, fire a new one.
// TODO: This should also throttle the heartbeat rate if the connection is busy and
// send_heartbeat takes a long time, which is not the case currently.
// Otherwise hearbeats might pile up, which is probably acceptable but not optimal.
if (self->continue_firing) {
self->heartbeat_timer_ = fire_timer_once(self->heartbeat_frequency_ms_, send_heartbeat_callback, self);
}
}
heartbeat_receiver_t::heartbeat_receiver_t(int heartbeat_timeout_ms) :
pause_watching_heartbeat_count_(0),
watch_heartbeat_active_(false),
heartbeat_timeout_ms_(heartbeat_timeout_ms),
heartbeat_timer_(NULL) {
rassert(heartbeat_timeout_ms_ > 0);
}
heartbeat_receiver_t::~heartbeat_receiver_t() {
unwatch_heartbeat();
rassert(pause_watching_heartbeat_count_ == 0);
}
void heartbeat_receiver_t::watch_heartbeat() {
rassert(!heartbeat_timer_);
rassert(!watch_heartbeat_active_);
watch_heartbeat_active_ = true;
if (pause_watching_heartbeat_count_ == 0) {
heartbeat_timer_ = fire_timer_once(heartbeat_timeout_ms_, heartbeat_timeout_callback, this);
}
}
void heartbeat_receiver_t::unwatch_heartbeat() {
watch_heartbeat_active_ = false;
if (heartbeat_timer_) {
cancel_timer(heartbeat_timer_);
heartbeat_timer_ = NULL;
}
}
void heartbeat_receiver_t::note_heartbeat() {
// If the heartbeat is watched, cancel the current timer and fire a new one,
// effectively resetting the timeout.
if (heartbeat_timer_) {
cancel_timer(heartbeat_timer_);
heartbeat_timer_ = fire_timer_once(heartbeat_timeout_ms_, heartbeat_timeout_callback, this);
}
}
void heartbeat_receiver_t::heartbeat_timeout_callback(void *data) {
heartbeat_receiver_t *self = ptr_cast<heartbeat_receiver_t>(data);
self->heartbeat_timer_ = NULL;
logINF("Did not receive a heartbeat within the last %d ms.\n", self->heartbeat_timeout_ms_);
coro_t::spawn_now(boost::bind(&heartbeat_receiver_t::on_heartbeat_timeout_wrapper, self));
}
heartbeat_receiver_t::pause_watching_heartbeat_t heartbeat_receiver_t::pause_watching_heartbeat() {
return pause_watching_heartbeat_t(this);
}
heartbeat_receiver_t::pause_watching_heartbeat_t::pause_watching_heartbeat_t(heartbeat_receiver_t *parent) :
parent_(parent) {
if (parent_->pause_watching_heartbeat_count_++ == 0 && parent_->watch_heartbeat_active_) {
// We are the first pauser
rassert(parent_->heartbeat_timer_);
cancel_timer(parent_->heartbeat_timer_);
parent_->heartbeat_timer_ = NULL;
}
}
heartbeat_receiver_t::pause_watching_heartbeat_t::~pause_watching_heartbeat_t() {
if (--parent_->pause_watching_heartbeat_count_ == 0) {
// We were the last pauser, resume watching the heartbeat if it is active
if (parent_->watch_heartbeat_active_) {
rassert(!parent_->heartbeat_timer_);
parent_->heartbeat_timer_ = fire_timer_once(parent_->heartbeat_timeout_ms_, parent_->heartbeat_timeout_callback, parent_);
}
}
}
heartbeat_receiver_t::pause_watching_heartbeat_t::pause_watching_heartbeat_t(const pause_watching_heartbeat_t &o) {
*this = o;
}
heartbeat_receiver_t::pause_watching_heartbeat_t &heartbeat_receiver_t::pause_watching_heartbeat_t::operator=(const heartbeat_receiver_t::pause_watching_heartbeat_t &o) {
parent_ = o.parent_;
rassert(parent_->pause_watching_heartbeat_count_ > 0);
parent_->pause_watching_heartbeat_count_++;
return *this;
}
<commit_msg>Fix another small glitch in the heartbeat manager<commit_after>#include "replication/heartbeat_manager.hpp"
#include "arch/arch.hpp"
#include "arch/timing.hpp"
heartbeat_sender_t::heartbeat_sender_t(int heartbeat_frequency_ms) :
heartbeat_frequency_ms_(heartbeat_frequency_ms), heartbeat_timer_(NULL), continue_firing(false) {
rassert(heartbeat_frequency_ms_ > 0);
}
heartbeat_sender_t::~heartbeat_sender_t() {
stop_sending_heartbeats();
}
void heartbeat_sender_t::start_sending_heartbeats() {
rassert(!heartbeat_timer_);
continue_firing = true;
heartbeat_timer_ = fire_timer_once(heartbeat_frequency_ms_, send_heartbeat_callback, this);
}
void heartbeat_sender_t::stop_sending_heartbeats() {
continue_firing = false; // Make sure that currently active send_heartbeat coros don't restart the timer
if (heartbeat_timer_) {
cancel_timer(heartbeat_timer_);
heartbeat_timer_ = NULL;
}
}
void heartbeat_sender_t::send_heartbeat_callback(void *data) {
heartbeat_sender_t *self = ptr_cast<heartbeat_sender_t>(data);
self->heartbeat_timer_ = NULL;
coro_t::spawn_now(boost::bind(&heartbeat_sender_t::send_heartbeat_wrapper, self));
// Once that heartbeat got dispatched, fire a new one.
// TODO: This should also throttle the heartbeat rate if the connection is busy and
// send_heartbeat takes a long time, which is not the case currently.
// Otherwise hearbeats might pile up, which is probably acceptable but not optimal.
if (self->continue_firing) {
self->heartbeat_timer_ = fire_timer_once(self->heartbeat_frequency_ms_, send_heartbeat_callback, self);
}
}
heartbeat_receiver_t::heartbeat_receiver_t(int heartbeat_timeout_ms) :
pause_watching_heartbeat_count_(0),
watch_heartbeat_active_(false),
heartbeat_timeout_ms_(heartbeat_timeout_ms),
heartbeat_timer_(NULL) {
rassert(heartbeat_timeout_ms_ > 0);
}
heartbeat_receiver_t::~heartbeat_receiver_t() {
unwatch_heartbeat();
rassert(pause_watching_heartbeat_count_ == 0);
}
void heartbeat_receiver_t::watch_heartbeat() {
rassert(!heartbeat_timer_);
rassert(!watch_heartbeat_active_);
watch_heartbeat_active_ = true;
if (pause_watching_heartbeat_count_ == 0) {
heartbeat_timer_ = fire_timer_once(heartbeat_timeout_ms_, heartbeat_timeout_callback, this);
}
}
void heartbeat_receiver_t::unwatch_heartbeat() {
watch_heartbeat_active_ = false;
if (heartbeat_timer_) {
cancel_timer(heartbeat_timer_);
heartbeat_timer_ = NULL;
}
}
void heartbeat_receiver_t::note_heartbeat() {
// If the heartbeat is watched, cancel the current timer and fire a new one,
// effectively resetting the timeout.
if (heartbeat_timer_) {
cancel_timer(heartbeat_timer_);
heartbeat_timer_ = fire_timer_once(heartbeat_timeout_ms_, heartbeat_timeout_callback, this);
}
}
void heartbeat_receiver_t::heartbeat_timeout_callback(void *data) {
heartbeat_receiver_t *self = ptr_cast<heartbeat_receiver_t>(data);
self->heartbeat_timer_ = NULL;
self->watch_heartbeat_active_ = false;
logINF("Did not receive a heartbeat within the last %d ms.\n", self->heartbeat_timeout_ms_);
coro_t::spawn_now(boost::bind(&heartbeat_receiver_t::on_heartbeat_timeout_wrapper, self));
}
heartbeat_receiver_t::pause_watching_heartbeat_t heartbeat_receiver_t::pause_watching_heartbeat() {
return pause_watching_heartbeat_t(this);
}
heartbeat_receiver_t::pause_watching_heartbeat_t::pause_watching_heartbeat_t(heartbeat_receiver_t *parent) :
parent_(parent) {
rassert(!parent_->watch_heartbeat_active_ || parent_->heartbeat_timer_); // Consistency check...
if (parent_->pause_watching_heartbeat_count_++ == 0 && parent_->heartbeat_timer_) {
// We are the first pauser
cancel_timer(parent_->heartbeat_timer_);
parent_->heartbeat_timer_ = NULL;
}
}
heartbeat_receiver_t::pause_watching_heartbeat_t::~pause_watching_heartbeat_t() {
if (--parent_->pause_watching_heartbeat_count_ == 0) {
// We were the last pauser, resume watching the heartbeat if it is active
if (parent_->watch_heartbeat_active_) {
rassert(!parent_->heartbeat_timer_);
parent_->heartbeat_timer_ = fire_timer_once(parent_->heartbeat_timeout_ms_, parent_->heartbeat_timeout_callback, parent_);
}
}
}
heartbeat_receiver_t::pause_watching_heartbeat_t::pause_watching_heartbeat_t(const pause_watching_heartbeat_t &o) {
*this = o;
}
heartbeat_receiver_t::pause_watching_heartbeat_t &heartbeat_receiver_t::pause_watching_heartbeat_t::operator=(const heartbeat_receiver_t::pause_watching_heartbeat_t &o) {
parent_ = o.parent_;
rassert(parent_->pause_watching_heartbeat_count_ > 0);
parent_->pause_watching_heartbeat_count_++;
return *this;
}
<|endoftext|> |
<commit_before>#include <sstream>
#include "runtime/core/arithmetic_impl.h"
#include "errors/error_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/casting.h"
#include "util/Assert.h"
#include "runtime/numerics/NumericsImpl.h"
#include "errors/error_factory.h"
namespace xqp {
void ArithOperationsCommons::createError(
const char* aOp,
const yy::location* aLoc,
TypeConstants::atomic_type_code_t aType0,
TypeConstants::atomic_type_code_t aType1
)
{
AtomicXQType lAType0(aType0, TypeConstants::QUANT_ONE);
AtomicXQType lAType1(aType1, TypeConstants::QUANT_ONE);
std::stringstream lStream;
lStream << "The operation '";
lStream << aOp;
lStream << "' is not possible with parameters of the type ";
lAType0.serialize(lStream);
lStream << " and ";
lAType1.serialize(lStream);
lStream << "!";
ZORBA_ERROR_ALERT(
ZorbaError::XPTY0004,
aLoc,
DONT_CONTINUE_EXECUTION,
lStream.str()
);
}
/* begin class GenericArithIterator */
template< class Operations>
GenericArithIterator<Operations>::GenericArithIterator
( const yy::location& loc, PlanIter_t& iter0, PlanIter_t& iter1 )
:
BinaryBaseIterator<GenericArithIterator<Operations>, PlanIteratorState > ( loc, iter0, iter1 )
{ }
template < class Operation >
Item_t GenericArithIterator<Operation>::nextImpl ( PlanState& planState ) const
{
Item_t n0;
Item_t n1;
Item_t res;
PlanIteratorState* state;
DEFAULT_STACK_INIT ( PlanIteratorState, state, planState );
n0 = consumeNext( this->theChild0.getp(), planState );
if ( n0 != NULL )
{
n1 = consumeNext( this->theChild1.getp(), planState );
if ( n1 != NULL )
{
res = compute(this->loc, n0, n1);
if ( consumeNext(this->theChild0.getp(), planState ) != NULL
|| consumeNext(this->theChild1.getp(), planState ) != NULL )
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation has a sequences greater than one as an operator.");
STACK_PUSH ( res, state );
}
}
STACK_END();
}
template < class Operation >
Item_t GenericArithIterator<Operation>::compute(const yy::location& aLoc, Item_t n0, Item_t n1)
{
n0 = n0->getAtomizationValue();
n1 = n1->getAtomizationValue();
xqtref_t type0 = GENV_TYPESYSTEM.create_type ( n0->getType(), TypeConstants::QUANT_ONE );
xqtref_t type1 = GENV_TYPESYSTEM.create_type ( n1->getType(), TypeConstants::QUANT_ONE );
if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DURATION_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DOUBLE_TYPE_ONE ))
return Operation::template compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE> ( &aLoc, n0, n1 );
else
return Operation::template computeSingleType<TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if ( GENV_TYPESYSTEM.is_numeric(*type0)
|| GENV_TYPESYSTEM.is_numeric(*type1)
|| GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE)
|| GENV_TYPESYSTEM.is_subtype(*type1, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE))
{
return NumArithIterator<Operation>::computeAtomic(aLoc, n0, type0, n1, type1);
}
else
{
ZORBA_ASSERT(false);
}
return 0;
}
/**
* Information: It is not possible to move this function to
* runtime/visitors/accept.cpp!
*/
template < class Operation >
void GenericArithIterator<Operation>::accept(PlanIterVisitor& v) const {
v.beginVisit(*this);
this->theChild0->accept(v);
this->theChild1->accept(v);
v.endVisit(*this);
}
/* instantiate GenericArithIterator for all types */
template class GenericArithIterator<AddOperation>;
template class GenericArithIterator<SubtractOperation>;
template class GenericArithIterator<MultiplyOperation>;
template class GenericArithIterator<DivideOperation>;
template class GenericArithIterator<IntegerDivideOperation>;
template class GenericArithIterator<ModOperation>;
/* end class GenericArithIterator */
}
<commit_msg>Solved a bug in the divide operations that involve durations and doubles.<commit_after>#include <sstream>
#include "runtime/core/arithmetic_impl.h"
#include "errors/error_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/casting.h"
#include "util/Assert.h"
#include "runtime/numerics/NumericsImpl.h"
#include "errors/error_factory.h"
namespace xqp {
void ArithOperationsCommons::createError(
const char* aOp,
const yy::location* aLoc,
TypeConstants::atomic_type_code_t aType0,
TypeConstants::atomic_type_code_t aType1
)
{
AtomicXQType lAType0(aType0, TypeConstants::QUANT_ONE);
AtomicXQType lAType1(aType1, TypeConstants::QUANT_ONE);
std::stringstream lStream;
lStream << "The operation '";
lStream << aOp;
lStream << "' is not possible with parameters of the type ";
lAType0.serialize(lStream);
lStream << " and ";
lAType1.serialize(lStream);
lStream << "!";
ZORBA_ERROR_ALERT(
ZorbaError::XPTY0004,
aLoc,
DONT_CONTINUE_EXECUTION,
lStream.str()
);
}
/* begin class GenericArithIterator */
template< class Operations>
GenericArithIterator<Operations>::GenericArithIterator
( const yy::location& loc, PlanIter_t& iter0, PlanIter_t& iter1 )
:
BinaryBaseIterator<GenericArithIterator<Operations>, PlanIteratorState > ( loc, iter0, iter1 )
{ }
template < class Operation >
Item_t GenericArithIterator<Operation>::nextImpl ( PlanState& planState ) const
{
Item_t n0;
Item_t n1;
Item_t res;
PlanIteratorState* state;
DEFAULT_STACK_INIT ( PlanIteratorState, state, planState );
n0 = consumeNext( this->theChild0.getp(), planState );
if ( n0 != NULL )
{
n1 = consumeNext( this->theChild1.getp(), planState );
if ( n1 != NULL )
{
res = compute(this->loc, n0, n1);
if ( consumeNext(this->theChild0.getp(), planState ) != NULL
|| consumeNext(this->theChild1.getp(), planState ) != NULL )
ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,
NULL, DONT_CONTINUE_EXECUTION, "Arithmetic operation has a sequences greater than one as an operator.");
STACK_PUSH ( res, state );
}
}
STACK_END();
}
template < class Operation >
Item_t GenericArithIterator<Operation>::compute(const yy::location& aLoc, Item_t n0, Item_t n1)
{
n0 = n0->getAtomizationValue();
n1 = n1->getAtomizationValue();
xqtref_t type0 = GENV_TYPESYSTEM.create_type ( n0->getType(), TypeConstants::QUANT_ONE );
xqtref_t type1 = GENV_TYPESYSTEM.create_type ( n1->getType(), TypeConstants::QUANT_ONE );
if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DURATION_TYPE_ONE ))
{
if(GENV_TYPESYSTEM.is_numeric(*type1))
return Operation::template compute<TypeConstants::XS_DURATION,TypeConstants::XS_DOUBLE> ( &aLoc, n0, n1 );
else
return Operation::template computeSingleType<TypeConstants::XS_DURATION> ( &aLoc, n0, n1 );
}
else if ( GENV_TYPESYSTEM.is_numeric(*type0)
|| GENV_TYPESYSTEM.is_numeric(*type1)
|| GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE)
|| GENV_TYPESYSTEM.is_subtype(*type1, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE))
{
return NumArithIterator<Operation>::computeAtomic(aLoc, n0, type0, n1, type1);
}
else
{
ZORBA_ASSERT(false);
}
return 0;
}
/**
* Information: It is not possible to move this function to
* runtime/visitors/accept.cpp!
*/
template < class Operation >
void GenericArithIterator<Operation>::accept(PlanIterVisitor& v) const {
v.beginVisit(*this);
this->theChild0->accept(v);
this->theChild1->accept(v);
v.endVisit(*this);
}
/* instantiate GenericArithIterator for all types */
template class GenericArithIterator<AddOperation>;
template class GenericArithIterator<SubtractOperation>;
template class GenericArithIterator<MultiplyOperation>;
template class GenericArithIterator<DivideOperation>;
template class GenericArithIterator<IntegerDivideOperation>;
template class GenericArithIterator<ModOperation>;
/* end class GenericArithIterator */
}
<|endoftext|> |
<commit_before>// This code is part of the project "Ligra: A Lightweight Graph Processing
// Framework for Shared Memory", presented at Principles and Practice of
// Parallel Programming, 2013.
// Copyright (c) 2013 Julian Shun and Guy Blelloch
//
// 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 "ligra.h"
// This is an implementation of the MIS algorithm from "Greedy
// Sequential Maximal Independent Set and Matching are Parallel on
// Average", Proceedings of the ACM Symposium on Parallelism in
// Algorithms and Architectures (SPAA), 2012 by Guy Blelloch, Jeremy
// Fineman and Julian Shun. Note: this is not the most efficient
// implementation. For a more efficient implementation, see
// http://www.cs.cmu.edu/~pbbs/benchmarks.html.
//For flags array to store status of each vertex
enum {UNDECIDED,CONDITIONALLY_IN,OUT,IN};
//uncomment the following line to enable checking for
//correctness. currently the checker does not work with Ligra+
//#define CHECK 1
#ifdef CHECK
template<class vertex>
bool checkMis(graph<vertex>& G, int* flags) {
const intE n = G.n;
bool correct = true;
parallel_for (int i = 0; i < n; i++) {
intE outDeg = G.V[i].getOutDegree();
intE numConflict = 0;
intE numInNgh = 0;
for (int j = 0; j < outDeg; j++) {
intE ngh = G.V[i].getOutNeighbor(j);
if (flags[i] == IN && flags[ngh] == IN) {
numConflict++;
}
else if (flags[ngh] == IN) {
numInNgh++;
}
}
if (numConflict > 0) {
if(correct) CAS(&correct,true,false);
}
if (flags[i] != IN && numInNgh == 0) {
if(correct) CAS(&correct,true,false);
}
}
return correct;
}
#endif
struct MIS_Update {
int* flags;
MIS_Update(int* _flags) : flags(_flags) {}
inline bool update (uintE s, uintE d) {
if(flags[d] == IN) {if(flags[s] != OUT) flags[s] = OUT;}
else if(d < s && flags[s] == CONDITIONALLY_IN && flags[d] < OUT)
flags[s] = UNDECIDED;
return 1;
}
inline bool updateAtomic (uintE s, uintE d) {
if(flags[d] == IN) {if(flags[s] != OUT) flags[s] = OUT;}
else if(d < s && flags[s] == CONDITIONALLY_IN && flags[d] < OUT)
flags[s] = UNDECIDED;
return 1;
}
inline bool cond (uintE i) {return cond_true(i);}
};
struct MIS_Filter {
int* flags;
MIS_Filter(int* _flags) : flags(_flags) {}
inline bool operator () (uintE i) {
if(flags[i] == CONDITIONALLY_IN) { flags[i] = IN; return 0; } //vertex in MIS
else if(flags[i] == OUT) return 0; //vertex not in MIS
else { flags[i] = CONDITIONALLY_IN; return 1; } //vertex undecided, move to next round
}
};
//Takes a symmetric graph as input; priority of a vertex is its ID.
template <class vertex>
void Compute(graph<vertex>& GA, commandLine P) {
const intE n = GA.n;
bool checkCorrectness = P.getOptionValue("-checkCorrectness");
//flags array: UNDECIDED means "undecided", CONDITIONALLY_IN means
//"conditionally in MIS", OUT means "not in MIS", IN means "in MIS"
int* flags = newA(int,n);
bool* frontier_data = newA(bool, n);
{parallel_for(long i=0;i<n;i++) {
flags[i] = CONDITIONALLY_IN;
frontier_data[i] = 1;
}}
long round = 0;
vertexSubset Frontier(n, frontier_data);
while (!Frontier.isEmpty()) {
edgeMap(GA, Frontier, MIS_Update(flags));
vertexSubset output = vertexFilter(Frontier, MIS_Filter(flags));
Frontier.del();
Frontier = output;
round++;
}
#ifdef CHECK
if (checkCorrectness) {
if(checkMis(GA,flags)) cout << "correct\n";
else cout << "incorrect\n";
}
#endif
free(flags);
Frontier.del();
}
<commit_msg>fixed comments<commit_after>// This code is part of the project "Ligra: A Lightweight Graph Processing
// Framework for Shared Memory", presented at Principles and Practice of
// Parallel Programming, 2013.
// Copyright (c) 2013 Julian Shun and Guy Blelloch
//
// 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.
//
// This is an implementation of the MIS algorithm from "Greedy
// Sequential Maximal Independent Set and Matching are Parallel on
// Average", Proceedings of the ACM Symposium on Parallelism in
// Algorithms and Architectures (SPAA), 2012 by Guy Blelloch, Jeremy
// Fineman and Julian Shun. Note: this is not the most efficient
// implementation. For a more efficient implementation, see
// http://www.cs.cmu.edu/~pbbs/benchmarks.html.
#include "ligra.h"
//For flags array to store status of each vertex
enum {UNDECIDED,CONDITIONALLY_IN,OUT,IN};
//Uncomment the following line to enable checking for
//correctness. Currently the checker does not work with Ligra+.
//#define CHECK 1
#ifdef CHECK
template<class vertex>
bool checkMis(graph<vertex>& G, int* flags) {
const intE n = G.n;
bool correct = true;
parallel_for (int i = 0; i < n; i++) {
intE outDeg = G.V[i].getOutDegree();
intE numConflict = 0;
intE numInNgh = 0;
for (int j = 0; j < outDeg; j++) {
intE ngh = G.V[i].getOutNeighbor(j);
if (flags[i] == IN && flags[ngh] == IN) {
numConflict++;
}
else if (flags[ngh] == IN) {
numInNgh++;
}
}
if (numConflict > 0) {
if(correct) CAS(&correct,true,false);
}
if (flags[i] != IN && numInNgh == 0) {
if(correct) CAS(&correct,true,false);
}
}
return correct;
}
#endif
struct MIS_Update {
int* flags;
MIS_Update(int* _flags) : flags(_flags) {}
inline bool update (uintE s, uintE d) {
if(flags[d] == IN) {if(flags[s] != OUT) flags[s] = OUT;}
else if(d < s && flags[s] == CONDITIONALLY_IN && flags[d] < OUT)
flags[s] = UNDECIDED;
return 1;
}
inline bool updateAtomic (uintE s, uintE d) {
if(flags[d] == IN) {if(flags[s] != OUT) flags[s] = OUT;}
else if(d < s && flags[s] == CONDITIONALLY_IN && flags[d] < OUT)
flags[s] = UNDECIDED;
return 1;
}
inline bool cond (uintE i) {return cond_true(i);}
};
struct MIS_Filter {
int* flags;
MIS_Filter(int* _flags) : flags(_flags) {}
inline bool operator () (uintE i) {
if(flags[i] == CONDITIONALLY_IN) { flags[i] = IN; return 0; } //vertex in MIS
else if(flags[i] == OUT) return 0; //vertex not in MIS
else { flags[i] = CONDITIONALLY_IN; return 1; } //vertex undecided, move to next round
}
};
//Takes a symmetric graph as input; priority of a vertex is its ID.
template <class vertex>
void Compute(graph<vertex>& GA, commandLine P) {
const intE n = GA.n;
bool checkCorrectness = P.getOptionValue("-checkCorrectness");
//flags array: UNDECIDED means "undecided", CONDITIONALLY_IN means
//"conditionally in MIS", OUT means "not in MIS", IN means "in MIS"
int* flags = newA(int,n);
bool* frontier_data = newA(bool, n);
{parallel_for(long i=0;i<n;i++) {
flags[i] = CONDITIONALLY_IN;
frontier_data[i] = 1;
}}
long round = 0;
vertexSubset Frontier(n, frontier_data);
while (!Frontier.isEmpty()) {
edgeMap(GA, Frontier, MIS_Update(flags));
vertexSubset output = vertexFilter(Frontier, MIS_Filter(flags));
Frontier.del();
Frontier = output;
round++;
}
#ifdef CHECK
if (checkCorrectness) {
if(checkMis(GA,flags)) cout << "correct\n";
else cout << "incorrect\n";
}
#endif
free(flags);
Frontier.del();
}
<|endoftext|> |
<commit_before>// armory.cpp : Defines the entry point for the DLL application.
// Some code copied from other default plugins ;)
/*
BSD license
Copyright (c) 2016 Kaadmy
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.
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 FreeBSD Project.
*/
#include <vector>
#include <map>
#include <math.h>
#include "bzfsAPI.h"
#include "plugin_utils.h"
enum {
ATTACKERS = 0,
DEFENDERS,
TIE
};
// armorypoint class
class ArmoryPoint:public bz_CustomZoneObject
{
public:
ArmoryPoint():bz_CustomZoneObject() {}
std::string title;
std::string name;
std::string unlock;
};
// main armory class
class armory:public bz_Plugin, bz_CustomMapObjectHandler
{
public:
virtual const char* Name (){return "Armory";}
virtual bool MapObject (bz_ApiString object, bz_CustomMapObjectInfo *data);
virtual bool EnoughPlayers(void);
virtual bool NoPlayers(void);
virtual void StartMatch(void);
virtual void WinState (int team);
virtual void Event (bz_EventData *eventData);
virtual void Init (const char* config);
virtual void Cleanup (void);
std::vector<ArmoryPoint> armoryPoints;
std::map<std::string, int> unlockedPoints; // list of unlocked points names
float matchTime; // time for each round to be; this shouldn't change after init
float matchEndTime; // what time the round ends at
bool matchEnded; // if the match is ended or not enough players
float nextTimeWarning; // when to show the next "time remaining" message
bz_eTeamType attackTeamColor;
bz_eTeamType defendTeamColor;
int attackerWins;
int attackerLosses;
int defenderWins;
int defenderLosses;
protected:
typedef struct
{
int playerID;
std::string callsign;
bool hasKey;
int team;
} playerRecord;
std::map<int, playerRecord> playerList;
};
BZ_PLUGIN(armory)
bool armory::NoPlayers() {
if(bz_getTeamCount(attackTeamColor) == 0 && bz_getTeamCount(defendTeamColor) == 0)
return true;
return false;
}
bool armory::EnoughPlayers() {
if(bz_getTeamCount(attackTeamColor) >= 1 && bz_getTeamCount(defendTeamColor) >= 1)
return false;
return true;
}
void armory::StartMatch (void) {
if(!matchEnded)
return;
if(!EnoughPlayers())
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS,
"Not enough players, please wait for more players to join.");
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Round has begun!");
matchEnded = false;
matchEndTime = bz_getCurrentTime() + matchTime;
nextTimeWarning = bz_getCurrentTime() + 3;
// reset all the player scores
for(unsigned int i = 0; i < playerList.size(); i++) {
bz_setPlayerLosses(playerList[i].playerID, 0);
bz_setPlayerWins(playerList[i].playerID, 0);
}
}
void armory::WinState (int team) {
if(matchEnded)
return;
matchEnded = true;
std::string teamString = "Attackers";
if(team == ATTACKERS) {
attackerWins ++;
defenderLosses --;
} else if(team == DEFENDERS) {
defenderWins ++;
attackerLosses --;
teamString = "Defenders";
} else if(team == TIE) {
teamString = "Nobody";
}
if(stdcmp(teamString.c_str(), "Nobody"))
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Nobody won the round; It's a tie!");
else
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "The %s have won the round!", teamString.c_str());
int highestRank = 0;
int mvp = -1;
// bz_debugMessage(0, std::to_string(playerList.size()).c_str());
for(unsigned int i = 0; i < playerList.size(); i++) {
if(team != TIE) {
int rank = bz_getPlayerRank(playerList[i].playerID);
if(playerList[i].team == team && rank > highestRank) {
highestRank = rank;
mvp = i;
}
}
// kill the player
bz_killPlayer(playerList[i].playerID, false, BZ_SERVER);
// and "fix" the player's score after killing them
bz_setPlayerLosses(playerList[i].playerID, bz_getPlayerLosses(playerList[i].playerID) - 1);
}
if(mvp != -1)
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS,
"%s was the %s's MVP this round.", playerList[mvp].callsign.c_str(), teamString.c_str());
}
bool armory::MapObject (bz_ApiString object, bz_CustomMapObjectInfo *data) {
if(object != "ARMORYPOINT" || !data)
return false;
ArmoryPoint zone;
zone.handleDefaultOptions(data);
zone.title = "UNKNOWN";
zone.name = "";
zone.unlock = "";
for (unsigned int i = 0; i < data->data.size(); i++) {
std::string line = data->data.get(i).c_str();
bz_APIStringList *nubs = bz_newStringList();
nubs->tokenize(line.c_str(), " ", 0, true);
if (nubs->size() > 0) {
std::string key = bz_toupper(nubs->get(0).c_str());
if (key == "TITLE" && nubs->size() > 1)
zone.title = nubs->get(1).c_str();
else if (key == "NAME" && nubs->size() > 1)
zone.name = nubs->get(1).c_str();
else if (key == "UNLOCK" && nubs->size() > 1)
zone.unlock = nubs->get(1).c_str();
}
bz_deleteStringList(nubs);
}
armoryPoints.push_back(zone);
return true;
}
void armory::Event (bz_EventData *eventData) {
switch(eventData->eventType) {
case bz_eTickEvent:
{
bz_TickEventData_V1* tick = (bz_TickEventData_V1*)eventData;
if(!EnoughPlayers())
return;
float timeLeft = matchEndTime - bz_getCurrentTime(); // seconds remaining in the match
if(timeLeft < 0.0) {
WinState(DEFENDERS);
}
if(timeLeft > 0.0 && (float)tick->eventTime >= nextTimeWarning) {
if(timeLeft < 10.0) {
nextTimeWarning += 1.0; // every second less than 10 seconds
std::string txt = + " seconds remaining";
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%d seconds remaining",
(int)ceil(timeLeft));
} else if(timeLeft < 30.0) {
nextTimeWarning += 20.0; // from 10 seconds down
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%d seconds remaining",
(int)ceil(timeLeft));
} else {
int minutesLeft = ceil(timeLeft / 60);
if(minutesLeft == 1)
nextTimeWarning += 30.0; // half minute
else
nextTimeWarning += 60.0; // next minute
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%d minutes remaining", minutesLeft);
}
}
break;
}
case bz_ePlayerSpawnEvent:
{
StartMatch();
break;
}
case bz_ePlayerJoinEvent:
{
bz_PlayerJoinPartEventData_V1* event = (bz_PlayerJoinPartEventData_V1*)eventData;
playerRecord record;
record.playerID = event->playerID;
record.callsign = event->record->callsign.c_str();
record.hasKey = false;
record.team = bz_getPlayerTeam(event->playerID);
playerList[event->playerID] = record;
}
break;
case bz_ePlayerPartEvent:
{
bz_PlayerJoinPartEventData_V1* event = (bz_PlayerJoinPartEventData_V1*)eventData;
std::map<int, playerRecord>::iterator itr = playerList.find(event->playerID);
if (itr != playerList.end())
playerList.erase(itr);
if(NoPlayers())
WinState(TIE);
}
break;
case bz_ePlayerUpdateEvent: {
bz_PlayerUpdateEventData_V1* player = (bz_PlayerUpdateEventData_V1*)eventData;
playerRecord &record = playerList.find(player->playerID)->second;
if(record.hasKey) {
for(unsigned int i = 0; i < armoryPoints.size(); i++) {
if(armoryPoints[i].pointInZone(player->state.pos)) {
if(unlockedPoints.find(armoryPoints[i].name) != unlockedPoints.end())
continue;
bool unlocked = true;
for(unsigned int j = 0; j < armoryPoints.size(); j++) {
if(armoryPoints[j].unlock == armoryPoints[i].name && unlockedPoints.find(armoryPoints[j].name) == unlockedPoints.end()) {
unlocked = false;
break;
}
}
if(!unlocked)
continue;
int flagID = bz_getPlayerFlagID(player->playerID);
bz_resetFlag(flagID);
if(!EnoughPlayers()) {
bz_sendTextMessage(BZ_SERVER, player->playerID, "Not enough players, play fair!");
return;
}
std::string capStr;
if(armoryPoints[i].unlock != "") {
for(unsigned int j = 0; j < armoryPoints.size(); j++) {
if(armoryPoints[j].name == armoryPoints[i].unlock) {
capStr = armoryPoints[j].title;
capStr += " has been unlocked by ";
capStr += record.callsign;
capStr += "!";
matchEndTime += 10; // increase time limit by 10 seconds
capStr += " +10 seconds!";
break;
}
}
} else {
capStr = record.callsign;
capStr += " has captured ";
capStr += armoryPoints[i].title;
capStr += "!";
WinState(ATTACKERS);
}
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (capStr).c_str());
unlockedPoints.insert(std::pair<std::string, int>(armoryPoints[i].name, 0));
record.hasKey = false;
break;
}
}
}
break;
}
case bz_eFlagGrabbedEvent: {
bz_FlagGrabbedEventData_V1* event = (bz_FlagGrabbedEventData_V1*)eventData;
if(strcmp(event->flagType, "KY") == 0) {
playerRecord &record = playerList.find(event->playerID)->second;
if(bz_getPlayerTeam(event->playerID) == attackTeamColor) {
if(!EnoughPlayers()) {
bz_sendTextMessage(BZ_SERVER, event->playerID, "Not enough players, play fair!");
int flagID = bz_getPlayerFlagID(event->playerID);
bz_resetFlag(flagID);
return;
}
record.hasKey = true;
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (record.callsign + " has picked up the Key!").c_str());
} else {
int flagID = bz_getPlayerFlagID(event->playerID);
bz_resetFlag(flagID);
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (record.callsign + " has returned the Key!").c_str());
}
}
break;
}
case bz_eFlagDroppedEvent: {
bz_FlagDroppedEventData_V1* event = (bz_FlagDroppedEventData_V1*)eventData;
if(strcmp(event->flagType, "KY") == 0) {
playerRecord &record = playerList.find(event->playerID)->second;
if(record.hasKey) {
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "The Key has been dropped!");
record.hasKey = false;
}
}
break;
}
case bz_eFlagTransferredEvent: {
bz_FlagTransferredEventData_V1* event = (bz_FlagTransferredEventData_V1*)eventData;
if(strcmp(event->flagType, "KY") == 0) {
playerRecord &fromRecord = playerList.find(event->fromPlayerID)->second;
playerRecord &toRecord = playerList.find(event->toPlayerID)->second;
fromRecord.hasKey = false;
toRecord.hasKey = true;
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (toRecord.callsign + " has taken the key!").c_str());
}
break;
}
default: {
break;
}
}
}
void armory::Init (const char* commandLine) {
matchTime = 2 * 60; // default 2 minutes
matchEndTime = -1;
matchEnded = true;
nextTimeWarning = -1;
attackTeamColor = eRedTeam; // hardcode for now, maybe changeable later
defendTeamColor = eGreenTeam; // hardcode for now, maybe changeable later
std::string param = commandLine;
int time = atoi(param.c_str());
if(time > 0) matchTime = (float)(time * 60);
matchTime += 3; // extra 3 seconds for preparation/spawning
Register(bz_eTickEvent);
Register(bz_ePlayerUpdateEvent);
Register(bz_ePlayerSpawnEvent);
Register(bz_ePlayerPartEvent);
Register(bz_ePlayerJoinEvent);
Register(bz_eFlagGrabbedEvent);
Register(bz_eFlagDroppedEvent);
Register(bz_eFlagTransferredEvent);
bz_RegisterCustomFlag("KY", "Key", "Take the key through armory points to unlock the armory!", 0, eGoodFlag);
bz_registerCustomMapObject("armorypoint", this);
MaxWaitTime = 0.1;
}
void armory::Cleanup (void) {
Flush();
bz_removeCustomMapObject("armorypoint");
}
<commit_msg>fix typos<commit_after>// armory.cpp : Defines the entry point for the DLL application.
// Some code copied from other default plugins ;)
/*
BSD license
Copyright (c) 2016 Kaadmy
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.
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 FreeBSD Project.
*/
#include <vector>
#include <map>
#include <math.h>
#include "bzfsAPI.h"
#include "plugin_utils.h"
enum {
ATTACKERS = 0,
DEFENDERS,
TIE
};
// armorypoint class
class ArmoryPoint:public bz_CustomZoneObject
{
public:
ArmoryPoint():bz_CustomZoneObject() {}
std::string title;
std::string name;
std::string unlock;
};
// main armory class
class armory:public bz_Plugin, bz_CustomMapObjectHandler
{
public:
virtual const char* Name (){return "Armory";}
virtual bool MapObject (bz_ApiString object, bz_CustomMapObjectInfo *data);
virtual bool EnoughPlayers(void);
virtual bool NoPlayers(void);
virtual void StartMatch(void);
virtual void WinState (int team);
virtual void Event (bz_EventData *eventData);
virtual void Init (const char* config);
virtual void Cleanup (void);
std::vector<ArmoryPoint> armoryPoints;
std::map<std::string, int> unlockedPoints; // list of unlocked points names
float matchTime; // time for each round to be; this shouldn't change after init
float matchEndTime; // what time the round ends at
bool matchEnded; // if the match is ended or not enough players
float nextTimeWarning; // when to show the next "time remaining" message
bz_eTeamType attackTeamColor;
bz_eTeamType defendTeamColor;
int attackerWins;
int attackerLosses;
int defenderWins;
int defenderLosses;
protected:
typedef struct
{
int playerID;
std::string callsign;
bool hasKey;
int team;
} playerRecord;
std::map<int, playerRecord> playerList;
};
BZ_PLUGIN(armory)
bool armory::NoPlayers() {
if(bz_getTeamCount(attackTeamColor) == 0 && bz_getTeamCount(defendTeamColor) == 0)
return true;
return false;
}
bool armory::EnoughPlayers() {
if(bz_getTeamCount(attackTeamColor) >= 1 && bz_getTeamCount(defendTeamColor) >= 1)
return true;
return false;
}
void armory::StartMatch (void) {
if(!matchEnded)
return;
if(!EnoughPlayers())
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS,
"Not enough players, please wait for more players to join.");
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Round has begun!");
matchEnded = false;
matchEndTime = bz_getCurrentTime() + matchTime;
nextTimeWarning = bz_getCurrentTime() + 3;
// reset all the player scores
for(unsigned int i = 0; i < playerList.size(); i++) {
bz_setPlayerLosses(playerList[i].playerID, 0);
bz_setPlayerWins(playerList[i].playerID, 0);
}
}
void armory::WinState (int team) {
if(matchEnded)
return;
matchEnded = true;
std::string teamString = "Attackers";
if(team == ATTACKERS) {
attackerWins ++;
defenderLosses --;
} else if(team == DEFENDERS) {
defenderWins ++;
attackerLosses --;
teamString = "Defenders";
} else if(team == TIE) {
teamString = "Nobody";
}
if(strcmp(teamString.c_str(), "Nobody"))
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Nobody won the round; It's a tie!");
else
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "The %s have won the round!", teamString.c_str());
int highestRank = 0;
int mvp = -1;
// bz_debugMessage(0, std::to_string(playerList.size()).c_str());
for(unsigned int i = 0; i < playerList.size(); i++) {
if(team != TIE) {
int rank = bz_getPlayerRank(playerList[i].playerID);
if(playerList[i].team == team && rank > highestRank) {
highestRank = rank;
mvp = i;
}
}
// kill the player
bz_killPlayer(playerList[i].playerID, false, BZ_SERVER);
// and "fix" the player's score after killing them
bz_setPlayerLosses(playerList[i].playerID, bz_getPlayerLosses(playerList[i].playerID) - 1);
}
if(mvp != -1)
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS,
"%s was the %s's MVP this round.", playerList[mvp].callsign.c_str(), teamString.c_str());
}
bool armory::MapObject (bz_ApiString object, bz_CustomMapObjectInfo *data) {
if(object != "ARMORYPOINT" || !data)
return false;
ArmoryPoint zone;
zone.handleDefaultOptions(data);
zone.title = "UNKNOWN";
zone.name = "";
zone.unlock = "";
for (unsigned int i = 0; i < data->data.size(); i++) {
std::string line = data->data.get(i).c_str();
bz_APIStringList *nubs = bz_newStringList();
nubs->tokenize(line.c_str(), " ", 0, true);
if (nubs->size() > 0) {
std::string key = bz_toupper(nubs->get(0).c_str());
if (key == "TITLE" && nubs->size() > 1)
zone.title = nubs->get(1).c_str();
else if (key == "NAME" && nubs->size() > 1)
zone.name = nubs->get(1).c_str();
else if (key == "UNLOCK" && nubs->size() > 1)
zone.unlock = nubs->get(1).c_str();
}
bz_deleteStringList(nubs);
}
armoryPoints.push_back(zone);
return true;
}
void armory::Event (bz_EventData *eventData) {
switch(eventData->eventType) {
case bz_eTickEvent:
{
bz_TickEventData_V1* tick = (bz_TickEventData_V1*)eventData;
if(!EnoughPlayers())
return;
float timeLeft = matchEndTime - bz_getCurrentTime(); // seconds remaining in the match
if(timeLeft < 0.0) {
WinState(DEFENDERS);
}
if(timeLeft > 0.0 && (float)tick->eventTime >= nextTimeWarning) {
if(timeLeft < 10.0) {
nextTimeWarning += 1.0; // every second less than 10 seconds
std::string txt = + " seconds remaining";
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%d seconds remaining",
(int)ceil(timeLeft));
} else if(timeLeft < 30.0) {
nextTimeWarning += 20.0; // from 10 seconds down
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%d seconds remaining",
(int)ceil(timeLeft));
} else {
int minutesLeft = ceil(timeLeft / 60);
if(minutesLeft == 1)
nextTimeWarning += 30.0; // half minute
else
nextTimeWarning += 60.0; // next minute
bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%d minutes remaining", minutesLeft);
}
}
break;
}
case bz_ePlayerSpawnEvent:
{
StartMatch();
break;
}
case bz_ePlayerJoinEvent:
{
bz_PlayerJoinPartEventData_V1* event = (bz_PlayerJoinPartEventData_V1*)eventData;
playerRecord record;
record.playerID = event->playerID;
record.callsign = event->record->callsign.c_str();
record.hasKey = false;
record.team = bz_getPlayerTeam(event->playerID);
playerList[event->playerID] = record;
}
break;
case bz_ePlayerPartEvent:
{
bz_PlayerJoinPartEventData_V1* event = (bz_PlayerJoinPartEventData_V1*)eventData;
std::map<int, playerRecord>::iterator itr = playerList.find(event->playerID);
if (itr != playerList.end())
playerList.erase(itr);
if(NoPlayers())
WinState(TIE);
}
break;
case bz_ePlayerUpdateEvent: {
bz_PlayerUpdateEventData_V1* player = (bz_PlayerUpdateEventData_V1*)eventData;
playerRecord &record = playerList.find(player->playerID)->second;
if(record.hasKey) {
for(unsigned int i = 0; i < armoryPoints.size(); i++) {
if(armoryPoints[i].pointInZone(player->state.pos)) {
if(unlockedPoints.find(armoryPoints[i].name) != unlockedPoints.end())
continue;
bool unlocked = true;
for(unsigned int j = 0; j < armoryPoints.size(); j++) {
if(armoryPoints[j].unlock == armoryPoints[i].name && unlockedPoints.find(armoryPoints[j].name) == unlockedPoints.end()) {
unlocked = false;
break;
}
}
if(!unlocked)
continue;
int flagID = bz_getPlayerFlagID(player->playerID);
bz_resetFlag(flagID);
if(!EnoughPlayers()) {
bz_sendTextMessage(BZ_SERVER, player->playerID, "Not enough players, play fair!");
return;
}
std::string capStr;
if(armoryPoints[i].unlock != "") {
for(unsigned int j = 0; j < armoryPoints.size(); j++) {
if(armoryPoints[j].name == armoryPoints[i].unlock) {
capStr = armoryPoints[j].title;
capStr += " has been unlocked by ";
capStr += record.callsign;
capStr += "!";
matchEndTime += 10; // increase time limit by 10 seconds
capStr += " +10 seconds!";
break;
}
}
} else {
capStr = record.callsign;
capStr += " has captured ";
capStr += armoryPoints[i].title;
capStr += "!";
WinState(ATTACKERS);
}
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (capStr).c_str());
unlockedPoints.insert(std::pair<std::string, int>(armoryPoints[i].name, 0));
record.hasKey = false;
break;
}
}
}
break;
}
case bz_eFlagGrabbedEvent: {
bz_FlagGrabbedEventData_V1* event = (bz_FlagGrabbedEventData_V1*)eventData;
if(strcmp(event->flagType, "KY") == 0) {
playerRecord &record = playerList.find(event->playerID)->second;
if(bz_getPlayerTeam(event->playerID) == attackTeamColor) {
if(!EnoughPlayers()) {
bz_sendTextMessage(BZ_SERVER, event->playerID, "Not enough players, play fair!");
int flagID = bz_getPlayerFlagID(event->playerID);
bz_resetFlag(flagID);
return;
}
record.hasKey = true;
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (record.callsign + " has picked up the Key!").c_str());
} else {
int flagID = bz_getPlayerFlagID(event->playerID);
bz_resetFlag(flagID);
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (record.callsign + " has returned the Key!").c_str());
}
}
break;
}
case bz_eFlagDroppedEvent: {
bz_FlagDroppedEventData_V1* event = (bz_FlagDroppedEventData_V1*)eventData;
if(strcmp(event->flagType, "KY") == 0) {
playerRecord &record = playerList.find(event->playerID)->second;
if(record.hasKey) {
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "The Key has been dropped!");
record.hasKey = false;
}
}
break;
}
case bz_eFlagTransferredEvent: {
bz_FlagTransferredEventData_V1* event = (bz_FlagTransferredEventData_V1*)eventData;
if(strcmp(event->flagType, "KY") == 0) {
playerRecord &fromRecord = playerList.find(event->fromPlayerID)->second;
playerRecord &toRecord = playerList.find(event->toPlayerID)->second;
fromRecord.hasKey = false;
toRecord.hasKey = true;
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, (toRecord.callsign + " has taken the key!").c_str());
}
break;
}
default: {
break;
}
}
}
void armory::Init (const char* commandLine) {
matchTime = 2 * 60; // default 2 minutes
matchEndTime = -1;
matchEnded = true;
nextTimeWarning = -1;
attackTeamColor = eRedTeam; // hardcode for now, maybe changeable later
defendTeamColor = eGreenTeam; // hardcode for now, maybe changeable later
std::string param = commandLine;
int time = atoi(param.c_str());
if(time > 0) matchTime = (float)(time * 60);
matchTime += 3; // extra 3 seconds for preparation/spawning
Register(bz_eTickEvent);
Register(bz_ePlayerUpdateEvent);
Register(bz_ePlayerSpawnEvent);
Register(bz_ePlayerPartEvent);
Register(bz_ePlayerJoinEvent);
Register(bz_eFlagGrabbedEvent);
Register(bz_eFlagDroppedEvent);
Register(bz_eFlagTransferredEvent);
bz_RegisterCustomFlag("KY", "Key", "Take the key through armory points to unlock the armory!", 0, eGoodFlag);
bz_registerCustomMapObject("armorypoint", this);
MaxWaitTime = 0.1;
}
void armory::Cleanup (void) {
Flush();
bz_removeCustomMapObject("armorypoint");
}
<|endoftext|> |
<commit_before>// @(#)root/minuit2:$Name: $:$Id: Numerical2PGradientCalculator.cpp,v 1.8.4.4 2005/11/29 11:08:35 moneta Exp $
// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005
/**********************************************************************
* *
* Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT *
* *
**********************************************************************/
#include "Minuit2/Numerical2PGradientCalculator.h"
#include "Minuit2/InitialGradientCalculator.h"
#include "Minuit2/MnFcn.h"
#include "Minuit2/MnUserTransformation.h"
#include "Minuit2/MnMachinePrecision.h"
#include "Minuit2/MinimumParameters.h"
#include "Minuit2/FunctionGradient.h"
#include "Minuit2/MnStrategy.h"
#ifdef DEBUG
#include "Minuit2/MnPrint.h"
#endif
#include <math.h>
namespace ROOT {
namespace Minuit2 {
FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParameters& par) const {
InitialGradientCalculator gc(fFcn, fTransformation, fStrategy);
FunctionGradient gra = gc(par);
return (*this)(par, gra);
}
// comment it, because it was added
FunctionGradient Numerical2PGradientCalculator::operator()(const std::vector<double>& params) const {
int npar = params.size();
MnAlgebraicVector par(npar);
for (int i = 0; i < npar; ++i) {
par(i) = params[i];
}
double fval = Fcn()(par);
MinimumParameters minpars = MinimumParameters(par, fval);
return (*this)(minpars);
}
FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient& Gradient) const {
// std::cout<<"########### Numerical2PDerivative"<<std::endl;
// std::cout<<"initial grd: "<<Gradient.Grad()<<std::endl;
// std::cout<<"position: "<<par.Vec()<<std::endl;
assert(par.IsValid());
MnAlgebraicVector x = par.Vec();
double fcnmin = par.Fval();
// std::cout<<"fval: "<<fcnmin<<std::endl;
double dfmin = 8.*Precision().Eps2()*(fabs(fcnmin)+Fcn().Up());
double vrysml = 8.*Precision().Eps()*Precision().Eps();
// double vrysml = std::max(1.e-4, Precision().Eps2());
// std::cout<<"dfmin= "<<dfmin<<std::endl;
// std::cout<<"vrysml= "<<vrysml<<std::endl;
// std::cout << " ncycle " << Ncycle() << std::endl;
unsigned int n = x.size();
// MnAlgebraicVector vgrd(n), vgrd2(n), vgstp(n);
MnAlgebraicVector grd = Gradient.Grad();
MnAlgebraicVector g2 = Gradient.G2();
MnAlgebraicVector gstep = Gradient.Gstep();
for(unsigned int i = 0; i < n; i++) {
double xtf = x(i);
double epspri = Precision().Eps2() + fabs(grd(i)*Precision().Eps2());
double stepb4 = 0.;
for(unsigned int j = 0; j < Ncycle(); j++) {
double optstp = sqrt(dfmin/(fabs(g2(i))+epspri));
double step = std::max(optstp, fabs(0.1*gstep(i)));
// std::cout<<"step: "<<step;
if(Trafo().Parameter(Trafo().ExtOfInt(i)).HasLimits()) {
if(step > 0.5) step = 0.5;
}
double stpmax = 10.*fabs(gstep(i));
if(step > stpmax) step = stpmax;
// std::cout<<" "<<step;
double stpmin = std::max(vrysml, 8.*fabs(Precision().Eps2()*x(i)));
if(step < stpmin) step = stpmin;
// std::cout<<" "<<step<<std::endl;
// std::cout<<"step: "<<step<<std::endl;
if(fabs((step-stepb4)/step) < StepTolerance()) {
// std::cout<<"(step-stepb4)/step"<<std::endl;
// std::cout<<"j= "<<j<<std::endl;
// std::cout<<"step= "<<step<<std::endl;
break;
}
gstep(i) = step;
stepb4 = step;
// MnAlgebraicVector pstep(n);
// pstep(i) = step;
// double fs1 = Fcn()(pstate + pstep);
// double fs2 = Fcn()(pstate - pstep);
x(i) = xtf + step;
double fs1 = Fcn()(x);
x(i) = xtf - step;
double fs2 = Fcn()(x);
x(i) = xtf;
double grdb4 = grd(i);
grd(i) = 0.5*(fs1 - fs2)/step;
g2(i) = (fs1 + fs2 - 2.*fcnmin)/step/step;
if(fabs(grdb4-grd(i))/(fabs(grd(i))+dfmin/step) < GradTolerance()) {
// std::cout<<"j= "<<j<<std::endl;
// std::cout<<"step= "<<step<<std::endl;
// std::cout<<"fs1, fs2: "<<fs1<<" "<<fs2<<std::endl;
// std::cout<<"fs1-fs2: "<<fs1-fs2<<std::endl;
break;
}
}
// vgrd(i) = grd;
// vgrd2(i) = g2;
// vgstp(i) = gstep;
}
// std::cout<<"final grd: "<<grd<<std::endl;
// std::cout<<"########### return from Numerical2PDerivative"<<std::endl;
return FunctionGradient(grd, g2, gstep);
}
const MnMachinePrecision& Numerical2PGradientCalculator::Precision() const {
return fTransformation.Precision();
}
unsigned int Numerical2PGradientCalculator::Ncycle() const {
return Strategy().GradientNCycles();
}
double Numerical2PGradientCalculator::StepTolerance() const {
return Strategy().GradientStepTolerance();
}
double Numerical2PGradientCalculator::GradTolerance() const {
return Strategy().GradientTolerance();
}
} // namespace Minuit2
} // namespace ROOT
<commit_msg>small changes (caching some variables) to improve performances<commit_after>// @(#)root/minuit2:$Name: $:$Id: Numerical2PGradientCalculator.cxx,v 1.1 2005/11/29 14:43:31 moneta Exp $
// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005
/**********************************************************************
* *
* Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT *
* *
**********************************************************************/
#include "Minuit2/Numerical2PGradientCalculator.h"
#include "Minuit2/InitialGradientCalculator.h"
#include "Minuit2/MnFcn.h"
#include "Minuit2/MnUserTransformation.h"
#include "Minuit2/MnMachinePrecision.h"
#include "Minuit2/MinimumParameters.h"
#include "Minuit2/FunctionGradient.h"
#include "Minuit2/MnStrategy.h"
#ifdef DEBUG
#include "Minuit2/MnPrint.h"
#endif
#include <math.h>
namespace ROOT {
namespace Minuit2 {
FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParameters& par) const {
InitialGradientCalculator gc(fFcn, fTransformation, fStrategy);
FunctionGradient gra = gc(par);
return (*this)(par, gra);
}
// comment it, because it was added
FunctionGradient Numerical2PGradientCalculator::operator()(const std::vector<double>& params) const {
int npar = params.size();
MnAlgebraicVector par(npar);
for (int i = 0; i < npar; ++i) {
par(i) = params[i];
}
double fval = Fcn()(par);
MinimumParameters minpars = MinimumParameters(par, fval);
return (*this)(minpars);
}
FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient& Gradient) const {
// std::cout<<"########### Numerical2PDerivative"<<std::endl;
// std::cout<<"initial grd: "<<Gradient.Grad()<<std::endl;
// std::cout<<"position: "<<par.Vec()<<std::endl;
assert(par.IsValid());
MnAlgebraicVector x = par.Vec();
double fcnmin = par.Fval();
// std::cout<<"fval: "<<fcnmin<<std::endl;
double eps2 = Precision().Eps2();
double eps = Precision().Eps();
double dfmin = 8.*eps2*(fabs(fcnmin)+Fcn().Up());
double vrysml = 8.*eps*eps;
// double vrysml = std::max(1.e-4, eps2);
// std::cout<<"dfmin= "<<dfmin<<std::endl;
// std::cout<<"vrysml= "<<vrysml<<std::endl;
// std::cout << " ncycle " << Ncycle() << std::endl;
unsigned int n = x.size();
unsigned int ncycle = Ncycle();
// MnAlgebraicVector vgrd(n), vgrd2(n), vgstp(n);
MnAlgebraicVector grd = Gradient.Grad();
MnAlgebraicVector g2 = Gradient.G2();
MnAlgebraicVector gstep = Gradient.Gstep();
for(unsigned int i = 0; i < n; i++) {
double xtf = x(i);
double epspri = eps2 + fabs(grd(i)*eps2);
double stepb4 = 0.;
for(unsigned int j = 0; j < ncycle; j++) {
double optstp = sqrt(dfmin/(fabs(g2(i))+epspri));
double step = std::max(optstp, fabs(0.1*gstep(i)));
double wstep = 1./step;
// std::cout<<"step: "<<step;
if(Trafo().Parameter(Trafo().ExtOfInt(i)).HasLimits()) {
if(step > 0.5) step = 0.5;
}
double stpmax = 10.*fabs(gstep(i));
if(step > stpmax) step = stpmax;
// std::cout<<" "<<step;
double stpmin = std::max(vrysml, 8.*fabs(eps2*x(i)));
if(step < stpmin) step = stpmin;
// std::cout<<" "<<step<<std::endl;
// std::cout<<"step: "<<step<<std::endl;
if(fabs((step-stepb4)*wstep) < StepTolerance()) {
// std::cout<<"(step-stepb4)/step"<<std::endl;
// std::cout<<"j= "<<j<<std::endl;
// std::cout<<"step= "<<step<<std::endl;
break;
}
gstep(i) = step;
stepb4 = step;
// MnAlgebraicVector pstep(n);
// pstep(i) = step;
// double fs1 = Fcn()(pstate + pstep);
// double fs2 = Fcn()(pstate - pstep);
x(i) = xtf + step;
double fs1 = Fcn()(x);
x(i) = xtf - step;
double fs2 = Fcn()(x);
x(i) = xtf;
double grdb4 = grd(i);
grd(i) = 0.5*(fs1 - fs2)*wstep;
g2(i) = (fs1 + fs2 - 2.*fcnmin)*wstep*wstep;
if(fabs(grdb4-grd(i))/(fabs(grd(i))+dfmin*wstep) < GradTolerance()) {
// std::cout<<"j= "<<j<<std::endl;
// std::cout<<"step= "<<step<<std::endl;
// std::cout<<"fs1, fs2: "<<fs1<<" "<<fs2<<std::endl;
// std::cout<<"fs1-fs2: "<<fs1-fs2<<std::endl;
break;
}
}
// vgrd(i) = grd;
// vgrd2(i) = g2;
// vgstp(i) = gstep;
}
// std::cout<<"final grd: "<<grd<<std::endl;
// std::cout<<"########### return from Numerical2PDerivative"<<std::endl;
return FunctionGradient(grd, g2, gstep);
}
const MnMachinePrecision& Numerical2PGradientCalculator::Precision() const {
return fTransformation.Precision();
}
unsigned int Numerical2PGradientCalculator::Ncycle() const {
return Strategy().GradientNCycles();
}
double Numerical2PGradientCalculator::StepTolerance() const {
return Strategy().GradientStepTolerance();
}
double Numerical2PGradientCalculator::GradTolerance() const {
return Strategy().GradientTolerance();
}
} // namespace Minuit2
} // namespace ROOT
<|endoftext|> |
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_peek.h"
#include <vespa/eval/eval/nested_loop.h>
#include <vespa/eval/eval/wrap_param.h>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <vespa/vespalib/util/shared_string_repo.h>
#include <cassert>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using State = InterpretedFunction::State;
using Instruction = InterpretedFunction::Instruction;
using Handle = SharedStringRepo::Handle;
namespace {
static constexpr size_t npos = -1;
using Spec = GenericPeek::SpecMap;
size_t count_children(const Spec &spec)
{
// accounts for "input" child:
size_t num_children = 1;
for (const auto & [dim_name, child_or_label] : spec) {
if (std::holds_alternative<size_t>(child_or_label)) {
++num_children;
}
}
return num_children;
}
struct DimSpec {
enum class DimType { CHILD_IDX, LABEL_IDX, LABEL_STR };
vespalib::string name;
DimType dim_type;
size_t idx;
Handle str;
static DimSpec from_child(const vespalib::string &name_in, size_t child_idx) {
return {name_in, DimType::CHILD_IDX, child_idx, Handle()};
}
static DimSpec from_label(const vespalib::string &name_in, const TensorSpec::Label &label) {
if (label.is_mapped()) {
return {name_in, DimType::LABEL_STR, 0, Handle(label.name)};
} else {
assert(label.is_indexed());
return {name_in, DimType::LABEL_IDX, label.index, Handle()};
}
}
~DimSpec();
bool has_child() const {
return (dim_type == DimType::CHILD_IDX);
}
bool has_label() const {
return (dim_type != DimType::CHILD_IDX);
}
size_t get_child_idx() const {
assert(dim_type == DimType::CHILD_IDX);
return idx;
}
string_id get_label_name() const {
assert(dim_type == DimType::LABEL_STR);
return str.id();
}
size_t get_label_index() const {
assert(dim_type == DimType::LABEL_IDX);
return idx;
}
};
DimSpec::~DimSpec() = default;
struct ExtractedSpecs {
using Dimension = ValueType::Dimension;
struct MyComp {
bool operator() (const Dimension &a, const Spec::value_type &b) { return a.name < b.first; }
bool operator() (const Spec::value_type &a, const Dimension &b) { return a.first < b.name; }
};
std::vector<Dimension> dimensions;
std::vector<DimSpec> specs;
ExtractedSpecs(bool indexed,
const std::vector<Dimension> &input_dims,
const Spec &spec)
{
auto visitor = overload
{
[&](visit_ranges_first, const auto &a) {
if (a.is_indexed() == indexed) dimensions.push_back(a);
},
[&](visit_ranges_second, const auto &) {
// spec has unknown dimension
abort();
},
[&](visit_ranges_both, const auto &a, const auto &b) {
if (a.is_indexed() == indexed) {
dimensions.push_back(a);
const auto & [spec_dim_name, child_or_label] = b;
assert(a.name == spec_dim_name);
if (std::holds_alternative<size_t>(child_or_label)) {
specs.push_back(DimSpec::from_child(a.name, std::get<size_t>(child_or_label)));
} else {
specs.push_back(DimSpec::from_label(a.name, std::get<TensorSpec::Label>(child_or_label)));
}
}
}
};
visit_ranges(visitor,
input_dims.begin(), input_dims.end(),
spec.begin(), spec.end(), MyComp());
}
~ExtractedSpecs();
};
ExtractedSpecs::~ExtractedSpecs() = default;
struct DenseSizes {
SmallVector<size_t> size;
SmallVector<size_t> stride;
size_t cur_size;
DenseSizes(const std::vector<ValueType::Dimension> &dims)
: size(), stride(dims.size()), cur_size(1)
{
for (const auto &dim : dims) {
assert(dim.is_indexed());
size.push_back(dim.size);
}
for (size_t i = size.size(); i-- > 0; ) {
stride[i] = cur_size;
cur_size *= size[i];
}
}
};
/** Compute input offsets for all output cells */
struct DensePlan {
size_t in_dense_size;
size_t out_dense_size;
SmallVector<size_t> loop_cnt;
SmallVector<size_t> in_stride;
size_t verbatim_offset = 0;
struct Child {
size_t idx;
size_t stride;
size_t limit;
};
SmallVector<Child,4> children;
DensePlan(const ValueType &input_type, const Spec &spec)
{
const ExtractedSpecs mine(true, input_type.dimensions(), spec);
DenseSizes sizes(mine.dimensions);
in_dense_size = sizes.cur_size;
out_dense_size = 1;
auto pos = mine.specs.begin();
for (size_t i = 0; i < mine.dimensions.size(); ++i) {
const auto &dim = mine.dimensions[i];
if ((pos == mine.specs.end()) || (dim.name < pos->name)) {
loop_cnt.push_back(sizes.size[i]);
in_stride.push_back(sizes.stride[i]);
out_dense_size *= sizes.size[i];
} else {
assert(dim.name == pos->name);
if (pos->has_child()) {
children.push_back(Child{pos->get_child_idx(), sizes.stride[i], sizes.size[i]});
} else {
assert(pos->has_label());
size_t label_index = pos->get_label_index();
assert(label_index < sizes.size[i]);
verbatim_offset += label_index * sizes.stride[i];
}
++pos;
}
}
assert(pos == mine.specs.end());
}
/** Get initial offset (from verbatim labels and child values) */
template <typename Getter>
size_t get_offset(const Getter &get_child_value) const {
size_t offset = verbatim_offset;
for (size_t i = 0; i < children.size(); ++i) {
size_t from_child = get_child_value(children[i].idx);
if (from_child < children[i].limit) {
offset += from_child * children[i].stride;
} else {
return npos;
}
}
return offset;
}
template<typename F> void execute(size_t offset, const F &f) const {
run_nested_loop<F>(offset, loop_cnt, in_stride, f);
}
};
struct SparseState {
SmallVector<Handle> handles;
SmallVector<string_id> view_addr;
SmallVector<const string_id *> lookup_refs;
SmallVector<string_id> output_addr;
SmallVector<string_id *> fetch_addr;
SparseState(SmallVector<Handle> handles_in, SmallVector<string_id> view_addr_in, size_t out_dims)
: handles(std::move(handles_in)),
view_addr(std::move(view_addr_in)),
lookup_refs(view_addr.size()),
output_addr(out_dims),
fetch_addr(out_dims)
{
for (size_t i = 0; i < view_addr.size(); ++i) {
lookup_refs[i] = &view_addr[i];
}
for (size_t i = 0; i < out_dims; ++i) {
fetch_addr[i] = &output_addr[i];
}
}
~SparseState();
};
SparseState::~SparseState() = default;
struct SparsePlan {
size_t out_mapped_dims;
std::vector<DimSpec> lookup_specs;
SmallVector<size_t> view_dims;
SparsePlan(const ValueType &input_type,
const GenericPeek::SpecMap &spec)
: out_mapped_dims(0),
view_dims()
{
ExtractedSpecs mine(false, input_type.dimensions(), spec);
lookup_specs = std::move(mine.specs);
auto pos = lookup_specs.begin();
for (size_t dim_idx = 0; dim_idx < mine.dimensions.size(); ++dim_idx) {
const auto & dim = mine.dimensions[dim_idx];
if ((pos == lookup_specs.end()) || (dim.name < pos->name)) {
++out_mapped_dims;
} else {
assert(dim.name == pos->name);
view_dims.push_back(dim_idx);
++pos;
}
}
assert(pos == lookup_specs.end());
}
~SparsePlan();
template <typename Getter>
SparseState make_state(const Getter &get_child_value) const {
SmallVector<Handle> handles;
SmallVector<string_id> view_addr;
for (const auto & dim : lookup_specs) {
if (dim.has_child()) {
int64_t child_value = get_child_value(dim.get_child_idx());
handles.emplace_back(vespalib::make_string("%" PRId64, child_value));
view_addr.push_back(handles.back().id());
} else {
view_addr.push_back(dim.get_label_name());
}
}
assert(view_addr.size() == view_dims.size());
return SparseState(std::move(handles), std::move(view_addr), out_mapped_dims);
}
};
SparsePlan::~SparsePlan() = default;
struct PeekParam {
const ValueType res_type;
DensePlan dense_plan;
SparsePlan sparse_plan;
size_t num_children;
const ValueBuilderFactory &factory;
PeekParam(const ValueType &input_type,
const ValueType &res_type_in,
const GenericPeek::SpecMap &spec_in,
const ValueBuilderFactory &factory_in)
: res_type(res_type_in),
dense_plan(input_type, spec_in),
sparse_plan(input_type, spec_in),
num_children(count_children(spec_in)),
factory(factory_in)
{
assert(dense_plan.in_dense_size == input_type.dense_subspace_size());
assert(dense_plan.out_dense_size == res_type.dense_subspace_size());
}
};
template <typename ICT, typename OCT, typename Getter>
Value::UP
generic_mixed_peek(const ValueType &res_type,
const Value &input_value,
const SparsePlan &sparse_plan,
const DensePlan &dense_plan,
const ValueBuilderFactory &factory,
const Getter &get_child_value)
{
auto input_cells = input_value.cells().typify<ICT>();
size_t bad_guess = 1;
auto builder = factory.create_transient_value_builder<OCT>(res_type,
sparse_plan.out_mapped_dims,
dense_plan.out_dense_size,
bad_guess);
size_t filled_subspaces = 0;
size_t dense_offset = dense_plan.get_offset(get_child_value);
if (dense_offset != npos) {
SparseState state = sparse_plan.make_state(get_child_value);
auto view = input_value.index().create_view(sparse_plan.view_dims);
view->lookup(state.lookup_refs);
size_t input_subspace;
while (view->next_result(state.fetch_addr, input_subspace)) {
auto dst = builder->add_subspace(state.output_addr).begin();
auto input_offset = input_subspace * dense_plan.in_dense_size;
dense_plan.execute(dense_offset + input_offset,
[&](size_t idx) { *dst++ = input_cells[idx]; });
++filled_subspaces;
}
}
if ((sparse_plan.out_mapped_dims == 0) && (filled_subspaces == 0)) {
for (auto & v : builder->add_subspace()) {
v = OCT{};
}
}
return builder->build(std::move(builder));
}
template <typename ICT, typename OCT>
void my_generic_peek_op(State &state, uint64_t param_in) {
const auto ¶m = unwrap_param<PeekParam>(param_in);
// stack index for children are in range [0, num_children>
size_t last_valid_stack_idx = param.num_children - 1;
const Value & input_value = state.peek(last_valid_stack_idx);
auto get_child_value = [&] (size_t child_idx) {
size_t stack_idx = last_valid_stack_idx - child_idx;
return int64_t(state.peek(stack_idx).as_double());
};
auto up = generic_mixed_peek<ICT,OCT>(param.res_type, input_value,
param.sparse_plan, param.dense_plan,
param.factory, get_child_value);
const Value &result = *state.stash.create<Value::UP>(std::move(up));
// num_children includes the "input" param
state.pop_n_push(param.num_children, result);
}
struct SelectGenericPeekOp {
template <typename ICT, typename OCT> static auto invoke() {
return my_generic_peek_op<ICT,OCT>;
}
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
Instruction
GenericPeek::make_instruction(const ValueType &input_type,
const ValueType &res_type,
const SpecMap &spec,
const ValueBuilderFactory &factory,
Stash &stash)
{
const auto ¶m = stash.create<PeekParam>(input_type, res_type, spec, factory);
auto fun = typify_invoke<2,TypifyCellType,SelectGenericPeekOp>(input_type.cell_type(), res_type.cell_type());
return Instruction(fun, wrap_param<PeekParam>(param));
}
} // namespace
<commit_msg>trim down run-time DimSpec for GenericPeek<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_peek.h"
#include <vespa/eval/eval/nested_loop.h>
#include <vespa/eval/eval/wrap_param.h>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <vespa/vespalib/util/shared_string_repo.h>
#include <cassert>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using State = InterpretedFunction::State;
using Instruction = InterpretedFunction::Instruction;
using Handle = SharedStringRepo::Handle;
namespace {
static constexpr size_t npos = -1;
using Spec = GenericPeek::SpecMap;
size_t count_children(const Spec &spec)
{
// accounts for "input" child:
size_t num_children = 1;
for (const auto & [dim_name, child_or_label] : spec) {
if (std::holds_alternative<size_t>(child_or_label)) {
++num_children;
}
}
return num_children;
}
struct DimSpec {
enum class DimType { CHILD_IDX, LABEL_IDX, LABEL_STR };
DimType dim_type;
Handle str;
size_t idx;
static DimSpec from_child(size_t child_idx) {
return {DimType::CHILD_IDX, Handle(), child_idx};
}
static DimSpec from_label(const TensorSpec::Label &label) {
if (label.is_mapped()) {
return {DimType::LABEL_STR, Handle(label.name), 0};
} else {
assert(label.is_indexed());
return {DimType::LABEL_IDX, Handle(), label.index};
}
}
~DimSpec();
bool has_child() const {
return (dim_type == DimType::CHILD_IDX);
}
bool has_label() const {
return (dim_type != DimType::CHILD_IDX);
}
size_t get_child_idx() const {
assert(dim_type == DimType::CHILD_IDX);
return idx;
}
string_id get_label_name() const {
assert(dim_type == DimType::LABEL_STR);
return str.id();
}
size_t get_label_index() const {
assert(dim_type == DimType::LABEL_IDX);
return idx;
}
};
DimSpec::~DimSpec() = default;
struct ExtractedSpecs {
using Dimension = ValueType::Dimension;
struct MyComp {
bool operator() (const Dimension &a, const Spec::value_type &b) { return a.name < b.first; }
bool operator() (const Spec::value_type &a, const Dimension &b) { return a.first < b.name; }
};
std::vector<Dimension> dimensions;
struct NamedDimSpec {
const vespalib::string & name;
DimSpec spec;
};
SmallVector<NamedDimSpec,4> specs;
ExtractedSpecs(bool indexed,
const std::vector<Dimension> &input_dims,
const Spec &spec)
{
auto visitor = overload
{
[&](visit_ranges_first, const auto &a) {
if (a.is_indexed() == indexed) dimensions.push_back(a);
},
[&](visit_ranges_second, const auto &) {
// spec has unknown dimension
abort();
},
[&](visit_ranges_both, const auto &a, const auto &b) {
if (a.is_indexed() == indexed) {
dimensions.push_back(a);
const auto & [spec_dim_name, child_or_label] = b;
assert(a.name == spec_dim_name);
if (std::holds_alternative<size_t>(child_or_label)) {
NamedDimSpec nds{a.name, DimSpec::from_child(std::get<size_t>(child_or_label))};
specs.push_back(nds);
} else {
NamedDimSpec nds{a.name, DimSpec::from_label(std::get<TensorSpec::Label>(child_or_label))};
specs.push_back(nds);
}
}
}
};
visit_ranges(visitor,
input_dims.begin(), input_dims.end(),
spec.begin(), spec.end(), MyComp());
}
~ExtractedSpecs();
};
ExtractedSpecs::~ExtractedSpecs() = default;
struct DenseSizes {
SmallVector<size_t> size;
SmallVector<size_t> stride;
size_t cur_size;
DenseSizes(const std::vector<ValueType::Dimension> &dims)
: size(), stride(dims.size()), cur_size(1)
{
for (const auto &dim : dims) {
assert(dim.is_indexed());
size.push_back(dim.size);
}
for (size_t i = size.size(); i-- > 0; ) {
stride[i] = cur_size;
cur_size *= size[i];
}
}
};
/** Compute input offsets for all output cells */
struct DensePlan {
size_t in_dense_size;
size_t out_dense_size;
SmallVector<size_t> loop_cnt;
SmallVector<size_t> in_stride;
size_t verbatim_offset = 0;
struct Child {
size_t idx;
size_t stride;
size_t limit;
};
SmallVector<Child,4> children;
DensePlan(const ValueType &input_type, const Spec &spec)
{
const ExtractedSpecs mine(true, input_type.dimensions(), spec);
DenseSizes sizes(mine.dimensions);
in_dense_size = sizes.cur_size;
out_dense_size = 1;
auto pos = mine.specs.begin();
for (size_t i = 0; i < mine.dimensions.size(); ++i) {
const auto &dim = mine.dimensions[i];
if ((pos == mine.specs.end()) || (dim.name < pos->name)) {
loop_cnt.push_back(sizes.size[i]);
in_stride.push_back(sizes.stride[i]);
out_dense_size *= sizes.size[i];
} else {
assert(dim.name == pos->name);
if (pos->spec.has_child()) {
children.push_back(Child{pos->spec.get_child_idx(), sizes.stride[i], sizes.size[i]});
} else {
assert(pos->spec.has_label());
size_t label_index = pos->spec.get_label_index();
assert(label_index < sizes.size[i]);
verbatim_offset += label_index * sizes.stride[i];
}
++pos;
}
}
assert(pos == mine.specs.end());
}
/** Get initial offset (from verbatim labels and child values) */
template <typename Getter>
size_t get_offset(const Getter &get_child_value) const {
size_t offset = verbatim_offset;
for (size_t i = 0; i < children.size(); ++i) {
size_t from_child = get_child_value(children[i].idx);
if (from_child < children[i].limit) {
offset += from_child * children[i].stride;
} else {
return npos;
}
}
return offset;
}
template<typename F> void execute(size_t offset, const F &f) const {
run_nested_loop<F>(offset, loop_cnt, in_stride, f);
}
};
struct SparseState {
SmallVector<Handle> handles;
SmallVector<string_id> view_addr;
SmallVector<const string_id *> lookup_refs;
SmallVector<string_id> output_addr;
SmallVector<string_id *> fetch_addr;
SparseState(SmallVector<Handle> handles_in, SmallVector<string_id> view_addr_in, size_t out_dims)
: handles(std::move(handles_in)),
view_addr(std::move(view_addr_in)),
lookup_refs(view_addr.size()),
output_addr(out_dims),
fetch_addr(out_dims)
{
for (size_t i = 0; i < view_addr.size(); ++i) {
lookup_refs[i] = &view_addr[i];
}
for (size_t i = 0; i < out_dims; ++i) {
fetch_addr[i] = &output_addr[i];
}
}
~SparseState();
};
SparseState::~SparseState() = default;
struct SparsePlan {
size_t out_mapped_dims;
SmallVector<DimSpec> lookup_specs;
SmallVector<size_t> view_dims;
SparsePlan(const ValueType &input_type,
const GenericPeek::SpecMap &spec)
: out_mapped_dims(0),
view_dims()
{
ExtractedSpecs mine(false, input_type.dimensions(), spec);
auto pos = mine.specs.begin();
for (size_t dim_idx = 0; dim_idx < mine.dimensions.size(); ++dim_idx) {
const auto & dim = mine.dimensions[dim_idx];
if ((pos == mine.specs.end()) || (dim.name < pos->name)) {
++out_mapped_dims;
} else {
assert(dim.name == pos->name);
view_dims.push_back(dim_idx);
lookup_specs.push_back(pos->spec);
++pos;
}
}
assert(pos == mine.specs.end());
}
~SparsePlan();
template <typename Getter>
SparseState make_state(const Getter &get_child_value) const {
SmallVector<Handle> handles;
SmallVector<string_id> view_addr;
for (const auto & dim : lookup_specs) {
if (dim.has_child()) {
int64_t child_value = get_child_value(dim.get_child_idx());
handles.emplace_back(vespalib::make_string("%" PRId64, child_value));
view_addr.push_back(handles.back().id());
} else {
view_addr.push_back(dim.get_label_name());
}
}
assert(view_addr.size() == view_dims.size());
return SparseState(std::move(handles), std::move(view_addr), out_mapped_dims);
}
};
SparsePlan::~SparsePlan() = default;
struct PeekParam {
const ValueType res_type;
DensePlan dense_plan;
SparsePlan sparse_plan;
size_t num_children;
const ValueBuilderFactory &factory;
PeekParam(const ValueType &input_type,
const ValueType &res_type_in,
const GenericPeek::SpecMap &spec_in,
const ValueBuilderFactory &factory_in)
: res_type(res_type_in),
dense_plan(input_type, spec_in),
sparse_plan(input_type, spec_in),
num_children(count_children(spec_in)),
factory(factory_in)
{
assert(dense_plan.in_dense_size == input_type.dense_subspace_size());
assert(dense_plan.out_dense_size == res_type.dense_subspace_size());
}
};
template <typename ICT, typename OCT, typename Getter>
Value::UP
generic_mixed_peek(const ValueType &res_type,
const Value &input_value,
const SparsePlan &sparse_plan,
const DensePlan &dense_plan,
const ValueBuilderFactory &factory,
const Getter &get_child_value)
{
auto input_cells = input_value.cells().typify<ICT>();
size_t bad_guess = 1;
auto builder = factory.create_transient_value_builder<OCT>(res_type,
sparse_plan.out_mapped_dims,
dense_plan.out_dense_size,
bad_guess);
size_t filled_subspaces = 0;
size_t dense_offset = dense_plan.get_offset(get_child_value);
if (dense_offset != npos) {
SparseState state = sparse_plan.make_state(get_child_value);
auto view = input_value.index().create_view(sparse_plan.view_dims);
view->lookup(state.lookup_refs);
size_t input_subspace;
while (view->next_result(state.fetch_addr, input_subspace)) {
auto dst = builder->add_subspace(state.output_addr).begin();
auto input_offset = input_subspace * dense_plan.in_dense_size;
dense_plan.execute(dense_offset + input_offset,
[&](size_t idx) { *dst++ = input_cells[idx]; });
++filled_subspaces;
}
}
if ((sparse_plan.out_mapped_dims == 0) && (filled_subspaces == 0)) {
for (auto & v : builder->add_subspace()) {
v = OCT{};
}
}
return builder->build(std::move(builder));
}
template <typename ICT, typename OCT>
void my_generic_peek_op(State &state, uint64_t param_in) {
const auto ¶m = unwrap_param<PeekParam>(param_in);
// stack index for children are in range [0, num_children>
size_t last_valid_stack_idx = param.num_children - 1;
const Value & input_value = state.peek(last_valid_stack_idx);
auto get_child_value = [&] (size_t child_idx) {
size_t stack_idx = last_valid_stack_idx - child_idx;
return int64_t(state.peek(stack_idx).as_double());
};
auto up = generic_mixed_peek<ICT,OCT>(param.res_type, input_value,
param.sparse_plan, param.dense_plan,
param.factory, get_child_value);
const Value &result = *state.stash.create<Value::UP>(std::move(up));
// num_children includes the "input" param
state.pop_n_push(param.num_children, result);
}
struct SelectGenericPeekOp {
template <typename ICT, typename OCT> static auto invoke() {
return my_generic_peek_op<ICT,OCT>;
}
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
Instruction
GenericPeek::make_instruction(const ValueType &input_type,
const ValueType &res_type,
const SpecMap &spec,
const ValueBuilderFactory &factory,
Stash &stash)
{
const auto ¶m = stash.create<PeekParam>(input_type, res_type, spec, factory);
auto fun = typify_invoke<2,TypifyCellType,SelectGenericPeekOp>(input_type.cell_type(), res_type.cell_type());
return Instruction(fun, wrap_param<PeekParam>(param));
}
} // namespace
<|endoftext|> |
<commit_before>/*
* SerialTopLvlProtocoll.cpp
*
* Created on: 18.05.2017
* Author: aca619
*/
#include <cstring>
#include "SerialProtocoll.h"
#include "ITopLvlProtocoll.h"
#include "../../Tests/Serial/SerialTestStub.h"
#include <string.h>
#include <Logger.h>
#include <Logscope.h>
#include "PuckSignal.h"
using namespace Serial_n;
/**
* This is an unidirectional Protocoll over Serial
* One must always be the Sender of Pucks
* One must always be the receiver Pucks
* @param mode Be receiver or sender?
*/
SerialProtocoll::SerialProtocoll(Serial_mode mode) {
// TODO mode is not implemented
}
SerialProtocoll::~SerialProtocoll() {
// TODO Auto-generated destructor stub
}
pulse SerialProtocoll::convToPulse(void *buff) {
pulse resu;
ser_proto_msg msg_in = *(ser_proto_msg*)buff;
resu.code = SER_IN;
switch(msg_in){
case ACCEPT_SER:
case STOP_SER:
case RESUME_SER:
case INVALID_SER:
case RECEIVED_SER:
case POL_SER:
resu.value = msg_in;
break;
case TRANSM_SER:
{
resu.code = TRANSM_IN;
ISerializable *obj = new PuckSignal::PuckType;
obj->deserialize(((char*)buff) + sizeof(ser_proto_msg)); //cast to char* because void* cant be used in arith
resu.value = (uint32_t) obj;
}
break;
default:
break; //TODO ERROR
}
return resu;
}
serialized SerialProtocoll::wrapInFrame(int8_t code, int32_t value) {
serialized resu;
switch(code){
case SER_IN: //Inout nothing needs to be done
case SER_OUT :
{
int32_t* msg_type = new int32_t;
*msg_type = value;
resu.size = sizeof(int32_t);
resu.obj = msg_type;
break;
}
case TRANSM_IN:
case TRANSM_OUT:
{
serialized tmp;
ISerializable* obj = (ISerializable*) value;
tmp = obj->serialize();
char* frame = new char[tmp.size+ sizeof(ser_proto_msg)]; //make space for msg type
memcpy((frame+sizeof(ser_proto_msg)), tmp.obj, tmp.size);
ser_proto_msg *msg_ptr = (ser_proto_msg *) frame;
*msg_ptr = TRANSM_SER;
resu.obj = frame;
resu.size = tmp.size + sizeof(ser_proto_msg);
break;
}
default: //TODO error handler
break;
}
return resu;
}
pulse SerialProtocoll::protocollState(int8_t int8, int32_t int32) {
pulse empty; //TODO Fill with logic
return empty;
}
<commit_msg>SerialProtocoll: Define missing serial messages<commit_after>/*
* SerialTopLvlProtocoll.cpp
*
* Created on: 18.05.2017
* Author: aca619
*/
#include <cstring>
#include "SerialProtocoll.h"
#include "ITopLvlProtocoll.h"
#include "../../Tests/Serial/SerialTestStub.h"
#include <string.h>
#include <Logger.h>
#include <Logscope.h>
#include "PuckSignal.h"
using namespace Serial_n;
/**
* This is an unidirectional Protocoll over Serial
* One must always be the Sender of Pucks
* One must always be the receiver Pucks
* @param mode Be receiver or sender?
*/
SerialProtocoll::SerialProtocoll(Serial_mode mode) {
// TODO mode is not implemented
}
SerialProtocoll::~SerialProtocoll() {
// TODO Auto-generated destructor stub
}
pulse SerialProtocoll::convToPulse(void *buff) {
pulse resu;
ser_proto_msg msg_in = *(ser_proto_msg*)buff;
resu.code = SER_IN;
switch(msg_in){
case ACCEPT_SER:
case STOP_SER:
case RESUME_SER:
case INVALID_SER:
case RECEIVED_SER:
case SLIDE_FULL_SER:
case POL_SER:
case ERROR_SER:
case ESTOP_SER:
resu.value = msg_in;
break;
case TRANSM_SER:
{
resu.code = TRANSM_IN;
ISerializable *obj = new PuckSignal::PuckType;
obj->deserialize(((char*)buff) + sizeof(ser_proto_msg)); //cast to char* because void* cant be used in arith
resu.value = (uint32_t) obj;
}
break;
default:
LOG_DEBUG << "[SerialProtocoll] Sending undefined messages: " << (int)msg_in << endl;
break; //TODO ERROR
}
return resu;
}
serialized SerialProtocoll::wrapInFrame(int8_t code, int32_t value) {
serialized resu;
switch(code){
case SER_IN: //Inout nothing needs to be done
case SER_OUT :
{
int32_t* msg_type = new int32_t;
*msg_type = value;
resu.size = sizeof(int32_t);
resu.obj = msg_type;
break;
}
case TRANSM_IN:
case TRANSM_OUT:
{
serialized tmp;
ISerializable* obj = (ISerializable*) value;
tmp = obj->serialize();
char* frame = new char[tmp.size+ sizeof(ser_proto_msg)]; //make space for msg type
memcpy((frame+sizeof(ser_proto_msg)), tmp.obj, tmp.size);
ser_proto_msg *msg_ptr = (ser_proto_msg *) frame;
*msg_ptr = TRANSM_SER;
resu.obj = frame;
resu.size = tmp.size + sizeof(ser_proto_msg);
break;
}
default: //TODO error handler
break;
}
return resu;
}
pulse SerialProtocoll::protocollState(int8_t int8, int32_t int32) {
pulse empty; //TODO Fill with logic
return empty;
}
<|endoftext|> |
<commit_before>/* -*-c++-*-
* Copyright (C) 2008 Cedric Pinson <mornifle@plopbyte.net>
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <iostream>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/Geode>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>
#include <osgUtil/SmoothingVisitor>
#include <osg/io_utils>
#include <osgAnimation/MorphGeometry>
#include <osgAnimation/BasicAnimationManager>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
struct GeometryFinder : public osg::NodeVisitor
{
osg::ref_ptr<osg::Geometry> _geom;
GeometryFinder() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
void apply(osg::Geode& geode)
{
if (_geom.valid())
return;
for (unsigned int i = 0; i < geode.getNumDrawables(); i++)
{
osg::Geometry* geom = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));
if (geom) {
_geom = geom;
return;
}
}
}
};
osg::Geometry* getShape(const std::string& name)
{
osg::Node* shape0 = osgDB::readNodeFile(name);
GeometryFinder finder;
shape0->accept(finder);
return finder._geom.get();
}
int main (int argc, char* argv[])
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
osgAnimation::Animation* animation = new osgAnimation::Animation;
osgAnimation::FloatLinearChannel* channel0 = new osgAnimation::FloatLinearChannel;
channel0->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(0,0.0));
channel0->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(1,1.0));
channel0->setTargetName("MorphNodeCallback");
channel0->setName("0");
osgAnimation::FloatLinearChannel* channel1 = new osgAnimation::FloatLinearChannel;
channel1->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(0,1.0));
channel1->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(1,0.0));
channel1->setTargetName("MorphNodeCallback");
channel1->setName("1");
animation->addChannel(channel0);
animation->addChannel(channel1);
animation->setName("Morph");
animation->computeDuration();
animation->setPlaymode(osgAnimation::Animation::PPONG);
osgAnimation::BasicAnimationManager* bam = new osgAnimation::BasicAnimationManager;
bam->registerAnimation(animation);
osg::Geometry* geom0 = getShape("morphtarget_shape0.osg");
if (!geom0) {
std::cerr << "can't read morphtarget_shape0.osg" << std::endl;
return 0;
}
osg::Geometry* geom1 = getShape("morphtarget_shape1.osg");
if (!geom1) {
std::cerr << "can't read morphtarget_shape1.osg" << std::endl;
return 0;
}
// initialize with the first shape
osgAnimation::MorphGeometry* morph = new osgAnimation::MorphGeometry(*geom0);
morph->addMorphTarget(geom0);
morph->addMorphTarget(geom1);
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
osg::Group* scene = new osg::Group;
scene->addUpdateCallback(bam);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(morph);
geode->addUpdateCallback(new osgAnimation::UpdateMorph("MorphNodeCallback"));
scene->addChild(geode);
viewer.addEventHandler(new osgViewer::StatsHandler());
viewer.addEventHandler(new osgViewer::WindowSizeHandler());
viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));
// let's run !
viewer.setSceneData( scene );
viewer.realize();
bam->playAnimation(animation);
while (!viewer.done())
{
viewer.frame();
}
osgDB::writeNodeFile(*scene, "morph_scene.osg");
return 0;
}
<commit_msg>From Roland Smeenk, "Here's a small simplification of the osganimationmorph example. Only one morphtarget needs to be added to the MorphGeometry since it already has a base geometry. The animation will morph between the base geometry and the first target.<commit_after>/* -*-c++-*-
* Copyright (C) 2008 Cedric Pinson <mornifle@plopbyte.net>
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <iostream>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/Geode>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>
#include <osgUtil/SmoothingVisitor>
#include <osg/io_utils>
#include <osgAnimation/MorphGeometry>
#include <osgAnimation/BasicAnimationManager>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
struct GeometryFinder : public osg::NodeVisitor
{
osg::ref_ptr<osg::Geometry> _geom;
GeometryFinder() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
void apply(osg::Geode& geode)
{
if (_geom.valid())
return;
for (unsigned int i = 0; i < geode.getNumDrawables(); i++)
{
osg::Geometry* geom = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));
if (geom) {
_geom = geom;
return;
}
}
}
};
osg::Geometry* getShape(const std::string& name)
{
osg::Node* shape0 = osgDB::readNodeFile(name);
GeometryFinder finder;
shape0->accept(finder);
return finder._geom.get();
}
int main (int argc, char* argv[])
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
osgAnimation::Animation* animation = new osgAnimation::Animation;
osgAnimation::FloatLinearChannel* channel0 = new osgAnimation::FloatLinearChannel;
channel0->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(0,0.0));
channel0->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::FloatKeyframe(1,1.0));
channel0->setTargetName("MorphNodeCallback");
channel0->setName("0");
animation->addChannel(channel0);
animation->setName("Morph");
animation->computeDuration();
animation->setPlaymode(osgAnimation::Animation::PPONG);
osgAnimation::BasicAnimationManager* bam = new osgAnimation::BasicAnimationManager;
bam->registerAnimation(animation);
osg::Geometry* geom0 = getShape("morphtarget_shape0.osg");
if (!geom0) {
std::cerr << "can't read morphtarget_shape0.osg" << std::endl;
return 0;
}
osg::Geometry* geom1 = getShape("morphtarget_shape1.osg");
if (!geom1) {
std::cerr << "can't read morphtarget_shape1.osg" << std::endl;
return 0;
}
// initialize with the first shape
osgAnimation::MorphGeometry* morph = new osgAnimation::MorphGeometry(*geom0);
morph->addMorphTarget(geom1);
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
osg::Group* scene = new osg::Group;
scene->addUpdateCallback(bam);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(morph);
geode->addUpdateCallback(new osgAnimation::UpdateMorph("MorphNodeCallback"));
scene->addChild(geode);
viewer.addEventHandler(new osgViewer::StatsHandler());
viewer.addEventHandler(new osgViewer::WindowSizeHandler());
viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));
// let's run !
viewer.setSceneData( scene );
viewer.realize();
bam->playAnimation(animation);
while (!viewer.done())
{
viewer.frame();
}
osgDB::writeNodeFile(*scene, "morph_scene.osg");
return 0;
}
<|endoftext|> |
<commit_before>/**
Released as open source by Gabriel Caudrelier
Developed by Gabriel Caudrelier, gabriel dot caudrelier at gmail dot com
https://github.com/metrodango/pip3line
Released under AGPL see LICENSE for more information
**/
#include "packetmodelabstract.h"
#include "packet.h"
#include <QDebug>
#include <QChar>
#include <QIcon>
#include <transformmgmt.h>
#include <threadedprocessor.h>
#include "shared/guiconst.h"
const qint64 PacketModelAbstract::INVALID_POS = -1;
const QString PacketModelAbstract::COLUMN_DIRECTION_STR = "D";
const QString PacketModelAbstract::COLUMN_TIMESPTAMP_STR = "Timestamp";
const QString PacketModelAbstract::COLUMN_PAYLOAD_STR = "Payload";
const QString PacketModelAbstract::COLUMN_COMMENT_STR = "Comment";
const QString PacketModelAbstract::COLUMN_CID_STR = "CID";
const QString PacketModelAbstract::COLUMN_LENGTH_STR = "Length";
const QString PacketModelAbstract::DEFAULT_DATETIME_FORMAT = "dd/MM/yyyy hh:mm:ss.zzz";
const int PacketModelAbstract::DEFAULT_MAX_PAYLOAD_DISPLAY_SIZE = 20;
const int PacketModelAbstract::MAX_PAYLOAD_DISPLAY_SIZE_MIN_VAL = 10;
const int PacketModelAbstract::MAX_PAYLOAD_DISPLAY_SIZE_MAX_VAL = 100;
const QString PacketModelAbstract::TRUNCATED_STR = QByteArray("[...]");
PacketModelAbstract::PacketModelAbstract(TransformMgmt *transformFactory, QObject *parent) :
QAbstractTableModel(parent),
transformFactory(transformFactory)
{
autoMergeConsecutivePackets = false;
columnNames << COLUMN_DIRECTION_STR
<< COLUMN_TIMESPTAMP_STR
<< COLUMN_PAYLOAD_STR
<< COLUMN_COMMENT_STR
<< COLUMN_CID_STR
<< COLUMN_LENGTH_STR;
lastPredefinedColumn = columnNames.size() - 1 ;
dateTimeFormat = DEFAULT_DATETIME_FORMAT;
maxPayloadDisplaySize = DEFAULT_MAX_PAYLOAD_DISPLAY_SIZE;
Usercolumn uc;
uc.format = Pip3lineConst::HEXAFORMAT;
userColumnsDef.insert(COLUMN_PAYLOAD_STR, uc);
connect(this, &PacketModelAbstract::rowsInserted,this, &PacketModelAbstract::onRowsInserted);
}
PacketModelAbstract::~PacketModelAbstract()
{
clearUserColumns();
}
void PacketModelAbstract::resetColumnNames()
{
if (columnNames.size() > lastPredefinedColumn + 1) { // difference between index and size
columnNames.clear();
columnNames << COLUMN_DIRECTION_STR
<< COLUMN_TIMESPTAMP_STR
<< COLUMN_PAYLOAD_STR
<< COLUMN_COMMENT_STR
<< COLUMN_CID_STR
<< COLUMN_LENGTH_STR;
}
}
int PacketModelAbstract::getMaxPayloadDisplaySize() const
{
return maxPayloadDisplaySize;
}
int PacketModelAbstract::getDefaultWidthForColumn(const int &col)
{
switch(col) {
case (PacketModelAbstract::COLUMN_DIRECTION):
return DIRECTION_COLUMN_WIDTH;
case (PacketModelAbstract::COLUMN_TIMESPTAMP):
return GuiConst::calculateStringWidthWithGlobalFont(dateTimeFormat);
case (PacketModelAbstract::COLUMN_CID):
return GuiConst::calculateStringWidthWithGlobalFont(COLUMN_CID_STR);
case (PacketModelAbstract::COLUMN_LENGTH):
return GuiConst::calculateStringWidthWithGlobalFont(COLUMN_LENGTH_STR);
default:
return RAWDATA_COLUMN_WIDTH;
}
}
void PacketModelAbstract::setMaxPayloadDisplaySize(int value)
{
maxPayloadDisplaySize = value;
emit dataChanged(createIndex(0, COLUMN_PAYLOAD), createIndex(size() - 1, COLUMN_PAYLOAD));
}
bool PacketModelAbstract::isAutoMergeConsecutivePackets() const
{
return autoMergeConsecutivePackets;
}
void PacketModelAbstract::setAutoMergeConsecutivePackets(bool value)
{
autoMergeConsecutivePackets = value;
}
QStringList PacketModelAbstract::getColumnNames() const
{
return columnNames;
}
void PacketModelAbstract::setColumnNames(const QStringList &value)
{
columnNames = value;
}
int PacketModelAbstract::columnCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return columnNames.size();
}
QVariant PacketModelAbstract::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
return section < columnNames.size() ? QVariant(columnNames.at(section)) : QVariant();
} else {
return QVariant(section + 1);
}
}
QVariant PacketModelAbstract::payloadData(const QSharedPointer<Packet> packet, int column, int role) const
{
if (packet == nullptr)
return QVariant();
// Only deal with DisplayRole, DecorationRole, BackgroundRole and ForegroundRole
if (role == Qt::DisplayRole) {
if ( column == COLUMN_TIMESPTAMP) {
QString final = packet->getTimestamp().toString(dateTimeFormat);
if (dateTimeFormat == DEFAULT_DATETIME_FORMAT && packet->getMicrosec() != 0) {
final = QString("%1%2").arg(final).arg(packet->getMicrosec(),3,10,QChar('0'));
}
return QVariant(final);
}
else if (column == COLUMN_PAYLOAD) {
OutputFormat of = userColumnsDef.value(COLUMN_PAYLOAD_STR,Usercolumn()).format;
QByteArray extract = packet->getData();
bool wastruncated = false;
if (extract.size() > maxPayloadDisplaySize) {
extract = extract.left(maxPayloadDisplaySize);
wastruncated = true;
}
QString finals = (of == Pip3lineConst::TEXTFORMAT ? QString::fromUtf8(extract): QString::fromUtf8(extract.toHex()));
if (wastruncated)
finals.append(TRUNCATED_STR);
return QVariant(finals);
}
else if (column == COLUMN_COMMENT)
return QVariant(packet->getComment());
else if (column == COLUMN_CID)
return QVariant(packet->getSourceid());
else if (column == COLUMN_LENGTH)
return QVariant(GuiConst::convertSizetoBytesString(packet->getData().length()));
else if (column > lastPredefinedColumn && column < columnNames.size()) {
QHash<QString, QString> fields = packet->getAdditionalFields();
if (fields.contains(columnNames.at(column))) {
return QVariant(fields.value(columnNames.at(column)));
}
}
} else if (role == Qt::DecorationRole) {
if (column == COLUMN_DIRECTION) {
switch (packet->getDirection()) {
case Packet::LEFTRIGHT:
if (packet->isInjected())
return QVariant(QIcon(":/Images/icons/arrow-right-3-1.png"));
else
return QVariant(QIcon(":/Images/icons/arrow-right-3-mod.png"));
case Packet::RIGHTLEFT:
if (packet->isInjected())
return QVariant(QIcon(":/Images/icons/arrow-left-3-1.png"));
else
return QVariant(QIcon(":/Images/icons/arrow-left-3.png"));
case Packet::NODIRECTION:
return QVariant();
}
}
} else if (role == Qt::BackgroundRole) {
QColor color = packet->getBackground();
return color.isValid() ? QVariant(color) : QVariant();
} else if (role == Qt::ForegroundRole) {
QColor color = packet->getForeground();
return color.isValid() ? QVariant(color) : QVariant();
} else if (role == Qt::ToolTipRole) {
return packet->getSourceString();
} else if (role == Qt::FontRole) {
return GlobalsValues::GLOBAL_REGULAR_FONT;
} else if (role == Qt::TextAlignmentRole && column == COLUMN_LENGTH) {
return Qt::AlignRight;
}
return QVariant();
}
QSharedPointer<Packet> PacketModelAbstract::getPacket(const QModelIndex &index)
{
if (index.isValid()) {
return getPacket((qint64)index.row());
}
return nullptr;
}
qint64 PacketModelAbstract::indexToPacketIndex(const QModelIndex &index)
{
if (index.isValid()) {
// by default nothing to do
return (qint64)index.row();
}
return INVALID_POS;
}
QModelIndex PacketModelAbstract::createIndex(int row, int column) const
{
return QAbstractTableModel::createIndex(row, column);
}
void PacketModelAbstract::addUserColumn(const QString &name, TransformAbstract *transform, OutputFormat outFormat)
{
if (userColumnsDef.contains(name)) {
emit log(tr("A column with this name \"%1\" already exists, ignoring").arg(name), "PacketModel", Pip3lineConst::LERROR);
delete transform;
return;
}
Usercolumn col;
col.transform = transform;
col.format = outFormat;
userColumnsDef.insert(name,col);
int newIndex = columnNames.size();
beginInsertColumns(QModelIndex(),newIndex,newIndex);
columnNames << name;
endInsertColumns();
if (transform != nullptr) {
connect(transform, &TransformAbstract::confUpdated, this, &PacketModelAbstract::transformUpdated);
internalAddUserColumn(name,transform);
}
emit columnsUpdated();
}
void PacketModelAbstract::removeUserColumn(const QString &name)
{
removeUserColumn(columnNames.indexOf(name));
}
void PacketModelAbstract::removeUserColumn(const int &index)
{
if (index > lastPredefinedColumn && index < columnNames.size()) {
beginRemoveColumns(QModelIndex(), index, index);
QString name = columnNames.at(index);
if (userColumnsDef.contains(name)) {
Usercolumn col = userColumnsDef.take(name);
delete col.transform;
} else {
qWarning() << tr("[PacketModelAbstract::removeUserColumn] Column name not found in the definitions %1 T_T").arg(name);
}
columnNames.removeAt(index);
endRemoveColumns();
clearAdditionalField(name);
emit columnsUpdated();
} else {
qCritical() << tr("[PacketModelAbstract::removeUserColumn] No column at index %1 T_T").arg(index);
}
}
void PacketModelAbstract::clearUserColumns()
{
foreach (Usercolumn col, userColumnsDef)
delete col.transform;
userColumnsDef.clear();
resetColumnNames();
emit columnsUpdated();
}
bool PacketModelAbstract::isUserColumn(const QString &name) const
{
return isUserColumn(columnNames.indexOf(name));
}
bool PacketModelAbstract::isUserColumn(int column) const
{
return column > lastPredefinedColumn && column < columnNames.size();
}
bool PacketModelAbstract::isDefaultColumn(const QString &name) const
{
return isDefaultColumn(columnNames.indexOf(name));
}
bool PacketModelAbstract::isDefaultColumn(int column) const
{
return column >= 0 && column <= lastPredefinedColumn;
}
int PacketModelAbstract::getColumnIndex(const QString &name)
{
int index = columnNames.indexOf(name);
if (index == -1) {
qCritical() << tr("[PacketModelAbstract::getColumnIndex] No column named %1 T_T").arg(name);
return COLUMN_INVALID;
}
return index;
}
void PacketModelAbstract::refreshAllColumn()
{
for (int i = lastPredefinedColumn + 1 ; i < columnNames.size(); i++) {
if (userColumnsDef.contains(columnNames.at(i))) {
TransformAbstract * transform = userColumnsDef.value(columnNames.at(i)).transform;
launchUpdate(transform,0,i);
}
}
}
void PacketModelAbstract::onRowsInserted(const QModelIndex &parent, int start, int end)
{
if (parent.isValid()) // not supposed to hapen for a table
return;
for (int i = lastPredefinedColumn + 1 ; i < columnNames.size(); i++) {
if (userColumnsDef.contains(columnNames.at(i))) {
TransformAbstract * transform = userColumnsDef.value(columnNames.at(i)).transform;
launchUpdate(transform, start,i, end - start + 1);
}
}
}
QWidget *PacketModelAbstract::getGuiForUserColumn(const QString &name, QWidget * parent)
{
if (userColumnsDef.contains(name)) {
TransformAbstract * ta = userColumnsDef.value(name).transform;
return ( ta != nullptr ? ta->getGui(parent) : nullptr);
} else {
qCritical() << tr("[PacketModelAbstract::getGuiForUserColumn] Cannot find the column name (%1) T_T").arg(name);
}
return nullptr;
}
QWidget *PacketModelAbstract::getGuiForUserColumn(int index, QWidget *parent)
{
if (index > lastPredefinedColumn && index < columnNames.size()) {
return getGuiForUserColumn(columnNames.at(index),parent);
} else {
qCritical() << tr("[PacketModelAbstract::getGuiForUserColumn] Cannot find the column at (%1) T_T").arg(index);
}
return nullptr;
}
TransformAbstract *PacketModelAbstract::getTransform(const QString &columnName)
{
if (userColumnsDef.contains(columnName)) {
return userColumnsDef.value(columnName).transform;
} else {
qCritical() << tr("[PacketModelAbstract::getTransform] Cannot find the column name (%1) T_T").arg(columnName);
}
return nullptr;
}
TransformAbstract *PacketModelAbstract::getTransform(int index)
{
if (index > lastPredefinedColumn && index < columnNames.size()) {
return getTransform(columnNames.at(index));
} else {
qCritical() << tr("[PacketModelAbstract::getTransform] Cannot find the column at (%1) T_T").arg(index);
}
return nullptr;
}
void PacketModelAbstract::setColumnFormat(int index, OutputFormat format)
{
if ((index > lastPredefinedColumn && index < columnNames.size()) || index == COLUMN_PAYLOAD) {
setColumnFormat(columnNames.at(index), format);
} else {
qCritical() << tr("[PacketModelAbstract::setColumnFormat] Cannot find the column at (%1) T_T").arg(index);
}
}
void PacketModelAbstract::setColumnFormat(const QString &columnName, OutputFormat format)
{
if (columnName == COLUMN_PAYLOAD_STR) {
Usercolumn uc = userColumnsDef.value(columnName);
uc.format = format;
userColumnsDef.insert(columnName, uc);
emit dataChanged(createIndex(0,COLUMN_PAYLOAD), createIndex(size() - 1, COLUMN_PAYLOAD));
} else if (userColumnsDef.contains(columnName)) {
Usercolumn uc = userColumnsDef.value(columnName);
uc.format = format;
userColumnsDef.insert(columnName, uc);
refreshColumn(columnName);
} else {
qCritical() << tr("[PacketModelAbstract::setColumnFormat] Cannot find the column name (%1) T_T").arg(columnName);
}
}
OutputFormat PacketModelAbstract::getColumnFormat(int index)
{
if ((index > lastPredefinedColumn && index < columnNames.size()) || index == COLUMN_PAYLOAD) {
return getColumnFormat(columnNames.at(index));
} else {
qCritical() << tr("[PacketModelAbstract::getColumnFormat] Cannot find the column at (%1) T_T").arg(index);
}
return Pip3lineConst::TEXTFORMAT;
}
OutputFormat PacketModelAbstract::getColumnFormat(const QString &columnName)
{
if (userColumnsDef.contains(columnName)) {
return userColumnsDef.value(columnName).format;
} else {
qCritical() << tr("[PacketModelAbstract::getColumnFormat] Cannot find the column name (%1) T_T").arg(columnName);
}
return Pip3lineConst::TEXTFORMAT;
}
QString PacketModelAbstract::getColumnName(int index)
{
if (index >= 0 && index < columnNames.size()) {
return columnNames.at(index);
} else {
qCritical() << tr("[PacketModelAbstract::getColumnName] Cannot find the column at (%1) T_T").arg(index);
}
return GuiConst::UNDEFINED_TEXT;
}
<commit_msg>Travis Build #3<commit_after>/**
Released as open source by Gabriel Caudrelier
Developed by Gabriel Caudrelier, gabriel dot caudrelier at gmail dot com
https://github.com/metrodango/pip3line
Released under AGPL see LICENSE for more information
**/
#include "packetmodelabstract.h"
#include "packet.h"
#include <QDebug>
#include <QChar>
#include <QIcon>
#include <transformmgmt.h>
#include <threadedprocessor.h>
#include "shared/guiconst.h"
const qint64 PacketModelAbstract::INVALID_POS = -1;
const QString PacketModelAbstract::COLUMN_DIRECTION_STR = "D";
const QString PacketModelAbstract::COLUMN_TIMESPTAMP_STR = "Timestamp";
const QString PacketModelAbstract::COLUMN_PAYLOAD_STR = "Payload";
const QString PacketModelAbstract::COLUMN_COMMENT_STR = "Comment";
const QString PacketModelAbstract::COLUMN_CID_STR = "CID";
const QString PacketModelAbstract::COLUMN_LENGTH_STR = "Length";
const QString PacketModelAbstract::DEFAULT_DATETIME_FORMAT = "dd/MM/yyyy hh:mm:ss.zzz";
const int PacketModelAbstract::DEFAULT_MAX_PAYLOAD_DISPLAY_SIZE = 20;
const int PacketModelAbstract::MAX_PAYLOAD_DISPLAY_SIZE_MIN_VAL = 10;
const int PacketModelAbstract::MAX_PAYLOAD_DISPLAY_SIZE_MAX_VAL = 100;
const QString PacketModelAbstract::TRUNCATED_STR = QByteArray("[...]");
PacketModelAbstract::PacketModelAbstract(TransformMgmt *transformFactory, QObject *parent) :
QAbstractTableModel(parent),
transformFactory(transformFactory)
{
autoMergeConsecutivePackets = false;
columnNames << COLUMN_DIRECTION_STR
<< COLUMN_TIMESPTAMP_STR
<< COLUMN_PAYLOAD_STR
<< COLUMN_COMMENT_STR
<< COLUMN_CID_STR
<< COLUMN_LENGTH_STR;
lastPredefinedColumn = columnNames.size() - 1 ;
dateTimeFormat = DEFAULT_DATETIME_FORMAT;
maxPayloadDisplaySize = DEFAULT_MAX_PAYLOAD_DISPLAY_SIZE;
Usercolumn uc;
uc.format = Pip3lineConst::HEXAFORMAT;
userColumnsDef.insert(COLUMN_PAYLOAD_STR, uc);
connect(this, &PacketModelAbstract::rowsInserted,this, &PacketModelAbstract::onRowsInserted);
}
PacketModelAbstract::~PacketModelAbstract()
{
clearUserColumns();
}
void PacketModelAbstract::resetColumnNames()
{
if (columnNames.size() > lastPredefinedColumn + 1) { // difference between index and size
columnNames.clear();
columnNames << COLUMN_DIRECTION_STR
<< COLUMN_TIMESPTAMP_STR
<< COLUMN_PAYLOAD_STR
<< COLUMN_COMMENT_STR
<< COLUMN_CID_STR
<< COLUMN_LENGTH_STR;
}
}
int PacketModelAbstract::getMaxPayloadDisplaySize() const
{
return maxPayloadDisplaySize;
}
int PacketModelAbstract::getDefaultWidthForColumn(const int &col)
{
switch(col) {
case (PacketModelAbstract::COLUMN_DIRECTION):
return DIRECTION_COLUMN_WIDTH;
case (PacketModelAbstract::COLUMN_TIMESPTAMP):
return GuiConst::calculateStringWidthWithGlobalFont(dateTimeFormat);
case (PacketModelAbstract::COLUMN_CID):
return GuiConst::calculateStringWidthWithGlobalFont(COLUMN_CID_STR);
case (PacketModelAbstract::COLUMN_LENGTH):
return GuiConst::calculateStringWidthWithGlobalFont(COLUMN_LENGTH_STR);
default:
return RAWDATA_COLUMN_WIDTH;
}
}
void PacketModelAbstract::setMaxPayloadDisplaySize(int value)
{
maxPayloadDisplaySize = value;
emit dataChanged(createIndex(0, COLUMN_PAYLOAD), createIndex(size() - 1, COLUMN_PAYLOAD));
}
bool PacketModelAbstract::isAutoMergeConsecutivePackets() const
{
return autoMergeConsecutivePackets;
}
void PacketModelAbstract::setAutoMergeConsecutivePackets(bool value)
{
autoMergeConsecutivePackets = value;
}
QStringList PacketModelAbstract::getColumnNames() const
{
return columnNames;
}
void PacketModelAbstract::setColumnNames(const QStringList &value)
{
columnNames = value;
}
int PacketModelAbstract::columnCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return columnNames.size();
}
QVariant PacketModelAbstract::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
return section < columnNames.size() ? QVariant(columnNames.at(section)) : QVariant();
} else {
return QVariant(section + 1);
}
}
QVariant PacketModelAbstract::payloadData(const QSharedPointer<Packet> packet, int column, int role) const
{
if (packet == nullptr)
return QVariant();
// Only deal with DisplayRole, DecorationRole, BackgroundRole and ForegroundRole
if (role == Qt::DisplayRole) {
if ( column == COLUMN_TIMESPTAMP) {
QString final = packet->getTimestamp().toString(dateTimeFormat);
if (dateTimeFormat == DEFAULT_DATETIME_FORMAT && packet->getMicrosec() != 0) {
final = QString("%1%2").arg(final).arg(packet->getMicrosec(),3,10,QChar('0'));
}
return QVariant(final);
}
else if (column == COLUMN_PAYLOAD) {
OutputFormat of = userColumnsDef.value(COLUMN_PAYLOAD_STR,Usercolumn()).format;
QByteArray extract = packet->getData();
bool wastruncated = false;
if (extract.size() > maxPayloadDisplaySize) {
extract = extract.left(maxPayloadDisplaySize);
wastruncated = true;
}
QString finals = (of == Pip3lineConst::TEXTFORMAT ? QString::fromUtf8(extract): QString::fromUtf8(extract.toHex()));
if (wastruncated)
finals.append(TRUNCATED_STR);
return QVariant(finals);
}
else if (column == COLUMN_COMMENT)
return QVariant(packet->getComment());
else if (column == COLUMN_CID)
return QVariant(packet->getSourceid());
else if (column == COLUMN_LENGTH)
return QVariant(GuiConst::convertSizetoBytesString(packet->getData().length()));
else if (column > lastPredefinedColumn && column < columnNames.size()) {
QHash<QString, QString> fields = packet->getAdditionalFields();
if (fields.contains(columnNames.at(column))) {
return QVariant(fields.value(columnNames.at(column)));
}
}
} else if (role == Qt::DecorationRole) {
if (column == COLUMN_DIRECTION) {
switch (packet->getDirection()) {
case Packet::LEFTRIGHT:
if (packet->isInjected())
return QVariant(QIcon(":/Images/icons/arrow-right-3-1.png"));
else
return QVariant(QIcon(":/Images/icons/arrow-right-3-mod.png"));
case Packet::RIGHTLEFT:
if (packet->isInjected())
return QVariant(QIcon(":/Images/icons/arrow-left-3-1.png"));
else
return QVariant(QIcon(":/Images/icons/arrow-left-3.png"));
case Packet::NODIRECTION:
return QVariant();
}
}
} else if (role == Qt::BackgroundRole) {
QColor color = packet->getBackground();
return color.isValid() ? QVariant(color) : QVariant();
} else if (role == Qt::ForegroundRole) {
QColor color = packet->getForeground();
return color.isValid() ? QVariant(color) : QVariant();
} else if (role == Qt::ToolTipRole) {
return packet->getSourceString();
} else if (role == Qt::FontRole) {
return GlobalsValues::GLOBAL_REGULAR_FONT;
} else if (role == Qt::TextAlignmentRole && column == COLUMN_LENGTH) {
return Qt::AlignRight;
}
return QVariant();
}
QSharedPointer<Packet> PacketModelAbstract::getPacket(const QModelIndex &index)
{
if (index.isValid()) {
return getPacket((qint64)index.row());
}
return QSharedPointer<Packet>();
}
qint64 PacketModelAbstract::indexToPacketIndex(const QModelIndex &index)
{
if (index.isValid()) {
// by default nothing to do
return (qint64)index.row();
}
return INVALID_POS;
}
QModelIndex PacketModelAbstract::createIndex(int row, int column) const
{
return QAbstractTableModel::createIndex(row, column);
}
void PacketModelAbstract::addUserColumn(const QString &name, TransformAbstract *transform, OutputFormat outFormat)
{
if (userColumnsDef.contains(name)) {
emit log(tr("A column with this name \"%1\" already exists, ignoring").arg(name), "PacketModel", Pip3lineConst::LERROR);
delete transform;
return;
}
Usercolumn col;
col.transform = transform;
col.format = outFormat;
userColumnsDef.insert(name,col);
int newIndex = columnNames.size();
beginInsertColumns(QModelIndex(),newIndex,newIndex);
columnNames << name;
endInsertColumns();
if (transform != nullptr) {
connect(transform, &TransformAbstract::confUpdated, this, &PacketModelAbstract::transformUpdated);
internalAddUserColumn(name,transform);
}
emit columnsUpdated();
}
void PacketModelAbstract::removeUserColumn(const QString &name)
{
removeUserColumn(columnNames.indexOf(name));
}
void PacketModelAbstract::removeUserColumn(const int &index)
{
if (index > lastPredefinedColumn && index < columnNames.size()) {
beginRemoveColumns(QModelIndex(), index, index);
QString name = columnNames.at(index);
if (userColumnsDef.contains(name)) {
Usercolumn col = userColumnsDef.take(name);
delete col.transform;
} else {
qWarning() << tr("[PacketModelAbstract::removeUserColumn] Column name not found in the definitions %1 T_T").arg(name);
}
columnNames.removeAt(index);
endRemoveColumns();
clearAdditionalField(name);
emit columnsUpdated();
} else {
qCritical() << tr("[PacketModelAbstract::removeUserColumn] No column at index %1 T_T").arg(index);
}
}
void PacketModelAbstract::clearUserColumns()
{
foreach (Usercolumn col, userColumnsDef)
delete col.transform;
userColumnsDef.clear();
resetColumnNames();
emit columnsUpdated();
}
bool PacketModelAbstract::isUserColumn(const QString &name) const
{
return isUserColumn(columnNames.indexOf(name));
}
bool PacketModelAbstract::isUserColumn(int column) const
{
return column > lastPredefinedColumn && column < columnNames.size();
}
bool PacketModelAbstract::isDefaultColumn(const QString &name) const
{
return isDefaultColumn(columnNames.indexOf(name));
}
bool PacketModelAbstract::isDefaultColumn(int column) const
{
return column >= 0 && column <= lastPredefinedColumn;
}
int PacketModelAbstract::getColumnIndex(const QString &name)
{
int index = columnNames.indexOf(name);
if (index == -1) {
qCritical() << tr("[PacketModelAbstract::getColumnIndex] No column named %1 T_T").arg(name);
return COLUMN_INVALID;
}
return index;
}
void PacketModelAbstract::refreshAllColumn()
{
for (int i = lastPredefinedColumn + 1 ; i < columnNames.size(); i++) {
if (userColumnsDef.contains(columnNames.at(i))) {
TransformAbstract * transform = userColumnsDef.value(columnNames.at(i)).transform;
launchUpdate(transform,0,i);
}
}
}
void PacketModelAbstract::onRowsInserted(const QModelIndex &parent, int start, int end)
{
if (parent.isValid()) // not supposed to hapen for a table
return;
for (int i = lastPredefinedColumn + 1 ; i < columnNames.size(); i++) {
if (userColumnsDef.contains(columnNames.at(i))) {
TransformAbstract * transform = userColumnsDef.value(columnNames.at(i)).transform;
launchUpdate(transform, start,i, end - start + 1);
}
}
}
QWidget *PacketModelAbstract::getGuiForUserColumn(const QString &name, QWidget * parent)
{
if (userColumnsDef.contains(name)) {
TransformAbstract * ta = userColumnsDef.value(name).transform;
return ( ta != nullptr ? ta->getGui(parent) : nullptr);
} else {
qCritical() << tr("[PacketModelAbstract::getGuiForUserColumn] Cannot find the column name (%1) T_T").arg(name);
}
return nullptr;
}
QWidget *PacketModelAbstract::getGuiForUserColumn(int index, QWidget *parent)
{
if (index > lastPredefinedColumn && index < columnNames.size()) {
return getGuiForUserColumn(columnNames.at(index),parent);
} else {
qCritical() << tr("[PacketModelAbstract::getGuiForUserColumn] Cannot find the column at (%1) T_T").arg(index);
}
return nullptr;
}
TransformAbstract *PacketModelAbstract::getTransform(const QString &columnName)
{
if (userColumnsDef.contains(columnName)) {
return userColumnsDef.value(columnName).transform;
} else {
qCritical() << tr("[PacketModelAbstract::getTransform] Cannot find the column name (%1) T_T").arg(columnName);
}
return nullptr;
}
TransformAbstract *PacketModelAbstract::getTransform(int index)
{
if (index > lastPredefinedColumn && index < columnNames.size()) {
return getTransform(columnNames.at(index));
} else {
qCritical() << tr("[PacketModelAbstract::getTransform] Cannot find the column at (%1) T_T").arg(index);
}
return nullptr;
}
void PacketModelAbstract::setColumnFormat(int index, OutputFormat format)
{
if ((index > lastPredefinedColumn && index < columnNames.size()) || index == COLUMN_PAYLOAD) {
setColumnFormat(columnNames.at(index), format);
} else {
qCritical() << tr("[PacketModelAbstract::setColumnFormat] Cannot find the column at (%1) T_T").arg(index);
}
}
void PacketModelAbstract::setColumnFormat(const QString &columnName, OutputFormat format)
{
if (columnName == COLUMN_PAYLOAD_STR) {
Usercolumn uc = userColumnsDef.value(columnName);
uc.format = format;
userColumnsDef.insert(columnName, uc);
emit dataChanged(createIndex(0,COLUMN_PAYLOAD), createIndex(size() - 1, COLUMN_PAYLOAD));
} else if (userColumnsDef.contains(columnName)) {
Usercolumn uc = userColumnsDef.value(columnName);
uc.format = format;
userColumnsDef.insert(columnName, uc);
refreshColumn(columnName);
} else {
qCritical() << tr("[PacketModelAbstract::setColumnFormat] Cannot find the column name (%1) T_T").arg(columnName);
}
}
OutputFormat PacketModelAbstract::getColumnFormat(int index)
{
if ((index > lastPredefinedColumn && index < columnNames.size()) || index == COLUMN_PAYLOAD) {
return getColumnFormat(columnNames.at(index));
} else {
qCritical() << tr("[PacketModelAbstract::getColumnFormat] Cannot find the column at (%1) T_T").arg(index);
}
return Pip3lineConst::TEXTFORMAT;
}
OutputFormat PacketModelAbstract::getColumnFormat(const QString &columnName)
{
if (userColumnsDef.contains(columnName)) {
return userColumnsDef.value(columnName).format;
} else {
qCritical() << tr("[PacketModelAbstract::getColumnFormat] Cannot find the column name (%1) T_T").arg(columnName);
}
return Pip3lineConst::TEXTFORMAT;
}
QString PacketModelAbstract::getColumnName(int index)
{
if (index >= 0 && index < columnNames.size()) {
return columnNames.at(index);
} else {
qCritical() << tr("[PacketModelAbstract::getColumnName] Cannot find the column at (%1) T_T").arg(index);
}
return GuiConst::UNDEFINED_TEXT;
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright( C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
/*
definition of the current version of OpenCV
Usefull to test in user programs
*/
#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__
#define CV_VERSION_EPOCH 2
#define CV_VERSION_MAJOR 4
#define CV_VERSION_MINOR 10
#define CV_VERSION_REVISION 0
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
#define CVAUX_STRW_EXP(__A) L#__A
#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)
#if CV_VERSION_REVISION
# define CV_VERSION CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION)
#else
# define CV_VERSION CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR)
#endif
/* old style version constants*/
#define CV_MAJOR_VERSION CV_VERSION_EPOCH
#define CV_MINOR_VERSION CV_VERSION_MAJOR
#define CV_SUBMINOR_VERSION CV_VERSION_MINOR
#endif
<commit_msg>Version++.<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright( C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
/*
definition of the current version of OpenCV
Usefull to test in user programs
*/
#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__
#define CV_VERSION_EPOCH 2
#define CV_VERSION_MAJOR 4
#define CV_VERSION_MINOR 10
#define CV_VERSION_REVISION 1
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
#define CVAUX_STRW_EXP(__A) L#__A
#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)
#if CV_VERSION_REVISION
# define CV_VERSION CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION)
#else
# define CV_VERSION CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR)
#endif
/* old style version constants*/
#define CV_MAJOR_VERSION CV_VERSION_EPOCH
#define CV_MINOR_VERSION CV_VERSION_MAJOR
#define CV_SUBMINOR_VERSION CV_VERSION_MINOR
#endif
<|endoftext|> |
<commit_before>/*
==============================================================================
OscProcessor.cpp
Created: 22 Jan 2015 10:56:59pm
Author: Daniel Lindenfelser
==============================================================================
*/
#include "OscProcessor.h"
OscProcessor::OscProcessor()
: oscServer(this)
{
}
OscProcessor::~OscProcessor()
{
managedOscParameters.clear();
}
void OscProcessor::handleOscMessage(osc::ReceivedPacket packet)
{
parseOscPacket(packet);
}
void OscProcessor::changeListenerCallback(ChangeBroadcaster* source)
{
OscParameter* parameter = static_cast<OscParameter*>(source);
if (parameter) {
char buffer[1024];
osc::OutboundPacketStream packet(buffer, 1024);
parameter->appendOscMessageToStream(packet);
oscServer.sendMessage(packet);
}
}
void OscProcessor::addOscParameter(OscParameter* parameter, bool internal)
{
if (parameter) {
managedOscParameters.addIfNotAlreadyThere(parameter);
if (!internal) {
parameter->addChangeListener(this);
}
}
}
void OscProcessor::removeOscParameter(OscParameter* p)
{
managedOscParameters.removeObject(p);
}
void OscProcessor::removeOscParameter(String regex)
{
Array<OscParameter*> toRemove;
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->addressMatch(regex)) {
toRemove.add(managedOscParameters[index]);
}
}
for (int index = 0; index < toRemove.size(); index++) {
managedOscParameters.removeObject(toRemove[index]);
}
}
Array<OscParameter*> OscProcessor::getAllOscParameter(String regex)
{
Array<OscParameter*> parameters;
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->addressMatch(regex)) {
parameters.add(managedOscParameters[index]);
}
}
return parameters;
}
OscParameter* OscProcessor::getOscParameter(String address)
{
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->getAddress() == address) {
return managedOscParameters[index];
}
}
return nullptr;
}
Array<OscParameter*> OscProcessor::getAllOscParameter()
{
Array<OscParameter*> parameters;
for (int index = 0; index < managedOscParameters.size(); index++) {
parameters.add(managedOscParameters[index]);
}
return parameters;
}
void OscProcessor::dumpOscParameters()
{
for (int index = 0; index < managedOscParameters.size(); index++) {
char buffer[1024];
osc::OutboundPacketStream packet(buffer, 1024);
managedOscParameters[index]->appendOscMessageToStream(packet);
oscServer.sendMessage(packet);
}
}
var OscProcessor::getOscParameterValue(String address)
{
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->getAddress() == address) {
return var(managedOscParameters[index]->getValue());
}
}
return var::null;
}
void OscProcessor::setOscParameterValue(String address, var value)
{
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->getAddress() == address) {
managedOscParameters[index]->setValue(value);
return;
}
}
}
void OscProcessor::addOscParameterListener(OscParameterListener* listener, OscParameter* parameter)
{
parameter->addOscParameterListener(listener);
}
void OscProcessor::addOscParameterListener(OscParameterListener* listener, String regex)
{
auto parameters = getAllOscParameter(regex);
for (int index = 0; index < parameters.size(); index++) {
parameters[index]->addOscParameterListener(listener);
}
}
void OscProcessor::removeOscParameterListener(OscParameterListener* listener)
{
auto parameters = getAllOscParameter();
for (int index = 0; index < parameters.size(); index++) {
parameters[index]->removeOscParameterListener(listener);
}
}
void OscProcessor::parseOscPacket(osc::ReceivedPacket packet)
{
if (packet.Size()) {
if (packet.IsBundle()) {
osc::ReceivedBundle bundle(packet);
parseOscBundle(bundle);
}
else {
osc::ReceivedMessage message(packet);
parseOscMessage(message);
}
}
}
void OscProcessor::parseOscMessage(osc::ReceivedMessage message)
{
String address(message.AddressPattern());
OscParameter* parameter = getOscParameter(address);
if (parameter) {
osc::ReceivedMessage::const_iterator arg = message.ArgumentsBegin();
while (arg != message.ArgumentsEnd()) {
if (arg->IsFloat()) {
parameter->setValue(var(arg->AsFloat()));
}
else if (arg->IsBool()) {
parameter->setValue(var(arg->IsBool()));
}
else if (arg->IsInt32()) {
parameter->setValue(var(arg->AsInt32()));
}
else if (arg->IsChar()) {
parameter->setValue(var(String(arg->AsChar())));
}
else if (arg->IsDouble()) {
parameter->setValue(var(arg->AsDouble()));
}
else if (arg->IsString()) {
parameter->setValue(var(String(arg->AsString())));
}
else if (arg->IsSymbol()) {
parameter->setValue(var(String(arg->IsSymbol())));
}
arg++;
}
}
}
void OscProcessor::parseOscBundle(osc::ReceivedBundle bundle)
{
osc::ReceivedBundleElementIterator initiator = bundle.ElementsBegin();
for (int i = 0; i < bundle.ElementCount(); i++) {
initiator++;
if (initiator->IsBundle()) {
osc::ReceivedBundle bundle(*initiator);
parseOscBundle(bundle);
}
else {
osc::ReceivedMessage message(*initiator);
parseOscMessage(message);
}
}
}
OscServer* OscProcessor::getOscServer()
{
return &oscServer;
}
<commit_msg>finalize settings with new osc backend<commit_after>/*
==============================================================================
OscProcessor.cpp
Created: 22 Jan 2015 10:56:59pm
Author: Daniel Lindenfelser
==============================================================================
*/
#include "OscProcessor.h"
OscProcessor::OscProcessor()
: oscServer(this)
{
}
OscProcessor::~OscProcessor()
{
managedOscParameters.clear();
}
void OscProcessor::handleOscMessage(osc::ReceivedPacket packet)
{
parseOscPacket(packet);
}
void OscProcessor::changeListenerCallback(ChangeBroadcaster* source)
{
OscParameter* parameter = static_cast<OscParameter*>(source);
if (parameter) {
char buffer[1024];
osc::OutboundPacketStream packet(buffer, 1024);
parameter->appendOscMessageToStream(packet);
oscServer.sendMessage(packet);
}
}
void OscProcessor::addOscParameter(OscParameter* parameter, bool internal)
{
if (parameter) {
managedOscParameters.addIfNotAlreadyThere(parameter);
if (!internal) {
parameter->addChangeListener(this);
}
}
}
void OscProcessor::removeOscParameter(OscParameter* p)
{
managedOscParameters.removeObject(p);
}
void OscProcessor::removeOscParameter(String regex)
{
Array<OscParameter*> toRemove;
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->addressMatch(regex)) {
toRemove.add(managedOscParameters[index]);
}
}
for (int index = 0; index < toRemove.size(); index++) {
managedOscParameters.removeObject(toRemove[index]);
}
}
Array<OscParameter*> OscProcessor::getAllOscParameter(String regex)
{
Array<OscParameter*> parameters;
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->addressMatch(regex)) {
parameters.add(managedOscParameters[index]);
}
}
return parameters;
}
OscParameter* OscProcessor::getOscParameter(String address)
{
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->getAddress() == address) {
return managedOscParameters[index];
}
}
return nullptr;
}
Array<OscParameter*> OscProcessor::getAllOscParameter()
{
Array<OscParameter*> parameters;
for (int index = 0; index < managedOscParameters.size(); index++) {
parameters.add(managedOscParameters[index]);
}
return parameters;
}
void OscProcessor::dumpOscParameters()
{
for (int index = 0; index < managedOscParameters.size(); index++) {
char buffer[1024];
osc::OutboundPacketStream packet(buffer, 1024);
managedOscParameters[index]->appendOscMessageToStream(packet);
oscServer.sendMessage(packet);
}
}
var OscProcessor::getOscParameterValue(String address)
{
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->getAddress() == address) {
return var(managedOscParameters[index]->getValue());
}
}
return var::null;
}
void OscProcessor::setOscParameterValue(String address, var value)
{
for (int index = 0; index < managedOscParameters.size(); index++) {
if (managedOscParameters[index]->getAddress() == address) {
managedOscParameters[index]->setValue(value);
return;
}
}
Logger::outputDebugString("setOscParameterValue: address " + address + " not found!");
}
void OscProcessor::addOscParameterListener(OscParameterListener* listener, OscParameter* parameter)
{
parameter->addOscParameterListener(listener);
}
void OscProcessor::addOscParameterListener(OscParameterListener* listener, String regex)
{
auto parameters = getAllOscParameter(regex);
for (int index = 0; index < parameters.size(); index++) {
parameters[index]->addOscParameterListener(listener);
}
}
void OscProcessor::removeOscParameterListener(OscParameterListener* listener)
{
auto parameters = getAllOscParameter();
for (int index = 0; index < parameters.size(); index++) {
parameters[index]->removeOscParameterListener(listener);
}
}
void OscProcessor::parseOscPacket(osc::ReceivedPacket packet)
{
if (packet.Size()) {
if (packet.IsBundle()) {
osc::ReceivedBundle bundle(packet);
parseOscBundle(bundle);
}
else {
osc::ReceivedMessage message(packet);
parseOscMessage(message);
}
}
}
void OscProcessor::parseOscMessage(osc::ReceivedMessage message)
{
String address(message.AddressPattern());
OscParameter* parameter = getOscParameter(address);
if (parameter) {
osc::ReceivedMessage::const_iterator arg = message.ArgumentsBegin();
while (arg != message.ArgumentsEnd()) {
if (arg->IsFloat()) {
parameter->setValue(var(arg->AsFloat()));
}
else if (arg->IsBool()) {
parameter->setValue(var(arg->IsBool()));
}
else if (arg->IsInt32()) {
parameter->setValue(var(arg->AsInt32()));
}
else if (arg->IsChar()) {
parameter->setValue(var(String(arg->AsChar())));
}
else if (arg->IsDouble()) {
parameter->setValue(var(arg->AsDouble()));
}
else if (arg->IsString()) {
parameter->setValue(var(String(arg->AsString())));
}
else if (arg->IsSymbol()) {
parameter->setValue(var(String(arg->IsSymbol())));
}
arg++;
}
}
}
void OscProcessor::parseOscBundle(osc::ReceivedBundle bundle)
{
osc::ReceivedBundleElementIterator initiator = bundle.ElementsBegin();
for (int i = 0; i < bundle.ElementCount(); i++) {
initiator++;
if (initiator->IsBundle()) {
osc::ReceivedBundle bundle(*initiator);
parseOscBundle(bundle);
}
else {
osc::ReceivedMessage message(*initiator);
parseOscMessage(message);
}
}
}
OscServer* OscProcessor::getOscServer()
{
return &oscServer;
}
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
# define LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
# include <boost/type_traits/is_polymorphic.hpp>
# include <luabind/detail/inheritance.hpp>
# include <luabind/detail/object_rep.hpp>
namespace luabind { namespace detail {
template <class T>
std::pair<class_id, void*> get_dynamic_class_aux(
lua_State* L, T const* p, mpl::true_)
{
lua_pushliteral(L, "__luabind_class_id_map");
lua_rawget(L, LUA_REGISTRYINDEX);
class_id_map& class_ids = *static_cast<class_id_map*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
return std::make_pair(
class_ids.get_local(typeid(*p))
, dynamic_cast<void*>(const_cast<T*>(p))
);
}
template <class T>
std::pair<class_id, void*> get_dynamic_class_aux(
lua_State*, T const* p, mpl::false_)
{
return std::make_pair(registered_class<T>::id, (void*)p);
}
template <class T>
std::pair<class_id, void*> get_dynamic_class(lua_State* L, T* p)
{
return get_dynamic_class_aux(L, p, boost::is_polymorphic<T>());
}
template <class T>
class_rep* get_pointee_class(class_map const& classes, T*)
{
return classes.get(registered_class<T>::id);
}
template <class P>
class_rep* get_pointee_class(lua_State* L, P const& p, class_id dynamic_id)
{
lua_pushliteral(L, "__luabind_class_map");
lua_rawget(L, LUA_REGISTRYINDEX);
class_map const& classes = *static_cast<class_map*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
class_rep* cls = classes.get(dynamic_id);
if (!cls)
cls = get_pointee_class(classes, get_pointer(p));
return cls;
}
// Create an appropriate instance holder for the given pointer like object.
template <class P>
void make_instance(lua_State* L, P p)
{
std::pair<class_id, void*> dynamic = get_dynamic_class(L, get_pointer(p));
class_rep* cls = get_pointee_class(L, p, dynamic.first);
if (!cls)
{
throw std::runtime_error("Trying to use unregistered class");
}
object_rep* instance = push_new_instance(L, cls);
typedef pointer_holder<P> holder_type;
void* storage = instance->allocate(sizeof(holder_type));
try
{
new (storage) holder_type(p, dynamic.first, dynamic.second, cls);
}
catch (...)
{
instance->deallocate(storage);
lua_pop(L, 1);
throw;
}
instance->set_instance(static_cast<holder_type*>(storage));
}
}} // namespace luabind::detail
#endif // LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
<commit_msg>Improved LuaBind error message when class not found.<commit_after>// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
# define LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
# include <boost/type_traits/is_polymorphic.hpp>
# include <luabind/detail/inheritance.hpp>
# include <luabind/detail/object_rep.hpp>
# include <string>
namespace luabind { namespace detail {
template <class T>
std::pair<class_id, void*> get_dynamic_class_aux(
lua_State* L, T const* p, mpl::true_)
{
lua_pushliteral(L, "__luabind_class_id_map");
lua_rawget(L, LUA_REGISTRYINDEX);
class_id_map& class_ids = *static_cast<class_id_map*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
return std::make_pair(
class_ids.get_local(typeid(*p))
, dynamic_cast<void*>(const_cast<T*>(p))
);
}
template <class T>
std::pair<class_id, void*> get_dynamic_class_aux(
lua_State*, T const* p, mpl::false_)
{
return std::make_pair(registered_class<T>::id, (void*)p);
}
template <class T>
std::pair<class_id, void*> get_dynamic_class(lua_State* L, T* p)
{
return get_dynamic_class_aux(L, p, boost::is_polymorphic<T>());
}
template <class T>
class_rep* get_pointee_class(class_map const& classes, T*)
{
return classes.get(registered_class<T>::id);
}
template <class P>
class_rep* get_pointee_class(lua_State* L, P const& p, class_id dynamic_id)
{
lua_pushliteral(L, "__luabind_class_map");
lua_rawget(L, LUA_REGISTRYINDEX);
class_map const& classes = *static_cast<class_map*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
class_rep* cls = classes.get(dynamic_id);
if (!cls)
cls = get_pointee_class(classes, get_pointer(p));
return cls;
}
// Create an appropriate instance holder for the given pointer like object.
template <class P>
void make_instance(lua_State* L, P p)
{
std::pair<class_id, void*> dynamic = get_dynamic_class(L, get_pointer(p));
class_rep* cls = get_pointee_class(L, p, dynamic.first);
if (!cls)
{
std::string msg("Trying to use unregistered class: ");
throw std::runtime_error(msg + typeid(*p).name());
}
object_rep* instance = push_new_instance(L, cls);
typedef pointer_holder<P> holder_type;
void* storage = instance->allocate(sizeof(holder_type));
try
{
new (storage) holder_type(p, dynamic.first, dynamic.second, cls);
}
catch (...)
{
instance->deallocate(storage);
lua_pop(L, 1);
throw;
}
instance->set_instance(static_cast<holder_type*>(storage));
}
}} // namespace luabind::detail
#endif // LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
<|endoftext|> |
<commit_before>#include <cassert>
#include <cmath>
#include <vector>
#ifdef _WIN32
#include "mferror.h"
#include "windows.h"
#include "mmsystem.h"
#include "mmreg.h"
#endif
#include "VorbisDecoder.hpp"
#ifdef _DEBUG
#include "odbgstream.hpp"
#include "iidstr.hpp"
using std::endl;
// keep the compiler quiet about do/while(0)'s used in log macros
#pragma warning(disable:4127)
#define DBGLOG(X) \
do { \
wodbgstream wos; \
wos << "["__FUNCTION__"] " << X << endl; \
} while(0)
#else
#define DBGLOG(X) do {} while(0)
#endif
namespace WebmMfVorbisDecLib
{
VorbisDecoder::VorbisDecoder() :
m_ogg_packet_count(0),
m_output_format_tag(WAVE_FORMAT_IEEE_FLOAT),
m_output_bits_per_sample(sizeof(float))
{
::memset(&m_vorbis_info, 0, sizeof vorbis_info);
::memset(&m_vorbis_comment, 0, sizeof vorbis_comment);
::memset(&m_vorbis_state, 0, sizeof vorbis_dsp_state);
::memset(&m_vorbis_block, 0, sizeof vorbis_block);
::memset(&m_ogg_packet, 0, sizeof ogg_packet);
}
VorbisDecoder::~VorbisDecoder()
{
DestroyDecoder();
}
int VorbisDecoder::NextOggPacket_(const BYTE* ptr_packet, DWORD packet_size)
{
if (!ptr_packet || packet_size == 0)
return E_INVALIDARG;
m_ogg_packet.b_o_s = (m_ogg_packet_count == 0);
m_ogg_packet.bytes = packet_size;
// TODO(tomfinegan): implement End Of Stream handling
m_ogg_packet.e_o_s = 0;
m_ogg_packet.granulepos = 0;
m_ogg_packet.packet = const_cast<BYTE*>(ptr_packet);
m_ogg_packet.packetno = m_ogg_packet_count++;
return S_OK;
}
int VorbisDecoder::CreateDecoder(const BYTE** const ptr_headers,
const DWORD* const header_lengths,
unsigned int num_headers)
{
assert(ptr_headers);
assert(header_lengths);
assert(num_headers == 3);
vorbis_info_init(&m_vorbis_info);
vorbis_comment_init(&m_vorbis_comment);
int status;
// feed the ident and comment headers into libvorbis
for (BYTE header_num = 0; header_num < 3; ++header_num)
{
assert(header_lengths[header_num] > 0);
// create an ogg packet in m_ogg_packet with current header for data
status = NextOggPacket_(ptr_headers[header_num],
header_lengths[header_num]);
if (FAILED(status))
return E_INVALIDARG;
assert(m_ogg_packet.packetno == header_num);
status = vorbis_synthesis_headerin(&m_vorbis_info, &m_vorbis_comment,
&m_ogg_packet);
if (status < 0)
return E_INVALIDARG;
}
// final init steps, setup decoder state...
status = vorbis_synthesis_init(&m_vorbis_state, &m_vorbis_info);
if (status != 0)
return E_INVALIDARG;
// ... and vorbis block structs
status = vorbis_block_init(&m_vorbis_state, &m_vorbis_block);
if (status != 0)
return E_INVALIDARG;
SetDecodedWaveFormat_();
assert(m_vorbis_info.rate > 0);
assert(m_vorbis_info.channels > 0);
return S_OK;
}
void VorbisDecoder::DestroyDecoder()
{
m_ogg_packet_count = 0;
vorbis_block_clear(&m_vorbis_block);
vorbis_dsp_clear(&m_vorbis_state);
vorbis_comment_clear(&m_vorbis_comment);
// note, from vorbis decoder sample: vorbis_info_clear must be last call
vorbis_info_clear(&m_vorbis_info);
m_output_samples.clear();
}
void VorbisDecoder::SetDecodedWaveFormat_()
{
m_wave_format.nChannels = static_cast<WORD>(m_vorbis_info.channels);
m_wave_format.nSamplesPerSec = static_cast<WORD>(m_vorbis_info.rate);
m_wave_format.wBitsPerSample = sizeof(float) * 8;
m_wave_format.nBlockAlign = m_wave_format.nChannels * sizeof(float);
m_wave_format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
m_wave_format.nAvgBytesPerSec = m_wave_format.nBlockAlign *
m_wave_format.nSamplesPerSec;
}
int VorbisDecoder::GetWaveFormat(WAVEFORMATEX* ptr_out_wave_format)
{
if (!ptr_out_wave_format)
return E_INVALIDARG;
assert(m_wave_format.cbSize == 0);
memcpy(ptr_out_wave_format, &m_wave_format, sizeof WAVEFORMATEX);
return S_OK;
}
int VorbisDecoder::Decode(BYTE* ptr_samples, UINT32 length)
{
int status = NextOggPacket_(ptr_samples, length);
if (FAILED(status))
return E_FAIL;
// start decoding the chunk of vorbis data we just wrapped in an ogg packet
status = vorbis_synthesis(&m_vorbis_block, &m_ogg_packet);
// TODO(tomfinegan): will vorbis_synthesis ever return non-zero?
assert(status == 0);
if (status != 0)
return E_FAIL;
status = vorbis_synthesis_blockin(&m_vorbis_state, &m_vorbis_block);
assert(status == 0);
if (status != 0)
return E_FAIL;
// Consume all PCM samples from libvorbis
int samples = 0;
float** pp_pcm;
while ((samples = vorbis_synthesis_pcmout(&m_vorbis_state, &pp_pcm)) > 0)
{
for (int sample = 0; sample < samples; ++sample)
{
for (int channel = 0; channel < m_vorbis_info.channels; ++channel)
{
m_output_samples.push_back(pp_pcm[channel][sample]);
}
}
vorbis_synthesis_read(&m_vorbis_state, samples);
}
return S_OK;
}
int VorbisDecoder::GetOutputSamplesAvailable(UINT32* ptr_num_samples_available)
{
if (!ptr_num_samples_available)
return E_INVALIDARG;
const UINT32 total_samples_available = m_output_samples.size();
const UINT32 channels = m_vorbis_info.channels;
if (channels > 1)
{
// caller wants the total samples, not the size of the sample vector
*ptr_num_samples_available =
(total_samples_available + (channels - 1)) / channels;
}
else
{
// for mono the size of the samples vector is the number of samples
*ptr_num_samples_available = total_samples_available;
}
return S_OK;
}
int VorbisDecoder::ConsumeOutputSamples(BYTE* ptr_out_sample_buffer,
UINT32 buffer_limit_in_bytes,
UINT32* ptr_output_bytes_written,
UINT32* ptr_output_sample_count)
{
if (!ptr_out_sample_buffer || !ptr_output_bytes_written ||
!ptr_output_sample_count)
return E_INVALIDARG;
if (m_output_samples.empty())
return MF_E_TRANSFORM_NEED_MORE_INPUT;
const UINT32 bytes_per_sample = m_wave_format.wBitsPerSample >> 3;
const UINT32 bytes_available = m_output_samples.size() * bytes_per_sample;
UINT32 bytes_to_copy = bytes_available > buffer_limit_in_bytes ?
buffer_limit_in_bytes : bytes_available;
if (m_output_format_tag == WAVE_FORMAT_PCM)
{
return ConvertOutputSamplesS16_(ptr_out_sample_buffer,
buffer_limit_in_bytes,
ptr_output_bytes_written,
ptr_output_sample_count);
}
::memcpy(ptr_out_sample_buffer, &m_output_samples[0], bytes_to_copy);
const UINT32 samples_consumed =
static_cast<UINT32>((double)bytes_to_copy / (double)bytes_per_sample);
typedef pcm_samples_t::const_iterator pcm_iterator;
pcm_iterator pcm_iter = m_output_samples.begin();
m_output_samples.erase(pcm_iter, pcm_iter+samples_consumed);
*ptr_output_sample_count = static_cast<UINT32>(
(double)samples_consumed / (double)m_vorbis_info.channels);
DBGLOG("bytes_available=" << bytes_available);
DBGLOG("buffer_limit_in_bytes=" << buffer_limit_in_bytes);
DBGLOG("bytes_to_copy=" << bytes_to_copy);
DBGLOG("samples_consumed=" << samples_consumed);
DBGLOG("out_sample_count=" << *ptr_output_sample_count);
*ptr_output_bytes_written = bytes_to_copy;
return S_OK;
}
namespace
{
INT16 clip16(int val)
{
if (val > 32767)
val = 32767;
else if (val < -32768)
val = -32768;
return static_cast<INT16>(val);
}
} // end anon namespace
int VorbisDecoder::ConvertOutputSamplesS16_(BYTE* ptr_out_sample_buffer,
UINT32 buffer_limit_in_bytes,
UINT32* ptr_output_bytes_written,
UINT32* ptr_output_sample_count)
{
assert(m_output_bits_per_sample == 16);
assert(m_output_format_tag == WAVE_FORMAT_PCM);
typedef pcm_samples_t::const_iterator pcm_iterator;
pcm_iterator pcm_iter = m_output_samples.begin();
pcm_iterator pcm_end = m_output_samples.end();
UINT32 bytes_per_sample = m_output_bits_per_sample >> 3;
UINT32 max_samples = static_cast<UINT32>(
(double)buffer_limit_in_bytes / (double)bytes_per_sample);
UINT32 sample;
INT16* ptr_out_sample_buffer_s16 = reinterpret_cast<INT16*>(
ptr_out_sample_buffer);
for (sample = 0; pcm_iter != pcm_end && sample < max_samples;
++pcm_iter, ++sample)
{
ptr_out_sample_buffer_s16[sample] = static_cast<INT16>(
clip16((int)floor(*pcm_iter * 32767.f + .5f)));
}
if (pcm_iter != pcm_end)
m_output_samples.erase(m_output_samples.begin(), pcm_iter);
else
m_output_samples.clear();
*ptr_output_bytes_written = sample * bytes_per_sample;
*ptr_output_sample_count = static_cast<UINT32>(
(double)sample / (double)m_vorbis_info.channels);
return S_OK;
}
void VorbisDecoder::Flush()
{
vorbis_synthesis_restart(&m_vorbis_state);
m_output_samples.clear();
}
int VorbisDecoder::SetOutputWaveFormat(int format_tag, int bits_per_sample)
{
assert(format_tag == WAVE_FORMAT_IEEE_FLOAT ||
format_tag == WAVE_FORMAT_PCM);
if (format_tag != WAVE_FORMAT_IEEE_FLOAT && format_tag == WAVE_FORMAT_PCM)
return E_INVALIDARG;
const int bits_ieee = sizeof(float) * 8;
const int bits_s16 = sizeof(INT16) * 8;
assert(bits_per_sample == bits_ieee || bits_s16 == sizeof(INT16));
if (bits_ieee != sizeof(float) && bits_s16 != sizeof(INT16))
return E_INVALIDARG;
m_output_format_tag = format_tag;
m_output_bits_per_sample = bits_per_sample;
return S_OK;
}
} // end namespace WebmMfVorbisDecLib
<commit_msg>webmmfvorbisdec: zero VorbisDecoder WAVEFORMATEX<commit_after>#include <cassert>
#include <cmath>
#include <vector>
#ifdef _WIN32
#include "mferror.h"
#include "windows.h"
#include "mmsystem.h"
#include "mmreg.h"
#endif
#include "VorbisDecoder.hpp"
#ifdef _DEBUG
#include "odbgstream.hpp"
#include "iidstr.hpp"
using std::endl;
// keep the compiler quiet about do/while(0)'s used in log macros
#pragma warning(disable:4127)
#define DBGLOG(X) \
do { \
wodbgstream wos; \
wos << "["__FUNCTION__"] " << X << endl; \
} while(0)
#else
#define DBGLOG(X) do {} while(0)
#endif
namespace WebmMfVorbisDecLib
{
VorbisDecoder::VorbisDecoder() :
m_ogg_packet_count(0),
m_output_format_tag(WAVE_FORMAT_IEEE_FLOAT),
m_output_bits_per_sample(sizeof(float))
{
::memset(&m_vorbis_info, 0, sizeof vorbis_info);
::memset(&m_vorbis_comment, 0, sizeof vorbis_comment);
::memset(&m_vorbis_state, 0, sizeof vorbis_dsp_state);
::memset(&m_vorbis_block, 0, sizeof vorbis_block);
::memset(&m_ogg_packet, 0, sizeof ogg_packet);
::memset(&m_wave_format, 0, sizeof WAVEFORMATEX);
}
VorbisDecoder::~VorbisDecoder()
{
DestroyDecoder();
}
int VorbisDecoder::NextOggPacket_(const BYTE* ptr_packet, DWORD packet_size)
{
if (!ptr_packet || packet_size == 0)
return E_INVALIDARG;
m_ogg_packet.b_o_s = (m_ogg_packet_count == 0);
m_ogg_packet.bytes = packet_size;
// TODO(tomfinegan): implement End Of Stream handling
m_ogg_packet.e_o_s = 0;
m_ogg_packet.granulepos = 0;
m_ogg_packet.packet = const_cast<BYTE*>(ptr_packet);
m_ogg_packet.packetno = m_ogg_packet_count++;
return S_OK;
}
int VorbisDecoder::CreateDecoder(const BYTE** const ptr_headers,
const DWORD* const header_lengths,
unsigned int num_headers)
{
assert(ptr_headers);
assert(header_lengths);
assert(num_headers == 3);
vorbis_info_init(&m_vorbis_info);
vorbis_comment_init(&m_vorbis_comment);
int status;
// feed the ident and comment headers into libvorbis
for (BYTE header_num = 0; header_num < 3; ++header_num)
{
assert(header_lengths[header_num] > 0);
// create an ogg packet in m_ogg_packet with current header for data
status = NextOggPacket_(ptr_headers[header_num],
header_lengths[header_num]);
if (FAILED(status))
return E_INVALIDARG;
assert(m_ogg_packet.packetno == header_num);
status = vorbis_synthesis_headerin(&m_vorbis_info, &m_vorbis_comment,
&m_ogg_packet);
if (status < 0)
return E_INVALIDARG;
}
// final init steps, setup decoder state...
status = vorbis_synthesis_init(&m_vorbis_state, &m_vorbis_info);
if (status != 0)
return E_INVALIDARG;
// ... and vorbis block structs
status = vorbis_block_init(&m_vorbis_state, &m_vorbis_block);
if (status != 0)
return E_INVALIDARG;
SetDecodedWaveFormat_();
assert(m_vorbis_info.rate > 0);
assert(m_vorbis_info.channels > 0);
return S_OK;
}
void VorbisDecoder::DestroyDecoder()
{
m_ogg_packet_count = 0;
vorbis_block_clear(&m_vorbis_block);
vorbis_dsp_clear(&m_vorbis_state);
vorbis_comment_clear(&m_vorbis_comment);
// note, from vorbis decoder sample: vorbis_info_clear must be last call
vorbis_info_clear(&m_vorbis_info);
m_output_samples.clear();
}
void VorbisDecoder::SetDecodedWaveFormat_()
{
m_wave_format.nChannels = static_cast<WORD>(m_vorbis_info.channels);
m_wave_format.nSamplesPerSec = static_cast<WORD>(m_vorbis_info.rate);
m_wave_format.wBitsPerSample = sizeof(float) * 8;
m_wave_format.nBlockAlign = m_wave_format.nChannels * sizeof(float);
m_wave_format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
m_wave_format.nAvgBytesPerSec = m_wave_format.nBlockAlign *
m_wave_format.nSamplesPerSec;
}
int VorbisDecoder::GetWaveFormat(WAVEFORMATEX* ptr_out_wave_format)
{
if (!ptr_out_wave_format)
return E_INVALIDARG;
assert(m_wave_format.cbSize == 0);
memcpy(ptr_out_wave_format, &m_wave_format, sizeof WAVEFORMATEX);
return S_OK;
}
int VorbisDecoder::Decode(BYTE* ptr_samples, UINT32 length)
{
int status = NextOggPacket_(ptr_samples, length);
if (FAILED(status))
return E_FAIL;
// start decoding the chunk of vorbis data we just wrapped in an ogg packet
status = vorbis_synthesis(&m_vorbis_block, &m_ogg_packet);
// TODO(tomfinegan): will vorbis_synthesis ever return non-zero?
assert(status == 0);
if (status != 0)
return E_FAIL;
status = vorbis_synthesis_blockin(&m_vorbis_state, &m_vorbis_block);
assert(status == 0);
if (status != 0)
return E_FAIL;
// Consume all PCM samples from libvorbis
int samples = 0;
float** pp_pcm;
while ((samples = vorbis_synthesis_pcmout(&m_vorbis_state, &pp_pcm)) > 0)
{
for (int sample = 0; sample < samples; ++sample)
{
for (int channel = 0; channel < m_vorbis_info.channels; ++channel)
{
m_output_samples.push_back(pp_pcm[channel][sample]);
}
}
vorbis_synthesis_read(&m_vorbis_state, samples);
}
return S_OK;
}
int VorbisDecoder::GetOutputSamplesAvailable(UINT32* ptr_num_samples_available)
{
if (!ptr_num_samples_available)
return E_INVALIDARG;
const UINT32 total_samples_available = m_output_samples.size();
const UINT32 channels = m_vorbis_info.channels;
if (channels > 1)
{
// caller wants the total samples, not the size of the sample vector
*ptr_num_samples_available =
(total_samples_available + (channels - 1)) / channels;
}
else
{
// for mono the size of the samples vector is the number of samples
*ptr_num_samples_available = total_samples_available;
}
return S_OK;
}
int VorbisDecoder::ConsumeOutputSamples(BYTE* ptr_out_sample_buffer,
UINT32 buffer_limit_in_bytes,
UINT32* ptr_output_bytes_written,
UINT32* ptr_output_sample_count)
{
if (!ptr_out_sample_buffer || !ptr_output_bytes_written ||
!ptr_output_sample_count)
return E_INVALIDARG;
if (m_output_samples.empty())
return MF_E_TRANSFORM_NEED_MORE_INPUT;
const UINT32 bytes_per_sample = m_wave_format.wBitsPerSample >> 3;
const UINT32 bytes_available = m_output_samples.size() * bytes_per_sample;
UINT32 bytes_to_copy = bytes_available > buffer_limit_in_bytes ?
buffer_limit_in_bytes : bytes_available;
if (m_output_format_tag == WAVE_FORMAT_PCM)
{
return ConvertOutputSamplesS16_(ptr_out_sample_buffer,
buffer_limit_in_bytes,
ptr_output_bytes_written,
ptr_output_sample_count);
}
::memcpy(ptr_out_sample_buffer, &m_output_samples[0], bytes_to_copy);
const UINT32 samples_consumed =
static_cast<UINT32>((double)bytes_to_copy / (double)bytes_per_sample);
typedef pcm_samples_t::const_iterator pcm_iterator;
pcm_iterator pcm_iter = m_output_samples.begin();
m_output_samples.erase(pcm_iter, pcm_iter+samples_consumed);
*ptr_output_sample_count = static_cast<UINT32>(
(double)samples_consumed / (double)m_vorbis_info.channels);
DBGLOG("bytes_available=" << bytes_available);
DBGLOG("buffer_limit_in_bytes=" << buffer_limit_in_bytes);
DBGLOG("bytes_to_copy=" << bytes_to_copy);
DBGLOG("samples_consumed=" << samples_consumed);
DBGLOG("out_sample_count=" << *ptr_output_sample_count);
*ptr_output_bytes_written = bytes_to_copy;
return S_OK;
}
namespace
{
INT16 clip16(int val)
{
if (val > 32767)
val = 32767;
else if (val < -32768)
val = -32768;
return static_cast<INT16>(val);
}
} // end anon namespace
int VorbisDecoder::ConvertOutputSamplesS16_(BYTE* ptr_out_sample_buffer,
UINT32 buffer_limit_in_bytes,
UINT32* ptr_output_bytes_written,
UINT32* ptr_output_sample_count)
{
assert(m_output_bits_per_sample == 16);
assert(m_output_format_tag == WAVE_FORMAT_PCM);
typedef pcm_samples_t::const_iterator pcm_iterator;
pcm_iterator pcm_iter = m_output_samples.begin();
pcm_iterator pcm_end = m_output_samples.end();
UINT32 bytes_per_sample = m_output_bits_per_sample >> 3;
UINT32 max_samples = static_cast<UINT32>(
(double)buffer_limit_in_bytes / (double)bytes_per_sample);
UINT32 sample;
INT16* ptr_out_sample_buffer_s16 = reinterpret_cast<INT16*>(
ptr_out_sample_buffer);
for (sample = 0; pcm_iter != pcm_end && sample < max_samples;
++pcm_iter, ++sample)
{
ptr_out_sample_buffer_s16[sample] = static_cast<INT16>(
clip16((int)floor(*pcm_iter * 32767.f + .5f)));
}
if (pcm_iter != pcm_end)
m_output_samples.erase(m_output_samples.begin(), pcm_iter);
else
m_output_samples.clear();
*ptr_output_bytes_written = sample * bytes_per_sample;
*ptr_output_sample_count = static_cast<UINT32>(
(double)sample / (double)m_vorbis_info.channels);
return S_OK;
}
void VorbisDecoder::Flush()
{
vorbis_synthesis_restart(&m_vorbis_state);
m_output_samples.clear();
}
int VorbisDecoder::SetOutputWaveFormat(int format_tag, int bits_per_sample)
{
assert(format_tag == WAVE_FORMAT_IEEE_FLOAT ||
format_tag == WAVE_FORMAT_PCM);
if (format_tag != WAVE_FORMAT_IEEE_FLOAT && format_tag == WAVE_FORMAT_PCM)
return E_INVALIDARG;
const int bits_ieee = sizeof(float) * 8;
const int bits_s16 = sizeof(INT16) * 8;
assert(bits_per_sample == bits_ieee || bits_s16 == sizeof(INT16));
if (bits_ieee != sizeof(float) && bits_s16 != sizeof(INT16))
return E_INVALIDARG;
m_output_format_tag = format_tag;
m_output_bits_per_sample = bits_per_sample;
return S_OK;
}
} // end namespace WebmMfVorbisDecLib
<|endoftext|> |
<commit_before>#include "Mocks.hpp"
#include <ctime>
using namespace blackhole;
class base_frontend_t {
public:
virtual void handle(log::record_t&& record) = 0;
};
template<class Formatter, class Sink>
class frontend_t : public base_frontend_t {
const std::unique_ptr<Formatter> m_formatter;
const std::unique_ptr<Sink> m_sink;
public:
frontend_t(std::unique_ptr<Formatter> formatter, std::unique_ptr<Sink> sink) :
m_formatter(std::move(formatter)),
m_sink(std::move(sink))
{}
void handle(log::record_t&& record) {
auto msg = std::move(m_formatter->format(record));
m_sink->consume(msg);
}
};
typedef std::function<bool(const log::attributes_t& attributes)> filter_t;
struct default_filter_t {
static default_filter_t& instance() {
static default_filter_t filter;
return filter;
}
bool operator()(const log::attributes_t&) {
return true;
}
private:
default_filter_t() {}
};
struct LessEqThan {
template<typename L, typename R>
bool operator()(const L& left, const R& right) const {
return left <= right;
}
};
log::attributes_t merge(const std::initializer_list<log::attributes_t>& args) {
log::attributes_t summary;
for (auto it = args.begin(); it != args.end(); ++it) {
summary.insert(it->begin(), it->end());
}
return summary;
}
namespace keyword {
template<typename T>
struct severity_t {
static_assert(std::is_enum<T>::value, "severity type must be enum");
typedef typename std::underlying_type<T>::type type;
static const char* name() {
return "severity";
}
filter_t operator>=(T value) const {
return action_t<LessEqThan>(value);
}
log::attributes_t operator=(T value) const {
log::attributes_t attributes;
attributes[name()] = static_cast<type>(value);
return attributes;
}
template<typename Action>
struct action_t {
Action action;
T value;
action_t(T value) :
value(value)
{}
bool operator()(const log::attributes_t& attributes) const {
//!@todo: attributes.extract<keyword::severity>();
return action(value, static_cast<T>(boost::get<type>(attributes.at(severity_t<T>::name()))));
}
};
};
template<typename T>
static severity_t<T>& severity() {
static severity_t<T> self;
return self;
}
// DECLARE_KEYWORD(severity, level);
} // namespace keyword
class logger_base_t {
bool m_enabled;
protected:
filter_t m_filter;
std::unique_ptr<base_frontend_t> m_frontend;
public:
logger_base_t() :
m_enabled(true),
m_filter(default_filter_t::instance())
{}
bool enabled() const {
return m_enabled;
}
void enable() {
m_enabled = true;
}
void disable() {
m_enabled = false;
}
void set_filter(filter_t&& filter) {
m_filter = filter;
}
void add_frontend(std::unique_ptr<base_frontend_t> frontend) {
m_frontend = std::move(frontend);
}
log::record_t open_record() const {
return open_record(log::attributes_t());
}
log::record_t open_record(log::attributes_t&& local_attributes) const {
if (enabled()) {
log::attributes_t attributes = merge({
std::move(get_scoped_attributes()),
std::move(local_attributes)
});
if (m_filter(attributes)) {
log::record_t record;
record.attributes = std::move(attributes);
return record;
}
}
return log::record_t();
}
void push(log::record_t&& record) {
m_frontend->handle(std::move(record));
}
private:
log::attributes_t get_scoped_attributes() const {
log::attributes_t attributes;
attributes["timestamp_id"] = std::time(nullptr);
return attributes;
}
};
template<typename Level>
class verbose_logger_t : public logger_base_t {
typedef typename std::underlying_type<Level>::type level_type;
public:
log::record_t open_record(Level level) const {
return logger_base_t::open_record(keyword::severity<Level>() = level);
}
};
TEST(logger_base_t, CanBeEnabled) {
logger_base_t log;
log.enable();
EXPECT_TRUE(log.enabled());
}
TEST(logger_base_t, CanBeDisabled) {
logger_base_t log;
log.disable();
EXPECT_FALSE(log.enabled());
}
TEST(logger_base_t, EnabledByDefault) {
logger_base_t log;
EXPECT_TRUE(log.enabled());
}
TEST(logger_base_t, OpenRecordByDefault) {
logger_base_t log;
EXPECT_TRUE(log.open_record().valid());
}
TEST(logger_base_t, DoNotOpenRecordIfDisabled) {
logger_base_t log;
log.disable();
EXPECT_FALSE(log.open_record().valid());
}
TEST(verbose_logger_t, Class) {
enum level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
UNUSED(log);
}
TEST(verbose_logger_t, OpenRecordByDefault) {
enum level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
log::record_t record = log.open_record(level::debug);
EXPECT_TRUE(record.valid());
}
TEST(verbose_logger_t, OpenRecordForValidVerbosityLevel) {
enum class level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
log.set_filter(keyword::severity<level>() >= level::info);
EXPECT_FALSE(log.open_record(level::debug).valid());
EXPECT_TRUE(log.open_record(level::info).valid());
EXPECT_TRUE(log.open_record(level::warn).valid());
EXPECT_TRUE(log.open_record(level::error).valid());
}
// Allow to make custom filters. severity >= warning || has_tag(urgent) && !!urgent
TEST(verbose_logger_t, Manual) {
enum level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
//!@note: Factory starts here...
auto formatter = std::make_unique<formatter::string_t>("[]: %(message)s");
auto sink = std::make_unique<sink::file_t<>>("/dev/stdout");
auto frontend = std::make_unique<frontend_t<formatter::string_t, sink::file_t<>>>(std::move(formatter), std::move(sink));
//!@note ... till here.
log.add_frontend(std::move(frontend));
//!@note: Next lines can be hided via macro: LOG(log, debug, "Message %s", "Hell", keyword::answer = 42);
log::record_t record = log.open_record(level::error);
if (record.valid()) {
record.attributes["message"] = utils::format("Some message from: '%s'!", "Hell");
// Add another attributes.
log.push(std::move(record));
}
}
<commit_msg>Convenient naming. Keyword and severity declaration via macro.<commit_after>#include "Mocks.hpp"
#include <ctime>
using namespace blackhole;
class base_frontend_t {
public:
virtual void handle(log::record_t&& record) = 0;
};
template<class Formatter, class Sink>
class frontend_t : public base_frontend_t {
const std::unique_ptr<Formatter> m_formatter;
const std::unique_ptr<Sink> m_sink;
public:
frontend_t(std::unique_ptr<Formatter> formatter, std::unique_ptr<Sink> sink) :
m_formatter(std::move(formatter)),
m_sink(std::move(sink))
{}
void handle(log::record_t&& record) {
auto msg = std::move(m_formatter->format(record));
m_sink->consume(msg);
}
};
typedef std::function<bool(const log::attributes_t& attributes)> filter_t;
struct default_filter_t {
static default_filter_t& instance() {
static default_filter_t filter;
return filter;
}
bool operator()(const log::attributes_t&) {
return true;
}
private:
default_filter_t() {}
};
struct LessEqThan {
template<typename L, typename R>
bool operator()(const L& left, const R& right) const {
return left <= right;
}
};
log::attributes_t merge(const std::initializer_list<log::attributes_t>& args) {
log::attributes_t summary;
for (auto it = args.begin(); it != args.end(); ++it) {
summary.insert(it->begin(), it->end());
}
return summary;
}
namespace keyword {
template<typename T, class = void>
struct keyword_base_t {
typedef T type;
};
template<typename T>
struct keyword_base_t<T, typename std::enable_if<std::is_enum<T>::value>::type> {
typedef T type;
typedef typename std::underlying_type<T>::type underlying_type;
static const char* name() {
return "severity";
}
filter_t operator>=(T value) const {
return action_t<LessEqThan>(value);
}
log::attributes_t operator=(T value) const {
log::attributes_t attributes;
attributes[name()] = static_cast<underlying_type>(value);
return attributes;
}
template<typename Action>
struct action_t {
Action action;
T value;
action_t(T value) :
value(value)
{}
bool operator()(const log::attributes_t& attributes) const {
//!@todo: attributes.extract<keyword::severity>();
return action(value, static_cast<T>(boost::get<underlying_type>(attributes.at(keyword_base_t<T>::name()))));
}
};
};
#define DECLARE_SEVERITY(__name__) \
template<typename T> \
static keyword::keyword_base_t<T>& __name__() { \
static keyword::keyword_base_t<T> self; \
return self; \
}
#define DECLARE_KEYWORD(__name__, __type__) \
static keyword::keyword_base_t<__type__>& __name__() { \
static keyword::keyword_base_t<__type__> self; \
return self; \
}
DECLARE_SEVERITY(severity)
DECLARE_KEYWORD(timestamp_id, std::time_t)
} // namespace keyword
class logger_base_t {
bool m_enabled;
protected:
filter_t m_filter;
std::unique_ptr<base_frontend_t> m_frontend;
public:
logger_base_t() :
m_enabled(true),
m_filter(default_filter_t::instance())
{}
bool enabled() const {
return m_enabled;
}
void enable() {
m_enabled = true;
}
void disable() {
m_enabled = false;
}
void set_filter(filter_t&& filter) {
m_filter = filter;
}
void add_frontend(std::unique_ptr<base_frontend_t> frontend) {
m_frontend = std::move(frontend);
}
log::record_t open_record() const {
return open_record(log::attributes_t());
}
log::record_t open_record(log::attributes_t&& local_attributes) const {
if (enabled()) {
log::attributes_t attributes = merge({
std::move(get_scoped_attributes()),
std::move(local_attributes)
});
if (m_filter(attributes)) {
log::record_t record;
record.attributes = std::move(attributes);
return record;
}
}
return log::record_t();
}
void push(log::record_t&& record) {
m_frontend->handle(std::move(record));
}
private:
log::attributes_t get_scoped_attributes() const {
log::attributes_t attributes;
attributes["timestamp_id"] = std::time(nullptr);
return attributes;
}
};
template<typename Level>
class verbose_logger_t : public logger_base_t {
typedef typename std::underlying_type<Level>::type level_type;
public:
log::record_t open_record(Level level) const {
return logger_base_t::open_record(keyword::severity<Level>() = level);
}
};
TEST(logger_base_t, CanBeEnabled) {
logger_base_t log;
log.enable();
EXPECT_TRUE(log.enabled());
}
TEST(logger_base_t, CanBeDisabled) {
logger_base_t log;
log.disable();
EXPECT_FALSE(log.enabled());
}
TEST(logger_base_t, EnabledByDefault) {
logger_base_t log;
EXPECT_TRUE(log.enabled());
}
TEST(logger_base_t, OpenRecordByDefault) {
logger_base_t log;
EXPECT_TRUE(log.open_record().valid());
}
TEST(logger_base_t, DoNotOpenRecordIfDisabled) {
logger_base_t log;
log.disable();
EXPECT_FALSE(log.open_record().valid());
}
TEST(verbose_logger_t, Class) {
enum level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
UNUSED(log);
}
TEST(verbose_logger_t, OpenRecordByDefault) {
enum level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
log::record_t record = log.open_record(level::debug);
EXPECT_TRUE(record.valid());
}
TEST(verbose_logger_t, OpenRecordForValidVerbosityLevel) {
enum class level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
log.set_filter(keyword::severity<level>() >= level::info);
EXPECT_FALSE(log.open_record(level::debug).valid());
EXPECT_TRUE(log.open_record(level::info).valid());
EXPECT_TRUE(log.open_record(level::warn).valid());
EXPECT_TRUE(log.open_record(level::error).valid());
}
// Allow to make custom filters. severity >= warning || has_tag(urgent) && !!urgent
TEST(verbose_logger_t, Manual) {
enum level : std::uint64_t { debug, info, warn, error };
verbose_logger_t<level> log;
//!@note: Factory starts here...
auto formatter = std::make_unique<formatter::string_t>("[]: %(message)s");
auto sink = std::make_unique<sink::file_t<>>("/dev/stdout");
auto frontend = std::make_unique<frontend_t<formatter::string_t, sink::file_t<>>>(std::move(formatter), std::move(sink));
//!@note ... till here.
log.add_frontend(std::move(frontend));
//!@note: Next lines can be hided via macro: LOG(log, debug, "Message %s", "Hell", keyword::answer = 42);
log::record_t record = log.open_record(level::error);
if (record.valid()) {
record.attributes["message"] = utils::format("Some message from: '%s'!", "Hell");
// Add another attributes.
log.push(std::move(record));
}
}
<|endoftext|> |
<commit_before>//#define NDEBUG // Debug supression
#include <os>
#include <iostream>
#include <net/inet>
using namespace std;
using namespace net;
uint8_t* buf = 0;
int bufsize = 0;
uint8_t* prev_data = 0;
class global {
static int i;
public:
global(){
printf("[*] Global constructor printing %i \n",++i);
}
void test(){
printf("[*] C++ constructor finds %i instances \n",i);
}
int instances(){ return i; }
~global(){
printf("[*] C++ destructor deleted 1 instance, %i remains \n",--i);
}
};
int global::i = 0;
global glob1;
int _test_glob2 = 1;
int _test_glob3 = 1;
__attribute__ ((constructor)) void foo(void)
{
_test_glob3 = 0xfa7ca7;
}
/* @todo - make configuration happen here
void Service::init(){
Inet net;
auto eth0 = Dev::eth(0);
auto mac = eth0.mac();
net.ifconfig(ETH0,{192,168,mac.part[4],mac.part[5]},{255,255,0,0});
//net.ifconfig(ETH0,{192,168,0,10}); => netmask == 255.255.255.0.
//net.route("*",{192.168.0.1});
Dev::eth(ETH0)
//Dev::eth(1).dhclient();
}*/
void Service::start()
{
cout << "*** Service is up - with OS Included! ***" << endl;
printf("[%s] Global C constructors in service \n",
_test_glob3 == 0xfa7ca7 ? "x" : " ");
printf("[%s] Global int initialization in service \n",
_test_glob2 == 1 ? "x" : " ");
global* glob2 = new global();;
glob1.test();
printf("[%s] Local C++ constructors in service \n", glob1.instances() == 2 ? "x" : " ");
delete glob2;
printf("[%s] C++ destructors in service \n", glob1.instances() == 1 ? "x" : " ");
auto& mac = Dev::eth(0).mac();
Inet::ifconfig(net::ETH0,{mac.part[2],mac.part[3],mac.part[4],mac.part[5]},{255,255,0,0});
/** Trying to access non-existing nic will cause a panic */
//auto& mac1 = Dev::eth(1).mac();
//Inet::ifconfig(net::ETH1,{192,168,mac1.part[4],mac1.part[5]},{255,255,0,0});
//Inet* net
shared_ptr<Inet> net(Inet::up());
cout << "...Starting UDP server on IP "
<< net->ip4(net::ETH0).str()
<< endl;
//A one-way UDP server (a primitive test)
net->udp_listen(8080,[net](std::shared_ptr<net::Packet> pckt){
UDP::full_header* full_hdr = (UDP::full_header*)pckt->buffer();
UDP::udp_header* hdr = &full_hdr->udp_hdr;
int data_len = __builtin_bswap16(hdr->length) - sizeof(UDP::udp_header);
auto data_loc = pckt->buffer() + sizeof(UDP::full_header);
// Netcat doesn't necessariliy zero-pad the string in UDP
// ... But this buffer is const
// auto data_end = data + hdr->length - sizeof(UDP::udp_header);
// *data_end = 0;
debug("<APP SERVER> Got %i b of data (%i b frame) from %s:%i -> %s:%i\n",
data_len, len, full_hdr->ip_hdr.saddr.str().c_str(),
__builtin_bswap16(hdr->sport),
full_hdr->ip_hdr.daddr.str().c_str(),
__builtin_bswap16(hdr->dport));
printf("%s : ",full_hdr->ip_hdr.saddr.str().c_str());
for (int i = 0; i < data_len; i++)
printf("%c", data_loc[i]);
// Craft response
string response(string((const char*)data_loc,data_len));
bufsize = response.size() + sizeof(UDP::full_header);
// Ethernet padding if necessary
if (bufsize < Ethernet::minimum_payload)
bufsize = Ethernet::minimum_payload;
if(buf)
delete[] buf;
buf = new uint8_t[bufsize];
strcpy((char*)buf + sizeof(UDP::full_header),response.c_str());
// Respond
debug("<APP SERVER> Sending %li b wrapped in %i b buffer \n",
response.size(),bufsize);
/** Populate outgoing UDP header */
UDP::full_header* full_hdr_out = (UDP::full_header*)buf;
full_hdr_out->udp_hdr.dport = hdr->sport;
full_hdr_out->udp_hdr.sport = hdr->dport;
/** Populate outgoing IP header */
full_hdr_out->ip_hdr.saddr = full_hdr->ip_hdr.daddr;
full_hdr_out->ip_hdr.daddr = full_hdr->ip_hdr.saddr;
full_hdr_out->ip_hdr.protocol = IP4::IP4_UDP;
Packet pckt_out(buf,bufsize,Packet::DOWNSTREAM);
net->udp_send(std::shared_ptr<Packet>(&pckt_out));
return 0;
});
cout << "<APP SERVER> Listening to UDP port 8080 " << endl;
// Hook up to I/O events and do something useful ...
cout << "Service out! " << endl;
}
<commit_msg>Fixed #102 (or so it seems) by atomically incrementing virtio available index. As suggested by the standard.<commit_after>//#define NDEBUG // Debug supression
#include <os>
#include <iostream>
#include <net/inet>
using namespace std;
using namespace net;
uint8_t* buf = 0;
int bufsize = 0;
uint8_t* prev_data = 0;
class global {
static int i;
public:
global(){
printf("[*] Global constructor printing %i \n",++i);
}
void test(){
printf("[*] C++ constructor finds %i instances \n",i);
}
int instances(){ return i; }
~global(){
printf("[*] C++ destructor deleted 1 instance, %i remains \n",--i);
}
};
int global::i = 0;
global glob1;
int _test_glob2 = 1;
int _test_glob3 = 1;
__attribute__ ((constructor)) void foo(void)
{
_test_glob3 = 0xfa7ca7;
}
/* @todo - make configuration happen here
void Service::init(){
Inet net;
auto eth0 = Dev::eth(0);
auto mac = eth0.mac();
net.ifconfig(ETH0,{192,168,mac.part[4],mac.part[5]},{255,255,0,0});
//net.ifconfig(ETH0,{192,168,0,10}); => netmask == 255.255.255.0.
//net.route("*",{192.168.0.1});
Dev::eth(ETH0)
//Dev::eth(1).dhclient();
}*/
void Service::start()
{
cout << "*** Service is up - with OS Included! ***" << endl;
printf("[%s] Global C constructors in service \n",
_test_glob3 == 0xfa7ca7 ? "x" : " ");
printf("[%s] Global int initialization in service \n",
_test_glob2 == 1 ? "x" : " ");
global* glob2 = new global();;
glob1.test();
printf("[%s] Local C++ constructors in service \n", glob1.instances() == 2 ? "x" : " ");
delete glob2;
printf("[%s] C++ destructors in service \n", glob1.instances() == 1 ? "x" : " ");
auto& mac = Dev::eth(0).mac();
Inet::ifconfig(net::ETH0,{mac.part[2],mac.part[3],mac.part[4],mac.part[5]},{255,255,0,0});
/** Trying to access non-existing nic will cause a panic */
//auto& mac1 = Dev::eth(1).mac();
//Inet::ifconfig(net::ETH1,{192,168,mac1.part[4],mac1.part[5]},{255,255,0,0});
//Inet* net
shared_ptr<Inet> net(Inet::up());
cout << "...Starting UDP server on IP "
<< net->ip4(net::ETH0).str()
<< endl;
//A one-way UDP server (a primitive test)
net->udp_listen(8080,[net](std::shared_ptr<net::Packet> pckt){
UDP::full_header* full_hdr = (UDP::full_header*)pckt->buffer();
UDP::udp_header* hdr = &full_hdr->udp_hdr;
int data_len = __builtin_bswap16(hdr->length) - sizeof(UDP::udp_header);
auto data_loc = pckt->buffer() + sizeof(UDP::full_header);
// Netcat doesn't necessariliy zero-pad the string in UDP
// ... But this buffer is const
// auto data_end = data + hdr->length - sizeof(UDP::udp_header);
// *data_end = 0;
debug("<APP SERVER> Got %i b of data (%i b frame) from %s:%i -> %s:%i\n",
data_len, len, full_hdr->ip_hdr.saddr.str().c_str(),
__builtin_bswap16(hdr->sport),
full_hdr->ip_hdr.daddr.str().c_str(),
__builtin_bswap16(hdr->dport));
//printf("%s : ",full_hdr->ip_hdr.saddr.str().c_str());
for (int i = 0; i < data_len; i++)
printf("%c", data_loc[i]);
// Craft response
string response(string((const char*)data_loc,data_len));
bufsize = response.size() + sizeof(UDP::full_header);
// Ethernet padding if necessary
if (bufsize < Ethernet::minimum_payload)
bufsize = Ethernet::minimum_payload;
if(buf)
delete[] buf;
buf = new uint8_t[bufsize];
strcpy((char*)buf + sizeof(UDP::full_header),response.c_str());
// Respond
debug("<APP SERVER> Sending %li b wrapped in %i b buffer \n",
response.size(),bufsize);
/** Populate outgoing UDP header */
UDP::full_header* full_hdr_out = (UDP::full_header*)buf;
full_hdr_out->udp_hdr.dport = hdr->sport;
full_hdr_out->udp_hdr.sport = hdr->dport;
/** Populate outgoing IP header */
full_hdr_out->ip_hdr.saddr = full_hdr->ip_hdr.daddr;
full_hdr_out->ip_hdr.daddr = full_hdr->ip_hdr.saddr;
full_hdr_out->ip_hdr.protocol = IP4::IP4_UDP;
Packet pckt_out(buf,bufsize,Packet::DOWNSTREAM);
net->udp_send(std::shared_ptr<Packet>(&pckt_out));
return 0;
});
cout << "<APP SERVER> Listening to UDP port 8080 " << endl;
// Hook up to I/O events and do something useful ...
cout << "Service out! " << endl;
}
<|endoftext|> |
<commit_before>/** @file editorviewscene.cpp
* @brief Сцена для отрисовки объектов
* */
#include "editorviewscene.h"
#include <QGraphicsTextItem>
#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "mainwindow.h"
#include "../mainwindow/mainwindow.h"
using namespace qReal;
EditorViewScene::EditorViewScene(QObject * parent)
: QGraphicsScene(parent), mWindow(NULL)
{
setItemIndexMethod(NoIndex);
setEnabled(false);
}
void EditorViewScene::setEnabled(bool enabled)
{
foreach (QGraphicsView *view, views())
{
view->setEnabled(enabled);
}
}
void EditorViewScene::clearScene()
{
QList < QGraphicsItem * >list = items();
QList < QGraphicsItem * >::Iterator it = list.begin();
for (; it != list.end(); ++it) {
removeItem(*it);
}
}
UML::Element * EditorViewScene::getElem(qReal::Id const &uuid)
{
if (uuid == ROOT_ID)
return NULL;
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->uuid() == uuid) {
return elem;
}
}
}
return NULL;
}
UML::Element * EditorViewScene::getElemByModelIndex(const QModelIndex &ind)
{
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->index() == ind)
return elem;
}
}
Q_ASSERT(!"Element not found");
return NULL;
}
void EditorViewScene::dragEnterEvent ( QGraphicsSceneDragDropEvent * event )
{
const QMimeData *mimeData = event->mimeData();
if (mimeData->hasFormat("application/x-real-uml-data"))
QGraphicsScene::dragEnterEvent(event);
else
event->ignore();
}
void EditorViewScene::dragMoveEvent ( QGraphicsSceneDragDropEvent * event )
{
Q_UNUSED(event);
}
void EditorViewScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
Q_UNUSED(event);
}
void EditorViewScene::dropEvent(QGraphicsSceneDragDropEvent * event)
{
Q_ASSERT(mWindow); // Значение mWindow должно быть инициализировано
// отдельно, через конструктор это делать нехорошо,
// поскольку сцена создаётся в сгенерённом ui-шнике.
//если нет ни одной диаграммы, то ниего не создаем.
if (mv_iface->model()->rowCount(QModelIndex()) == 0)
{
return;
}
// Transform mime data to include coordinates.
const QMimeData *mimeData = event->mimeData();
QByteArray itemData = mimeData->data("application/x-real-uml-data");
QDataStream in_stream(&itemData, QIODevice::ReadOnly);
QString uuid = "";
QString pathToItem = "";
QString name;
QPointF pos;
QString metatype;
in_stream >> uuid;
in_stream >> pathToItem;
in_stream >> name;
in_stream >> pos;
QByteArray newItemData;
QDataStream stream(&newItemData, QIODevice::WriteOnly);
UML::Element *newParent = NULL;
// TODO: возможно, это можно сделать проще
UML::Element *e = mWindow->manager()->graphicalObject(qReal::Id::loadFromString(uuid));
// = UML::GUIObjectFactory(type_id);
if (dynamic_cast<UML::NodeElement*>(e)) {
newParent = getElemAt(event->scenePos());
}
if (e) {
delete e;
}
stream << uuid; // uuid
stream << pathToItem;
stream << name;
if (!newParent) {
stream << event->scenePos();
} else {
stream << newParent->mapToItem(newParent, newParent->mapFromScene(event->scenePos()));
}
QMimeData *newMimeData = new QMimeData;
newMimeData->setData("application/x-real-uml-data", newItemData);
if (newParent) {
mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
mv_iface->model()->rowCount(newParent->index()), 0, newParent->index() );
} else {
mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
mv_iface->model()->rowCount(mv_iface->rootIndex()), 0, mv_iface->rootIndex() );
}
delete newMimeData;
}
void EditorViewScene::keyPressEvent( QKeyEvent * event )
{
if (dynamic_cast<QGraphicsTextItem*>(this->focusItem())) {
// Forward event to text editor
QGraphicsScene::keyPressEvent(event);
} else if (event->key() == Qt::Key_Delete) {
// Delete selected elements from scene
mainWindow()->deleteFromScene();
} else
QGraphicsScene::keyPressEvent(event);
}
void EditorViewScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// Let scene update selection and perform other operations
QGraphicsScene::mousePressEvent(event);
if (event->button() != Qt::RightButton)
return;
UML::Element *e = getElemAt(event->scenePos());
if (!e) return;
if (!e->isSelected())
{
clearSelection();
e->setSelected(true);
}
// Menu belongs to scene handler because it can delete elements.
// We cannot not allow elements to commit suicide.
QMenu menu;
menu.addAction(mWindow->ui.actionDeleteFromDiagram);
// FIXME: add check for diagram
// if (selectedItems().count() == 1)
// menu.addAction(window->ui.actionJumpToAvatar);
menu.exec(QCursor::pos());
}
void EditorViewScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
// Double click on a title activates it
if (UML::ElementTitle *title = dynamic_cast<UML::ElementTitle*>(itemAt(event->scenePos()))) {
event->accept();
title->startTextInteraction();
return;
}
else if (UML::NodeElement *element = dynamic_cast<UML::NodeElement*>(itemAt(event->scenePos()))) {
event->accept();
mainWindow()->activateSubdiagram(element->index());
// Now scene is changed from outside. Being a mere mortal I do not
// know whether it is good or not, but what is the destiny of
// workflow after this return?
return;
}
}
QGraphicsScene::mouseDoubleClickEvent(event);
}
UML::Element* EditorViewScene::getElemAt(QPointF const &position)
{
foreach (QGraphicsItem *item, items(position)) {
UML::Element *e = dynamic_cast<UML::Element *>(item);
if (e)
return e;
}
return NULL;
}
QPersistentModelIndex EditorViewScene::rootItem()
{
return mv_iface->rootIndex();
}
void EditorViewScene::setMainWindow(qReal::MainWindow *mainWindow)
{
mWindow = mainWindow;
}
qReal::MainWindow *EditorViewScene::mainWindow() const
{
return mWindow;
}
<commit_msg>Do not activate already activated item<commit_after>/** @file editorviewscene.cpp
* @brief Сцена для отрисовки объектов
* */
#include "editorviewscene.h"
#include <QGraphicsTextItem>
#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "mainwindow.h"
#include "../mainwindow/mainwindow.h"
using namespace qReal;
EditorViewScene::EditorViewScene(QObject * parent)
: QGraphicsScene(parent), mWindow(NULL)
{
setItemIndexMethod(NoIndex);
setEnabled(false);
}
void EditorViewScene::setEnabled(bool enabled)
{
foreach (QGraphicsView *view, views())
{
view->setEnabled(enabled);
}
}
void EditorViewScene::clearScene()
{
QList < QGraphicsItem * >list = items();
QList < QGraphicsItem * >::Iterator it = list.begin();
for (; it != list.end(); ++it) {
removeItem(*it);
}
}
UML::Element * EditorViewScene::getElem(qReal::Id const &uuid)
{
if (uuid == ROOT_ID)
return NULL;
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->uuid() == uuid) {
return elem;
}
}
}
return NULL;
}
UML::Element * EditorViewScene::getElemByModelIndex(const QModelIndex &ind)
{
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->index() == ind)
return elem;
}
}
Q_ASSERT(!"Element not found");
return NULL;
}
void EditorViewScene::dragEnterEvent ( QGraphicsSceneDragDropEvent * event )
{
const QMimeData *mimeData = event->mimeData();
if (mimeData->hasFormat("application/x-real-uml-data"))
QGraphicsScene::dragEnterEvent(event);
else
event->ignore();
}
void EditorViewScene::dragMoveEvent ( QGraphicsSceneDragDropEvent * event )
{
Q_UNUSED(event);
}
void EditorViewScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
Q_UNUSED(event);
}
void EditorViewScene::dropEvent(QGraphicsSceneDragDropEvent * event)
{
Q_ASSERT(mWindow); // Значение mWindow должно быть инициализировано
// отдельно, через конструктор это делать нехорошо,
// поскольку сцена создаётся в сгенерённом ui-шнике.
//если нет ни одной диаграммы, то ниего не создаем.
if (mv_iface->model()->rowCount(QModelIndex()) == 0)
{
return;
}
// Transform mime data to include coordinates.
const QMimeData *mimeData = event->mimeData();
QByteArray itemData = mimeData->data("application/x-real-uml-data");
QDataStream in_stream(&itemData, QIODevice::ReadOnly);
QString uuid = "";
QString pathToItem = "";
QString name;
QPointF pos;
QString metatype;
in_stream >> uuid;
in_stream >> pathToItem;
in_stream >> name;
in_stream >> pos;
QByteArray newItemData;
QDataStream stream(&newItemData, QIODevice::WriteOnly);
UML::Element *newParent = NULL;
// TODO: возможно, это можно сделать проще
UML::Element *e = mWindow->manager()->graphicalObject(qReal::Id::loadFromString(uuid));
// = UML::GUIObjectFactory(type_id);
if (dynamic_cast<UML::NodeElement*>(e)) {
newParent = getElemAt(event->scenePos());
}
if (e) {
delete e;
}
stream << uuid; // uuid
stream << pathToItem;
stream << name;
if (!newParent) {
stream << event->scenePos();
} else {
stream << newParent->mapToItem(newParent, newParent->mapFromScene(event->scenePos()));
}
QMimeData *newMimeData = new QMimeData;
newMimeData->setData("application/x-real-uml-data", newItemData);
if (newParent) {
mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
mv_iface->model()->rowCount(newParent->index()), 0, newParent->index() );
} else {
mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
mv_iface->model()->rowCount(mv_iface->rootIndex()), 0, mv_iface->rootIndex() );
}
delete newMimeData;
}
void EditorViewScene::keyPressEvent( QKeyEvent * event )
{
if (dynamic_cast<QGraphicsTextItem*>(this->focusItem())) {
// Forward event to text editor
QGraphicsScene::keyPressEvent(event);
} else if (event->key() == Qt::Key_Delete) {
// Delete selected elements from scene
mainWindow()->deleteFromScene();
} else
QGraphicsScene::keyPressEvent(event);
}
void EditorViewScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// Let scene update selection and perform other operations
QGraphicsScene::mousePressEvent(event);
if (event->button() != Qt::RightButton)
return;
UML::Element *e = getElemAt(event->scenePos());
if (!e) return;
if (!e->isSelected())
{
clearSelection();
e->setSelected(true);
}
// Menu belongs to scene handler because it can delete elements.
// We cannot not allow elements to commit suicide.
QMenu menu;
menu.addAction(mWindow->ui.actionDeleteFromDiagram);
// FIXME: add check for diagram
// if (selectedItems().count() == 1)
// menu.addAction(window->ui.actionJumpToAvatar);
menu.exec(QCursor::pos());
}
void EditorViewScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
// Double click on a title activates it
if (UML::ElementTitle *title = dynamic_cast<UML::ElementTitle*>(itemAt(event->scenePos()))) {
if (!title->hasFocus()) // Do not activate already activated item
{
event->accept();
title->startTextInteraction();
return;
}
}
else if (UML::NodeElement *element = dynamic_cast<UML::NodeElement*>(itemAt(event->scenePos()))) {
event->accept();
mainWindow()->activateSubdiagram(element->index());
// Now scene is changed from outside. Being a mere mortal I do not
// know whether it is good or not, but what is the destiny of
// workflow after this return?
return;
}
}
QGraphicsScene::mouseDoubleClickEvent(event);
}
UML::Element* EditorViewScene::getElemAt(QPointF const &position)
{
foreach (QGraphicsItem *item, items(position)) {
UML::Element *e = dynamic_cast<UML::Element *>(item);
if (e)
return e;
}
return NULL;
}
QPersistentModelIndex EditorViewScene::rootItem()
{
return mv_iface->rootIndex();
}
void EditorViewScene::setMainWindow(qReal::MainWindow *mainWindow)
{
mWindow = mainWindow;
}
qReal::MainWindow *EditorViewScene::mainWindow() const
{
return mWindow;
}
<|endoftext|> |
<commit_before>/**
Copyright 2015 Joachim Wolff
Master Thesis
Tutor: Fabrizio Costa
Winter semester 2015/2016
Chair of Bioinformatics
Department of Computer Science
Faculty of Engineering
Albert-Ludwig-University Freiburg im Breisgau
**/
#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
#ifdef OPENMP
#include <omp.h>
#endif
#include "inverseIndex.h"
class sort_map {
public:
size_t key;
size_t val;
};
bool mapSortDescByValue(const sort_map& a, const sort_map& b) {
return a.val > b.val;
};
InverseIndex::InverseIndex(size_t pNumberOfHashFunctions, size_t pBlockSize,
size_t pNumberOfCores, size_t pChunkSize,
size_t pMaxBinSize, size_t pMinimalBlocksInCommon,
size_t pExcessFactor, size_t pMaximalNumberOfHashCollisions, size_t pBloomierFilter) {
mNumberOfHashFunctions = pNumberOfHashFunctions;
mBlockSize = pBlockSize;
mNumberOfCores = pNumberOfCores;
mChunkSize = pChunkSize;
mMaxBinSize = pMaxBinSize;
mMinimalBlocksInCommon = pMinimalBlocksInCommon;
mExcessFactor = pExcessFactor;
mMaximalNumberOfHashCollisions = pMaximalNumberOfHashCollisions;
mSignatureStorage = new umap_uniqueElement();
mHash = new Hash();
size_t inverseIndexSize = ceil(((float) mNumberOfHashFunctions / (float) mBlockSize)+1);
if (pBloomierFilter) {
std::cout << "Using bloomier filter. " << std::endl;
mInverseIndexStorage = new InverseIndexStorageBloomierFilter(inverseIndexSize, mMaxBinSize);
} else {
std::cout << "Using unorderedMap. " << std::endl;
mInverseIndexStorage = new InverseIndexStorageUnorderedMap(inverseIndexSize, mMaxBinSize);
}
// mInverseIndexUmapVector = new vector__umapVector(inverseIndexSize);
// mInverseIndexUmapVector->resize(inverseIndexSize);
}
InverseIndex::~InverseIndex() {
for (auto it = (*mSignatureStorage).begin(); it != (*mSignatureStorage).end(); ++it) {
delete it->second->instances;
delete it->second->signature;
delete it->second;
}
delete mSignatureStorage;
// delete mInverseIndexUmapVector;
}
// compute the signature for one instance
vsize_t* InverseIndex::computeSignature(const SparseMatrixFloat* pRawData, const size_t pInstance) {
vsize_t signatureHash;
signatureHash.reserve(mNumberOfHashFunctions);
for(size_t j = 0; j < mNumberOfHashFunctions; ++j) {
size_t minHashValue = MAX_VALUE;
for (size_t i = 0; i < pRawData->getSizeOfInstance(pInstance); ++i) {
// hash(size_t pKey, size_t pModulo, size_t pSeed)
size_t hashValue = mHash->hash((pRawData->getNextElement(pInstance, i) +1), (j+1), MAX_VALUE);
if (hashValue < minHashValue) {
minHashValue = hashValue;
}
}
signatureHash[j] = minHashValue;
}
// reduce number of hash values by a factor of blockSize
size_t k = 0;
vsize_t* signature = new vsize_t();
signature->reserve((mNumberOfHashFunctions / mBlockSize) + 1);
while (k < (mNumberOfHashFunctions)) {
// use computed hash value as a seed for the next computation
size_t signatureBlockValue = signatureHash[k];
for (size_t j = 0; j < mBlockSize; ++j) {
signatureBlockValue = mHash->hash((signatureHash[k+j]), signatureBlockValue, MAX_VALUE);
}
signature->push_back(signatureBlockValue);
k += mBlockSize;
}
return signature;
}
umap_uniqueElement* InverseIndex::computeSignatureMap(const SparseMatrixFloat* pRawData) {
mDoubleElementsQueryCount = 0;
const size_t sizeOfInstances = pRawData->size();
umap_uniqueElement* instanceSignature = new umap_uniqueElement();
(*instanceSignature).reserve(sizeOfInstances);
if (mChunkSize <= 0) {
mChunkSize = ceil(pRawData->size() / static_cast<float>(mNumberOfCores));
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for(size_t index = 0; index < pRawData->size(); ++index) {
// vsize_t* features = pRawData->getFeatureRow(index);
// compute unique id
size_t signatureId = 0;
for (size_t j = 0; j < pRawData->getSizeOfInstance(index); ++j) {
signatureId = mHash->hash((pRawData->getNextElement(index, j) +1), (signatureId+1), MAX_VALUE);
}
// signature is in storage &&
auto signatureIt = (*mSignatureStorage).find(signatureId);
if (signatureIt != (*mSignatureStorage).end() && (instanceSignature->find(signatureId) != instanceSignature->end())) {
#pragma omp critical
{
instanceSignature->operator[](signatureId) = (*mSignatureStorage)[signatureId];
instanceSignature->operator[](signatureId)->instances->push_back(index);
mDoubleElementsQueryCount += (*mSignatureStorage)[signatureId]->instances->size();
}
continue;
}
// for every hash function: compute the hash values of all features and take the minimum of these
// as the hash value for one hash function --> h_j(x) = argmin (x_i of x) f_j(x_i)
vsize_t* signature = computeSignature(pRawData, index);
#pragma omp critical
{
if (instanceSignature->find(signatureId) == instanceSignature->end()) {
vsize_t* doubleInstanceVector = new vsize_t(1);
(*doubleInstanceVector)[0] = index;
uniqueElement* element = new uniqueElement();;
element->instances = doubleInstanceVector;
element->signature = signature;
instanceSignature->operator[](signatureId) = element;
} else {
instanceSignature->operator[](signatureId)->instances->push_back(index);
mDoubleElementsQueryCount += 1;
}
}
}
return instanceSignature;
}
void InverseIndex::fit(const SparseMatrixFloat* pRawData) {
// std::cout << "158" << std::endl;
mDoubleElementsStorageCount = 0;
// size_t inverseIndexSize = ceil(((float) mNumberOfHashFunctions / (float) mBlockSize)+1);
// mInverseIndexUmapVector->resize(inverseIndexSize);
// mInverseIndexStorage->
if (mChunkSize <= 0) {
mChunkSize = ceil(pRawData->size() / static_cast<float>(mNumberOfCores));
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
// std::cout << "170" << std::endl;
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for (size_t index = 0; index < pRawData->size(); ++index) {
size_t signatureId = 0;
// std::cout << "176" << std::endl;
for (size_t j = 0; j < pRawData->getSizeOfInstance(index); ++j) {
// std::cout << "179" << std::endl;
signatureId = mHash->hash((pRawData->getNextElement(index, j) +1), (signatureId+1), MAX_VALUE);
// std::cout << "182" << std::endl;
}
// std::cout << "185" << std::endl;
vsize_t* signature;
auto itSignatureStorage = mSignatureStorage->find(signatureId);
// std::cout << "189" << std::endl;
if (itSignatureStorage == mSignatureStorage->end()) {
// std::cout << "192" << std::endl;
signature = computeSignature(pRawData, index);
} else {
// std::cout << "196" << std::endl;
signature = itSignatureStorage->second->signature;
}
// std::cout << "200" << std::endl;
#pragma omp critical
{
if (itSignatureStorage == mSignatureStorage->end()) {
vsize_t* doubleInstanceVector = new vsize_t(1);
(*doubleInstanceVector)[0] = index;
uniqueElement* element = new uniqueElement();
element->instances = doubleInstanceVector;
element->signature = signature;
mSignatureStorage->operator[](signatureId) = element;
} else {
mSignatureStorage->operator[](signatureId)->instances->push_back(index);
mDoubleElementsStorageCount += 1;
}
for (size_t j = 0; j < signature->size(); ++j) {
std::cout << "203" << std::endl;
mInverseIndexStorage->insert(j, (*signature)[j], index);
std::cout << "206" << std::endl;
}
}
}
std::cout << "227" << std::endl;
// mInverseIndexStorage->create();
}
neighborhood* InverseIndex::kneighbors(const umap_uniqueElement* pSignaturesMap,
const int pNneighborhood, const bool pDoubleElementsStorageCount) {
size_t doubleElements = 0;
if (pDoubleElementsStorageCount) {
doubleElements = mDoubleElementsStorageCount;
} else {
doubleElements = mDoubleElementsQueryCount;
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
vvint* neighbors = new vvint();
vvfloat* distances = new vvfloat();
neighbors->resize(pSignaturesMap->size()+doubleElements);
distances->resize(pSignaturesMap->size()+doubleElements);
if (mChunkSize <= 0) {
// mChunkSize = ceil(mInverseIndexUmapVector->size() / static_cast<float>(mNumberOfCores));
mChunkSize = ceil(mInverseIndexStorage->size() / static_cast<float>(mNumberOfCores));
// mInverseIndexStorage
}
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for (size_t i = 0; i < pSignaturesMap->size(); ++i) {
umap_uniqueElement::const_iterator instanceId = pSignaturesMap->begin();
std::advance(instanceId, i);
std::unordered_map<size_t, size_t> neighborhood;
const vsize_t* signature = instanceId->second->signature;
for (size_t j = 0; j < signature->size(); ++j) {
size_t hashID = (*signature)[j];
if (hashID != 0 && hashID != MAX_VALUE) {
size_t collisionSize = 0;
vsize_t* instances = mInverseIndexStorage->getElement(j, hashID);
// umapVector::const_iterator instances = mInverseIndexUmapVector->at(j).find(hashID);
if (instances->size() != 0) {
collisionSize = instances->size();
} else {
continue;
}
if (collisionSize < mMaxBinSize && collisionSize > 0) {
for (size_t k = 0; k < instances->size(); ++k) {
neighborhood[instances->at(k)] += 1;
}
}
}
}
std::vector< sort_map > neighborhoodVectorForSorting;
for (auto it = neighborhood.begin(); it != neighborhood.end(); ++it) {
sort_map mapForSorting;
mapForSorting.key = (*it).first;
mapForSorting.val = (*it).second;
neighborhoodVectorForSorting.push_back(mapForSorting);
}
size_t numberOfElementsToSort = pNneighborhood;
if (pNneighborhood > neighborhoodVectorForSorting.size()) {
numberOfElementsToSort = neighborhoodVectorForSorting.size();
}
std::partial_sort(neighborhoodVectorForSorting.begin(), neighborhoodVectorForSorting.begin()+numberOfElementsToSort, neighborhoodVectorForSorting.end(), mapSortDescByValue);
size_t sizeOfNeighborhoodAdjusted;
if (pNneighborhood == MAX_VALUE) {
sizeOfNeighborhoodAdjusted = std::min(static_cast<size_t>(pNneighborhood), neighborhoodVectorForSorting.size());
} else {
sizeOfNeighborhoodAdjusted = std::min(static_cast<size_t>(pNneighborhood * mExcessFactor), neighborhoodVectorForSorting.size());
}
size_t count = 0;
vvint* neighborsForThisInstance = new vvint(instanceId->second->instances->size());
vvfloat* distancesForThisInstance = new vvfloat(instanceId->second->instances->size());
for (size_t j = 0; j < neighborsForThisInstance->size(); ++j) {
vint neighborhoodVector;
std::vector<float> distanceVector;
if (neighborhoodVectorForSorting[0].key != instanceId->second->instances->operator[](j)) {
neighborhoodVector.push_back(instanceId->second->instances->operator[](j));
distanceVector.push_back(0);
++count;
}
for (auto it = neighborhoodVectorForSorting.begin();
it != neighborhoodVectorForSorting.end(); ++it) {
neighborhoodVector.push_back((*it).key);
distanceVector.push_back(1 - ((*it).val / static_cast<float>(mMaximalNumberOfHashCollisions)));
++count;
if (count >= sizeOfNeighborhoodAdjusted) {
(*neighborsForThisInstance)[j] = neighborhoodVector;
(*distancesForThisInstance)[j] = distanceVector;
break;
}
}
}
#pragma omp critical
{
for (size_t j = 0; j < instanceId->second->instances->size(); ++j) {
(*neighbors)[instanceId->second->instances->operator[](j)] = (*neighborsForThisInstance)[j];
(*distances)[instanceId->second->instances->operator[](j)] = (*distancesForThisInstance)[j];
}
}
}
neighborhood* neighborhood_ = new neighborhood();
neighborhood_->neighbors = neighbors;
neighborhood_->distances = distances;
return neighborhood_;
}<commit_msg>Commented debug lines out<commit_after>/**
Copyright 2015 Joachim Wolff
Master Thesis
Tutor: Fabrizio Costa
Winter semester 2015/2016
Chair of Bioinformatics
Department of Computer Science
Faculty of Engineering
Albert-Ludwig-University Freiburg im Breisgau
**/
#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
#ifdef OPENMP
#include <omp.h>
#endif
#include "inverseIndex.h"
class sort_map {
public:
size_t key;
size_t val;
};
bool mapSortDescByValue(const sort_map& a, const sort_map& b) {
return a.val > b.val;
};
InverseIndex::InverseIndex(size_t pNumberOfHashFunctions, size_t pBlockSize,
size_t pNumberOfCores, size_t pChunkSize,
size_t pMaxBinSize, size_t pMinimalBlocksInCommon,
size_t pExcessFactor, size_t pMaximalNumberOfHashCollisions, size_t pBloomierFilter) {
mNumberOfHashFunctions = pNumberOfHashFunctions;
mBlockSize = pBlockSize;
mNumberOfCores = pNumberOfCores;
mChunkSize = pChunkSize;
mMaxBinSize = pMaxBinSize;
mMinimalBlocksInCommon = pMinimalBlocksInCommon;
mExcessFactor = pExcessFactor;
mMaximalNumberOfHashCollisions = pMaximalNumberOfHashCollisions;
mSignatureStorage = new umap_uniqueElement();
mHash = new Hash();
size_t inverseIndexSize = ceil(((float) mNumberOfHashFunctions / (float) mBlockSize)+1);
if (pBloomierFilter) {
std::cout << "Using bloomier filter. " << std::endl;
mInverseIndexStorage = new InverseIndexStorageBloomierFilter(inverseIndexSize, mMaxBinSize);
} else {
std::cout << "Using unorderedMap. " << std::endl;
mInverseIndexStorage = new InverseIndexStorageUnorderedMap(inverseIndexSize, mMaxBinSize);
}
// mInverseIndexUmapVector = new vector__umapVector(inverseIndexSize);
// mInverseIndexUmapVector->resize(inverseIndexSize);
}
InverseIndex::~InverseIndex() {
for (auto it = (*mSignatureStorage).begin(); it != (*mSignatureStorage).end(); ++it) {
delete it->second->instances;
delete it->second->signature;
delete it->second;
}
delete mSignatureStorage;
// delete mInverseIndexUmapVector;
}
// compute the signature for one instance
vsize_t* InverseIndex::computeSignature(const SparseMatrixFloat* pRawData, const size_t pInstance) {
vsize_t signatureHash;
signatureHash.reserve(mNumberOfHashFunctions);
for(size_t j = 0; j < mNumberOfHashFunctions; ++j) {
size_t minHashValue = MAX_VALUE;
for (size_t i = 0; i < pRawData->getSizeOfInstance(pInstance); ++i) {
// hash(size_t pKey, size_t pModulo, size_t pSeed)
size_t hashValue = mHash->hash((pRawData->getNextElement(pInstance, i) +1), (j+1), MAX_VALUE);
if (hashValue < minHashValue) {
minHashValue = hashValue;
}
}
signatureHash[j] = minHashValue;
}
// reduce number of hash values by a factor of blockSize
size_t k = 0;
vsize_t* signature = new vsize_t();
signature->reserve((mNumberOfHashFunctions / mBlockSize) + 1);
while (k < (mNumberOfHashFunctions)) {
// use computed hash value as a seed for the next computation
size_t signatureBlockValue = signatureHash[k];
for (size_t j = 0; j < mBlockSize; ++j) {
signatureBlockValue = mHash->hash((signatureHash[k+j]), signatureBlockValue, MAX_VALUE);
}
signature->push_back(signatureBlockValue);
k += mBlockSize;
}
return signature;
}
umap_uniqueElement* InverseIndex::computeSignatureMap(const SparseMatrixFloat* pRawData) {
mDoubleElementsQueryCount = 0;
const size_t sizeOfInstances = pRawData->size();
umap_uniqueElement* instanceSignature = new umap_uniqueElement();
(*instanceSignature).reserve(sizeOfInstances);
if (mChunkSize <= 0) {
mChunkSize = ceil(pRawData->size() / static_cast<float>(mNumberOfCores));
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for(size_t index = 0; index < pRawData->size(); ++index) {
// vsize_t* features = pRawData->getFeatureRow(index);
// compute unique id
size_t signatureId = 0;
for (size_t j = 0; j < pRawData->getSizeOfInstance(index); ++j) {
signatureId = mHash->hash((pRawData->getNextElement(index, j) +1), (signatureId+1), MAX_VALUE);
}
// signature is in storage &&
auto signatureIt = (*mSignatureStorage).find(signatureId);
if (signatureIt != (*mSignatureStorage).end() && (instanceSignature->find(signatureId) != instanceSignature->end())) {
#pragma omp critical
{
instanceSignature->operator[](signatureId) = (*mSignatureStorage)[signatureId];
instanceSignature->operator[](signatureId)->instances->push_back(index);
mDoubleElementsQueryCount += (*mSignatureStorage)[signatureId]->instances->size();
}
continue;
}
// for every hash function: compute the hash values of all features and take the minimum of these
// as the hash value for one hash function --> h_j(x) = argmin (x_i of x) f_j(x_i)
vsize_t* signature = computeSignature(pRawData, index);
#pragma omp critical
{
if (instanceSignature->find(signatureId) == instanceSignature->end()) {
vsize_t* doubleInstanceVector = new vsize_t(1);
(*doubleInstanceVector)[0] = index;
uniqueElement* element = new uniqueElement();;
element->instances = doubleInstanceVector;
element->signature = signature;
instanceSignature->operator[](signatureId) = element;
} else {
instanceSignature->operator[](signatureId)->instances->push_back(index);
mDoubleElementsQueryCount += 1;
}
}
}
return instanceSignature;
}
void InverseIndex::fit(const SparseMatrixFloat* pRawData) {
// std::cout << "158" << std::endl;
mDoubleElementsStorageCount = 0;
// size_t inverseIndexSize = ceil(((float) mNumberOfHashFunctions / (float) mBlockSize)+1);
// mInverseIndexUmapVector->resize(inverseIndexSize);
// mInverseIndexStorage->
if (mChunkSize <= 0) {
mChunkSize = ceil(pRawData->size() / static_cast<float>(mNumberOfCores));
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
// std::cout << "170" << std::endl;
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for (size_t index = 0; index < pRawData->size(); ++index) {
size_t signatureId = 0;
// std::cout << "176" << std::endl;
for (size_t j = 0; j < pRawData->getSizeOfInstance(index); ++j) {
// std::cout << "179" << std::endl;
signatureId = mHash->hash((pRawData->getNextElement(index, j) +1), (signatureId+1), MAX_VALUE);
// std::cout << "182" << std::endl;
}
// std::cout << "185" << std::endl;
vsize_t* signature;
auto itSignatureStorage = mSignatureStorage->find(signatureId);
// std::cout << "189" << std::endl;
if (itSignatureStorage == mSignatureStorage->end()) {
// std::cout << "192" << std::endl;
signature = computeSignature(pRawData, index);
} else {
// std::cout << "196" << std::endl;
signature = itSignatureStorage->second->signature;
}
// std::cout << "200" << std::endl;
#pragma omp critical
{
if (itSignatureStorage == mSignatureStorage->end()) {
vsize_t* doubleInstanceVector = new vsize_t(1);
(*doubleInstanceVector)[0] = index;
uniqueElement* element = new uniqueElement();
element->instances = doubleInstanceVector;
element->signature = signature;
mSignatureStorage->operator[](signatureId) = element;
} else {
mSignatureStorage->operator[](signatureId)->instances->push_back(index);
mDoubleElementsStorageCount += 1;
}
for (size_t j = 0; j < signature->size(); ++j) {
// std::cout << "203" << std::endl;
mInverseIndexStorage->insert(j, (*signature)[j], index);
// std::cout << "206" << std::endl;
}
}
}
// std::cout << "227" << std::endl;
// mInverseIndexStorage->create();
}
neighborhood* InverseIndex::kneighbors(const umap_uniqueElement* pSignaturesMap,
const int pNneighborhood, const bool pDoubleElementsStorageCount) {
size_t doubleElements = 0;
if (pDoubleElementsStorageCount) {
doubleElements = mDoubleElementsStorageCount;
} else {
doubleElements = mDoubleElementsQueryCount;
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
vvint* neighbors = new vvint();
vvfloat* distances = new vvfloat();
neighbors->resize(pSignaturesMap->size()+doubleElements);
distances->resize(pSignaturesMap->size()+doubleElements);
if (mChunkSize <= 0) {
// mChunkSize = ceil(mInverseIndexUmapVector->size() / static_cast<float>(mNumberOfCores));
mChunkSize = ceil(mInverseIndexStorage->size() / static_cast<float>(mNumberOfCores));
// mInverseIndexStorage
}
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for (size_t i = 0; i < pSignaturesMap->size(); ++i) {
umap_uniqueElement::const_iterator instanceId = pSignaturesMap->begin();
std::advance(instanceId, i);
std::unordered_map<size_t, size_t> neighborhood;
const vsize_t* signature = instanceId->second->signature;
for (size_t j = 0; j < signature->size(); ++j) {
size_t hashID = (*signature)[j];
if (hashID != 0 && hashID != MAX_VALUE) {
size_t collisionSize = 0;
vsize_t* instances = mInverseIndexStorage->getElement(j, hashID);
// umapVector::const_iterator instances = mInverseIndexUmapVector->at(j).find(hashID);
if (instances->size() != 0) {
collisionSize = instances->size();
} else {
continue;
}
if (collisionSize < mMaxBinSize && collisionSize > 0) {
for (size_t k = 0; k < instances->size(); ++k) {
neighborhood[instances->at(k)] += 1;
}
}
}
}
std::vector< sort_map > neighborhoodVectorForSorting;
for (auto it = neighborhood.begin(); it != neighborhood.end(); ++it) {
sort_map mapForSorting;
mapForSorting.key = (*it).first;
mapForSorting.val = (*it).second;
neighborhoodVectorForSorting.push_back(mapForSorting);
}
size_t numberOfElementsToSort = pNneighborhood;
if (pNneighborhood > neighborhoodVectorForSorting.size()) {
numberOfElementsToSort = neighborhoodVectorForSorting.size();
}
std::partial_sort(neighborhoodVectorForSorting.begin(), neighborhoodVectorForSorting.begin()+numberOfElementsToSort, neighborhoodVectorForSorting.end(), mapSortDescByValue);
size_t sizeOfNeighborhoodAdjusted;
if (pNneighborhood == MAX_VALUE) {
sizeOfNeighborhoodAdjusted = std::min(static_cast<size_t>(pNneighborhood), neighborhoodVectorForSorting.size());
} else {
sizeOfNeighborhoodAdjusted = std::min(static_cast<size_t>(pNneighborhood * mExcessFactor), neighborhoodVectorForSorting.size());
}
size_t count = 0;
vvint* neighborsForThisInstance = new vvint(instanceId->second->instances->size());
vvfloat* distancesForThisInstance = new vvfloat(instanceId->second->instances->size());
for (size_t j = 0; j < neighborsForThisInstance->size(); ++j) {
vint neighborhoodVector;
std::vector<float> distanceVector;
if (neighborhoodVectorForSorting[0].key != instanceId->second->instances->operator[](j)) {
neighborhoodVector.push_back(instanceId->second->instances->operator[](j));
distanceVector.push_back(0);
++count;
}
for (auto it = neighborhoodVectorForSorting.begin();
it != neighborhoodVectorForSorting.end(); ++it) {
neighborhoodVector.push_back((*it).key);
distanceVector.push_back(1 - ((*it).val / static_cast<float>(mMaximalNumberOfHashCollisions)));
++count;
if (count >= sizeOfNeighborhoodAdjusted) {
(*neighborsForThisInstance)[j] = neighborhoodVector;
(*distancesForThisInstance)[j] = distanceVector;
break;
}
}
}
#pragma omp critical
{
for (size_t j = 0; j < instanceId->second->instances->size(); ++j) {
(*neighbors)[instanceId->second->instances->operator[](j)] = (*neighborsForThisInstance)[j];
(*distances)[instanceId->second->instances->operator[](j)] = (*distancesForThisInstance)[j];
}
}
}
neighborhood* neighborhood_ = new neighborhood();
neighborhood_->neighbors = neighbors;
neighborhood_->distances = distances;
return neighborhood_;
}<|endoftext|> |
<commit_before>//
// Copyright (C) 2007-2009 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007-2009 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Keith Kyzivat <kkyzivat AT SIPez DOT com>
// SYSTEM INCLUDES
#include <os/OsIntTypes.h>
#include <os/OsStatus.h>
#include <os/OsSysLog.h>
// APPLICATION INCLUDES
#include "mp/MpMMTimer.h"
#if defined(WIN32) // [ WIN32
# include "mp/MpMMTimerWnt.h"
# define DEFAULT_TIMER_CLASS MpMMTimerWnt
#elif 0 //defined(__pingtel_on_posix__) // ][ POSIX
# include "mp/MpMMTimerPosix.h"
# define DEFAULT_TIMER_CLASS MpMMTimerPosix
#else // ][ Unsupported platform
# error Unsupported target platform.
#endif // ] Unsupported platform
// DEFINES
// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
/* //////////////////////////////// PUBLIC //////////////////////////////// */
/* =============================== CREATORS =============================== */
MpMMTimer *MpMMTimer::create(MMTimerType type, const UtlString &name)
{
if (name.isNull())
{
return new DEFAULT_TIMER_CLASS(type);
}
#ifdef WIN32 // [
else if (name.compareTo(MpMMTimerWnt::TYPE, UtlString::ignoreCase))
{
return new MpMMTimerWnt(type);
}
#endif // WIN32 ]
#if 0 //def __pingtel_on_posix__ // [
else if (name.compareTo(MpMMTimerPosix::TYPE, UtlString::ignoreCase))
{
return new MpMMTimerPosix(type);
}
#endif // __pingtel_on_posix__ ]
return NULL;
}
MpMMTimer::~MpMMTimer()
{
}
/* ============================= MANIPULATORS ============================= */
OsStatus MpMMTimer::setNotification(OsNotification* notification)
{
return OS_INVALID_STATE;
}
OsStatus MpMMTimer::waitForNextTick()
{
OsStatus ret =
(mTimerType != Linear) ? OS_INVALID_STATE : OS_NOT_YET_IMPLEMENTED;
return ret;
}
/* ============================== ACCESSORS =============================== */
OsStatus MpMMTimer::getResolution(unsigned& resolution)
{
return OS_NOT_YET_IMPLEMENTED;
}
OsStatus MpMMTimer::getPeriodRange(unsigned* pMinUSecs,
unsigned* pMaxUSecs)
{
return OS_NOT_YET_IMPLEMENTED;
}
/* =============================== INQUIRY ================================ */
/* ////////////////////////////// PROTECTED /////////////////////////////// */
/* /////////////////////////////// PRIVATE //////////////////////////////// */
/* ============================== FUNCTIONS =============================== */
<commit_msg>sipXmediaLib: Fix compilation under Linux, while MpMMTimerPosix is not implemented.<commit_after>//
// Copyright (C) 2007-2009 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007-2009 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Keith Kyzivat <kkyzivat AT SIPez DOT com>
// SYSTEM INCLUDES
#include <os/OsIntTypes.h>
#include <os/OsStatus.h>
#include <os/OsSysLog.h>
// APPLICATION INCLUDES
#include "mp/MpMMTimer.h"
#if defined(WIN32) // [ WIN32
# include "mp/MpMMTimerWnt.h"
# define DEFAULT_TIMER_CLASS MpMMTimerWnt
#elif 0 //defined(__pingtel_on_posix__) // ][ POSIX
# include "mp/MpMMTimerPosix.h"
# define DEFAULT_TIMER_CLASS MpMMTimerPosix
#else // ][ Unsupported platform
# error Unsupported target platform.
#endif // ] Unsupported platform
// DEFINES
// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
/* //////////////////////////////// PUBLIC //////////////////////////////// */
/* =============================== CREATORS =============================== */
MpMMTimer *MpMMTimer::create(MMTimerType type, const UtlString &name)
{
#ifdef WIN32 // [
if (name.isNull())
{
return new DEFAULT_TIMER_CLASS(type);
}
//#ifdef WIN32 // [
else if (name.compareTo(MpMMTimerWnt::TYPE, UtlString::ignoreCase))
{
return new MpMMTimerWnt(type);
}
#endif // WIN32 ]
#if 0 //def __pingtel_on_posix__ // [
else if (name.compareTo(MpMMTimerPosix::TYPE, UtlString::ignoreCase))
{
return new MpMMTimerPosix(type);
}
#endif // __pingtel_on_posix__ ]
return NULL;
}
MpMMTimer::~MpMMTimer()
{
}
/* ============================= MANIPULATORS ============================= */
OsStatus MpMMTimer::setNotification(OsNotification* notification)
{
return OS_INVALID_STATE;
}
OsStatus MpMMTimer::waitForNextTick()
{
OsStatus ret =
(mTimerType != Linear) ? OS_INVALID_STATE : OS_NOT_YET_IMPLEMENTED;
return ret;
}
/* ============================== ACCESSORS =============================== */
OsStatus MpMMTimer::getResolution(unsigned& resolution)
{
return OS_NOT_YET_IMPLEMENTED;
}
OsStatus MpMMTimer::getPeriodRange(unsigned* pMinUSecs,
unsigned* pMaxUSecs)
{
return OS_NOT_YET_IMPLEMENTED;
}
/* =============================== INQUIRY ================================ */
/* ////////////////////////////// PROTECTED /////////////////////////////// */
/* /////////////////////////////// PRIVATE //////////////////////////////// */
/* ============================== FUNCTIONS =============================== */
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Illustrates how to use worker threads that issue completion callbacks
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/threading/worker_pool.h"
#include "net/base/completion_callback.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
typedef PlatformTest TestCompletionCallbackTest;
using net::OldCompletionCallback;
const int kMagicResult = 8888;
// ExampleEmployer is a toy version of HostResolver
// TODO: restore damage done in extracting example from real code
// (e.g. bring back real destructor, bring back comments)
class ExampleEmployer {
public:
ExampleEmployer();
~ExampleEmployer();
// Do some imaginary work on a worker thread;
// when done, worker posts callback on the original thread.
// Returns true on success
bool DoSomething(const net::CompletionCallback& callback);
private:
class ExampleWorker;
friend class ExampleWorker;
scoped_refptr<ExampleWorker> request_;
DISALLOW_COPY_AND_ASSIGN(ExampleEmployer);
};
// Helper class; this is how ExampleEmployer puts work on a different thread
class ExampleEmployer::ExampleWorker
: public base::RefCountedThreadSafe<ExampleWorker> {
public:
ExampleWorker(ExampleEmployer* employer,
const net::CompletionCallback& callback)
: employer_(employer), callback_(callback),
origin_loop_(MessageLoop::current()) {
}
void DoWork();
void DoCallback();
private:
friend class base::RefCountedThreadSafe<ExampleWorker>;
~ExampleWorker() {}
// Only used on the origin thread (where DoSomething was called).
ExampleEmployer* employer_;
net::CompletionCallback callback_;
// Used to post ourselves onto the origin thread.
base::Lock origin_loop_lock_;
MessageLoop* origin_loop_;
};
void ExampleEmployer::ExampleWorker::DoWork() {
// Running on the worker thread
// In a real worker thread, some work would be done here.
// Pretend it is, and send the completion callback.
// The origin loop could go away while we are trying to post to it, so we
// need to call its PostTask method inside a lock. See ~ExampleEmployer.
{
base::AutoLock locked(origin_loop_lock_);
if (origin_loop_)
origin_loop_->PostTask(FROM_HERE,
base::Bind(&ExampleWorker::DoCallback, this));
}
}
void ExampleEmployer::ExampleWorker::DoCallback() {
// Running on the origin thread.
// Drop the employer_'s reference to us. Do this before running the
// callback since the callback might result in the employer being
// destroyed.
employer_->request_ = NULL;
callback_.Run(kMagicResult);
}
ExampleEmployer::ExampleEmployer() {
}
ExampleEmployer::~ExampleEmployer() {
}
bool ExampleEmployer::DoSomething(const net::CompletionCallback& callback) {
DCHECK(!request_) << "already in use";
request_ = new ExampleWorker(this, callback);
// Dispatch to worker thread...
if (!base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&ExampleWorker::DoWork, request_.get()),
true)) {
NOTREACHED();
request_ = NULL;
return false;
}
return true;
}
TEST_F(TestCompletionCallbackTest, Simple) {
ExampleEmployer boss;
net::TestCompletionCallback callback;
bool queued = boss.DoSomething(callback.callback());
EXPECT_EQ(queued, true);
int result = callback.WaitForResult();
EXPECT_EQ(result, kMagicResult);
}
// TODO: test deleting ExampleEmployer while work outstanding
<commit_msg>base::Bind: Remove an unused using statement.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Illustrates how to use worker threads that issue completion callbacks
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/threading/worker_pool.h"
#include "net/base/completion_callback.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
typedef PlatformTest TestCompletionCallbackTest;
const int kMagicResult = 8888;
// ExampleEmployer is a toy version of HostResolver
// TODO: restore damage done in extracting example from real code
// (e.g. bring back real destructor, bring back comments)
class ExampleEmployer {
public:
ExampleEmployer();
~ExampleEmployer();
// Do some imaginary work on a worker thread;
// when done, worker posts callback on the original thread.
// Returns true on success
bool DoSomething(const net::CompletionCallback& callback);
private:
class ExampleWorker;
friend class ExampleWorker;
scoped_refptr<ExampleWorker> request_;
DISALLOW_COPY_AND_ASSIGN(ExampleEmployer);
};
// Helper class; this is how ExampleEmployer puts work on a different thread
class ExampleEmployer::ExampleWorker
: public base::RefCountedThreadSafe<ExampleWorker> {
public:
ExampleWorker(ExampleEmployer* employer,
const net::CompletionCallback& callback)
: employer_(employer), callback_(callback),
origin_loop_(MessageLoop::current()) {
}
void DoWork();
void DoCallback();
private:
friend class base::RefCountedThreadSafe<ExampleWorker>;
~ExampleWorker() {}
// Only used on the origin thread (where DoSomething was called).
ExampleEmployer* employer_;
net::CompletionCallback callback_;
// Used to post ourselves onto the origin thread.
base::Lock origin_loop_lock_;
MessageLoop* origin_loop_;
};
void ExampleEmployer::ExampleWorker::DoWork() {
// Running on the worker thread
// In a real worker thread, some work would be done here.
// Pretend it is, and send the completion callback.
// The origin loop could go away while we are trying to post to it, so we
// need to call its PostTask method inside a lock. See ~ExampleEmployer.
{
base::AutoLock locked(origin_loop_lock_);
if (origin_loop_)
origin_loop_->PostTask(FROM_HERE,
base::Bind(&ExampleWorker::DoCallback, this));
}
}
void ExampleEmployer::ExampleWorker::DoCallback() {
// Running on the origin thread.
// Drop the employer_'s reference to us. Do this before running the
// callback since the callback might result in the employer being
// destroyed.
employer_->request_ = NULL;
callback_.Run(kMagicResult);
}
ExampleEmployer::ExampleEmployer() {
}
ExampleEmployer::~ExampleEmployer() {
}
bool ExampleEmployer::DoSomething(const net::CompletionCallback& callback) {
DCHECK(!request_) << "already in use";
request_ = new ExampleWorker(this, callback);
// Dispatch to worker thread...
if (!base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&ExampleWorker::DoWork, request_.get()),
true)) {
NOTREACHED();
request_ = NULL;
return false;
}
return true;
}
TEST_F(TestCompletionCallbackTest, Simple) {
ExampleEmployer boss;
net::TestCompletionCallback callback;
bool queued = boss.DoSomething(callback.callback());
EXPECT_EQ(queued, true);
int result = callback.WaitForResult();
EXPECT_EQ(result, kMagicResult);
}
// TODO: test deleting ExampleEmployer while work outstanding
<|endoftext|> |
<commit_before>/**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef FURFURYLIC_GUARD_4B6A00F6_E33D_4114_9F57_D2C2E984E809
#define FURFURYLIC_GUARD_4B6A00F6_E33D_4114_9F57_D2C2E984E809
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <ios>
#include <memory>
#include <string>
#include <streambuf>
#include <utility>
#include "csv_error.hpp"
#include "key_chars.hpp"
namespace furfurylic {
namespace commata {
class parse_error :
public csv_error
{
public:
explicit parse_error(std::string what_arg) :
csv_error(std::move(what_arg))
{}
};
namespace detail {
enum class state : std::int_fast8_t
{
left_of_value,
in_value,
right_of_open_quote,
in_quoted_value,
in_quoted_value_after_quote,
after_cr,
after_lf
};
template <state s>
struct handler
{};
template <>
struct handler<state::left_of_value>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.set_first_last();
parser.finalize();
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.change_state(state::right_of_open_quote);
break;
case key_chars<typename Parser::char_type>::CR:
parser.set_first_last();
parser.finalize();
parser.end_record();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.set_first_last();
parser.finalize();
parser.end_record();
parser.change_state(state::after_lf);
break;
default:
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_value);
break;
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& parser) const
{
parser.finalize();
}
};
template <>
struct handler<state::in_value>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
throw parse_error(
"A quotation mark found in a non-escaped value");
case key_chars<typename Parser::char_type>::CR:
parser.finalize();
parser.end_record();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.finalize();
parser.end_record();
parser.change_state(state::after_lf);
break;
default:
parser.update_last();
break;
}
}
template <class Parser>
void underflow(Parser& parser) const
{
parser.update();
}
template <class Parser>
void eof(Parser& parser) const
{
parser.finalize();
}
};
template <>
struct handler<state::right_of_open_quote>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
parser.set_first_last();
if (c == key_chars<typename Parser::char_type>::DQUOTE) {
parser.change_state(state::in_quoted_value_after_quote);
} else {
parser.update_last();
parser.change_state(state::in_quoted_value);
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& /*parser*/) const
{
throw parse_error("EOF reached with an open escaped value");
}
};
template <>
struct handler<state::in_quoted_value>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
if (c == key_chars<typename Parser::char_type>::DQUOTE) {
parser.update();
parser.set_first_last();
parser.change_state(state::in_quoted_value_after_quote);
} else {
parser.update_last();
}
}
template <class Parser>
void underflow(Parser& parser) const
{
parser.update();
}
template <class Parser>
void eof(Parser& /*parser*/) const
{
throw parse_error("EOF reached with an open escaped value");
}
};
template <>
struct handler<state::in_quoted_value_after_quote>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_quoted_value);
break;
case key_chars<typename Parser::char_type>::CR:
parser.finalize();
parser.end_record();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.finalize();
parser.end_record();
parser.change_state(state::after_lf);
break;
default:
throw parse_error(
"An invalid character found after a closed escaped value");
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& parser) const
{
parser.finalize();
}
};
template <>
struct handler<state::after_cr>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.new_physical_row();
parser.set_first_last();
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.new_physical_row();
parser.force_start_record();
parser.change_state(state::right_of_open_quote);
break;
case key_chars<typename Parser::char_type>::CR:
parser.new_physical_row();
break;
case key_chars<typename Parser::char_type>::LF:
parser.change_state(state::after_lf);
break;
default:
parser.new_physical_row();
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_value);
break;
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& /*parser*/) const
{}
};
template <>
struct handler<state::after_lf>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.new_physical_row();
parser.set_first_last();
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.new_physical_row();
parser.force_start_record();
parser.change_state(state::right_of_open_quote);
break;
case key_chars<typename Parser::char_type>::CR:
parser.new_physical_row();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.new_physical_row();
break;
default:
parser.new_physical_row();
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_value);
break;
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& /*parser*/) const
{}
};
template <class Ch, class Sink>
class primitive_parser
{
const Ch* p_;
Sink f_;
bool record_started_;
state s_;
const Ch* field_start_;
const Ch* field_end_;
std::size_t physical_row_index_;
const Ch* physical_row_or_buffer_begin_;
std::size_t physical_row_chars_passed_away_;
private:
template <state>
friend struct handler;
// To make control flows clearer, we adopt exceptions. Sigh...
struct parse_aborted
{};
public:
using char_type = Ch;
explicit primitive_parser(Sink f) :
f_(std::move(f)),
record_started_(false), s_(state::after_lf),
physical_row_index_(parse_error::npos),
physical_row_chars_passed_away_(0)
{}
primitive_parser(primitive_parser&&) = default;
primitive_parser& operator=(primitive_parser&&) = default;
bool parse(const Ch* begin, const Ch* end)
{
try {
p_ = begin;
physical_row_or_buffer_begin_ = begin;
set_first_last();
f_.start_buffer(begin);
while (p_ < end) {
with_handler([this](const auto& h) { h.normal(*this, *p_); });
++p_;
}
with_handler([this](const auto& h) { h.underflow(*this); });
f_.end_buffer(end);
physical_row_chars_passed_away_ +=
p_ - physical_row_or_buffer_begin_;
return true;
} catch (csv_error& e) {
e.set_physical_position(
physical_row_index_,
(p_ - physical_row_or_buffer_begin_)
+ physical_row_chars_passed_away_);
throw;
} catch (const parse_aborted&) {
return false;
}
}
bool eof()
{
try {
p_ = nullptr;
set_first_last();
f_.start_buffer(nullptr);
with_handler([this](const auto& h) { h.eof(*this); });
if (record_started_) {
end_record();
}
f_.end_buffer(nullptr);
return true;
} catch (const parse_aborted&) {
return false;
}
}
private:
void new_physical_row()
{
if (physical_row_index_ == parse_error::npos) {
physical_row_index_ = 0;
} else {
++physical_row_index_;
}
physical_row_or_buffer_begin_ = p_;
physical_row_chars_passed_away_ = 0;
}
void change_state(state s)
{
s_ = s;
}
void set_first_last()
{
field_start_ = p_;
field_end_ = p_;
}
void update_last()
{
field_end_ = p_ + 1;
}
void update()
{
if (!record_started_) {
f_.start_record(field_start_);
record_started_ = true;
}
if (field_start_ < field_end_) {
if (!f_.update(field_start_, field_end_)) {
throw parse_aborted();
}
}
}
void finalize()
{
if (!record_started_) {
f_.start_record(field_start_);
record_started_ = true;
}
if (!f_.finalize(field_start_, field_end_)) {
throw parse_aborted();
}
}
void force_start_record()
{
f_.start_record(p_);
record_started_ = true;
}
void end_record()
{
if (!f_.end_record(p_)) {
throw parse_aborted();
}
record_started_ = false;
}
private:
template <class F>
void with_handler(F f)
{
switch (s_) {
case state::left_of_value:
f(handler<state::left_of_value>());
break;
case state::in_value:
f(handler<state::in_value>());
break;
case state::right_of_open_quote:
f(handler<state::right_of_open_quote>());
break;
case state::in_quoted_value:
f(handler<state::in_quoted_value>());
break;
case state::in_quoted_value_after_quote:
f(handler<state::in_quoted_value_after_quote>());
break;
case state::after_cr:
f(handler<state::after_cr>());
break;
case state::after_lf:
f(handler<state::after_lf>());
break;
default:
assert(false);
break;
}
}
};
} // end namespace detail
template <class Ch, class Tr, class Sink>
bool parse(std::basic_streambuf<Ch, Tr>& in, std::streamsize buffer_size,
Sink sink)
{
std::unique_ptr<Ch[]> buffer(new Ch[buffer_size]);
detail::primitive_parser<Ch, Sink> p(std::move(sink));
for (;;) {
std::streamsize loaded_size = in.sgetn(buffer.get(), buffer_size);
if (loaded_size == 0) {
break;
}
if (!p.parse(buffer.get(), buffer.get() + loaded_size)) {
return false;
}
}
return p.eof();
}
}}
#endif
<commit_msg>Make the input-consuming loop efficient and reside in primitive_parser<commit_after>/**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef FURFURYLIC_GUARD_4B6A00F6_E33D_4114_9F57_D2C2E984E809
#define FURFURYLIC_GUARD_4B6A00F6_E33D_4114_9F57_D2C2E984E809
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <ios>
#include <memory>
#include <string>
#include <streambuf>
#include <utility>
#include "csv_error.hpp"
#include "key_chars.hpp"
namespace furfurylic {
namespace commata {
class parse_error :
public csv_error
{
public:
explicit parse_error(std::string what_arg) :
csv_error(std::move(what_arg))
{}
};
namespace detail {
enum class state : std::int_fast8_t
{
left_of_value,
in_value,
right_of_open_quote,
in_quoted_value,
in_quoted_value_after_quote,
after_cr,
after_lf
};
template <state s>
struct handler
{};
template <>
struct handler<state::left_of_value>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.set_first_last();
parser.finalize();
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.change_state(state::right_of_open_quote);
break;
case key_chars<typename Parser::char_type>::CR:
parser.set_first_last();
parser.finalize();
parser.end_record();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.set_first_last();
parser.finalize();
parser.end_record();
parser.change_state(state::after_lf);
break;
default:
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_value);
break;
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& parser) const
{
parser.finalize();
}
};
template <>
struct handler<state::in_value>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
throw parse_error(
"A quotation mark found in a non-escaped value");
case key_chars<typename Parser::char_type>::CR:
parser.finalize();
parser.end_record();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.finalize();
parser.end_record();
parser.change_state(state::after_lf);
break;
default:
parser.update_last();
break;
}
}
template <class Parser>
void underflow(Parser& parser) const
{
parser.update();
}
template <class Parser>
void eof(Parser& parser) const
{
parser.finalize();
}
};
template <>
struct handler<state::right_of_open_quote>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
parser.set_first_last();
if (c == key_chars<typename Parser::char_type>::DQUOTE) {
parser.change_state(state::in_quoted_value_after_quote);
} else {
parser.update_last();
parser.change_state(state::in_quoted_value);
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& /*parser*/) const
{
throw parse_error("EOF reached with an open escaped value");
}
};
template <>
struct handler<state::in_quoted_value>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
if (c == key_chars<typename Parser::char_type>::DQUOTE) {
parser.update();
parser.set_first_last();
parser.change_state(state::in_quoted_value_after_quote);
} else {
parser.update_last();
}
}
template <class Parser>
void underflow(Parser& parser) const
{
parser.update();
}
template <class Parser>
void eof(Parser& /*parser*/) const
{
throw parse_error("EOF reached with an open escaped value");
}
};
template <>
struct handler<state::in_quoted_value_after_quote>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_quoted_value);
break;
case key_chars<typename Parser::char_type>::CR:
parser.finalize();
parser.end_record();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.finalize();
parser.end_record();
parser.change_state(state::after_lf);
break;
default:
throw parse_error(
"An invalid character found after a closed escaped value");
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& parser) const
{
parser.finalize();
}
};
template <>
struct handler<state::after_cr>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.new_physical_row();
parser.set_first_last();
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.new_physical_row();
parser.force_start_record();
parser.change_state(state::right_of_open_quote);
break;
case key_chars<typename Parser::char_type>::CR:
parser.new_physical_row();
break;
case key_chars<typename Parser::char_type>::LF:
parser.change_state(state::after_lf);
break;
default:
parser.new_physical_row();
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_value);
break;
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& /*parser*/) const
{}
};
template <>
struct handler<state::after_lf>
{
template <class Parser>
void normal(Parser& parser, typename Parser::char_type c) const
{
switch (c) {
case key_chars<typename Parser::char_type>::COMMA:
parser.new_physical_row();
parser.set_first_last();
parser.finalize();
parser.change_state(state::left_of_value);
break;
case key_chars<typename Parser::char_type>::DQUOTE:
parser.new_physical_row();
parser.force_start_record();
parser.change_state(state::right_of_open_quote);
break;
case key_chars<typename Parser::char_type>::CR:
parser.new_physical_row();
parser.change_state(state::after_cr);
break;
case key_chars<typename Parser::char_type>::LF:
parser.new_physical_row();
break;
default:
parser.new_physical_row();
parser.set_first_last();
parser.update_last();
parser.change_state(state::in_value);
break;
}
}
template <class Parser>
void underflow(Parser& /*parser*/) const
{}
template <class Parser>
void eof(Parser& /*parser*/) const
{}
};
template <class Ch, class Sink>
class primitive_parser
{
const Ch* p_;
Sink f_;
bool record_started_;
state s_;
const Ch* field_start_;
const Ch* field_end_;
std::size_t physical_row_index_;
const Ch* physical_row_or_buffer_begin_;
std::size_t physical_row_chars_passed_away_;
private:
template <state>
friend struct handler;
// To make control flows clearer, we adopt exceptions. Sigh...
struct parse_aborted
{};
public:
using char_type = Ch;
explicit primitive_parser(Sink f) :
f_(std::move(f)),
record_started_(false), s_(state::after_lf),
physical_row_index_(parse_error::npos),
physical_row_chars_passed_away_(0)
{}
primitive_parser(primitive_parser&&) = default;
primitive_parser& operator=(primitive_parser&&) = default;
template <class Tr>
bool parse_all(std::basic_streambuf<Ch, Tr>& in, std::streamsize buffer_size)
{
std::unique_ptr<Ch[]> buffer(new Ch[buffer_size]);
for (;;) {
bool eof_reached = false;
std::streamsize loaded_size = 0;
std::size_t offset = 0;
do {
std::streamsize length = in.sgetn(buffer.get() + offset, buffer_size - offset);
if (length == 0) {
eof_reached = true;
break;
}
loaded_size += length;
} while (loaded_size < buffer_size);
if (!parse(buffer.get(), buffer.get() + loaded_size)) {
return false;
}
if (eof_reached) {
return eof();
}
}
}
private:
bool parse(const Ch* begin, const Ch* end)
{
try {
p_ = begin;
physical_row_or_buffer_begin_ = begin;
set_first_last();
f_.start_buffer(begin);
while (p_ < end) {
with_handler([this](const auto& h) { h.normal(*this, *p_); });
++p_;
}
with_handler([this](const auto& h) { h.underflow(*this); });
f_.end_buffer(end);
physical_row_chars_passed_away_ +=
p_ - physical_row_or_buffer_begin_;
return true;
} catch (csv_error& e) {
e.set_physical_position(
physical_row_index_,
(p_ - physical_row_or_buffer_begin_)
+ physical_row_chars_passed_away_);
throw;
} catch (const parse_aborted&) {
return false;
}
}
bool eof()
{
try {
p_ = nullptr;
set_first_last();
f_.start_buffer(nullptr);
with_handler([this](const auto& h) { h.eof(*this); });
if (record_started_) {
end_record();
}
f_.end_buffer(nullptr);
return true;
} catch (const parse_aborted&) {
return false;
}
}
private:
void new_physical_row()
{
if (physical_row_index_ == parse_error::npos) {
physical_row_index_ = 0;
} else {
++physical_row_index_;
}
physical_row_or_buffer_begin_ = p_;
physical_row_chars_passed_away_ = 0;
}
void change_state(state s)
{
s_ = s;
}
void set_first_last()
{
field_start_ = p_;
field_end_ = p_;
}
void update_last()
{
field_end_ = p_ + 1;
}
void update()
{
if (!record_started_) {
f_.start_record(field_start_);
record_started_ = true;
}
if (field_start_ < field_end_) {
if (!f_.update(field_start_, field_end_)) {
throw parse_aborted();
}
}
}
void finalize()
{
if (!record_started_) {
f_.start_record(field_start_);
record_started_ = true;
}
if (!f_.finalize(field_start_, field_end_)) {
throw parse_aborted();
}
}
void force_start_record()
{
f_.start_record(p_);
record_started_ = true;
}
void end_record()
{
if (!f_.end_record(p_)) {
throw parse_aborted();
}
record_started_ = false;
}
private:
template <class F>
void with_handler(F f)
{
switch (s_) {
case state::left_of_value:
f(handler<state::left_of_value>());
break;
case state::in_value:
f(handler<state::in_value>());
break;
case state::right_of_open_quote:
f(handler<state::right_of_open_quote>());
break;
case state::in_quoted_value:
f(handler<state::in_quoted_value>());
break;
case state::in_quoted_value_after_quote:
f(handler<state::in_quoted_value_after_quote>());
break;
case state::after_cr:
f(handler<state::after_cr>());
break;
case state::after_lf:
f(handler<state::after_lf>());
break;
default:
assert(false);
break;
}
}
};
} // end namespace detail
template <class Ch, class Tr, class Sink>
bool parse(std::basic_streambuf<Ch, Tr>& in, std::streamsize buffer_size,
Sink sink)
{
detail::primitive_parser<Ch, Sink> p(std::move(sink));
return p.parse_all(in, buffer_size);
}
}}
#endif
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <map>
#include <random>
#include <GLFW/glfw3.h>
#include <glbinding/Binding.h>
#include <glbinding/callbacks.h>
#include <glbinding/gl/gl.h>
#include <globjects/globjects.h>
#include <glm/gtc/matrix_transform.hpp>
#include <openll/GlyphRenderer.h>
#include <openll/FontLoader.h>
#include <openll/Typesetter.h>
#include <openll/stages/GlyphPreparationStage.h>
#include <openll/FontFace.h>
#include <openll/GlyphSequence.h>
#include <openll/Alignment.h>
#include <openll/LineAnchor.h>
#include <openll/layout/layoutbase.h>
#include <openll/layout/algorithm.h>
#include <cpplocate/cpplocate.h>
#include <cpplocate/ModuleInfo.h>
#include "PointDrawable.h"
#include "RectangleDrawable.h"
#include "benchmark.h"
using namespace gl;
glm::uvec2 g_viewport{640, 480};
bool g_config_changed = true;
size_t g_algorithmID = 0;
struct Algorithm
{
std::string name;
std::function<void(std::vector<gloperate_text::Label>&)> function;
};
using namespace std::placeholders;
std::vector<Algorithm> layoutAlgorithms
{
{"constant", gloperate_text::layout::constant},
{"random", gloperate_text::layout::random},
{"greedy", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::overlapCount)},
{"greedy with area", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::overlapArea)},
{"discreteGradientDescent", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::overlapCount)},
{"discreteGradientDescent with area", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::overlapArea)},
{"simulatedAnnealing with area", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::overlapArea, false)},
{"simulatedAnnealing", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false)},
{"simulatedAnnealing with selection", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true)},
};
void onResize(GLFWwindow*, int width, int height)
{
g_viewport = {width, height};
g_config_changed = true;
}
void onKeyPress(GLFWwindow * window, int key, int, int action, int mods)
{
if (key == 'Q' && action == GLFW_PRESS && mods == GLFW_MOD_CONTROL)
{
glfwSetWindowShouldClose(window, 1);
}
else if ('1' <= key && key <= '9' && action == GLFW_PRESS)
{
g_algorithmID = std::min(static_cast<size_t>(key - '1'), layoutAlgorithms.size() - 1);
g_config_changed = true;
}
}
void glInitialize()
{
glbinding::Binding::initialize(false);
glbinding::setCallbackMaskExcept(
glbinding::CallbackMask::After | glbinding::CallbackMask::Parameters,
{"glGetError"});
glbinding::setAfterCallback([](const glbinding::FunctionCall& call) {
const auto error = glGetError();
if (error != GL_NO_ERROR)
{
std::cout << error << " in " << call.function->name()
<< " with parameters:" << std::endl;
for (const auto& parameter : call.parameters)
{
std::cout << " " << parameter->asString() << std::endl;
}
}
});
globjects::init();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
}
std::string random_name(std::default_random_engine engine)
{
std::uniform_int_distribution<int> charDistribution(32, 126);
std::uniform_int_distribution<int> lengthDistribution(3, 15);
const auto length = lengthDistribution(engine);
std::vector<char> characters;
for (int i = 0; i < length; ++i)
{
characters.push_back(static_cast<char>(charDistribution(engine)));
}
return {characters.begin(), characters.end()};
}
std::vector<gloperate_text::Label> prepareLabels(gloperate_text::FontFace * font, glm::uvec2 viewport)
{
std::vector<gloperate_text::Label> labels;
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(-1.f, 1.f);
std::uniform_int_distribution<unsigned int> priorityDistribution(1, 10);
for (int i = 0; i < 50; ++i)
{
const auto string = random_name(generator);
const auto priority = priorityDistribution(generator);
gloperate_text::GlyphSequence sequence;
std::u32string unicode_string(string.begin(), string.end());
sequence.setString(unicode_string);
sequence.setWordWrap(true);
sequence.setLineWidth(400.f);
sequence.setAlignment(gloperate_text::Alignment::LeftAligned);
sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent);
sequence.setFontSize(10.f + priority);
sequence.setFontFace(font);
sequence.setFontColor(glm::vec4(glm::vec3(0.5f - priority * 0.05f), 1.f));
const auto origin = glm::vec2{distribution(generator), distribution(generator)};
// compute transform matrix
glm::mat4 transform;
transform = glm::translate(transform, glm::vec3(origin, 0.f));
transform = glm::scale(transform, glm::vec3(1.f,
static_cast<float>(viewport.x) / viewport.y, 1.f));
transform = glm::scale(transform, glm::vec3(1 / 300.f));
const auto placement = gloperate_text::LabelPlacement{ glm::vec2{ 0.f, 0.f }
, gloperate_text::Alignment::LeftAligned, gloperate_text::LineAnchor::Baseline, true };
sequence.setAdditionalTransform(transform);
labels.push_back({sequence, origin, priority, placement });
}
return labels;
}
gloperate_text::GlyphVertexCloud prepareCloud(const std::vector<gloperate_text::Label> & labels)
{
std::vector<gloperate_text::GlyphSequence> sequences;
for (const auto & label : labels)
{
if (label.placement.display)
{
sequences.push_back(gloperate_text::applyPlacement(label));
}
}
return gloperate_text::prepareGlyphs(sequences, true);
}
void preparePointDrawable(const std::vector<gloperate_text::Label> & labels, PointDrawable& pointDrawable)
{
std::vector<glm::vec2> points;
for (const auto & label : labels)
{
points.push_back(label.pointLocation);
}
pointDrawable.initialize(points);
}
void prepareRectangleDrawable(const std::vector<gloperate_text::Label> & labels, RectangleDrawable& rectangleDrawable)
{
std::vector<glm::vec2> rectangles;
for (const auto & label : labels)
{
auto sequence = gloperate_text::applyPlacement(label);
auto extent = gloperate_text::Typesetter::rectangle(sequence, glm::vec3(label.pointLocation, 0.f));
rectangles.push_back(extent.first);
rectangles.push_back(extent.first + extent.second);
}
rectangleDrawable.initialize(rectangles);
}
void runAndBenchmark(std::vector<gloperate_text::Label> & labels, Algorithm algorithm)
{
auto start = std::chrono::steady_clock::now();
algorithm.function(labels);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Evaluation results for " << algorithm.name << ":" << std::endl
<< "Runtime: " << diff.count() << "s" << std::endl
<< "Labels hidden: " << labelsHidden(labels) << "/" << labels.size() << std::endl
<< "Overlaps: " << labelOverlaps(labels) << std::endl
<< "Overlap area: " << labelOverlapArea(labels) << std::endl
<< "Relative label positions:" << std::endl;
auto positions = labelPositionDesirability(labels);
std::cout
<< " Upper Right: " << positions[gloperate_text::RelativeLabelPosition::UpperRight] << std::endl
<< " Upper Left: " << positions[gloperate_text::RelativeLabelPosition::UpperLeft] << std::endl
<< " Lower Right: " << positions[gloperate_text::RelativeLabelPosition::LowerRight] << std::endl
<< " Lower Left: " << positions[gloperate_text::RelativeLabelPosition::LowerLeft] << std::endl;
std::cout << std::endl;
}
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
auto window = glfwCreateWindow(g_viewport.x, g_viewport.y, "Text-Demo", 0, nullptr);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glInitialize();
glfwSetWindowSizeCallback(window, onResize);
glfwSetKeyCallback(window, onKeyPress);
cpplocate::ModuleInfo moduleInfo = cpplocate::findModule("openll");
std::string dataPath = moduleInfo.value("dataPath");
gloperate_text::FontLoader loader;
auto font = loader.load(dataPath + "/fonts/opensansr36/opensansr36.fnt");
gloperate_text::GlyphRenderer renderer;
gloperate_text::GlyphVertexCloud cloud;
std::vector<gloperate_text::Label> labels;
PointDrawable pointDrawable {dataPath};
RectangleDrawable rectangleDrawable {dataPath};
glClearColor(1.f, 1.f, 1.f, 1.f);
while (!glfwWindowShouldClose(window))
{
if (g_config_changed)
{
glViewport(0, 0, g_viewport.x, g_viewport.y);
labels = prepareLabels(font, g_viewport);
runAndBenchmark(labels, layoutAlgorithms[g_algorithmID]);
cloud = prepareCloud(labels);
preparePointDrawable(labels, pointDrawable);
prepareRectangleDrawable(labels, rectangleDrawable);
}
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
gl::glDepthMask(gl::GL_FALSE);
gl::glEnable(gl::GL_CULL_FACE);
gl::glEnable(gl::GL_BLEND);
gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA);
renderer.render(cloud);
pointDrawable.render();
rectangleDrawable.render();
gl::glDepthMask(gl::GL_TRUE);
gl::glDisable(gl::GL_CULL_FACE);
gl::glDisable(gl::GL_BLEND);
g_config_changed = false;
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
<commit_msg>Add option to remove frames in layouting example<commit_after>#include <cassert>
#include <iostream>
#include <map>
#include <random>
#include <GLFW/glfw3.h>
#include <glbinding/Binding.h>
#include <glbinding/callbacks.h>
#include <glbinding/gl/gl.h>
#include <globjects/globjects.h>
#include <glm/gtc/matrix_transform.hpp>
#include <openll/GlyphRenderer.h>
#include <openll/FontLoader.h>
#include <openll/Typesetter.h>
#include <openll/stages/GlyphPreparationStage.h>
#include <openll/FontFace.h>
#include <openll/GlyphSequence.h>
#include <openll/Alignment.h>
#include <openll/LineAnchor.h>
#include <openll/layout/layoutbase.h>
#include <openll/layout/algorithm.h>
#include <cpplocate/cpplocate.h>
#include <cpplocate/ModuleInfo.h>
#include "PointDrawable.h"
#include "RectangleDrawable.h"
#include "benchmark.h"
using namespace gl;
glm::uvec2 g_viewport{640, 480};
bool g_config_changed = true;
size_t g_algorithmID = 0;
bool g_frames_visible = true;
struct Algorithm
{
std::string name;
std::function<void(std::vector<gloperate_text::Label>&)> function;
};
using namespace std::placeholders;
std::vector<Algorithm> layoutAlgorithms
{
{"constant", gloperate_text::layout::constant},
{"random", gloperate_text::layout::random},
{"greedy", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::overlapCount)},
{"greedy with area", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::overlapArea)},
{"discreteGradientDescent", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::overlapCount)},
{"discreteGradientDescent with area", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::overlapArea)},
{"simulatedAnnealing with area", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::overlapArea, false)},
{"simulatedAnnealing", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false)},
{"simulatedAnnealing with selection", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true)},
};
void onResize(GLFWwindow*, int width, int height)
{
g_viewport = {width, height};
g_config_changed = true;
}
void onKeyPress(GLFWwindow * window, int key, int, int action, int mods)
{
if (key == 'Q' && action == GLFW_PRESS && mods == GLFW_MOD_CONTROL)
{
glfwSetWindowShouldClose(window, 1);
}
else if (key == 'F' && action == GLFW_PRESS)
{
g_frames_visible = !g_frames_visible;
}
else if ('1' <= key && key <= '9' && action == GLFW_PRESS)
{
g_algorithmID = std::min(static_cast<size_t>(key - '1'), layoutAlgorithms.size() - 1);
g_config_changed = true;
}
}
void glInitialize()
{
glbinding::Binding::initialize(false);
glbinding::setCallbackMaskExcept(
glbinding::CallbackMask::After | glbinding::CallbackMask::Parameters,
{"glGetError"});
glbinding::setAfterCallback([](const glbinding::FunctionCall& call) {
const auto error = glGetError();
if (error != GL_NO_ERROR)
{
std::cout << error << " in " << call.function->name()
<< " with parameters:" << std::endl;
for (const auto& parameter : call.parameters)
{
std::cout << " " << parameter->asString() << std::endl;
}
}
});
globjects::init();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
}
std::string random_name(std::default_random_engine engine)
{
std::uniform_int_distribution<int> charDistribution(32, 126);
std::uniform_int_distribution<int> lengthDistribution(3, 15);
const auto length = lengthDistribution(engine);
std::vector<char> characters;
for (int i = 0; i < length; ++i)
{
characters.push_back(static_cast<char>(charDistribution(engine)));
}
return {characters.begin(), characters.end()};
}
std::vector<gloperate_text::Label> prepareLabels(gloperate_text::FontFace * font, glm::uvec2 viewport)
{
std::vector<gloperate_text::Label> labels;
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(-1.f, 1.f);
std::uniform_int_distribution<unsigned int> priorityDistribution(1, 10);
for (int i = 0; i < 50; ++i)
{
const auto string = random_name(generator);
const auto priority = priorityDistribution(generator);
gloperate_text::GlyphSequence sequence;
std::u32string unicode_string(string.begin(), string.end());
sequence.setString(unicode_string);
sequence.setWordWrap(true);
sequence.setLineWidth(400.f);
sequence.setAlignment(gloperate_text::Alignment::LeftAligned);
sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent);
sequence.setFontSize(10.f + priority);
sequence.setFontFace(font);
sequence.setFontColor(glm::vec4(glm::vec3(0.5f - priority * 0.05f), 1.f));
const auto origin = glm::vec2{distribution(generator), distribution(generator)};
// compute transform matrix
glm::mat4 transform;
transform = glm::translate(transform, glm::vec3(origin, 0.f));
transform = glm::scale(transform, glm::vec3(1.f,
static_cast<float>(viewport.x) / viewport.y, 1.f));
transform = glm::scale(transform, glm::vec3(1 / 300.f));
const auto placement = gloperate_text::LabelPlacement{ glm::vec2{ 0.f, 0.f }
, gloperate_text::Alignment::LeftAligned, gloperate_text::LineAnchor::Baseline, true };
sequence.setAdditionalTransform(transform);
labels.push_back({sequence, origin, priority, placement });
}
return labels;
}
gloperate_text::GlyphVertexCloud prepareCloud(const std::vector<gloperate_text::Label> & labels)
{
std::vector<gloperate_text::GlyphSequence> sequences;
for (const auto & label : labels)
{
if (label.placement.display)
{
sequences.push_back(gloperate_text::applyPlacement(label));
}
}
return gloperate_text::prepareGlyphs(sequences, true);
}
void preparePointDrawable(const std::vector<gloperate_text::Label> & labels, PointDrawable& pointDrawable)
{
std::vector<glm::vec2> points;
for (const auto & label : labels)
{
points.push_back(label.pointLocation);
}
pointDrawable.initialize(points);
}
void prepareRectangleDrawable(const std::vector<gloperate_text::Label> & labels, RectangleDrawable& rectangleDrawable)
{
std::vector<glm::vec2> rectangles;
for (const auto & label : labels)
{
auto sequence = gloperate_text::applyPlacement(label);
auto extent = gloperate_text::Typesetter::rectangle(sequence, glm::vec3(label.pointLocation, 0.f));
rectangles.push_back(extent.first);
rectangles.push_back(extent.first + extent.second);
}
rectangleDrawable.initialize(rectangles);
}
void runAndBenchmark(std::vector<gloperate_text::Label> & labels, Algorithm algorithm)
{
auto start = std::chrono::steady_clock::now();
algorithm.function(labels);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Evaluation results for " << algorithm.name << ":" << std::endl
<< "Runtime: " << diff.count() << "s" << std::endl
<< "Labels hidden: " << labelsHidden(labels) << "/" << labels.size() << std::endl
<< "Overlaps: " << labelOverlaps(labels) << std::endl
<< "Overlap area: " << labelOverlapArea(labels) << std::endl
<< "Relative label positions:" << std::endl;
auto positions = labelPositionDesirability(labels);
std::cout
<< " Upper Right: " << positions[gloperate_text::RelativeLabelPosition::UpperRight] << std::endl
<< " Upper Left: " << positions[gloperate_text::RelativeLabelPosition::UpperLeft] << std::endl
<< " Lower Right: " << positions[gloperate_text::RelativeLabelPosition::LowerRight] << std::endl
<< " Lower Left: " << positions[gloperate_text::RelativeLabelPosition::LowerLeft] << std::endl;
std::cout << std::endl;
}
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
auto window = glfwCreateWindow(g_viewport.x, g_viewport.y, "Text-Demo", 0, nullptr);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glInitialize();
glfwSetWindowSizeCallback(window, onResize);
glfwSetKeyCallback(window, onKeyPress);
cpplocate::ModuleInfo moduleInfo = cpplocate::findModule("openll");
std::string dataPath = moduleInfo.value("dataPath");
gloperate_text::FontLoader loader;
auto font = loader.load(dataPath + "/fonts/opensansr36/opensansr36.fnt");
gloperate_text::GlyphRenderer renderer;
gloperate_text::GlyphVertexCloud cloud;
std::vector<gloperate_text::Label> labels;
PointDrawable pointDrawable {dataPath};
RectangleDrawable rectangleDrawable {dataPath};
glClearColor(1.f, 1.f, 1.f, 1.f);
while (!glfwWindowShouldClose(window))
{
if (g_config_changed)
{
glViewport(0, 0, g_viewport.x, g_viewport.y);
labels = prepareLabels(font, g_viewport);
runAndBenchmark(labels, layoutAlgorithms[g_algorithmID]);
cloud = prepareCloud(labels);
preparePointDrawable(labels, pointDrawable);
prepareRectangleDrawable(labels, rectangleDrawable);
}
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
gl::glDepthMask(gl::GL_FALSE);
gl::glEnable(gl::GL_CULL_FACE);
gl::glEnable(gl::GL_BLEND);
gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA);
renderer.render(cloud);
pointDrawable.render();
if (g_frames_visible)
rectangleDrawable.render();
gl::glDepthMask(gl::GL_TRUE);
gl::glDisable(gl::GL_CULL_FACE);
gl::glDisable(gl::GL_BLEND);
g_config_changed = false;
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <climits>
#include "solvers/difference_assistant.h"
#include "config.h"
using namespace theorysolver;
#define VERBOSE_ASSISTANT false
#define EF satsolver::ExtendedFormula
#define SPEF std::shared_ptr<EF>
#define DA DifferenceAtom
#define SPDA std::shared_ptr<DA>
// Return a formula that uses only atoms in the canonical “xi-xj<=n” form.
// Note that it may use literal #0; for instance, xi >= n is converted to
// x0 - xi <= -n, so we will have to make sure x0 is always equal to 0.
SPEF canonize_atom(SPDA atom, std::vector<SPDA> &literal_to_DA, std::string literal) {
unsigned long int id1, id2;
assert(atom);
if (atom->i == atom->j) {
bool v;
switch (atom->op) {
case DA::LOWER:
v = atom->n > 0;
break;
case DA::LEQ:
v = atom->n >= 0;
break;
case DA::GREATER:
v = atom->n < 0;
break;
case DA::GEQ:
v = atom->n <= 0;
break;
case DA::EQUAL:
v = atom->n == 0;
break;
case DA::UNEQUAL:
v = atom->n != 0;
break;
default:
assert(false);
}
atom->canonical = SPEF(new EF(v ? EF::TRUE : EF::FALSE));
return atom->canonical;
}
switch (atom->op) {
case DA::LOWER: // xi - xj < n --> xi - xj <= n-1
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n-1);
atom->canonical = SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1)));
break;
case DA::LEQ: // xi - xj <= n --> xi - xj <= n
atom->canonical = SPEF(new EF(EF::LITERAL, literal));
break;
case DA::GREATER: // xi - xj > n --> ~(xi - xj <= n)
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n);
atom->canonical = SPEF(new EF(EF::NOT,
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1)))
));
break;
case DA::GEQ: // xi - xj >= n --> xj - xi <= -n
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->j, atom->i, DA::LEQ, -atom->n);
atom->canonical = SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1)));
break;
case DA::EQUAL: // xi - xj = n --> xi - xj <= n ∧ xj - xi <= -n
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n);
id2 = DifferenceAtom::add_DA(literal_to_DA, atom->j, atom->i, DA::LEQ, -atom->n);
atom->canonical = SPEF(new EF(EF::AND,
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1))),
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id2)))));
break;
case DA::UNEQUAL: // xi - xj != n --> xi - xj <= n-1 ∨ xj - xi <= -n-1
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n-1);
id2 = DifferenceAtom::add_DA(literal_to_DA, atom->j, atom->i, DA::LEQ, -atom->n-1);
atom->canonical = SPEF(new EF(EF::OR,
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1))),
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id2)))));
break;
}
return atom->canonical;
}
SPEF DifferenceAssistant::canonize_formula(SPEF formula, std::vector<SPDA> &literal_to_DA) {
SPDA atom;
switch (formula->get_type()) {
case EF::XOR:
case EF::OR:
case EF::AND:
case EF::IMPLIES:
return std::make_shared<EF>(formula->get_type(), DifferenceAssistant::canonize_formula(formula->get_f1(), literal_to_DA), DifferenceAssistant::canonize_formula(formula->get_f2(), literal_to_DA));
case EF::NOT:
return std::make_shared<EF>(formula->get_type(), DifferenceAssistant::canonize_formula(formula->get_f1(), literal_to_DA));
case EF::LITERAL:
atom = DifferenceAtom::SPDA_from_variable(literal_to_DA, formula->get_literal());
if (!DifferenceAtom::is_atom_variable(formula->get_literal()))
return std::make_shared<EF>(formula->get_type(), formula->get_literal());
atom = DifferenceAtom::SPDA_from_variable(literal_to_DA, formula->get_literal());
return canonize_atom(atom, literal_to_DA, formula->get_literal());
case EF::TRUE:
case EF::FALSE:
return std::make_shared<EF>(formula->get_type());
}
assert(false);
}
DifferenceAssistant::DifferenceAssistant(std::vector<SPDA> &literal_to_DA, std::shared_ptr<std::map<std::string, int>> name_to_variable, std::shared_ptr<satsolver::Formula> formula) :
formula(formula), literal_to_DA(literal_to_DA), name_to_variable(*name_to_variable), variable_to_name(), adj_graph(), consistent_state(true), edge_of_cycle(std::make_pair(0, 0), 0), old_polarity(formula->get_nb_variables()+1, 0), depth_back(-1) {
for (auto it : *name_to_variable)
this->variable_to_name.insert(make_pair(it.second, it.first));
}
int DifferenceAssistant::on_flip(unsigned int variable) {
unsigned int atom_id;
SPDA atom;
unsigned int i, j, tmp;
int clause_id=-1;
int n;
std::pair<std::list<path_item>, int> r;
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "flip variable: " << variable;
if (!DifferenceAtom::is_atom_literal(this->variable_to_name, variable)) {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << ", which is not an atom." << std::endl;
return -1; // We care only about variables matching atoms.
}
assert(variable <= static_cast<unsigned int>(this->formula->get_nb_variables()));
atom_id = DifferenceAtom::atom_id_from_literal(this->variable_to_name, variable);
atom = DifferenceAtom::SPDA_from_literal(this->literal_to_DA, this->variable_to_name, variable);
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << ", whose atom is: " << atom_id << ", and whose new state is: ";
i = atom->i;
j = atom->j;
n = atom->n;
if (this->formula->get_aff()->is_true(variable)) {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "true" << std::endl;
assert(this->consistent_state);
if (this->old_polarity[variable] == 1)
return -1;
r = this->adj_graph.find_lowest_path(j, i);
this->adj_graph.add_edge(i, j, atom_id, n);
if (r.second < -n) { // It creates a negative cycle
clause_id = this->learn_clause(r.first, atom_id);
assert(this->consistent_state);
this->edge_of_cycle = std::make_pair(std::make_pair(i, j), variable);
this->consistent_state = false;
}
this->old_polarity[variable] = 1;
}
else if (this->formula->get_aff()->is_false(variable)) {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "false" << std::endl;
assert(this->consistent_state);
if (this->old_polarity[variable] == -1)
return -1;
r = this->adj_graph.find_lowest_path(i, j);
this->adj_graph.add_edge(j, i, atom_id, -n-1);
if (r.second < n+1) { // It creates a negative cycle
clause_id = this->learn_clause(r.first, atom_id);
assert(this->consistent_state);
this->edge_of_cycle = std::make_pair(std::make_pair(j, i), variable);
this->consistent_state = false;
}
this->old_polarity[variable] = -1;
// ~(xi - xj <= n) <-> (xj - xi <= -n-1)
}
else {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "unknown" << std::endl;
if (this->old_polarity[variable] == 0)
return -1;
if (this->old_polarity[variable] == -1) {
tmp = i;
i = j;
j = tmp;
}
this->adj_graph.delete_edge(i, j, atom_id);
if (!this->consistent_state) {
if (i == this->edge_of_cycle.first.first && j == this->edge_of_cycle.first.second)
this->consistent_state = true;
else {
r = this->adj_graph.find_lowest_path(this->edge_of_cycle.first.second, this->edge_of_cycle.first.first);
// u->v was part of all negative cycles of the graph.
// Search if there is no more negative cycle containing u->v.
if (r.second >= -this->adj_graph.get_weight(this->edge_of_cycle.second)) {
this->consistent_state = true;
}
}
}
this->old_polarity[variable] = 0;
}
return clause_id;
}
int DifferenceAssistant::literal_from_atom_id(int atom_id) const {
if (atom_id > 0)
return DifferenceAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(atom_id));
else
return -DifferenceAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(-atom_id));
}
#define invert_polarity(lit) this->formula->get_aff()->is_true(lit) ? -lit : lit
int DifferenceAssistant::learn_clause(std::list<path_item> &path, int atom_id) {
int max_depth=-1, max_depth_l=0 ;
int lit, lit_conf = this->literal_from_atom_id(atom_id) ;
int tmp ;
std::unordered_set<int> clause;
clause.insert(invert_polarity(lit_conf));
for (auto it : path) {
lit = this->literal_from_atom_id(it.tag);
clause.insert(invert_polarity(lit));
if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) {
max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;
max_depth_l = lit ;
}
}
assert(max_depth >= 0);
this->depth_back = max_depth ;
assert(clause.size()>=2) ;
tmp = static_cast<int>(this->formula->add_clause(std::make_shared<satsolver::Clause>(this->formula->get_nb_variables(), clause, this->formula->get_aff())));
if(WITH_WL) this->formula->to_clauses_vector()[tmp]->init_WL_CL(lit_conf,max_depth_l) ;
return tmp ;
}
bool DifferenceAssistant::is_state_consistent() {
return this->consistent_state;
}
bool DifferenceAssistant::detect_isolated_literals() {
return false;
}
unsigned int DifferenceAssistant::get_depth_back() {
assert(this->depth_back>=0) ;
unsigned int tmp = static_cast<unsigned int>(this->depth_back) ; // cette fonction ne doit être appelée qu'une fois par clause apprise
this->depth_back = -1 ;
return tmp ;
}
<commit_msg>Correct little mistake in patch.<commit_after>#include <cassert>
#include <iostream>
#include <climits>
#include "solvers/difference_assistant.h"
#include "config.h"
using namespace theorysolver;
#define VERBOSE_ASSISTANT false
#define EF satsolver::ExtendedFormula
#define SPEF std::shared_ptr<EF>
#define DA DifferenceAtom
#define SPDA std::shared_ptr<DA>
// Return a formula that uses only atoms in the canonical “xi-xj<=n” form.
// Note that it may use literal #0; for instance, xi >= n is converted to
// x0 - xi <= -n, so we will have to make sure x0 is always equal to 0.
SPEF canonize_atom(SPDA atom, std::vector<SPDA> &literal_to_DA, std::string literal) {
unsigned long int id1, id2;
assert(atom);
if (atom->i == atom->j) {
bool v;
switch (atom->op) {
case DA::LOWER:
v = atom->n > 0;
break;
case DA::LEQ:
v = atom->n >= 0;
break;
case DA::GREATER:
v = atom->n < 0;
break;
case DA::GEQ:
v = atom->n <= 0;
break;
case DA::EQUAL:
v = atom->n == 0;
break;
case DA::UNEQUAL:
v = atom->n != 0;
break;
default:
assert(false);
}
atom->canonical = SPEF(new EF(v ? EF::TRUE : EF::FALSE));
return atom->canonical;
}
switch (atom->op) {
case DA::LOWER: // xi - xj < n --> xi - xj <= n-1
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n-1);
atom->canonical = SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1)));
break;
case DA::LEQ: // xi - xj <= n --> xi - xj <= n
atom->canonical = SPEF(new EF(EF::LITERAL, literal));
break;
case DA::GREATER: // xi - xj > n --> ~(xi - xj <= n)
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n);
atom->canonical = SPEF(new EF(EF::NOT,
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1)))
));
break;
case DA::GEQ: // xi - xj >= n --> xj - xi <= -n
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->j, atom->i, DA::LEQ, -atom->n);
atom->canonical = SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1)));
break;
case DA::EQUAL: // xi - xj = n --> xi - xj <= n ∧ xj - xi <= -n
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n);
id2 = DifferenceAtom::add_DA(literal_to_DA, atom->j, atom->i, DA::LEQ, -atom->n);
atom->canonical = SPEF(new EF(EF::AND,
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1))),
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id2)))));
break;
case DA::UNEQUAL: // xi - xj != n --> xi - xj <= n-1 ∨ xj - xi <= -n-1
id1 = DifferenceAtom::add_DA(literal_to_DA, atom->i, atom->j, DA::LEQ, atom->n-1);
id2 = DifferenceAtom::add_DA(literal_to_DA, atom->j, atom->i, DA::LEQ, -atom->n-1);
atom->canonical = SPEF(new EF(EF::OR,
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id1))),
SPEF(new EF(EF::LITERAL, DifferenceAtom::variable_name_from_atom_id(id2)))));
break;
}
return atom->canonical;
}
SPEF DifferenceAssistant::canonize_formula(SPEF formula, std::vector<SPDA> &literal_to_DA) {
SPDA atom;
switch (formula->get_type()) {
case EF::XOR:
case EF::OR:
case EF::AND:
case EF::IMPLIES:
return std::make_shared<EF>(formula->get_type(), DifferenceAssistant::canonize_formula(formula->get_f1(), literal_to_DA), DifferenceAssistant::canonize_formula(formula->get_f2(), literal_to_DA));
case EF::NOT:
return std::make_shared<EF>(formula->get_type(), DifferenceAssistant::canonize_formula(formula->get_f1(), literal_to_DA));
case EF::LITERAL:
atom = DifferenceAtom::SPDA_from_variable(literal_to_DA, formula->get_literal());
if (!DifferenceAtom::is_atom_variable(formula->get_literal()))
return std::make_shared<EF>(formula->get_type(), formula->get_literal());
atom = DifferenceAtom::SPDA_from_variable(literal_to_DA, formula->get_literal());
return canonize_atom(atom, literal_to_DA, formula->get_literal());
case EF::TRUE:
case EF::FALSE:
return std::make_shared<EF>(formula->get_type());
}
assert(false);
}
DifferenceAssistant::DifferenceAssistant(std::vector<SPDA> &literal_to_DA, std::shared_ptr<std::map<std::string, int>> name_to_variable, std::shared_ptr<satsolver::Formula> formula) :
formula(formula), literal_to_DA(literal_to_DA), name_to_variable(*name_to_variable), variable_to_name(), adj_graph(), consistent_state(true), edge_of_cycle(std::make_pair(0, 0), 0), old_polarity(formula->get_nb_variables()+1, 0), depth_back(-1) {
for (auto it : *name_to_variable)
this->variable_to_name.insert(make_pair(it.second, it.first));
}
int DifferenceAssistant::on_flip(unsigned int variable) {
unsigned int atom_id;
SPDA atom;
unsigned int i, j, tmp;
int clause_id=-1;
int n;
std::pair<std::list<path_item>, int> r;
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "flip variable: " << variable;
if (!DifferenceAtom::is_atom_literal(this->variable_to_name, variable)) {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << ", which is not an atom." << std::endl;
return -1; // We care only about variables matching atoms.
}
assert(variable <= static_cast<unsigned int>(this->formula->get_nb_variables()));
atom_id = DifferenceAtom::atom_id_from_literal(this->variable_to_name, variable);
atom = DifferenceAtom::SPDA_from_literal(this->literal_to_DA, this->variable_to_name, variable);
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << ", whose atom is: " << atom_id << ", and whose new state is: ";
i = atom->i;
j = atom->j;
n = atom->n;
if (this->formula->get_aff()->is_true(variable)) {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "true" << std::endl;
assert(this->consistent_state);
if (this->old_polarity[variable] == 1)
return -1;
r = this->adj_graph.find_lowest_path(j, i);
this->adj_graph.add_edge(i, j, atom_id, n);
if (r.second < -n) { // It creates a negative cycle
clause_id = this->learn_clause(r.first, atom_id);
assert(this->consistent_state);
this->edge_of_cycle = std::make_pair(std::make_pair(i, j), variable);
this->consistent_state = false;
}
this->old_polarity[variable] = 1;
}
else if (this->formula->get_aff()->is_false(variable)) {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "false" << std::endl;
assert(this->consistent_state);
if (this->old_polarity[variable] == -1)
return -1;
r = this->adj_graph.find_lowest_path(i, j);
this->adj_graph.add_edge(j, i, atom_id, -n-1);
if (r.second < n+1) { // It creates a negative cycle
clause_id = this->learn_clause(r.first, atom_id);
assert(this->consistent_state);
this->edge_of_cycle = std::make_pair(std::make_pair(j, i), variable);
this->consistent_state = false;
}
this->old_polarity[variable] = -1;
// ~(xi - xj <= n) <-> (xj - xi <= -n-1)
}
else {
if (VERBOSE_ASSISTANT && VERBOSE)
std::cout << "unknown" << std::endl;
if (this->old_polarity[variable] == 0)
return -1;
if (this->old_polarity[variable] == -1) {
tmp = i;
i = j;
j = tmp;
}
this->adj_graph.delete_edge(i, j, atom_id);
if (!this->consistent_state) {
if (i == this->edge_of_cycle.first.first && j == this->edge_of_cycle.first.second)
this->consistent_state = true;
else {
r = this->adj_graph.find_lowest_path(this->edge_of_cycle.first.second, this->edge_of_cycle.first.first);
// u->v was part of all negative cycles of the graph.
// Search if there is no more negative cycle containing u->v.
if (r.second >= -this->adj_graph.get_weight(this->edge_of_cycle.second)) {
this->consistent_state = true;
}
}
}
this->old_polarity[variable] = 0;
}
return clause_id;
}
int DifferenceAssistant::literal_from_atom_id(int atom_id) const {
if (atom_id > 0)
return DifferenceAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(atom_id));
else
return -DifferenceAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(-atom_id));
}
#define invert_polarity(lit) this->formula->get_aff()->is_true(lit) ? -lit : lit
int DifferenceAssistant::learn_clause(std::list<path_item> &path, int atom_id) {
int max_depth=-1, max_depth_l=0 ;
int lit, lit_conf = invert_polarity(this->literal_from_atom_id(atom_id)) ;
int tmp ;
std::unordered_set<int> clause;
clause.insert(lit_conf);
for (auto it : path) {
lit = invert_polarity(this->literal_from_atom_id(it.tag));
clause.insert(lit);
if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) {
max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;
max_depth_l = lit ;
}
}
assert(max_depth >= 0);
this->depth_back = max_depth ;
assert(clause.size()>=2) ;
tmp = static_cast<int>(this->formula->add_clause(std::make_shared<satsolver::Clause>(this->formula->get_nb_variables(), clause, this->formula->get_aff())));
if(WITH_WL) this->formula->to_clauses_vector()[tmp]->init_WL_CL(lit_conf,max_depth_l) ;
return tmp ;
}
bool DifferenceAssistant::is_state_consistent() {
return this->consistent_state;
}
bool DifferenceAssistant::detect_isolated_literals() {
return false;
}
unsigned int DifferenceAssistant::get_depth_back() {
assert(this->depth_back>=0) ;
unsigned int tmp = static_cast<unsigned int>(this->depth_back) ; // cette fonction ne doit être appelée qu'une fois par clause apprise
this->depth_back = -1 ;
return tmp ;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cef_handler.h"
#include "include/base/cef_bind.h"
#include "include/cef_app.h"
#include "include/wrapper/cef_closure_task.h"
#include "include/wrapper/cef_helpers.h"
#include "include/wrapper/cef_stream_resource_handler.h"
#include "message_delegate/app_message_delegate.h"
#include "message_delegate/app_window_message_delegate.h"
#include "helper.h"
#include "resource_util.h"
#include "platform_util.h"
#include "window_util.h"
namespace {
CefRefPtr<ClientHandler> g_instance = NULL;
const char kInterceptionPath[] = "/desktop_app/internals/";
std::string kScriptLoader = "appWindow.loadScript('#URL#');";
std::string kUnknownInternalContent = "Failed to load resource";
} // namespace
ClientHandler::ClientHandler()
: is_closing_ (false),
main_handle_ (NULL),
status_icon_handle_ (NULL),
account_manager_ (NULL)
{
DCHECK(!g_instance);
g_instance = this;
callbackId = 0;
CreateProcessMessageDelegates(process_message_delegates_);
}
ClientHandler::~ClientHandler() {
g_instance = NULL;
}
// static
CefRefPtr<ClientHandler>
ClientHandler::GetInstance() {
return g_instance;
}
void
ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
CEF_REQUIRE_UI_THREAD();
if (!GetBrowser()) {
base::AutoLock lock_scope(lock_);
// We need to keep the main child window, but not popup windows
browser_ = browser;
browser_id_ = browser->GetIdentifier();
} else if (browser->IsPopup()) {
// Add to the list of popup browsers.
// popup_browsers_.push_back(browser);
CefWindowHandle window = browser->GetHost()->GetWindowHandle();
// Base window initialization...
window_util::InitWindow(window);
// Init our popup
window_util::InitAsPopup(window);
// Let's initialize some hooks (e.g. handlers for non-fatail X11 errors)
window_util::InitHooks();
// Give focus to the popup browser. Perform asynchronously because the
// parent window may attempt to keep focus after launching the popup.
CefPostTask(TID_UI,
base::Bind(&CefBrowserHost::SetFocus, browser->GetHost().get(), true));
}
// Add to the list of existing browsers.
browser_list_.push_back(browser);
}
bool
ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
CEF_REQUIRE_UI_THREAD();
// Closing the main window requires special handling. See the DoClose()
// documentation in the CEF header for a detailed destription of this
// process.
if (browser_list_.size() == 1) {
// Set a flag to indicate that the window close should be allowed.
is_closing_ = true;
}
// Allow the close. For windowed browsers this will result in the OS close
// event being sent.
return false;
}
void
ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
CEF_REQUIRE_UI_THREAD();
// Remove from the list of existing browsers.
BrowserList::iterator bit = browser_list_.begin();
for (; bit != browser_list_.end(); ++bit) {
if ((*bit)->IsSame(browser)) {
browser_list_.erase(bit);
break;
}
}
if (browser_list_.empty()) {
// All browser windows have closed. Quit the application message loop.
CefQuitMessageLoop();
} else if (!browser->IsPopup()) {
// If we close main window - close all popups...
CloseAllBrowsers(true);
}
}
void
ClientHandler::OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& errorText,
const CefString& failedUrl) {
CEF_REQUIRE_UI_THREAD();
// Don't display an error for downloaded files.
if (errorCode == ERR_ABORTED)
return;
std::stringstream error_explain;
error_explain << std::string(failedUrl) <<
", with error" << std::string(errorText) <<
" (" << errorCode << ")";
LOG(INFO) << "Failed to load URL:" << error_explain.str();
frame->LoadURL(GetAccountManager()->GetCurrentAccount()->GetBaseUrl() + "internals/pages/offline");
}
void
ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) {
if (httpStatusCode != 200 || !frame->IsMain())
return; // We need only successful loaded main frame
#if 0
frame->ExecuteJavaScript(
helper::string_replace(kScriptLoader, "#URL#", "http://ya.ru"),
"",
0
);
#endif
// Fix IM autoresize
std::string code =
"(function(window) {"
"var event = document.createEvent('UIEvents');"
"event.initUIEvent('resize', true, false, window, 0);"
"window.dispatchEvent(event);"
"})(window)";
frame->ExecuteJavaScript(
code,
"",
0
);
}
void
ClientHandler::CloseAllBrowsers(bool force_close) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close));
return;
}
if (browser_list_.empty())
return;
BrowserList::const_iterator it = browser_list_.begin();
for (; it != browser_list_.end(); ++it)
(*it)->GetHost()->CloseBrowser(force_close);
}
void
ClientHandler::CloseAllPopups(bool force_close) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close));
return;
}
if (browser_list_.empty())
return;
BrowserList::const_iterator it = browser_list_.begin();
for (; it != browser_list_.end(); ++it) {
if (!(*it)->IsPopup())
continue;
(*it)->GetHost()->CloseBrowser(force_close);
}
}
void
ClientHandler::OnBeforeContextMenu(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params,
CefRefPtr<CefMenuModel> model) {
CEF_REQUIRE_UI_THREAD();
if ((params->GetTypeFlags() & (CM_TYPEFLAG_PAGE | CM_TYPEFLAG_FRAME)) != 0) {
// Add a separator if the menu already has items.
if (model->GetCount() > 0)
model->AddSeparator();
// Add DevTools items to all context menus.
model->AddItem(1, "&Show DevTools");
model->AddItem(2, "Close DevTools");
model->AddSeparator();
model->AddItem(3, "Inspect Element");
}
}
bool
ClientHandler::OnContextMenuCommand(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params,
int command_id,
EventFlags event_flags) {
CEF_REQUIRE_UI_THREAD();
switch (command_id) {
case 1:
ShowDevTools(browser, CefPoint());
return true;
case 2:
CloseDevTools(browser);
return true;
case 3:
ShowDevTools(browser, CefPoint(params->GetXCoord(), params->GetYCoord()));
return true;
default:
return false;
}
}
void
ClientHandler::ShowDevTools(CefRefPtr<CefBrowser> browser,
const CefPoint& inspect_element_at) {
CefWindowInfo windowInfo;
CefBrowserSettings settings;
#if defined(OS_WIN)
windowInfo.SetAsPopup(browser->GetHost()->GetWindowHandle(), "DevTools");
#endif
browser->GetHost()->ShowDevTools(windowInfo, this, settings,
inspect_element_at);
}
void
ClientHandler::CloseDevTools(CefRefPtr<CefBrowser> browser) {
browser->GetHost()->CloseDevTools();
}
bool
ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& target_url,
const CefString& target_frame_name,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings,
bool* no_javascript_access) {
CEF_REQUIRE_IO_THREAD();
std::string url = target_url;
if (!IsAllowedUrl(url)) {
platform_util::OpenExternal(url);
return true;
}
return false;
}
bool
ClientHandler::OnBeforeBrowse(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request,
bool is_redirect) {
std::string url = request->GetURL();
if (!IsAllowedUrl(url)) {
platform_util::OpenExternal(url);
return true;
}
return false;
}
CefRefPtr<CefResourceHandler>
ClientHandler::GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) {
CEF_REQUIRE_IO_THREAD();
std::string url = request->GetURL();
if (url.find(kInterceptionPath) == std::string::npos)
return NULL;
// Handle URLs in interception path
std::string file_name, mime_type;
if (helper::ParseUrl(url, &file_name, &mime_type)) {
// Remove interception path
file_name = file_name.substr(strlen(kInterceptionPath) - 1);
// Load the resource from file.
CefRefPtr<CefStreamReader> stream =
GetBinaryResourceReader(app_settings_.resource_dir, file_name.c_str());
if (stream.get())
return new CefStreamResourceHandler(mime_type, stream);
}
// Never let the internal links to the external world
CefRefPtr<CefStreamReader> stream =
CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(kUnknownInternalContent.c_str())),
kUnknownInternalContent.size()
);
ASSERT(stream.get());
return new CefStreamResourceHandler("text/plain", stream);
}
bool
ClientHandler::OnProcessMessageReceived(
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) {
bool handled = false;
// Check for callbacks first
if (message->GetName() == "executeCommandCallback") {
int32 commandId = message->GetArgumentList()->GetInt(0);
bool result = message->GetArgumentList()->GetBool(1);
CefRefPtr<CommandCallback> callback = command_callback_map_[commandId];
callback->CommandComplete(result);
command_callback_map_.erase(commandId);
handled = true;
}
std::string message_name = message->GetName();
// Execute delegate callbacks.
ProcessMessageDelegateSet::iterator it = process_message_delegates_.begin();
for (; it != process_message_delegates_.end() && !handled; ++it) {
if ((*it)->IsAcceptedNamespace(message_name)) {
handled = (*it)->OnProcessMessageReceived(
this,
browser,
source_process,
message
);
}
}
if (!handled)
LOG(WARNING) << "Unknown proccess message: " << message_name;
return handled;
}
void
ClientHandler::SetAccountManager(CefRefPtr<AccountManager> account_manager) {
account_manager_ = account_manager;
}
CefRefPtr<AccountManager>
ClientHandler::GetAccountManager() const {
return account_manager_;
}
void
ClientHandler::SetMainWindowHandle(CefRefPtr<MainWindow> handle) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::SetMainWindowHandle, this, handle));
return;
}
main_handle_ = handle;
}
CefRefPtr<MainWindow>
ClientHandler::GetMainWindowHandle() const {
CEF_REQUIRE_UI_THREAD();
return main_handle_;
}
void
ClientHandler::SetAppSettings(AppSettings settings) {
app_settings_ = settings;
}
AppSettings
ClientHandler::GetAppSettings() const {
return app_settings_;
}
void
ClientHandler::SetStatusIconHandle(CefRefPtr<StatusIcon> handle) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::SetStatusIconHandle, this, handle));
return;
}
status_icon_handle_ = handle;
}
CefRefPtr<StatusIcon>
ClientHandler::GetStatusIconHandle() const {
CEF_REQUIRE_UI_THREAD();
return status_icon_handle_;
}
CefRefPtr<CefBrowser> ClientHandler::GetBrowser() const {
base::AutoLock lock_scope(lock_);
return browser_;
}
int
ClientHandler::GetBrowserId() const {
base::AutoLock lock_scope(lock_);
return browser_id_;
}
bool
ClientHandler::IsAllowedUrl(std::string url) {
if (
// Ugly temporary fix for file downloading...
// ToDo: fix it!
url.find("/desktop_app/download.file.php") != std::string::npos
|| url.find("/desktop_app/show.file.php") != std::string::npos
)
return false;
return (
account_manager_->GetCurrentAccount()->CheckBaseUrl(url)
|| url.find("chrome-devtools://") == 0
);
}
void
ClientHandler::SwitchAccount(int id) {
CloseAllPopups(true);
// ToDo: delete host/domain cookies here!!!
account_manager_->SwitchAccount(id);
browser_->GetMainFrame()->LoadURL(
account_manager_->GetCurrentAccount()->GetBaseUrl() + "internals/pages/portal-loader#login=yes"
);
}
// static
void
ClientHandler::CreateProcessMessageDelegates(ProcessMessageDelegateSet& delegates) {
AppMessageDelegate::CreateProcessMessageDelegates(delegates);
AppWindowMessageDelegate::CreateProcessMessageDelegates(delegates);
}<commit_msg>Коммитим изменения в AccountManager'е при смене аккаунта<commit_after>// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cef_handler.h"
#include "include/base/cef_bind.h"
#include "include/cef_app.h"
#include "include/wrapper/cef_closure_task.h"
#include "include/wrapper/cef_helpers.h"
#include "include/wrapper/cef_stream_resource_handler.h"
#include "message_delegate/app_message_delegate.h"
#include "message_delegate/app_window_message_delegate.h"
#include "helper.h"
#include "resource_util.h"
#include "platform_util.h"
#include "window_util.h"
namespace {
CefRefPtr<ClientHandler> g_instance = NULL;
const char kInterceptionPath[] = "/desktop_app/internals/";
std::string kScriptLoader = "appWindow.loadScript('#URL#');";
std::string kUnknownInternalContent = "Failed to load resource";
} // namespace
ClientHandler::ClientHandler()
: is_closing_ (false),
main_handle_ (NULL),
status_icon_handle_ (NULL),
account_manager_ (NULL)
{
DCHECK(!g_instance);
g_instance = this;
callbackId = 0;
CreateProcessMessageDelegates(process_message_delegates_);
}
ClientHandler::~ClientHandler() {
g_instance = NULL;
}
// static
CefRefPtr<ClientHandler>
ClientHandler::GetInstance() {
return g_instance;
}
void
ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
CEF_REQUIRE_UI_THREAD();
if (!GetBrowser()) {
base::AutoLock lock_scope(lock_);
// We need to keep the main child window, but not popup windows
browser_ = browser;
browser_id_ = browser->GetIdentifier();
} else if (browser->IsPopup()) {
// Add to the list of popup browsers.
// popup_browsers_.push_back(browser);
CefWindowHandle window = browser->GetHost()->GetWindowHandle();
// Base window initialization...
window_util::InitWindow(window);
// Init our popup
window_util::InitAsPopup(window);
// Let's initialize some hooks (e.g. handlers for non-fatail X11 errors)
window_util::InitHooks();
// Give focus to the popup browser. Perform asynchronously because the
// parent window may attempt to keep focus after launching the popup.
CefPostTask(TID_UI,
base::Bind(&CefBrowserHost::SetFocus, browser->GetHost().get(), true));
}
// Add to the list of existing browsers.
browser_list_.push_back(browser);
}
bool
ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
CEF_REQUIRE_UI_THREAD();
// Closing the main window requires special handling. See the DoClose()
// documentation in the CEF header for a detailed destription of this
// process.
if (browser_list_.size() == 1) {
// Set a flag to indicate that the window close should be allowed.
is_closing_ = true;
}
// Allow the close. For windowed browsers this will result in the OS close
// event being sent.
return false;
}
void
ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
CEF_REQUIRE_UI_THREAD();
// Remove from the list of existing browsers.
BrowserList::iterator bit = browser_list_.begin();
for (; bit != browser_list_.end(); ++bit) {
if ((*bit)->IsSame(browser)) {
browser_list_.erase(bit);
break;
}
}
if (browser_list_.empty()) {
// All browser windows have closed. Quit the application message loop.
CefQuitMessageLoop();
} else if (!browser->IsPopup()) {
// If we close main window - close all popups...
CloseAllBrowsers(true);
}
}
void
ClientHandler::OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& errorText,
const CefString& failedUrl) {
CEF_REQUIRE_UI_THREAD();
// Don't display an error for downloaded files.
if (errorCode == ERR_ABORTED)
return;
std::stringstream error_explain;
error_explain << std::string(failedUrl) <<
", with error" << std::string(errorText) <<
" (" << errorCode << ")";
LOG(INFO) << "Failed to load URL:" << error_explain.str();
frame->LoadURL(GetAccountManager()->GetCurrentAccount()->GetBaseUrl() + "internals/pages/offline");
}
void
ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) {
if (httpStatusCode != 200 || !frame->IsMain())
return; // We need only successful loaded main frame
#if 0
frame->ExecuteJavaScript(
helper::string_replace(kScriptLoader, "#URL#", "http://ya.ru"),
"",
0
);
#endif
// Fix IM autoresize
std::string code =
"(function(window) {"
"var event = document.createEvent('UIEvents');"
"event.initUIEvent('resize', true, false, window, 0);"
"window.dispatchEvent(event);"
"})(window)";
frame->ExecuteJavaScript(
code,
"",
0
);
}
void
ClientHandler::CloseAllBrowsers(bool force_close) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close));
return;
}
if (browser_list_.empty())
return;
BrowserList::const_iterator it = browser_list_.begin();
for (; it != browser_list_.end(); ++it)
(*it)->GetHost()->CloseBrowser(force_close);
}
void
ClientHandler::CloseAllPopups(bool force_close) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close));
return;
}
if (browser_list_.empty())
return;
BrowserList::const_iterator it = browser_list_.begin();
for (; it != browser_list_.end(); ++it) {
if (!(*it)->IsPopup())
continue;
(*it)->GetHost()->CloseBrowser(force_close);
}
}
void
ClientHandler::OnBeforeContextMenu(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params,
CefRefPtr<CefMenuModel> model) {
CEF_REQUIRE_UI_THREAD();
if ((params->GetTypeFlags() & (CM_TYPEFLAG_PAGE | CM_TYPEFLAG_FRAME)) != 0) {
// Add a separator if the menu already has items.
if (model->GetCount() > 0)
model->AddSeparator();
// Add DevTools items to all context menus.
model->AddItem(1, "&Show DevTools");
model->AddItem(2, "Close DevTools");
model->AddSeparator();
model->AddItem(3, "Inspect Element");
}
}
bool
ClientHandler::OnContextMenuCommand(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params,
int command_id,
EventFlags event_flags) {
CEF_REQUIRE_UI_THREAD();
switch (command_id) {
case 1:
ShowDevTools(browser, CefPoint());
return true;
case 2:
CloseDevTools(browser);
return true;
case 3:
ShowDevTools(browser, CefPoint(params->GetXCoord(), params->GetYCoord()));
return true;
default:
return false;
}
}
void
ClientHandler::ShowDevTools(CefRefPtr<CefBrowser> browser,
const CefPoint& inspect_element_at) {
CefWindowInfo windowInfo;
CefBrowserSettings settings;
#if defined(OS_WIN)
windowInfo.SetAsPopup(browser->GetHost()->GetWindowHandle(), "DevTools");
#endif
browser->GetHost()->ShowDevTools(windowInfo, this, settings,
inspect_element_at);
}
void
ClientHandler::CloseDevTools(CefRefPtr<CefBrowser> browser) {
browser->GetHost()->CloseDevTools();
}
bool
ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& target_url,
const CefString& target_frame_name,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings,
bool* no_javascript_access) {
CEF_REQUIRE_IO_THREAD();
std::string url = target_url;
if (!IsAllowedUrl(url)) {
platform_util::OpenExternal(url);
return true;
}
return false;
}
bool
ClientHandler::OnBeforeBrowse(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request,
bool is_redirect) {
std::string url = request->GetURL();
if (!IsAllowedUrl(url)) {
platform_util::OpenExternal(url);
return true;
}
return false;
}
CefRefPtr<CefResourceHandler>
ClientHandler::GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) {
CEF_REQUIRE_IO_THREAD();
std::string url = request->GetURL();
if (url.find(kInterceptionPath) == std::string::npos)
return NULL;
// Handle URLs in interception path
std::string file_name, mime_type;
if (helper::ParseUrl(url, &file_name, &mime_type)) {
// Remove interception path
file_name = file_name.substr(strlen(kInterceptionPath) - 1);
// Load the resource from file.
CefRefPtr<CefStreamReader> stream =
GetBinaryResourceReader(app_settings_.resource_dir, file_name.c_str());
if (stream.get())
return new CefStreamResourceHandler(mime_type, stream);
}
// Never let the internal links to the external world
CefRefPtr<CefStreamReader> stream =
CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(kUnknownInternalContent.c_str())),
kUnknownInternalContent.size()
);
ASSERT(stream.get());
return new CefStreamResourceHandler("text/plain", stream);
}
bool
ClientHandler::OnProcessMessageReceived(
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) {
bool handled = false;
// Check for callbacks first
if (message->GetName() == "executeCommandCallback") {
int32 commandId = message->GetArgumentList()->GetInt(0);
bool result = message->GetArgumentList()->GetBool(1);
CefRefPtr<CommandCallback> callback = command_callback_map_[commandId];
callback->CommandComplete(result);
command_callback_map_.erase(commandId);
handled = true;
}
std::string message_name = message->GetName();
// Execute delegate callbacks.
ProcessMessageDelegateSet::iterator it = process_message_delegates_.begin();
for (; it != process_message_delegates_.end() && !handled; ++it) {
if ((*it)->IsAcceptedNamespace(message_name)) {
handled = (*it)->OnProcessMessageReceived(
this,
browser,
source_process,
message
);
}
}
if (!handled)
LOG(WARNING) << "Unknown proccess message: " << message_name;
return handled;
}
void
ClientHandler::SetAccountManager(CefRefPtr<AccountManager> account_manager) {
account_manager_ = account_manager;
}
CefRefPtr<AccountManager>
ClientHandler::GetAccountManager() const {
return account_manager_;
}
void
ClientHandler::SetMainWindowHandle(CefRefPtr<MainWindow> handle) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::SetMainWindowHandle, this, handle));
return;
}
main_handle_ = handle;
}
CefRefPtr<MainWindow>
ClientHandler::GetMainWindowHandle() const {
CEF_REQUIRE_UI_THREAD();
return main_handle_;
}
void
ClientHandler::SetAppSettings(AppSettings settings) {
app_settings_ = settings;
}
AppSettings
ClientHandler::GetAppSettings() const {
return app_settings_;
}
void
ClientHandler::SetStatusIconHandle(CefRefPtr<StatusIcon> handle) {
if (!CefCurrentlyOn(TID_UI)) {
// Execute on the UI thread.
CefPostTask(TID_UI,
base::Bind(&ClientHandler::SetStatusIconHandle, this, handle));
return;
}
status_icon_handle_ = handle;
}
CefRefPtr<StatusIcon>
ClientHandler::GetStatusIconHandle() const {
CEF_REQUIRE_UI_THREAD();
return status_icon_handle_;
}
CefRefPtr<CefBrowser> ClientHandler::GetBrowser() const {
base::AutoLock lock_scope(lock_);
return browser_;
}
int
ClientHandler::GetBrowserId() const {
base::AutoLock lock_scope(lock_);
return browser_id_;
}
bool
ClientHandler::IsAllowedUrl(std::string url) {
if (
// Ugly temporary fix for file downloading...
// ToDo: fix it!
url.find("/desktop_app/download.file.php") != std::string::npos
|| url.find("/desktop_app/show.file.php") != std::string::npos
)
return false;
return (
account_manager_->GetCurrentAccount()->CheckBaseUrl(url)
|| url.find("chrome-devtools://") == 0
);
}
void
ClientHandler::SwitchAccount(int id) {
CloseAllPopups(true);
// ToDo: delete host/domain cookies here!!!
account_manager_->SwitchAccount(id);
browser_->GetMainFrame()->LoadURL(
account_manager_->GetCurrentAccount()->GetBaseUrl() + "internals/pages/portal-loader#login=yes"
);
account_manager_->Commit();
}
// static
void
ClientHandler::CreateProcessMessageDelegates(ProcessMessageDelegateSet& delegates) {
AppMessageDelegate::CreateProcessMessageDelegates(delegates);
AppWindowMessageDelegate::CreateProcessMessageDelegates(delegates);
}<|endoftext|> |
<commit_before>AliAnalysisTaskMinijet* AddTaskMinijet(Int_t runNumber = -1,
TString format = "esd",
Bool_t useMC = false,
Bool_t mcOnly = false,
Bool_t useHighMult = false
)
{
//Seetings
Float_t ptTrigMin = 0.7;
Float_t ptAssocMin = 0.4;
Float_t maxVtxZ = 10.;
Int_t filterBit = 128;
Int_t debugLevel = 0;
// Get the pointer to the existing analysis manager via the static access method.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) mgr = new AliAnalysisManager("Analysis train");
// Set TPC track cuts (used for ESDs)
AliESDtrackCuts* esdTrackCutsTPC=0x0;
if(!format.CompareTo("esd")){
esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
esdTrackCutsTPC->SetMinNClustersTPC(80);
}
// First task for min bias events
AliAnalysisTaskMinijet *taskMB =
new AliAnalysisTaskMinijet("AliAnalysisTaskMinijet Min bias");
taskMB->SetUseMC(useMC,mcOnly);
taskMB->SetTriggerPtCut(ptTrigMin);
taskMB->SetAssociatePtCut(ptAssocMin);
taskMB->SetMaxVertexZ(maxVtxZ);
taskMB->SetTriggerMask(AliVEvent::kMB);
// taskMB->SelectCollisionCandidates(AliVEvent::kMB);//MB //now inside task
taskMB->SetFilterBit(filterBit); // used only in AOD case
taskMB->SetDebugLevel(debugLevel);
if(!format.CompareTo("esd")){
taskMB->SetCuts(esdTrackCutsTPC);
taskMB->SetModeEsdAod(0); // 0 = reading ESDs
}
else if (!format.CompareTo("aod")){
// Cuts already applied through esd filter
taskMB->SetModeEsdAod(1); // 1 = reading AODs
}
// Second task for high multipliciy events
AliAnalysisTaskMinijet *taskHM =0x0;
if(useHighMult){
taskHM = new AliAnalysisTaskMinijet("AliAnalysisTaskMinijet HighMult");
taskHM->SetUseMC(useMC, mcOnly);
taskHM->SetTriggerPtCut(ptTrigMin);
taskHM->SetAssociatePtCut(ptAssocMin);
taskHM->SetMaxVertexZ(maxVtxZ);
taskHM->SetTriggerMask(AliVEvent::kHighMult);
//taskHM->SelectCollisionCandidates(AliVEvent::kHighMult); // now inside task
taskMB->SetFilterBit(filterBit); // used only in AOD case
taskHM->SetDebugLevel(debugLevel);
if(!format.CompareTo("esd")){
taskHM->SetCuts(esdTrackCutsTPC);
taskHM->SetModeEsdAod(0); // 0 = reading ESDs
}
else if (!format.CompareTo("aod")){
//cuts already applied through esd filter during writing of AODs
taskHM->SetModeEsdAod(1); // 1 = reading AODs
}
}
//create output containers
AliAnalysisDataContainer *outputMB = 0x0;
AliAnalysisDataContainer *outputHM = 0x0;
if(runNumber>0){
outputMB = mgr->CreateContainer("MiniJets",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("run%d.root",runNumber));
if(useHighMult){
outputHM = mgr->CreateContainer("MiniJets_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("run%d.root",runNumber));
}
}
else{
outputMB = mgr->CreateContainer("MiniJets",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG4_MiniJets",
AliAnalysisManager::GetCommonFileName()));
if(useHighMult){
outputHM = mgr->CreateContainer("MiniJets_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG4_MiniJets",
AliAnalysisManager::GetCommonFileName()));
}
}
// Add first task to the manager and connect container
mgr->AddTask(taskMB);
mgr->ConnectInput(taskMB, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskMB, 1, outputMB);
// Add second task to the manager and connect container
if(useHighMult){
mgr->AddTask(taskHM);
mgr->ConnectInput (taskHM, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskHM, 1, outputHM);
}
return taskMB;
}
<commit_msg>Add parameter in AddTask macro.<commit_after>AliAnalysisTaskMinijet* AddTaskMinijet(Int_t runNumber = -1,
TString format = "aod",
Bool_t useMC = false,
Bool_t mcOnly = false,
Bool_t useHighMult = false,
Float_t ptTrigMin = 0.7,
Float_t ptAssocMin = 0.4,
Float_t maxVtxZ = 10.,
Int_t filterBit = 128,
Int_t debugLevel = 0,
Float_t maxEta = 0.9,
Float_t ptMin = 0.2,
Float_t ptMax = 50.0)
{
// Get the pointer to the existing analysis manager via the static access method.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) mgr = new AliAnalysisManager("Analysis train");
// Set TPC track cuts (used for ESDs)
AliESDtrackCuts* esdTrackCutsTPC=0x0;
if(!format.CompareTo("esd")){
esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
esdTrackCutsTPC->SetMinNClustersTPC(80);
}
// First task for min bias events
AliAnalysisTaskMinijet *taskMB =
new AliAnalysisTaskMinijet("AliAnalysisTaskMinijet Min bias");
taskMB->SetUseMC(useMC,mcOnly);
taskMB->SetTriggerPtCut(ptTrigMin);
taskMB->SetAssociatePtCut(ptAssocMin);
taskMB->SetMaxEta(maxEta);
taskMB->SetPtRange(ptMin, ptMax);
taskMB->SetMaxVertexZ(maxVtxZ);
taskMB->SetTriggerMask(AliVEvent::kMB);
// taskMB->SelectCollisionCandidates(AliVEvent::kMB);//MB //now inside task
taskMB->SetFilterBit(filterBit); // used only in AOD case
taskMB->SetDebugLevel(debugLevel);
if(!format.CompareTo("esd")){
taskMB->SetCuts(esdTrackCutsTPC);
taskMB->SetModeEsdAod(0); // 0 = reading ESDs
}
else if (!format.CompareTo("aod")){
// Cuts already applied through esd filter
taskMB->SetModeEsdAod(1); // 1 = reading AODs
}
// Second task for high multipliciy events
AliAnalysisTaskMinijet *taskHM =0x0;
if(useHighMult){
taskHM = new AliAnalysisTaskMinijet("AliAnalysisTaskMinijet HighMult");
taskHM->SetUseMC(useMC, mcOnly);
taskHM->SetTriggerPtCut(ptTrigMin);
taskHM->SetAssociatePtCut(ptAssocMin);
taskMB->SetMaxEta(maxEta);
taskMB->SetPtRange(ptMin, ptMax);
taskHM->SetMaxVertexZ(maxVtxZ);
taskHM->SetTriggerMask(AliVEvent::kHighMult);
//taskHM->SelectCollisionCandidates(AliVEvent::kHighMult); // now inside task
taskMB->SetFilterBit(filterBit); // used only in AOD case
taskHM->SetDebugLevel(debugLevel);
if(!format.CompareTo("esd")){
taskHM->SetCuts(esdTrackCutsTPC);
taskHM->SetModeEsdAod(0); // 0 = reading ESDs
}
else if (!format.CompareTo("aod")){
//cuts already applied through esd filter during writing of AODs
taskHM->SetModeEsdAod(1); // 1 = reading AODs
}
}
//create output containers
AliAnalysisDataContainer *outputMB = 0x0;
AliAnalysisDataContainer *outputHM = 0x0;
if(runNumber>0){
outputMB = mgr->CreateContainer("MiniJets",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("run%d.root",runNumber));
if(useHighMult){
outputHM = mgr->CreateContainer("MiniJets_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("run%d.root",runNumber));
}
}
else{
outputMB = mgr->CreateContainer("MiniJets",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG4_MiniJets",
AliAnalysisManager::GetCommonFileName()));
if(useHighMult){
outputHM = mgr->CreateContainer("MiniJets_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG4_MiniJets",
AliAnalysisManager::GetCommonFileName()));
}
}
// Add first task to the manager and connect container
mgr->AddTask(taskMB);
mgr->ConnectInput(taskMB, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskMB, 1, outputMB);
// Add second task to the manager and connect container
if(useHighMult){
mgr->AddTask(taskHM);
mgr->ConnectInput (taskHM, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskHM, 1, outputHM);
}
return taskMB;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkAMRUtilities.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkAMRUtilities.h"
#include "vtkAMRBox.h"
#include "vtkUniformGrid.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkMPIController.h"
#include "vtkCommunicator.h"
#include <cmath>
#include <limits>
#include <cassert>
//------------------------------------------------------------------------------
void vtkAMRUtilities::PrintSelf( std::ostream& os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::GenerateMetaData(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *controller )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
CollectAMRMetaData( amrData, controller );
ComputeLevelRefinementRatio( amrData );
if( controller != NULL )
controller->Barrier();
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeDataSetOrigin(
double origin[3], vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *controller )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
double min[3];
min[0] = min[1] = min[2] = std::numeric_limits<double>::max();
// Note, we only need to check at level 0 since, the grids at
// level 0 are guaranteed to cover the entire domain. Most datasets
// will have a single grid at level 0.
for( int idx=0; idx < amrData->GetNumberOfDataSets(0); ++idx )
{
vtkUniformGrid *gridPtr = amrData->GetDataSet( 0, idx );
if( gridPtr != NULL )
{
double *gridBounds = gridPtr->GetBounds();
assert( "Failed when accessing grid bounds!" && (gridBounds!=NULL) );
if( gridBounds[0] < min[0] )
min[0] = gridBounds[0];
if( gridBounds[2] < min[1] )
min[1] = gridBounds[2];
if( gridBounds[4] < min[2] )
min[2] = gridBounds[4];
}
} // END for all data-sets at level 0
// If data is distributed, get the global min
if( controller != NULL )
{
if( controller->GetNumberOfProcesses() > 1 )
{
// TODO: Define a custom operator s.t. only one all-reduce operation
// is called.
controller->AllReduce(&min[0],&origin[0],1,vtkCommunicator::MIN_OP);
controller->AllReduce(&min[1],&origin[1],1,vtkCommunicator::MIN_OP);
controller->AllReduce(&min[2],&origin[2],1,vtkCommunicator::MIN_OP);
return;
}
}
// Else this is a single process
origin[0] = min[0];
origin[1] = min[1];
origin[2] = min[2];
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeGlobalBounds(
double bounds[6], vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
double min[3];
double max[3];
min[0] = min[1] = min[2] = std::numeric_limits<double>::max();
max[0] = max[1] = max[2] = std::numeric_limits<double>::min();
// Note, we only need to check at level 0 since, the grids at
// level 0 are guaranteed to cover the entire domain. Most datasets
// will have a single grid at level 0.
for( int idx=0; idx < amrData->GetNumberOfDataSets(0); ++idx )
{
vtkUniformGrid *gridPtr = amrData->GetDataSet( 0, idx );
if( gridPtr != NULL )
{
// Get the bounnds of the grid: {xmin,xmax,ymin,ymax,zmin,zmax}
double *gridBounds = gridPtr->GetBounds();
assert( "Failed when accessing grid bounds!" && (gridBounds!=NULL) );
// Check min
if( gridBounds[0] < min[0] )
min[0] = gridBounds[0];
if( gridBounds[2] < min[1] )
min[1] = gridBounds[2];
if( gridBounds[4] < min[2] )
min[2] = gridBounds[4];
// Check max
if( gridBounds[1] > max[0])
max[0] = gridBounds[1];
if( gridBounds[3] > max[1])
max[1] = gridBounds[3];
if( gridBounds[5] > max[2] )
max[2] = gridBounds[5];
}
} // END for all data-sets at level 0
if( myController != NULL )
{
if( myController->GetNumberOfProcesses() > 1 )
{
// All Reduce min
myController->AllReduce(&min[0],&bounds[0],1,vtkCommunicator::MIN_OP);
myController->AllReduce(&min[1],&bounds[1],1,vtkCommunicator::MIN_OP);
myController->AllReduce(&min[2],&bounds[2],1,vtkCommunicator::MIN_OP);
// All Reduce max
myController->AllReduce(&max[0],&bounds[3],1,vtkCommunicator::MAX_OP);
myController->AllReduce(&max[1],&bounds[4],1,vtkCommunicator::MAX_OP);
myController->AllReduce(&max[2],&bounds[5],1,vtkCommunicator::MAX_OP);
return;
}
}
bounds[0] = min[0];
bounds[1] = min[1];
bounds[2] = min[2];
bounds[3] = max[0];
bounds[4] = max[1];
bounds[5] = max[2];
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::CollectAMRMetaData(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL));
// STEP 0: Compute the global dataset origin
double origin[3];
ComputeDataSetOrigin( origin, amrData, myController );
// STEP 1: Compute the metadata of each process locally
int process = (myController == NULL)? 0 : myController->GetLocalProcessId();
ComputeLocalMetaData( origin, amrData, process );
// STEP 2: Distribute meta-data to all processes
if( myController != NULL )
{
DistributeMetaData( amrData, myController );
}
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::SerializeMetaData(
vtkHierarchicalBoxDataSet *amrData,
unsigned char *&buffer,
vtkIdType &numBytes )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
// STEP 0: Collect all the AMR boxes in a vector
std::vector< vtkAMRBox > boxList;
for( int level=0; level < amrData->GetNumberOfLevels(); ++level )
{
for( int idx=0; idx < amrData->GetNumberOfDataSets( level ); ++idx )
{
if( amrData->GetDataSet(level,idx) != NULL )
{
vtkAMRBox myBox;
amrData->GetMetaData(level,idx,myBox);
boxList.push_back( myBox );
}
} // END for all data at the current level
} // END for all levels
// STEP 1: Compute & Allocate buffer size
int N = boxList.size( );
numBytes = sizeof( int ) + vtkAMRBox::GetBytesize()*N;
buffer = new unsigned char[ numBytes ];
// STEP 2: Serialize the number of boxes in the buffer
unsigned char *ptr = buffer;
memcpy( ptr, &N, sizeof(int) );
ptr += sizeof(int);
// STEP 3: Serialize each box
for( int i=0; i < boxList.size( ); ++i )
{
assert( "ptr is NULL" && (ptr != NULL) );
unsigned char *tmp = NULL;
vtkIdType nbytes = 0;
boxList[ i ].Serialize( tmp, nbytes );
memcpy( ptr, tmp, vtkAMRBox::GetBytesize() );
ptr += vtkAMRBox::GetBytesize();
}
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::DeserializeMetaData(
unsigned char *buffer,
const vtkIdType numBytes,
std::vector< vtkAMRBox > &boxList )
{
// Sanity check
assert( "Buffer to deserialize is NULL" && (buffer != NULL) );
assert( "Expected numBytes > 0" && (numBytes > 0) );
unsigned char *ptr = buffer;
int N = 0;
// STEP 0: Deserialize the number of boxes in the buffer
memcpy( &N, ptr, sizeof(int) );
ptr += sizeof(int);
boxList.resize( N );
for( int i=0; i < N; ++i )
{
assert( "ptr is NULL" && (ptr != NULL) );
vtkIdType nbytes = vtkAMRBox::GetBytesize();
boxList[ i ].Deserialize( ptr, nbytes );
ptr += nbytes;
}
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::DistributeMetaData(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
assert( "Multi-Process controller is NULL" && (myController != NULL) );
// STEP 0: Serialize the meta-data owned by this process into a bytestream
unsigned char *buffer = NULL;
vtkIdType numBytes = 0;
SerializeMetaData( amrData, buffer, numBytes );
assert( "Serialized buffer should not be NULL!" && (buffer != NULL) );
assert( "Expected NumBytes > 0" && (numBytes > 0) );
// STEP 1: Get the buffer sizes at each rank with an allGather
int numRanks = myController->GetNumberOfProcesses();
vtkIdType *rcvcounts = new vtkIdType[ numRanks ];
myController->AllGather( &numBytes, rcvcounts, 1);
// STEP 2: Compute the receive buffer & Allocate
vtkIdType rbufferSize = rcvcounts[0];
for( int i=1; i < numRanks; ++i)
rbufferSize+=rcvcounts[i];
unsigned char *rcvBuffer = new unsigned char[ rbufferSize ];
assert( "Receive buffer is NULL" && (rcvBuffer != NULL) );
// STEP 3: Compute off-sets
vtkIdType *offSet = new vtkIdType[ numRanks];
offSet[0] = 0;
for( int i=1; i < numRanks; ++i )
offSet[ i ] = offSet[ i-1 ]+rcvcounts[ i-1 ];
// STEP 4: All-gatherv boxes
myController->AllGatherV( buffer, rcvBuffer, numBytes, rcvcounts, offSet );
// STEP 5: Unpack receive buffer
std::vector< std::vector< vtkAMRBox > > amrBoxes;
amrBoxes.resize( numRanks );
for( int i=0; i < numRanks; ++i )
{
if( i != myController->GetLocalProcessId() )
{
DeserializeMetaData( rcvBuffer+offSet[i],rcvcounts[i],amrBoxes[i] );
for( int j=0; j < amrBoxes[i].size(); ++j )
{
int level = amrBoxes[i][j].GetLevel();
int index = amrBoxes[i][j].GetBlockId();
amrData->SetMetaData( level,index,amrBoxes[i][j] );
}
}
}
// STEP 7: Clean up all dynamically allocated memory
delete [] buffer;
delete [] rcvcounts;
delete [] offSet;
delete [] rcvBuffer;
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::CreateAMRBoxForGrid(
double origin[3], vtkUniformGrid *myGrid, vtkAMRBox &myBox )
{
// Sanity check
assert( "Input AMR Grid is not NULL" && (myGrid != NULL) );
double *gridOrigin = myGrid->GetOrigin();
assert( "Null Grid Origin" && (gridOrigin != NULL) );
int ndim[3];
int lo[3];
int hi[3];
// Get pointer to the grid's spacing array
double *h = myGrid->GetSpacing();
assert( "Grid Spacing array is NULL!" && (h!=NULL) );
// Get the grid's cell dimensions,i.e., number of cells along each dimension.
myGrid->GetDimensions( ndim );
ndim[0]--; ndim[1]--; ndim[2]--;
// Compute lo,hi box dimensions
for( int i=0; i < 3; ++i )
{
ndim[i] = (ndim[i] < 1)? 1 : ndim[i];
lo[i] = round( (gridOrigin[i]-origin[i])/h[i] );
hi[i] = round( lo[i] + ( ndim[i]-1 ) );
}
myBox.SetDimensions( lo, hi );
myBox.SetDataSetOrigin( origin );
myBox.SetGridSpacing( h );
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeLocalMetaData(
double origin[3], vtkHierarchicalBoxDataSet* myAMRData, const int process )
{
// Sanity check
assert( "Input AMR data is NULL" && (myAMRData != NULL) );
for( int level=0; level < myAMRData->GetNumberOfLevels(); ++level )
{
for( int idx=0; idx < myAMRData->GetNumberOfDataSets(level); ++idx )
{
vtkUniformGrid *myGrid = myAMRData->GetDataSet( level, idx );
if( myGrid != NULL )
{
vtkAMRBox myBox;
CreateAMRBoxForGrid( origin, myGrid, myBox );
myBox.SetLevel( level );
myBox.SetProcessId( process );
myAMRData->SetMetaData( level, idx, myBox );
// Write box for debugging purposes.
// myBox.WriteBox();
}
} // END for all data at current level
} // END for all levels
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeLevelRefinementRatio(
vtkHierarchicalBoxDataSet *amr )
{
// sanity check
assert( "Input AMR Data is NULL" && (amr != NULL) );
int numLevels = amr->GetNumberOfLevels();
if( numLevels < 1 )
{
// Dataset is empty!
return;
}
if( numLevels == 1)
{
// No refinement, data-set has only a single level.
// The refinement ratio is set to 2 to satisfy the
// vtkHierarchicalBoxDataSet requirement.
amr->SetRefinementRatio(0,2);
return;
}
for( int level=1; level < numLevels; ++level )
{
int parentLevel = level-1;
assert("No data at parent!" && amr->GetNumberOfDataSets(parentLevel)>=1);
assert("No data in this level" && amr->GetNumberOfDataSets(level)>=1 );
vtkAMRBox parentBox;
amr->GetMetaData(parentLevel,0,parentBox);
vtkAMRBox myBox;
amr->GetMetaData(level,0,myBox);
double parentSpacing[3];
parentBox.GetGridSpacing(parentSpacing);
double currentSpacing[3];
myBox.GetGridSpacing( currentSpacing );
// Note current implementation assumes uniform spacing. The
// refinement ratio is the same in each dimension i,j,k.
int ratio = round(parentSpacing[0]/currentSpacing[0]);
// Set the ratio at the root level, i.e., level 0, to be the same as
// the ratio at level 1,since level 0 doesn't really have a refinement
// ratio.
if( level==1 )
{
amr->SetRefinementRatio(0,ratio);
}
amr->SetRefinementRatio(level,ratio);
} // END for all hi-res levels
}
<commit_msg>COMP: Resolve compiler warnings<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkAMRUtilities.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkAMRUtilities.h"
#include "vtkAMRBox.h"
#include "vtkUniformGrid.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkMPIController.h"
#include "vtkCommunicator.h"
#include <cmath>
#include <limits>
#include <cassert>
//------------------------------------------------------------------------------
void vtkAMRUtilities::PrintSelf( std::ostream& os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::GenerateMetaData(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *controller )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
CollectAMRMetaData( amrData, controller );
ComputeLevelRefinementRatio( amrData );
if( controller != NULL )
controller->Barrier();
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeDataSetOrigin(
double origin[3], vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *controller )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
double min[3];
min[0] = min[1] = min[2] = std::numeric_limits<double>::max();
// Note, we only need to check at level 0 since, the grids at
// level 0 are guaranteed to cover the entire domain. Most datasets
// will have a single grid at level 0.
for( unsigned int idx=0; idx < amrData->GetNumberOfDataSets(0); ++idx )
{
vtkUniformGrid *gridPtr = amrData->GetDataSet( 0, idx );
if( gridPtr != NULL )
{
double *gridBounds = gridPtr->GetBounds();
assert( "Failed when accessing grid bounds!" && (gridBounds!=NULL) );
if( gridBounds[0] < min[0] )
min[0] = gridBounds[0];
if( gridBounds[2] < min[1] )
min[1] = gridBounds[2];
if( gridBounds[4] < min[2] )
min[2] = gridBounds[4];
}
} // END for all data-sets at level 0
// If data is distributed, get the global min
if( controller != NULL )
{
if( controller->GetNumberOfProcesses() > 1 )
{
// TODO: Define a custom operator s.t. only one all-reduce operation
// is called.
controller->AllReduce(&min[0],&origin[0],1,vtkCommunicator::MIN_OP);
controller->AllReduce(&min[1],&origin[1],1,vtkCommunicator::MIN_OP);
controller->AllReduce(&min[2],&origin[2],1,vtkCommunicator::MIN_OP);
return;
}
}
// Else this is a single process
origin[0] = min[0];
origin[1] = min[1];
origin[2] = min[2];
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeGlobalBounds(
double bounds[6], vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
double min[3];
double max[3];
min[0] = min[1] = min[2] = std::numeric_limits<double>::max();
max[0] = max[1] = max[2] = std::numeric_limits<double>::min();
// Note, we only need to check at level 0 since, the grids at
// level 0 are guaranteed to cover the entire domain. Most datasets
// will have a single grid at level 0.
for( unsigned int idx=0; idx < amrData->GetNumberOfDataSets(0); ++idx )
{
vtkUniformGrid *gridPtr = amrData->GetDataSet( 0, idx );
if( gridPtr != NULL )
{
// Get the bounnds of the grid: {xmin,xmax,ymin,ymax,zmin,zmax}
double *gridBounds = gridPtr->GetBounds();
assert( "Failed when accessing grid bounds!" && (gridBounds!=NULL) );
// Check min
if( gridBounds[0] < min[0] )
min[0] = gridBounds[0];
if( gridBounds[2] < min[1] )
min[1] = gridBounds[2];
if( gridBounds[4] < min[2] )
min[2] = gridBounds[4];
// Check max
if( gridBounds[1] > max[0])
max[0] = gridBounds[1];
if( gridBounds[3] > max[1])
max[1] = gridBounds[3];
if( gridBounds[5] > max[2] )
max[2] = gridBounds[5];
}
} // END for all data-sets at level 0
if( myController != NULL )
{
if( myController->GetNumberOfProcesses() > 1 )
{
// All Reduce min
myController->AllReduce(&min[0],&bounds[0],1,vtkCommunicator::MIN_OP);
myController->AllReduce(&min[1],&bounds[1],1,vtkCommunicator::MIN_OP);
myController->AllReduce(&min[2],&bounds[2],1,vtkCommunicator::MIN_OP);
// All Reduce max
myController->AllReduce(&max[0],&bounds[3],1,vtkCommunicator::MAX_OP);
myController->AllReduce(&max[1],&bounds[4],1,vtkCommunicator::MAX_OP);
myController->AllReduce(&max[2],&bounds[5],1,vtkCommunicator::MAX_OP);
return;
}
}
bounds[0] = min[0];
bounds[1] = min[1];
bounds[2] = min[2];
bounds[3] = max[0];
bounds[4] = max[1];
bounds[5] = max[2];
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::CollectAMRMetaData(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL));
// STEP 0: Compute the global dataset origin
double origin[3];
ComputeDataSetOrigin( origin, amrData, myController );
// STEP 1: Compute the metadata of each process locally
int process = (myController == NULL)? 0 : myController->GetLocalProcessId();
ComputeLocalMetaData( origin, amrData, process );
// STEP 2: Distribute meta-data to all processes
if( myController != NULL )
{
DistributeMetaData( amrData, myController );
}
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::SerializeMetaData(
vtkHierarchicalBoxDataSet *amrData,
unsigned char *&buffer,
vtkIdType &numBytes )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
// STEP 0: Collect all the AMR boxes in a vector
std::vector< vtkAMRBox > boxList;
for( unsigned int level=0; level < amrData->GetNumberOfLevels(); ++level )
{
for(unsigned int idx=0;idx < amrData->GetNumberOfDataSets( level );++idx )
{
if( amrData->GetDataSet(level,idx) != NULL )
{
vtkAMRBox myBox;
amrData->GetMetaData(level,idx,myBox);
boxList.push_back( myBox );
}
} // END for all data at the current level
} // END for all levels
// STEP 1: Compute & Allocate buffer size
int N = boxList.size( );
numBytes = sizeof( int ) + vtkAMRBox::GetBytesize()*N;
buffer = new unsigned char[ numBytes ];
// STEP 2: Serialize the number of boxes in the buffer
unsigned char *ptr = buffer;
memcpy( ptr, &N, sizeof(int) );
ptr += sizeof(int);
// STEP 3: Serialize each box
for( unsigned int i=0; i < boxList.size( ); ++i )
{
assert( "ptr is NULL" && (ptr != NULL) );
unsigned char *tmp = NULL;
vtkIdType nbytes = 0;
boxList[ i ].Serialize( tmp, nbytes );
memcpy( ptr, tmp, vtkAMRBox::GetBytesize() );
ptr += vtkAMRBox::GetBytesize();
}
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::DeserializeMetaData(
unsigned char *buffer,
const vtkIdType numBytes,
std::vector< vtkAMRBox > &boxList )
{
// Sanity check
assert( "Buffer to deserialize is NULL" && (buffer != NULL) );
assert( "Expected numBytes > 0" && (numBytes > 0) );
unsigned char *ptr = buffer;
int N = 0;
// STEP 0: Deserialize the number of boxes in the buffer
memcpy( &N, ptr, sizeof(int) );
ptr += sizeof(int);
boxList.resize( N );
for( int i=0; i < N; ++i )
{
assert( "ptr is NULL" && (ptr != NULL) );
vtkIdType nbytes = vtkAMRBox::GetBytesize();
boxList[ i ].Deserialize( ptr, nbytes );
ptr += nbytes;
}
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::DistributeMetaData(
vtkHierarchicalBoxDataSet *amrData,
vtkMultiProcessController *myController )
{
// Sanity check
assert( "Input AMR Data is NULL" && (amrData != NULL) );
assert( "Multi-Process controller is NULL" && (myController != NULL) );
// STEP 0: Serialize the meta-data owned by this process into a bytestream
unsigned char *buffer = NULL;
vtkIdType numBytes = 0;
SerializeMetaData( amrData, buffer, numBytes );
assert( "Serialized buffer should not be NULL!" && (buffer != NULL) );
assert( "Expected NumBytes > 0" && (numBytes > 0) );
// STEP 1: Get the buffer sizes at each rank with an allGather
int numRanks = myController->GetNumberOfProcesses();
vtkIdType *rcvcounts = new vtkIdType[ numRanks ];
myController->AllGather( &numBytes, rcvcounts, 1);
// STEP 2: Compute the receive buffer & Allocate
vtkIdType rbufferSize = rcvcounts[0];
for( int i=1; i < numRanks; ++i)
rbufferSize+=rcvcounts[i];
unsigned char *rcvBuffer = new unsigned char[ rbufferSize ];
assert( "Receive buffer is NULL" && (rcvBuffer != NULL) );
// STEP 3: Compute off-sets
vtkIdType *offSet = new vtkIdType[ numRanks];
offSet[0] = 0;
for( int i=1; i < numRanks; ++i )
offSet[ i ] = offSet[ i-1 ]+rcvcounts[ i-1 ];
// STEP 4: All-gatherv boxes
myController->AllGatherV( buffer, rcvBuffer, numBytes, rcvcounts, offSet );
// STEP 5: Unpack receive buffer
std::vector< std::vector< vtkAMRBox > > amrBoxes;
amrBoxes.resize( numRanks );
for( int i=0; i < numRanks; ++i )
{
if( i != myController->GetLocalProcessId() )
{
DeserializeMetaData( rcvBuffer+offSet[i],rcvcounts[i],amrBoxes[i] );
for( unsigned int j=0; j < amrBoxes[i].size(); ++j )
{
int level = amrBoxes[i][j].GetLevel();
int index = amrBoxes[i][j].GetBlockId();
amrData->SetMetaData( level,index,amrBoxes[i][j] );
}
}
}
// STEP 7: Clean up all dynamically allocated memory
delete [] buffer;
delete [] rcvcounts;
delete [] offSet;
delete [] rcvBuffer;
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::CreateAMRBoxForGrid(
double origin[3], vtkUniformGrid *myGrid, vtkAMRBox &myBox )
{
// Sanity check
assert( "Input AMR Grid is not NULL" && (myGrid != NULL) );
double *gridOrigin = myGrid->GetOrigin();
assert( "Null Grid Origin" && (gridOrigin != NULL) );
int ndim[3];
int lo[3];
int hi[3];
// Get pointer to the grid's spacing array
double *h = myGrid->GetSpacing();
assert( "Grid Spacing array is NULL!" && (h!=NULL) );
// Get the grid's cell dimensions,i.e., number of cells along each dimension.
myGrid->GetDimensions( ndim );
ndim[0]--; ndim[1]--; ndim[2]--;
// Compute lo,hi box dimensions
for( int i=0; i < 3; ++i )
{
ndim[i] = (ndim[i] < 1)? 1 : ndim[i];
lo[i] = round( (gridOrigin[i]-origin[i])/h[i] );
hi[i] = round( lo[i] + ( ndim[i]-1 ) );
}
myBox.SetDimensions( lo, hi );
myBox.SetDataSetOrigin( origin );
myBox.SetGridSpacing( h );
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeLocalMetaData(
double origin[3], vtkHierarchicalBoxDataSet* myAMRData, const int process )
{
// Sanity check
assert( "Input AMR data is NULL" && (myAMRData != NULL) );
for( unsigned int level=0; level < myAMRData->GetNumberOfLevels(); ++level )
{
for(unsigned int idx=0;idx < myAMRData->GetNumberOfDataSets(level);++idx )
{
vtkUniformGrid *myGrid = myAMRData->GetDataSet( level, idx );
if( myGrid != NULL )
{
vtkAMRBox myBox;
CreateAMRBoxForGrid( origin, myGrid, myBox );
myBox.SetLevel( level );
myBox.SetProcessId( process );
myAMRData->SetMetaData( level, idx, myBox );
// Write box for debugging purposes.
// myBox.WriteBox();
}
} // END for all data at current level
} // END for all levels
}
//------------------------------------------------------------------------------
void vtkAMRUtilities::ComputeLevelRefinementRatio(
vtkHierarchicalBoxDataSet *amr )
{
// sanity check
assert( "Input AMR Data is NULL" && (amr != NULL) );
int numLevels = amr->GetNumberOfLevels();
if( numLevels < 1 )
{
// Dataset is empty!
return;
}
if( numLevels == 1)
{
// No refinement, data-set has only a single level.
// The refinement ratio is set to 2 to satisfy the
// vtkHierarchicalBoxDataSet requirement.
amr->SetRefinementRatio(0,2);
return;
}
for( int level=1; level < numLevels; ++level )
{
int parentLevel = level-1;
assert("No data at parent!" && amr->GetNumberOfDataSets(parentLevel)>=1);
assert("No data in this level" && amr->GetNumberOfDataSets(level)>=1 );
vtkAMRBox parentBox;
amr->GetMetaData(parentLevel,0,parentBox);
vtkAMRBox myBox;
amr->GetMetaData(level,0,myBox);
double parentSpacing[3];
parentBox.GetGridSpacing(parentSpacing);
double currentSpacing[3];
myBox.GetGridSpacing( currentSpacing );
// Note current implementation assumes uniform spacing. The
// refinement ratio is the same in each dimension i,j,k.
int ratio = round(parentSpacing[0]/currentSpacing[0]);
// Set the ratio at the root level, i.e., level 0, to be the same as
// the ratio at level 1,since level 0 doesn't really have a refinement
// ratio.
if( level==1 )
{
amr->SetRefinementRatio(0,ratio);
}
amr->SetRefinementRatio(level,ratio);
} // END for all hi-res levels
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008 Volker Krause <vkrause@kde.org>
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 "kabcmigrator.h"
#include "kcalmigrator.h"
#include "infodialog.h"
#include <akonadi/control.h>
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <QDBusConnection>
void connectMigrator( KResMigratorBase *m, InfoDialog *dlg )
{
if ( !dlg || !m )
return;
dlg->migratorAdded();
QObject::connect( m, SIGNAL(message(KResMigratorBase::MessageType,QString)), dlg,
SLOT(message(KResMigratorBase::MessageType,QString)) );
QObject::connect( m, SIGNAL(destroyed()), dlg, SLOT(migratorDone()) );
}
int main( int argc, char **argv )
{
KAboutData aboutData( "kres-migrator", 0,
ki18n( "KResource Migration Tool" ),
"0.1",
ki18n( "Migration of KResource settings and application to Akonadi" ),
KAboutData::License_LGPL,
ki18n( "(c) 2008 the Akonadi developers" ),
KLocalizedString(),
"http://pim.kde.org/akonadi/" );
aboutData.setProgramIconName( "akonadi" );
aboutData.addAuthor( ki18n( "Volker Krause" ), ki18n( "Author" ), "vkrause@kde.org" );
const QStringList supportedTypes = QStringList() << "contact" << "calendar";
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add( "bridge-only", ki18n("Only migrate to Akonadi KResource bridges") );
options.add( "contacts-only", ki18n("Only migrate contact resources") );
options.add( "calendar-only", ki18n("Only migrate calendar resources") );
options.add( "type <type>", ki18n("Only migrate the specified types (supported: contact, calendar)" ), "contact,calendar" );
options.add( "interactive", ki18n( "Show reporting dialog") );
options.add( "interactive-on-change", ki18n("Show report only if changes were made") );
KCmdLineArgs::addCmdLineOptions( options );
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
QStringList typesToMigrate;
foreach ( const QString &type, args->getOption( "type" ).split( ',' ) ) {
if ( !QDBusConnection::sessionBus().registerService( "org.kde.Akonadi.KResMigrator." + type ) )
kWarning() << "Migrator instance already running for type " << type;
else
typesToMigrate << type;
}
if ( typesToMigrate.isEmpty() )
return 1;
KApplication app;
app.setQuitOnLastWindowClosed( false );
KGlobal::setAllowQuit( true );
if ( !Akonadi::Control::start( 0 ) )
return 2;
InfoDialog *infoDialog = 0;
if ( args->isSet( "interactive" ) || args->isSet( "interactive-on-change" ) ) {
infoDialog = new InfoDialog( args->isSet( "interactive-on-change" ) );
infoDialog->show();
}
foreach ( const QString &type, typesToMigrate ) {
KResMigratorBase *m = 0;
if ( type == "contact" )
m = new KABCMigrator();
else if ( type == "calendar" )
m = new KCalMigrator();
else {
kError() << "Unknown resource type: " << type;
continue;
}
m->setBridgingOnly( args->isSet( "bridge-only" ) );
connectMigrator( m, infoDialog );
}
const int result = app.exec();
if ( infoDialog && infoDialog->hasError() )
return 3;
return result;
}
<commit_msg>Detect unsupported types before creating the dialog (which in case that only unsupported types have been specified cannot even be closed).<commit_after>/*
Copyright (c) 2008 Volker Krause <vkrause@kde.org>
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 "kabcmigrator.h"
#include "kcalmigrator.h"
#include "infodialog.h"
#include <akonadi/control.h>
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <QDBusConnection>
void connectMigrator( KResMigratorBase *m, InfoDialog *dlg )
{
if ( !dlg || !m )
return;
dlg->migratorAdded();
QObject::connect( m, SIGNAL(message(KResMigratorBase::MessageType,QString)), dlg,
SLOT(message(KResMigratorBase::MessageType,QString)) );
QObject::connect( m, SIGNAL(destroyed()), dlg, SLOT(migratorDone()) );
}
int main( int argc, char **argv )
{
KAboutData aboutData( "kres-migrator", 0,
ki18n( "KResource Migration Tool" ),
"0.1",
ki18n( "Migration of KResource settings and application to Akonadi" ),
KAboutData::License_LGPL,
ki18n( "(c) 2008 the Akonadi developers" ),
KLocalizedString(),
"http://pim.kde.org/akonadi/" );
aboutData.setProgramIconName( "akonadi" );
aboutData.addAuthor( ki18n( "Volker Krause" ), ki18n( "Author" ), "vkrause@kde.org" );
const QStringList supportedTypes = QStringList() << "contact" << "calendar";
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add( "bridge-only", ki18n("Only migrate to Akonadi KResource bridges") );
options.add( "contacts-only", ki18n("Only migrate contact resources") );
options.add( "calendar-only", ki18n("Only migrate calendar resources") );
options.add( "type <type>", ki18n("Only migrate the specified types (supported: contact, calendar)" ),
supportedTypes.join( "," ).toLatin1() );
options.add( "interactive", ki18n( "Show reporting dialog") );
options.add( "interactive-on-change", ki18n("Show report only if changes were made") );
KCmdLineArgs::addCmdLineOptions( options );
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
QStringList typesToMigrate;
foreach ( const QString &type, args->getOption( "type" ).split( ',' ) ) {
if ( !supportedTypes.contains( type ) )
kWarning() << "Unknown resource type: " << type;
else if ( !QDBusConnection::sessionBus().registerService( "org.kde.Akonadi.KResMigrator." + type ) )
kWarning() << "Migrator instance already running for type " << type;
else
typesToMigrate << type;
}
if ( typesToMigrate.isEmpty() )
return 1;
KApplication app;
app.setQuitOnLastWindowClosed( false );
KGlobal::setAllowQuit( true );
if ( !Akonadi::Control::start( 0 ) )
return 2;
InfoDialog *infoDialog = 0;
if ( args->isSet( "interactive" ) || args->isSet( "interactive-on-change" ) ) {
infoDialog = new InfoDialog( args->isSet( "interactive-on-change" ) );
infoDialog->show();
}
foreach ( const QString &type, typesToMigrate ) {
KResMigratorBase *m = 0;
if ( type == "contact" )
m = new KABCMigrator();
else if ( type == "calendar" )
m = new KCalMigrator();
else {
kError() << "Unknown resource type: " << type;
continue;
}
m->setBridgingOnly( args->isSet( "bridge-only" ) );
connectMigrator( m, infoDialog );
}
const int result = app.exec();
if ( infoDialog && infoDialog->hasError() )
return 3;
return result;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xdictionary.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: er $ $Date: 2002-12-06 18:50:38 $
*
* 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): _______________________________________
*
*
************************************************************************/
// xdictionary.cpp: implementation of the xdictionary class.
//
//////////////////////////////////////////////////////////////////////
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#include <com/sun/star/i18n/WordType.hpp>
#include <tools/string.hxx>
#include <xdictionary.hxx>
#include <unicode.hxx>
#include <string.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
xdictionary::xdictionary(sal_Char *lang)
{
#ifdef SAL_DLLPREFIX
OUStringBuffer aBuf( strlen(lang) + 7 + 6 ); // mostly "lib*.so" (with * == dict_zh)
aBuf.appendAscii( SAL_DLLPREFIX );
#else
OUStringBuffer aBuf( strlen(lang) + 7 + 4 ); // mostly "*.dll" (with * == dict_zh)
#endif
aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION );
oslModule hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
if( hModule ) {
int (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getExistMark").pData );
existMark = (sal_uInt8*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex1").pData );
index1 = (sal_Int16*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex2").pData );
index2 = (sal_Int32*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getLenArray").pData );
lenArray = (sal_Int32*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getDataArea").pData );
dataArea = (sal_Unicode*) (*func)();
}
else
existMark = NULL;
for (sal_Int32 i = 0; i < CACHE_MAX; i++)
cache[i].size = 0;
// for CTL breakiterator, which the word boundary should not inside cell.
useCellBoundary = sal_False;
}
xdictionary::~xdictionary() {
osl_unloadModule(hModule);
for (sal_Int32 i = 0; i < CACHE_MAX; i++) {
if (cache[i].size > 0) {
delete cache[i].contents;
delete cache[i].wordboundary;
}
}
}
sal_Bool xdictionary::exists(const sal_Unicode u) {
return existMark ? ((existMark[u>>3] & (1<<(u&0x07))) != 0) : sal_False;
}
sal_Int32 SAL_CALL
xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) {
sal_Int16 idx = index1[str[0] >> 8];
if (idx == 0xFF) return 1;
idx = (idx<<8) | (str[0]&0xff);
sal_uInt32 begin = index2[idx], end = index2[idx+1];
if (begin == 0) return 1;
str++; sLen--; // first character is not stored in the dictionary
for (sal_uInt32 i = end; i > begin; i--) {
sal_Int32 len = lenArray[i] - lenArray[i - 1];
if (sLen >= len) {
const sal_Unicode *dstr = dataArea + lenArray[i-1];
sal_Int32 pos = 0;
while (pos < len && dstr[pos] == str[pos]) { pos++; }
if (pos == len)
return len + 1;
}
}
return 1;
}
/*
* Compare two unicode string,
*/
sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) {
// Different length, different string.
if (length != boundary.endPos - boundary.startPos) return sal_False;
for (sal_Int32 i = 0; i < length; i++)
if (contents[i] != str[i + boundary.startPos]) return sal_False;
return sal_True;
}
/*
* Retrieve the segment containing the character at pos.
* @param pos : Position of the given character.
* @return true if CJK.
*/
sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos,
sal_Int32 len, Boundary& boundary) {
for (boundary.startPos = pos - 1;
boundary.startPos >= 0 &&
(unicode::isWhiteSpace(text[boundary.startPos]) || exists(text[boundary.startPos]));
boundary.startPos--);
boundary.startPos++;
for (boundary.endPos = pos;
boundary.endPos < len &&
(unicode::isWhiteSpace(text[boundary.endPos]) || exists(text[boundary.endPos]));
boundary.endPos++);
return boundary.endPos > boundary.startPos + 1;
}
WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& boundary)
{
WordBreakCache& aCache = cache[text[0] & 0x1f];
if (aCache.size != 0 && aCache.equals(text, boundary))
return aCache;
sal_Int32 len = boundary.endPos - boundary.startPos;
if (aCache.size == 0 || len > aCache.size) {
if (aCache.size != 0) {
delete aCache.contents;
delete aCache.wordboundary;
aCache.size = len;
}
else
aCache.size = DEFAULT_SIZE;
aCache.contents = new sal_Unicode[aCache.size + 1];
aCache.wordboundary = new sal_Int32[aCache.size + 2];
}
aCache.length = len;
memcpy(aCache.contents, text + boundary.startPos, len * sizeof(sal_Unicode));
*(aCache.contents + len) = 0x0000;
// reset the wordboundary in cache
memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2));
sal_Int32 i = 0; // loop variable
while (aCache.wordboundary[i] < aCache.length) {
len = 0;
// look the continuous white space as one word and cashe it
while (unicode::isWhiteSpace(text[boundary.startPos + aCache.wordboundary[i] + len]))
len ++;
if (len == 0)
len = getLongestMatch(text + boundary.startPos + aCache.wordboundary[i],
aCache.length - aCache.wordboundary[i]);
aCache.wordboundary[i+1] = aCache.wordboundary[i] + len;
i++;
if (useCellBoundary) {
sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + boundary.startPos - 1];
if (cBoundary > 0)
aCache.wordboundary[i] = cBoundary - boundary.startPos;
}
}
aCache.wordboundary[i + 1] = aCache.length + 1;
return aCache;
}
Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
// looking for the first non-whitespace character from anyPos
while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --;
return getWordBoundary(text, anyPos - 1, len, wordType, true);
}
Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
boundary = getWordBoundary(text, anyPos, len, wordType, true);
// looknig for the first non-whitespace character from anyPos
anyPos = boundary.endPos;
while (unicode::isWhiteSpace(text[anyPos])) anyPos ++;
return getWordBoundary(text, anyPos, len, wordType, true);
}
Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection)
{
Boundary boundary;
if (anyPos >= len || anyPos < 0) {
boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len;
} else if (seekSegment(text, anyPos, len, boundary)) { // character in dict
WordBreakCache& aCache = getCache(text, boundary);
sal_Int32 i = 0;
while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++;
sal_Int32 startPos = aCache.wordboundary[i - 1];
// if bDirection is false
if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) &&
unicode::isWhiteSpace(text[anyPos - 1]))
i--;
boundary.endPos = aCache.wordboundary[i] + boundary.startPos;
boundary.startPos += aCache.wordboundary[i - 1];
} else {
boundary.startPos = anyPos++;
boundary.endPos = anyPos < len ? anyPos : len;
}
if (wordType == WordType::WORD_COUNT) {
// skip punctuation for word count.
while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos]))
boundary.endPos++;
}
return boundary;
}
void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray)
{
useCellBoundary = sal_True;
cellBoundary = cellArray;
}
} } } }
<commit_msg>INTEGRATION: CWS i18napi (1.5.46); FILE MERGED 2003/04/19 19:40:58 er 1.5.46.1: #107686# drafts.com.sun.star.i18n to com.sun.star.i18n<commit_after>/*************************************************************************
*
* $RCSfile: xdictionary.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-24 11:05:35 $
*
* 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): _______________________________________
*
*
************************************************************************/
// xdictionary.cpp: implementation of the xdictionary class.
//
//////////////////////////////////////////////////////////////////////
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#include <com/sun/star/i18n/WordType.hpp>
#include <tools/string.hxx>
#include <xdictionary.hxx>
#include <i18nutil/unicode.hxx>
#include <string.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
xdictionary::xdictionary(sal_Char *lang)
{
#ifdef SAL_DLLPREFIX
OUStringBuffer aBuf( strlen(lang) + 7 + 6 ); // mostly "lib*.so" (with * == dict_zh)
aBuf.appendAscii( SAL_DLLPREFIX );
#else
OUStringBuffer aBuf( strlen(lang) + 7 + 4 ); // mostly "*.dll" (with * == dict_zh)
#endif
aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION );
oslModule hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
if( hModule ) {
int (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getExistMark").pData );
existMark = (sal_uInt8*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex1").pData );
index1 = (sal_Int16*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex2").pData );
index2 = (sal_Int32*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getLenArray").pData );
lenArray = (sal_Int32*) (*func)();
func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getDataArea").pData );
dataArea = (sal_Unicode*) (*func)();
}
else
existMark = NULL;
for (sal_Int32 i = 0; i < CACHE_MAX; i++)
cache[i].size = 0;
// for CTL breakiterator, which the word boundary should not inside cell.
useCellBoundary = sal_False;
}
xdictionary::~xdictionary() {
osl_unloadModule(hModule);
for (sal_Int32 i = 0; i < CACHE_MAX; i++) {
if (cache[i].size > 0) {
delete cache[i].contents;
delete cache[i].wordboundary;
}
}
}
sal_Bool xdictionary::exists(const sal_Unicode u) {
return existMark ? ((existMark[u>>3] & (1<<(u&0x07))) != 0) : sal_False;
}
sal_Int32 SAL_CALL
xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) {
sal_Int16 idx = index1[str[0] >> 8];
if (idx == 0xFF) return 1;
idx = (idx<<8) | (str[0]&0xff);
sal_uInt32 begin = index2[idx], end = index2[idx+1];
if (begin == 0) return 1;
str++; sLen--; // first character is not stored in the dictionary
for (sal_uInt32 i = end; i > begin; i--) {
sal_Int32 len = lenArray[i] - lenArray[i - 1];
if (sLen >= len) {
const sal_Unicode *dstr = dataArea + lenArray[i-1];
sal_Int32 pos = 0;
while (pos < len && dstr[pos] == str[pos]) { pos++; }
if (pos == len)
return len + 1;
}
}
return 1;
}
/*
* Compare two unicode string,
*/
sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) {
// Different length, different string.
if (length != boundary.endPos - boundary.startPos) return sal_False;
for (sal_Int32 i = 0; i < length; i++)
if (contents[i] != str[i + boundary.startPos]) return sal_False;
return sal_True;
}
/*
* Retrieve the segment containing the character at pos.
* @param pos : Position of the given character.
* @return true if CJK.
*/
sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos,
sal_Int32 len, Boundary& boundary) {
for (boundary.startPos = pos - 1;
boundary.startPos >= 0 &&
(unicode::isWhiteSpace(text[boundary.startPos]) || exists(text[boundary.startPos]));
boundary.startPos--);
boundary.startPos++;
for (boundary.endPos = pos;
boundary.endPos < len &&
(unicode::isWhiteSpace(text[boundary.endPos]) || exists(text[boundary.endPos]));
boundary.endPos++);
return boundary.endPos > boundary.startPos + 1;
}
WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& boundary)
{
WordBreakCache& aCache = cache[text[0] & 0x1f];
if (aCache.size != 0 && aCache.equals(text, boundary))
return aCache;
sal_Int32 len = boundary.endPos - boundary.startPos;
if (aCache.size == 0 || len > aCache.size) {
if (aCache.size != 0) {
delete aCache.contents;
delete aCache.wordboundary;
aCache.size = len;
}
else
aCache.size = DEFAULT_SIZE;
aCache.contents = new sal_Unicode[aCache.size + 1];
aCache.wordboundary = new sal_Int32[aCache.size + 2];
}
aCache.length = len;
memcpy(aCache.contents, text + boundary.startPos, len * sizeof(sal_Unicode));
*(aCache.contents + len) = 0x0000;
// reset the wordboundary in cache
memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2));
sal_Int32 i = 0; // loop variable
while (aCache.wordboundary[i] < aCache.length) {
len = 0;
// look the continuous white space as one word and cashe it
while (unicode::isWhiteSpace(text[boundary.startPos + aCache.wordboundary[i] + len]))
len ++;
if (len == 0)
len = getLongestMatch(text + boundary.startPos + aCache.wordboundary[i],
aCache.length - aCache.wordboundary[i]);
aCache.wordboundary[i+1] = aCache.wordboundary[i] + len;
i++;
if (useCellBoundary) {
sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + boundary.startPos - 1];
if (cBoundary > 0)
aCache.wordboundary[i] = cBoundary - boundary.startPos;
}
}
aCache.wordboundary[i + 1] = aCache.length + 1;
return aCache;
}
Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
// looking for the first non-whitespace character from anyPos
while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --;
return getWordBoundary(text, anyPos - 1, len, wordType, true);
}
Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
boundary = getWordBoundary(text, anyPos, len, wordType, true);
// looknig for the first non-whitespace character from anyPos
anyPos = boundary.endPos;
while (unicode::isWhiteSpace(text[anyPos])) anyPos ++;
return getWordBoundary(text, anyPos, len, wordType, true);
}
Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection)
{
Boundary boundary;
if (anyPos >= len || anyPos < 0) {
boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len;
} else if (seekSegment(text, anyPos, len, boundary)) { // character in dict
WordBreakCache& aCache = getCache(text, boundary);
sal_Int32 i = 0;
while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++;
sal_Int32 startPos = aCache.wordboundary[i - 1];
// if bDirection is false
if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) &&
unicode::isWhiteSpace(text[anyPos - 1]))
i--;
boundary.endPos = aCache.wordboundary[i] + boundary.startPos;
boundary.startPos += aCache.wordboundary[i - 1];
} else {
boundary.startPos = anyPos++;
boundary.endPos = anyPos < len ? anyPos : len;
}
if (wordType == WordType::WORD_COUNT) {
// skip punctuation for word count.
while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos]))
boundary.endPos++;
}
return boundary;
}
void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray)
{
useCellBoundary = sal_True;
cellBoundary = cellArray;
}
} } } }
<|endoftext|> |
<commit_before>/*
* ForwardChainer.cc
*
* Copyright (C) 2014,2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/util/Logger.h>
#include <opencog/atoms/bind/PatternLink.h>
#include <opencog/atomutils/AtomUtils.h>
#include <opencog/query/DefaultImplicator.h>
#include <opencog/rule-engine/Rule.h>
#include <opencog/atoms/bind/BindLink.h>
#include "ForwardChainer.h"
#include "ForwardChainerCallBack.h"
using namespace opencog;
ForwardChainer::ForwardChainer(AtomSpace& as, Handle rbs) :
_as(as), _rec(_as), _rbs(rbs), _configReader(as, rbs), _fcmem(&as)
{
init();
}
void ForwardChainer::init()
{
_fcmem.set_search_in_af(_configReader.get_attention_allocation());
_fcmem.set_rules(_configReader.get_rules());
_fcmem.set_cur_rule(nullptr);
// Provide a logger
_log = NULL;
setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true));
}
void ForwardChainer::setLogger(Logger* log)
{
if (_log)
delete _log;
_log = log;
}
Logger* ForwardChainer::getLogger()
{
return _log;
}
/**
* Does one step forward chaining
*
* @param fcb a concrete implementation of of ForwardChainerCallBack class
*/
UnorderedHandleSet ForwardChainer::do_step(bool search_focus_set/* = false*/)
{
Handle hsource = choose_next_source(_fcmem);
_log->debug("[ForwardChainer] Next source %s", hsource->toString().c_str());
_fcmem.set_source(hsource);
HandleSeq derived_rhandles;
//choose a rule that source unifies with one of its premises.
Rule *rule = choose_rule(hsource, false);
if (rule) {
_fcmem.set_cur_rule(rule);
derived_rhandles = derive_rules(hsource, rule);
} else {
//choose rule that unifies that source unifies with sub-atoms of its premises.
rule = choose_rule(hsource, true);
if (rule) {
_fcmem.set_cur_rule(rule);
derived_rhandles = derive_rules(hsource, rule,
true);
}
}
_log->debug( "Derived rule size = %d", derived_rhandles.size());
UnorderedHandleSet products;
for (Handle rhandle : derived_rhandles) {
HandleSeq temp_result = apply_rule(rhandle,search_focus_set);
std::copy(temp_result.begin(), temp_result.end(),
std::inserter(products, products.end()));
}
return products;
}
void ForwardChainer::do_chain(Handle hsource, HandleSeq focus_set)
{
validate(hsource,focus_set);
_fcmem.set_focus_set(focus_set);
HandleSeq init_sources;
//Accept set of initial sources wrapped in a SET_LINK
if(LinkCast(hsource) and hsource->getType() == SET_LINK)
{
init_sources = _as.get_outgoing(hsource);
//Relex2Logic uses this.TODO make a separate class
//to handle this robustly.
if(init_sources.empty())
{
bool search_in_af = not focus_set.empty();
apply_all_rules(search_in_af);
return;
}
}
else
{
init_sources.push_back(hsource);
}
// Variable fulfillment query.
UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource,
{ VARIABLE_NODE });
if (not var_nodes.empty())
return do_pm(hsource, var_nodes);
// Default forward chaining
_fcmem.update_potential_sources(init_sources);
auto max_iter = _configReader.get_maximum_iterations();
while (_iteration < max_iter /*OR other termination criteria*/) {
_log->debug("Iteration %d", _iteration);
UnorderedHandleSet products;
if (focus_set.empty())
products = do_step(false);
else
products = do_step(true);
_fcmem.add_rules_product(_iteration,
HandleSeq(products.begin(), products.end()));
_fcmem.update_potential_sources(
HandleSeq(products.begin(), products.end()));
_iteration++;
}
_log->debug("[ForwardChainer] finished forwarch chaining.");
}
/**
* Does pattern matching for a variable containing query.
* @param source a variable containing handle passed as an input to the pattern matcher
* @param var_nodes the VariableNodes in @param hsource
* @param fcb a forward chainer callback implementation used here only for choosing rules
* that contain @param hsource in their implicant
*/
void ForwardChainer::do_pm(const Handle& hsource,
const UnorderedHandleSet& var_nodes,
ForwardChainerCallBack& fcb)
{
DefaultImplicator impl(&_as);
impl.implicand = hsource;
HandleSeq vars;
for (auto h : var_nodes)
vars.push_back(h);
_fcmem.set_source(hsource);
Handle hvar_list = _as.add_link(VARIABLE_LIST, vars);
Handle hclause = _as.add_link(AND_LINK, hsource);
// Run the pattern matcher, find all patterns that satisfy the
// the clause, with the given variables in it.
PatternLinkPtr sl(createPatternLink(hvar_list, hclause));
sl->satisfy(impl);
// Update result
_fcmem.add_rules_product(0, impl.get_result_list());
// Delete the AND_LINK and LIST_LINK
_as.remove_atom(hvar_list);
_as.remove_atom(hclause);
//!Additionally, find applicable rules and apply.
vector<Rule*> rules = fcb.choose_rules(_fcmem);
for (Rule* rule : rules) {
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(&_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_fcmem.add_rules_product(0, impl.get_result_list());
}
}
/**
* Invokes pattern matcher using each rule declared in the configuration file.
*/
void ForwardChainer::do_pm()
{
//! Do pattern matching using the rules declared in the declaration file
_log->info("Forward chaining on the rule-based system %s "
"declared in %s", _rbs->toString().c_str());
vector<Rule*> rules = _fcmem.get_rules();
for (Rule* rule : rules) {
_log->info("Applying rule %s on ", rule->get_name().c_str());
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(&_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_log->info("OUTPUTS");
for (auto h : impl.get_result_list())
_log->info("%s", h->toString().c_str());
_fcmem.add_rules_product(0, impl.get_result_list());
}
}
HandleSeq ForwardChainer::get_chaining_result()
{
return _fcmem.get_result();
}
Rule* ForwardChainer::choose_rule(Handle hsource, bool subatom_match)
{
//TODO move this somewhere else
std::map<Rule*, float> rule_weight;
for (Rule* r : _fcmem.get_rules())
rule_weight[r] = r->get_weight();
_log->debug("[ForwardChainer] %d rules to be searched",rule_weight.size());
//Select a rule among the admissible rules in the rule-base via stochastic
//selection,based on the weights of the rules in the current context.
Rule* rule = nullptr;
bool unifiable = false;
if (subatom_match) {
_log->debug("[ForwardChainer] Subatom-unifying. %s",(hsource->toShortString()).c_str());
while (!unifiable and !rule_weight.empty()) {
Rule* temp = _rec.tournament_select(rule_weight);
if (subatom_unify(hsource, temp)) {
unifiable = true;
rule = temp;
break;
}
rule_weight.erase(temp);
}
} else {
_log->debug("[ForwardChainer] Unifying. %s",(hsource->toShortString()).c_str());
while (!unifiable and !rule_weight.empty()) {
Rule *temp = _rec.tournament_select(rule_weight);
HandleSeq hs = temp->get_implicant_seq();
for (Handle target : hs) {
if (unify(hsource, target, temp)) {
unifiable = true;
rule = temp;
break;
}
}
rule_weight.erase(temp);
}
}
if(nullptr != rule)
_log->debug("[ForwardChainer] Selected rule is %s",
(rule->get_handle())->toShortString().c_str());
else
_log->debug("[ForwardChainer] No match found.");
return rule;
};
<commit_msg>Rule application newer implementation<commit_after>/*
* ForwardChainer.cc
*
* Copyright (C) 2014,2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/util/Logger.h>
#include <opencog/atoms/bind/PatternLink.h>
#include <opencog/atomutils/AtomUtils.h>
#include <opencog/query/DefaultImplicator.h>
#include <opencog/rule-engine/Rule.h>
#include <opencog/atoms/bind/BindLink.h>
#include "ForwardChainer.h"
#include "ForwardChainerCallBack.h"
using namespace opencog;
ForwardChainer::ForwardChainer(AtomSpace& as, Handle rbs) :
_as(as), _rec(_as), _rbs(rbs), _configReader(as, rbs), _fcmem(&as)
{
init();
}
void ForwardChainer::init()
{
_fcmem.set_search_in_af(_configReader.get_attention_allocation());
_fcmem.set_rules(_configReader.get_rules());
_fcmem.set_cur_rule(nullptr);
// Provide a logger
_log = NULL;
setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true));
}
void ForwardChainer::setLogger(Logger* log)
{
if (_log)
delete _log;
_log = log;
}
Logger* ForwardChainer::getLogger()
{
return _log;
}
/**
* Does one step forward chaining
*
* @param fcb a concrete implementation of of ForwardChainerCallBack class
*/
UnorderedHandleSet ForwardChainer::do_step(bool search_focus_set/* = false*/)
{
Handle hsource = choose_next_source(_fcmem);
_log->debug("[ForwardChainer] Next source %s", hsource->toString().c_str());
_fcmem.set_source(hsource);
HandleSeq derived_rhandles;
//choose a rule that source unifies with one of its premises.
Rule *rule = choose_rule(hsource, false);
if (rule) {
_fcmem.set_cur_rule(rule);
derived_rhandles = derive_rules(hsource, rule);
} else {
//choose rule that unifies that source unifies with sub-atoms of its premises.
rule = choose_rule(hsource, true);
if (rule) {
_fcmem.set_cur_rule(rule);
derived_rhandles = derive_rules(hsource, rule,
true);
}
}
_log->debug( "Derived rule size = %d", derived_rhandles.size());
UnorderedHandleSet products;
for (Handle rhandle : derived_rhandles) {
HandleSeq temp_result = apply_rule(rhandle,search_focus_set);
std::copy(temp_result.begin(), temp_result.end(),
std::inserter(products, products.end()));
}
return products;
}
void ForwardChainer::do_chain(Handle hsource, HandleSeq focus_set)
{
validate(hsource,focus_set);
_fcmem.set_focus_set(focus_set);
HandleSeq init_sources;
//Accept set of initial sources wrapped in a SET_LINK
if(LinkCast(hsource) and hsource->getType() == SET_LINK)
{
init_sources = _as.get_outgoing(hsource);
//Relex2Logic uses this.TODO make a separate class
//to handle this robustly.
if(init_sources.empty())
{
bool search_in_af = not focus_set.empty();
apply_all_rules(search_in_af);
return;
}
}
else
{
init_sources.push_back(hsource);
}
// Variable fulfillment query.
UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource,
{ VARIABLE_NODE });
if (not var_nodes.empty())
return do_pm(hsource, var_nodes);
// Default forward chaining
_fcmem.update_potential_sources(init_sources);
auto max_iter = _configReader.get_maximum_iterations();
while (_iteration < max_iter /*OR other termination criteria*/) {
_log->debug("Iteration %d", _iteration);
UnorderedHandleSet products;
if (focus_set.empty())
products = do_step(false);
else
products = do_step(true);
_fcmem.add_rules_product(_iteration,
HandleSeq(products.begin(), products.end()));
_fcmem.update_potential_sources(
HandleSeq(products.begin(), products.end()));
_iteration++;
}
_log->debug("[ForwardChainer] finished forwarch chaining.");
}
/**
* Does pattern matching for a variable containing query.
* @param source a variable containing handle passed as an input to the pattern matcher
* @param var_nodes the VariableNodes in @param hsource
* @param fcb a forward chainer callback implementation used here only for choosing rules
* that contain @param hsource in their implicant
*/
void ForwardChainer::do_pm(const Handle& hsource,
const UnorderedHandleSet& var_nodes,
ForwardChainerCallBack& fcb)
{
DefaultImplicator impl(&_as);
impl.implicand = hsource;
HandleSeq vars;
for (auto h : var_nodes)
vars.push_back(h);
_fcmem.set_source(hsource);
Handle hvar_list = _as.add_link(VARIABLE_LIST, vars);
Handle hclause = _as.add_link(AND_LINK, hsource);
// Run the pattern matcher, find all patterns that satisfy the
// the clause, with the given variables in it.
PatternLinkPtr sl(createPatternLink(hvar_list, hclause));
sl->satisfy(impl);
// Update result
_fcmem.add_rules_product(0, impl.get_result_list());
// Delete the AND_LINK and LIST_LINK
_as.remove_atom(hvar_list);
_as.remove_atom(hclause);
//!Additionally, find applicable rules and apply.
vector<Rule*> rules = fcb.choose_rules(_fcmem);
for (Rule* rule : rules) {
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(&_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_fcmem.add_rules_product(0, impl.get_result_list());
}
}
/**
* Invokes pattern matcher using each rule declared in the configuration file.
*/
void ForwardChainer::do_pm()
{
//! Do pattern matching using the rules declared in the declaration file
_log->info("Forward chaining on the rule-based system %s "
"declared in %s", _rbs->toString().c_str());
vector<Rule*> rules = _fcmem.get_rules();
for (Rule* rule : rules) {
_log->info("Applying rule %s on ", rule->get_name().c_str());
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(&_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_log->info("OUTPUTS");
for (auto h : impl.get_result_list())
_log->info("%s", h->toString().c_str());
_fcmem.add_rules_product(0, impl.get_result_list());
}
}
HandleSeq ForwardChainer::get_chaining_result()
{
return _fcmem.get_result();
}
Rule* ForwardChainer::choose_rule(Handle hsource, bool subatom_match)
{
//TODO move this somewhere else
std::map<Rule*, float> rule_weight;
for (Rule* r : _fcmem.get_rules())
rule_weight[r] = r->get_weight();
_log->debug("[ForwardChainer] %d rules to be searched",rule_weight.size());
//Select a rule among the admissible rules in the rule-base via stochastic
//selection,based on the weights of the rules in the current context.
Rule* rule = nullptr;
bool unifiable = false;
if (subatom_match) {
_log->debug("[ForwardChainer] Subatom-unifying. %s",(hsource->toShortString()).c_str());
while (!unifiable and !rule_weight.empty()) {
Rule* temp = _rec.tournament_select(rule_weight);
if (subatom_unify(hsource, temp)) {
unifiable = true;
rule = temp;
break;
}
rule_weight.erase(temp);
}
} else {
_log->debug("[ForwardChainer] Unifying. %s",(hsource->toShortString()).c_str());
while (!unifiable and !rule_weight.empty()) {
Rule *temp = _rec.tournament_select(rule_weight);
HandleSeq hs = temp->get_implicant_seq();
for (Handle target : hs) {
if (unify(hsource, target, temp)) {
unifiable = true;
rule = temp;
break;
}
}
rule_weight.erase(temp);
}
}
if(nullptr != rule)
_log->debug("[ForwardChainer] Selected rule is %s",
(rule->get_handle())->toShortString().c_str());
else
_log->debug("[ForwardChainer] No match found.");
return rule;
};
HandleSeq ForwardChainer::apply_rule(Handle rhandle,bool search_in_focus_set /*=false*/)
{
HandleSeq result;
if (search_in_focus_set) {
//This restricts PM to look only in the focus set
AtomSpace focus_set_as;
//Add focus set atoms to focus_set atomspace
HandleSeq focus_set_atoms = _fcmem.get_focus_set();
for (Handle h : focus_set_atoms)
focus_set_as.add_atom(h);
//Add source atoms to focus_set atomspace
HandleSeq sources = _fcmem.get_potential_sources();
for (Handle h : sources)
focus_set_as.add_atom(h);
//rhandle may introduce a new atoms that satisfies condition for the output
//In order to prevent this undesirable effect, lets store rhandle in a child
//atomspace of parent focus_set_as so that PM will never be able to find this
//new undesired atom created from partial grounding.
AtomSpace derived_rule_as(&focus_set_as);
Handle rhcpy = derived_rule_as.add_atom(rhandle);
BindLinkPtr bl = BindLinkCast(rhcpy);
FocusSetPMCB fs_pmcb(&derived_rule_as, &_as);
fs_pmcb.implicand = bl->get_implicand();
_log->debug("Applying rule in focus set %s ",(rhcpy->toShortString()).c_str());
std::cout << "ATOMSPACE:" << derived_rule_as << std::endl;
bl->imply(fs_pmcb);
result = fs_pmcb.get_result_list();
_log->debug(
"Result is %s ",
((_as.add_link(SET_LINK, result))->toShortString()).c_str());
}
//Search the whole atomspace
else {
AtomSpace derived_rule_as(&_as);
Handle rhcpy = derived_rule_as.add_atom(rhandle);
_log->debug("Applying rule on atomspace %s ",(rhcpy->toShortString()).c_str());
Handle h = bindlink(&derived_rule_as,rhcpy);
_log->debug("Result is %s ",(h->toShortString()).c_str());
result = derived_rule_as.get_outgoing(h);
}
//add the results back to main atomspace
for(Handle h:result) _as.add_atom(h);
return result;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
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 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 <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"
int main(int argc, char* argv[])
{
using namespace libtorrent;
if (argc != 2)
{
std::cerr << "usage: dump_torrent torrent-file\n";
return 1;
}
int size = file_size(argv[1]);
if (size > 10 * 1000000)
{
std::cerr << "file too big (" << size << "), aborting\n";
return 1;
}
std::vector<char> buf(size);
std::ifstream(argv[1], std::ios_base::binary).read(&buf[0], size);
lazy_entry e;
int ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);
if (ret != 0)
{
std::cerr << "invalid bencoding: " << ret << std::endl;
return 1;
}
std::cout << "\n\n----- raw info -----\n\n";
std::cout << print_entry(e) << std::endl;
error_code ec;
torrent_info t(e, ec);
if (ec)
{
std::cout << ec.message() << std::endl;
return 1;
}
// print info about torrent
std::cout << "\n\n----- torrent file info -----\n\n";
std::cout << "nodes:\n";
typedef std::vector<std::pair<std::string, int> > node_vec;
node_vec const& nodes = t.nodes();
for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
i != end; ++i)
{
std::cout << i->first << ":" << i->second << "\n";
}
std::cout << "trackers:\n";
for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
i != t.trackers().end(); ++i)
{
std::cout << i->tier << ": " << i->url << "\n";
}
std::cout << "number of pieces: " << t.num_pieces() << "\n";
std::cout << "piece length: " << t.piece_length() << "\n";
char ih[41];
to_hex((char const*)&t.info_hash()[0], 20, ih);
std::cout << "info hash: " << ih << "\n";
std::cout << "comment: " << t.comment() << "\n";
std::cout << "created by: " << t.creator() << "\n";
std::cout << "magnet link: " << make_magnet_uri(t) << "\n";
std::cout << "name: " << t.name() << "\n";
std::cout << "files:\n";
int index = 0;
for (torrent_info::file_iterator i = t.begin_files();
i != t.end_files(); ++i, ++index)
{
int first = t.map_file(index, 0, 0).piece;
int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
std::cout << " " << std::setw(11) << i->size
<< " "
<< (i->pad_file?'p':'-')
<< (i->executable_attribute?'x':'-')
<< (i->hidden_attribute?'h':'-')
<< (i->symlink_attribute?'l':'-')
<< " "
<< "[ " << std::setw(4) << first << ", " << std::setw(4) << last << " ]\t"
<< i->path;
if (i->symlink_attribute)
std::cout << " -> " << i->symlink_path;
std::cout << std::endl;
}
return 0;
}
<commit_msg>replaced iostream in dump_torrent example<commit_after>/*
Copyright (c) 2003, Arvid Norberg
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 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 "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"
int main(int argc, char* argv[])
{
using namespace libtorrent;
if (argc != 2)
{
fputs("usage: dump_torrent torrent-file\n", stderr);
return 1;
}
int size = file_size(argv[1]);
if (size > 10 * 1000000)
{
fprintf(stderr, "file too big (%d), aborting\n", size);
return 1;
}
std::vector<char> buf(size);
int ret = load_file(argv[1], buf);
if (ret != 0)
{
fprintf(stderr, "failed to load file: %d\n", ret);
return 1;
}
lazy_entry e;
ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);
if (ret != 0)
{
fprintf(stderr, "invalid bencoding: %d\n", ret);
return 1;
}
printf("\n\n----- raw info -----\n\n%s\n", print_entry(e).c_str());
error_code ec;
torrent_info t(e, ec);
if (ec)
{
fprintf(stderr, "%s\n", ec.message().c_str());
return 1;
}
// print info about torrent
printf("\n\n----- torrent file info -----\n\n"
"nodes:\n");
typedef std::vector<std::pair<std::string, int> > node_vec;
node_vec const& nodes = t.nodes();
for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
i != end; ++i)
{
printf("%s: %d\n", i->first.c_str(), i->second);
}
puts("trackers:\n");
for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
i != t.trackers().end(); ++i)
{
printf("%2d: %s\n", i->tier, i->url.c_str());
}
char ih[41];
to_hex((char const*)&t.info_hash()[0], 20, ih);
printf("number of pieces: %d\n"
"piece length: %d\n"
"info hash: %s\n"
"comment: %s\n"
"created by: %s\n"
"magnet link: %s\n"
"name: %s\n"
"files:\n"
, t.num_pieces()
, t.piece_length()
, ih
, t.comment().c_str()
, t.creator().c_str()
, make_magnet_uri(t).c_str()
, t.name().c_str());
int index = 0;
for (torrent_info::file_iterator i = t.begin_files();
i != t.end_files(); ++i, ++index)
{
int first = t.map_file(index, 0, 0).piece;
int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
printf(" %11"PRId64" %c%c%c%c [ %4d, %4d ] %s %s%s\n"
, i->size
, (i->pad_file?'p':'-')
, (i->executable_attribute?'x':'-')
, (i->hidden_attribute?'h':'-')
, (i->symlink_attribute?'l':'-')
, first, last, i->path.c_str()
, i->symlink_attribute ? "-> ": ""
, i->symlink_attribute ? i->symlink_path.c_str() : "");
}
return 0;
}
<|endoftext|> |
<commit_before>#include "DeclarativeSettings.hpp"
#include "Utils.hpp"
#include <QLoggingCategory>
namespace Telegram {
namespace Client {
DeclarativeRsaKey::DeclarativeRsaKey(QObject *parent)
: QObject(parent)
{
}
bool DeclarativeRsaKey::isValid() const
{
return m_key.isValid();
}
bool DeclarativeRsaKey::loadDefault() const
{
return m_loadDefaultKey;
}
void DeclarativeRsaKey::setFileName(const QString &fileName)
{
qDebug() << Q_FUNC_INFO << fileName;
if (m_fileName == fileName) {
return;
}
m_fileName = fileName;
if (!fileName.isEmpty()) {
const QUrl url(fileName);
setKey(RsaKey::fromFile(url.toLocalFile()));
}
emit fileNameChanged(fileName);
}
void DeclarativeRsaKey::setLoadDefault(bool loadDefault)
{
if (m_loadDefaultKey == loadDefault) {
return;
}
m_loadDefaultKey = loadDefault;
if (loadDefault) {
setKey(Utils::loadHardcodedKey());
}
emit loadDefaultChanged(loadDefault);
}
void DeclarativeRsaKey::setKey(const RsaKey &key)
{
RsaKey oldKey = m_key;
m_key = key;
if (oldKey.isValid() != key.isValid()) {
emit validChanged(key.isValid());
}
}
DeclarativeProxySettings::DeclarativeProxySettings(QObject *parent) :
QObject(parent)
{
}
void DeclarativeProxySettings::setPort(quint16 port)
{
m_port = port;
}
void DeclarativeProxySettings::setAddress(const QString &address)
{
m_address = address;
}
DeclarativeSettings::DeclarativeSettings(QObject *parent) :
Settings(parent)
{
m_proxySettings = new DeclarativeProxySettings(this);
}
QQmlListProperty<DeclarativeServerOption> DeclarativeSettings::serverOptions()
{
return QQmlListProperty<DeclarativeServerOption>(this, this,
&DeclarativeSettings::appendServerOption,
&DeclarativeSettings::serverOptionCount,
&DeclarativeSettings::getServerOption,
&DeclarativeSettings::clearServerOptions);
}
void DeclarativeSettings::appendServerOption(DeclarativeServerOption *option)
{
m_options.append(option);
syncSettings();
}
void DeclarativeSettings::setServerKey(DeclarativeRsaKey *serverKey)
{
m_serverKey = serverKey;
emit serverKeyChanged();
syncSettings();
}
void DeclarativeSettings::syncSettings()
{
QVector<Telegram::DcOption> dcs;
for (const DeclarativeServerOption *declOption : m_options) {
dcs.append(*declOption);
}
if (m_serverKey) {
setServerRsaKey(m_serverKey->key());
}
setServerConfiguration(dcs);
QNetworkProxy proxy;
if (!m_proxySettings->address().isEmpty()) {
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(m_proxySettings->address());
proxy.setPort(m_proxySettings->port());
}
setProxy(proxy);
}
void DeclarativeSettings::appendServerOption(QQmlListProperty<DeclarativeServerOption> *list, DeclarativeServerOption *option)
{
reinterpret_cast<DeclarativeSettings*>(list->data)->appendServerOption(option);
}
int DeclarativeSettings::serverOptionCount(QQmlListProperty<DeclarativeServerOption> *list)
{
return reinterpret_cast<DeclarativeSettings*>(list->data)->serverOptionCount();
}
DeclarativeServerOption *DeclarativeSettings::getServerOption(QQmlListProperty<DeclarativeServerOption> *list, int index)
{
return reinterpret_cast<DeclarativeSettings*>(list->data)->getServerOption(index);
}
void DeclarativeSettings::clearServerOptions(QQmlListProperty<DeclarativeServerOption> *list)
{
reinterpret_cast<DeclarativeSettings*>(list->data)->clearServerOptions();
}
} // Client
} // Telegram
<commit_msg>QML Plugin/RsaKey: Fix access to defaultServerPublicRsaKey()<commit_after>#include "DeclarativeSettings.hpp"
#include <QLoggingCategory>
namespace Telegram {
namespace Client {
DeclarativeRsaKey::DeclarativeRsaKey(QObject *parent)
: QObject(parent)
{
}
bool DeclarativeRsaKey::isValid() const
{
return m_key.isValid();
}
bool DeclarativeRsaKey::loadDefault() const
{
return m_loadDefaultKey;
}
void DeclarativeRsaKey::setFileName(const QString &fileName)
{
qDebug() << Q_FUNC_INFO << fileName;
if (m_fileName == fileName) {
return;
}
m_fileName = fileName;
if (!fileName.isEmpty()) {
const QUrl url(fileName);
setKey(RsaKey::fromFile(url.toLocalFile()));
}
emit fileNameChanged(fileName);
}
void DeclarativeRsaKey::setLoadDefault(bool loadDefault)
{
if (m_loadDefaultKey == loadDefault) {
return;
}
m_loadDefaultKey = loadDefault;
if (loadDefault) {
setKey(Settings::defaultServerPublicRsaKey());
}
emit loadDefaultChanged(loadDefault);
}
void DeclarativeRsaKey::setKey(const RsaKey &key)
{
RsaKey oldKey = m_key;
m_key = key;
if (oldKey.isValid() != key.isValid()) {
emit validChanged(key.isValid());
}
}
DeclarativeProxySettings::DeclarativeProxySettings(QObject *parent) :
QObject(parent)
{
}
void DeclarativeProxySettings::setPort(quint16 port)
{
m_port = port;
}
void DeclarativeProxySettings::setAddress(const QString &address)
{
m_address = address;
}
DeclarativeSettings::DeclarativeSettings(QObject *parent) :
Settings(parent)
{
m_proxySettings = new DeclarativeProxySettings(this);
}
QQmlListProperty<DeclarativeServerOption> DeclarativeSettings::serverOptions()
{
return QQmlListProperty<DeclarativeServerOption>(this, this,
&DeclarativeSettings::appendServerOption,
&DeclarativeSettings::serverOptionCount,
&DeclarativeSettings::getServerOption,
&DeclarativeSettings::clearServerOptions);
}
void DeclarativeSettings::appendServerOption(DeclarativeServerOption *option)
{
m_options.append(option);
syncSettings();
}
void DeclarativeSettings::setServerKey(DeclarativeRsaKey *serverKey)
{
m_serverKey = serverKey;
emit serverKeyChanged();
syncSettings();
}
void DeclarativeSettings::syncSettings()
{
QVector<Telegram::DcOption> dcs;
for (const DeclarativeServerOption *declOption : m_options) {
dcs.append(*declOption);
}
if (m_serverKey) {
setServerRsaKey(m_serverKey->key());
}
setServerConfiguration(dcs);
QNetworkProxy proxy;
if (!m_proxySettings->address().isEmpty()) {
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(m_proxySettings->address());
proxy.setPort(m_proxySettings->port());
}
setProxy(proxy);
}
void DeclarativeSettings::appendServerOption(QQmlListProperty<DeclarativeServerOption> *list, DeclarativeServerOption *option)
{
reinterpret_cast<DeclarativeSettings*>(list->data)->appendServerOption(option);
}
int DeclarativeSettings::serverOptionCount(QQmlListProperty<DeclarativeServerOption> *list)
{
return reinterpret_cast<DeclarativeSettings*>(list->data)->serverOptionCount();
}
DeclarativeServerOption *DeclarativeSettings::getServerOption(QQmlListProperty<DeclarativeServerOption> *list, int index)
{
return reinterpret_cast<DeclarativeSettings*>(list->data)->getServerOption(index);
}
void DeclarativeSettings::clearServerOptions(QQmlListProperty<DeclarativeServerOption> *list)
{
reinterpret_cast<DeclarativeSettings*>(list->data)->clearServerOptions();
}
} // Client
} // Telegram
<|endoftext|> |
<commit_before>/*
* math.hpp
*
* Created on: Aug 19, 2017
* Author: santiago
*/
#pragma once
#include <math.h>
#include <algorithm>
#include <functional>
#include <cassert>
namespace mch{
constexpr float PI = 3.14159265359f;
//CONVERSION CONSTANTS
static constexpr float D2R = (PI) / 180.f;
static constexpr float R2D = 180.f / (PI);
inline constexpr float degToRad(float deg){
return deg*D2R;
}
inline constexpr float radToDeg(float rad){
return rad*R2D;
}
template<typename T>
inline T sign(T x){
return (T)((x > (T)0) - (x < (T)0));
}
template<class T, class Compare>
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ){
return assert( !comp(hi, lo) ),
comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}
template<class T>
constexpr const T& clamp( const T& v, const T& lo, const T& hi ){
return clamp( v, lo, hi, std::less<T>() );
}
template<typename T>
inline T approach(T init, T target, T amount){
T diff = target-init;
T dir = sign(diff);
T abs_diff = diff*sign(diff);
T approached = init + dir*std::min(amount,abs_diff);
return approached;
}
template<>
inline float approach(float init, float target, float amount){
float diff = target-init;
float dir = copysignf(1.0f, diff);
float abs_diff = copysignf(diff, 1.0f);
float approached = init + dir*std::min(amount,abs_diff);
return approached;
}
}
<commit_msg>agrego funcion modulo<commit_after>/*
* math.hpp
*
* Created on: Aug 19, 2017
* Author: santiago
*/
#pragma once
#include <math.h>
#include <algorithm>
#include <functional>
#include <cassert>
#include "Mocho/definitions.hpp"
namespace mch{
constexpr float PI = 3.14159265359f;
//CONVERSION CONSTANTS
static constexpr float D2R = (PI) / 180.f;
static constexpr float R2D = 180.f / (PI);
inline constexpr float degToRad(float deg){
return deg*D2R;
}
inline constexpr float radToDeg(float rad){
return rad*R2D;
}
template<typename T>
inline T sign(T x){
return (T)((x > (T)0) - (x < (T)0));
}
template<class T, class Compare>
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ){
return assert( !comp(hi, lo) ),
std::min(std::max(v, lo, comp), hi, comp);
}
template<class T>
constexpr const T& clamp( const T& v, const T& lo, const T& hi ){
return assert(!(hi<lo)),
std::min(std::max(v,lo),hi);
}
template<typename T>
inline T approach(T init, T target, T amount){
T diff = target-init;
T dir = sign(diff);
T abs_diff = diff*sign(diff);
T approached = init + dir*std::min(amount,abs_diff);
return approached;
}
template<>
inline float approach(float init, float target, float amount){
float diff = target-init;
float dir = copysignf(1.0f, diff);
float abs_diff = copysignf(diff, 1.0f);
float approached = init + dir*std::min(amount,abs_diff);
return approached;
}
//applies the true modulo operation
//@returns the distance in units between n
// and size's lowest multiple that is higher than n
inline uint32 modulo(int32 n, int32 size){
return ((n % size) + size) % size;
};
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstring>
#include <stdexcept>
namespace accelergy
{
std::string exec(const char* cmd) {
std::string result = "";
char buffer[128];
FILE* pipe = popen("which accelergy", "r");
if (!pipe) {
std::cout << "popen(" << cmd << ") failed" << std::endl;
exit(0);
}
try {
while (fgets(buffer, 128, pipe) != nullptr) {
result += buffer;
}
} catch (...) {
pclose(pipe);
}
pclose(pipe);
return result;
}
void invokeAccelergy(std::vector<std::string> input_files, std::string out_prefix, std::string out_dir) {
#ifdef USE_ACCELERGY
std::string accelergy_path = exec("which accelergy");
// if `which` does not find it, we will try env
if (accelergy_path.find("accelergy") == std::string::npos) {
accelergy_path = exec("echo $ACCELERGYPATH");
accelergy_path += "accelergy";
}
//std::cout << "Invoke Accelergy at: " << accelergy_path << std::endl;
std::string cmd = accelergy_path.substr(0, accelergy_path.size() - 1);
for (auto input_file : input_files) {
cmd += " " + input_file;
}
cmd += " --oprefix " + out_prefix + ".";
cmd += " -o " + out_dir + "/ > " + out_prefix + ".accelergy.log 2>&1";
std::cout << "execute:" << cmd << std::endl;
int ret = system(cmd.c_str());
if (ret) {
std::cout << "Failed to run Accelergy. Did you install Accelergy or specify ACCELERGYPATH correctly? Or check accelergy.log to see what went wrong" << std::endl;
exit(0);
}
#else
(void) input_files;
(void) out_prefix;
#endif
return;
}
} // namespace accelergy
<commit_msg>Fixed a compile error without Accelergy<commit_after>#include <iostream>
#include <cstring>
#include <stdexcept>
namespace accelergy
{
std::string exec(const char* cmd) {
std::string result = "";
char buffer[128];
FILE* pipe = popen("which accelergy", "r");
if (!pipe) {
std::cout << "popen(" << cmd << ") failed" << std::endl;
exit(0);
}
try {
while (fgets(buffer, 128, pipe) != nullptr) {
result += buffer;
}
} catch (...) {
pclose(pipe);
}
pclose(pipe);
return result;
}
void invokeAccelergy(std::vector<std::string> input_files, std::string out_prefix, std::string out_dir) {
#ifdef USE_ACCELERGY
std::string accelergy_path = exec("which accelergy");
// if `which` does not find it, we will try env
if (accelergy_path.find("accelergy") == std::string::npos) {
accelergy_path = exec("echo $ACCELERGYPATH");
accelergy_path += "accelergy";
}
//std::cout << "Invoke Accelergy at: " << accelergy_path << std::endl;
std::string cmd = accelergy_path.substr(0, accelergy_path.size() - 1);
for (auto input_file : input_files) {
cmd += " " + input_file;
}
cmd += " --oprefix " + out_prefix + ".";
cmd += " -o " + out_dir + "/ > " + out_prefix + ".accelergy.log 2>&1";
std::cout << "execute:" << cmd << std::endl;
int ret = system(cmd.c_str());
if (ret) {
std::cout << "Failed to run Accelergy. Did you install Accelergy or specify ACCELERGYPATH correctly? Or check accelergy.log to see what went wrong" << std::endl;
exit(0);
}
#else
(void) input_files;
(void) out_prefix;
(void) out_dir;
#endif
return;
}
} // namespace accelergy
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.